system_tray_delegate_chromeos.cc revision effb81e5f8246d0db0270817048dc992db66e9fb
1// Copyright 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/ui/ash/system_tray_delegate_chromeos.h"
6
7#include <algorithm>
8#include <set>
9#include <string>
10#include <vector>
11
12#include "ash/ash_switches.h"
13#include "ash/desktop_background/desktop_background_controller.h"
14#include "ash/ime/input_method_menu_item.h"
15#include "ash/ime/input_method_menu_manager.h"
16#include "ash/metrics/user_metrics_recorder.h"
17#include "ash/session_state_delegate.h"
18#include "ash/session_state_observer.h"
19#include "ash/shell.h"
20#include "ash/shell_delegate.h"
21#include "ash/shell_window_ids.h"
22#include "ash/system/bluetooth/bluetooth_observer.h"
23#include "ash/system/chromeos/session/logout_button_observer.h"
24#include "ash/system/date/clock_observer.h"
25#include "ash/system/drive/drive_observer.h"
26#include "ash/system/ime/ime_observer.h"
27#include "ash/system/tray/system_tray.h"
28#include "ash/system/tray/system_tray_delegate.h"
29#include "ash/system/tray/system_tray_notifier.h"
30#include "ash/system/tray_accessibility.h"
31#include "ash/system/user/login_status.h"
32#include "ash/system/user/update_observer.h"
33#include "ash/system/user/user_observer.h"
34#include "ash/volume_control_delegate.h"
35#include "ash/wm/lock_state_controller.h"
36#include "base/bind_helpers.h"
37#include "base/callback.h"
38#include "base/logging.h"
39#include "base/memory/weak_ptr.h"
40#include "base/prefs/pref_service.h"
41#include "base/strings/stringprintf.h"
42#include "base/strings/utf_string_conversions.h"
43#include "base/sys_info.h"
44#include "base/time/time.h"
45#include "chrome/browser/browser_process.h"
46#include "chrome/browser/chrome_notification_types.h"
47#include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
48#include "chrome/browser/chromeos/accessibility/magnification_manager.h"
49#include "chrome/browser/chromeos/bluetooth/bluetooth_pairing_dialog.h"
50#include "chrome/browser/chromeos/charger_replace/charger_replacement_dialog.h"
51#include "chrome/browser/chromeos/choose_mobile_network_dialog.h"
52#include "chrome/browser/chromeos/drive/drive_integration_service.h"
53#include "chrome/browser/chromeos/drive/job_list.h"
54#include "chrome/browser/chromeos/enrollment_dialog_view.h"
55#include "chrome/browser/chromeos/events/system_key_event_listener.h"
56#include "chrome/browser/chromeos/input_method/input_method_util.h"
57#include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.h"
58#include "chrome/browser/chromeos/login/help_app_launcher.h"
59#include "chrome/browser/chromeos/login/login_display_host.h"
60#include "chrome/browser/chromeos/login/login_display_host_impl.h"
61#include "chrome/browser/chromeos/login/login_wizard.h"
62#include "chrome/browser/chromeos/login/startup_utils.h"
63#include "chrome/browser/chromeos/login/supervised_user_manager.h"
64#include "chrome/browser/chromeos/login/user.h"
65#include "chrome/browser/chromeos/login/user_adding_screen.h"
66#include "chrome/browser/chromeos/login/user_manager.h"
67#include "chrome/browser/chromeos/net/network_portal_detector.h"
68#include "chrome/browser/chromeos/options/network_config_view.h"
69#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
70#include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h"
71#include "chrome/browser/chromeos/profiles/multiprofiles_intro_dialog.h"
72#include "chrome/browser/chromeos/settings/cros_settings.h"
73#include "chrome/browser/chromeos/sim_dialog_delegate.h"
74#include "chrome/browser/drive/drive_service_interface.h"
75#include "chrome/browser/feedback/tracing_manager.h"
76#include "chrome/browser/google/google_util.h"
77#include "chrome/browser/lifetime/application_lifetime.h"
78#include "chrome/browser/profiles/profile_manager.h"
79#include "chrome/browser/ui/ash/multi_user/multi_user_util.h"
80#include "chrome/browser/ui/ash/volume_controller_chromeos.h"
81#include "chrome/browser/ui/browser.h"
82#include "chrome/browser/ui/browser_finder.h"
83#include "chrome/browser/ui/browser_list.h"
84#include "chrome/browser/ui/chrome_pages.h"
85#include "chrome/browser/ui/host_desktop.h"
86#include "chrome/browser/ui/scoped_tabbed_browser_displayer.h"
87#include "chrome/browser/ui/singleton_tabs.h"
88#include "chrome/browser/ui/tabs/tab_strip_model.h"
89#include "chrome/browser/ui/webui/chromeos/charger_replacement_handler.h"
90#include "chrome/browser/ui/webui/chromeos/mobile_setup_dialog.h"
91#include "chrome/browser/upgrade_detector.h"
92#include "chrome/common/chrome_switches.h"
93#include "chrome/common/pref_names.h"
94#include "chrome/common/url_constants.h"
95#include "chromeos/dbus/dbus_thread_manager.h"
96#include "chromeos/dbus/session_manager_client.h"
97#include "chromeos/ime/extension_ime_util.h"
98#include "chromeos/ime/input_method_manager.h"
99#include "chromeos/ime/xkeyboard.h"
100#include "chromeos/login/login_state.h"
101#include "components/policy/core/common/cloud/cloud_policy_store.h"
102#include "content/public/browser/notification_observer.h"
103#include "content/public/browser/notification_service.h"
104#include "content/public/browser/user_metrics.h"
105#include "content/public/browser/web_contents.h"
106#include "device/bluetooth/bluetooth_adapter.h"
107#include "device/bluetooth/bluetooth_adapter_factory.h"
108#include "device/bluetooth/bluetooth_device.h"
109#include "grit/ash_strings.h"
110#include "grit/generated_resources.h"
111#include "grit/locale_settings.h"
112#include "net/base/escape.h"
113#include "third_party/cros_system_api/dbus/service_constants.h"
114#include "ui/base/l10n/l10n_util.h"
115#include "ui/base/l10n/time_format.h"
116
117using drive::DriveIntegrationService;
118using drive::DriveIntegrationServiceFactory;
119
120namespace chromeos {
121
122namespace {
123
124// The minimum session length limit that can be set.
125const int kSessionLengthLimitMinMs = 30 * 1000;  // 30 seconds.
126
127// The maximum session length limit that can be set.
128const int kSessionLengthLimitMaxMs = 24 * 60 * 60 * 1000;  // 24 hours.
129
130const char kDisplaySettingsSubPageName[] = "display";
131const char kDisplayOverscanSettingsSubPageName[] = "displayOverscan";
132
133// The URL for the Google Drive settings page.
134const char kDriveSettingsPageURL[] = "https://drive.google.com";
135
136void ExtractIMEInfo(const input_method::InputMethodDescriptor& ime,
137                    const input_method::InputMethodUtil& util,
138                    ash::IMEInfo* info) {
139  info->id = ime.id();
140  info->name = util.GetInputMethodLongName(ime);
141  info->medium_name = util.GetInputMethodMediumName(ime);
142  info->short_name = util.GetInputMethodShortName(ime);
143  info->third_party = extension_ime_util::IsExtensionIME(ime.id());
144}
145
146gfx::NativeWindow GetNativeWindowByStatus(ash::user::LoginStatus login_status,
147                                          bool session_started) {
148  int container_id =
149      (!session_started || login_status == ash::user::LOGGED_IN_NONE ||
150       login_status == ash::user::LOGGED_IN_LOCKED) ?
151          ash::internal::kShellWindowId_LockSystemModalContainer :
152          ash::internal::kShellWindowId_SystemModalContainer;
153  return ash::Shell::GetContainer(ash::Shell::GetPrimaryRootWindow(),
154                                  container_id);
155}
156
157// Converts drive::JobInfo to ash::DriveOperationStatus.
158// If the job is not of type that ash tray is interested, returns false.
159bool ConvertToDriveOperationStatus(const drive::JobInfo& info,
160                                   ash::DriveOperationStatus* status) {
161  if (info.job_type == drive::TYPE_DOWNLOAD_FILE) {
162    status->type = ash::DriveOperationStatus::OPERATION_DOWNLOAD;
163  } else if (info.job_type == drive::TYPE_UPLOAD_NEW_FILE ||
164             info.job_type == drive::TYPE_UPLOAD_EXISTING_FILE) {
165    status->type = ash::DriveOperationStatus::OPERATION_UPLOAD;
166  } else {
167    return false;
168  }
169
170  if (info.state == drive::STATE_NONE)
171    status->state = ash::DriveOperationStatus::OPERATION_NOT_STARTED;
172  else
173    status->state = ash::DriveOperationStatus::OPERATION_IN_PROGRESS;
174
175  status->id = info.job_id;
176  status->file_path = info.file_path;
177  status->progress = info.num_total_bytes == 0 ? 0.0 :
178      static_cast<double>(info.num_completed_bytes) /
179          static_cast<double>(info.num_total_bytes);
180  return true;
181}
182
183// Converts drive::JobInfo that has finished in |error| state
184// to ash::DriveOperationStatus.
185// If the job is not of type that ash tray is interested, returns false.
186bool ConvertToFinishedDriveOperationStatus(const drive::JobInfo& info,
187                                           drive::FileError error,
188                                           ash::DriveOperationStatus* status) {
189  if (!ConvertToDriveOperationStatus(info, status))
190    return false;
191  status->state = (error == drive::FILE_ERROR_OK)
192                      ? ash::DriveOperationStatus::OPERATION_COMPLETED
193                      : ash::DriveOperationStatus::OPERATION_FAILED;
194  return true;
195}
196
197// Converts a list of drive::JobInfo to a list of ash::DriveOperationStatusList.
198ash::DriveOperationStatusList ConvertToDriveStatusList(
199    const std::vector<drive::JobInfo>& list) {
200  ash::DriveOperationStatusList results;
201  for (size_t i = 0; i < list.size(); ++i) {
202    ash::DriveOperationStatus status;
203    if (ConvertToDriveOperationStatus(list[i], &status))
204      results.push_back(status);
205  }
206  return results;
207}
208
209void BluetoothPowerFailure() {
210  // TODO(sad): Show an error bubble?
211}
212
213void BluetoothSetDiscoveringError() {
214  LOG(ERROR) << "BluetoothSetDiscovering failed.";
215}
216
217void BluetoothDeviceConnectError(
218    device::BluetoothDevice::ConnectErrorCode error_code) {
219  // TODO(sad): Do something?
220}
221
222void ShowSettingsSubPageForActiveUser(const std::string& sub_page) {
223  chrome::ShowSettingsSubPageForProfile(
224      ProfileManager::GetActiveUserProfile(), sub_page);
225}
226
227void ShowNetworkSettingsPage(const std::string& service_path) {
228  std::string page = chrome::kInternetOptionsSubPage;
229  page += "?servicePath=" + net::EscapeUrlEncodedData(service_path, true);
230  content::RecordAction(base::UserMetricsAction("OpenInternetOptionsDialog"));
231  ShowSettingsSubPageForActiveUser(page);
232}
233
234void OnAcceptMultiprofilesIntro(bool no_show_again) {
235  PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs();
236  prefs->SetBoolean(prefs::kMultiProfileNeverShowIntro, no_show_again);
237  UserAddingScreen::Get()->Start();
238}
239
240}  // namespace
241
242SystemTrayDelegateChromeOS::SystemTrayDelegateChromeOS()
243    : weak_ptr_factory_(this),
244      user_profile_(NULL),
245      clock_type_(base::GetHourClockType()),
246      search_key_mapped_to_(input_method::kSearchKey),
247      screen_locked_(false),
248      have_session_start_time_(false),
249      have_session_length_limit_(false),
250      should_run_bluetooth_discovery_(false),
251      volume_control_delegate_(new VolumeController()),
252      device_settings_observer_(CrosSettings::Get()->AddSettingsObserver(
253          kSystemUse24HourClock,
254          base::Bind(&SystemTrayDelegateChromeOS::UpdateClockType,
255                     base::Unretained(this)))) {
256  // Register notifications on construction so that events such as
257  // PROFILE_CREATED do not get missed if they happen before Initialize().
258  registrar_.reset(new content::NotificationRegistrar);
259  registrar_->Add(this,
260                  chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
261                  content::NotificationService::AllSources());
262  registrar_->Add(this,
263                  chrome::NOTIFICATION_LOGIN_USER_IMAGE_CHANGED,
264                  content::NotificationService::AllSources());
265  if (GetUserLoginStatus() == ash::user::LOGGED_IN_NONE) {
266    registrar_->Add(this,
267                    chrome::NOTIFICATION_SESSION_STARTED,
268                    content::NotificationService::AllSources());
269  }
270  registrar_->Add(this,
271                  chrome::NOTIFICATION_PROFILE_CREATED,
272                  content::NotificationService::AllSources());
273  registrar_->Add(this,
274                  chrome::NOTIFICATION_PROFILE_DESTROYED,
275                  content::NotificationService::AllSources());
276
277  AccessibilityManager* accessibility_manager = AccessibilityManager::Get();
278  CHECK(accessibility_manager);
279  accessibility_subscription_ = accessibility_manager->RegisterCallback(
280      base::Bind(&SystemTrayDelegateChromeOS::OnAccessibilityStatusChanged,
281                 base::Unretained(this)));
282}
283
284void SystemTrayDelegateChromeOS::Initialize() {
285  DBusThreadManager::Get()->GetSessionManagerClient()->AddObserver(this);
286
287  input_method::InputMethodManager::Get()->AddObserver(this);
288  ash::ime::InputMethodMenuManager::GetInstance()->AddObserver(this);
289  UpdateClockType();
290
291  device::BluetoothAdapterFactory::GetAdapter(
292      base::Bind(&SystemTrayDelegateChromeOS::InitializeOnAdapterReady,
293                 weak_ptr_factory_.GetWeakPtr()));
294
295  ash::Shell::GetInstance()->session_state_delegate()->AddSessionStateObserver(
296      this);
297
298  if (LoginState::IsInitialized())
299    LoginState::Get()->AddObserver(this);
300
301  if (CrasAudioHandler::IsInitialized())
302    CrasAudioHandler::Get()->AddAudioObserver(this);
303
304  BrowserList::AddObserver(this);
305}
306
307void SystemTrayDelegateChromeOS::Shutdown() {
308  device_settings_observer_.reset();
309}
310
311void SystemTrayDelegateChromeOS::InitializeOnAdapterReady(
312    scoped_refptr<device::BluetoothAdapter> adapter) {
313  bluetooth_adapter_ = adapter;
314  CHECK(bluetooth_adapter_.get());
315  bluetooth_adapter_->AddObserver(this);
316
317  local_state_registrar_.reset(new PrefChangeRegistrar);
318  local_state_registrar_->Init(g_browser_process->local_state());
319
320  UpdateSessionStartTime();
321  UpdateSessionLengthLimit();
322
323  local_state_registrar_->Add(
324      prefs::kSessionStartTime,
325      base::Bind(&SystemTrayDelegateChromeOS::UpdateSessionStartTime,
326                 base::Unretained(this)));
327  local_state_registrar_->Add(
328      prefs::kSessionLengthLimit,
329      base::Bind(&SystemTrayDelegateChromeOS::UpdateSessionLengthLimit,
330                 base::Unretained(this)));
331
332  policy::BrowserPolicyConnectorChromeOS* policy_connector =
333      g_browser_process->platform_part()->browser_policy_connector_chromeos();
334  policy::DeviceCloudPolicyManagerChromeOS* policy_manager =
335      policy_connector->GetDeviceCloudPolicyManager();
336  if (policy_manager)
337    policy_manager->core()->store()->AddObserver(this);
338  UpdateEnterpriseDomain();
339}
340
341SystemTrayDelegateChromeOS::~SystemTrayDelegateChromeOS() {
342  // Unregister PrefChangeRegistrars.
343  local_state_registrar_.reset();
344  user_pref_registrar_.reset();
345
346  // Unregister content notifications before destroying any components.
347  registrar_.reset();
348
349  // Unregister a11y status subscription.
350  accessibility_subscription_.reset();
351
352  DBusThreadManager::Get()->GetSessionManagerClient()->RemoveObserver(this);
353  input_method::InputMethodManager::Get()->RemoveObserver(this);
354  ash::ime::InputMethodMenuManager::GetInstance()->RemoveObserver(this);
355  bluetooth_adapter_->RemoveObserver(this);
356  ash::Shell::GetInstance()
357      ->session_state_delegate()
358      ->RemoveSessionStateObserver(this);
359  LoginState::Get()->RemoveObserver(this);
360
361  if (CrasAudioHandler::IsInitialized())
362    CrasAudioHandler::Get()->RemoveAudioObserver(this);
363
364  BrowserList::RemoveObserver(this);
365  StopObservingAppWindowRegistry();
366
367  // Stop observing Drive operations.
368  UnobserveDriveUpdates();
369
370  policy::BrowserPolicyConnectorChromeOS* connector =
371      g_browser_process->platform_part()->browser_policy_connector_chromeos();
372  policy::DeviceCloudPolicyManagerChromeOS* policy_manager =
373      connector->GetDeviceCloudPolicyManager();
374  if (policy_manager)
375    policy_manager->core()->store()->RemoveObserver(this);
376}
377
378// Overridden from ash::SystemTrayDelegate:
379bool SystemTrayDelegateChromeOS::GetTrayVisibilityOnStartup() {
380  // In case of OOBE / sign in screen tray will be shown later.
381  return LoginState::Get()->IsUserLoggedIn();
382}
383
384ash::user::LoginStatus SystemTrayDelegateChromeOS::GetUserLoginStatus() const {
385  // All non-logged in ChromeOS specific LOGGED_IN states map to the same
386  // Ash specific LOGGED_IN state.
387  if (!LoginState::Get()->IsUserLoggedIn())
388    return ash::user::LOGGED_IN_NONE;
389
390  if (screen_locked_)
391    return ash::user::LOGGED_IN_LOCKED;
392
393  LoginState::LoggedInUserType user_type =
394      LoginState::Get()->GetLoggedInUserType();
395  switch (user_type) {
396    case LoginState::LOGGED_IN_USER_NONE:
397      return ash::user::LOGGED_IN_NONE;
398    case LoginState::LOGGED_IN_USER_REGULAR:
399      return ash::user::LOGGED_IN_USER;
400    case LoginState::LOGGED_IN_USER_OWNER:
401      return ash::user::LOGGED_IN_OWNER;
402    case LoginState::LOGGED_IN_USER_GUEST:
403      return ash::user::LOGGED_IN_GUEST;
404    case LoginState::LOGGED_IN_USER_RETAIL_MODE:
405      return ash::user::LOGGED_IN_RETAIL_MODE;
406    case LoginState::LOGGED_IN_USER_PUBLIC_ACCOUNT:
407      return ash::user::LOGGED_IN_PUBLIC;
408    case LoginState::LOGGED_IN_USER_LOCALLY_MANAGED:
409      return ash::user::LOGGED_IN_LOCALLY_MANAGED;
410    case LoginState::LOGGED_IN_USER_KIOSK_APP:
411      return ash::user::LOGGED_IN_KIOSK_APP;
412  }
413  NOTREACHED();
414  return ash::user::LOGGED_IN_NONE;
415}
416
417bool SystemTrayDelegateChromeOS::IsOobeCompleted() const {
418  if (!base::SysInfo::IsRunningOnChromeOS() &&
419      LoginState::Get()->IsUserLoggedIn())
420    return true;
421  return StartupUtils::IsOobeCompleted();
422}
423
424void SystemTrayDelegateChromeOS::ChangeProfilePicture() {
425  content::RecordAction(
426      base::UserMetricsAction("OpenChangeProfilePictureDialog"));
427  ShowSettingsSubPageForActiveUser(chrome::kChangeProfilePictureSubPage);
428}
429
430const std::string SystemTrayDelegateChromeOS::GetEnterpriseDomain() const {
431  return enterprise_domain_;
432}
433
434const base::string16 SystemTrayDelegateChromeOS::GetEnterpriseMessage() const {
435  if (GetEnterpriseDomain().empty())
436    return base::string16();
437  return l10n_util::GetStringFUTF16(IDS_DEVICE_OWNED_BY_NOTICE,
438                                    base::UTF8ToUTF16(GetEnterpriseDomain()));
439}
440
441const std::string SystemTrayDelegateChromeOS::GetLocallyManagedUserManager()
442    const {
443  if (GetUserLoginStatus() != ash::user::LOGGED_IN_LOCALLY_MANAGED)
444    return std::string();
445  return UserManager::Get()->GetSupervisedUserManager()->GetManagerDisplayEmail(
446      chromeos::UserManager::Get()->GetActiveUser()->email());
447}
448
449const base::string16
450SystemTrayDelegateChromeOS::GetLocallyManagedUserManagerName() const {
451  if (GetUserLoginStatus() != ash::user::LOGGED_IN_LOCALLY_MANAGED)
452    return base::string16();
453  return UserManager::Get()->GetSupervisedUserManager()->GetManagerDisplayName(
454      chromeos::UserManager::Get()->GetActiveUser()->email());
455}
456
457const base::string16 SystemTrayDelegateChromeOS::GetLocallyManagedUserMessage()
458    const {
459  if (GetUserLoginStatus() != ash::user::LOGGED_IN_LOCALLY_MANAGED)
460    return base::string16();
461  return l10n_util::GetStringFUTF16(
462      IDS_USER_IS_LOCALLY_MANAGED_BY_NOTICE,
463      base::UTF8ToUTF16(GetLocallyManagedUserManager()));
464}
465
466bool SystemTrayDelegateChromeOS::SystemShouldUpgrade() const {
467  return UpgradeDetector::GetInstance()->notify_upgrade();
468}
469
470base::HourClockType SystemTrayDelegateChromeOS::GetHourClockType() const {
471  return clock_type_;
472}
473
474void SystemTrayDelegateChromeOS::ShowSettings() {
475  ShowSettingsSubPageForActiveUser("");
476}
477
478bool SystemTrayDelegateChromeOS::ShouldShowSettings() {
479  return UserManager::Get()->GetCurrentUserFlow()->ShouldShowSettings();
480}
481
482void SystemTrayDelegateChromeOS::ShowDateSettings() {
483  content::RecordAction(base::UserMetricsAction("ShowDateOptions"));
484  std::string sub_page =
485      std::string(chrome::kSearchSubPage) + "#" +
486      l10n_util::GetStringUTF8(IDS_OPTIONS_SETTINGS_SECTION_TITLE_DATETIME);
487  // Everybody can change the time zone (even though it is a device setting).
488  ShowSettingsSubPageForActiveUser(sub_page);
489}
490
491void SystemTrayDelegateChromeOS::ShowNetworkSettings(
492    const std::string& service_path) {
493  if (!LoginState::Get()->IsUserLoggedIn())
494    return;
495  ShowNetworkSettingsPage(service_path);
496}
497
498void SystemTrayDelegateChromeOS::ShowBluetoothSettings() {
499  // TODO(sad): Make this work.
500}
501
502void SystemTrayDelegateChromeOS::ShowDisplaySettings() {
503  content::RecordAction(base::UserMetricsAction("ShowDisplayOptions"));
504  ShowSettingsSubPageForActiveUser(kDisplaySettingsSubPageName);
505}
506
507void SystemTrayDelegateChromeOS::ShowChromeSlow() {
508  chrome::ScopedTabbedBrowserDisplayer displayer(
509      ProfileManager::GetPrimaryUserProfile(), chrome::HOST_DESKTOP_TYPE_ASH);
510  chrome::ShowSlow(displayer.browser());
511}
512
513bool SystemTrayDelegateChromeOS::ShouldShowDisplayNotification() {
514  // Packaged app is not counted as 'last active', so if a browser opening the
515  // display settings is in background of a packaged app, it will return true.
516  // TODO(mukai): fix this.
517  Browser* active_browser =
518      chrome::FindLastActiveWithHostDesktopType(chrome::HOST_DESKTOP_TYPE_ASH);
519  if (!active_browser)
520    return true;
521
522  content::WebContents* active_contents =
523      active_browser->tab_strip_model()->GetActiveWebContents();
524  if (!active_contents)
525    return true;
526
527  GURL visible_url = active_contents->GetLastCommittedURL();
528  GURL display_settings_url =
529      chrome::GetSettingsUrl(kDisplaySettingsSubPageName);
530  GURL display_overscan_url =
531      chrome::GetSettingsUrl(kDisplayOverscanSettingsSubPageName);
532  return (visible_url != display_settings_url &&
533          visible_url != display_overscan_url);
534}
535
536void SystemTrayDelegateChromeOS::ShowDriveSettings() {
537  // TODO(tengs): Open the drive-specific settings page once we put it in.
538  // For now just show Google Drive main page.
539  chrome::ScopedTabbedBrowserDisplayer displayer(
540      ProfileManager::GetActiveUserProfile(), chrome::HOST_DESKTOP_TYPE_ASH);
541  chrome::ShowSingletonTabOverwritingNTP(
542      displayer.browser(),
543      chrome::GetSingletonTabNavigateParams(displayer.browser(),
544                                            GURL(kDriveSettingsPageURL)));
545}
546
547void SystemTrayDelegateChromeOS::ShowIMESettings() {
548  content::RecordAction(base::UserMetricsAction("OpenLanguageOptionsDialog"));
549  ShowSettingsSubPageForActiveUser(chrome::kLanguageOptionsSubPage);
550}
551
552void SystemTrayDelegateChromeOS::ShowHelp() {
553  chrome::ShowHelpForProfile(ProfileManager::GetActiveUserProfile(),
554                             chrome::HOST_DESKTOP_TYPE_ASH,
555                             chrome::HELP_SOURCE_MENU);
556}
557
558void SystemTrayDelegateChromeOS::ShowAccessibilityHelp() {
559  chrome::ScopedTabbedBrowserDisplayer displayer(
560      ProfileManager::GetActiveUserProfile(), chrome::HOST_DESKTOP_TYPE_ASH);
561  accessibility::ShowAccessibilityHelp(displayer.browser());
562}
563
564void SystemTrayDelegateChromeOS::ShowAccessibilitySettings() {
565  content::RecordAction(base::UserMetricsAction("ShowAccessibilitySettings"));
566  std::string sub_page = std::string(chrome::kSearchSubPage) + "#" +
567                         l10n_util::GetStringUTF8(
568                             IDS_OPTIONS_SETTINGS_SECTION_TITLE_ACCESSIBILITY);
569  ShowSettingsSubPageForActiveUser(sub_page);
570}
571
572void SystemTrayDelegateChromeOS::ShowPublicAccountInfo() {
573  chrome::ScopedTabbedBrowserDisplayer displayer(
574      ProfileManager::GetActiveUserProfile(), chrome::HOST_DESKTOP_TYPE_ASH);
575  chrome::ShowPolicy(displayer.browser());
576}
577
578void SystemTrayDelegateChromeOS::ShowLocallyManagedUserInfo() {
579  // TODO(antrim): find out what should we show in this case.
580  // http://crbug.com/229762
581}
582
583void SystemTrayDelegateChromeOS::ShowEnterpriseInfo() {
584  ash::user::LoginStatus status = GetUserLoginStatus();
585  if (status == ash::user::LOGGED_IN_NONE ||
586      status == ash::user::LOGGED_IN_LOCKED) {
587    scoped_refptr<chromeos::HelpAppLauncher> help_app(
588        new chromeos::HelpAppLauncher(GetNativeWindow()));
589    help_app->ShowHelpTopic(chromeos::HelpAppLauncher::HELP_ENTERPRISE);
590  } else {
591    GURL url(google_util::StringAppendGoogleLocaleParam(
592        chrome::kLearnMoreEnterpriseURL));
593    chrome::ScopedTabbedBrowserDisplayer displayer(
594        ProfileManager::GetActiveUserProfile(), chrome::HOST_DESKTOP_TYPE_ASH);
595    chrome::ShowSingletonTab(displayer.browser(), url);
596  }
597}
598
599void SystemTrayDelegateChromeOS::ShowUserLogin() {
600  ash::Shell* shell = ash::Shell::GetInstance();
601  if (!shell->delegate()->IsMultiProfilesEnabled())
602    return;
603
604  // Only regular users could add other users to current session.
605  if (UserManager::Get()->GetActiveUser()->GetType() !=
606      User::USER_TYPE_REGULAR) {
607    return;
608  }
609
610  if (static_cast<int>(UserManager::Get()->GetLoggedInUsers().size()) >=
611      shell->session_state_delegate()->GetMaximumNumberOfLoggedInUsers())
612    return;
613
614  // Launch sign in screen to add another user to current session.
615  if (UserManager::Get()->GetUsersAdmittedForMultiProfile().size()) {
616    // Don't show dialog if any logged in user in multi-profiles session
617    // dismissed it.
618    bool show_intro = true;
619    const UserList logged_in_users = UserManager::Get()->GetLoggedInUsers();
620    for (UserList::const_iterator it = logged_in_users.begin();
621         it != logged_in_users.end();
622         ++it) {
623      show_intro &= !multi_user_util::GetProfileFromUserID(
624                         multi_user_util::GetUserIDFromEmail((*it)->email()))
625                         ->GetPrefs()
626                         ->GetBoolean(prefs::kMultiProfileNeverShowIntro);
627      if (!show_intro)
628        break;
629    }
630    if (show_intro) {
631      base::Callback<void(bool)> on_accept =
632          base::Bind(&OnAcceptMultiprofilesIntro);
633      ShowMultiprofilesIntroDialog(on_accept);
634    } else {
635      UserAddingScreen::Get()->Start();
636    }
637  }
638}
639
640bool SystemTrayDelegateChromeOS::ShowSpringChargerReplacementDialog() {
641  if (!ChargerReplacementDialog::ShouldShowDialog())
642    return false;
643
644  ChargerReplacementDialog* dialog =
645      new ChargerReplacementDialog(GetNativeWindow());
646  dialog->Show();
647  return true;
648}
649
650bool SystemTrayDelegateChromeOS::IsSpringChargerReplacementDialogVisible() {
651  return ChargerReplacementDialog::IsDialogVisible();
652}
653
654bool SystemTrayDelegateChromeOS::HasUserConfirmedSafeSpringCharger() {
655  return ChargerReplacementHandler::GetChargerStatusPref() ==
656         ChargerReplacementHandler::CONFIRM_SAFE_CHARGER;
657}
658
659void SystemTrayDelegateChromeOS::ShutDown() {
660  ash::Shell::GetInstance()->lock_state_controller()->RequestShutdown();
661}
662
663void SystemTrayDelegateChromeOS::SignOut() {
664  chrome::AttemptUserExit();
665}
666
667void SystemTrayDelegateChromeOS::RequestLockScreen() {
668  // TODO(antrim) : additional logging for crbug/173178
669  LOG(WARNING) << "Requesting screen lock from AshSystemTrayDelegate";
670  DBusThreadManager::Get()->GetSessionManagerClient()->RequestLockScreen();
671}
672
673void SystemTrayDelegateChromeOS::RequestRestartForUpdate() {
674  // We expect that UpdateEngine is in "Reboot for update" state now.
675  chrome::NotifyAndTerminate(true /* fast path */);
676}
677
678void SystemTrayDelegateChromeOS::GetAvailableBluetoothDevices(
679    ash::BluetoothDeviceList* list) {
680  device::BluetoothAdapter::DeviceList devices =
681      bluetooth_adapter_->GetDevices();
682  for (size_t i = 0; i < devices.size(); ++i) {
683    device::BluetoothDevice* device = devices[i];
684    ash::BluetoothDeviceInfo info;
685    info.address = device->GetAddress();
686    info.display_name = device->GetName();
687    info.connected = device->IsConnected();
688    info.connecting = device->IsConnecting();
689    info.paired = device->IsPaired();
690    list->push_back(info);
691  }
692}
693
694void SystemTrayDelegateChromeOS::BluetoothStartDiscovering() {
695  if (bluetooth_discovery_session_.get() &&
696      bluetooth_discovery_session_->IsActive()) {
697    LOG(WARNING) << "Already have active Bluetooth device discovery session.";
698    return;
699  }
700  VLOG(1) << "Requesting new Bluetooth device discovery session.";
701  should_run_bluetooth_discovery_ = true;
702  bluetooth_adapter_->StartDiscoverySession(
703      base::Bind(&SystemTrayDelegateChromeOS::OnStartBluetoothDiscoverySession,
704                 weak_ptr_factory_.GetWeakPtr()),
705      base::Bind(&BluetoothSetDiscoveringError));
706}
707
708void SystemTrayDelegateChromeOS::BluetoothStopDiscovering() {
709  should_run_bluetooth_discovery_ = false;
710  if (!bluetooth_discovery_session_.get() ||
711      !bluetooth_discovery_session_->IsActive()) {
712    LOG(WARNING) << "No active Bluetooth device discovery session.";
713    return;
714  }
715  VLOG(1) << "Stopping Bluetooth device discovery session.";
716  bluetooth_discovery_session_->Stop(
717      base::Bind(&base::DoNothing), base::Bind(&BluetoothSetDiscoveringError));
718}
719
720void SystemTrayDelegateChromeOS::ConnectToBluetoothDevice(
721    const std::string& address) {
722  device::BluetoothDevice* device = bluetooth_adapter_->GetDevice(address);
723  if (!device || device->IsConnecting() ||
724      (device->IsConnected() && device->IsPaired())) {
725    return;
726  }
727  if (device->IsPaired() && !device->IsConnectable())
728    return;
729  if (device->IsPaired() || !device->IsPairable()) {
730    ash::Shell::GetInstance()->metrics()->RecordUserMetricsAction(
731        ash::UMA_STATUS_AREA_BLUETOOTH_CONNECT_KNOWN_DEVICE);
732    device->Connect(NULL,
733                    base::Bind(&base::DoNothing),
734                    base::Bind(&BluetoothDeviceConnectError));
735  } else {  // Show paring dialog for the unpaired device.
736    ash::Shell::GetInstance()->metrics()->RecordUserMetricsAction(
737        ash::UMA_STATUS_AREA_BLUETOOTH_CONNECT_UNKNOWN_DEVICE);
738    BluetoothPairingDialog* dialog =
739        new BluetoothPairingDialog(GetNativeWindow(), device);
740    // The dialog deletes itself on close.
741    dialog->Show();
742  }
743}
744
745bool SystemTrayDelegateChromeOS::IsBluetoothDiscovering() {
746  return bluetooth_adapter_->IsDiscovering();
747}
748
749void SystemTrayDelegateChromeOS::GetCurrentIME(ash::IMEInfo* info) {
750  input_method::InputMethodManager* manager =
751      input_method::InputMethodManager::Get();
752  input_method::InputMethodUtil* util = manager->GetInputMethodUtil();
753  input_method::InputMethodDescriptor ime = manager->GetCurrentInputMethod();
754  ExtractIMEInfo(ime, *util, info);
755  info->selected = true;
756}
757
758void SystemTrayDelegateChromeOS::GetAvailableIMEList(ash::IMEInfoList* list) {
759  input_method::InputMethodManager* manager =
760      input_method::InputMethodManager::Get();
761  input_method::InputMethodUtil* util = manager->GetInputMethodUtil();
762  scoped_ptr<input_method::InputMethodDescriptors> ime_descriptors(
763      manager->GetActiveInputMethods());
764  std::string current = manager->GetCurrentInputMethod().id();
765  for (size_t i = 0; i < ime_descriptors->size(); i++) {
766    input_method::InputMethodDescriptor& ime = ime_descriptors->at(i);
767    ash::IMEInfo info;
768    ExtractIMEInfo(ime, *util, &info);
769    info.selected = ime.id() == current;
770    list->push_back(info);
771  }
772}
773
774void SystemTrayDelegateChromeOS::GetCurrentIMEProperties(
775    ash::IMEPropertyInfoList* list) {
776  ash::ime::InputMethodMenuItemList menu_list =
777      ash::ime::InputMethodMenuManager::GetInstance()->
778      GetCurrentInputMethodMenuItemList();
779  for (size_t i = 0; i < menu_list.size(); ++i) {
780    ash::IMEPropertyInfo property;
781    property.key = menu_list[i].key;
782    property.name = base::UTF8ToUTF16(menu_list[i].label);
783    property.selected = menu_list[i].is_selection_item_checked;
784    list->push_back(property);
785  }
786}
787
788void SystemTrayDelegateChromeOS::SwitchIME(const std::string& ime_id) {
789  input_method::InputMethodManager::Get()->ChangeInputMethod(ime_id);
790}
791
792void SystemTrayDelegateChromeOS::ActivateIMEProperty(const std::string& key) {
793  input_method::InputMethodManager::Get()->ActivateInputMethodMenuItem(key);
794}
795
796void SystemTrayDelegateChromeOS::CancelDriveOperation(int32 operation_id) {
797  DriveIntegrationService* integration_service = FindDriveIntegrationService();
798  if (!integration_service)
799    return;
800
801  integration_service->job_list()->CancelJob(operation_id);
802}
803
804void SystemTrayDelegateChromeOS::GetDriveOperationStatusList(
805    ash::DriveOperationStatusList* list) {
806  DriveIntegrationService* integration_service = FindDriveIntegrationService();
807  if (!integration_service)
808    return;
809
810  *list = ConvertToDriveStatusList(
811      integration_service->job_list()->GetJobInfoList());
812}
813
814void SystemTrayDelegateChromeOS::ShowNetworkConfigure(
815    const std::string& network_id,
816    gfx::NativeWindow parent_window) {
817  NetworkConfigView::Show(network_id, parent_window);
818}
819
820bool SystemTrayDelegateChromeOS::EnrollNetwork(
821    const std::string& network_id,
822    gfx::NativeWindow parent_window) {
823  return enrollment::CreateDialog(network_id, parent_window);
824}
825
826void SystemTrayDelegateChromeOS::ManageBluetoothDevices() {
827  content::RecordAction(base::UserMetricsAction("ShowBluetoothSettingsPage"));
828  std::string sub_page =
829      std::string(chrome::kSearchSubPage) + "#" +
830      l10n_util::GetStringUTF8(IDS_OPTIONS_SETTINGS_SECTION_TITLE_BLUETOOTH);
831  ShowSettingsSubPageForActiveUser(sub_page);
832}
833
834void SystemTrayDelegateChromeOS::ToggleBluetooth() {
835  bluetooth_adapter_->SetPowered(!bluetooth_adapter_->IsPowered(),
836                                 base::Bind(&base::DoNothing),
837                                 base::Bind(&BluetoothPowerFailure));
838}
839
840void SystemTrayDelegateChromeOS::ShowMobileSimDialog() {
841  SimDialogDelegate::ShowDialog(GetNativeWindow(),
842                                SimDialogDelegate::SIM_DIALOG_UNLOCK);
843}
844
845void SystemTrayDelegateChromeOS::ShowMobileSetupDialog(
846    const std::string& service_path) {
847  MobileSetupDialog::Show(service_path);
848}
849
850void SystemTrayDelegateChromeOS::ShowOtherNetworkDialog(
851    const std::string& type) {
852  if (type == shill::kTypeCellular) {
853    ChooseMobileNetworkDialog::ShowDialog(GetNativeWindow());
854    return;
855  }
856  NetworkConfigView::ShowForType(type, GetNativeWindow());
857}
858
859bool SystemTrayDelegateChromeOS::GetBluetoothAvailable() {
860  return bluetooth_adapter_->IsPresent();
861}
862
863bool SystemTrayDelegateChromeOS::GetBluetoothEnabled() {
864  return bluetooth_adapter_->IsPowered();
865}
866
867void SystemTrayDelegateChromeOS::ChangeProxySettings() {
868  CHECK(GetUserLoginStatus() == ash::user::LOGGED_IN_NONE);
869  LoginDisplayHostImpl::default_host()->OpenProxySettings();
870}
871
872ash::VolumeControlDelegate*
873SystemTrayDelegateChromeOS::GetVolumeControlDelegate() const {
874  return volume_control_delegate_.get();
875}
876
877void SystemTrayDelegateChromeOS::SetVolumeControlDelegate(
878    scoped_ptr<ash::VolumeControlDelegate> delegate) {
879  volume_control_delegate_.swap(delegate);
880}
881
882bool SystemTrayDelegateChromeOS::GetSessionStartTime(
883    base::TimeTicks* session_start_time) {
884  *session_start_time = session_start_time_;
885  return have_session_start_time_;
886}
887
888bool SystemTrayDelegateChromeOS::GetSessionLengthLimit(
889    base::TimeDelta* session_length_limit) {
890  *session_length_limit = session_length_limit_;
891  return have_session_length_limit_;
892}
893
894int SystemTrayDelegateChromeOS::GetSystemTrayMenuWidth() {
895  return l10n_util::GetLocalizedContentsWidthInPixels(
896      IDS_SYSTEM_TRAY_MENU_BUBBLE_WIDTH_PIXELS);
897}
898
899void SystemTrayDelegateChromeOS::ActiveUserWasChanged() {
900  GetSystemTrayNotifier()->NotifyUserUpdate();
901}
902
903bool SystemTrayDelegateChromeOS::IsNetworkBehindCaptivePortal(
904    const std::string& service_path) const {
905  NetworkPortalDetector::CaptivePortalState state =
906      NetworkPortalDetector::Get()->GetCaptivePortalState(service_path);
907  return state.status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_PORTAL;
908}
909
910bool SystemTrayDelegateChromeOS::IsSearchKeyMappedToCapsLock() {
911  return search_key_mapped_to_ == input_method::kCapsLockKey;
912}
913
914ash::SystemTray* SystemTrayDelegateChromeOS::GetPrimarySystemTray() {
915  return ash::Shell::GetInstance()->GetPrimarySystemTray();
916}
917
918ash::SystemTrayNotifier* SystemTrayDelegateChromeOS::GetSystemTrayNotifier() {
919  return ash::Shell::GetInstance()->system_tray_notifier();
920}
921
922void SystemTrayDelegateChromeOS::SetProfile(Profile* profile) {
923  // Stop observing the Drive integration status and the AppWindowRegistry of
924  // the current |user_profile_|.
925  UnobserveDriveUpdates();
926  StopObservingAppWindowRegistry();
927
928  user_profile_ = profile;
929
930  // Start observing the Drive integration status and the AppWindowRegistry of
931  // the newly set |user_profile_|.
932  ObserveDriveUpdates();
933  apps::AppWindowRegistry::Get(user_profile_)->AddObserver(this);
934
935  PrefService* prefs = profile->GetPrefs();
936  user_pref_registrar_.reset(new PrefChangeRegistrar);
937  user_pref_registrar_->Init(prefs);
938  user_pref_registrar_->Add(
939      prefs::kUse24HourClock,
940      base::Bind(&SystemTrayDelegateChromeOS::UpdateClockType,
941                 base::Unretained(this)));
942  user_pref_registrar_->Add(
943      prefs::kLanguageRemapSearchKeyTo,
944      base::Bind(&SystemTrayDelegateChromeOS::OnLanguageRemapSearchKeyToChanged,
945                 base::Unretained(this)));
946  user_pref_registrar_->Add(
947      prefs::kShowLogoutButtonInTray,
948      base::Bind(&SystemTrayDelegateChromeOS::UpdateShowLogoutButtonInTray,
949                 base::Unretained(this)));
950  user_pref_registrar_->Add(
951      prefs::kLogoutDialogDurationMs,
952      base::Bind(&SystemTrayDelegateChromeOS::UpdateLogoutDialogDuration,
953                 base::Unretained(this)));
954  user_pref_registrar_->Add(
955      prefs::kLargeCursorEnabled,
956      base::Bind(&SystemTrayDelegateChromeOS::OnAccessibilityModeChanged,
957                 base::Unretained(this),
958                 ash::A11Y_NOTIFICATION_NONE));
959  user_pref_registrar_->Add(
960      prefs::kAutoclickEnabled,
961      base::Bind(&SystemTrayDelegateChromeOS::OnAccessibilityModeChanged,
962                 base::Unretained(this),
963                 ash::A11Y_NOTIFICATION_NONE));
964  user_pref_registrar_->Add(
965      prefs::kShouldAlwaysShowAccessibilityMenu,
966      base::Bind(&SystemTrayDelegateChromeOS::OnAccessibilityModeChanged,
967                 base::Unretained(this),
968                 ash::A11Y_NOTIFICATION_NONE));
969  user_pref_registrar_->Add(
970      prefs::kPerformanceTracingEnabled,
971      base::Bind(&SystemTrayDelegateChromeOS::UpdatePerformanceTracing,
972                 base::Unretained(this)));
973
974  UpdateClockType();
975  UpdateShowLogoutButtonInTray();
976  UpdateLogoutDialogDuration();
977  UpdatePerformanceTracing();
978  search_key_mapped_to_ =
979      profile->GetPrefs()->GetInteger(prefs::kLanguageRemapSearchKeyTo);
980}
981
982bool SystemTrayDelegateChromeOS::UnsetProfile(Profile* profile) {
983  if (profile != user_profile_)
984    return false;
985  user_pref_registrar_.reset();
986  user_profile_ = NULL;
987  return true;
988}
989
990void SystemTrayDelegateChromeOS::ObserveDriveUpdates() {
991  DriveIntegrationService* integration_service = FindDriveIntegrationService();
992  if (integration_service)
993    integration_service->job_list()->AddObserver(this);
994}
995
996void SystemTrayDelegateChromeOS::UnobserveDriveUpdates() {
997  DriveIntegrationService* integration_service = FindDriveIntegrationService();
998  if (integration_service)
999    integration_service->job_list()->RemoveObserver(this);
1000}
1001
1002bool SystemTrayDelegateChromeOS::GetShouldUse24HourClockForTesting() const {
1003  return ShouldUse24HourClock();
1004}
1005
1006bool SystemTrayDelegateChromeOS::ShouldUse24HourClock() const {
1007  // On login screen and in guest mode owner default is used for
1008  // kUse24HourClock preference.
1009  const ash::user::LoginStatus status = GetUserLoginStatus();
1010  const CrosSettings* const cros_settings = CrosSettings::Get();
1011  bool system_use_24_hour_clock = true;
1012  const bool system_value_found = cros_settings->GetBoolean(
1013      kSystemUse24HourClock, &system_use_24_hour_clock);
1014
1015  if ((status == ash::user::LOGGED_IN_NONE) || !user_pref_registrar_)
1016    return (system_value_found
1017                ? system_use_24_hour_clock
1018                : (base::GetHourClockType() == base::k24HourClock));
1019
1020  const PrefService::Preference* user_pref =
1021      user_pref_registrar_->prefs()->FindPreference(prefs::kUse24HourClock);
1022  if (status == ash::user::LOGGED_IN_GUEST && user_pref->IsDefaultValue())
1023    return (system_value_found
1024                ? system_use_24_hour_clock
1025                : (base::GetHourClockType() == base::k24HourClock));
1026
1027  bool use_24_hour_clock = true;
1028  user_pref->GetValue()->GetAsBoolean(&use_24_hour_clock);
1029  return use_24_hour_clock;
1030}
1031
1032void SystemTrayDelegateChromeOS::UpdateClockType() {
1033  const bool use_24_hour_clock = ShouldUse24HourClock();
1034  clock_type_ = use_24_hour_clock ? base::k24HourClock : base::k12HourClock;
1035  GetSystemTrayNotifier()->NotifyDateFormatChanged();
1036  // This also works for enterprise-managed devices because they never have
1037  // local owner.
1038  if (chromeos::UserManager::Get()->IsCurrentUserOwner())
1039    CrosSettings::Get()->SetBoolean(kSystemUse24HourClock, use_24_hour_clock);
1040}
1041
1042void SystemTrayDelegateChromeOS::UpdateShowLogoutButtonInTray() {
1043  GetSystemTrayNotifier()->NotifyShowLoginButtonChanged(
1044      user_pref_registrar_->prefs()->GetBoolean(
1045          prefs::kShowLogoutButtonInTray));
1046}
1047
1048void SystemTrayDelegateChromeOS::UpdateLogoutDialogDuration() {
1049  const int duration_ms =
1050      user_pref_registrar_->prefs()->GetInteger(prefs::kLogoutDialogDurationMs);
1051  GetSystemTrayNotifier()->NotifyLogoutDialogDurationChanged(
1052      base::TimeDelta::FromMilliseconds(duration_ms));
1053}
1054
1055void SystemTrayDelegateChromeOS::UpdateSessionStartTime() {
1056  const PrefService* local_state = local_state_registrar_->prefs();
1057  if (local_state->HasPrefPath(prefs::kSessionStartTime)) {
1058    have_session_start_time_ = true;
1059    session_start_time_ = base::TimeTicks::FromInternalValue(
1060        local_state->GetInt64(prefs::kSessionStartTime));
1061  } else {
1062    have_session_start_time_ = false;
1063    session_start_time_ = base::TimeTicks();
1064  }
1065  GetSystemTrayNotifier()->NotifySessionStartTimeChanged();
1066}
1067
1068void SystemTrayDelegateChromeOS::UpdateSessionLengthLimit() {
1069  const PrefService* local_state = local_state_registrar_->prefs();
1070  if (local_state->HasPrefPath(prefs::kSessionLengthLimit)) {
1071    have_session_length_limit_ = true;
1072    session_length_limit_ = base::TimeDelta::FromMilliseconds(
1073        std::min(std::max(local_state->GetInteger(prefs::kSessionLengthLimit),
1074                          kSessionLengthLimitMinMs),
1075                 kSessionLengthLimitMaxMs));
1076  } else {
1077    have_session_length_limit_ = false;
1078    session_length_limit_ = base::TimeDelta();
1079  }
1080  GetSystemTrayNotifier()->NotifySessionLengthLimitChanged();
1081}
1082
1083void SystemTrayDelegateChromeOS::StopObservingAppWindowRegistry() {
1084  if (!user_profile_)
1085    return;
1086
1087  apps::AppWindowRegistry* registry =
1088      apps::AppWindowRegistry::Factory::GetForBrowserContext(user_profile_,
1089                                                             false);
1090  if (registry)
1091    registry->RemoveObserver(this);
1092}
1093
1094void SystemTrayDelegateChromeOS::NotifyIfLastWindowClosed() {
1095  if (!user_profile_)
1096    return;
1097
1098  BrowserList* browser_list =
1099      BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_ASH);
1100  for (BrowserList::const_iterator it = browser_list->begin();
1101       it != browser_list->end();
1102       ++it) {
1103    if ((*it)->profile()->IsSameProfile(user_profile_)) {
1104      // The current user has at least one open browser window.
1105      return;
1106    }
1107  }
1108
1109  if (!apps::AppWindowRegistry::Get(user_profile_)->app_windows().empty()) {
1110    // The current user has at least one open app window.
1111    return;
1112  }
1113
1114  GetSystemTrayNotifier()->NotifyLastWindowClosed();
1115}
1116
1117// LoginState::Observer overrides.
1118void SystemTrayDelegateChromeOS::LoggedInStateChanged() {
1119  // It apparently sometimes takes a while after login before the current user
1120  // is recognized as the owner. Make sure that the system-wide clock setting
1121  // is updated when the recognition eventually happens
1122  // (http://crbug.com/278601).
1123  //
1124  // Note that it isn't safe to blindly call UpdateClockType() from this
1125  // method, as LoggedInStateChanged() is also called before the logged-in
1126  // user's profile has actually been loaded (http://crbug.com/317745). The
1127  // system tray's time format is updated at login via SetProfile().
1128  if (chromeos::UserManager::Get()->IsCurrentUserOwner()) {
1129    CrosSettings::Get()->SetBoolean(kSystemUse24HourClock,
1130                                    ShouldUse24HourClock());
1131  }
1132}
1133
1134// Overridden from SessionManagerClient::Observer.
1135void SystemTrayDelegateChromeOS::ScreenIsLocked() {
1136  screen_locked_ = true;
1137  ash::Shell::GetInstance()->UpdateAfterLoginStatusChange(GetUserLoginStatus());
1138}
1139
1140void SystemTrayDelegateChromeOS::ScreenIsUnlocked() {
1141  screen_locked_ = false;
1142  ash::Shell::GetInstance()->UpdateAfterLoginStatusChange(GetUserLoginStatus());
1143}
1144
1145gfx::NativeWindow SystemTrayDelegateChromeOS::GetNativeWindow() const {
1146  bool session_started = ash::Shell::GetInstance()
1147                             ->session_state_delegate()
1148                             ->IsActiveUserSessionStarted();
1149  return GetNativeWindowByStatus(GetUserLoginStatus(), session_started);
1150}
1151
1152// content::NotificationObserver implementation.
1153void SystemTrayDelegateChromeOS::Observe(
1154    int type,
1155    const content::NotificationSource& source,
1156    const content::NotificationDetails& details) {
1157  switch (type) {
1158    case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
1159      UpgradeDetector* detector =
1160          content::Source<UpgradeDetector>(source).ptr();
1161      ash::UpdateObserver::UpdateSeverity severity =
1162          ash::UpdateObserver::UPDATE_NORMAL;
1163      switch (detector->upgrade_notification_stage()) {
1164        case UpgradeDetector::UPGRADE_ANNOYANCE_SEVERE:
1165          severity = ash::UpdateObserver::UPDATE_SEVERE_RED;
1166          break;
1167
1168        case UpgradeDetector::UPGRADE_ANNOYANCE_HIGH:
1169          severity = ash::UpdateObserver::UPDATE_HIGH_ORANGE;
1170          break;
1171
1172        case UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED:
1173          severity = ash::UpdateObserver::UPDATE_LOW_GREEN;
1174          break;
1175
1176        case UpgradeDetector::UPGRADE_ANNOYANCE_LOW:
1177        default:
1178          severity = ash::UpdateObserver::UPDATE_NORMAL;
1179          break;
1180      }
1181      GetSystemTrayNotifier()->NotifyUpdateRecommended(severity);
1182      break;
1183    }
1184    case chrome::NOTIFICATION_LOGIN_USER_IMAGE_CHANGED: {
1185      // This notification is also sent on login screen when user avatar
1186      // is loaded from file.
1187      if (GetUserLoginStatus() != ash::user::LOGGED_IN_NONE) {
1188        GetSystemTrayNotifier()->NotifyUserUpdate();
1189      }
1190      break;
1191    }
1192    case chrome::NOTIFICATION_PROFILE_CREATED: {
1193      SetProfile(content::Source<Profile>(source).ptr());
1194      registrar_->Remove(this,
1195                         chrome::NOTIFICATION_PROFILE_CREATED,
1196                         content::NotificationService::AllSources());
1197      break;
1198    }
1199    case chrome::NOTIFICATION_PROFILE_DESTROYED: {
1200      if (UnsetProfile(content::Source<Profile>(source).ptr())) {
1201        registrar_->Remove(this,
1202                           chrome::NOTIFICATION_PROFILE_DESTROYED,
1203                           content::NotificationService::AllSources());
1204      }
1205      break;
1206    }
1207    case chrome::NOTIFICATION_SESSION_STARTED: {
1208      ash::Shell::GetInstance()->UpdateAfterLoginStatusChange(
1209          GetUserLoginStatus());
1210      SetProfile(ProfileManager::GetActiveUserProfile());
1211      break;
1212    }
1213    default:
1214      NOTREACHED();
1215  }
1216}
1217
1218void SystemTrayDelegateChromeOS::OnLanguageRemapSearchKeyToChanged() {
1219  search_key_mapped_to_ = user_pref_registrar_->prefs()->GetInteger(
1220      prefs::kLanguageRemapSearchKeyTo);
1221}
1222
1223void SystemTrayDelegateChromeOS::OnAccessibilityModeChanged(
1224    ash::AccessibilityNotificationVisibility notify) {
1225  GetSystemTrayNotifier()->NotifyAccessibilityModeChanged(notify);
1226}
1227
1228void SystemTrayDelegateChromeOS::UpdatePerformanceTracing() {
1229  if (!user_pref_registrar_)
1230    return;
1231  bool value = user_pref_registrar_->prefs()->GetBoolean(
1232      prefs::kPerformanceTracingEnabled);
1233  GetSystemTrayNotifier()->NotifyTracingModeChanged(value);
1234}
1235
1236// Overridden from InputMethodManager::Observer.
1237void SystemTrayDelegateChromeOS::InputMethodChanged(
1238    input_method::InputMethodManager* manager,
1239    bool show_message) {
1240  GetSystemTrayNotifier()->NotifyRefreshIME();
1241}
1242
1243// Overridden from InputMethodMenuManager::Observer.
1244void SystemTrayDelegateChromeOS::InputMethodMenuItemChanged(
1245    ash::ime::InputMethodMenuManager* manager) {
1246  GetSystemTrayNotifier()->NotifyRefreshIME();
1247}
1248
1249// Overridden from CrasAudioHandler::AudioObserver.
1250void SystemTrayDelegateChromeOS::OnOutputVolumeChanged() {
1251  GetSystemTrayNotifier()->NotifyAudioOutputVolumeChanged();
1252}
1253
1254void SystemTrayDelegateChromeOS::OnOutputMuteChanged() {
1255  GetSystemTrayNotifier()->NotifyAudioOutputMuteChanged();
1256}
1257
1258void SystemTrayDelegateChromeOS::OnInputGainChanged() {
1259}
1260
1261void SystemTrayDelegateChromeOS::OnInputMuteChanged() {
1262}
1263
1264void SystemTrayDelegateChromeOS::OnAudioNodesChanged() {
1265  GetSystemTrayNotifier()->NotifyAudioNodesChanged();
1266}
1267
1268void SystemTrayDelegateChromeOS::OnActiveOutputNodeChanged() {
1269  GetSystemTrayNotifier()->NotifyAudioActiveOutputNodeChanged();
1270}
1271
1272void SystemTrayDelegateChromeOS::OnActiveInputNodeChanged() {
1273  GetSystemTrayNotifier()->NotifyAudioActiveInputNodeChanged();
1274}
1275
1276// drive::JobListObserver overrides.
1277void SystemTrayDelegateChromeOS::OnJobAdded(const drive::JobInfo& job_info) {
1278  OnJobUpdated(job_info);
1279}
1280
1281void SystemTrayDelegateChromeOS::OnJobDone(const drive::JobInfo& job_info,
1282                                           drive::FileError error) {
1283  ash::DriveOperationStatus status;
1284  if (ConvertToFinishedDriveOperationStatus(job_info, error, &status))
1285    GetSystemTrayNotifier()->NotifyDriveJobUpdated(status);
1286}
1287
1288void SystemTrayDelegateChromeOS::OnJobUpdated(const drive::JobInfo& job_info) {
1289  ash::DriveOperationStatus status;
1290  if (ConvertToDriveOperationStatus(job_info, &status))
1291    GetSystemTrayNotifier()->NotifyDriveJobUpdated(status);
1292}
1293
1294DriveIntegrationService*
1295SystemTrayDelegateChromeOS::FindDriveIntegrationService() {
1296  return user_profile_
1297             ? DriveIntegrationServiceFactory::FindForProfile(user_profile_)
1298             : NULL;
1299}
1300
1301// Overridden from BluetoothAdapter::Observer.
1302void SystemTrayDelegateChromeOS::AdapterPresentChanged(
1303    device::BluetoothAdapter* adapter,
1304    bool present) {
1305  GetSystemTrayNotifier()->NotifyRefreshBluetooth();
1306}
1307
1308void SystemTrayDelegateChromeOS::AdapterPoweredChanged(
1309    device::BluetoothAdapter* adapter,
1310    bool powered) {
1311  GetSystemTrayNotifier()->NotifyRefreshBluetooth();
1312}
1313
1314void SystemTrayDelegateChromeOS::AdapterDiscoveringChanged(
1315    device::BluetoothAdapter* adapter,
1316    bool discovering) {
1317  GetSystemTrayNotifier()->NotifyBluetoothDiscoveringChanged();
1318}
1319
1320void SystemTrayDelegateChromeOS::DeviceAdded(device::BluetoothAdapter* adapter,
1321                                             device::BluetoothDevice* device) {
1322  GetSystemTrayNotifier()->NotifyRefreshBluetooth();
1323}
1324
1325void SystemTrayDelegateChromeOS::DeviceChanged(
1326    device::BluetoothAdapter* adapter,
1327    device::BluetoothDevice* device) {
1328  GetSystemTrayNotifier()->NotifyRefreshBluetooth();
1329}
1330
1331void SystemTrayDelegateChromeOS::DeviceRemoved(
1332    device::BluetoothAdapter* adapter,
1333    device::BluetoothDevice* device) {
1334  GetSystemTrayNotifier()->NotifyRefreshBluetooth();
1335}
1336
1337void SystemTrayDelegateChromeOS::OnStartBluetoothDiscoverySession(
1338    scoped_ptr<device::BluetoothDiscoverySession> discovery_session) {
1339  // If the discovery session was returned after a request to stop discovery
1340  // (e.g. the user dismissed the Bluetooth detailed view before the call
1341  // returned), don't claim the discovery session and let it clean up.
1342  if (!should_run_bluetooth_discovery_)
1343    return;
1344  VLOG(1) << "Claiming new Bluetooth device discovery session.";
1345  bluetooth_discovery_session_ = discovery_session.Pass();
1346}
1347
1348void SystemTrayDelegateChromeOS::UpdateEnterpriseDomain() {
1349  policy::BrowserPolicyConnectorChromeOS* connector =
1350      g_browser_process->platform_part()->browser_policy_connector_chromeos();
1351  std::string enterprise_domain = connector->GetEnterpriseDomain();
1352  if (enterprise_domain_ != enterprise_domain) {
1353    enterprise_domain_ = enterprise_domain;
1354    GetSystemTrayNotifier()->NotifyEnterpriseDomainChanged();
1355  }
1356}
1357
1358// Overridden from CloudPolicyStore::Observer
1359void SystemTrayDelegateChromeOS::OnStoreLoaded(
1360    policy::CloudPolicyStore* store) {
1361  UpdateEnterpriseDomain();
1362}
1363
1364void SystemTrayDelegateChromeOS::OnStoreError(policy::CloudPolicyStore* store) {
1365  UpdateEnterpriseDomain();
1366}
1367
1368// Overridden from ash::SessionStateObserver
1369void SystemTrayDelegateChromeOS::UserAddedToSession(
1370    const std::string& user_id) {
1371  GetSystemTrayNotifier()->NotifyUserAddedToSession();
1372}
1373
1374// Overridden from chrome::BrowserListObserver.
1375void SystemTrayDelegateChromeOS::OnBrowserRemoved(Browser* browser) {
1376  NotifyIfLastWindowClosed();
1377}
1378
1379// Overridden from apps::AppWindowRegistry::Observer.
1380void SystemTrayDelegateChromeOS::OnAppWindowAdded(apps::AppWindow* app_window) {
1381}
1382
1383void SystemTrayDelegateChromeOS::OnAppWindowIconChanged(
1384    apps::AppWindow* app_window) {}
1385
1386void SystemTrayDelegateChromeOS::OnAppWindowRemoved(
1387    apps::AppWindow* app_window) {
1388  NotifyIfLastWindowClosed();
1389}
1390
1391void SystemTrayDelegateChromeOS::OnAccessibilityStatusChanged(
1392    const AccessibilityStatusEventDetails& details) {
1393  if (details.notification_type == ACCESSIBILITY_MANAGER_SHUTDOWN)
1394    accessibility_subscription_.reset();
1395  else
1396    OnAccessibilityModeChanged(details.notify);
1397}
1398
1399ash::SystemTrayDelegate* CreateSystemTrayDelegate() {
1400  return new SystemTrayDelegateChromeOS();
1401}
1402
1403}  // namespace chromeos
1404