Fire an error if a pref used in the UI is missing once all prefs are fetched.
[chromium-blink-merge.git] / chrome / browser / notifications / message_center_settings_controller.cc
blob140532652554bbf0c317eac011d8b25e4378a919
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/message_loop/message_loop_proxy.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/task/cancelable_task_tracker.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 FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(
241 profile, ServiceAccessType::EXPLICIT_ACCESS);
242 favicon_tracker_.reset(new base::CancelableTaskTracker());
243 patterns_.clear();
244 for (ContentSettingsForOneType::const_iterator iter = settings.begin();
245 iter != settings.end(); ++iter) {
246 if (iter->primary_pattern == ContentSettingsPattern::Wildcard() &&
247 iter->secondary_pattern == ContentSettingsPattern::Wildcard() &&
248 iter->source != "preference") {
249 continue;
252 std::string url_pattern = iter->primary_pattern.ToString();
253 base::string16 name = base::UTF8ToUTF16(url_pattern);
254 GURL url(url_pattern);
255 NotifierId notifier_id(url);
256 notifiers->push_back(new Notifier(
257 notifier_id,
258 name,
259 notification_service->IsNotifierEnabled(notifier_id)));
260 patterns_[name] = iter->primary_pattern;
261 // Note that favicon service obtains the favicon from history. This means
262 // that it will fail to obtain the image if there are no history data for
263 // that URL.
264 favicon_service->GetFaviconImageForPageURL(
265 url,
266 base::Bind(&MessageCenterSettingsController::OnFaviconLoaded,
267 base::Unretained(this),
268 url),
269 favicon_tracker_.get());
272 // Screenshot notification feature is only for ChromeOS. See crbug.com/238358
273 #if defined(OS_CHROMEOS)
274 const base::string16 screenshot_name =
275 l10n_util::GetStringUTF16(IDS_MESSAGE_CENTER_NOTIFIER_SCREENSHOT_NAME);
276 NotifierId screenshot_notifier_id(
277 NotifierId::SYSTEM_COMPONENT, ash::system_notifier::kNotifierScreenshot);
278 Notifier* const screenshot_notifier = new Notifier(
279 screenshot_notifier_id,
280 screenshot_name,
281 notification_service->IsNotifierEnabled(screenshot_notifier_id));
282 screenshot_notifier->icon =
283 ui::ResourceBundle::GetSharedInstance().GetImageNamed(
284 IDR_SCREENSHOT_NOTIFICATION_ICON);
285 notifiers->push_back(screenshot_notifier);
286 #endif
288 UErrorCode error = U_ZERO_ERROR;
289 scoped_ptr<icu::Collator> collator(icu::Collator::createInstance(error));
290 scoped_ptr<NotifierComparator> comparator(
291 new NotifierComparator(U_SUCCESS(error) ? collator.get() : NULL));
293 std::sort(notifiers->begin(), notifiers->end(), *comparator);
296 void MessageCenterSettingsController::SetNotifierEnabled(
297 const Notifier& notifier,
298 bool enabled) {
299 DCHECK_LT(current_notifier_group_, notifier_groups_.size());
300 Profile* profile = notifier_groups_[current_notifier_group_]->profile();
302 DesktopNotificationService* notification_service =
303 DesktopNotificationServiceFactory::GetForProfile(profile);
305 if (notifier.notifier_id.type == NotifierId::WEB_PAGE) {
306 // WEB_PAGE notifier cannot handle in DesktopNotificationService
307 // since it has the exact URL pattern.
308 // TODO(mukai): fix this.
309 ContentSetting default_setting =
310 profile->GetHostContentSettingsMap()->GetDefaultContentSetting(
311 CONTENT_SETTINGS_TYPE_NOTIFICATIONS, NULL);
313 DCHECK(default_setting == CONTENT_SETTING_ALLOW ||
314 default_setting == CONTENT_SETTING_BLOCK ||
315 default_setting == CONTENT_SETTING_ASK);
316 if ((enabled && default_setting != CONTENT_SETTING_ALLOW) ||
317 (!enabled && default_setting == CONTENT_SETTING_ALLOW)) {
318 if (notifier.notifier_id.url.is_valid()) {
319 if (enabled)
320 DesktopNotificationProfileUtil::GrantPermission(
321 profile, notifier.notifier_id.url);
322 else
323 DesktopNotificationProfileUtil::DenyPermission(
324 profile, notifier.notifier_id.url);
325 } else {
326 LOG(ERROR) << "Invalid url pattern: "
327 << notifier.notifier_id.url.spec();
329 } else {
330 std::map<base::string16, ContentSettingsPattern>::const_iterator iter =
331 patterns_.find(notifier.name);
332 if (iter != patterns_.end()) {
333 DesktopNotificationProfileUtil::ClearSetting(profile, iter->second);
334 } else {
335 LOG(ERROR) << "Invalid url pattern: "
336 << notifier.notifier_id.url.spec();
339 } else {
340 notification_service->SetNotifierEnabled(notifier.notifier_id, enabled);
342 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
343 observers_,
344 NotifierEnabledChanged(notifier.notifier_id, enabled));
347 void MessageCenterSettingsController::OnNotifierSettingsClosing() {
348 DCHECK(favicon_tracker_.get());
349 favicon_tracker_->TryCancelAll();
350 patterns_.clear();
353 bool MessageCenterSettingsController::NotifierHasAdvancedSettings(
354 const NotifierId& notifier_id) const {
355 // TODO(dewittj): Refactor this so that notifiers have a delegate that can
356 // handle this in a more appropriate location.
357 if (notifier_id.type != NotifierId::APPLICATION)
358 return false;
360 const std::string& extension_id = notifier_id.id;
362 if (notifier_groups_.size() < current_notifier_group_)
363 return false;
364 Profile* profile = notifier_groups_[current_notifier_group_]->profile();
366 extensions::EventRouter* event_router = extensions::EventRouter::Get(profile);
368 return event_router->ExtensionHasEventListener(
369 extension_id, extensions::api::notifications::OnShowSettings::kEventName);
372 void MessageCenterSettingsController::OnNotifierAdvancedSettingsRequested(
373 const NotifierId& notifier_id,
374 const std::string* notification_id) {
375 // TODO(dewittj): Refactor this so that notifiers have a delegate that can
376 // handle this in a more appropriate location.
377 if (notifier_id.type != NotifierId::APPLICATION)
378 return;
380 const std::string& extension_id = notifier_id.id;
382 if (notifier_groups_.size() < current_notifier_group_)
383 return;
384 Profile* profile = notifier_groups_[current_notifier_group_]->profile();
386 extensions::EventRouter* event_router = extensions::EventRouter::Get(profile);
387 scoped_ptr<base::ListValue> args(new base::ListValue());
389 scoped_ptr<extensions::Event> event(new extensions::Event(
390 extensions::api::notifications::OnShowSettings::kEventName, args.Pass()));
391 event_router->DispatchEventToExtension(extension_id, event.Pass());
394 void MessageCenterSettingsController::OnFaviconLoaded(
395 const GURL& url,
396 const favicon_base::FaviconImageResult& favicon_result) {
397 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
398 observers_,
399 UpdateIconImage(NotifierId(url), favicon_result.image));
403 #if defined(OS_CHROMEOS)
404 void MessageCenterSettingsController::ActiveUserChanged(
405 const user_manager::User* active_user) {
406 RebuildNotifierGroups(false);
408 #endif
410 void MessageCenterSettingsController::SetAppImage(const std::string& id,
411 const gfx::ImageSkia& image) {
412 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
413 observers_,
414 UpdateIconImage(NotifierId(NotifierId::APPLICATION, id),
415 gfx::Image(image)));
418 void MessageCenterSettingsController::Observe(
419 int type,
420 const content::NotificationSource& source,
421 const content::NotificationDetails& details) {
422 // GetOffTheRecordProfile() may create a new off-the-record profile, but that
423 // doesn't need to rebuild the groups.
424 if (type == chrome::NOTIFICATION_PROFILE_CREATED &&
425 content::Source<Profile>(source).ptr()->IsOffTheRecord()) {
426 return;
429 RebuildNotifierGroups(true);
432 void MessageCenterSettingsController::OnProfileAdded(
433 const base::FilePath& profile_path) {
434 RebuildNotifierGroups(true);
436 void MessageCenterSettingsController::OnProfileWasRemoved(
437 const base::FilePath& profile_path,
438 const base::string16& profile_name) {
439 RebuildNotifierGroups(true);
441 void MessageCenterSettingsController::OnProfileNameChanged(
442 const base::FilePath& profile_path,
443 const base::string16& old_profile_name) {
444 RebuildNotifierGroups(true);
446 void MessageCenterSettingsController::OnProfileUserNameChanged(
447 const base::FilePath& profile_path) {
448 RebuildNotifierGroups(true);
451 #if defined(OS_CHROMEOS)
452 void MessageCenterSettingsController::CreateNotifierGroupForGuestLogin() {
453 // Already created.
454 if (!notifier_groups_.empty())
455 return;
457 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
458 // |notifier_groups_| can be empty in login screen too.
459 if (!user_manager->IsLoggedInAsGuest())
460 return;
462 user_manager::User* user = user_manager->GetActiveUser();
463 Profile* profile =
464 chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(user);
465 DCHECK(profile);
466 notifier_groups_.push_back(
467 new message_center::ProfileNotifierGroup(gfx::Image(user->GetImage()),
468 user->GetDisplayName(),
469 user->GetDisplayName(),
471 profile));
473 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
474 observers_,
475 NotifierGroupChanged());
477 #endif
479 void MessageCenterSettingsController::RebuildNotifierGroups(bool notify) {
480 notifier_groups_.clear();
481 current_notifier_group_ = 0;
483 const size_t count = profile_info_cache_->GetNumberOfProfiles();
484 for (size_t i = 0; i < count; ++i) {
485 scoped_ptr<message_center::ProfileNotifierGroup> group(
486 new message_center::ProfileNotifierGroup(
487 profile_info_cache_->GetAvatarIconOfProfileAtIndex(i),
488 profile_info_cache_->GetNameOfProfileAtIndex(i),
489 profile_info_cache_->GetUserNameOfProfileAtIndex(i),
491 profile_info_cache_->GetPathOfProfileAtIndex(i)));
492 if (group->profile() == NULL)
493 continue;
495 #if defined(OS_CHROMEOS)
496 // Allows the active user only.
497 // UserManager may not exist in some tests.
498 if (user_manager::UserManager::IsInitialized()) {
499 user_manager::UserManager* user_manager =
500 user_manager::UserManager::Get();
501 if (chromeos::ProfileHelper::Get()->GetUserByProfile(group->profile()) !=
502 user_manager->GetActiveUser()) {
503 continue;
507 // In ChromeOS, the login screen first creates a dummy profile which is not
508 // actually used, and then the real profile for the user is created when
509 // login (or turns into kiosk mode). This profile should be skipped.
510 if (chromeos::ProfileHelper::IsSigninProfile(group->profile()))
511 continue;
512 #endif
513 notifier_groups_.push_back(group.release());
516 #if defined(OS_CHROMEOS)
517 // ChromeOS guest login cannot get the profile from the for-loop above, so
518 // get the group here.
519 if (notifier_groups_.empty() && user_manager::UserManager::IsInitialized() &&
520 user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
521 // Do not invoke CreateNotifierGroupForGuestLogin() directly. In some tests,
522 // this method may be called before the primary profile is created, which
523 // means ProfileHelper::Get()->GetProfileByUser() will create a new primary
524 // profile. But creating a primary profile causes an Observe() before
525 // registering it as the primary one, which causes this method which causes
526 // another creating a primary profile, and causes an infinite loop.
527 // Thus, it would be better to delay creating group for guest login.
528 base::MessageLoopProxy::current()->PostTask(
529 FROM_HERE,
530 base::Bind(
531 &MessageCenterSettingsController::CreateNotifierGroupForGuestLogin,
532 weak_factory_.GetWeakPtr()));
534 #endif
536 if (notify) {
537 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
538 observers_,
539 NotifierGroupChanged());