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