ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / profiles / profile_info_cache.cc
blob3e7c05c3c2a4f4bd141d3e47e2ed662488ec0af5
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/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/profiler/scoped_tracker.h"
16 #include "base/rand_util.h"
17 #include "base/stl_util.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_piece.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/values.h"
22 #include "chrome/browser/browser_process.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 "ui/base/l10n/l10n_util.h"
31 #include "ui/base/resource/resource_bundle.h"
32 #include "ui/gfx/image/image.h"
33 #include "ui/gfx/image/image_util.h"
35 #if defined(ENABLE_SUPERVISED_USERS)
36 #include "chrome/browser/supervised_user/supervised_user_constants.h"
37 #endif
39 using content::BrowserThread;
41 namespace {
43 const char kNameKey[] = "name";
44 const char kShortcutNameKey[] = "shortcut_name";
45 const char kGAIANameKey[] = "gaia_name";
46 const char kGAIAGivenNameKey[] = "gaia_given_name";
47 const char kUserNameKey[] = "user_name";
48 const char kIsUsingDefaultNameKey[] = "is_using_default_name";
49 const char kIsUsingDefaultAvatarKey[] = "is_using_default_avatar";
50 const char kAvatarIconKey[] = "avatar_icon";
51 const char kAuthCredentialsKey[] = "local_auth_credentials";
52 const char kUseGAIAPictureKey[] = "use_gaia_picture";
53 const char kBackgroundAppsKey[] = "background_apps";
54 const char kGAIAPictureFileNameKey[] = "gaia_picture_file_name";
55 const char kIsOmittedFromProfileListKey[] = "is_omitted_from_profile_list";
56 const char kSigninRequiredKey[] = "signin_required";
57 const char kSupervisedUserId[] = "managed_user_id";
58 const char kProfileIsEphemeral[] = "is_ephemeral";
59 const char kActiveTimeKey[] = "active_time";
60 const char kIsAuthErrorKey[] = "is_auth_error";
62 // First eight are generic icons, which use IDS_NUMBERED_PROFILE_NAME.
63 const int kDefaultNames[] = {
64 IDS_DEFAULT_AVATAR_NAME_8,
65 IDS_DEFAULT_AVATAR_NAME_9,
66 IDS_DEFAULT_AVATAR_NAME_10,
67 IDS_DEFAULT_AVATAR_NAME_11,
68 IDS_DEFAULT_AVATAR_NAME_12,
69 IDS_DEFAULT_AVATAR_NAME_13,
70 IDS_DEFAULT_AVATAR_NAME_14,
71 IDS_DEFAULT_AVATAR_NAME_15,
72 IDS_DEFAULT_AVATAR_NAME_16,
73 IDS_DEFAULT_AVATAR_NAME_17,
74 IDS_DEFAULT_AVATAR_NAME_18,
75 IDS_DEFAULT_AVATAR_NAME_19,
76 IDS_DEFAULT_AVATAR_NAME_20,
77 IDS_DEFAULT_AVATAR_NAME_21,
78 IDS_DEFAULT_AVATAR_NAME_22,
79 IDS_DEFAULT_AVATAR_NAME_23,
80 IDS_DEFAULT_AVATAR_NAME_24,
81 IDS_DEFAULT_AVATAR_NAME_25,
82 IDS_DEFAULT_AVATAR_NAME_26
85 typedef std::vector<unsigned char> ImageData;
87 // Writes |data| to disk and takes ownership of the pointer. On successful
88 // completion, it runs |callback|.
89 void SaveBitmap(scoped_ptr<ImageData> data,
90 const base::FilePath& image_path,
91 const base::Closure& callback) {
92 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
94 // Make sure the destination directory exists.
95 base::FilePath dir = image_path.DirName();
96 if (!base::DirectoryExists(dir) && !base::CreateDirectory(dir)) {
97 LOG(ERROR) << "Failed to create parent directory.";
98 return;
101 if (base::WriteFile(image_path, reinterpret_cast<char*>(&(*data)[0]),
102 data->size()) == -1) {
103 LOG(ERROR) << "Failed to save image to file.";
104 return;
107 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback);
110 // Reads a PNG from disk and decodes it. If the bitmap was successfully read
111 // from disk the then |out_image| will contain the bitmap image, otherwise it
112 // will be NULL.
113 void ReadBitmap(const base::FilePath& image_path,
114 gfx::Image** out_image) {
115 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
116 *out_image = NULL;
118 // If the path doesn't exist, don't even try reading it.
119 if (!base::PathExists(image_path))
120 return;
122 std::string image_data;
123 if (!base::ReadFileToString(image_path, &image_data)) {
124 LOG(ERROR) << "Failed to read PNG file from disk.";
125 return;
128 gfx::Image image = gfx::Image::CreateFrom1xPNGBytes(
129 base::RefCountedString::TakeString(&image_data));
130 if (image.IsEmpty()) {
131 LOG(ERROR) << "Failed to decode PNG file.";
132 return;
135 *out_image = new gfx::Image(image);
138 void RunCallbackIfFileMissing(const base::FilePath& file_path,
139 const base::Closure& callback) {
140 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
141 if (!base::PathExists(file_path))
142 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback);
145 void DeleteBitmap(const base::FilePath& image_path) {
146 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
147 base::DeleteFile(image_path, false);
150 } // namespace
152 ProfileInfoCache::ProfileInfoCache(PrefService* prefs,
153 const base::FilePath& user_data_dir)
154 : prefs_(prefs),
155 user_data_dir_(user_data_dir) {
156 // Populate the cache
157 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
158 base::DictionaryValue* cache = update.Get();
159 for (base::DictionaryValue::Iterator it(*cache);
160 !it.IsAtEnd(); it.Advance()) {
161 base::DictionaryValue* info = NULL;
162 cache->GetDictionaryWithoutPathExpansion(it.key(), &info);
163 base::string16 name;
164 info->GetString(kNameKey, &name);
165 sorted_keys_.insert(FindPositionForProfile(it.key(), name), it.key());
167 bool using_default_name;
168 if (!info->GetBoolean(kIsUsingDefaultNameKey, &using_default_name)) {
169 // If the preference hasn't been set, and the name is default, assume
170 // that the user hasn't done this on purpose.
171 using_default_name = IsDefaultProfileName(name);
172 info->SetBoolean(kIsUsingDefaultNameKey, using_default_name);
175 // For profiles that don't have the "using default avatar" state set yet,
176 // assume it's the same as the "using default name" state.
177 if (!info->HasKey(kIsUsingDefaultAvatarKey)) {
178 info->SetBoolean(kIsUsingDefaultAvatarKey, using_default_name);
182 // If needed, start downloading the high-res avatars and migrate any legacy
183 // profile names.
184 if (switches::IsNewAvatarMenu())
185 MigrateLegacyProfileNamesAndDownloadAvatars();
188 ProfileInfoCache::~ProfileInfoCache() {
189 STLDeleteContainerPairSecondPointers(
190 cached_avatar_images_.begin(), cached_avatar_images_.end());
191 STLDeleteContainerPairSecondPointers(
192 avatar_images_downloads_in_progress_.begin(),
193 avatar_images_downloads_in_progress_.end());
196 void ProfileInfoCache::AddProfileToCache(
197 const base::FilePath& profile_path,
198 const base::string16& name,
199 const base::string16& username,
200 size_t icon_index,
201 const std::string& supervised_user_id) {
202 std::string key = CacheKeyFromProfilePath(profile_path);
203 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
204 base::DictionaryValue* cache = update.Get();
206 scoped_ptr<base::DictionaryValue> info(new base::DictionaryValue);
207 info->SetString(kNameKey, name);
208 info->SetString(kUserNameKey, username);
209 info->SetString(kAvatarIconKey,
210 profiles::GetDefaultAvatarIconUrl(icon_index));
211 // Default value for whether background apps are running is false.
212 info->SetBoolean(kBackgroundAppsKey, false);
213 info->SetString(kSupervisedUserId, supervised_user_id);
214 info->SetBoolean(kIsOmittedFromProfileListKey, !supervised_user_id.empty());
215 info->SetBoolean(kProfileIsEphemeral, false);
216 info->SetBoolean(kIsUsingDefaultNameKey, IsDefaultProfileName(name));
217 // Assume newly created profiles use a default avatar.
218 info->SetBoolean(kIsUsingDefaultAvatarKey, true);
219 cache->SetWithoutPathExpansion(key, info.release());
221 sorted_keys_.insert(FindPositionForProfile(key, name), key);
223 if (switches::IsNewAvatarMenu())
224 DownloadHighResAvatarIfNeeded(icon_index, profile_path);
226 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
227 observer_list_,
228 OnProfileAdded(profile_path));
231 void ProfileInfoCache::AddObserver(ProfileInfoCacheObserver* obs) {
232 observer_list_.AddObserver(obs);
235 void ProfileInfoCache::RemoveObserver(ProfileInfoCacheObserver* obs) {
236 observer_list_.RemoveObserver(obs);
239 void ProfileInfoCache::DeleteProfileFromCache(
240 const base::FilePath& profile_path) {
241 size_t profile_index = GetIndexOfProfileWithPath(profile_path);
242 if (profile_index == std::string::npos) {
243 NOTREACHED();
244 return;
246 base::string16 name = GetNameOfProfileAtIndex(profile_index);
248 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
249 observer_list_,
250 OnProfileWillBeRemoved(profile_path));
252 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
253 base::DictionaryValue* cache = update.Get();
254 std::string key = CacheKeyFromProfilePath(profile_path);
255 cache->Remove(key, NULL);
256 sorted_keys_.erase(std::find(sorted_keys_.begin(), sorted_keys_.end(), key));
258 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
259 observer_list_,
260 OnProfileWasRemoved(profile_path, name));
263 size_t ProfileInfoCache::GetNumberOfProfiles() const {
264 return sorted_keys_.size();
267 size_t ProfileInfoCache::GetIndexOfProfileWithPath(
268 const base::FilePath& profile_path) const {
269 if (profile_path.DirName() != user_data_dir_)
270 return std::string::npos;
271 std::string search_key = CacheKeyFromProfilePath(profile_path);
272 for (size_t i = 0; i < sorted_keys_.size(); ++i) {
273 if (sorted_keys_[i] == search_key)
274 return i;
276 return std::string::npos;
279 base::string16 ProfileInfoCache::GetNameOfProfileAtIndex(size_t index) const {
280 base::string16 name;
281 // Unless the user has customized the profile name, we should use the
282 // profile's Gaia given name, if it's available.
283 if (ProfileIsUsingDefaultNameAtIndex(index)) {
284 base::string16 given_name = GetGAIAGivenNameOfProfileAtIndex(index);
285 name = given_name.empty() ? GetGAIANameOfProfileAtIndex(index) : given_name;
287 if (name.empty())
288 GetInfoForProfileAtIndex(index)->GetString(kNameKey, &name);
289 return name;
292 base::string16 ProfileInfoCache::GetShortcutNameOfProfileAtIndex(size_t index)
293 const {
294 base::string16 shortcut_name;
295 GetInfoForProfileAtIndex(index)->GetString(
296 kShortcutNameKey, &shortcut_name);
297 return shortcut_name;
300 base::FilePath ProfileInfoCache::GetPathOfProfileAtIndex(size_t index) const {
301 return user_data_dir_.AppendASCII(sorted_keys_[index]);
304 base::Time ProfileInfoCache::GetProfileActiveTimeAtIndex(size_t index) const {
305 double dt;
306 if (GetInfoForProfileAtIndex(index)->GetDouble(kActiveTimeKey, &dt)) {
307 return base::Time::FromDoubleT(dt);
308 } else {
309 return base::Time();
313 base::string16 ProfileInfoCache::GetUserNameOfProfileAtIndex(
314 size_t index) const {
315 base::string16 user_name;
316 GetInfoForProfileAtIndex(index)->GetString(kUserNameKey, &user_name);
317 return user_name;
320 const gfx::Image& ProfileInfoCache::GetAvatarIconOfProfileAtIndex(
321 size_t index) const {
322 if (IsUsingGAIAPictureOfProfileAtIndex(index)) {
323 const gfx::Image* image = GetGAIAPictureOfProfileAtIndex(index);
324 if (image)
325 return *image;
328 // Use the high resolution version of the avatar if it exists.
329 if (switches::IsNewAvatarMenu()) {
330 const gfx::Image* image = GetHighResAvatarOfProfileAtIndex(index);
331 if (image)
332 return *image;
335 int resource_id = profiles::GetDefaultAvatarIconResourceIDAtIndex(
336 GetAvatarIconIndexOfProfileAtIndex(index));
337 return ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
340 std::string ProfileInfoCache::GetLocalAuthCredentialsOfProfileAtIndex(
341 size_t index) const {
342 std::string credentials;
343 GetInfoForProfileAtIndex(index)->GetString(kAuthCredentialsKey, &credentials);
344 return credentials;
347 bool ProfileInfoCache::GetBackgroundStatusOfProfileAtIndex(
348 size_t index) const {
349 bool background_app_status;
350 if (!GetInfoForProfileAtIndex(index)->GetBoolean(kBackgroundAppsKey,
351 &background_app_status)) {
352 return false;
354 return background_app_status;
357 base::string16 ProfileInfoCache::GetGAIANameOfProfileAtIndex(
358 size_t index) const {
359 base::string16 name;
360 GetInfoForProfileAtIndex(index)->GetString(kGAIANameKey, &name);
361 return name;
364 base::string16 ProfileInfoCache::GetGAIAGivenNameOfProfileAtIndex(
365 size_t index) const {
366 base::string16 name;
367 GetInfoForProfileAtIndex(index)->GetString(kGAIAGivenNameKey, &name);
368 return name;
371 const gfx::Image* ProfileInfoCache::GetGAIAPictureOfProfileAtIndex(
372 size_t index) const {
373 base::FilePath path = GetPathOfProfileAtIndex(index);
374 std::string key = CacheKeyFromProfilePath(path);
376 std::string file_name;
377 GetInfoForProfileAtIndex(index)->GetString(
378 kGAIAPictureFileNameKey, &file_name);
380 // If the picture is not on disk then return NULL.
381 if (file_name.empty())
382 return NULL;
384 base::FilePath image_path = path.AppendASCII(file_name);
385 return LoadAvatarPictureFromPath(path, key, image_path);
388 bool ProfileInfoCache::IsUsingGAIAPictureOfProfileAtIndex(size_t index) const {
389 bool value = false;
390 GetInfoForProfileAtIndex(index)->GetBoolean(kUseGAIAPictureKey, &value);
391 if (!value) {
392 // Prefer the GAIA avatar over a non-customized avatar.
393 value = ProfileIsUsingDefaultAvatarAtIndex(index) &&
394 GetGAIAPictureOfProfileAtIndex(index);
396 return value;
399 bool ProfileInfoCache::ProfileIsSupervisedAtIndex(size_t index) const {
400 return !GetSupervisedUserIdOfProfileAtIndex(index).empty();
403 bool ProfileInfoCache::ProfileIsChildAtIndex(size_t index) const {
404 #if defined(ENABLE_SUPERVISED_USERS)
405 return GetSupervisedUserIdOfProfileAtIndex(index) ==
406 supervised_users::kChildAccountSUID;
407 #else
408 return false;
409 #endif
412 bool ProfileInfoCache::ProfileIsLegacySupervisedAtIndex(size_t index) const {
413 return ProfileIsSupervisedAtIndex(index) && !ProfileIsChildAtIndex(index);
416 bool ProfileInfoCache::IsOmittedProfileAtIndex(size_t index) const {
417 bool value = false;
418 GetInfoForProfileAtIndex(index)->GetBoolean(kIsOmittedFromProfileListKey,
419 &value);
420 return value;
423 bool ProfileInfoCache::ProfileIsSigninRequiredAtIndex(size_t index) const {
424 bool value = false;
425 GetInfoForProfileAtIndex(index)->GetBoolean(kSigninRequiredKey, &value);
426 return value;
429 std::string ProfileInfoCache::GetSupervisedUserIdOfProfileAtIndex(
430 size_t index) const {
431 std::string supervised_user_id;
432 GetInfoForProfileAtIndex(index)->GetString(kSupervisedUserId,
433 &supervised_user_id);
434 return supervised_user_id;
437 bool ProfileInfoCache::ProfileIsEphemeralAtIndex(size_t index) const {
438 bool value = false;
439 GetInfoForProfileAtIndex(index)->GetBoolean(kProfileIsEphemeral, &value);
440 return value;
443 bool ProfileInfoCache::ProfileIsUsingDefaultNameAtIndex(size_t index) const {
444 bool value = false;
445 GetInfoForProfileAtIndex(index)->GetBoolean(kIsUsingDefaultNameKey, &value);
446 return value;
449 bool ProfileInfoCache::ProfileIsUsingDefaultAvatarAtIndex(size_t index) const {
450 bool value = false;
451 GetInfoForProfileAtIndex(index)->GetBoolean(kIsUsingDefaultAvatarKey, &value);
452 return value;
455 bool ProfileInfoCache::ProfileIsAuthErrorAtIndex(size_t index) const {
456 bool value = false;
457 GetInfoForProfileAtIndex(index)->GetBoolean(kIsAuthErrorKey, &value);
458 return value;
461 size_t ProfileInfoCache::GetAvatarIconIndexOfProfileAtIndex(size_t index)
462 const {
463 std::string icon_url;
464 GetInfoForProfileAtIndex(index)->GetString(kAvatarIconKey, &icon_url);
465 size_t icon_index = 0;
466 if (!profiles::IsDefaultAvatarIconUrl(icon_url, &icon_index))
467 DLOG(WARNING) << "Unknown avatar icon: " << icon_url;
469 return icon_index;
472 void ProfileInfoCache::SetProfileActiveTimeAtIndex(size_t index) {
473 scoped_ptr<base::DictionaryValue> info(
474 GetInfoForProfileAtIndex(index)->DeepCopy());
475 info->SetDouble(kActiveTimeKey, base::Time::Now().ToDoubleT());
476 // This takes ownership of |info|.
477 SetInfoForProfileAtIndex(index, info.release());
480 void ProfileInfoCache::SetNameOfProfileAtIndex(size_t index,
481 const base::string16& name) {
482 scoped_ptr<base::DictionaryValue> info(
483 GetInfoForProfileAtIndex(index)->DeepCopy());
484 base::string16 current_name;
485 info->GetString(kNameKey, &current_name);
486 if (name == current_name)
487 return;
489 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
490 info->SetString(kNameKey, name);
492 // This takes ownership of |info|.
493 SetInfoForProfileAtIndex(index, info.release());
495 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
496 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
497 UpdateSortForProfileIndex(index);
499 if (old_display_name != new_display_name) {
500 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
501 observer_list_,
502 OnProfileNameChanged(profile_path, old_display_name));
506 void ProfileInfoCache::SetShortcutNameOfProfileAtIndex(
507 size_t index,
508 const base::string16& shortcut_name) {
509 if (shortcut_name == GetShortcutNameOfProfileAtIndex(index))
510 return;
511 scoped_ptr<base::DictionaryValue> info(
512 GetInfoForProfileAtIndex(index)->DeepCopy());
513 info->SetString(kShortcutNameKey, shortcut_name);
514 // This takes ownership of |info|.
515 SetInfoForProfileAtIndex(index, info.release());
518 void ProfileInfoCache::SetUserNameOfProfileAtIndex(
519 size_t index,
520 const base::string16& user_name) {
521 if (user_name == GetUserNameOfProfileAtIndex(index))
522 return;
524 scoped_ptr<base::DictionaryValue> info(
525 GetInfoForProfileAtIndex(index)->DeepCopy());
526 info->SetString(kUserNameKey, user_name);
527 // This takes ownership of |info|.
528 SetInfoForProfileAtIndex(index, info.release());
530 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
531 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
532 observer_list_,
533 OnProfileUserNameChanged(profile_path));
536 void ProfileInfoCache::SetAvatarIconOfProfileAtIndex(size_t index,
537 size_t icon_index) {
538 scoped_ptr<base::DictionaryValue> info(
539 GetInfoForProfileAtIndex(index)->DeepCopy());
540 info->SetString(kAvatarIconKey,
541 profiles::GetDefaultAvatarIconUrl(icon_index));
542 // This takes ownership of |info|.
543 SetInfoForProfileAtIndex(index, info.release());
545 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
547 if (switches::IsNewAvatarMenu())
548 DownloadHighResAvatarIfNeeded(icon_index, profile_path);
550 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
551 observer_list_,
552 OnProfileAvatarChanged(profile_path));
555 void ProfileInfoCache::SetIsOmittedProfileAtIndex(size_t index,
556 bool is_omitted) {
557 if (IsOmittedProfileAtIndex(index) == is_omitted)
558 return;
559 scoped_ptr<base::DictionaryValue> info(
560 GetInfoForProfileAtIndex(index)->DeepCopy());
561 info->SetBoolean(kIsOmittedFromProfileListKey, is_omitted);
562 // This takes ownership of |info|.
563 SetInfoForProfileAtIndex(index, info.release());
566 void ProfileInfoCache::SetSupervisedUserIdOfProfileAtIndex(
567 size_t index,
568 const std::string& id) {
569 if (GetSupervisedUserIdOfProfileAtIndex(index) == id)
570 return;
571 scoped_ptr<base::DictionaryValue> info(
572 GetInfoForProfileAtIndex(index)->DeepCopy());
573 info->SetString(kSupervisedUserId, id);
574 // This takes ownership of |info|.
575 SetInfoForProfileAtIndex(index, info.release());
577 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
578 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
579 observer_list_,
580 OnProfileSupervisedUserIdChanged(profile_path));
583 void ProfileInfoCache::SetLocalAuthCredentialsOfProfileAtIndex(
584 size_t index,
585 const std::string& credentials) {
586 scoped_ptr<base::DictionaryValue> info(
587 GetInfoForProfileAtIndex(index)->DeepCopy());
588 info->SetString(kAuthCredentialsKey, credentials);
589 // This takes ownership of |info|.
590 SetInfoForProfileAtIndex(index, info.release());
593 void ProfileInfoCache::SetBackgroundStatusOfProfileAtIndex(
594 size_t index,
595 bool running_background_apps) {
596 if (GetBackgroundStatusOfProfileAtIndex(index) == running_background_apps)
597 return;
598 scoped_ptr<base::DictionaryValue> info(
599 GetInfoForProfileAtIndex(index)->DeepCopy());
600 info->SetBoolean(kBackgroundAppsKey, running_background_apps);
601 // This takes ownership of |info|.
602 SetInfoForProfileAtIndex(index, info.release());
605 void ProfileInfoCache::SetGAIANameOfProfileAtIndex(size_t index,
606 const base::string16& name) {
607 if (name == GetGAIANameOfProfileAtIndex(index))
608 return;
610 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
611 scoped_ptr<base::DictionaryValue> info(
612 GetInfoForProfileAtIndex(index)->DeepCopy());
613 info->SetString(kGAIANameKey, name);
614 // This takes ownership of |info|.
615 SetInfoForProfileAtIndex(index, info.release());
616 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
617 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
618 UpdateSortForProfileIndex(index);
620 if (old_display_name != new_display_name) {
621 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
622 observer_list_,
623 OnProfileNameChanged(profile_path, old_display_name));
627 void ProfileInfoCache::SetGAIAGivenNameOfProfileAtIndex(
628 size_t index,
629 const base::string16& name) {
630 if (name == GetGAIAGivenNameOfProfileAtIndex(index))
631 return;
633 base::string16 old_display_name = GetNameOfProfileAtIndex(index);
634 scoped_ptr<base::DictionaryValue> info(
635 GetInfoForProfileAtIndex(index)->DeepCopy());
636 info->SetString(kGAIAGivenNameKey, name);
637 // This takes ownership of |info|.
638 SetInfoForProfileAtIndex(index, info.release());
639 base::string16 new_display_name = GetNameOfProfileAtIndex(index);
640 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
641 UpdateSortForProfileIndex(index);
643 if (old_display_name != new_display_name) {
644 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
645 observer_list_,
646 OnProfileNameChanged(profile_path, old_display_name));
650 void ProfileInfoCache::SetGAIAPictureOfProfileAtIndex(size_t index,
651 const gfx::Image* image) {
652 base::FilePath path = GetPathOfProfileAtIndex(index);
653 std::string key = CacheKeyFromProfilePath(path);
655 // Delete the old bitmap from cache.
656 std::map<std::string, gfx::Image*>::iterator it =
657 cached_avatar_images_.find(key);
658 if (it != cached_avatar_images_.end()) {
659 delete it->second;
660 cached_avatar_images_.erase(it);
663 std::string old_file_name;
664 GetInfoForProfileAtIndex(index)->GetString(
665 kGAIAPictureFileNameKey, &old_file_name);
666 std::string new_file_name;
668 if (!image) {
669 // Delete the old bitmap from disk.
670 if (!old_file_name.empty()) {
671 base::FilePath image_path = path.AppendASCII(old_file_name);
672 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
673 base::Bind(&DeleteBitmap, image_path));
675 } else {
676 // Save the new bitmap to disk.
677 new_file_name =
678 old_file_name.empty() ? profiles::kGAIAPictureFileName : old_file_name;
679 base::FilePath image_path = path.AppendASCII(new_file_name);
680 SaveAvatarImageAtPath(
681 image, key, image_path, GetPathOfProfileAtIndex(index));
684 scoped_ptr<base::DictionaryValue> info(
685 GetInfoForProfileAtIndex(index)->DeepCopy());
686 info->SetString(kGAIAPictureFileNameKey, new_file_name);
687 // This takes ownership of |info|.
688 SetInfoForProfileAtIndex(index, info.release());
690 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
691 observer_list_,
692 OnProfileAvatarChanged(path));
695 void ProfileInfoCache::SetIsUsingGAIAPictureOfProfileAtIndex(size_t index,
696 bool value) {
697 scoped_ptr<base::DictionaryValue> info(
698 GetInfoForProfileAtIndex(index)->DeepCopy());
699 info->SetBoolean(kUseGAIAPictureKey, value);
700 // This takes ownership of |info|.
701 SetInfoForProfileAtIndex(index, info.release());
703 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
704 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
705 observer_list_,
706 OnProfileAvatarChanged(profile_path));
709 void ProfileInfoCache::SetProfileSigninRequiredAtIndex(size_t index,
710 bool value) {
711 if (value == ProfileIsSigninRequiredAtIndex(index))
712 return;
714 scoped_ptr<base::DictionaryValue> info(
715 GetInfoForProfileAtIndex(index)->DeepCopy());
716 info->SetBoolean(kSigninRequiredKey, value);
717 // This takes ownership of |info|.
718 SetInfoForProfileAtIndex(index, info.release());
720 base::FilePath profile_path = GetPathOfProfileAtIndex(index);
721 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
722 observer_list_,
723 OnProfileSigninRequiredChanged(profile_path));
726 void ProfileInfoCache::SetProfileIsEphemeralAtIndex(size_t index, bool value) {
727 if (value == ProfileIsEphemeralAtIndex(index))
728 return;
730 scoped_ptr<base::DictionaryValue> info(
731 GetInfoForProfileAtIndex(index)->DeepCopy());
732 info->SetBoolean(kProfileIsEphemeral, value);
733 // This takes ownership of |info|.
734 SetInfoForProfileAtIndex(index, info.release());
737 void ProfileInfoCache::SetProfileIsUsingDefaultNameAtIndex(
738 size_t index, bool value) {
739 if (value == ProfileIsUsingDefaultNameAtIndex(index))
740 return;
742 scoped_ptr<base::DictionaryValue> info(
743 GetInfoForProfileAtIndex(index)->DeepCopy());
744 info->SetBoolean(kIsUsingDefaultNameKey, value);
745 // This takes ownership of |info|.
746 SetInfoForProfileAtIndex(index, info.release());
749 void ProfileInfoCache::SetProfileIsUsingDefaultAvatarAtIndex(
750 size_t index, bool value) {
751 if (value == ProfileIsUsingDefaultAvatarAtIndex(index))
752 return;
754 scoped_ptr<base::DictionaryValue> info(
755 GetInfoForProfileAtIndex(index)->DeepCopy());
756 info->SetBoolean(kIsUsingDefaultAvatarKey, value);
757 // This takes ownership of |info|.
758 SetInfoForProfileAtIndex(index, info.release());
761 void ProfileInfoCache::SetProfileIsAuthErrorAtIndex(size_t index, bool value) {
762 if (value == ProfileIsAuthErrorAtIndex(index))
763 return;
765 scoped_ptr<base::DictionaryValue> info(
766 GetInfoForProfileAtIndex(index)->DeepCopy());
767 info->SetBoolean(kIsAuthErrorKey, value);
768 // This takes ownership of |info|.
769 SetInfoForProfileAtIndex(index, info.release());
772 bool ProfileInfoCache::IsDefaultProfileName(const base::string16& name) const {
773 // Check if it's a "First user" old-style name.
774 if (name == l10n_util::GetStringUTF16(IDS_DEFAULT_PROFILE_NAME) ||
775 name == l10n_util::GetStringUTF16(IDS_LEGACY_DEFAULT_PROFILE_NAME))
776 return true;
778 // Check if it's one of the old-style profile names.
779 for (size_t i = 0; i < arraysize(kDefaultNames); ++i) {
780 if (name == l10n_util::GetStringUTF16(kDefaultNames[i]))
781 return true;
784 // Check whether it's one of the "Person %d" style names.
785 std::string default_name_format = l10n_util::GetStringFUTF8(
786 IDS_NEW_NUMBERED_PROFILE_NAME, base::ASCIIToUTF16("%d"));
788 int generic_profile_number; // Unused. Just a placeholder for sscanf.
789 int assignments = sscanf(base::UTF16ToUTF8(name).c_str(),
790 default_name_format.c_str(),
791 &generic_profile_number);
792 // Unless it matched the format, this is a custom name.
793 return assignments == 1;
796 base::string16 ProfileInfoCache::ChooseNameForNewProfile(
797 size_t icon_index) const {
798 base::string16 name;
799 for (int name_index = 1; ; ++name_index) {
800 if (switches::IsNewAvatarMenu()) {
801 name = l10n_util::GetStringFUTF16Int(IDS_NEW_NUMBERED_PROFILE_NAME,
802 name_index);
803 } else if (icon_index < profiles::GetGenericAvatarIconCount()) {
804 name = l10n_util::GetStringFUTF16Int(IDS_NUMBERED_PROFILE_NAME,
805 name_index);
806 } else {
807 name = l10n_util::GetStringUTF16(
808 kDefaultNames[icon_index - profiles::GetGenericAvatarIconCount()]);
809 if (name_index > 1)
810 name.append(base::UTF8ToUTF16(base::IntToString(name_index)));
813 // Loop through previously named profiles to ensure we're not duplicating.
814 bool name_found = false;
815 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
816 if (GetNameOfProfileAtIndex(i) == name) {
817 name_found = true;
818 break;
821 if (!name_found)
822 return name;
826 size_t ProfileInfoCache::ChooseAvatarIconIndexForNewProfile() const {
827 size_t icon_index = 0;
828 // Try to find a unique, non-generic icon.
829 if (ChooseAvatarIconIndexForNewProfile(false, true, &icon_index))
830 return icon_index;
831 // Try to find any unique icon.
832 if (ChooseAvatarIconIndexForNewProfile(true, true, &icon_index))
833 return icon_index;
834 // Settle for any random icon, even if it's not unique.
835 if (ChooseAvatarIconIndexForNewProfile(true, false, &icon_index))
836 return icon_index;
838 NOTREACHED();
839 return 0;
842 const base::FilePath& ProfileInfoCache::GetUserDataDir() const {
843 return user_data_dir_;
846 // static
847 void ProfileInfoCache::RegisterPrefs(PrefRegistrySimple* registry) {
848 registry->RegisterDictionaryPref(prefs::kProfileInfoCache);
851 void ProfileInfoCache::DownloadHighResAvatarIfNeeded(
852 size_t icon_index,
853 const base::FilePath& profile_path) {
854 // Downloading is only supported on desktop.
855 #if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS)
856 return;
857 #endif
859 const base::FilePath& file_path =
860 profiles::GetPathOfHighResAvatarAtIndex(icon_index);
861 base::Closure callback =
862 base::Bind(&ProfileInfoCache::DownloadHighResAvatar,
863 AsWeakPtr(),
864 icon_index,
865 profile_path);
866 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
867 base::Bind(&RunCallbackIfFileMissing, file_path, callback));
870 void ProfileInfoCache::SaveAvatarImageAtPath(
871 const gfx::Image* image,
872 const std::string& key,
873 const base::FilePath& image_path,
874 const base::FilePath& profile_path) {
875 cached_avatar_images_[key] = new gfx::Image(*image);
877 scoped_ptr<ImageData> data(new ImageData);
878 scoped_refptr<base::RefCountedMemory> png_data = image->As1xPNGBytes();
879 data->assign(png_data->front(), png_data->front() + png_data->size());
881 // Remove the file from the list of downloads in progress. Note that this list
882 // only contains the high resolution avatars, and not the Gaia profile images.
883 auto downloader_iter = avatar_images_downloads_in_progress_.find(key);
884 if (downloader_iter != avatar_images_downloads_in_progress_.end()) {
885 // We mustn't delete the avatar downloader right here, since we're being
886 // called by it.
887 BrowserThread::DeleteSoon(BrowserThread::UI, FROM_HERE,
888 downloader_iter->second);
889 avatar_images_downloads_in_progress_.erase(downloader_iter);
892 if (!data->size()) {
893 LOG(ERROR) << "Failed to PNG encode the image.";
894 } else {
895 base::Closure callback = base::Bind(&ProfileInfoCache::OnAvatarPictureSaved,
896 AsWeakPtr(), key, profile_path);
897 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
898 base::Bind(&SaveBitmap, base::Passed(&data), image_path, callback));
902 const base::DictionaryValue* ProfileInfoCache::GetInfoForProfileAtIndex(
903 size_t index) const {
904 DCHECK_LT(index, GetNumberOfProfiles());
905 const base::DictionaryValue* cache =
906 prefs_->GetDictionary(prefs::kProfileInfoCache);
907 const base::DictionaryValue* info = NULL;
908 cache->GetDictionaryWithoutPathExpansion(sorted_keys_[index], &info);
909 return info;
912 void ProfileInfoCache::SetInfoForProfileAtIndex(size_t index,
913 base::DictionaryValue* info) {
914 DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
915 base::DictionaryValue* cache = update.Get();
916 cache->SetWithoutPathExpansion(sorted_keys_[index], info);
919 std::string ProfileInfoCache::CacheKeyFromProfilePath(
920 const base::FilePath& profile_path) const {
921 DCHECK(user_data_dir_ == profile_path.DirName());
922 base::FilePath base_name = profile_path.BaseName();
923 return base_name.MaybeAsASCII();
926 std::vector<std::string>::iterator ProfileInfoCache::FindPositionForProfile(
927 const std::string& search_key,
928 const base::string16& search_name) {
929 base::string16 search_name_l = base::i18n::ToLower(search_name);
930 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
931 base::string16 name_l = base::i18n::ToLower(GetNameOfProfileAtIndex(i));
932 int name_compare = search_name_l.compare(name_l);
933 if (name_compare < 0)
934 return sorted_keys_.begin() + i;
935 if (name_compare == 0) {
936 int key_compare = search_key.compare(sorted_keys_[i]);
937 if (key_compare < 0)
938 return sorted_keys_.begin() + i;
941 return sorted_keys_.end();
944 bool ProfileInfoCache::IconIndexIsUnique(size_t icon_index) const {
945 for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
946 if (GetAvatarIconIndexOfProfileAtIndex(i) == icon_index)
947 return false;
949 return true;
952 bool ProfileInfoCache::ChooseAvatarIconIndexForNewProfile(
953 bool allow_generic_icon,
954 bool must_be_unique,
955 size_t* out_icon_index) const {
956 // Always allow all icons for new profiles if using the
957 // --new-avatar-menu flag.
958 if (switches::IsNewAvatarMenu())
959 allow_generic_icon = true;
960 size_t start = allow_generic_icon ? 0 : profiles::GetGenericAvatarIconCount();
961 size_t end = profiles::GetDefaultAvatarIconCount();
962 size_t count = end - start;
964 int rand = base::RandInt(0, count);
965 for (size_t i = 0; i < count; ++i) {
966 size_t icon_index = start + (rand + i) % count;
967 if (!must_be_unique || IconIndexIsUnique(icon_index)) {
968 *out_icon_index = icon_index;
969 return true;
973 return false;
976 void ProfileInfoCache::UpdateSortForProfileIndex(size_t index) {
977 base::string16 name = GetNameOfProfileAtIndex(index);
979 // Remove and reinsert key in |sorted_keys_| to alphasort.
980 std::string key = CacheKeyFromProfilePath(GetPathOfProfileAtIndex(index));
981 std::vector<std::string>::iterator key_it =
982 std::find(sorted_keys_.begin(), sorted_keys_.end(), key);
983 DCHECK(key_it != sorted_keys_.end());
984 sorted_keys_.erase(key_it);
985 sorted_keys_.insert(FindPositionForProfile(key, name), key);
988 const gfx::Image* ProfileInfoCache::GetHighResAvatarOfProfileAtIndex(
989 size_t index) const {
990 int avatar_index = GetAvatarIconIndexOfProfileAtIndex(index);
991 std::string key = profiles::GetDefaultAvatarIconFileNameAtIndex(avatar_index);
993 // If this is the placeholder avatar, it is already included in the
994 // resources, so it doesn't need to be downloaded.
995 if (!strcmp(key.c_str(), profiles::GetNoHighResAvatarFileName())) {
996 return &ui::ResourceBundle::GetSharedInstance().GetImageNamed(
997 profiles::GetPlaceholderAvatarIconResourceID());
1000 base::FilePath image_path =
1001 profiles::GetPathOfHighResAvatarAtIndex(avatar_index);
1002 return LoadAvatarPictureFromPath(GetPathOfProfileAtIndex(index),
1003 key, image_path);
1006 void ProfileInfoCache::DownloadHighResAvatar(
1007 size_t icon_index,
1008 const base::FilePath& profile_path) {
1009 // Downloading is only supported on desktop.
1010 #if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS)
1011 return;
1012 #endif
1013 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/461175
1014 // is fixed.
1015 tracked_objects::ScopedTracker tracking_profile1(
1016 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1017 "461175 ProfileInfoCache::DownloadHighResAvatar::GetFileName"));
1018 const std::string file_name =
1019 profiles::GetDefaultAvatarIconFileNameAtIndex(icon_index);
1020 // If the file is already being downloaded, don't start another download.
1021 if (avatar_images_downloads_in_progress_.count(file_name))
1022 return;
1024 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/461175
1025 // is fixed.
1026 tracked_objects::ScopedTracker tracking_profile2(
1027 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1028 "461175 ProfileInfoCache::DownloadHighResAvatar::MakeDownloader"));
1029 // Start the download for this file. The cache takes ownership of the
1030 // |avatar_downloader|, which will be deleted when the download completes, or
1031 // if that never happens, when the ProfileInfoCache is destroyed.
1032 ProfileAvatarDownloader* avatar_downloader = new ProfileAvatarDownloader(
1033 icon_index,
1034 profile_path,
1035 this);
1036 avatar_images_downloads_in_progress_[file_name] = avatar_downloader;
1038 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/461175
1039 // is fixed.
1040 tracked_objects::ScopedTracker tracking_profile3(
1041 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1042 "461175 ProfileInfoCache::DownloadHighResAvatar::StartDownload"));
1043 avatar_downloader->Start();
1046 const gfx::Image* ProfileInfoCache::LoadAvatarPictureFromPath(
1047 const base::FilePath& profile_path,
1048 const std::string& key,
1049 const base::FilePath& image_path) const {
1050 // If the picture is already loaded then use it.
1051 if (cached_avatar_images_.count(key)) {
1052 if (cached_avatar_images_[key]->IsEmpty())
1053 return NULL;
1054 return cached_avatar_images_[key];
1057 // If the picture is already being loaded then don't try loading it again.
1058 if (cached_avatar_images_loading_[key])
1059 return NULL;
1060 cached_avatar_images_loading_[key] = true;
1062 gfx::Image** image = new gfx::Image*;
1063 BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE,
1064 base::Bind(&ReadBitmap, image_path, image),
1065 base::Bind(&ProfileInfoCache::OnAvatarPictureLoaded,
1066 const_cast<ProfileInfoCache*>(this)->AsWeakPtr(),
1067 profile_path, key, image));
1068 return NULL;
1071 void ProfileInfoCache::OnAvatarPictureLoaded(const base::FilePath& profile_path,
1072 const std::string& key,
1073 gfx::Image** image) const {
1074 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1076 cached_avatar_images_loading_[key] = false;
1077 delete cached_avatar_images_[key];
1079 if (*image) {
1080 cached_avatar_images_[key] = *image;
1081 } else {
1082 // Place an empty image in the cache to avoid reloading it again.
1083 cached_avatar_images_[key] = new gfx::Image();
1085 delete image;
1087 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
1088 observer_list_,
1089 OnProfileHighResAvatarLoaded(profile_path));
1092 void ProfileInfoCache::OnAvatarPictureSaved(
1093 const std::string& file_name,
1094 const base::FilePath& profile_path) {
1095 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1097 FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
1098 observer_list_,
1099 OnProfileHighResAvatarLoaded(profile_path));
1102 void ProfileInfoCache::MigrateLegacyProfileNamesAndDownloadAvatars() {
1103 DCHECK(switches::IsNewAvatarMenu());
1105 // Only do this on desktop platforms.
1106 #if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)
1107 // Migrate any legacy profile names ("First user", "Default Profile") to
1108 // new style default names ("Person 1"). The problem here is that every
1109 // time you rename a profile, the ProfileInfoCache sorts itself, so
1110 // whatever you were iterating through is no longer valid. We need to
1111 // save a list of the profile paths (which thankfully do not change) that
1112 // need to be renamed. We also can't pre-compute the new names, as they
1113 // depend on the names of all the other profiles in the info cache, so they
1114 // need to be re-computed after each rename.
1115 std::vector<base::FilePath> profiles_to_rename;
1117 const base::string16 default_profile_name = base::i18n::ToLower(
1118 l10n_util::GetStringUTF16(IDS_DEFAULT_PROFILE_NAME));
1119 const base::string16 default_legacy_profile_name = base::i18n::ToLower(
1120 l10n_util::GetStringUTF16(IDS_LEGACY_DEFAULT_PROFILE_NAME));
1122 for (size_t i = 0; i < GetNumberOfProfiles(); i++) {
1123 DownloadHighResAvatarIfNeeded(GetAvatarIconIndexOfProfileAtIndex(i),
1124 GetPathOfProfileAtIndex(i));
1126 base::string16 name = base::i18n::ToLower(GetNameOfProfileAtIndex(i));
1127 if (name == default_profile_name || name == default_legacy_profile_name)
1128 profiles_to_rename.push_back(GetPathOfProfileAtIndex(i));
1131 // Rename the necessary profiles.
1132 std::vector<base::FilePath>::const_iterator it;
1133 for (it = profiles_to_rename.begin(); it != profiles_to_rename.end(); ++it) {
1134 size_t profile_index = GetIndexOfProfileWithPath(*it);
1135 SetProfileIsUsingDefaultNameAtIndex(profile_index, true);
1136 // This will assign a new "Person %d" type name and re-sort the cache.
1137 SetNameOfProfileAtIndex(profile_index, ChooseNameForNewProfile(
1138 GetAvatarIconIndexOfProfileAtIndex(profile_index)));
1140 #endif