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