chrome_browser_main_chromeos.cc revision 03b57e008b61dfcb1fbad3aea950ae0e001748b0
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
129namespace chromeos {
130
131namespace {
132
133void ChromeOSVersionCallback(const std::string& version) {
134  base::SetLinuxDistro(std::string("CrOS ") + version);
135}
136
137bool 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
147namespace 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.
152class 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
223ChromeBrowserMainPartsChromeos::ChromeBrowserMainPartsChromeos(
224    const content::MainFunctionParams& parameters)
225    : ChromeBrowserMainPartsLinux(parameters) {
226}
227
228ChromeBrowserMainPartsChromeos::~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
240void 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
278void 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
287void 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.
304void 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
331void 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
442class 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
457void 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* manager =
463      input_method::InputMethodManager::Get();
464  scoped_refptr<input_method::InputMethodManager::State> ime_state =
465      manager->GetActiveIMEState();
466  // Active layout must be hardware "login layout".
467  // The previous one must be "locale default layout".
468  // First, enable all hardware input methods.
469  const std::vector<std::string>& input_methods =
470      manager->GetInputMethodUtil()->GetHardwareInputMethodIds();
471  for (size_t i = 0; i < input_methods.size(); ++i)
472    ime_state->EnableInputMethod(input_methods[i]);
473
474  // Second, enable locale based input methods.
475  const std::string locale_default_input_method =
476      manager->GetInputMethodUtil()->GetLanguageDefaultInputMethodId(
477          loaded_locale);
478  if (!locale_default_input_method.empty()) {
479    PrefService* user_prefs = self->profile->GetPrefs();
480    user_prefs->SetString(prefs::kLanguagePreviousInputMethod,
481                          locale_default_input_method);
482    ime_state->EnableInputMethod(locale_default_input_method);
483  }
484
485  // Finally, activate the first login input method.
486  const std::vector<std::string>& login_input_methods =
487      manager->GetInputMethodUtil()->GetHardwareLoginInputMethodIds();
488  ime_state->ChangeInputMethod(login_input_methods[0],
489                               false /* show_message */);
490}
491
492void SetGuestLocale(Profile* const profile) {
493  scoped_ptr<GuestLanguageSetCallbackData> data(
494      new GuestLanguageSetCallbackData(profile));
495  scoped_ptr<locale_util::SwitchLanguageCallback> callback(
496      new locale_util::SwitchLanguageCallback(base::Bind(
497          &GuestLanguageSetCallbackData::Callback, base::Passed(data.Pass()))));
498  user_manager::User* const user =
499      ProfileHelper::Get()->GetUserByProfile(profile);
500  UserSessionManager::GetInstance()->RespectLocalePreference(
501      profile, user, callback.Pass());
502}
503
504void ChromeBrowserMainPartsChromeos::PostProfileInit() {
505  // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
506  // -- just after CreateProfile().
507
508  BootTimesLoader::Get()->OnChromeProcessStart();
509
510  // Initialize the network portal detector for Chrome OS. The network
511  // portal detector starts to listen for notifications from
512  // NetworkStateHandler and initiates captive portal detection for
513  // active networks. Should be called before call to CreateSessionManager,
514  // because it depends on NetworkPortalDetector.
515  NetworkPortalDetectorImpl::Initialize(
516      g_browser_process->system_request_context());
517  {
518    NetworkPortalDetector* detector = NetworkPortalDetector::Get();
519#if defined(GOOGLE_CHROME_BUILD)
520    bool is_official_build = true;
521#else
522    bool is_official_build = false;
523#endif
524    // Enable portal detector if EULA was previously accepted or if
525    // this is an unofficial build.
526    if (!is_official_build || StartupUtils::IsEulaAccepted())
527      detector->Enable(true);
528  }
529
530  // Initialize input methods.
531  input_method::InputMethodManager* manager =
532      input_method::InputMethodManager::Get();
533  UserSessionManager* session_manager = UserSessionManager::GetInstance();
534  DCHECK(manager);
535  DCHECK(session_manager);
536
537  manager->SetState(session_manager->GetDefaultIMEState(profile()));
538
539  bool is_running_test = parameters().ui_task != NULL;
540  g_browser_process->platform_part()->InitializeSessionManager(
541      parsed_command_line(), profile(), is_running_test);
542  g_browser_process->platform_part()->SessionManager()->Start();
543
544  // Guest user profile is never initialized with locale settings,
545  // so we need special handling for Guest session.
546  if (user_manager::UserManager::Get()->IsLoggedInAsGuest())
547    SetGuestLocale(profile());
548
549  // These observers must be initialized after the profile because
550  // they use the profile to dispatch extension events.
551  extension_system_event_observer_.reset(new ExtensionSystemEventObserver());
552  if (KioskModeSettings::Get()->IsKioskModeEnabled()) {
553    retail_mode_power_save_blocker_ = content::PowerSaveBlocker::Create(
554        content::PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
555        "Retail mode");
556  }
557
558  peripheral_battery_observer_.reset(new PeripheralBatteryObserver());
559
560  renderer_freezer_.reset(new RendererFreezer());
561
562  g_browser_process->platform_part()->InitializeAutomaticRebootManager();
563
564  // This observer cannot be created earlier because it requires the shell to be
565  // available.
566  idle_action_warning_observer_.reset(new IdleActionWarningObserver());
567
568  ChromeBrowserMainPartsLinux::PostProfileInit();
569}
570
571void ChromeBrowserMainPartsChromeos::PreBrowserStart() {
572  // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
573  // -- just before MetricsService::LogNeedForCleanShutdown().
574
575  // Start the external metrics service, which collects metrics from Chrome OS
576  // and passes them to the browser process.
577  external_metrics_ = new chromeos::ExternalMetrics;
578  external_metrics_->Start();
579
580#if defined(USE_X11)
581  // Listen for system key events so that the user will be able to adjust the
582  // volume on the login screen, if Chrome is running on Chrome OS
583  // (i.e. not Linux desktop), and in non-test mode.
584  // Note: SystemKeyEventListener depends on the DBus thread.
585  if (base::SysInfo::IsRunningOnChromeOS() &&
586      !parameters().ui_task) {  // ui_task is non-NULL when running tests.
587    SystemKeyEventListener::Initialize();
588  }
589
590  // Listen for XI_HierarchyChanged events. Note: if this is moved to
591  // PreMainMessageLoopRun() then desktopui_PageCyclerTests fail for unknown
592  // reasons, see http://crosbug.com/24833.
593  XInputHierarchyChangedEventListener::GetInstance();
594
595  // Start the CrOS input device UMA watcher
596  DeviceUMA::GetInstance();
597#endif
598
599  // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
600  // -- immediately after ChildProcess::WaitForDebugger().
601
602  // Start the out-of-memory priority manager here so that we give the most
603  // amount of time for the other services to start up before we start
604  // adjusting the oom priority.
605  g_browser_process->platform_part()->oom_priority_manager()->Start();
606
607  if (ui::ShouldDefaultToNaturalScroll()) {
608    CommandLine::ForCurrentProcess()->AppendSwitch(
609        chromeos::switches::kNaturalScrollDefault);
610    system::InputDeviceSettings::Get()->SetTapToClick(true);
611  }
612
613  ChromeBrowserMainPartsLinux::PreBrowserStart();
614}
615
616void ChromeBrowserMainPartsChromeos::PostBrowserStart() {
617  // These are dependent on the ash::Shell singleton already having been
618  // initialized.
619  power_button_observer_.reset(new PowerButtonObserver);
620  data_promo_notification_.reset(new DataPromoNotification());
621
622  keyboard_event_rewriters_.reset(new EventRewriterController());
623  keyboard_event_rewriters_->AddEventRewriter(
624      scoped_ptr<ui::EventRewriter>(new KeyboardDrivenEventRewriter()));
625  keyboard_event_rewriters_->AddEventRewriter(scoped_ptr<ui::EventRewriter>(
626      new EventRewriter(ash::Shell::GetInstance()->sticky_keys_controller())));
627  keyboard_event_rewriters_->Init();
628
629  ChromeBrowserMainPartsLinux::PostBrowserStart();
630}
631
632// Shut down services before the browser process, etc are destroyed.
633void ChromeBrowserMainPartsChromeos::PostMainMessageLoopRun() {
634  BootTimesLoader::Get()->AddLogoutTimeMarker("UIMessageLoopEnded", true);
635
636  g_browser_process->platform_part()->oom_priority_manager()->Stop();
637
638  // Early wake-up of HID device service.
639  InputServiceProxy::WarmUp();
640
641  // Destroy the application name notifier for Kiosk mode.
642  KioskModeIdleAppNameNotification::Shutdown();
643
644  // Shutdown the upgrade detector for Chrome OS. The upgrade detector
645  // stops monitoring changes from the update engine.
646  if (UpgradeDetectorChromeos::GetInstance())
647    UpgradeDetectorChromeos::GetInstance()->Shutdown();
648
649  // Shutdown the network change notifier for Chrome OS. The network
650  // change notifier stops monitoring changes from the power manager and
651  // the network manager.
652  if (NetworkChangeNotifierFactoryChromeos::GetInstance())
653    NetworkChangeNotifierFactoryChromeos::GetInstance()->Shutdown();
654
655  // Destroy UI related classes before destroying services that they may
656  // depend on.
657  data_promo_notification_.reset();
658
659  // Tell DeviceSettingsService to stop talking to session_manager. Do not
660  // shutdown DeviceSettingsService yet, it might still be accessed by
661  // BrowserPolicyConnector (owned by g_browser_process).
662  DeviceSettingsService::Get()->UnsetSessionManager();
663
664  // We should remove observers attached to D-Bus clients before
665  // DBusThreadManager is shut down.
666  extension_system_event_observer_.reset();
667  retail_mode_power_save_blocker_.reset();
668  peripheral_battery_observer_.reset();
669  power_prefs_.reset();
670  renderer_freezer_.reset();
671
672  // Let the ScreenLocker unregister itself from SessionManagerClient before
673  // DBusThreadManager is shut down.
674  if (!KioskModeSettings::Get()->IsKioskModeEnabled())
675    ScreenLocker::ShutDownClass();
676
677  keyboard_event_rewriters_.reset();
678#if defined(USE_X11)
679  // The XInput2 event listener needs to be shut down earlier than when
680  // Singletons are finally destroyed in AtExitManager.
681  XInputHierarchyChangedEventListener::GetInstance()->Stop();
682
683  DeviceUMA::GetInstance()->Stop();
684
685  // SystemKeyEventListener::Shutdown() is always safe to call,
686  // even if Initialize() wasn't called.
687  SystemKeyEventListener::Shutdown();
688#endif
689
690  imageburner::BurnManager::Shutdown();
691  CrasAudioHandler::Shutdown();
692
693  // Detach D-Bus clients before DBusThreadManager is shut down.
694  power_button_observer_.reset();
695  idle_action_warning_observer_.reset();
696
697  MagnificationManager::Shutdown();
698  AccessibilityManager::Shutdown();
699
700  media::SoundsManager::Shutdown();
701
702  system::StatisticsProvider::GetInstance()->Shutdown();
703
704  // Let the UserManager and WallpaperManager unregister itself as an observer
705  // of the CrosSettings singleton before it is destroyed. This also ensures
706  // that the UserManager has no URLRequest pending (see
707  // http://crbug.com/276659).
708  g_browser_process->platform_part()->user_manager()->Shutdown();
709  WallpaperManager::Get()->Shutdown();
710
711  // Let the AutomaticRebootManager unregister itself as an observer of several
712  // subsystems.
713  g_browser_process->platform_part()->ShutdownAutomaticRebootManager();
714
715  // Clean up dependency on CrosSettings and stop pending data fetches.
716  KioskAppManager::Shutdown();
717
718  // Give BrowserPolicyConnectorChromeOS a chance to unregister any observers
719  // on services that are going to be deleted later but before its Shutdown()
720  // is called.
721  g_browser_process->platform_part()->browser_policy_connector_chromeos()->
722      PreShutdown();
723
724  // We first call PostMainMessageLoopRun and then destroy UserManager, because
725  // Ash needs to be closed before UserManager is destroyed.
726  ChromeBrowserMainPartsLinux::PostMainMessageLoopRun();
727
728  input_method::Shutdown();
729
730  // Stops all in-flight OAuth2 token fetchers before the IO thread stops.
731  DeviceOAuth2TokenServiceFactory::Shutdown();
732
733  // Called after
734  // ChromeBrowserMainPartsLinux::PostMainMessageLoopRun() to be
735  // executed after execution of chrome::CloseAsh(), because some
736  // parts of WebUI depends on NetworkPortalDetector.
737  NetworkPortalDetector::Shutdown();
738
739  g_browser_process->platform_part()->DestroyChromeUserManager();
740
741  g_browser_process->platform_part()->ShutdownSessionManager();
742}
743
744void ChromeBrowserMainPartsChromeos::PostDestroyThreads() {
745  // Destroy DBus services immediately after threads are stopped.
746  dbus_services_.reset();
747
748  ChromeBrowserMainPartsLinux::PostDestroyThreads();
749
750  // Destroy DeviceSettingsService after g_browser_process.
751  DeviceSettingsService::Shutdown();
752}
753
754}  //  namespace chromeos
755