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 and migrate any legacy
174 if (switches::IsNewAvatarMenu())
175 MigrateLegacyProfileNamesAndDownloadAvatars();
178 ProfileInfoCache::~ProfileInfoCache() {
179 STLDeleteContainerPairSecondPointers(
180 cached_avatar_images_.begin(), cached_avatar_images_.end());
181 STLDeleteContainerPairSecondPointers(
182 avatar_images_downloads_in_progress_.begin(),
183 avatar_images_downloads_in_progress_.end());
186 void ProfileInfoCache::AddProfileToCache(
187 const base::FilePath& profile_path,
188 const base::string16& name,
189 const base::string16& username,
191 const std::string& supervised_user_id) {
192 std::string key = CacheKeyFromProfilePath(profile_path);
193 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
194 base::DictionaryValue* cache = update.Get();
196 scoped_ptr<base::DictionaryValue> info(new base::DictionaryValue);
197 info->SetString(kNameKey, name);
198 info->SetString(kUserNameKey, username);
199 info->SetString(kAvatarIconKey,
200 profiles::GetDefaultAvatarIconUrl(icon_index));
201 // Default value for whether background apps are running is false.
202 info->SetBoolean(kBackgroundAppsKey, false);
203 info->SetString(kSupervisedUserId, supervised_user_id);
204 info->SetBoolean(kIsOmittedFromProfileListKey, !supervised_user_id.empty());
205 info->SetBoolean(kProfileIsEphemeral, false);
206 info->SetBoolean(kIsUsingDefaultNameKey, IsDefaultProfileName(name));
207 // Assume newly created profiles use a default avatar.
208 info->SetBoolean(kIsUsingDefaultAvatarKey, true);
209 cache->SetWithoutPathExpansion(key, info.release());
211 sorted_keys_.insert(FindPositionForProfile(key, name), key);
213 if (switches::IsNewAvatarMenu())
214 DownloadHighResAvatar(icon_index, profile_path);
216 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
218 OnProfileAdded(profile_path));
220 content::NotificationService::current()->Notify(
221 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
222 content::NotificationService::AllSources(),
223 content::NotificationService::NoDetails());
226 void ProfileInfoCache::AddObserver(ProfileInfoCacheObserver* obs) {
227 observer_list_.AddObserver(obs);
230 void ProfileInfoCache::RemoveObserver(ProfileInfoCacheObserver* obs) {
231 observer_list_.RemoveObserver(obs);
234 void ProfileInfoCache::DeleteProfileFromCache(
235 const base::FilePath& profile_path) {
236 size_t profile_index = GetIndexOfProfileWithPath(profile_path);
237 if (profile_index == std::string::npos) {
241 base::string16 name = GetNameOfProfileAtIndex(profile_index);
243 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
245 OnProfileWillBeRemoved(profile_path));
247 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
248 base::DictionaryValue* cache = update.Get();
249 std::string key = CacheKeyFromProfilePath(profile_path);
250 cache->Remove(key, NULL);
251 sorted_keys_.erase(std::find(sorted_keys_.begin(), sorted_keys_.end(), key));
253 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
255 OnProfileWasRemoved(profile_path, name));
257 content::NotificationService::current()->Notify(
258 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
259 content::NotificationService::AllSources(),
260 content::NotificationService::NoDetails());
263 size_t ProfileInfoCache::GetNumberOfProfiles() const {
264 return sorted_keys_.size();
267 size_t ProfileInfoCache::GetIndexOfProfileWithPath(
268 const base::FilePath& profile_path) const {
269 if (profile_path.DirName() != user_data_dir_)
270 return std::string::npos;
271 std::string search_key = CacheKeyFromProfilePath(profile_path);
272 for (size_t i = 0; i < sorted_keys_.size(); ++i) {
273 if (sorted_keys_[i] == search_key)
276 return std::string::npos;
279 base::string16 ProfileInfoCache::GetNameOfProfileAtIndex(size_t index) const {
281 // Unless the user has customized the profile name, we should use the
282 // profile's Gaia given name, if it's available.
283 if (ProfileIsUsingDefaultNameAtIndex(index)) {
284 base::string16 given_name = GetGAIAGivenNameOfProfileAtIndex(index);
285 name = given_name.empty() ? GetGAIANameOfProfileAtIndex(index) : given_name;
288 GetInfoForProfileAtIndex(index)->GetString(kNameKey, &name);
292 base::string16 ProfileInfoCache::GetShortcutNameOfProfileAtIndex(size_t index)
294 base::string16 shortcut_name;
295 GetInfoForProfileAtIndex(index)->GetString(
296 kShortcutNameKey, &shortcut_name);
297 return shortcut_name;
300 base::FilePath ProfileInfoCache::GetPathOfProfileAtIndex(size_t index) const {
301 return user_data_dir_.AppendASCII(sorted_keys_[index]);
304 base::Time ProfileInfoCache::GetProfileActiveTimeAtIndex(size_t index) const {
306 if (GetInfoForProfileAtIndex(index)->GetDouble(kActiveTimeKey, &dt)) {
307 return base::Time::FromDoubleT(dt);
313 base::string16 ProfileInfoCache::GetUserNameOfProfileAtIndex(
314 size_t index) const {
315 base::string16 user_name;
316 GetInfoForProfileAtIndex(index)->GetString(kUserNameKey, &user_name);
320 const gfx::Image& ProfileInfoCache::GetAvatarIconOfProfileAtIndex(
321 size_t index) const {
322 if (IsUsingGAIAPictureOfProfileAtIndex(index)) {
323 const gfx::Image* image = GetGAIAPictureOfProfileAtIndex(index);
328 // Use the high resolution version of the avatar if it exists.
329 if (switches::IsNewAvatarMenu()) {
330 const gfx::Image* image = GetHighResAvatarOfProfileAtIndex(index);
335 int resource_id = profiles::GetDefaultAvatarIconResourceIDAtIndex(
336 GetAvatarIconIndexOfProfileAtIndex(index));
337 return ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
340 std::string ProfileInfoCache::GetLocalAuthCredentialsOfProfileAtIndex(
341 size_t index) const {
342 std::string credentials;
343 GetInfoForProfileAtIndex(index)->GetString(kAuthCredentialsKey, &credentials);
347 bool ProfileInfoCache::GetBackgroundStatusOfProfileAtIndex(
348 size_t index) const {
349 bool background_app_status;
350 if (!GetInfoForProfileAtIndex(index)->GetBoolean(kBackgroundAppsKey,
351 &background_app_status)) {
354 return background_app_status;
357 base::string16 ProfileInfoCache::GetGAIANameOfProfileAtIndex(
358 size_t index) const {
360 GetInfoForProfileAtIndex(index)->GetString(kGAIANameKey, &name);
364 base::string16 ProfileInfoCache::GetGAIAGivenNameOfProfileAtIndex(
365 size_t index) const {
367 GetInfoForProfileAtIndex(index)->GetString(kGAIAGivenNameKey, &name);
371 const gfx::Image* ProfileInfoCache::GetGAIAPictureOfProfileAtIndex(
372 size_t index) const {
373 base::FilePath path = GetPathOfProfileAtIndex(index);
374 std::string key = CacheKeyFromProfilePath(path);
376 std::string file_name;
377 GetInfoForProfileAtIndex(index)->GetString(
378 kGAIAPictureFileNameKey, &file_name);
380 // If the picture is not on disk then return NULL.
381 if (file_name.empty())
384 base::FilePath image_path = path.AppendASCII(file_name);
385 return LoadAvatarPictureFromPath(key, image_path);
388 bool ProfileInfoCache::IsUsingGAIAPictureOfProfileAtIndex(size_t index) const {
390 GetInfoForProfileAtIndex(index)->GetBoolean(kUseGAIAPictureKey, &value);
392 // Prefer the GAIA avatar over a non-customized avatar.
393 value = ProfileIsUsingDefaultAvatarAtIndex(index) &&
394 GetGAIAPictureOfProfileAtIndex(index);
399 bool ProfileInfoCache::ProfileIsSupervisedAtIndex(size_t index) const {
400 return !GetSupervisedUserIdOfProfileAtIndex(index).empty();
403 bool ProfileInfoCache::IsOmittedProfileAtIndex(size_t index) const {
405 GetInfoForProfileAtIndex(index)->GetBoolean(kIsOmittedFromProfileListKey,
410 bool ProfileInfoCache::ProfileIsSigninRequiredAtIndex(size_t index) const {
412 GetInfoForProfileAtIndex(index)->GetBoolean(kSigninRequiredKey, &value);
416 std::string ProfileInfoCache::GetSupervisedUserIdOfProfileAtIndex(
417 size_t index) const {
418 std::string supervised_user_id;
419 GetInfoForProfileAtIndex(index)->GetString(kSupervisedUserId,
420 &supervised_user_id);
421 return supervised_user_id;
424 bool ProfileInfoCache::ProfileIsEphemeralAtIndex(size_t index) const {
426 GetInfoForProfileAtIndex(index)->GetBoolean(kProfileIsEphemeral, &value);
430 bool ProfileInfoCache::ProfileIsUsingDefaultNameAtIndex(size_t index) const {
432 GetInfoForProfileAtIndex(index)->GetBoolean(kIsUsingDefaultNameKey, &value);
436 bool ProfileInfoCache::ProfileIsUsingDefaultAvatarAtIndex(size_t index) const {
438 GetInfoForProfileAtIndex(index)->GetBoolean(kIsUsingDefaultAvatarKey, &value);
442 size_t ProfileInfoCache::GetAvatarIconIndexOfProfileAtIndex(size_t index)
444 std::string icon_url;
445 GetInfoForProfileAtIndex(index)->GetString(kAvatarIconKey, &icon_url);
446 size_t icon_index = 0;
447 if (!profiles::IsDefaultAvatarIconUrl(icon_url, &icon_index))
448 DLOG(WARNING) << "Unknown avatar icon: " << icon_url;
453 void ProfileInfoCache::SetProfileActiveTimeAtIndex(size_t index) {
454 scoped_ptr<base::DictionaryValue> info(
455 GetInfoForProfileAtIndex(index)->DeepCopy());
456 info->SetDouble(kActiveTimeKey, base::Time::Now().ToDoubleT());
457 // This takes ownership of |info|.
458 SetInfoQuietlyForProfileAtIndex(index, info.release());
461 void ProfileInfoCache::SetNameOfProfileAtIndex(size_t index,
462 const base::string16& name) {
463 scoped_ptr<base::DictionaryValue> info(
464 GetInfoForProfileAtIndex(index)->DeepCopy());
465 base::string16 current_name;
466 info->GetString(kNameKey, ¤t_name);
467 if (name == current_name)
470 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
471 info->SetString(kNameKey, name);
473 // This takes ownership of |info|.
474 SetInfoForProfileAtIndex(index, info.release());
476 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
477 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
478 UpdateSortForProfileIndex(index);
480 if (old_display_name != new_display_name) {
481 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
483 OnProfileNameChanged(profile_path, old_display_name));
487 void ProfileInfoCache::SetShortcutNameOfProfileAtIndex(
489 const base::string16& shortcut_name) {
490 if (shortcut_name == GetShortcutNameOfProfileAtIndex(index))
492 scoped_ptr<base::DictionaryValue> info(
493 GetInfoForProfileAtIndex(index)->DeepCopy());
494 info->SetString(kShortcutNameKey, shortcut_name);
495 // This takes ownership of |info|.
496 SetInfoForProfileAtIndex(index, info.release());
499 void ProfileInfoCache::SetUserNameOfProfileAtIndex(
501 const base::string16& user_name) {
502 if (user_name == GetUserNameOfProfileAtIndex(index))
505 scoped_ptr<base::DictionaryValue> info(
506 GetInfoForProfileAtIndex(index)->DeepCopy());
507 info->SetString(kUserNameKey, user_name);
508 // This takes ownership of |info|.
509 SetInfoForProfileAtIndex(index, info.release());
512 void ProfileInfoCache::SetAvatarIconOfProfileAtIndex(size_t index,
514 scoped_ptr<base::DictionaryValue> info(
515 GetInfoForProfileAtIndex(index)->DeepCopy());
516 info->SetString(kAvatarIconKey,
517 profiles::GetDefaultAvatarIconUrl(icon_index));
518 // This takes ownership of |info|.
519 SetInfoForProfileAtIndex(index, info.release());
521 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
523 // If needed, start downloading the high-res avatar.
524 if (switches::IsNewAvatarMenu())
525 DownloadHighResAvatar(icon_index, profile_path);
527 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
529 OnProfileAvatarChanged(profile_path));
532 void ProfileInfoCache::SetIsOmittedProfileAtIndex(size_t index,
534 if (IsOmittedProfileAtIndex(index) == is_omitted)
536 scoped_ptr<base::DictionaryValue> info(
537 GetInfoForProfileAtIndex(index)->DeepCopy());
538 info->SetBoolean(kIsOmittedFromProfileListKey, is_omitted);
539 // This takes ownership of |info|.
540 SetInfoForProfileAtIndex(index, info.release());
543 void ProfileInfoCache::SetSupervisedUserIdOfProfileAtIndex(
545 const std::string& id) {
546 if (GetSupervisedUserIdOfProfileAtIndex(index) == id)
548 scoped_ptr<base::DictionaryValue> info(
549 GetInfoForProfileAtIndex(index)->DeepCopy());
550 info->SetString(kSupervisedUserId, id);
551 // This takes ownership of |info|.
552 SetInfoForProfileAtIndex(index, info.release());
554 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
555 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
557 OnProfileSupervisedUserIdChanged(profile_path));
560 void ProfileInfoCache::SetLocalAuthCredentialsOfProfileAtIndex(
562 const std::string& credentials) {
563 scoped_ptr<base::DictionaryValue> info(
564 GetInfoForProfileAtIndex(index)->DeepCopy());
565 info->SetString(kAuthCredentialsKey, credentials);
566 // This takes ownership of |info|.
567 SetInfoForProfileAtIndex(index, info.release());
570 void ProfileInfoCache::SetBackgroundStatusOfProfileAtIndex(
572 bool running_background_apps) {
573 if (GetBackgroundStatusOfProfileAtIndex(index) == running_background_apps)
575 scoped_ptr<base::DictionaryValue> info(
576 GetInfoForProfileAtIndex(index)->DeepCopy());
577 info->SetBoolean(kBackgroundAppsKey, running_background_apps);
578 // This takes ownership of |info|.
579 SetInfoForProfileAtIndex(index, info.release());
582 void ProfileInfoCache::SetGAIANameOfProfileAtIndex(size_t index,
583 const base::string16& name) {
584 if (name == GetGAIANameOfProfileAtIndex(index))
587 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
588 scoped_ptr<base::DictionaryValue> info(
589 GetInfoForProfileAtIndex(index)->DeepCopy());
590 info->SetString(kGAIANameKey, name);
591 // This takes ownership of |info|.
592 SetInfoForProfileAtIndex(index, info.release());
593 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
594 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
595 UpdateSortForProfileIndex(index);
597 if (old_display_name != new_display_name) {
598 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
600 OnProfileNameChanged(profile_path, old_display_name));
604 void ProfileInfoCache::SetGAIAGivenNameOfProfileAtIndex(
606 const base::string16& name) {
607 if (name == GetGAIAGivenNameOfProfileAtIndex(index))
610 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
611 scoped_ptr<base::DictionaryValue> info(
612 GetInfoForProfileAtIndex(index)->DeepCopy());
613 info->SetString(kGAIAGivenNameKey, name);
614 // This takes ownership of |info|.
615 SetInfoForProfileAtIndex(index, info.release());
616 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
617 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
618 UpdateSortForProfileIndex(index);
620 if (old_display_name != new_display_name) {
621 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
623 OnProfileNameChanged(profile_path, old_display_name));
627 void ProfileInfoCache::SetGAIAPictureOfProfileAtIndex(size_t index,
628 const gfx::Image* image) {
629 base::FilePath path = GetPathOfProfileAtIndex(index);
630 std::string key = CacheKeyFromProfilePath(path);
632 // Delete the old bitmap from cache.
633 std::map<std::string, gfx::Image*>::iterator it =
634 cached_avatar_images_.find(key);
635 if (it != cached_avatar_images_.end()) {
637 cached_avatar_images_.erase(it);
640 std::string old_file_name;
641 GetInfoForProfileAtIndex(index)->GetString(
642 kGAIAPictureFileNameKey, &old_file_name);
643 std::string new_file_name;
646 // Delete the old bitmap from disk.
647 if (!old_file_name.empty()) {
648 base::FilePath image_path = path.AppendASCII(old_file_name);
649 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
650 base::Bind(&DeleteBitmap, image_path));
653 // Save the new bitmap to disk.
655 old_file_name.empty() ? profiles::kGAIAPictureFileName : old_file_name;
656 base::FilePath image_path = path.AppendASCII(new_file_name);
657 SaveAvatarImageAtPath(
658 image, key, image_path, GetPathOfProfileAtIndex(index));
661 scoped_ptr<base::DictionaryValue> info(
662 GetInfoForProfileAtIndex(index)->DeepCopy());
663 info->SetString(kGAIAPictureFileNameKey, new_file_name);
664 // This takes ownership of |info|.
665 SetInfoForProfileAtIndex(index, info.release());
667 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
669 OnProfileAvatarChanged(path));
672 void ProfileInfoCache::SetIsUsingGAIAPictureOfProfileAtIndex(size_t index,
674 scoped_ptr<base::DictionaryValue> info(
675 GetInfoForProfileAtIndex(index)->DeepCopy());
676 info->SetBoolean(kUseGAIAPictureKey, value);
677 // This takes ownership of |info|.
678 SetInfoForProfileAtIndex(index, info.release());
680 // Retrieve some info to update observers who care about avatar changes.
681 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
682 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
684 OnProfileAvatarChanged(profile_path));
687 void ProfileInfoCache::SetProfileSigninRequiredAtIndex(size_t index,
689 if (value == ProfileIsSigninRequiredAtIndex(index))
692 scoped_ptr<base::DictionaryValue> info(
693 GetInfoForProfileAtIndex(index)->DeepCopy());
694 info->SetBoolean(kSigninRequiredKey, value);
695 // This takes ownership of |info|.
696 SetInfoForProfileAtIndex(index, info.release());
698 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
699 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
701 OnProfileSigninRequiredChanged(profile_path));
704 void ProfileInfoCache::SetProfileIsEphemeralAtIndex(size_t index, bool value) {
705 if (value == ProfileIsEphemeralAtIndex(index))
708 scoped_ptr<base::DictionaryValue> info(
709 GetInfoForProfileAtIndex(index)->DeepCopy());
710 info->SetBoolean(kProfileIsEphemeral, value);
711 // This takes ownership of |info|.
712 SetInfoForProfileAtIndex(index, info.release());
715 void ProfileInfoCache::SetProfileIsUsingDefaultNameAtIndex(
716 size_t index, bool value) {
717 if (value == ProfileIsUsingDefaultNameAtIndex(index))
720 scoped_ptr<base::DictionaryValue> info(
721 GetInfoForProfileAtIndex(index)->DeepCopy());
722 info->SetBoolean(kIsUsingDefaultNameKey, value);
723 // This takes ownership of |info|.
724 SetInfoForProfileAtIndex(index, info.release());
727 void ProfileInfoCache::SetProfileIsUsingDefaultAvatarAtIndex(
728 size_t index, bool value) {
729 if (value == ProfileIsUsingDefaultAvatarAtIndex(index))
732 scoped_ptr<base::DictionaryValue> info(
733 GetInfoForProfileAtIndex(index)->DeepCopy());
734 info->SetBoolean(kIsUsingDefaultAvatarKey, value);
735 // This takes ownership of |info|.
736 SetInfoForProfileAtIndex(index, info.release());
739 bool ProfileInfoCache::IsDefaultProfileName(const base::string16& name) {
740 // Check if it's a "First user" old-style name.
741 if (name == l10n_util::GetStringUTF16(IDS_DEFAULT_PROFILE_NAME) ||
742 name == l10n_util::GetStringUTF16(IDS_LEGACY_DEFAULT_PROFILE_NAME))
745 // Check if it's one of the old-style profile names.
746 for (size_t i = 0; i < arraysize(kDefaultNames); ++i) {
747 if (name == l10n_util::GetStringUTF16(kDefaultNames[i]))
751 // Check whether it's one of the "Person %d" style names.
752 std::string default_name_format = l10n_util::GetStringFUTF8(
753 IDS_NEW_NUMBERED_PROFILE_NAME, base::ASCIIToUTF16("%d"));
755 int generic_profile_number; // Unused. Just a placeholder for sscanf.
756 int assignments = sscanf(base::UTF16ToUTF8(name).c_str(),
757 default_name_format.c_str(),
758 &generic_profile_number);
759 // Unless it matched the format, this is a custom name.
760 return assignments == 1;
763 base::string16 ProfileInfoCache::ChooseNameForNewProfile(
764 size_t icon_index) const {
766 for (int name_index = 1; ; ++name_index) {
767 if (switches::IsNewAvatarMenu()) {
768 name = l10n_util::GetStringFUTF16Int(IDS_NEW_NUMBERED_PROFILE_NAME,
770 } else if (icon_index < profiles::GetGenericAvatarIconCount()) {
771 name = l10n_util::GetStringFUTF16Int(IDS_NUMBERED_PROFILE_NAME,
774 name = l10n_util::GetStringUTF16(
775 kDefaultNames[icon_index - profiles::GetGenericAvatarIconCount()]);
777 name.append(base::UTF8ToUTF16(base::IntToString(name_index)));
780 // Loop through previously named profiles to ensure we're not duplicating.
781 bool name_found = false;
782 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
783 if (GetNameOfProfileAtIndex(i) == name) {
793 size_t ProfileInfoCache::ChooseAvatarIconIndexForNewProfile() const {
794 size_t icon_index = 0;
795 // Try to find a unique, non-generic icon.
796 if (ChooseAvatarIconIndexForNewProfile(false, true, &icon_index))
798 // Try to find any unique icon.
799 if (ChooseAvatarIconIndexForNewProfile(true, true, &icon_index))
801 // Settle for any random icon, even if it's not unique.
802 if (ChooseAvatarIconIndexForNewProfile(true, false, &icon_index))
809 const base::FilePath& ProfileInfoCache::GetUserDataDir() const {
810 return user_data_dir_;
814 std::vector<base::string16> ProfileInfoCache::GetProfileNames() {
815 std::vector<base::string16> names;
816 PrefService* local_state = g_browser_process->local_state();
817 const base::DictionaryValue* cache = local_state->GetDictionary(
818 prefs::kProfileInfoCache);
820 for (base::DictionaryValue::Iterator it(*cache); !it.IsAtEnd();
822 const base::DictionaryValue* info = NULL;
823 it.value().GetAsDictionary(&info);
824 info->GetString(kNameKey, &name);
825 names.push_back(name);
831 void ProfileInfoCache::RegisterPrefs(PrefRegistrySimple* registry) {
832 registry->RegisterDictionaryPref(prefs::kProfileInfoCache);
835 void ProfileInfoCache::DownloadHighResAvatar(
837 const base::FilePath& profile_path) {
838 // Downloading is only supported on desktop.
839 #if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS)
843 // TODO(noms): We should check whether the file already exists on disk
844 // before trying to re-download it. For now, since this is behind a flag and
845 // the resources are still changing, re-download it every time the profile
846 // avatar changes, to make sure we have the latest copy.
847 std::string file_name = profiles::GetDefaultAvatarIconFileNameAtIndex(
849 // If the file is already being downloaded, don't start another download.
850 if (avatar_images_downloads_in_progress_[file_name])
853 // Start the download for this file. The cache takes ownership of the
854 // |avatar_downloader|, which will be deleted when the download completes, or
855 // if that never happens, when the ProfileInfoCache is destroyed.
856 ProfileAvatarDownloader* avatar_downloader = new ProfileAvatarDownloader(
860 avatar_images_downloads_in_progress_[file_name] = avatar_downloader;
861 avatar_downloader->Start();
864 void ProfileInfoCache::SaveAvatarImageAtPath(
865 const gfx::Image* image,
866 const std::string& key,
867 const base::FilePath& image_path,
868 const base::FilePath& profile_path) {
869 cached_avatar_images_[key] = new gfx::Image(*image);
871 scoped_ptr<ImageData> data(new ImageData);
872 scoped_refptr<base::RefCountedMemory> png_data = image->As1xPNGBytes();
873 data->assign(png_data->front(), png_data->front() + png_data->size());
876 LOG(ERROR) << "Failed to PNG encode the image.";
878 base::Closure callback = base::Bind(&ProfileInfoCache::OnAvatarPictureSaved,
879 AsWeakPtr(), key, profile_path);
881 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
882 base::Bind(&SaveBitmap, base::Passed(&data), image_path, callback));
886 const base::DictionaryValue* ProfileInfoCache::GetInfoForProfileAtIndex(
887 size_t index) const {
888 DCHECK_LT(index, GetNumberOfProfiles());
889 const base::DictionaryValue* cache =
890 prefs_->GetDictionary(prefs::kProfileInfoCache);
891 const base::DictionaryValue* info = NULL;
892 cache->GetDictionaryWithoutPathExpansion(sorted_keys_[index], &info);
896 void ProfileInfoCache::SetInfoQuietlyForProfileAtIndex(
897 size_t index, base::DictionaryValue* info) {
898 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
899 base::DictionaryValue* cache = update.Get();
900 cache->SetWithoutPathExpansion(sorted_keys_[index], info);
903 // TODO(noms): Switch to newer notification system.
904 void ProfileInfoCache::SetInfoForProfileAtIndex(size_t index,
905 base::DictionaryValue* info) {
906 SetInfoQuietlyForProfileAtIndex(index, info);
908 content::NotificationService::current()->Notify(
909 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
910 content::NotificationService::AllSources(),
911 content::NotificationService::NoDetails());
914 std::string ProfileInfoCache::CacheKeyFromProfilePath(
915 const base::FilePath& profile_path) const {
916 DCHECK(user_data_dir_ == profile_path.DirName());
917 base::FilePath base_name = profile_path.BaseName();
918 return base_name.MaybeAsASCII();
921 std::vector<std::string>::iterator ProfileInfoCache::FindPositionForProfile(
922 const std::string& search_key,
923 const base::string16& search_name) {
924 base::string16 search_name_l = base::i18n::ToLower(search_name);
925 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
926 base::string16 name_l = base::i18n::ToLower(GetNameOfProfileAtIndex(i));
927 int name_compare = search_name_l.compare(name_l);
928 if (name_compare < 0)
929 return sorted_keys_.begin() + i;
930 if (name_compare == 0) {
931 int key_compare = search_key.compare(sorted_keys_[i]);
933 return sorted_keys_.begin() + i;
936 return sorted_keys_.end();
939 bool ProfileInfoCache::IconIndexIsUnique(size_t icon_index) const {
940 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
941 if (GetAvatarIconIndexOfProfileAtIndex(i) == icon_index)
947 bool ProfileInfoCache::ChooseAvatarIconIndexForNewProfile(
948 bool allow_generic_icon,
950 size_t* out_icon_index) const {
951 // Always allow all icons for new profiles if using the
952 // --new-avatar-menu flag.
953 if (switches::IsNewAvatarMenu())
954 allow_generic_icon = true;
955 size_t start = allow_generic_icon ? 0 : profiles::GetGenericAvatarIconCount();
956 size_t end = profiles::GetDefaultAvatarIconCount();
957 size_t count = end - start;
959 int rand = base::RandInt(0, count);
960 for (size_t i = 0; i < count; ++i) {
961 size_t icon_index = start + (rand + i) % count;
962 if (!must_be_unique || IconIndexIsUnique(icon_index)) {
963 *out_icon_index = icon_index;
971 void ProfileInfoCache::UpdateSortForProfileIndex(size_t index) {
972 base::string16 name = GetNameOfProfileAtIndex(index);
974 // Remove and reinsert key in |sorted_keys_| to alphasort.
975 std::string key = CacheKeyFromProfilePath(GetPathOfProfileAtIndex(index));
976 std::vector<std::string>::iterator key_it =
977 std::find(sorted_keys_.begin(), sorted_keys_.end(), key);
978 DCHECK(key_it != sorted_keys_.end());
979 sorted_keys_.erase(key_it);
980 sorted_keys_.insert(FindPositionForProfile(key, name), key);
982 content::NotificationService::current()->Notify(
983 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
984 content::NotificationService::AllSources(),
985 content::NotificationService::NoDetails());
988 const gfx::Image* ProfileInfoCache::GetHighResAvatarOfProfileAtIndex(
989 size_t index) const {
990 int avatar_index = GetAvatarIconIndexOfProfileAtIndex(index);
991 std::string key = profiles::GetDefaultAvatarIconFileNameAtIndex(avatar_index);
993 if (!strcmp(key.c_str(), profiles::GetNoHighResAvatarFileName()))
996 base::FilePath image_path =
997 profiles::GetPathOfHighResAvatarAtIndex(avatar_index);
998 return LoadAvatarPictureFromPath(key, image_path);
1001 const gfx::Image* ProfileInfoCache::LoadAvatarPictureFromPath(
1002 const std::string& key,
1003 const base::FilePath& image_path) const {
1004 // If the picture is already loaded then use it.
1005 if (cached_avatar_images_.count(key)) {
1006 if (cached_avatar_images_[key]->IsEmpty())
1008 return cached_avatar_images_[key];
1011 // If the picture is already being loaded then don't try loading it again.
1012 if (cached_avatar_images_loading_[key])
1014 cached_avatar_images_loading_[key] = true;
1016 gfx::Image** image = new gfx::Image*;
1017 BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE,
1018 base::Bind(&ReadBitmap, image_path, image),
1019 base::Bind(&ProfileInfoCache::OnAvatarPictureLoaded,
1020 const_cast<ProfileInfoCache*>(this)->AsWeakPtr(), key, image));
1024 void ProfileInfoCache::OnAvatarPictureLoaded(const std::string& key,
1025 gfx::Image** image) const {
1026 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1028 cached_avatar_images_loading_[key] = false;
1029 delete cached_avatar_images_[key];
1032 cached_avatar_images_[key] = *image;
1034 // Place an empty image in the cache to avoid reloading it again.
1035 cached_avatar_images_[key] = new gfx::Image();
1039 content::NotificationService::current()->Notify(
1040 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
1041 content::NotificationService::AllSources(),
1042 content::NotificationService::NoDetails());
1045 void ProfileInfoCache::OnAvatarPictureSaved(
1046 const std::string& file_name,
1047 const base::FilePath& profile_path) {
1048 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1050 content::NotificationService::current()->Notify(
1051 chrome::NOTIFICATION_PROFILE_CACHE_PICTURE_SAVED,
1052 content::NotificationService::AllSources(),
1053 content::NotificationService::NoDetails());
1055 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
1057 OnProfileAvatarChanged(profile_path));
1059 // Remove the file from the list of downloads in progress. Note that this list
1060 // only contains the high resolution avatars, and not the Gaia profile images.
1061 if (!avatar_images_downloads_in_progress_[file_name])
1064 delete avatar_images_downloads_in_progress_[file_name];
1065 avatar_images_downloads_in_progress_[file_name] = NULL;
1068 void ProfileInfoCache::MigrateLegacyProfileNamesAndDownloadAvatars() {
1069 DCHECK(switches::IsNewAvatarMenu());
1071 // Only do this on desktop platforms.
1072 #if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)
1073 // Migrate any legacy profile names ("First user", "Default Profile") to
1074 // new style default names ("Person 1"). The problem here is that every
1075 // time you rename a profile, the ProfileInfoCache sorts itself, so
1076 // whatever you were iterating through is no longer valid. We need to
1077 // save a list of the profile paths (which thankfully do not change) that
1078 // need to be renamed. We also can't pre-compute the new names, as they
1079 // depend on the names of all the other profiles in the info cache, so they
1080 // need to be re-computed after each rename.
1081 std::vector<base::FilePath> profiles_to_rename;
1083 const base::string16 default_profile_name = base::i18n::ToLower(
1084 l10n_util::GetStringUTF16(IDS_DEFAULT_PROFILE_NAME));
1085 const base::string16 default_legacy_profile_name = base::i18n::ToLower(
1086 l10n_util::GetStringUTF16(IDS_LEGACY_DEFAULT_PROFILE_NAME));
1088 for (size_t i = 0; i < GetNumberOfProfiles(); i++) {
1089 // If needed, start downloading the high-res avatar for this profile.
1090 DownloadHighResAvatar(GetAvatarIconIndexOfProfileAtIndex(i),
1091 GetPathOfProfileAtIndex(i));
1093 base::string16 name = base::i18n::ToLower(GetNameOfProfileAtIndex(i));
1094 if (name == default_profile_name || name == default_legacy_profile_name)
1095 profiles_to_rename.push_back(GetPathOfProfileAtIndex(i));
1098 // Rename the necessary profiles.
1099 std::vector<base::FilePath>::const_iterator it;
1100 for (it = profiles_to_rename.begin(); it != profiles_to_rename.end(); ++it) {
1101 size_t profile_index = GetIndexOfProfileWithPath(*it);
1102 SetProfileIsUsingDefaultNameAtIndex(profile_index, true);
1103 // This will assign a new "Person %d" type name and re-sort the cache.
1104 SetNameOfProfileAtIndex(profile_index, ChooseNameForNewProfile(
1105 GetAvatarIconIndexOfProfileAtIndex(profile_index)));