1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/sync/glue/favicon_cache.h"
7 #include "base/message_loop/message_loop.h"
8 #include "base/metrics/histogram.h"
9 #include "chrome/browser/chrome_notification_types.h"
10 #include "chrome/browser/favicon/favicon_service.h"
11 #include "chrome/browser/favicon/favicon_service_factory.h"
12 #include "chrome/browser/history/history_notifications.h"
13 #include "chrome/browser/history/history_types.h"
14 #include "content/public/browser/notification_details.h"
15 #include "content/public/browser/notification_source.h"
16 #include "sync/api/time.h"
17 #include "sync/protocol/favicon_image_specifics.pb.h"
18 #include "sync/protocol/favicon_tracking_specifics.pb.h"
19 #include "sync/protocol/sync.pb.h"
20 #include "ui/gfx/favicon_size.h"
22 namespace browser_sync
{
24 // Synced favicon storage and tracking.
25 // Note: we don't use the favicon service for storing these because these
26 // favicons are not necessarily associated with any local navigation, and
27 // hence would not work with the current expiration logic. We have custom
28 // expiration logic based on visit time/bookmark status/etc.
29 // See crbug.com/122890.
30 struct SyncedFaviconInfo
{
31 explicit SyncedFaviconInfo(const GURL
& favicon_url
)
32 : favicon_url(favicon_url
),
34 received_local_update(false) {}
36 // The actual favicon data.
37 // TODO(zea): don't keep around the actual data for locally sourced
38 // favicons (UI can access those directly).
39 favicon_base::FaviconBitmapResult bitmap_data
[NUM_SIZES
];
40 // The URL this favicon was loaded from.
41 const GURL favicon_url
;
42 // Is the favicon for a bookmarked page?
44 // The last time a tab needed this favicon.
45 // Note: Do not modify this directly! It should only be modified via
46 // UpdateFaviconVisitTime(..).
47 base::Time last_visit_time
;
48 // Whether we've received a local update for this favicon since starting up.
49 bool received_local_update
;
52 DISALLOW_COPY_AND_ASSIGN(SyncedFaviconInfo
);
55 // Information for handling local favicon updates. Used in
56 // OnFaviconDataAvailable.
57 struct LocalFaviconUpdateInfo
{
58 LocalFaviconUpdateInfo()
61 image_needs_rewrite(false),
66 bool image_needs_rewrite
;
67 SyncedFaviconInfo
* favicon_info
;
72 // Maximum number of favicons to keep in memory (0 means no limit).
73 const size_t kMaxFaviconsInMem
= 0;
75 // Maximum width/height resolution supported.
76 const int kMaxFaviconResolution
= 16;
78 // Returns a mask of the supported favicon types.
79 // TODO(zea): Supporting other favicons types will involve some work in the
80 // favicon service and navigation controller. See crbug.com/181068.
81 int SupportedFaviconTypes() { return favicon_base::FAVICON
; }
83 // Returns the appropriate IconSize to use for a given gfx::Size pixel
85 IconSize
GetIconSizeBinFromBitmapResult(const gfx::Size
& pixel_size
) {
87 (pixel_size
.width() > pixel_size
.height() ?
88 pixel_size
.width() : pixel_size
.height());
89 // TODO(zea): re-enable 64p and 32p resolutions once we support them.
92 else if (max_size
> 32)
94 else if (max_size
> 16)
100 // Helper for debug statements.
101 std::string
IconSizeToString(IconSize icon_size
) {
114 // Extract the favicon url from either of the favicon types.
115 GURL
GetFaviconURLFromSpecifics(const sync_pb::EntitySpecifics
& specifics
) {
116 if (specifics
.has_favicon_tracking())
117 return GURL(specifics
.favicon_tracking().favicon_url());
119 return GURL(specifics
.favicon_image().favicon_url());
122 // Convert protobuf image data into a FaviconBitmapResult.
123 favicon_base::FaviconBitmapResult
GetImageDataFromSpecifics(
124 const sync_pb::FaviconData
& favicon_data
) {
125 base::RefCountedString
* temp_string
=
126 new base::RefCountedString();
127 temp_string
->data() = favicon_data
.favicon();
128 favicon_base::FaviconBitmapResult bitmap_result
;
129 bitmap_result
.bitmap_data
= temp_string
;
130 bitmap_result
.pixel_size
.set_height(favicon_data
.height());
131 bitmap_result
.pixel_size
.set_width(favicon_data
.width());
132 return bitmap_result
;
135 // Convert a FaviconBitmapResult into protobuf image data.
136 void FillSpecificsWithImageData(
137 const favicon_base::FaviconBitmapResult
& bitmap_result
,
138 sync_pb::FaviconData
* favicon_data
) {
139 if (!bitmap_result
.bitmap_data
.get())
141 favicon_data
->set_height(bitmap_result
.pixel_size
.height());
142 favicon_data
->set_width(bitmap_result
.pixel_size
.width());
143 favicon_data
->set_favicon(bitmap_result
.bitmap_data
->front(),
144 bitmap_result
.bitmap_data
->size());
147 // Build a FaviconImageSpecifics from a SyncedFaviconInfo.
148 void BuildImageSpecifics(
149 const SyncedFaviconInfo
* favicon_info
,
150 sync_pb::FaviconImageSpecifics
* image_specifics
) {
151 image_specifics
->set_favicon_url(favicon_info
->favicon_url
.spec());
152 FillSpecificsWithImageData(favicon_info
->bitmap_data
[SIZE_16
],
153 image_specifics
->mutable_favicon_web());
154 // TODO(zea): bring this back if we can handle the load.
155 // FillSpecificsWithImageData(favicon_info->bitmap_data[SIZE_32],
156 // image_specifics->mutable_favicon_web_32());
157 // FillSpecificsWithImageData(favicon_info->bitmap_data[SIZE_64],
158 // image_specifics->mutable_favicon_touch_64());
161 // Build a FaviconTrackingSpecifics from a SyncedFaviconInfo.
162 void BuildTrackingSpecifics(
163 const SyncedFaviconInfo
* favicon_info
,
164 sync_pb::FaviconTrackingSpecifics
* tracking_specifics
) {
165 tracking_specifics
->set_favicon_url(favicon_info
->favicon_url
.spec());
166 tracking_specifics
->set_last_visit_time_ms(
167 syncer::TimeToProtoTime(favicon_info
->last_visit_time
));
168 tracking_specifics
->set_is_bookmarked(favicon_info
->is_bookmarked
);
171 // Updates |favicon_info| with the image data in |bitmap_result|.
172 bool UpdateFaviconFromBitmapResult(
173 const favicon_base::FaviconBitmapResult
& bitmap_result
,
174 SyncedFaviconInfo
* favicon_info
) {
175 DCHECK_EQ(favicon_info
->favicon_url
, bitmap_result
.icon_url
);
176 if (!bitmap_result
.is_valid()) {
177 DVLOG(1) << "Received invalid favicon at " << bitmap_result
.icon_url
.spec();
181 IconSize icon_size
= GetIconSizeBinFromBitmapResult(
182 bitmap_result
.pixel_size
);
183 if (icon_size
== SIZE_INVALID
) {
184 DVLOG(1) << "Ignoring unsupported resolution "
185 << bitmap_result
.pixel_size
.height() << "x"
186 << bitmap_result
.pixel_size
.width();
188 } else if (!favicon_info
->bitmap_data
[icon_size
].bitmap_data
.get() ||
189 !favicon_info
->received_local_update
) {
190 DVLOG(1) << "Storing " << IconSizeToString(icon_size
) << "p"
191 << " favicon for " << favicon_info
->favicon_url
.spec()
192 << " with size " << bitmap_result
.bitmap_data
->size()
194 favicon_info
->bitmap_data
[icon_size
] = bitmap_result
;
195 favicon_info
->received_local_update
= true;
198 // We only allow updating the image data once per restart.
199 DVLOG(2) << "Ignoring local update for " << bitmap_result
.icon_url
.spec();
204 bool FaviconInfoHasImages(const SyncedFaviconInfo
& favicon_info
) {
205 return favicon_info
.bitmap_data
[SIZE_16
].bitmap_data
.get() ||
206 favicon_info
.bitmap_data
[SIZE_32
].bitmap_data
.get() ||
207 favicon_info
.bitmap_data
[SIZE_64
].bitmap_data
.get();
210 bool FaviconInfoHasTracking(const SyncedFaviconInfo
& favicon_info
) {
211 return !favicon_info
.last_visit_time
.is_null();
214 bool FaviconInfoHasValidTypeData(const SyncedFaviconInfo
& favicon_info
,
215 syncer::ModelType type
) {
216 if (type
== syncer::FAVICON_IMAGES
)
217 return FaviconInfoHasImages(favicon_info
);
218 else if (type
== syncer::FAVICON_TRACKING
)
219 return FaviconInfoHasTracking(favicon_info
);
226 FaviconCache::FaviconCache(Profile
* profile
, int max_sync_favicon_limit
)
228 max_sync_favicon_limit_(max_sync_favicon_limit
),
229 weak_ptr_factory_(this) {
230 notification_registrar_
.Add(this,
231 chrome::NOTIFICATION_HISTORY_URLS_DELETED
,
232 content::Source
<Profile
>(profile_
));
233 DVLOG(1) << "Setting favicon limit to " << max_sync_favicon_limit
;
236 FaviconCache::~FaviconCache() {}
238 syncer::SyncMergeResult
FaviconCache::MergeDataAndStartSyncing(
239 syncer::ModelType type
,
240 const syncer::SyncDataList
& initial_sync_data
,
241 scoped_ptr
<syncer::SyncChangeProcessor
> sync_processor
,
242 scoped_ptr
<syncer::SyncErrorFactory
> error_handler
) {
243 DCHECK(type
== syncer::FAVICON_IMAGES
|| type
== syncer::FAVICON_TRACKING
);
244 if (type
== syncer::FAVICON_IMAGES
)
245 favicon_images_sync_processor_
= sync_processor
.Pass();
247 favicon_tracking_sync_processor_
= sync_processor
.Pass();
249 syncer::SyncMergeResult
merge_result(type
);
250 merge_result
.set_num_items_before_association(synced_favicons_
.size());
251 std::set
<GURL
> unsynced_favicon_urls
;
252 for (FaviconMap::const_iterator iter
= synced_favicons_
.begin();
253 iter
!= synced_favicons_
.end(); ++iter
) {
254 if (FaviconInfoHasValidTypeData(*(iter
->second
), type
))
255 unsynced_favicon_urls
.insert(iter
->first
);
258 syncer::SyncChangeList local_changes
;
259 for (syncer::SyncDataList::const_iterator iter
= initial_sync_data
.begin();
260 iter
!= initial_sync_data
.end(); ++iter
) {
261 GURL remote_url
= GetFaviconURLFromSpecifics(iter
->GetSpecifics());
262 GURL favicon_url
= GetLocalFaviconFromSyncedData(*iter
);
263 if (favicon_url
.is_valid()) {
264 unsynced_favicon_urls
.erase(favicon_url
);
265 MergeSyncFavicon(*iter
, &local_changes
);
266 merge_result
.set_num_items_modified(
267 merge_result
.num_items_modified() + 1);
269 AddLocalFaviconFromSyncedData(*iter
);
270 merge_result
.set_num_items_added(merge_result
.num_items_added() + 1);
274 // Rather than trigger a bunch of deletions when we set up sync, we drop
275 // local favicons. Those pages that are currently open are likely to result in
276 // loading new favicons/refreshing old favicons anyways, at which point
277 // they'll be re-added and the appropriate synced favicons will be evicted.
278 // TODO(zea): implement a smarter ordering of the which favicons to drop.
279 int available_favicons
= max_sync_favicon_limit_
- initial_sync_data
.size();
280 UMA_HISTOGRAM_BOOLEAN("Sync.FaviconsAvailableAtMerge",
281 available_favicons
> 0);
282 for (std::set
<GURL
>::const_iterator iter
= unsynced_favicon_urls
.begin();
283 iter
!= unsynced_favicon_urls
.end(); ++iter
) {
284 if (available_favicons
> 0) {
285 local_changes
.push_back(
286 syncer::SyncChange(FROM_HERE
,
287 syncer::SyncChange::ACTION_ADD
,
288 CreateSyncDataFromLocalFavicon(type
, *iter
)));
289 available_favicons
--;
291 FaviconMap::iterator favicon_iter
= synced_favicons_
.find(*iter
);
292 DVLOG(1) << "Dropping local favicon "
293 << favicon_iter
->second
->favicon_url
.spec();
294 DropPartialFavicon(favicon_iter
, type
);
295 merge_result
.set_num_items_deleted(merge_result
.num_items_deleted() + 1);
298 UMA_HISTOGRAM_COUNTS_10000("Sync.FaviconCount", synced_favicons_
.size());
299 merge_result
.set_num_items_after_association(synced_favicons_
.size());
301 if (type
== syncer::FAVICON_IMAGES
) {
302 favicon_images_sync_processor_
->ProcessSyncChanges(FROM_HERE
,
305 favicon_tracking_sync_processor_
->ProcessSyncChanges(FROM_HERE
,
311 void FaviconCache::StopSyncing(syncer::ModelType type
) {
312 favicon_images_sync_processor_
.reset();
313 favicon_tracking_sync_processor_
.reset();
314 cancelable_task_tracker_
.TryCancelAll();
315 page_task_map_
.clear();
318 syncer::SyncDataList
FaviconCache::GetAllSyncData(syncer::ModelType type
)
320 syncer::SyncDataList data_list
;
321 for (FaviconMap::const_iterator iter
= synced_favicons_
.begin();
322 iter
!= synced_favicons_
.end(); ++iter
) {
323 if ((type
== syncer::FAVICON_IMAGES
&&
324 FaviconInfoHasImages(*iter
->second
)) ||
325 (type
== syncer::FAVICON_TRACKING
&&
326 FaviconInfoHasTracking(*iter
->second
))) {
327 data_list
.push_back(CreateSyncDataFromLocalFavicon(type
, iter
->first
));
333 syncer::SyncError
FaviconCache::ProcessSyncChanges(
334 const tracked_objects::Location
& from_here
,
335 const syncer::SyncChangeList
& change_list
) {
336 if (!favicon_images_sync_processor_
.get() ||
337 !favicon_tracking_sync_processor_
.get()) {
338 return syncer::SyncError(FROM_HERE
,
339 syncer::SyncError::DATATYPE_ERROR
,
340 "One or both favicon types disabled.",
341 change_list
[0].sync_data().GetDataType());
344 syncer::SyncChangeList new_changes
;
345 syncer::SyncError error
;
346 syncer::ModelType type
= syncer::UNSPECIFIED
;
347 for (syncer::SyncChangeList::const_iterator iter
= change_list
.begin();
348 iter
!= change_list
.end(); ++iter
) {
349 type
= iter
->sync_data().GetDataType();
350 DCHECK(type
== syncer::FAVICON_IMAGES
|| type
== syncer::FAVICON_TRACKING
);
352 GetFaviconURLFromSpecifics(iter
->sync_data().GetSpecifics());
353 if (!favicon_url
.is_valid()) {
354 error
.Reset(FROM_HERE
, "Received invalid favicon url.", type
);
357 FaviconMap::iterator favicon_iter
= synced_favicons_
.find(favicon_url
);
358 if (iter
->change_type() == syncer::SyncChange::ACTION_DELETE
) {
359 if (favicon_iter
== synced_favicons_
.end()) {
360 // Two clients might wind up deleting different parts of the same
361 // favicon, so ignore this.
364 DVLOG(1) << "Deleting favicon at " << favicon_url
.spec();
365 // If we only have partial data for the favicon (which implies orphaned
366 // nodes), delete the local favicon only if the type corresponds to the
367 // partial data we have. If we do have orphaned nodes, we rely on the
368 // expiration logic to remove them eventually.
369 DropPartialFavicon(favicon_iter
, type
);
371 } else if (iter
->change_type() == syncer::SyncChange::ACTION_UPDATE
||
372 iter
->change_type() == syncer::SyncChange::ACTION_ADD
) {
373 // Adds and updates are treated the same due to the lack of strong
374 // consistency (it's possible we'll receive an update for a tracking info
375 // before we've received the add for the image, and should handle both
377 if (favicon_iter
== synced_favicons_
.end()) {
378 DVLOG(1) << "Adding favicon at " << favicon_url
.spec();
379 AddLocalFaviconFromSyncedData(iter
->sync_data());
381 DVLOG(1) << "Updating favicon at " << favicon_url
.spec();
382 MergeSyncFavicon(iter
->sync_data(), &new_changes
);
385 error
.Reset(FROM_HERE
, "Invalid action received.", type
);
390 // Note: we deliberately do not expire favicons here. If we received new
391 // favicons and are now over the limit, the next local favicon change will
392 // trigger the necessary expiration.
393 if (!error
.IsSet() && !new_changes
.empty()) {
394 if (type
== syncer::FAVICON_IMAGES
) {
395 favicon_images_sync_processor_
->ProcessSyncChanges(FROM_HERE
,
398 favicon_tracking_sync_processor_
->ProcessSyncChanges(FROM_HERE
,
406 void FaviconCache::OnPageFaviconUpdated(const GURL
& page_url
) {
407 DCHECK(page_url
.is_valid());
409 // If a favicon load is already happening for this url, let it finish.
410 if (page_task_map_
.find(page_url
) != page_task_map_
.end())
413 PageFaviconMap::const_iterator url_iter
= page_favicon_map_
.find(page_url
);
414 if (url_iter
!= page_favicon_map_
.end()) {
415 FaviconMap::const_iterator icon_iter
=
416 synced_favicons_
.find(url_iter
->second
);
417 // TODO(zea): consider what to do when only a subset of supported
418 // resolutions are available.
419 if (icon_iter
!= synced_favicons_
.end() &&
420 icon_iter
->second
->bitmap_data
[SIZE_16
].bitmap_data
.get()) {
421 DVLOG(2) << "Using cached favicon url for " << page_url
.spec()
422 << ": " << icon_iter
->second
->favicon_url
.spec();
423 UpdateFaviconVisitTime(icon_iter
->second
->favicon_url
, base::Time::Now());
424 UpdateSyncState(icon_iter
->second
->favicon_url
,
425 syncer::SyncChange::ACTION_INVALID
,
426 syncer::SyncChange::ACTION_UPDATE
);
431 DVLOG(1) << "Triggering favicon load for url " << page_url
.spec();
434 page_task_map_
[page_url
] = 0; // For testing only.
437 FaviconService
* favicon_service
=
438 FaviconServiceFactory::GetForProfile(profile_
, Profile::EXPLICIT_ACCESS
);
439 if (!favicon_service
)
441 // TODO(zea): This appears to only fetch one favicon (best match based on
442 // desired_size_in_dip). Figure out a way to fetch all favicons we support.
443 // See crbug.com/181068.
444 base::CancelableTaskTracker::TaskId id
= favicon_service
->GetFaviconForURL(
445 FaviconService::FaviconForURLParams(
446 page_url
, SupportedFaviconTypes(), kMaxFaviconResolution
),
447 base::Bind(&FaviconCache::OnFaviconDataAvailable
,
448 weak_ptr_factory_
.GetWeakPtr(),
450 &cancelable_task_tracker_
);
451 page_task_map_
[page_url
] = id
;
454 void FaviconCache::OnFaviconVisited(const GURL
& page_url
,
455 const GURL
& favicon_url
) {
456 DCHECK(page_url
.is_valid());
457 if (!favicon_url
.is_valid() ||
458 synced_favicons_
.find(favicon_url
) == synced_favicons_
.end()) {
459 // TODO(zea): consider triggering a favicon load if we have some but not
460 // all desired resolutions?
461 OnPageFaviconUpdated(page_url
);
465 DVLOG(1) << "Associating " << page_url
.spec() << " with favicon at "
466 << favicon_url
.spec() << " and marking visited.";
467 page_favicon_map_
[page_url
] = favicon_url
;
468 bool had_tracking
= FaviconInfoHasTracking(
469 *synced_favicons_
.find(favicon_url
)->second
);
470 UpdateFaviconVisitTime(favicon_url
, base::Time::Now());
472 UpdateSyncState(favicon_url
,
473 syncer::SyncChange::ACTION_INVALID
,
475 syncer::SyncChange::ACTION_UPDATE
:
476 syncer::SyncChange::ACTION_ADD
));
479 bool FaviconCache::GetSyncedFaviconForFaviconURL(
480 const GURL
& favicon_url
,
481 scoped_refptr
<base::RefCountedMemory
>* favicon_png
) const {
482 if (!favicon_url
.is_valid())
484 FaviconMap::const_iterator iter
= synced_favicons_
.find(favicon_url
);
486 UMA_HISTOGRAM_BOOLEAN("Sync.FaviconCacheLookupSucceeded",
487 iter
!= synced_favicons_
.end());
488 if (iter
== synced_favicons_
.end())
491 // TODO(zea): support getting other resolutions.
492 if (!iter
->second
->bitmap_data
[SIZE_16
].bitmap_data
.get())
495 *favicon_png
= iter
->second
->bitmap_data
[SIZE_16
].bitmap_data
;
499 bool FaviconCache::GetSyncedFaviconForPageURL(
500 const GURL
& page_url
,
501 scoped_refptr
<base::RefCountedMemory
>* favicon_png
) const {
502 if (!page_url
.is_valid())
504 PageFaviconMap::const_iterator iter
= page_favicon_map_
.find(page_url
);
506 if (iter
== page_favicon_map_
.end())
509 return GetSyncedFaviconForFaviconURL(iter
->second
, favicon_png
);
512 void FaviconCache::OnReceivedSyncFavicon(const GURL
& page_url
,
513 const GURL
& icon_url
,
514 const std::string
& icon_bytes
,
515 int64 visit_time_ms
) {
516 if (!icon_url
.is_valid() || !page_url
.is_valid() || icon_url
.SchemeIs("data"))
518 DVLOG(1) << "Associating " << page_url
.spec() << " with favicon at "
520 page_favicon_map_
[page_url
] = icon_url
;
522 // If there is no actual image, it means there either is no synced
523 // favicon, or it's on its way (race condition).
524 // TODO(zea): potentially trigger a favicon web download here (delayed?).
525 if (icon_bytes
.size() == 0)
528 // Post a task to do the actual association because this method may have been
529 // called while in a transaction.
530 base::MessageLoop::current()->PostTask(
532 base::Bind(&FaviconCache::OnReceivedSyncFaviconImpl
,
533 weak_ptr_factory_
.GetWeakPtr(),
539 void FaviconCache::OnReceivedSyncFaviconImpl(
540 const GURL
& icon_url
,
541 const std::string
& icon_bytes
,
542 int64 visit_time_ms
) {
543 // If this favicon is already synced, do nothing else.
544 if (synced_favicons_
.find(icon_url
) != synced_favicons_
.end())
547 // Don't add any more favicons once we hit our in memory limit.
548 // TODO(zea): UMA this.
549 if (kMaxFaviconsInMem
!= 0 && synced_favicons_
.size() > kMaxFaviconsInMem
)
552 SyncedFaviconInfo
* favicon_info
= GetFaviconInfo(icon_url
);
554 return; // We reached the in-memory limit.
555 base::RefCountedString
* temp_string
= new base::RefCountedString();
556 temp_string
->data() = icon_bytes
;
557 favicon_info
->bitmap_data
[SIZE_16
].bitmap_data
= temp_string
;
558 // We assume legacy favicons are 16x16.
559 favicon_info
->bitmap_data
[SIZE_16
].pixel_size
.set_width(16);
560 favicon_info
->bitmap_data
[SIZE_16
].pixel_size
.set_height(16);
561 bool added_tracking
= !FaviconInfoHasTracking(*favicon_info
);
562 UpdateFaviconVisitTime(icon_url
,
563 syncer::ProtoTimeToTime(visit_time_ms
));
565 UpdateSyncState(icon_url
,
566 syncer::SyncChange::ACTION_ADD
,
568 syncer::SyncChange::ACTION_ADD
:
569 syncer::SyncChange::ACTION_UPDATE
));
572 void FaviconCache::Observe(int type
,
573 const content::NotificationSource
& source
,
574 const content::NotificationDetails
& details
) {
575 DCHECK_EQ(type
, chrome::NOTIFICATION_HISTORY_URLS_DELETED
);
577 content::Details
<history::URLsDeletedDetails
> deleted_details(details
);
579 // We only care about actual user (or sync) deletions.
580 if (deleted_details
->archived
)
583 if (!deleted_details
->all_history
) {
584 DeleteSyncedFavicons(deleted_details
->favicon_urls
);
588 // All history was cleared: just delete all favicons.
589 DVLOG(1) << "History clear detected, deleting all synced favicons.";
590 syncer::SyncChangeList image_deletions
, tracking_deletions
;
591 while (!synced_favicons_
.empty()) {
592 DeleteSyncedFavicon(synced_favicons_
.begin(),
594 &tracking_deletions
);
597 if (favicon_images_sync_processor_
.get()) {
598 favicon_images_sync_processor_
->ProcessSyncChanges(FROM_HERE
,
601 if (favicon_tracking_sync_processor_
.get()) {
602 favicon_tracking_sync_processor_
->ProcessSyncChanges(FROM_HERE
,
607 bool FaviconCache::FaviconRecencyFunctor::operator()(
608 const linked_ptr
<SyncedFaviconInfo
>& lhs
,
609 const linked_ptr
<SyncedFaviconInfo
>& rhs
) const {
610 // TODO(zea): incorporate bookmarked status here once we care about it.
611 if (lhs
->last_visit_time
< rhs
->last_visit_time
)
613 else if (lhs
->last_visit_time
== rhs
->last_visit_time
)
614 return lhs
->favicon_url
.spec() < rhs
->favicon_url
.spec();
618 void FaviconCache::OnFaviconDataAvailable(
619 const GURL
& page_url
,
620 const std::vector
<favicon_base::FaviconBitmapResult
>& bitmap_results
) {
621 PageTaskMap::iterator page_iter
= page_task_map_
.find(page_url
);
622 if (page_iter
== page_task_map_
.end())
624 page_task_map_
.erase(page_iter
);
626 if (bitmap_results
.size() == 0) {
627 // Either the favicon isn't loaded yet or there is no valid favicon.
628 // We already cleared the task id, so just return.
629 DVLOG(1) << "Favicon load failed for page " << page_url
.spec();
633 base::Time now
= base::Time::Now();
634 std::map
<GURL
, LocalFaviconUpdateInfo
> favicon_updates
;
635 for (size_t i
= 0; i
< bitmap_results
.size(); ++i
) {
636 const favicon_base::FaviconBitmapResult
& bitmap_result
= bitmap_results
[i
];
637 GURL favicon_url
= bitmap_result
.icon_url
;
638 if (!favicon_url
.is_valid() || favicon_url
.SchemeIs("data"))
639 continue; // Can happen if the page is still loading.
641 SyncedFaviconInfo
* favicon_info
= GetFaviconInfo(favicon_url
);
643 return; // We reached the in-memory limit.
645 favicon_updates
[favicon_url
].new_image
|=
646 !FaviconInfoHasImages(*favicon_info
);
647 favicon_updates
[favicon_url
].new_tracking
|=
648 !FaviconInfoHasTracking(*favicon_info
);
649 favicon_updates
[favicon_url
].image_needs_rewrite
|=
650 UpdateFaviconFromBitmapResult(bitmap_result
, favicon_info
);
651 favicon_updates
[favicon_url
].favicon_info
= favicon_info
;
654 for (std::map
<GURL
, LocalFaviconUpdateInfo
>::const_iterator
655 iter
= favicon_updates
.begin(); iter
!= favicon_updates
.end();
657 SyncedFaviconInfo
* favicon_info
= iter
->second
.favicon_info
;
658 const GURL
& favicon_url
= favicon_info
->favicon_url
;
660 // TODO(zea): support multiple favicon urls per page.
661 page_favicon_map_
[page_url
] = favicon_url
;
663 if (!favicon_info
->last_visit_time
.is_null()) {
664 UMA_HISTOGRAM_COUNTS_10000(
665 "Sync.FaviconVisitPeriod",
666 (now
- favicon_info
->last_visit_time
).InHours());
668 favicon_info
->received_local_update
= true;
669 UpdateFaviconVisitTime(favicon_url
, now
);
671 syncer::SyncChange::SyncChangeType image_change
=
672 syncer::SyncChange::ACTION_INVALID
;
673 if (iter
->second
.new_image
)
674 image_change
= syncer::SyncChange::ACTION_ADD
;
675 else if (iter
->second
.image_needs_rewrite
)
676 image_change
= syncer::SyncChange::ACTION_UPDATE
;
677 syncer::SyncChange::SyncChangeType tracking_change
=
678 syncer::SyncChange::ACTION_UPDATE
;
679 if (iter
->second
.new_tracking
)
680 tracking_change
= syncer::SyncChange::ACTION_ADD
;
681 UpdateSyncState(favicon_url
, image_change
, tracking_change
);
685 void FaviconCache::UpdateSyncState(
686 const GURL
& icon_url
,
687 syncer::SyncChange::SyncChangeType image_change_type
,
688 syncer::SyncChange::SyncChangeType tracking_change_type
) {
689 DCHECK(icon_url
.is_valid());
690 // It's possible that we'll receive a favicon update before both types
691 // have finished setting up. In that case ignore the update.
692 // TODO(zea): consider tracking these skipped updates somehow?
693 if (!favicon_images_sync_processor_
.get() ||
694 !favicon_tracking_sync_processor_
.get()) {
698 FaviconMap::const_iterator iter
= synced_favicons_
.find(icon_url
);
699 DCHECK(iter
!= synced_favicons_
.end());
700 const SyncedFaviconInfo
* favicon_info
= iter
->second
.get();
702 syncer::SyncChangeList image_changes
;
703 syncer::SyncChangeList tracking_changes
;
704 if (image_change_type
!= syncer::SyncChange::ACTION_INVALID
) {
705 sync_pb::EntitySpecifics new_specifics
;
706 sync_pb::FaviconImageSpecifics
* image_specifics
=
707 new_specifics
.mutable_favicon_image();
708 BuildImageSpecifics(favicon_info
, image_specifics
);
710 image_changes
.push_back(
711 syncer::SyncChange(FROM_HERE
,
713 syncer::SyncData::CreateLocalData(
718 if (tracking_change_type
!= syncer::SyncChange::ACTION_INVALID
) {
719 sync_pb::EntitySpecifics new_specifics
;
720 sync_pb::FaviconTrackingSpecifics
* tracking_specifics
=
721 new_specifics
.mutable_favicon_tracking();
722 BuildTrackingSpecifics(favicon_info
, tracking_specifics
);
724 tracking_changes
.push_back(
725 syncer::SyncChange(FROM_HERE
,
726 tracking_change_type
,
727 syncer::SyncData::CreateLocalData(
732 ExpireFaviconsIfNecessary(&image_changes
, &tracking_changes
);
733 if (!image_changes
.empty()) {
734 favicon_images_sync_processor_
->ProcessSyncChanges(FROM_HERE
,
737 if (!tracking_changes
.empty()) {
738 favicon_tracking_sync_processor_
->ProcessSyncChanges(FROM_HERE
,
743 SyncedFaviconInfo
* FaviconCache::GetFaviconInfo(
744 const GURL
& icon_url
) {
745 DCHECK_EQ(recent_favicons_
.size(), synced_favicons_
.size());
746 if (synced_favicons_
.count(icon_url
) != 0)
747 return synced_favicons_
[icon_url
].get();
749 // TODO(zea): implement in-memory eviction.
750 DVLOG(1) << "Adding favicon info for " << icon_url
.spec();
751 SyncedFaviconInfo
* favicon_info
= new SyncedFaviconInfo(icon_url
);
752 synced_favicons_
[icon_url
] = make_linked_ptr(favicon_info
);
753 recent_favicons_
.insert(synced_favicons_
[icon_url
]);
754 DCHECK_EQ(recent_favicons_
.size(), synced_favicons_
.size());
758 void FaviconCache::UpdateFaviconVisitTime(const GURL
& icon_url
,
760 DCHECK_EQ(recent_favicons_
.size(), synced_favicons_
.size());
761 FaviconMap::const_iterator iter
= synced_favicons_
.find(icon_url
);
762 DCHECK(iter
!= synced_favicons_
.end());
763 if (iter
->second
->last_visit_time
>= time
)
765 // Erase, update the time, then re-insert to maintain ordering.
766 recent_favicons_
.erase(iter
->second
);
767 DVLOG(1) << "Updating " << icon_url
.spec() << " visit time to "
768 << syncer::GetTimeDebugString(time
);
769 iter
->second
->last_visit_time
= time
;
770 recent_favicons_
.insert(iter
->second
);
773 for (RecencySet::const_iterator iter
= recent_favicons_
.begin();
774 iter
!= recent_favicons_
.end(); ++iter
) {
775 DVLOG(2) << "Favicon " << iter
->get()->favicon_url
.spec() << ": "
776 << syncer::GetTimeDebugString(iter
->get()->last_visit_time
);
779 DCHECK_EQ(recent_favicons_
.size(), synced_favicons_
.size());
782 void FaviconCache::ExpireFaviconsIfNecessary(
783 syncer::SyncChangeList
* image_changes
,
784 syncer::SyncChangeList
* tracking_changes
) {
785 DCHECK_EQ(recent_favicons_
.size(), synced_favicons_
.size());
786 // TODO(zea): once we have in-memory eviction, we'll need to track sync
787 // favicon count separately from the synced_favicons_/recent_favicons_.
789 // Iterate until we've removed the necessary amount. |recent_favicons_| is
790 // already in recency order, so just start from the beginning.
791 // TODO(zea): to reduce thrashing, consider removing more than the minimum.
792 while (recent_favicons_
.size() > max_sync_favicon_limit_
) {
793 linked_ptr
<SyncedFaviconInfo
> candidate
= *recent_favicons_
.begin();
794 DVLOG(1) << "Expiring favicon " << candidate
->favicon_url
.spec();
795 DeleteSyncedFavicon(synced_favicons_
.find(candidate
->favicon_url
),
799 DCHECK_EQ(recent_favicons_
.size(), synced_favicons_
.size());
802 GURL
FaviconCache::GetLocalFaviconFromSyncedData(
803 const syncer::SyncData
& sync_favicon
) const {
804 syncer::ModelType type
= sync_favicon
.GetDataType();
805 DCHECK(type
== syncer::FAVICON_IMAGES
|| type
== syncer::FAVICON_TRACKING
);
806 GURL favicon_url
= GetFaviconURLFromSpecifics(sync_favicon
.GetSpecifics());
807 return (synced_favicons_
.count(favicon_url
) > 0 ? favicon_url
: GURL());
810 void FaviconCache::MergeSyncFavicon(const syncer::SyncData
& sync_favicon
,
811 syncer::SyncChangeList
* sync_changes
) {
812 syncer::ModelType type
= sync_favicon
.GetDataType();
813 DCHECK(type
== syncer::FAVICON_IMAGES
|| type
== syncer::FAVICON_TRACKING
);
814 sync_pb::EntitySpecifics new_specifics
;
815 GURL favicon_url
= GetFaviconURLFromSpecifics(sync_favicon
.GetSpecifics());
816 FaviconMap::const_iterator iter
= synced_favicons_
.find(favicon_url
);
817 DCHECK(iter
!= synced_favicons_
.end());
818 SyncedFaviconInfo
* favicon_info
= iter
->second
.get();
819 if (type
== syncer::FAVICON_IMAGES
) {
820 sync_pb::FaviconImageSpecifics image_specifics
=
821 sync_favicon
.GetSpecifics().favicon_image();
823 // Remote image data always clobbers local image data.
824 bool needs_update
= false;
825 if (image_specifics
.has_favicon_web()) {
826 favicon_info
->bitmap_data
[SIZE_16
] = GetImageDataFromSpecifics(
827 image_specifics
.favicon_web());
828 } else if (favicon_info
->bitmap_data
[SIZE_16
].bitmap_data
.get()) {
831 if (image_specifics
.has_favicon_web_32()) {
832 favicon_info
->bitmap_data
[SIZE_32
] = GetImageDataFromSpecifics(
833 image_specifics
.favicon_web_32());
834 } else if (favicon_info
->bitmap_data
[SIZE_32
].bitmap_data
.get()) {
837 if (image_specifics
.has_favicon_touch_64()) {
838 favicon_info
->bitmap_data
[SIZE_64
] = GetImageDataFromSpecifics(
839 image_specifics
.favicon_touch_64());
840 } else if (favicon_info
->bitmap_data
[SIZE_64
].bitmap_data
.get()) {
845 BuildImageSpecifics(favicon_info
, new_specifics
.mutable_favicon_image());
847 sync_pb::FaviconTrackingSpecifics tracking_specifics
=
848 sync_favicon
.GetSpecifics().favicon_tracking();
850 // Tracking data is merged, such that bookmark data is the logical OR
851 // of the two, and last visit time is the most recent.
853 base::Time last_visit
= syncer::ProtoTimeToTime(
854 tracking_specifics
.last_visit_time_ms());
855 // Due to crbug.com/258196, there are tracking nodes out there with
856 // null visit times. If this is one of those, artificially make it a valid
857 // visit time, so we know the node exists and update it properly on the next
859 if (last_visit
.is_null())
860 last_visit
= last_visit
+ base::TimeDelta::FromMilliseconds(1);
861 UpdateFaviconVisitTime(favicon_url
, last_visit
);
862 favicon_info
->is_bookmarked
= (favicon_info
->is_bookmarked
||
863 tracking_specifics
.is_bookmarked());
865 if (syncer::TimeToProtoTime(favicon_info
->last_visit_time
) !=
866 tracking_specifics
.last_visit_time_ms() ||
867 favicon_info
->is_bookmarked
!= tracking_specifics
.is_bookmarked()) {
868 BuildTrackingSpecifics(favicon_info
,
869 new_specifics
.mutable_favicon_tracking());
871 DCHECK(!favicon_info
->last_visit_time
.is_null());
874 if (new_specifics
.has_favicon_image() ||
875 new_specifics
.has_favicon_tracking()) {
876 sync_changes
->push_back(syncer::SyncChange(
878 syncer::SyncChange::ACTION_UPDATE
,
879 syncer::SyncData::CreateLocalData(favicon_url
.spec(),
885 void FaviconCache::AddLocalFaviconFromSyncedData(
886 const syncer::SyncData
& sync_favicon
) {
887 syncer::ModelType type
= sync_favicon
.GetDataType();
888 DCHECK(type
== syncer::FAVICON_IMAGES
|| type
== syncer::FAVICON_TRACKING
);
889 if (type
== syncer::FAVICON_IMAGES
) {
890 sync_pb::FaviconImageSpecifics image_specifics
=
891 sync_favicon
.GetSpecifics().favicon_image();
892 GURL favicon_url
= GURL(image_specifics
.favicon_url());
893 DCHECK(favicon_url
.is_valid());
894 DCHECK(!synced_favicons_
.count(favicon_url
));
896 SyncedFaviconInfo
* favicon_info
= GetFaviconInfo(favicon_url
);
898 return; // We reached the in-memory limit.
899 if (image_specifics
.has_favicon_web()) {
900 favicon_info
->bitmap_data
[SIZE_16
] = GetImageDataFromSpecifics(
901 image_specifics
.favicon_web());
903 if (image_specifics
.has_favicon_web_32()) {
904 favicon_info
->bitmap_data
[SIZE_32
] = GetImageDataFromSpecifics(
905 image_specifics
.favicon_web_32());
907 if (image_specifics
.has_favicon_touch_64()) {
908 favicon_info
->bitmap_data
[SIZE_64
] = GetImageDataFromSpecifics(
909 image_specifics
.favicon_touch_64());
912 sync_pb::FaviconTrackingSpecifics tracking_specifics
=
913 sync_favicon
.GetSpecifics().favicon_tracking();
914 GURL favicon_url
= GURL(tracking_specifics
.favicon_url());
915 DCHECK(favicon_url
.is_valid());
916 DCHECK(!synced_favicons_
.count(favicon_url
));
918 SyncedFaviconInfo
* favicon_info
= GetFaviconInfo(favicon_url
);
920 return; // We reached the in-memory limit.
921 base::Time last_visit
= syncer::ProtoTimeToTime(
922 tracking_specifics
.last_visit_time_ms());
923 // Due to crbug.com/258196, there are tracking nodes out there with
924 // null visit times. If this is one of those, artificially make it a valid
925 // visit time, so we know the node exists and update it properly on the next
927 if (last_visit
.is_null())
928 last_visit
= last_visit
+ base::TimeDelta::FromMilliseconds(1);
929 UpdateFaviconVisitTime(favicon_url
, last_visit
);
930 favicon_info
->is_bookmarked
= tracking_specifics
.is_bookmarked();
931 DCHECK(!favicon_info
->last_visit_time
.is_null());
935 syncer::SyncData
FaviconCache::CreateSyncDataFromLocalFavicon(
936 syncer::ModelType type
,
937 const GURL
& favicon_url
) const {
938 DCHECK(type
== syncer::FAVICON_IMAGES
|| type
== syncer::FAVICON_TRACKING
);
939 DCHECK(favicon_url
.is_valid());
940 FaviconMap::const_iterator iter
= synced_favicons_
.find(favicon_url
);
941 DCHECK(iter
!= synced_favicons_
.end());
942 SyncedFaviconInfo
* favicon_info
= iter
->second
.get();
944 syncer::SyncData data
;
945 sync_pb::EntitySpecifics specifics
;
946 if (type
== syncer::FAVICON_IMAGES
) {
947 sync_pb::FaviconImageSpecifics
* image_specifics
=
948 specifics
.mutable_favicon_image();
949 BuildImageSpecifics(favicon_info
, image_specifics
);
951 sync_pb::FaviconTrackingSpecifics
* tracking_specifics
=
952 specifics
.mutable_favicon_tracking();
953 BuildTrackingSpecifics(favicon_info
, tracking_specifics
);
955 data
= syncer::SyncData::CreateLocalData(favicon_url
.spec(),
961 void FaviconCache::DeleteSyncedFavicons(const std::set
<GURL
>& favicon_urls
) {
962 syncer::SyncChangeList image_deletions
, tracking_deletions
;
963 for (std::set
<GURL
>::const_iterator iter
= favicon_urls
.begin();
964 iter
!= favicon_urls
.end(); ++iter
) {
965 FaviconMap::iterator favicon_iter
= synced_favicons_
.find(*iter
);
966 if (favicon_iter
== synced_favicons_
.end())
968 DeleteSyncedFavicon(favicon_iter
,
970 &tracking_deletions
);
972 DVLOG(1) << "Deleting " << image_deletions
.size() << " synced favicons.";
973 if (favicon_images_sync_processor_
.get()) {
974 favicon_images_sync_processor_
->ProcessSyncChanges(FROM_HERE
,
977 if (favicon_tracking_sync_processor_
.get()) {
978 favicon_tracking_sync_processor_
->ProcessSyncChanges(FROM_HERE
,
983 void FaviconCache::DeleteSyncedFavicon(
984 FaviconMap::iterator favicon_iter
,
985 syncer::SyncChangeList
* image_changes
,
986 syncer::SyncChangeList
* tracking_changes
) {
987 linked_ptr
<SyncedFaviconInfo
> favicon_info
= favicon_iter
->second
;
988 if (FaviconInfoHasImages(*(favicon_iter
->second
))) {
989 DVLOG(1) << "Deleting image for "
990 << favicon_iter
->second
.get()->favicon_url
;
991 image_changes
->push_back(
992 syncer::SyncChange(FROM_HERE
,
993 syncer::SyncChange::ACTION_DELETE
,
994 syncer::SyncData::CreateLocalDelete(
995 favicon_info
->favicon_url
.spec(),
996 syncer::FAVICON_IMAGES
)));
998 if (FaviconInfoHasTracking(*(favicon_iter
->second
))) {
999 DVLOG(1) << "Deleting tracking for "
1000 << favicon_iter
->second
.get()->favicon_url
;
1001 tracking_changes
->push_back(
1002 syncer::SyncChange(FROM_HERE
,
1003 syncer::SyncChange::ACTION_DELETE
,
1004 syncer::SyncData::CreateLocalDelete(
1005 favicon_info
->favicon_url
.spec(),
1006 syncer::FAVICON_TRACKING
)));
1008 DropSyncedFavicon(favicon_iter
);
1011 void FaviconCache::DropSyncedFavicon(FaviconMap::iterator favicon_iter
) {
1012 DVLOG(1) << "Dropping favicon " << favicon_iter
->second
.get()->favicon_url
;
1013 recent_favicons_
.erase(favicon_iter
->second
);
1014 synced_favicons_
.erase(favicon_iter
);
1017 void FaviconCache::DropPartialFavicon(FaviconMap::iterator favicon_iter
,
1018 syncer::ModelType type
) {
1019 // If the type being dropped has no valid data, do nothing.
1020 if ((type
== syncer::FAVICON_TRACKING
&&
1021 !FaviconInfoHasTracking(*favicon_iter
->second
)) ||
1022 (type
== syncer::FAVICON_IMAGES
&&
1023 !FaviconInfoHasImages(*favicon_iter
->second
))) {
1027 // If the type being dropped is the only type with valid data, just delete
1028 // the favicon altogether.
1029 if ((type
== syncer::FAVICON_TRACKING
&&
1030 !FaviconInfoHasImages(*favicon_iter
->second
)) ||
1031 (type
== syncer::FAVICON_IMAGES
&&
1032 !FaviconInfoHasTracking(*favicon_iter
->second
))) {
1033 DropSyncedFavicon(favicon_iter
);
1037 if (type
== syncer::FAVICON_IMAGES
) {
1038 DVLOG(1) << "Dropping favicon image "
1039 << favicon_iter
->second
.get()->favicon_url
;
1040 for (int i
= 0; i
< NUM_SIZES
; ++i
) {
1041 favicon_iter
->second
->bitmap_data
[i
] =
1042 favicon_base::FaviconBitmapResult();
1044 DCHECK(!FaviconInfoHasImages(*favicon_iter
->second
));
1046 DCHECK_EQ(type
, syncer::FAVICON_TRACKING
);
1047 DVLOG(1) << "Dropping favicon tracking "
1048 << favicon_iter
->second
.get()->favicon_url
;
1049 recent_favicons_
.erase(favicon_iter
->second
);
1050 favicon_iter
->second
->last_visit_time
= base::Time();
1051 favicon_iter
->second
->is_bookmarked
= false;
1052 recent_favicons_
.insert(favicon_iter
->second
);
1053 DCHECK(!FaviconInfoHasTracking(*favicon_iter
->second
));
1057 size_t FaviconCache::NumFaviconsForTest() const {
1058 return synced_favicons_
.size();
1061 size_t FaviconCache::NumTasksForTest() const {
1062 return page_task_map_
.size();
1065 } // namespace browser_sync