Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / chrome_browser_main_chromeos.cc
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.
4
5 #include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
6
7 #include <string>
8 #include <vector>
9
10 #include "ash/ash_switches.h"
11 #include "ash/shell.h"
12 #include "base/bind.h"
13 #include "base/callback.h"
14 #include "base/command_line.h"
15 #include "base/file_util.h"
16 #include "base/lazy_instance.h"
17 #include "base/linux_util.h"
18 #include "base/path_service.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_split.h"
22 #include "base/sys_info.h"
23 #include "chrome/browser/browser_process.h"
24 #include "chrome/browser/browser_process_platform_part_chromeos.h"
25 #include "chrome/browser/chrome_notification_types.h"
26 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
27 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
28 #include "chrome/browser/chromeos/app_mode/kiosk_app_launch_error.h"
29 #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
30 #include "chrome/browser/chromeos/app_mode/kiosk_mode_idle_app_name_notification.h"
31 #include "chrome/browser/chromeos/boot_times_loader.h"
32 #include "chrome/browser/chromeos/dbus/cros_dbus_service.h"
33 #include "chrome/browser/chromeos/device/input_service_proxy.h"
34 #include "chrome/browser/chromeos/events/event_rewriter.h"
35 #include "chrome/browser/chromeos/events/event_rewriter_controller.h"
36 #include "chrome/browser/chromeos/events/keyboard_driven_event_rewriter.h"
37 #include "chrome/browser/chromeos/extensions/default_app_order.h"
38 #include "chrome/browser/chromeos/extensions/extension_system_event_observer.h"
39 #include "chrome/browser/chromeos/external_metrics.h"
40 #include "chrome/browser/chromeos/imageburner/burn_manager.h"
41 #include "chrome/browser/chromeos/input_method/input_method_configuration.h"
42 #include "chrome/browser/chromeos/input_method/input_method_util.h"
43 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_idle_logout.h"
44 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_screensaver.h"
45 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.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/options/cert_library.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/idle_action_warning_observer.h"
61 #include "chrome/browser/chromeos/power/peripheral_battery_observer.h"
62 #include "chrome/browser/chromeos/power/power_button_observer.h"
63 #include "chrome/browser/chromeos/power/power_data_collector.h"
64 #include "chrome/browser/chromeos/power/power_prefs.h"
65 #include "chrome/browser/chromeos/power/renderer_freezer.h"
66 #include "chrome/browser/chromeos/profiles/profile_helper.h"
67 #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h"
68 #include "chrome/browser/chromeos/settings/device_settings_service.h"
69 #include "chrome/browser/chromeos/settings/owner_key_util.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/rlz/rlz.h"
79 #include "chrome/common/chrome_constants.h"
80 #include "chrome/common/chrome_paths.h"
81 #include "chrome/common/chrome_switches.h"
82 #include "chrome/common/chrome_version_info.h"
83 #include "chrome/common/logging_chrome.h"
84 #include "chrome/common/pref_names.h"
85 #include "chromeos/audio/audio_devices_pref_handler.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/session_manager_client.h"
96 #include "chromeos/disks/disk_mount_manager.h"
97 #include "chromeos/ime/ime_keyboard.h"
98 #include "chromeos/ime/input_method_manager.h"
99 #include "chromeos/login/login_state.h"
100 #include "chromeos/login/user_names.h"
101 #include "chromeos/login_event_recorder.h"
102 #include "chromeos/network/network_change_notifier_chromeos.h"
103 #include "chromeos/network/network_change_notifier_factory_chromeos.h"
104 #include "chromeos/network/network_handler.h"
105 #include "chromeos/system/statistics_provider.h"
106 #include "chromeos/tpm_token_loader.h"
107 #include "components/metrics/metrics_service.h"
108 #include "components/session_manager/core/session_manager.h"
109 #include "components/user_manager/user.h"
110 #include "components/user_manager/user_manager.h"
111 #include "content/public/browser/browser_thread.h"
112 #include "content/public/browser/notification_service.h"
113 #include "content/public/browser/power_save_blocker.h"
114 #include "content/public/common/main_function_params.h"
115 #include "media/audio/sounds/sounds_manager.h"
116 #include "net/base/network_change_notifier.h"
117 #include "net/url_request/url_request.h"
118 #include "net/url_request/url_request_context_getter.h"
119 #include "ui/base/touch/touch_device.h"
120 #include "ui/events/event_utils.h"
121
122 // Exclude X11 dependents for ozone
123 #if defined(USE_X11)
124 #include "chrome/browser/chromeos/device_uma.h"
125 #include "chrome/browser/chromeos/events/system_key_event_listener.h"
126 #include "chrome/browser/chromeos/events/xinput_hierarchy_changed_event_listener.h"
127 #endif
128
129 namespace chromeos {
130
131 namespace {
132
133 void ChromeOSVersionCallback(const std::string& version) {
134   base::SetLinuxDistro(std::string("CrOS ") + version);
135 }
136
137 bool ShouldAutoLaunchKioskApp(const base::CommandLine& command_line) {
138   KioskAppManager* app_manager = KioskAppManager::Get();
139   return command_line.HasSwitch(switches::kLoginManager) &&
140       !command_line.HasSwitch(switches::kForceLoginManagerInTests) &&
141       app_manager->IsAutoLaunchEnabled() &&
142       KioskAppLaunchError::Get() == KioskAppLaunchError::NONE;
143 }
144
145 }  // namespace
146
147 namespace internal {
148
149 // Wrapper class for initializing dbus related services and shutting them
150 // down. This gets instantiated in a scoped_ptr so that shutdown methods in the
151 // destructor will get called if and only if this has been instantiated.
152 class DBusServices {
153  public:
154   explicit DBusServices(const content::MainFunctionParams& parameters) {
155     // Initialize DBusThreadManager for the browser. This must be done after
156     // the main message loop is started, as it uses the message loop.
157     DBusThreadManager::Initialize();
158     CrosDBusService::Initialize();
159
160     // Initialize PowerDataCollector after DBusThreadManager is initialized.
161     PowerDataCollector::Initialize();
162
163     LoginState::Initialize();
164     SystemSaltGetter::Initialize();
165     TPMTokenLoader::Initialize();
166     CertLoader::Initialize();
167
168     disks::DiskMountManager::Initialize();
169     cryptohome::AsyncMethodCaller::Initialize();
170     cryptohome::HomedirMethods::Initialize();
171
172     NetworkHandler::Initialize();
173     CertLibrary::Initialize();
174
175     // Initialize the network change notifier for Chrome OS. The network
176     // change notifier starts to monitor changes from the power manager and
177     // the network manager.
178     NetworkChangeNotifierFactoryChromeos::GetInstance()->Initialize();
179
180     // Likewise, initialize the upgrade detector for Chrome OS. The upgrade
181     // detector starts to monitor changes from the update engine.
182     UpgradeDetectorChromeos::GetInstance()->Init();
183
184     // Initialize the device settings service so that we'll take actions per
185     // signals sent from the session manager. This needs to happen before
186     // g_browser_process initializes BrowserPolicyConnector.
187     DeviceSettingsService::Initialize();
188     DeviceSettingsService::Get()->SetSessionManager(
189         DBusThreadManager::Get()->GetSessionManagerClient(),
190         OwnerKeyUtil::Create());
191   }
192
193   ~DBusServices() {
194     CertLibrary::Shutdown();
195     NetworkHandler::Shutdown();
196
197     cryptohome::AsyncMethodCaller::Shutdown();
198     disks::DiskMountManager::Shutdown();
199
200     SystemSaltGetter::Shutdown();
201     LoginState::Shutdown();
202     CertLoader::Shutdown();
203     TPMTokenLoader::Shutdown();
204
205     CrosDBusService::Shutdown();
206
207     // Shutdown the PowerDataCollector before shutting down DBusThreadManager.
208     PowerDataCollector::Shutdown();
209
210     // NOTE: This must only be called if Initialize() was called.
211     DBusThreadManager::Shutdown();
212   }
213
214  private:
215
216   DISALLOW_COPY_AND_ASSIGN(DBusServices);
217 };
218
219 }  //  namespace internal
220
221 // ChromeBrowserMainPartsChromeos ----------------------------------------------
222
223 ChromeBrowserMainPartsChromeos::ChromeBrowserMainPartsChromeos(
224     const content::MainFunctionParams& parameters)
225     : ChromeBrowserMainPartsLinux(parameters) {
226 }
227
228 ChromeBrowserMainPartsChromeos::~ChromeBrowserMainPartsChromeos() {
229   if (KioskModeSettings::Get()->IsKioskModeEnabled())
230     ShutdownKioskModeScreensaver();
231
232   // To be precise, logout (browser shutdown) is not yet done, but the
233   // remaining work is negligible, hence we say LogoutDone here.
234   BootTimesLoader::Get()->AddLogoutTimeMarker("LogoutDone", false);
235   BootTimesLoader::Get()->WriteLogoutTimes();
236 }
237
238 // content::BrowserMainParts and ChromeBrowserMainExtraParts overrides ---------
239
240 void ChromeBrowserMainPartsChromeos::PreEarlyInitialization() {
241   CommandLine* singleton_command_line = CommandLine::ForCurrentProcess();
242
243   if (parsed_command_line().HasSwitch(switches::kGuestSession)) {
244     // Disable sync and extensions if we're in "browse without sign-in" mode.
245     singleton_command_line->AppendSwitch(::switches::kDisableSync);
246     singleton_command_line->AppendSwitch(::switches::kDisableExtensions);
247     browser_defaults::bookmarks_enabled = false;
248   }
249
250   // If we're not running on real Chrome OS hardware (or under VM), and are not
251   // showing the login manager or attempting a command line login, login with a
252   // stub user.
253   if (!base::SysInfo::IsRunningOnChromeOS() &&
254       !parsed_command_line().HasSwitch(switches::kLoginManager) &&
255       !parsed_command_line().HasSwitch(switches::kLoginUser) &&
256       !parsed_command_line().HasSwitch(switches::kGuestSession)) {
257     singleton_command_line->AppendSwitchASCII(switches::kLoginUser,
258                                               chromeos::login::kStubUser);
259     if (!parsed_command_line().HasSwitch(switches::kLoginProfile)) {
260       singleton_command_line->AppendSwitchASCII(switches::kLoginProfile,
261                                                 chrome::kTestUserProfileDir);
262     }
263     LOG(WARNING) << "Running as stub user with profile dir: "
264                  << singleton_command_line->GetSwitchValuePath(
265                      switches::kLoginProfile).value();
266   }
267
268 #if defined(GOOGLE_CHROME_BUILD)
269   const char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK";
270   std::string channel;
271   if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &channel))
272     chrome::VersionInfo::SetChannel(channel);
273 #endif
274
275   ChromeBrowserMainPartsLinux::PreEarlyInitialization();
276 }
277
278 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopStart() {
279   // Replace the default NetworkChangeNotifierFactory with ChromeOS specific
280   // implementation. This must be done before BrowserMainLoop calls
281   // net::NetworkChangeNotifier::Create() in MainMessageLoopStart().
282   net::NetworkChangeNotifier::SetFactory(
283       new NetworkChangeNotifierFactoryChromeos());
284   ChromeBrowserMainPartsLinux::PreMainMessageLoopStart();
285 }
286
287 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopStart() {
288   base::FilePath user_data_dir;
289   if (!base::SysInfo::IsRunningOnChromeOS() &&
290       PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
291     // Override some paths with stub locations so that cloud policy and
292     // enterprise enrollment work on desktop builds, for ease of
293     // development.
294     chromeos::RegisterStubPathOverrides(user_data_dir);
295   }
296
297   dbus_services_.reset(new internal::DBusServices(parameters()));
298
299   ChromeBrowserMainPartsLinux::PostMainMessageLoopStart();
300 }
301
302 // Threads are initialized between MainMessageLoopStart and MainMessageLoopRun.
303 // about_flags settings are applied in ChromeBrowserMainParts::PreCreateThreads.
304 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopRun() {
305   // Set the crypto thread after the IO thread has been created/started.
306   TPMTokenLoader::Get()->SetCryptoTaskRunner(
307       content::BrowserThread::GetMessageLoopProxyForThread(
308           content::BrowserThread::IO));
309
310   CrasAudioHandler::Initialize(
311       AudioDevicesPrefHandler::Create(g_browser_process->local_state()));
312
313   // Start loading machine statistics here. StatisticsProvider::Shutdown()
314   // will ensure that loading is aborted on early exit.
315   bool load_oem_statistics = !StartupUtils::IsOobeCompleted();
316   system::StatisticsProvider::GetInstance()->StartLoadingMachineStatistics(
317       content::BrowserThread::GetMessageLoopProxyForThread(
318           content::BrowserThread::FILE),
319       load_oem_statistics);
320
321   base::FilePath downloads_directory;
322   CHECK(PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &downloads_directory));
323   imageburner::BurnManager::Initialize(
324       downloads_directory, g_browser_process->system_request_context());
325
326   DeviceOAuth2TokenServiceFactory::Initialize();
327
328   ChromeBrowserMainPartsLinux::PreMainMessageLoopRun();
329 }
330
331 void ChromeBrowserMainPartsChromeos::PreProfileInit() {
332   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
333   // -- immediately before Profile creation().
334
335   // Now that the file thread exists we can record our stats.
336   BootTimesLoader::Get()->RecordChromeMainStats();
337   LoginEventRecorder::Get()->SetDelegate(BootTimesLoader::Get());
338
339   // Trigger prefetching of ownership status.
340   DeviceSettingsService::Get()->Load();
341
342   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
343   // -- just before CreateProfile().
344
345   g_browser_process->platform_part()->InitializeChromeUserManager();
346
347   // Initialize the screen locker now so that it can receive
348   // LOGIN_USER_CHANGED notification from UserManager.
349   if (KioskModeSettings::Get()->IsKioskModeEnabled())
350     KioskModeIdleLogout::Initialize();
351   else
352     ScreenLocker::InitClass();
353
354   // This forces the ProfileManager to be created and register for the
355   // notification it needs to track the logged in user.
356   g_browser_process->profile_manager();
357
358   // AccessibilityManager and SystemKeyEventListener use InputMethodManager.
359   input_method::Initialize();
360
361   // ProfileHelper has to be initialized after UserManager instance is created.
362   ProfileHelper::Get()->Initialize();
363
364   // TODO(abarth): Should this move to InitializeNetworkOptions()?
365   // Allow access to file:// on ChromeOS for tests.
366   if (parsed_command_line().HasSwitch(::switches::kAllowFileAccess))
367     ChromeNetworkDelegate::AllowAccessToAllFiles();
368
369   // If kLoginUser is passed this indicates that user has already
370   // logged in and we should behave accordingly.
371   bool immediate_login =
372       parsed_command_line().HasSwitch(switches::kLoginUser);
373   if (immediate_login){
374     // Redirects Chrome logging to the user data dir.
375     logging::RedirectChromeLogging(parsed_command_line());
376
377     // Load the default app order synchronously for restarting case.
378     app_order_loader_.reset(
379         new default_app_order::ExternalLoader(false /* async */));
380   }
381
382   if (!app_order_loader_) {
383     app_order_loader_.reset(
384         new default_app_order::ExternalLoader(true /* async */));
385   }
386
387   media::SoundsManager::Create();
388
389   // Initialize magnification manager before ash tray is created. And this must
390   // be placed after UserManager::SessionStarted();
391   AccessibilityManager::Initialize();
392   MagnificationManager::Initialize();
393
394   // Add observers for WallpaperManager. This depends on PowerManagerClient,
395   // TimezoneSettings and CrosSettings.
396   WallpaperManager::Get()->AddObservers();
397
398   cros_version_loader_.GetVersion(VersionLoader::VERSION_FULL,
399                                   base::Bind(&ChromeOSVersionCallback),
400                                   &tracker_);
401
402   // Make sure that wallpaper boot transition and other delays in OOBE
403   // are disabled for tests and kiosk app launch by default.
404   // Individual tests may enable them if they want.
405   if (parsed_command_line().HasSwitch(::switches::kTestType) ||
406       ShouldAutoLaunchKioskApp(parsed_command_line())) {
407     WizardController::SetZeroDelays();
408   }
409
410   power_prefs_.reset(new PowerPrefs(
411       DBusThreadManager::Get()->GetPowerPolicyController()));
412
413   // In Aura builds this will initialize ash::Shell.
414   ChromeBrowserMainPartsLinux::PreProfileInit();
415
416   if (immediate_login) {
417     const std::string user_id = login::CanonicalizeUserID(
418         parsed_command_line().GetSwitchValueASCII(switches::kLoginUser));
419     user_manager::UserManager* user_manager = user_manager::UserManager::Get();
420
421     if (policy::IsDeviceLocalAccountUser(user_id, NULL) &&
422         !user_manager->IsKnownUser(user_id)) {
423       // When a device-local account is removed, its policy is deleted from disk
424       // immediately. If a session using this account happens to be in progress,
425       // the session is allowed to continue with policy served from an in-memory
426       // cache. If Chrome crashes later in the session, the policy becomes
427       // completely unavailable. Exit the session in that case, rather than
428       // allowing it to continue without policy.
429       chrome::AttemptUserExit();
430       return;
431     }
432
433     // In case of multi-profiles --login-profile will contain user_id_hash.
434     std::string user_id_hash =
435         parsed_command_line().GetSwitchValueASCII(switches::kLoginProfile);
436     user_manager->UserLoggedIn(user_id, user_id_hash, true);
437     VLOG(1) << "Relaunching browser for user: " << user_id
438             << " with hash: " << user_id_hash;
439   }
440 }
441
442 class GuestLanguageSetCallbackData {
443  public:
444   explicit GuestLanguageSetCallbackData(Profile* profile) : profile(profile) {
445   }
446
447   // Must match SwitchLanguageCallback type.
448   static void Callback(const scoped_ptr<GuestLanguageSetCallbackData>& self,
449                        const std::string& locale,
450                        const std::string& loaded_locale,
451                        bool success);
452
453   Profile* profile;
454 };
455
456 // static
457 void GuestLanguageSetCallbackData::Callback(
458     const scoped_ptr<GuestLanguageSetCallbackData>& self,
459     const std::string& locale,
460     const std::string& loaded_locale,
461     bool success) {
462   input_method::InputMethodManager* const ime_manager =
463       input_method::InputMethodManager::Get();
464   // Active layout must be hardware "login layout".
465   // The previous one must be "locale default layout".
466   // First, enable all hardware input methods.
467   const std::vector<std::string>& input_methods =
468       ime_manager->GetInputMethodUtil()->GetHardwareInputMethodIds();
469   for (size_t i = 0; i < input_methods.size(); ++i)
470     ime_manager->EnableInputMethod(input_methods[i]);
471
472   // Second, enable locale based input methods.
473   const std::string locale_default_input_method =
474       ime_manager->GetInputMethodUtil()->
475           GetLanguageDefaultInputMethodId(loaded_locale);
476   if (!locale_default_input_method.empty()) {
477     PrefService* user_prefs = self->profile->GetPrefs();
478     user_prefs->SetString(prefs::kLanguagePreviousInputMethod,
479                           locale_default_input_method);
480     ime_manager->EnableInputMethod(locale_default_input_method);
481   }
482
483   // Finally, activate the first login input method.
484   const std::vector<std::string>& login_input_methods =
485       ime_manager->GetInputMethodUtil()->GetHardwareLoginInputMethodIds();
486   ime_manager->ChangeInputMethod(login_input_methods[0]);
487 }
488
489 void SetGuestLocale(Profile* const profile) {
490   scoped_ptr<GuestLanguageSetCallbackData> data(
491       new GuestLanguageSetCallbackData(profile));
492   scoped_ptr<locale_util::SwitchLanguageCallback> callback(
493       new locale_util::SwitchLanguageCallback(base::Bind(
494           &GuestLanguageSetCallbackData::Callback, base::Passed(data.Pass()))));
495   user_manager::User* const user =
496       ProfileHelper::Get()->GetUserByProfile(profile);
497   UserSessionManager::GetInstance()->RespectLocalePreference(
498       profile, user, callback.Pass());
499 }
500
501 void ChromeBrowserMainPartsChromeos::PostProfileInit() {
502   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
503   // -- just after CreateProfile().
504
505   BootTimesLoader::Get()->OnChromeProcessStart();
506
507   // Initialize the network portal detector for Chrome OS. The network
508   // portal detector starts to listen for notifications from
509   // NetworkStateHandler and initiates captive portal detection for
510   // active networks. Should be called before call to CreateSessionManager,
511   // because it depends on NetworkPortalDetector.
512   NetworkPortalDetectorImpl::Initialize(
513       g_browser_process->system_request_context());
514   {
515     NetworkPortalDetector* detector = NetworkPortalDetector::Get();
516 #if defined(GOOGLE_CHROME_BUILD)
517     bool is_official_build = true;
518 #else
519     bool is_official_build = false;
520 #endif
521     // Enable portal detector if EULA was previously accepted or if
522     // this is an unofficial build.
523     if (!is_official_build || StartupUtils::IsEulaAccepted())
524       detector->Enable(true);
525   }
526
527   bool is_running_test = parameters().ui_task != NULL;
528   g_browser_process->platform_part()->InitializeSessionManager(
529       parsed_command_line(), profile(), is_running_test);
530   g_browser_process->platform_part()->SessionManager()->Start();
531
532   // Guest user profile is never initialized with locale settings,
533   // so we need special handling for Guest session.
534   if (user_manager::UserManager::Get()->IsLoggedInAsGuest())
535     SetGuestLocale(profile());
536
537   // These observers must be initialized after the profile because
538   // they use the profile to dispatch extension events.
539   extension_system_event_observer_.reset(new ExtensionSystemEventObserver());
540   if (KioskModeSettings::Get()->IsKioskModeEnabled()) {
541     retail_mode_power_save_blocker_ = content::PowerSaveBlocker::Create(
542         content::PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
543         "Retail mode");
544   }
545
546   peripheral_battery_observer_.reset(new PeripheralBatteryObserver());
547
548   renderer_freezer_.reset(new RendererFreezer());
549
550   g_browser_process->platform_part()->InitializeAutomaticRebootManager();
551
552   // This observer cannot be created earlier because it requires the shell to be
553   // available.
554   idle_action_warning_observer_.reset(new IdleActionWarningObserver());
555
556   ChromeBrowserMainPartsLinux::PostProfileInit();
557 }
558
559 void ChromeBrowserMainPartsChromeos::PreBrowserStart() {
560   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
561   // -- just before MetricsService::LogNeedForCleanShutdown().
562
563   // Start the external metrics service, which collects metrics from Chrome OS
564   // and passes them to the browser process.
565   external_metrics_ = new chromeos::ExternalMetrics;
566   external_metrics_->Start();
567
568 #if defined(USE_X11)
569   // Listen for system key events so that the user will be able to adjust the
570   // volume on the login screen, if Chrome is running on Chrome OS
571   // (i.e. not Linux desktop), and in non-test mode.
572   // Note: SystemKeyEventListener depends on the DBus thread.
573   if (base::SysInfo::IsRunningOnChromeOS() &&
574       !parameters().ui_task) {  // ui_task is non-NULL when running tests.
575     SystemKeyEventListener::Initialize();
576   }
577
578   // Listen for XI_HierarchyChanged events. Note: if this is moved to
579   // PreMainMessageLoopRun() then desktopui_PageCyclerTests fail for unknown
580   // reasons, see http://crosbug.com/24833.
581   XInputHierarchyChangedEventListener::GetInstance();
582
583   // Start the CrOS input device UMA watcher
584   DeviceUMA::GetInstance();
585 #endif
586
587   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
588   // -- immediately after ChildProcess::WaitForDebugger().
589
590   // Start the out-of-memory priority manager here so that we give the most
591   // amount of time for the other services to start up before we start
592   // adjusting the oom priority.
593   g_browser_process->platform_part()->oom_priority_manager()->Start();
594
595   if (ui::ShouldDefaultToNaturalScroll()) {
596     CommandLine::ForCurrentProcess()->AppendSwitch(
597         chromeos::switches::kNaturalScrollDefault);
598     system::InputDeviceSettings::Get()->SetTapToClick(true);
599   }
600
601   ChromeBrowserMainPartsLinux::PreBrowserStart();
602 }
603
604 void ChromeBrowserMainPartsChromeos::PostBrowserStart() {
605   // These are dependent on the ash::Shell singleton already having been
606   // initialized.
607   power_button_observer_.reset(new PowerButtonObserver);
608   data_promo_notification_.reset(new DataPromoNotification());
609
610   keyboard_event_rewriters_.reset(new EventRewriterController());
611   keyboard_event_rewriters_->AddEventRewriter(
612       scoped_ptr<ui::EventRewriter>(new KeyboardDrivenEventRewriter()));
613   keyboard_event_rewriters_->AddEventRewriter(scoped_ptr<ui::EventRewriter>(
614       new EventRewriter(ash::Shell::GetInstance()->sticky_keys_controller())));
615   keyboard_event_rewriters_->Init();
616
617   ChromeBrowserMainPartsLinux::PostBrowserStart();
618 }
619
620 // Shut down services before the browser process, etc are destroyed.
621 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopRun() {
622   BootTimesLoader::Get()->AddLogoutTimeMarker("UIMessageLoopEnded", true);
623
624   g_browser_process->platform_part()->oom_priority_manager()->Stop();
625
626   // Early wake-up of HID device service.
627   InputServiceProxy::WarmUp();
628
629   // Destroy the application name notifier for Kiosk mode.
630   KioskModeIdleAppNameNotification::Shutdown();
631
632   // Shutdown the upgrade detector for Chrome OS. The upgrade detector
633   // stops monitoring changes from the update engine.
634   if (UpgradeDetectorChromeos::GetInstance())
635     UpgradeDetectorChromeos::GetInstance()->Shutdown();
636
637   // Shutdown the network change notifier for Chrome OS. The network
638   // change notifier stops monitoring changes from the power manager and
639   // the network manager.
640   if (NetworkChangeNotifierFactoryChromeos::GetInstance())
641     NetworkChangeNotifierFactoryChromeos::GetInstance()->Shutdown();
642
643   // Destroy UI related classes before destroying services that they may
644   // depend on.
645   data_promo_notification_.reset();
646
647   // Tell DeviceSettingsService to stop talking to session_manager. Do not
648   // shutdown DeviceSettingsService yet, it might still be accessed by
649   // BrowserPolicyConnector (owned by g_browser_process).
650   DeviceSettingsService::Get()->UnsetSessionManager();
651
652   // We should remove observers attached to D-Bus clients before
653   // DBusThreadManager is shut down.
654   extension_system_event_observer_.reset();
655   retail_mode_power_save_blocker_.reset();
656   peripheral_battery_observer_.reset();
657   power_prefs_.reset();
658   renderer_freezer_.reset();
659
660   // Let the ScreenLocker unregister itself from SessionManagerClient before
661   // DBusThreadManager is shut down.
662   if (!KioskModeSettings::Get()->IsKioskModeEnabled())
663     ScreenLocker::ShutDownClass();
664
665   keyboard_event_rewriters_.reset();
666 #if defined(USE_X11)
667   // The XInput2 event listener needs to be shut down earlier than when
668   // Singletons are finally destroyed in AtExitManager.
669   XInputHierarchyChangedEventListener::GetInstance()->Stop();
670
671   DeviceUMA::GetInstance()->Stop();
672
673   // SystemKeyEventListener::Shutdown() is always safe to call,
674   // even if Initialize() wasn't called.
675   SystemKeyEventListener::Shutdown();
676 #endif
677
678   imageburner::BurnManager::Shutdown();
679   CrasAudioHandler::Shutdown();
680
681   // Detach D-Bus clients before DBusThreadManager is shut down.
682   power_button_observer_.reset();
683   idle_action_warning_observer_.reset();
684
685   MagnificationManager::Shutdown();
686   AccessibilityManager::Shutdown();
687
688   media::SoundsManager::Shutdown();
689
690   system::StatisticsProvider::GetInstance()->Shutdown();
691
692   // Let the UserManager and WallpaperManager unregister itself as an observer
693   // of the CrosSettings singleton before it is destroyed. This also ensures
694   // that the UserManager has no URLRequest pending (see
695   // http://crbug.com/276659).
696   g_browser_process->platform_part()->user_manager()->Shutdown();
697   WallpaperManager::Get()->Shutdown();
698
699   // Let the AutomaticRebootManager unregister itself as an observer of several
700   // subsystems.
701   g_browser_process->platform_part()->ShutdownAutomaticRebootManager();
702
703   // Clean up dependency on CrosSettings and stop pending data fetches.
704   KioskAppManager::Shutdown();
705
706   // Let the DeviceCloudPolicyInvalidator unregister itself as an observer of
707   // per-Profile InvalidationServices and the device-global
708   // invalidation::TiclInvalidationService it may have created as an observer of
709   // the DeviceOAuth2TokenService that is about to be destroyed.
710   g_browser_process->platform_part()->browser_policy_connector_chromeos()->
711       ShutdownInvalidator();
712
713   // We first call PostMainMessageLoopRun and then destroy UserManager, because
714   // Ash needs to be closed before UserManager is destroyed.
715   ChromeBrowserMainPartsLinux::PostMainMessageLoopRun();
716
717   input_method::Shutdown();
718
719   // Stops all in-flight OAuth2 token fetchers before the IO thread stops.
720   DeviceOAuth2TokenServiceFactory::Shutdown();
721
722   // Called after
723   // ChromeBrowserMainPartsLinux::PostMainMessageLoopRun() to be
724   // executed after execution of chrome::CloseAsh(), because some
725   // parts of WebUI depends on NetworkPortalDetector.
726   NetworkPortalDetector::Shutdown();
727
728   g_browser_process->platform_part()->DestroyChromeUserManager();
729
730   g_browser_process->platform_part()->ShutdownSessionManager();
731 }
732
733 void ChromeBrowserMainPartsChromeos::PostDestroyThreads() {
734   // Destroy DBus services immediately after threads are stopped.
735   dbus_services_.reset();
736
737   ChromeBrowserMainPartsLinux::PostDestroyThreads();
738
739   // Destroy DeviceSettingsService after g_browser_process.
740   DeviceSettingsService::Shutdown();
741 }
742
743 }  //  namespace chromeos