system_tray_delegate_chromeos.cc revision c5cede9ae108bb15f6b7a8aea21c7e1fefa2834c
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::kShellWindowId_LockSystemModalContainer
152          : ash::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 (GetBluetoothDiscovering()) {
696    LOG(WARNING) << "Already have active Bluetooth device discovery session.";
697    return;
698  }
699  VLOG(1) << "Requesting new Bluetooth device discovery session.";
700  should_run_bluetooth_discovery_ = true;
701  bluetooth_adapter_->StartDiscoverySession(
702      base::Bind(&SystemTrayDelegateChromeOS::OnStartBluetoothDiscoverySession,
703                 weak_ptr_factory_.GetWeakPtr()),
704      base::Bind(&BluetoothSetDiscoveringError));
705}
706
707void SystemTrayDelegateChromeOS::BluetoothStopDiscovering() {
708  should_run_bluetooth_discovery_ = false;
709  if (!GetBluetoothDiscovering()) {
710    LOG(WARNING) << "No active Bluetooth device discovery session.";
711    return;
712  }
713  VLOG(1) << "Stopping Bluetooth device discovery session.";
714  bluetooth_discovery_session_->Stop(
715      base::Bind(&base::DoNothing), base::Bind(&BluetoothSetDiscoveringError));
716}
717
718void SystemTrayDelegateChromeOS::ConnectToBluetoothDevice(
719    const std::string& address) {
720  device::BluetoothDevice* device = bluetooth_adapter_->GetDevice(address);
721  if (!device || device->IsConnecting() ||
722      (device->IsConnected() && device->IsPaired())) {
723    return;
724  }
725  if (device->IsPaired() && !device->IsConnectable())
726    return;
727  if (device->IsPaired() || !device->IsPairable()) {
728    ash::Shell::GetInstance()->metrics()->RecordUserMetricsAction(
729        ash::UMA_STATUS_AREA_BLUETOOTH_CONNECT_KNOWN_DEVICE);
730    device->Connect(NULL,
731                    base::Bind(&base::DoNothing),
732                    base::Bind(&BluetoothDeviceConnectError));
733  } else {  // Show paring dialog for the unpaired device.
734    ash::Shell::GetInstance()->metrics()->RecordUserMetricsAction(
735        ash::UMA_STATUS_AREA_BLUETOOTH_CONNECT_UNKNOWN_DEVICE);
736    BluetoothPairingDialog* dialog =
737        new BluetoothPairingDialog(GetNativeWindow(), device);
738    // The dialog deletes itself on close.
739    dialog->Show();
740  }
741}
742
743bool SystemTrayDelegateChromeOS::IsBluetoothDiscovering() {
744  return bluetooth_adapter_->IsDiscovering();
745}
746
747void SystemTrayDelegateChromeOS::GetCurrentIME(ash::IMEInfo* info) {
748  input_method::InputMethodManager* manager =
749      input_method::InputMethodManager::Get();
750  input_method::InputMethodUtil* util = manager->GetInputMethodUtil();
751  input_method::InputMethodDescriptor ime = manager->GetCurrentInputMethod();
752  ExtractIMEInfo(ime, *util, info);
753  info->selected = true;
754}
755
756void SystemTrayDelegateChromeOS::GetAvailableIMEList(ash::IMEInfoList* list) {
757  input_method::InputMethodManager* manager =
758      input_method::InputMethodManager::Get();
759  input_method::InputMethodUtil* util = manager->GetInputMethodUtil();
760  scoped_ptr<input_method::InputMethodDescriptors> ime_descriptors(
761      manager->GetActiveInputMethods());
762  std::string current = manager->GetCurrentInputMethod().id();
763  for (size_t i = 0; i < ime_descriptors->size(); i++) {
764    input_method::InputMethodDescriptor& ime = ime_descriptors->at(i);
765    ash::IMEInfo info;
766    ExtractIMEInfo(ime, *util, &info);
767    info.selected = ime.id() == current;
768    list->push_back(info);
769  }
770}
771
772void SystemTrayDelegateChromeOS::GetCurrentIMEProperties(
773    ash::IMEPropertyInfoList* list) {
774  ash::ime::InputMethodMenuItemList menu_list =
775      ash::ime::InputMethodMenuManager::GetInstance()->
776      GetCurrentInputMethodMenuItemList();
777  for (size_t i = 0; i < menu_list.size(); ++i) {
778    ash::IMEPropertyInfo property;
779    property.key = menu_list[i].key;
780    property.name = base::UTF8ToUTF16(menu_list[i].label);
781    property.selected = menu_list[i].is_selection_item_checked;
782    list->push_back(property);
783  }
784}
785
786void SystemTrayDelegateChromeOS::SwitchIME(const std::string& ime_id) {
787  input_method::InputMethodManager::Get()->ChangeInputMethod(ime_id);
788}
789
790void SystemTrayDelegateChromeOS::ActivateIMEProperty(const std::string& key) {
791  input_method::InputMethodManager::Get()->ActivateInputMethodMenuItem(key);
792}
793
794void SystemTrayDelegateChromeOS::CancelDriveOperation(int32 operation_id) {
795  DriveIntegrationService* integration_service = FindDriveIntegrationService();
796  if (!integration_service)
797    return;
798
799  integration_service->job_list()->CancelJob(operation_id);
800}
801
802void SystemTrayDelegateChromeOS::GetDriveOperationStatusList(
803    ash::DriveOperationStatusList* list) {
804  DriveIntegrationService* integration_service = FindDriveIntegrationService();
805  if (!integration_service)
806    return;
807
808  *list = ConvertToDriveStatusList(
809      integration_service->job_list()->GetJobInfoList());
810}
811
812void SystemTrayDelegateChromeOS::ShowNetworkConfigure(
813    const std::string& network_id,
814    gfx::NativeWindow parent_window) {
815  NetworkConfigView::Show(network_id, parent_window);
816}
817
818bool SystemTrayDelegateChromeOS::EnrollNetwork(
819    const std::string& network_id,
820    gfx::NativeWindow parent_window) {
821  return enrollment::CreateDialog(network_id, parent_window);
822}
823
824void SystemTrayDelegateChromeOS::ManageBluetoothDevices() {
825  content::RecordAction(base::UserMetricsAction("ShowBluetoothSettingsPage"));
826  std::string sub_page =
827      std::string(chrome::kSearchSubPage) + "#" +
828      l10n_util::GetStringUTF8(IDS_OPTIONS_SETTINGS_SECTION_TITLE_BLUETOOTH);
829  ShowSettingsSubPageForActiveUser(sub_page);
830}
831
832void SystemTrayDelegateChromeOS::ToggleBluetooth() {
833  bluetooth_adapter_->SetPowered(!bluetooth_adapter_->IsPowered(),
834                                 base::Bind(&base::DoNothing),
835                                 base::Bind(&BluetoothPowerFailure));
836}
837
838void SystemTrayDelegateChromeOS::ShowMobileSimDialog() {
839  SimDialogDelegate::ShowDialog(GetNativeWindow(),
840                                SimDialogDelegate::SIM_DIALOG_UNLOCK);
841}
842
843void SystemTrayDelegateChromeOS::ShowMobileSetupDialog(
844    const std::string& service_path) {
845  MobileSetupDialog::Show(service_path);
846}
847
848void SystemTrayDelegateChromeOS::ShowOtherNetworkDialog(
849    const std::string& type) {
850  if (type == shill::kTypeCellular) {
851    ChooseMobileNetworkDialog::ShowDialog(GetNativeWindow());
852    return;
853  }
854  NetworkConfigView::ShowForType(type, GetNativeWindow());
855}
856
857bool SystemTrayDelegateChromeOS::GetBluetoothAvailable() {
858  return bluetooth_adapter_->IsPresent();
859}
860
861bool SystemTrayDelegateChromeOS::GetBluetoothEnabled() {
862  return bluetooth_adapter_->IsPowered();
863}
864
865bool SystemTrayDelegateChromeOS::GetBluetoothDiscovering() {
866  return (bluetooth_discovery_session_.get() &&
867      bluetooth_discovery_session_->IsActive());
868}
869
870void SystemTrayDelegateChromeOS::ChangeProxySettings() {
871  CHECK(GetUserLoginStatus() == ash::user::LOGGED_IN_NONE);
872  LoginDisplayHostImpl::default_host()->OpenProxySettings();
873}
874
875ash::VolumeControlDelegate*
876SystemTrayDelegateChromeOS::GetVolumeControlDelegate() const {
877  return volume_control_delegate_.get();
878}
879
880void SystemTrayDelegateChromeOS::SetVolumeControlDelegate(
881    scoped_ptr<ash::VolumeControlDelegate> delegate) {
882  volume_control_delegate_.swap(delegate);
883}
884
885bool SystemTrayDelegateChromeOS::GetSessionStartTime(
886    base::TimeTicks* session_start_time) {
887  *session_start_time = session_start_time_;
888  return have_session_start_time_;
889}
890
891bool SystemTrayDelegateChromeOS::GetSessionLengthLimit(
892    base::TimeDelta* session_length_limit) {
893  *session_length_limit = session_length_limit_;
894  return have_session_length_limit_;
895}
896
897int SystemTrayDelegateChromeOS::GetSystemTrayMenuWidth() {
898  return l10n_util::GetLocalizedContentsWidthInPixels(
899      IDS_SYSTEM_TRAY_MENU_BUBBLE_WIDTH_PIXELS);
900}
901
902void SystemTrayDelegateChromeOS::ActiveUserWasChanged() {
903  GetSystemTrayNotifier()->NotifyUserUpdate();
904}
905
906bool SystemTrayDelegateChromeOS::IsNetworkBehindCaptivePortal(
907    const std::string& service_path) const {
908  NetworkPortalDetector::CaptivePortalState state =
909      NetworkPortalDetector::Get()->GetCaptivePortalState(service_path);
910  return state.status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_PORTAL;
911}
912
913bool SystemTrayDelegateChromeOS::IsSearchKeyMappedToCapsLock() {
914  return search_key_mapped_to_ == input_method::kCapsLockKey;
915}
916
917ash::SystemTray* SystemTrayDelegateChromeOS::GetPrimarySystemTray() {
918  return ash::Shell::GetInstance()->GetPrimarySystemTray();
919}
920
921ash::SystemTrayNotifier* SystemTrayDelegateChromeOS::GetSystemTrayNotifier() {
922  return ash::Shell::GetInstance()->system_tray_notifier();
923}
924
925void SystemTrayDelegateChromeOS::SetProfile(Profile* profile) {
926  // Stop observing the Drive integration status and the AppWindowRegistry of
927  // the current |user_profile_|.
928  UnobserveDriveUpdates();
929  StopObservingAppWindowRegistry();
930
931  user_profile_ = profile;
932
933  // Start observing the Drive integration status and the AppWindowRegistry of
934  // the newly set |user_profile_|.
935  ObserveDriveUpdates();
936  apps::AppWindowRegistry::Get(user_profile_)->AddObserver(this);
937
938  PrefService* prefs = profile->GetPrefs();
939  user_pref_registrar_.reset(new PrefChangeRegistrar);
940  user_pref_registrar_->Init(prefs);
941  user_pref_registrar_->Add(
942      prefs::kUse24HourClock,
943      base::Bind(&SystemTrayDelegateChromeOS::UpdateClockType,
944                 base::Unretained(this)));
945  user_pref_registrar_->Add(
946      prefs::kLanguageRemapSearchKeyTo,
947      base::Bind(&SystemTrayDelegateChromeOS::OnLanguageRemapSearchKeyToChanged,
948                 base::Unretained(this)));
949  user_pref_registrar_->Add(
950      prefs::kShowLogoutButtonInTray,
951      base::Bind(&SystemTrayDelegateChromeOS::UpdateShowLogoutButtonInTray,
952                 base::Unretained(this)));
953  user_pref_registrar_->Add(
954      prefs::kLogoutDialogDurationMs,
955      base::Bind(&SystemTrayDelegateChromeOS::UpdateLogoutDialogDuration,
956                 base::Unretained(this)));
957  user_pref_registrar_->Add(
958      prefs::kLargeCursorEnabled,
959      base::Bind(&SystemTrayDelegateChromeOS::OnAccessibilityModeChanged,
960                 base::Unretained(this),
961                 ash::A11Y_NOTIFICATION_NONE));
962  user_pref_registrar_->Add(
963      prefs::kAutoclickEnabled,
964      base::Bind(&SystemTrayDelegateChromeOS::OnAccessibilityModeChanged,
965                 base::Unretained(this),
966                 ash::A11Y_NOTIFICATION_NONE));
967  user_pref_registrar_->Add(
968      prefs::kShouldAlwaysShowAccessibilityMenu,
969      base::Bind(&SystemTrayDelegateChromeOS::OnAccessibilityModeChanged,
970                 base::Unretained(this),
971                 ash::A11Y_NOTIFICATION_NONE));
972  user_pref_registrar_->Add(
973      prefs::kPerformanceTracingEnabled,
974      base::Bind(&SystemTrayDelegateChromeOS::UpdatePerformanceTracing,
975                 base::Unretained(this)));
976
977  UpdateClockType();
978  UpdateShowLogoutButtonInTray();
979  UpdateLogoutDialogDuration();
980  UpdatePerformanceTracing();
981  search_key_mapped_to_ =
982      profile->GetPrefs()->GetInteger(prefs::kLanguageRemapSearchKeyTo);
983}
984
985bool SystemTrayDelegateChromeOS::UnsetProfile(Profile* profile) {
986  if (profile != user_profile_)
987    return false;
988  user_pref_registrar_.reset();
989  user_profile_ = NULL;
990  return true;
991}
992
993void SystemTrayDelegateChromeOS::ObserveDriveUpdates() {
994  DriveIntegrationService* integration_service = FindDriveIntegrationService();
995  if (integration_service)
996    integration_service->job_list()->AddObserver(this);
997}
998
999void SystemTrayDelegateChromeOS::UnobserveDriveUpdates() {
1000  DriveIntegrationService* integration_service = FindDriveIntegrationService();
1001  if (integration_service)
1002    integration_service->job_list()->RemoveObserver(this);
1003}
1004
1005bool SystemTrayDelegateChromeOS::GetShouldUse24HourClockForTesting() const {
1006  return ShouldUse24HourClock();
1007}
1008
1009bool SystemTrayDelegateChromeOS::ShouldUse24HourClock() const {
1010  // On login screen and in guest mode owner default is used for
1011  // kUse24HourClock preference.
1012  const ash::user::LoginStatus status = GetUserLoginStatus();
1013  const CrosSettings* const cros_settings = CrosSettings::Get();
1014  bool system_use_24_hour_clock = true;
1015  const bool system_value_found = cros_settings->GetBoolean(
1016      kSystemUse24HourClock, &system_use_24_hour_clock);
1017
1018  if ((status == ash::user::LOGGED_IN_NONE) || !user_pref_registrar_)
1019    return (system_value_found
1020                ? system_use_24_hour_clock
1021                : (base::GetHourClockType() == base::k24HourClock));
1022
1023  const PrefService::Preference* user_pref =
1024      user_pref_registrar_->prefs()->FindPreference(prefs::kUse24HourClock);
1025  if (status == ash::user::LOGGED_IN_GUEST && user_pref->IsDefaultValue())
1026    return (system_value_found
1027                ? system_use_24_hour_clock
1028                : (base::GetHourClockType() == base::k24HourClock));
1029
1030  bool use_24_hour_clock = true;
1031  user_pref->GetValue()->GetAsBoolean(&use_24_hour_clock);
1032  return use_24_hour_clock;
1033}
1034
1035void SystemTrayDelegateChromeOS::UpdateClockType() {
1036  const bool use_24_hour_clock = ShouldUse24HourClock();
1037  clock_type_ = use_24_hour_clock ? base::k24HourClock : base::k12HourClock;
1038  GetSystemTrayNotifier()->NotifyDateFormatChanged();
1039  // This also works for enterprise-managed devices because they never have
1040  // local owner.
1041  if (chromeos::UserManager::Get()->IsCurrentUserOwner())
1042    CrosSettings::Get()->SetBoolean(kSystemUse24HourClock, use_24_hour_clock);
1043}
1044
1045void SystemTrayDelegateChromeOS::UpdateShowLogoutButtonInTray() {
1046  GetSystemTrayNotifier()->NotifyShowLoginButtonChanged(
1047      user_pref_registrar_->prefs()->GetBoolean(
1048          prefs::kShowLogoutButtonInTray));
1049}
1050
1051void SystemTrayDelegateChromeOS::UpdateLogoutDialogDuration() {
1052  const int duration_ms =
1053      user_pref_registrar_->prefs()->GetInteger(prefs::kLogoutDialogDurationMs);
1054  GetSystemTrayNotifier()->NotifyLogoutDialogDurationChanged(
1055      base::TimeDelta::FromMilliseconds(duration_ms));
1056}
1057
1058void SystemTrayDelegateChromeOS::UpdateSessionStartTime() {
1059  const PrefService* local_state = local_state_registrar_->prefs();
1060  if (local_state->HasPrefPath(prefs::kSessionStartTime)) {
1061    have_session_start_time_ = true;
1062    session_start_time_ = base::TimeTicks::FromInternalValue(
1063        local_state->GetInt64(prefs::kSessionStartTime));
1064  } else {
1065    have_session_start_time_ = false;
1066    session_start_time_ = base::TimeTicks();
1067  }
1068  GetSystemTrayNotifier()->NotifySessionStartTimeChanged();
1069}
1070
1071void SystemTrayDelegateChromeOS::UpdateSessionLengthLimit() {
1072  const PrefService* local_state = local_state_registrar_->prefs();
1073  if (local_state->HasPrefPath(prefs::kSessionLengthLimit)) {
1074    have_session_length_limit_ = true;
1075    session_length_limit_ = base::TimeDelta::FromMilliseconds(
1076        std::min(std::max(local_state->GetInteger(prefs::kSessionLengthLimit),
1077                          kSessionLengthLimitMinMs),
1078                 kSessionLengthLimitMaxMs));
1079  } else {
1080    have_session_length_limit_ = false;
1081    session_length_limit_ = base::TimeDelta();
1082  }
1083  GetSystemTrayNotifier()->NotifySessionLengthLimitChanged();
1084}
1085
1086void SystemTrayDelegateChromeOS::StopObservingAppWindowRegistry() {
1087  if (!user_profile_)
1088    return;
1089
1090  apps::AppWindowRegistry* registry =
1091      apps::AppWindowRegistry::Factory::GetForBrowserContext(user_profile_,
1092                                                             false);
1093  if (registry)
1094    registry->RemoveObserver(this);
1095}
1096
1097void SystemTrayDelegateChromeOS::NotifyIfLastWindowClosed() {
1098  if (!user_profile_)
1099    return;
1100
1101  BrowserList* browser_list =
1102      BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_ASH);
1103  for (BrowserList::const_iterator it = browser_list->begin();
1104       it != browser_list->end();
1105       ++it) {
1106    if ((*it)->profile()->IsSameProfile(user_profile_)) {
1107      // The current user has at least one open browser window.
1108      return;
1109    }
1110  }
1111
1112  if (!apps::AppWindowRegistry::Get(user_profile_)->app_windows().empty()) {
1113    // The current user has at least one open app window.
1114    return;
1115  }
1116
1117  GetSystemTrayNotifier()->NotifyLastWindowClosed();
1118}
1119
1120// LoginState::Observer overrides.
1121void SystemTrayDelegateChromeOS::LoggedInStateChanged() {
1122  // It apparently sometimes takes a while after login before the current user
1123  // is recognized as the owner. Make sure that the system-wide clock setting
1124  // is updated when the recognition eventually happens
1125  // (http://crbug.com/278601).
1126  //
1127  // Note that it isn't safe to blindly call UpdateClockType() from this
1128  // method, as LoggedInStateChanged() is also called before the logged-in
1129  // user's profile has actually been loaded (http://crbug.com/317745). The
1130  // system tray's time format is updated at login via SetProfile().
1131  if (chromeos::UserManager::Get()->IsCurrentUserOwner()) {
1132    CrosSettings::Get()->SetBoolean(kSystemUse24HourClock,
1133                                    ShouldUse24HourClock());
1134  }
1135}
1136
1137// Overridden from SessionManagerClient::Observer.
1138void SystemTrayDelegateChromeOS::ScreenIsLocked() {
1139  screen_locked_ = true;
1140  ash::Shell::GetInstance()->UpdateAfterLoginStatusChange(GetUserLoginStatus());
1141}
1142
1143void SystemTrayDelegateChromeOS::ScreenIsUnlocked() {
1144  screen_locked_ = false;
1145  ash::Shell::GetInstance()->UpdateAfterLoginStatusChange(GetUserLoginStatus());
1146}
1147
1148gfx::NativeWindow SystemTrayDelegateChromeOS::GetNativeWindow() const {
1149  bool session_started = ash::Shell::GetInstance()
1150                             ->session_state_delegate()
1151                             ->IsActiveUserSessionStarted();
1152  return GetNativeWindowByStatus(GetUserLoginStatus(), session_started);
1153}
1154
1155// content::NotificationObserver implementation.
1156void SystemTrayDelegateChromeOS::Observe(
1157    int type,
1158    const content::NotificationSource& source,
1159    const content::NotificationDetails& details) {
1160  switch (type) {
1161    case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
1162      UpgradeDetector* detector =
1163          content::Source<UpgradeDetector>(source).ptr();
1164      ash::UpdateObserver::UpdateSeverity severity =
1165          ash::UpdateObserver::UPDATE_NORMAL;
1166      switch (detector->upgrade_notification_stage()) {
1167        case UpgradeDetector::UPGRADE_ANNOYANCE_SEVERE:
1168          severity = ash::UpdateObserver::UPDATE_SEVERE_RED;
1169          break;
1170
1171        case UpgradeDetector::UPGRADE_ANNOYANCE_HIGH:
1172          severity = ash::UpdateObserver::UPDATE_HIGH_ORANGE;
1173          break;
1174
1175        case UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED:
1176          severity = ash::UpdateObserver::UPDATE_LOW_GREEN;
1177          break;
1178
1179        case UpgradeDetector::UPGRADE_ANNOYANCE_LOW:
1180        default:
1181          severity = ash::UpdateObserver::UPDATE_NORMAL;
1182          break;
1183      }
1184      GetSystemTrayNotifier()->NotifyUpdateRecommended(severity);
1185      break;
1186    }
1187    case chrome::NOTIFICATION_LOGIN_USER_IMAGE_CHANGED: {
1188      // This notification is also sent on login screen when user avatar
1189      // is loaded from file.
1190      if (GetUserLoginStatus() != ash::user::LOGGED_IN_NONE) {
1191        GetSystemTrayNotifier()->NotifyUserUpdate();
1192      }
1193      break;
1194    }
1195    case chrome::NOTIFICATION_PROFILE_CREATED: {
1196      SetProfile(content::Source<Profile>(source).ptr());
1197      registrar_->Remove(this,
1198                         chrome::NOTIFICATION_PROFILE_CREATED,
1199                         content::NotificationService::AllSources());
1200      break;
1201    }
1202    case chrome::NOTIFICATION_PROFILE_DESTROYED: {
1203      if (UnsetProfile(content::Source<Profile>(source).ptr())) {
1204        registrar_->Remove(this,
1205                           chrome::NOTIFICATION_PROFILE_DESTROYED,
1206                           content::NotificationService::AllSources());
1207      }
1208      break;
1209    }
1210    case chrome::NOTIFICATION_SESSION_STARTED: {
1211      ash::Shell::GetInstance()->UpdateAfterLoginStatusChange(
1212          GetUserLoginStatus());
1213      SetProfile(ProfileManager::GetActiveUserProfile());
1214      break;
1215    }
1216    default:
1217      NOTREACHED();
1218  }
1219}
1220
1221void SystemTrayDelegateChromeOS::OnLanguageRemapSearchKeyToChanged() {
1222  search_key_mapped_to_ = user_pref_registrar_->prefs()->GetInteger(
1223      prefs::kLanguageRemapSearchKeyTo);
1224}
1225
1226void SystemTrayDelegateChromeOS::OnAccessibilityModeChanged(
1227    ash::AccessibilityNotificationVisibility notify) {
1228  GetSystemTrayNotifier()->NotifyAccessibilityModeChanged(notify);
1229}
1230
1231void SystemTrayDelegateChromeOS::UpdatePerformanceTracing() {
1232  if (!user_pref_registrar_)
1233    return;
1234  bool value = user_pref_registrar_->prefs()->GetBoolean(
1235      prefs::kPerformanceTracingEnabled);
1236  GetSystemTrayNotifier()->NotifyTracingModeChanged(value);
1237}
1238
1239// Overridden from InputMethodManager::Observer.
1240void SystemTrayDelegateChromeOS::InputMethodChanged(
1241    input_method::InputMethodManager* manager,
1242    bool show_message) {
1243  GetSystemTrayNotifier()->NotifyRefreshIME();
1244}
1245
1246// Overridden from InputMethodMenuManager::Observer.
1247void SystemTrayDelegateChromeOS::InputMethodMenuItemChanged(
1248    ash::ime::InputMethodMenuManager* manager) {
1249  GetSystemTrayNotifier()->NotifyRefreshIME();
1250}
1251
1252// Overridden from CrasAudioHandler::AudioObserver.
1253void SystemTrayDelegateChromeOS::OnOutputVolumeChanged() {
1254  GetSystemTrayNotifier()->NotifyAudioOutputVolumeChanged();
1255}
1256
1257void SystemTrayDelegateChromeOS::OnOutputMuteChanged() {
1258  GetSystemTrayNotifier()->NotifyAudioOutputMuteChanged();
1259}
1260
1261void SystemTrayDelegateChromeOS::OnInputGainChanged() {
1262}
1263
1264void SystemTrayDelegateChromeOS::OnInputMuteChanged() {
1265}
1266
1267void SystemTrayDelegateChromeOS::OnAudioNodesChanged() {
1268  GetSystemTrayNotifier()->NotifyAudioNodesChanged();
1269}
1270
1271void SystemTrayDelegateChromeOS::OnActiveOutputNodeChanged() {
1272  GetSystemTrayNotifier()->NotifyAudioActiveOutputNodeChanged();
1273}
1274
1275void SystemTrayDelegateChromeOS::OnActiveInputNodeChanged() {
1276  GetSystemTrayNotifier()->NotifyAudioActiveInputNodeChanged();
1277}
1278
1279// drive::JobListObserver overrides.
1280void SystemTrayDelegateChromeOS::OnJobAdded(const drive::JobInfo& job_info) {
1281  OnJobUpdated(job_info);
1282}
1283
1284void SystemTrayDelegateChromeOS::OnJobDone(const drive::JobInfo& job_info,
1285                                           drive::FileError error) {
1286  ash::DriveOperationStatus status;
1287  if (ConvertToFinishedDriveOperationStatus(job_info, error, &status))
1288    GetSystemTrayNotifier()->NotifyDriveJobUpdated(status);
1289}
1290
1291void SystemTrayDelegateChromeOS::OnJobUpdated(const drive::JobInfo& job_info) {
1292  ash::DriveOperationStatus status;
1293  if (ConvertToDriveOperationStatus(job_info, &status))
1294    GetSystemTrayNotifier()->NotifyDriveJobUpdated(status);
1295}
1296
1297DriveIntegrationService*
1298SystemTrayDelegateChromeOS::FindDriveIntegrationService() {
1299  return user_profile_
1300             ? DriveIntegrationServiceFactory::FindForProfile(user_profile_)
1301             : NULL;
1302}
1303
1304// Overridden from BluetoothAdapter::Observer.
1305void SystemTrayDelegateChromeOS::AdapterPresentChanged(
1306    device::BluetoothAdapter* adapter,
1307    bool present) {
1308  GetSystemTrayNotifier()->NotifyRefreshBluetooth();
1309}
1310
1311void SystemTrayDelegateChromeOS::AdapterPoweredChanged(
1312    device::BluetoothAdapter* adapter,
1313    bool powered) {
1314  GetSystemTrayNotifier()->NotifyRefreshBluetooth();
1315}
1316
1317void SystemTrayDelegateChromeOS::AdapterDiscoveringChanged(
1318    device::BluetoothAdapter* adapter,
1319    bool discovering) {
1320  GetSystemTrayNotifier()->NotifyBluetoothDiscoveringChanged();
1321}
1322
1323void SystemTrayDelegateChromeOS::DeviceAdded(device::BluetoothAdapter* adapter,
1324                                             device::BluetoothDevice* device) {
1325  GetSystemTrayNotifier()->NotifyRefreshBluetooth();
1326}
1327
1328void SystemTrayDelegateChromeOS::DeviceChanged(
1329    device::BluetoothAdapter* adapter,
1330    device::BluetoothDevice* device) {
1331  GetSystemTrayNotifier()->NotifyRefreshBluetooth();
1332}
1333
1334void SystemTrayDelegateChromeOS::DeviceRemoved(
1335    device::BluetoothAdapter* adapter,
1336    device::BluetoothDevice* device) {
1337  GetSystemTrayNotifier()->NotifyRefreshBluetooth();
1338}
1339
1340void SystemTrayDelegateChromeOS::OnStartBluetoothDiscoverySession(
1341    scoped_ptr<device::BluetoothDiscoverySession> discovery_session) {
1342  // If the discovery session was returned after a request to stop discovery
1343  // (e.g. the user dismissed the Bluetooth detailed view before the call
1344  // returned), don't claim the discovery session and let it clean up.
1345  if (!should_run_bluetooth_discovery_)
1346    return;
1347  VLOG(1) << "Claiming new Bluetooth device discovery session.";
1348  bluetooth_discovery_session_ = discovery_session.Pass();
1349  GetSystemTrayNotifier()->NotifyBluetoothDiscoveringChanged();
1350}
1351
1352void SystemTrayDelegateChromeOS::UpdateEnterpriseDomain() {
1353  policy::BrowserPolicyConnectorChromeOS* connector =
1354      g_browser_process->platform_part()->browser_policy_connector_chromeos();
1355  std::string enterprise_domain = connector->GetEnterpriseDomain();
1356  if (enterprise_domain_ != enterprise_domain) {
1357    enterprise_domain_ = enterprise_domain;
1358    GetSystemTrayNotifier()->NotifyEnterpriseDomainChanged();
1359  }
1360}
1361
1362// Overridden from CloudPolicyStore::Observer
1363void SystemTrayDelegateChromeOS::OnStoreLoaded(
1364    policy::CloudPolicyStore* store) {
1365  UpdateEnterpriseDomain();
1366}
1367
1368void SystemTrayDelegateChromeOS::OnStoreError(policy::CloudPolicyStore* store) {
1369  UpdateEnterpriseDomain();
1370}
1371
1372// Overridden from ash::SessionStateObserver
1373void SystemTrayDelegateChromeOS::UserAddedToSession(
1374    const std::string& user_id) {
1375  GetSystemTrayNotifier()->NotifyUserAddedToSession();
1376}
1377
1378// Overridden from chrome::BrowserListObserver.
1379void SystemTrayDelegateChromeOS::OnBrowserRemoved(Browser* browser) {
1380  NotifyIfLastWindowClosed();
1381}
1382
1383// Overridden from apps::AppWindowRegistry::Observer.
1384void SystemTrayDelegateChromeOS::OnAppWindowAdded(apps::AppWindow* app_window) {
1385}
1386
1387void SystemTrayDelegateChromeOS::OnAppWindowIconChanged(
1388    apps::AppWindow* app_window) {}
1389
1390void SystemTrayDelegateChromeOS::OnAppWindowRemoved(
1391    apps::AppWindow* app_window) {
1392  NotifyIfLastWindowClosed();
1393}
1394
1395void SystemTrayDelegateChromeOS::OnAccessibilityStatusChanged(
1396    const AccessibilityStatusEventDetails& details) {
1397  if (details.notification_type == ACCESSIBILITY_MANAGER_SHUTDOWN)
1398    accessibility_subscription_.reset();
1399  else
1400    OnAccessibilityModeChanged(details.notify);
1401}
1402
1403ash::SystemTrayDelegate* CreateSystemTrayDelegate() {
1404  return new SystemTrayDelegateChromeOS();
1405}
1406
1407}  // namespace chromeos
1408