No dual_mode on Win10+ shortcuts.
[chromium-blink-merge.git] / chrome / browser / notifications / message_center_settings_controller.cc
blob5a59cbfc3c469a4312f53eedf810daeb77f3f910
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/notifications/message_center_settings_controller.h"
7 #include <algorithm>
9 #include "base/command_line.h"
10 #include "base/i18n/string_compare.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/task/cancelable_task_tracker.h"
13 #include "base/thread_task_runner_handle.h"
14 #include "chrome/browser/browser_process.h"
15 #include "chrome/browser/chrome_notification_types.h"
16 #include "chrome/browser/extensions/app_icon_loader_impl.h"
17 #include "chrome/browser/favicon/favicon_service_factory.h"
18 #include "chrome/browser/notifications/desktop_notification_profile_util.h"
19 #include "chrome/browser/notifications/desktop_notification_service.h"
20 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
21 #include "chrome/browser/profiles/profile.h"
22 #include "chrome/browser/profiles/profile_info_cache.h"
23 #include "chrome/browser/profiles/profile_manager.h"
24 #include "chrome/common/extensions/api/notifications.h"
25 #include "chrome/common/extensions/extension_constants.h"
26 #include "components/content_settings/core/browser/host_content_settings_map.h"
27 #include "components/favicon/core/favicon_service.h"
28 #include "components/favicon_base/favicon_types.h"
29 #include "components/history/core/browser/history_types.h"
30 #include "content/public/browser/notification_service.h"
31 #include "content/public/browser/notification_source.h"
32 #include "extensions/browser/event_router.h"
33 #include "extensions/browser/extension_registry.h"
34 #include "extensions/common/constants.h"
35 #include "extensions/common/extension.h"
36 #include "extensions/common/permissions/permissions_data.h"
37 #include "grit/theme_resources.h"
38 #include "ui/base/l10n/l10n_util.h"
39 #include "ui/base/resource/resource_bundle.h"
40 #include "ui/gfx/image/image.h"
41 #include "ui/message_center/message_center_style.h"
42 #include "ui/strings/grit/ui_strings.h"
44 #if defined(OS_CHROMEOS)
45 #include "ash/system/system_notifier.h"
46 #include "chrome/browser/chromeos/profiles/profile_helper.h"
47 #endif
49 using message_center::Notifier;
50 using message_center::NotifierId;
52 namespace message_center {
54 class ProfileNotifierGroup : public message_center::NotifierGroup {
55 public:
56 ProfileNotifierGroup(const gfx::Image& icon,
57 const base::string16& display_name,
58 const base::string16& login_info,
59 size_t index,
60 const base::FilePath& profile_path);
61 ProfileNotifierGroup(const gfx::Image& icon,
62 const base::string16& display_name,
63 const base::string16& login_info,
64 size_t index,
65 Profile* profile);
66 virtual ~ProfileNotifierGroup() {}
68 Profile* profile() const { return profile_; }
70 private:
71 Profile* profile_;
74 ProfileNotifierGroup::ProfileNotifierGroup(const gfx::Image& icon,
75 const base::string16& display_name,
76 const base::string16& login_info,
77 size_t index,
78 const base::FilePath& profile_path)
79 : message_center::NotifierGroup(icon, display_name, login_info, index),
80 profile_(NULL) {
81 // Try to get the profile
82 profile_ =
83 g_browser_process->profile_manager()->GetProfileByPath(profile_path);
86 ProfileNotifierGroup::ProfileNotifierGroup(const gfx::Image& icon,
87 const base::string16& display_name,
88 const base::string16& login_info,
89 size_t index,
90 Profile* profile)
91 : message_center::NotifierGroup(icon, display_name, login_info, index),
92 profile_(profile) {
95 } // namespace message_center
97 namespace {
98 class NotifierComparator {
99 public:
100 explicit NotifierComparator(icu::Collator* collator) : collator_(collator) {}
102 bool operator() (Notifier* n1, Notifier* n2) {
103 if (n1->notifier_id.type != n2->notifier_id.type)
104 return n1->notifier_id.type < n2->notifier_id.type;
106 if (collator_) {
107 return base::i18n::CompareString16WithCollator(*collator_, n1->name,
108 n2->name) == UCOL_LESS;
110 return n1->name < n2->name;
113 private:
114 icu::Collator* collator_;
117 } // namespace
119 MessageCenterSettingsController::MessageCenterSettingsController(
120 ProfileInfoCache* profile_info_cache)
121 : current_notifier_group_(0),
122 profile_info_cache_(profile_info_cache),
123 weak_factory_(this) {
124 DCHECK(profile_info_cache_);
125 // The following events all represent changes that may need to be reflected in
126 // the profile selector context menu, so listen for them all. We'll just
127 // rebuild the list when we get any of them.
128 registrar_.Add(this,
129 chrome::NOTIFICATION_PROFILE_CREATED,
130 content::NotificationService::AllBrowserContextsAndSources());
131 registrar_.Add(this,
132 chrome::NOTIFICATION_PROFILE_ADDED,
133 content::NotificationService::AllBrowserContextsAndSources());
134 registrar_.Add(this,
135 chrome::NOTIFICATION_PROFILE_DESTROYED,
136 content::NotificationService::AllBrowserContextsAndSources());
137 g_browser_process->profile_manager()->GetProfileInfoCache().AddObserver(this);
138 RebuildNotifierGroups(false);
140 #if defined(OS_CHROMEOS)
141 // UserManager may not exist in some tests.
142 if (user_manager::UserManager::IsInitialized())
143 user_manager::UserManager::Get()->AddSessionStateObserver(this);
144 #endif
147 MessageCenterSettingsController::~MessageCenterSettingsController() {
148 g_browser_process->profile_manager()->
149 GetProfileInfoCache().RemoveObserver(this);
150 #if defined(OS_CHROMEOS)
151 // UserManager may not exist in some tests.
152 if (user_manager::UserManager::IsInitialized())
153 user_manager::UserManager::Get()->RemoveSessionStateObserver(this);
154 #endif
157 void MessageCenterSettingsController::AddObserver(
158 message_center::NotifierSettingsObserver* observer) {
159 observers_.AddObserver(observer);
162 void MessageCenterSettingsController::RemoveObserver(
163 message_center::NotifierSettingsObserver* observer) {
164 observers_.RemoveObserver(observer);
167 size_t MessageCenterSettingsController::GetNotifierGroupCount() const {
168 return notifier_groups_.size();
171 const message_center::NotifierGroup&
172 MessageCenterSettingsController::GetNotifierGroupAt(size_t index) const {
173 DCHECK_LT(index, notifier_groups_.size());
174 return *(notifier_groups_[index]);
177 bool MessageCenterSettingsController::IsNotifierGroupActiveAt(
178 size_t index) const {
179 return current_notifier_group_ == index;
182 const message_center::NotifierGroup&
183 MessageCenterSettingsController::GetActiveNotifierGroup() const {
184 DCHECK_LT(current_notifier_group_, notifier_groups_.size());
185 return *(notifier_groups_[current_notifier_group_]);
188 void MessageCenterSettingsController::SwitchToNotifierGroup(size_t index) {
189 DCHECK_LT(index, notifier_groups_.size());
190 if (current_notifier_group_ == index)
191 return;
193 current_notifier_group_ = index;
194 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
195 observers_,
196 NotifierGroupChanged());
199 void MessageCenterSettingsController::GetNotifierList(
200 std::vector<Notifier*>* notifiers) {
201 DCHECK(notifiers);
202 if (notifier_groups_.size() <= current_notifier_group_)
203 return;
204 // Temporarily use the last used profile to prevent chrome from crashing when
205 // the default profile is not loaded.
206 Profile* profile = notifier_groups_[current_notifier_group_]->profile();
208 DesktopNotificationService* notification_service =
209 DesktopNotificationServiceFactory::GetForProfile(profile);
211 const extensions::ExtensionSet& extension_set =
212 extensions::ExtensionRegistry::Get(profile)->enabled_extensions();
213 // The extension icon size has to be 32x32 at least to load bigger icons if
214 // the icon doesn't exist for the specified size, and in that case it falls
215 // back to the default icon. The fetched icon will be resized in the settings
216 // dialog. See chrome/browser/extensions/extension_icon_image.cc and
217 // crbug.com/222931
218 app_icon_loader_.reset(new extensions::AppIconLoaderImpl(
219 profile, extension_misc::EXTENSION_ICON_SMALL, this));
220 for (extensions::ExtensionSet::const_iterator iter = extension_set.begin();
221 iter != extension_set.end();
222 ++iter) {
223 const extensions::Extension* extension = iter->get();
224 if (!extension->permissions_data()->HasAPIPermission(
225 extensions::APIPermission::kNotifications)) {
226 continue;
229 NotifierId notifier_id(NotifierId::APPLICATION, extension->id());
230 notifiers->push_back(new Notifier(
231 notifier_id,
232 base::UTF8ToUTF16(extension->name()),
233 notification_service->IsNotifierEnabled(notifier_id)));
234 app_icon_loader_->FetchImage(extension->id());
237 ContentSettingsForOneType settings;
238 DesktopNotificationProfileUtil::GetNotificationsSettings(profile, &settings);
240 favicon::FaviconService* favicon_service =
241 FaviconServiceFactory::GetForProfile(profile,
242 ServiceAccessType::EXPLICIT_ACCESS);
243 favicon_tracker_.reset(new base::CancelableTaskTracker());
244 patterns_.clear();
245 for (ContentSettingsForOneType::const_iterator iter = settings.begin();
246 iter != settings.end(); ++iter) {
247 if (iter->primary_pattern == ContentSettingsPattern::Wildcard() &&
248 iter->secondary_pattern == ContentSettingsPattern::Wildcard() &&
249 iter->source != "preference") {
250 continue;
253 std::string url_pattern = iter->primary_pattern.ToString();
254 base::string16 name = base::UTF8ToUTF16(url_pattern);
255 GURL url(url_pattern);
256 NotifierId notifier_id(url);
257 notifiers->push_back(new Notifier(
258 notifier_id,
259 name,
260 notification_service->IsNotifierEnabled(notifier_id)));
261 patterns_[name] = iter->primary_pattern;
262 // Note that favicon service obtains the favicon from history. This means
263 // that it will fail to obtain the image if there are no history data for
264 // that URL.
265 favicon_service->GetFaviconImageForPageURL(
266 url,
267 base::Bind(&MessageCenterSettingsController::OnFaviconLoaded,
268 base::Unretained(this),
269 url),
270 favicon_tracker_.get());
273 // Screenshot notification feature is only for ChromeOS. See crbug.com/238358
274 #if defined(OS_CHROMEOS)
275 const base::string16 screenshot_name =
276 l10n_util::GetStringUTF16(IDS_MESSAGE_CENTER_NOTIFIER_SCREENSHOT_NAME);
277 NotifierId screenshot_notifier_id(
278 NotifierId::SYSTEM_COMPONENT, ash::system_notifier::kNotifierScreenshot);
279 Notifier* const screenshot_notifier = new Notifier(
280 screenshot_notifier_id,
281 screenshot_name,
282 notification_service->IsNotifierEnabled(screenshot_notifier_id));
283 screenshot_notifier->icon =
284 ui::ResourceBundle::GetSharedInstance().GetImageNamed(
285 IDR_SCREENSHOT_NOTIFICATION_ICON);
286 notifiers->push_back(screenshot_notifier);
287 #endif
289 UErrorCode error = U_ZERO_ERROR;
290 scoped_ptr<icu::Collator> collator(icu::Collator::createInstance(error));
291 scoped_ptr<NotifierComparator> comparator(
292 new NotifierComparator(U_SUCCESS(error) ? collator.get() : NULL));
294 std::sort(notifiers->begin(), notifiers->end(), *comparator);
297 void MessageCenterSettingsController::SetNotifierEnabled(
298 const Notifier& notifier,
299 bool enabled) {
300 DCHECK_LT(current_notifier_group_, notifier_groups_.size());
301 Profile* profile = notifier_groups_[current_notifier_group_]->profile();
303 DesktopNotificationService* notification_service =
304 DesktopNotificationServiceFactory::GetForProfile(profile);
306 if (notifier.notifier_id.type == NotifierId::WEB_PAGE) {
307 // WEB_PAGE notifier cannot handle in DesktopNotificationService
308 // since it has the exact URL pattern.
309 // TODO(mukai): fix this.
310 ContentSetting default_setting =
311 profile->GetHostContentSettingsMap()->GetDefaultContentSetting(
312 CONTENT_SETTINGS_TYPE_NOTIFICATIONS, NULL);
314 DCHECK(default_setting == CONTENT_SETTING_ALLOW ||
315 default_setting == CONTENT_SETTING_BLOCK ||
316 default_setting == CONTENT_SETTING_ASK);
318 // The content setting for notifications needs to clear when it changes to
319 // the default value or get explicitly set when it differs from the default.
320 bool differs_from_default_value =
321 (default_setting != CONTENT_SETTING_ALLOW && enabled) ||
322 (default_setting == CONTENT_SETTING_ALLOW && !enabled);
324 if (differs_from_default_value) {
325 if (notifier.notifier_id.url.is_valid()) {
326 if (enabled) {
327 DesktopNotificationProfileUtil::GrantPermission(
328 profile, notifier.notifier_id.url);
329 } else {
330 DesktopNotificationProfileUtil::DenyPermission(
331 profile, notifier.notifier_id.url);
333 } else {
334 LOG(ERROR) << "Invalid url pattern: "
335 << notifier.notifier_id.url.spec();
337 } else {
338 ContentSettingsPattern pattern;
340 const auto& iter = patterns_.find(notifier.name);
341 if (iter != patterns_.end()) {
342 pattern = iter->second;
343 } else if (notifier.notifier_id.url.is_valid()) {
344 pattern =
345 ContentSettingsPattern::FromURLNoWildcard(notifier.notifier_id.url);
346 } else {
347 LOG(ERROR) << "Invalid url pattern: "
348 << notifier.notifier_id.url.spec();
351 if (pattern.IsValid())
352 DesktopNotificationProfileUtil::ClearSetting(profile, pattern);
354 } else {
355 notification_service->SetNotifierEnabled(notifier.notifier_id, enabled);
357 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
358 observers_,
359 NotifierEnabledChanged(notifier.notifier_id, enabled));
362 void MessageCenterSettingsController::OnNotifierSettingsClosing() {
363 DCHECK(favicon_tracker_.get());
364 favicon_tracker_->TryCancelAll();
365 patterns_.clear();
368 bool MessageCenterSettingsController::NotifierHasAdvancedSettings(
369 const NotifierId& notifier_id) const {
370 // TODO(dewittj): Refactor this so that notifiers have a delegate that can
371 // handle this in a more appropriate location.
372 if (notifier_id.type != NotifierId::APPLICATION)
373 return false;
375 const std::string& extension_id = notifier_id.id;
377 if (notifier_groups_.size() < current_notifier_group_)
378 return false;
379 Profile* profile = notifier_groups_[current_notifier_group_]->profile();
381 extensions::EventRouter* event_router = extensions::EventRouter::Get(profile);
383 return event_router->ExtensionHasEventListener(
384 extension_id, extensions::api::notifications::OnShowSettings::kEventName);
387 void MessageCenterSettingsController::OnNotifierAdvancedSettingsRequested(
388 const NotifierId& notifier_id,
389 const std::string* notification_id) {
390 // TODO(dewittj): Refactor this so that notifiers have a delegate that can
391 // handle this in a more appropriate location.
392 if (notifier_id.type != NotifierId::APPLICATION)
393 return;
395 const std::string& extension_id = notifier_id.id;
397 if (notifier_groups_.size() < current_notifier_group_)
398 return;
399 Profile* profile = notifier_groups_[current_notifier_group_]->profile();
401 extensions::EventRouter* event_router = extensions::EventRouter::Get(profile);
402 scoped_ptr<base::ListValue> args(new base::ListValue());
404 scoped_ptr<extensions::Event> event(new extensions::Event(
405 extensions::events::NOTIFICATIONS_ON_SHOW_SETTINGS,
406 extensions::api::notifications::OnShowSettings::kEventName, args.Pass()));
407 event_router->DispatchEventToExtension(extension_id, event.Pass());
410 void MessageCenterSettingsController::OnFaviconLoaded(
411 const GURL& url,
412 const favicon_base::FaviconImageResult& favicon_result) {
413 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
414 observers_,
415 UpdateIconImage(NotifierId(url), favicon_result.image));
419 #if defined(OS_CHROMEOS)
420 void MessageCenterSettingsController::ActiveUserChanged(
421 const user_manager::User* active_user) {
422 RebuildNotifierGroups(false);
424 #endif
426 void MessageCenterSettingsController::SetAppImage(const std::string& id,
427 const gfx::ImageSkia& image) {
428 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
429 observers_,
430 UpdateIconImage(NotifierId(NotifierId::APPLICATION, id),
431 gfx::Image(image)));
434 void MessageCenterSettingsController::Observe(
435 int type,
436 const content::NotificationSource& source,
437 const content::NotificationDetails& details) {
438 // GetOffTheRecordProfile() may create a new off-the-record profile, but that
439 // doesn't need to rebuild the groups.
440 if (type == chrome::NOTIFICATION_PROFILE_CREATED &&
441 content::Source<Profile>(source).ptr()->IsOffTheRecord()) {
442 return;
445 RebuildNotifierGroups(true);
448 void MessageCenterSettingsController::OnProfileAdded(
449 const base::FilePath& profile_path) {
450 RebuildNotifierGroups(true);
452 void MessageCenterSettingsController::OnProfileWasRemoved(
453 const base::FilePath& profile_path,
454 const base::string16& profile_name) {
455 RebuildNotifierGroups(true);
457 void MessageCenterSettingsController::OnProfileNameChanged(
458 const base::FilePath& profile_path,
459 const base::string16& old_profile_name) {
460 RebuildNotifierGroups(true);
462 void MessageCenterSettingsController::OnProfileAuthInfoChanged(
463 const base::FilePath& profile_path) {
464 RebuildNotifierGroups(true);
467 #if defined(OS_CHROMEOS)
468 void MessageCenterSettingsController::CreateNotifierGroupForGuestLogin() {
469 // Already created.
470 if (!notifier_groups_.empty())
471 return;
473 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
474 // |notifier_groups_| can be empty in login screen too.
475 if (!user_manager->IsLoggedInAsGuest())
476 return;
478 user_manager::User* user = user_manager->GetActiveUser();
479 Profile* profile =
480 chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(user);
481 DCHECK(profile);
482 notifier_groups_.push_back(
483 new message_center::ProfileNotifierGroup(gfx::Image(user->GetImage()),
484 user->GetDisplayName(),
485 user->GetDisplayName(),
487 profile));
489 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
490 observers_,
491 NotifierGroupChanged());
493 #endif
495 void MessageCenterSettingsController::RebuildNotifierGroups(bool notify) {
496 notifier_groups_.clear();
497 current_notifier_group_ = 0;
499 const size_t count = profile_info_cache_->GetNumberOfProfiles();
500 for (size_t i = 0; i < count; ++i) {
501 scoped_ptr<message_center::ProfileNotifierGroup> group(
502 new message_center::ProfileNotifierGroup(
503 profile_info_cache_->GetAvatarIconOfProfileAtIndex(i),
504 profile_info_cache_->GetNameOfProfileAtIndex(i),
505 profile_info_cache_->GetUserNameOfProfileAtIndex(i),
507 profile_info_cache_->GetPathOfProfileAtIndex(i)));
508 if (group->profile() == NULL)
509 continue;
511 #if defined(OS_CHROMEOS)
512 // Allows the active user only.
513 // UserManager may not exist in some tests.
514 if (user_manager::UserManager::IsInitialized()) {
515 user_manager::UserManager* user_manager =
516 user_manager::UserManager::Get();
517 if (chromeos::ProfileHelper::Get()->GetUserByProfile(group->profile()) !=
518 user_manager->GetActiveUser()) {
519 continue;
523 // In ChromeOS, the login screen first creates a dummy profile which is not
524 // actually used, and then the real profile for the user is created when
525 // login (or turns into kiosk mode). This profile should be skipped.
526 if (chromeos::ProfileHelper::IsSigninProfile(group->profile()))
527 continue;
528 #endif
529 notifier_groups_.push_back(group.release());
532 #if defined(OS_CHROMEOS)
533 // ChromeOS guest login cannot get the profile from the for-loop above, so
534 // get the group here.
535 if (notifier_groups_.empty() && user_manager::UserManager::IsInitialized() &&
536 user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
537 // Do not invoke CreateNotifierGroupForGuestLogin() directly. In some tests,
538 // this method may be called before the primary profile is created, which
539 // means ProfileHelper::Get()->GetProfileByUser() will create a new primary
540 // profile. But creating a primary profile causes an Observe() before
541 // registering it as the primary one, which causes this method which causes
542 // another creating a primary profile, and causes an infinite loop.
543 // Thus, it would be better to delay creating group for guest login.
544 base::ThreadTaskRunnerHandle::Get()->PostTask(
545 FROM_HERE,
546 base::Bind(
547 &MessageCenterSettingsController::CreateNotifierGroupForGuestLogin,
548 weak_factory_.GetWeakPtr()));
550 #endif
552 if (notify) {
553 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
554 observers_,
555 NotifierGroupChanged());