Revert of Add button to add new FSP services to Files app. (patchset #8 id:140001...
[chromium-blink-merge.git] / chrome / browser / chromeos / chrome_browser_main_chromeos.cc
blob9bdf63f0bdbea9529412cb8e6bbb09045ee8eb1c
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::Initialize();
427 WallpaperManager::Get()->AddObservers();
429 base::PostTaskAndReplyWithResult(
430 content::BrowserThread::GetBlockingPool(),
431 FROM_HERE,
432 base::Bind(&version_loader::GetVersion,
433 version_loader::VERSION_FULL),
434 base::Bind(&ChromeOSVersionCallback));
436 // Make sure that wallpaper boot transition and other delays in OOBE
437 // are disabled for tests and kiosk app launch by default.
438 // Individual tests may enable them if they want.
439 if (parsed_command_line().HasSwitch(::switches::kTestType) ||
440 ShouldAutoLaunchKioskApp(parsed_command_line())) {
441 WizardController::SetZeroDelays();
444 power_prefs_.reset(new PowerPrefs(PowerPolicyController::Get()));
446 // In Aura builds this will initialize ash::Shell.
447 ChromeBrowserMainPartsLinux::PreProfileInit();
449 if (immediate_login) {
450 const std::string user_id = login::CanonicalizeUserID(
451 parsed_command_line().GetSwitchValueASCII(switches::kLoginUser));
452 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
454 if (policy::IsDeviceLocalAccountUser(user_id, NULL) &&
455 !user_manager->IsKnownUser(user_id)) {
456 // When a device-local account is removed, its policy is deleted from disk
457 // immediately. If a session using this account happens to be in progress,
458 // the session is allowed to continue with policy served from an in-memory
459 // cache. If Chrome crashes later in the session, the policy becomes
460 // completely unavailable. Exit the session in that case, rather than
461 // allowing it to continue without policy.
462 chrome::AttemptUserExit();
463 return;
466 // In case of multi-profiles --login-profile will contain user_id_hash.
467 std::string user_id_hash =
468 parsed_command_line().GetSwitchValueASCII(switches::kLoginProfile);
469 user_manager->UserLoggedIn(user_id, user_id_hash, true);
470 VLOG(1) << "Relaunching browser for user: " << user_id
471 << " with hash: " << user_id_hash;
475 class GuestLanguageSetCallbackData {
476 public:
477 explicit GuestLanguageSetCallbackData(Profile* profile) : profile(profile) {
480 // Must match SwitchLanguageCallback type.
481 static void Callback(const scoped_ptr<GuestLanguageSetCallbackData>& self,
482 const locale_util::LanguageSwitchResult& result);
484 Profile* profile;
487 // static
488 void GuestLanguageSetCallbackData::Callback(
489 const scoped_ptr<GuestLanguageSetCallbackData>& self,
490 const locale_util::LanguageSwitchResult& result) {
491 input_method::InputMethodManager* manager =
492 input_method::InputMethodManager::Get();
493 scoped_refptr<input_method::InputMethodManager::State> ime_state =
494 manager->GetActiveIMEState();
495 // Active layout must be hardware "login layout".
496 // The previous one must be "locale default layout".
497 // First, enable all hardware input methods.
498 const std::vector<std::string>& input_methods =
499 manager->GetInputMethodUtil()->GetHardwareInputMethodIds();
500 for (size_t i = 0; i < input_methods.size(); ++i)
501 ime_state->EnableInputMethod(input_methods[i]);
503 // Second, enable locale based input methods.
504 const std::string locale_default_input_method =
505 manager->GetInputMethodUtil()->GetLanguageDefaultInputMethodId(
506 result.loaded_locale);
507 if (!locale_default_input_method.empty()) {
508 PrefService* user_prefs = self->profile->GetPrefs();
509 user_prefs->SetString(prefs::kLanguagePreviousInputMethod,
510 locale_default_input_method);
511 ime_state->EnableInputMethod(locale_default_input_method);
514 // Finally, activate the first login input method.
515 const std::vector<std::string>& login_input_methods =
516 manager->GetInputMethodUtil()->GetHardwareLoginInputMethodIds();
517 ime_state->ChangeInputMethod(login_input_methods[0],
518 false /* show_message */);
521 void SetGuestLocale(Profile* const profile) {
522 scoped_ptr<GuestLanguageSetCallbackData> data(
523 new GuestLanguageSetCallbackData(profile));
524 locale_util::SwitchLanguageCallback callback(base::Bind(
525 &GuestLanguageSetCallbackData::Callback, base::Passed(data.Pass())));
526 const user_manager::User* const user =
527 ProfileHelper::Get()->GetUserByProfile(profile);
528 UserSessionManager::GetInstance()->RespectLocalePreference(
529 profile, user, callback);
532 void ChromeBrowserMainPartsChromeos::PostProfileInit() {
533 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
534 // -- just after CreateProfile().
536 // Force loading of signin profile if it was not loaded before. It is possible
537 // when we are restoring session or skipping login screen for some other
538 // reason.
539 if (!chromeos::ProfileHelper::IsSigninProfile(profile()))
540 chromeos::ProfileHelper::GetSigninProfile();
542 BootTimesRecorder::Get()->OnChromeProcessStart();
544 // Initialize the network portal detector for Chrome OS. The network
545 // portal detector starts to listen for notifications from
546 // NetworkStateHandler and initiates captive portal detection for
547 // active networks. Should be called before call to CreateSessionManager,
548 // because it depends on NetworkPortalDetector.
549 NetworkPortalDetectorImpl::Initialize(
550 g_browser_process->system_request_context());
552 NetworkPortalDetector* detector = NetworkPortalDetector::Get();
553 #if defined(GOOGLE_CHROME_BUILD)
554 bool is_official_build = true;
555 #else
556 bool is_official_build = false;
557 #endif
558 // Enable portal detector if EULA was previously accepted or if
559 // this is an unofficial build.
560 if (!is_official_build || StartupUtils::IsEulaAccepted())
561 detector->Enable(true);
564 // Initialize input methods.
565 input_method::InputMethodManager* manager =
566 input_method::InputMethodManager::Get();
567 UserSessionManager* session_manager = UserSessionManager::GetInstance();
568 DCHECK(manager);
569 DCHECK(session_manager);
571 manager->SetState(session_manager->GetDefaultIMEState(profile()));
573 bool is_running_test = parameters().ui_task != NULL;
574 g_browser_process->platform_part()->InitializeSessionManager(
575 parsed_command_line(), profile(), is_running_test);
576 g_browser_process->platform_part()->SessionManager()->Start();
578 // Guest user profile is never initialized with locale settings,
579 // so we need special handling for Guest session.
580 if (user_manager::UserManager::Get()->IsLoggedInAsGuest())
581 SetGuestLocale(profile());
583 peripheral_battery_observer_.reset(new PeripheralBatteryObserver());
585 renderer_freezer_.reset(
586 new RendererFreezer(scoped_ptr<RendererFreezer::Delegate>(
587 new FreezerCgroupProcessManager())));
589 g_browser_process->platform_part()->InitializeAutomaticRebootManager();
590 g_browser_process->platform_part()->InitializeDeviceDisablingManager();
592 // This observer cannot be created earlier because it requires the shell to be
593 // available.
594 idle_action_warning_observer_.reset(new IdleActionWarningObserver());
596 ChromeBrowserMainPartsLinux::PostProfileInit();
599 void ChromeBrowserMainPartsChromeos::PreBrowserStart() {
600 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
601 // -- just before MetricsService::LogNeedForCleanShutdown().
603 // Start the external metrics service, which collects metrics from Chrome OS
604 // and passes them to the browser process.
605 external_metrics_ = new chromeos::ExternalMetrics;
606 external_metrics_->Start();
608 #if defined(USE_X11)
609 // Listen for system key events so that the user will be able to adjust the
610 // volume on the login screen, if Chrome is running on Chrome OS
611 // (i.e. not Linux desktop), and in non-test mode.
612 // Note: SystemKeyEventListener depends on the DBus thread.
613 if (base::SysInfo::IsRunningOnChromeOS() &&
614 !parameters().ui_task) { // ui_task is non-NULL when running tests.
615 SystemKeyEventListener::Initialize();
618 // Listen for XI_HierarchyChanged events. Note: if this is moved to
619 // PreMainMessageLoopRun() then desktopui_PageCyclerTests fail for unknown
620 // reasons, see http://crosbug.com/24833.
621 XInputHierarchyChangedEventListener::GetInstance();
623 // Start the CrOS input device UMA watcher
624 DeviceUMA::GetInstance();
625 #endif
627 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
628 // -- immediately after ChildProcess::WaitForDebugger().
630 // Start the out-of-memory priority manager here so that we give the most
631 // amount of time for the other services to start up before we start
632 // adjusting the oom priority.
633 g_browser_process->platform_part()->oom_priority_manager()->Start();
635 if (ui::ShouldDefaultToNaturalScroll()) {
636 base::CommandLine::ForCurrentProcess()->AppendSwitch(
637 chromeos::switches::kNaturalScrollDefault);
638 system::InputDeviceSettings::Get()->SetTapToClick(true);
641 ChromeBrowserMainPartsLinux::PreBrowserStart();
644 void ChromeBrowserMainPartsChromeos::PostBrowserStart() {
645 // These are dependent on the ash::Shell singleton already having been
646 // initialized.
647 // TODO(oshima): Remove ash dependency in PowerButtonObserver.
648 // crbug.com/408832.
649 power_button_observer_.reset(new PowerButtonObserver);
650 data_promo_notification_.reset(new DataPromoNotification());
652 keyboard_event_rewriters_.reset(new EventRewriterController());
653 keyboard_event_rewriters_->AddEventRewriter(
654 scoped_ptr<ui::EventRewriter>(new KeyboardDrivenEventRewriter()));
655 keyboard_event_rewriters_->AddEventRewriter(scoped_ptr<ui::EventRewriter>(
656 new EventRewriter(ash::Shell::GetInstance()->sticky_keys_controller())));
657 keyboard_event_rewriters_->Init();
659 ChromeBrowserMainPartsLinux::PostBrowserStart();
662 // Shut down services before the browser process, etc are destroyed.
663 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopRun() {
664 BootTimesRecorder::Get()->AddLogoutTimeMarker("UIMessageLoopEnded", true);
666 g_browser_process->platform_part()->oom_priority_manager()->Stop();
668 // Early wake-up of HID device service.
669 InputServiceProxy::WarmUp();
671 // Destroy the application name notifier for Kiosk mode.
672 KioskModeIdleAppNameNotification::Shutdown();
674 // Shutdown the upgrade detector for Chrome OS. The upgrade detector
675 // stops monitoring changes from the update engine.
676 if (UpgradeDetectorChromeos::GetInstance())
677 UpgradeDetectorChromeos::GetInstance()->Shutdown();
679 // Shutdown the network change notifier for Chrome OS. The network
680 // change notifier stops monitoring changes from the power manager and
681 // the network manager.
682 if (NetworkChangeNotifierFactoryChromeos::GetInstance())
683 NetworkChangeNotifierFactoryChromeos::GetInstance()->Shutdown();
685 // Destroy UI related classes before destroying services that they may
686 // depend on.
687 data_promo_notification_.reset();
689 // Tell DeviceSettingsService to stop talking to session_manager. Do not
690 // shutdown DeviceSettingsService yet, it might still be accessed by
691 // BrowserPolicyConnector (owned by g_browser_process).
692 DeviceSettingsService::Get()->UnsetSessionManager();
694 // We should remove observers attached to D-Bus clients before
695 // DBusThreadManager is shut down.
696 peripheral_battery_observer_.reset();
697 power_prefs_.reset();
698 renderer_freezer_.reset();
699 wake_on_wifi_manager_.reset();
700 ScreenLocker::ShutDownClass();
701 keyboard_event_rewriters_.reset();
702 #if defined(USE_X11)
703 // The XInput2 event listener needs to be shut down earlier than when
704 // Singletons are finally destroyed in AtExitManager.
705 XInputHierarchyChangedEventListener::GetInstance()->Stop();
707 DeviceUMA::GetInstance()->Stop();
709 // SystemKeyEventListener::Shutdown() is always safe to call,
710 // even if Initialize() wasn't called.
711 SystemKeyEventListener::Shutdown();
712 #endif
714 // Detach D-Bus clients before DBusThreadManager is shut down.
715 power_button_observer_.reset();
716 idle_action_warning_observer_.reset();
718 MagnificationManager::Shutdown();
720 AccessibilityManager::Shutdown();
722 media::SoundsManager::Shutdown();
724 system::StatisticsProvider::GetInstance()->Shutdown();
726 // Let the UserManager and WallpaperManager unregister itself as an observer
727 // of the CrosSettings singleton before it is destroyed. This also ensures
728 // that the UserManager has no URLRequest pending (see
729 // http://crbug.com/276659).
730 g_browser_process->platform_part()->user_manager()->Shutdown();
731 WallpaperManager::Shutdown();
733 // Let the DeviceDisablingManager unregister itself as an observer of the
734 // CrosSettings singleton before it is destroyed.
735 g_browser_process->platform_part()->ShutdownDeviceDisablingManager();
737 // Let the AutomaticRebootManager unregister itself as an observer of several
738 // subsystems.
739 g_browser_process->platform_part()->ShutdownAutomaticRebootManager();
741 // Clean up dependency on CrosSettings and stop pending data fetches.
742 KioskAppManager::Shutdown();
744 // Give BrowserPolicyConnectorChromeOS a chance to unregister any observers
745 // on services that are going to be deleted later but before its Shutdown()
746 // is called.
747 g_browser_process->platform_part()->browser_policy_connector_chromeos()->
748 PreShutdown();
750 // We first call PostMainMessageLoopRun and then destroy UserManager, because
751 // Ash needs to be closed before UserManager is destroyed.
752 ChromeBrowserMainPartsLinux::PostMainMessageLoopRun();
754 input_method::Shutdown();
756 // Stops all in-flight OAuth2 token fetchers before the IO thread stops.
757 DeviceOAuth2TokenServiceFactory::Shutdown();
759 // Shutdown after PostMainMessageLoopRun() which should destroy all observers.
760 CrasAudioHandler::Shutdown();
762 // Called after
763 // ChromeBrowserMainPartsLinux::PostMainMessageLoopRun() to be
764 // executed after execution of chrome::CloseAsh(), because some
765 // parts of WebUI depends on NetworkPortalDetector.
766 NetworkPortalDetector::Shutdown();
768 g_browser_process->platform_part()->DestroyChromeUserManager();
770 g_browser_process->platform_part()->ShutdownSessionManager();
773 void ChromeBrowserMainPartsChromeos::PostDestroyThreads() {
774 // Destroy DBus services immediately after threads are stopped.
775 dbus_services_.reset();
777 ChromeBrowserMainPartsLinux::PostDestroyThreads();
779 // Destroy DeviceSettingsService after g_browser_process.
780 DeviceSettingsService::Shutdown();
783 } // namespace chromeos