Check USB device path access when prompting users to select a device.
[chromium-blink-merge.git] / chrome / browser / notifications / message_center_settings_controller.cc
blob18203cd973fe2747a57cf5ab6fb84b24bb2d307e
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 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);
317 if ((enabled && default_setting != CONTENT_SETTING_ALLOW) ||
318 (!enabled && default_setting == CONTENT_SETTING_ALLOW)) {
319 if (notifier.notifier_id.url.is_valid()) {
320 if (enabled)
321 DesktopNotificationProfileUtil::GrantPermission(
322 profile, notifier.notifier_id.url);
323 else
324 DesktopNotificationProfileUtil::DenyPermission(
325 profile, notifier.notifier_id.url);
326 } else {
327 LOG(ERROR) << "Invalid url pattern: "
328 << notifier.notifier_id.url.spec();
330 } else {
331 std::map<base::string16, ContentSettingsPattern>::const_iterator iter =
332 patterns_.find(notifier.name);
333 if (iter != patterns_.end()) {
334 DesktopNotificationProfileUtil::ClearSetting(profile, iter->second);
335 } else {
336 LOG(ERROR) << "Invalid url pattern: "
337 << notifier.notifier_id.url.spec();
340 } else {
341 notification_service->SetNotifierEnabled(notifier.notifier_id, enabled);
343 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
344 observers_,
345 NotifierEnabledChanged(notifier.notifier_id, enabled));
348 void MessageCenterSettingsController::OnNotifierSettingsClosing() {
349 DCHECK(favicon_tracker_.get());
350 favicon_tracker_->TryCancelAll();
351 patterns_.clear();
354 bool MessageCenterSettingsController::NotifierHasAdvancedSettings(
355 const NotifierId& notifier_id) const {
356 // TODO(dewittj): Refactor this so that notifiers have a delegate that can
357 // handle this in a more appropriate location.
358 if (notifier_id.type != NotifierId::APPLICATION)
359 return false;
361 const std::string& extension_id = notifier_id.id;
363 if (notifier_groups_.size() < current_notifier_group_)
364 return false;
365 Profile* profile = notifier_groups_[current_notifier_group_]->profile();
367 extensions::EventRouter* event_router = extensions::EventRouter::Get(profile);
369 return event_router->ExtensionHasEventListener(
370 extension_id, extensions::api::notifications::OnShowSettings::kEventName);
373 void MessageCenterSettingsController::OnNotifierAdvancedSettingsRequested(
374 const NotifierId& notifier_id,
375 const std::string* notification_id) {
376 // TODO(dewittj): Refactor this so that notifiers have a delegate that can
377 // handle this in a more appropriate location.
378 if (notifier_id.type != NotifierId::APPLICATION)
379 return;
381 const std::string& extension_id = notifier_id.id;
383 if (notifier_groups_.size() < current_notifier_group_)
384 return;
385 Profile* profile = notifier_groups_[current_notifier_group_]->profile();
387 extensions::EventRouter* event_router = extensions::EventRouter::Get(profile);
388 scoped_ptr<base::ListValue> args(new base::ListValue());
390 scoped_ptr<extensions::Event> event(new extensions::Event(
391 extensions::api::notifications::OnShowSettings::kEventName, args.Pass()));
392 event_router->DispatchEventToExtension(extension_id, event.Pass());
395 void MessageCenterSettingsController::OnFaviconLoaded(
396 const GURL& url,
397 const favicon_base::FaviconImageResult& favicon_result) {
398 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
399 observers_,
400 UpdateIconImage(NotifierId(url), favicon_result.image));
404 #if defined(OS_CHROMEOS)
405 void MessageCenterSettingsController::ActiveUserChanged(
406 const user_manager::User* active_user) {
407 RebuildNotifierGroups(false);
409 #endif
411 void MessageCenterSettingsController::SetAppImage(const std::string& id,
412 const gfx::ImageSkia& image) {
413 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
414 observers_,
415 UpdateIconImage(NotifierId(NotifierId::APPLICATION, id),
416 gfx::Image(image)));
419 void MessageCenterSettingsController::Observe(
420 int type,
421 const content::NotificationSource& source,
422 const content::NotificationDetails& details) {
423 // GetOffTheRecordProfile() may create a new off-the-record profile, but that
424 // doesn't need to rebuild the groups.
425 if (type == chrome::NOTIFICATION_PROFILE_CREATED &&
426 content::Source<Profile>(source).ptr()->IsOffTheRecord()) {
427 return;
430 RebuildNotifierGroups(true);
433 void MessageCenterSettingsController::OnProfileAdded(
434 const base::FilePath& profile_path) {
435 RebuildNotifierGroups(true);
437 void MessageCenterSettingsController::OnProfileWasRemoved(
438 const base::FilePath& profile_path,
439 const base::string16& profile_name) {
440 RebuildNotifierGroups(true);
442 void MessageCenterSettingsController::OnProfileNameChanged(
443 const base::FilePath& profile_path,
444 const base::string16& old_profile_name) {
445 RebuildNotifierGroups(true);
447 void MessageCenterSettingsController::OnProfileUserNameChanged(
448 const base::FilePath& profile_path) {
449 RebuildNotifierGroups(true);
452 #if defined(OS_CHROMEOS)
453 void MessageCenterSettingsController::CreateNotifierGroupForGuestLogin() {
454 // Already created.
455 if (!notifier_groups_.empty())
456 return;
458 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
459 // |notifier_groups_| can be empty in login screen too.
460 if (!user_manager->IsLoggedInAsGuest())
461 return;
463 user_manager::User* user = user_manager->GetActiveUser();
464 Profile* profile =
465 chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(user);
466 DCHECK(profile);
467 notifier_groups_.push_back(
468 new message_center::ProfileNotifierGroup(gfx::Image(user->GetImage()),
469 user->GetDisplayName(),
470 user->GetDisplayName(),
472 profile));
474 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
475 observers_,
476 NotifierGroupChanged());
478 #endif
480 void MessageCenterSettingsController::RebuildNotifierGroups(bool notify) {
481 notifier_groups_.clear();
482 current_notifier_group_ = 0;
484 const size_t count = profile_info_cache_->GetNumberOfProfiles();
485 for (size_t i = 0; i < count; ++i) {
486 scoped_ptr<message_center::ProfileNotifierGroup> group(
487 new message_center::ProfileNotifierGroup(
488 profile_info_cache_->GetAvatarIconOfProfileAtIndex(i),
489 profile_info_cache_->GetNameOfProfileAtIndex(i),
490 profile_info_cache_->GetUserNameOfProfileAtIndex(i),
492 profile_info_cache_->GetPathOfProfileAtIndex(i)));
493 if (group->profile() == NULL)
494 continue;
496 #if defined(OS_CHROMEOS)
497 // Allows the active user only.
498 // UserManager may not exist in some tests.
499 if (user_manager::UserManager::IsInitialized()) {
500 user_manager::UserManager* user_manager =
501 user_manager::UserManager::Get();
502 if (chromeos::ProfileHelper::Get()->GetUserByProfile(group->profile()) !=
503 user_manager->GetActiveUser()) {
504 continue;
508 // In ChromeOS, the login screen first creates a dummy profile which is not
509 // actually used, and then the real profile for the user is created when
510 // login (or turns into kiosk mode). This profile should be skipped.
511 if (chromeos::ProfileHelper::IsSigninProfile(group->profile()))
512 continue;
513 #endif
514 notifier_groups_.push_back(group.release());
517 #if defined(OS_CHROMEOS)
518 // ChromeOS guest login cannot get the profile from the for-loop above, so
519 // get the group here.
520 if (notifier_groups_.empty() && user_manager::UserManager::IsInitialized() &&
521 user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
522 // Do not invoke CreateNotifierGroupForGuestLogin() directly. In some tests,
523 // this method may be called before the primary profile is created, which
524 // means ProfileHelper::Get()->GetProfileByUser() will create a new primary
525 // profile. But creating a primary profile causes an Observe() before
526 // registering it as the primary one, which causes this method which causes
527 // another creating a primary profile, and causes an infinite loop.
528 // Thus, it would be better to delay creating group for guest login.
529 base::MessageLoopProxy::current()->PostTask(
530 FROM_HERE,
531 base::Bind(
532 &MessageCenterSettingsController::CreateNotifierGroupForGuestLogin,
533 weak_factory_.GetWeakPtr()));
535 #endif
537 if (notify) {
538 FOR_EACH_OBSERVER(message_center::NotifierSettingsObserver,
539 observers_,
540 NotifierGroupChanged());