Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / chrome_browser_main_chromeos.cc
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
6
7 #include <string>
8 #include <vector>
9
10 #include "ash/ash_switches.h"
11 #include "ash/shell.h"
12 #include "base/bind.h"
13 #include "base/callback.h"
14 #include "base/command_line.h"
15 #include "base/file_util.h"
16 #include "base/lazy_instance.h"
17 #include "base/linux_util.h"
18 #include "base/path_service.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_split.h"
22 #include "base/sys_info.h"
23 #include "chrome/browser/browser_process.h"
24 #include "chrome/browser/browser_process_platform_part_chromeos.h"
25 #include "chrome/browser/chrome_notification_types.h"
26 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
27 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
28 #include "chrome/browser/chromeos/app_mode/kiosk_app_launch_error.h"
29 #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
30 #include "chrome/browser/chromeos/app_mode/kiosk_mode_idle_app_name_notification.h"
31 #include "chrome/browser/chromeos/boot_times_loader.h"
32 #include "chrome/browser/chromeos/dbus/cros_dbus_service.h"
33 #include "chrome/browser/chromeos/events/event_rewriter.h"
34 #include "chrome/browser/chromeos/events/event_rewriter_controller.h"
35 #include "chrome/browser/chromeos/events/keyboard_driven_event_rewriter.h"
36 #include "chrome/browser/chromeos/extensions/default_app_order.h"
37 #include "chrome/browser/chromeos/extensions/extension_system_event_observer.h"
38 #include "chrome/browser/chromeos/external_metrics.h"
39 #include "chrome/browser/chromeos/imageburner/burn_manager.h"
40 #include "chrome/browser/chromeos/input_method/input_method_configuration.h"
41 #include "chrome/browser/chromeos/input_method/input_method_util.h"
42 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_idle_logout.h"
43 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_screensaver.h"
44 #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.h"
45 #include "chrome/browser/chromeos/language_preferences.h"
46 #include "chrome/browser/chromeos/login/authenticator.h"
47 #include "chrome/browser/chromeos/login/login_utils.h"
48 #include "chrome/browser/chromeos/login/login_wizard.h"
49 #include "chrome/browser/chromeos/login/screen_locker.h"
50 #include "chrome/browser/chromeos/login/startup_utils.h"
51 #include "chrome/browser/chromeos/login/user.h"
52 #include "chrome/browser/chromeos/login/user_manager.h"
53 #include "chrome/browser/chromeos/login/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.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/profiles/profile_helper.h"
66 #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h"
67 #include "chrome/browser/chromeos/settings/device_settings_service.h"
68 #include "chrome/browser/chromeos/settings/owner_key_util.h"
69 #include "chrome/browser/chromeos/status/data_promo_notification.h"
70 #include "chrome/browser/chromeos/system/input_device_settings.h"
71 #include "chrome/browser/chromeos/upgrade_detector_chromeos.h"
72 #include "chrome/browser/defaults.h"
73 #include "chrome/browser/lifetime/application_lifetime.h"
74 #include "chrome/browser/metrics/metrics_service.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/network/network_change_notifier_chromeos.h"
101 #include "chromeos/network/network_change_notifier_factory_chromeos.h"
102 #include "chromeos/network/network_handler.h"
103 #include "chromeos/system/statistics_provider.h"
104 #include "chromeos/tpm_token_loader.h"
105 #include "content/public/browser/browser_thread.h"
106 #include "content/public/browser/notification_service.h"
107 #include "content/public/browser/power_save_blocker.h"
108 #include "content/public/common/main_function_params.h"
109 #include "grit/platform_locale_settings.h"
110 #include "media/audio/sounds/sounds_manager.h"
111 #include "net/base/network_change_notifier.h"
112 #include "net/url_request/url_request.h"
113 #include "net/url_request/url_request_context_getter.h"
114 #include "ui/base/touch/touch_device.h"
115 #include "ui/events/event_utils.h"
116
117 // Exclude X11 dependents for ozone
118 #if defined(USE_X11)
119 #include "chrome/browser/chromeos/device_uma.h"
120 #include "chrome/browser/chromeos/events/system_key_event_listener.h"
121 #include "chrome/browser/chromeos/events/xinput_hierarchy_changed_event_listener.h"
122 #endif
123
124 namespace chromeos {
125
126 namespace {
127
128 void ChromeOSVersionCallback(const std::string& version) {
129   base::SetLinuxDistro(std::string("CrOS ") + version);
130 }
131
132 // Login -----------------------------------------------------------------------
133
134 // Class is used to login using passed username and password.
135 // The instance will be deleted upon success or failure.
136 class StubLogin : public LoginStatusConsumer,
137                   public LoginUtils::Delegate {
138  public:
139   StubLogin(std::string username, std::string password)
140       : profile_prepared_(false) {
141     authenticator_ = LoginUtils::Get()->CreateAuthenticator(this);
142     authenticator_.get()->AuthenticateToLogin(
143         ProfileHelper::GetSigninProfile(),
144         UserContext(username, password, std::string() /* auth_code */));
145   }
146
147   virtual ~StubLogin() {
148     LoginUtils::Get()->DelegateDeleted(this);
149   }
150
151   virtual void OnLoginFailure(const LoginFailure& error) OVERRIDE {
152     LOG(ERROR) << "Login Failure: " << error.GetErrorString();
153     delete this;
154   }
155
156   virtual void OnLoginSuccess(const UserContext& user_context) OVERRIDE {
157     if (!profile_prepared_) {
158       // Will call OnProfilePrepared in the end.
159       LoginUtils::Get()->PrepareProfile(user_context,
160                                         std::string(),  // display_email
161                                         false,          // has_cookies
162                                         true,           // has_active_session
163                                         this);
164     } else {
165       delete this;
166     }
167   }
168
169   // LoginUtils::Delegate implementation:
170   virtual void OnProfilePrepared(Profile* profile) OVERRIDE {
171     const std::string login_user =
172         CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
173             chromeos::switches::kLoginUser);
174     if (!policy::IsDeviceLocalAccountUser(login_user, NULL)) {
175       profile->GetPrefs()->SetString(prefs::kGoogleServicesUsername,
176                                      login_user);
177     }
178     profile_prepared_ = true;
179     LoginUtils::Get()->DoBrowserLaunch(profile, NULL);
180     delete this;
181   }
182
183   scoped_refptr<Authenticator> authenticator_;
184   bool profile_prepared_;
185 };
186
187 bool ShouldAutoLaunchKioskApp(const CommandLine& command_line) {
188   KioskAppManager* app_manager = KioskAppManager::Get();
189   return command_line.HasSwitch(switches::kLoginManager) &&
190       !command_line.HasSwitch(switches::kForceLoginManagerInTests) &&
191       app_manager->IsAutoLaunchEnabled() &&
192       KioskAppLaunchError::Get() == KioskAppLaunchError::NONE;
193 }
194
195 void RunAutoLaunchKioskApp() {
196   ShowLoginWizard(chromeos::WizardController::kAppLaunchSplashScreenName);
197
198   // Login screen is skipped but 'login-prompt-visible' signal is still needed.
199   VLOG(1) << "Kiosk app auto launch >> login-prompt-visible";
200   DBusThreadManager::Get()->GetSessionManagerClient()->
201       EmitLoginPromptVisible();
202 }
203
204 void OptionallyRunChromeOSLoginManager(const CommandLine& parsed_command_line,
205                                        Profile* profile) {
206   if (ShouldAutoLaunchKioskApp(parsed_command_line)) {
207     RunAutoLaunchKioskApp();
208   } else if (parsed_command_line.HasSwitch(switches::kLoginManager)) {
209     ShowLoginWizard(std::string());
210
211     if (KioskModeSettings::Get()->IsKioskModeEnabled())
212       InitializeKioskModeScreensaver();
213
214     // Reset reboot after update flag when login screen is shown.
215     policy::BrowserPolicyConnectorChromeOS* connector =
216         g_browser_process->platform_part()->browser_policy_connector_chromeos();
217     if (!connector->IsEnterpriseManaged()) {
218       PrefService* local_state = g_browser_process->local_state();
219       local_state->ClearPref(prefs::kRebootAfterUpdate);
220     }
221   } else if (parsed_command_line.HasSwitch(switches::kLoginUser) &&
222              parsed_command_line.HasSwitch(switches::kLoginPassword)) {
223     BootTimesLoader::Get()->RecordLoginAttempted();
224     new StubLogin(
225         parsed_command_line.GetSwitchValueASCII(switches::kLoginUser),
226         parsed_command_line.GetSwitchValueASCII(switches::kLoginPassword));
227   } else {
228     if (!parsed_command_line.HasSwitch(::switches::kTestName)) {
229       // Enable CrasAudioHandler logging when chrome restarts after crashing.
230       if (chromeos::CrasAudioHandler::IsInitialized())
231         chromeos::CrasAudioHandler::Get()->LogErrors();
232
233       // We did not log in (we crashed or are debugging), so we need to
234       // restore Sync.
235       LoginUtils::Get()->RestoreAuthenticationSession(profile);
236     }
237   }
238 }
239
240 }  // namespace
241
242 namespace internal {
243
244 // Wrapper class for initializing dbus related services and shutting them
245 // down. This gets instantiated in a scoped_ptr so that shutdown methods in the
246 // destructor will get called if and only if this has been instantiated.
247 class DBusServices {
248  public:
249   explicit DBusServices(const content::MainFunctionParams& parameters) {
250     // Initialize DBusThreadManager for the browser. This must be done after
251     // the main message loop is started, as it uses the message loop.
252     DBusThreadManager::Initialize();
253     CrosDBusService::Initialize();
254
255     // Initialize PowerDataCollector after DBusThreadManager is initialized.
256     PowerDataCollector::Initialize();
257
258     LoginState::Initialize();
259     SystemSaltGetter::Initialize();
260     TPMTokenLoader::Initialize();
261     CertLoader::Initialize();
262
263     // This function and SystemKeyEventListener use InputMethodManager.
264     chromeos::input_method::Initialize(
265         content::BrowserThread::GetMessageLoopProxyForThread(
266             content::BrowserThread::UI),
267         content::BrowserThread::GetMessageLoopProxyForThread(
268             content::BrowserThread::FILE));
269     disks::DiskMountManager::Initialize();
270     cryptohome::AsyncMethodCaller::Initialize();
271     cryptohome::HomedirMethods::Initialize();
272
273     NetworkHandler::Initialize();
274     CertLibrary::Initialize();
275
276     // Initialize the network change notifier for Chrome OS. The network
277     // change notifier starts to monitor changes from the power manager and
278     // the network manager.
279     NetworkChangeNotifierFactoryChromeos::GetInstance()->Initialize();
280
281     // Likewise, initialize the upgrade detector for Chrome OS. The upgrade
282     // detector starts to monitor changes from the update engine.
283     UpgradeDetectorChromeos::GetInstance()->Init();
284
285     if (base::SysInfo::IsRunningOnChromeOS()) {
286       // Disable Num Lock on X start up for http://crosbug.com/29169.
287       input_method::InputMethodManager::Get()
288           ->GetImeKeyboard()
289           ->DisableNumLock();
290     }
291
292     // Initialize the device settings service so that we'll take actions per
293     // signals sent from the session manager. This needs to happen before
294     // g_browser_process initializes BrowserPolicyConnector.
295     DeviceSettingsService::Initialize();
296     DeviceSettingsService::Get()->SetSessionManager(
297         DBusThreadManager::Get()->GetSessionManagerClient(),
298         OwnerKeyUtil::Create());
299   }
300
301   ~DBusServices() {
302     CertLibrary::Shutdown();
303     NetworkHandler::Shutdown();
304
305     cryptohome::AsyncMethodCaller::Shutdown();
306     disks::DiskMountManager::Shutdown();
307     input_method::Shutdown();
308
309     SystemSaltGetter::Shutdown();
310     LoginState::Shutdown();
311     CertLoader::Shutdown();
312     TPMTokenLoader::Shutdown();
313
314     CrosDBusService::Shutdown();
315
316     // Shutdown the PowerDataCollector before shutting down DBusThreadManager.
317     PowerDataCollector::Shutdown();
318
319     // NOTE: This must only be called if Initialize() was called.
320     DBusThreadManager::Shutdown();
321   }
322
323  private:
324
325   DISALLOW_COPY_AND_ASSIGN(DBusServices);
326 };
327
328 }  //  namespace internal
329
330 // ChromeBrowserMainPartsChromeos ----------------------------------------------
331
332 ChromeBrowserMainPartsChromeos::ChromeBrowserMainPartsChromeos(
333     const content::MainFunctionParams& parameters)
334     : ChromeBrowserMainPartsLinux(parameters) {
335 }
336
337 ChromeBrowserMainPartsChromeos::~ChromeBrowserMainPartsChromeos() {
338   if (KioskModeSettings::Get()->IsKioskModeEnabled())
339     ShutdownKioskModeScreensaver();
340
341   // To be precise, logout (browser shutdown) is not yet done, but the
342   // remaining work is negligible, hence we say LogoutDone here.
343   BootTimesLoader::Get()->AddLogoutTimeMarker("LogoutDone", false);
344   BootTimesLoader::Get()->WriteLogoutTimes();
345 }
346
347 // content::BrowserMainParts and ChromeBrowserMainExtraParts overrides ---------
348
349 void ChromeBrowserMainPartsChromeos::PreEarlyInitialization() {
350   CommandLine* singleton_command_line = CommandLine::ForCurrentProcess();
351
352   if (parsed_command_line().HasSwitch(switches::kGuestSession)) {
353     // Disable sync and extensions if we're in "browse without sign-in" mode.
354     singleton_command_line->AppendSwitch(::switches::kDisableSync);
355     singleton_command_line->AppendSwitch(::switches::kDisableExtensions);
356     browser_defaults::bookmarks_enabled = false;
357   }
358
359   // If we're not running on real ChromeOS hardware (or under VM), and are not
360   // showing the login manager or attempting a command line login, login with a
361   // stub user.
362   if (!base::SysInfo::IsRunningOnChromeOS() &&
363       !parsed_command_line().HasSwitch(switches::kLoginManager) &&
364       !parsed_command_line().HasSwitch(switches::kLoginUser) &&
365       !parsed_command_line().HasSwitch(switches::kGuestSession)) {
366     singleton_command_line->AppendSwitchASCII(
367         switches::kLoginUser, UserManager::kStubUser);
368     if (!parsed_command_line().HasSwitch(switches::kLoginProfile)) {
369       singleton_command_line->AppendSwitchASCII(switches::kLoginProfile,
370                                                 chrome::kTestUserProfileDir);
371     }
372     LOG(WARNING) << "Running as stub user with profile dir: "
373                  << singleton_command_line->GetSwitchValuePath(
374                      switches::kLoginProfile).value();
375   }
376
377 #if defined(GOOGLE_CHROME_BUILD)
378   const char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK";
379   std::string channel;
380   if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &channel))
381     chrome::VersionInfo::SetChannel(channel);
382 #endif
383
384   ChromeBrowserMainPartsLinux::PreEarlyInitialization();
385 }
386
387 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopStart() {
388   // Replace the default NetworkChangeNotifierFactory with ChromeOS specific
389   // implementation. This must be done before BrowserMainLoop calls
390   // net::NetworkChangeNotifier::Create() in MainMessageLoopStart().
391   net::NetworkChangeNotifier::SetFactory(
392       new NetworkChangeNotifierFactoryChromeos());
393   ChromeBrowserMainPartsLinux::PreMainMessageLoopStart();
394 }
395
396 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopStart() {
397   base::FilePath user_data_dir;
398   if (!base::SysInfo::IsRunningOnChromeOS() &&
399       PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
400     // Override some paths with stub locations so that cloud policy and
401     // enterprise enrollment work on desktop builds, for ease of
402     // development.
403     chromeos::RegisterStubPathOverrides(user_data_dir);
404   }
405
406   dbus_services_.reset(new internal::DBusServices(parameters()));
407
408   ChromeBrowserMainPartsLinux::PostMainMessageLoopStart();
409 }
410
411 // Threads are initialized between MainMessageLoopStart and MainMessageLoopRun.
412 // about_flags settings are applied in ChromeBrowserMainParts::PreCreateThreads.
413 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopRun() {
414   // Set the crypto thread after the IO thread has been created/started.
415   TPMTokenLoader::Get()->SetCryptoTaskRunner(
416       content::BrowserThread::GetMessageLoopProxyForThread(
417           content::BrowserThread::IO));
418
419   CrasAudioHandler::Initialize(
420       AudioDevicesPrefHandler::Create(g_browser_process->local_state()));
421
422   // Start loading machine statistics here. StatisticsProvider::Shutdown()
423   // will ensure that loading is aborted on early exit.
424   bool load_oem_statistics = !StartupUtils::IsOobeCompleted();
425   system::StatisticsProvider::GetInstance()->StartLoadingMachineStatistics(
426       content::BrowserThread::GetMessageLoopProxyForThread(
427           content::BrowserThread::FILE),
428       load_oem_statistics);
429
430   base::FilePath downloads_directory;
431   CHECK(PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &downloads_directory));
432   imageburner::BurnManager::Initialize(
433       downloads_directory, g_browser_process->system_request_context());
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   // This forces the ProfileManager to be created and register for the
463   // notification it needs to track the logged in user.
464   g_browser_process->profile_manager();
465
466   // ProfileHelper has to be initialized after UserManager instance is created.
467   g_browser_process->platform_part()->profile_helper()->Initialize();
468
469   // TODO(abarth): Should this move to InitializeNetworkOptions()?
470   // Allow access to file:// on ChromeOS for tests.
471   if (parsed_command_line().HasSwitch(::switches::kAllowFileAccess))
472     ChromeNetworkDelegate::AllowAccessToAllFiles();
473
474   // There are two use cases for kLoginUser:
475   //   1) if passed in tandem with kLoginPassword, to drive a "StubLogin"
476   //   2) if passed alone, to signal that the indicated user has already
477   //      logged in and we should behave accordingly.
478   // This handles case 2.
479   bool immediate_login =
480       parsed_command_line().HasSwitch(switches::kLoginUser) &&
481       !parsed_command_line().HasSwitch(switches::kLoginPassword);
482   if (immediate_login){
483     // Redirects Chrome logging to the user data dir.
484     logging::RedirectChromeLogging(parsed_command_line());
485
486     // Load the default app order synchronously for restarting case.
487     app_order_loader_.reset(
488         new default_app_order::ExternalLoader(false /* async */));
489   }
490
491   if (!app_order_loader_) {
492     app_order_loader_.reset(
493         new default_app_order::ExternalLoader(true /* async */));
494   }
495
496   media::SoundsManager::Create();
497
498   // Initialize magnification manager before ash tray is created. And this must
499   // be placed after UserManager::SessionStarted();
500   AccessibilityManager::Initialize();
501   MagnificationManager::Initialize();
502
503   // Add observers for WallpaperManager. This depends on PowerManagerClient,
504   // TimezoneSettings and CrosSettings.
505   WallpaperManager::Get()->AddObservers();
506
507   cros_version_loader_.GetVersion(VersionLoader::VERSION_FULL,
508                                   base::Bind(&ChromeOSVersionCallback),
509                                   &tracker_);
510
511   // Make sure that wallpaper boot transition and other delays in OOBE
512   // are disabled for tests and kiosk app launch by default.
513   // Individual tests may enable them if they want.
514   if (parsed_command_line().HasSwitch(::switches::kTestType) ||
515       ShouldAutoLaunchKioskApp(parsed_command_line())) {
516     WizardController::SetZeroDelays();
517   }
518
519   power_prefs_.reset(new PowerPrefs(
520       DBusThreadManager::Get()->GetPowerPolicyController()));
521
522   // In Aura builds this will initialize ash::Shell.
523   ChromeBrowserMainPartsLinux::PreProfileInit();
524
525   if (immediate_login) {
526     const std::string user_id =
527         parsed_command_line().GetSwitchValueASCII(switches::kLoginUser);
528     UserManager* user_manager = UserManager::Get();
529
530     if (policy::IsDeviceLocalAccountUser(user_id, NULL) &&
531         !user_manager->IsKnownUser(user_id)) {
532       // When a device-local account is removed, its policy is deleted from disk
533       // immediately. If a session using this account happens to be in progress,
534       // the session is allowed to continue with policy served from an in-memory
535       // cache. If Chrome crashes later in the session, the policy becomes
536       // completely unavailable. Exit the session in that case, rather than
537       // allowing it to continue without policy.
538       chrome::AttemptUserExit();
539       return;
540     }
541
542     // In case of multi-profiles --login-profile will contain user_id_hash.
543     std::string user_id_hash =
544         parsed_command_line().GetSwitchValueASCII(switches::kLoginProfile);
545     user_manager->UserLoggedIn(user_id, user_id_hash, true);
546     VLOG(1) << "Relaunching browser for user: " << user_id
547             << " with hash: " << user_id_hash;
548   }
549 }
550
551 class GuestLanguageSetCallbackData {
552  public:
553   explicit GuestLanguageSetCallbackData(Profile* profile) : profile(profile) {
554   }
555
556   // Must match SwitchLanguageCallback type.
557   static void Callback(const scoped_ptr<GuestLanguageSetCallbackData>& self,
558                        const std::string& locale,
559                        const std::string& loaded_locale,
560                        bool success);
561
562   Profile* profile;
563 };
564
565 // static
566 void GuestLanguageSetCallbackData::Callback(
567     const scoped_ptr<GuestLanguageSetCallbackData>& self,
568     const std::string& locale,
569     const std::string& loaded_locale,
570     bool success) {
571   input_method::InputMethodManager* const ime_manager =
572       input_method::InputMethodManager::Get();
573   // Active layout must be hardware "login layout".
574   // The previous one must be "locale default layout".
575   // First, enable all hardware input methods.
576   const std::vector<std::string>& input_methods =
577       ime_manager->GetInputMethodUtil()->GetHardwareInputMethodIds();
578   for (size_t i = 0; i < input_methods.size(); ++i)
579     ime_manager->EnableInputMethod(input_methods[i]);
580
581   // Second, enable locale based input methods.
582   const std::string locale_default_input_method =
583       ime_manager->GetInputMethodUtil()->
584           GetLanguageDefaultInputMethodId(loaded_locale);
585   if (!locale_default_input_method.empty()) {
586     PrefService* user_prefs = self->profile->GetPrefs();
587     user_prefs->SetString(prefs::kLanguagePreviousInputMethod,
588                           locale_default_input_method);
589     ime_manager->EnableInputMethod(locale_default_input_method);
590   }
591
592   // Finally, activate the first login input method.
593   const std::vector<std::string>& login_input_methods =
594       ime_manager->GetInputMethodUtil()->GetHardwareLoginInputMethodIds();
595   ime_manager->ChangeInputMethod(login_input_methods[0]);
596 }
597
598 void SetGuestLocale(UserManager* const usermanager, Profile* const profile) {
599   scoped_ptr<GuestLanguageSetCallbackData> data(
600       new GuestLanguageSetCallbackData(profile));
601   scoped_ptr<locale_util::SwitchLanguageCallback> callback(
602       new locale_util::SwitchLanguageCallback(base::Bind(
603           &GuestLanguageSetCallbackData::Callback, base::Passed(data.Pass()))));
604   User* const user = usermanager->GetUserByProfile(profile);
605   usermanager->RespectLocalePreference(profile, user, callback.Pass());
606 }
607
608 void ChromeBrowserMainPartsChromeos::PostProfileInit() {
609   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
610   // -- just after CreateProfile().
611
612   // Restarting Chrome inside existing user session. Possible cases:
613   // 1. Chrome is restarted after crash.
614   // 2. Chrome is started in browser_tests skipping the login flow
615   // 3. Chrome is started on dev machine
616   //    i.e. not on Chrome OS device w/o login flow.
617   if (parsed_command_line().HasSwitch(switches::kLoginUser) &&
618       !parsed_command_line().HasSwitch(switches::kLoginPassword)) {
619     std::string login_user = parsed_command_line().GetSwitchValueASCII(
620         chromeos::switches::kLoginUser);
621     if (!base::SysInfo::IsRunningOnChromeOS() &&
622         login_user == UserManager::kStubUser) {
623       // For dev machines and stub user emulate as if sync has been initialized.
624       profile()->GetPrefs()->SetString(prefs::kGoogleServicesUsername,
625                                        login_user);
626     }
627
628     // This is done in LoginUtils::OnProfileCreated during normal login.
629     LoginUtils::Get()->InitRlzDelayed(profile());
630
631     // Send the PROFILE_PREPARED notification and call SessionStarted()
632     // so that the Launcher and other Profile dependent classes are created.
633     content::NotificationService::current()->Notify(
634         chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
635         content::NotificationService::AllSources(),
636         content::Details<Profile>(profile()));
637     UserManager::Get()->SessionStarted();
638
639     // Now is the good time to retrieve other logged in users for this session.
640     // First user has been already marked as logged in and active in
641     // PreProfileInit(). Chrome should tread other user in a session as active
642     // in the background.
643     UserManager::Get()->RestoreActiveSessions();
644   }
645
646   // Initialize the network portal detector for Chrome OS. The network
647   // portal detector starts to listen for notifications from
648   // NetworkStateHandler and initiates captive portal detection for
649   // active networks. Shoule be called before call to
650   // OptionallyRunChromeOSLoginManager, because it depends on
651   // NetworkPortalDetector.
652   NetworkPortalDetector::Initialize();
653   {
654     NetworkPortalDetector* detector = NetworkPortalDetector::Get();
655 #if defined(GOOGLE_CHROME_BUILD)
656     bool is_official_build = true;
657 #else
658     bool is_official_build = false;
659 #endif
660     // Enable portal detector if EULA was previously accepted or if
661     // this is an unofficial build.
662     if (!is_official_build || StartupUtils::IsEulaAccepted())
663       detector->Enable(true);
664   }
665
666   // Tests should be able to tune login manager before showing it.
667   // Thus only show login manager in normal (non-testing) mode.
668   if (!parameters().ui_task ||
669       parsed_command_line().HasSwitch(switches::kForceLoginManagerInTests)) {
670     OptionallyRunChromeOSLoginManager(parsed_command_line(), profile());
671   }
672
673   // Guest user profile is never initialized with locale settings,
674   // so we need special handling for Guest session.
675   UserManager* const usermanager = UserManager::Get();
676   if (usermanager->IsLoggedInAsGuest())
677     SetGuestLocale(usermanager, profile());
678
679   // These observers must be initialized after the profile because
680   // they use the profile to dispatch extension events.
681   extension_system_event_observer_.reset(new ExtensionSystemEventObserver());
682   if (KioskModeSettings::Get()->IsKioskModeEnabled()) {
683     retail_mode_power_save_blocker_ = content::PowerSaveBlocker::Create(
684         content::PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
685         "Retail mode");
686   }
687
688   peripheral_battery_observer_.reset(new PeripheralBatteryObserver());
689
690   g_browser_process->platform_part()->InitializeAutomaticRebootManager();
691
692   // This observer cannot be created earlier because it requires the shell to be
693   // available.
694   idle_action_warning_observer_.reset(new IdleActionWarningObserver());
695
696   ChromeBrowserMainPartsLinux::PostProfileInit();
697 }
698
699 void ChromeBrowserMainPartsChromeos::PreBrowserStart() {
700   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
701   // -- just before MetricsService::LogNeedForCleanShutdown().
702
703   g_browser_process->metrics_service()->StartExternalMetrics();
704
705 #if defined(USE_X11)
706   // Listen for system key events so that the user will be able to adjust the
707   // volume on the login screen, if Chrome is running on Chrome OS
708   // (i.e. not Linux desktop), and in non-test mode.
709   // Note: SystemKeyEventListener depends on the DBus thread.
710   if (base::SysInfo::IsRunningOnChromeOS() &&
711       !parameters().ui_task) {  // ui_task is non-NULL when running tests.
712     SystemKeyEventListener::Initialize();
713   }
714
715   // Listen for XI_HierarchyChanged events. Note: if this is moved to
716   // PreMainMessageLoopRun() then desktopui_PageCyclerTests fail for unknown
717   // reasons, see http://crosbug.com/24833.
718   XInputHierarchyChangedEventListener::GetInstance();
719
720   // Start the CrOS input device UMA watcher
721   DeviceUMA::GetInstance();
722 #endif
723   keyboard_event_rewriters_.reset(new EventRewriterController());
724   keyboard_event_rewriters_->AddEventRewriter(
725       scoped_ptr<ui::EventRewriter>(new KeyboardDrivenEventRewriter()));
726   keyboard_event_rewriters_->AddEventRewriter(
727       scoped_ptr<ui::EventRewriter>(new EventRewriter()));
728
729   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
730   // -- immediately after ChildProcess::WaitForDebugger().
731
732   // Start the out-of-memory priority manager here so that we give the most
733   // amount of time for the other services to start up before we start
734   // adjusting the oom priority.
735   g_browser_process->platform_part()->oom_priority_manager()->Start();
736
737   if (ui::ShouldDefaultToNaturalScroll()) {
738     CommandLine::ForCurrentProcess()->AppendSwitch(
739         chromeos::switches::kNaturalScrollDefault);
740     system::InputDeviceSettings::Get()->SetTapToClick(true);
741   }
742
743   ChromeBrowserMainPartsLinux::PreBrowserStart();
744 }
745
746 void ChromeBrowserMainPartsChromeos::PostBrowserStart() {
747   // These are dependent on the ash::Shell singleton already having been
748   // initialized.
749   power_button_observer_.reset(new PowerButtonObserver);
750   data_promo_notification_.reset(new DataPromoNotification()),
751   keyboard_event_rewriters_->Init();
752
753   ChromeBrowserMainPartsLinux::PostBrowserStart();
754 }
755
756 // Shut down services before the browser process, etc are destroyed.
757 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopRun() {
758   BootTimesLoader::Get()->AddLogoutTimeMarker("UIMessageLoopEnded", true);
759
760   g_browser_process->platform_part()->oom_priority_manager()->Stop();
761
762   // Destroy the application name notifier for Kiosk mode.
763   KioskModeIdleAppNameNotification::Shutdown();
764
765   // Shutdown the upgrade detector for Chrome OS. The upgrade detector
766   // stops monitoring changes from the update engine.
767   if (UpgradeDetectorChromeos::GetInstance())
768     UpgradeDetectorChromeos::GetInstance()->Shutdown();
769
770   // Shutdown the network change notifier for Chrome OS. The network
771   // change notifier stops monitoring changes from the power manager and
772   // the network manager.
773   if (NetworkChangeNotifierFactoryChromeos::GetInstance())
774     NetworkChangeNotifierFactoryChromeos::GetInstance()->Shutdown();
775
776   // Destroy UI related classes before destroying services that they may
777   // depend on.
778   data_promo_notification_.reset();
779
780   // Tell DeviceSettingsService to stop talking to session_manager. Do not
781   // shutdown DeviceSettingsService yet, it might still be accessed by
782   // BrowserPolicyConnector (owned by g_browser_process).
783   DeviceSettingsService::Get()->UnsetSessionManager();
784
785   // We should remove observers attached to D-Bus clients before
786   // DBusThreadManager is shut down.
787   extension_system_event_observer_.reset();
788   retail_mode_power_save_blocker_.reset();
789   peripheral_battery_observer_.reset();
790   power_prefs_.reset();
791
792   // Let the ScreenLocker unregister itself from SessionManagerClient before
793   // DBusThreadManager is shut down.
794   if (!KioskModeSettings::Get()->IsKioskModeEnabled())
795     ScreenLocker::ShutDownClass();
796
797   keyboard_event_rewriters_.reset();
798 #if defined(USE_X11)
799   // The XInput2 event listener needs to be shut down earlier than when
800   // Singletons are finally destroyed in AtExitManager.
801   XInputHierarchyChangedEventListener::GetInstance()->Stop();
802
803   DeviceUMA::GetInstance()->Stop();
804
805   // SystemKeyEventListener::Shutdown() is always safe to call,
806   // even if Initialize() wasn't called.
807   SystemKeyEventListener::Shutdown();
808 #endif
809
810   imageburner::BurnManager::Shutdown();
811   CrasAudioHandler::Shutdown();
812
813   // Detach D-Bus clients before DBusThreadManager is shut down.
814   power_button_observer_.reset();
815   idle_action_warning_observer_.reset();
816
817   MagnificationManager::Shutdown();
818   AccessibilityManager::Shutdown();
819
820   media::SoundsManager::Shutdown();
821
822   system::StatisticsProvider::GetInstance()->Shutdown();
823
824   // Let the UserManager and WallpaperManager unregister itself as an observer
825   // of the CrosSettings singleton before it is destroyed. This also ensures
826   // that the UserManager has no URLRequest pending (see
827   // http://crbug.com/276659).
828   UserManager::Get()->Shutdown();
829   WallpaperManager::Get()->Shutdown();
830
831   // Let the AutomaticRebootManager unregister itself as an observer of several
832   // subsystems.
833   g_browser_process->platform_part()->ShutdownAutomaticRebootManager();
834
835   // Clean up dependency on CrosSettings and stop pending data fetches.
836   KioskAppManager::Shutdown();
837
838   // We first call PostMainMessageLoopRun and then destroy UserManager, because
839   // Ash needs to be closed before UserManager is destroyed.
840   ChromeBrowserMainPartsLinux::PostMainMessageLoopRun();
841
842   // Stops all in-flight OAuth2 token fetchers before the IO thread stops.
843   DeviceOAuth2TokenServiceFactory::Shutdown();
844
845   // Called after
846   // ChromeBrowserMainPartsLinux::PostMainMessageLoopRun() to be
847   // executed after execution of chrome::CloseAsh(), because some
848   // parts of WebUI depends on NetworkPortalDetector.
849   NetworkPortalDetector::Shutdown();
850
851   UserManager::Destroy();
852 }
853
854 void ChromeBrowserMainPartsChromeos::PostDestroyThreads() {
855   // Destroy DBus services immediately after threads are stopped.
856   dbus_services_.reset();
857
858   ChromeBrowserMainPartsLinux::PostDestroyThreads();
859
860   // Destroy DeviceSettingsService after g_browser_process.
861   DeviceSettingsService::Shutdown();
862 }
863
864 }  //  namespace chromeos