Temporarily re-enabling SizeAfterPrefChange test with traces (this time for Linux...
[chromium-blink-merge.git] / chrome / browser / profiles / profile_info_cache.cc
blobe479fee2bb4fc25822b5d41c9a16b27db272eae7
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/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;
39 namespace {
41 const char kNameKey[] = "name";
42 const char kShortcutNameKey[] = "shortcut_name";
43 const char kGAIANameKey[] = "gaia_name";
44 const char kGAIAGivenNameKey[] = "gaia_given_name";
45 const char kUserNameKey[] = "user_name";
46 const char kIsUsingDefaultName[] = "is_using_default_name";
47 const char kAvatarIconKey[] = "avatar_icon";
48 const char kAuthCredentialsKey[] = "local_auth_credentials";
49 const char kUseGAIAPictureKey[] = "use_gaia_picture";
50 const char kBackgroundAppsKey[] = "background_apps";
51 const char kGAIAPictureFileNameKey[] = "gaia_picture_file_name";
52 const char 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 // 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.";
95 return;
98 if (base::WriteFile(image_path, reinterpret_cast<char*>(&(*data)[0]),
99 data->size()) == -1) {
100 LOG(ERROR) << "Failed to save image to file.";
101 return;
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
109 // will be NULL.
110 void ReadBitmap(const base::FilePath& image_path,
111 gfx::Image** out_image) {
112 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
113 *out_image = NULL;
115 // If the path doesn't exist, don't even try reading it.
116 if (!base::PathExists(image_path))
117 return;
119 std::string image_data;
120 if (!base::ReadFileToString(image_path, &image_data)) {
121 LOG(ERROR) << "Failed to read PNG file from disk.";
122 return;
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.";
129 return;
132 *out_image = new gfx::Image(image);
135 void DeleteBitmap(const base::FilePath& image_path) {
136 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
137 base::DeleteFile(image_path, false);
140 bool IsDefaultName(const base::string16& name) {
141 // Check if it's a "First user" old-style name.
142 if (name == l10n_util::GetStringUTF16(IDS_DEFAULT_PROFILE_NAME))
143 return true;
145 // Check if it's one of the old-style profile names.
146 for (size_t i = 0; i < arraysize(kDefaultNames); ++i) {
147 if (name == l10n_util::GetStringUTF16(kDefaultNames[i]))
148 return true;
151 // Check whether it's one of the "Person %d" style names.
152 std::string default_name_format = l10n_util::GetStringFUTF8(
153 IDS_NEW_NUMBERED_PROFILE_NAME, base::string16()) + "%d";
155 int generic_profile_number; // Unused. Just a placeholder for sscanf.
156 int assignments = sscanf(base::UTF16ToUTF8(name).c_str(),
157 default_name_format.c_str(),
158 &generic_profile_number);
159 // Unless it matched the format, this is a custom name.
160 return assignments == 1;
163 } // namespace
165 ProfileInfoCache::ProfileInfoCache(PrefService* prefs,
166 const base::FilePath& user_data_dir)
167 : prefs_(prefs),
168 user_data_dir_(user_data_dir) {
169 // Populate the cache
170 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
171 base::DictionaryValue* cache = update.Get();
172 for (base::DictionaryValue::Iterator it(*cache);
173 !it.IsAtEnd(); it.Advance()) {
174 base::DictionaryValue* info = NULL;
175 cache->GetDictionaryWithoutPathExpansion(it.key(), &info);
176 base::string16 name;
177 info->GetString(kNameKey, &name);
178 sorted_keys_.insert(FindPositionForProfile(it.key(), name), it.key());
179 // TODO(ibraaaa): delete this when 97% of our users are using M31.
180 // http://crbug.com/276163
181 bool is_managed = false;
182 if (info->GetBoolean(kIsManagedKey, &is_managed)) {
183 info->Remove(kIsManagedKey, NULL);
184 info->SetString(kManagedUserId, is_managed ? "DUMMY_ID" : std::string());
186 info->SetBoolean(kIsUsingDefaultName, IsDefaultName(name));
189 // If needed, start downloading the high-res avatars.
190 if (switches::IsNewAvatarMenu()) {
191 for (size_t i = 0; i < GetNumberOfProfiles(); i++) {
192 DownloadHighResAvatar(GetAvatarIconIndexOfProfileAtIndex(i),
193 GetPathOfProfileAtIndex(i));
198 ProfileInfoCache::~ProfileInfoCache() {
199 STLDeleteContainerPairSecondPointers(
200 cached_avatar_images_.begin(), cached_avatar_images_.end());
201 STLDeleteContainerPairSecondPointers(
202 avatar_images_downloads_in_progress_.begin(),
203 avatar_images_downloads_in_progress_.end());
206 void ProfileInfoCache::AddProfileToCache(const base::FilePath& profile_path,
207 const base::string16& name,
208 const base::string16& username,
209 size_t icon_index,
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,
219 profiles::GetDefaultAvatarIconUrl(icon_index));
220 // Default value for whether background apps are running is false.
221 info->SetBoolean(kBackgroundAppsKey, false);
222 info->SetString(kManagedUserId, managed_user_id);
223 info->SetBoolean(kIsOmittedFromProfileListKey, !managed_user_id.empty());
224 info->SetBoolean(kProfileIsEphemeral, false);
225 info->SetBoolean(kIsUsingDefaultName, IsDefaultName(name));
226 cache->SetWithoutPathExpansion(key, info.release());
228 sorted_keys_.insert(FindPositionForProfile(key, name), key);
230 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
231 observer_list_,
232 OnProfileAdded(profile_path));
234 content::NotificationService::current()->Notify(
235 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
236 content::NotificationService::AllSources(),
237 content::NotificationService::NoDetails());
240 void ProfileInfoCache::AddObserver(ProfileInfoCacheObserver* obs) {
241 observer_list_.AddObserver(obs);
244 void ProfileInfoCache::RemoveObserver(ProfileInfoCacheObserver* obs) {
245 observer_list_.RemoveObserver(obs);
248 void ProfileInfoCache::DeleteProfileFromCache(
249 const base::FilePath& profile_path) {
250 size_t profile_index = GetIndexOfProfileWithPath(profile_path);
251 if (profile_index == std::string::npos) {
252 NOTREACHED();
253 return;
255 base::string16 name = GetNameOfProfileAtIndex(profile_index);
257 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
258 observer_list_,
259 OnProfileWillBeRemoved(profile_path));
261 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
262 base::DictionaryValue* cache = update.Get();
263 std::string key = CacheKeyFromProfilePath(profile_path);
264 cache->Remove(key, NULL);
265 sorted_keys_.erase(std::find(sorted_keys_.begin(), sorted_keys_.end(), key));
267 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
268 observer_list_,
269 OnProfileWasRemoved(profile_path, name));
271 content::NotificationService::current()->Notify(
272 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
273 content::NotificationService::AllSources(),
274 content::NotificationService::NoDetails());
277 size_t ProfileInfoCache::GetNumberOfProfiles() const {
278 return sorted_keys_.size();
281 size_t ProfileInfoCache::GetIndexOfProfileWithPath(
282 const base::FilePath& profile_path) const {
283 if (profile_path.DirName() != user_data_dir_)
284 return std::string::npos;
285 std::string search_key = CacheKeyFromProfilePath(profile_path);
286 for (size_t i = 0; i < sorted_keys_.size(); ++i) {
287 if (sorted_keys_[i] == search_key)
288 return i;
290 return std::string::npos;
293 base::string16 ProfileInfoCache::GetNameOfProfileAtIndex(size_t index) const {
294 base::string16 name;
295 // Unless the user has customized the profile name, we should use the
296 // profile's Gaia given name, if it's available.
297 if (ProfileIsUsingDefaultNameAtIndex(index)) {
298 base::string16 given_name = GetGAIAGivenNameOfProfileAtIndex(index);
299 name = given_name.empty() ? GetGAIANameOfProfileAtIndex(index) : given_name;
301 if (name.empty())
302 GetInfoForProfileAtIndex(index)->GetString(kNameKey, &name);
303 return name;
306 base::string16 ProfileInfoCache::GetShortcutNameOfProfileAtIndex(size_t index)
307 const {
308 base::string16 shortcut_name;
309 GetInfoForProfileAtIndex(index)->GetString(
310 kShortcutNameKey, &shortcut_name);
311 return shortcut_name;
314 base::FilePath ProfileInfoCache::GetPathOfProfileAtIndex(size_t index) const {
315 return user_data_dir_.AppendASCII(sorted_keys_[index]);
318 base::Time ProfileInfoCache::GetProfileActiveTimeAtIndex(size_t index) const {
319 double dt;
320 if (GetInfoForProfileAtIndex(index)->GetDouble(kActiveTimeKey, &dt)) {
321 return base::Time::FromDoubleT(dt);
322 } else {
323 return base::Time();
327 base::string16 ProfileInfoCache::GetUserNameOfProfileAtIndex(
328 size_t index) const {
329 base::string16 user_name;
330 GetInfoForProfileAtIndex(index)->GetString(kUserNameKey, &user_name);
331 return user_name;
334 const gfx::Image& ProfileInfoCache::GetAvatarIconOfProfileAtIndex(
335 size_t index) const {
336 if (IsUsingGAIAPictureOfProfileAtIndex(index)) {
337 const gfx::Image* image = GetGAIAPictureOfProfileAtIndex(index);
338 if (image)
339 return *image;
342 // Use the high resolution version of the avatar if it exists.
343 if (switches::IsNewAvatarMenu()) {
344 const gfx::Image* image = GetHighResAvatarOfProfileAtIndex(index);
345 if (image)
346 return *image;
349 int resource_id = profiles::GetDefaultAvatarIconResourceIDAtIndex(
350 GetAvatarIconIndexOfProfileAtIndex(index));
351 return ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
354 std::string ProfileInfoCache::GetLocalAuthCredentialsOfProfileAtIndex(
355 size_t index) const {
356 std::string credentials;
357 GetInfoForProfileAtIndex(index)->GetString(kAuthCredentialsKey, &credentials);
358 return credentials;
361 bool ProfileInfoCache::GetBackgroundStatusOfProfileAtIndex(
362 size_t index) const {
363 bool background_app_status;
364 if (!GetInfoForProfileAtIndex(index)->GetBoolean(kBackgroundAppsKey,
365 &background_app_status)) {
366 return false;
368 return background_app_status;
371 base::string16 ProfileInfoCache::GetGAIANameOfProfileAtIndex(
372 size_t index) const {
373 base::string16 name;
374 GetInfoForProfileAtIndex(index)->GetString(kGAIANameKey, &name);
375 return name;
378 base::string16 ProfileInfoCache::GetGAIAGivenNameOfProfileAtIndex(
379 size_t index) const {
380 base::string16 name;
381 GetInfoForProfileAtIndex(index)->GetString(kGAIAGivenNameKey, &name);
382 return name;
385 const gfx::Image* ProfileInfoCache::GetGAIAPictureOfProfileAtIndex(
386 size_t index) const {
387 base::FilePath path = GetPathOfProfileAtIndex(index);
388 std::string key = CacheKeyFromProfilePath(path);
390 std::string file_name;
391 GetInfoForProfileAtIndex(index)->GetString(
392 kGAIAPictureFileNameKey, &file_name);
394 // If the picture is not on disk then return NULL.
395 if (file_name.empty())
396 return NULL;
398 base::FilePath image_path = path.AppendASCII(file_name);
399 return LoadAvatarPictureFromPath(key, image_path);
402 bool ProfileInfoCache::IsUsingGAIAPictureOfProfileAtIndex(size_t index) const {
403 bool value = false;
404 GetInfoForProfileAtIndex(index)->GetBoolean(kUseGAIAPictureKey, &value);
405 return value;
408 bool ProfileInfoCache::ProfileIsManagedAtIndex(size_t index) const {
409 return !GetManagedUserIdOfProfileAtIndex(index).empty();
412 bool ProfileInfoCache::IsOmittedProfileAtIndex(size_t index) const {
413 bool value = false;
414 GetInfoForProfileAtIndex(index)->GetBoolean(kIsOmittedFromProfileListKey,
415 &value);
416 return value;
419 bool ProfileInfoCache::ProfileIsSigninRequiredAtIndex(size_t index) const {
420 bool value = false;
421 GetInfoForProfileAtIndex(index)->GetBoolean(kSigninRequiredKey, &value);
422 return value;
425 std::string ProfileInfoCache::GetManagedUserIdOfProfileAtIndex(
426 size_t index) const {
427 std::string managed_user_id;
428 GetInfoForProfileAtIndex(index)->GetString(kManagedUserId, &managed_user_id);
429 return managed_user_id;
432 bool ProfileInfoCache::ProfileIsEphemeralAtIndex(size_t index) const {
433 bool value = false;
434 GetInfoForProfileAtIndex(index)->GetBoolean(kProfileIsEphemeral, &value);
435 return value;
438 bool ProfileInfoCache::ProfileIsUsingDefaultNameAtIndex(size_t index) const {
439 bool value = false;
440 GetInfoForProfileAtIndex(index)->GetBoolean(kIsUsingDefaultName, &value);
441 return value;
444 size_t ProfileInfoCache::GetAvatarIconIndexOfProfileAtIndex(size_t index)
445 const {
446 std::string icon_url;
447 GetInfoForProfileAtIndex(index)->GetString(kAvatarIconKey, &icon_url);
448 size_t icon_index = 0;
449 if (!profiles::IsDefaultAvatarIconUrl(icon_url, &icon_index))
450 DLOG(WARNING) << "Unknown avatar icon: " << icon_url;
452 return icon_index;
455 void ProfileInfoCache::SetProfileActiveTimeAtIndex(size_t index) {
456 scoped_ptr<base::DictionaryValue> info(
457 GetInfoForProfileAtIndex(index)->DeepCopy());
458 info->SetDouble(kActiveTimeKey, base::Time::Now().ToDoubleT());
459 // This takes ownership of |info|.
460 SetInfoQuietlyForProfileAtIndex(index, info.release());
463 void ProfileInfoCache::SetNameOfProfileAtIndex(size_t index,
464 const base::string16& name) {
465 scoped_ptr<base::DictionaryValue> info(
466 GetInfoForProfileAtIndex(index)->DeepCopy());
467 base::string16 current_name;
468 info->GetString(kNameKey, &current_name);
469 if (name == current_name)
470 return;
472 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
473 info->SetString(kNameKey, name);
474 info->SetBoolean(kIsUsingDefaultName, false);
476 // This takes ownership of |info|.
477 SetInfoForProfileAtIndex(index, info.release());
478 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
479 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
480 UpdateSortForProfileIndex(index);
482 if (old_display_name != new_display_name) {
483 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
484 observer_list_,
485 OnProfileNameChanged(profile_path, old_display_name));
489 void ProfileInfoCache::SetShortcutNameOfProfileAtIndex(
490 size_t index,
491 const base::string16& shortcut_name) {
492 if (shortcut_name == GetShortcutNameOfProfileAtIndex(index))
493 return;
494 scoped_ptr<base::DictionaryValue> info(
495 GetInfoForProfileAtIndex(index)->DeepCopy());
496 info->SetString(kShortcutNameKey, shortcut_name);
497 // This takes ownership of |info|.
498 SetInfoForProfileAtIndex(index, info.release());
501 void ProfileInfoCache::SetUserNameOfProfileAtIndex(
502 size_t index,
503 const base::string16& user_name) {
504 if (user_name == GetUserNameOfProfileAtIndex(index))
505 return;
507 scoped_ptr<base::DictionaryValue> info(
508 GetInfoForProfileAtIndex(index)->DeepCopy());
509 info->SetString(kUserNameKey, user_name);
510 // This takes ownership of |info|.
511 SetInfoForProfileAtIndex(index, info.release());
514 void ProfileInfoCache::SetAvatarIconOfProfileAtIndex(size_t index,
515 size_t icon_index) {
516 scoped_ptr<base::DictionaryValue> info(
517 GetInfoForProfileAtIndex(index)->DeepCopy());
518 info->SetString(kAvatarIconKey,
519 profiles::GetDefaultAvatarIconUrl(icon_index));
520 // This takes ownership of |info|.
521 SetInfoForProfileAtIndex(index, info.release());
523 // If needed, start downloading the high-res avatar.
524 if (switches::IsNewAvatarMenu())
525 DownloadHighResAvatar(icon_index, GetPathOfProfileAtIndex(index));
527 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
528 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
529 observer_list_,
530 OnProfileAvatarChanged(profile_path));
533 void ProfileInfoCache::SetIsOmittedProfileAtIndex(size_t index,
534 bool is_omitted) {
535 if (IsOmittedProfileAtIndex(index) == is_omitted)
536 return;
537 scoped_ptr<base::DictionaryValue> info(
538 GetInfoForProfileAtIndex(index)->DeepCopy());
539 info->SetBoolean(kIsOmittedFromProfileListKey, is_omitted);
540 // This takes ownership of |info|.
541 SetInfoForProfileAtIndex(index, info.release());
544 void ProfileInfoCache::SetManagedUserIdOfProfileAtIndex(size_t index,
545 const std::string& id) {
546 if (GetManagedUserIdOfProfileAtIndex(index) == id)
547 return;
548 scoped_ptr<base::DictionaryValue> info(
549 GetInfoForProfileAtIndex(index)->DeepCopy());
550 info->SetString(kManagedUserId, id);
551 // This takes ownership of |info|.
552 SetInfoForProfileAtIndex(index, info.release());
555 void ProfileInfoCache::SetLocalAuthCredentialsOfProfileAtIndex(
556 size_t index,
557 const std::string& credentials) {
558 scoped_ptr<base::DictionaryValue> info(
559 GetInfoForProfileAtIndex(index)->DeepCopy());
560 info->SetString(kAuthCredentialsKey, credentials);
561 // This takes ownership of |info|.
562 SetInfoForProfileAtIndex(index, info.release());
565 void ProfileInfoCache::SetBackgroundStatusOfProfileAtIndex(
566 size_t index,
567 bool running_background_apps) {
568 if (GetBackgroundStatusOfProfileAtIndex(index) == running_background_apps)
569 return;
570 scoped_ptr<base::DictionaryValue> info(
571 GetInfoForProfileAtIndex(index)->DeepCopy());
572 info->SetBoolean(kBackgroundAppsKey, running_background_apps);
573 // This takes ownership of |info|.
574 SetInfoForProfileAtIndex(index, info.release());
577 void ProfileInfoCache::SetGAIANameOfProfileAtIndex(size_t index,
578 const base::string16& name) {
579 if (name == GetGAIANameOfProfileAtIndex(index))
580 return;
582 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
583 scoped_ptr<base::DictionaryValue> info(
584 GetInfoForProfileAtIndex(index)->DeepCopy());
585 info->SetString(kGAIANameKey, name);
586 // This takes ownership of |info|.
587 SetInfoForProfileAtIndex(index, info.release());
588 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
589 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
590 UpdateSortForProfileIndex(index);
592 if (old_display_name != new_display_name) {
593 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
594 observer_list_,
595 OnProfileNameChanged(profile_path, old_display_name));
599 void ProfileInfoCache::SetGAIAGivenNameOfProfileAtIndex(
600 size_t index,
601 const base::string16& name) {
602 if (name == GetGAIAGivenNameOfProfileAtIndex(index))
603 return;
605 scoped_ptr<base::DictionaryValue> info(
606 GetInfoForProfileAtIndex(index)->DeepCopy());
607 info->SetString(kGAIAGivenNameKey, name);
608 // This takes ownership of |info|.
609 SetInfoForProfileAtIndex(index, info.release());
612 void ProfileInfoCache::SetGAIAPictureOfProfileAtIndex(size_t index,
613 const gfx::Image* image) {
614 base::FilePath path = GetPathOfProfileAtIndex(index);
615 std::string key = CacheKeyFromProfilePath(path);
617 // Delete the old bitmap from cache.
618 std::map<std::string, gfx::Image*>::iterator it =
619 cached_avatar_images_.find(key);
620 if (it != cached_avatar_images_.end()) {
621 delete it->second;
622 cached_avatar_images_.erase(it);
625 std::string old_file_name;
626 GetInfoForProfileAtIndex(index)->GetString(
627 kGAIAPictureFileNameKey, &old_file_name);
628 std::string new_file_name;
630 if (!image) {
631 // Delete the old bitmap from disk.
632 if (!old_file_name.empty()) {
633 base::FilePath image_path = path.AppendASCII(old_file_name);
634 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
635 base::Bind(&DeleteBitmap, image_path));
637 } else {
638 // Save the new bitmap to disk.
639 new_file_name =
640 old_file_name.empty() ? profiles::kGAIAPictureFileName : old_file_name;
641 base::FilePath image_path = path.AppendASCII(new_file_name);
642 SaveAvatarImageAtPath(
643 image, key, image_path, GetPathOfProfileAtIndex(index));
646 scoped_ptr<base::DictionaryValue> info(
647 GetInfoForProfileAtIndex(index)->DeepCopy());
648 info->SetString(kGAIAPictureFileNameKey, new_file_name);
649 // This takes ownership of |info|.
650 SetInfoForProfileAtIndex(index, info.release());
652 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
653 observer_list_,
654 OnProfileAvatarChanged(path));
657 void ProfileInfoCache::SetIsUsingGAIAPictureOfProfileAtIndex(size_t index,
658 bool value) {
659 scoped_ptr<base::DictionaryValue> info(
660 GetInfoForProfileAtIndex(index)->DeepCopy());
661 info->SetBoolean(kUseGAIAPictureKey, value);
662 // This takes ownership of |info|.
663 SetInfoForProfileAtIndex(index, info.release());
665 // Retrieve some info to update observers who care about avatar changes.
666 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
667 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
668 observer_list_,
669 OnProfileAvatarChanged(profile_path));
672 void ProfileInfoCache::SetProfileSigninRequiredAtIndex(size_t index,
673 bool value) {
674 if (value == ProfileIsSigninRequiredAtIndex(index))
675 return;
677 scoped_ptr<base::DictionaryValue> info(
678 GetInfoForProfileAtIndex(index)->DeepCopy());
679 info->SetBoolean(kSigninRequiredKey, value);
680 // This takes ownership of |info|.
681 SetInfoForProfileAtIndex(index, info.release());
683 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
684 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
685 observer_list_,
686 OnProfileSigninRequiredChanged(profile_path));
689 void ProfileInfoCache::SetProfileIsEphemeralAtIndex(size_t index, bool value) {
690 if (value == ProfileIsEphemeralAtIndex(index))
691 return;
693 scoped_ptr<base::DictionaryValue> info(
694 GetInfoForProfileAtIndex(index)->DeepCopy());
695 info->SetBoolean(kProfileIsEphemeral, value);
696 // This takes ownership of |info|.
697 SetInfoForProfileAtIndex(index, info.release());
700 void ProfileInfoCache::SetProfileIsUsingDefaultNameAtIndex(
701 size_t index, bool value) {
702 if (value == ProfileIsUsingDefaultNameAtIndex(index))
703 return;
705 scoped_ptr<base::DictionaryValue> info(
706 GetInfoForProfileAtIndex(index)->DeepCopy());
707 info->SetBoolean(kIsUsingDefaultName, value);
708 // This takes ownership of |info|.
709 SetInfoForProfileAtIndex(index, info.release());
712 base::string16 ProfileInfoCache::ChooseNameForNewProfile(
713 size_t icon_index) const {
714 base::string16 name;
715 for (int name_index = 1; ; ++name_index) {
716 if (switches::IsNewProfileManagement()) {
717 name = l10n_util::GetStringFUTF16Int(IDS_NEW_NUMBERED_PROFILE_NAME,
718 name_index);
719 } else if (icon_index < profiles::GetGenericAvatarIconCount()) {
720 name = l10n_util::GetStringFUTF16Int(IDS_NUMBERED_PROFILE_NAME,
721 name_index);
722 } else {
723 name = l10n_util::GetStringUTF16(
724 kDefaultNames[icon_index - profiles::GetGenericAvatarIconCount()]);
725 if (name_index > 1)
726 name.append(base::UTF8ToUTF16(base::IntToString(name_index)));
729 // Loop through previously named profiles to ensure we're not duplicating.
730 bool name_found = false;
731 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
732 if (GetNameOfProfileAtIndex(i) == name) {
733 name_found = true;
734 break;
737 if (!name_found)
738 return name;
742 size_t ProfileInfoCache::ChooseAvatarIconIndexForNewProfile() const {
743 size_t icon_index = 0;
744 // Try to find a unique, non-generic icon.
745 if (ChooseAvatarIconIndexForNewProfile(false, true, &icon_index))
746 return icon_index;
747 // Try to find any unique icon.
748 if (ChooseAvatarIconIndexForNewProfile(true, true, &icon_index))
749 return icon_index;
750 // Settle for any random icon, even if it's not unique.
751 if (ChooseAvatarIconIndexForNewProfile(true, false, &icon_index))
752 return icon_index;
754 NOTREACHED();
755 return 0;
758 const base::FilePath& ProfileInfoCache::GetUserDataDir() const {
759 return user_data_dir_;
762 // static
763 std::vector<base::string16> ProfileInfoCache::GetProfileNames() {
764 std::vector<base::string16> names;
765 PrefService* local_state = g_browser_process->local_state();
766 const base::DictionaryValue* cache = local_state->GetDictionary(
767 prefs::kProfileInfoCache);
768 base::string16 name;
769 for (base::DictionaryValue::Iterator it(*cache); !it.IsAtEnd();
770 it.Advance()) {
771 const base::DictionaryValue* info = NULL;
772 it.value().GetAsDictionary(&info);
773 info->GetString(kNameKey, &name);
774 names.push_back(name);
776 return names;
779 // static
780 void ProfileInfoCache::RegisterPrefs(PrefRegistrySimple* registry) {
781 registry->RegisterDictionaryPref(prefs::kProfileInfoCache);
784 void ProfileInfoCache::DownloadHighResAvatar(
785 size_t icon_index,
786 const base::FilePath& profile_path) {
787 // TODO(noms): We should check whether the file already exists on disk
788 // before trying to re-download it. For now, since this is behind a flag and
789 // the resources are still changing, re-download it every time the profile
790 // avatar changes, to make sure we have the latest copy.
791 std::string file_name = profiles::GetDefaultAvatarIconFileNameAtIndex(
792 icon_index);
793 // If the file is already being downloaded, don't start another download.
794 if (avatar_images_downloads_in_progress_[file_name])
795 return;
797 // Start the download for this file. The cache takes ownership of the
798 // |avatar_downloader|, which will be deleted when the download completes, or
799 // if that never happens, when the ProfileInfoCache is destroyed.
800 ProfileAvatarDownloader* avatar_downloader = new ProfileAvatarDownloader(
801 icon_index,
802 profile_path,
803 this);
804 avatar_images_downloads_in_progress_[file_name] = avatar_downloader;
805 avatar_downloader->Start();
808 void ProfileInfoCache::SaveAvatarImageAtPath(
809 const gfx::Image* image,
810 const std::string& key,
811 const base::FilePath& image_path,
812 const base::FilePath& profile_path) {
813 cached_avatar_images_[key] = new gfx::Image(*image);
815 scoped_ptr<ImageData> data(new ImageData);
816 scoped_refptr<base::RefCountedMemory> png_data = image->As1xPNGBytes();
817 data->assign(png_data->front(), png_data->front() + png_data->size());
819 if (!data->size()) {
820 LOG(ERROR) << "Failed to PNG encode the image.";
821 } else {
822 base::Closure callback = base::Bind(&ProfileInfoCache::OnAvatarPictureSaved,
823 AsWeakPtr(), key, profile_path);
825 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
826 base::Bind(&SaveBitmap, base::Passed(&data), image_path, callback));
830 const base::DictionaryValue* ProfileInfoCache::GetInfoForProfileAtIndex(
831 size_t index) const {
832 DCHECK_LT(index, GetNumberOfProfiles());
833 const base::DictionaryValue* cache =
834 prefs_->GetDictionary(prefs::kProfileInfoCache);
835 const base::DictionaryValue* info = NULL;
836 cache->GetDictionaryWithoutPathExpansion(sorted_keys_[index], &info);
837 return info;
840 void ProfileInfoCache::SetInfoQuietlyForProfileAtIndex(
841 size_t index, base::DictionaryValue* info) {
842 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
843 base::DictionaryValue* cache = update.Get();
844 cache->SetWithoutPathExpansion(sorted_keys_[index], info);
847 // TODO(noms): Switch to newer notification system.
848 void ProfileInfoCache::SetInfoForProfileAtIndex(size_t index,
849 base::DictionaryValue* info) {
850 SetInfoQuietlyForProfileAtIndex(index, info);
852 content::NotificationService::current()->Notify(
853 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
854 content::NotificationService::AllSources(),
855 content::NotificationService::NoDetails());
858 std::string ProfileInfoCache::CacheKeyFromProfilePath(
859 const base::FilePath& profile_path) const {
860 DCHECK(user_data_dir_ == profile_path.DirName());
861 base::FilePath base_name = profile_path.BaseName();
862 return base_name.MaybeAsASCII();
865 std::vector<std::string>::iterator ProfileInfoCache::FindPositionForProfile(
866 const std::string& search_key,
867 const base::string16& search_name) {
868 base::string16 search_name_l = base::i18n::ToLower(search_name);
869 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
870 base::string16 name_l = base::i18n::ToLower(GetNameOfProfileAtIndex(i));
871 int name_compare = search_name_l.compare(name_l);
872 if (name_compare < 0)
873 return sorted_keys_.begin() + i;
874 if (name_compare == 0) {
875 int key_compare = search_key.compare(sorted_keys_[i]);
876 if (key_compare < 0)
877 return sorted_keys_.begin() + i;
880 return sorted_keys_.end();
883 bool ProfileInfoCache::IconIndexIsUnique(size_t icon_index) const {
884 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
885 if (GetAvatarIconIndexOfProfileAtIndex(i) == icon_index)
886 return false;
888 return true;
891 bool ProfileInfoCache::ChooseAvatarIconIndexForNewProfile(
892 bool allow_generic_icon,
893 bool must_be_unique,
894 size_t* out_icon_index) const {
895 // Always allow all icons for new profiles if using the
896 // --new-profile-management flag.
897 if (switches::IsNewProfileManagement())
898 allow_generic_icon = true;
899 size_t start = allow_generic_icon ? 0 : profiles::GetGenericAvatarIconCount();
900 size_t end = profiles::GetDefaultAvatarIconCount();
901 size_t count = end - start;
903 int rand = base::RandInt(0, count);
904 for (size_t i = 0; i < count; ++i) {
905 size_t icon_index = start + (rand + i) % count;
906 if (!must_be_unique || IconIndexIsUnique(icon_index)) {
907 *out_icon_index = icon_index;
908 return true;
912 return false;
915 void ProfileInfoCache::UpdateSortForProfileIndex(size_t index) {
916 base::string16 name = GetNameOfProfileAtIndex(index);
918 // Remove and reinsert key in |sorted_keys_| to alphasort.
919 std::string key = CacheKeyFromProfilePath(GetPathOfProfileAtIndex(index));
920 std::vector<std::string>::iterator key_it =
921 std::find(sorted_keys_.begin(), sorted_keys_.end(), key);
922 DCHECK(key_it != sorted_keys_.end());
923 sorted_keys_.erase(key_it);
924 sorted_keys_.insert(FindPositionForProfile(key, name), key);
926 content::NotificationService::current()->Notify(
927 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
928 content::NotificationService::AllSources(),
929 content::NotificationService::NoDetails());
932 const gfx::Image* ProfileInfoCache::GetHighResAvatarOfProfileAtIndex(
933 size_t index) const {
934 int avatar_index = GetAvatarIconIndexOfProfileAtIndex(index);
935 std::string key = profiles::GetDefaultAvatarIconFileNameAtIndex(avatar_index);
937 if (!strcmp(key.c_str(), profiles::GetNoHighResAvatarFileName()))
938 return NULL;
940 base::FilePath image_path =
941 profiles::GetPathOfHighResAvatarAtIndex(avatar_index);
942 return LoadAvatarPictureFromPath(key, image_path);
945 const gfx::Image* ProfileInfoCache::LoadAvatarPictureFromPath(
946 const std::string& key,
947 const base::FilePath& image_path) const {
948 // If the picture is already loaded then use it.
949 if (cached_avatar_images_.count(key)) {
950 if (cached_avatar_images_[key]->IsEmpty())
951 return NULL;
952 return cached_avatar_images_[key];
955 // If the picture is already being loaded then don't try loading it again.
956 if (cached_avatar_images_loading_[key])
957 return NULL;
958 cached_avatar_images_loading_[key] = true;
960 gfx::Image** image = new gfx::Image*;
961 BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE,
962 base::Bind(&ReadBitmap, image_path, image),
963 base::Bind(&ProfileInfoCache::OnAvatarPictureLoaded,
964 const_cast<ProfileInfoCache*>(this)->AsWeakPtr(), key, image));
965 return NULL;
968 void ProfileInfoCache::OnAvatarPictureLoaded(const std::string& key,
969 gfx::Image** image) const {
970 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
972 cached_avatar_images_loading_[key] = false;
973 delete cached_avatar_images_[key];
975 if (*image) {
976 cached_avatar_images_[key] = *image;
977 } else {
978 // Place an empty image in the cache to avoid reloading it again.
979 cached_avatar_images_[key] = new gfx::Image();
981 delete image;
983 content::NotificationService::current()->Notify(
984 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
985 content::NotificationService::AllSources(),
986 content::NotificationService::NoDetails());
989 void ProfileInfoCache::OnAvatarPictureSaved(
990 const std::string& file_name,
991 const base::FilePath& profile_path) {
992 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
994 content::NotificationService::current()->Notify(
995 chrome::NOTIFICATION_PROFILE_CACHE_PICTURE_SAVED,
996 content::NotificationService::AllSources(),
997 content::NotificationService::NoDetails());
999 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
1000 observer_list_,
1001 OnProfileAvatarChanged(profile_path));
1003 // Remove the file from the list of downloads in progress. Note that this list
1004 // only contains the high resolution avatars, and not the Gaia profile images.
1005 if (!avatar_images_downloads_in_progress_[file_name])
1006 return;
1008 delete avatar_images_downloads_in_progress_[file_name];
1009 avatar_images_downloads_in_progress_[file_name] = NULL;