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.
5 #include "chrome/browser/profiles/profile_info_cache.h"
8 #include "base/file_util.h"
9 #include "base/i18n/case_conversion.h"
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/prefs/pref_registry_simple.h"
13 #include "base/prefs/pref_service.h"
14 #include "base/prefs/scoped_user_pref_update.h"
15 #include "base/rand_util.h"
16 #include "base/stl_util.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_piece.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/values.h"
21 #include "chrome/browser/browser_process.h"
22 #include "chrome/browser/chrome_notification_types.h"
23 #include "chrome/browser/profiles/profile_avatar_downloader.h"
24 #include "chrome/browser/profiles/profile_avatar_icon_util.h"
25 #include "chrome/browser/profiles/profiles_state.h"
26 #include "chrome/common/pref_names.h"
27 #include "components/signin/core/common/profile_management_switches.h"
28 #include "content/public/browser/browser_thread.h"
29 #include "content/public/browser/notification_service.h"
30 #include "grit/generated_resources.h"
31 #include "grit/theme_resources.h"
32 #include "ui/base/l10n/l10n_util.h"
33 #include "ui/base/resource/resource_bundle.h"
34 #include "ui/gfx/image/image.h"
35 #include "ui/gfx/image/image_util.h"
37 using content::BrowserThread;
41 const char kNameKey[] = "name";
42 const char kShortcutNameKey[] = "shortcut_name";
43 const char kGAIANameKey[] = "gaia_name";
44 const char kGAIAGivenNameKey[] = "gaia_given_name";
45 const char kUserNameKey[] = "user_name";
46 const char kIsUsingDefaultName[] = "is_using_default_name";
47 const char kAvatarIconKey[] = "avatar_icon";
48 const char kAuthCredentialsKey[] = "local_auth_credentials";
49 const char kUseGAIAPictureKey[] = "use_gaia_picture";
50 const char kBackgroundAppsKey[] = "background_apps";
51 const char kGAIAPictureFileNameKey[] = "gaia_picture_file_name";
52 const char kIsSupervisedKey[] = "is_managed";
53 const char kIsOmittedFromProfileListKey[] = "is_omitted_from_profile_list";
54 const char kSigninRequiredKey[] = "signin_required";
55 const char kSupervisedUserId[] = "managed_user_id";
56 const char kProfileIsEphemeral[] = "is_ephemeral";
57 const char kActiveTimeKey[] = "active_time";
59 // First eight are generic icons, which use IDS_NUMBERED_PROFILE_NAME.
60 const int kDefaultNames[] = {
61 IDS_DEFAULT_AVATAR_NAME_8,
62 IDS_DEFAULT_AVATAR_NAME_9,
63 IDS_DEFAULT_AVATAR_NAME_10,
64 IDS_DEFAULT_AVATAR_NAME_11,
65 IDS_DEFAULT_AVATAR_NAME_12,
66 IDS_DEFAULT_AVATAR_NAME_13,
67 IDS_DEFAULT_AVATAR_NAME_14,
68 IDS_DEFAULT_AVATAR_NAME_15,
69 IDS_DEFAULT_AVATAR_NAME_16,
70 IDS_DEFAULT_AVATAR_NAME_17,
71 IDS_DEFAULT_AVATAR_NAME_18,
72 IDS_DEFAULT_AVATAR_NAME_19,
73 IDS_DEFAULT_AVATAR_NAME_20,
74 IDS_DEFAULT_AVATAR_NAME_21,
75 IDS_DEFAULT_AVATAR_NAME_22,
76 IDS_DEFAULT_AVATAR_NAME_23,
77 IDS_DEFAULT_AVATAR_NAME_24,
78 IDS_DEFAULT_AVATAR_NAME_25,
79 IDS_DEFAULT_AVATAR_NAME_26
82 typedef std::vector<unsigned char> ImageData;
84 // Writes |data| to disk and takes ownership of the pointer. On successful
85 // completion, it runs |callback|.
86 void SaveBitmap(scoped_ptr<ImageData> data,
87 const base::FilePath& image_path,
88 const base::Closure& callback) {
89 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
91 // Make sure the destination directory exists.
92 base::FilePath dir = image_path.DirName();
93 if (!base::DirectoryExists(dir) && !base::CreateDirectory(dir)) {
94 LOG(ERROR) << "Failed to create parent directory.";
98 if (base::WriteFile(image_path, reinterpret_cast<char*>(&(*data)[0]),
99 data->size()) == -1) {
100 LOG(ERROR) << "Failed to save image to file.";
104 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback);
107 // Reads a PNG from disk and decodes it. If the bitmap was successfully read
108 // from disk the then |out_image| will contain the bitmap image, otherwise it
110 void ReadBitmap(const base::FilePath& image_path,
111 gfx::Image** out_image) {
112 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
115 // If the path doesn't exist, don't even try reading it.
116 if (!base::PathExists(image_path))
119 std::string image_data;
120 if (!base::ReadFileToString(image_path, &image_data)) {
121 LOG(ERROR) << "Failed to read PNG file from disk.";
125 gfx::Image image = gfx::Image::CreateFrom1xPNGBytes(
126 base::RefCountedString::TakeString(&image_data));
127 if (image.IsEmpty()) {
128 LOG(ERROR) << "Failed to decode PNG file.";
132 *out_image = new gfx::Image(image);
135 void DeleteBitmap(const base::FilePath& image_path) {
136 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
137 base::DeleteFile(image_path, false);
140 bool IsDefaultName(const base::string16& name) {
141 // Check if it's a "First user" old-style name.
142 if (name == l10n_util::GetStringUTF16(IDS_DEFAULT_PROFILE_NAME))
145 // Check if it's one of the old-style profile names.
146 for (size_t i = 0; i < arraysize(kDefaultNames); ++i) {
147 if (name == l10n_util::GetStringUTF16(kDefaultNames[i]))
151 // Check whether it's one of the "Person %d" style names.
152 std::string default_name_format = l10n_util::GetStringFUTF8(
153 IDS_NEW_NUMBERED_PROFILE_NAME, base::string16()) + "%d";
155 int generic_profile_number; // Unused. Just a placeholder for sscanf.
156 int assignments = sscanf(base::UTF16ToUTF8(name).c_str(),
157 default_name_format.c_str(),
158 &generic_profile_number);
159 // Unless it matched the format, this is a custom name.
160 return assignments == 1;
165 ProfileInfoCache::ProfileInfoCache(PrefService* prefs,
166 const base::FilePath& user_data_dir)
168 user_data_dir_(user_data_dir) {
169 // Populate the cache
170 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
171 base::DictionaryValue* cache = update.Get();
172 for (base::DictionaryValue::Iterator it(*cache);
173 !it.IsAtEnd(); it.Advance()) {
174 base::DictionaryValue* info = NULL;
175 cache->GetDictionaryWithoutPathExpansion(it.key(), &info);
177 info->GetString(kNameKey, &name);
178 sorted_keys_.insert(FindPositionForProfile(it.key(), name), it.key());
179 // TODO(ibraaaa): delete this when 97% of our users are using M31.
180 // http://crbug.com/276163
181 bool is_supervised = false;
182 if (info->GetBoolean(kIsSupervisedKey, &is_supervised)) {
183 info->Remove(kIsSupervisedKey, NULL);
184 info->SetString(kSupervisedUserId,
185 is_supervised ? "DUMMY_ID" : std::string());
187 info->SetBoolean(kIsUsingDefaultName, IsDefaultName(name));
190 // If needed, start downloading the high-res avatars.
191 if (switches::IsNewAvatarMenu()) {
192 for (size_t i = 0; i < GetNumberOfProfiles(); i++) {
193 DownloadHighResAvatar(GetAvatarIconIndexOfProfileAtIndex(i),
194 GetPathOfProfileAtIndex(i));
199 ProfileInfoCache::~ProfileInfoCache() {
200 STLDeleteContainerPairSecondPointers(
201 cached_avatar_images_.begin(), cached_avatar_images_.end());
202 STLDeleteContainerPairSecondPointers(
203 avatar_images_downloads_in_progress_.begin(),
204 avatar_images_downloads_in_progress_.end());
207 void ProfileInfoCache::AddProfileToCache(
208 const base::FilePath& profile_path,
209 const base::string16& name,
210 const base::string16& username,
212 const std::string& supervised_user_id) {
213 std::string key = CacheKeyFromProfilePath(profile_path);
214 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
215 base::DictionaryValue* cache = update.Get();
217 scoped_ptr<base::DictionaryValue> info(new base::DictionaryValue);
218 info->SetString(kNameKey, name);
219 info->SetString(kUserNameKey, username);
220 info->SetString(kAvatarIconKey,
221 profiles::GetDefaultAvatarIconUrl(icon_index));
222 // Default value for whether background apps are running is false.
223 info->SetBoolean(kBackgroundAppsKey, false);
224 info->SetString(kSupervisedUserId, supervised_user_id);
225 info->SetBoolean(kIsOmittedFromProfileListKey, !supervised_user_id.empty());
226 info->SetBoolean(kProfileIsEphemeral, false);
227 info->SetBoolean(kIsUsingDefaultName, IsDefaultName(name));
228 cache->SetWithoutPathExpansion(key, info.release());
230 sorted_keys_.insert(FindPositionForProfile(key, name), key);
232 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
234 OnProfileAdded(profile_path));
236 content::NotificationService::current()->Notify(
237 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
238 content::NotificationService::AllSources(),
239 content::NotificationService::NoDetails());
242 void ProfileInfoCache::AddObserver(ProfileInfoCacheObserver* obs) {
243 observer_list_.AddObserver(obs);
246 void ProfileInfoCache::RemoveObserver(ProfileInfoCacheObserver* obs) {
247 observer_list_.RemoveObserver(obs);
250 void ProfileInfoCache::DeleteProfileFromCache(
251 const base::FilePath& profile_path) {
252 size_t profile_index = GetIndexOfProfileWithPath(profile_path);
253 if (profile_index == std::string::npos) {
257 base::string16 name = GetNameOfProfileAtIndex(profile_index);
259 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
261 OnProfileWillBeRemoved(profile_path));
263 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
264 base::DictionaryValue* cache = update.Get();
265 std::string key = CacheKeyFromProfilePath(profile_path);
266 cache->Remove(key, NULL);
267 sorted_keys_.erase(std::find(sorted_keys_.begin(), sorted_keys_.end(), key));
269 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
271 OnProfileWasRemoved(profile_path, name));
273 content::NotificationService::current()->Notify(
274 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
275 content::NotificationService::AllSources(),
276 content::NotificationService::NoDetails());
279 size_t ProfileInfoCache::GetNumberOfProfiles() const {
280 return sorted_keys_.size();
283 size_t ProfileInfoCache::GetIndexOfProfileWithPath(
284 const base::FilePath& profile_path) const {
285 if (profile_path.DirName() != user_data_dir_)
286 return std::string::npos;
287 std::string search_key = CacheKeyFromProfilePath(profile_path);
288 for (size_t i = 0; i < sorted_keys_.size(); ++i) {
289 if (sorted_keys_[i] == search_key)
292 return std::string::npos;
295 base::string16 ProfileInfoCache::GetNameOfProfileAtIndex(size_t index) const {
297 // Unless the user has customized the profile name, we should use the
298 // profile's Gaia given name, if it's available.
299 if (ProfileIsUsingDefaultNameAtIndex(index)) {
300 base::string16 given_name = GetGAIAGivenNameOfProfileAtIndex(index);
301 name = given_name.empty() ? GetGAIANameOfProfileAtIndex(index) : given_name;
304 GetInfoForProfileAtIndex(index)->GetString(kNameKey, &name);
308 base::string16 ProfileInfoCache::GetShortcutNameOfProfileAtIndex(size_t index)
310 base::string16 shortcut_name;
311 GetInfoForProfileAtIndex(index)->GetString(
312 kShortcutNameKey, &shortcut_name);
313 return shortcut_name;
316 base::FilePath ProfileInfoCache::GetPathOfProfileAtIndex(size_t index) const {
317 return user_data_dir_.AppendASCII(sorted_keys_[index]);
320 base::Time ProfileInfoCache::GetProfileActiveTimeAtIndex(size_t index) const {
322 if (GetInfoForProfileAtIndex(index)->GetDouble(kActiveTimeKey, &dt)) {
323 return base::Time::FromDoubleT(dt);
329 base::string16 ProfileInfoCache::GetUserNameOfProfileAtIndex(
330 size_t index) const {
331 base::string16 user_name;
332 GetInfoForProfileAtIndex(index)->GetString(kUserNameKey, &user_name);
336 const gfx::Image& ProfileInfoCache::GetAvatarIconOfProfileAtIndex(
337 size_t index) const {
338 if (IsUsingGAIAPictureOfProfileAtIndex(index)) {
339 const gfx::Image* image = GetGAIAPictureOfProfileAtIndex(index);
344 // Use the high resolution version of the avatar if it exists.
345 if (switches::IsNewAvatarMenu()) {
346 const gfx::Image* image = GetHighResAvatarOfProfileAtIndex(index);
351 int resource_id = profiles::GetDefaultAvatarIconResourceIDAtIndex(
352 GetAvatarIconIndexOfProfileAtIndex(index));
353 return ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
356 std::string ProfileInfoCache::GetLocalAuthCredentialsOfProfileAtIndex(
357 size_t index) const {
358 std::string credentials;
359 GetInfoForProfileAtIndex(index)->GetString(kAuthCredentialsKey, &credentials);
363 bool ProfileInfoCache::GetBackgroundStatusOfProfileAtIndex(
364 size_t index) const {
365 bool background_app_status;
366 if (!GetInfoForProfileAtIndex(index)->GetBoolean(kBackgroundAppsKey,
367 &background_app_status)) {
370 return background_app_status;
373 base::string16 ProfileInfoCache::GetGAIANameOfProfileAtIndex(
374 size_t index) const {
376 GetInfoForProfileAtIndex(index)->GetString(kGAIANameKey, &name);
380 base::string16 ProfileInfoCache::GetGAIAGivenNameOfProfileAtIndex(
381 size_t index) const {
383 GetInfoForProfileAtIndex(index)->GetString(kGAIAGivenNameKey, &name);
387 const gfx::Image* ProfileInfoCache::GetGAIAPictureOfProfileAtIndex(
388 size_t index) const {
389 base::FilePath path = GetPathOfProfileAtIndex(index);
390 std::string key = CacheKeyFromProfilePath(path);
392 std::string file_name;
393 GetInfoForProfileAtIndex(index)->GetString(
394 kGAIAPictureFileNameKey, &file_name);
396 // If the picture is not on disk then return NULL.
397 if (file_name.empty())
400 base::FilePath image_path = path.AppendASCII(file_name);
401 return LoadAvatarPictureFromPath(key, image_path);
404 bool ProfileInfoCache::IsUsingGAIAPictureOfProfileAtIndex(size_t index) const {
406 GetInfoForProfileAtIndex(index)->GetBoolean(kUseGAIAPictureKey, &value);
410 bool ProfileInfoCache::ProfileIsSupervisedAtIndex(size_t index) const {
411 return !GetSupervisedUserIdOfProfileAtIndex(index).empty();
414 bool ProfileInfoCache::IsOmittedProfileAtIndex(size_t index) const {
416 GetInfoForProfileAtIndex(index)->GetBoolean(kIsOmittedFromProfileListKey,
421 bool ProfileInfoCache::ProfileIsSigninRequiredAtIndex(size_t index) const {
423 GetInfoForProfileAtIndex(index)->GetBoolean(kSigninRequiredKey, &value);
427 std::string ProfileInfoCache::GetSupervisedUserIdOfProfileAtIndex(
428 size_t index) const {
429 std::string supervised_user_id;
430 GetInfoForProfileAtIndex(index)->GetString(kSupervisedUserId,
431 &supervised_user_id);
432 return supervised_user_id;
435 bool ProfileInfoCache::ProfileIsEphemeralAtIndex(size_t index) const {
437 GetInfoForProfileAtIndex(index)->GetBoolean(kProfileIsEphemeral, &value);
441 bool ProfileInfoCache::ProfileIsUsingDefaultNameAtIndex(size_t index) const {
443 GetInfoForProfileAtIndex(index)->GetBoolean(kIsUsingDefaultName, &value);
447 size_t ProfileInfoCache::GetAvatarIconIndexOfProfileAtIndex(size_t index)
449 std::string icon_url;
450 GetInfoForProfileAtIndex(index)->GetString(kAvatarIconKey, &icon_url);
451 size_t icon_index = 0;
452 if (!profiles::IsDefaultAvatarIconUrl(icon_url, &icon_index))
453 DLOG(WARNING) << "Unknown avatar icon: " << icon_url;
458 void ProfileInfoCache::SetProfileActiveTimeAtIndex(size_t index) {
459 scoped_ptr<base::DictionaryValue> info(
460 GetInfoForProfileAtIndex(index)->DeepCopy());
461 info->SetDouble(kActiveTimeKey, base::Time::Now().ToDoubleT());
462 // This takes ownership of |info|.
463 SetInfoQuietlyForProfileAtIndex(index, info.release());
466 void ProfileInfoCache::SetNameOfProfileAtIndex(size_t index,
467 const base::string16& name) {
468 scoped_ptr<base::DictionaryValue> info(
469 GetInfoForProfileAtIndex(index)->DeepCopy());
470 base::string16 current_name;
471 info->GetString(kNameKey, ¤t_name);
472 if (name == current_name)
475 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
476 info->SetString(kNameKey, name);
477 info->SetBoolean(kIsUsingDefaultName, false);
479 // This takes ownership of |info|.
480 SetInfoForProfileAtIndex(index, info.release());
481 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
482 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
483 UpdateSortForProfileIndex(index);
485 if (old_display_name != new_display_name) {
486 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
488 OnProfileNameChanged(profile_path, old_display_name));
492 void ProfileInfoCache::SetShortcutNameOfProfileAtIndex(
494 const base::string16& shortcut_name) {
495 if (shortcut_name == GetShortcutNameOfProfileAtIndex(index))
497 scoped_ptr<base::DictionaryValue> info(
498 GetInfoForProfileAtIndex(index)->DeepCopy());
499 info->SetString(kShortcutNameKey, shortcut_name);
500 // This takes ownership of |info|.
501 SetInfoForProfileAtIndex(index, info.release());
504 void ProfileInfoCache::SetUserNameOfProfileAtIndex(
506 const base::string16& user_name) {
507 if (user_name == GetUserNameOfProfileAtIndex(index))
510 scoped_ptr<base::DictionaryValue> info(
511 GetInfoForProfileAtIndex(index)->DeepCopy());
512 info->SetString(kUserNameKey, user_name);
513 // This takes ownership of |info|.
514 SetInfoForProfileAtIndex(index, info.release());
517 void ProfileInfoCache::SetAvatarIconOfProfileAtIndex(size_t index,
519 scoped_ptr<base::DictionaryValue> info(
520 GetInfoForProfileAtIndex(index)->DeepCopy());
521 info->SetString(kAvatarIconKey,
522 profiles::GetDefaultAvatarIconUrl(icon_index));
523 // This takes ownership of |info|.
524 SetInfoForProfileAtIndex(index, info.release());
526 // If needed, start downloading the high-res avatar.
527 if (switches::IsNewAvatarMenu())
528 DownloadHighResAvatar(icon_index, GetPathOfProfileAtIndex(index));
530 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
531 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
533 OnProfileAvatarChanged(profile_path));
536 void ProfileInfoCache::SetIsOmittedProfileAtIndex(size_t index,
538 if (IsOmittedProfileAtIndex(index) == is_omitted)
540 scoped_ptr<base::DictionaryValue> info(
541 GetInfoForProfileAtIndex(index)->DeepCopy());
542 info->SetBoolean(kIsOmittedFromProfileListKey, is_omitted);
543 // This takes ownership of |info|.
544 SetInfoForProfileAtIndex(index, info.release());
547 void ProfileInfoCache::SetSupervisedUserIdOfProfileAtIndex(
549 const std::string& id) {
550 if (GetSupervisedUserIdOfProfileAtIndex(index) == id)
552 scoped_ptr<base::DictionaryValue> info(
553 GetInfoForProfileAtIndex(index)->DeepCopy());
554 info->SetString(kSupervisedUserId, id);
555 // This takes ownership of |info|.
556 SetInfoForProfileAtIndex(index, info.release());
558 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
559 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
561 OnProfileSupervisedUserIdChanged(profile_path));
564 void ProfileInfoCache::SetLocalAuthCredentialsOfProfileAtIndex(
566 const std::string& credentials) {
567 scoped_ptr<base::DictionaryValue> info(
568 GetInfoForProfileAtIndex(index)->DeepCopy());
569 info->SetString(kAuthCredentialsKey, credentials);
570 // This takes ownership of |info|.
571 SetInfoForProfileAtIndex(index, info.release());
574 void ProfileInfoCache::SetBackgroundStatusOfProfileAtIndex(
576 bool running_background_apps) {
577 if (GetBackgroundStatusOfProfileAtIndex(index) == running_background_apps)
579 scoped_ptr<base::DictionaryValue> info(
580 GetInfoForProfileAtIndex(index)->DeepCopy());
581 info->SetBoolean(kBackgroundAppsKey, running_background_apps);
582 // This takes ownership of |info|.
583 SetInfoForProfileAtIndex(index, info.release());
586 void ProfileInfoCache::SetGAIANameOfProfileAtIndex(size_t index,
587 const base::string16& name) {
588 if (name == GetGAIANameOfProfileAtIndex(index))
591 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
592 scoped_ptr<base::DictionaryValue> info(
593 GetInfoForProfileAtIndex(index)->DeepCopy());
594 info->SetString(kGAIANameKey, name);
595 // This takes ownership of |info|.
596 SetInfoForProfileAtIndex(index, info.release());
597 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
598 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
599 UpdateSortForProfileIndex(index);
601 if (old_display_name != new_display_name) {
602 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
604 OnProfileNameChanged(profile_path, old_display_name));
608 void ProfileInfoCache::SetGAIAGivenNameOfProfileAtIndex(
610 const base::string16& name) {
611 if (name == GetGAIAGivenNameOfProfileAtIndex(index))
614 scoped_ptr<base::DictionaryValue> info(
615 GetInfoForProfileAtIndex(index)->DeepCopy());
616 info->SetString(kGAIAGivenNameKey, name);
617 // This takes ownership of |info|.
618 SetInfoForProfileAtIndex(index, info.release());
621 void ProfileInfoCache::SetGAIAPictureOfProfileAtIndex(size_t index,
622 const gfx::Image* image) {
623 base::FilePath path = GetPathOfProfileAtIndex(index);
624 std::string key = CacheKeyFromProfilePath(path);
626 // Delete the old bitmap from cache.
627 std::map<std::string, gfx::Image*>::iterator it =
628 cached_avatar_images_.find(key);
629 if (it != cached_avatar_images_.end()) {
631 cached_avatar_images_.erase(it);
634 std::string old_file_name;
635 GetInfoForProfileAtIndex(index)->GetString(
636 kGAIAPictureFileNameKey, &old_file_name);
637 std::string new_file_name;
640 // Delete the old bitmap from disk.
641 if (!old_file_name.empty()) {
642 base::FilePath image_path = path.AppendASCII(old_file_name);
643 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
644 base::Bind(&DeleteBitmap, image_path));
647 // Save the new bitmap to disk.
649 old_file_name.empty() ? profiles::kGAIAPictureFileName : old_file_name;
650 base::FilePath image_path = path.AppendASCII(new_file_name);
651 SaveAvatarImageAtPath(
652 image, key, image_path, GetPathOfProfileAtIndex(index));
655 scoped_ptr<base::DictionaryValue> info(
656 GetInfoForProfileAtIndex(index)->DeepCopy());
657 info->SetString(kGAIAPictureFileNameKey, new_file_name);
658 // This takes ownership of |info|.
659 SetInfoForProfileAtIndex(index, info.release());
661 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
663 OnProfileAvatarChanged(path));
666 void ProfileInfoCache::SetIsUsingGAIAPictureOfProfileAtIndex(size_t index,
668 scoped_ptr<base::DictionaryValue> info(
669 GetInfoForProfileAtIndex(index)->DeepCopy());
670 info->SetBoolean(kUseGAIAPictureKey, value);
671 // This takes ownership of |info|.
672 SetInfoForProfileAtIndex(index, info.release());
674 // Retrieve some info to update observers who care about avatar changes.
675 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
676 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
678 OnProfileAvatarChanged(profile_path));
681 void ProfileInfoCache::SetProfileSigninRequiredAtIndex(size_t index,
683 if (value == ProfileIsSigninRequiredAtIndex(index))
686 scoped_ptr<base::DictionaryValue> info(
687 GetInfoForProfileAtIndex(index)->DeepCopy());
688 info->SetBoolean(kSigninRequiredKey, value);
689 // This takes ownership of |info|.
690 SetInfoForProfileAtIndex(index, info.release());
692 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
693 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
695 OnProfileSigninRequiredChanged(profile_path));
698 void ProfileInfoCache::SetProfileIsEphemeralAtIndex(size_t index, bool value) {
699 if (value == ProfileIsEphemeralAtIndex(index))
702 scoped_ptr<base::DictionaryValue> info(
703 GetInfoForProfileAtIndex(index)->DeepCopy());
704 info->SetBoolean(kProfileIsEphemeral, value);
705 // This takes ownership of |info|.
706 SetInfoForProfileAtIndex(index, info.release());
709 void ProfileInfoCache::SetProfileIsUsingDefaultNameAtIndex(
710 size_t index, bool value) {
711 if (value == ProfileIsUsingDefaultNameAtIndex(index))
714 scoped_ptr<base::DictionaryValue> info(
715 GetInfoForProfileAtIndex(index)->DeepCopy());
716 info->SetBoolean(kIsUsingDefaultName, value);
717 // This takes ownership of |info|.
718 SetInfoForProfileAtIndex(index, info.release());
721 base::string16 ProfileInfoCache::ChooseNameForNewProfile(
722 size_t icon_index) const {
724 for (int name_index = 1; ; ++name_index) {
725 if (switches::IsNewProfileManagement()) {
726 name = l10n_util::GetStringFUTF16Int(IDS_NEW_NUMBERED_PROFILE_NAME,
728 } else if (icon_index < profiles::GetGenericAvatarIconCount()) {
729 name = l10n_util::GetStringFUTF16Int(IDS_NUMBERED_PROFILE_NAME,
732 name = l10n_util::GetStringUTF16(
733 kDefaultNames[icon_index - profiles::GetGenericAvatarIconCount()]);
735 name.append(base::UTF8ToUTF16(base::IntToString(name_index)));
738 // Loop through previously named profiles to ensure we're not duplicating.
739 bool name_found = false;
740 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
741 if (GetNameOfProfileAtIndex(i) == name) {
751 size_t ProfileInfoCache::ChooseAvatarIconIndexForNewProfile() const {
752 size_t icon_index = 0;
753 // Try to find a unique, non-generic icon.
754 if (ChooseAvatarIconIndexForNewProfile(false, true, &icon_index))
756 // Try to find any unique icon.
757 if (ChooseAvatarIconIndexForNewProfile(true, true, &icon_index))
759 // Settle for any random icon, even if it's not unique.
760 if (ChooseAvatarIconIndexForNewProfile(true, false, &icon_index))
767 const base::FilePath& ProfileInfoCache::GetUserDataDir() const {
768 return user_data_dir_;
772 std::vector<base::string16> ProfileInfoCache::GetProfileNames() {
773 std::vector<base::string16> names;
774 PrefService* local_state = g_browser_process->local_state();
775 const base::DictionaryValue* cache = local_state->GetDictionary(
776 prefs::kProfileInfoCache);
778 for (base::DictionaryValue::Iterator it(*cache); !it.IsAtEnd();
780 const base::DictionaryValue* info = NULL;
781 it.value().GetAsDictionary(&info);
782 info->GetString(kNameKey, &name);
783 names.push_back(name);
789 void ProfileInfoCache::RegisterPrefs(PrefRegistrySimple* registry) {
790 registry->RegisterDictionaryPref(prefs::kProfileInfoCache);
793 void ProfileInfoCache::DownloadHighResAvatar(
795 const base::FilePath& profile_path) {
796 // Downloading is only supported on desktop.
797 #if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS)
801 // TODO(noms): We should check whether the file already exists on disk
802 // before trying to re-download it. For now, since this is behind a flag and
803 // the resources are still changing, re-download it every time the profile
804 // avatar changes, to make sure we have the latest copy.
805 std::string file_name = profiles::GetDefaultAvatarIconFileNameAtIndex(
807 // If the file is already being downloaded, don't start another download.
808 if (avatar_images_downloads_in_progress_[file_name])
811 // Start the download for this file. The cache takes ownership of the
812 // |avatar_downloader|, which will be deleted when the download completes, or
813 // if that never happens, when the ProfileInfoCache is destroyed.
814 ProfileAvatarDownloader* avatar_downloader = new ProfileAvatarDownloader(
818 avatar_images_downloads_in_progress_[file_name] = avatar_downloader;
819 avatar_downloader->Start();
822 void ProfileInfoCache::SaveAvatarImageAtPath(
823 const gfx::Image* image,
824 const std::string& key,
825 const base::FilePath& image_path,
826 const base::FilePath& profile_path) {
827 cached_avatar_images_[key] = new gfx::Image(*image);
829 scoped_ptr<ImageData> data(new ImageData);
830 scoped_refptr<base::RefCountedMemory> png_data = image->As1xPNGBytes();
831 data->assign(png_data->front(), png_data->front() + png_data->size());
834 LOG(ERROR) << "Failed to PNG encode the image.";
836 base::Closure callback = base::Bind(&ProfileInfoCache::OnAvatarPictureSaved,
837 AsWeakPtr(), key, profile_path);
839 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
840 base::Bind(&SaveBitmap, base::Passed(&data), image_path, callback));
844 const base::DictionaryValue* ProfileInfoCache::GetInfoForProfileAtIndex(
845 size_t index) const {
846 DCHECK_LT(index, GetNumberOfProfiles());
847 const base::DictionaryValue* cache =
848 prefs_->GetDictionary(prefs::kProfileInfoCache);
849 const base::DictionaryValue* info = NULL;
850 cache->GetDictionaryWithoutPathExpansion(sorted_keys_[index], &info);
854 void ProfileInfoCache::SetInfoQuietlyForProfileAtIndex(
855 size_t index, base::DictionaryValue* info) {
856 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
857 base::DictionaryValue* cache = update.Get();
858 cache->SetWithoutPathExpansion(sorted_keys_[index], info);
861 // TODO(noms): Switch to newer notification system.
862 void ProfileInfoCache::SetInfoForProfileAtIndex(size_t index,
863 base::DictionaryValue* info) {
864 SetInfoQuietlyForProfileAtIndex(index, info);
866 content::NotificationService::current()->Notify(
867 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
868 content::NotificationService::AllSources(),
869 content::NotificationService::NoDetails());
872 std::string ProfileInfoCache::CacheKeyFromProfilePath(
873 const base::FilePath& profile_path) const {
874 DCHECK(user_data_dir_ == profile_path.DirName());
875 base::FilePath base_name = profile_path.BaseName();
876 return base_name.MaybeAsASCII();
879 std::vector<std::string>::iterator ProfileInfoCache::FindPositionForProfile(
880 const std::string& search_key,
881 const base::string16& search_name) {
882 base::string16 search_name_l = base::i18n::ToLower(search_name);
883 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
884 base::string16 name_l = base::i18n::ToLower(GetNameOfProfileAtIndex(i));
885 int name_compare = search_name_l.compare(name_l);
886 if (name_compare < 0)
887 return sorted_keys_.begin() + i;
888 if (name_compare == 0) {
889 int key_compare = search_key.compare(sorted_keys_[i]);
891 return sorted_keys_.begin() + i;
894 return sorted_keys_.end();
897 bool ProfileInfoCache::IconIndexIsUnique(size_t icon_index) const {
898 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
899 if (GetAvatarIconIndexOfProfileAtIndex(i) == icon_index)
905 bool ProfileInfoCache::ChooseAvatarIconIndexForNewProfile(
906 bool allow_generic_icon,
908 size_t* out_icon_index) const {
909 // Always allow all icons for new profiles if using the
910 // --new-profile-management flag.
911 if (switches::IsNewProfileManagement())
912 allow_generic_icon = true;
913 size_t start = allow_generic_icon ? 0 : profiles::GetGenericAvatarIconCount();
914 size_t end = profiles::GetDefaultAvatarIconCount();
915 size_t count = end - start;
917 int rand = base::RandInt(0, count);
918 for (size_t i = 0; i < count; ++i) {
919 size_t icon_index = start + (rand + i) % count;
920 if (!must_be_unique || IconIndexIsUnique(icon_index)) {
921 *out_icon_index = icon_index;
929 void ProfileInfoCache::UpdateSortForProfileIndex(size_t index) {
930 base::string16 name = GetNameOfProfileAtIndex(index);
932 // Remove and reinsert key in |sorted_keys_| to alphasort.
933 std::string key = CacheKeyFromProfilePath(GetPathOfProfileAtIndex(index));
934 std::vector<std::string>::iterator key_it =
935 std::find(sorted_keys_.begin(), sorted_keys_.end(), key);
936 DCHECK(key_it != sorted_keys_.end());
937 sorted_keys_.erase(key_it);
938 sorted_keys_.insert(FindPositionForProfile(key, name), key);
940 content::NotificationService::current()->Notify(
941 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
942 content::NotificationService::AllSources(),
943 content::NotificationService::NoDetails());
946 const gfx::Image* ProfileInfoCache::GetHighResAvatarOfProfileAtIndex(
947 size_t index) const {
948 int avatar_index = GetAvatarIconIndexOfProfileAtIndex(index);
949 std::string key = profiles::GetDefaultAvatarIconFileNameAtIndex(avatar_index);
951 if (!strcmp(key.c_str(), profiles::GetNoHighResAvatarFileName()))
954 base::FilePath image_path =
955 profiles::GetPathOfHighResAvatarAtIndex(avatar_index);
956 return LoadAvatarPictureFromPath(key, image_path);
959 const gfx::Image* ProfileInfoCache::LoadAvatarPictureFromPath(
960 const std::string& key,
961 const base::FilePath& image_path) const {
962 // If the picture is already loaded then use it.
963 if (cached_avatar_images_.count(key)) {
964 if (cached_avatar_images_[key]->IsEmpty())
966 return cached_avatar_images_[key];
969 // If the picture is already being loaded then don't try loading it again.
970 if (cached_avatar_images_loading_[key])
972 cached_avatar_images_loading_[key] = true;
974 gfx::Image** image = new gfx::Image*;
975 BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE,
976 base::Bind(&ReadBitmap, image_path, image),
977 base::Bind(&ProfileInfoCache::OnAvatarPictureLoaded,
978 const_cast<ProfileInfoCache*>(this)->AsWeakPtr(), key, image));
982 void ProfileInfoCache::OnAvatarPictureLoaded(const std::string& key,
983 gfx::Image** image) const {
984 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
986 cached_avatar_images_loading_[key] = false;
987 delete cached_avatar_images_[key];
990 cached_avatar_images_[key] = *image;
992 // Place an empty image in the cache to avoid reloading it again.
993 cached_avatar_images_[key] = new gfx::Image();
997 content::NotificationService::current()->Notify(
998 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
999 content::NotificationService::AllSources(),
1000 content::NotificationService::NoDetails());
1003 void ProfileInfoCache::OnAvatarPictureSaved(
1004 const std::string& file_name,
1005 const base::FilePath& profile_path) {
1006 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1008 content::NotificationService::current()->Notify(
1009 chrome::NOTIFICATION_PROFILE_CACHE_PICTURE_SAVED,
1010 content::NotificationService::AllSources(),
1011 content::NotificationService::NoDetails());
1013 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
1015 OnProfileAvatarChanged(profile_path));
1017 // Remove the file from the list of downloads in progress. Note that this list
1018 // only contains the high resolution avatars, and not the Gaia profile images.
1019 if (!avatar_images_downloads_in_progress_[file_name])
1022 delete avatar_images_downloads_in_progress_[file_name];
1023 avatar_images_downloads_in_progress_[file_name] = NULL;