ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / chromeos / chrome_browser_main_chromeos.cc
blob0556a2eeb97b98fb11fad8229069f67243d8d451
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"
7 #include <string>
8 #include <vector>
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/files/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 "base/task_runner_util.h"
24 #include "chrome/browser/browser_process.h"
25 #include "chrome/browser/browser_process_platform_part_chromeos.h"
26 #include "chrome/browser/chrome_notification_types.h"
27 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
28 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
29 #include "chrome/browser/chromeos/app_mode/kiosk_app_launch_error.h"
30 #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
31 #include "chrome/browser/chromeos/app_mode/kiosk_mode_idle_app_name_notification.h"
32 #include "chrome/browser/chromeos/boot_times_recorder.h"
33 #include "chrome/browser/chromeos/dbus/chrome_console_service_provider_delegate.h"
34 #include "chrome/browser/chromeos/dbus/chrome_display_power_service_provider_delegate.h"
35 #include "chrome/browser/chromeos/dbus/chrome_proxy_resolver_delegate.h"
36 #include "chrome/browser/chromeos/dbus/printer_service_provider.h"
37 #include "chrome/browser/chromeos/dbus/screen_lock_service_provider.h"
38 #include "chrome/browser/chromeos/device/input_service_proxy.h"
39 #include "chrome/browser/chromeos/events/event_rewriter.h"
40 #include "chrome/browser/chromeos/events/event_rewriter_controller.h"
41 #include "chrome/browser/chromeos/events/keyboard_driven_event_rewriter.h"
42 #include "chrome/browser/chromeos/extensions/default_app_order.h"
43 #include "chrome/browser/chromeos/external_metrics.h"
44 #include "chrome/browser/chromeos/input_method/input_method_configuration.h"
45 #include "chrome/browser/chromeos/input_method/input_method_util.h"
46 #include "chrome/browser/chromeos/language_preferences.h"
47 #include "chrome/browser/chromeos/login/helper.h"
48 #include "chrome/browser/chromeos/login/lock/screen_locker.h"
49 #include "chrome/browser/chromeos/login/login_wizard.h"
50 #include "chrome/browser/chromeos/login/session/user_session_manager.h"
51 #include "chrome/browser/chromeos/login/startup_utils.h"
52 #include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
53 #include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h"
54 #include "chrome/browser/chromeos/login/wizard_controller.h"
55 #include "chrome/browser/chromeos/memory/oom_priority_manager.h"
56 #include "chrome/browser/chromeos/net/network_portal_detector_impl.h"
57 #include "chrome/browser/chromeos/net/wake_on_wifi_manager.h"
58 #include "chrome/browser/chromeos/options/cert_library.h"
59 #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h"
60 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
61 #include "chrome/browser/chromeos/policy/device_local_account.h"
62 #include "chrome/browser/chromeos/power/freezer_cgroup_process_manager.h"
63 #include "chrome/browser/chromeos/power/idle_action_warning_observer.h"
64 #include "chrome/browser/chromeos/power/peripheral_battery_observer.h"
65 #include "chrome/browser/chromeos/power/power_button_observer.h"
66 #include "chrome/browser/chromeos/power/power_data_collector.h"
67 #include "chrome/browser/chromeos/power/power_prefs.h"
68 #include "chrome/browser/chromeos/power/renderer_freezer.h"
69 #include "chrome/browser/chromeos/profiles/profile_helper.h"
70 #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h"
71 #include "chrome/browser/chromeos/settings/device_settings_service.h"
72 #include "chrome/browser/chromeos/status/data_promo_notification.h"
73 #include "chrome/browser/chromeos/system/input_device_settings.h"
74 #include "chrome/browser/chromeos/upgrade_detector_chromeos.h"
75 #include "chrome/browser/defaults.h"
76 #include "chrome/browser/lifetime/application_lifetime.h"
77 #include "chrome/browser/net/chrome_network_delegate.h"
78 #include "chrome/browser/profiles/profile.h"
79 #include "chrome/browser/profiles/profile_manager.h"
80 #include "chrome/browser/rlz/rlz.h"
81 #include "chrome/browser/ui/ash/network_connect_delegate_chromeos.h"
82 #include "chrome/common/chrome_constants.h"
83 #include "chrome/common/chrome_paths.h"
84 #include "chrome/common/chrome_switches.h"
85 #include "chrome/common/chrome_version_info.h"
86 #include "chrome/common/logging_chrome.h"
87 #include "chrome/common/pref_names.h"
88 #include "chromeos/audio/audio_devices_pref_handler_impl.h"
89 #include "chromeos/audio/cras_audio_handler.h"
90 #include "chromeos/cert_loader.h"
91 #include "chromeos/chromeos_paths.h"
92 #include "chromeos/chromeos_switches.h"
93 #include "chromeos/cryptohome/async_method_caller.h"
94 #include "chromeos/cryptohome/homedir_methods.h"
95 #include "chromeos/cryptohome/system_salt_getter.h"
96 #include "chromeos/dbus/dbus_thread_manager.h"
97 #include "chromeos/dbus/power_policy_controller.h"
98 #include "chromeos/dbus/services/console_service_provider.h"
99 #include "chromeos/dbus/services/cros_dbus_service.h"
100 #include "chromeos/dbus/services/display_power_service_provider.h"
101 #include "chromeos/dbus/services/liveness_service_provider.h"
102 #include "chromeos/dbus/services/proxy_resolution_service_provider.h"
103 #include "chromeos/dbus/session_manager_client.h"
104 #include "chromeos/disks/disk_mount_manager.h"
105 #include "chromeos/login/login_state.h"
106 #include "chromeos/login/user_names.h"
107 #include "chromeos/login_event_recorder.h"
108 #include "chromeos/network/network_change_notifier_chromeos.h"
109 #include "chromeos/network/network_change_notifier_factory_chromeos.h"
110 #include "chromeos/network/network_handler.h"
111 #include "chromeos/system/statistics_provider.h"
112 #include "chromeos/tpm/tpm_token_loader.h"
113 #include "components/metrics/metrics_service.h"
114 #include "components/ownership/owner_key_util.h"
115 #include "components/session_manager/core/session_manager.h"
116 #include "components/user_manager/user.h"
117 #include "components/user_manager/user_manager.h"
118 #include "components/wallpaper/wallpaper_manager_base.h"
119 #include "content/public/browser/browser_thread.h"
120 #include "content/public/browser/notification_service.h"
121 #include "content/public/common/main_function_params.h"
122 #include "device/bluetooth/bluetooth_adapter_factory.h"
123 #include "media/audio/sounds/sounds_manager.h"
124 #include "net/base/network_change_notifier.h"
125 #include "net/socket/ssl_server_socket.h"
126 #include "net/url_request/url_request.h"
127 #include "net/url_request/url_request_context_getter.h"
128 #include "ui/base/ime/chromeos/ime_keyboard.h"
129 #include "ui/base/ime/chromeos/input_method_manager.h"
130 #include "ui/base/touch/touch_device.h"
131 #include "ui/events/event_utils.h"
133 // Exclude X11 dependents for ozone
134 #if defined(USE_X11)
135 #include "chrome/browser/chromeos/device_uma.h"
136 #include "chrome/browser/chromeos/events/system_key_event_listener.h"
137 #include "chrome/browser/chromeos/events/xinput_hierarchy_changed_event_listener.h"
138 #endif
140 namespace chromeos {
142 namespace {
144 void ChromeOSVersionCallback(const std::string& version) {
145 base::SetLinuxDistro(std::string("CrOS ") + version);
148 bool ShouldAutoLaunchKioskApp(const base::CommandLine& command_line) {
149 KioskAppManager* app_manager = KioskAppManager::Get();
150 return command_line.HasSwitch(switches::kLoginManager) &&
151 !command_line.HasSwitch(switches::kForceLoginManagerInTests) &&
152 app_manager->IsAutoLaunchEnabled() &&
153 KioskAppLaunchError::Get() == KioskAppLaunchError::NONE;
156 } // namespace
158 namespace internal {
160 // Wrapper class for initializing dbus related services and shutting them
161 // down. This gets instantiated in a scoped_ptr so that shutdown methods in the
162 // destructor will get called if and only if this has been instantiated.
163 class DBusServices {
164 public:
165 explicit DBusServices(const content::MainFunctionParams& parameters) {
166 // Initialize DBusThreadManager for the browser. This must be done after
167 // the main message loop is started, as it uses the message loop.
168 DBusThreadManager::Initialize();
169 PowerPolicyController::Initialize(
170 DBusThreadManager::Get()->GetPowerManagerClient());
172 ScopedVector<CrosDBusService::ServiceProviderInterface> service_providers;
173 service_providers.push_back(ProxyResolutionServiceProvider::Create(
174 make_scoped_ptr(new ChromeProxyResolverDelegate())));
175 service_providers.push_back(new DisplayPowerServiceProvider(
176 make_scoped_ptr(new ChromeDisplayPowerServiceProviderDelegate)));
177 service_providers.push_back(new PrinterServiceProvider);
178 service_providers.push_back(new LivenessServiceProvider);
179 service_providers.push_back(new ScreenLockServiceProvider);
180 service_providers.push_back(new ConsoleServiceProvider(
181 make_scoped_ptr(new ChromeConsoleServiceProviderDelegate)));
182 CrosDBusService::Initialize(service_providers.Pass());
184 // Initialize PowerDataCollector after DBusThreadManager is initialized.
185 PowerDataCollector::Initialize();
187 LoginState::Initialize();
188 SystemSaltGetter::Initialize();
189 TPMTokenLoader::Initialize();
190 CertLoader::Initialize();
192 disks::DiskMountManager::Initialize();
193 cryptohome::AsyncMethodCaller::Initialize();
194 cryptohome::HomedirMethods::Initialize();
196 NetworkHandler::Initialize();
197 CertLibrary::Initialize();
199 // Initialize the network change notifier for Chrome OS. The network
200 // change notifier starts to monitor changes from the power manager and
201 // the network manager.
202 NetworkChangeNotifierFactoryChromeos::GetInstance()->Initialize();
204 // Initialize the NetworkConnect handler.
205 network_connect_delegate_.reset(new NetworkConnectDelegateChromeOS);
206 ui::NetworkConnect::Initialize(network_connect_delegate_.get());
208 // Likewise, initialize the upgrade detector for Chrome OS. The upgrade
209 // detector starts to monitor changes from the update engine.
210 UpgradeDetectorChromeos::GetInstance()->Init();
212 // Initialize the device settings service so that we'll take actions per
213 // signals sent from the session manager. This needs to happen before
214 // g_browser_process initializes BrowserPolicyConnector.
215 DeviceSettingsService::Initialize();
216 DeviceSettingsService::Get()->SetSessionManager(
217 DBusThreadManager::Get()->GetSessionManagerClient(),
218 OwnerSettingsServiceChromeOSFactory::GetInstance()->GetOwnerKeyUtil());
221 ~DBusServices() {
222 ui::NetworkConnect::Shutdown();
223 network_connect_delegate_.reset();
224 CertLibrary::Shutdown();
225 NetworkHandler::Shutdown();
226 cryptohome::AsyncMethodCaller::Shutdown();
227 disks::DiskMountManager::Shutdown();
228 SystemSaltGetter::Shutdown();
229 LoginState::Shutdown();
230 CertLoader::Shutdown();
231 TPMTokenLoader::Shutdown();
232 CrosDBusService::Shutdown();
233 PowerDataCollector::Shutdown();
234 PowerPolicyController::Shutdown();
235 device::BluetoothAdapterFactory::Shutdown();
237 // NOTE: This must only be called if Initialize() was called.
238 DBusThreadManager::Shutdown();
241 private:
242 scoped_ptr<NetworkConnectDelegateChromeOS> network_connect_delegate_;
244 DISALLOW_COPY_AND_ASSIGN(DBusServices);
247 } // namespace internal
249 // ChromeBrowserMainPartsChromeos ----------------------------------------------
251 ChromeBrowserMainPartsChromeos::ChromeBrowserMainPartsChromeos(
252 const content::MainFunctionParams& parameters)
253 : ChromeBrowserMainPartsLinux(parameters) {
256 ChromeBrowserMainPartsChromeos::~ChromeBrowserMainPartsChromeos() {
257 // To be precise, logout (browser shutdown) is not yet done, but the
258 // remaining work is negligible, hence we say LogoutDone here.
259 BootTimesRecorder::Get()->AddLogoutTimeMarker("LogoutDone", false);
260 BootTimesRecorder::Get()->WriteLogoutTimes();
263 // content::BrowserMainParts and ChromeBrowserMainExtraParts overrides ---------
265 void ChromeBrowserMainPartsChromeos::PreEarlyInitialization() {
266 base::CommandLine* singleton_command_line =
267 base::CommandLine::ForCurrentProcess();
269 if (parsed_command_line().HasSwitch(switches::kGuestSession)) {
270 // Disable sync and extensions if we're in "browse without sign-in" mode.
271 singleton_command_line->AppendSwitch(::switches::kDisableSync);
272 singleton_command_line->AppendSwitch(::switches::kDisableExtensions);
273 browser_defaults::bookmarks_enabled = false;
276 // If we're not running on real Chrome OS hardware (or under VM), and are not
277 // showing the login manager or attempting a command line login, login with a
278 // stub user.
279 if (!base::SysInfo::IsRunningOnChromeOS() &&
280 !parsed_command_line().HasSwitch(switches::kLoginManager) &&
281 !parsed_command_line().HasSwitch(switches::kLoginUser) &&
282 !parsed_command_line().HasSwitch(switches::kGuestSession)) {
283 singleton_command_line->AppendSwitchASCII(switches::kLoginUser,
284 chromeos::login::kStubUser);
285 if (!parsed_command_line().HasSwitch(switches::kLoginProfile)) {
286 singleton_command_line->AppendSwitchASCII(switches::kLoginProfile,
287 chrome::kTestUserProfileDir);
289 LOG(WARNING) << "Running as stub user with profile dir: "
290 << singleton_command_line->GetSwitchValuePath(
291 switches::kLoginProfile).value();
294 #if defined(GOOGLE_CHROME_BUILD)
295 const char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK";
296 std::string channel;
297 if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &channel))
298 chrome::VersionInfo::SetChannel(channel);
299 #endif
301 ChromeBrowserMainPartsLinux::PreEarlyInitialization();
304 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopStart() {
305 // Replace the default NetworkChangeNotifierFactory with ChromeOS specific
306 // implementation. This must be done before BrowserMainLoop calls
307 // net::NetworkChangeNotifier::Create() in MainMessageLoopStart().
308 net::NetworkChangeNotifier::SetFactory(
309 new NetworkChangeNotifierFactoryChromeos());
310 ChromeBrowserMainPartsLinux::PreMainMessageLoopStart();
313 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopStart() {
314 base::FilePath user_data_dir;
315 if (!base::SysInfo::IsRunningOnChromeOS() &&
316 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
317 // Override some paths with stub locations so that cloud policy and
318 // enterprise enrollment work on desktop builds, for ease of
319 // development.
320 chromeos::RegisterStubPathOverrides(user_data_dir);
323 dbus_services_.reset(new internal::DBusServices(parameters()));
325 // Enable support for SSL server sockets, which must be done while still
326 // single-threaded. This is required for remote assistance host on Chrome OS.
327 net::EnableSSLServerSockets();
329 ChromeBrowserMainPartsLinux::PostMainMessageLoopStart();
332 // Threads are initialized between MainMessageLoopStart and MainMessageLoopRun.
333 // about_flags settings are applied in ChromeBrowserMainParts::PreCreateThreads.
334 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopRun() {
335 // Set the crypto thread after the IO thread has been created/started.
336 TPMTokenLoader::Get()->SetCryptoTaskRunner(
337 content::BrowserThread::GetMessageLoopProxyForThread(
338 content::BrowserThread::IO));
340 CrasAudioHandler::Initialize(
341 new AudioDevicesPrefHandlerImpl(g_browser_process->local_state()));
343 // Start loading machine statistics here. StatisticsProvider::Shutdown()
344 // will ensure that loading is aborted on early exit.
345 bool load_oem_statistics = !StartupUtils::IsOobeCompleted();
346 system::StatisticsProvider::GetInstance()->StartLoadingMachineStatistics(
347 content::BrowserThread::GetMessageLoopProxyForThread(
348 content::BrowserThread::FILE),
349 load_oem_statistics);
351 base::FilePath downloads_directory;
352 CHECK(PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &downloads_directory));
354 DeviceOAuth2TokenServiceFactory::Initialize();
356 wake_on_wifi_manager_.reset(new WakeOnWifiManager());
358 ChromeBrowserMainPartsLinux::PreMainMessageLoopRun();
361 void ChromeBrowserMainPartsChromeos::PreProfileInit() {
362 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
363 // -- immediately before Profile creation().
365 // Now that the file thread exists we can record our stats.
366 BootTimesRecorder::Get()->RecordChromeMainStats();
367 LoginEventRecorder::Get()->SetDelegate(BootTimesRecorder::Get());
369 // Trigger prefetching of ownership status.
370 DeviceSettingsService::Get()->Load();
372 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
373 // -- just before CreateProfile().
375 g_browser_process->platform_part()->InitializeChromeUserManager();
377 ScreenLocker::InitClass();
379 // This forces the ProfileManager to be created and register for the
380 // notification it needs to track the logged in user.
381 g_browser_process->profile_manager();
383 // AccessibilityManager and SystemKeyEventListener use InputMethodManager.
384 input_method::Initialize();
386 // ProfileHelper has to be initialized after UserManager instance is created.
387 ProfileHelper::Get()->Initialize();
389 // TODO(abarth): Should this move to InitializeNetworkOptions()?
390 // Allow access to file:// on ChromeOS for tests.
391 if (parsed_command_line().HasSwitch(::switches::kAllowFileAccess))
392 ChromeNetworkDelegate::AllowAccessToAllFiles();
394 // If kLoginUser is passed this indicates that user has already
395 // logged in and we should behave accordingly.
396 bool immediate_login =
397 parsed_command_line().HasSwitch(switches::kLoginUser);
398 if (immediate_login) {
399 // Redirects Chrome logging to the user data dir.
400 logging::RedirectChromeLogging(parsed_command_line());
402 // Load the default app order synchronously for restarting case.
403 app_order_loader_.reset(
404 new default_app_order::ExternalLoader(false /* async */));
407 if (!app_order_loader_) {
408 app_order_loader_.reset(
409 new default_app_order::ExternalLoader(true /* async */));
412 media::SoundsManager::Create();
414 // Initialize magnification manager before ash tray is created. And this must
415 // be placed after UserManager::SessionStarted();
416 AccessibilityManager::Initialize();
417 MagnificationManager::Initialize();
419 wallpaper::WallpaperManagerBase::SetPathIds(
420 chrome::DIR_USER_DATA,
421 chrome::DIR_CHROMEOS_WALLPAPERS,
422 chrome::DIR_CHROMEOS_CUSTOM_WALLPAPERS);
424 // Add observers for WallpaperManager. This depends on PowerManagerClient,
425 // TimezoneSettings and CrosSettings.
426 WallpaperManager::Get()->AddObservers();
428 base::PostTaskAndReplyWithResult(
429 content::BrowserThread::GetBlockingPool(),
430 FROM_HERE,
431 base::Bind(&version_loader::GetVersion,
432 version_loader::VERSION_FULL),
433 base::Bind(&ChromeOSVersionCallback));
435 // Make sure that wallpaper boot transition and other delays in OOBE
436 // are disabled for tests and kiosk app launch by default.
437 // Individual tests may enable them if they want.
438 if (parsed_command_line().HasSwitch(::switches::kTestType) ||
439 ShouldAutoLaunchKioskApp(parsed_command_line())) {
440 WizardController::SetZeroDelays();
443 power_prefs_.reset(new PowerPrefs(PowerPolicyController::Get()));
445 // In Aura builds this will initialize ash::Shell.
446 ChromeBrowserMainPartsLinux::PreProfileInit();
448 if (immediate_login) {
449 const std::string user_id = login::CanonicalizeUserID(
450 parsed_command_line().GetSwitchValueASCII(switches::kLoginUser));
451 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
453 if (policy::IsDeviceLocalAccountUser(user_id, NULL) &&
454 !user_manager->IsKnownUser(user_id)) {
455 // When a device-local account is removed, its policy is deleted from disk
456 // immediately. If a session using this account happens to be in progress,
457 // the session is allowed to continue with policy served from an in-memory
458 // cache. If Chrome crashes later in the session, the policy becomes
459 // completely unavailable. Exit the session in that case, rather than
460 // allowing it to continue without policy.
461 chrome::AttemptUserExit();
462 return;
465 // In case of multi-profiles --login-profile will contain user_id_hash.
466 std::string user_id_hash =
467 parsed_command_line().GetSwitchValueASCII(switches::kLoginProfile);
468 user_manager->UserLoggedIn(user_id, user_id_hash, true);
469 VLOG(1) << "Relaunching browser for user: " << user_id
470 << " with hash: " << user_id_hash;
474 class GuestLanguageSetCallbackData {
475 public:
476 explicit GuestLanguageSetCallbackData(Profile* profile) : profile(profile) {
479 // Must match SwitchLanguageCallback type.
480 static void Callback(const scoped_ptr<GuestLanguageSetCallbackData>& self,
481 const locale_util::LanguageSwitchResult& result);
483 Profile* profile;
486 // static
487 void GuestLanguageSetCallbackData::Callback(
488 const scoped_ptr<GuestLanguageSetCallbackData>& self,
489 const locale_util::LanguageSwitchResult& result) {
490 input_method::InputMethodManager* manager =
491 input_method::InputMethodManager::Get();
492 scoped_refptr<input_method::InputMethodManager::State> ime_state =
493 manager->GetActiveIMEState();
494 // Active layout must be hardware "login layout".
495 // The previous one must be "locale default layout".
496 // First, enable all hardware input methods.
497 const std::vector<std::string>& input_methods =
498 manager->GetInputMethodUtil()->GetHardwareInputMethodIds();
499 for (size_t i = 0; i < input_methods.size(); ++i)
500 ime_state->EnableInputMethod(input_methods[i]);
502 // Second, enable locale based input methods.
503 const std::string locale_default_input_method =
504 manager->GetInputMethodUtil()->GetLanguageDefaultInputMethodId(
505 result.loaded_locale);
506 if (!locale_default_input_method.empty()) {
507 PrefService* user_prefs = self->profile->GetPrefs();
508 user_prefs->SetString(prefs::kLanguagePreviousInputMethod,
509 locale_default_input_method);
510 ime_state->EnableInputMethod(locale_default_input_method);
513 // Finally, activate the first login input method.
514 const std::vector<std::string>& login_input_methods =
515 manager->GetInputMethodUtil()->GetHardwareLoginInputMethodIds();
516 ime_state->ChangeInputMethod(login_input_methods[0],
517 false /* show_message */);
520 void SetGuestLocale(Profile* const profile) {
521 scoped_ptr<GuestLanguageSetCallbackData> data(
522 new GuestLanguageSetCallbackData(profile));
523 locale_util::SwitchLanguageCallback callback(base::Bind(
524 &GuestLanguageSetCallbackData::Callback, base::Passed(data.Pass())));
525 const user_manager::User* const user =
526 ProfileHelper::Get()->GetUserByProfile(profile);
527 UserSessionManager::GetInstance()->RespectLocalePreference(
528 profile, user, callback);
531 void ChromeBrowserMainPartsChromeos::PostProfileInit() {
532 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
533 // -- just after CreateProfile().
535 // Force loading of signin profile if it was not loaded before. It is possible
536 // when we are restoring session or skipping login screen for some other
537 // reason.
538 if (!chromeos::ProfileHelper::IsSigninProfile(profile()))
539 chromeos::ProfileHelper::GetSigninProfile();
541 BootTimesRecorder::Get()->OnChromeProcessStart();
543 // Initialize the network portal detector for Chrome OS. The network
544 // portal detector starts to listen for notifications from
545 // NetworkStateHandler and initiates captive portal detection for
546 // active networks. Should be called before call to CreateSessionManager,
547 // because it depends on NetworkPortalDetector.
548 NetworkPortalDetectorImpl::Initialize(
549 g_browser_process->system_request_context());
551 NetworkPortalDetector* detector = NetworkPortalDetector::Get();
552 #if defined(GOOGLE_CHROME_BUILD)
553 bool is_official_build = true;
554 #else
555 bool is_official_build = false;
556 #endif
557 // Enable portal detector if EULA was previously accepted or if
558 // this is an unofficial build.
559 if (!is_official_build || StartupUtils::IsEulaAccepted())
560 detector->Enable(true);
563 // Initialize input methods.
564 input_method::InputMethodManager* manager =
565 input_method::InputMethodManager::Get();
566 UserSessionManager* session_manager = UserSessionManager::GetInstance();
567 DCHECK(manager);
568 DCHECK(session_manager);
570 manager->SetState(session_manager->GetDefaultIMEState(profile()));
572 bool is_running_test = parameters().ui_task != NULL;
573 g_browser_process->platform_part()->InitializeSessionManager(
574 parsed_command_line(), profile(), is_running_test);
575 g_browser_process->platform_part()->SessionManager()->Start();
577 // Guest user profile is never initialized with locale settings,
578 // so we need special handling for Guest session.
579 if (user_manager::UserManager::Get()->IsLoggedInAsGuest())
580 SetGuestLocale(profile());
582 peripheral_battery_observer_.reset(new PeripheralBatteryObserver());
584 renderer_freezer_.reset(
585 new RendererFreezer(scoped_ptr<RendererFreezer::Delegate>(
586 new FreezerCgroupProcessManager())));
588 g_browser_process->platform_part()->InitializeAutomaticRebootManager();
589 g_browser_process->platform_part()->InitializeDeviceDisablingManager();
591 // This observer cannot be created earlier because it requires the shell to be
592 // available.
593 idle_action_warning_observer_.reset(new IdleActionWarningObserver());
595 ChromeBrowserMainPartsLinux::PostProfileInit();
598 void ChromeBrowserMainPartsChromeos::PreBrowserStart() {
599 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
600 // -- just before MetricsService::LogNeedForCleanShutdown().
602 // Start the external metrics service, which collects metrics from Chrome OS
603 // and passes them to the browser process.
604 external_metrics_ = new chromeos::ExternalMetrics;
605 external_metrics_->Start();
607 #if defined(USE_X11)
608 // Listen for system key events so that the user will be able to adjust the
609 // volume on the login screen, if Chrome is running on Chrome OS
610 // (i.e. not Linux desktop), and in non-test mode.
611 // Note: SystemKeyEventListener depends on the DBus thread.
612 if (base::SysInfo::IsRunningOnChromeOS() &&
613 !parameters().ui_task) { // ui_task is non-NULL when running tests.
614 SystemKeyEventListener::Initialize();
617 // Listen for XI_HierarchyChanged events. Note: if this is moved to
618 // PreMainMessageLoopRun() then desktopui_PageCyclerTests fail for unknown
619 // reasons, see http://crosbug.com/24833.
620 XInputHierarchyChangedEventListener::GetInstance();
622 // Start the CrOS input device UMA watcher
623 DeviceUMA::GetInstance();
624 #endif
626 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
627 // -- immediately after ChildProcess::WaitForDebugger().
629 // Start the out-of-memory priority manager here so that we give the most
630 // amount of time for the other services to start up before we start
631 // adjusting the oom priority.
632 g_browser_process->platform_part()->oom_priority_manager()->Start();
634 if (ui::ShouldDefaultToNaturalScroll()) {
635 base::CommandLine::ForCurrentProcess()->AppendSwitch(
636 chromeos::switches::kNaturalScrollDefault);
637 system::InputDeviceSettings::Get()->SetTapToClick(true);
640 ChromeBrowserMainPartsLinux::PreBrowserStart();
643 void ChromeBrowserMainPartsChromeos::PostBrowserStart() {
644 // These are dependent on the ash::Shell singleton already having been
645 // initialized.
646 // TODO(oshima): Remove ash dependency in PowerButtonObserver.
647 // crbug.com/408832.
648 power_button_observer_.reset(new PowerButtonObserver);
649 data_promo_notification_.reset(new DataPromoNotification());
651 keyboard_event_rewriters_.reset(new EventRewriterController());
652 keyboard_event_rewriters_->AddEventRewriter(
653 scoped_ptr<ui::EventRewriter>(new KeyboardDrivenEventRewriter()));
654 keyboard_event_rewriters_->AddEventRewriter(scoped_ptr<ui::EventRewriter>(
655 new EventRewriter(ash::Shell::GetInstance()->sticky_keys_controller())));
656 keyboard_event_rewriters_->Init();
658 ChromeBrowserMainPartsLinux::PostBrowserStart();
661 // Shut down services before the browser process, etc are destroyed.
662 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopRun() {
663 BootTimesRecorder::Get()->AddLogoutTimeMarker("UIMessageLoopEnded", true);
665 g_browser_process->platform_part()->oom_priority_manager()->Stop();
667 // Early wake-up of HID device service.
668 InputServiceProxy::WarmUp();
670 // Destroy the application name notifier for Kiosk mode.
671 KioskModeIdleAppNameNotification::Shutdown();
673 // Shutdown the upgrade detector for Chrome OS. The upgrade detector
674 // stops monitoring changes from the update engine.
675 if (UpgradeDetectorChromeos::GetInstance())
676 UpgradeDetectorChromeos::GetInstance()->Shutdown();
678 // Shutdown the network change notifier for Chrome OS. The network
679 // change notifier stops monitoring changes from the power manager and
680 // the network manager.
681 if (NetworkChangeNotifierFactoryChromeos::GetInstance())
682 NetworkChangeNotifierFactoryChromeos::GetInstance()->Shutdown();
684 // Destroy UI related classes before destroying services that they may
685 // depend on.
686 data_promo_notification_.reset();
688 // Tell DeviceSettingsService to stop talking to session_manager. Do not
689 // shutdown DeviceSettingsService yet, it might still be accessed by
690 // BrowserPolicyConnector (owned by g_browser_process).
691 DeviceSettingsService::Get()->UnsetSessionManager();
693 // We should remove observers attached to D-Bus clients before
694 // DBusThreadManager is shut down.
695 peripheral_battery_observer_.reset();
696 power_prefs_.reset();
697 renderer_freezer_.reset();
698 wake_on_wifi_manager_.reset();
699 ScreenLocker::ShutDownClass();
700 keyboard_event_rewriters_.reset();
701 #if defined(USE_X11)
702 // The XInput2 event listener needs to be shut down earlier than when
703 // Singletons are finally destroyed in AtExitManager.
704 XInputHierarchyChangedEventListener::GetInstance()->Stop();
706 DeviceUMA::GetInstance()->Stop();
708 // SystemKeyEventListener::Shutdown() is always safe to call,
709 // even if Initialize() wasn't called.
710 SystemKeyEventListener::Shutdown();
711 #endif
713 // Detach D-Bus clients before DBusThreadManager is shut down.
714 power_button_observer_.reset();
715 idle_action_warning_observer_.reset();
717 MagnificationManager::Shutdown();
719 AccessibilityManager::Shutdown();
721 media::SoundsManager::Shutdown();
723 system::StatisticsProvider::GetInstance()->Shutdown();
725 // Let the UserManager and WallpaperManager unregister itself as an observer
726 // of the CrosSettings singleton before it is destroyed. This also ensures
727 // that the UserManager has no URLRequest pending (see
728 // http://crbug.com/276659).
729 g_browser_process->platform_part()->user_manager()->Shutdown();
730 WallpaperManager::Get()->Shutdown();
732 // Let the DeviceDisablingManager unregister itself as an observer of the
733 // CrosSettings singleton before it is destroyed.
734 g_browser_process->platform_part()->ShutdownDeviceDisablingManager();
736 // Let the AutomaticRebootManager unregister itself as an observer of several
737 // subsystems.
738 g_browser_process->platform_part()->ShutdownAutomaticRebootManager();
740 // Clean up dependency on CrosSettings and stop pending data fetches.
741 KioskAppManager::Shutdown();
743 // Give BrowserPolicyConnectorChromeOS a chance to unregister any observers
744 // on services that are going to be deleted later but before its Shutdown()
745 // is called.
746 g_browser_process->platform_part()->browser_policy_connector_chromeos()->
747 PreShutdown();
749 // We first call PostMainMessageLoopRun and then destroy UserManager, because
750 // Ash needs to be closed before UserManager is destroyed.
751 ChromeBrowserMainPartsLinux::PostMainMessageLoopRun();
753 input_method::Shutdown();
755 // Stops all in-flight OAuth2 token fetchers before the IO thread stops.
756 DeviceOAuth2TokenServiceFactory::Shutdown();
758 // Shutdown after PostMainMessageLoopRun() which should destroy all observers.
759 CrasAudioHandler::Shutdown();
761 // Called after
762 // ChromeBrowserMainPartsLinux::PostMainMessageLoopRun() to be
763 // executed after execution of chrome::CloseAsh(), because some
764 // parts of WebUI depends on NetworkPortalDetector.
765 NetworkPortalDetector::Shutdown();
767 g_browser_process->platform_part()->DestroyChromeUserManager();
769 g_browser_process->platform_part()->ShutdownSessionManager();
772 void ChromeBrowserMainPartsChromeos::PostDestroyThreads() {
773 // Destroy DBus services immediately after threads are stopped.
774 dbus_services_.reset();
776 ChromeBrowserMainPartsLinux::PostDestroyThreads();
778 // Destroy DeviceSettingsService after g_browser_process.
779 DeviceSettingsService::Shutdown();
782 } // namespace chromeos