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