1 // Copyright (c) 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 #ifndef CHROME_BROWSER_HISTORY_TOP_SITES_IMPL_H_
6 #define CHROME_BROWSER_HISTORY_TOP_SITES_IMPL_H_
14 #include "base/basictypes.h"
15 #include "base/callback.h"
16 #include "base/gtest_prod_util.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/synchronization/lock.h"
19 #include "base/time/time.h"
20 #include "base/timer/timer.h"
21 #include "chrome/browser/common/cancelable_request.h"
22 #include "chrome/browser/history/history_service.h"
23 #include "chrome/browser/history/history_types.h"
24 #include "chrome/browser/history/page_usage_data.h"
25 #include "chrome/browser/history/top_sites.h"
26 #include "chrome/browser/history/top_sites_backend.h"
27 #include "chrome/common/cancelable_task_tracker.h"
28 #include "chrome/common/thumbnail_score.h"
29 #include "third_party/skia/include/core/SkColor.h"
30 #include "ui/gfx/image/image.h"
37 class RefCountedBytes;
38 class RefCountedMemory;
44 class TopSitesImplTest;
46 // This class allows requests for most visited urls and thumbnails on any
47 // thread. All other methods must be invoked on the UI thread. All mutations
48 // to internal state happen on the UI thread and are scheduled to update the
49 // db using TopSitesBackend.
50 class TopSitesImpl : public TopSites {
52 explicit TopSitesImpl(Profile* profile);
54 // Initializes TopSitesImpl.
55 void Init(const base::FilePath& db_name);
57 virtual bool SetPageThumbnail(const GURL& url,
58 const gfx::Image& thumbnail,
59 const ThumbnailScore& score) OVERRIDE;
60 virtual bool SetPageThumbnailToJPEGBytes(
62 const base::RefCountedMemory* memory,
63 const ThumbnailScore& score) OVERRIDE;
64 virtual void GetMostVisitedURLs(
65 const GetMostVisitedURLsCallback& callback) OVERRIDE;
66 virtual bool GetPageThumbnail(
69 scoped_refptr<base::RefCountedMemory>* bytes) OVERRIDE;
70 virtual bool GetPageThumbnailScore(const GURL& url,
71 ThumbnailScore* score) OVERRIDE;
72 virtual bool GetTemporaryPageThumbnailScore(const GURL& url,
73 ThumbnailScore* score) OVERRIDE;
74 virtual void SyncWithHistory() OVERRIDE;
75 virtual bool HasBlacklistedItems() const OVERRIDE;
76 virtual void AddBlacklistedURL(const GURL& url) OVERRIDE;
77 virtual void RemoveBlacklistedURL(const GURL& url) OVERRIDE;
78 virtual bool IsBlacklisted(const GURL& url) OVERRIDE;
79 virtual void ClearBlacklistedURLs() OVERRIDE;
80 virtual void Shutdown() OVERRIDE;
81 virtual CancelableRequestProvider::Handle StartQueryForMostVisited() OVERRIDE;
82 virtual bool IsKnownURL(const GURL& url) OVERRIDE;
83 virtual const std::string& GetCanonicalURLString(
84 const GURL& url) const OVERRIDE;
85 virtual bool IsFull() OVERRIDE;
86 virtual MostVisitedURLList GetPrepopulatePages() OVERRIDE;
87 virtual bool loaded() const OVERRIDE;
90 virtual ~TopSitesImpl();
93 friend class TopSitesImplTest;
94 FRIEND_TEST_ALL_PREFIXES(TopSitesImplTest, DiffMostVisited);
96 typedef std::pair<GURL, Images> TempImage;
97 typedef std::list<TempImage> TempImages;
99 // Generates the diff of things that happened between "old" and "new."
101 // The URLs that are in "new" but not "old" will be have their index into
102 // "new" put in |added_urls|. The URLs that are in "old" but not "new" will
103 // have their index into "old" put into |deleted_urls|.
105 // URLs appearing in both old and new lists but having different indices will
106 // have their index into "new" be put into |moved_urls|.
107 static void DiffMostVisited(const MostVisitedURLList& old_list,
108 const MostVisitedURLList& new_list,
109 TopSitesDelta* delta);
111 // Sets the thumbnail without writing to the database. Useful when
112 // reading last known top sites from the DB.
113 // Returns true if the thumbnail was set, false if the existing one is better.
114 bool SetPageThumbnailNoDB(const GURL& url,
115 const base::RefCountedMemory* thumbnail_data,
116 const ThumbnailScore& score);
118 // A version of SetPageThumbnail that takes RefCountedBytes as
119 // returned by HistoryService.
120 bool SetPageThumbnailEncoded(const GURL& url,
121 const base::RefCountedMemory* thumbnail,
122 const ThumbnailScore& score);
124 // Encodes the bitmap to bytes for storage to the db. Returns true if the
125 // bitmap was successfully encoded.
126 static bool EncodeBitmap(const gfx::Image& bitmap,
127 scoped_refptr<base::RefCountedBytes>* bytes);
129 // Removes the cached thumbnail for url. Does nothing if |url| if not cached
130 // in |temp_images_|.
131 void RemoveTemporaryThumbnailByURL(const GURL& url);
133 // Add a thumbnail for an unknown url. See temp_thumbnails_map_.
134 void AddTemporaryThumbnail(const GURL& url,
135 const base::RefCountedMemory* thumbnail,
136 const ThumbnailScore& score);
138 // Called by our timer. Starts the query for the most visited sites.
141 // Finds the given URL in the redirect chain for the given TopSite, and
142 // returns the distance from the destination in hops that the given URL is.
143 // The URL is assumed to be in the list. The destination is 0.
144 static int GetRedirectDistanceForURL(const MostVisitedURL& most_visited,
147 // Add prepopulated pages: 'welcome to Chrome' and themes gallery to |urls|.
148 // Returns true if any pages were added.
149 bool AddPrepopulatedPages(MostVisitedURLList* urls);
151 // Takes |urls|, produces it's copy in |out| after removing blacklisted URLs.
152 void ApplyBlacklist(const MostVisitedURLList& urls, MostVisitedURLList* out);
154 // Returns an MD5 hash of the URL. Hashing is required for blacklisted URLs.
155 std::string GetURLHash(const GURL& url);
157 // Returns the delay until the next update of history is needed.
158 // Uses num_urls_changed
159 base::TimeDelta GetUpdateDelay();
161 // Implementation of content::NotificationObserver.
162 virtual void Observe(int type,
163 const content::NotificationSource& source,
164 const content::NotificationDetails& details) OVERRIDE;
166 // Resets top_sites_ and updates the db (in the background). All mutations to
167 // top_sites_ *must* go through this. Should be called from the UI thread.
168 void SetTopSites(const MostVisitedURLList& new_top_sites);
170 // Returns the number of most visted results to request from history. This
171 // changes depending upon how many urls have been blacklisted. Should be
172 // called from the UI thread.
173 int num_results_to_request_from_history() const;
175 // Invoked when transitioning to LOADED. Notifies any queued up callbacks.
176 // Should be called from the UI thread.
177 void MoveStateToLoaded();
179 void ResetThreadSafeCache();
181 void ResetThreadSafeImageCache();
183 void NotifyTopSitesChanged();
185 // Stops and starts timer with a delay of |delta|.
186 void RestartQueryForTopSitesTimer(base::TimeDelta delta);
188 // Callback from TopSites with the top sites/thumbnails. Should be called
189 // from the UI thread.
190 void OnGotMostVisitedThumbnails(
191 const scoped_refptr<MostVisitedThumbnails>& thumbnails);
193 // Called when history service returns a list of top URLs.
194 void OnTopSitesAvailableFromHistory(CancelableRequestProvider::Handle handle,
195 MostVisitedURLList data);
197 scoped_refptr<TopSitesBackend> backend_;
199 // The top sites data.
200 scoped_ptr<TopSitesCache> cache_;
202 // Copy of the top sites data that may be accessed on any thread (assuming
203 // you hold |lock_|). The data in |thread_safe_cache_| has blacklisted and
204 // pinned urls applied (|cache_| does not).
205 scoped_ptr<TopSitesCache> thread_safe_cache_;
209 // Lock used to access |thread_safe_cache_|.
210 mutable base::Lock lock_;
212 // Need a separate consumer for each CancelableRequestProvider we interact
213 // with (HistoryService and TopSitesBackend).
214 CancelableRequestConsumer history_consumer_;
215 CancelableTaskTracker cancelable_task_tracker_;
217 // Timer that asks history for the top sites. This is used to make sure our
218 // data stays in sync with history.
219 base::OneShotTimer<TopSitesImpl> timer_;
221 // The time we started |timer_| at. Only valid if |timer_| is running.
222 base::TimeTicks timer_start_time_;
224 content::NotificationRegistrar registrar_;
226 // The number of URLs changed on the last update.
227 size_t last_num_urls_changed_;
229 // The pending requests for the top sites list. Can only be non-empty at
230 // startup. After we read the top sites from the DB, we'll always have a
231 // cached list and be able to run callbacks immediately.
232 PendingCallbacks pending_callbacks_;
234 // Stores thumbnails for unknown pages. When SetPageThumbnail is
235 // called, if we don't know about that URL yet and we don't have
236 // enough Top Sites (new profile), we store it until the next
238 TempImages temp_images_;
240 // URL List of prepopulated page.
241 std::vector<GURL> prepopulated_page_urls_;
246 DISALLOW_COPY_AND_ASSIGN(TopSitesImpl);
249 } // namespace history
251 #endif // CHROME_BROWSER_HISTORY_TOP_SITES_IMPL_H_