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/files/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 "chrome/grit/generated_resources.h"
28 #include "components/signin/core/common/profile_management_switches.h"
29 #include "content/public/browser/browser_thread.h"
30 #include "content/public/browser/notification_service.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 #if defined(ENABLE_SUPERVISED_USERS)
37 #include "chrome/browser/supervised_user/supervised_user_constants.h"
40 using content::BrowserThread
;
44 const char kNameKey
[] = "name";
45 const char kShortcutNameKey
[] = "shortcut_name";
46 const char kGAIANameKey
[] = "gaia_name";
47 const char kGAIAGivenNameKey
[] = "gaia_given_name";
48 const char kUserNameKey
[] = "user_name";
49 const char kIsUsingDefaultNameKey
[] = "is_using_default_name";
50 const char kIsUsingDefaultAvatarKey
[] = "is_using_default_avatar";
51 const char kAvatarIconKey
[] = "avatar_icon";
52 const char kAuthCredentialsKey
[] = "local_auth_credentials";
53 const char kUseGAIAPictureKey
[] = "use_gaia_picture";
54 const char kBackgroundAppsKey
[] = "background_apps";
55 const char kGAIAPictureFileNameKey
[] = "gaia_picture_file_name";
56 const char kIsOmittedFromProfileListKey
[] = "is_omitted_from_profile_list";
57 const char kSigninRequiredKey
[] = "signin_required";
58 const char kSupervisedUserId
[] = "managed_user_id";
59 const char kProfileIsEphemeral
[] = "is_ephemeral";
60 const char kActiveTimeKey
[] = "active_time";
61 const char kIsAuthErrorKey
[] = "is_auth_error";
63 // First eight are generic icons, which use IDS_NUMBERED_PROFILE_NAME.
64 const int kDefaultNames
[] = {
65 IDS_DEFAULT_AVATAR_NAME_8
,
66 IDS_DEFAULT_AVATAR_NAME_9
,
67 IDS_DEFAULT_AVATAR_NAME_10
,
68 IDS_DEFAULT_AVATAR_NAME_11
,
69 IDS_DEFAULT_AVATAR_NAME_12
,
70 IDS_DEFAULT_AVATAR_NAME_13
,
71 IDS_DEFAULT_AVATAR_NAME_14
,
72 IDS_DEFAULT_AVATAR_NAME_15
,
73 IDS_DEFAULT_AVATAR_NAME_16
,
74 IDS_DEFAULT_AVATAR_NAME_17
,
75 IDS_DEFAULT_AVATAR_NAME_18
,
76 IDS_DEFAULT_AVATAR_NAME_19
,
77 IDS_DEFAULT_AVATAR_NAME_20
,
78 IDS_DEFAULT_AVATAR_NAME_21
,
79 IDS_DEFAULT_AVATAR_NAME_22
,
80 IDS_DEFAULT_AVATAR_NAME_23
,
81 IDS_DEFAULT_AVATAR_NAME_24
,
82 IDS_DEFAULT_AVATAR_NAME_25
,
83 IDS_DEFAULT_AVATAR_NAME_26
86 typedef std::vector
<unsigned char> ImageData
;
88 // Writes |data| to disk and takes ownership of the pointer. On successful
89 // completion, it runs |callback|.
90 void SaveBitmap(scoped_ptr
<ImageData
> data
,
91 const base::FilePath
& image_path
,
92 const base::Closure
& callback
) {
93 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
95 // Make sure the destination directory exists.
96 base::FilePath dir
= image_path
.DirName();
97 if (!base::DirectoryExists(dir
) && !base::CreateDirectory(dir
)) {
98 LOG(ERROR
) << "Failed to create parent directory.";
102 if (base::WriteFile(image_path
, reinterpret_cast<char*>(&(*data
)[0]),
103 data
->size()) == -1) {
104 LOG(ERROR
) << "Failed to save image to file.";
108 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, callback
);
111 // Reads a PNG from disk and decodes it. If the bitmap was successfully read
112 // from disk the then |out_image| will contain the bitmap image, otherwise it
114 void ReadBitmap(const base::FilePath
& image_path
,
115 gfx::Image
** out_image
) {
116 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
119 // If the path doesn't exist, don't even try reading it.
120 if (!base::PathExists(image_path
))
123 std::string image_data
;
124 if (!base::ReadFileToString(image_path
, &image_data
)) {
125 LOG(ERROR
) << "Failed to read PNG file from disk.";
129 gfx::Image image
= gfx::Image::CreateFrom1xPNGBytes(
130 base::RefCountedString::TakeString(&image_data
));
131 if (image
.IsEmpty()) {
132 LOG(ERROR
) << "Failed to decode PNG file.";
136 *out_image
= new gfx::Image(image
);
139 void RunCallbackIfFileMissing(const base::FilePath
& file_path
,
140 const base::Closure
& callback
) {
141 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
142 if (!base::PathExists(file_path
))
143 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, callback
);
146 void DeleteBitmap(const base::FilePath
& image_path
) {
147 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
148 base::DeleteFile(image_path
, false);
153 ProfileInfoCache::ProfileInfoCache(PrefService
* prefs
,
154 const base::FilePath
& user_data_dir
)
156 user_data_dir_(user_data_dir
) {
157 // Populate the cache
158 DictionaryPrefUpdate
update(prefs_
, prefs::kProfileInfoCache
);
159 base::DictionaryValue
* cache
= update
.Get();
160 for (base::DictionaryValue::Iterator
it(*cache
);
161 !it
.IsAtEnd(); it
.Advance()) {
162 base::DictionaryValue
* info
= NULL
;
163 cache
->GetDictionaryWithoutPathExpansion(it
.key(), &info
);
165 info
->GetString(kNameKey
, &name
);
166 sorted_keys_
.insert(FindPositionForProfile(it
.key(), name
), it
.key());
168 bool using_default_name
;
169 if (!info
->GetBoolean(kIsUsingDefaultNameKey
, &using_default_name
)) {
170 // If the preference hasn't been set, and the name is default, assume
171 // that the user hasn't done this on purpose.
172 using_default_name
= IsDefaultProfileName(name
);
173 info
->SetBoolean(kIsUsingDefaultNameKey
, using_default_name
);
176 // For profiles that don't have the "using default avatar" state set yet,
177 // assume it's the same as the "using default name" state.
178 if (!info
->HasKey(kIsUsingDefaultAvatarKey
)) {
179 info
->SetBoolean(kIsUsingDefaultAvatarKey
, using_default_name
);
183 // If needed, start downloading the high-res avatars and migrate any legacy
185 if (switches::IsNewAvatarMenu())
186 MigrateLegacyProfileNamesAndDownloadAvatars();
189 ProfileInfoCache::~ProfileInfoCache() {
190 STLDeleteContainerPairSecondPointers(
191 cached_avatar_images_
.begin(), cached_avatar_images_
.end());
192 STLDeleteContainerPairSecondPointers(
193 avatar_images_downloads_in_progress_
.begin(),
194 avatar_images_downloads_in_progress_
.end());
197 void ProfileInfoCache::AddProfileToCache(
198 const base::FilePath
& profile_path
,
199 const base::string16
& name
,
200 const base::string16
& username
,
202 const std::string
& supervised_user_id
) {
203 std::string key
= CacheKeyFromProfilePath(profile_path
);
204 DictionaryPrefUpdate
update(prefs_
, prefs::kProfileInfoCache
);
205 base::DictionaryValue
* cache
= update
.Get();
207 scoped_ptr
<base::DictionaryValue
> info(new base::DictionaryValue
);
208 info
->SetString(kNameKey
, name
);
209 info
->SetString(kUserNameKey
, username
);
210 info
->SetString(kAvatarIconKey
,
211 profiles::GetDefaultAvatarIconUrl(icon_index
));
212 // Default value for whether background apps are running is false.
213 info
->SetBoolean(kBackgroundAppsKey
, false);
214 info
->SetString(kSupervisedUserId
, supervised_user_id
);
215 info
->SetBoolean(kIsOmittedFromProfileListKey
, !supervised_user_id
.empty());
216 info
->SetBoolean(kProfileIsEphemeral
, false);
217 info
->SetBoolean(kIsUsingDefaultNameKey
, IsDefaultProfileName(name
));
218 // Assume newly created profiles use a default avatar.
219 info
->SetBoolean(kIsUsingDefaultAvatarKey
, true);
220 cache
->SetWithoutPathExpansion(key
, info
.release());
222 sorted_keys_
.insert(FindPositionForProfile(key
, name
), key
);
224 if (switches::IsNewAvatarMenu())
225 DownloadHighResAvatarIfNeeded(icon_index
, profile_path
);
227 FOR_EACH_OBSERVER(ProfileInfoCacheObserver
,
229 OnProfileAdded(profile_path
));
231 content::NotificationService::current()->Notify(
232 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED
,
233 content::NotificationService::AllSources(),
234 content::NotificationService::NoDetails());
237 void ProfileInfoCache::AddObserver(ProfileInfoCacheObserver
* obs
) {
238 observer_list_
.AddObserver(obs
);
241 void ProfileInfoCache::RemoveObserver(ProfileInfoCacheObserver
* obs
) {
242 observer_list_
.RemoveObserver(obs
);
245 void ProfileInfoCache::DeleteProfileFromCache(
246 const base::FilePath
& profile_path
) {
247 size_t profile_index
= GetIndexOfProfileWithPath(profile_path
);
248 if (profile_index
== std::string::npos
) {
252 base::string16 name
= GetNameOfProfileAtIndex(profile_index
);
254 FOR_EACH_OBSERVER(ProfileInfoCacheObserver
,
256 OnProfileWillBeRemoved(profile_path
));
258 DictionaryPrefUpdate
update(prefs_
, prefs::kProfileInfoCache
);
259 base::DictionaryValue
* cache
= update
.Get();
260 std::string key
= CacheKeyFromProfilePath(profile_path
);
261 cache
->Remove(key
, NULL
);
262 sorted_keys_
.erase(std::find(sorted_keys_
.begin(), sorted_keys_
.end(), key
));
264 FOR_EACH_OBSERVER(ProfileInfoCacheObserver
,
266 OnProfileWasRemoved(profile_path
, name
));
268 content::NotificationService::current()->Notify(
269 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED
,
270 content::NotificationService::AllSources(),
271 content::NotificationService::NoDetails());
274 size_t ProfileInfoCache::GetNumberOfProfiles() const {
275 return sorted_keys_
.size();
278 size_t ProfileInfoCache::GetIndexOfProfileWithPath(
279 const base::FilePath
& profile_path
) const {
280 if (profile_path
.DirName() != user_data_dir_
)
281 return std::string::npos
;
282 std::string search_key
= CacheKeyFromProfilePath(profile_path
);
283 for (size_t i
= 0; i
< sorted_keys_
.size(); ++i
) {
284 if (sorted_keys_
[i
] == search_key
)
287 return std::string::npos
;
290 base::string16
ProfileInfoCache::GetNameOfProfileAtIndex(size_t index
) const {
292 // Unless the user has customized the profile name, we should use the
293 // profile's Gaia given name, if it's available.
294 if (ProfileIsUsingDefaultNameAtIndex(index
)) {
295 base::string16 given_name
= GetGAIAGivenNameOfProfileAtIndex(index
);
296 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 // Use the high resolution version of the avatar if it exists.
340 if (switches::IsNewAvatarMenu()) {
341 const gfx::Image
* image
= GetHighResAvatarOfProfileAtIndex(index
);
346 int resource_id
= profiles::GetDefaultAvatarIconResourceIDAtIndex(
347 GetAvatarIconIndexOfProfileAtIndex(index
));
348 return ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id
);
351 std::string
ProfileInfoCache::GetLocalAuthCredentialsOfProfileAtIndex(
352 size_t index
) const {
353 std::string credentials
;
354 GetInfoForProfileAtIndex(index
)->GetString(kAuthCredentialsKey
, &credentials
);
358 bool ProfileInfoCache::GetBackgroundStatusOfProfileAtIndex(
359 size_t index
) const {
360 bool background_app_status
;
361 if (!GetInfoForProfileAtIndex(index
)->GetBoolean(kBackgroundAppsKey
,
362 &background_app_status
)) {
365 return background_app_status
;
368 base::string16
ProfileInfoCache::GetGAIANameOfProfileAtIndex(
369 size_t index
) const {
371 GetInfoForProfileAtIndex(index
)->GetString(kGAIANameKey
, &name
);
375 base::string16
ProfileInfoCache::GetGAIAGivenNameOfProfileAtIndex(
376 size_t index
) const {
378 GetInfoForProfileAtIndex(index
)->GetString(kGAIAGivenNameKey
, &name
);
382 const gfx::Image
* ProfileInfoCache::GetGAIAPictureOfProfileAtIndex(
383 size_t index
) const {
384 base::FilePath path
= GetPathOfProfileAtIndex(index
);
385 std::string key
= CacheKeyFromProfilePath(path
);
387 std::string file_name
;
388 GetInfoForProfileAtIndex(index
)->GetString(
389 kGAIAPictureFileNameKey
, &file_name
);
391 // If the picture is not on disk then return NULL.
392 if (file_name
.empty())
395 base::FilePath image_path
= path
.AppendASCII(file_name
);
396 return LoadAvatarPictureFromPath(path
, key
, image_path
);
399 bool ProfileInfoCache::IsUsingGAIAPictureOfProfileAtIndex(size_t index
) const {
401 GetInfoForProfileAtIndex(index
)->GetBoolean(kUseGAIAPictureKey
, &value
);
403 // Prefer the GAIA avatar over a non-customized avatar.
404 value
= ProfileIsUsingDefaultAvatarAtIndex(index
) &&
405 GetGAIAPictureOfProfileAtIndex(index
);
410 bool ProfileInfoCache::ProfileIsSupervisedAtIndex(size_t index
) const {
411 return !GetSupervisedUserIdOfProfileAtIndex(index
).empty();
414 bool ProfileInfoCache::ProfileIsChildAtIndex(size_t index
) const {
415 #if defined(ENABLE_SUPERVISED_USERS)
416 return GetSupervisedUserIdOfProfileAtIndex(index
) ==
417 supervised_users::kChildAccountSUID
;
423 bool ProfileInfoCache::ProfileIsLegacySupervisedAtIndex(size_t index
) const {
424 return ProfileIsSupervisedAtIndex(index
) && !ProfileIsChildAtIndex(index
);
427 bool ProfileInfoCache::IsOmittedProfileAtIndex(size_t index
) const {
429 GetInfoForProfileAtIndex(index
)->GetBoolean(kIsOmittedFromProfileListKey
,
434 bool ProfileInfoCache::ProfileIsSigninRequiredAtIndex(size_t index
) const {
436 GetInfoForProfileAtIndex(index
)->GetBoolean(kSigninRequiredKey
, &value
);
440 std::string
ProfileInfoCache::GetSupervisedUserIdOfProfileAtIndex(
441 size_t index
) const {
442 std::string supervised_user_id
;
443 GetInfoForProfileAtIndex(index
)->GetString(kSupervisedUserId
,
444 &supervised_user_id
);
445 return supervised_user_id
;
448 bool ProfileInfoCache::ProfileIsEphemeralAtIndex(size_t index
) const {
450 GetInfoForProfileAtIndex(index
)->GetBoolean(kProfileIsEphemeral
, &value
);
454 bool ProfileInfoCache::ProfileIsUsingDefaultNameAtIndex(size_t index
) const {
456 GetInfoForProfileAtIndex(index
)->GetBoolean(kIsUsingDefaultNameKey
, &value
);
460 bool ProfileInfoCache::ProfileIsUsingDefaultAvatarAtIndex(size_t index
) const {
462 GetInfoForProfileAtIndex(index
)->GetBoolean(kIsUsingDefaultAvatarKey
, &value
);
466 bool ProfileInfoCache::ProfileIsAuthErrorAtIndex(size_t index
) const {
468 GetInfoForProfileAtIndex(index
)->GetBoolean(kIsAuthErrorKey
, &value
);
472 size_t ProfileInfoCache::GetAvatarIconIndexOfProfileAtIndex(size_t index
)
474 std::string icon_url
;
475 GetInfoForProfileAtIndex(index
)->GetString(kAvatarIconKey
, &icon_url
);
476 size_t icon_index
= 0;
477 if (!profiles::IsDefaultAvatarIconUrl(icon_url
, &icon_index
))
478 DLOG(WARNING
) << "Unknown avatar icon: " << icon_url
;
483 void ProfileInfoCache::SetProfileActiveTimeAtIndex(size_t index
) {
484 scoped_ptr
<base::DictionaryValue
> info(
485 GetInfoForProfileAtIndex(index
)->DeepCopy());
486 info
->SetDouble(kActiveTimeKey
, base::Time::Now().ToDoubleT());
487 // This takes ownership of |info|.
488 SetInfoQuietlyForProfileAtIndex(index
, info
.release());
491 void ProfileInfoCache::SetNameOfProfileAtIndex(size_t index
,
492 const base::string16
& name
) {
493 scoped_ptr
<base::DictionaryValue
> info(
494 GetInfoForProfileAtIndex(index
)->DeepCopy());
495 base::string16 current_name
;
496 info
->GetString(kNameKey
, ¤t_name
);
497 if (name
== current_name
)
500 base::string16 old_display_name
= GetNameOfProfileAtIndex(index
);
501 info
->SetString(kNameKey
, name
);
503 // This takes ownership of |info|.
504 SetInfoForProfileAtIndex(index
, info
.release());
506 base::string16 new_display_name
= GetNameOfProfileAtIndex(index
);
507 base::FilePath profile_path
= GetPathOfProfileAtIndex(index
);
508 UpdateSortForProfileIndex(index
);
510 if (old_display_name
!= new_display_name
) {
511 FOR_EACH_OBSERVER(ProfileInfoCacheObserver
,
513 OnProfileNameChanged(profile_path
, old_display_name
));
517 void ProfileInfoCache::SetShortcutNameOfProfileAtIndex(
519 const base::string16
& shortcut_name
) {
520 if (shortcut_name
== GetShortcutNameOfProfileAtIndex(index
))
522 scoped_ptr
<base::DictionaryValue
> info(
523 GetInfoForProfileAtIndex(index
)->DeepCopy());
524 info
->SetString(kShortcutNameKey
, shortcut_name
);
525 // This takes ownership of |info|.
526 SetInfoForProfileAtIndex(index
, info
.release());
529 void ProfileInfoCache::SetUserNameOfProfileAtIndex(
531 const base::string16
& user_name
) {
532 if (user_name
== GetUserNameOfProfileAtIndex(index
))
535 scoped_ptr
<base::DictionaryValue
> info(
536 GetInfoForProfileAtIndex(index
)->DeepCopy());
537 info
->SetString(kUserNameKey
, user_name
);
538 // This takes ownership of |info|.
539 SetInfoForProfileAtIndex(index
, info
.release());
542 void ProfileInfoCache::SetAvatarIconOfProfileAtIndex(size_t index
,
544 scoped_ptr
<base::DictionaryValue
> info(
545 GetInfoForProfileAtIndex(index
)->DeepCopy());
546 info
->SetString(kAvatarIconKey
,
547 profiles::GetDefaultAvatarIconUrl(icon_index
));
548 // This takes ownership of |info|.
549 SetInfoForProfileAtIndex(index
, info
.release());
551 base::FilePath profile_path
= GetPathOfProfileAtIndex(index
);
553 if (switches::IsNewAvatarMenu())
554 DownloadHighResAvatarIfNeeded(icon_index
, profile_path
);
556 FOR_EACH_OBSERVER(ProfileInfoCacheObserver
,
558 OnProfileAvatarChanged(profile_path
));
561 void ProfileInfoCache::SetIsOmittedProfileAtIndex(size_t index
,
563 if (IsOmittedProfileAtIndex(index
) == is_omitted
)
565 scoped_ptr
<base::DictionaryValue
> info(
566 GetInfoForProfileAtIndex(index
)->DeepCopy());
567 info
->SetBoolean(kIsOmittedFromProfileListKey
, is_omitted
);
568 // This takes ownership of |info|.
569 SetInfoForProfileAtIndex(index
, info
.release());
572 void ProfileInfoCache::SetSupervisedUserIdOfProfileAtIndex(
574 const std::string
& id
) {
575 if (GetSupervisedUserIdOfProfileAtIndex(index
) == id
)
577 scoped_ptr
<base::DictionaryValue
> info(
578 GetInfoForProfileAtIndex(index
)->DeepCopy());
579 info
->SetString(kSupervisedUserId
, id
);
580 // This takes ownership of |info|.
581 SetInfoForProfileAtIndex(index
, info
.release());
583 base::FilePath profile_path
= GetPathOfProfileAtIndex(index
);
584 FOR_EACH_OBSERVER(ProfileInfoCacheObserver
,
586 OnProfileSupervisedUserIdChanged(profile_path
));
589 void ProfileInfoCache::SetLocalAuthCredentialsOfProfileAtIndex(
591 const std::string
& credentials
) {
592 scoped_ptr
<base::DictionaryValue
> info(
593 GetInfoForProfileAtIndex(index
)->DeepCopy());
594 info
->SetString(kAuthCredentialsKey
, credentials
);
595 // This takes ownership of |info|.
596 SetInfoForProfileAtIndex(index
, info
.release());
599 void ProfileInfoCache::SetBackgroundStatusOfProfileAtIndex(
601 bool running_background_apps
) {
602 if (GetBackgroundStatusOfProfileAtIndex(index
) == running_background_apps
)
604 scoped_ptr
<base::DictionaryValue
> info(
605 GetInfoForProfileAtIndex(index
)->DeepCopy());
606 info
->SetBoolean(kBackgroundAppsKey
, running_background_apps
);
607 // This takes ownership of |info|.
608 SetInfoForProfileAtIndex(index
, info
.release());
611 void ProfileInfoCache::SetGAIANameOfProfileAtIndex(size_t index
,
612 const base::string16
& name
) {
613 if (name
== GetGAIANameOfProfileAtIndex(index
))
616 base::string16 old_display_name
= GetNameOfProfileAtIndex(index
);
617 scoped_ptr
<base::DictionaryValue
> info(
618 GetInfoForProfileAtIndex(index
)->DeepCopy());
619 info
->SetString(kGAIANameKey
, name
);
620 // This takes ownership of |info|.
621 SetInfoForProfileAtIndex(index
, info
.release());
622 base::string16 new_display_name
= GetNameOfProfileAtIndex(index
);
623 base::FilePath profile_path
= GetPathOfProfileAtIndex(index
);
624 UpdateSortForProfileIndex(index
);
626 if (old_display_name
!= new_display_name
) {
627 FOR_EACH_OBSERVER(ProfileInfoCacheObserver
,
629 OnProfileNameChanged(profile_path
, old_display_name
));
633 void ProfileInfoCache::SetGAIAGivenNameOfProfileAtIndex(
635 const base::string16
& name
) {
636 if (name
== GetGAIAGivenNameOfProfileAtIndex(index
))
639 base::string16 old_display_name
= GetNameOfProfileAtIndex(index
);
640 scoped_ptr
<base::DictionaryValue
> info(
641 GetInfoForProfileAtIndex(index
)->DeepCopy());
642 info
->SetString(kGAIAGivenNameKey
, name
);
643 // This takes ownership of |info|.
644 SetInfoForProfileAtIndex(index
, info
.release());
645 base::string16 new_display_name
= GetNameOfProfileAtIndex(index
);
646 base::FilePath profile_path
= GetPathOfProfileAtIndex(index
);
647 UpdateSortForProfileIndex(index
);
649 if (old_display_name
!= new_display_name
) {
650 FOR_EACH_OBSERVER(ProfileInfoCacheObserver
,
652 OnProfileNameChanged(profile_path
, old_display_name
));
656 void ProfileInfoCache::SetGAIAPictureOfProfileAtIndex(size_t index
,
657 const gfx::Image
* image
) {
658 base::FilePath path
= GetPathOfProfileAtIndex(index
);
659 std::string key
= CacheKeyFromProfilePath(path
);
661 // Delete the old bitmap from cache.
662 std::map
<std::string
, gfx::Image
*>::iterator it
=
663 cached_avatar_images_
.find(key
);
664 if (it
!= cached_avatar_images_
.end()) {
666 cached_avatar_images_
.erase(it
);
669 std::string old_file_name
;
670 GetInfoForProfileAtIndex(index
)->GetString(
671 kGAIAPictureFileNameKey
, &old_file_name
);
672 std::string new_file_name
;
675 // Delete the old bitmap from disk.
676 if (!old_file_name
.empty()) {
677 base::FilePath image_path
= path
.AppendASCII(old_file_name
);
678 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
679 base::Bind(&DeleteBitmap
, image_path
));
682 // Save the new bitmap to disk.
684 old_file_name
.empty() ? profiles::kGAIAPictureFileName
: old_file_name
;
685 base::FilePath image_path
= path
.AppendASCII(new_file_name
);
686 SaveAvatarImageAtPath(
687 image
, key
, image_path
, GetPathOfProfileAtIndex(index
));
690 scoped_ptr
<base::DictionaryValue
> info(
691 GetInfoForProfileAtIndex(index
)->DeepCopy());
692 info
->SetString(kGAIAPictureFileNameKey
, new_file_name
);
693 // This takes ownership of |info|.
694 SetInfoForProfileAtIndex(index
, info
.release());
696 FOR_EACH_OBSERVER(ProfileInfoCacheObserver
,
698 OnProfileAvatarChanged(path
));
701 void ProfileInfoCache::SetIsUsingGAIAPictureOfProfileAtIndex(size_t index
,
703 scoped_ptr
<base::DictionaryValue
> info(
704 GetInfoForProfileAtIndex(index
)->DeepCopy());
705 info
->SetBoolean(kUseGAIAPictureKey
, value
);
706 // This takes ownership of |info|.
707 SetInfoForProfileAtIndex(index
, info
.release());
709 base::FilePath profile_path
= GetPathOfProfileAtIndex(index
);
710 FOR_EACH_OBSERVER(ProfileInfoCacheObserver
,
712 OnProfileAvatarChanged(profile_path
));
715 void ProfileInfoCache::SetProfileSigninRequiredAtIndex(size_t index
,
717 if (value
== ProfileIsSigninRequiredAtIndex(index
))
720 scoped_ptr
<base::DictionaryValue
> info(
721 GetInfoForProfileAtIndex(index
)->DeepCopy());
722 info
->SetBoolean(kSigninRequiredKey
, value
);
723 // This takes ownership of |info|.
724 SetInfoForProfileAtIndex(index
, info
.release());
726 base::FilePath profile_path
= GetPathOfProfileAtIndex(index
);
727 FOR_EACH_OBSERVER(ProfileInfoCacheObserver
,
729 OnProfileSigninRequiredChanged(profile_path
));
732 void ProfileInfoCache::SetProfileIsEphemeralAtIndex(size_t index
, bool value
) {
733 if (value
== ProfileIsEphemeralAtIndex(index
))
736 scoped_ptr
<base::DictionaryValue
> info(
737 GetInfoForProfileAtIndex(index
)->DeepCopy());
738 info
->SetBoolean(kProfileIsEphemeral
, value
);
739 // This takes ownership of |info|.
740 SetInfoForProfileAtIndex(index
, info
.release());
743 void ProfileInfoCache::SetProfileIsUsingDefaultNameAtIndex(
744 size_t index
, bool value
) {
745 if (value
== ProfileIsUsingDefaultNameAtIndex(index
))
748 scoped_ptr
<base::DictionaryValue
> info(
749 GetInfoForProfileAtIndex(index
)->DeepCopy());
750 info
->SetBoolean(kIsUsingDefaultNameKey
, value
);
751 // This takes ownership of |info|.
752 SetInfoForProfileAtIndex(index
, info
.release());
755 void ProfileInfoCache::SetProfileIsUsingDefaultAvatarAtIndex(
756 size_t index
, bool value
) {
757 if (value
== ProfileIsUsingDefaultAvatarAtIndex(index
))
760 scoped_ptr
<base::DictionaryValue
> info(
761 GetInfoForProfileAtIndex(index
)->DeepCopy());
762 info
->SetBoolean(kIsUsingDefaultAvatarKey
, value
);
763 // This takes ownership of |info|.
764 SetInfoForProfileAtIndex(index
, info
.release());
767 void ProfileInfoCache::SetProfileIsAuthErrorAtIndex(size_t index
, bool value
) {
768 if (value
== ProfileIsAuthErrorAtIndex(index
))
771 scoped_ptr
<base::DictionaryValue
> info(
772 GetInfoForProfileAtIndex(index
)->DeepCopy());
773 info
->SetBoolean(kIsAuthErrorKey
, value
);
774 // This takes ownership of |info|.
775 SetInfoForProfileAtIndex(index
, info
.release());
778 bool ProfileInfoCache::IsDefaultProfileName(const base::string16
& name
) const {
779 // Check if it's a "First user" old-style name.
780 if (name
== l10n_util::GetStringUTF16(IDS_DEFAULT_PROFILE_NAME
) ||
781 name
== l10n_util::GetStringUTF16(IDS_LEGACY_DEFAULT_PROFILE_NAME
))
784 // Check if it's one of the old-style profile names.
785 for (size_t i
= 0; i
< arraysize(kDefaultNames
); ++i
) {
786 if (name
== l10n_util::GetStringUTF16(kDefaultNames
[i
]))
790 // Check whether it's one of the "Person %d" style names.
791 std::string default_name_format
= l10n_util::GetStringFUTF8(
792 IDS_NEW_NUMBERED_PROFILE_NAME
, base::ASCIIToUTF16("%d"));
794 int generic_profile_number
; // Unused. Just a placeholder for sscanf.
795 int assignments
= sscanf(base::UTF16ToUTF8(name
).c_str(),
796 default_name_format
.c_str(),
797 &generic_profile_number
);
798 // Unless it matched the format, this is a custom name.
799 return assignments
== 1;
802 base::string16
ProfileInfoCache::ChooseNameForNewProfile(
803 size_t icon_index
) const {
805 for (int name_index
= 1; ; ++name_index
) {
806 if (switches::IsNewAvatarMenu()) {
807 name
= l10n_util::GetStringFUTF16Int(IDS_NEW_NUMBERED_PROFILE_NAME
,
809 } else if (icon_index
< profiles::GetGenericAvatarIconCount()) {
810 name
= l10n_util::GetStringFUTF16Int(IDS_NUMBERED_PROFILE_NAME
,
813 name
= l10n_util::GetStringUTF16(
814 kDefaultNames
[icon_index
- profiles::GetGenericAvatarIconCount()]);
816 name
.append(base::UTF8ToUTF16(base::IntToString(name_index
)));
819 // Loop through previously named profiles to ensure we're not duplicating.
820 bool name_found
= false;
821 for (size_t i
= 0; i
< GetNumberOfProfiles(); ++i
) {
822 if (GetNameOfProfileAtIndex(i
) == name
) {
832 size_t ProfileInfoCache::ChooseAvatarIconIndexForNewProfile() const {
833 size_t icon_index
= 0;
834 // Try to find a unique, non-generic icon.
835 if (ChooseAvatarIconIndexForNewProfile(false, true, &icon_index
))
837 // Try to find any unique icon.
838 if (ChooseAvatarIconIndexForNewProfile(true, true, &icon_index
))
840 // Settle for any random icon, even if it's not unique.
841 if (ChooseAvatarIconIndexForNewProfile(true, false, &icon_index
))
848 const base::FilePath
& ProfileInfoCache::GetUserDataDir() const {
849 return user_data_dir_
;
853 void ProfileInfoCache::RegisterPrefs(PrefRegistrySimple
* registry
) {
854 registry
->RegisterDictionaryPref(prefs::kProfileInfoCache
);
857 void ProfileInfoCache::DownloadHighResAvatarIfNeeded(
859 const base::FilePath
& profile_path
) {
860 // Downloading is only supported on desktop.
861 #if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS)
865 const base::FilePath
& file_path
=
866 profiles::GetPathOfHighResAvatarAtIndex(icon_index
);
867 base::Closure callback
=
868 base::Bind(&ProfileInfoCache::DownloadHighResAvatar
,
872 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
873 base::Bind(&RunCallbackIfFileMissing
, file_path
, callback
));
876 void ProfileInfoCache::SaveAvatarImageAtPath(
877 const gfx::Image
* image
,
878 const std::string
& key
,
879 const base::FilePath
& image_path
,
880 const base::FilePath
& profile_path
) {
881 cached_avatar_images_
[key
] = new gfx::Image(*image
);
883 scoped_ptr
<ImageData
> data(new ImageData
);
884 scoped_refptr
<base::RefCountedMemory
> png_data
= image
->As1xPNGBytes();
885 data
->assign(png_data
->front(), png_data
->front() + png_data
->size());
887 // Remove the file from the list of downloads in progress. Note that this list
888 // only contains the high resolution avatars, and not the Gaia profile images.
889 auto downloader_iter
= avatar_images_downloads_in_progress_
.find(key
);
890 if (downloader_iter
!= avatar_images_downloads_in_progress_
.end()) {
891 // We mustn't delete the avatar downloader right here, since we're being
893 BrowserThread::DeleteSoon(BrowserThread::UI
, FROM_HERE
,
894 downloader_iter
->second
);
895 avatar_images_downloads_in_progress_
.erase(downloader_iter
);
899 LOG(ERROR
) << "Failed to PNG encode the image.";
901 base::Closure callback
= base::Bind(&ProfileInfoCache::OnAvatarPictureSaved
,
902 AsWeakPtr(), key
, profile_path
);
903 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
904 base::Bind(&SaveBitmap
, base::Passed(&data
), image_path
, callback
));
908 const base::DictionaryValue
* ProfileInfoCache::GetInfoForProfileAtIndex(
909 size_t index
) const {
910 DCHECK_LT(index
, GetNumberOfProfiles());
911 const base::DictionaryValue
* cache
=
912 prefs_
->GetDictionary(prefs::kProfileInfoCache
);
913 const base::DictionaryValue
* info
= NULL
;
914 cache
->GetDictionaryWithoutPathExpansion(sorted_keys_
[index
], &info
);
918 void ProfileInfoCache::SetInfoQuietlyForProfileAtIndex(
919 size_t index
, base::DictionaryValue
* info
) {
920 DictionaryPrefUpdate
update(prefs_
, prefs::kProfileInfoCache
);
921 base::DictionaryValue
* cache
= update
.Get();
922 cache
->SetWithoutPathExpansion(sorted_keys_
[index
], info
);
925 // TODO(noms): Switch to newer notification system.
926 void ProfileInfoCache::SetInfoForProfileAtIndex(size_t index
,
927 base::DictionaryValue
* info
) {
928 SetInfoQuietlyForProfileAtIndex(index
, info
);
930 content::NotificationService::current()->Notify(
931 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED
,
932 content::NotificationService::AllSources(),
933 content::NotificationService::NoDetails());
936 std::string
ProfileInfoCache::CacheKeyFromProfilePath(
937 const base::FilePath
& profile_path
) const {
938 DCHECK(user_data_dir_
== profile_path
.DirName());
939 base::FilePath base_name
= profile_path
.BaseName();
940 return base_name
.MaybeAsASCII();
943 std::vector
<std::string
>::iterator
ProfileInfoCache::FindPositionForProfile(
944 const std::string
& search_key
,
945 const base::string16
& search_name
) {
946 base::string16 search_name_l
= base::i18n::ToLower(search_name
);
947 for (size_t i
= 0; i
< GetNumberOfProfiles(); ++i
) {
948 base::string16 name_l
= base::i18n::ToLower(GetNameOfProfileAtIndex(i
));
949 int name_compare
= search_name_l
.compare(name_l
);
950 if (name_compare
< 0)
951 return sorted_keys_
.begin() + i
;
952 if (name_compare
== 0) {
953 int key_compare
= search_key
.compare(sorted_keys_
[i
]);
955 return sorted_keys_
.begin() + i
;
958 return sorted_keys_
.end();
961 bool ProfileInfoCache::IconIndexIsUnique(size_t icon_index
) const {
962 for (size_t i
= 0; i
< GetNumberOfProfiles(); ++i
) {
963 if (GetAvatarIconIndexOfProfileAtIndex(i
) == icon_index
)
969 bool ProfileInfoCache::ChooseAvatarIconIndexForNewProfile(
970 bool allow_generic_icon
,
972 size_t* out_icon_index
) const {
973 // Always allow all icons for new profiles if using the
974 // --new-avatar-menu flag.
975 if (switches::IsNewAvatarMenu())
976 allow_generic_icon
= true;
977 size_t start
= allow_generic_icon
? 0 : profiles::GetGenericAvatarIconCount();
978 size_t end
= profiles::GetDefaultAvatarIconCount();
979 size_t count
= end
- start
;
981 int rand
= base::RandInt(0, count
);
982 for (size_t i
= 0; i
< count
; ++i
) {
983 size_t icon_index
= start
+ (rand
+ i
) % count
;
984 if (!must_be_unique
|| IconIndexIsUnique(icon_index
)) {
985 *out_icon_index
= icon_index
;
993 void ProfileInfoCache::UpdateSortForProfileIndex(size_t index
) {
994 base::string16 name
= GetNameOfProfileAtIndex(index
);
996 // Remove and reinsert key in |sorted_keys_| to alphasort.
997 std::string key
= CacheKeyFromProfilePath(GetPathOfProfileAtIndex(index
));
998 std::vector
<std::string
>::iterator key_it
=
999 std::find(sorted_keys_
.begin(), sorted_keys_
.end(), key
);
1000 DCHECK(key_it
!= sorted_keys_
.end());
1001 sorted_keys_
.erase(key_it
);
1002 sorted_keys_
.insert(FindPositionForProfile(key
, name
), key
);
1004 content::NotificationService::current()->Notify(
1005 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED
,
1006 content::NotificationService::AllSources(),
1007 content::NotificationService::NoDetails());
1010 const gfx::Image
* ProfileInfoCache::GetHighResAvatarOfProfileAtIndex(
1011 size_t index
) const {
1012 int avatar_index
= GetAvatarIconIndexOfProfileAtIndex(index
);
1013 std::string key
= profiles::GetDefaultAvatarIconFileNameAtIndex(avatar_index
);
1015 // If this is the placeholder avatar, it is already included in the
1016 // resources, so it doesn't need to be downloaded.
1017 if (!strcmp(key
.c_str(), profiles::GetNoHighResAvatarFileName())) {
1018 return &ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1019 profiles::GetPlaceholderAvatarIconResourceID());
1022 base::FilePath image_path
=
1023 profiles::GetPathOfHighResAvatarAtIndex(avatar_index
);
1024 return LoadAvatarPictureFromPath(GetPathOfProfileAtIndex(index
),
1028 void ProfileInfoCache::DownloadHighResAvatar(
1030 const base::FilePath
& profile_path
) {
1031 // Downloading is only supported on desktop.
1032 #if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS)
1035 const std::string file_name
=
1036 profiles::GetDefaultAvatarIconFileNameAtIndex(icon_index
);
1037 // If the file is already being downloaded, don't start another download.
1038 if (avatar_images_downloads_in_progress_
.count(file_name
))
1041 // Start the download for this file. The cache takes ownership of the
1042 // |avatar_downloader|, which will be deleted when the download completes, or
1043 // if that never happens, when the ProfileInfoCache is destroyed.
1044 ProfileAvatarDownloader
* avatar_downloader
= new ProfileAvatarDownloader(
1048 avatar_images_downloads_in_progress_
[file_name
] = avatar_downloader
;
1049 avatar_downloader
->Start();
1052 const gfx::Image
* ProfileInfoCache::LoadAvatarPictureFromPath(
1053 const base::FilePath
& profile_path
,
1054 const std::string
& key
,
1055 const base::FilePath
& image_path
) const {
1056 // If the picture is already loaded then use it.
1057 if (cached_avatar_images_
.count(key
)) {
1058 if (cached_avatar_images_
[key
]->IsEmpty())
1060 return cached_avatar_images_
[key
];
1063 // If the picture is already being loaded then don't try loading it again.
1064 if (cached_avatar_images_loading_
[key
])
1066 cached_avatar_images_loading_
[key
] = true;
1068 gfx::Image
** image
= new gfx::Image
*;
1069 BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE
,
1070 base::Bind(&ReadBitmap
, image_path
, image
),
1071 base::Bind(&ProfileInfoCache::OnAvatarPictureLoaded
,
1072 const_cast<ProfileInfoCache
*>(this)->AsWeakPtr(),
1073 profile_path
, key
, image
));
1077 void ProfileInfoCache::OnAvatarPictureLoaded(const base::FilePath
& profile_path
,
1078 const std::string
& key
,
1079 gfx::Image
** image
) const {
1080 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
1082 cached_avatar_images_loading_
[key
] = false;
1083 delete cached_avatar_images_
[key
];
1086 cached_avatar_images_
[key
] = *image
;
1088 // Place an empty image in the cache to avoid reloading it again.
1089 cached_avatar_images_
[key
] = new gfx::Image();
1093 content::NotificationService::current()->Notify(
1094 chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED
,
1095 content::NotificationService::AllSources(),
1096 content::NotificationService::NoDetails());
1098 FOR_EACH_OBSERVER(ProfileInfoCacheObserver
,
1100 OnProfileHighResAvatarLoaded(profile_path
));
1103 void ProfileInfoCache::OnAvatarPictureSaved(
1104 const std::string
& file_name
,
1105 const base::FilePath
& profile_path
) {
1106 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
1108 content::NotificationService::current()->Notify(
1109 chrome::NOTIFICATION_PROFILE_CACHE_PICTURE_SAVED
,
1110 content::NotificationService::AllSources(),
1111 content::NotificationService::NoDetails());
1113 FOR_EACH_OBSERVER(ProfileInfoCacheObserver
,
1115 OnProfileHighResAvatarLoaded(profile_path
));
1118 void ProfileInfoCache::MigrateLegacyProfileNamesAndDownloadAvatars() {
1119 DCHECK(switches::IsNewAvatarMenu());
1121 // Only do this on desktop platforms.
1122 #if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)
1123 // Migrate any legacy profile names ("First user", "Default Profile") to
1124 // new style default names ("Person 1"). The problem here is that every
1125 // time you rename a profile, the ProfileInfoCache sorts itself, so
1126 // whatever you were iterating through is no longer valid. We need to
1127 // save a list of the profile paths (which thankfully do not change) that
1128 // need to be renamed. We also can't pre-compute the new names, as they
1129 // depend on the names of all the other profiles in the info cache, so they
1130 // need to be re-computed after each rename.
1131 std::vector
<base::FilePath
> profiles_to_rename
;
1133 const base::string16 default_profile_name
= base::i18n::ToLower(
1134 l10n_util::GetStringUTF16(IDS_DEFAULT_PROFILE_NAME
));
1135 const base::string16 default_legacy_profile_name
= base::i18n::ToLower(
1136 l10n_util::GetStringUTF16(IDS_LEGACY_DEFAULT_PROFILE_NAME
));
1138 for (size_t i
= 0; i
< GetNumberOfProfiles(); i
++) {
1139 DownloadHighResAvatarIfNeeded(GetAvatarIconIndexOfProfileAtIndex(i
),
1140 GetPathOfProfileAtIndex(i
));
1142 base::string16 name
= base::i18n::ToLower(GetNameOfProfileAtIndex(i
));
1143 if (name
== default_profile_name
|| name
== default_legacy_profile_name
)
1144 profiles_to_rename
.push_back(GetPathOfProfileAtIndex(i
));
1147 // Rename the necessary profiles.
1148 std::vector
<base::FilePath
>::const_iterator it
;
1149 for (it
= profiles_to_rename
.begin(); it
!= profiles_to_rename
.end(); ++it
) {
1150 size_t profile_index
= GetIndexOfProfileWithPath(*it
);
1151 SetProfileIsUsingDefaultNameAtIndex(profile_index
, true);
1152 // This will assign a new "Person %d" type name and re-sort the cache.
1153 SetNameOfProfileAtIndex(profile_index
, ChooseNameForNewProfile(
1154 GetAvatarIconIndexOfProfileAtIndex(profile_index
)));