Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / history / history_service.h
index fec0c64..7e7eb10 100644 (file)
@@ -11,6 +11,7 @@
 #include "base/basictypes.h"
 #include "base/bind.h"
 #include "base/callback.h"
+#include "base/callback_list.h"
 #include "base/files/file_path.h"
 #include "base/logging.h"
 #include "base/memory/ref_counted.h"
 #include "base/task/cancelable_task_tracker.h"
 #include "base/threading/thread_checker.h"
 #include "base/time/time.h"
-#include "chrome/browser/common/cancelable_request.h"
-#include "chrome/browser/favicon/favicon_service.h"
 #include "chrome/browser/history/delete_directive_handler.h"
-#include "chrome/browser/history/history_types.h"
 #include "chrome/browser/history/typed_url_syncable_service.h"
-#include "chrome/browser/search_engines/template_url_id.h"
 #include "chrome/common/ref_counted_util.h"
+#include "components/favicon_base/favicon_callback.h"
+#include "components/history/core/browser/history_client.h"
+#include "components/history/core/browser/keyword_id.h"
 #include "components/keyed_service/core/keyed_service.h"
 #include "components/visitedlink/browser/visitedlink_delegate.h"
 #include "content/public/browser/download_manager_delegate.h"
 #include "content/public/browser/notification_observer.h"
 #include "content/public/browser/notification_registrar.h"
-#include "content/public/common/page_transition_types.h"
 #include "sql/init_status.h"
 #include "sync/api/syncable_service.h"
-#include "ui/base/layout.h"
+#include "ui/base/page_transition_types.h"
 
 #if defined(OS_ANDROID)
-#include "chrome/browser/history/android/android_history_provider_service.h"
+class AndroidHistoryProviderService;
 #endif
 
-class BookmarkService;
 class GURL;
-class HistoryURLProvider;
 class PageUsageData;
 class PageUsageRequest;
 class Profile;
-struct HistoryURLProviderParams;
+struct ImportedFaviconUsage;
+class SkBitmap;
 
 namespace base {
 class FilePath;
@@ -62,18 +60,21 @@ class VisitedLinkMaster;
 namespace history {
 
 class HistoryBackend;
+class HistoryClient;
 class HistoryDatabase;
 class HistoryDBTask;
 class HistoryQueryTest;
+class HistoryServiceObserver;
+class HistoryTest;
 class InMemoryHistoryBackend;
 class InMemoryURLIndex;
 class InMemoryURLIndexTest;
 class URLDatabase;
-class VisitDatabaseObserver;
 class VisitFilter;
 struct DownloadRow;
 struct HistoryAddPageArgs;
 struct HistoryDetails;
+struct KeywordSearchTermVisit;
 
 }  // namespace history
 
@@ -82,8 +83,7 @@ struct HistoryDetails;
 //
 // This service is thread safe. Each request callback is invoked in the
 // thread that made the request.
-class HistoryService : public CancelableRequestProvider,
-                       public content::NotificationObserver,
+class HistoryService : public content::NotificationObserver,
                        public syncer::SyncableService,
                        public KeyedService,
                        public visitedlink::VisitedLinkDelegate {
@@ -91,19 +91,19 @@ class HistoryService : public CancelableRequestProvider,
   // Miscellaneous commonly-used types.
   typedef std::vector<PageUsageData*> PageUsageDataList;
 
-  // Must call Init after construction.
-  explicit HistoryService(Profile* profile);
+  // Must call Init after construction. The |history::HistoryClient| object
+  // must be valid for the whole lifetime of |HistoryService|.
+  explicit HistoryService(history::HistoryClient* client, Profile* profile);
   // The empty constructor is provided only for testing.
   HistoryService();
 
-  virtual ~HistoryService();
+  ~HistoryService() override;
 
   // Initializes the history service, returning true on success. On false, do
   // not call any other functions. The given directory will be used for storing
-  // the history files. The BookmarkService is used when deleting URLs to
-  // test if a URL is bookmarked; it may be NULL during testing.
-  bool Init(const base::FilePath& history_dir, BookmarkService* bookmark_service) {
-    return Init(history_dir, bookmark_service, false);
+  // the history files.
+  bool Init(const base::FilePath& history_dir) {
+    return Init(history_dir, false);
   }
 
   // Triggers the backend to load if it hasn't already, and then returns whether
@@ -114,24 +114,10 @@ class HistoryService : public CancelableRequestProvider,
   // Returns true if the backend has finished loading.
   bool backend_loaded() const { return backend_loaded_; }
 
-  // Called on shutdown, this will tell the history backend to complete and
-  // will release pointers to it. No other functions should be called once
-  // cleanup has happened that may dispatch to the history thread (because it
-  // will be NULL).
-  //
-  // In practice, this will be called by the service manager (BrowserProcess)
-  // when it is being destroyed. Because that reference is being destroyed, it
-  // should be impossible for anybody else to call the service, even if it is
-  // still in memory (pending requests may be holding a reference to us).
-  void Cleanup();
-
-  // RenderProcessHost pointers are used to scope page IDs (see AddPage). These
-  // objects must tell us when they are being destroyed so that we can clear
-  // out any cached data associated with that scope.
-  //
-  // The given pointer will not be dereferenced, it is only used for
-  // identification purposes, hence it is a void*.
-  void NotifyRenderProcessHostDestruction(const void* host);
+  // Context ids are used to scope page IDs (see AddPage). These contexts
+  // must tell us when they are being invalidated so that we can clear
+  // out any cached data associated with that context.
+  void ClearCachedDataForContextID(history::ContextID context_id);
 
   // Triggers the backend to load if it hasn't already, and then returns the
   // in-memory URL database. The returned pointer MAY BE NULL if the in-memory
@@ -165,21 +151,20 @@ class HistoryService : public CancelableRequestProvider,
   }
 
   // KeyedService:
-  virtual void Shutdown() OVERRIDE;
+  void Shutdown() override;
 
   // Navigation ----------------------------------------------------------------
 
   // Adds the given canonical URL to history with the given time as the visit
   // time. Referrer may be the empty string.
   //
-  // The supplied render process host is used to scope the given page ID. Page
-  // IDs are only unique inside a given render process, so we need that to
-  // differentiate them. This pointer should not be dereferenced by the history
-  // system.
+  // The supplied context id is used to scope the given page ID. Page IDs
+  // are only unique inside a given context, so we need that to differentiate
+  // them.
   //
-  // The scope/ids can be NULL if there is no meaningful tracking information
-  // that can be performed on the given URL. The 'page_id' should be the ID of
-  // the current session history entry in the given process.
+  // The context/page ids can be NULL if there is no meaningful tracking
+  // information that can be performed on the given URL. The 'page_id' should
+  // be the ID of the current session history entry in the given process.
   //
   // 'redirects' is an array of redirect URLs leading to this page, with the
   // page itself as the last item (so when there is no redirect, it will have
@@ -193,11 +178,11 @@ class HistoryService : public CancelableRequestProvider,
   // All "Add Page" functions will update the visited link database.
   void AddPage(const GURL& url,
                base::Time time,
-               const void* id_scope,
+               history::ContextID context_id,
                int32 page_id,
                const GURL& referrer,
                const history::RedirectList& redirects,
-               content::PageTransition transition,
+               ui::PageTransition transition,
                history::VisitSource visit_source,
                bool did_replace_entry);
 
@@ -219,12 +204,9 @@ class HistoryService : public CancelableRequestProvider,
   void SetPageTitle(const GURL& url, const base::string16& title);
 
   // Updates the history database with a page's ending time stamp information.
-  // The page can be identified by the combination of the pointer to
-  // a RenderProcessHost, the page id and the url.
-  //
-  // The given pointer will not be dereferenced, it is only used for
-  // identification purposes, hence it is a void*.
-  void UpdateWithPageEndTime(const void* host,
+  // The page can be identified by the combination of the context id, the page
+  // id and the url.
+  void UpdateWithPageEndTime(history::ContextID context_id,
                              int32 page_id,
                              const GURL& url,
                              base::Time end_ts);
@@ -238,34 +220,34 @@ class HistoryService : public CancelableRequestProvider,
   // empty.
   //
   // If success is false, neither the row nor the vector will be valid.
-  typedef base::Callback<void(
-      Handle,
-      bool,  // Success flag, when false, nothing else is valid.
-      const history::URLRow*,
-      history::VisitVector*)> QueryURLCallback;
+  typedef base::Callback<
+      void(bool,  // Success flag, when false, nothing else is valid.
+           const history::URLRow&,
+           const history::VisitVector&)> QueryURLCallback;
 
   // Queries the basic information about the URL in the history database. If
   // the caller is interested in the visits (each time the URL is visited),
   // set |want_visits| to true. If these are not needed, the function will be
   // faster by setting this to false.
-  Handle QueryURL(const GURL& url,
-                  bool want_visits,
-                  CancelableRequestConsumerBase* consumer,
-                  const QueryURLCallback& callback);
+  base::CancelableTaskTracker::TaskId QueryURL(
+      const GURL& url,
+      bool want_visits,
+      const QueryURLCallback& callback,
+      base::CancelableTaskTracker* tracker);
 
   // Provides the result of a query. See QueryResults in history_types.h.
   // The common use will be to use QueryResults.Swap to suck the contents of
   // the results out of the passed in parameter and take ownership of them.
-  typedef base::Callback<void(Handle, history::QueryResults*)>
-      QueryHistoryCallback;
+  typedef base::Callback<void(history::QueryResults*)> QueryHistoryCallback;
 
   // Queries all history with the given options (see QueryOptions in
   // history_types.h).  If empty, all results matching the given options
   // will be returned.
-  Handle QueryHistory(const base::string16& text_query,
-                      const history::QueryOptions& options,
-                      CancelableRequestConsumerBase* consumer,
-                      const QueryHistoryCallback& callback);
+  base::CancelableTaskTracker::TaskId QueryHistory(
+      const base::string16& text_query,
+      const history::QueryOptions& options,
+      const QueryHistoryCallback& callback,
+      base::CancelableTaskTracker* tracker);
 
   // Called when the results of QueryRedirectsFrom are available.
   // The given vector will contain a list of all redirects, not counting
@@ -276,75 +258,52 @@ class HistoryService : public CancelableRequestProvider,
   // contain [B, A] and C will be in 'to_url'.
   //
   // If there is no such URL in the database or the most recent visit has no
-  // redirect, the vector will be empty. If the history system failed for
-  // some reason, success will additionally be false. If the given page
-  // has redirected to multiple destinations, this will pick a random one.
-  typedef base::Callback<void(Handle,
-                              GURL,  // from_url / to_url
-                              bool,  // success
-                              history::RedirectList*)> QueryRedirectsCallback;
+  // redirect, the vector will be empty. If the given page has redirected to
+  // multiple destinations, this will pick a random one.
+  typedef base::Callback<void(const history::RedirectList*)>
+      QueryRedirectsCallback;
 
   // Schedules a query for the most recent redirect coming out of the given
   // URL. See the RedirectQuerySource above, which is guaranteed to be called
   // if the request is not canceled.
-  Handle QueryRedirectsFrom(const GURL& from_url,
-                            CancelableRequestConsumerBase* consumer,
-                            const QueryRedirectsCallback& callback);
+  base::CancelableTaskTracker::TaskId QueryRedirectsFrom(
+      const GURL& from_url,
+      const QueryRedirectsCallback& callback,
+      base::CancelableTaskTracker* tracker);
 
   // Schedules a query to get the most recent redirects ending at the given
   // URL.
-  Handle QueryRedirectsTo(const GURL& to_url,
-                          CancelableRequestConsumerBase* consumer,
-                          const QueryRedirectsCallback& callback);
-
-  typedef base::Callback<
-      void(Handle,
-           bool,        // Were we able to determine the # of visits?
-           int,         // Number of visits.
-           base::Time)> // Time of first visit. Only set if bool
-                        // is true and int is > 0.
-      GetVisibleVisitCountToHostCallback;
+  base::CancelableTaskTracker::TaskId QueryRedirectsTo(
+      const GURL& to_url,
+      const QueryRedirectsCallback& callback,
+      base::CancelableTaskTracker* tracker);
 
   // Requests the number of user-visible visits (i.e. no redirects or subframes)
   // to all urls on the same scheme/host/port as |url|.  This is only valid for
   // HTTP and HTTPS URLs.
-  Handle GetVisibleVisitCountToHost(
-      const GURL& url,
-      CancelableRequestConsumerBase* consumer,
-      const GetVisibleVisitCountToHostCallback& callback);
-
-  // Called when QueryTopURLsAndRedirects completes. The vector contains a list
-  // of the top |result_count| URLs.  For each of these URLs, there is an entry
-  // in the map containing redirects from the URL.  For example, if we have the
-  // redirect chain A -> B -> C and A is a top visited URL, then A will be in
-  // the vector and "A => {B -> C}" will be in the map.
   typedef base::Callback<
-      void(Handle,
-           bool,  // Did we get the top urls and redirects?
-           std::vector<GURL>*,  // List of top URLs.
-           history::RedirectMap*)>  // Redirects for top URLs.
-      QueryTopURLsAndRedirectsCallback;
-
-  // Request the top |result_count| most visited URLs and the chain of redirects
-  // leading to each of these URLs.
-  // TODO(Nik): remove this. Use QueryMostVisitedURLs instead.
-  Handle QueryTopURLsAndRedirects(
-      int result_count,
-      CancelableRequestConsumerBase* consumer,
-      const QueryTopURLsAndRedirectsCallback& callback);
-
-  typedef base::Callback<void(Handle, history::MostVisitedURLList)>
-      QueryMostVisitedURLsCallback;
+      void(bool,         // Were we able to determine the # of visits?
+           int,          // Number of visits.
+           base::Time)>  // Time of first visit. Only set if bool
+                         // is true and int is > 0.
+      GetVisibleVisitCountToHostCallback;
 
-  typedef base::Callback<void(Handle, const history::FilteredURLList&)>
-      QueryFilteredURLsCallback;
+  base::CancelableTaskTracker::TaskId GetVisibleVisitCountToHost(
+      const GURL& url,
+      const GetVisibleVisitCountToHostCallback& callback,
+      base::CancelableTaskTracker* tracker);
 
   // Request the |result_count| most visited URLs and the chain of
   // redirects leading to each of these URLs. |days_back| is the
   // number of days of history to use. Used by TopSites.
-  Handle QueryMostVisitedURLs(int result_count, int days_back,
-                              CancelableRequestConsumerBase* consumer,
-                              const QueryMostVisitedURLsCallback& callback);
+  typedef base::Callback<void(const history::MostVisitedURLList*)>
+      QueryMostVisitedURLsCallback;
+
+  base::CancelableTaskTracker::TaskId QueryMostVisitedURLs(
+      int result_count,
+      int days_back,
+      const QueryMostVisitedURLsCallback& callback,
+      base::CancelableTaskTracker* tracker);
 
   // Request the |result_count| URLs filtered and sorted based on the |filter|.
   // If |extended_info| is true, additional data will be provided in the
@@ -352,12 +311,15 @@ class HistoryService : public CancelableRequestProvider,
   // more expensive as additional data points are added in future changes, and
   // not useful in most cases. Set |extended_info| to true only if you
   // explicitly require the additional data.
-  Handle QueryFilteredURLs(
+  typedef base::Callback<void(const history::FilteredURLList*)>
+      QueryFilteredURLsCallback;
+
+  base::CancelableTaskTracker::TaskId QueryFilteredURLs(
       int result_count,
       const history::VisitFilter& filter,
       bool extended_info,
-      CancelableRequestConsumerBase* consumer,
-      const QueryFilteredURLsCallback& callback);
+      const QueryFilteredURLsCallback& callback,
+      base::CancelableTaskTracker* tracker);
 
   // Database management operations --------------------------------------------
 
@@ -444,61 +406,23 @@ class HistoryService : public CancelableRequestProvider,
   // and forget' operation.
   void RemoveDownloads(const std::set<uint32>& ids);
 
-  // Visit Segments ------------------------------------------------------------
-
-  typedef base::Callback<void(Handle, std::vector<PageUsageData*>*)>
-      SegmentQueryCallback;
-
-  // Query usage data for all visit segments since the provided time.
-  //
-  // The request is performed asynchronously and can be cancelled by using the
-  // returned handle.
-  //
-  // The vector provided to the callback and its contents is owned by the
-  // history system. It will be deeply deleted after the callback is invoked.
-  // If you want to preserve any PageUsageData instance, simply remove them
-  // from the vector.
-  //
-  // The vector contains a list of PageUsageData. Each PageUsageData ID is set
-  // to the segment ID. The URL and all the other information is set to the page
-  // representing the segment.
-  Handle QuerySegmentUsageSince(CancelableRequestConsumerBase* consumer,
-                                const base::Time from_time,
-                                int max_result_count,
-                                const SegmentQueryCallback& callback);
-
   // Keyword search terms -----------------------------------------------------
 
   // Sets the search terms for the specified url and keyword. url_id gives the
   // id of the url, keyword_id the id of the keyword and term the search term.
   void SetKeywordSearchTermsForURL(const GURL& url,
-                                   TemplateURLID keyword_id,
+                                   history::KeywordID keyword_id,
                                    const base::string16& term);
 
   // Deletes all search terms for the specified keyword.
-  void DeleteAllSearchTermsForKeyword(TemplateURLID keyword_id);
-
-  typedef base::Callback<
-      void(Handle, std::vector<history::KeywordSearchTermVisit>*)>
-          GetMostRecentKeywordSearchTermsCallback;
-
-  // Returns up to max_count of the most recent search terms starting with the
-  // specified text. The matching is case insensitive. The results are ordered
-  // in descending order up to |max_count| with the most recent search term
-  // first.
-  Handle GetMostRecentKeywordSearchTerms(
-      TemplateURLID keyword_id,
-      const base::string16& prefix,
-      int max_count,
-      CancelableRequestConsumerBase* consumer,
-      const GetMostRecentKeywordSearchTermsCallback& callback);
+  void DeleteAllSearchTermsForKeyword(history::KeywordID keyword_id);
 
   // Deletes any search term corresponding to |url|.
   void DeleteKeywordSearchTermForURL(const GURL& url);
 
   // Deletes all URL and search term entries matching the given |term| and
   // |keyword_id|.
-  void DeleteMatchingURLsForKeyword(TemplateURLID keyword_id,
+  void DeleteMatchingURLsForKeyword(history::KeywordID keyword_id,
                                     const base::string16& term);
 
   // Bookmarks -----------------------------------------------------------------
@@ -506,18 +430,28 @@ class HistoryService : public CancelableRequestProvider,
   // Notification that a URL is no longer bookmarked.
   void URLsNoLongerBookmarked(const std::set<GURL>& urls);
 
+  // Observers -----------------------------------------------------------------
+
+  // Adds/Removes an Observer.
+  void AddObserver(history::HistoryServiceObserver* observer);
+  void RemoveObserver(history::HistoryServiceObserver* observer);
+
   // Generic Stuff -------------------------------------------------------------
 
   // Schedules a HistoryDBTask for running on the history backend thread. See
-  // HistoryDBTask for details on what this does.
-  virtual void ScheduleDBTask(history::HistoryDBTask* task,
-                              CancelableRequestConsumerBase* consumer);
+  // HistoryDBTask for details on what this does. Takes ownership of |task|.
+  virtual void ScheduleDBTask(scoped_ptr<history::HistoryDBTask> task,
+                              base::CancelableTaskTracker* tracker);
 
-  // Adds or removes observers for the VisitDatabase.
-  void AddVisitDatabaseObserver(history::VisitDatabaseObserver* observer);
-  void RemoveVisitDatabaseObserver(history::VisitDatabaseObserver* observer);
+  // This callback is invoked when favicon change for urls.
+  typedef base::Callback<void(const std::set<GURL>&)> OnFaviconChangedCallback;
 
-  void NotifyVisitDBObserversOnAddVisit(const history::BriefVisitInfo& info);
+  // Add a callback to the list. The callback will remain registered until the
+  // returned Subscription is destroyed. This must occurs before HistoryService
+  // is destroyed.
+  scoped_ptr<base::CallbackList<void(const std::set<GURL>&)>::Subscription>
+      AddFaviconChangedCallback(const OnFaviconChangedCallback& callback)
+      WARN_UNUSED_RESULT;
 
   // Testing -------------------------------------------------------------------
 
@@ -562,20 +496,22 @@ class HistoryService : public CancelableRequestProvider,
   // history. We filter out some URLs such as JavaScript.
   static bool CanAddURL(const GURL& url);
 
+  // Returns the HistoryClient.
+  history::HistoryClient* history_client() { return history_client_; }
+
   base::WeakPtr<HistoryService> AsWeakPtr();
 
   // syncer::SyncableService implementation.
-  virtual syncer::SyncMergeResult MergeDataAndStartSyncing(
+  syncer::SyncMergeResult MergeDataAndStartSyncing(
       syncer::ModelType type,
       const syncer::SyncDataList& initial_sync_data,
       scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
-      scoped_ptr<syncer::SyncErrorFactory> error_handler) OVERRIDE;
-  virtual void StopSyncing(syncer::ModelType type) OVERRIDE;
-  virtual syncer::SyncDataList GetAllSyncData(
-      syncer::ModelType type) const OVERRIDE;
-  virtual syncer::SyncError ProcessSyncChanges(
+      scoped_ptr<syncer::SyncErrorFactory> error_handler) override;
+  void StopSyncing(syncer::ModelType type) override;
+  syncer::SyncDataList GetAllSyncData(syncer::ModelType type) const override;
+  syncer::SyncError ProcessSyncChanges(
       const tracked_objects::Location& from_here,
-      const syncer::SyncChangeList& change_list) OVERRIDE;
+      const syncer::SyncChangeList& change_list) override;
 
  protected:
   // These are not currently used, hopefully we can do something in the future
@@ -598,6 +534,7 @@ class HistoryService : public CancelableRequestProvider,
   friend class history::HistoryQueryTest;
   friend class HistoryOperation;
   friend class HistoryQuickProviderTest;
+  friend class history::HistoryTest;
   friend class HistoryURLProvider;
   friend class HistoryURLProviderTest;
   friend class history::InMemoryURLIndexTest;
@@ -606,26 +543,34 @@ class HistoryService : public CancelableRequestProvider,
   friend class RedirectRequest;
   friend class TestingProfile;
 
+  // Called on shutdown, this will tell the history backend to complete and
+  // will release pointers to it. No other functions should be called once
+  // cleanup has happened that may dispatch to the history thread (because it
+  // will be NULL).
+  //
+  // In practice, this will be called by the service manager (BrowserProcess)
+  // when it is being destroyed. Because that reference is being destroyed, it
+  // should be impossible for anybody else to call the service, even if it is
+  // still in memory (pending requests may be holding a reference to us).
+  void Cleanup();
+
   // Implementation of content::NotificationObserver.
-  virtual void Observe(int type,
-                       const content::NotificationSource& source,
-                       const content::NotificationDetails& details) OVERRIDE;
+  void Observe(int type,
+               const content::NotificationSource& source,
+               const content::NotificationDetails& details) override;
 
   // Implementation of visitedlink::VisitedLinkDelegate.
-  virtual void RebuildTable(
-      const scoped_refptr<URLEnumerator>& enumerator) OVERRIDE;
+  void RebuildTable(const scoped_refptr<URLEnumerator>& enumerator) override;
 
   // Low-level Init().  Same as the public version, but adds a |no_db| parameter
   // that is only set by unittests which causes the backend to not init its DB.
-  bool Init(const base::FilePath& history_dir,
-            BookmarkService* bookmark_service,
-            bool no_db);
+  bool Init(const base::FilePath& history_dir, bool no_db);
 
   // Called by the HistoryURLProvider class to schedule an autocomplete, it
   // will be called back on the internal history thread with the history
   // database so it can query. See history_autocomplete.cc for a diagram.
-  void ScheduleAutocomplete(HistoryURLProvider* provider,
-                            HistoryURLProviderParams* params);
+  void ScheduleAutocomplete(const base::Callback<
+      void(history::HistoryBackend*, history::URLDatabase*)>& callback);
 
   // Broadcasts the given notification. This is called by the backend so that
   // the notification will be broadcast on the main thread.
@@ -642,6 +587,22 @@ class HistoryService : public CancelableRequestProvider,
   // available or the URL does not exist.
   bool GetRowForURL(const GURL& url, history::URLRow* url_row);
 
+  // Observers ----------------------------------------------------------------
+
+  // Notify all Observers registered that the VisitDatabase was changed.
+  void NotifyAddVisit(const history::BriefVisitInfo& info);
+
+  // Notify all HistoryServiceObservers registered that user is visiting a URL.
+  // The |row| ID will be set to the value that is currently in effect in the
+  // main history database. |redirects| is the list of redirects leading up to
+  // the URL. If we have a redirect chain A -> B -> C and user is visiting C,
+  // then |redirects[0]=B| and |redirects[1]=A|. If there are no redirects,
+  // |redirects| is an empty vector.
+  void NotifyURLVisited(ui::PageTransition transition,
+                        const history::URLRow& row,
+                        const history::RedirectList& redirects,
+                        base::Time visit_time);
+
   // Favicon -------------------------------------------------------------------
 
   // These favicon methods are exposed to the FaviconService. Instead of calling
@@ -649,38 +610,36 @@ class HistoryService : public CancelableRequestProvider,
   // FaviconService.
 
   // Used by FaviconService to get the favicon bitmaps from the history backend
-  // which most closely match |desired_size_in_dip| x |desired_size_in_dip| and
-  // |desired_scale_factors| for |icon_types|. If |desired_size_in_dip| is 0,
-  // the largest favicon bitmap for |icon_types| is returned. The returned
-  // FaviconBitmapResults will have at most one result for each of
-  // |desired_scale_factors|. If a favicon bitmap is determined to be the best
-  // candidate for multiple scale factors there will be less results.
+  // whose edge sizes most closely match |desired_sizes| for |icon_types|. If
+  // |desired_sizes| has a '0' entry, the largest favicon bitmap for
+  // |icon_types| is returned. The returned FaviconBitmapResults will have at
+  // most one result for each entry in |desired_sizes|. If a favicon bitmap is
+  // determined to be the best candidate for multiple |desired_sizes| there will
+  // be fewer results.
   // If |icon_types| has several types, results for only a single type will be
   // returned in the priority of TOUCH_PRECOMPOSED_ICON, TOUCH_ICON, and
   // FAVICON.
   base::CancelableTaskTracker::TaskId GetFavicons(
       const std::vector<GURL>& icon_urls,
       int icon_types,
-      int desired_size_in_dip,
-      const std::vector<ui::ScaleFactor>& desired_scale_factors,
-      const FaviconService::FaviconResultsCallback& callback,
+      const std::vector<int>& desired_sizes,
+      const favicon_base::FaviconResultsCallback& callback,
       base::CancelableTaskTracker* tracker);
 
   // Used by the FaviconService to get favicons mapped to |page_url| for
-  // |icon_types| which most closely match |desired_size_in_dip| and
-  // |desired_scale_factors|. If |desired_size_in_dip| is 0, the largest favicon
-  // bitmap for |icon_types| is returned. The returned FaviconBitmapResults will
-  // have at most one result for each of |desired_scale_factors|. If a favicon
-  // bitmap is determined to be the best candidate for multiple scale factors
-  // there will be less results. If |icon_types| has several types, results for
-  // only a single type will be returned in the priority of
-  // TOUCH_PRECOMPOSED_ICON, TOUCH_ICON, and FAVICON.
+  // |icon_types| whose edge sizes most closely match |desired_sizes|. If
+  // |desired_sizes| has a '0' entry, the largest favicon bitmap for
+  // |icon_types| is returned. The returned FaviconBitmapResults will have at
+  // most one result for each entry in |desired_sizes|. If a favicon bitmap is
+  // determined to be the best candidate for multiple |desired_sizes| there
+  // will be fewer results. If |icon_types| has several types, results for only
+  // a single type will be returned in the priority of TOUCH_PRECOMPOSED_ICON,
+  // TOUCH_ICON, and FAVICON.
   base::CancelableTaskTracker::TaskId GetFaviconsForURL(
       const GURL& page_url,
       int icon_types,
-      int desired_size_in_dip,
-      const std::vector<ui::ScaleFactor>& desired_scale_factors,
-      const FaviconService::FaviconResultsCallback& callback,
+      const std::vector<int>& desired_sizes,
+      const favicon_base::FaviconResultsCallback& callback,
       base::CancelableTaskTracker* tracker);
 
   // Used by FaviconService to find the first favicon bitmap whose width and
@@ -692,24 +651,23 @@ class HistoryService : public CancelableRequestProvider,
   // |icon_types| will be searched and so on.
   // If no icon is larger than |minimum_size_in_pixel|, the largest one of all
   // icon types in |icon_types| is returned.
-  // This feature is especially useful when some types of icon is perfered as
+  // This feature is especially useful when some types of icon is preferred as
   // long as its size is larger than a specific value.
   base::CancelableTaskTracker::TaskId GetLargestFaviconForURL(
       const GURL& page_url,
       const std::vector<int>& icon_types,
       int minimum_size_in_pixels,
-      const FaviconService::FaviconRawCallback& callback,
+      const favicon_base::FaviconRawBitmapCallback& callback,
       base::CancelableTaskTracker* tracker);
 
   // Used by the FaviconService to get the favicon bitmap which most closely
-  // matches |desired_size_in_dip| and |desired_scale_factor| from the favicon
-  // with |favicon_id| from the history backend. If |desired_size_in_dip| is 0,
-  // the largest favicon bitmap for |favicon_id| is returned.
+  // matches |desired_size| from the favicon with |favicon_id| from the history
+  // backend. If |desired_size| is 0, the largest favicon bitmap for
+  // |favicon_id| is returned.
   base::CancelableTaskTracker::TaskId GetFaviconForID(
-      chrome::FaviconID favicon_id,
-      int desired_size_in_dip,
-      ui::ScaleFactor desired_scale_factor,
-      const FaviconService::FaviconResultsCallback& callback,
+      favicon_base::FaviconID favicon_id,
+      int desired_size,
+      const favicon_base::FaviconResultsCallback& callback,
       base::CancelableTaskTracker* tracker);
 
   // Used by the FaviconService to replace the favicon mappings to |page_url|
@@ -727,17 +685,15 @@ class HistoryService : public CancelableRequestProvider,
   //    Sample new mappings to |page_url|: { ICON_URL3 }
   // |icon_types| can only have multiple IconTypes if
   // |icon_types| == TOUCH_ICON | TOUCH_PRECOMPOSED_ICON.
-  // The favicon bitmaps which most closely match |desired_size_in_dip|
-  // and |desired_scale_factors| from the favicons which were just mapped
-  // to |page_url| are returned. If |desired_size_in_dip| is 0, the
-  // largest favicon bitmap is returned.
+  // The favicon bitmaps whose edge sizes most closely match |desired_sizes|
+  // from the favicons which were just mapped to |page_url| are returned. If
+  // |desired_sizes| has a '0' entry, the largest favicon bitmap is returned.
   base::CancelableTaskTracker::TaskId UpdateFaviconMappingsAndFetch(
       const GURL& page_url,
       const std::vector<GURL>& icon_urls,
       int icon_types,
-      int desired_size_in_dip,
-      const std::vector<ui::ScaleFactor>& desired_scale_factors,
-      const FaviconService::FaviconResultsCallback& callback,
+      const std::vector<int>& desired_sizes,
+      const favicon_base::FaviconResultsCallback& callback,
       base::CancelableTaskTracker* tracker);
 
   // Used by FaviconService to set a favicon for |page_url| and |icon_url| with
@@ -762,25 +718,20 @@ class HistoryService : public CancelableRequestProvider,
   // TODO(pkotwicz): Remove once no longer required by sync.
   void MergeFavicon(const GURL& page_url,
                     const GURL& icon_url,
-                    chrome::IconType icon_type,
+                    favicon_base::IconType icon_type,
                     scoped_refptr<base::RefCountedMemory> bitmap_data,
                     const gfx::Size& pixel_size);
 
-  // Used by the FaviconService to set the favicons for a page on the history
-  // backend.
-  // |favicon_bitmap_data| replaces all the favicon bitmaps mapped to
-  // |page_url|.
-  // |expired| and |icon_type| fields in FaviconBitmapData are ignored.
-  // Use MergeFavicon() if |favicon_bitmap_data| is incomplete, and favicon
-  // bitmaps in the database should be preserved if possible. For instance,
-  // favicon bitmaps from sync are 1x only. MergeFavicon() is used to avoid
-  // deleting the 2x favicon bitmap if it is present in the history backend.
-  // See HistoryBackend::ValidateSetFaviconsParams() for more details on the
-  // criteria for |favicon_bitmap_data| to be valid.
-  void SetFavicons(
-      const GURL& page_url,
-      chrome::IconType icon_type,
-      const std::vector<chrome::FaviconBitmapData>& favicon_bitmap_data);
+  // Used by the FaviconService to replace all of the favicon bitmaps mapped to
+  // |page_url| for |icon_type|.
+  // Use MergeFavicon() if |bitmaps| is incomplete, and favicon bitmaps in the
+  // database should be preserved if possible. For instance, favicon bitmaps
+  // from sync are 1x only. MergeFavicon() is used to avoid deleting the 2x
+  // favicon bitmap if it is present in the history backend.
+  void SetFavicons(const GURL& page_url,
+                   favicon_base::IconType icon_type,
+                   const GURL& icon_url,
+                   const std::vector<SkBitmap>& bitmaps);
 
   // Used by the FaviconService to mark the favicon for the page as being out
   // of date.
@@ -808,108 +759,8 @@ class HistoryService : public CancelableRequestProvider,
   // specified priority. The task will have ownership taken.
   void ScheduleTask(SchedulePriority priority, const base::Closure& task);
 
-  // Schedule ------------------------------------------------------------------
-  //
-  // Functions for scheduling operations on the history thread that have a
-  // handle and may be cancelable. For fire-and-forget operations, see
-  // ScheduleAndForget below.
-
-  template<typename BackendFunc, class RequestType>
-  Handle Schedule(SchedulePriority priority,
-                  BackendFunc func,  // Function to call on the HistoryBackend.
-                  CancelableRequestConsumerBase* consumer,
-                  RequestType* request) {
-    DCHECK(thread_) << "History service being called after cleanup";
-    DCHECK(thread_checker_.CalledOnValidThread());
-    if (consumer)
-      AddRequest(request, consumer);
-    ScheduleTask(priority,
-                 base::Bind(func, history_backend_.get(),
-                            scoped_refptr<RequestType>(request)));
-    return request->handle();
-  }
-
-  template<typename BackendFunc, class RequestType, typename ArgA>
-  Handle Schedule(SchedulePriority priority,
-                  BackendFunc func,  // Function to call on the HistoryBackend.
-                  CancelableRequestConsumerBase* consumer,
-                  RequestType* request,
-                  const ArgA& a) {
-    DCHECK(thread_) << "History service being called after cleanup";
-    DCHECK(thread_checker_.CalledOnValidThread());
-    if (consumer)
-      AddRequest(request, consumer);
-    ScheduleTask(priority,
-                 base::Bind(func, history_backend_.get(),
-                            scoped_refptr<RequestType>(request), a));
-    return request->handle();
-  }
-
-  template<typename BackendFunc,
-           class RequestType,  // Descendant of CancelableRequestBase.
-           typename ArgA,
-           typename ArgB>
-  Handle Schedule(SchedulePriority priority,
-                  BackendFunc func,  // Function to call on the HistoryBackend.
-                  CancelableRequestConsumerBase* consumer,
-                  RequestType* request,
-                  const ArgA& a,
-                  const ArgB& b) {
-    DCHECK(thread_) << "History service being called after cleanup";
-    DCHECK(thread_checker_.CalledOnValidThread());
-    if (consumer)
-      AddRequest(request, consumer);
-    ScheduleTask(priority,
-                 base::Bind(func, history_backend_.get(),
-                            scoped_refptr<RequestType>(request), a, b));
-    return request->handle();
-  }
-
-  template<typename BackendFunc,
-           class RequestType,  // Descendant of CancelableRequestBase.
-           typename ArgA,
-           typename ArgB,
-           typename ArgC>
-  Handle Schedule(SchedulePriority priority,
-                  BackendFunc func,  // Function to call on the HistoryBackend.
-                  CancelableRequestConsumerBase* consumer,
-                  RequestType* request,
-                  const ArgA& a,
-                  const ArgB& b,
-                  const ArgC& c) {
-    DCHECK(thread_) << "History service being called after cleanup";
-    DCHECK(thread_checker_.CalledOnValidThread());
-    if (consumer)
-      AddRequest(request, consumer);
-    ScheduleTask(priority,
-                 base::Bind(func, history_backend_.get(),
-                            scoped_refptr<RequestType>(request), a, b, c));
-    return request->handle();
-  }
-
-  template<typename BackendFunc,
-           class RequestType,  // Descendant of CancelableRequestBase.
-           typename ArgA,
-           typename ArgB,
-           typename ArgC,
-           typename ArgD>
-  Handle Schedule(SchedulePriority priority,
-                  BackendFunc func,  // Function to call on the HistoryBackend.
-                  CancelableRequestConsumerBase* consumer,
-                  RequestType* request,
-                  const ArgA& a,
-                  const ArgB& b,
-                  const ArgC& c,
-                  const ArgD& d) {
-    DCHECK(thread_) << "History service being called after cleanup";
-    DCHECK(thread_checker_.CalledOnValidThread());
-    if (consumer)
-      AddRequest(request, consumer);
-    ScheduleTask(priority,
-                 base::Bind(func, history_backend_.get(),
-                            scoped_refptr<RequestType>(request), a, b, c, d));
-    return request->handle();
-  }
+  // Invokes all callback registered by AddFaviconChangedCallback.
+  void NotifyFaviconChanged(const std::set<GURL>& changed_favicons);
 
   // ScheduleAndForget ---------------------------------------------------------
   //
@@ -990,17 +841,10 @@ class HistoryService : public CancelableRequestProvider,
                                       a, b, c, d, e));
   }
 
-  // All vended weak pointers are invalidated in Cleanup().
-  base::WeakPtrFactory<HistoryService> weak_ptr_factory_;
-
   base::ThreadChecker thread_checker_;
 
   content::NotificationRegistrar registrar_;
 
-  // Some void primitives require some internal processing in the main thread
-  // when done. We use this internal consumer for this purpose.
-  CancelableRequestConsumer internal_consumer_;
-
   // The thread used by the history service to run complicated operations.
   // |thread_| is NULL once |Cleanup| is NULL.
   base::Thread* thread_;
@@ -1019,6 +863,10 @@ class HistoryService : public CancelableRequestProvider,
   // TODO(mrossetti): Consider changing ownership. See http://crbug.com/138321
   scoped_ptr<history::InMemoryHistoryBackend> in_memory_backend_;
 
+  // The history client, may be null when testing. The object should otherwise
+  // outlive |HistoryService|.
+  history::HistoryClient* history_client_;
+
   // The profile, may be null when testing.
   Profile* profile_;
 
@@ -1032,7 +880,6 @@ class HistoryService : public CancelableRequestProvider,
 
   // Cached values from Init(), used whenever we need to reload the backend.
   base::FilePath history_dir_;
-  BookmarkService* bookmark_service_;
   bool no_db_;
 
   // The index used for quick history lookups.
@@ -1040,10 +887,15 @@ class HistoryService : public CancelableRequestProvider,
   // See http://crbug.com/138321
   scoped_ptr<history::InMemoryURLIndex> in_memory_url_index_;
 
-  ObserverList<history::VisitDatabaseObserver> visit_database_observers_;
+  ObserverList<history::HistoryServiceObserver> observers_;
+  base::CallbackList<void(const std::set<GURL>&)>
+      favicon_changed_callback_list_;
 
   history::DeleteDirectiveHandler delete_directive_handler_;
 
+  // All vended weak pointers are invalidated in Cleanup().
+  base::WeakPtrFactory<HistoryService> weak_ptr_factory_;
+
   DISALLOW_COPY_AND_ASSIGN(HistoryService);
 };