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);
79 // NetworkScreenHandler, public: -----------------------------------------------
81 NetworkScreenHandler::NetworkScreenHandler(CoreOobeActor* core_oobe_actor)
82 : BaseScreenHandler(kJsScreenPath),
84 core_oobe_actor_(core_oobe_actor),
85 is_continue_enabled_(false),
87 should_reinitialize_language_keyboard_list_(false),
88 weak_ptr_factory_(this) {
89 DCHECK(core_oobe_actor_);
92 input_method::InputMethodManager* manager =
93 input_method::InputMethodManager::Get();
94 manager->SetInputMethodLoginDefault();
95 manager->GetComponentExtensionIMEManager()->AddObserver(this);
98 NetworkScreenHandler::~NetworkScreenHandler() {
100 screen_->OnActorDestroyed(this);
102 input_method::InputMethodManager::Get()
103 ->GetComponentExtensionIMEManager()
104 ->RemoveObserver(this);
107 // NetworkScreenHandler, NetworkScreenActor implementation: --------------------
109 void NetworkScreenHandler::SetDelegate(NetworkScreenActor::Delegate* screen) {
113 void NetworkScreenHandler::PrepareToShow() {
116 void NetworkScreenHandler::Show() {
117 if (!page_is_ready()) {
118 show_on_init_ = true;
122 ShowScreen(OobeUI::kScreenOobeNetwork, NULL);
124 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableDemoMode))
128 StartIdleDetection();
133 void NetworkScreenHandler::Hide() {
136 void NetworkScreenHandler::ShowError(const base::string16& message) {
137 CallJS("showError", message);
140 void NetworkScreenHandler::ClearErrors() {
142 core_oobe_actor_->ClearErrors();
145 void NetworkScreenHandler::ShowConnectingStatus(
147 const base::string16& network_id) {
150 void NetworkScreenHandler::EnableContinue(bool enabled) {
151 is_continue_enabled_ = enabled;
153 CallJS("enableContinueButton", enabled);
156 // NetworkScreenHandler, BaseScreenHandler implementation: --------------------
158 void NetworkScreenHandler::DeclareLocalizedValues(
159 LocalizedValuesBuilder* builder) {
160 if (system::InputDeviceSettings::Get()->ForceKeyboardDrivenUINavigation())
161 builder->Add("networkScreenGreeting", IDS_REMORA_CONFIRM_MESSAGE);
163 builder->Add("networkScreenGreeting", IDS_WELCOME_SCREEN_GREETING);
165 builder->Add("networkScreenTitle", IDS_WELCOME_SCREEN_TITLE);
166 builder->Add("networkScreenAccessibleTitle",
167 IDS_NETWORK_SCREEN_ACCESSIBLE_TITLE);
168 builder->Add("selectLanguage", IDS_LANGUAGE_SELECTION_SELECT);
169 builder->Add("selectKeyboard", IDS_KEYBOARD_SELECTION_SELECT);
170 builder->Add("selectNetwork", IDS_NETWORK_SELECTION_SELECT);
171 builder->Add("selectTimezone", IDS_OPTIONS_SETTINGS_TIMEZONE_DESCRIPTION);
172 builder->Add("proxySettings", IDS_OPTIONS_PROXIES_CONFIGURE_BUTTON);
173 builder->Add("continueButton", IDS_NETWORK_SELECTION_CONTINUE_BUTTON);
176 void NetworkScreenHandler::GetAdditionalParameters(
177 base::DictionaryValue* dict) {
178 dict->Set("languageList", GetLanguageList());
179 dict->Set("inputMethodsList", GetInputMethods());
180 dict->Set("timezoneList", GetTimezoneList());
183 void NetworkScreenHandler::Initialize() {
184 EnableContinue(is_continue_enabled_);
186 show_on_init_ = false;
190 if (should_reinitialize_language_keyboard_list_) {
191 should_reinitialize_language_keyboard_list_ = false;
192 ReloadLocalizedContent();
195 timezone_subscription_ = CrosSettings::Get()->AddSettingsObserver(
197 base::Bind(&NetworkScreenHandler::OnSystemTimezoneChanged,
198 base::Unretained(this)));
199 OnSystemTimezoneChanged();
202 // NetworkScreenHandler, WebUIMessageHandler implementation: -------------------
204 void NetworkScreenHandler::RegisterMessages() {
205 AddCallback(kJsApiNetworkOnExit, &NetworkScreenHandler::HandleOnExit);
206 AddCallback(kJsApiNetworkOnLanguageChanged,
207 &NetworkScreenHandler::HandleOnLanguageChanged);
208 AddCallback(kJsApiNetworkOnInputMethodChanged,
209 &NetworkScreenHandler::HandleOnInputMethodChanged);
210 AddCallback(kJsApiNetworkOnTimezoneChanged,
211 &NetworkScreenHandler::HandleOnTimezoneChanged);
216 void NetworkScreenHandler::RegisterPrefs(PrefRegistrySimple* registry) {
217 registry->RegisterInt64Pref(prefs::kTimeOnOobe, 0);
220 // NetworkScreenHandler, private: ----------------------------------------------
222 void NetworkScreenHandler::HandleOnExit() {
223 idle_detector_.reset();
226 screen_->OnContinuePressed();
229 struct NetworkScreenHandlerOnLanguageChangedCallbackData {
230 explicit NetworkScreenHandlerOnLanguageChangedCallbackData(
231 base::WeakPtr<NetworkScreenHandler>& handler)
232 : handler_(handler) {}
234 base::WeakPtr<NetworkScreenHandler> handler_;
236 // Block UI while resource bundle is being reloaded.
237 chromeos::InputEventsBlocker input_events_blocker;
241 void NetworkScreenHandler::OnLanguageChangedCallback(
242 scoped_ptr<NetworkScreenHandlerOnLanguageChangedCallbackData> context,
243 const std::string& /*requested locale*/,
244 const std::string& /*loaded_locale*/,
245 const bool /*success*/) {
246 if (!context or !context->handler_)
249 NetworkScreenHandler* const self = context->handler_.get();
250 self->ReloadLocalizedContent();
252 AccessibilityManager::Get()->OnLocaleChanged();
255 void NetworkScreenHandler::HandleOnLanguageChanged(const std::string& locale) {
256 const std::string app_locale = g_browser_process->GetApplicationLocale();
257 if (app_locale == locale)
260 base::WeakPtr<NetworkScreenHandler> weak_self =
261 weak_ptr_factory_.GetWeakPtr();
262 scoped_ptr<NetworkScreenHandlerOnLanguageChangedCallbackData> callback_data(
263 new NetworkScreenHandlerOnLanguageChangedCallbackData(weak_self));
264 scoped_ptr<locale_util::SwitchLanguageCallback> callback(
265 new locale_util::SwitchLanguageCallback(
266 base::Bind(&NetworkScreenHandler::OnLanguageChangedCallback,
267 base::Passed(callback_data.Pass()))));
268 locale_util::SwitchLanguage(locale,
269 true /* enableLocaleKeyboardLayouts */,
270 true /* login_layouts_only */,
274 void NetworkScreenHandler::HandleOnInputMethodChanged(const std::string& id) {
275 input_method::InputMethodManager::Get()->ChangeInputMethod(id);
278 void NetworkScreenHandler::HandleOnTimezoneChanged(
279 const std::string& timezone_id) {
280 std::string current_timezone_id;
281 CrosSettings::Get()->GetString(kSystemTimezone, ¤t_timezone_id);
282 if (current_timezone_id == timezone_id)
285 CrosSettings::Get()->SetString(kSystemTimezone, timezone_id);
288 void NetworkScreenHandler::OnSystemTimezoneChanged() {
289 std::string current_timezone_id;
290 CrosSettings::Get()->GetString(kSystemTimezone, ¤t_timezone_id);
291 CallJS("setTimezone", current_timezone_id);
294 void NetworkScreenHandler::StartIdleDetection() {
295 if (!idle_detector_.get()) {
296 idle_detector_.reset(
297 new IdleDetector(base::Closure(),
298 base::Bind(&NetworkScreenHandler::OnIdle,
299 weak_ptr_factory_.GetWeakPtr())));
301 idle_detector_->Start(derelict_idle_timeout_);
304 void NetworkScreenHandler::StartOobeTimer() {
305 oobe_timer_.Start(FROM_HERE,
306 oobe_timer_update_interval_,
308 &NetworkScreenHandler::OnOobeTimerUpdate);
311 void NetworkScreenHandler::OnIdle() {
312 LoginDisplayHost* host = LoginDisplayHostImpl::default_host();
313 host->StartDemoAppLaunch();
316 void NetworkScreenHandler::OnOobeTimerUpdate() {
317 time_on_oobe_ += oobe_timer_update_interval_;
319 PrefService* prefs = g_browser_process->local_state();
320 prefs->SetInt64(prefs::kTimeOnOobe, time_on_oobe_.InSeconds());
324 StartIdleDetection();
328 void NetworkScreenHandler::SetupTimeouts() {
329 CommandLine* cmdline = CommandLine::ForCurrentProcess();
332 PrefService* prefs = g_browser_process->local_state();
334 base::TimeDelta::FromSeconds(prefs->GetInt64(prefs::kTimeOnOobe));
336 int derelict_detection_timeout;
337 if (!cmdline->HasSwitch(switches::kDerelictDetectionTimeout) ||
339 cmdline->GetSwitchValueASCII(switches::kDerelictDetectionTimeout),
340 &derelict_detection_timeout)) {
341 derelict_detection_timeout = kDerelectDetectionTimeoutSeconds;
343 derelict_detection_timeout_ =
344 base::TimeDelta::FromSeconds(derelict_detection_timeout);
346 int derelict_idle_timeout;
347 if (!cmdline->HasSwitch(switches::kDerelictIdleTimeout) ||
349 cmdline->GetSwitchValueASCII(switches::kDerelictIdleTimeout),
350 &derelict_idle_timeout)) {
351 derelict_idle_timeout = kDerelectIdleTimeoutSeconds;
353 derelict_idle_timeout_ = base::TimeDelta::FromSeconds(derelict_idle_timeout);
356 int oobe_timer_update_interval;
357 if (!cmdline->HasSwitch(switches::kOobeTimerInterval) ||
359 cmdline->GetSwitchValueASCII(switches::kOobeTimerInterval),
360 &oobe_timer_update_interval)) {
361 oobe_timer_update_interval = kOobeTimerUpdateIntervalSeconds;
363 oobe_timer_update_interval_ =
364 base::TimeDelta::FromSeconds(oobe_timer_update_interval);
366 // In case we'd be derelict before our timer is set to trigger, reduce
367 // the interval so we check again when we're scheduled to go derelict.
368 oobe_timer_update_interval_ =
369 std::max(std::min(oobe_timer_update_interval_,
370 derelict_detection_timeout_ - time_on_oobe_),
371 base::TimeDelta::FromSeconds(0));
374 bool NetworkScreenHandler::IsDerelict() {
375 return time_on_oobe_ >= derelict_detection_timeout_;
379 base::ListValue* NetworkScreenHandler::GetLanguageList() {
380 const std::string app_locale = g_browser_process->GetApplicationLocale();
381 input_method::InputMethodManager* manager =
382 input_method::InputMethodManager::Get();
383 ComponentExtensionIMEManager* comp_manager =
384 manager->GetComponentExtensionIMEManager();
385 input_method::InputMethodDescriptors descriptors;
386 if (extension_ime_util::UseWrappedExtensionKeyboardLayouts()) {
387 if (comp_manager->IsInitialized())
388 descriptors = comp_manager->GetXkbIMEAsInputMethodDescriptor();
390 descriptors = *(manager->GetSupportedInputMethods());
392 base::ListValue* languages_list =
393 options::CrosLanguageOptionsHandler::GetUILanguageList(descriptors);
394 for (size_t i = 0; i < languages_list->GetSize(); ++i) {
395 base::DictionaryValue* language_info = NULL;
396 if (!languages_list->GetDictionary(i, &language_info))
400 language_info->GetString("code", &value);
401 std::string display_name;
402 language_info->GetString("displayName", &display_name);
403 std::string native_name;
404 language_info->GetString("nativeDisplayName", &native_name);
406 // If it's option group divider, add field name.
407 if (value == options::kVendorOtherLanguagesListDivider) {
408 language_info->SetString(
410 l10n_util::GetStringUTF16(IDS_OOBE_OTHER_LANGUAGES));
412 if (display_name != native_name) {
413 display_name = base::StringPrintf("%s - %s",
414 display_name.c_str(),
415 native_name.c_str());
418 language_info->SetString("value", value);
419 language_info->SetString("title", display_name);
420 language_info->SetBoolean("selected", value == app_locale);
422 return languages_list;
425 base::DictionaryValue* CreateInputMethodsEntry(
426 const input_method::InputMethodDescriptor& method,
427 const std::string current_input_method_id) {
428 input_method::InputMethodUtil* util =
429 input_method::InputMethodManager::Get()->GetInputMethodUtil();
430 const std::string& ime_id = method.id();
431 scoped_ptr<base::DictionaryValue> input_method(new base::DictionaryValue);
432 input_method->SetString("value", ime_id);
433 input_method->SetString("title", util->GetInputMethodLongName(method));
434 input_method->SetBoolean("selected", ime_id == current_input_method_id);
435 return input_method.release();
438 void NetworkScreenHandler::OnImeComponentExtensionInitialized() {
439 input_method::InputMethodManager::Get()->SetInputMethodLoginDefault();
441 // Refreshes the language and keyboard list once the component extension
442 // IMEs are initialized.
444 ReloadLocalizedContent();
446 should_reinitialize_language_keyboard_list_ = true;
449 void NetworkScreenHandler::ReloadLocalizedContent() {
450 base::DictionaryValue localized_strings;
451 static_cast<OobeUI*>(web_ui()->GetController())
452 ->GetLocalizedStrings(&localized_strings);
453 core_oobe_actor_->ReloadContent(localized_strings);
455 // Buttons are recreated, updated "Continue" button state.
456 EnableContinue(is_continue_enabled_);
460 base::ListValue* NetworkScreenHandler::GetInputMethods() {
461 base::ListValue* input_methods_list = new base::ListValue;
462 input_method::InputMethodManager* manager =
463 input_method::InputMethodManager::Get();
464 input_method::InputMethodUtil* util = manager->GetInputMethodUtil();
465 if (extension_ime_util::UseWrappedExtensionKeyboardLayouts()) {
466 ComponentExtensionIMEManager* comp_manager =
467 manager->GetComponentExtensionIMEManager();
468 if (!comp_manager->IsInitialized()) {
469 input_method::InputMethodDescriptor fallback =
470 util->GetFallbackInputMethodDescriptor();
471 input_methods_list->Append(
472 CreateInputMethodsEntry(fallback, fallback.id()));
473 return input_methods_list;
477 scoped_ptr<input_method::InputMethodDescriptors> input_methods(
478 manager->GetActiveInputMethods());
479 const std::string& current_input_method_id =
480 manager->GetCurrentInputMethod().id();
481 const std::vector<std::string>& hardware_login_input_methods =
482 util->GetHardwareLoginInputMethodIds();
483 std::set<std::string> input_methods_added;
485 for (std::vector<std::string>::const_iterator i =
486 hardware_login_input_methods.begin();
487 i != hardware_login_input_methods.end();
489 const input_method::InputMethodDescriptor* ime =
490 util->GetInputMethodDescriptorFromId(*i);
492 // Do not crash in case of misconfiguration.
494 input_methods_added.insert(*i);
495 input_methods_list->Append(
496 CreateInputMethodsEntry(*ime, current_input_method_id));
500 bool optgroup_added = false;
501 for (size_t i = 0; i < input_methods->size(); ++i) {
502 // Makes sure the id is in legacy xkb id format.
503 const std::string& ime_id = (*input_methods)[i].id();
504 if (!InsertString(ime_id, input_methods_added))
506 if (!optgroup_added) {
507 optgroup_added = true;
508 AddOptgroupOtherLayouts(input_methods_list);
510 input_methods_list->Append(
511 CreateInputMethodsEntry((*input_methods)[i], current_input_method_id));
513 // "xkb:us::eng" should always be in the list of available layouts.
514 const std::string& us_keyboard_id =
515 extension_ime_util::GetInputMethodIDByKeyboardLayout(kUSLayout);
516 if (input_methods_added.find(us_keyboard_id) == input_methods_added.end()) {
517 const input_method::InputMethodDescriptor* us_eng_descriptor =
518 util->GetInputMethodDescriptorFromId(us_keyboard_id);
519 DCHECK(us_eng_descriptor != NULL);
520 if (!optgroup_added) {
521 optgroup_added = true;
522 AddOptgroupOtherLayouts(input_methods_list);
524 input_methods_list->Append(
525 CreateInputMethodsEntry(*us_eng_descriptor, current_input_method_id));
527 return input_methods_list;
531 base::ListValue* NetworkScreenHandler::GetTimezoneList() {
532 std::string current_timezone_id;
533 CrosSettings::Get()->GetString(kSystemTimezone, ¤t_timezone_id);
535 scoped_ptr<base::ListValue> timezone_list(new base::ListValue);
536 scoped_ptr<base::ListValue> timezones = system::GetTimezoneList().Pass();
537 for (size_t i = 0; i < timezones->GetSize(); ++i) {
538 const base::ListValue* timezone = NULL;
539 CHECK(timezones->GetList(i, &timezone));
541 std::string timezone_id;
542 CHECK(timezone->GetString(0, &timezone_id));
544 std::string timezone_name;
545 CHECK(timezone->GetString(1, &timezone_name));
547 scoped_ptr<base::DictionaryValue> timezone_option(
548 new base::DictionaryValue);
549 timezone_option->SetString("value", timezone_id);
550 timezone_option->SetString("title", timezone_name);
551 timezone_option->SetBoolean("selected", timezone_id == current_timezone_id);
552 timezone_list->Append(timezone_option.release());
555 return timezone_list.release();
558 } // namespace chromeos