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