Home | History | Annotate | Download | only in chromeos
      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/message_loop/message_loop.h"
     19 #include "base/path_service.h"
     20 #include "base/prefs/pref_service.h"
     21 #include "base/strings/string_number_conversions.h"
     22 #include "base/strings/string_split.h"
     23 #include "base/sys_info.h"
     24 #include "chrome/browser/browser_process.h"
     25 #include "chrome/browser/browser_process_platform_part_chromeos.h"
     26 #include "chrome/browser/chrome_notification_types.h"
     27 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
     28 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
     29 #include "chrome/browser/chromeos/app_mode/kiosk_app_launch_error.h"
     30 #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
     31 #include "chrome/browser/chromeos/boot_times_loader.h"
     32 #include "chrome/browser/chromeos/contacts/contact_manager.h"
     33 #include "chrome/browser/chromeos/dbus/cros_dbus_service.h"
     34 #include "chrome/browser/chromeos/display/display_configuration_observer.h"
     35 #include "chrome/browser/chromeos/extensions/default_app_order.h"
     36 #include "chrome/browser/chromeos/extensions/extension_system_event_observer.h"
     37 #include "chrome/browser/chromeos/external_metrics.h"
     38 #include "chrome/browser/chromeos/imageburner/burn_manager.h"
     39 #include "chrome/browser/chromeos/input_method/input_method_configuration.h"
     40 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_idle_logout.h"
     41 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_screensaver.h"
     42 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.h"
     43 #include "chrome/browser/chromeos/login/authenticator.h"
     44 #include "chrome/browser/chromeos/login/login_utils.h"
     45 #include "chrome/browser/chromeos/login/login_wizard.h"
     46 #include "chrome/browser/chromeos/login/screen_locker.h"
     47 #include "chrome/browser/chromeos/login/startup_utils.h"
     48 #include "chrome/browser/chromeos/login/user_manager.h"
     49 #include "chrome/browser/chromeos/login/wallpaper_manager.h"
     50 #include "chrome/browser/chromeos/login/wizard_controller.h"
     51 #include "chrome/browser/chromeos/memory/oom_priority_manager.h"
     52 #include "chrome/browser/chromeos/net/network_portal_detector.h"
     53 #include "chrome/browser/chromeos/options/cert_library.h"
     54 #include "chrome/browser/chromeos/power/idle_action_warning_observer.h"
     55 #include "chrome/browser/chromeos/power/peripheral_battery_observer.h"
     56 #include "chrome/browser/chromeos/power/power_button_observer.h"
     57 #include "chrome/browser/chromeos/power/power_prefs.h"
     58 #include "chrome/browser/chromeos/profiles/profile_helper.h"
     59 #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h"
     60 #include "chrome/browser/chromeos/settings/device_settings_service.h"
     61 #include "chrome/browser/chromeos/settings/owner_key_util.h"
     62 #include "chrome/browser/chromeos/status/data_promo_notification.h"
     63 #include "chrome/browser/chromeos/system_key_event_listener.h"
     64 #include "chrome/browser/chromeos/upgrade_detector_chromeos.h"
     65 #include "chrome/browser/chromeos/xinput_hierarchy_changed_event_listener.h"
     66 #include "chrome/browser/defaults.h"
     67 #include "chrome/browser/metrics/metrics_service.h"
     68 #include "chrome/browser/net/chrome_network_delegate.h"
     69 #include "chrome/browser/policy/browser_policy_connector.h"
     70 #include "chrome/browser/profiles/profile.h"
     71 #include "chrome/browser/profiles/profile_manager.h"
     72 #include "chrome/browser/rlz/rlz.h"
     73 #include "chrome/common/chrome_constants.h"
     74 #include "chrome/common/chrome_paths.h"
     75 #include "chrome/common/chrome_switches.h"
     76 #include "chrome/common/chrome_version_info.h"
     77 #include "chrome/common/logging_chrome.h"
     78 #include "chrome/common/pref_names.h"
     79 #include "chromeos/audio/audio_devices_pref_handler.h"
     80 #include "chromeos/audio/cras_audio_handler.h"
     81 #include "chromeos/chromeos_paths.h"
     82 #include "chromeos/chromeos_switches.h"
     83 #include "chromeos/cryptohome/async_method_caller.h"
     84 #include "chromeos/cryptohome/system_salt_getter.h"
     85 #include "chromeos/dbus/dbus_thread_manager.h"
     86 #include "chromeos/dbus/power_policy_controller.h"
     87 #include "chromeos/dbus/session_manager_client.h"
     88 #include "chromeos/disks/disk_mount_manager.h"
     89 #include "chromeos/ime/input_method_manager.h"
     90 #include "chromeos/ime/xkeyboard.h"
     91 #include "chromeos/login/login_state.h"
     92 #include "chromeos/network/network_change_notifier_chromeos.h"
     93 #include "chromeos/network/network_change_notifier_factory_chromeos.h"
     94 #include "chromeos/network/network_handler.h"
     95 #include "chromeos/system/statistics_provider.h"
     96 #include "content/public/browser/browser_thread.h"
     97 #include "content/public/browser/notification_service.h"
     98 #include "content/public/browser/power_save_blocker.h"
     99 #include "content/public/common/main_function_params.h"
    100 #include "grit/platform_locale_settings.h"
    101 #include "media/audio/sounds/sounds_manager.h"
    102 #include "net/base/network_change_notifier.h"
    103 #include "net/url_request/url_request.h"
    104 #include "net/url_request/url_request_context_getter.h"
    105 #include "ui/base/touch/touch_device.h"
    106 #include "ui/events/event_utils.h"
    107 
    108 // Exclude X11 dependents for ozone
    109 #if defined(USE_X11)
    110 #include "chrome/browser/chromeos/device_uma.h"
    111 #endif
    112 
    113 namespace chromeos {
    114 
    115 namespace {
    116 
    117 void ChromeOSVersionCallback(const std::string& version) {
    118   base::SetLinuxDistro(std::string("CrOS ") + version);
    119 }
    120 
    121 class MessageLoopObserver : public base::MessageLoopForUI::Observer {
    122   virtual base::EventStatus WillProcessEvent(
    123       const base::NativeEvent& event) OVERRIDE {
    124     return base::EVENT_CONTINUE;
    125   }
    126 
    127   virtual void DidProcessEvent(
    128       const base::NativeEvent& event) OVERRIDE {
    129   }
    130 };
    131 
    132 static base::LazyInstance<MessageLoopObserver> g_message_loop_observer =
    133     LAZY_INSTANCE_INITIALIZER;
    134 
    135 // Login -----------------------------------------------------------------------
    136 
    137 // Class is used to login using passed username and password.
    138 // The instance will be deleted upon success or failure.
    139 class StubLogin : public LoginStatusConsumer,
    140                   public LoginUtils::Delegate {
    141  public:
    142   StubLogin(std::string username, std::string password)
    143       : profile_prepared_(false) {
    144     authenticator_ = LoginUtils::Get()->CreateAuthenticator(this);
    145     authenticator_.get()->AuthenticateToLogin(
    146         ProfileHelper::GetSigninProfile(),
    147         UserContext(username, password, std::string() /* auth_code */));
    148   }
    149 
    150   virtual ~StubLogin() {
    151     LoginUtils::Get()->DelegateDeleted(this);
    152   }
    153 
    154   virtual void OnLoginFailure(const LoginFailure& error) OVERRIDE {
    155     LOG(ERROR) << "Login Failure: " << error.GetErrorString();
    156     delete this;
    157   }
    158 
    159   virtual void OnLoginSuccess(const UserContext& user_context) OVERRIDE {
    160     if (!profile_prepared_) {
    161       // Will call OnProfilePrepared in the end.
    162       LoginUtils::Get()->PrepareProfile(user_context,
    163                                         std::string(),  // display_email
    164                                         false,          // has_cookies
    165                                         true,           // has_active_session
    166                                         this);
    167     } else {
    168       delete this;
    169     }
    170   }
    171 
    172   // LoginUtils::Delegate implementation:
    173   virtual void OnProfilePrepared(Profile* profile) OVERRIDE {
    174     profile_prepared_ = true;
    175     LoginUtils::Get()->DoBrowserLaunch(profile, NULL);
    176     delete this;
    177   }
    178 
    179   scoped_refptr<Authenticator> authenticator_;
    180   bool profile_prepared_;
    181 };
    182 
    183 bool ShouldAutoLaunchKioskApp(const CommandLine& command_line) {
    184   KioskAppManager* app_manager = KioskAppManager::Get();
    185   return command_line.HasSwitch(switches::kLoginManager) &&
    186       !command_line.HasSwitch(switches::kForceLoginManagerInTests) &&
    187       app_manager->IsAutoLaunchEnabled() &&
    188       KioskAppLaunchError::Get() == KioskAppLaunchError::NONE;
    189 }
    190 
    191 void RunAutoLaunchKioskApp() {
    192   ShowLoginWizard(chromeos::WizardController::kAppLaunchSplashScreenName);
    193 
    194   // Login screen is skipped but 'login-prompt-visible' signal is still needed.
    195   VLOG(1) << "Kiosk app auto launch >> login-prompt-visible";
    196   DBusThreadManager::Get()->GetSessionManagerClient()->
    197       EmitLoginPromptVisible();
    198 }
    199 
    200 void OptionallyRunChromeOSLoginManager(const CommandLine& parsed_command_line,
    201                                        Profile* profile) {
    202   if (ShouldAutoLaunchKioskApp(parsed_command_line)) {
    203     RunAutoLaunchKioskApp();
    204   } else if (parsed_command_line.HasSwitch(switches::kLoginManager)) {
    205     const std::string first_screen =
    206         parsed_command_line.HasSwitch(switches::kLoginScreen) ?
    207             WizardController::kLoginScreenName : std::string();
    208     ShowLoginWizard(first_screen);
    209 
    210     if (KioskModeSettings::Get()->IsKioskModeEnabled())
    211       InitializeKioskModeScreensaver();
    212 
    213     // Reset reboot after update flag when login screen is shown.
    214     if (!g_browser_process->browser_policy_connector()->
    215         IsEnterpriseManaged()) {
    216       PrefService* local_state = g_browser_process->local_state();
    217       local_state->ClearPref(prefs::kRebootAfterUpdate);
    218     }
    219   } else if (parsed_command_line.HasSwitch(switches::kLoginUser) &&
    220              parsed_command_line.HasSwitch(switches::kLoginPassword)) {
    221     BootTimesLoader::Get()->RecordLoginAttempted();
    222     new StubLogin(
    223         parsed_command_line.GetSwitchValueASCII(switches::kLoginUser),
    224         parsed_command_line.GetSwitchValueASCII(switches::kLoginPassword));
    225   } else {
    226     if (!parsed_command_line.HasSwitch(::switches::kTestName)) {
    227       // Enable CrasAudioHandler logging when chrome restarts after crashing.
    228       if (chromeos::CrasAudioHandler::IsInitialized())
    229         chromeos::CrasAudioHandler::Get()->LogErrors();
    230 
    231       // We did not log in (we crashed or are debugging), so we need to
    232       // restore Sync.
    233       LoginUtils::Get()->RestoreAuthenticationSession(profile);
    234     }
    235   }
    236 }
    237 
    238 }  // namespace
    239 
    240 namespace internal {
    241 
    242 // Wrapper class for initializing dbus related services and shutting them
    243 // down. This gets instantiated in a scoped_ptr so that shutdown methods in the
    244 // destructor will get called if and only if this has been instantiated.
    245 class DBusServices {
    246  public:
    247   explicit DBusServices(const content::MainFunctionParams& parameters) {
    248     if (!base::SysInfo::IsRunningOnChromeOS()) {
    249       // Override this path on the desktop, so that the user policy key can be
    250       // stored by the stub SessionManagerClient.
    251       base::FilePath user_data_dir;
    252       if (PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
    253         PathService::Override(chromeos::DIR_USER_POLICY_KEYS,
    254                               user_data_dir.AppendASCII("stub_user_policy"));
    255       }
    256     }
    257 
    258     // Initialize DBusThreadManager for the browser. This must be done after
    259     // the main message loop is started, as it uses the message loop.
    260     DBusThreadManager::Initialize();
    261     CrosDBusService::Initialize();
    262 
    263     LoginState::Initialize();
    264     SystemSaltGetter::Initialize();
    265     CertLoader::Initialize();
    266 
    267     // This function and SystemKeyEventListener use InputMethodManager.
    268     chromeos::input_method::Initialize(
    269         content::BrowserThread::GetMessageLoopProxyForThread(
    270             content::BrowserThread::UI),
    271         content::BrowserThread::GetMessageLoopProxyForThread(
    272             content::BrowserThread::FILE));
    273     disks::DiskMountManager::Initialize();
    274     cryptohome::AsyncMethodCaller::Initialize();
    275 
    276     NetworkHandler::Initialize();
    277     CertLibrary::Initialize();
    278 
    279     // Initialize the network change notifier for Chrome OS. The network
    280     // change notifier starts to monitor changes from the power manager and
    281     // the network manager.
    282     NetworkChangeNotifierFactoryChromeos::GetInstance()->Initialize();
    283 
    284     // Likewise, initialize the upgrade detector for Chrome OS. The upgrade
    285     // detector starts to monitor changes from the update engine.
    286     UpgradeDetectorChromeos::GetInstance()->Init();
    287 
    288     if (base::SysInfo::IsRunningOnChromeOS()) {
    289       // Disable Num Lock on X start up for http://crosbug.com/29169.
    290       input_method::InputMethodManager::Get()->GetXKeyboard()->
    291           SetNumLockEnabled(false);
    292     }
    293 
    294     // Initialize the device settings service so that we'll take actions per
    295     // signals sent from the session manager. This needs to happen before
    296     // g_browser_process initializes BrowserPolicyConnector.
    297     DeviceSettingsService::Initialize();
    298     DeviceSettingsService::Get()->SetSessionManager(
    299         DBusThreadManager::Get()->GetSessionManagerClient(),
    300         OwnerKeyUtil::Create());
    301   }
    302 
    303   ~DBusServices() {
    304     CertLibrary::Shutdown();
    305     NetworkHandler::Shutdown();
    306 
    307     cryptohome::AsyncMethodCaller::Shutdown();
    308     disks::DiskMountManager::Shutdown();
    309     input_method::Shutdown();
    310 
    311     SystemSaltGetter::Shutdown();
    312     LoginState::Shutdown();
    313 
    314     CrosDBusService::Shutdown();
    315 
    316     // NOTE: This must only be called if Initialize() was called.
    317     DBusThreadManager::Shutdown();
    318   }
    319 
    320  private:
    321 
    322   DISALLOW_COPY_AND_ASSIGN(DBusServices);
    323 };
    324 
    325 }  //  namespace internal
    326 
    327 // ChromeBrowserMainPartsChromeos ----------------------------------------------
    328 
    329 ChromeBrowserMainPartsChromeos::ChromeBrowserMainPartsChromeos(
    330     const content::MainFunctionParams& parameters)
    331     : ChromeBrowserMainPartsLinux(parameters) {
    332 }
    333 
    334 ChromeBrowserMainPartsChromeos::~ChromeBrowserMainPartsChromeos() {
    335   if (KioskModeSettings::Get()->IsKioskModeEnabled())
    336     ShutdownKioskModeScreensaver();
    337 
    338   // To be precise, logout (browser shutdown) is not yet done, but the
    339   // remaining work is negligible, hence we say LogoutDone here.
    340   BootTimesLoader::Get()->AddLogoutTimeMarker("LogoutDone", false);
    341   BootTimesLoader::Get()->WriteLogoutTimes();
    342 }
    343 
    344 // content::BrowserMainParts and ChromeBrowserMainExtraParts overrides ---------
    345 
    346 void ChromeBrowserMainPartsChromeos::PreEarlyInitialization() {
    347   CommandLine* singleton_command_line = CommandLine::ForCurrentProcess();
    348 
    349   if (parsed_command_line().HasSwitch(switches::kGuestSession)) {
    350     // Disable sync and extensions if we're in "browse without sign-in" mode.
    351     singleton_command_line->AppendSwitch(::switches::kDisableSync);
    352     singleton_command_line->AppendSwitch(::switches::kDisableExtensions);
    353     browser_defaults::bookmarks_enabled = false;
    354   }
    355 
    356   // If we're not running on real ChromeOS hardware (or under VM), and are not
    357   // showing the login manager or attempting a command line login, login with a
    358   // stub user.
    359   if (!base::SysInfo::IsRunningOnChromeOS() &&
    360       !parsed_command_line().HasSwitch(switches::kLoginManager) &&
    361       !parsed_command_line().HasSwitch(switches::kLoginUser) &&
    362       !parsed_command_line().HasSwitch(switches::kGuestSession)) {
    363     singleton_command_line->AppendSwitchASCII(
    364         switches::kLoginUser, UserManager::kStubUser);
    365     if (!parsed_command_line().HasSwitch(switches::kLoginProfile)) {
    366       singleton_command_line->AppendSwitchASCII(switches::kLoginProfile,
    367                                                 chrome::kTestUserProfileDir);
    368     }
    369     LOG(WARNING) << "Running as stub user with profile dir: "
    370                  << singleton_command_line->GetSwitchValuePath(
    371                      switches::kLoginProfile).value();
    372   }
    373 
    374 #if defined(GOOGLE_CHROME_BUILD)
    375   const char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK";
    376   std::string channel;
    377   if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &channel))
    378     chrome::VersionInfo::SetChannel(channel);
    379 #endif
    380 
    381   ChromeBrowserMainPartsLinux::PreEarlyInitialization();
    382 }
    383 
    384 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopStart() {
    385   // Replace the default NetworkChangeNotifierFactory with ChromeOS specific
    386   // implementation. This must be done before BrowserMainLoop calls
    387   // net::NetworkChangeNotifier::Create() in MainMessageLoopStart().
    388   net::NetworkChangeNotifier::SetFactory(
    389       new NetworkChangeNotifierFactoryChromeos());
    390   ChromeBrowserMainPartsLinux::PreMainMessageLoopStart();
    391 }
    392 
    393 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopStart() {
    394   base::MessageLoopForUI* message_loop = base::MessageLoopForUI::current();
    395   message_loop->AddObserver(g_message_loop_observer.Pointer());
    396 
    397   dbus_services_.reset(new internal::DBusServices(parameters()));
    398 
    399   ChromeBrowserMainPartsLinux::PostMainMessageLoopStart();
    400 }
    401 
    402 // Threads are initialized between MainMessageLoopStart and MainMessageLoopRun.
    403 // about_flags settings are applied in ChromeBrowserMainParts::PreCreateThreads.
    404 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopRun() {
    405   // Set the crypto thread after the IO thread has been created/started.
    406   CertLoader::Get()->SetCryptoTaskRunner(
    407       content::BrowserThread::GetMessageLoopProxyForThread(
    408           content::BrowserThread::IO));
    409 
    410   CrasAudioHandler::Initialize(
    411       AudioDevicesPrefHandler::Create(g_browser_process->local_state()));
    412 
    413   // Start loading machine statistics here. StatisticsProvider::Shutdown()
    414   // will ensure that loading is aborted on early exit.
    415   bool load_oem_statistics = !StartupUtils::IsOobeCompleted();
    416   system::StatisticsProvider::GetInstance()->StartLoadingMachineStatistics(
    417       content::BrowserThread::GetMessageLoopProxyForThread(
    418           content::BrowserThread::FILE),
    419       load_oem_statistics);
    420 
    421   base::FilePath downloads_directory;
    422   CHECK(PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &downloads_directory));
    423   imageburner::BurnManager::Initialize(
    424       downloads_directory, g_browser_process->system_request_context());
    425 
    426   // Listen for system key events so that the user will be able to adjust the
    427   // volume on the login screen, if Chrome is running on Chrome OS
    428   // (i.e. not Linux desktop), and in non-test mode.
    429   // Note: SystemKeyEventListener depends on the DBus thread.
    430   if (base::SysInfo::IsRunningOnChromeOS() &&
    431       !parameters().ui_task) {  // ui_task is non-NULL when running tests.
    432     SystemKeyEventListener::Initialize();
    433   }
    434 
    435   DeviceOAuth2TokenServiceFactory::Initialize();
    436 
    437   ChromeBrowserMainPartsLinux::PreMainMessageLoopRun();
    438 }
    439 
    440 void ChromeBrowserMainPartsChromeos::PreProfileInit() {
    441   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
    442   // -- immediately before Profile creation().
    443 
    444   // Now that the file thread exists we can record our stats.
    445   BootTimesLoader::Get()->RecordChromeMainStats();
    446 
    447   // Trigger prefetching of ownership status.
    448   DeviceSettingsService::Get()->Load();
    449 
    450   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
    451   // -- just before CreateProfile().
    452 
    453   UserManager::Initialize();
    454 
    455   // Initialize the screen locker now so that it can receive
    456   // LOGIN_USER_CHANGED notification from UserManager.
    457   if (KioskModeSettings::Get()->IsKioskModeEnabled()) {
    458     KioskModeIdleLogout::Initialize();
    459   } else {
    460     ScreenLocker::InitClass();
    461   }
    462 
    463   // This forces the ProfileManager to be created and register for the
    464   // notification it needs to track the logged in user.
    465   g_browser_process->profile_manager();
    466 
    467   // ProfileHelper has to be initialized after UserManager instance is created.
    468   g_browser_process->platform_part()->profile_helper()->Initialize();
    469 
    470   // TODO(abarth): Should this move to InitializeNetworkOptions()?
    471   // Allow access to file:// on ChromeOS for tests.
    472   if (parsed_command_line().HasSwitch(::switches::kAllowFileAccess))
    473     ChromeNetworkDelegate::AllowAccessToAllFiles();
    474 
    475   if (parsed_command_line().HasSwitch(::switches::kEnableContacts)) {
    476     contact_manager_.reset(new contacts::ContactManager());
    477     contact_manager_->Init();
    478   }
    479 
    480   // There are two use cases for kLoginUser:
    481   //   1) if passed in tandem with kLoginPassword, to drive a "StubLogin"
    482   //   2) if passed alone, to signal that the indicated user has already
    483   //      logged in and we should behave accordingly.
    484   // This handles case 2.
    485   bool immediate_login =
    486       parsed_command_line().HasSwitch(switches::kLoginUser) &&
    487       !parsed_command_line().HasSwitch(switches::kLoginPassword);
    488   if (immediate_login){
    489     // Redirects Chrome logging to the user data dir.
    490     logging::RedirectChromeLogging(parsed_command_line());
    491 
    492     // Load the default app order synchronously for restarting case.
    493     app_order_loader_.reset(
    494         new default_app_order::ExternalLoader(false /* async */));
    495   }
    496 
    497   if (!app_order_loader_) {
    498     app_order_loader_.reset(
    499         new default_app_order::ExternalLoader(true /* async */));
    500   }
    501 
    502   media::SoundsManager::Create();
    503 
    504   // Initialize magnification manager before ash tray is created. And this must
    505   // be placed after UserManager::SessionStarted();
    506   AccessibilityManager::Initialize();
    507   MagnificationManager::Initialize();
    508 
    509   // Add observers for WallpaperManager. This depends on PowerManagerClient,
    510   // TimezoneSettings and CrosSettings.
    511   WallpaperManager::Get()->AddObservers();
    512 
    513   cros_version_loader_.GetVersion(VersionLoader::VERSION_FULL,
    514                                   base::Bind(&ChromeOSVersionCallback),
    515                                   &tracker_);
    516 
    517   // Make sure that wallpaper boot transition and other delays in OOBE
    518   // are disabled for tests and kiosk app launch by default.
    519   // Individual tests may enable them if they want.
    520   if (parsed_command_line().HasSwitch(::switches::kTestType) ||
    521       ShouldAutoLaunchKioskApp(parsed_command_line())) {
    522     WizardController::SetZeroDelays();
    523   }
    524 
    525   power_prefs_.reset(new PowerPrefs(
    526       DBusThreadManager::Get()->GetPowerPolicyController()));
    527 
    528   // In Aura builds this will initialize ash::Shell.
    529   ChromeBrowserMainPartsLinux::PreProfileInit();
    530 
    531   if (immediate_login) {
    532     std::string username =
    533         parsed_command_line().GetSwitchValueASCII(switches::kLoginUser);
    534     UserManager* user_manager = UserManager::Get();
    535     // In case of multi-profiles --login-profile will contain user_id_hash.
    536     std::string username_hash =
    537         parsed_command_line().GetSwitchValueASCII(switches::kLoginProfile);
    538     user_manager->UserLoggedIn(username, username_hash, true);
    539     VLOG(1) << "Relaunching browser for user: " << username
    540             << " with hash: " << username_hash;
    541   }
    542 }
    543 
    544 void ChromeBrowserMainPartsChromeos::PostProfileInit() {
    545   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
    546   // -- just after CreateProfile().
    547 
    548   // Restarting Chrome inside existing user session. Possible cases:
    549   // 1. Chrome is restarted after crash.
    550   // 2. Chrome is started in browser_tests skipping the login flow
    551   // 3. Chrome is started on dev machine
    552   //    i.e. not on Chrome OS device w/o login flow.
    553   if (parsed_command_line().HasSwitch(switches::kLoginUser) &&
    554       !parsed_command_line().HasSwitch(switches::kLoginPassword)) {
    555     // This is done in LoginUtils::OnProfileCreated during normal login.
    556     LoginUtils::Get()->InitRlzDelayed(profile());
    557 
    558     // Send the PROFILE_PREPARED notification and call SessionStarted()
    559     // so that the Launcher and other Profile dependent classes are created.
    560     content::NotificationService::current()->Notify(
    561         chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
    562         content::NotificationService::AllSources(),
    563         content::Details<Profile>(profile()));
    564     UserManager::Get()->SessionStarted();
    565 
    566     // Now is the good time to retrieve other logged in users for this session.
    567     // First user has been already marked as logged in and active in
    568     // PreProfileInit(). Chrome should tread other user in a session as active
    569     // in the background.
    570     UserManager::Get()->RestoreActiveSessions();
    571   }
    572 
    573   // Initialize the network portal detector for Chrome OS. The network
    574   // portal detector starts to listen for notifications from
    575   // NetworkStateHandler and initiates captive portal detection for
    576   // active networks. Shoule be called before call to
    577   // OptionallyRunChromeOSLoginManager, because it depends on
    578   // NetworkPortalDetector.
    579   NetworkPortalDetector::Initialize();
    580   {
    581     NetworkPortalDetector* detector = NetworkPortalDetector::Get();
    582 #if defined(GOOGLE_CHROME_BUILD)
    583     bool is_official_build = true;
    584 #else
    585     bool is_official_build = false;
    586 #endif
    587     // Enable portal detector if EULA was previously accepted or if
    588     // this is an unofficial build.
    589     if (!is_official_build || StartupUtils::IsEulaAccepted())
    590       detector->Enable(true);
    591   }
    592 
    593   // Tests should be able to tune login manager before showing it.
    594   // Thus only show login manager in normal (non-testing) mode.
    595   if (!parameters().ui_task ||
    596       parsed_command_line().HasSwitch(switches::kForceLoginManagerInTests)) {
    597     OptionallyRunChromeOSLoginManager(parsed_command_line(), profile());
    598   }
    599 
    600   // These observers must be initialized after the profile because
    601   // they use the profile to dispatch extension events.
    602   extension_system_event_observer_.reset(new ExtensionSystemEventObserver());
    603   if (KioskModeSettings::Get()->IsKioskModeEnabled()) {
    604     retail_mode_power_save_blocker_ = content::PowerSaveBlocker::Create(
    605         content::PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
    606         "Retail mode");
    607   }
    608 
    609   peripheral_battery_observer_.reset(new PeripheralBatteryObserver());
    610 
    611   display_configuration_observer_.reset(
    612       new DisplayConfigurationObserver());
    613 
    614   g_browser_process->platform_part()->InitializeAutomaticRebootManager();
    615 
    616   // This observer cannot be created earlier because it requires the shell to be
    617   // available.
    618   idle_action_warning_observer_.reset(new IdleActionWarningObserver());
    619 
    620   ChromeBrowserMainPartsLinux::PostProfileInit();
    621 }
    622 
    623 void ChromeBrowserMainPartsChromeos::PreBrowserStart() {
    624   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
    625   // -- just before MetricsService::LogNeedForCleanShutdown().
    626 
    627   g_browser_process->metrics_service()->StartExternalMetrics();
    628 
    629   // Listen for XI_HierarchyChanged events. Note: if this is moved to
    630   // PreMainMessageLoopRun() then desktopui_PageCyclerTests fail for unknown
    631   // reasons, see http://crosbug.com/24833.
    632   XInputHierarchyChangedEventListener::GetInstance();
    633 
    634 #if defined(USE_X11)
    635   // Start the CrOS input device UMA watcher
    636   DeviceUMA::GetInstance();
    637 #endif
    638 
    639   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
    640   // -- immediately after ChildProcess::WaitForDebugger().
    641 
    642   // Start the out-of-memory priority manager here so that we give the most
    643   // amount of time for the other services to start up before we start
    644   // adjusting the oom priority.
    645   g_browser_process->platform_part()->oom_priority_manager()->Start();
    646 
    647   if (ui::ShouldDefaultToNaturalScroll()) {
    648     CommandLine::ForCurrentProcess()->AppendSwitch(
    649         chromeos::switches::kNaturalScrollDefault);
    650     ui::SetNaturalScroll(true);
    651   }
    652 
    653   ChromeBrowserMainPartsLinux::PreBrowserStart();
    654 }
    655 
    656 void ChromeBrowserMainPartsChromeos::PostBrowserStart() {
    657   // These are dependent on the ash::Shell singleton already having been
    658   // initialized.
    659   power_button_observer_.reset(new PowerButtonObserver);
    660   data_promo_notification_.reset(new DataPromoNotification()),
    661 
    662   ChromeBrowserMainPartsLinux::PostBrowserStart();
    663 }
    664 
    665 // Shut down services before the browser process, etc are destroyed.
    666 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopRun() {
    667   BootTimesLoader::Get()->AddLogoutTimeMarker("UIMessageLoopEnded", true);
    668 
    669   g_browser_process->platform_part()->oom_priority_manager()->Stop();
    670 
    671   // Stops all in-flight OAuth2 token fetchers before the IO thread stops.
    672   DeviceOAuth2TokenServiceFactory::Shutdown();
    673 
    674   // Shutdown the upgrade detector for Chrome OS. The upgrade detector
    675   // stops monitoring changes from the update engine.
    676   if (UpgradeDetectorChromeos::GetInstance())
    677     UpgradeDetectorChromeos::GetInstance()->Shutdown();
    678 
    679   // Shutdown the network change notifier for Chrome OS. The network
    680   // change notifier stops monitoring changes from the power manager and
    681   // the network manager.
    682   if (NetworkChangeNotifierFactoryChromeos::GetInstance())
    683     NetworkChangeNotifierFactoryChromeos::GetInstance()->Shutdown();
    684 
    685   // Destroy UI related classes before destroying services that they may
    686   // depend on.
    687   data_promo_notification_.reset();
    688 
    689   // Tell DeviceSettingsService to stop talking to session_manager. Do not
    690   // shutdown DeviceSettingsService yet, it might still be accessed by
    691   // BrowserPolicyConnector (owned by g_browser_process).
    692   DeviceSettingsService::Get()->UnsetSessionManager();
    693 
    694   // We should remove observers attached to D-Bus clients before
    695   // DBusThreadManager is shut down.
    696   extension_system_event_observer_.reset();
    697   retail_mode_power_save_blocker_.reset();
    698   peripheral_battery_observer_.reset();
    699   power_prefs_.reset();
    700 
    701   // The XInput2 event listener needs to be shut down earlier than when
    702   // Singletons are finally destroyed in AtExitManager.
    703   XInputHierarchyChangedEventListener::GetInstance()->Stop();
    704 
    705 #if defined(USE_X11)
    706   DeviceUMA::GetInstance()->Stop();
    707 #endif
    708 
    709   // SystemKeyEventListener::Shutdown() is always safe to call,
    710   // even if Initialize() wasn't called.
    711   SystemKeyEventListener::Shutdown();
    712   imageburner::BurnManager::Shutdown();
    713   CrasAudioHandler::Shutdown();
    714 
    715   // Let classes unregister themselves as observers of the ash::Shell singleton
    716   // before the shell is destroyed.
    717   display_configuration_observer_.reset();
    718 
    719   // Detach D-Bus clients before DBusThreadManager is shut down.
    720   power_button_observer_.reset();
    721   idle_action_warning_observer_.reset();
    722 
    723   // Delete ContactManager while |g_browser_process| is still alive.
    724   contact_manager_.reset();
    725 
    726   MagnificationManager::Shutdown();
    727   AccessibilityManager::Shutdown();
    728 
    729   media::SoundsManager::Shutdown();
    730 
    731   system::StatisticsProvider::GetInstance()->Shutdown();
    732 
    733   // Let the UserManager and WallpaperManager unregister itself as an observer
    734   // of the CrosSettings singleton before it is destroyed. This also ensures
    735   // that the UserManager has no URLRequest pending (see
    736   // http://crbug.com/276659).
    737   UserManager::Get()->Shutdown();
    738   WallpaperManager::Get()->Shutdown();
    739 
    740   // Let the AutomaticRebootManager unregister itself as an observer of several
    741   // subsystems.
    742   g_browser_process->platform_part()->ShutdownAutomaticRebootManager();
    743 
    744   // Clean up dependency on CrosSettings and stop pending data fetches.
    745   KioskAppManager::Shutdown();
    746 
    747   // We first call PostMainMessageLoopRun and then destroy UserManager, because
    748   // Ash needs to be closed before UserManager is destroyed. Also, on some tests
    749   // MergeSessionThrottle::ShouldShowMergeSessionPage gets triggered during
    750   // PostMainMessageLoopRun, which also requires UserManager to live (see
    751   // http://crbug.com/243364).
    752   ChromeBrowserMainPartsLinux::PostMainMessageLoopRun();
    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   UserManager::Destroy();
    761 }
    762 
    763 void ChromeBrowserMainPartsChromeos::PostDestroyThreads() {
    764   // Destroy DBus services immediately after threads are stopped.
    765   dbus_services_.reset();
    766 
    767   ChromeBrowserMainPartsLinux::PostDestroyThreads();
    768 
    769   // Destroy DeviceSettingsService after g_browser_process.
    770   DeviceSettingsService::Shutdown();
    771 }
    772 
    773 }  //  namespace chromeos
    774