Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / profiles / profile_info_cache.cc
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.
4
5 #include "chrome/browser/profiles/profile_info_cache.h"
6
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"
36
37 using content::BrowserThread;
38
39 namespace {
40
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 kIsUsingDefaultNameKey[] = "is_using_default_name";
47 const char kIsUsingDefaultAvatarKey[] = "is_using_default_avatar";
48 const char kAvatarIconKey[] = "avatar_icon";
49 const char kAuthCredentialsKey[] = "local_auth_credentials";
50 const char kUseGAIAPictureKey[] = "use_gaia_picture";
51 const char kBackgroundAppsKey[] = "background_apps";
52 const char kGAIAPictureFileNameKey[] = "gaia_picture_file_name";
53 const char kIsOmittedFromProfileListKey[] = "is_omitted_from_profile_list";
54 const char kSigninRequiredKey[] = "signin_required";
55 const char kSupervisedUserId[] = "managed_user_id";
56 const char kProfileIsEphemeral[] = "is_ephemeral";
57 const char kActiveTimeKey[] = "active_time";
58
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
80 };
81
82 typedef std::vector<unsigned char> ImageData;
83
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));
90
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;
96   }
97
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;
102   }
103
104   BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback);
105 }
106
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;
114
115   // If the path doesn't exist, don't even try reading it.
116   if (!base::PathExists(image_path))
117     return;
118
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;
123   }
124
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;
130   }
131
132   *out_image = new gfx::Image(image);
133 }
134
135 void DeleteBitmap(const base::FilePath& image_path) {
136   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
137   base::DeleteFile(image_path, false);
138 }
139
140 }  // namespace
141
142 ProfileInfoCache::ProfileInfoCache(PrefService* prefs,
143                                    const base::FilePath& user_data_dir)
144     : prefs_(prefs),
145       user_data_dir_(user_data_dir) {
146   // Populate the cache
147   DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
148   base::DictionaryValue* cache = update.Get();
149   for (base::DictionaryValue::Iterator it(*cache);
150        !it.IsAtEnd(); it.Advance()) {
151     base::DictionaryValue* info = NULL;
152     cache->GetDictionaryWithoutPathExpansion(it.key(), &info);
153     base::string16 name;
154     info->GetString(kNameKey, &name);
155     sorted_keys_.insert(FindPositionForProfile(it.key(), name), it.key());
156
157     bool using_default_name;
158     if (!info->GetBoolean(kIsUsingDefaultNameKey, &using_default_name)) {
159       // If the preference hasn't been set, and the name is default, assume
160       // that the user hasn't done this on purpose.
161       using_default_name = IsDefaultProfileName(name);
162       info->SetBoolean(kIsUsingDefaultNameKey, using_default_name);
163     }
164
165     // For profiles that don't have the "using default avatar" state set yet,
166     // assume it's the same as the "using default name" state.
167     if (!info->HasKey(kIsUsingDefaultAvatarKey)) {
168       info->SetBoolean(kIsUsingDefaultAvatarKey, using_default_name);
169     }
170   }
171
172   // If needed, start downloading the high-res avatars.
173   if (switches::IsNewAvatarMenu()) {
174     for (size_t i = 0; i < GetNumberOfProfiles(); i++) {
175       DownloadHighResAvatar(GetAvatarIconIndexOfProfileAtIndex(i),
176                             GetPathOfProfileAtIndex(i));
177     }
178   }
179 }
180
181 ProfileInfoCache::~ProfileInfoCache() {
182   STLDeleteContainerPairSecondPointers(
183       cached_avatar_images_.begin(), cached_avatar_images_.end());
184   STLDeleteContainerPairSecondPointers(
185       avatar_images_downloads_in_progress_.begin(),
186       avatar_images_downloads_in_progress_.end());
187 }
188
189 void ProfileInfoCache::AddProfileToCache(
190     const base::FilePath& profile_path,
191     const base::string16& name,
192     const base::string16& username,
193     size_t icon_index,
194     const std::string& supervised_user_id) {
195   std::string key = CacheKeyFromProfilePath(profile_path);
196   DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
197   base::DictionaryValue* cache = update.Get();
198
199   scoped_ptr<base::DictionaryValue> info(new base::DictionaryValue);
200   info->SetString(kNameKey, name);
201   info->SetString(kUserNameKey, username);
202   info->SetString(kAvatarIconKey,
203       profiles::GetDefaultAvatarIconUrl(icon_index));
204   // Default value for whether background apps are running is false.
205   info->SetBoolean(kBackgroundAppsKey, false);
206   info->SetString(kSupervisedUserId, supervised_user_id);
207   info->SetBoolean(kIsOmittedFromProfileListKey, !supervised_user_id.empty());
208   info->SetBoolean(kProfileIsEphemeral, false);
209   info->SetBoolean(kIsUsingDefaultNameKey, IsDefaultProfileName(name));
210   // Assume newly created profiles use a default avatar.
211   info->SetBoolean(kIsUsingDefaultAvatarKey, true);
212   cache->SetWithoutPathExpansion(key, info.release());
213
214   sorted_keys_.insert(FindPositionForProfile(key, name), key);
215
216   if (switches::IsNewAvatarMenu())
217     DownloadHighResAvatar(icon_index, profile_path);
218
219   FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
220                     observer_list_,
221                     OnProfileAdded(profile_path));
222
223   content::NotificationService::current()->Notify(
224       chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
225       content::NotificationService::AllSources(),
226       content::NotificationService::NoDetails());
227 }
228
229 void ProfileInfoCache::AddObserver(ProfileInfoCacheObserver* obs) {
230   observer_list_.AddObserver(obs);
231 }
232
233 void ProfileInfoCache::RemoveObserver(ProfileInfoCacheObserver* obs) {
234   observer_list_.RemoveObserver(obs);
235 }
236
237 void ProfileInfoCache::DeleteProfileFromCache(
238     const base::FilePath& profile_path) {
239   size_t profile_index = GetIndexOfProfileWithPath(profile_path);
240   if (profile_index == std::string::npos) {
241     NOTREACHED();
242     return;
243   }
244   base::string16 name = GetNameOfProfileAtIndex(profile_index);
245
246   FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
247                     observer_list_,
248                     OnProfileWillBeRemoved(profile_path));
249
250   DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
251   base::DictionaryValue* cache = update.Get();
252   std::string key = CacheKeyFromProfilePath(profile_path);
253   cache->Remove(key, NULL);
254   sorted_keys_.erase(std::find(sorted_keys_.begin(), sorted_keys_.end(), key));
255
256   FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
257                     observer_list_,
258                     OnProfileWasRemoved(profile_path, name));
259
260   content::NotificationService::current()->Notify(
261       chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
262       content::NotificationService::AllSources(),
263       content::NotificationService::NoDetails());
264 }
265
266 size_t ProfileInfoCache::GetNumberOfProfiles() const {
267   return sorted_keys_.size();
268 }
269
270 size_t ProfileInfoCache::GetIndexOfProfileWithPath(
271     const base::FilePath& profile_path) const {
272   if (profile_path.DirName() != user_data_dir_)
273     return std::string::npos;
274   std::string search_key = CacheKeyFromProfilePath(profile_path);
275   for (size_t i = 0; i < sorted_keys_.size(); ++i) {
276     if (sorted_keys_[i] == search_key)
277       return i;
278   }
279   return std::string::npos;
280 }
281
282 base::string16 ProfileInfoCache::GetNameOfProfileAtIndex(size_t index) const {
283   base::string16 name;
284   // Unless the user has customized the profile name, we should use the
285   // profile's Gaia given name, if it's available.
286   if (ProfileIsUsingDefaultNameAtIndex(index)) {
287     base::string16 given_name = GetGAIAGivenNameOfProfileAtIndex(index);
288     name = given_name.empty() ? GetGAIANameOfProfileAtIndex(index) : given_name;
289   }
290   if (name.empty())
291     GetInfoForProfileAtIndex(index)->GetString(kNameKey, &name);
292   return name;
293 }
294
295 base::string16 ProfileInfoCache::GetShortcutNameOfProfileAtIndex(size_t index)
296     const {
297   base::string16 shortcut_name;
298   GetInfoForProfileAtIndex(index)->GetString(
299       kShortcutNameKey, &shortcut_name);
300   return shortcut_name;
301 }
302
303 base::FilePath ProfileInfoCache::GetPathOfProfileAtIndex(size_t index) const {
304   return user_data_dir_.AppendASCII(sorted_keys_[index]);
305 }
306
307 base::Time ProfileInfoCache::GetProfileActiveTimeAtIndex(size_t index) const {
308   double dt;
309   if (GetInfoForProfileAtIndex(index)->GetDouble(kActiveTimeKey, &dt)) {
310     return base::Time::FromDoubleT(dt);
311   } else {
312     return base::Time();
313   }
314 }
315
316 base::string16 ProfileInfoCache::GetUserNameOfProfileAtIndex(
317     size_t index) const {
318   base::string16 user_name;
319   GetInfoForProfileAtIndex(index)->GetString(kUserNameKey, &user_name);
320   return user_name;
321 }
322
323 const gfx::Image& ProfileInfoCache::GetAvatarIconOfProfileAtIndex(
324     size_t index) const {
325   if (IsUsingGAIAPictureOfProfileAtIndex(index)) {
326     const gfx::Image* image = GetGAIAPictureOfProfileAtIndex(index);
327     if (image)
328       return *image;
329   }
330
331   // Use the high resolution version of the avatar if it exists.
332   if (switches::IsNewAvatarMenu()) {
333     const gfx::Image* image = GetHighResAvatarOfProfileAtIndex(index);
334     if (image)
335       return *image;
336   }
337
338   int resource_id = profiles::GetDefaultAvatarIconResourceIDAtIndex(
339       GetAvatarIconIndexOfProfileAtIndex(index));
340   return ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
341 }
342
343 std::string ProfileInfoCache::GetLocalAuthCredentialsOfProfileAtIndex(
344     size_t index) const {
345   std::string credentials;
346   GetInfoForProfileAtIndex(index)->GetString(kAuthCredentialsKey, &credentials);
347   return credentials;
348 }
349
350 bool ProfileInfoCache::GetBackgroundStatusOfProfileAtIndex(
351     size_t index) const {
352   bool background_app_status;
353   if (!GetInfoForProfileAtIndex(index)->GetBoolean(kBackgroundAppsKey,
354                                                    &background_app_status)) {
355     return false;
356   }
357   return background_app_status;
358 }
359
360 base::string16 ProfileInfoCache::GetGAIANameOfProfileAtIndex(
361     size_t index) const {
362   base::string16 name;
363   GetInfoForProfileAtIndex(index)->GetString(kGAIANameKey, &name);
364   return name;
365 }
366
367 base::string16 ProfileInfoCache::GetGAIAGivenNameOfProfileAtIndex(
368     size_t index) const {
369   base::string16 name;
370   GetInfoForProfileAtIndex(index)->GetString(kGAIAGivenNameKey, &name);
371   return name;
372 }
373
374 const gfx::Image* ProfileInfoCache::GetGAIAPictureOfProfileAtIndex(
375     size_t index) const {
376   base::FilePath path = GetPathOfProfileAtIndex(index);
377   std::string key = CacheKeyFromProfilePath(path);
378
379   std::string file_name;
380   GetInfoForProfileAtIndex(index)->GetString(
381       kGAIAPictureFileNameKey, &file_name);
382
383   // If the picture is not on disk then return NULL.
384   if (file_name.empty())
385     return NULL;
386
387   base::FilePath image_path = path.AppendASCII(file_name);
388   return LoadAvatarPictureFromPath(key, image_path);
389 }
390
391 bool ProfileInfoCache::IsUsingGAIAPictureOfProfileAtIndex(size_t index) const {
392   bool value = false;
393   GetInfoForProfileAtIndex(index)->GetBoolean(kUseGAIAPictureKey, &value);
394   if (!value) {
395     // Prefer the GAIA avatar over a non-customized avatar.
396     value = ProfileIsUsingDefaultAvatarAtIndex(index) &&
397         GetGAIAPictureOfProfileAtIndex(index);
398   }
399   return value;
400 }
401
402 bool ProfileInfoCache::ProfileIsSupervisedAtIndex(size_t index) const {
403   return !GetSupervisedUserIdOfProfileAtIndex(index).empty();
404 }
405
406 bool ProfileInfoCache::IsOmittedProfileAtIndex(size_t index) const {
407   bool value = false;
408   GetInfoForProfileAtIndex(index)->GetBoolean(kIsOmittedFromProfileListKey,
409                                               &value);
410   return value;
411 }
412
413 bool ProfileInfoCache::ProfileIsSigninRequiredAtIndex(size_t index) const {
414   bool value = false;
415   GetInfoForProfileAtIndex(index)->GetBoolean(kSigninRequiredKey, &value);
416   return value;
417 }
418
419 std::string ProfileInfoCache::GetSupervisedUserIdOfProfileAtIndex(
420     size_t index) const {
421   std::string supervised_user_id;
422   GetInfoForProfileAtIndex(index)->GetString(kSupervisedUserId,
423                                              &supervised_user_id);
424   return supervised_user_id;
425 }
426
427 bool ProfileInfoCache::ProfileIsEphemeralAtIndex(size_t index) const {
428   bool value = false;
429   GetInfoForProfileAtIndex(index)->GetBoolean(kProfileIsEphemeral, &value);
430   return value;
431 }
432
433 bool ProfileInfoCache::ProfileIsUsingDefaultNameAtIndex(size_t index) const {
434   bool value = false;
435   GetInfoForProfileAtIndex(index)->GetBoolean(kIsUsingDefaultNameKey, &value);
436   return value;
437 }
438
439 bool ProfileInfoCache::ProfileIsUsingDefaultAvatarAtIndex(size_t index) const {
440   bool value = false;
441   GetInfoForProfileAtIndex(index)->GetBoolean(kIsUsingDefaultAvatarKey, &value);
442   return value;
443 }
444
445 size_t ProfileInfoCache::GetAvatarIconIndexOfProfileAtIndex(size_t index)
446     const {
447   std::string icon_url;
448   GetInfoForProfileAtIndex(index)->GetString(kAvatarIconKey, &icon_url);
449   size_t icon_index = 0;
450   if (!profiles::IsDefaultAvatarIconUrl(icon_url, &icon_index))
451     DLOG(WARNING) << "Unknown avatar icon: " << icon_url;
452
453   return icon_index;
454 }
455
456 void ProfileInfoCache::SetProfileActiveTimeAtIndex(size_t index) {
457   scoped_ptr<base::DictionaryValue> info(
458       GetInfoForProfileAtIndex(index)->DeepCopy());
459   info->SetDouble(kActiveTimeKey, base::Time::Now().ToDoubleT());
460   // This takes ownership of |info|.
461   SetInfoQuietlyForProfileAtIndex(index, info.release());
462 }
463
464 void ProfileInfoCache::SetNameOfProfileAtIndex(size_t index,
465                                                const base::string16& name) {
466   scoped_ptr<base::DictionaryValue> info(
467       GetInfoForProfileAtIndex(index)->DeepCopy());
468   base::string16 current_name;
469   info->GetString(kNameKey, &current_name);
470   if (name == current_name)
471     return;
472
473   base::string16 old_display_name = GetNameOfProfileAtIndex(index);
474   info->SetString(kNameKey, name);
475
476   // This takes ownership of |info|.
477   SetInfoForProfileAtIndex(index, info.release());
478
479   base::string16 new_display_name = GetNameOfProfileAtIndex(index);
480   base::FilePath profile_path = GetPathOfProfileAtIndex(index);
481   UpdateSortForProfileIndex(index);
482
483   if (old_display_name != new_display_name) {
484     FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
485                       observer_list_,
486                       OnProfileNameChanged(profile_path, old_display_name));
487   }
488 }
489
490 void ProfileInfoCache::SetShortcutNameOfProfileAtIndex(
491     size_t index,
492     const base::string16& shortcut_name) {
493   if (shortcut_name == GetShortcutNameOfProfileAtIndex(index))
494     return;
495   scoped_ptr<base::DictionaryValue> info(
496       GetInfoForProfileAtIndex(index)->DeepCopy());
497   info->SetString(kShortcutNameKey, shortcut_name);
498   // This takes ownership of |info|.
499   SetInfoForProfileAtIndex(index, info.release());
500 }
501
502 void ProfileInfoCache::SetUserNameOfProfileAtIndex(
503     size_t index,
504     const base::string16& user_name) {
505   if (user_name == GetUserNameOfProfileAtIndex(index))
506     return;
507
508   scoped_ptr<base::DictionaryValue> info(
509       GetInfoForProfileAtIndex(index)->DeepCopy());
510   info->SetString(kUserNameKey, user_name);
511   // This takes ownership of |info|.
512   SetInfoForProfileAtIndex(index, info.release());
513 }
514
515 void ProfileInfoCache::SetAvatarIconOfProfileAtIndex(size_t index,
516                                                      size_t icon_index) {
517   scoped_ptr<base::DictionaryValue> info(
518       GetInfoForProfileAtIndex(index)->DeepCopy());
519   info->SetString(kAvatarIconKey,
520       profiles::GetDefaultAvatarIconUrl(icon_index));
521   // This takes ownership of |info|.
522   SetInfoForProfileAtIndex(index, info.release());
523
524   base::FilePath profile_path = GetPathOfProfileAtIndex(index);
525
526   // If needed, start downloading the high-res avatar.
527   if (switches::IsNewAvatarMenu())
528     DownloadHighResAvatar(icon_index, profile_path);
529
530   FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
531                     observer_list_,
532                     OnProfileAvatarChanged(profile_path));
533 }
534
535 void ProfileInfoCache::SetIsOmittedProfileAtIndex(size_t index,
536                                                   bool is_omitted) {
537   if (IsOmittedProfileAtIndex(index) == is_omitted)
538     return;
539   scoped_ptr<base::DictionaryValue> info(
540       GetInfoForProfileAtIndex(index)->DeepCopy());
541   info->SetBoolean(kIsOmittedFromProfileListKey, is_omitted);
542   // This takes ownership of |info|.
543   SetInfoForProfileAtIndex(index, info.release());
544 }
545
546 void ProfileInfoCache::SetSupervisedUserIdOfProfileAtIndex(
547     size_t index,
548     const std::string& id) {
549   if (GetSupervisedUserIdOfProfileAtIndex(index) == id)
550     return;
551   scoped_ptr<base::DictionaryValue> info(
552       GetInfoForProfileAtIndex(index)->DeepCopy());
553   info->SetString(kSupervisedUserId, id);
554   // This takes ownership of |info|.
555   SetInfoForProfileAtIndex(index, info.release());
556
557   base::FilePath profile_path = GetPathOfProfileAtIndex(index);
558   FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
559                     observer_list_,
560                     OnProfileSupervisedUserIdChanged(profile_path));
561 }
562
563 void ProfileInfoCache::SetLocalAuthCredentialsOfProfileAtIndex(
564     size_t index,
565     const std::string& credentials) {
566   scoped_ptr<base::DictionaryValue> info(
567       GetInfoForProfileAtIndex(index)->DeepCopy());
568   info->SetString(kAuthCredentialsKey, credentials);
569   // This takes ownership of |info|.
570   SetInfoForProfileAtIndex(index, info.release());
571 }
572
573 void ProfileInfoCache::SetBackgroundStatusOfProfileAtIndex(
574     size_t index,
575     bool running_background_apps) {
576   if (GetBackgroundStatusOfProfileAtIndex(index) == running_background_apps)
577     return;
578   scoped_ptr<base::DictionaryValue> info(
579       GetInfoForProfileAtIndex(index)->DeepCopy());
580   info->SetBoolean(kBackgroundAppsKey, running_background_apps);
581   // This takes ownership of |info|.
582   SetInfoForProfileAtIndex(index, info.release());
583 }
584
585 void ProfileInfoCache::SetGAIANameOfProfileAtIndex(size_t index,
586                                                    const base::string16& name) {
587   if (name == GetGAIANameOfProfileAtIndex(index))
588     return;
589
590   base::string16 old_display_name = GetNameOfProfileAtIndex(index);
591   scoped_ptr<base::DictionaryValue> info(
592       GetInfoForProfileAtIndex(index)->DeepCopy());
593   info->SetString(kGAIANameKey, name);
594   // This takes ownership of |info|.
595   SetInfoForProfileAtIndex(index, info.release());
596   base::string16 new_display_name = GetNameOfProfileAtIndex(index);
597   base::FilePath profile_path = GetPathOfProfileAtIndex(index);
598   UpdateSortForProfileIndex(index);
599
600   if (old_display_name != new_display_name) {
601     FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
602                       observer_list_,
603                       OnProfileNameChanged(profile_path, old_display_name));
604   }
605 }
606
607 void ProfileInfoCache::SetGAIAGivenNameOfProfileAtIndex(
608     size_t index,
609     const base::string16& name) {
610   if (name == GetGAIAGivenNameOfProfileAtIndex(index))
611     return;
612
613   base::string16 old_display_name = GetNameOfProfileAtIndex(index);
614   scoped_ptr<base::DictionaryValue> info(
615       GetInfoForProfileAtIndex(index)->DeepCopy());
616   info->SetString(kGAIAGivenNameKey, name);
617   // This takes ownership of |info|.
618   SetInfoForProfileAtIndex(index, info.release());
619   base::string16 new_display_name = GetNameOfProfileAtIndex(index);
620   base::FilePath profile_path = GetPathOfProfileAtIndex(index);
621   UpdateSortForProfileIndex(index);
622
623   if (old_display_name != new_display_name) {
624     FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
625                       observer_list_,
626                       OnProfileNameChanged(profile_path, old_display_name));
627   }
628 }
629
630 void ProfileInfoCache::SetGAIAPictureOfProfileAtIndex(size_t index,
631                                                       const gfx::Image* image) {
632   base::FilePath path = GetPathOfProfileAtIndex(index);
633   std::string key = CacheKeyFromProfilePath(path);
634
635   // Delete the old bitmap from cache.
636   std::map<std::string, gfx::Image*>::iterator it =
637       cached_avatar_images_.find(key);
638   if (it != cached_avatar_images_.end()) {
639     delete it->second;
640     cached_avatar_images_.erase(it);
641   }
642
643   std::string old_file_name;
644   GetInfoForProfileAtIndex(index)->GetString(
645       kGAIAPictureFileNameKey, &old_file_name);
646   std::string new_file_name;
647
648   if (!image) {
649     // Delete the old bitmap from disk.
650     if (!old_file_name.empty()) {
651       base::FilePath image_path = path.AppendASCII(old_file_name);
652       BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
653                               base::Bind(&DeleteBitmap, image_path));
654     }
655   } else {
656     // Save the new bitmap to disk.
657     new_file_name =
658         old_file_name.empty() ? profiles::kGAIAPictureFileName : old_file_name;
659     base::FilePath image_path = path.AppendASCII(new_file_name);
660     SaveAvatarImageAtPath(
661         image, key, image_path, GetPathOfProfileAtIndex(index));
662   }
663
664   scoped_ptr<base::DictionaryValue> info(
665       GetInfoForProfileAtIndex(index)->DeepCopy());
666   info->SetString(kGAIAPictureFileNameKey, new_file_name);
667   // This takes ownership of |info|.
668   SetInfoForProfileAtIndex(index, info.release());
669
670   FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
671                     observer_list_,
672                     OnProfileAvatarChanged(path));
673 }
674
675 void ProfileInfoCache::SetIsUsingGAIAPictureOfProfileAtIndex(size_t index,
676                                                              bool value) {
677   scoped_ptr<base::DictionaryValue> info(
678       GetInfoForProfileAtIndex(index)->DeepCopy());
679   info->SetBoolean(kUseGAIAPictureKey, value);
680   // This takes ownership of |info|.
681   SetInfoForProfileAtIndex(index, info.release());
682
683   // Retrieve some info to update observers who care about avatar changes.
684   base::FilePath profile_path = GetPathOfProfileAtIndex(index);
685   FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
686                     observer_list_,
687                     OnProfileAvatarChanged(profile_path));
688 }
689
690 void ProfileInfoCache::SetProfileSigninRequiredAtIndex(size_t index,
691                                                        bool value) {
692   if (value == ProfileIsSigninRequiredAtIndex(index))
693     return;
694
695   scoped_ptr<base::DictionaryValue> info(
696       GetInfoForProfileAtIndex(index)->DeepCopy());
697   info->SetBoolean(kSigninRequiredKey, value);
698   // This takes ownership of |info|.
699   SetInfoForProfileAtIndex(index, info.release());
700
701   base::FilePath profile_path = GetPathOfProfileAtIndex(index);
702   FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
703                     observer_list_,
704                     OnProfileSigninRequiredChanged(profile_path));
705 }
706
707 void ProfileInfoCache::SetProfileIsEphemeralAtIndex(size_t index, bool value) {
708   if (value == ProfileIsEphemeralAtIndex(index))
709     return;
710
711   scoped_ptr<base::DictionaryValue> info(
712       GetInfoForProfileAtIndex(index)->DeepCopy());
713   info->SetBoolean(kProfileIsEphemeral, value);
714   // This takes ownership of |info|.
715   SetInfoForProfileAtIndex(index, info.release());
716 }
717
718 void ProfileInfoCache::SetProfileIsUsingDefaultNameAtIndex(
719     size_t index, bool value) {
720   if (value == ProfileIsUsingDefaultNameAtIndex(index))
721     return;
722
723   scoped_ptr<base::DictionaryValue> info(
724       GetInfoForProfileAtIndex(index)->DeepCopy());
725   info->SetBoolean(kIsUsingDefaultNameKey, value);
726   // This takes ownership of |info|.
727   SetInfoForProfileAtIndex(index, info.release());
728 }
729
730 void ProfileInfoCache::SetProfileIsUsingDefaultAvatarAtIndex(
731     size_t index, bool value) {
732   if (value == ProfileIsUsingDefaultAvatarAtIndex(index))
733     return;
734
735   scoped_ptr<base::DictionaryValue> info(
736       GetInfoForProfileAtIndex(index)->DeepCopy());
737   info->SetBoolean(kIsUsingDefaultAvatarKey, value);
738   // This takes ownership of |info|.
739   SetInfoForProfileAtIndex(index, info.release());
740 }
741
742 bool ProfileInfoCache::IsDefaultProfileName(const base::string16& name) {
743   // Check if it's a "First user" old-style name.
744   if (name == l10n_util::GetStringUTF16(IDS_DEFAULT_PROFILE_NAME) ||
745       name == l10n_util::GetStringUTF16(IDS_LEGACY_DEFAULT_PROFILE_NAME))
746     return true;
747
748   // Check if it's one of the old-style profile names.
749   for (size_t i = 0; i < arraysize(kDefaultNames); ++i) {
750     if (name == l10n_util::GetStringUTF16(kDefaultNames[i]))
751       return true;
752   }
753
754   // Check whether it's one of the "Person %d" style names.
755   std::string default_name_format = l10n_util::GetStringFUTF8(
756       IDS_NEW_NUMBERED_PROFILE_NAME, base::ASCIIToUTF16("%d"));
757
758   int generic_profile_number;  // Unused. Just a placeholder for sscanf.
759   int assignments = sscanf(base::UTF16ToUTF8(name).c_str(),
760                            default_name_format.c_str(),
761                            &generic_profile_number);
762   // Unless it matched the format, this is a custom name.
763   return assignments == 1;
764 }
765
766 base::string16 ProfileInfoCache::ChooseNameForNewProfile(
767     size_t icon_index) const {
768   base::string16 name;
769   for (int name_index = 1; ; ++name_index) {
770     if (switches::IsNewAvatarMenu()) {
771       name = l10n_util::GetStringFUTF16Int(IDS_NEW_NUMBERED_PROFILE_NAME,
772                                            name_index);
773     } else if (icon_index < profiles::GetGenericAvatarIconCount()) {
774       name = l10n_util::GetStringFUTF16Int(IDS_NUMBERED_PROFILE_NAME,
775                                            name_index);
776     } else {
777       name = l10n_util::GetStringUTF16(
778           kDefaultNames[icon_index - profiles::GetGenericAvatarIconCount()]);
779       if (name_index > 1)
780         name.append(base::UTF8ToUTF16(base::IntToString(name_index)));
781     }
782
783     // Loop through previously named profiles to ensure we're not duplicating.
784     bool name_found = false;
785     for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
786       if (GetNameOfProfileAtIndex(i) == name) {
787         name_found = true;
788         break;
789       }
790     }
791     if (!name_found)
792       return name;
793   }
794 }
795
796 size_t ProfileInfoCache::ChooseAvatarIconIndexForNewProfile() const {
797   size_t icon_index = 0;
798   // Try to find a unique, non-generic icon.
799   if (ChooseAvatarIconIndexForNewProfile(false, true, &icon_index))
800     return icon_index;
801   // Try to find any unique icon.
802   if (ChooseAvatarIconIndexForNewProfile(true, true, &icon_index))
803     return icon_index;
804   // Settle for any random icon, even if it's not unique.
805   if (ChooseAvatarIconIndexForNewProfile(true, false, &icon_index))
806     return icon_index;
807
808   NOTREACHED();
809   return 0;
810 }
811
812 const base::FilePath& ProfileInfoCache::GetUserDataDir() const {
813   return user_data_dir_;
814 }
815
816 // static
817 std::vector<base::string16> ProfileInfoCache::GetProfileNames() {
818   std::vector<base::string16> names;
819   PrefService* local_state = g_browser_process->local_state();
820   const base::DictionaryValue* cache = local_state->GetDictionary(
821       prefs::kProfileInfoCache);
822   base::string16 name;
823   for (base::DictionaryValue::Iterator it(*cache); !it.IsAtEnd();
824        it.Advance()) {
825     const base::DictionaryValue* info = NULL;
826     it.value().GetAsDictionary(&info);
827     info->GetString(kNameKey, &name);
828     names.push_back(name);
829   }
830   return names;
831 }
832
833 // static
834 void ProfileInfoCache::RegisterPrefs(PrefRegistrySimple* registry) {
835   registry->RegisterDictionaryPref(prefs::kProfileInfoCache);
836 }
837
838 void ProfileInfoCache::DownloadHighResAvatar(
839     size_t icon_index,
840     const base::FilePath& profile_path) {
841   // Downloading is only supported on desktop.
842 #if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS)
843   return;
844 #endif
845
846   // TODO(noms): We should check whether the file already exists on disk
847   // before trying to re-download it. For now, since this is behind a flag and
848   // the resources are still changing, re-download it every time the profile
849   // avatar changes, to make sure we have the latest copy.
850   std::string file_name = profiles::GetDefaultAvatarIconFileNameAtIndex(
851       icon_index);
852   // If the file is already being downloaded, don't start another download.
853   if (avatar_images_downloads_in_progress_[file_name])
854     return;
855
856   // Start the download for this file. The cache takes ownership of the
857   // |avatar_downloader|, which will be deleted when the download completes, or
858   // if that never happens, when the ProfileInfoCache is destroyed.
859   ProfileAvatarDownloader* avatar_downloader = new ProfileAvatarDownloader(
860       icon_index,
861       profile_path,
862       this);
863   avatar_images_downloads_in_progress_[file_name] = avatar_downloader;
864   avatar_downloader->Start();
865 }
866
867 void ProfileInfoCache::SaveAvatarImageAtPath(
868     const gfx::Image* image,
869     const std::string& key,
870     const base::FilePath& image_path,
871     const base::FilePath& profile_path) {
872   cached_avatar_images_[key] = new gfx::Image(*image);
873
874   scoped_ptr<ImageData> data(new ImageData);
875   scoped_refptr<base::RefCountedMemory> png_data = image->As1xPNGBytes();
876   data->assign(png_data->front(), png_data->front() + png_data->size());
877
878   if (!data->size()) {
879     LOG(ERROR) << "Failed to PNG encode the image.";
880   } else {
881     base::Closure callback = base::Bind(&ProfileInfoCache::OnAvatarPictureSaved,
882         AsWeakPtr(), key, profile_path);
883
884     BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
885         base::Bind(&SaveBitmap, base::Passed(&data), image_path, callback));
886   }
887 }
888
889 const base::DictionaryValue* ProfileInfoCache::GetInfoForProfileAtIndex(
890     size_t index) const {
891   DCHECK_LT(index, GetNumberOfProfiles());
892   const base::DictionaryValue* cache =
893       prefs_->GetDictionary(prefs::kProfileInfoCache);
894   const base::DictionaryValue* info = NULL;
895   cache->GetDictionaryWithoutPathExpansion(sorted_keys_[index], &info);
896   return info;
897 }
898
899 void ProfileInfoCache::SetInfoQuietlyForProfileAtIndex(
900     size_t index, base::DictionaryValue* info) {
901   DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache);
902   base::DictionaryValue* cache = update.Get();
903   cache->SetWithoutPathExpansion(sorted_keys_[index], info);
904 }
905
906 // TODO(noms): Switch to newer notification system.
907 void ProfileInfoCache::SetInfoForProfileAtIndex(size_t index,
908                                                 base::DictionaryValue* info) {
909   SetInfoQuietlyForProfileAtIndex(index, info);
910
911   content::NotificationService::current()->Notify(
912       chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
913       content::NotificationService::AllSources(),
914       content::NotificationService::NoDetails());
915 }
916
917 std::string ProfileInfoCache::CacheKeyFromProfilePath(
918     const base::FilePath& profile_path) const {
919   DCHECK(user_data_dir_ == profile_path.DirName());
920   base::FilePath base_name = profile_path.BaseName();
921   return base_name.MaybeAsASCII();
922 }
923
924 std::vector<std::string>::iterator ProfileInfoCache::FindPositionForProfile(
925     const std::string& search_key,
926     const base::string16& search_name) {
927   base::string16 search_name_l = base::i18n::ToLower(search_name);
928   for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
929     base::string16 name_l = base::i18n::ToLower(GetNameOfProfileAtIndex(i));
930     int name_compare = search_name_l.compare(name_l);
931     if (name_compare < 0)
932       return sorted_keys_.begin() + i;
933     if (name_compare == 0) {
934       int key_compare = search_key.compare(sorted_keys_[i]);
935       if (key_compare < 0)
936         return sorted_keys_.begin() + i;
937     }
938   }
939   return sorted_keys_.end();
940 }
941
942 bool ProfileInfoCache::IconIndexIsUnique(size_t icon_index) const {
943   for (size_t i = 0; i < GetNumberOfProfiles(); ++i) {
944     if (GetAvatarIconIndexOfProfileAtIndex(i) == icon_index)
945       return false;
946   }
947   return true;
948 }
949
950 bool ProfileInfoCache::ChooseAvatarIconIndexForNewProfile(
951     bool allow_generic_icon,
952     bool must_be_unique,
953     size_t* out_icon_index) const {
954   // Always allow all icons for new profiles if using the
955   // --new-avatar-menu flag.
956   if (switches::IsNewAvatarMenu())
957     allow_generic_icon = true;
958   size_t start = allow_generic_icon ? 0 : profiles::GetGenericAvatarIconCount();
959   size_t end = profiles::GetDefaultAvatarIconCount();
960   size_t count = end - start;
961
962   int rand = base::RandInt(0, count);
963   for (size_t i = 0; i < count; ++i) {
964     size_t icon_index = start + (rand + i) %  count;
965     if (!must_be_unique || IconIndexIsUnique(icon_index)) {
966       *out_icon_index = icon_index;
967       return true;
968     }
969   }
970
971   return false;
972 }
973
974 void ProfileInfoCache::UpdateSortForProfileIndex(size_t index) {
975   base::string16 name = GetNameOfProfileAtIndex(index);
976
977   // Remove and reinsert key in |sorted_keys_| to alphasort.
978   std::string key = CacheKeyFromProfilePath(GetPathOfProfileAtIndex(index));
979   std::vector<std::string>::iterator key_it =
980       std::find(sorted_keys_.begin(), sorted_keys_.end(), key);
981   DCHECK(key_it != sorted_keys_.end());
982   sorted_keys_.erase(key_it);
983   sorted_keys_.insert(FindPositionForProfile(key, name), key);
984
985   content::NotificationService::current()->Notify(
986       chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
987       content::NotificationService::AllSources(),
988       content::NotificationService::NoDetails());
989 }
990
991 const gfx::Image* ProfileInfoCache::GetHighResAvatarOfProfileAtIndex(
992     size_t index) const {
993   int avatar_index = GetAvatarIconIndexOfProfileAtIndex(index);
994   std::string key = profiles::GetDefaultAvatarIconFileNameAtIndex(avatar_index);
995
996   if (!strcmp(key.c_str(), profiles::GetNoHighResAvatarFileName()))
997       return NULL;
998
999   base::FilePath image_path =
1000       profiles::GetPathOfHighResAvatarAtIndex(avatar_index);
1001   return LoadAvatarPictureFromPath(key, image_path);
1002 }
1003
1004 const gfx::Image* ProfileInfoCache::LoadAvatarPictureFromPath(
1005     const std::string& key,
1006     const base::FilePath& image_path) const {
1007   // If the picture is already loaded then use it.
1008   if (cached_avatar_images_.count(key)) {
1009     if (cached_avatar_images_[key]->IsEmpty())
1010       return NULL;
1011     return cached_avatar_images_[key];
1012   }
1013
1014   // If the picture is already being loaded then don't try loading it again.
1015   if (cached_avatar_images_loading_[key])
1016     return NULL;
1017   cached_avatar_images_loading_[key] = true;
1018
1019   gfx::Image** image = new gfx::Image*;
1020   BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE,
1021       base::Bind(&ReadBitmap, image_path, image),
1022       base::Bind(&ProfileInfoCache::OnAvatarPictureLoaded,
1023           const_cast<ProfileInfoCache*>(this)->AsWeakPtr(), key, image));
1024   return NULL;
1025 }
1026
1027 void ProfileInfoCache::OnAvatarPictureLoaded(const std::string& key,
1028                                              gfx::Image** image) const {
1029   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1030
1031   cached_avatar_images_loading_[key] = false;
1032   delete cached_avatar_images_[key];
1033
1034   if (*image) {
1035     cached_avatar_images_[key] = *image;
1036   } else {
1037     // Place an empty image in the cache to avoid reloading it again.
1038     cached_avatar_images_[key] = new gfx::Image();
1039   }
1040   delete image;
1041
1042   content::NotificationService::current()->Notify(
1043       chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
1044       content::NotificationService::AllSources(),
1045       content::NotificationService::NoDetails());
1046 }
1047
1048 void ProfileInfoCache::OnAvatarPictureSaved(
1049       const std::string& file_name,
1050       const base::FilePath& profile_path) {
1051   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1052
1053   content::NotificationService::current()->Notify(
1054       chrome::NOTIFICATION_PROFILE_CACHE_PICTURE_SAVED,
1055       content::NotificationService::AllSources(),
1056       content::NotificationService::NoDetails());
1057
1058   FOR_EACH_OBSERVER(ProfileInfoCacheObserver,
1059                     observer_list_,
1060                     OnProfileAvatarChanged(profile_path));
1061
1062   // Remove the file from the list of downloads in progress. Note that this list
1063   // only contains the high resolution avatars, and not the Gaia profile images.
1064   if (!avatar_images_downloads_in_progress_[file_name])
1065     return;
1066
1067   delete avatar_images_downloads_in_progress_[file_name];
1068   avatar_images_downloads_in_progress_[file_name] = NULL;
1069 }