history_service.h revision 5f1c94371a64b3196d4be9466099bb892df9b88e
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#ifndef CHROME_BROWSER_HISTORY_HISTORY_SERVICE_H_
6#define CHROME_BROWSER_HISTORY_HISTORY_SERVICE_H_
7
8#include <set>
9#include <vector>
10
11#include "base/basictypes.h"
12#include "base/bind.h"
13#include "base/callback.h"
14#include "base/files/file_path.h"
15#include "base/logging.h"
16#include "base/memory/ref_counted.h"
17#include "base/memory/scoped_ptr.h"
18#include "base/memory/weak_ptr.h"
19#include "base/observer_list.h"
20#include "base/strings/string16.h"
21#include "base/task/cancelable_task_tracker.h"
22#include "base/threading/thread_checker.h"
23#include "base/time/time.h"
24#include "chrome/browser/history/delete_directive_handler.h"
25#include "chrome/browser/history/typed_url_syncable_service.h"
26#include "chrome/common/ref_counted_util.h"
27#include "components/favicon_base/favicon_callback.h"
28#include "components/history/core/browser/history_client.h"
29#include "components/history/core/browser/keyword_id.h"
30#include "components/keyed_service/core/keyed_service.h"
31#include "components/visitedlink/browser/visitedlink_delegate.h"
32#include "content/public/browser/download_manager_delegate.h"
33#include "content/public/browser/notification_observer.h"
34#include "content/public/browser/notification_registrar.h"
35#include "content/public/common/page_transition_types.h"
36#include "sql/init_status.h"
37#include "sync/api/syncable_service.h"
38
39#if defined(OS_ANDROID)
40class AndroidHistoryProviderService;
41#endif
42
43class GURL;
44class PageUsageData;
45class PageUsageRequest;
46class Profile;
47struct ImportedFaviconUsage;
48
49namespace base {
50class FilePath;
51class Thread;
52}
53
54namespace visitedlink {
55class VisitedLinkMaster;
56}
57
58namespace history {
59
60class HistoryBackend;
61class HistoryClient;
62class HistoryDatabase;
63class HistoryDBTask;
64class HistoryQueryTest;
65class InMemoryHistoryBackend;
66class InMemoryURLIndex;
67class InMemoryURLIndexTest;
68class URLDatabase;
69class VisitDatabaseObserver;
70class VisitFilter;
71struct DownloadRow;
72struct HistoryAddPageArgs;
73struct HistoryDetails;
74struct KeywordSearchTermVisit;
75
76}  // namespace history
77
78// The history service records page titles, and visit times, as well as
79// (eventually) information about autocomplete.
80//
81// This service is thread safe. Each request callback is invoked in the
82// thread that made the request.
83class HistoryService : public content::NotificationObserver,
84                       public syncer::SyncableService,
85                       public KeyedService,
86                       public visitedlink::VisitedLinkDelegate {
87 public:
88  // Miscellaneous commonly-used types.
89  typedef std::vector<PageUsageData*> PageUsageDataList;
90
91  // Must call Init after construction. The |history::HistoryClient| object
92  // must be valid for the whole lifetime of |HistoryService|.
93  explicit HistoryService(history::HistoryClient* client, Profile* profile);
94  // The empty constructor is provided only for testing.
95  HistoryService();
96
97  virtual ~HistoryService();
98
99  // Initializes the history service, returning true on success. On false, do
100  // not call any other functions. The given directory will be used for storing
101  // the history files.
102  bool Init(const base::FilePath& history_dir) {
103    return Init(history_dir, false);
104  }
105
106  // Triggers the backend to load if it hasn't already, and then returns whether
107  // it's finished loading.
108  // Note: Virtual needed for mocking.
109  virtual bool BackendLoaded();
110
111  // Returns true if the backend has finished loading.
112  bool backend_loaded() const { return backend_loaded_; }
113
114  // Called on shutdown, this will tell the history backend to complete and
115  // will release pointers to it. No other functions should be called once
116  // cleanup has happened that may dispatch to the history thread (because it
117  // will be NULL).
118  //
119  // In practice, this will be called by the service manager (BrowserProcess)
120  // when it is being destroyed. Because that reference is being destroyed, it
121  // should be impossible for anybody else to call the service, even if it is
122  // still in memory (pending requests may be holding a reference to us).
123  void Cleanup();
124
125  // Context ids are used to scope page IDs (see AddPage). These contexts
126  // must tell us when they are being invalidated so that we can clear
127  // out any cached data associated with that context.
128  void ClearCachedDataForContextID(history::ContextID context_id);
129
130  // Triggers the backend to load if it hasn't already, and then returns the
131  // in-memory URL database. The returned pointer MAY BE NULL if the in-memory
132  // database has not been loaded yet. This pointer is owned by the history
133  // system. Callers should not store or cache this value.
134  //
135  // TODO(brettw) this should return the InMemoryHistoryBackend.
136  history::URLDatabase* InMemoryDatabase();
137
138  // Following functions get URL information from in-memory database.
139  // They return false if database is not available (e.g. not loaded yet) or the
140  // URL does not exist.
141
142  // Reads the number of times the user has typed the given URL.
143  bool GetTypedCountForURL(const GURL& url, int* typed_count);
144
145  // Reads the last visit time for the given URL.
146  bool GetLastVisitTimeForURL(const GURL& url, base::Time* last_visit);
147
148  // Reads the number of times this URL has been visited.
149  bool GetVisitCountForURL(const GURL& url, int* visit_count);
150
151  // Returns a pointer to the TypedUrlSyncableService owned by HistoryBackend.
152  // This method should only be called from the history thread, because the
153  // returned service is intended to be accessed only via the history thread.
154  history::TypedUrlSyncableService* GetTypedUrlSyncableService() const;
155
156  // Return the quick history index.
157  history::InMemoryURLIndex* InMemoryIndex() const {
158    return in_memory_url_index_.get();
159  }
160
161  // KeyedService:
162  virtual void Shutdown() OVERRIDE;
163
164  // Navigation ----------------------------------------------------------------
165
166  // Adds the given canonical URL to history with the given time as the visit
167  // time. Referrer may be the empty string.
168  //
169  // The supplied context id is used to scope the given page ID. Page IDs
170  // are only unique inside a given context, so we need that to differentiate
171  // them.
172  //
173  // The context/page ids can be NULL if there is no meaningful tracking
174  // information that can be performed on the given URL. The 'page_id' should
175  // be the ID of the current session history entry in the given process.
176  //
177  // 'redirects' is an array of redirect URLs leading to this page, with the
178  // page itself as the last item (so when there is no redirect, it will have
179  // one entry). If there are no redirects, this array may also be empty for
180  // the convenience of callers.
181  //
182  // 'did_replace_entry' is true when the navigation entry for this page has
183  // replaced the existing entry. A non-user initiated redirect causes such
184  // replacement.
185  //
186  // All "Add Page" functions will update the visited link database.
187  void AddPage(const GURL& url,
188               base::Time time,
189               history::ContextID context_id,
190               int32 page_id,
191               const GURL& referrer,
192               const history::RedirectList& redirects,
193               content::PageTransition transition,
194               history::VisitSource visit_source,
195               bool did_replace_entry);
196
197  // For adding pages to history where no tracking information can be done.
198  void AddPage(const GURL& url,
199               base::Time time,
200               history::VisitSource visit_source);
201
202  // All AddPage variants end up here.
203  void AddPage(const history::HistoryAddPageArgs& add_page_args);
204
205  // Adds an entry for the specified url without creating a visit. This should
206  // only be used when bookmarking a page, otherwise the row leaks in the
207  // history db (it never gets cleaned).
208  void AddPageNoVisitForBookmark(const GURL& url, const base::string16& title);
209
210  // Sets the title for the given page. The page should be in history. If it
211  // is not, this operation is ignored.
212  void SetPageTitle(const GURL& url, const base::string16& title);
213
214  // Updates the history database with a page's ending time stamp information.
215  // The page can be identified by the combination of the context id, the page
216  // id and the url.
217  void UpdateWithPageEndTime(history::ContextID context_id,
218                             int32 page_id,
219                             const GURL& url,
220                             base::Time end_ts);
221
222  // Querying ------------------------------------------------------------------
223
224  // Returns the information about the requested URL. If the URL is found,
225  // success will be true and the information will be in the URLRow parameter.
226  // On success, the visits, if requested, will be sorted by date. If they have
227  // not been requested, the pointer will be valid, but the vector will be
228  // empty.
229  //
230  // If success is false, neither the row nor the vector will be valid.
231  typedef base::Callback<
232      void(bool,  // Success flag, when false, nothing else is valid.
233           const history::URLRow&,
234           const history::VisitVector&)> QueryURLCallback;
235
236  // Queries the basic information about the URL in the history database. If
237  // the caller is interested in the visits (each time the URL is visited),
238  // set |want_visits| to true. If these are not needed, the function will be
239  // faster by setting this to false.
240  base::CancelableTaskTracker::TaskId QueryURL(
241      const GURL& url,
242      bool want_visits,
243      const QueryURLCallback& callback,
244      base::CancelableTaskTracker* tracker);
245
246  // Provides the result of a query. See QueryResults in history_types.h.
247  // The common use will be to use QueryResults.Swap to suck the contents of
248  // the results out of the passed in parameter and take ownership of them.
249  typedef base::Callback<void(history::QueryResults*)> QueryHistoryCallback;
250
251  // Queries all history with the given options (see QueryOptions in
252  // history_types.h).  If empty, all results matching the given options
253  // will be returned.
254  base::CancelableTaskTracker::TaskId QueryHistory(
255      const base::string16& text_query,
256      const history::QueryOptions& options,
257      const QueryHistoryCallback& callback,
258      base::CancelableTaskTracker* tracker);
259
260  // Called when the results of QueryRedirectsFrom are available.
261  // The given vector will contain a list of all redirects, not counting
262  // the original page. If A redirects to B which redirects to C, the vector
263  // will contain [B, C], and A will be in 'from_url'.
264  //
265  // For QueryRedirectsTo, the order is reversed. For A->B->C, the vector will
266  // contain [B, A] and C will be in 'to_url'.
267  //
268  // If there is no such URL in the database or the most recent visit has no
269  // redirect, the vector will be empty. If the given page has redirected to
270  // multiple destinations, this will pick a random one.
271  typedef base::Callback<void(const history::RedirectList*)>
272      QueryRedirectsCallback;
273
274  // Schedules a query for the most recent redirect coming out of the given
275  // URL. See the RedirectQuerySource above, which is guaranteed to be called
276  // if the request is not canceled.
277  base::CancelableTaskTracker::TaskId QueryRedirectsFrom(
278      const GURL& from_url,
279      const QueryRedirectsCallback& callback,
280      base::CancelableTaskTracker* tracker);
281
282  // Schedules a query to get the most recent redirects ending at the given
283  // URL.
284  base::CancelableTaskTracker::TaskId QueryRedirectsTo(
285      const GURL& to_url,
286      const QueryRedirectsCallback& callback,
287      base::CancelableTaskTracker* tracker);
288
289  // Requests the number of user-visible visits (i.e. no redirects or subframes)
290  // to all urls on the same scheme/host/port as |url|.  This is only valid for
291  // HTTP and HTTPS URLs.
292  typedef base::Callback<
293      void(bool,         // Were we able to determine the # of visits?
294           int,          // Number of visits.
295           base::Time)>  // Time of first visit. Only set if bool
296                         // is true and int is > 0.
297      GetVisibleVisitCountToHostCallback;
298
299  base::CancelableTaskTracker::TaskId GetVisibleVisitCountToHost(
300      const GURL& url,
301      const GetVisibleVisitCountToHostCallback& callback,
302      base::CancelableTaskTracker* tracker);
303
304  // Request the |result_count| most visited URLs and the chain of
305  // redirects leading to each of these URLs. |days_back| is the
306  // number of days of history to use. Used by TopSites.
307  typedef base::Callback<void(const history::MostVisitedURLList*)>
308      QueryMostVisitedURLsCallback;
309
310  base::CancelableTaskTracker::TaskId QueryMostVisitedURLs(
311      int result_count,
312      int days_back,
313      const QueryMostVisitedURLsCallback& callback,
314      base::CancelableTaskTracker* tracker);
315
316  // Request the |result_count| URLs filtered and sorted based on the |filter|.
317  // If |extended_info| is true, additional data will be provided in the
318  // results. Computing this additional data is expensive, likely to become
319  // more expensive as additional data points are added in future changes, and
320  // not useful in most cases. Set |extended_info| to true only if you
321  // explicitly require the additional data.
322  typedef base::Callback<void(const history::FilteredURLList*)>
323      QueryFilteredURLsCallback;
324
325  base::CancelableTaskTracker::TaskId QueryFilteredURLs(
326      int result_count,
327      const history::VisitFilter& filter,
328      bool extended_info,
329      const QueryFilteredURLsCallback& callback,
330      base::CancelableTaskTracker* tracker);
331
332  // Database management operations --------------------------------------------
333
334  // Delete all the information related to a single url.
335  void DeleteURL(const GURL& url);
336
337  // Delete all the information related to a list of urls.  (Deleting
338  // URLs one by one is slow as it has to flush to disk each time.)
339  void DeleteURLsForTest(const std::vector<GURL>& urls);
340
341  // Removes all visits in the selected time range (including the
342  // start time), updating the URLs accordingly. This deletes any
343  // associated data. This function also deletes the associated
344  // favicons, if they are no longer referenced. |callback| runs when
345  // the expiration is complete. You may use null Time values to do an
346  // unbounded delete in either direction.
347  // If |restrict_urls| is not empty, only visits to the URLs in this set are
348  // removed.
349  void ExpireHistoryBetween(const std::set<GURL>& restrict_urls,
350                            base::Time begin_time,
351                            base::Time end_time,
352                            const base::Closure& callback,
353                            base::CancelableTaskTracker* tracker);
354
355  // Removes all visits to specified URLs in specific time ranges.
356  // This is the equivalent ExpireHistoryBetween() once for each element in the
357  // vector. The fields of |ExpireHistoryArgs| map directly to the arguments of
358  // of ExpireHistoryBetween().
359  void ExpireHistory(const std::vector<history::ExpireHistoryArgs>& expire_list,
360                     const base::Closure& callback,
361                     base::CancelableTaskTracker* tracker);
362
363  // Removes all visits to the given URLs in the specified time range. Calls
364  // ExpireHistoryBetween() to delete local visits, and handles deletion of
365  // synced visits if appropriate.
366  void ExpireLocalAndRemoteHistoryBetween(const std::set<GURL>& restrict_urls,
367                                          base::Time begin_time,
368                                          base::Time end_time,
369                                          const base::Closure& callback,
370                                          base::CancelableTaskTracker* tracker);
371
372  // Processes the given |delete_directive| and sends it to the
373  // SyncChangeProcessor (if it exists).  Returns any error resulting
374  // from sending the delete directive to sync.
375  syncer::SyncError ProcessLocalDeleteDirective(
376      const sync_pb::HistoryDeleteDirectiveSpecifics& delete_directive);
377
378  // Downloads -----------------------------------------------------------------
379
380  // Implemented by the caller of 'CreateDownload' below, and is called when the
381  // history service has created a new entry for a download in the history db.
382  typedef base::Callback<void(bool)> DownloadCreateCallback;
383
384  // Begins a history request to create a new row for a download. 'info'
385  // contains all the download's creation state, and 'callback' runs when the
386  // history service request is complete. The callback is called on the thread
387  // that calls CreateDownload().
388  void CreateDownload(
389      const history::DownloadRow& info,
390      const DownloadCreateCallback& callback);
391
392  // Responds on the calling thread with the maximum id of all downloads records
393  // in the database plus 1.
394  void GetNextDownloadId(const content::DownloadIdCallback& callback);
395
396  // Implemented by the caller of 'QueryDownloads' below, and is called when the
397  // history service has retrieved a list of all download state. The call
398  typedef base::Callback<void(
399      scoped_ptr<std::vector<history::DownloadRow> >)>
400          DownloadQueryCallback;
401
402  // Begins a history request to retrieve the state of all downloads in the
403  // history db. 'callback' runs when the history service request is complete,
404  // at which point 'info' contains an array of history::DownloadRow, one per
405  // download. The callback is called on the thread that calls QueryDownloads().
406  void QueryDownloads(const DownloadQueryCallback& callback);
407
408  // Called to update the history service about the current state of a download.
409  // This is a 'fire and forget' query, so just pass the relevant state info to
410  // the database with no need for a callback.
411  void UpdateDownload(const history::DownloadRow& data);
412
413  // Permanently remove some downloads from the history system. This is a 'fire
414  // and forget' operation.
415  void RemoveDownloads(const std::set<uint32>& ids);
416
417  // Keyword search terms -----------------------------------------------------
418
419  // Sets the search terms for the specified url and keyword. url_id gives the
420  // id of the url, keyword_id the id of the keyword and term the search term.
421  void SetKeywordSearchTermsForURL(const GURL& url,
422                                   history::KeywordID keyword_id,
423                                   const base::string16& term);
424
425  // Deletes all search terms for the specified keyword.
426  void DeleteAllSearchTermsForKeyword(history::KeywordID keyword_id);
427
428  // Deletes any search term corresponding to |url|.
429  void DeleteKeywordSearchTermForURL(const GURL& url);
430
431  // Deletes all URL and search term entries matching the given |term| and
432  // |keyword_id|.
433  void DeleteMatchingURLsForKeyword(history::KeywordID keyword_id,
434                                    const base::string16& term);
435
436  // Bookmarks -----------------------------------------------------------------
437
438  // Notification that a URL is no longer bookmarked.
439  void URLsNoLongerBookmarked(const std::set<GURL>& urls);
440
441  // Generic Stuff -------------------------------------------------------------
442
443  // Schedules a HistoryDBTask for running on the history backend thread. See
444  // HistoryDBTask for details on what this does. Takes ownership of |task|.
445  virtual void ScheduleDBTask(scoped_ptr<history::HistoryDBTask> task,
446                              base::CancelableTaskTracker* tracker);
447
448  // Adds or removes observers for the VisitDatabase.
449  void AddVisitDatabaseObserver(history::VisitDatabaseObserver* observer);
450  void RemoveVisitDatabaseObserver(history::VisitDatabaseObserver* observer);
451
452  void NotifyVisitDBObserversOnAddVisit(const history::BriefVisitInfo& info);
453
454  // Testing -------------------------------------------------------------------
455
456  // Runs |flushed| after bouncing off the history thread.
457  void FlushForTest(const base::Closure& flushed);
458
459  // Designed for unit tests, this passes the given task on to the history
460  // backend to be called once the history backend has terminated. This allows
461  // callers to know when the history thread is complete and the database files
462  // can be deleted and the next test run. Otherwise, the history thread may
463  // still be running, causing problems in subsequent tests.
464  //
465  // There can be only one closing task, so this will override any previously
466  // set task. We will take ownership of the pointer and delete it when done.
467  // The task will be run on the calling thread (this function is threadsafe).
468  void SetOnBackendDestroyTask(const base::Closure& task);
469
470  // Used for unit testing and potentially importing to get known information
471  // into the database. This assumes the URL doesn't exist in the database
472  //
473  // Calling this function many times may be slow because each call will
474  // dispatch to the history thread and will be a separate database
475  // transaction. If this functionality is needed for importing many URLs,
476  // callers should use AddPagesWithDetails() instead.
477  //
478  // Note that this routine (and AddPageWithDetails()) always adds a single
479  // visit using the |last_visit| timestamp, and a PageTransition type of LINK,
480  // if |visit_source| != SYNCED.
481  void AddPageWithDetails(const GURL& url,
482                          const base::string16& title,
483                          int visit_count,
484                          int typed_count,
485                          base::Time last_visit,
486                          bool hidden,
487                          history::VisitSource visit_source);
488
489  // The same as AddPageWithDetails() but takes a vector.
490  void AddPagesWithDetails(const history::URLRows& info,
491                           history::VisitSource visit_source);
492
493  // Returns true if this looks like the type of URL we want to add to the
494  // history. We filter out some URLs such as JavaScript.
495  static bool CanAddURL(const GURL& url);
496
497  // Returns the HistoryClient.
498  history::HistoryClient* history_client() { return history_client_; }
499
500  base::WeakPtr<HistoryService> AsWeakPtr();
501
502  // syncer::SyncableService implementation.
503  virtual syncer::SyncMergeResult MergeDataAndStartSyncing(
504      syncer::ModelType type,
505      const syncer::SyncDataList& initial_sync_data,
506      scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
507      scoped_ptr<syncer::SyncErrorFactory> error_handler) OVERRIDE;
508  virtual void StopSyncing(syncer::ModelType type) OVERRIDE;
509  virtual syncer::SyncDataList GetAllSyncData(
510      syncer::ModelType type) const OVERRIDE;
511  virtual syncer::SyncError ProcessSyncChanges(
512      const tracked_objects::Location& from_here,
513      const syncer::SyncChangeList& change_list) OVERRIDE;
514
515 protected:
516  // These are not currently used, hopefully we can do something in the future
517  // to ensure that the most important things happen first.
518  enum SchedulePriority {
519    PRIORITY_UI,      // The highest priority (must respond to UI events).
520    PRIORITY_NORMAL,  // Normal stuff like adding a page.
521    PRIORITY_LOW,     // Low priority things like indexing or expiration.
522  };
523
524 private:
525  class BackendDelegate;
526#if defined(OS_ANDROID)
527  friend class AndroidHistoryProviderService;
528#endif
529  friend class base::RefCountedThreadSafe<HistoryService>;
530  friend class BackendDelegate;
531  friend class FaviconService;
532  friend class history::HistoryBackend;
533  friend class history::HistoryQueryTest;
534  friend class HistoryOperation;
535  friend class HistoryQuickProviderTest;
536  friend class HistoryURLProvider;
537  friend class HistoryURLProviderTest;
538  friend class history::InMemoryURLIndexTest;
539  template<typename Info, typename Callback> friend class DownloadRequest;
540  friend class PageUsageRequest;
541  friend class RedirectRequest;
542  friend class TestingProfile;
543
544  // Implementation of content::NotificationObserver.
545  virtual void Observe(int type,
546                       const content::NotificationSource& source,
547                       const content::NotificationDetails& details) OVERRIDE;
548
549  // Implementation of visitedlink::VisitedLinkDelegate.
550  virtual void RebuildTable(
551      const scoped_refptr<URLEnumerator>& enumerator) OVERRIDE;
552
553  // Low-level Init().  Same as the public version, but adds a |no_db| parameter
554  // that is only set by unittests which causes the backend to not init its DB.
555  bool Init(const base::FilePath& history_dir, bool no_db);
556
557  // Called by the HistoryURLProvider class to schedule an autocomplete, it
558  // will be called back on the internal history thread with the history
559  // database so it can query. See history_autocomplete.cc for a diagram.
560  void ScheduleAutocomplete(const base::Callback<
561      void(history::HistoryBackend*, history::URLDatabase*)>& callback);
562
563  // Broadcasts the given notification. This is called by the backend so that
564  // the notification will be broadcast on the main thread.
565  void BroadcastNotificationsHelper(
566      int type,
567      scoped_ptr<history::HistoryDetails> details);
568
569  // Notification from the backend that it has finished loading. Sends
570  // notification (NOTIFY_HISTORY_LOADED) and sets backend_loaded_ to true.
571  void OnDBLoaded();
572
573  // Helper function for getting URL information.
574  // Reads a URLRow from in-memory database. Returns false if database is not
575  // available or the URL does not exist.
576  bool GetRowForURL(const GURL& url, history::URLRow* url_row);
577
578  // Favicon -------------------------------------------------------------------
579
580  // These favicon methods are exposed to the FaviconService. Instead of calling
581  // these methods directly you should call the respective method on the
582  // FaviconService.
583
584  // Used by FaviconService to get the favicon bitmaps from the history backend
585  // whose edge sizes most closely match |desired_sizes| for |icon_types|. If
586  // |desired_sizes| has a '0' entry, the largest favicon bitmap for
587  // |icon_types| is returned. The returned FaviconBitmapResults will have at
588  // most one result for each entry in |desired_sizes|. If a favicon bitmap is
589  // determined to be the best candidate for multiple |desired_sizes| there will
590  // be fewer results.
591  // If |icon_types| has several types, results for only a single type will be
592  // returned in the priority of TOUCH_PRECOMPOSED_ICON, TOUCH_ICON, and
593  // FAVICON.
594  base::CancelableTaskTracker::TaskId GetFavicons(
595      const std::vector<GURL>& icon_urls,
596      int icon_types,
597      const std::vector<int>& desired_sizes,
598      const favicon_base::FaviconResultsCallback& callback,
599      base::CancelableTaskTracker* tracker);
600
601  // Used by the FaviconService to get favicons mapped to |page_url| for
602  // |icon_types| whose edge sizes most closely match |desired_sizes|. If
603  // |desired_sizes| has a '0' entry, the largest favicon bitmap for
604  // |icon_types| is returned. The returned FaviconBitmapResults will have at
605  // most one result for each entry in |desired_sizes|. If a favicon bitmap is
606  // determined to be the best candidate for multiple |desired_sizes| there
607  // will be fewer results. If |icon_types| has several types, results for only
608  // a single type will be returned in the priority of TOUCH_PRECOMPOSED_ICON,
609  // TOUCH_ICON, and FAVICON.
610  base::CancelableTaskTracker::TaskId GetFaviconsForURL(
611      const GURL& page_url,
612      int icon_types,
613      const std::vector<int>& desired_sizes,
614      const favicon_base::FaviconResultsCallback& callback,
615      base::CancelableTaskTracker* tracker);
616
617  // Used by FaviconService to find the first favicon bitmap whose width and
618  // height are greater than that of |minimum_size_in_pixels|. This searches
619  // for icons by IconType. Each element of |icon_types| is a bitmask of
620  // IconTypes indicating the types to search for.
621  // If the largest icon of |icon_types[0]| is not larger than
622  // |minimum_size_in_pixel|, the next icon types of
623  // |icon_types| will be searched and so on.
624  // If no icon is larger than |minimum_size_in_pixel|, the largest one of all
625  // icon types in |icon_types| is returned.
626  // This feature is especially useful when some types of icon is preferred as
627  // long as its size is larger than a specific value.
628  base::CancelableTaskTracker::TaskId GetLargestFaviconForURL(
629      const GURL& page_url,
630      const std::vector<int>& icon_types,
631      int minimum_size_in_pixels,
632      const favicon_base::FaviconRawBitmapCallback& callback,
633      base::CancelableTaskTracker* tracker);
634
635  // Used by the FaviconService to get the favicon bitmap which most closely
636  // matches |desired_size| from the favicon with |favicon_id| from the history
637  // backend. If |desired_size| is 0, the largest favicon bitmap for
638  // |favicon_id| is returned.
639  base::CancelableTaskTracker::TaskId GetFaviconForID(
640      favicon_base::FaviconID favicon_id,
641      int desired_size,
642      const favicon_base::FaviconResultsCallback& callback,
643      base::CancelableTaskTracker* tracker);
644
645  // Used by the FaviconService to replace the favicon mappings to |page_url|
646  // for |icon_types| on the history backend.
647  // Sample |icon_urls|:
648  //  { ICON_URL1 -> TOUCH_ICON, known to the database,
649  //    ICON_URL2 -> TOUCH_ICON, not known to the database,
650  //    ICON_URL3 -> TOUCH_PRECOMPOSED_ICON, known to the database }
651  // The new mappings are computed from |icon_urls| with these rules:
652  // 1) Any urls in |icon_urls| which are not already known to the database are
653  //    rejected.
654  //    Sample new mappings to |page_url|: { ICON_URL1, ICON_URL3 }
655  // 2) If |icon_types| has multiple types, the mappings are only set for the
656  //    largest icon type.
657  //    Sample new mappings to |page_url|: { ICON_URL3 }
658  // |icon_types| can only have multiple IconTypes if
659  // |icon_types| == TOUCH_ICON | TOUCH_PRECOMPOSED_ICON.
660  // The favicon bitmaps whose edge sizes most closely match |desired_sizes|
661  // from the favicons which were just mapped to |page_url| are returned. If
662  // |desired_sizes| has a '0' entry, the largest favicon bitmap is returned.
663  base::CancelableTaskTracker::TaskId UpdateFaviconMappingsAndFetch(
664      const GURL& page_url,
665      const std::vector<GURL>& icon_urls,
666      int icon_types,
667      const std::vector<int>& desired_sizes,
668      const favicon_base::FaviconResultsCallback& callback,
669      base::CancelableTaskTracker* tracker);
670
671  // Used by FaviconService to set a favicon for |page_url| and |icon_url| with
672  // |pixel_size|.
673  // Example:
674  //   |page_url|: www.google.com
675  // 2 favicons in history for |page_url|:
676  //   www.google.com/a.ico  16x16
677  //   www.google.com/b.ico  32x32
678  // MergeFavicon(|page_url|, www.google.com/a.ico, ..., ..., 16x16)
679  //
680  // Merging occurs in the following manner:
681  // 1) |page_url| is set to map to only to |icon_url|. In order to not lose
682  //    data, favicon bitmaps mapped to |page_url| but not to |icon_url| are
683  //    copied to the favicon at |icon_url|.
684  //    For the example above, |page_url| will only be mapped to a.ico.
685  //    The 32x32 favicon bitmap at b.ico is copied to a.ico
686  // 2) |bitmap_data| is added to the favicon at |icon_url|, overwriting any
687  //    favicon bitmaps of |pixel_size|.
688  //    For the example above, |bitmap_data| overwrites the 16x16 favicon
689  //    bitmap for a.ico.
690  // TODO(pkotwicz): Remove once no longer required by sync.
691  void MergeFavicon(const GURL& page_url,
692                    const GURL& icon_url,
693                    favicon_base::IconType icon_type,
694                    scoped_refptr<base::RefCountedMemory> bitmap_data,
695                    const gfx::Size& pixel_size);
696
697  // Used by the FaviconService to set the favicons for a page on the history
698  // backend.
699  // |favicon_bitmap_data| replaces all the favicon bitmaps mapped to
700  // |page_url|.
701  // |expired| and |icon_type| fields in FaviconBitmapData are ignored.
702  // Use MergeFavicon() if |favicon_bitmap_data| is incomplete, and favicon
703  // bitmaps in the database should be preserved if possible. For instance,
704  // favicon bitmaps from sync are 1x only. MergeFavicon() is used to avoid
705  // deleting the 2x favicon bitmap if it is present in the history backend.
706  // See HistoryBackend::ValidateSetFaviconsParams() for more details on the
707  // criteria for |favicon_bitmap_data| to be valid.
708  void SetFavicons(const GURL& page_url,
709                   favicon_base::IconType icon_type,
710                   const std::vector<favicon_base::FaviconRawBitmapData>&
711                       favicon_bitmap_data);
712
713  // Used by the FaviconService to mark the favicon for the page as being out
714  // of date.
715  void SetFaviconsOutOfDateForPage(const GURL& page_url);
716
717  // Used by the FaviconService to clone favicons from one page to another,
718  // provided that other page does not already have favicons.
719  void CloneFavicons(const GURL& old_page_url, const GURL& new_page_url);
720
721  // Used by the FaviconService for importing many favicons for many pages at
722  // once. The pages must exist, any favicon sets for unknown pages will be
723  // discarded. Existing favicons will not be overwritten.
724  void SetImportedFavicons(
725      const std::vector<ImportedFaviconUsage>& favicon_usage);
726
727  // Sets the in-memory URL database. This is called by the backend once the
728  // database is loaded to make it available.
729  void SetInMemoryBackend(
730      scoped_ptr<history::InMemoryHistoryBackend> mem_backend);
731
732  // Called by our BackendDelegate when there is a problem reading the database.
733  void NotifyProfileError(sql::InitStatus init_status);
734
735  // Call to schedule a given task for running on the history thread with the
736  // specified priority. The task will have ownership taken.
737  void ScheduleTask(SchedulePriority priority, const base::Closure& task);
738
739  // ScheduleAndForget ---------------------------------------------------------
740  //
741  // Functions for scheduling operations on the history thread that do not need
742  // any callbacks and are not cancelable.
743
744  template<typename BackendFunc>
745  void ScheduleAndForget(SchedulePriority priority,
746                         BackendFunc func) {  // Function to call on backend.
747    DCHECK(thread_) << "History service being called after cleanup";
748    DCHECK(thread_checker_.CalledOnValidThread());
749    ScheduleTask(priority, base::Bind(func, history_backend_.get()));
750  }
751
752  template<typename BackendFunc, typename ArgA>
753  void ScheduleAndForget(SchedulePriority priority,
754                         BackendFunc func,  // Function to call on backend.
755                         const ArgA& a) {
756    DCHECK(thread_) << "History service being called after cleanup";
757    DCHECK(thread_checker_.CalledOnValidThread());
758    ScheduleTask(priority, base::Bind(func, history_backend_.get(), a));
759  }
760
761  template<typename BackendFunc, typename ArgA, typename ArgB>
762  void ScheduleAndForget(SchedulePriority priority,
763                         BackendFunc func,  // Function to call on backend.
764                         const ArgA& a,
765                         const ArgB& b) {
766    DCHECK(thread_) << "History service being called after cleanup";
767    DCHECK(thread_checker_.CalledOnValidThread());
768    ScheduleTask(priority, base::Bind(func, history_backend_.get(), a, b));
769  }
770
771  template<typename BackendFunc, typename ArgA, typename ArgB, typename ArgC>
772  void ScheduleAndForget(SchedulePriority priority,
773                         BackendFunc func,  // Function to call on backend.
774                         const ArgA& a,
775                         const ArgB& b,
776                         const ArgC& c) {
777    DCHECK(thread_) << "History service being called after cleanup";
778    DCHECK(thread_checker_.CalledOnValidThread());
779    ScheduleTask(priority, base::Bind(func, history_backend_.get(), a, b, c));
780  }
781
782  template<typename BackendFunc,
783           typename ArgA,
784           typename ArgB,
785           typename ArgC,
786           typename ArgD>
787  void ScheduleAndForget(SchedulePriority priority,
788                         BackendFunc func,  // Function to call on backend.
789                         const ArgA& a,
790                         const ArgB& b,
791                         const ArgC& c,
792                         const ArgD& d) {
793    DCHECK(thread_) << "History service being called after cleanup";
794    DCHECK(thread_checker_.CalledOnValidThread());
795    ScheduleTask(priority, base::Bind(func, history_backend_.get(),
796                                      a, b, c, d));
797  }
798
799  template<typename BackendFunc,
800           typename ArgA,
801           typename ArgB,
802           typename ArgC,
803           typename ArgD,
804           typename ArgE>
805  void ScheduleAndForget(SchedulePriority priority,
806                         BackendFunc func,  // Function to call on backend.
807                         const ArgA& a,
808                         const ArgB& b,
809                         const ArgC& c,
810                         const ArgD& d,
811                         const ArgE& e) {
812    DCHECK(thread_) << "History service being called after cleanup";
813    DCHECK(thread_checker_.CalledOnValidThread());
814    ScheduleTask(priority, base::Bind(func, history_backend_.get(),
815                                      a, b, c, d, e));
816  }
817
818  // All vended weak pointers are invalidated in Cleanup().
819  base::WeakPtrFactory<HistoryService> weak_ptr_factory_;
820
821  base::ThreadChecker thread_checker_;
822
823  content::NotificationRegistrar registrar_;
824
825  // The thread used by the history service to run complicated operations.
826  // |thread_| is NULL once |Cleanup| is NULL.
827  base::Thread* thread_;
828
829  // This class has most of the implementation and runs on the 'thread_'.
830  // You MUST communicate with this class ONLY through the thread_'s
831  // message_loop().
832  //
833  // This pointer will be NULL once Cleanup() has been called, meaning no
834  // more calls should be made to the history thread.
835  scoped_refptr<history::HistoryBackend> history_backend_;
836
837  // A cache of the user-typed URLs kept in memory that is used by the
838  // autocomplete system. This will be NULL until the database has been created
839  // on the background thread.
840  // TODO(mrossetti): Consider changing ownership. See http://crbug.com/138321
841  scoped_ptr<history::InMemoryHistoryBackend> in_memory_backend_;
842
843  // The history client, may be null when testing. The object should otherwise
844  // outlive |HistoryService|.
845  history::HistoryClient* history_client_;
846
847  // The profile, may be null when testing.
848  Profile* profile_;
849
850  // Used for propagating link highlighting data across renderers. May be null
851  // in tests.
852  scoped_ptr<visitedlink::VisitedLinkMaster> visitedlink_master_;
853
854  // Has the backend finished loading? The backend is loaded once Init has
855  // completed.
856  bool backend_loaded_;
857
858  // Cached values from Init(), used whenever we need to reload the backend.
859  base::FilePath history_dir_;
860  bool no_db_;
861
862  // The index used for quick history lookups.
863  // TODO(mrossetti): Move in_memory_url_index out of history_service.
864  // See http://crbug.com/138321
865  scoped_ptr<history::InMemoryURLIndex> in_memory_url_index_;
866
867  ObserverList<history::VisitDatabaseObserver> visit_database_observers_;
868
869  history::DeleteDirectiveHandler delete_directive_handler_;
870
871  DISALLOW_COPY_AND_ASSIGN(HistoryService);
872};
873
874#endif  // CHROME_BROWSER_HISTORY_HISTORY_SERVICE_H_
875