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/format_macros.h"
10 #include "base/i18n/case_conversion.h"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/prefs/pref_registry_simple.h"
14 #include "base/prefs/pref_service.h"
15 #include "base/prefs/scoped_user_pref_update.h"
16 #include "base/rand_util.h"
17 #include "base/stl_util.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_piece.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/values.h"
23 #include "chrome/browser/browser_process.h"
24 #include "chrome/browser/chrome_notification_types.h"
25 #include "chrome/common/pref_names.h"
26 #include "content/public/browser/browser_thread.h"
27 #include "content/public/browser/notification_service.h"
28 #include "grit/generated_resources.h"
29 #include "grit/theme_resources.h"
30 #include "third_party/skia/include/core/SkBitmap.h"
31 #include "ui/base/l10n/l10n_util.h"
32 #include "ui/base/resource/resource_bundle.h"
33 #include "ui/gfx/image/image.h"
34 #include "ui/gfx/image/image_util.h"
36 using content::BrowserThread;
40 const char kNameKey[] = "name";
41 const char kShortcutNameKey[] = "shortcut_name";
42 const char kGAIANameKey[] = "gaia_name";
43 const char kGAIAGivenNameKey[] = "gaia_given_name";
44 const char kUseGAIANameKey[] = "use_gaia_name";
45 const char kUserNameKey[] = "user_name";
46 const char kAvatarIconKey[] = "avatar_icon";
47 const char kAuthCredentialsKey[] = "local_auth_credentials";
48 const char kUseGAIAPictureKey[] = "use_gaia_picture";
49 const char kBackgroundAppsKey[] = "background_apps";
50 const char kHasMigratedToGAIAInfoKey[] = "has_migrated_to_gaia_info";
51 const char kGAIAPictureFileNameKey[] = "gaia_picture_file_name";
52 const char kIsManagedKey[] = "is_managed";
53 const char kIsOmittedFromProfileListKey[] = "is_omitted_from_profile_list";
54 const char kSigninRequiredKey[] = "signin_required";
55 const char kManagedUserId[] = "managed_user_id";
56 const char kProfileIsEphemeral[] = "is_ephemeral";
57 const char kActiveTimeKey[] = "active_time";
59 const char kDefaultUrlPrefix[] = "chrome://theme/IDR_PROFILE_AVATAR_";
60 const char kGAIAPictureFileName[] = "Google Profile Picture.png";
62 const int kDefaultAvatarIconResources[] = {
73 IDR_PROFILE_AVATAR_10,
74 IDR_PROFILE_AVATAR_11,
75 IDR_PROFILE_AVATAR_12,
76 IDR_PROFILE_AVATAR_13,
77 IDR_PROFILE_AVATAR_14,
78 IDR_PROFILE_AVATAR_15,
79 IDR_PROFILE_AVATAR_16,
80 IDR_PROFILE_AVATAR_17,
81 IDR_PROFILE_AVATAR_18,
82 IDR_PROFILE_AVATAR_19,
83 IDR_PROFILE_AVATAR_20,
84 IDR_PROFILE_AVATAR_21,
85 IDR_PROFILE_AVATAR_22,
86 IDR_PROFILE_AVATAR_23,
87 IDR_PROFILE_AVATAR_24,
88 IDR_PROFILE_AVATAR_25,
91 const size_t kDefaultAvatarIconsCount = arraysize(kDefaultAvatarIconResources);
93 // The first 8 icons are generic.
94 const size_t kGenericIconCount = 8;
96 // First eight are generic icons, which use IDS_NUMBERED_PROFILE_NAME.
97 const int kDefaultNames[] = {
98 IDS_DEFAULT_AVATAR_NAME_8,
99 IDS_DEFAULT_AVATAR_NAME_9,
100 IDS_DEFAULT_AVATAR_NAME_10,
101 IDS_DEFAULT_AVATAR_NAME_11,
102 IDS_DEFAULT_AVATAR_NAME_12,
103 IDS_DEFAULT_AVATAR_NAME_13,
104 IDS_DEFAULT_AVATAR_NAME_14,
105 IDS_DEFAULT_AVATAR_NAME_15,
106 IDS_DEFAULT_AVATAR_NAME_16,
107 IDS_DEFAULT_AVATAR_NAME_17,
108 IDS_DEFAULT_AVATAR_NAME_18,
109 IDS_DEFAULT_AVATAR_NAME_19,
110 IDS_DEFAULT_AVATAR_NAME_20,
111 IDS_DEFAULT_AVATAR_NAME_21,
112 IDS_DEFAULT_AVATAR_NAME_22,
113 IDS_DEFAULT_AVATAR_NAME_23,
114 IDS_DEFAULT_AVATAR_NAME_24,
115 IDS_DEFAULT_AVATAR_NAME_25
118 typedef std::vector<unsigned char> ImageData;
120 // Writes |data| to disk and takes ownership of the pointer. On completion
121 // |success| is set to true on success and false on failure.
122 void SaveBitmap(ImageData* data,
123 const base::FilePath& image_path,
125 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
126 scoped_ptr<ImageData> data_owner(data);
129 // Make sure the destination directory exists.
130 base::FilePath dir = image_path.DirName();
131 if (!base::DirectoryExists(dir) && !base::CreateDirectory(dir)) {
132 LOG(ERROR) << "Failed to create parent directory.";
136 if (file_util::WriteFile(image_path,
137 reinterpret_cast<char*>(&(*data)[0]),
138 data->size()) == -1) {
139 LOG(ERROR) << "Failed to save image to file.";
146 // Reads a PNG from disk and decodes it. If the bitmap was successfully read
147 // from disk the then |out_image| will contain the bitmap image, otherwise it
149 void ReadBitmap(const base::FilePath& image_path,
150 gfx::Image** out_image) {
151 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
154 std::string image_data;
155 if (!base::ReadFileToString(image_path, &image_data)) {
156 LOG(ERROR) << "Failed to read PNG file from disk.";
160 gfx::Image image = gfx::Image::CreateFrom1xPNGBytes(
161 base::RefCountedString::TakeString(&image_data));
162 if (image.IsEmpty()) {
163 LOG(ERROR) << "Failed to decode PNG file.";
167 *out_image = new gfx::Image(image);
170 void DeleteBitmap(const base::FilePath& image_path) {
171 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
172 base::DeleteFile(image_path, false);
177 ProfileInfoCache::ProfileInfoCache(PrefService* prefs,
178 const base::FilePath& user_data_dir)
180 user_data_dir_(user_data_dir) {
181 // Populate the cache
182 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
183 base::DictionaryValue* cache = update.Get();
184 for (base::DictionaryValue::Iterator it(*cache);
185 !it.IsAtEnd(); it.Advance()) {
186 base::DictionaryValue* info = NULL;
187 cache->GetDictionaryWithoutPathExpansion(it.key(), &info);
189 info->GetString(kNameKey, &name);
190 sorted_keys_.insert(FindPositionForProfile(it.key(), name), it.key());
191 // TODO(ibraaaa): delete this when 97% of our users are using M31.
192 // http://crbug.com/276163
193 bool is_managed = false;
194 if (info->GetBoolean(kIsManagedKey, &is_managed)) {
195 info->Remove(kIsManagedKey, NULL);
196 info->SetString(kManagedUserId, is_managed ? "DUMMY_ID" : std::string());
201 ProfileInfoCache::~ProfileInfoCache() {
202 STLDeleteContainerPairSecondPointers(
203 gaia_pictures_.begin(), gaia_pictures_.end());
206 void ProfileInfoCache::AddProfileToCache(const base::FilePath& profile_path,
207 const base::string16& name,
208 const base::string16& username,
210 const std::string& managed_user_id) {
211 std::string key = CacheKeyFromProfilePath(profile_path);
212 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
213 base::DictionaryValue* cache = update.Get();
215 scoped_ptr<base::DictionaryValue> info(new base::DictionaryValue);
216 info->SetString(kNameKey, name);
217 info->SetString(kUserNameKey, username);
218 info->SetString(kAvatarIconKey, GetDefaultAvatarIconUrl(icon_index));
219 // Default value for whether background apps are running is false.
220 info->SetBoolean(kBackgroundAppsKey, false);
221 info->SetString(kManagedUserId, managed_user_id);
222 info->SetBoolean(kIsOmittedFromProfileListKey, !managed_user_id.empty());
223 info->SetBoolean(kProfileIsEphemeral, false);
224 cache->SetWithoutPathExpansion(key, info.release());
226 sorted_keys_.insert(FindPositionForProfile(key, name), key);
228 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
230 OnProfileAdded(profile_path));
232 content::NotificationService::current()->Notify(
233 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
234 content::NotificationService::AllSources(),
235 content::NotificationService::NoDetails());
238 void ProfileInfoCache::AddObserver(ProfileInfoCacheObserver* obs) {
239 observer_list_.AddObserver(obs);
242 void ProfileInfoCache::RemoveObserver(ProfileInfoCacheObserver* obs) {
243 observer_list_.RemoveObserver(obs);
246 void ProfileInfoCache::DeleteProfileFromCache(
247 const base::FilePath& profile_path) {
248 size_t profile_index = GetIndexOfProfileWithPath(profile_path);
249 if (profile_index == std::string::npos) {
253 base::string16 name = GetNameOfProfileAtIndex(profile_index);
255 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
257 OnProfileWillBeRemoved(profile_path));
259 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
260 base::DictionaryValue* cache = update.Get();
261 std::string key = CacheKeyFromProfilePath(profile_path);
262 cache->Remove(key, NULL);
263 sorted_keys_.erase(std::find(sorted_keys_.begin(), sorted_keys_.end(), key));
265 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
267 OnProfileWasRemoved(profile_path, name));
269 content::NotificationService::current()->Notify(
270 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
271 content::NotificationService::AllSources(),
272 content::NotificationService::NoDetails());
275 size_t ProfileInfoCache::GetNumberOfProfiles() const {
276 return sorted_keys_.size();
279 size_t ProfileInfoCache::GetIndexOfProfileWithPath(
280 const base::FilePath& profile_path) const {
281 if (profile_path.DirName() != user_data_dir_)
282 return std::string::npos;
283 std::string search_key = CacheKeyFromProfilePath(profile_path);
284 for (size_t i = 0; i < sorted_keys_.size(); ++i) {
285 if (sorted_keys_[i] == search_key)
288 return std::string::npos;
291 base::string16 ProfileInfoCache::GetNameOfProfileAtIndex(size_t index) const {
293 if (IsUsingGAIANameOfProfileAtIndex(index)) {
294 base::string16 given_name = GetGAIAGivenNameOfProfileAtIndex(index);
295 name = given_name.empty() ? GetGAIANameOfProfileAtIndex(index) : given_name;
299 GetInfoForProfileAtIndex(index)->GetString(kNameKey, &name);
303 base::string16 ProfileInfoCache::GetShortcutNameOfProfileAtIndex(size_t index)
305 base::string16 shortcut_name;
306 GetInfoForProfileAtIndex(index)->GetString(
307 kShortcutNameKey, &shortcut_name);
308 return shortcut_name;
311 base::FilePath ProfileInfoCache::GetPathOfProfileAtIndex(size_t index) const {
312 return user_data_dir_.AppendASCII(sorted_keys_[index]);
315 base::Time ProfileInfoCache::GetProfileActiveTimeAtIndex(size_t index) const {
317 if (GetInfoForProfileAtIndex(index)->GetDouble(kActiveTimeKey, &dt)) {
318 return base::Time::FromDoubleT(dt);
324 base::string16 ProfileInfoCache::GetUserNameOfProfileAtIndex(
325 size_t index) const {
326 base::string16 user_name;
327 GetInfoForProfileAtIndex(index)->GetString(kUserNameKey, &user_name);
331 const gfx::Image& ProfileInfoCache::GetAvatarIconOfProfileAtIndex(
332 size_t index) const {
333 if (IsUsingGAIAPictureOfProfileAtIndex(index)) {
334 const gfx::Image* image = GetGAIAPictureOfProfileAtIndex(index);
339 int resource_id = GetDefaultAvatarIconResourceIDAtIndex(
340 GetAvatarIconIndexOfProfileAtIndex(index));
341 return ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
344 std::string ProfileInfoCache::GetLocalAuthCredentialsOfProfileAtIndex(
345 size_t index) const {
346 std::string credentials;
347 GetInfoForProfileAtIndex(index)->GetString(kAuthCredentialsKey, &credentials);
351 bool ProfileInfoCache::GetBackgroundStatusOfProfileAtIndex(
352 size_t index) const {
353 bool background_app_status;
354 if (!GetInfoForProfileAtIndex(index)->GetBoolean(kBackgroundAppsKey,
355 &background_app_status)) {
358 return background_app_status;
361 base::string16 ProfileInfoCache::GetGAIANameOfProfileAtIndex(
362 size_t index) const {
364 GetInfoForProfileAtIndex(index)->GetString(kGAIANameKey, &name);
368 base::string16 ProfileInfoCache::GetGAIAGivenNameOfProfileAtIndex(
369 size_t index) const {
371 GetInfoForProfileAtIndex(index)->GetString(kGAIAGivenNameKey, &name);
375 bool ProfileInfoCache::IsUsingGAIANameOfProfileAtIndex(size_t index) const {
377 GetInfoForProfileAtIndex(index)->GetBoolean(kUseGAIANameKey, &value);
381 const gfx::Image* ProfileInfoCache::GetGAIAPictureOfProfileAtIndex(
382 size_t index) const {
383 base::FilePath path = GetPathOfProfileAtIndex(index);
384 std::string key = CacheKeyFromProfilePath(path);
386 // If the picture is already loaded then use it.
387 if (gaia_pictures_.count(key)) {
388 if (gaia_pictures_[key]->IsEmpty())
390 return gaia_pictures_[key];
393 std::string file_name;
394 GetInfoForProfileAtIndex(index)->GetString(
395 kGAIAPictureFileNameKey, &file_name);
397 // If the picture is not on disk or it is already being loaded then return
399 if (file_name.empty() || gaia_pictures_loading_[key])
402 gaia_pictures_loading_[key] = true;
403 base::FilePath image_path = path.AppendASCII(file_name);
404 gfx::Image** image = new gfx::Image*;
405 BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE,
406 base::Bind(&ReadBitmap, image_path, image),
407 base::Bind(&ProfileInfoCache::OnGAIAPictureLoaded,
408 const_cast<ProfileInfoCache*>(this)->AsWeakPtr(), path, image));
413 bool ProfileInfoCache::ProfileIsManagedAtIndex(size_t index) const {
414 return !GetManagedUserIdOfProfileAtIndex(index).empty();
417 bool ProfileInfoCache::IsOmittedProfileAtIndex(size_t index) const {
419 GetInfoForProfileAtIndex(index)->GetBoolean(kIsOmittedFromProfileListKey,
424 bool ProfileInfoCache::ProfileIsSigninRequiredAtIndex(size_t index) const {
426 GetInfoForProfileAtIndex(index)->GetBoolean(kSigninRequiredKey, &value);
430 std::string ProfileInfoCache::GetManagedUserIdOfProfileAtIndex(
431 size_t index) const {
432 std::string managed_user_id;
433 GetInfoForProfileAtIndex(index)->GetString(kManagedUserId, &managed_user_id);
434 return managed_user_id;
437 bool ProfileInfoCache::ProfileIsEphemeralAtIndex(size_t index) const {
439 GetInfoForProfileAtIndex(index)->GetBoolean(kProfileIsEphemeral, &value);
443 void ProfileInfoCache::OnGAIAPictureLoaded(const base::FilePath& path,
444 gfx::Image** image) const {
445 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
447 std::string key = CacheKeyFromProfilePath(path);
448 gaia_pictures_loading_[key] = false;
451 delete gaia_pictures_[key];
452 gaia_pictures_[key] = *image;
454 // Place an empty image in the cache to avoid reloading it again.
455 gaia_pictures_[key] = new gfx::Image();
459 content::NotificationService::current()->Notify(
460 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
461 content::NotificationService::AllSources(),
462 content::NotificationService::NoDetails());
465 void ProfileInfoCache::OnGAIAPictureSaved(const base::FilePath& path,
466 bool* success) const {
467 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
470 content::NotificationService::current()->Notify(
471 chrome::NOTIFICATION_PROFILE_CACHE_PICTURE_SAVED,
472 content::NotificationService::AllSources(),
473 content::NotificationService::NoDetails());
478 bool ProfileInfoCache::IsUsingGAIAPictureOfProfileAtIndex(
479 size_t index) const {
481 GetInfoForProfileAtIndex(index)->GetBoolean(kUseGAIAPictureKey, &value);
485 size_t ProfileInfoCache::GetAvatarIconIndexOfProfileAtIndex(size_t index)
487 std::string icon_url;
488 GetInfoForProfileAtIndex(index)->GetString(kAvatarIconKey, &icon_url);
489 size_t icon_index = 0;
490 if (!IsDefaultAvatarIconUrl(icon_url, &icon_index))
491 DLOG(WARNING) << "Unknown avatar icon: " << icon_url;
496 void ProfileInfoCache::SetProfileActiveTimeAtIndex(size_t index) {
497 scoped_ptr<base::DictionaryValue> info(
498 GetInfoForProfileAtIndex(index)->DeepCopy());
499 info->SetDouble(kActiveTimeKey, base::Time::Now().ToDoubleT());
500 // This takes ownership of |info|.
501 SetInfoQuietlyForProfileAtIndex(index, info.release());
504 void ProfileInfoCache::SetNameOfProfileAtIndex(size_t index,
505 const base::string16& name) {
506 scoped_ptr<base::DictionaryValue> info(
507 GetInfoForProfileAtIndex(index)->DeepCopy());
508 base::string16 current_name;
509 info->GetString(kNameKey, ¤t_name);
510 if (name == current_name)
513 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
514 info->SetString(kNameKey, name);
515 // This takes ownership of |info|.
516 SetInfoForProfileAtIndex(index, info.release());
517 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
518 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
519 UpdateSortForProfileIndex(index);
521 if (old_display_name != new_display_name) {
522 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
524 OnProfileNameChanged(profile_path, old_display_name));
528 void ProfileInfoCache::SetShortcutNameOfProfileAtIndex(
530 const base::string16& shortcut_name) {
531 if (shortcut_name == GetShortcutNameOfProfileAtIndex(index))
533 scoped_ptr<base::DictionaryValue> info(
534 GetInfoForProfileAtIndex(index)->DeepCopy());
535 info->SetString(kShortcutNameKey, shortcut_name);
536 // This takes ownership of |info|.
537 SetInfoForProfileAtIndex(index, info.release());
540 void ProfileInfoCache::SetUserNameOfProfileAtIndex(
542 const base::string16& user_name) {
543 if (user_name == GetUserNameOfProfileAtIndex(index))
546 scoped_ptr<base::DictionaryValue> info(
547 GetInfoForProfileAtIndex(index)->DeepCopy());
548 info->SetString(kUserNameKey, user_name);
549 // This takes ownership of |info|.
550 SetInfoForProfileAtIndex(index, info.release());
553 void ProfileInfoCache::SetAvatarIconOfProfileAtIndex(size_t index,
555 scoped_ptr<base::DictionaryValue> info(
556 GetInfoForProfileAtIndex(index)->DeepCopy());
557 info->SetString(kAvatarIconKey, GetDefaultAvatarIconUrl(icon_index));
558 // This takes ownership of |info|.
559 SetInfoForProfileAtIndex(index, info.release());
561 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
562 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
564 OnProfileAvatarChanged(profile_path));
567 void ProfileInfoCache::SetIsOmittedProfileAtIndex(size_t index,
569 if (IsOmittedProfileAtIndex(index) == is_omitted)
571 scoped_ptr<base::DictionaryValue> info(
572 GetInfoForProfileAtIndex(index)->DeepCopy());
573 info->SetBoolean(kIsOmittedFromProfileListKey, is_omitted);
574 // This takes ownership of |info|.
575 SetInfoForProfileAtIndex(index, info.release());
578 void ProfileInfoCache::SetManagedUserIdOfProfileAtIndex(size_t index,
579 const std::string& id) {
580 scoped_ptr<base::DictionaryValue> info(
581 GetInfoForProfileAtIndex(index)->DeepCopy());
582 info->SetString(kManagedUserId, id);
583 // This takes ownership of |info|.
584 SetInfoForProfileAtIndex(index, info.release());
587 void ProfileInfoCache::SetLocalAuthCredentialsOfProfileAtIndex(
589 const std::string& credentials) {
590 scoped_ptr<base::DictionaryValue> info(
591 GetInfoForProfileAtIndex(index)->DeepCopy());
592 info->SetString(kAuthCredentialsKey, credentials);
593 // This takes ownership of |info|.
594 SetInfoForProfileAtIndex(index, info.release());
597 void ProfileInfoCache::SetBackgroundStatusOfProfileAtIndex(
599 bool running_background_apps) {
600 if (GetBackgroundStatusOfProfileAtIndex(index) == running_background_apps)
602 scoped_ptr<base::DictionaryValue> info(
603 GetInfoForProfileAtIndex(index)->DeepCopy());
604 info->SetBoolean(kBackgroundAppsKey, running_background_apps);
605 // This takes ownership of |info|.
606 SetInfoForProfileAtIndex(index, info.release());
609 void ProfileInfoCache::SetGAIANameOfProfileAtIndex(size_t index,
610 const base::string16& name) {
611 if (name == GetGAIANameOfProfileAtIndex(index))
614 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
615 scoped_ptr<base::DictionaryValue> info(
616 GetInfoForProfileAtIndex(index)->DeepCopy());
617 info->SetString(kGAIANameKey, name);
618 // This takes ownership of |info|.
619 SetInfoForProfileAtIndex(index, info.release());
620 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
621 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
622 UpdateSortForProfileIndex(index);
624 if (old_display_name != new_display_name) {
625 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
627 OnProfileNameChanged(profile_path, old_display_name));
631 void ProfileInfoCache::SetGAIAGivenNameOfProfileAtIndex(
633 const base::string16& name) {
634 if (name == GetGAIAGivenNameOfProfileAtIndex(index))
637 scoped_ptr<base::DictionaryValue> info(
638 GetInfoForProfileAtIndex(index)->DeepCopy());
639 info->SetString(kGAIAGivenNameKey, name);
640 // This takes ownership of |info|.
641 SetInfoForProfileAtIndex(index, info.release());
644 void ProfileInfoCache::SetIsUsingGAIANameOfProfileAtIndex(size_t index,
646 if (value == IsUsingGAIANameOfProfileAtIndex(index))
649 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
650 scoped_ptr<base::DictionaryValue> info(
651 GetInfoForProfileAtIndex(index)->DeepCopy());
652 info->SetBoolean(kUseGAIANameKey, value);
653 // This takes ownership of |info|.
654 SetInfoForProfileAtIndex(index, info.release());
655 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
656 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
657 UpdateSortForProfileIndex(index);
659 if (old_display_name != new_display_name) {
660 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
662 OnProfileNameChanged(profile_path, old_display_name));
666 void ProfileInfoCache::SetGAIAPictureOfProfileAtIndex(size_t index,
667 const gfx::Image* image) {
668 base::FilePath path = GetPathOfProfileAtIndex(index);
669 std::string key = CacheKeyFromProfilePath(path);
671 // Delete the old bitmap from cache.
672 std::map<std::string, gfx::Image*>::iterator it = gaia_pictures_.find(key);
673 if (it != gaia_pictures_.end()) {
675 gaia_pictures_.erase(it);
678 std::string old_file_name;
679 GetInfoForProfileAtIndex(index)->GetString(
680 kGAIAPictureFileNameKey, &old_file_name);
681 std::string new_file_name;
684 // Delete the old bitmap from disk.
685 if (!old_file_name.empty()) {
686 base::FilePath image_path = path.AppendASCII(old_file_name);
687 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
688 base::Bind(&DeleteBitmap, image_path));
691 // Save the new bitmap to disk.
692 gaia_pictures_[key] = new gfx::Image(*image);
693 scoped_ptr<ImageData> data(new ImageData);
694 scoped_refptr<base::RefCountedMemory> png_data = image->As1xPNGBytes();
695 data->assign(png_data->front(), png_data->front() + png_data->size());
697 LOG(ERROR) << "Failed to PNG encode the image.";
700 old_file_name.empty() ? kGAIAPictureFileName : old_file_name;
701 base::FilePath image_path = path.AppendASCII(new_file_name);
702 bool* success = new bool;
703 BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE,
704 base::Bind(&SaveBitmap, data.release(), image_path, success),
705 base::Bind(&ProfileInfoCache::OnGAIAPictureSaved, AsWeakPtr(),
710 scoped_ptr<base::DictionaryValue> info(
711 GetInfoForProfileAtIndex(index)->DeepCopy());
712 info->SetString(kGAIAPictureFileNameKey, new_file_name);
713 // This takes ownership of |info|.
714 SetInfoForProfileAtIndex(index, info.release());
716 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
718 OnProfileAvatarChanged(path));
721 void ProfileInfoCache::SetIsUsingGAIAPictureOfProfileAtIndex(size_t index,
723 scoped_ptr<base::DictionaryValue> info(
724 GetInfoForProfileAtIndex(index)->DeepCopy());
725 info->SetBoolean(kUseGAIAPictureKey, value);
726 // This takes ownership of |info|.
727 SetInfoForProfileAtIndex(index, info.release());
729 // Retrieve some info to update observers who care about avatar changes.
730 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
731 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
733 OnProfileAvatarChanged(profile_path));
736 void ProfileInfoCache::SetProfileSigninRequiredAtIndex(size_t index,
738 if (value == ProfileIsSigninRequiredAtIndex(index))
741 scoped_ptr<base::DictionaryValue> info(
742 GetInfoForProfileAtIndex(index)->DeepCopy());
743 info->SetBoolean(kSigninRequiredKey, value);
744 // This takes ownership of |info|.
745 SetInfoForProfileAtIndex(index, info.release());
747 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
748 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
750 OnProfileSigninRequiredChanged(profile_path));
753 void ProfileInfoCache::SetProfileIsEphemeralAtIndex(size_t index, bool value) {
754 if (value == ProfileIsEphemeralAtIndex(index))
757 scoped_ptr<base::DictionaryValue> info(
758 GetInfoForProfileAtIndex(index)->DeepCopy());
759 info->SetBoolean(kProfileIsEphemeral, value);
760 // This takes ownership of |info|.
761 SetInfoForProfileAtIndex(index, info.release());
764 base::string16 ProfileInfoCache::ChooseNameForNewProfile(
765 size_t icon_index) const {
767 for (int name_index = 1; ; ++name_index) {
768 if (icon_index < kGenericIconCount) {
769 name = l10n_util::GetStringFUTF16Int(IDS_NUMBERED_PROFILE_NAME,
772 name = l10n_util::GetStringUTF16(
773 kDefaultNames[icon_index - kGenericIconCount]);
775 name.append(base::UTF8ToUTF16(base::IntToString(name_index)));
778 // Loop through previously named profiles to ensure we're not duplicating.
779 bool name_found = false;
780 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
781 if (GetNameOfProfileAtIndex(i) == name) {
791 bool ProfileInfoCache::GetHasMigratedToGAIAInfoOfProfileAtIndex(
792 size_t index) const {
794 GetInfoForProfileAtIndex(index)->GetBoolean(
795 kHasMigratedToGAIAInfoKey, &value);
799 void ProfileInfoCache::SetHasMigratedToGAIAInfoOfProfileAtIndex(
800 size_t index, bool value) {
801 scoped_ptr<base::DictionaryValue> info(
802 GetInfoForProfileAtIndex(index)->DeepCopy());
803 info->SetBoolean(kHasMigratedToGAIAInfoKey, value);
804 // This takes ownership of |info|.
805 SetInfoForProfileAtIndex(index, info.release());
808 bool ProfileInfoCache::IconIndexIsUnique(size_t icon_index) const {
809 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
810 if (GetAvatarIconIndexOfProfileAtIndex(i) == icon_index)
816 bool ProfileInfoCache::ChooseAvatarIconIndexForNewProfile(
817 bool allow_generic_icon,
819 size_t* out_icon_index) const {
820 size_t start = allow_generic_icon ? 0 : kGenericIconCount;
821 size_t end = GetDefaultAvatarIconCount();
822 size_t count = end - start;
824 int rand = base::RandInt(0, count);
825 for (size_t i = 0; i < count; ++i) {
826 size_t icon_index = start + (rand + i) % count;
827 if (!must_be_unique || IconIndexIsUnique(icon_index)) {
828 *out_icon_index = icon_index;
836 size_t ProfileInfoCache::ChooseAvatarIconIndexForNewProfile() const {
837 size_t icon_index = 0;
838 // Try to find a unique, non-generic icon.
839 if (ChooseAvatarIconIndexForNewProfile(false, true, &icon_index))
841 // Try to find any unique icon.
842 if (ChooseAvatarIconIndexForNewProfile(true, true, &icon_index))
844 // Settle for any random icon, even if it's not unique.
845 if (ChooseAvatarIconIndexForNewProfile(true, false, &icon_index))
852 const base::FilePath& ProfileInfoCache::GetUserDataDir() const {
853 return user_data_dir_;
857 size_t ProfileInfoCache::GetDefaultAvatarIconCount() {
858 return kDefaultAvatarIconsCount;
862 int ProfileInfoCache::GetDefaultAvatarIconResourceIDAtIndex(size_t index) {
863 DCHECK(IsDefaultAvatarIconIndex(index));
864 return kDefaultAvatarIconResources[index];
868 std::string ProfileInfoCache::GetDefaultAvatarIconUrl(size_t index) {
869 DCHECK(IsDefaultAvatarIconIndex(index));
870 return base::StringPrintf("%s%" PRIuS, kDefaultUrlPrefix, index);
874 bool ProfileInfoCache::IsDefaultAvatarIconIndex(size_t index) {
875 return index < kDefaultAvatarIconsCount;
879 bool ProfileInfoCache::IsDefaultAvatarIconUrl(const std::string& url,
880 size_t* icon_index) {
882 if (url.find(kDefaultUrlPrefix) != 0)
886 if (base::StringToInt(base::StringPiece(url.begin() +
887 strlen(kDefaultUrlPrefix),
891 int_value >= static_cast<int>(kDefaultAvatarIconsCount))
893 *icon_index = int_value;
900 const base::DictionaryValue* ProfileInfoCache::GetInfoForProfileAtIndex(
901 size_t index) const {
902 DCHECK_LT(index, GetNumberOfProfiles());
903 const base::DictionaryValue* cache =
904 prefs_->GetDictionary(prefs::kProfileInfoCache);
905 const base::DictionaryValue* info = NULL;
906 cache->GetDictionaryWithoutPathExpansion(sorted_keys_[index], &info);
910 void ProfileInfoCache::SetInfoQuietlyForProfileAtIndex(
911 size_t index, base::DictionaryValue* info) {
912 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
913 base::DictionaryValue* cache = update.Get();
914 cache->SetWithoutPathExpansion(sorted_keys_[index], info);
917 // TODO(noms): Switch to newer notification system.
918 void ProfileInfoCache::SetInfoForProfileAtIndex(size_t index,
919 base::DictionaryValue* info) {
920 SetInfoQuietlyForProfileAtIndex(index, info);
922 content::NotificationService::current()->Notify(
923 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
924 content::NotificationService::AllSources(),
925 content::NotificationService::NoDetails());
928 std::string ProfileInfoCache::CacheKeyFromProfilePath(
929 const base::FilePath& profile_path) const {
930 DCHECK(user_data_dir_ == profile_path.DirName());
931 base::FilePath base_name = profile_path.BaseName();
932 return base_name.MaybeAsASCII();
935 std::vector<std::string>::iterator ProfileInfoCache::FindPositionForProfile(
936 const std::string& search_key,
937 const base::string16& search_name) {
938 base::string16 search_name_l = base::i18n::ToLower(search_name);
939 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
940 base::string16 name_l = base::i18n::ToLower(GetNameOfProfileAtIndex(i));
941 int name_compare = search_name_l.compare(name_l);
942 if (name_compare < 0)
943 return sorted_keys_.begin() + i;
944 if (name_compare == 0) {
945 int key_compare = search_key.compare(sorted_keys_[i]);
947 return sorted_keys_.begin() + i;
950 return sorted_keys_.end();
953 void ProfileInfoCache::UpdateSortForProfileIndex(size_t index) {
954 base::string16 name = GetNameOfProfileAtIndex(index);
956 // Remove and reinsert key in |sorted_keys_| to alphasort.
957 std::string key = CacheKeyFromProfilePath(GetPathOfProfileAtIndex(index));
958 std::vector<std::string>::iterator key_it =
959 std::find(sorted_keys_.begin(), sorted_keys_.end(), key);
960 DCHECK(key_it != sorted_keys_.end());
961 sorted_keys_.erase(key_it);
962 sorted_keys_.insert(FindPositionForProfile(key, name), key);
964 content::NotificationService::current()->Notify(
965 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
966 content::NotificationService::AllSources(),
967 content::NotificationService::NoDetails());
971 std::vector<base::string16> ProfileInfoCache::GetProfileNames() {
972 std::vector<base::string16> names;
973 PrefService* local_state = g_browser_process->local_state();
974 const base::DictionaryValue* cache = local_state->GetDictionary(
975 prefs::kProfileInfoCache);
977 for (base::DictionaryValue::Iterator it(*cache); !it.IsAtEnd();
979 const base::DictionaryValue* info = NULL;
980 it.value().GetAsDictionary(&info);
981 info->GetString(kNameKey, &name);
982 names.push_back(name);
988 void ProfileInfoCache::RegisterPrefs(PrefRegistrySimple* registry) {
989 registry->RegisterDictionaryPref(prefs::kProfileInfoCache);