1 // Copyright (c) 2012 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.
9 #include "base/base_paths.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/logging.h"
13 #include "base/prefs/pref_registry_simple.h"
14 #include "base/prefs/pref_service.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "chrome/app/chrome_command_ids.h"
17 #include "chrome/browser/background/background_application_list_model.h"
18 #include "chrome/browser/background/background_mode_manager.h"
19 #include "chrome/browser/browser_process.h"
20 #include "chrome/browser/browser_shutdown.h"
21 #include "chrome/browser/chrome_notification_types.h"
22 #include "chrome/browser/extensions/extension_service.h"
23 #include "chrome/browser/lifetime/application_lifetime.h"
24 #include "chrome/browser/profiles/profile.h"
25 #include "chrome/browser/profiles/profile_info_cache.h"
26 #include "chrome/browser/profiles/profile_manager.h"
27 #include "chrome/browser/status_icons/status_icon.h"
28 #include "chrome/browser/status_icons/status_tray.h"
29 #include "chrome/browser/ui/browser.h"
30 #include "chrome/browser/ui/browser_commands.h"
31 #include "chrome/browser/ui/browser_finder.h"
32 #include "chrome/browser/ui/browser_list.h"
33 #include "chrome/browser/ui/chrome_pages.h"
34 #include "chrome/browser/ui/extensions/application_launch.h"
35 #include "chrome/browser/ui/host_desktop.h"
36 #include "chrome/common/chrome_constants.h"
37 #include "chrome/common/chrome_switches.h"
38 #include "chrome/common/extensions/extension_constants.h"
39 #include "chrome/common/pref_names.h"
40 #include "chrome/grit/chromium_strings.h"
41 #include "chrome/grit/generated_resources.h"
42 #include "content/public/browser/notification_service.h"
43 #include "content/public/browser/user_metrics.h"
44 #include "extensions/browser/extension_system.h"
45 #include "extensions/common/extension.h"
46 #include "extensions/common/manifest_handlers/options_page_info.h"
47 #include "extensions/common/permissions/permission_set.h"
48 #include "grit/chrome_unscaled_resources.h"
49 #include "ui/base/l10n/l10n_util.h"
50 #include "ui/base/resource/resource_bundle.h"
52 using base::UserMetricsAction
;
53 using extensions::Extension
;
54 using extensions::UpdatedExtensionPermissionsInfo
;
57 const int kInvalidExtensionIndex
= -1;
60 BackgroundModeManager::BackgroundModeData::BackgroundModeData(
62 CommandIdExtensionVector
* command_id_extension_vector
)
63 : applications_(new BackgroundApplicationListModel(profile
)),
65 command_id_extension_vector_(command_id_extension_vector
) {
68 BackgroundModeManager::BackgroundModeData::~BackgroundModeData() {
71 ///////////////////////////////////////////////////////////////////////////////
72 // BackgroundModeManager::BackgroundModeData, StatusIconMenuModel overrides
73 void BackgroundModeManager::BackgroundModeData::ExecuteCommand(
77 case IDC_MinimumLabelValue
:
78 // Do nothing. This is just a label.
81 // Launch the app associated with this Command ID.
82 int extension_index
= command_id_extension_vector_
->at(command_id
);
83 if (extension_index
!= kInvalidExtensionIndex
) {
84 const Extension
* extension
=
85 applications_
->GetExtension(extension_index
);
86 BackgroundModeManager::LaunchBackgroundApplication(profile_
, extension
);
92 Browser
* BackgroundModeManager::BackgroundModeData::GetBrowserWindow() {
93 chrome::HostDesktopType host_desktop_type
= chrome::GetActiveDesktop();
94 Browser
* browser
= chrome::FindLastActiveWithProfile(profile_
,
96 return browser
? browser
: chrome::OpenEmptyWindow(profile_
,
100 int BackgroundModeManager::BackgroundModeData::GetBackgroundAppCount() const {
101 return applications_
->size();
104 void BackgroundModeManager::BackgroundModeData::BuildProfileMenu(
105 StatusIconMenuModel
* menu
,
106 StatusIconMenuModel
* containing_menu
) {
108 // When there are no background applications, we want to display
109 // just a label stating that none are running.
110 if (applications_
->size() < 1) {
111 menu
->AddItemWithStringId(IDC_MinimumLabelValue
,
112 IDS_BACKGROUND_APP_NOT_INSTALLED
);
113 menu
->SetCommandIdEnabled(IDC_MinimumLabelValue
, false);
115 for (extensions::ExtensionList::const_iterator cursor
=
116 applications_
->begin();
117 cursor
!= applications_
->end();
118 ++cursor
, ++position
) {
119 const gfx::ImageSkia
* icon
= applications_
->GetIcon(cursor
->get());
120 DCHECK(position
== applications_
->GetPosition(cursor
->get()));
121 const std::string
& name
= (*cursor
)->name();
122 int command_id
= command_id_extension_vector_
->size();
123 // Check that the command ID is within the dynamic range.
124 DCHECK(command_id
< IDC_MinimumLabelValue
);
125 command_id_extension_vector_
->push_back(position
);
126 menu
->AddItem(command_id
, base::UTF8ToUTF16(name
));
128 menu
->SetIcon(menu
->GetItemCount() - 1, gfx::Image(*icon
));
130 // Component extensions with background that do not have an options page
131 // will cause this menu item to go to the extensions page with an
132 // absent component extension.
134 // Ideally, we would remove this item, but this conflicts with the user
135 // model where this menu shows the extensions with background.
137 // The compromise is to disable the item, avoiding the non-actionable
138 // navigate to the extensions page and preserving the user model.
139 if ((*cursor
)->location() == extensions::Manifest::COMPONENT
) {
141 extensions::OptionsPageInfo::GetOptionsPage(cursor
->get());
142 if (!options_page
.is_valid())
143 menu
->SetCommandIdEnabled(command_id
, false);
147 if (containing_menu
) {
148 int menu_command_id
= command_id_extension_vector_
->size();
149 // Check that the command ID is within the dynamic range.
150 DCHECK(menu_command_id
< IDC_MinimumLabelValue
);
151 command_id_extension_vector_
->push_back(kInvalidExtensionIndex
);
152 containing_menu
->AddSubMenu(menu_command_id
, name_
, menu
);
156 void BackgroundModeManager::BackgroundModeData::SetName(
157 const base::string16
& new_profile_name
) {
158 name_
= new_profile_name
;
161 base::string16
BackgroundModeManager::BackgroundModeData::name() {
165 std::set
<const extensions::Extension
*>
166 BackgroundModeManager::BackgroundModeData::GetNewBackgroundApps() {
167 std::set
<const extensions::Extension
*> new_apps
;
169 // Copy all current extensions into our list of |current_extensions_|.
170 for (extensions::ExtensionList::const_iterator it
= applications_
->begin();
171 it
!= applications_
->end(); ++it
) {
172 const extensions::ExtensionId
& id
= (*it
)->id();
173 if (current_extensions_
.count(id
) == 0) {
174 // Not found in our set yet - add it and maybe return as a previously
176 current_extensions_
.insert(id
);
177 // If this application has been newly loaded after the initial startup,
179 if (applications_
->is_ready()) {
180 const extensions::Extension
* extension
= (*it
).get();
181 new_apps
.insert(extension
);
189 bool BackgroundModeManager::BackgroundModeData::BackgroundModeDataCompare(
190 const BackgroundModeData
* bmd1
,
191 const BackgroundModeData
* bmd2
) {
192 return bmd1
->name_
< bmd2
->name_
;
196 ///////////////////////////////////////////////////////////////////////////////
197 // BackgroundModeManager, public
198 BackgroundModeManager::BackgroundModeManager(
199 CommandLine
* command_line
,
200 ProfileInfoCache
* profile_cache
)
201 : profile_cache_(profile_cache
),
205 in_background_mode_(false),
206 keep_alive_for_startup_(false),
207 keep_alive_for_test_(false),
208 background_mode_suspended_(false),
209 keeping_alive_(false) {
210 // We should never start up if there is no browser process or if we are
211 // currently quitting.
212 CHECK(g_browser_process
!= NULL
);
213 CHECK(!browser_shutdown::IsTryingToQuit());
215 // Add self as an observer for the profile info cache so we know when profiles
216 // are deleted and their names change.
217 profile_cache_
->AddObserver(this);
219 // Listen for the background mode preference changing.
220 if (g_browser_process
->local_state()) { // Skip for unit tests
221 pref_registrar_
.Init(g_browser_process
->local_state());
223 prefs::kBackgroundModeEnabled
,
224 base::Bind(&BackgroundModeManager::OnBackgroundModeEnabledPrefChanged
,
225 base::Unretained(this)));
228 // Keep the browser alive until extensions are done loading - this is needed
229 // by the --no-startup-window flag. We want to stay alive until we load
230 // extensions, at which point we should either run in background mode (if
231 // there are background apps) or exit if there are none.
232 if (command_line
->HasSwitch(switches::kNoStartupWindow
)) {
233 keep_alive_for_startup_
= true;
234 chrome::IncrementKeepAliveCount();
236 // Otherwise, start with background mode suspended in case we're launching
237 // in a mode that doesn't open a browser window. It will be resumed when the
238 // first browser window is opened.
239 SuspendBackgroundMode();
242 // If the -keep-alive-for-test flag is passed, then always keep chrome running
243 // in the background until the user explicitly terminates it.
244 if (command_line
->HasSwitch(switches::kKeepAliveForTest
))
245 keep_alive_for_test_
= true;
247 if (ShouldBeInBackgroundMode())
248 StartBackgroundMode();
250 // Listen for the application shutting down so we can decrement our KeepAlive
252 registrar_
.Add(this, chrome::NOTIFICATION_APP_TERMINATING
,
253 content::NotificationService::AllSources());
254 BrowserList::AddObserver(this);
257 BackgroundModeManager::~BackgroundModeManager() {
258 // Remove ourselves from the application observer list (only needed by unit
259 // tests since APP_TERMINATING is what does this in a real running system).
260 for (BackgroundModeInfoMap::iterator it
=
261 background_mode_data_
.begin();
262 it
!= background_mode_data_
.end();
264 it
->second
->applications_
->RemoveObserver(this);
266 BrowserList::RemoveObserver(this);
268 // We're going away, so exit background mode (does nothing if we aren't in
269 // background mode currently). This is primarily needed for unit tests,
270 // because in an actual running system we'd get an APP_TERMINATING
271 // notification before being destroyed.
276 void BackgroundModeManager::RegisterPrefs(PrefRegistrySimple
* registry
) {
277 #if defined(OS_MACOSX)
278 registry
->RegisterBooleanPref(prefs::kUserRemovedLoginItem
, false);
279 registry
->RegisterBooleanPref(prefs::kChromeCreatedLoginItem
, false);
280 registry
->RegisterBooleanPref(prefs::kMigratedLoginItemPref
, false);
282 registry
->RegisterBooleanPref(prefs::kBackgroundModeEnabled
, true);
286 void BackgroundModeManager::RegisterProfile(Profile
* profile
) {
287 // We don't want to register multiple times for one profile.
288 DCHECK(background_mode_data_
.find(profile
) == background_mode_data_
.end());
289 BackgroundModeInfo
bmd(new BackgroundModeData(profile
,
290 &command_id_extension_vector_
));
291 background_mode_data_
[profile
] = bmd
;
293 // Initially set the name for this background mode data.
294 size_t index
= profile_cache_
->GetIndexOfProfileWithPath(profile
->GetPath());
295 base::string16 name
= l10n_util::GetStringUTF16(IDS_PROFILES_DEFAULT_NAME
);
296 if (index
!= std::string::npos
)
297 name
= profile_cache_
->GetNameOfProfileAtIndex(index
);
300 // Check for the presence of background apps after all extensions have been
301 // loaded, to handle the case where an extension has been manually removed
302 // while Chrome was not running.
304 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED
,
305 content::Source
<Profile
>(profile
));
307 bmd
->applications_
->AddObserver(this);
309 // If we're adding a new profile and running in multi-profile mode, this new
310 // profile should be added to the status icon if one currently exists.
311 if (in_background_mode_
&& status_icon_
)
312 UpdateStatusTrayIconContextMenu();
316 void BackgroundModeManager::LaunchBackgroundApplication(
318 const Extension
* extension
) {
319 OpenApplication(AppLaunchParams(profile
, extension
, NEW_FOREGROUND_TAB
));
322 bool BackgroundModeManager::IsBackgroundModeActive() {
323 return in_background_mode_
;
326 int BackgroundModeManager::NumberOfBackgroundModeData() {
327 return background_mode_data_
.size();
330 ///////////////////////////////////////////////////////////////////////////////
331 // BackgroundModeManager, content::NotificationObserver overrides
332 void BackgroundModeManager::Observe(
334 const content::NotificationSource
& source
,
335 const content::NotificationDetails
& details
) {
337 case extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED
:
338 // Extensions are loaded, so we don't need to manually keep the browser
339 // process alive any more when running in no-startup-window mode.
340 DecrementKeepAliveCountForStartup();
342 case chrome::NOTIFICATION_APP_TERMINATING
:
343 // Make sure we aren't still keeping the app alive (only happens if we
344 // don't receive an EXTENSIONS_READY notification for some reason).
345 DecrementKeepAliveCountForStartup();
346 // Performing an explicit shutdown, so exit background mode (does nothing
347 // if we aren't in background mode currently).
349 // Shutting down, so don't listen for any more notifications so we don't
350 // try to re-enter/exit background mode again.
351 registrar_
.RemoveAll();
352 for (BackgroundModeInfoMap::iterator it
=
353 background_mode_data_
.begin();
354 it
!= background_mode_data_
.end();
356 it
->second
->applications_
->RemoveObserver(this);
365 void BackgroundModeManager::OnBackgroundModeEnabledPrefChanged() {
366 if (IsBackgroundModePrefEnabled())
367 EnableBackgroundMode();
369 DisableBackgroundMode();
372 ///////////////////////////////////////////////////////////////////////////////
373 // BackgroundModeManager, BackgroundApplicationListModel::Observer overrides
374 void BackgroundModeManager::OnApplicationDataChanged(
375 const Extension
* extension
, Profile
* profile
) {
376 UpdateStatusTrayIconContextMenu();
379 void BackgroundModeManager::OnApplicationListChanged(Profile
* profile
) {
380 if (!IsBackgroundModePrefEnabled())
383 // Update the profile cache with the fact whether background apps are running
385 size_t profile_index
= profile_cache_
->GetIndexOfProfileWithPath(
387 if (profile_index
!= std::string::npos
) {
388 profile_cache_
->SetBackgroundStatusOfProfileAtIndex(
389 profile_index
, GetBackgroundAppCountForProfile(profile
) != 0);
392 if (!ShouldBeInBackgroundMode()) {
393 // We've uninstalled our last background app, make sure we exit background
394 // mode and no longer launch on startup.
395 EnableLaunchOnStartup(false);
398 // We have at least one background app running - make sure we're in
400 if (!in_background_mode_
) {
401 // We're entering background mode - make sure we have launch-on-startup
402 // enabled. On Mac, the platform-specific code tracks whether the user
403 // has deleted a login item in the past, and if so, no login item will
404 // be created (to avoid overriding the specific user action).
405 EnableLaunchOnStartup(true);
407 StartBackgroundMode();
409 // List of applications changed so update the UI.
410 UpdateStatusTrayIconContextMenu();
412 // Notify the user about any new applications.
413 BackgroundModeData
* bmd
= GetBackgroundModeData(profile
);
414 std::set
<const extensions::Extension
*> new_apps
=
415 bmd
->GetNewBackgroundApps();
416 for (std::set
<const extensions::Extension
*>::const_iterator it
=
417 new_apps
.begin(); it
!= new_apps
.end(); ++it
) {
418 OnBackgroundAppInstalled(*it
);
423 ///////////////////////////////////////////////////////////////////////////////
424 // BackgroundModeManager, ProfileInfoCacheObserver overrides
425 void BackgroundModeManager::OnProfileAdded(const base::FilePath
& profile_path
) {
426 ProfileInfoCache
& cache
=
427 g_browser_process
->profile_manager()->GetProfileInfoCache();
428 base::string16 profile_name
= cache
.GetNameOfProfileAtIndex(
429 cache
.GetIndexOfProfileWithPath(profile_path
));
430 // At this point, the profile should be registered with the background mode
431 // manager, but when it's actually added to the cache is when its name is
432 // set so we need up to update that with the background_mode_data.
433 for (BackgroundModeInfoMap::const_iterator it
=
434 background_mode_data_
.begin();
435 it
!= background_mode_data_
.end();
437 if (it
->first
->GetPath() == profile_path
) {
438 it
->second
->SetName(profile_name
);
439 UpdateStatusTrayIconContextMenu();
445 void BackgroundModeManager::OnProfileWillBeRemoved(
446 const base::FilePath
& profile_path
) {
447 ProfileInfoCache
& cache
=
448 g_browser_process
->profile_manager()->GetProfileInfoCache();
449 base::string16 profile_name
= cache
.GetNameOfProfileAtIndex(
450 cache
.GetIndexOfProfileWithPath(profile_path
));
451 // Remove the profile from our map of profiles.
452 BackgroundModeInfoMap::iterator it
=
453 GetBackgroundModeIterator(profile_name
);
454 // If a profile isn't running a background app, it may not be in the map.
455 if (it
!= background_mode_data_
.end()) {
456 it
->second
->applications_
->RemoveObserver(this);
457 background_mode_data_
.erase(it
);
458 // If there are no background mode profiles any longer, then turn off
460 if (!ShouldBeInBackgroundMode()) {
461 EnableLaunchOnStartup(false);
464 UpdateStatusTrayIconContextMenu();
468 void BackgroundModeManager::OnProfileNameChanged(
469 const base::FilePath
& profile_path
,
470 const base::string16
& old_profile_name
) {
471 ProfileInfoCache
& cache
=
472 g_browser_process
->profile_manager()->GetProfileInfoCache();
473 base::string16 new_profile_name
= cache
.GetNameOfProfileAtIndex(
474 cache
.GetIndexOfProfileWithPath(profile_path
));
475 BackgroundModeInfoMap::const_iterator it
=
476 GetBackgroundModeIterator(old_profile_name
);
477 // We check that the returned iterator is valid due to unittests, but really
478 // this should only be called on profiles already known by the background
480 if (it
!= background_mode_data_
.end()) {
481 it
->second
->SetName(new_profile_name
);
482 UpdateStatusTrayIconContextMenu();
486 ///////////////////////////////////////////////////////////////////////////////
487 // BackgroundModeManager::BackgroundModeData, StatusIconMenuModel overrides
488 void BackgroundModeManager::ExecuteCommand(int command_id
, int event_flags
) {
489 // When a browser window is necessary, we use the first profile. The windows
490 // opened for these commands are not profile-specific, so any profile would
491 // work and the first is convenient.
492 BackgroundModeData
* bmd
= background_mode_data_
.begin()->second
.get();
493 switch (command_id
) {
495 chrome::ShowAboutChrome(bmd
->GetBrowserWindow());
497 case IDC_TASK_MANAGER
:
498 chrome::OpenTaskManager(bmd
->GetBrowserWindow());
501 content::RecordAction(UserMetricsAction("Exit"));
502 chrome::CloseAllBrowsers();
504 case IDC_STATUS_TRAY_KEEP_CHROME_RUNNING_IN_BACKGROUND
: {
505 // Background mode must already be enabled (as otherwise this menu would
507 DCHECK(IsBackgroundModePrefEnabled());
508 DCHECK(chrome::WillKeepAlive());
510 // Set the background mode pref to "disabled" - the resulting notification
511 // will result in a call to DisableBackgroundMode().
512 PrefService
* service
= g_browser_process
->local_state();
514 service
->SetBoolean(prefs::kBackgroundModeEnabled
, false);
518 bmd
->ExecuteCommand(command_id
, event_flags
);
524 ///////////////////////////////////////////////////////////////////////////////
525 // BackgroundModeManager, private
526 void BackgroundModeManager::DecrementKeepAliveCountForStartup() {
527 if (keep_alive_for_startup_
) {
528 keep_alive_for_startup_
= false;
529 // We call this via the message queue to make sure we don't try to end
530 // keep-alive (which can shutdown Chrome) before the message loop has
532 base::MessageLoop::current()->PostTask(
533 FROM_HERE
, base::Bind(&chrome::DecrementKeepAliveCount
));
537 void BackgroundModeManager::StartBackgroundMode() {
538 DCHECK(ShouldBeInBackgroundMode());
539 // Don't bother putting ourselves in background mode if we're already there
540 // or if background mode is disabled.
541 if (in_background_mode_
)
544 // Mark ourselves as running in background mode.
545 in_background_mode_
= true;
547 UpdateKeepAliveAndTrayIcon();
549 content::NotificationService::current()->Notify(
550 chrome::NOTIFICATION_BACKGROUND_MODE_CHANGED
,
551 content::Source
<BackgroundModeManager
>(this),
552 content::Details
<bool>(&in_background_mode_
));
555 void BackgroundModeManager::EndBackgroundMode() {
556 if (!in_background_mode_
)
558 in_background_mode_
= false;
560 UpdateKeepAliveAndTrayIcon();
562 content::NotificationService::current()->Notify(
563 chrome::NOTIFICATION_BACKGROUND_MODE_CHANGED
,
564 content::Source
<BackgroundModeManager
>(this),
565 content::Details
<bool>(&in_background_mode_
));
568 void BackgroundModeManager::EnableBackgroundMode() {
569 DCHECK(IsBackgroundModePrefEnabled());
570 // If background mode should be enabled, but isn't, turn it on.
571 if (!in_background_mode_
&& ShouldBeInBackgroundMode()) {
572 StartBackgroundMode();
573 EnableLaunchOnStartup(true);
577 void BackgroundModeManager::DisableBackgroundMode() {
578 DCHECK(!IsBackgroundModePrefEnabled());
579 // If background mode is currently enabled, turn it off.
580 if (in_background_mode_
) {
582 EnableLaunchOnStartup(false);
586 void BackgroundModeManager::SuspendBackgroundMode() {
587 background_mode_suspended_
= true;
588 UpdateKeepAliveAndTrayIcon();
591 void BackgroundModeManager::ResumeBackgroundMode() {
592 background_mode_suspended_
= false;
593 UpdateKeepAliveAndTrayIcon();
596 void BackgroundModeManager::UpdateKeepAliveAndTrayIcon() {
597 if (in_background_mode_
&& !background_mode_suspended_
) {
598 if (!keeping_alive_
) {
599 keeping_alive_
= true;
600 chrome::IncrementKeepAliveCount();
602 CreateStatusTrayIcon();
606 RemoveStatusTrayIcon();
607 if (keeping_alive_
) {
608 keeping_alive_
= false;
609 chrome::DecrementKeepAliveCount();
613 void BackgroundModeManager::OnBrowserAdded(Browser
* browser
) {
614 ResumeBackgroundMode();
617 int BackgroundModeManager::GetBackgroundAppCount() const {
619 // Walk the BackgroundModeData for all profiles and count the number of apps.
620 for (BackgroundModeInfoMap::const_iterator it
=
621 background_mode_data_
.begin();
622 it
!= background_mode_data_
.end();
624 count
+= it
->second
->GetBackgroundAppCount();
630 int BackgroundModeManager::GetBackgroundAppCountForProfile(
631 Profile
* const profile
) const {
632 BackgroundModeData
* bmd
= GetBackgroundModeData(profile
);
633 return bmd
->GetBackgroundAppCount();
636 bool BackgroundModeManager::ShouldBeInBackgroundMode() const {
637 return IsBackgroundModePrefEnabled() &&
638 (GetBackgroundAppCount() > 0 || keep_alive_for_test_
);
641 void BackgroundModeManager::OnBackgroundAppInstalled(
642 const Extension
* extension
) {
643 // Background mode is disabled - don't do anything.
644 if (!IsBackgroundModePrefEnabled())
647 // Ensure we have a tray icon (needed so we can display the app-installed
648 // notification below).
649 EnableBackgroundMode();
650 ResumeBackgroundMode();
652 // Notify the user that a background app has been installed.
653 if (extension
) { // NULL when called by unit tests.
654 DisplayAppInstalledNotification(extension
);
658 void BackgroundModeManager::CreateStatusTrayIcon() {
659 // Only need status icons on windows/linux. ChromeOS doesn't allow exiting
660 // Chrome and Mac can use the dock icon instead.
662 // Since there are multiple profiles which share the status tray, we now
663 // use the browser process to keep track of it.
664 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
666 status_tray_
= g_browser_process
->status_tray();
669 // If the platform doesn't support status icons, or we've already created
670 // our status icon, just return.
671 if (!status_tray_
|| status_icon_
)
674 // TODO(rlp): Status tray icon should have submenus for each profile.
675 gfx::ImageSkia
* image_skia
= ui::ResourceBundle::GetSharedInstance().
676 GetImageSkiaNamed(IDR_STATUS_TRAY_ICON
);
678 status_icon_
= status_tray_
->CreateStatusIcon(
679 StatusTray::BACKGROUND_MODE_ICON
,
681 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME
));
684 UpdateStatusTrayIconContextMenu();
687 void BackgroundModeManager::UpdateStatusTrayIconContextMenu() {
688 // Ensure we have a tray icon if appropriate.
689 UpdateKeepAliveAndTrayIcon();
691 // If we don't have a status icon or one could not be created succesfully,
692 // then no need to continue the update.
696 // We should only get here if we have a profile loaded, or if we're running
698 if (background_mode_data_
.empty()) {
699 DCHECK(keep_alive_for_test_
);
703 // We are building a new menu. Reset the Command IDs.
704 command_id_extension_vector_
.clear();
706 // Clear the submenus too since we will be creating new ones.
709 // TODO(rlp): Add current profile color or indicator.
710 // Create a context menu item for Chrome.
711 scoped_ptr
<StatusIconMenuModel
> menu(new StatusIconMenuModel(this));
713 menu
->AddItem(IDC_ABOUT
, l10n_util::GetStringUTF16(IDS_ABOUT
));
714 menu
->AddItemWithStringId(IDC_TASK_MANAGER
, IDS_TASK_MANAGER
);
715 menu
->AddSeparator(ui::NORMAL_SEPARATOR
);
717 if (profile_cache_
->GetNumberOfProfiles() > 1) {
718 std::vector
<BackgroundModeData
*> bmd_vector
;
719 for (BackgroundModeInfoMap::iterator it
=
720 background_mode_data_
.begin();
721 it
!= background_mode_data_
.end();
723 bmd_vector
.push_back(it
->second
.get());
725 std::sort(bmd_vector
.begin(), bmd_vector
.end(),
726 &BackgroundModeData::BackgroundModeDataCompare
);
727 int profiles_with_apps
= 0;
728 for (std::vector
<BackgroundModeData
*>::const_iterator bmd_it
=
730 bmd_it
!= bmd_vector
.end();
732 BackgroundModeData
* bmd
= *bmd_it
;
733 // We should only display the profile in the status icon if it has at
734 // least one background app.
735 if (bmd
->GetBackgroundAppCount() > 0) {
736 StatusIconMenuModel
* submenu
= new StatusIconMenuModel(bmd
);
737 // The submenu constructor caller owns the lifetime of the submenu.
738 // The containing menu does not handle the lifetime.
739 submenus
.push_back(submenu
);
740 bmd
->BuildProfileMenu(submenu
, menu
.get());
741 profiles_with_apps
++;
744 // We should only be displaying the status tray icon if there is at least
745 // one profile with a background app.
746 DCHECK_GT(profiles_with_apps
, 0);
748 // We should only have one profile in the cache if we are not
749 // using multi-profiles. If keep_alive_for_test_ is set, then we may not
750 // have any profiles in the cache.
751 DCHECK(profile_cache_
->GetNumberOfProfiles() == size_t(1) ||
752 keep_alive_for_test_
);
753 background_mode_data_
.begin()->second
->BuildProfileMenu(menu
.get(), NULL
);
756 menu
->AddSeparator(ui::NORMAL_SEPARATOR
);
757 menu
->AddCheckItemWithStringId(
758 IDC_STATUS_TRAY_KEEP_CHROME_RUNNING_IN_BACKGROUND
,
759 IDS_STATUS_TRAY_KEEP_CHROME_RUNNING_IN_BACKGROUND
);
760 menu
->SetCommandIdChecked(IDC_STATUS_TRAY_KEEP_CHROME_RUNNING_IN_BACKGROUND
,
763 PrefService
* service
= g_browser_process
->local_state();
766 service
->IsUserModifiablePreference(prefs::kBackgroundModeEnabled
);
767 menu
->SetCommandIdEnabled(IDC_STATUS_TRAY_KEEP_CHROME_RUNNING_IN_BACKGROUND
,
770 menu
->AddItemWithStringId(IDC_EXIT
, IDS_EXIT
);
772 context_menu_
= menu
.get();
773 status_icon_
->SetContextMenu(menu
.Pass());
776 void BackgroundModeManager::RemoveStatusTrayIcon() {
778 status_tray_
->RemoveStatusIcon(status_icon_
);
780 context_menu_
= NULL
;
783 BackgroundModeManager::BackgroundModeData
*
784 BackgroundModeManager::GetBackgroundModeData(Profile
* const profile
) const {
785 DCHECK(background_mode_data_
.find(profile
) != background_mode_data_
.end());
786 return background_mode_data_
.find(profile
)->second
.get();
789 BackgroundModeManager::BackgroundModeInfoMap::iterator
790 BackgroundModeManager::GetBackgroundModeIterator(
791 const base::string16
& profile_name
) {
792 BackgroundModeInfoMap::iterator profile_it
=
793 background_mode_data_
.end();
794 for (BackgroundModeInfoMap::iterator it
=
795 background_mode_data_
.begin();
796 it
!= background_mode_data_
.end();
798 if (it
->second
->name() == profile_name
) {
805 bool BackgroundModeManager::IsBackgroundModePrefEnabled() const {
806 PrefService
* service
= g_browser_process
->local_state();
808 return service
->GetBoolean(prefs::kBackgroundModeEnabled
);