Updates the mic icon status based on the device's audio state (2nd)
[chromium-blink-merge.git] / chrome / browser / chromeos / chrome_browser_main_chromeos.cc
blob58ae1d8752ddfab93a9809c4c96ef4bedcbd1a82
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 "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/chrome_console_service_provider_delegate.h"
33 #include "chrome/browser/chromeos/dbus/chrome_display_power_service_provider_delegate.h"
34 #include "chrome/browser/chromeos/dbus/chrome_proxy_resolver_delegate.h"
35 #include "chrome/browser/chromeos/dbus/printer_service_provider.h"
36 #include "chrome/browser/chromeos/dbus/screen_lock_service_provider.h"
37 #include "chrome/browser/chromeos/device/input_service_proxy.h"
38 #include "chrome/browser/chromeos/events/event_rewriter.h"
39 #include "chrome/browser/chromeos/events/event_rewriter_controller.h"
40 #include "chrome/browser/chromeos/events/keyboard_driven_event_rewriter.h"
41 #include "chrome/browser/chromeos/extensions/default_app_order.h"
42 #include "chrome/browser/chromeos/extensions/extension_system_event_observer.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/kiosk_mode/kiosk_mode_settings.h"
47 #include "chrome/browser/chromeos/language_preferences.h"
48 #include "chrome/browser/chromeos/login/helper.h"
49 #include "chrome/browser/chromeos/login/lock/screen_locker.h"
50 #include "chrome/browser/chromeos/login/login_wizard.h"
51 #include "chrome/browser/chromeos/login/session/user_session_manager.h"
52 #include "chrome/browser/chromeos/login/startup_utils.h"
53 #include "chrome/browser/chromeos/login/users/chrome_user_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/light_bar.h"
65 #include "chrome/browser/chromeos/power/peripheral_battery_observer.h"
66 #include "chrome/browser/chromeos/power/power_button_observer.h"
67 #include "chrome/browser/chromeos/power/power_data_collector.h"
68 #include "chrome/browser/chromeos/power/power_prefs.h"
69 #include "chrome/browser/chromeos/power/renderer_freezer.h"
70 #include "chrome/browser/chromeos/profiles/profile_helper.h"
71 #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h"
72 #include "chrome/browser/chromeos/settings/device_settings_service.h"
73 #include "chrome/browser/chromeos/status/data_promo_notification.h"
74 #include "chrome/browser/chromeos/system/input_device_settings.h"
75 #include "chrome/browser/chromeos/upgrade_detector_chromeos.h"
76 #include "chrome/browser/defaults.h"
77 #include "chrome/browser/lifetime/application_lifetime.h"
78 #include "chrome/browser/net/chrome_network_delegate.h"
79 #include "chrome/browser/profiles/profile.h"
80 #include "chrome/browser/profiles/profile_manager.h"
81 #include "chrome/browser/rlz/rlz.h"
82 #include "chrome/browser/ui/ash/network_connect_delegate_chromeos.h"
83 #include "chrome/common/chrome_constants.h"
84 #include "chrome/common/chrome_paths.h"
85 #include "chrome/common/chrome_switches.h"
86 #include "chrome/common/chrome_version_info.h"
87 #include "chrome/common/logging_chrome.h"
88 #include "chrome/common/pref_names.h"
89 #include "chromeos/audio/audio_devices_pref_handler.h"
90 #include "chromeos/audio/cras_audio_handler.h"
91 #include "chromeos/cert_loader.h"
92 #include "chromeos/chromeos_paths.h"
93 #include "chromeos/chromeos_switches.h"
94 #include "chromeos/cryptohome/async_method_caller.h"
95 #include "chromeos/cryptohome/homedir_methods.h"
96 #include "chromeos/cryptohome/system_salt_getter.h"
97 #include "chromeos/dbus/dbus_thread_manager.h"
98 #include "chromeos/dbus/power_policy_controller.h"
99 #include "chromeos/dbus/services/console_service_provider.h"
100 #include "chromeos/dbus/services/cros_dbus_service.h"
101 #include "chromeos/dbus/services/display_power_service_provider.h"
102 #include "chromeos/dbus/services/liveness_service_provider.h"
103 #include "chromeos/dbus/services/proxy_resolution_service_provider.h"
104 #include "chromeos/dbus/session_manager_client.h"
105 #include "chromeos/disks/disk_mount_manager.h"
106 #include "chromeos/login/login_state.h"
107 #include "chromeos/login/user_names.h"
108 #include "chromeos/login_event_recorder.h"
109 #include "chromeos/network/network_change_notifier_chromeos.h"
110 #include "chromeos/network/network_change_notifier_factory_chromeos.h"
111 #include "chromeos/network/network_handler.h"
112 #include "chromeos/system/statistics_provider.h"
113 #include "chromeos/tpm_token_loader.h"
114 #include "components/metrics/metrics_service.h"
115 #include "components/ownership/owner_key_util.h"
116 #include "components/session_manager/core/session_manager.h"
117 #include "components/user_manager/user.h"
118 #include "components/user_manager/user_manager.h"
119 #include "content/public/browser/browser_thread.h"
120 #include "content/public/browser/notification_service.h"
121 #include "content/public/browser/power_save_blocker.h"
122 #include "content/public/common/main_function_params.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 #if !defined(USE_ATHENA)
141 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_idle_logout.h"
142 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_screensaver.h"
143 #include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h"
144 #endif
146 namespace chromeos {
148 namespace {
150 void ChromeOSVersionCallback(const std::string& version) {
151 base::SetLinuxDistro(std::string("CrOS ") + version);
154 bool ShouldAutoLaunchKioskApp(const base::CommandLine& command_line) {
155 KioskAppManager* app_manager = KioskAppManager::Get();
156 return command_line.HasSwitch(switches::kLoginManager) &&
157 !command_line.HasSwitch(switches::kForceLoginManagerInTests) &&
158 app_manager->IsAutoLaunchEnabled() &&
159 KioskAppLaunchError::Get() == KioskAppLaunchError::NONE;
162 } // namespace
164 namespace internal {
166 // Wrapper class for initializing dbus related services and shutting them
167 // down. This gets instantiated in a scoped_ptr so that shutdown methods in the
168 // destructor will get called if and only if this has been instantiated.
169 class DBusServices {
170 public:
171 explicit DBusServices(const content::MainFunctionParams& parameters) {
172 // Initialize DBusThreadManager for the browser. This must be done after
173 // the main message loop is started, as it uses the message loop.
174 DBusThreadManager::Initialize();
175 PowerPolicyController::Initialize(
176 DBusThreadManager::Get()->GetPowerManagerClient());
178 ScopedVector<CrosDBusService::ServiceProviderInterface> service_providers;
179 service_providers.push_back(ProxyResolutionServiceProvider::Create(
180 make_scoped_ptr(new ChromeProxyResolverDelegate())));
181 #if !defined(USE_ATHENA)
182 // crbug.com/413897
183 service_providers.push_back(new DisplayPowerServiceProvider(
184 make_scoped_ptr(new ChromeDisplayPowerServiceProviderDelegate)));
185 // crbug.com/401285
186 service_providers.push_back(new PrinterServiceProvider);
187 #endif
188 service_providers.push_back(new LivenessServiceProvider);
189 service_providers.push_back(new ScreenLockServiceProvider);
190 service_providers.push_back(new ConsoleServiceProvider(
191 make_scoped_ptr(new ChromeConsoleServiceProviderDelegate)));
192 CrosDBusService::Initialize(service_providers.Pass());
194 // Initialize PowerDataCollector after DBusThreadManager is initialized.
195 PowerDataCollector::Initialize();
197 LoginState::Initialize();
198 SystemSaltGetter::Initialize();
199 TPMTokenLoader::Initialize();
200 CertLoader::Initialize();
202 disks::DiskMountManager::Initialize();
203 cryptohome::AsyncMethodCaller::Initialize();
204 cryptohome::HomedirMethods::Initialize();
206 NetworkHandler::Initialize();
207 CertLibrary::Initialize();
209 // Initialize the network change notifier for Chrome OS. The network
210 // change notifier starts to monitor changes from the power manager and
211 // the network manager.
212 NetworkChangeNotifierFactoryChromeos::GetInstance()->Initialize();
214 // Initialize the NetworkConnect handler.
215 network_connect_delegate_.reset(new NetworkConnectDelegateChromeOS);
216 ui::NetworkConnect::Initialize(network_connect_delegate_.get());
218 // Likewise, initialize the upgrade detector for Chrome OS. The upgrade
219 // detector starts to monitor changes from the update engine.
220 UpgradeDetectorChromeos::GetInstance()->Init();
222 // Initialize the device settings service so that we'll take actions per
223 // signals sent from the session manager. This needs to happen before
224 // g_browser_process initializes BrowserPolicyConnector.
225 DeviceSettingsService::Initialize();
226 DeviceSettingsService::Get()->SetSessionManager(
227 DBusThreadManager::Get()->GetSessionManagerClient(),
228 OwnerSettingsServiceChromeOSFactory::GetInstance()->GetOwnerKeyUtil());
231 ~DBusServices() {
232 ui::NetworkConnect::Shutdown();
233 network_connect_delegate_.reset();
235 CertLibrary::Shutdown();
236 NetworkHandler::Shutdown();
238 cryptohome::AsyncMethodCaller::Shutdown();
239 disks::DiskMountManager::Shutdown();
241 SystemSaltGetter::Shutdown();
242 LoginState::Shutdown();
243 CertLoader::Shutdown();
244 TPMTokenLoader::Shutdown();
246 CrosDBusService::Shutdown();
248 // Shutdown the PowerDataCollector before shutting down DBusThreadManager.
249 PowerDataCollector::Shutdown();
251 PowerPolicyController::Shutdown();
253 // NOTE: This must only be called if Initialize() was called.
254 DBusThreadManager::Shutdown();
257 private:
258 scoped_ptr<NetworkConnectDelegateChromeOS> network_connect_delegate_;
260 DISALLOW_COPY_AND_ASSIGN(DBusServices);
263 } // namespace internal
265 // ChromeBrowserMainPartsChromeos ----------------------------------------------
267 ChromeBrowserMainPartsChromeos::ChromeBrowserMainPartsChromeos(
268 const content::MainFunctionParams& parameters)
269 : ChromeBrowserMainPartsLinux(parameters) {
272 ChromeBrowserMainPartsChromeos::~ChromeBrowserMainPartsChromeos() {
273 #if !defined(USE_ATHENA)
274 if (KioskModeSettings::Get()->IsKioskModeEnabled())
275 ShutdownKioskModeScreensaver();
276 #endif
278 // To be precise, logout (browser shutdown) is not yet done, but the
279 // remaining work is negligible, hence we say LogoutDone here.
280 BootTimesLoader::Get()->AddLogoutTimeMarker("LogoutDone", false);
281 BootTimesLoader::Get()->WriteLogoutTimes();
284 // content::BrowserMainParts and ChromeBrowserMainExtraParts overrides ---------
286 void ChromeBrowserMainPartsChromeos::PreEarlyInitialization() {
287 CommandLine* singleton_command_line = CommandLine::ForCurrentProcess();
289 if (parsed_command_line().HasSwitch(switches::kGuestSession)) {
290 // Disable sync and extensions if we're in "browse without sign-in" mode.
291 singleton_command_line->AppendSwitch(::switches::kDisableSync);
292 singleton_command_line->AppendSwitch(::switches::kDisableExtensions);
293 browser_defaults::bookmarks_enabled = false;
296 // If we're not running on real Chrome OS hardware (or under VM), and are not
297 // showing the login manager or attempting a command line login, login with a
298 // stub user.
299 if (!base::SysInfo::IsRunningOnChromeOS() &&
300 !parsed_command_line().HasSwitch(switches::kLoginManager) &&
301 !parsed_command_line().HasSwitch(switches::kLoginUser) &&
302 !parsed_command_line().HasSwitch(switches::kGuestSession)) {
303 singleton_command_line->AppendSwitchASCII(switches::kLoginUser,
304 chromeos::login::kStubUser);
305 if (!parsed_command_line().HasSwitch(switches::kLoginProfile)) {
306 singleton_command_line->AppendSwitchASCII(switches::kLoginProfile,
307 chrome::kTestUserProfileDir);
309 LOG(WARNING) << "Running as stub user with profile dir: "
310 << singleton_command_line->GetSwitchValuePath(
311 switches::kLoginProfile).value();
314 #if defined(GOOGLE_CHROME_BUILD)
315 const char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK";
316 std::string channel;
317 if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &channel))
318 chrome::VersionInfo::SetChannel(channel);
319 #endif
321 ChromeBrowserMainPartsLinux::PreEarlyInitialization();
324 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopStart() {
325 // Replace the default NetworkChangeNotifierFactory with ChromeOS specific
326 // implementation. This must be done before BrowserMainLoop calls
327 // net::NetworkChangeNotifier::Create() in MainMessageLoopStart().
328 net::NetworkChangeNotifier::SetFactory(
329 new NetworkChangeNotifierFactoryChromeos());
330 ChromeBrowserMainPartsLinux::PreMainMessageLoopStart();
333 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopStart() {
334 base::FilePath user_data_dir;
335 if (!base::SysInfo::IsRunningOnChromeOS() &&
336 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
337 // Override some paths with stub locations so that cloud policy and
338 // enterprise enrollment work on desktop builds, for ease of
339 // development.
340 chromeos::RegisterStubPathOverrides(user_data_dir);
343 dbus_services_.reset(new internal::DBusServices(parameters()));
345 // Enable support for SSL server sockets, which must be done while still
346 // single-threaded. This is required for remote assistance host on Chrome OS.
347 net::EnableSSLServerSockets();
349 ChromeBrowserMainPartsLinux::PostMainMessageLoopStart();
352 // Threads are initialized between MainMessageLoopStart and MainMessageLoopRun.
353 // about_flags settings are applied in ChromeBrowserMainParts::PreCreateThreads.
354 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopRun() {
355 // Set the crypto thread after the IO thread has been created/started.
356 TPMTokenLoader::Get()->SetCryptoTaskRunner(
357 content::BrowserThread::GetMessageLoopProxyForThread(
358 content::BrowserThread::IO));
360 CrasAudioHandler::Initialize(
361 AudioDevicesPrefHandler::Create(g_browser_process->local_state()));
363 // Start loading machine statistics here. StatisticsProvider::Shutdown()
364 // will ensure that loading is aborted on early exit.
365 bool load_oem_statistics = !StartupUtils::IsOobeCompleted();
366 system::StatisticsProvider::GetInstance()->StartLoadingMachineStatistics(
367 content::BrowserThread::GetMessageLoopProxyForThread(
368 content::BrowserThread::FILE),
369 load_oem_statistics);
371 base::FilePath downloads_directory;
372 CHECK(PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &downloads_directory));
374 DeviceOAuth2TokenServiceFactory::Initialize();
376 wake_on_wifi_manager_.reset(new WakeOnWifiManager());
378 ChromeBrowserMainPartsLinux::PreMainMessageLoopRun();
381 void ChromeBrowserMainPartsChromeos::PreProfileInit() {
382 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
383 // -- immediately before Profile creation().
385 // Now that the file thread exists we can record our stats.
386 BootTimesLoader::Get()->RecordChromeMainStats();
387 LoginEventRecorder::Get()->SetDelegate(BootTimesLoader::Get());
389 // Trigger prefetching of ownership status.
390 DeviceSettingsService::Get()->Load();
392 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
393 // -- just before CreateProfile().
395 g_browser_process->platform_part()->InitializeChromeUserManager();
397 #if defined(USE_ATHENA)
398 ScreenLocker::InitClass();
399 #else
400 // Initialize the screen locker now so that it can receive
401 // LOGIN_USER_CHANGED notification from UserManager.
402 if (KioskModeSettings::Get()->IsKioskModeEnabled())
403 KioskModeIdleLogout::Initialize();
404 else
405 ScreenLocker::InitClass();
406 #endif
408 // This forces the ProfileManager to be created and register for the
409 // notification it needs to track the logged in user.
410 g_browser_process->profile_manager();
412 // AccessibilityManager and SystemKeyEventListener use InputMethodManager.
413 input_method::Initialize();
415 // ProfileHelper has to be initialized after UserManager instance is created.
416 ProfileHelper::Get()->Initialize();
418 // TODO(abarth): Should this move to InitializeNetworkOptions()?
419 // Allow access to file:// on ChromeOS for tests.
420 if (parsed_command_line().HasSwitch(::switches::kAllowFileAccess))
421 ChromeNetworkDelegate::AllowAccessToAllFiles();
423 // If kLoginUser is passed this indicates that user has already
424 // logged in and we should behave accordingly.
425 bool immediate_login =
426 parsed_command_line().HasSwitch(switches::kLoginUser);
427 if (immediate_login){
428 // Redirects Chrome logging to the user data dir.
429 logging::RedirectChromeLogging(parsed_command_line());
431 // Load the default app order synchronously for restarting case.
432 app_order_loader_.reset(
433 new default_app_order::ExternalLoader(false /* async */));
436 if (!app_order_loader_) {
437 app_order_loader_.reset(
438 new default_app_order::ExternalLoader(true /* async */));
441 media::SoundsManager::Create();
443 // Initialize magnification manager before ash tray is created. And this must
444 // be placed after UserManager::SessionStarted();
445 AccessibilityManager::Initialize();
446 #if !defined(USE_ATHENA)
447 // TODO(oshima): MagnificationManager/WallpaperManager depends on ash.
448 // crbug.com/408733, crbug.com/408734.
449 MagnificationManager::Initialize();
451 // Add observers for WallpaperManager. This depends on PowerManagerClient,
452 // TimezoneSettings and CrosSettings.
453 WallpaperManager::Get()->AddObservers();
454 #endif
456 cros_version_loader_.GetVersion(VersionLoader::VERSION_FULL,
457 base::Bind(&ChromeOSVersionCallback),
458 &tracker_);
460 // Make sure that wallpaper boot transition and other delays in OOBE
461 // are disabled for tests and kiosk app launch by default.
462 // Individual tests may enable them if they want.
463 if (parsed_command_line().HasSwitch(::switches::kTestType) ||
464 ShouldAutoLaunchKioskApp(parsed_command_line())) {
465 WizardController::SetZeroDelays();
468 power_prefs_.reset(new PowerPrefs(PowerPolicyController::Get()));
470 // In Aura builds this will initialize ash::Shell.
471 ChromeBrowserMainPartsLinux::PreProfileInit();
473 if (immediate_login) {
474 const std::string user_id = login::CanonicalizeUserID(
475 parsed_command_line().GetSwitchValueASCII(switches::kLoginUser));
476 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
478 if (policy::IsDeviceLocalAccountUser(user_id, NULL) &&
479 !user_manager->IsKnownUser(user_id)) {
480 // When a device-local account is removed, its policy is deleted from disk
481 // immediately. If a session using this account happens to be in progress,
482 // the session is allowed to continue with policy served from an in-memory
483 // cache. If Chrome crashes later in the session, the policy becomes
484 // completely unavailable. Exit the session in that case, rather than
485 // allowing it to continue without policy.
486 chrome::AttemptUserExit();
487 return;
490 // In case of multi-profiles --login-profile will contain user_id_hash.
491 std::string user_id_hash =
492 parsed_command_line().GetSwitchValueASCII(switches::kLoginProfile);
493 user_manager->UserLoggedIn(user_id, user_id_hash, true);
494 VLOG(1) << "Relaunching browser for user: " << user_id
495 << " with hash: " << user_id_hash;
499 class GuestLanguageSetCallbackData {
500 public:
501 explicit GuestLanguageSetCallbackData(Profile* profile) : profile(profile) {
504 // Must match SwitchLanguageCallback type.
505 static void Callback(const scoped_ptr<GuestLanguageSetCallbackData>& self,
506 const locale_util::LanguageSwitchResult& result);
508 Profile* profile;
511 // static
512 void GuestLanguageSetCallbackData::Callback(
513 const scoped_ptr<GuestLanguageSetCallbackData>& self,
514 const locale_util::LanguageSwitchResult& result) {
515 input_method::InputMethodManager* manager =
516 input_method::InputMethodManager::Get();
517 scoped_refptr<input_method::InputMethodManager::State> ime_state =
518 manager->GetActiveIMEState();
519 // Active layout must be hardware "login layout".
520 // The previous one must be "locale default layout".
521 // First, enable all hardware input methods.
522 const std::vector<std::string>& input_methods =
523 manager->GetInputMethodUtil()->GetHardwareInputMethodIds();
524 for (size_t i = 0; i < input_methods.size(); ++i)
525 ime_state->EnableInputMethod(input_methods[i]);
527 // Second, enable locale based input methods.
528 const std::string locale_default_input_method =
529 manager->GetInputMethodUtil()->GetLanguageDefaultInputMethodId(
530 result.loaded_locale);
531 if (!locale_default_input_method.empty()) {
532 PrefService* user_prefs = self->profile->GetPrefs();
533 user_prefs->SetString(prefs::kLanguagePreviousInputMethod,
534 locale_default_input_method);
535 ime_state->EnableInputMethod(locale_default_input_method);
538 // Finally, activate the first login input method.
539 const std::vector<std::string>& login_input_methods =
540 manager->GetInputMethodUtil()->GetHardwareLoginInputMethodIds();
541 ime_state->ChangeInputMethod(login_input_methods[0],
542 false /* show_message */);
545 void SetGuestLocale(Profile* const profile) {
546 scoped_ptr<GuestLanguageSetCallbackData> data(
547 new GuestLanguageSetCallbackData(profile));
548 locale_util::SwitchLanguageCallback callback(base::Bind(
549 &GuestLanguageSetCallbackData::Callback, base::Passed(data.Pass())));
550 user_manager::User* const user =
551 ProfileHelper::Get()->GetUserByProfile(profile);
552 UserSessionManager::GetInstance()->RespectLocalePreference(
553 profile, user, callback);
556 void ChromeBrowserMainPartsChromeos::PostProfileInit() {
557 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
558 // -- just after CreateProfile().
560 BootTimesLoader::Get()->OnChromeProcessStart();
562 // Initialize the network portal detector for Chrome OS. The network
563 // portal detector starts to listen for notifications from
564 // NetworkStateHandler and initiates captive portal detection for
565 // active networks. Should be called before call to CreateSessionManager,
566 // because it depends on NetworkPortalDetector.
567 NetworkPortalDetectorImpl::Initialize(
568 g_browser_process->system_request_context());
570 NetworkPortalDetector* detector = NetworkPortalDetector::Get();
571 #if defined(GOOGLE_CHROME_BUILD)
572 bool is_official_build = true;
573 #else
574 bool is_official_build = false;
575 #endif
576 // Enable portal detector if EULA was previously accepted or if
577 // this is an unofficial build.
578 if (!is_official_build || StartupUtils::IsEulaAccepted())
579 detector->Enable(true);
582 // Initialize input methods.
583 input_method::InputMethodManager* manager =
584 input_method::InputMethodManager::Get();
585 UserSessionManager* session_manager = UserSessionManager::GetInstance();
586 DCHECK(manager);
587 DCHECK(session_manager);
589 manager->SetState(session_manager->GetDefaultIMEState(profile()));
591 bool is_running_test = parameters().ui_task != NULL;
592 g_browser_process->platform_part()->InitializeSessionManager(
593 parsed_command_line(), profile(), is_running_test);
594 g_browser_process->platform_part()->SessionManager()->Start();
596 // Guest user profile is never initialized with locale settings,
597 // so we need special handling for Guest session.
598 if (user_manager::UserManager::Get()->IsLoggedInAsGuest())
599 SetGuestLocale(profile());
601 // These observers must be initialized after the profile because
602 // they use the profile to dispatch extension events.
603 extension_system_event_observer_.reset(new ExtensionSystemEventObserver());
604 if (KioskModeSettings::Get()->IsKioskModeEnabled()) {
605 retail_mode_power_save_blocker_ = content::PowerSaveBlocker::Create(
606 content::PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
607 "Retail mode");
610 peripheral_battery_observer_.reset(new PeripheralBatteryObserver());
612 renderer_freezer_.reset(
613 new RendererFreezer(scoped_ptr<RendererFreezer::Delegate>(
614 new FreezerCgroupProcessManager())));
615 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kWakeOnPackets))
616 light_bar_.reset(new LightBar());
618 g_browser_process->platform_part()->InitializeAutomaticRebootManager();
619 g_browser_process->platform_part()->InitializeDeviceDisablingManager();
621 // This observer cannot be created earlier because it requires the shell to be
622 // available.
623 idle_action_warning_observer_.reset(new IdleActionWarningObserver());
625 ChromeBrowserMainPartsLinux::PostProfileInit();
628 void ChromeBrowserMainPartsChromeos::PreBrowserStart() {
629 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
630 // -- just before MetricsService::LogNeedForCleanShutdown().
632 // Start the external metrics service, which collects metrics from Chrome OS
633 // and passes them to the browser process.
634 external_metrics_ = new chromeos::ExternalMetrics;
635 external_metrics_->Start();
637 #if defined(USE_X11)
638 // Listen for system key events so that the user will be able to adjust the
639 // volume on the login screen, if Chrome is running on Chrome OS
640 // (i.e. not Linux desktop), and in non-test mode.
641 // Note: SystemKeyEventListener depends on the DBus thread.
642 if (base::SysInfo::IsRunningOnChromeOS() &&
643 !parameters().ui_task) { // ui_task is non-NULL when running tests.
644 SystemKeyEventListener::Initialize();
647 // Listen for XI_HierarchyChanged events. Note: if this is moved to
648 // PreMainMessageLoopRun() then desktopui_PageCyclerTests fail for unknown
649 // reasons, see http://crosbug.com/24833.
650 XInputHierarchyChangedEventListener::GetInstance();
652 // Start the CrOS input device UMA watcher
653 DeviceUMA::GetInstance();
654 #endif
656 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
657 // -- immediately after ChildProcess::WaitForDebugger().
659 // Start the out-of-memory priority manager here so that we give the most
660 // amount of time for the other services to start up before we start
661 // adjusting the oom priority.
662 g_browser_process->platform_part()->oom_priority_manager()->Start();
664 if (ui::ShouldDefaultToNaturalScroll()) {
665 CommandLine::ForCurrentProcess()->AppendSwitch(
666 chromeos::switches::kNaturalScrollDefault);
667 system::InputDeviceSettings::Get()->SetTapToClick(true);
670 ChromeBrowserMainPartsLinux::PreBrowserStart();
673 void ChromeBrowserMainPartsChromeos::PostBrowserStart() {
674 // These are dependent on the ash::Shell singleton already having been
675 // initialized.
676 #if !defined(USE_ATHENA)
677 // TODO(oshima): Remove ash dependency in PowerButtonObserver.
678 // crbug.com/408832.
679 power_button_observer_.reset(new PowerButtonObserver);
680 #endif
681 data_promo_notification_.reset(new DataPromoNotification());
683 #if !defined(USE_ATHENA)
684 // TODO(oshima): Support accessibility on athena. crbug.com/408733.
685 keyboard_event_rewriters_.reset(new EventRewriterController());
686 keyboard_event_rewriters_->AddEventRewriter(
687 scoped_ptr<ui::EventRewriter>(new KeyboardDrivenEventRewriter()));
688 keyboard_event_rewriters_->AddEventRewriter(scoped_ptr<ui::EventRewriter>(
689 new EventRewriter(ash::Shell::GetInstance()->sticky_keys_controller())));
690 keyboard_event_rewriters_->Init();
691 #endif
693 ChromeBrowserMainPartsLinux::PostBrowserStart();
696 // Shut down services before the browser process, etc are destroyed.
697 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopRun() {
698 BootTimesLoader::Get()->AddLogoutTimeMarker("UIMessageLoopEnded", true);
700 g_browser_process->platform_part()->oom_priority_manager()->Stop();
702 // Early wake-up of HID device service.
703 InputServiceProxy::WarmUp();
705 // Destroy the application name notifier for Kiosk mode.
706 KioskModeIdleAppNameNotification::Shutdown();
708 // Shutdown the upgrade detector for Chrome OS. The upgrade detector
709 // stops monitoring changes from the update engine.
710 if (UpgradeDetectorChromeos::GetInstance())
711 UpgradeDetectorChromeos::GetInstance()->Shutdown();
713 // Shutdown the network change notifier for Chrome OS. The network
714 // change notifier stops monitoring changes from the power manager and
715 // the network manager.
716 if (NetworkChangeNotifierFactoryChromeos::GetInstance())
717 NetworkChangeNotifierFactoryChromeos::GetInstance()->Shutdown();
719 // Destroy UI related classes before destroying services that they may
720 // depend on.
721 data_promo_notification_.reset();
723 // Tell DeviceSettingsService to stop talking to session_manager. Do not
724 // shutdown DeviceSettingsService yet, it might still be accessed by
725 // BrowserPolicyConnector (owned by g_browser_process).
726 DeviceSettingsService::Get()->UnsetSessionManager();
728 // We should remove observers attached to D-Bus clients before
729 // DBusThreadManager is shut down.
730 extension_system_event_observer_.reset();
731 retail_mode_power_save_blocker_.reset();
732 peripheral_battery_observer_.reset();
733 power_prefs_.reset();
734 renderer_freezer_.reset();
735 light_bar_.reset();
736 wake_on_wifi_manager_.reset();
738 // Let the ScreenLocker unregister itself from SessionManagerClient before
739 // DBusThreadManager is shut down.
740 if (!KioskModeSettings::Get()->IsKioskModeEnabled())
741 ScreenLocker::ShutDownClass();
743 keyboard_event_rewriters_.reset();
744 #if defined(USE_X11)
745 // The XInput2 event listener needs to be shut down earlier than when
746 // Singletons are finally destroyed in AtExitManager.
747 XInputHierarchyChangedEventListener::GetInstance()->Stop();
749 DeviceUMA::GetInstance()->Stop();
751 // SystemKeyEventListener::Shutdown() is always safe to call,
752 // even if Initialize() wasn't called.
753 SystemKeyEventListener::Shutdown();
754 #endif
756 // Detach D-Bus clients before DBusThreadManager is shut down.
757 power_button_observer_.reset();
758 idle_action_warning_observer_.reset();
760 #if !defined(USE_ATHENA)
761 MagnificationManager::Shutdown();
762 #endif
764 AccessibilityManager::Shutdown();
766 media::SoundsManager::Shutdown();
768 system::StatisticsProvider::GetInstance()->Shutdown();
770 // Let the UserManager and WallpaperManager unregister itself as an observer
771 // of the CrosSettings singleton before it is destroyed. This also ensures
772 // that the UserManager has no URLRequest pending (see
773 // http://crbug.com/276659).
774 g_browser_process->platform_part()->user_manager()->Shutdown();
775 #if !defined(USE_ATHENA)
776 WallpaperManager::Get()->Shutdown();
777 #endif
779 // Let the DeviceDisablingManager unregister itself as an observer of the
780 // CrosSettings singleton before it is destroyed.
781 g_browser_process->platform_part()->ShutdownDeviceDisablingManager();
783 // Let the AutomaticRebootManager unregister itself as an observer of several
784 // subsystems.
785 g_browser_process->platform_part()->ShutdownAutomaticRebootManager();
787 // Clean up dependency on CrosSettings and stop pending data fetches.
788 KioskAppManager::Shutdown();
790 // Give BrowserPolicyConnectorChromeOS a chance to unregister any observers
791 // on services that are going to be deleted later but before its Shutdown()
792 // is called.
793 g_browser_process->platform_part()->browser_policy_connector_chromeos()->
794 PreShutdown();
796 // We first call PostMainMessageLoopRun and then destroy UserManager, because
797 // Ash needs to be closed before UserManager is destroyed.
798 ChromeBrowserMainPartsLinux::PostMainMessageLoopRun();
800 input_method::Shutdown();
802 // Stops all in-flight OAuth2 token fetchers before the IO thread stops.
803 DeviceOAuth2TokenServiceFactory::Shutdown();
805 // Shutdown after PostMainMessageLoopRun() which should destroy all observers.
806 CrasAudioHandler::Shutdown();
808 // Called after
809 // ChromeBrowserMainPartsLinux::PostMainMessageLoopRun() to be
810 // executed after execution of chrome::CloseAsh(), because some
811 // parts of WebUI depends on NetworkPortalDetector.
812 NetworkPortalDetector::Shutdown();
814 g_browser_process->platform_part()->DestroyChromeUserManager();
816 g_browser_process->platform_part()->ShutdownSessionManager();
819 void ChromeBrowserMainPartsChromeos::PostDestroyThreads() {
820 // Destroy DBus services immediately after threads are stopped.
821 dbus_services_.reset();
823 ChromeBrowserMainPartsLinux::PostDestroyThreads();
825 // Destroy DeviceSettingsService after g_browser_process.
826 DeviceSettingsService::Shutdown();
829 } // namespace chromeos