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 kIsUsingDefaultNameKey[] = "is_using_default_name";
47 const char kIsUsingDefaultAvatarKey[] = "is_using_default_avatar";
48 const char kAvatarIconKey[] = "avatar_icon";
49 const char kAuthCredentialsKey[] = "local_auth_credentials";
50 const char kUseGAIAPictureKey[] = "use_gaia_picture";
51 const char kBackgroundAppsKey[] = "background_apps";
52 const char kGAIAPictureFileNameKey[] = "gaia_picture_file_name";
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);
142 ProfileInfoCache::ProfileInfoCache(PrefService* prefs,
143 const base::FilePath& user_data_dir)
145 user_data_dir_(user_data_dir) {
146 // Populate the cache
147 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
148 base::DictionaryValue* cache = update.Get();
149 for (base::DictionaryValue::Iterator it(*cache);
150 !it.IsAtEnd(); it.Advance()) {
151 base::DictionaryValue* info = NULL;
152 cache->GetDictionaryWithoutPathExpansion(it.key(), &info);
154 info->GetString(kNameKey, &name);
155 sorted_keys_.insert(FindPositionForProfile(it.key(), name), it.key());
157 bool using_default_name;
158 if (!info->GetBoolean(kIsUsingDefaultNameKey, &using_default_name)) {
159 // If the preference hasn't been set, and the name is default, assume
160 // that the user hasn't done this on purpose.
161 using_default_name = IsDefaultProfileName(name);
162 info->SetBoolean(kIsUsingDefaultNameKey, using_default_name);
165 // For profiles that don't have the "using default avatar" state set yet,
166 // assume it's the same as the "using default name" state.
167 if (!info->HasKey(kIsUsingDefaultAvatarKey)) {
168 info->SetBoolean(kIsUsingDefaultAvatarKey, using_default_name);
172 // If needed, start downloading the high-res avatars.
173 if (switches::IsNewAvatarMenu()) {
174 for (size_t i = 0; i < GetNumberOfProfiles(); i++) {
175 DownloadHighResAvatar(GetAvatarIconIndexOfProfileAtIndex(i),
176 GetPathOfProfileAtIndex(i));
181 ProfileInfoCache::~ProfileInfoCache() {
182 STLDeleteContainerPairSecondPointers(
183 cached_avatar_images_.begin(), cached_avatar_images_.end());
184 STLDeleteContainerPairSecondPointers(
185 avatar_images_downloads_in_progress_.begin(),
186 avatar_images_downloads_in_progress_.end());
189 void ProfileInfoCache::AddProfileToCache(
190 const base::FilePath& profile_path,
191 const base::string16& name,
192 const base::string16& username,
194 const std::string& supervised_user_id) {
195 std::string key = CacheKeyFromProfilePath(profile_path);
196 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
197 base::DictionaryValue* cache = update.Get();
199 scoped_ptr<base::DictionaryValue> info(new base::DictionaryValue);
200 info->SetString(kNameKey, name);
201 info->SetString(kUserNameKey, username);
202 info->SetString(kAvatarIconKey,
203 profiles::GetDefaultAvatarIconUrl(icon_index));
204 // Default value for whether background apps are running is false.
205 info->SetBoolean(kBackgroundAppsKey, false);
206 info->SetString(kSupervisedUserId, supervised_user_id);
207 info->SetBoolean(kIsOmittedFromProfileListKey, !supervised_user_id.empty());
208 info->SetBoolean(kProfileIsEphemeral, false);
209 info->SetBoolean(kIsUsingDefaultNameKey, IsDefaultProfileName(name));
210 // Assume newly created profiles use a default avatar.
211 info->SetBoolean(kIsUsingDefaultAvatarKey, true);
212 cache->SetWithoutPathExpansion(key, info.release());
214 sorted_keys_.insert(FindPositionForProfile(key, name), key);
216 if (switches::IsNewAvatarMenu())
217 DownloadHighResAvatar(icon_index, profile_path);
219 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
221 OnProfileAdded(profile_path));
223 content::NotificationService::current()->Notify(
224 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
225 content::NotificationService::AllSources(),
226 content::NotificationService::NoDetails());
229 void ProfileInfoCache::AddObserver(ProfileInfoCacheObserver* obs) {
230 observer_list_.AddObserver(obs);
233 void ProfileInfoCache::RemoveObserver(ProfileInfoCacheObserver* obs) {
234 observer_list_.RemoveObserver(obs);
237 void ProfileInfoCache::DeleteProfileFromCache(
238 const base::FilePath& profile_path) {
239 size_t profile_index = GetIndexOfProfileWithPath(profile_path);
240 if (profile_index == std::string::npos) {
244 base::string16 name = GetNameOfProfileAtIndex(profile_index);
246 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
248 OnProfileWillBeRemoved(profile_path));
250 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
251 base::DictionaryValue* cache = update.Get();
252 std::string key = CacheKeyFromProfilePath(profile_path);
253 cache->Remove(key, NULL);
254 sorted_keys_.erase(std::find(sorted_keys_.begin(), sorted_keys_.end(), key));
256 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
258 OnProfileWasRemoved(profile_path, name));
260 content::NotificationService::current()->Notify(
261 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
262 content::NotificationService::AllSources(),
263 content::NotificationService::NoDetails());
266 size_t ProfileInfoCache::GetNumberOfProfiles() const {
267 return sorted_keys_.size();
270 size_t ProfileInfoCache::GetIndexOfProfileWithPath(
271 const base::FilePath& profile_path) const {
272 if (profile_path.DirName() != user_data_dir_)
273 return std::string::npos;
274 std::string search_key = CacheKeyFromProfilePath(profile_path);
275 for (size_t i = 0; i < sorted_keys_.size(); ++i) {
276 if (sorted_keys_[i] == search_key)
279 return std::string::npos;
282 base::string16 ProfileInfoCache::GetNameOfProfileAtIndex(size_t index) const {
284 // Unless the user has customized the profile name, we should use the
285 // profile's Gaia given name, if it's available.
286 if (ProfileIsUsingDefaultNameAtIndex(index)) {
287 base::string16 given_name = GetGAIAGivenNameOfProfileAtIndex(index);
288 name = given_name.empty() ? GetGAIANameOfProfileAtIndex(index) : given_name;
291 GetInfoForProfileAtIndex(index)->GetString(kNameKey, &name);
295 base::string16 ProfileInfoCache::GetShortcutNameOfProfileAtIndex(size_t index)
297 base::string16 shortcut_name;
298 GetInfoForProfileAtIndex(index)->GetString(
299 kShortcutNameKey, &shortcut_name);
300 return shortcut_name;
303 base::FilePath ProfileInfoCache::GetPathOfProfileAtIndex(size_t index) const {
304 return user_data_dir_.AppendASCII(sorted_keys_[index]);
307 base::Time ProfileInfoCache::GetProfileActiveTimeAtIndex(size_t index) const {
309 if (GetInfoForProfileAtIndex(index)->GetDouble(kActiveTimeKey, &dt)) {
310 return base::Time::FromDoubleT(dt);
316 base::string16 ProfileInfoCache::GetUserNameOfProfileAtIndex(
317 size_t index) const {
318 base::string16 user_name;
319 GetInfoForProfileAtIndex(index)->GetString(kUserNameKey, &user_name);
323 const gfx::Image& ProfileInfoCache::GetAvatarIconOfProfileAtIndex(
324 size_t index) const {
325 if (IsUsingGAIAPictureOfProfileAtIndex(index)) {
326 const gfx::Image* image = GetGAIAPictureOfProfileAtIndex(index);
331 // Use the high resolution version of the avatar if it exists.
332 if (switches::IsNewAvatarMenu()) {
333 const gfx::Image* image = GetHighResAvatarOfProfileAtIndex(index);
338 int resource_id = profiles::GetDefaultAvatarIconResourceIDAtIndex(
339 GetAvatarIconIndexOfProfileAtIndex(index));
340 return ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
343 std::string ProfileInfoCache::GetLocalAuthCredentialsOfProfileAtIndex(
344 size_t index) const {
345 std::string credentials;
346 GetInfoForProfileAtIndex(index)->GetString(kAuthCredentialsKey, &credentials);
350 bool ProfileInfoCache::GetBackgroundStatusOfProfileAtIndex(
351 size_t index) const {
352 bool background_app_status;
353 if (!GetInfoForProfileAtIndex(index)->GetBoolean(kBackgroundAppsKey,
354 &background_app_status)) {
357 return background_app_status;
360 base::string16 ProfileInfoCache::GetGAIANameOfProfileAtIndex(
361 size_t index) const {
363 GetInfoForProfileAtIndex(index)->GetString(kGAIANameKey, &name);
367 base::string16 ProfileInfoCache::GetGAIAGivenNameOfProfileAtIndex(
368 size_t index) const {
370 GetInfoForProfileAtIndex(index)->GetString(kGAIAGivenNameKey, &name);
374 const gfx::Image* ProfileInfoCache::GetGAIAPictureOfProfileAtIndex(
375 size_t index) const {
376 base::FilePath path = GetPathOfProfileAtIndex(index);
377 std::string key = CacheKeyFromProfilePath(path);
379 std::string file_name;
380 GetInfoForProfileAtIndex(index)->GetString(
381 kGAIAPictureFileNameKey, &file_name);
383 // If the picture is not on disk then return NULL.
384 if (file_name.empty())
387 base::FilePath image_path = path.AppendASCII(file_name);
388 return LoadAvatarPictureFromPath(key, image_path);
391 bool ProfileInfoCache::IsUsingGAIAPictureOfProfileAtIndex(size_t index) const {
393 GetInfoForProfileAtIndex(index)->GetBoolean(kUseGAIAPictureKey, &value);
395 // Prefer the GAIA avatar over a non-customized avatar.
396 value = ProfileIsUsingDefaultAvatarAtIndex(index) &&
397 GetGAIAPictureOfProfileAtIndex(index);
402 bool ProfileInfoCache::ProfileIsSupervisedAtIndex(size_t index) const {
403 return !GetSupervisedUserIdOfProfileAtIndex(index).empty();
406 bool ProfileInfoCache::IsOmittedProfileAtIndex(size_t index) const {
408 GetInfoForProfileAtIndex(index)->GetBoolean(kIsOmittedFromProfileListKey,
413 bool ProfileInfoCache::ProfileIsSigninRequiredAtIndex(size_t index) const {
415 GetInfoForProfileAtIndex(index)->GetBoolean(kSigninRequiredKey, &value);
419 std::string ProfileInfoCache::GetSupervisedUserIdOfProfileAtIndex(
420 size_t index) const {
421 std::string supervised_user_id;
422 GetInfoForProfileAtIndex(index)->GetString(kSupervisedUserId,
423 &supervised_user_id);
424 return supervised_user_id;
427 bool ProfileInfoCache::ProfileIsEphemeralAtIndex(size_t index) const {
429 GetInfoForProfileAtIndex(index)->GetBoolean(kProfileIsEphemeral, &value);
433 bool ProfileInfoCache::ProfileIsUsingDefaultNameAtIndex(size_t index) const {
435 GetInfoForProfileAtIndex(index)->GetBoolean(kIsUsingDefaultNameKey, &value);
439 bool ProfileInfoCache::ProfileIsUsingDefaultAvatarAtIndex(size_t index) const {
441 GetInfoForProfileAtIndex(index)->GetBoolean(kIsUsingDefaultAvatarKey, &value);
445 size_t ProfileInfoCache::GetAvatarIconIndexOfProfileAtIndex(size_t index)
447 std::string icon_url;
448 GetInfoForProfileAtIndex(index)->GetString(kAvatarIconKey, &icon_url);
449 size_t icon_index = 0;
450 if (!profiles::IsDefaultAvatarIconUrl(icon_url, &icon_index))
451 DLOG(WARNING) << "Unknown avatar icon: " << icon_url;
456 void ProfileInfoCache::SetProfileActiveTimeAtIndex(size_t index) {
457 scoped_ptr<base::DictionaryValue> info(
458 GetInfoForProfileAtIndex(index)->DeepCopy());
459 info->SetDouble(kActiveTimeKey, base::Time::Now().ToDoubleT());
460 // This takes ownership of |info|.
461 SetInfoQuietlyForProfileAtIndex(index, info.release());
464 void ProfileInfoCache::SetNameOfProfileAtIndex(size_t index,
465 const base::string16& name) {
466 scoped_ptr<base::DictionaryValue> info(
467 GetInfoForProfileAtIndex(index)->DeepCopy());
468 base::string16 current_name;
469 info->GetString(kNameKey, ¤t_name);
470 if (name == current_name)
473 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
474 info->SetString(kNameKey, name);
476 // This takes ownership of |info|.
477 SetInfoForProfileAtIndex(index, info.release());
479 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
480 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
481 UpdateSortForProfileIndex(index);
483 if (old_display_name != new_display_name) {
484 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
486 OnProfileNameChanged(profile_path, old_display_name));
490 void ProfileInfoCache::SetShortcutNameOfProfileAtIndex(
492 const base::string16& shortcut_name) {
493 if (shortcut_name == GetShortcutNameOfProfileAtIndex(index))
495 scoped_ptr<base::DictionaryValue> info(
496 GetInfoForProfileAtIndex(index)->DeepCopy());
497 info->SetString(kShortcutNameKey, shortcut_name);
498 // This takes ownership of |info|.
499 SetInfoForProfileAtIndex(index, info.release());
502 void ProfileInfoCache::SetUserNameOfProfileAtIndex(
504 const base::string16& user_name) {
505 if (user_name == GetUserNameOfProfileAtIndex(index))
508 scoped_ptr<base::DictionaryValue> info(
509 GetInfoForProfileAtIndex(index)->DeepCopy());
510 info->SetString(kUserNameKey, user_name);
511 // This takes ownership of |info|.
512 SetInfoForProfileAtIndex(index, info.release());
515 void ProfileInfoCache::SetAvatarIconOfProfileAtIndex(size_t index,
517 scoped_ptr<base::DictionaryValue> info(
518 GetInfoForProfileAtIndex(index)->DeepCopy());
519 info->SetString(kAvatarIconKey,
520 profiles::GetDefaultAvatarIconUrl(icon_index));
521 // This takes ownership of |info|.
522 SetInfoForProfileAtIndex(index, info.release());
524 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
526 // If needed, start downloading the high-res avatar.
527 if (switches::IsNewAvatarMenu())
528 DownloadHighResAvatar(icon_index, profile_path);
530 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
532 OnProfileAvatarChanged(profile_path));
535 void ProfileInfoCache::SetIsOmittedProfileAtIndex(size_t index,
537 if (IsOmittedProfileAtIndex(index) == is_omitted)
539 scoped_ptr<base::DictionaryValue> info(
540 GetInfoForProfileAtIndex(index)->DeepCopy());
541 info->SetBoolean(kIsOmittedFromProfileListKey, is_omitted);
542 // This takes ownership of |info|.
543 SetInfoForProfileAtIndex(index, info.release());
546 void ProfileInfoCache::SetSupervisedUserIdOfProfileAtIndex(
548 const std::string& id) {
549 if (GetSupervisedUserIdOfProfileAtIndex(index) == id)
551 scoped_ptr<base::DictionaryValue> info(
552 GetInfoForProfileAtIndex(index)->DeepCopy());
553 info->SetString(kSupervisedUserId, id);
554 // This takes ownership of |info|.
555 SetInfoForProfileAtIndex(index, info.release());
557 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
558 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
560 OnProfileSupervisedUserIdChanged(profile_path));
563 void ProfileInfoCache::SetLocalAuthCredentialsOfProfileAtIndex(
565 const std::string& credentials) {
566 scoped_ptr<base::DictionaryValue> info(
567 GetInfoForProfileAtIndex(index)->DeepCopy());
568 info->SetString(kAuthCredentialsKey, credentials);
569 // This takes ownership of |info|.
570 SetInfoForProfileAtIndex(index, info.release());
573 void ProfileInfoCache::SetBackgroundStatusOfProfileAtIndex(
575 bool running_background_apps) {
576 if (GetBackgroundStatusOfProfileAtIndex(index) == running_background_apps)
578 scoped_ptr<base::DictionaryValue> info(
579 GetInfoForProfileAtIndex(index)->DeepCopy());
580 info->SetBoolean(kBackgroundAppsKey, running_background_apps);
581 // This takes ownership of |info|.
582 SetInfoForProfileAtIndex(index, info.release());
585 void ProfileInfoCache::SetGAIANameOfProfileAtIndex(size_t index,
586 const base::string16& name) {
587 if (name == GetGAIANameOfProfileAtIndex(index))
590 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
591 scoped_ptr<base::DictionaryValue> info(
592 GetInfoForProfileAtIndex(index)->DeepCopy());
593 info->SetString(kGAIANameKey, name);
594 // This takes ownership of |info|.
595 SetInfoForProfileAtIndex(index, info.release());
596 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
597 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
598 UpdateSortForProfileIndex(index);
600 if (old_display_name != new_display_name) {
601 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
603 OnProfileNameChanged(profile_path, old_display_name));
607 void ProfileInfoCache::SetGAIAGivenNameOfProfileAtIndex(
609 const base::string16& name) {
610 if (name == GetGAIAGivenNameOfProfileAtIndex(index))
613 base::string16 old_display_name = GetNameOfProfileAtIndex(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());
619 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
620 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
621 UpdateSortForProfileIndex(index);
623 if (old_display_name != new_display_name) {
624 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
626 OnProfileNameChanged(profile_path, old_display_name));
630 void ProfileInfoCache::SetGAIAPictureOfProfileAtIndex(size_t index,
631 const gfx::Image* image) {
632 base::FilePath path = GetPathOfProfileAtIndex(index);
633 std::string key = CacheKeyFromProfilePath(path);
635 // Delete the old bitmap from cache.
636 std::map<std::string, gfx::Image*>::iterator it =
637 cached_avatar_images_.find(key);
638 if (it != cached_avatar_images_.end()) {
640 cached_avatar_images_.erase(it);
643 std::string old_file_name;
644 GetInfoForProfileAtIndex(index)->GetString(
645 kGAIAPictureFileNameKey, &old_file_name);
646 std::string new_file_name;
649 // Delete the old bitmap from disk.
650 if (!old_file_name.empty()) {
651 base::FilePath image_path = path.AppendASCII(old_file_name);
652 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
653 base::Bind(&DeleteBitmap, image_path));
656 // Save the new bitmap to disk.
658 old_file_name.empty() ? profiles::kGAIAPictureFileName : old_file_name;
659 base::FilePath image_path = path.AppendASCII(new_file_name);
660 SaveAvatarImageAtPath(
661 image, key, image_path, GetPathOfProfileAtIndex(index));
664 scoped_ptr<base::DictionaryValue> info(
665 GetInfoForProfileAtIndex(index)->DeepCopy());
666 info->SetString(kGAIAPictureFileNameKey, new_file_name);
667 // This takes ownership of |info|.
668 SetInfoForProfileAtIndex(index, info.release());
670 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
672 OnProfileAvatarChanged(path));
675 void ProfileInfoCache::SetIsUsingGAIAPictureOfProfileAtIndex(size_t index,
677 scoped_ptr<base::DictionaryValue> info(
678 GetInfoForProfileAtIndex(index)->DeepCopy());
679 info->SetBoolean(kUseGAIAPictureKey, value);
680 // This takes ownership of |info|.
681 SetInfoForProfileAtIndex(index, info.release());
683 // Retrieve some info to update observers who care about avatar changes.
684 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
685 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
687 OnProfileAvatarChanged(profile_path));
690 void ProfileInfoCache::SetProfileSigninRequiredAtIndex(size_t index,
692 if (value == ProfileIsSigninRequiredAtIndex(index))
695 scoped_ptr<base::DictionaryValue> info(
696 GetInfoForProfileAtIndex(index)->DeepCopy());
697 info->SetBoolean(kSigninRequiredKey, value);
698 // This takes ownership of |info|.
699 SetInfoForProfileAtIndex(index, info.release());
701 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
702 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
704 OnProfileSigninRequiredChanged(profile_path));
707 void ProfileInfoCache::SetProfileIsEphemeralAtIndex(size_t index, bool value) {
708 if (value == ProfileIsEphemeralAtIndex(index))
711 scoped_ptr<base::DictionaryValue> info(
712 GetInfoForProfileAtIndex(index)->DeepCopy());
713 info->SetBoolean(kProfileIsEphemeral, value);
714 // This takes ownership of |info|.
715 SetInfoForProfileAtIndex(index, info.release());
718 void ProfileInfoCache::SetProfileIsUsingDefaultNameAtIndex(
719 size_t index, bool value) {
720 if (value == ProfileIsUsingDefaultNameAtIndex(index))
723 scoped_ptr<base::DictionaryValue> info(
724 GetInfoForProfileAtIndex(index)->DeepCopy());
725 info->SetBoolean(kIsUsingDefaultNameKey, value);
726 // This takes ownership of |info|.
727 SetInfoForProfileAtIndex(index, info.release());
730 void ProfileInfoCache::SetProfileIsUsingDefaultAvatarAtIndex(
731 size_t index, bool value) {
732 if (value == ProfileIsUsingDefaultAvatarAtIndex(index))
735 scoped_ptr<base::DictionaryValue> info(
736 GetInfoForProfileAtIndex(index)->DeepCopy());
737 info->SetBoolean(kIsUsingDefaultAvatarKey, value);
738 // This takes ownership of |info|.
739 SetInfoForProfileAtIndex(index, info.release());
742 bool ProfileInfoCache::IsDefaultProfileName(const base::string16& name) {
743 // Check if it's a "First user" old-style name.
744 if (name == l10n_util::GetStringUTF16(IDS_DEFAULT_PROFILE_NAME) ||
745 name == l10n_util::GetStringUTF16(IDS_LEGACY_DEFAULT_PROFILE_NAME))
748 // Check if it's one of the old-style profile names.
749 for (size_t i = 0; i < arraysize(kDefaultNames); ++i) {
750 if (name == l10n_util::GetStringUTF16(kDefaultNames[i]))
754 // Check whether it's one of the "Person %d" style names.
755 std::string default_name_format = l10n_util::GetStringFUTF8(
756 IDS_NEW_NUMBERED_PROFILE_NAME, base::ASCIIToUTF16("%d"));
758 int generic_profile_number; // Unused. Just a placeholder for sscanf.
759 int assignments = sscanf(base::UTF16ToUTF8(name).c_str(),
760 default_name_format.c_str(),
761 &generic_profile_number);
762 // Unless it matched the format, this is a custom name.
763 return assignments == 1;
766 base::string16 ProfileInfoCache::ChooseNameForNewProfile(
767 size_t icon_index) const {
769 for (int name_index = 1; ; ++name_index) {
770 if (switches::IsNewAvatarMenu()) {
771 name = l10n_util::GetStringFUTF16Int(IDS_NEW_NUMBERED_PROFILE_NAME,
773 } else if (icon_index < profiles::GetGenericAvatarIconCount()) {
774 name = l10n_util::GetStringFUTF16Int(IDS_NUMBERED_PROFILE_NAME,
777 name = l10n_util::GetStringUTF16(
778 kDefaultNames[icon_index - profiles::GetGenericAvatarIconCount()]);
780 name.append(base::UTF8ToUTF16(base::IntToString(name_index)));
783 // Loop through previously named profiles to ensure we're not duplicating.
784 bool name_found = false;
785 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
786 if (GetNameOfProfileAtIndex(i) == name) {
796 size_t ProfileInfoCache::ChooseAvatarIconIndexForNewProfile() const {
797 size_t icon_index = 0;
798 // Try to find a unique, non-generic icon.
799 if (ChooseAvatarIconIndexForNewProfile(false, true, &icon_index))
801 // Try to find any unique icon.
802 if (ChooseAvatarIconIndexForNewProfile(true, true, &icon_index))
804 // Settle for any random icon, even if it's not unique.
805 if (ChooseAvatarIconIndexForNewProfile(true, false, &icon_index))
812 const base::FilePath& ProfileInfoCache::GetUserDataDir() const {
813 return user_data_dir_;
817 std::vector<base::string16> ProfileInfoCache::GetProfileNames() {
818 std::vector<base::string16> names;
819 PrefService* local_state = g_browser_process->local_state();
820 const base::DictionaryValue* cache = local_state->GetDictionary(
821 prefs::kProfileInfoCache);
823 for (base::DictionaryValue::Iterator it(*cache); !it.IsAtEnd();
825 const base::DictionaryValue* info = NULL;
826 it.value().GetAsDictionary(&info);
827 info->GetString(kNameKey, &name);
828 names.push_back(name);
834 void ProfileInfoCache::RegisterPrefs(PrefRegistrySimple* registry) {
835 registry->RegisterDictionaryPref(prefs::kProfileInfoCache);
838 void ProfileInfoCache::DownloadHighResAvatar(
840 const base::FilePath& profile_path) {
841 // Downloading is only supported on desktop.
842 #if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS)
846 // TODO(noms): We should check whether the file already exists on disk
847 // before trying to re-download it. For now, since this is behind a flag and
848 // the resources are still changing, re-download it every time the profile
849 // avatar changes, to make sure we have the latest copy.
850 std::string file_name = profiles::GetDefaultAvatarIconFileNameAtIndex(
852 // If the file is already being downloaded, don't start another download.
853 if (avatar_images_downloads_in_progress_[file_name])
856 // Start the download for this file. The cache takes ownership of the
857 // |avatar_downloader|, which will be deleted when the download completes, or
858 // if that never happens, when the ProfileInfoCache is destroyed.
859 ProfileAvatarDownloader* avatar_downloader = new ProfileAvatarDownloader(
863 avatar_images_downloads_in_progress_[file_name] = avatar_downloader;
864 avatar_downloader->Start();
867 void ProfileInfoCache::SaveAvatarImageAtPath(
868 const gfx::Image* image,
869 const std::string& key,
870 const base::FilePath& image_path,
871 const base::FilePath& profile_path) {
872 cached_avatar_images_[key] = new gfx::Image(*image);
874 scoped_ptr<ImageData> data(new ImageData);
875 scoped_refptr<base::RefCountedMemory> png_data = image->As1xPNGBytes();
876 data->assign(png_data->front(), png_data->front() + png_data->size());
879 LOG(ERROR) << "Failed to PNG encode the image.";
881 base::Closure callback = base::Bind(&ProfileInfoCache::OnAvatarPictureSaved,
882 AsWeakPtr(), key, profile_path);
884 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
885 base::Bind(&SaveBitmap, base::Passed(&data), image_path, callback));
889 const base::DictionaryValue* ProfileInfoCache::GetInfoForProfileAtIndex(
890 size_t index) const {
891 DCHECK_LT(index, GetNumberOfProfiles());
892 const base::DictionaryValue* cache =
893 prefs_->GetDictionary(prefs::kProfileInfoCache);
894 const base::DictionaryValue* info = NULL;
895 cache->GetDictionaryWithoutPathExpansion(sorted_keys_[index], &info);
899 void ProfileInfoCache::SetInfoQuietlyForProfileAtIndex(
900 size_t index, base::DictionaryValue* info) {
901 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
902 base::DictionaryValue* cache = update.Get();
903 cache->SetWithoutPathExpansion(sorted_keys_[index], info);
906 // TODO(noms): Switch to newer notification system.
907 void ProfileInfoCache::SetInfoForProfileAtIndex(size_t index,
908 base::DictionaryValue* info) {
909 SetInfoQuietlyForProfileAtIndex(index, info);
911 content::NotificationService::current()->Notify(
912 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
913 content::NotificationService::AllSources(),
914 content::NotificationService::NoDetails());
917 std::string ProfileInfoCache::CacheKeyFromProfilePath(
918 const base::FilePath& profile_path) const {
919 DCHECK(user_data_dir_ == profile_path.DirName());
920 base::FilePath base_name = profile_path.BaseName();
921 return base_name.MaybeAsASCII();
924 std::vector<std::string>::iterator ProfileInfoCache::FindPositionForProfile(
925 const std::string& search_key,
926 const base::string16& search_name) {
927 base::string16 search_name_l = base::i18n::ToLower(search_name);
928 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
929 base::string16 name_l = base::i18n::ToLower(GetNameOfProfileAtIndex(i));
930 int name_compare = search_name_l.compare(name_l);
931 if (name_compare < 0)
932 return sorted_keys_.begin() + i;
933 if (name_compare == 0) {
934 int key_compare = search_key.compare(sorted_keys_[i]);
936 return sorted_keys_.begin() + i;
939 return sorted_keys_.end();
942 bool ProfileInfoCache::IconIndexIsUnique(size_t icon_index) const {
943 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
944 if (GetAvatarIconIndexOfProfileAtIndex(i) == icon_index)
950 bool ProfileInfoCache::ChooseAvatarIconIndexForNewProfile(
951 bool allow_generic_icon,
953 size_t* out_icon_index) const {
954 // Always allow all icons for new profiles if using the
955 // --new-avatar-menu flag.
956 if (switches::IsNewAvatarMenu())
957 allow_generic_icon = true;
958 size_t start = allow_generic_icon ? 0 : profiles::GetGenericAvatarIconCount();
959 size_t end = profiles::GetDefaultAvatarIconCount();
960 size_t count = end - start;
962 int rand = base::RandInt(0, count);
963 for (size_t i = 0; i < count; ++i) {
964 size_t icon_index = start + (rand + i) % count;
965 if (!must_be_unique || IconIndexIsUnique(icon_index)) {
966 *out_icon_index = icon_index;
974 void ProfileInfoCache::UpdateSortForProfileIndex(size_t index) {
975 base::string16 name = GetNameOfProfileAtIndex(index);
977 // Remove and reinsert key in |sorted_keys_| to alphasort.
978 std::string key = CacheKeyFromProfilePath(GetPathOfProfileAtIndex(index));
979 std::vector<std::string>::iterator key_it =
980 std::find(sorted_keys_.begin(), sorted_keys_.end(), key);
981 DCHECK(key_it != sorted_keys_.end());
982 sorted_keys_.erase(key_it);
983 sorted_keys_.insert(FindPositionForProfile(key, name), key);
985 content::NotificationService::current()->Notify(
986 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
987 content::NotificationService::AllSources(),
988 content::NotificationService::NoDetails());
991 const gfx::Image* ProfileInfoCache::GetHighResAvatarOfProfileAtIndex(
992 size_t index) const {
993 int avatar_index = GetAvatarIconIndexOfProfileAtIndex(index);
994 std::string key = profiles::GetDefaultAvatarIconFileNameAtIndex(avatar_index);
996 if (!strcmp(key.c_str(), profiles::GetNoHighResAvatarFileName()))
999 base::FilePath image_path =
1000 profiles::GetPathOfHighResAvatarAtIndex(avatar_index);
1001 return LoadAvatarPictureFromPath(key, image_path);
1004 const gfx::Image* ProfileInfoCache::LoadAvatarPictureFromPath(
1005 const std::string& key,
1006 const base::FilePath& image_path) const {
1007 // If the picture is already loaded then use it.
1008 if (cached_avatar_images_.count(key)) {
1009 if (cached_avatar_images_[key]->IsEmpty())
1011 return cached_avatar_images_[key];
1014 // If the picture is already being loaded then don't try loading it again.
1015 if (cached_avatar_images_loading_[key])
1017 cached_avatar_images_loading_[key] = true;
1019 gfx::Image** image = new gfx::Image*;
1020 BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE,
1021 base::Bind(&ReadBitmap, image_path, image),
1022 base::Bind(&ProfileInfoCache::OnAvatarPictureLoaded,
1023 const_cast<ProfileInfoCache*>(this)->AsWeakPtr(), key, image));
1027 void ProfileInfoCache::OnAvatarPictureLoaded(const std::string& key,
1028 gfx::Image** image) const {
1029 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1031 cached_avatar_images_loading_[key] = false;
1032 delete cached_avatar_images_[key];
1035 cached_avatar_images_[key] = *image;
1037 // Place an empty image in the cache to avoid reloading it again.
1038 cached_avatar_images_[key] = new gfx::Image();
1042 content::NotificationService::current()->Notify(
1043 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
1044 content::NotificationService::AllSources(),
1045 content::NotificationService::NoDetails());
1048 void ProfileInfoCache::OnAvatarPictureSaved(
1049 const std::string& file_name,
1050 const base::FilePath& profile_path) {
1051 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1053 content::NotificationService::current()->Notify(
1054 chrome::NOTIFICATION_PROFILE_CACHE_PICTURE_SAVED,
1055 content::NotificationService::AllSources(),
1056 content::NotificationService::NoDetails());
1058 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
1060 OnProfileAvatarChanged(profile_path));
1062 // Remove the file from the list of downloads in progress. Note that this list
1063 // only contains the high resolution avatars, and not the Gaia profile images.
1064 if (!avatar_images_downloads_in_progress_[file_name])
1067 delete avatar_images_downloads_in_progress_[file_name];
1068 avatar_images_downloads_in_progress_[file_name] = NULL;