Fix build break
[chromium-blink-merge.git] / chrome / browser / profiles / profile_info_cache.cc
blob8b62ecd051847f0ae4626379cd5cc75a72f595d7
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"
7 #include "base/bind.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/rand_util.h"
16 #include "base/stl_util.h"
17 #include "base/stringprintf.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_piece.h"
20 #include "base/utf_string_conversions.h"
21 #include "base/values.h"
22 #include "chrome/browser/browser_process.h"
23 #include "chrome/browser/prefs/scoped_user_pref_update.h"
24 #include "chrome/common/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;
38 namespace {
40 const char kNameKey[] = "name";
41 const char kShortcutNameKey[] = "shortcut_name";
42 const char kGAIANameKey[] = "gaia_name";
43 const char kUseGAIANameKey[] = "use_gaia_name";
44 const char kUserNameKey[] = "user_name";
45 const char kAvatarIconKey[] = "avatar_icon";
46 const char kUseGAIAPictureKey[] = "use_gaia_picture";
47 const char kBackgroundAppsKey[] = "background_apps";
48 const char kHasMigratedToGAIAInfoKey[] = "has_migrated_to_gaia_info";
49 const char kGAIAPictureFileNameKey[] = "gaia_picture_file_name";
50 const char kIsManagedKey[] = "is_managed";
52 const char kDefaultUrlPrefix[] = "chrome://theme/IDR_PROFILE_AVATAR_";
53 const char kGAIAPictureFileName[] = "Google Profile Picture.png";
55 const int kDefaultAvatarIconResources[] = {
56 IDR_PROFILE_AVATAR_0,
57 IDR_PROFILE_AVATAR_1,
58 IDR_PROFILE_AVATAR_2,
59 IDR_PROFILE_AVATAR_3,
60 IDR_PROFILE_AVATAR_4,
61 IDR_PROFILE_AVATAR_5,
62 IDR_PROFILE_AVATAR_6,
63 IDR_PROFILE_AVATAR_7,
64 IDR_PROFILE_AVATAR_8,
65 IDR_PROFILE_AVATAR_9,
66 IDR_PROFILE_AVATAR_10,
67 IDR_PROFILE_AVATAR_11,
68 IDR_PROFILE_AVATAR_12,
69 IDR_PROFILE_AVATAR_13,
70 IDR_PROFILE_AVATAR_14,
71 IDR_PROFILE_AVATAR_15,
72 IDR_PROFILE_AVATAR_16,
73 IDR_PROFILE_AVATAR_17,
74 IDR_PROFILE_AVATAR_18,
75 IDR_PROFILE_AVATAR_19,
76 IDR_PROFILE_AVATAR_20,
77 IDR_PROFILE_AVATAR_21,
78 IDR_PROFILE_AVATAR_22,
79 IDR_PROFILE_AVATAR_23,
80 IDR_PROFILE_AVATAR_24,
81 IDR_PROFILE_AVATAR_25,
84 const size_t kDefaultAvatarIconsCount = arraysize(kDefaultAvatarIconResources);
86 // The first 8 icons are generic.
87 const size_t kGenericIconCount = 8;
89 // First eight are generic icons, which use IDS_NUMBERED_PROFILE_NAME.
90 const int kDefaultNames[] = {
91 IDS_DEFAULT_AVATAR_NAME_8,
92 IDS_DEFAULT_AVATAR_NAME_9,
93 IDS_DEFAULT_AVATAR_NAME_10,
94 IDS_DEFAULT_AVATAR_NAME_11,
95 IDS_DEFAULT_AVATAR_NAME_12,
96 IDS_DEFAULT_AVATAR_NAME_13,
97 IDS_DEFAULT_AVATAR_NAME_14,
98 IDS_DEFAULT_AVATAR_NAME_15,
99 IDS_DEFAULT_AVATAR_NAME_16,
100 IDS_DEFAULT_AVATAR_NAME_17,
101 IDS_DEFAULT_AVATAR_NAME_18,
102 IDS_DEFAULT_AVATAR_NAME_19,
103 IDS_DEFAULT_AVATAR_NAME_20,
104 IDS_DEFAULT_AVATAR_NAME_21,
105 IDS_DEFAULT_AVATAR_NAME_22,
106 IDS_DEFAULT_AVATAR_NAME_23,
107 IDS_DEFAULT_AVATAR_NAME_24,
108 IDS_DEFAULT_AVATAR_NAME_25
111 typedef std::vector<unsigned char> ImageData;
113 // Writes |data| to disk and takes ownership of the pointer. On completion
114 // |success| is set to true on success and false on failure.
115 void SaveBitmap(ImageData* data,
116 const base::FilePath& image_path,
117 bool* success) {
118 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
119 scoped_ptr<ImageData> data_owner(data);
120 *success = false;
122 // Make sure the destination directory exists.
123 base::FilePath dir = image_path.DirName();
124 if (!file_util::DirectoryExists(dir) && !file_util::CreateDirectory(dir)) {
125 LOG(ERROR) << "Failed to create parent directory.";
126 return;
129 if (file_util::WriteFile(image_path,
130 reinterpret_cast<char*>(&(*data)[0]),
131 data->size()) == -1) {
132 LOG(ERROR) << "Failed to save image to file.";
133 return;
136 *success = true;
139 // Reads a PNG from disk and decodes it. If the bitmap was successfully read
140 // from disk the then |out_image| will contain the bitmap image, otherwise it
141 // will be NULL.
142 void ReadBitmap(const base::FilePath& image_path,
143 gfx::Image** out_image) {
144 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
145 *out_image = NULL;
147 std::string image_data;
148 if (!file_util::ReadFileToString(image_path, &image_data)) {
149 LOG(ERROR) << "Failed to read PNG file from disk.";
150 return;
153 const unsigned char* data =
154 reinterpret_cast<const unsigned char*>(image_data.data());
155 gfx::Image image =
156 gfx::Image::CreateFrom1xPNGBytes(data, image_data.length());
157 if (image.IsEmpty()) {
158 LOG(ERROR) << "Failed to decode PNG file.";
159 return;
162 *out_image = new gfx::Image(image);
165 void DeleteBitmap(const base::FilePath& image_path) {
166 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
167 file_util::Delete(image_path, false);
170 } // namespace
172 ProfileInfoCache::ProfileInfoCache(PrefService* prefs,
173 const base::FilePath& user_data_dir)
174 : prefs_(prefs),
175 user_data_dir_(user_data_dir) {
176 // Populate the cache
177 const DictionaryValue* cache =
178 prefs_->GetDictionary(prefs::kProfileInfoCache);
179 for (DictionaryValue::Iterator it(*cache); !it.IsAtEnd(); it.Advance()) {
180 const DictionaryValue* info = NULL;
181 it.value().GetAsDictionary(&info);
182 string16 name;
183 info->GetString(kNameKey, &name);
184 sorted_keys_.insert(FindPositionForProfile(it.key(), name), it.key());
188 ProfileInfoCache::~ProfileInfoCache() {
189 STLDeleteContainerPairSecondPointers(
190 gaia_pictures_.begin(), gaia_pictures_.end());
193 void ProfileInfoCache::AddProfileToCache(const base::FilePath& profile_path,
194 const string16& name,
195 const string16& username,
196 size_t icon_index,
197 bool is_managed) {
198 std::string key = CacheKeyFromProfilePath(profile_path);
199 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
200 DictionaryValue* cache = update.Get();
202 scoped_ptr<DictionaryValue> info(new DictionaryValue);
203 info->SetString(kNameKey, name);
204 info->SetString(kUserNameKey, username);
205 info->SetString(kAvatarIconKey, GetDefaultAvatarIconUrl(icon_index));
206 // Default value for whether background apps are running is false.
207 info->SetBoolean(kBackgroundAppsKey, false);
208 info->SetBoolean(kIsManagedKey, is_managed);
209 cache->Set(key, info.release());
211 sorted_keys_.insert(FindPositionForProfile(key, name), key);
213 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
214 observer_list_,
215 OnProfileAdded(profile_path));
217 content::NotificationService::current()->Notify(
218 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
219 content::NotificationService::AllSources(),
220 content::NotificationService::NoDetails());
223 void ProfileInfoCache::AddObserver(ProfileInfoCacheObserver* obs) {
224 observer_list_.AddObserver(obs);
227 void ProfileInfoCache::RemoveObserver(ProfileInfoCacheObserver* obs) {
228 observer_list_.RemoveObserver(obs);
231 void ProfileInfoCache::DeleteProfileFromCache(
232 const base::FilePath& profile_path) {
233 size_t profile_index = GetIndexOfProfileWithPath(profile_path);
234 if (profile_index == std::string::npos) {
235 NOTREACHED();
236 return;
238 string16 name = GetNameOfProfileAtIndex(profile_index);
240 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
241 observer_list_,
242 OnProfileWillBeRemoved(profile_path));
244 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
245 DictionaryValue* cache = update.Get();
246 std::string key = CacheKeyFromProfilePath(profile_path);
247 cache->Remove(key, NULL);
248 sorted_keys_.erase(std::find(sorted_keys_.begin(), sorted_keys_.end(), key));
250 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
251 observer_list_,
252 OnProfileWasRemoved(profile_path, name));
254 content::NotificationService::current()->Notify(
255 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
256 content::NotificationService::AllSources(),
257 content::NotificationService::NoDetails());
260 size_t ProfileInfoCache::GetNumberOfProfiles() const {
261 return sorted_keys_.size();
264 size_t ProfileInfoCache::GetIndexOfProfileWithPath(
265 const base::FilePath& profile_path) const {
266 if (profile_path.DirName() != user_data_dir_)
267 return std::string::npos;
268 std::string search_key = CacheKeyFromProfilePath(profile_path);
269 for (size_t i = 0; i < sorted_keys_.size(); ++i) {
270 if (sorted_keys_[i] == search_key)
271 return i;
273 return std::string::npos;
276 string16 ProfileInfoCache::GetNameOfProfileAtIndex(size_t index) const {
277 string16 name;
278 if (IsUsingGAIANameOfProfileAtIndex(index))
279 name = GetGAIANameOfProfileAtIndex(index);
280 if (name.empty())
281 GetInfoForProfileAtIndex(index)->GetString(kNameKey, &name);
282 return name;
285 string16 ProfileInfoCache::GetShortcutNameOfProfileAtIndex(size_t index)
286 const {
287 string16 shortcut_name;
288 GetInfoForProfileAtIndex(index)->GetString(
289 kShortcutNameKey, &shortcut_name);
290 return shortcut_name;
293 base::FilePath ProfileInfoCache::GetPathOfProfileAtIndex(size_t index) const {
294 return user_data_dir_.AppendASCII(sorted_keys_[index]);
297 string16 ProfileInfoCache::GetUserNameOfProfileAtIndex(size_t index) const {
298 string16 user_name;
299 GetInfoForProfileAtIndex(index)->GetString(kUserNameKey, &user_name);
300 return user_name;
303 const gfx::Image& ProfileInfoCache::GetAvatarIconOfProfileAtIndex(
304 size_t index) const {
305 if (IsUsingGAIAPictureOfProfileAtIndex(index)) {
306 const gfx::Image* image = GetGAIAPictureOfProfileAtIndex(index);
307 if (image)
308 return *image;
311 int resource_id = GetDefaultAvatarIconResourceIDAtIndex(
312 GetAvatarIconIndexOfProfileAtIndex(index));
313 return ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
316 bool ProfileInfoCache::GetBackgroundStatusOfProfileAtIndex(
317 size_t index) const {
318 bool background_app_status;
319 if (!GetInfoForProfileAtIndex(index)->GetBoolean(kBackgroundAppsKey,
320 &background_app_status)) {
321 return false;
323 return background_app_status;
326 string16 ProfileInfoCache::GetGAIANameOfProfileAtIndex(size_t index) const {
327 string16 name;
328 GetInfoForProfileAtIndex(index)->GetString(kGAIANameKey, &name);
329 return name;
332 bool ProfileInfoCache::IsUsingGAIANameOfProfileAtIndex(size_t index) const {
333 bool value = false;
334 GetInfoForProfileAtIndex(index)->GetBoolean(kUseGAIANameKey, &value);
335 return value;
338 const gfx::Image* ProfileInfoCache::GetGAIAPictureOfProfileAtIndex(
339 size_t index) const {
340 base::FilePath path = GetPathOfProfileAtIndex(index);
341 std::string key = CacheKeyFromProfilePath(path);
343 // If the picture is already loaded then use it.
344 if (gaia_pictures_.count(key)) {
345 if (gaia_pictures_[key]->IsEmpty())
346 return NULL;
347 return gaia_pictures_[key];
350 std::string file_name;
351 GetInfoForProfileAtIndex(index)->GetString(
352 kGAIAPictureFileNameKey, &file_name);
354 // If the picture is not on disk or it is already being loaded then return
355 // NULL.
356 if (file_name.empty() || gaia_pictures_loading_[key])
357 return NULL;
359 gaia_pictures_loading_[key] = true;
360 base::FilePath image_path = path.AppendASCII(file_name);
361 gfx::Image** image = new gfx::Image*;
362 BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE,
363 base::Bind(&ReadBitmap, image_path, image),
364 base::Bind(&ProfileInfoCache::OnGAIAPictureLoaded,
365 const_cast<ProfileInfoCache*>(this)->AsWeakPtr(), path, image));
367 return NULL;
370 bool ProfileInfoCache::ProfileIsManagedAtIndex(size_t index) const {
371 bool value = false;
372 GetInfoForProfileAtIndex(index)->GetBoolean(kIsManagedKey, &value);
373 return value;
376 void ProfileInfoCache::OnGAIAPictureLoaded(const base::FilePath& path,
377 gfx::Image** image) const {
378 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
380 std::string key = CacheKeyFromProfilePath(path);
381 gaia_pictures_loading_[key] = false;
383 if (*image) {
384 delete gaia_pictures_[key];
385 gaia_pictures_[key] = *image;
386 } else {
387 // Place an empty image in the cache to avoid reloading it again.
388 gaia_pictures_[key] = new gfx::Image();
390 delete image;
392 content::NotificationService::current()->Notify(
393 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
394 content::NotificationService::AllSources(),
395 content::NotificationService::NoDetails());
398 void ProfileInfoCache::OnGAIAPictureSaved(const base::FilePath& path,
399 bool* success) const {
400 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
402 if (*success) {
403 content::NotificationService::current()->Notify(
404 chrome::NOTIFICATION_PROFILE_CACHE_PICTURE_SAVED,
405 content::NotificationService::AllSources(),
406 content::NotificationService::NoDetails());
408 delete success;
411 bool ProfileInfoCache::IsUsingGAIAPictureOfProfileAtIndex(
412 size_t index) const {
413 bool value = false;
414 GetInfoForProfileAtIndex(index)->GetBoolean(kUseGAIAPictureKey, &value);
415 return value;
418 size_t ProfileInfoCache::GetAvatarIconIndexOfProfileAtIndex(size_t index)
419 const {
420 std::string icon_url;
421 GetInfoForProfileAtIndex(index)->GetString(kAvatarIconKey, &icon_url);
422 size_t icon_index = 0;
423 if (IsDefaultAvatarIconUrl(icon_url, &icon_index))
424 return icon_index;
426 DLOG(WARNING) << "Unknown avatar icon: " << icon_url;
427 return GetDefaultAvatarIconResourceIDAtIndex(0);
430 void ProfileInfoCache::SetNameOfProfileAtIndex(size_t index,
431 const string16& name) {
432 scoped_ptr<DictionaryValue> info(GetInfoForProfileAtIndex(index)->DeepCopy());
433 string16 current_name;
434 info->GetString(kNameKey, &current_name);
435 if (name == current_name)
436 return;
438 string16 old_display_name = GetNameOfProfileAtIndex(index);
439 info->SetString(kNameKey, name);
440 // This takes ownership of |info|.
441 SetInfoForProfileAtIndex(index, info.release());
442 string16 new_display_name = GetNameOfProfileAtIndex(index);
443 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
444 UpdateSortForProfileIndex(index);
446 if (old_display_name != new_display_name) {
447 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
448 observer_list_,
449 OnProfileNameChanged(profile_path, old_display_name));
453 void ProfileInfoCache::SetShortcutNameOfProfileAtIndex(
454 size_t index,
455 const string16& shortcut_name) {
456 if (shortcut_name == GetShortcutNameOfProfileAtIndex(index))
457 return;
458 scoped_ptr<DictionaryValue> info(GetInfoForProfileAtIndex(index)->DeepCopy());
459 info->SetString(kShortcutNameKey, shortcut_name);
460 // This takes ownership of |info|.
461 SetInfoForProfileAtIndex(index, info.release());
464 void ProfileInfoCache::SetUserNameOfProfileAtIndex(size_t index,
465 const string16& user_name) {
466 if (user_name == GetUserNameOfProfileAtIndex(index))
467 return;
469 scoped_ptr<DictionaryValue> info(GetInfoForProfileAtIndex(index)->DeepCopy());
470 info->SetString(kUserNameKey, user_name);
471 // This takes ownership of |info|.
472 SetInfoForProfileAtIndex(index, info.release());
475 void ProfileInfoCache::SetAvatarIconOfProfileAtIndex(size_t index,
476 size_t icon_index) {
477 scoped_ptr<DictionaryValue> info(GetInfoForProfileAtIndex(index)->DeepCopy());
478 info->SetString(kAvatarIconKey, GetDefaultAvatarIconUrl(icon_index));
479 // This takes ownership of |info|.
480 SetInfoForProfileAtIndex(index, info.release());
482 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
483 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
484 observer_list_,
485 OnProfileAvatarChanged(profile_path));
488 void ProfileInfoCache::SetBackgroundStatusOfProfileAtIndex(
489 size_t index,
490 bool running_background_apps) {
491 if (GetBackgroundStatusOfProfileAtIndex(index) == running_background_apps)
492 return;
493 scoped_ptr<DictionaryValue> info(GetInfoForProfileAtIndex(index)->DeepCopy());
494 info->SetBoolean(kBackgroundAppsKey, running_background_apps);
495 // This takes ownership of |info|.
496 SetInfoForProfileAtIndex(index, info.release());
499 void ProfileInfoCache::SetGAIANameOfProfileAtIndex(size_t index,
500 const string16& name) {
501 if (name == GetGAIANameOfProfileAtIndex(index))
502 return;
504 string16 old_display_name = GetNameOfProfileAtIndex(index);
505 scoped_ptr<DictionaryValue> info(GetInfoForProfileAtIndex(index)->DeepCopy());
506 info->SetString(kGAIANameKey, name);
507 // This takes ownership of |info|.
508 SetInfoForProfileAtIndex(index, info.release());
509 string16 new_display_name = GetNameOfProfileAtIndex(index);
510 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
511 UpdateSortForProfileIndex(index);
513 if (old_display_name != new_display_name) {
514 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
515 observer_list_,
516 OnProfileNameChanged(profile_path, old_display_name));
520 void ProfileInfoCache::SetIsUsingGAIANameOfProfileAtIndex(size_t index,
521 bool value) {
522 if (value == IsUsingGAIANameOfProfileAtIndex(index))
523 return;
525 string16 old_display_name = GetNameOfProfileAtIndex(index);
526 scoped_ptr<DictionaryValue> info(GetInfoForProfileAtIndex(index)->DeepCopy());
527 info->SetBoolean(kUseGAIANameKey, value);
528 // This takes ownership of |info|.
529 SetInfoForProfileAtIndex(index, info.release());
530 string16 new_display_name = GetNameOfProfileAtIndex(index);
531 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
532 UpdateSortForProfileIndex(index);
534 if (old_display_name != new_display_name) {
535 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
536 observer_list_,
537 OnProfileNameChanged(profile_path, old_display_name));
541 void ProfileInfoCache::SetGAIAPictureOfProfileAtIndex(size_t index,
542 const gfx::Image* image) {
543 base::FilePath path = GetPathOfProfileAtIndex(index);
544 std::string key = CacheKeyFromProfilePath(path);
546 // Delete the old bitmap from cache.
547 std::map<std::string, gfx::Image*>::iterator it = gaia_pictures_.find(key);
548 if (it != gaia_pictures_.end()) {
549 delete it->second;
550 gaia_pictures_.erase(it);
553 std::string old_file_name;
554 GetInfoForProfileAtIndex(index)->GetString(
555 kGAIAPictureFileNameKey, &old_file_name);
556 std::string new_file_name;
558 if (!image) {
559 // Delete the old bitmap from disk.
560 if (!old_file_name.empty()) {
561 base::FilePath image_path = path.AppendASCII(old_file_name);
562 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
563 base::Bind(&DeleteBitmap, image_path));
565 } else {
566 // Save the new bitmap to disk.
567 gaia_pictures_[key] = new gfx::Image(*image);
568 scoped_ptr<ImageData> data(new ImageData);
569 scoped_refptr<base::RefCountedMemory> png_data = image->As1xPNGBytes();
570 data->assign(png_data->front(), png_data->front() + png_data->size());
571 if (!data->size()) {
572 LOG(ERROR) << "Failed to PNG encode the image.";
573 } else {
574 new_file_name =
575 old_file_name.empty() ? kGAIAPictureFileName : old_file_name;
576 base::FilePath image_path = path.AppendASCII(new_file_name);
577 bool* success = new bool;
578 BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE,
579 base::Bind(&SaveBitmap, data.release(), image_path, success),
580 base::Bind(&ProfileInfoCache::OnGAIAPictureSaved, AsWeakPtr(),
581 path, success));
585 scoped_ptr<DictionaryValue> info(GetInfoForProfileAtIndex(index)->DeepCopy());
586 info->SetString(kGAIAPictureFileNameKey, new_file_name);
587 // This takes ownership of |info|.
588 SetInfoForProfileAtIndex(index, info.release());
590 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
591 observer_list_,
592 OnProfileAvatarChanged(path));
595 void ProfileInfoCache::SetIsUsingGAIAPictureOfProfileAtIndex(size_t index,
596 bool value) {
597 scoped_ptr<DictionaryValue> info(GetInfoForProfileAtIndex(index)->DeepCopy());
598 info->SetBoolean(kUseGAIAPictureKey, value);
599 // This takes ownership of |info|.
600 SetInfoForProfileAtIndex(index, info.release());
602 // Retrieve some info to update observers who care about avatar changes.
603 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
604 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
605 observer_list_,
606 OnProfileAvatarChanged(profile_path));
609 string16 ProfileInfoCache::ChooseNameForNewProfile(size_t icon_index) const {
610 string16 name;
611 for (int name_index = 1; ; ++name_index) {
612 if (icon_index < kGenericIconCount) {
613 name = l10n_util::GetStringFUTF16Int(IDS_NUMBERED_PROFILE_NAME,
614 name_index);
615 } else {
616 name = l10n_util::GetStringUTF16(
617 kDefaultNames[icon_index - kGenericIconCount]);
618 if (name_index > 1)
619 name.append(UTF8ToUTF16(base::IntToString(name_index)));
622 // Loop through previously named profiles to ensure we're not duplicating.
623 bool name_found = false;
624 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
625 if (GetNameOfProfileAtIndex(i) == name) {
626 name_found = true;
627 break;
630 if (!name_found)
631 return name;
635 bool ProfileInfoCache::GetHasMigratedToGAIAInfoOfProfileAtIndex(
636 size_t index) const {
637 bool value = false;
638 GetInfoForProfileAtIndex(index)->GetBoolean(
639 kHasMigratedToGAIAInfoKey, &value);
640 return value;
643 void ProfileInfoCache::SetHasMigratedToGAIAInfoOfProfileAtIndex(
644 size_t index, bool value) {
645 scoped_ptr<DictionaryValue> info(GetInfoForProfileAtIndex(index)->DeepCopy());
646 info->SetBoolean(kHasMigratedToGAIAInfoKey, value);
647 // This takes ownership of |info|.
648 SetInfoForProfileAtIndex(index, info.release());
651 bool ProfileInfoCache::IconIndexIsUnique(size_t icon_index) const {
652 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
653 if (GetAvatarIconIndexOfProfileAtIndex(i) == icon_index)
654 return false;
656 return true;
659 bool ProfileInfoCache::ChooseAvatarIconIndexForNewProfile(
660 bool allow_generic_icon,
661 bool must_be_unique,
662 size_t* out_icon_index) const {
663 size_t start = allow_generic_icon ? 0 : kGenericIconCount;
664 size_t end = GetDefaultAvatarIconCount();
665 size_t count = end - start;
667 int rand = base::RandInt(0, count);
668 for (size_t i = 0; i < count; ++i) {
669 size_t icon_index = start + (rand + i) % count;
670 if (!must_be_unique || IconIndexIsUnique(icon_index)) {
671 *out_icon_index = icon_index;
672 return true;
676 return false;
679 size_t ProfileInfoCache::ChooseAvatarIconIndexForNewProfile() const {
680 size_t icon_index = 0;
681 // Try to find a unique, non-generic icon.
682 if (ChooseAvatarIconIndexForNewProfile(false, true, &icon_index))
683 return icon_index;
684 // Try to find any unique icon.
685 if (ChooseAvatarIconIndexForNewProfile(true, true, &icon_index))
686 return icon_index;
687 // Settle for any random icon, even if it's not unique.
688 if (ChooseAvatarIconIndexForNewProfile(true, false, &icon_index))
689 return icon_index;
691 NOTREACHED();
692 return 0;
695 const base::FilePath& ProfileInfoCache::GetUserDataDir() const {
696 return user_data_dir_;
699 // static
700 size_t ProfileInfoCache::GetDefaultAvatarIconCount() {
701 return kDefaultAvatarIconsCount;
704 // static
705 int ProfileInfoCache::GetDefaultAvatarIconResourceIDAtIndex(size_t index) {
706 DCHECK(IsDefaultAvatarIconIndex(index));
707 return kDefaultAvatarIconResources[index];
710 // static
711 std::string ProfileInfoCache::GetDefaultAvatarIconUrl(size_t index) {
712 DCHECK(IsDefaultAvatarIconIndex(index));
713 return base::StringPrintf("%s%" PRIuS, kDefaultUrlPrefix, index);
716 // static
717 bool ProfileInfoCache::IsDefaultAvatarIconIndex(size_t index) {
718 return index < kDefaultAvatarIconsCount;
721 // static
722 bool ProfileInfoCache::IsDefaultAvatarIconUrl(const std::string& url,
723 size_t* icon_index) {
724 DCHECK(icon_index);
725 if (url.find(kDefaultUrlPrefix) != 0)
726 return false;
728 int int_value = -1;
729 if (base::StringToInt(base::StringPiece(url.begin() +
730 strlen(kDefaultUrlPrefix),
731 url.end()),
732 &int_value)) {
733 if (int_value < 0 ||
734 int_value >= static_cast<int>(kDefaultAvatarIconsCount))
735 return false;
736 *icon_index = int_value;
737 return true;
740 return false;
743 const DictionaryValue* ProfileInfoCache::GetInfoForProfileAtIndex(
744 size_t index) const {
745 DCHECK_LT(index, GetNumberOfProfiles());
746 const DictionaryValue* cache =
747 prefs_->GetDictionary(prefs::kProfileInfoCache);
748 const DictionaryValue* info = NULL;
749 cache->GetDictionary(sorted_keys_[index], &info);
750 return info;
753 void ProfileInfoCache::SetInfoForProfileAtIndex(size_t index,
754 DictionaryValue* info) {
755 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
756 DictionaryValue* cache = update.Get();
757 cache->Set(sorted_keys_[index], info);
759 content::NotificationService::current()->Notify(
760 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
761 content::NotificationService::AllSources(),
762 content::NotificationService::NoDetails());
765 std::string ProfileInfoCache::CacheKeyFromProfilePath(
766 const base::FilePath& profile_path) const {
767 DCHECK(user_data_dir_ == profile_path.DirName());
768 base::FilePath base_name = profile_path.BaseName();
769 return base_name.MaybeAsASCII();
772 std::vector<std::string>::iterator ProfileInfoCache::FindPositionForProfile(
773 const std::string& search_key,
774 const string16& search_name) {
775 string16 search_name_l = base::i18n::ToLower(search_name);
776 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
777 string16 name_l = base::i18n::ToLower(GetNameOfProfileAtIndex(i));
778 int name_compare = search_name_l.compare(name_l);
779 if (name_compare < 0)
780 return sorted_keys_.begin() + i;
781 if (name_compare == 0) {
782 int key_compare = search_key.compare(sorted_keys_[i]);
783 if (key_compare < 0)
784 return sorted_keys_.begin() + i;
787 return sorted_keys_.end();
790 void ProfileInfoCache::UpdateSortForProfileIndex(size_t index) {
791 string16 name = GetNameOfProfileAtIndex(index);
793 // Remove and reinsert key in |sorted_keys_| to alphasort.
794 std::string key = CacheKeyFromProfilePath(GetPathOfProfileAtIndex(index));
795 std::vector<std::string>::iterator key_it =
796 std::find(sorted_keys_.begin(), sorted_keys_.end(), key);
797 DCHECK(key_it != sorted_keys_.end());
798 sorted_keys_.erase(key_it);
799 sorted_keys_.insert(FindPositionForProfile(key, name), key);
801 content::NotificationService::current()->Notify(
802 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
803 content::NotificationService::AllSources(),
804 content::NotificationService::NoDetails());
807 // static
808 std::vector<string16> ProfileInfoCache::GetProfileNames() {
809 std::vector<string16> names;
810 PrefService* local_state = g_browser_process->local_state();
811 const DictionaryValue* cache = local_state->GetDictionary(
812 prefs::kProfileInfoCache);
813 string16 name;
814 for (base::DictionaryValue::Iterator it(*cache); !it.IsAtEnd();
815 it.Advance()) {
816 const base::DictionaryValue* info = NULL;
817 it.value().GetAsDictionary(&info);
818 info->GetString(kNameKey, &name);
819 names.push_back(name);
821 return names;
824 // static
825 void ProfileInfoCache::RegisterPrefs(PrefRegistrySimple* registry) {
826 registry->RegisterDictionaryPref(prefs::kProfileInfoCache);