Only grant permissions to new extensions from sync if they have the expected version
[chromium-blink-merge.git] / components / sync_driver / favicon_cache.cc
blob4b5d174eddc1e43bc62e9552f5f31df744bb4e29
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 "components/sync_driver/favicon_cache.h"
7 #include "base/location.h"
8 #include "base/metrics/histogram.h"
9 #include "base/single_thread_task_runner.h"
10 #include "base/thread_task_runner_handle.h"
11 #include "components/favicon/core/favicon_service.h"
12 #include "components/history/core/browser/history_service.h"
13 #include "components/history/core/browser/history_types.h"
14 #include "sync/api/time.h"
15 #include "sync/protocol/favicon_image_specifics.pb.h"
16 #include "sync/protocol/favicon_tracking_specifics.pb.h"
17 #include "sync/protocol/sync.pb.h"
18 #include "ui/gfx/favicon_size.h"
20 namespace browser_sync {
22 // Synced favicon storage and tracking.
23 // Note: we don't use the favicon service for storing these because these
24 // favicons are not necessarily associated with any local navigation, and
25 // hence would not work with the current expiration logic. We have custom
26 // expiration logic based on visit time/bookmark status/etc.
27 // See crbug.com/122890.
28 struct SyncedFaviconInfo {
29 explicit SyncedFaviconInfo(const GURL& favicon_url)
30 : favicon_url(favicon_url),
31 is_bookmarked(false),
32 received_local_update(false) {}
34 // The actual favicon data.
35 // TODO(zea): don't keep around the actual data for locally sourced
36 // favicons (UI can access those directly).
37 favicon_base::FaviconRawBitmapResult bitmap_data[NUM_SIZES];
38 // The URL this favicon was loaded from.
39 const GURL favicon_url;
40 // Is the favicon for a bookmarked page?
41 bool is_bookmarked;
42 // The last time a tab needed this favicon.
43 // Note: Do not modify this directly! It should only be modified via
44 // UpdateFaviconVisitTime(..).
45 base::Time last_visit_time;
46 // Whether we've received a local update for this favicon since starting up.
47 bool received_local_update;
49 private:
50 DISALLOW_COPY_AND_ASSIGN(SyncedFaviconInfo);
53 // Information for handling local favicon updates. Used in
54 // OnFaviconDataAvailable.
55 struct LocalFaviconUpdateInfo {
56 LocalFaviconUpdateInfo()
57 : new_image(false),
58 new_tracking(false),
59 image_needs_rewrite(false),
60 favicon_info(NULL) {}
62 bool new_image;
63 bool new_tracking;
64 bool image_needs_rewrite;
65 SyncedFaviconInfo* favicon_info;
68 namespace {
70 // Maximum number of favicons to keep in memory (0 means no limit).
71 const size_t kMaxFaviconsInMem = 0;
73 // Maximum width/height resolution supported.
74 const int kMaxFaviconResolution = 16;
76 // Returns a mask of the supported favicon types.
77 // TODO(zea): Supporting other favicons types will involve some work in the
78 // favicon service and navigation controller. See crbug.com/181068.
79 int SupportedFaviconTypes() { return favicon_base::FAVICON; }
81 // Returns the appropriate IconSize to use for a given gfx::Size pixel
82 // dimensions.
83 IconSize GetIconSizeBinFromBitmapResult(const gfx::Size& pixel_size) {
84 int max_size =
85 (pixel_size.width() > pixel_size.height() ?
86 pixel_size.width() : pixel_size.height());
87 // TODO(zea): re-enable 64p and 32p resolutions once we support them.
88 if (max_size > 64)
89 return SIZE_INVALID;
90 else if (max_size > 32)
91 return SIZE_INVALID;
92 else if (max_size > 16)
93 return SIZE_INVALID;
94 else
95 return SIZE_16;
98 // Helper for debug statements.
99 std::string IconSizeToString(IconSize icon_size) {
100 switch (icon_size) {
101 case SIZE_16:
102 return "16";
103 case SIZE_32:
104 return "32";
105 case SIZE_64:
106 return "64";
107 default:
108 return "INVALID";
112 // Extract the favicon url from either of the favicon types.
113 GURL GetFaviconURLFromSpecifics(const sync_pb::EntitySpecifics& specifics) {
114 if (specifics.has_favicon_tracking())
115 return GURL(specifics.favicon_tracking().favicon_url());
116 else
117 return GURL(specifics.favicon_image().favicon_url());
120 // Convert protobuf image data into a FaviconRawBitmapResult.
121 favicon_base::FaviconRawBitmapResult GetImageDataFromSpecifics(
122 const sync_pb::FaviconData& favicon_data) {
123 base::RefCountedString* temp_string =
124 new base::RefCountedString();
125 temp_string->data() = favicon_data.favicon();
126 favicon_base::FaviconRawBitmapResult bitmap_result;
127 bitmap_result.bitmap_data = temp_string;
128 bitmap_result.pixel_size.set_height(favicon_data.height());
129 bitmap_result.pixel_size.set_width(favicon_data.width());
130 return bitmap_result;
133 // Convert a FaviconRawBitmapResult into protobuf image data.
134 void FillSpecificsWithImageData(
135 const favicon_base::FaviconRawBitmapResult& bitmap_result,
136 sync_pb::FaviconData* favicon_data) {
137 if (!bitmap_result.bitmap_data.get())
138 return;
139 favicon_data->set_height(bitmap_result.pixel_size.height());
140 favicon_data->set_width(bitmap_result.pixel_size.width());
141 favicon_data->set_favicon(bitmap_result.bitmap_data->front(),
142 bitmap_result.bitmap_data->size());
145 // Build a FaviconImageSpecifics from a SyncedFaviconInfo.
146 void BuildImageSpecifics(
147 const SyncedFaviconInfo* favicon_info,
148 sync_pb::FaviconImageSpecifics* image_specifics) {
149 image_specifics->set_favicon_url(favicon_info->favicon_url.spec());
150 FillSpecificsWithImageData(favicon_info->bitmap_data[SIZE_16],
151 image_specifics->mutable_favicon_web());
152 // TODO(zea): bring this back if we can handle the load.
153 // FillSpecificsWithImageData(favicon_info->bitmap_data[SIZE_32],
154 // image_specifics->mutable_favicon_web_32());
155 // FillSpecificsWithImageData(favicon_info->bitmap_data[SIZE_64],
156 // image_specifics->mutable_favicon_touch_64());
159 // Build a FaviconTrackingSpecifics from a SyncedFaviconInfo.
160 void BuildTrackingSpecifics(
161 const SyncedFaviconInfo* favicon_info,
162 sync_pb::FaviconTrackingSpecifics* tracking_specifics) {
163 tracking_specifics->set_favicon_url(favicon_info->favicon_url.spec());
164 tracking_specifics->set_last_visit_time_ms(
165 syncer::TimeToProtoTime(favicon_info->last_visit_time));
166 tracking_specifics->set_is_bookmarked(favicon_info->is_bookmarked);
169 // Updates |favicon_info| with the image data in |bitmap_result|.
170 bool UpdateFaviconFromBitmapResult(
171 const favicon_base::FaviconRawBitmapResult& bitmap_result,
172 SyncedFaviconInfo* favicon_info) {
173 DCHECK_EQ(favicon_info->favicon_url, bitmap_result.icon_url);
174 if (!bitmap_result.is_valid()) {
175 DVLOG(1) << "Received invalid favicon at " << bitmap_result.icon_url.spec();
176 return false;
179 IconSize icon_size = GetIconSizeBinFromBitmapResult(
180 bitmap_result.pixel_size);
181 if (icon_size == SIZE_INVALID) {
182 DVLOG(1) << "Ignoring unsupported resolution "
183 << bitmap_result.pixel_size.height() << "x"
184 << bitmap_result.pixel_size.width();
185 return false;
186 } else if (!favicon_info->bitmap_data[icon_size].bitmap_data.get() ||
187 !favicon_info->received_local_update) {
188 DVLOG(1) << "Storing " << IconSizeToString(icon_size) << "p"
189 << " favicon for " << favicon_info->favicon_url.spec()
190 << " with size " << bitmap_result.bitmap_data->size()
191 << " bytes.";
192 favicon_info->bitmap_data[icon_size] = bitmap_result;
193 favicon_info->received_local_update = true;
194 return true;
195 } else {
196 // We only allow updating the image data once per restart.
197 DVLOG(2) << "Ignoring local update for " << bitmap_result.icon_url.spec();
198 return false;
202 bool FaviconInfoHasImages(const SyncedFaviconInfo& favicon_info) {
203 return favicon_info.bitmap_data[SIZE_16].bitmap_data.get() ||
204 favicon_info.bitmap_data[SIZE_32].bitmap_data.get() ||
205 favicon_info.bitmap_data[SIZE_64].bitmap_data.get();
208 bool FaviconInfoHasTracking(const SyncedFaviconInfo& favicon_info) {
209 return !favicon_info.last_visit_time.is_null();
212 bool FaviconInfoHasValidTypeData(const SyncedFaviconInfo& favicon_info,
213 syncer::ModelType type) {
214 if (type == syncer::FAVICON_IMAGES)
215 return FaviconInfoHasImages(favicon_info);
216 else if (type == syncer::FAVICON_TRACKING)
217 return FaviconInfoHasTracking(favicon_info);
218 NOTREACHED();
219 return false;
222 } // namespace
224 FaviconCache::FaviconCache(favicon::FaviconService* favicon_service,
225 history::HistoryService* history_service,
226 int max_sync_favicon_limit)
227 : favicon_service_(favicon_service),
228 max_sync_favicon_limit_(max_sync_favicon_limit),
229 history_service_observer_(this),
230 weak_ptr_factory_(this) {
231 if (history_service)
232 history_service_observer_.Add(history_service);
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();
246 else
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);
268 } else {
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--;
290 } else {
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,
303 local_changes);
304 } else {
305 favicon_tracking_sync_processor_->ProcessSyncChanges(FROM_HERE,
306 local_changes);
308 return merge_result;
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)
319 const {
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));
330 return data_list;
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);
351 GURL favicon_url =
352 GetFaviconURLFromSpecifics(iter->sync_data().GetSpecifics());
353 if (!favicon_url.is_valid()) {
354 error.Reset(FROM_HERE, "Received invalid favicon url.", type);
355 break;
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.
362 continue;
363 } else {
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
376 // gracefully).
377 if (favicon_iter == synced_favicons_.end()) {
378 DVLOG(1) << "Adding favicon at " << favicon_url.spec();
379 AddLocalFaviconFromSyncedData(iter->sync_data());
380 } else {
381 DVLOG(1) << "Updating favicon at " << favicon_url.spec();
382 MergeSyncFavicon(iter->sync_data(), &new_changes);
384 } else {
385 error.Reset(FROM_HERE, "Invalid action received.", type);
386 break;
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,
396 new_changes);
397 } else {
398 favicon_tracking_sync_processor_->ProcessSyncChanges(FROM_HERE,
399 new_changes);
403 return error;
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())
411 return;
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);
427 return;
431 DVLOG(1) << "Triggering favicon load for url " << page_url.spec();
433 if (!favicon_service_) {
434 page_task_map_[page_url] = 0; // For testing only.
435 return;
438 // TODO(zea): This appears to only fetch one favicon (best match based on
439 // desired_size_in_dip). Figure out a way to fetch all favicons we support.
440 // See crbug.com/181068.
441 base::CancelableTaskTracker::TaskId id =
442 favicon_service_->GetFaviconForPageURL(
443 page_url, SupportedFaviconTypes(), kMaxFaviconResolution,
444 base::Bind(&FaviconCache::OnFaviconDataAvailable,
445 weak_ptr_factory_.GetWeakPtr(), page_url),
446 &cancelable_task_tracker_);
447 page_task_map_[page_url] = id;
450 void FaviconCache::OnFaviconVisited(const GURL& page_url,
451 const GURL& favicon_url) {
452 DCHECK(page_url.is_valid());
453 if (!favicon_url.is_valid() ||
454 synced_favicons_.find(favicon_url) == synced_favicons_.end()) {
455 // TODO(zea): consider triggering a favicon load if we have some but not
456 // all desired resolutions?
457 OnPageFaviconUpdated(page_url);
458 return;
461 DVLOG(1) << "Associating " << page_url.spec() << " with favicon at "
462 << favicon_url.spec() << " and marking visited.";
463 page_favicon_map_[page_url] = favicon_url;
464 bool had_tracking = FaviconInfoHasTracking(
465 *synced_favicons_.find(favicon_url)->second);
466 UpdateFaviconVisitTime(favicon_url, base::Time::Now());
468 UpdateSyncState(favicon_url,
469 syncer::SyncChange::ACTION_INVALID,
470 (had_tracking ?
471 syncer::SyncChange::ACTION_UPDATE :
472 syncer::SyncChange::ACTION_ADD));
475 bool FaviconCache::GetSyncedFaviconForFaviconURL(
476 const GURL& favicon_url,
477 scoped_refptr<base::RefCountedMemory>* favicon_png) const {
478 if (!favicon_url.is_valid())
479 return false;
480 FaviconMap::const_iterator iter = synced_favicons_.find(favicon_url);
482 UMA_HISTOGRAM_BOOLEAN("Sync.FaviconCacheLookupSucceeded",
483 iter != synced_favicons_.end());
484 if (iter == synced_favicons_.end())
485 return false;
487 // TODO(zea): support getting other resolutions.
488 if (!iter->second->bitmap_data[SIZE_16].bitmap_data.get())
489 return false;
491 *favicon_png = iter->second->bitmap_data[SIZE_16].bitmap_data;
492 return true;
495 bool FaviconCache::GetSyncedFaviconForPageURL(
496 const GURL& page_url,
497 scoped_refptr<base::RefCountedMemory>* favicon_png) const {
498 if (!page_url.is_valid())
499 return false;
500 PageFaviconMap::const_iterator iter = page_favicon_map_.find(page_url);
502 if (iter == page_favicon_map_.end())
503 return false;
505 return GetSyncedFaviconForFaviconURL(iter->second, favicon_png);
508 void FaviconCache::OnReceivedSyncFavicon(const GURL& page_url,
509 const GURL& icon_url,
510 const std::string& icon_bytes,
511 int64 visit_time_ms) {
512 if (!icon_url.is_valid() || !page_url.is_valid() || icon_url.SchemeIs("data"))
513 return;
514 DVLOG(1) << "Associating " << page_url.spec() << " with favicon at "
515 << icon_url.spec();
516 page_favicon_map_[page_url] = icon_url;
518 // If there is no actual image, it means there either is no synced
519 // favicon, or it's on its way (race condition).
520 // TODO(zea): potentially trigger a favicon web download here (delayed?).
521 if (icon_bytes.size() == 0)
522 return;
524 // Post a task to do the actual association because this method may have been
525 // called while in a transaction.
526 base::ThreadTaskRunnerHandle::Get()->PostTask(
527 FROM_HERE, base::Bind(&FaviconCache::OnReceivedSyncFaviconImpl,
528 weak_ptr_factory_.GetWeakPtr(), icon_url,
529 icon_bytes, visit_time_ms));
532 void FaviconCache::OnReceivedSyncFaviconImpl(
533 const GURL& icon_url,
534 const std::string& icon_bytes,
535 int64 visit_time_ms) {
536 // If this favicon is already synced, do nothing else.
537 if (synced_favicons_.find(icon_url) != synced_favicons_.end())
538 return;
540 // Don't add any more favicons once we hit our in memory limit.
541 // TODO(zea): UMA this.
542 if (kMaxFaviconsInMem != 0 && synced_favicons_.size() > kMaxFaviconsInMem)
543 return;
545 SyncedFaviconInfo* favicon_info = GetFaviconInfo(icon_url);
546 if (!favicon_info)
547 return; // We reached the in-memory limit.
548 base::RefCountedString* temp_string = new base::RefCountedString();
549 temp_string->data() = icon_bytes;
550 favicon_info->bitmap_data[SIZE_16].bitmap_data = temp_string;
551 // We assume legacy favicons are 16x16.
552 favicon_info->bitmap_data[SIZE_16].pixel_size.set_width(16);
553 favicon_info->bitmap_data[SIZE_16].pixel_size.set_height(16);
554 bool added_tracking = !FaviconInfoHasTracking(*favicon_info);
555 UpdateFaviconVisitTime(icon_url,
556 syncer::ProtoTimeToTime(visit_time_ms));
558 UpdateSyncState(icon_url,
559 syncer::SyncChange::ACTION_ADD,
560 (added_tracking ?
561 syncer::SyncChange::ACTION_ADD :
562 syncer::SyncChange::ACTION_UPDATE));
565 bool FaviconCache::FaviconRecencyFunctor::operator()(
566 const linked_ptr<SyncedFaviconInfo>& lhs,
567 const linked_ptr<SyncedFaviconInfo>& rhs) const {
568 // TODO(zea): incorporate bookmarked status here once we care about it.
569 if (lhs->last_visit_time < rhs->last_visit_time)
570 return true;
571 else if (lhs->last_visit_time == rhs->last_visit_time)
572 return lhs->favicon_url.spec() < rhs->favicon_url.spec();
573 return false;
576 void FaviconCache::OnFaviconDataAvailable(
577 const GURL& page_url,
578 const std::vector<favicon_base::FaviconRawBitmapResult>& bitmap_results) {
579 PageTaskMap::iterator page_iter = page_task_map_.find(page_url);
580 if (page_iter == page_task_map_.end())
581 return;
582 page_task_map_.erase(page_iter);
584 if (bitmap_results.size() == 0) {
585 // Either the favicon isn't loaded yet or there is no valid favicon.
586 // We already cleared the task id, so just return.
587 DVLOG(1) << "Favicon load failed for page " << page_url.spec();
588 return;
591 base::Time now = base::Time::Now();
592 std::map<GURL, LocalFaviconUpdateInfo> favicon_updates;
593 for (size_t i = 0; i < bitmap_results.size(); ++i) {
594 const favicon_base::FaviconRawBitmapResult& bitmap_result =
595 bitmap_results[i];
596 GURL favicon_url = bitmap_result.icon_url;
597 if (!favicon_url.is_valid() || favicon_url.SchemeIs("data"))
598 continue; // Can happen if the page is still loading.
600 SyncedFaviconInfo* favicon_info = GetFaviconInfo(favicon_url);
601 if (!favicon_info)
602 return; // We reached the in-memory limit.
604 favicon_updates[favicon_url].new_image |=
605 !FaviconInfoHasImages(*favicon_info);
606 favicon_updates[favicon_url].new_tracking |=
607 !FaviconInfoHasTracking(*favicon_info);
608 favicon_updates[favicon_url].image_needs_rewrite |=
609 UpdateFaviconFromBitmapResult(bitmap_result, favicon_info);
610 favicon_updates[favicon_url].favicon_info = favicon_info;
613 for (std::map<GURL, LocalFaviconUpdateInfo>::const_iterator
614 iter = favicon_updates.begin(); iter != favicon_updates.end();
615 ++iter) {
616 SyncedFaviconInfo* favicon_info = iter->second.favicon_info;
617 const GURL& favicon_url = favicon_info->favicon_url;
619 // TODO(zea): support multiple favicon urls per page.
620 page_favicon_map_[page_url] = favicon_url;
622 if (!favicon_info->last_visit_time.is_null()) {
623 UMA_HISTOGRAM_COUNTS_10000(
624 "Sync.FaviconVisitPeriod",
625 (now - favicon_info->last_visit_time).InHours());
627 favicon_info->received_local_update = true;
628 UpdateFaviconVisitTime(favicon_url, now);
630 syncer::SyncChange::SyncChangeType image_change =
631 syncer::SyncChange::ACTION_INVALID;
632 if (iter->second.new_image)
633 image_change = syncer::SyncChange::ACTION_ADD;
634 else if (iter->second.image_needs_rewrite)
635 image_change = syncer::SyncChange::ACTION_UPDATE;
636 syncer::SyncChange::SyncChangeType tracking_change =
637 syncer::SyncChange::ACTION_UPDATE;
638 if (iter->second.new_tracking)
639 tracking_change = syncer::SyncChange::ACTION_ADD;
640 UpdateSyncState(favicon_url, image_change, tracking_change);
644 void FaviconCache::UpdateSyncState(
645 const GURL& icon_url,
646 syncer::SyncChange::SyncChangeType image_change_type,
647 syncer::SyncChange::SyncChangeType tracking_change_type) {
648 DCHECK(icon_url.is_valid());
649 // It's possible that we'll receive a favicon update before both types
650 // have finished setting up. In that case ignore the update.
651 // TODO(zea): consider tracking these skipped updates somehow?
652 if (!favicon_images_sync_processor_.get() ||
653 !favicon_tracking_sync_processor_.get()) {
654 return;
657 FaviconMap::const_iterator iter = synced_favicons_.find(icon_url);
658 DCHECK(iter != synced_favicons_.end());
659 const SyncedFaviconInfo* favicon_info = iter->second.get();
661 syncer::SyncChangeList image_changes;
662 syncer::SyncChangeList tracking_changes;
663 if (image_change_type != syncer::SyncChange::ACTION_INVALID) {
664 sync_pb::EntitySpecifics new_specifics;
665 sync_pb::FaviconImageSpecifics* image_specifics =
666 new_specifics.mutable_favicon_image();
667 BuildImageSpecifics(favicon_info, image_specifics);
669 image_changes.push_back(
670 syncer::SyncChange(FROM_HERE,
671 image_change_type,
672 syncer::SyncData::CreateLocalData(
673 icon_url.spec(),
674 icon_url.spec(),
675 new_specifics)));
677 if (tracking_change_type != syncer::SyncChange::ACTION_INVALID) {
678 sync_pb::EntitySpecifics new_specifics;
679 sync_pb::FaviconTrackingSpecifics* tracking_specifics =
680 new_specifics.mutable_favicon_tracking();
681 BuildTrackingSpecifics(favicon_info, tracking_specifics);
683 tracking_changes.push_back(
684 syncer::SyncChange(FROM_HERE,
685 tracking_change_type,
686 syncer::SyncData::CreateLocalData(
687 icon_url.spec(),
688 icon_url.spec(),
689 new_specifics)));
691 ExpireFaviconsIfNecessary(&image_changes, &tracking_changes);
692 if (!image_changes.empty()) {
693 favicon_images_sync_processor_->ProcessSyncChanges(FROM_HERE,
694 image_changes);
696 if (!tracking_changes.empty()) {
697 favicon_tracking_sync_processor_->ProcessSyncChanges(FROM_HERE,
698 tracking_changes);
702 SyncedFaviconInfo* FaviconCache::GetFaviconInfo(
703 const GURL& icon_url) {
704 DCHECK_EQ(recent_favicons_.size(), synced_favicons_.size());
705 if (synced_favicons_.count(icon_url) != 0)
706 return synced_favicons_[icon_url].get();
708 // TODO(zea): implement in-memory eviction.
709 DVLOG(1) << "Adding favicon info for " << icon_url.spec();
710 SyncedFaviconInfo* favicon_info = new SyncedFaviconInfo(icon_url);
711 synced_favicons_[icon_url] = make_linked_ptr(favicon_info);
712 recent_favicons_.insert(synced_favicons_[icon_url]);
713 DCHECK_EQ(recent_favicons_.size(), synced_favicons_.size());
714 return favicon_info;
717 void FaviconCache::UpdateFaviconVisitTime(const GURL& icon_url,
718 base::Time time) {
719 DCHECK_EQ(recent_favicons_.size(), synced_favicons_.size());
720 FaviconMap::const_iterator iter = synced_favicons_.find(icon_url);
721 DCHECK(iter != synced_favicons_.end());
722 if (iter->second->last_visit_time >= time)
723 return;
724 // Erase, update the time, then re-insert to maintain ordering.
725 recent_favicons_.erase(iter->second);
726 DVLOG(1) << "Updating " << icon_url.spec() << " visit time to "
727 << syncer::GetTimeDebugString(time);
728 iter->second->last_visit_time = time;
729 recent_favicons_.insert(iter->second);
731 if (VLOG_IS_ON(2)) {
732 for (RecencySet::const_iterator iter = recent_favicons_.begin();
733 iter != recent_favicons_.end(); ++iter) {
734 DVLOG(2) << "Favicon " << iter->get()->favicon_url.spec() << ": "
735 << syncer::GetTimeDebugString(iter->get()->last_visit_time);
738 DCHECK_EQ(recent_favicons_.size(), synced_favicons_.size());
741 void FaviconCache::ExpireFaviconsIfNecessary(
742 syncer::SyncChangeList* image_changes,
743 syncer::SyncChangeList* tracking_changes) {
744 DCHECK_EQ(recent_favicons_.size(), synced_favicons_.size());
745 // TODO(zea): once we have in-memory eviction, we'll need to track sync
746 // favicon count separately from the synced_favicons_/recent_favicons_.
748 // Iterate until we've removed the necessary amount. |recent_favicons_| is
749 // already in recency order, so just start from the beginning.
750 // TODO(zea): to reduce thrashing, consider removing more than the minimum.
751 while (recent_favicons_.size() > max_sync_favicon_limit_) {
752 linked_ptr<SyncedFaviconInfo> candidate = *recent_favicons_.begin();
753 DVLOG(1) << "Expiring favicon " << candidate->favicon_url.spec();
754 DeleteSyncedFavicon(synced_favicons_.find(candidate->favicon_url),
755 image_changes,
756 tracking_changes);
758 DCHECK_EQ(recent_favicons_.size(), synced_favicons_.size());
761 GURL FaviconCache::GetLocalFaviconFromSyncedData(
762 const syncer::SyncData& sync_favicon) const {
763 syncer::ModelType type = sync_favicon.GetDataType();
764 DCHECK(type == syncer::FAVICON_IMAGES || type == syncer::FAVICON_TRACKING);
765 GURL favicon_url = GetFaviconURLFromSpecifics(sync_favicon.GetSpecifics());
766 return (synced_favicons_.count(favicon_url) > 0 ? favicon_url : GURL());
769 void FaviconCache::MergeSyncFavicon(const syncer::SyncData& sync_favicon,
770 syncer::SyncChangeList* sync_changes) {
771 syncer::ModelType type = sync_favicon.GetDataType();
772 DCHECK(type == syncer::FAVICON_IMAGES || type == syncer::FAVICON_TRACKING);
773 sync_pb::EntitySpecifics new_specifics;
774 GURL favicon_url = GetFaviconURLFromSpecifics(sync_favicon.GetSpecifics());
775 FaviconMap::const_iterator iter = synced_favicons_.find(favicon_url);
776 DCHECK(iter != synced_favicons_.end());
777 SyncedFaviconInfo* favicon_info = iter->second.get();
778 if (type == syncer::FAVICON_IMAGES) {
779 sync_pb::FaviconImageSpecifics image_specifics =
780 sync_favicon.GetSpecifics().favicon_image();
782 // Remote image data always clobbers local image data.
783 bool needs_update = false;
784 if (image_specifics.has_favicon_web()) {
785 favicon_info->bitmap_data[SIZE_16] = GetImageDataFromSpecifics(
786 image_specifics.favicon_web());
787 } else if (favicon_info->bitmap_data[SIZE_16].bitmap_data.get()) {
788 needs_update = true;
790 if (image_specifics.has_favicon_web_32()) {
791 favicon_info->bitmap_data[SIZE_32] = GetImageDataFromSpecifics(
792 image_specifics.favicon_web_32());
793 } else if (favicon_info->bitmap_data[SIZE_32].bitmap_data.get()) {
794 needs_update = true;
796 if (image_specifics.has_favicon_touch_64()) {
797 favicon_info->bitmap_data[SIZE_64] = GetImageDataFromSpecifics(
798 image_specifics.favicon_touch_64());
799 } else if (favicon_info->bitmap_data[SIZE_64].bitmap_data.get()) {
800 needs_update = true;
803 if (needs_update)
804 BuildImageSpecifics(favicon_info, new_specifics.mutable_favicon_image());
805 } else {
806 sync_pb::FaviconTrackingSpecifics tracking_specifics =
807 sync_favicon.GetSpecifics().favicon_tracking();
809 // Tracking data is merged, such that bookmark data is the logical OR
810 // of the two, and last visit time is the most recent.
812 base::Time last_visit = syncer::ProtoTimeToTime(
813 tracking_specifics.last_visit_time_ms());
814 // Due to crbug.com/258196, there are tracking nodes out there with
815 // null visit times. If this is one of those, artificially make it a valid
816 // visit time, so we know the node exists and update it properly on the next
817 // real visit.
818 if (last_visit.is_null())
819 last_visit = last_visit + base::TimeDelta::FromMilliseconds(1);
820 UpdateFaviconVisitTime(favicon_url, last_visit);
821 favicon_info->is_bookmarked = (favicon_info->is_bookmarked ||
822 tracking_specifics.is_bookmarked());
824 if (syncer::TimeToProtoTime(favicon_info->last_visit_time) !=
825 tracking_specifics.last_visit_time_ms() ||
826 favicon_info->is_bookmarked != tracking_specifics.is_bookmarked()) {
827 BuildTrackingSpecifics(favicon_info,
828 new_specifics.mutable_favicon_tracking());
830 DCHECK(!favicon_info->last_visit_time.is_null());
833 if (new_specifics.has_favicon_image() ||
834 new_specifics.has_favicon_tracking()) {
835 sync_changes->push_back(syncer::SyncChange(
836 FROM_HERE,
837 syncer::SyncChange::ACTION_UPDATE,
838 syncer::SyncData::CreateLocalData(favicon_url.spec(),
839 favicon_url.spec(),
840 new_specifics)));
844 void FaviconCache::AddLocalFaviconFromSyncedData(
845 const syncer::SyncData& sync_favicon) {
846 syncer::ModelType type = sync_favicon.GetDataType();
847 DCHECK(type == syncer::FAVICON_IMAGES || type == syncer::FAVICON_TRACKING);
848 if (type == syncer::FAVICON_IMAGES) {
849 sync_pb::FaviconImageSpecifics image_specifics =
850 sync_favicon.GetSpecifics().favicon_image();
851 GURL favicon_url = GURL(image_specifics.favicon_url());
852 DCHECK(favicon_url.is_valid());
853 DCHECK(!synced_favicons_.count(favicon_url));
855 SyncedFaviconInfo* favicon_info = GetFaviconInfo(favicon_url);
856 if (!favicon_info)
857 return; // We reached the in-memory limit.
858 if (image_specifics.has_favicon_web()) {
859 favicon_info->bitmap_data[SIZE_16] = GetImageDataFromSpecifics(
860 image_specifics.favicon_web());
862 if (image_specifics.has_favicon_web_32()) {
863 favicon_info->bitmap_data[SIZE_32] = GetImageDataFromSpecifics(
864 image_specifics.favicon_web_32());
866 if (image_specifics.has_favicon_touch_64()) {
867 favicon_info->bitmap_data[SIZE_64] = GetImageDataFromSpecifics(
868 image_specifics.favicon_touch_64());
870 } else {
871 sync_pb::FaviconTrackingSpecifics tracking_specifics =
872 sync_favicon.GetSpecifics().favicon_tracking();
873 GURL favicon_url = GURL(tracking_specifics.favicon_url());
874 DCHECK(favicon_url.is_valid());
875 DCHECK(!synced_favicons_.count(favicon_url));
877 SyncedFaviconInfo* favicon_info = GetFaviconInfo(favicon_url);
878 if (!favicon_info)
879 return; // We reached the in-memory limit.
880 base::Time last_visit = syncer::ProtoTimeToTime(
881 tracking_specifics.last_visit_time_ms());
882 // Due to crbug.com/258196, there are tracking nodes out there with
883 // null visit times. If this is one of those, artificially make it a valid
884 // visit time, so we know the node exists and update it properly on the next
885 // real visit.
886 if (last_visit.is_null())
887 last_visit = last_visit + base::TimeDelta::FromMilliseconds(1);
888 UpdateFaviconVisitTime(favicon_url, last_visit);
889 favicon_info->is_bookmarked = tracking_specifics.is_bookmarked();
890 DCHECK(!favicon_info->last_visit_time.is_null());
894 syncer::SyncData FaviconCache::CreateSyncDataFromLocalFavicon(
895 syncer::ModelType type,
896 const GURL& favicon_url) const {
897 DCHECK(type == syncer::FAVICON_IMAGES || type == syncer::FAVICON_TRACKING);
898 DCHECK(favicon_url.is_valid());
899 FaviconMap::const_iterator iter = synced_favicons_.find(favicon_url);
900 DCHECK(iter != synced_favicons_.end());
901 SyncedFaviconInfo* favicon_info = iter->second.get();
903 syncer::SyncData data;
904 sync_pb::EntitySpecifics specifics;
905 if (type == syncer::FAVICON_IMAGES) {
906 sync_pb::FaviconImageSpecifics* image_specifics =
907 specifics.mutable_favicon_image();
908 BuildImageSpecifics(favicon_info, image_specifics);
909 } else {
910 sync_pb::FaviconTrackingSpecifics* tracking_specifics =
911 specifics.mutable_favicon_tracking();
912 BuildTrackingSpecifics(favicon_info, tracking_specifics);
914 data = syncer::SyncData::CreateLocalData(favicon_url.spec(),
915 favicon_url.spec(),
916 specifics);
917 return data;
920 void FaviconCache::DeleteSyncedFavicons(const std::set<GURL>& favicon_urls) {
921 syncer::SyncChangeList image_deletions, tracking_deletions;
922 for (std::set<GURL>::const_iterator iter = favicon_urls.begin();
923 iter != favicon_urls.end(); ++iter) {
924 FaviconMap::iterator favicon_iter = synced_favicons_.find(*iter);
925 if (favicon_iter == synced_favicons_.end())
926 continue;
927 DeleteSyncedFavicon(favicon_iter,
928 &image_deletions,
929 &tracking_deletions);
931 DVLOG(1) << "Deleting " << image_deletions.size() << " synced favicons.";
932 if (favicon_images_sync_processor_.get()) {
933 favicon_images_sync_processor_->ProcessSyncChanges(FROM_HERE,
934 image_deletions);
936 if (favicon_tracking_sync_processor_.get()) {
937 favicon_tracking_sync_processor_->ProcessSyncChanges(FROM_HERE,
938 tracking_deletions);
942 void FaviconCache::DeleteSyncedFavicon(
943 FaviconMap::iterator favicon_iter,
944 syncer::SyncChangeList* image_changes,
945 syncer::SyncChangeList* tracking_changes) {
946 linked_ptr<SyncedFaviconInfo> favicon_info = favicon_iter->second;
947 if (FaviconInfoHasImages(*(favicon_iter->second))) {
948 DVLOG(1) << "Deleting image for "
949 << favicon_iter->second.get()->favicon_url;
950 image_changes->push_back(
951 syncer::SyncChange(FROM_HERE,
952 syncer::SyncChange::ACTION_DELETE,
953 syncer::SyncData::CreateLocalDelete(
954 favicon_info->favicon_url.spec(),
955 syncer::FAVICON_IMAGES)));
957 if (FaviconInfoHasTracking(*(favicon_iter->second))) {
958 DVLOG(1) << "Deleting tracking for "
959 << favicon_iter->second.get()->favicon_url;
960 tracking_changes->push_back(
961 syncer::SyncChange(FROM_HERE,
962 syncer::SyncChange::ACTION_DELETE,
963 syncer::SyncData::CreateLocalDelete(
964 favicon_info->favicon_url.spec(),
965 syncer::FAVICON_TRACKING)));
967 DropSyncedFavicon(favicon_iter);
970 void FaviconCache::DropSyncedFavicon(FaviconMap::iterator favicon_iter) {
971 DVLOG(1) << "Dropping favicon " << favicon_iter->second.get()->favicon_url;
972 recent_favicons_.erase(favicon_iter->second);
973 synced_favicons_.erase(favicon_iter);
976 void FaviconCache::DropPartialFavicon(FaviconMap::iterator favicon_iter,
977 syncer::ModelType type) {
978 // If the type being dropped has no valid data, do nothing.
979 if ((type == syncer::FAVICON_TRACKING &&
980 !FaviconInfoHasTracking(*favicon_iter->second)) ||
981 (type == syncer::FAVICON_IMAGES &&
982 !FaviconInfoHasImages(*favicon_iter->second))) {
983 return;
986 // If the type being dropped is the only type with valid data, just delete
987 // the favicon altogether.
988 if ((type == syncer::FAVICON_TRACKING &&
989 !FaviconInfoHasImages(*favicon_iter->second)) ||
990 (type == syncer::FAVICON_IMAGES &&
991 !FaviconInfoHasTracking(*favicon_iter->second))) {
992 DropSyncedFavicon(favicon_iter);
993 return;
996 if (type == syncer::FAVICON_IMAGES) {
997 DVLOG(1) << "Dropping favicon image "
998 << favicon_iter->second.get()->favicon_url;
999 for (int i = 0; i < NUM_SIZES; ++i) {
1000 favicon_iter->second->bitmap_data[i] =
1001 favicon_base::FaviconRawBitmapResult();
1003 DCHECK(!FaviconInfoHasImages(*favicon_iter->second));
1004 } else {
1005 DCHECK_EQ(type, syncer::FAVICON_TRACKING);
1006 DVLOG(1) << "Dropping favicon tracking "
1007 << favicon_iter->second.get()->favicon_url;
1008 recent_favicons_.erase(favicon_iter->second);
1009 favicon_iter->second->last_visit_time = base::Time();
1010 favicon_iter->second->is_bookmarked = false;
1011 recent_favicons_.insert(favicon_iter->second);
1012 DCHECK(!FaviconInfoHasTracking(*favicon_iter->second));
1016 size_t FaviconCache::NumFaviconsForTest() const {
1017 return synced_favicons_.size();
1020 size_t FaviconCache::NumTasksForTest() const {
1021 return page_task_map_.size();
1024 void FaviconCache::OnURLsDeleted(history::HistoryService* history_service,
1025 bool all_history,
1026 bool expired,
1027 const history::URLRows& deleted_rows,
1028 const std::set<GURL>& favicon_urls) {
1029 // We only care about actual user (or sync) deletions.
1030 if (expired)
1031 return;
1033 if (!all_history) {
1034 DeleteSyncedFavicons(favicon_urls);
1035 return;
1038 // All history was cleared: just delete all favicons.
1039 DVLOG(1) << "History clear detected, deleting all synced favicons.";
1040 syncer::SyncChangeList image_deletions, tracking_deletions;
1041 while (!synced_favicons_.empty()) {
1042 DeleteSyncedFavicon(synced_favicons_.begin(), &image_deletions,
1043 &tracking_deletions);
1046 if (favicon_images_sync_processor_.get()) {
1047 favicon_images_sync_processor_->ProcessSyncChanges(FROM_HERE,
1048 image_deletions);
1050 if (favicon_tracking_sync_processor_.get()) {
1051 favicon_tracking_sync_processor_->ProcessSyncChanges(FROM_HERE,
1052 tracking_deletions);
1056 } // namespace browser_sync