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