1 // Copyright (c) 2013 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/chromeos/chrome_browser_main_chromeos.h"
10 #include "ash/ash_switches.h"
11 #include "ash/shell.h"
12 #include "base/bind.h"
13 #include "base/callback.h"
14 #include "base/command_line.h"
15 #include "base/file_util.h"
16 #include "base/lazy_instance.h"
17 #include "base/linux_util.h"
18 #include "base/path_service.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_split.h"
22 #include "base/sys_info.h"
23 #include "chrome/browser/browser_process.h"
24 #include "chrome/browser/browser_process_platform_part_chromeos.h"
25 #include "chrome/browser/chrome_notification_types.h"
26 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
27 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
28 #include "chrome/browser/chromeos/app_mode/kiosk_app_launch_error.h"
29 #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
30 #include "chrome/browser/chromeos/app_mode/kiosk_mode_idle_app_name_notification.h"
31 #include "chrome/browser/chromeos/boot_times_loader.h"
32 #include "chrome/browser/chromeos/dbus/cros_dbus_service.h"
33 #include "chrome/browser/chromeos/events/event_rewriter.h"
34 #include "chrome/browser/chromeos/events/system_key_event_listener.h"
35 #include "chrome/browser/chromeos/events/xinput_hierarchy_changed_event_listener.h"
36 #include "chrome/browser/chromeos/extensions/default_app_order.h"
37 #include "chrome/browser/chromeos/extensions/extension_system_event_observer.h"
38 #include "chrome/browser/chromeos/external_metrics.h"
39 #include "chrome/browser/chromeos/imageburner/burn_manager.h"
40 #include "chrome/browser/chromeos/input_method/input_method_configuration.h"
41 #include "chrome/browser/chromeos/input_method/input_method_util.h"
42 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_idle_logout.h"
43 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_screensaver.h"
44 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.h"
45 #include "chrome/browser/chromeos/language_preferences.h"
46 #include "chrome/browser/chromeos/login/authenticator.h"
47 #include "chrome/browser/chromeos/login/login_utils.h"
48 #include "chrome/browser/chromeos/login/login_wizard.h"
49 #include "chrome/browser/chromeos/login/screen_locker.h"
50 #include "chrome/browser/chromeos/login/startup_utils.h"
51 #include "chrome/browser/chromeos/login/user_manager.h"
52 #include "chrome/browser/chromeos/login/wallpaper_manager.h"
53 #include "chrome/browser/chromeos/login/wizard_controller.h"
54 #include "chrome/browser/chromeos/memory/oom_priority_manager.h"
55 #include "chrome/browser/chromeos/net/network_portal_detector.h"
56 #include "chrome/browser/chromeos/options/cert_library.h"
57 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
58 #include "chrome/browser/chromeos/power/idle_action_warning_observer.h"
59 #include "chrome/browser/chromeos/power/peripheral_battery_observer.h"
60 #include "chrome/browser/chromeos/power/power_button_observer.h"
61 #include "chrome/browser/chromeos/power/power_data_collector.h"
62 #include "chrome/browser/chromeos/power/power_prefs.h"
63 #include "chrome/browser/chromeos/profiles/profile_helper.h"
64 #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h"
65 #include "chrome/browser/chromeos/settings/device_settings_service.h"
66 #include "chrome/browser/chromeos/settings/owner_key_util.h"
67 #include "chrome/browser/chromeos/status/data_promo_notification.h"
68 #include "chrome/browser/chromeos/upgrade_detector_chromeos.h"
69 #include "chrome/browser/defaults.h"
70 #include "chrome/browser/metrics/metrics_service.h"
71 #include "chrome/browser/net/chrome_network_delegate.h"
72 #include "chrome/browser/profiles/profile.h"
73 #include "chrome/browser/profiles/profile_manager.h"
74 #include "chrome/browser/rlz/rlz.h"
75 #include "chrome/common/chrome_constants.h"
76 #include "chrome/common/chrome_paths.h"
77 #include "chrome/common/chrome_switches.h"
78 #include "chrome/common/chrome_version_info.h"
79 #include "chrome/common/logging_chrome.h"
80 #include "chrome/common/pref_names.h"
81 #include "chromeos/audio/audio_devices_pref_handler.h"
82 #include "chromeos/audio/cras_audio_handler.h"
83 #include "chromeos/cert_loader.h"
84 #include "chromeos/chromeos_paths.h"
85 #include "chromeos/chromeos_switches.h"
86 #include "chromeos/cryptohome/async_method_caller.h"
87 #include "chromeos/cryptohome/homedir_methods.h"
88 #include "chromeos/cryptohome/system_salt_getter.h"
89 #include "chromeos/dbus/dbus_thread_manager.h"
90 #include "chromeos/dbus/power_policy_controller.h"
91 #include "chromeos/dbus/session_manager_client.h"
92 #include "chromeos/disks/disk_mount_manager.h"
93 #include "chromeos/ime/input_method_manager.h"
94 #include "chromeos/ime/xkeyboard.h"
95 #include "chromeos/login/login_state.h"
96 #include "chromeos/network/network_change_notifier_chromeos.h"
97 #include "chromeos/network/network_change_notifier_factory_chromeos.h"
98 #include "chromeos/network/network_handler.h"
99 #include "chromeos/system/statistics_provider.h"
100 #include "chromeos/tpm_token_loader.h"
101 #include "content/public/browser/browser_thread.h"
102 #include "content/public/browser/notification_service.h"
103 #include "content/public/browser/power_save_blocker.h"
104 #include "content/public/common/main_function_params.h"
105 #include "grit/platform_locale_settings.h"
106 #include "media/audio/sounds/sounds_manager.h"
107 #include "net/base/network_change_notifier.h"
108 #include "net/url_request/url_request.h"
109 #include "net/url_request/url_request_context_getter.h"
110 #include "ui/base/touch/touch_device.h"
111 #include "ui/events/event_utils.h"
113 // Exclude X11 dependents for ozone
115 #include "chrome/browser/chromeos/device_uma.h"
122 void ChromeOSVersionCallback(const std::string
& version
) {
123 base::SetLinuxDistro(std::string("CrOS ") + version
);
126 // Login -----------------------------------------------------------------------
128 // Class is used to login using passed username and password.
129 // The instance will be deleted upon success or failure.
130 class StubLogin
: public LoginStatusConsumer
,
131 public LoginUtils::Delegate
{
133 StubLogin(std::string username
, std::string password
)
134 : profile_prepared_(false) {
135 authenticator_
= LoginUtils::Get()->CreateAuthenticator(this);
136 authenticator_
.get()->AuthenticateToLogin(
137 ProfileHelper::GetSigninProfile(),
138 UserContext(username
, password
, std::string() /* auth_code */));
141 virtual ~StubLogin() {
142 LoginUtils::Get()->DelegateDeleted(this);
145 virtual void OnLoginFailure(const LoginFailure
& error
) OVERRIDE
{
146 LOG(ERROR
) << "Login Failure: " << error
.GetErrorString();
150 virtual void OnLoginSuccess(const UserContext
& user_context
) OVERRIDE
{
151 if (!profile_prepared_
) {
152 // Will call OnProfilePrepared in the end.
153 LoginUtils::Get()->PrepareProfile(user_context
,
154 std::string(), // display_email
155 false, // has_cookies
156 true, // has_active_session
163 // LoginUtils::Delegate implementation:
164 virtual void OnProfilePrepared(Profile
* profile
) OVERRIDE
{
165 std::string login_user
=
166 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
167 chromeos::switches::kLoginUser
);
168 profile
->GetPrefs()->SetString(prefs::kGoogleServicesUsername
, login_user
);
169 profile_prepared_
= true;
170 LoginUtils::Get()->DoBrowserLaunch(profile
, NULL
);
174 scoped_refptr
<Authenticator
> authenticator_
;
175 bool profile_prepared_
;
178 bool ShouldAutoLaunchKioskApp(const CommandLine
& command_line
) {
179 KioskAppManager
* app_manager
= KioskAppManager::Get();
180 return command_line
.HasSwitch(switches::kLoginManager
) &&
181 !command_line
.HasSwitch(switches::kForceLoginManagerInTests
) &&
182 app_manager
->IsAutoLaunchEnabled() &&
183 KioskAppLaunchError::Get() == KioskAppLaunchError::NONE
;
186 void RunAutoLaunchKioskApp() {
187 ShowLoginWizard(chromeos::WizardController::kAppLaunchSplashScreenName
);
189 // Login screen is skipped but 'login-prompt-visible' signal is still needed.
190 VLOG(1) << "Kiosk app auto launch >> login-prompt-visible";
191 DBusThreadManager::Get()->GetSessionManagerClient()->
192 EmitLoginPromptVisible();
195 void OptionallyRunChromeOSLoginManager(const CommandLine
& parsed_command_line
,
197 if (ShouldAutoLaunchKioskApp(parsed_command_line
)) {
198 RunAutoLaunchKioskApp();
199 } else if (parsed_command_line
.HasSwitch(switches::kLoginManager
)) {
200 const std::string first_screen
=
201 parsed_command_line
.HasSwitch(switches::kLoginScreen
) ?
202 WizardController::kLoginScreenName
: std::string();
203 ShowLoginWizard(first_screen
);
205 if (KioskModeSettings::Get()->IsKioskModeEnabled())
206 InitializeKioskModeScreensaver();
208 // Reset reboot after update flag when login screen is shown.
209 policy::BrowserPolicyConnectorChromeOS
* connector
=
210 g_browser_process
->platform_part()->browser_policy_connector_chromeos();
211 if (!connector
->IsEnterpriseManaged()) {
212 PrefService
* local_state
= g_browser_process
->local_state();
213 local_state
->ClearPref(prefs::kRebootAfterUpdate
);
215 } else if (parsed_command_line
.HasSwitch(switches::kLoginUser
) &&
216 parsed_command_line
.HasSwitch(switches::kLoginPassword
)) {
217 BootTimesLoader::Get()->RecordLoginAttempted();
219 parsed_command_line
.GetSwitchValueASCII(switches::kLoginUser
),
220 parsed_command_line
.GetSwitchValueASCII(switches::kLoginPassword
));
222 if (!parsed_command_line
.HasSwitch(::switches::kTestName
)) {
223 // Enable CrasAudioHandler logging when chrome restarts after crashing.
224 if (chromeos::CrasAudioHandler::IsInitialized())
225 chromeos::CrasAudioHandler::Get()->LogErrors();
227 // We did not log in (we crashed or are debugging), so we need to
229 LoginUtils::Get()->RestoreAuthenticationSession(profile
);
238 // Wrapper class for initializing dbus related services and shutting them
239 // down. This gets instantiated in a scoped_ptr so that shutdown methods in the
240 // destructor will get called if and only if this has been instantiated.
243 explicit DBusServices(const content::MainFunctionParams
& parameters
) {
244 if (!base::SysInfo::IsRunningOnChromeOS()) {
245 // Override this path on the desktop, so that the user policy key can be
246 // stored by the stub SessionManagerClient.
247 base::FilePath user_data_dir
;
248 if (PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
)) {
249 PathService::Override(chromeos::DIR_USER_POLICY_KEYS
,
250 user_data_dir
.AppendASCII("stub_user_policy"));
254 // Initialize DBusThreadManager for the browser. This must be done after
255 // the main message loop is started, as it uses the message loop.
256 DBusThreadManager::Initialize();
257 CrosDBusService::Initialize();
259 // Initialize PowerDataCollector after DBusThreadManager is initialized.
260 PowerDataCollector::Initialize();
262 LoginState::Initialize();
263 SystemSaltGetter::Initialize();
264 TPMTokenLoader::Initialize();
265 CertLoader::Initialize();
267 // This function and SystemKeyEventListener use InputMethodManager.
268 chromeos::input_method::Initialize(
269 content::BrowserThread::GetMessageLoopProxyForThread(
270 content::BrowserThread::UI
),
271 content::BrowserThread::GetMessageLoopProxyForThread(
272 content::BrowserThread::FILE));
273 disks::DiskMountManager::Initialize();
274 cryptohome::AsyncMethodCaller::Initialize();
275 cryptohome::HomedirMethods::Initialize();
277 NetworkHandler::Initialize();
278 CertLibrary::Initialize();
280 // Initialize the network change notifier for Chrome OS. The network
281 // change notifier starts to monitor changes from the power manager and
282 // the network manager.
283 NetworkChangeNotifierFactoryChromeos::GetInstance()->Initialize();
285 // Likewise, initialize the upgrade detector for Chrome OS. The upgrade
286 // detector starts to monitor changes from the update engine.
287 UpgradeDetectorChromeos::GetInstance()->Init();
289 if (base::SysInfo::IsRunningOnChromeOS()) {
290 // Disable Num Lock on X start up for http://crosbug.com/29169.
291 input_method::InputMethodManager::Get()->GetXKeyboard()->DisableNumLock();
294 // Initialize the device settings service so that we'll take actions per
295 // signals sent from the session manager. This needs to happen before
296 // g_browser_process initializes BrowserPolicyConnector.
297 DeviceSettingsService::Initialize();
298 DeviceSettingsService::Get()->SetSessionManager(
299 DBusThreadManager::Get()->GetSessionManagerClient(),
300 OwnerKeyUtil::Create());
304 CertLibrary::Shutdown();
305 NetworkHandler::Shutdown();
307 cryptohome::AsyncMethodCaller::Shutdown();
308 disks::DiskMountManager::Shutdown();
309 input_method::Shutdown();
311 SystemSaltGetter::Shutdown();
312 LoginState::Shutdown();
313 CertLoader::Shutdown();
314 TPMTokenLoader::Shutdown();
316 CrosDBusService::Shutdown();
318 // Shutdown the PowerDataCollector before shutting down DBusThreadManager.
319 PowerDataCollector::Shutdown();
321 // NOTE: This must only be called if Initialize() was called.
322 DBusThreadManager::Shutdown();
327 DISALLOW_COPY_AND_ASSIGN(DBusServices
);
330 } // namespace internal
332 // ChromeBrowserMainPartsChromeos ----------------------------------------------
334 ChromeBrowserMainPartsChromeos::ChromeBrowserMainPartsChromeos(
335 const content::MainFunctionParams
& parameters
)
336 : ChromeBrowserMainPartsLinux(parameters
) {
339 ChromeBrowserMainPartsChromeos::~ChromeBrowserMainPartsChromeos() {
340 if (KioskModeSettings::Get()->IsKioskModeEnabled())
341 ShutdownKioskModeScreensaver();
343 // To be precise, logout (browser shutdown) is not yet done, but the
344 // remaining work is negligible, hence we say LogoutDone here.
345 BootTimesLoader::Get()->AddLogoutTimeMarker("LogoutDone", false);
346 BootTimesLoader::Get()->WriteLogoutTimes();
349 // content::BrowserMainParts and ChromeBrowserMainExtraParts overrides ---------
351 void ChromeBrowserMainPartsChromeos::PreEarlyInitialization() {
352 CommandLine
* singleton_command_line
= CommandLine::ForCurrentProcess();
354 if (parsed_command_line().HasSwitch(switches::kGuestSession
)) {
355 // Disable sync and extensions if we're in "browse without sign-in" mode.
356 singleton_command_line
->AppendSwitch(::switches::kDisableSync
);
357 singleton_command_line
->AppendSwitch(::switches::kDisableExtensions
);
358 browser_defaults::bookmarks_enabled
= false;
361 // If we're not running on real ChromeOS hardware (or under VM), and are not
362 // showing the login manager or attempting a command line login, login with a
364 if (!base::SysInfo::IsRunningOnChromeOS() &&
365 !parsed_command_line().HasSwitch(switches::kLoginManager
) &&
366 !parsed_command_line().HasSwitch(switches::kLoginUser
) &&
367 !parsed_command_line().HasSwitch(switches::kGuestSession
)) {
368 singleton_command_line
->AppendSwitchASCII(
369 switches::kLoginUser
, UserManager::kStubUser
);
370 if (!parsed_command_line().HasSwitch(switches::kLoginProfile
)) {
371 singleton_command_line
->AppendSwitchASCII(switches::kLoginProfile
,
372 chrome::kTestUserProfileDir
);
374 LOG(WARNING
) << "Running as stub user with profile dir: "
375 << singleton_command_line
->GetSwitchValuePath(
376 switches::kLoginProfile
).value();
379 #if defined(GOOGLE_CHROME_BUILD)
380 const char kChromeOSReleaseTrack
[] = "CHROMEOS_RELEASE_TRACK";
382 if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack
, &channel
))
383 chrome::VersionInfo::SetChannel(channel
);
386 ChromeBrowserMainPartsLinux::PreEarlyInitialization();
389 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopStart() {
390 // Replace the default NetworkChangeNotifierFactory with ChromeOS specific
391 // implementation. This must be done before BrowserMainLoop calls
392 // net::NetworkChangeNotifier::Create() in MainMessageLoopStart().
393 net::NetworkChangeNotifier::SetFactory(
394 new NetworkChangeNotifierFactoryChromeos());
395 ChromeBrowserMainPartsLinux::PreMainMessageLoopStart();
398 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopStart() {
399 dbus_services_
.reset(new internal::DBusServices(parameters()));
401 ChromeBrowserMainPartsLinux::PostMainMessageLoopStart();
404 // Threads are initialized between MainMessageLoopStart and MainMessageLoopRun.
405 // about_flags settings are applied in ChromeBrowserMainParts::PreCreateThreads.
406 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopRun() {
407 // Set the crypto thread after the IO thread has been created/started.
408 TPMTokenLoader::Get()->SetCryptoTaskRunner(
409 content::BrowserThread::GetMessageLoopProxyForThread(
410 content::BrowserThread::IO
));
412 CrasAudioHandler::Initialize(
413 AudioDevicesPrefHandler::Create(g_browser_process
->local_state()));
415 // Start loading machine statistics here. StatisticsProvider::Shutdown()
416 // will ensure that loading is aborted on early exit.
417 bool load_oem_statistics
= !StartupUtils::IsOobeCompleted();
418 system::StatisticsProvider::GetInstance()->StartLoadingMachineStatistics(
419 content::BrowserThread::GetMessageLoopProxyForThread(
420 content::BrowserThread::FILE),
421 load_oem_statistics
);
423 base::FilePath downloads_directory
;
424 CHECK(PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS
, &downloads_directory
));
425 imageburner::BurnManager::Initialize(
426 downloads_directory
, g_browser_process
->system_request_context());
428 // Listen for system key events so that the user will be able to adjust the
429 // volume on the login screen, if Chrome is running on Chrome OS
430 // (i.e. not Linux desktop), and in non-test mode.
431 // Note: SystemKeyEventListener depends on the DBus thread.
432 if (base::SysInfo::IsRunningOnChromeOS() &&
433 !parameters().ui_task
) { // ui_task is non-NULL when running tests.
434 SystemKeyEventListener::Initialize();
437 DeviceOAuth2TokenServiceFactory::Initialize();
439 ChromeBrowserMainPartsLinux::PreMainMessageLoopRun();
442 void ChromeBrowserMainPartsChromeos::PreProfileInit() {
443 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
444 // -- immediately before Profile creation().
446 // Now that the file thread exists we can record our stats.
447 BootTimesLoader::Get()->RecordChromeMainStats();
449 // Trigger prefetching of ownership status.
450 DeviceSettingsService::Get()->Load();
452 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
453 // -- just before CreateProfile().
455 UserManager::Initialize();
457 // Initialize the screen locker now so that it can receive
458 // LOGIN_USER_CHANGED notification from UserManager.
459 if (KioskModeSettings::Get()->IsKioskModeEnabled())
460 KioskModeIdleLogout::Initialize();
462 ScreenLocker::InitClass();
464 // This forces the ProfileManager to be created and register for the
465 // notification it needs to track the logged in user.
466 g_browser_process
->profile_manager();
468 // ProfileHelper has to be initialized after UserManager instance is created.
469 g_browser_process
->platform_part()->profile_helper()->Initialize();
471 // TODO(abarth): Should this move to InitializeNetworkOptions()?
472 // Allow access to file:// on ChromeOS for tests.
473 if (parsed_command_line().HasSwitch(::switches::kAllowFileAccess
))
474 ChromeNetworkDelegate::AllowAccessToAllFiles();
476 // There are two use cases for kLoginUser:
477 // 1) if passed in tandem with kLoginPassword, to drive a "StubLogin"
478 // 2) if passed alone, to signal that the indicated user has already
479 // logged in and we should behave accordingly.
480 // This handles case 2.
481 bool immediate_login
=
482 parsed_command_line().HasSwitch(switches::kLoginUser
) &&
483 !parsed_command_line().HasSwitch(switches::kLoginPassword
);
484 if (immediate_login
){
485 // Redirects Chrome logging to the user data dir.
486 logging::RedirectChromeLogging(parsed_command_line());
488 // Load the default app order synchronously for restarting case.
489 app_order_loader_
.reset(
490 new default_app_order::ExternalLoader(false /* async */));
493 if (!app_order_loader_
) {
494 app_order_loader_
.reset(
495 new default_app_order::ExternalLoader(true /* async */));
498 media::SoundsManager::Create();
500 // Initialize magnification manager before ash tray is created. And this must
501 // be placed after UserManager::SessionStarted();
502 AccessibilityManager::Initialize();
503 MagnificationManager::Initialize();
505 // Add observers for WallpaperManager. This depends on PowerManagerClient,
506 // TimezoneSettings and CrosSettings.
507 WallpaperManager::Get()->AddObservers();
509 cros_version_loader_
.GetVersion(VersionLoader::VERSION_FULL
,
510 base::Bind(&ChromeOSVersionCallback
),
513 // Make sure that wallpaper boot transition and other delays in OOBE
514 // are disabled for tests and kiosk app launch by default.
515 // Individual tests may enable them if they want.
516 if (parsed_command_line().HasSwitch(::switches::kTestType
) ||
517 ShouldAutoLaunchKioskApp(parsed_command_line())) {
518 WizardController::SetZeroDelays();
521 power_prefs_
.reset(new PowerPrefs(
522 DBusThreadManager::Get()->GetPowerPolicyController()));
524 // In Aura builds this will initialize ash::Shell.
525 ChromeBrowserMainPartsLinux::PreProfileInit();
527 if (immediate_login
) {
528 std::string username
=
529 parsed_command_line().GetSwitchValueASCII(switches::kLoginUser
);
530 UserManager
* user_manager
= UserManager::Get();
531 // In case of multi-profiles --login-profile will contain user_id_hash.
532 std::string username_hash
=
533 parsed_command_line().GetSwitchValueASCII(switches::kLoginProfile
);
534 user_manager
->UserLoggedIn(username
, username_hash
, true);
535 VLOG(1) << "Relaunching browser for user: " << username
536 << " with hash: " << username_hash
;
540 class GuestLanguageSetCallbackData
{
542 explicit GuestLanguageSetCallbackData(Profile
* profile
) : profile(profile
) {
545 // Must match SwitchLanguageCallback type.
546 static void Callback(const scoped_ptr
<GuestLanguageSetCallbackData
>& self
,
547 const std::string
& locale
,
548 const std::string
& loaded_locale
,
555 void GuestLanguageSetCallbackData::Callback(
556 const scoped_ptr
<GuestLanguageSetCallbackData
>& self
,
557 const std::string
& locale
,
558 const std::string
& loaded_locale
,
560 input_method::InputMethodManager
* const ime_manager
=
561 input_method::InputMethodManager::Get();
562 // Active layout must be hardware "login layout".
563 // The previous one must be "locale default layout".
564 // First, enable all hardware input methods.
565 const std::vector
<std::string
>& input_methods
=
566 ime_manager
->GetInputMethodUtil()->GetHardwareInputMethodIds();
567 for (size_t i
= 0; i
< input_methods
.size(); ++i
)
568 ime_manager
->EnableInputMethod(input_methods
[i
]);
570 // Second, enable locale based input methods.
571 const std::string locale_default_input_method
=
572 ime_manager
->GetInputMethodUtil()->
573 GetLanguageDefaultInputMethodId(loaded_locale
);
574 if (!locale_default_input_method
.empty()) {
575 PrefService
* user_prefs
= self
->profile
->GetPrefs();
576 user_prefs
->SetString(prefs::kLanguagePreviousInputMethod
,
577 locale_default_input_method
);
578 ime_manager
->EnableInputMethod(locale_default_input_method
);
581 // Finally, activate the first login input method.
582 const std::vector
<std::string
>& login_input_methods
=
583 ime_manager
->GetInputMethodUtil()->GetHardwareLoginInputMethodIds();
584 ime_manager
->ChangeInputMethod(login_input_methods
[0]);
587 void SetGuestLocale(UserManager
* const usermanager
, Profile
* const profile
) {
588 scoped_ptr
<GuestLanguageSetCallbackData
> data(
589 new GuestLanguageSetCallbackData(profile
));
590 scoped_ptr
<locale_util::SwitchLanguageCallback
> callback(
591 new locale_util::SwitchLanguageCallback(base::Bind(
592 &GuestLanguageSetCallbackData::Callback
, base::Passed(data
.Pass()))));
593 User
* const user
= usermanager
->GetUserByProfile(profile
);
594 usermanager
->RespectLocalePreference(profile
, user
, callback
.Pass());
597 void ChromeBrowserMainPartsChromeos::PostProfileInit() {
598 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
599 // -- just after CreateProfile().
601 // Restarting Chrome inside existing user session. Possible cases:
602 // 1. Chrome is restarted after crash.
603 // 2. Chrome is started in browser_tests skipping the login flow
604 // 3. Chrome is started on dev machine
605 // i.e. not on Chrome OS device w/o login flow.
606 if (parsed_command_line().HasSwitch(switches::kLoginUser
) &&
607 !parsed_command_line().HasSwitch(switches::kLoginPassword
)) {
608 std::string login_user
= parsed_command_line().GetSwitchValueASCII(
609 chromeos::switches::kLoginUser
);
610 if (!base::SysInfo::IsRunningOnChromeOS() &&
611 login_user
== UserManager::kStubUser
) {
612 // For dev machines and stub user emulate as if sync has been initialized.
613 profile()->GetPrefs()->SetString(prefs::kGoogleServicesUsername
,
617 // This is done in LoginUtils::OnProfileCreated during normal login.
618 LoginUtils::Get()->InitRlzDelayed(profile());
620 // Send the PROFILE_PREPARED notification and call SessionStarted()
621 // so that the Launcher and other Profile dependent classes are created.
622 content::NotificationService::current()->Notify(
623 chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED
,
624 content::NotificationService::AllSources(),
625 content::Details
<Profile
>(profile()));
626 UserManager::Get()->SessionStarted();
628 // Now is the good time to retrieve other logged in users for this session.
629 // First user has been already marked as logged in and active in
630 // PreProfileInit(). Chrome should tread other user in a session as active
631 // in the background.
632 UserManager::Get()->RestoreActiveSessions();
635 // Initialize the network portal detector for Chrome OS. The network
636 // portal detector starts to listen for notifications from
637 // NetworkStateHandler and initiates captive portal detection for
638 // active networks. Shoule be called before call to
639 // OptionallyRunChromeOSLoginManager, because it depends on
640 // NetworkPortalDetector.
641 NetworkPortalDetector::Initialize();
643 NetworkPortalDetector
* detector
= NetworkPortalDetector::Get();
644 #if defined(GOOGLE_CHROME_BUILD)
645 bool is_official_build
= true;
647 bool is_official_build
= false;
649 // Enable portal detector if EULA was previously accepted or if
650 // this is an unofficial build.
651 if (!is_official_build
|| StartupUtils::IsEulaAccepted())
652 detector
->Enable(true);
655 // Tests should be able to tune login manager before showing it.
656 // Thus only show login manager in normal (non-testing) mode.
657 if (!parameters().ui_task
||
658 parsed_command_line().HasSwitch(switches::kForceLoginManagerInTests
)) {
659 OptionallyRunChromeOSLoginManager(parsed_command_line(), profile());
662 // Guest user profile is never initialized with locale settings,
663 // so we need special handling for Guest session.
664 UserManager
* const usermanager
= UserManager::Get();
665 if (usermanager
->IsLoggedInAsGuest())
666 SetGuestLocale(usermanager
, profile());
668 // These observers must be initialized after the profile because
669 // they use the profile to dispatch extension events.
670 extension_system_event_observer_
.reset(new ExtensionSystemEventObserver());
671 if (KioskModeSettings::Get()->IsKioskModeEnabled()) {
672 retail_mode_power_save_blocker_
= content::PowerSaveBlocker::Create(
673 content::PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep
,
677 peripheral_battery_observer_
.reset(new PeripheralBatteryObserver());
679 g_browser_process
->platform_part()->InitializeAutomaticRebootManager();
681 // This observer cannot be created earlier because it requires the shell to be
683 idle_action_warning_observer_
.reset(new IdleActionWarningObserver());
685 ChromeBrowserMainPartsLinux::PostProfileInit();
688 void ChromeBrowserMainPartsChromeos::PreBrowserStart() {
689 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
690 // -- just before MetricsService::LogNeedForCleanShutdown().
692 g_browser_process
->metrics_service()->StartExternalMetrics();
694 // Listen for XI_HierarchyChanged events. Note: if this is moved to
695 // PreMainMessageLoopRun() then desktopui_PageCyclerTests fail for unknown
696 // reasons, see http://crosbug.com/24833.
697 XInputHierarchyChangedEventListener::GetInstance();
700 // Start the CrOS input device UMA watcher
701 DeviceUMA::GetInstance();
704 event_rewriter_
.reset(new EventRewriter());
706 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
707 // -- immediately after ChildProcess::WaitForDebugger().
709 // Start the out-of-memory priority manager here so that we give the most
710 // amount of time for the other services to start up before we start
711 // adjusting the oom priority.
712 g_browser_process
->platform_part()->oom_priority_manager()->Start();
714 if (ui::ShouldDefaultToNaturalScroll()) {
715 CommandLine::ForCurrentProcess()->AppendSwitch(
716 chromeos::switches::kNaturalScrollDefault
);
717 ui::SetNaturalScroll(true);
720 ChromeBrowserMainPartsLinux::PreBrowserStart();
723 void ChromeBrowserMainPartsChromeos::PostBrowserStart() {
724 // These are dependent on the ash::Shell singleton already having been
726 power_button_observer_
.reset(new PowerButtonObserver
);
727 data_promo_notification_
.reset(new DataPromoNotification()),
729 ChromeBrowserMainPartsLinux::PostBrowserStart();
732 // Shut down services before the browser process, etc are destroyed.
733 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopRun() {
734 BootTimesLoader::Get()->AddLogoutTimeMarker("UIMessageLoopEnded", true);
736 g_browser_process
->platform_part()->oom_priority_manager()->Stop();
738 // Destroy the application name notifier for Kiosk mode.
739 KioskModeIdleAppNameNotification::Shutdown();
741 // Shutdown the upgrade detector for Chrome OS. The upgrade detector
742 // stops monitoring changes from the update engine.
743 if (UpgradeDetectorChromeos::GetInstance())
744 UpgradeDetectorChromeos::GetInstance()->Shutdown();
746 // Shutdown the network change notifier for Chrome OS. The network
747 // change notifier stops monitoring changes from the power manager and
748 // the network manager.
749 if (NetworkChangeNotifierFactoryChromeos::GetInstance())
750 NetworkChangeNotifierFactoryChromeos::GetInstance()->Shutdown();
752 // Destroy UI related classes before destroying services that they may
754 data_promo_notification_
.reset();
756 // Tell DeviceSettingsService to stop talking to session_manager. Do not
757 // shutdown DeviceSettingsService yet, it might still be accessed by
758 // BrowserPolicyConnector (owned by g_browser_process).
759 DeviceSettingsService::Get()->UnsetSessionManager();
761 // We should remove observers attached to D-Bus clients before
762 // DBusThreadManager is shut down.
763 extension_system_event_observer_
.reset();
764 retail_mode_power_save_blocker_
.reset();
765 peripheral_battery_observer_
.reset();
766 power_prefs_
.reset();
767 event_rewriter_
.reset();
769 // Let the ScreenLocker unregister itself from SessionManagerClient before
770 // DBusThreadManager is shut down.
771 if (!KioskModeSettings::Get()->IsKioskModeEnabled())
772 ScreenLocker::ShutDownClass();
774 // The XInput2 event listener needs to be shut down earlier than when
775 // Singletons are finally destroyed in AtExitManager.
776 XInputHierarchyChangedEventListener::GetInstance()->Stop();
779 DeviceUMA::GetInstance()->Stop();
782 // SystemKeyEventListener::Shutdown() is always safe to call,
783 // even if Initialize() wasn't called.
784 SystemKeyEventListener::Shutdown();
785 imageburner::BurnManager::Shutdown();
786 CrasAudioHandler::Shutdown();
788 // Detach D-Bus clients before DBusThreadManager is shut down.
789 power_button_observer_
.reset();
790 idle_action_warning_observer_
.reset();
792 MagnificationManager::Shutdown();
793 AccessibilityManager::Shutdown();
795 media::SoundsManager::Shutdown();
797 system::StatisticsProvider::GetInstance()->Shutdown();
799 // Let the UserManager and WallpaperManager unregister itself as an observer
800 // of the CrosSettings singleton before it is destroyed. This also ensures
801 // that the UserManager has no URLRequest pending (see
802 // http://crbug.com/276659).
803 UserManager::Get()->Shutdown();
804 WallpaperManager::Get()->Shutdown();
806 // Let the AutomaticRebootManager unregister itself as an observer of several
808 g_browser_process
->platform_part()->ShutdownAutomaticRebootManager();
810 // Clean up dependency on CrosSettings and stop pending data fetches.
811 KioskAppManager::Shutdown();
813 // We first call PostMainMessageLoopRun and then destroy UserManager, because
814 // Ash needs to be closed before UserManager is destroyed.
815 ChromeBrowserMainPartsLinux::PostMainMessageLoopRun();
817 // Stops all in-flight OAuth2 token fetchers before the IO thread stops.
818 DeviceOAuth2TokenServiceFactory::Shutdown();
821 // ChromeBrowserMainPartsLinux::PostMainMessageLoopRun() to be
822 // executed after execution of chrome::CloseAsh(), because some
823 // parts of WebUI depends on NetworkPortalDetector.
824 NetworkPortalDetector::Shutdown();
826 UserManager::Destroy();
829 void ChromeBrowserMainPartsChromeos::PostDestroyThreads() {
830 // Destroy DBus services immediately after threads are stopped.
831 dbus_services_
.reset();
833 ChromeBrowserMainPartsLinux::PostDestroyThreads();
835 // Destroy DeviceSettingsService after g_browser_process.
836 DeviceSettingsService::Shutdown();
839 } // namespace chromeos