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