Update broken references to image assets
[chromium-blink-merge.git] / chrome / browser / chromeos / chrome_browser_main_chromeos.cc
blob52558ad056c398c8362a1c9d3b25f34f0f02f6b7
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/accessibility/spoken_feedback_event_rewriter.h"
30 #include "chrome/browser/chromeos/app_mode/kiosk_app_launch_error.h"
31 #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
32 #include "chrome/browser/chromeos/app_mode/kiosk_mode_idle_app_name_notification.h"
33 #include "chrome/browser/chromeos/boot_times_recorder.h"
34 #include "chrome/browser/chromeos/dbus/chrome_console_service_provider_delegate.h"
35 #include "chrome/browser/chromeos/dbus/chrome_display_power_service_provider_delegate.h"
36 #include "chrome/browser/chromeos/dbus/chrome_proxy_resolver_delegate.h"
37 #include "chrome/browser/chromeos/dbus/screen_lock_service_provider.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/external_metrics.h"
43 #include "chrome/browser/chromeos/input_method/input_method_configuration.h"
44 #include "chrome/browser/chromeos/input_method/input_method_util.h"
45 #include "chrome/browser/chromeos/language_preferences.h"
46 #include "chrome/browser/chromeos/login/helper.h"
47 #include "chrome/browser/chromeos/login/lock/screen_locker.h"
48 #include "chrome/browser/chromeos/login/login_wizard.h"
49 #include "chrome/browser/chromeos/login/session/user_session_manager.h"
50 #include "chrome/browser/chromeos/login/startup_utils.h"
51 #include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
52 #include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h"
53 #include "chrome/browser/chromeos/login/wizard_controller.h"
54 #include "chrome/browser/chromeos/net/network_portal_detector_impl.h"
55 #include "chrome/browser/chromeos/net/wake_on_wifi_manager.h"
56 #include "chrome/browser/chromeos/options/cert_library.h"
57 #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h"
58 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
59 #include "chrome/browser/chromeos/policy/device_local_account.h"
60 #include "chrome/browser/chromeos/power/freezer_cgroup_process_manager.h"
61 #include "chrome/browser/chromeos/power/idle_action_warning_observer.h"
62 #include "chrome/browser/chromeos/power/peripheral_battery_observer.h"
63 #include "chrome/browser/chromeos/power/power_button_observer.h"
64 #include "chrome/browser/chromeos/power/power_data_collector.h"
65 #include "chrome/browser/chromeos/power/power_prefs.h"
66 #include "chrome/browser/chromeos/power/renderer_freezer.h"
67 #include "chrome/browser/chromeos/profiles/profile_helper.h"
68 #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h"
69 #include "chrome/browser/chromeos/settings/device_settings_service.h"
70 #include "chrome/browser/chromeos/status/data_promo_notification.h"
71 #include "chrome/browser/chromeos/system/input_device_settings.h"
72 #include "chrome/browser/chromeos/upgrade_detector_chromeos.h"
73 #include "chrome/browser/defaults.h"
74 #include "chrome/browser/lifetime/application_lifetime.h"
75 #include "chrome/browser/net/chrome_network_delegate.h"
76 #include "chrome/browser/profiles/profile.h"
77 #include "chrome/browser/profiles/profile_manager.h"
78 #include "chrome/browser/ui/ash/network_connect_delegate_chromeos.h"
79 #include "chrome/common/channel_info.h"
80 #include "chrome/common/chrome_constants.h"
81 #include "chrome/common/chrome_paths.h"
82 #include "chrome/common/chrome_switches.h"
83 #include "chrome/common/logging_chrome.h"
84 #include "chrome/common/pref_names.h"
85 #include "chromeos/audio/audio_devices_pref_handler_impl.h"
86 #include "chromeos/audio/cras_audio_handler.h"
87 #include "chromeos/cert_loader.h"
88 #include "chromeos/chromeos_paths.h"
89 #include "chromeos/chromeos_switches.h"
90 #include "chromeos/cryptohome/async_method_caller.h"
91 #include "chromeos/cryptohome/homedir_methods.h"
92 #include "chromeos/cryptohome/system_salt_getter.h"
93 #include "chromeos/dbus/dbus_thread_manager.h"
94 #include "chromeos/dbus/power_policy_controller.h"
95 #include "chromeos/dbus/services/console_service_provider.h"
96 #include "chromeos/dbus/services/cros_dbus_service.h"
97 #include "chromeos/dbus/services/display_power_service_provider.h"
98 #include "chromeos/dbus/services/liveness_service_provider.h"
99 #include "chromeos/dbus/services/proxy_resolution_service_provider.h"
100 #include "chromeos/dbus/session_manager_client.h"
101 #include "chromeos/disks/disk_mount_manager.h"
102 #include "chromeos/login/login_state.h"
103 #include "chromeos/login/user_names.h"
104 #include "chromeos/login_event_recorder.h"
105 #include "chromeos/network/network_change_notifier_chromeos.h"
106 #include "chromeos/network/network_change_notifier_factory_chromeos.h"
107 #include "chromeos/network/network_handler.h"
108 #include "chromeos/system/statistics_provider.h"
109 #include "chromeos/tpm/tpm_token_loader.h"
110 #include "components/device_event_log/device_event_log.h"
111 #include "components/metrics/metrics_service.h"
112 #include "components/ownership/owner_key_util.h"
113 #include "components/session_manager/core/session_manager.h"
114 #include "components/user_manager/user.h"
115 #include "components/user_manager/user_manager.h"
116 #include "components/wallpaper/wallpaper_manager_base.h"
117 #include "content/public/browser/browser_thread.h"
118 #include "content/public/browser/notification_service.h"
119 #include "content/public/common/main_function_params.h"
120 #include "device/bluetooth/bluetooth_adapter_factory.h"
121 #include "media/audio/sounds/sounds_manager.h"
122 #include "net/base/network_change_notifier.h"
123 #include "net/socket/ssl_server_socket.h"
124 #include "net/url_request/url_request.h"
125 #include "net/url_request/url_request_context_getter.h"
126 #include "ui/base/ime/chromeos/ime_keyboard.h"
127 #include "ui/base/ime/chromeos/input_method_manager.h"
128 #include "ui/base/touch/touch_device.h"
129 #include "ui/events/event_utils.h"
131 #if defined(ENABLE_RLZ)
132 #include "components/rlz/rlz_tracker.h"
133 #endif
135 // Exclude X11 dependents for ozone
136 #if defined(USE_X11)
137 #include "chrome/browser/chromeos/device_uma.h"
138 #include "chrome/browser/chromeos/events/system_key_event_listener.h"
139 #include "chrome/browser/chromeos/events/xinput_hierarchy_changed_event_listener.h"
140 #endif
142 namespace chromeos {
144 namespace {
146 void ChromeOSVersionCallback(const std::string& version) {
147 base::SetLinuxDistro(std::string("CrOS ") + version);
150 bool ShouldAutoLaunchKioskApp(const base::CommandLine& command_line) {
151 KioskAppManager* app_manager = KioskAppManager::Get();
152 return command_line.HasSwitch(switches::kLoginManager) &&
153 !command_line.HasSwitch(switches::kForceLoginManagerInTests) &&
154 app_manager->IsAutoLaunchEnabled() &&
155 KioskAppLaunchError::Get() == KioskAppLaunchError::NONE;
158 } // namespace
160 namespace internal {
162 // Wrapper class for initializing dbus related services and shutting them
163 // down. This gets instantiated in a scoped_ptr so that shutdown methods in the
164 // destructor will get called if and only if this has been instantiated.
165 class DBusServices {
166 public:
167 explicit DBusServices(const content::MainFunctionParams& parameters) {
168 // Initialize DBusThreadManager for the browser. This must be done after
169 // the main message loop is started, as it uses the message loop.
170 DBusThreadManager::Initialize();
171 PowerPolicyController::Initialize(
172 DBusThreadManager::Get()->GetPowerManagerClient());
174 ScopedVector<CrosDBusService::ServiceProviderInterface> service_providers;
175 service_providers.push_back(ProxyResolutionServiceProvider::Create(
176 make_scoped_ptr(new ChromeProxyResolverDelegate())));
177 service_providers.push_back(new DisplayPowerServiceProvider(
178 make_scoped_ptr(new ChromeDisplayPowerServiceProviderDelegate)));
179 service_providers.push_back(new LivenessServiceProvider);
180 service_providers.push_back(new ScreenLockServiceProvider);
181 service_providers.push_back(new ConsoleServiceProvider(
182 make_scoped_ptr(new ChromeConsoleServiceProviderDelegate)));
183 CrosDBusService::Initialize(service_providers.Pass());
185 // Initialize PowerDataCollector after DBusThreadManager is initialized.
186 PowerDataCollector::Initialize();
188 LoginState::Initialize();
189 SystemSaltGetter::Initialize();
190 TPMTokenLoader::Initialize();
191 CertLoader::Initialize();
193 disks::DiskMountManager::Initialize();
194 cryptohome::AsyncMethodCaller::Initialize();
195 cryptohome::HomedirMethods::Initialize();
197 NetworkHandler::Initialize();
198 CertLibrary::Initialize();
200 // Initialize the network change notifier for Chrome OS. The network
201 // change notifier starts to monitor changes from the power manager and
202 // the network manager.
203 NetworkChangeNotifierFactoryChromeos::GetInstance()->Initialize();
205 // Initialize the NetworkConnect handler.
206 network_connect_delegate_.reset(new NetworkConnectDelegateChromeOS);
207 ui::NetworkConnect::Initialize(network_connect_delegate_.get());
209 // Likewise, initialize the upgrade detector for Chrome OS. The upgrade
210 // detector starts to monitor changes from the update engine.
211 UpgradeDetectorChromeos::GetInstance()->Init();
213 // Initialize the device settings service so that we'll take actions per
214 // signals sent from the session manager. This needs to happen before
215 // g_browser_process initializes BrowserPolicyConnector.
216 DeviceSettingsService::Initialize();
217 DeviceSettingsService::Get()->SetSessionManager(
218 DBusThreadManager::Get()->GetSessionManagerClient(),
219 OwnerSettingsServiceChromeOSFactory::GetInstance()->GetOwnerKeyUtil());
222 ~DBusServices() {
223 ui::NetworkConnect::Shutdown();
224 network_connect_delegate_.reset();
225 CertLibrary::Shutdown();
226 NetworkHandler::Shutdown();
227 cryptohome::AsyncMethodCaller::Shutdown();
228 disks::DiskMountManager::Shutdown();
229 SystemSaltGetter::Shutdown();
230 LoginState::Shutdown();
231 CertLoader::Shutdown();
232 TPMTokenLoader::Shutdown();
233 CrosDBusService::Shutdown();
234 PowerDataCollector::Shutdown();
235 PowerPolicyController::Shutdown();
236 device::BluetoothAdapterFactory::Shutdown();
238 // NOTE: This must only be called if Initialize() was called.
239 DBusThreadManager::Shutdown();
242 private:
243 scoped_ptr<NetworkConnectDelegateChromeOS> network_connect_delegate_;
245 DISALLOW_COPY_AND_ASSIGN(DBusServices);
248 } // namespace internal
250 // ChromeBrowserMainPartsChromeos ----------------------------------------------
252 ChromeBrowserMainPartsChromeos::ChromeBrowserMainPartsChromeos(
253 const content::MainFunctionParams& parameters)
254 : ChromeBrowserMainPartsLinux(parameters) {
257 ChromeBrowserMainPartsChromeos::~ChromeBrowserMainPartsChromeos() {
258 // To be precise, logout (browser shutdown) is not yet done, but the
259 // remaining work is negligible, hence we say LogoutDone here.
260 BootTimesRecorder::Get()->AddLogoutTimeMarker("LogoutDone", false);
261 BootTimesRecorder::Get()->WriteLogoutTimes();
264 // content::BrowserMainParts and ChromeBrowserMainExtraParts overrides ---------
266 void ChromeBrowserMainPartsChromeos::PreEarlyInitialization() {
267 base::CommandLine* singleton_command_line =
268 base::CommandLine::ForCurrentProcess();
270 if (parsed_command_line().HasSwitch(switches::kGuestSession)) {
271 // Disable sync and extensions if we're in "browse without sign-in" mode.
272 singleton_command_line->AppendSwitch(::switches::kDisableSync);
273 singleton_command_line->AppendSwitch(::switches::kDisableExtensions);
274 browser_defaults::bookmarks_enabled = false;
277 // If we're not running on real Chrome OS hardware (or under VM), and are not
278 // showing the login manager or attempting a command line login, login with a
279 // stub user.
280 if (!base::SysInfo::IsRunningOnChromeOS() &&
281 !parsed_command_line().HasSwitch(switches::kLoginManager) &&
282 !parsed_command_line().HasSwitch(switches::kLoginUser) &&
283 !parsed_command_line().HasSwitch(switches::kGuestSession)) {
284 singleton_command_line->AppendSwitchASCII(switches::kLoginUser,
285 chromeos::login::kStubUser);
286 if (!parsed_command_line().HasSwitch(switches::kLoginProfile)) {
287 singleton_command_line->AppendSwitchASCII(switches::kLoginProfile,
288 chrome::kTestUserProfileDir);
290 LOG(WARNING) << "Running as stub user with profile dir: "
291 << singleton_command_line->GetSwitchValuePath(
292 switches::kLoginProfile).value();
295 #if defined(GOOGLE_CHROME_BUILD)
296 const char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK";
297 std::string channel;
298 if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &channel))
299 chrome::SetChannel(channel);
300 #endif
302 ChromeBrowserMainPartsLinux::PreEarlyInitialization();
305 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopStart() {
306 // Replace the default NetworkChangeNotifierFactory with ChromeOS specific
307 // implementation. This must be done before BrowserMainLoop calls
308 // net::NetworkChangeNotifier::Create() in MainMessageLoopStart().
309 net::NetworkChangeNotifier::SetFactory(
310 new NetworkChangeNotifierFactoryChromeos());
311 ChromeBrowserMainPartsLinux::PreMainMessageLoopStart();
314 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopStart() {
315 // device_event_log must be initialized after the message loop.
316 device_event_log::Initialize(0 /* default max entries */);
318 base::FilePath user_data_dir;
319 if (!base::SysInfo::IsRunningOnChromeOS() &&
320 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
321 // Override some paths with stub locations so that cloud policy and
322 // enterprise enrollment work on desktop builds, for ease of
323 // development.
324 chromeos::RegisterStubPathOverrides(user_data_dir);
327 dbus_services_.reset(new internal::DBusServices(parameters()));
329 // Enable support for SSL server sockets, which must be done while still
330 // single-threaded. This is required for remote assistance host on Chrome OS.
331 net::EnableSSLServerSockets();
333 ChromeBrowserMainPartsLinux::PostMainMessageLoopStart();
336 // Threads are initialized between MainMessageLoopStart and MainMessageLoopRun.
337 // about_flags settings are applied in ChromeBrowserMainParts::PreCreateThreads.
338 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopRun() {
339 // Set the crypto thread after the IO thread has been created/started.
340 TPMTokenLoader::Get()->SetCryptoTaskRunner(
341 content::BrowserThread::GetMessageLoopProxyForThread(
342 content::BrowserThread::IO));
344 CrasAudioHandler::Initialize(
345 new AudioDevicesPrefHandlerImpl(g_browser_process->local_state()));
347 // Start loading machine statistics here. StatisticsProvider::Shutdown()
348 // will ensure that loading is aborted on early exit.
349 bool load_oem_statistics = !StartupUtils::IsOobeCompleted();
350 system::StatisticsProvider::GetInstance()->StartLoadingMachineStatistics(
351 content::BrowserThread::GetMessageLoopProxyForThread(
352 content::BrowserThread::FILE),
353 load_oem_statistics);
355 base::FilePath downloads_directory;
356 CHECK(PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &downloads_directory));
358 DeviceOAuth2TokenServiceFactory::Initialize();
360 wake_on_wifi_manager_.reset(new WakeOnWifiManager());
362 ChromeBrowserMainPartsLinux::PreMainMessageLoopRun();
365 void ChromeBrowserMainPartsChromeos::PreProfileInit() {
366 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
367 // -- immediately before Profile creation().
369 // Now that the file thread exists we can record our stats.
370 BootTimesRecorder::Get()->RecordChromeMainStats();
371 LoginEventRecorder::Get()->SetDelegate(BootTimesRecorder::Get());
373 // Trigger prefetching of ownership status.
374 DeviceSettingsService::Get()->Load();
376 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
377 // -- just before CreateProfile().
379 g_browser_process->platform_part()->InitializeChromeUserManager();
381 ScreenLocker::InitClass();
383 // This forces the ProfileManager to be created and register for the
384 // notification it needs to track the logged in user.
385 g_browser_process->profile_manager();
387 // AccessibilityManager and SystemKeyEventListener use InputMethodManager.
388 input_method::Initialize();
390 // ProfileHelper has to be initialized after UserManager instance is created.
391 ProfileHelper::Get()->Initialize();
393 // TODO(abarth): Should this move to InitializeNetworkOptions()?
394 // Allow access to file:// on ChromeOS for tests.
395 if (parsed_command_line().HasSwitch(::switches::kAllowFileAccess))
396 ChromeNetworkDelegate::AllowAccessToAllFiles();
398 // If kLoginUser is passed this indicates that user has already
399 // logged in and we should behave accordingly.
400 bool immediate_login =
401 parsed_command_line().HasSwitch(switches::kLoginUser);
402 if (immediate_login) {
403 // Redirects Chrome logging to the user data dir.
404 logging::RedirectChromeLogging(parsed_command_line());
406 // Load the default app order synchronously for restarting case.
407 app_order_loader_.reset(
408 new default_app_order::ExternalLoader(false /* async */));
411 if (!app_order_loader_) {
412 app_order_loader_.reset(
413 new default_app_order::ExternalLoader(true /* async */));
416 media::SoundsManager::Create();
418 // Initialize magnification manager before ash tray is created. And this must
419 // be placed after UserManager::SessionStarted();
420 AccessibilityManager::Initialize();
421 MagnificationManager::Initialize();
423 wallpaper::WallpaperManagerBase::SetPathIds(
424 chrome::DIR_USER_DATA,
425 chrome::DIR_CHROMEOS_WALLPAPERS,
426 chrome::DIR_CHROMEOS_CUSTOM_WALLPAPERS);
428 // Add observers for WallpaperManager. This depends on PowerManagerClient,
429 // TimezoneSettings and CrosSettings.
430 WallpaperManager::Initialize();
431 WallpaperManager::Get()->AddObservers();
433 base::PostTaskAndReplyWithResult(
434 content::BrowserThread::GetBlockingPool(),
435 FROM_HERE,
436 base::Bind(&version_loader::GetVersion,
437 version_loader::VERSION_FULL),
438 base::Bind(&ChromeOSVersionCallback));
440 // Make sure that wallpaper boot transition and other delays in OOBE
441 // are disabled for tests and kiosk app launch by default.
442 // Individual tests may enable them if they want.
443 if (parsed_command_line().HasSwitch(::switches::kTestType) ||
444 ShouldAutoLaunchKioskApp(parsed_command_line())) {
445 WizardController::SetZeroDelays();
448 power_prefs_.reset(new PowerPrefs(PowerPolicyController::Get()));
450 // In Aura builds this will initialize ash::Shell.
451 ChromeBrowserMainPartsLinux::PreProfileInit();
453 if (immediate_login) {
454 const std::string user_id = login::CanonicalizeUserID(
455 parsed_command_line().GetSwitchValueASCII(switches::kLoginUser));
456 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
458 if (policy::IsDeviceLocalAccountUser(user_id, NULL) &&
459 !user_manager->IsKnownUser(user_id)) {
460 // When a device-local account is removed, its policy is deleted from disk
461 // immediately. If a session using this account happens to be in progress,
462 // the session is allowed to continue with policy served from an in-memory
463 // cache. If Chrome crashes later in the session, the policy becomes
464 // completely unavailable. Exit the session in that case, rather than
465 // allowing it to continue without policy.
466 chrome::AttemptUserExit();
467 return;
470 // In case of multi-profiles --login-profile will contain user_id_hash.
471 std::string user_id_hash =
472 parsed_command_line().GetSwitchValueASCII(switches::kLoginProfile);
473 user_manager->UserLoggedIn(user_id, user_id_hash, true);
474 VLOG(1) << "Relaunching browser for user: " << user_id
475 << " with hash: " << user_id_hash;
479 class GuestLanguageSetCallbackData {
480 public:
481 explicit GuestLanguageSetCallbackData(Profile* profile) : profile(profile) {
484 // Must match SwitchLanguageCallback type.
485 static void Callback(const scoped_ptr<GuestLanguageSetCallbackData>& self,
486 const locale_util::LanguageSwitchResult& result);
488 Profile* profile;
491 // static
492 void GuestLanguageSetCallbackData::Callback(
493 const scoped_ptr<GuestLanguageSetCallbackData>& self,
494 const locale_util::LanguageSwitchResult& result) {
495 input_method::InputMethodManager* manager =
496 input_method::InputMethodManager::Get();
497 scoped_refptr<input_method::InputMethodManager::State> ime_state =
498 manager->GetActiveIMEState();
499 // Active layout must be hardware "login layout".
500 // The previous one must be "locale default layout".
501 // First, enable all hardware input methods.
502 const std::vector<std::string>& input_methods =
503 manager->GetInputMethodUtil()->GetHardwareInputMethodIds();
504 for (size_t i = 0; i < input_methods.size(); ++i)
505 ime_state->EnableInputMethod(input_methods[i]);
507 // Second, enable locale based input methods.
508 const std::string locale_default_input_method =
509 manager->GetInputMethodUtil()->GetLanguageDefaultInputMethodId(
510 result.loaded_locale);
511 if (!locale_default_input_method.empty()) {
512 PrefService* user_prefs = self->profile->GetPrefs();
513 user_prefs->SetString(prefs::kLanguagePreviousInputMethod,
514 locale_default_input_method);
515 ime_state->EnableInputMethod(locale_default_input_method);
518 // Finally, activate the first login input method.
519 const std::vector<std::string>& login_input_methods =
520 manager->GetInputMethodUtil()->GetHardwareLoginInputMethodIds();
521 ime_state->ChangeInputMethod(login_input_methods[0],
522 false /* show_message */);
525 void SetGuestLocale(Profile* const profile) {
526 scoped_ptr<GuestLanguageSetCallbackData> data(
527 new GuestLanguageSetCallbackData(profile));
528 locale_util::SwitchLanguageCallback callback(base::Bind(
529 &GuestLanguageSetCallbackData::Callback, base::Passed(data.Pass())));
530 const user_manager::User* const user =
531 ProfileHelper::Get()->GetUserByProfile(profile);
532 UserSessionManager::GetInstance()->RespectLocalePreference(
533 profile, user, callback);
536 void ChromeBrowserMainPartsChromeos::PostProfileInit() {
537 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
538 // -- just after CreateProfile().
540 // Force loading of signin profile if it was not loaded before. It is possible
541 // when we are restoring session or skipping login screen for some other
542 // reason.
543 if (!chromeos::ProfileHelper::IsSigninProfile(profile()))
544 chromeos::ProfileHelper::GetSigninProfile();
546 BootTimesRecorder::Get()->OnChromeProcessStart();
548 // Initialize the network portal detector for Chrome OS. The network
549 // portal detector starts to listen for notifications from
550 // NetworkStateHandler and initiates captive portal detection for
551 // active networks. Should be called before call to CreateSessionManager,
552 // because it depends on NetworkPortalDetector.
553 NetworkPortalDetectorImpl::Initialize(
554 g_browser_process->system_request_context());
556 NetworkPortalDetector* detector = NetworkPortalDetector::Get();
557 #if defined(GOOGLE_CHROME_BUILD)
558 bool is_official_build = true;
559 #else
560 bool is_official_build = false;
561 #endif
562 // Enable portal detector if EULA was previously accepted or if
563 // this is an unofficial build.
564 if (!is_official_build || StartupUtils::IsEulaAccepted())
565 detector->Enable(true);
568 // Initialize input methods.
569 input_method::InputMethodManager* manager =
570 input_method::InputMethodManager::Get();
571 UserSessionManager* session_manager = UserSessionManager::GetInstance();
572 DCHECK(manager);
573 DCHECK(session_manager);
575 manager->SetState(session_manager->GetDefaultIMEState(profile()));
577 bool is_running_test = parameters().ui_task != NULL;
578 g_browser_process->platform_part()->InitializeSessionManager(
579 parsed_command_line(), profile(), is_running_test);
580 g_browser_process->platform_part()->SessionManager()->Start();
582 // Guest user profile is never initialized with locale settings,
583 // so we need special handling for Guest session.
584 if (user_manager::UserManager::Get()->IsLoggedInAsGuest())
585 SetGuestLocale(profile());
587 peripheral_battery_observer_.reset(new PeripheralBatteryObserver());
589 renderer_freezer_.reset(
590 new RendererFreezer(scoped_ptr<RendererFreezer::Delegate>(
591 new FreezerCgroupProcessManager())));
593 g_browser_process->platform_part()->InitializeAutomaticRebootManager();
594 g_browser_process->platform_part()->InitializeDeviceDisablingManager();
596 // This observer cannot be created earlier because it requires the shell to be
597 // available.
598 idle_action_warning_observer_.reset(new IdleActionWarningObserver());
600 ChromeBrowserMainPartsLinux::PostProfileInit();
603 void ChromeBrowserMainPartsChromeos::PreBrowserStart() {
604 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
605 // -- just before MetricsService::LogNeedForCleanShutdown().
607 // Start the external metrics service, which collects metrics from Chrome OS
608 // and passes them to the browser process.
609 external_metrics_ = new chromeos::ExternalMetrics;
610 external_metrics_->Start();
612 #if defined(USE_X11)
613 // Listen for system key events so that the user will be able to adjust the
614 // volume on the login screen, if Chrome is running on Chrome OS
615 // (i.e. not Linux desktop), and in non-test mode.
616 // Note: SystemKeyEventListener depends on the DBus thread.
617 if (base::SysInfo::IsRunningOnChromeOS() &&
618 !parameters().ui_task) { // ui_task is non-NULL when running tests.
619 SystemKeyEventListener::Initialize();
622 // Listen for XI_HierarchyChanged events. Note: if this is moved to
623 // PreMainMessageLoopRun() then desktopui_PageCyclerTests fail for unknown
624 // reasons, see http://crosbug.com/24833.
625 XInputHierarchyChangedEventListener::GetInstance();
627 // Start the CrOS input device UMA watcher
628 DeviceUMA::GetInstance();
629 #endif
631 // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
632 // -- immediately after ChildProcess::WaitForDebugger().
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(
655 scoped_ptr<ui::EventRewriter>(new SpokenFeedbackEventRewriter()));
656 keyboard_event_rewriters_->AddEventRewriter(scoped_ptr<ui::EventRewriter>(
657 new EventRewriter(ash::Shell::GetInstance()->sticky_keys_controller())));
658 keyboard_event_rewriters_->Init();
660 ChromeBrowserMainPartsLinux::PostBrowserStart();
663 // Shut down services before the browser process, etc are destroyed.
664 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopRun() {
665 BootTimesRecorder::Get()->AddLogoutTimeMarker("UIMessageLoopEnded", true);
667 // Destroy the application name notifier for Kiosk mode.
668 KioskModeIdleAppNameNotification::Shutdown();
670 // Shutdown the upgrade detector for Chrome OS. The upgrade detector
671 // stops monitoring changes from the update engine.
672 if (UpgradeDetectorChromeos::GetInstance())
673 UpgradeDetectorChromeos::GetInstance()->Shutdown();
675 // Shutdown the network change notifier for Chrome OS. The network
676 // change notifier stops monitoring changes from the power manager and
677 // the network manager.
678 if (NetworkChangeNotifierFactoryChromeos::GetInstance())
679 NetworkChangeNotifierFactoryChromeos::GetInstance()->Shutdown();
681 // Destroy UI related classes before destroying services that they may
682 // depend on.
683 data_promo_notification_.reset();
685 // Tell DeviceSettingsService to stop talking to session_manager. Do not
686 // shutdown DeviceSettingsService yet, it might still be accessed by
687 // BrowserPolicyConnector (owned by g_browser_process).
688 DeviceSettingsService::Get()->UnsetSessionManager();
690 // We should remove observers attached to D-Bus clients before
691 // DBusThreadManager is shut down.
692 peripheral_battery_observer_.reset();
693 power_prefs_.reset();
694 renderer_freezer_.reset();
695 wake_on_wifi_manager_.reset();
696 ScreenLocker::ShutDownClass();
697 keyboard_event_rewriters_.reset();
698 #if defined(USE_X11)
699 // The XInput2 event listener needs to be shut down earlier than when
700 // Singletons are finally destroyed in AtExitManager.
701 XInputHierarchyChangedEventListener::GetInstance()->Stop();
703 DeviceUMA::GetInstance()->Stop();
705 // SystemKeyEventListener::Shutdown() is always safe to call,
706 // even if Initialize() wasn't called.
707 SystemKeyEventListener::Shutdown();
708 #endif
710 // Detach D-Bus clients before DBusThreadManager is shut down.
711 power_button_observer_.reset();
712 idle_action_warning_observer_.reset();
714 MagnificationManager::Shutdown();
716 AccessibilityManager::Shutdown();
718 media::SoundsManager::Shutdown();
720 system::StatisticsProvider::GetInstance()->Shutdown();
722 // Let the UserManager and WallpaperManager unregister itself as an observer
723 // of the CrosSettings singleton before it is destroyed. This also ensures
724 // that the UserManager has no URLRequest pending (see
725 // http://crbug.com/276659).
726 g_browser_process->platform_part()->user_manager()->Shutdown();
727 WallpaperManager::Shutdown();
729 // Let the DeviceDisablingManager unregister itself as an observer of the
730 // CrosSettings singleton before it is destroyed.
731 g_browser_process->platform_part()->ShutdownDeviceDisablingManager();
733 // Let the AutomaticRebootManager unregister itself as an observer of several
734 // subsystems.
735 g_browser_process->platform_part()->ShutdownAutomaticRebootManager();
737 // Clean up dependency on CrosSettings and stop pending data fetches.
738 KioskAppManager::Shutdown();
740 // Make sure that there is no pending URLRequests.
741 UserSessionManager::GetInstance()->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