history_service.h revision a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Copyright (c) 2012 The Chromium Authors. All rights reserved.
25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Use of this source code is governed by a BSD-style license that can be
35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// found in the LICENSE file.
45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
55821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#ifndef CHROME_BROWSER_HISTORY_HISTORY_SERVICE_H_
65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define CHROME_BROWSER_HISTORY_HISTORY_SERVICE_H_
75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
85821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <set>
95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <vector>
105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/basictypes.h"
120f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)#include "base/bind.h"
135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/callback.h"
144e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)#include "base/files/file_path.h"
155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/logging.h"
16a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch#include "base/memory/ref_counted.h"
175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/memory/scoped_ptr.h"
186e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)#include "base/memory/weak_ptr.h"
195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/observer_list.h"
206d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)#include "base/strings/string16.h"
214e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)#include "base/threading/thread_checker.h"
225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/time/time.h"
235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "chrome/browser/common/cancelable_request.h"
24116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch#include "chrome/browser/favicon/favicon_service.h"
255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "chrome/browser/history/delete_directive_handler.h"
265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "chrome/browser/history/history_types.h"
275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "chrome/browser/history/typed_url_syncable_service.h"
285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "chrome/browser/search_engines/template_url_id.h"
295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "chrome/common/cancelable_task_tracker.h"
305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "chrome/common/ref_counted_util.h"
315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "components/browser_context_keyed_service/browser_context_keyed_service.h"
325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "components/visitedlink/browser/visitedlink_delegate.h"
335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "content/public/browser/download_manager_delegate.h"
342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "content/public/browser/notification_observer.h"
352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "content/public/browser/notification_registrar.h"
365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "content/public/common/page_transition_types.h"
375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "sql/init_status.h"
38f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#include "sync/api/syncable_service.h"
39116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch#include "ui/base/layout.h"
40f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)
41116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch#if defined(OS_ANDROID)
42f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#include "chrome/browser/history/android/android_history_provider_service.h"
43f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#endif
4423730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)
4523730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)class BookmarkService;
4623730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)class GURL;
4723730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)class HistoryURLProvider;
485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class PageUsageData;
495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class PageUsageRequest;
50f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)class Profile;
515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)struct HistoryURLProviderParams;
525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)namespace base {
546e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)class FilePath;
55116680a4aac90f2aa7413d9095a592090648e557Ben Murdochclass Thread;
566e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)}
576e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)
585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)namespace visitedlink {
595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class VisitedLinkMaster;
605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)namespace history {
635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class HistoryBackend;
65cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)class HistoryDatabase;
66cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)class HistoryDBTask;
67cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)class HistoryQueryTest;
68cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)class InMemoryHistoryBackend;
695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class InMemoryURLIndex;
705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class InMemoryURLIndexTest;
715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class URLDatabase;
725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class VisitDatabaseObserver;
73116680a4aac90f2aa7413d9095a592090648e557Ben Murdochclass VisitFilter;
74116680a4aac90f2aa7413d9095a592090648e557Ben Murdochstruct DownloadRow;
75116680a4aac90f2aa7413d9095a592090648e557Ben Murdochstruct HistoryAddPageArgs;
76116680a4aac90f2aa7413d9095a592090648e557Ben Murdochstruct HistoryDetails;
77116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch
78116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch}  // namespace history
796e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)
806e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)// The history service records page titles, and visit times, as well as
81116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch// (eventually) information about autocomplete.
82116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch//
83116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch// This service is thread safe. Each request callback is invoked in the
846e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)// thread that made the request.
856e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)class HistoryService : public CancelableRequestProvider,
866e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)                       public content::NotificationObserver,
876e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)                       public syncer::SyncableService,
882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                       public BrowserContextKeyedService,
892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                       public visitedlink::VisitedLinkDelegate {
902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles) public:
912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Miscellaneous commonly-used types.
922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  typedef std::vector<PageUsageData*> PageUsageDataList;
935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Must call Init after construction.
956d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  explicit HistoryService(Profile* profile);
96f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  // The empty constructor is provided only for testing.
972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  HistoryService();
986d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  virtual ~HistoryService();
1002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Initializes the history service, returning true on success. On false, do
1022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // not call any other functions. The given directory will be used for storing
1036d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  // the history files. The BookmarkService is used when deleting URLs to
1042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // test if a URL is bookmarked; it may be NULL during testing.
1052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  bool Init(const base::FilePath& history_dir, BookmarkService* bookmark_service) {
1062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return Init(history_dir, bookmark_service, false);
1076d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  }
1086d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
1092a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Triggers the backend to load if it hasn't already, and then returns whether
1100f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  // it's finished loading.
1110f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  // Note: Virtual needed for mocking.
1120f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  virtual bool BackendLoaded();
1130f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)
1140f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  // Returns true if the backend has finished loading.
1150f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  bool backend_loaded() const { return backend_loaded_; }
1160f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)
1172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Unloads the backend without actually shutting down the history service.
1182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // This can be used to temporarily reduce the browser process' memory
1192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // footprint.
1202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  void UnloadBackend();
1212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Called on shutdown, this will tell the history backend to complete and
1232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // will release pointers to it. No other functions should be called once
1242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // cleanup has happened that may dispatch to the history thread (because it
1252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // will be NULL).
1262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  //
1272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // In practice, this will be called by the service manager (BrowserProcess)
1282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // when it is being destroyed. Because that reference is being destroyed, it
1292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // should be impossible for anybody else to call the service, even if it is
1302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // still in memory (pending requests may be holding a reference to us).
1312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  void Cleanup();
1322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // RenderProcessHost pointers are used to scope page IDs (see AddPage). These
1342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // objects must tell us when they are being destroyed so that we can clear
1355f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  // out any cached data associated with that scope.
1365f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  //
1375f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  // The given pointer will not be dereferenced, it is only used for
1385f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  // identification purposes, hence it is a void*.
1395f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  void NotifyRenderProcessHostDestruction(const void* host);
14023730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)
1416d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  // Triggers the backend to load if it hasn't already, and then returns the
1426d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  // in-memory URL database. The returned pointer MAY BE NULL if the in-memory
14323730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)  // database has not been loaded yet. This pointer is owned by the history
14423730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)  // system. Callers should not store or cache this value.
145cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  //
146cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  // TODO(brettw) this should return the InMemoryHistoryBackend.
147cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  history::URLDatabase* InMemoryDatabase();
148cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
149116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // Following functions get URL information from in-memory database.
150f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  // They return false if database is not available (e.g. not loaded yet) or the
151f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  // URL does not exist.
152f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)
153f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  // Reads the number of times the user has typed the given URL.
154f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  bool GetTypedCountForURL(const GURL& url, int* typed_count);
155116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch
156116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // Reads the last visit time for the given URL.
157116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  bool GetLastVisitTimeForURL(const GURL& url, base::Time* last_visit);
158116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch
159116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // Reads the number of times this URL has been visited.
160116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  bool GetVisitCountForURL(const GURL& url, int* visit_count);
161116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch
162116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // Returns a pointer to the TypedUrlSyncableService owned by HistoryBackend.
163116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // This method should only be called from the history thread, because the
164116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // returned service is intended to be accessed only via the history thread.
165116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  history::TypedUrlSyncableService* GetTypedUrlSyncableService() const;
166116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch
167116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // Return the quick history index.
168116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  history::InMemoryURLIndex* InMemoryIndex() const {
169116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch    return in_memory_url_index_.get();
170116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  }
171116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch
172116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // BrowserContextKeyedService:
1736e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)  virtual void Shutdown() OVERRIDE;
1746e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)
1756e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)  // Navigation ----------------------------------------------------------------
1766e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)
1774e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  // Adds the given canonical URL to history with the given time as the visit
1784e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  // time. Referrer may be the empty string.
1794e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  //
1805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // The supplied render process host is used to scope the given page ID. Page
1815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // IDs are only unique inside a given render process, so we need that to
1825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // differentiate them. This pointer should not be dereferenced by the history
1835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // system.
1845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  //
1852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // The scope/ids can be NULL if there is no meaningful tracking information
1865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // that can be performed on the given URL. The 'page_id' should be the ID of
1875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // the current session history entry in the given process.
1885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  //
1895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // 'redirects' is an array of redirect URLs leading to this page, with the
1905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // page itself as the last item (so when there is no redirect, it will have
1915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // one entry). If there are no redirects, this array may also be empty for
1925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // the convenience of callers.
1935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  //
1945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // 'did_replace_entry' is true when the navigation entry for this page has
1955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // replaced the existing entry. A non-user initiated redirect causes such
1965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // replacement.
1975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  //
1985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // All "Add Page" functions will update the visited link database.
1995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void AddPage(const GURL& url,
2005d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)               base::Time time,
2015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)               const void* id_scope,
2025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)               int32 page_id,
2035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)               const GURL& referrer,
2045d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)               const history::RedirectList& redirects,
2055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)               content::PageTransition transition,
2065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)               history::VisitSource visit_source,
2075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)               bool did_replace_entry);
2085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // For adding pages to history where no tracking information can be done.
2105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void AddPage(const GURL& url,
2115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)               base::Time time,
2125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)               history::VisitSource visit_source);
213116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch
2146e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)  // All AddPage variants end up here.
2156e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)  void AddPage(const history::HistoryAddPageArgs& add_page_args);
2166e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)
2176e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)  // Adds an entry for the specified url without creating a visit. This should
2186e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)  // only be used when bookmarking a page, otherwise the row leaks in the
2196e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)  // history db (it never gets cleaned).
2206e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)  void AddPageNoVisitForBookmark(const GURL& url, const base::string16& title);
2215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Sets the title for the given page. The page should be in history. If it
2235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // is not, this operation is ignored.
224116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  void SetPageTitle(const GURL& url, const base::string16& title);
225116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch
226116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // Updates the history database with a page's ending time stamp information.
227116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // The page can be identified by the combination of the pointer to
2285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // a RenderProcessHost, the page id and the url.
2295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  //
2305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // The given pointer will not be dereferenced, it is only used for
2315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // identification purposes, hence it is a void*.
2325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void UpdateWithPageEndTime(const void* host,
2335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                             int32 page_id,
234effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch                             const GURL& url,
235effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch                             base::Time end_ts);
2365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Querying ------------------------------------------------------------------
2385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Returns the information about the requested URL. If the URL is found,
2405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // success will be true and the information will be in the URLRow parameter.
2415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // On success, the visits, if requested, will be sorted by date. If they have
2425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // not been requested, the pointer will be valid, but the vector will be
2435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // empty.
244a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  //
2455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // If success is false, neither the row nor the vector will be valid.
2465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  typedef base::Callback<void(
2475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Handle,
2485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      bool,  // Success flag, when false, nothing else is valid.
2495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      const history::URLRow*,
2505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      history::VisitVector*)> QueryURLCallback;
2515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Queries the basic information about the URL in the history database. If
2535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // the caller is interested in the visits (each time the URL is visited),
2545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // set |want_visits| to true. If these are not needed, the function will be
2555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // faster by setting this to false.
2562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  Handle QueryURL(const GURL& url,
2575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                  bool want_visits,
2585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                  CancelableRequestConsumerBase* consumer,
25990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                  const QueryURLCallback& callback);
26090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
26190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // Provides the result of a query. See QueryResults in history_types.h.
2625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // The common use will be to use QueryResults.Swap to suck the contents of
2635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // the results out of the passed in parameter and take ownership of them.
2645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  typedef base::Callback<void(Handle, history::QueryResults*)>
2655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      QueryHistoryCallback;
2665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2675d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // Queries all history with the given options (see QueryOptions in
2685d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // history_types.h).  If empty, all results matching the given options
269a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  // will be returned.
2705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Handle QueryHistory(const base::string16& text_query,
2716d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)                      const history::QueryOptions& options,
2726d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)                      CancelableRequestConsumerBase* consumer,
2735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                      const QueryHistoryCallback& callback);
2740f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)
2755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Called when the results of QueryRedirectsFrom are available.
2765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // The given vector will contain a list of all redirects, not counting
2772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // the original page. If A redirects to B, the vector will contain only B,
2782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // and A will be in 'source_url'.
2795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  //
2805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // If there is no such URL in the database or the most recent visit has no
2815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // redirect, the vector will be empty. If the history system failed for
2825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // some reason, success will additionally be false. If the given page
2835f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  // has redirected to multiple destinations, this will pick a random one.
2845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  typedef base::Callback<void(Handle,
2855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                              GURL,  // from_url
2866d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)                              bool,  // success
2875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                              history::RedirectList*)> QueryRedirectsCallback;
2886d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
28923730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)  // Schedules a query for the most recent redirect coming out of the given
2905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // URL. See the RedirectQuerySource above, which is guaranteed to be called
2915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // if the request is not canceled.
2925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Handle QueryRedirectsFrom(const GURL& from_url,
2935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                            CancelableRequestConsumerBase* consumer,
2945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                            const QueryRedirectsCallback& callback);
2955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Schedules a query to get the most recent redirects ending at the given
2975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // URL.
2985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Handle QueryRedirectsTo(const GURL& to_url,
2995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                          CancelableRequestConsumerBase* consumer,
3005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                          const QueryRedirectsCallback& callback);
3015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  typedef base::Callback<
3035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      void(Handle,
3045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)           bool,        // Were we able to determine the # of visits?
3055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)           int,         // Number of visits.
3065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)           base::Time)> // Time of first visit. Only set if bool
3075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                        // is true and int is > 0.
3085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      GetVisibleVisitCountToHostCallback;
3094e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)
3104e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  // Requests the number of user-visible visits (i.e. no redirects or subframes)
311e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch  // to all urls on the same scheme/host/port as |url|.  This is only valid for
312e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch  // HTTP and HTTPS URLs.
313cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  Handle GetVisibleVisitCountToHost(
314cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)      const GURL& url,
315116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch      CancelableRequestConsumerBase* consumer,
316f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)      const GetVisibleVisitCountToHostCallback& callback);
317116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch
318116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // Called when QueryTopURLsAndRedirects completes. The vector contains a list
319116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // of the top |result_count| URLs.  For each of these URLs, there is an entry
320116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // in the map containing redirects from the URL.  For example, if we have the
321116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // redirect chain A -> B -> C and A is a top visited URL, then A will be in
322116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // the vector and "A => {B -> C}" will be in the map.
323116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  typedef base::Callback<
324116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch      void(Handle,
3256e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)           bool,  // Did we get the top urls and redirects?
326f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)           std::vector<GURL>*,  // List of top URLs.
3275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)           history::RedirectMap*)>  // Redirects for top URLs.
3285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      QueryTopURLsAndRedirectsCallback;
3295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Request the top |result_count| most visited URLs and the chain of redirects
331  // leading to each of these URLs.
332  // TODO(Nik): remove this. Use QueryMostVisitedURLs instead.
333  Handle QueryTopURLsAndRedirects(
334      int result_count,
335      CancelableRequestConsumerBase* consumer,
336      const QueryTopURLsAndRedirectsCallback& callback);
337
338  typedef base::Callback<void(Handle, history::MostVisitedURLList)>
339      QueryMostVisitedURLsCallback;
340
341  typedef base::Callback<void(Handle, const history::FilteredURLList&)>
342      QueryFilteredURLsCallback;
343
344  // Request the |result_count| most visited URLs and the chain of
345  // redirects leading to each of these URLs. |days_back| is the
346  // number of days of history to use. Used by TopSites.
347  Handle QueryMostVisitedURLs(int result_count, int days_back,
348                              CancelableRequestConsumerBase* consumer,
349                              const QueryMostVisitedURLsCallback& callback);
350
351  // Request the |result_count| URLs filtered and sorted based on the |filter|.
352  // If |extended_info| is true, additional data will be provided in the
353  // results. Computing this additional data is expensive, likely to become
354  // more expensive as additional data points are added in future changes, and
355  // not useful in most cases. Set |extended_info| to true only if you
356  // explicitly require the additional data.
357  Handle QueryFilteredURLs(
358      int result_count,
359      const history::VisitFilter& filter,
360      bool extended_info,
361      CancelableRequestConsumerBase* consumer,
362      const QueryFilteredURLsCallback& callback);
363
364  // Database management operations --------------------------------------------
365
366  // Delete all the information related to a single url.
367  void DeleteURL(const GURL& url);
368
369  // Delete all the information related to a list of urls.  (Deleting
370  // URLs one by one is slow as it has to flush to disk each time.)
371  void DeleteURLsForTest(const std::vector<GURL>& urls);
372
373  // Removes all visits in the selected time range (including the
374  // start time), updating the URLs accordingly. This deletes any
375  // associated data. This function also deletes the associated
376  // favicons, if they are no longer referenced. |callback| runs when
377  // the expiration is complete. You may use null Time values to do an
378  // unbounded delete in either direction.
379  // If |restrict_urls| is not empty, only visits to the URLs in this set are
380  // removed.
381  void ExpireHistoryBetween(const std::set<GURL>& restrict_urls,
382                            base::Time begin_time,
383                            base::Time end_time,
384                            const base::Closure& callback,
385                            CancelableTaskTracker* tracker);
386
387  // Removes all visits to specified URLs in specific time ranges.
388  // This is the equivalent ExpireHistoryBetween() once for each element in the
389  // vector. The fields of |ExpireHistoryArgs| map directly to the arguments of
390  // of ExpireHistoryBetween().
391  void ExpireHistory(const std::vector<history::ExpireHistoryArgs>& expire_list,
392                     const base::Closure& callback,
393                     CancelableTaskTracker* tracker);
394
395  // Removes all visits to the given URLs in the specified time range. Calls
396  // ExpireHistoryBetween() to delete local visits, and handles deletion of
397  // synced visits if appropriate.
398  void ExpireLocalAndRemoteHistoryBetween(
399      const std::set<GURL>& restrict_urls,
400      base::Time begin_time,
401      base::Time end_time,
402      const base::Closure& callback,
403      CancelableTaskTracker* tracker);
404
405  // Processes the given |delete_directive| and sends it to the
406  // SyncChangeProcessor (if it exists).  Returns any error resulting
407  // from sending the delete directive to sync.
408  syncer::SyncError ProcessLocalDeleteDirective(
409      const sync_pb::HistoryDeleteDirectiveSpecifics& delete_directive);
410
411  // Downloads -----------------------------------------------------------------
412
413  // Implemented by the caller of 'CreateDownload' below, and is called when the
414  // history service has created a new entry for a download in the history db.
415  typedef base::Callback<void(bool)> DownloadCreateCallback;
416
417  // Begins a history request to create a new row for a download. 'info'
418  // contains all the download's creation state, and 'callback' runs when the
419  // history service request is complete. The callback is called on the thread
420  // that calls CreateDownload().
421  void CreateDownload(
422      const history::DownloadRow& info,
423      const DownloadCreateCallback& callback);
424
425  // Responds on the calling thread with the maximum id of all downloads records
426  // in the database plus 1.
427  void GetNextDownloadId(const content::DownloadIdCallback& callback);
428
429  // Implemented by the caller of 'QueryDownloads' below, and is called when the
430  // history service has retrieved a list of all download state. The call
431  typedef base::Callback<void(
432      scoped_ptr<std::vector<history::DownloadRow> >)>
433          DownloadQueryCallback;
434
435  // Begins a history request to retrieve the state of all downloads in the
436  // history db. 'callback' runs when the history service request is complete,
437  // at which point 'info' contains an array of history::DownloadRow, one per
438  // download. The callback is called on the thread that calls QueryDownloads().
439  void QueryDownloads(const DownloadQueryCallback& callback);
440
441  // Called to update the history service about the current state of a download.
442  // This is a 'fire and forget' query, so just pass the relevant state info to
443  // the database with no need for a callback.
444  void UpdateDownload(const history::DownloadRow& data);
445
446  // Permanently remove some downloads from the history system. This is a 'fire
447  // and forget' operation.
448  void RemoveDownloads(const std::set<uint32>& ids);
449
450  // Visit Segments ------------------------------------------------------------
451
452  typedef base::Callback<void(Handle, std::vector<PageUsageData*>*)>
453      SegmentQueryCallback;
454
455  // Query usage data for all visit segments since the provided time.
456  //
457  // The request is performed asynchronously and can be cancelled by using the
458  // returned handle.
459  //
460  // The vector provided to the callback and its contents is owned by the
461  // history system. It will be deeply deleted after the callback is invoked.
462  // If you want to preserve any PageUsageData instance, simply remove them
463  // from the vector.
464  //
465  // The vector contains a list of PageUsageData. Each PageUsageData ID is set
466  // to the segment ID. The URL and all the other information is set to the page
467  // representing the segment.
468  Handle QuerySegmentUsageSince(CancelableRequestConsumerBase* consumer,
469                                const base::Time from_time,
470                                int max_result_count,
471                                const SegmentQueryCallback& callback);
472
473  // Increases the amount of time the user actively viewed the url.
474  void IncreaseSegmentDuration(const GURL& url,
475                               base::Time time,
476                               base::TimeDelta delta);
477
478  // Queries segments based on active time viewed.
479  Handle QuerySegmentDurationSince(CancelableRequestConsumerBase* consumer,
480                                   base::Time from_time,
481                                   int max_result_count,
482                                   const SegmentQueryCallback& callback);
483
484  // Keyword search terms -----------------------------------------------------
485
486  // Sets the search terms for the specified url and keyword. url_id gives the
487  // id of the url, keyword_id the id of the keyword and term the search term.
488  void SetKeywordSearchTermsForURL(const GURL& url,
489                                   TemplateURLID keyword_id,
490                                   const base::string16& term);
491
492  // Deletes all search terms for the specified keyword.
493  void DeleteAllSearchTermsForKeyword(TemplateURLID keyword_id);
494
495  typedef base::Callback<
496      void(Handle, std::vector<history::KeywordSearchTermVisit>*)>
497          GetMostRecentKeywordSearchTermsCallback;
498
499  // Returns up to max_count of the most recent search terms starting with the
500  // specified text. The matching is case insensitive. The results are ordered
501  // in descending order up to |max_count| with the most recent search term
502  // first.
503  Handle GetMostRecentKeywordSearchTerms(
504      TemplateURLID keyword_id,
505      const base::string16& prefix,
506      int max_count,
507      CancelableRequestConsumerBase* consumer,
508      const GetMostRecentKeywordSearchTermsCallback& callback);
509
510  // Deletes any search term corresponding to |url|.
511  void DeleteKeywordSearchTermForURL(const GURL& url);
512
513  // Bookmarks -----------------------------------------------------------------
514
515  // Notification that a URL is no longer bookmarked.
516  void URLsNoLongerBookmarked(const std::set<GURL>& urls);
517
518  // Generic Stuff -------------------------------------------------------------
519
520  // Schedules a HistoryDBTask for running on the history backend thread. See
521  // HistoryDBTask for details on what this does.
522  virtual void ScheduleDBTask(history::HistoryDBTask* task,
523                              CancelableRequestConsumerBase* consumer);
524
525  // Adds or removes observers for the VisitDatabase.
526  void AddVisitDatabaseObserver(history::VisitDatabaseObserver* observer);
527  void RemoveVisitDatabaseObserver(history::VisitDatabaseObserver* observer);
528
529  void NotifyVisitDBObserversOnAddVisit(const history::BriefVisitInfo& info);
530
531  // Testing -------------------------------------------------------------------
532
533  // Runs |flushed| after bouncing off the history thread.
534  void FlushForTest(const base::Closure& flushed);
535
536  // Designed for unit tests, this passes the given task on to the history
537  // backend to be called once the history backend has terminated. This allows
538  // callers to know when the history thread is complete and the database files
539  // can be deleted and the next test run. Otherwise, the history thread may
540  // still be running, causing problems in subsequent tests.
541  //
542  // There can be only one closing task, so this will override any previously
543  // set task. We will take ownership of the pointer and delete it when done.
544  // The task will be run on the calling thread (this function is threadsafe).
545  void SetOnBackendDestroyTask(const base::Closure& task);
546
547  // Used for unit testing and potentially importing to get known information
548  // into the database. This assumes the URL doesn't exist in the database
549  //
550  // Calling this function many times may be slow because each call will
551  // dispatch to the history thread and will be a separate database
552  // transaction. If this functionality is needed for importing many URLs,
553  // callers should use AddPagesWithDetails() instead.
554  //
555  // Note that this routine (and AddPageWithDetails()) always adds a single
556  // visit using the |last_visit| timestamp, and a PageTransition type of LINK,
557  // if |visit_source| != SYNCED.
558  void AddPageWithDetails(const GURL& url,
559                          const base::string16& title,
560                          int visit_count,
561                          int typed_count,
562                          base::Time last_visit,
563                          bool hidden,
564                          history::VisitSource visit_source);
565
566  // The same as AddPageWithDetails() but takes a vector.
567  void AddPagesWithDetails(const history::URLRows& info,
568                           history::VisitSource visit_source);
569
570  // Returns true if this looks like the type of URL we want to add to the
571  // history. We filter out some URLs such as JavaScript.
572  static bool CanAddURL(const GURL& url);
573
574  base::WeakPtr<HistoryService> AsWeakPtr();
575
576  // syncer::SyncableService implementation.
577  virtual syncer::SyncMergeResult MergeDataAndStartSyncing(
578      syncer::ModelType type,
579      const syncer::SyncDataList& initial_sync_data,
580      scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
581      scoped_ptr<syncer::SyncErrorFactory> error_handler) OVERRIDE;
582  virtual void StopSyncing(syncer::ModelType type) OVERRIDE;
583  virtual syncer::SyncDataList GetAllSyncData(
584      syncer::ModelType type) const OVERRIDE;
585  virtual syncer::SyncError ProcessSyncChanges(
586      const tracked_objects::Location& from_here,
587      const syncer::SyncChangeList& change_list) OVERRIDE;
588
589 protected:
590  // These are not currently used, hopefully we can do something in the future
591  // to ensure that the most important things happen first.
592  enum SchedulePriority {
593    PRIORITY_UI,      // The highest priority (must respond to UI events).
594    PRIORITY_NORMAL,  // Normal stuff like adding a page.
595    PRIORITY_LOW,     // Low priority things like indexing or expiration.
596  };
597
598 private:
599  class BackendDelegate;
600#if defined(OS_ANDROID)
601  friend class AndroidHistoryProviderService;
602#endif
603  friend class base::RefCountedThreadSafe<HistoryService>;
604  friend class BackendDelegate;
605  friend class FaviconService;
606  friend class history::HistoryBackend;
607  friend class history::HistoryQueryTest;
608  friend class HistoryOperation;
609  friend class HistoryQuickProviderTest;
610  friend class HistoryURLProvider;
611  friend class HistoryURLProviderTest;
612  friend class history::InMemoryURLIndexTest;
613  template<typename Info, typename Callback> friend class DownloadRequest;
614  friend class PageUsageRequest;
615  friend class RedirectRequest;
616  friend class TestingProfile;
617
618  // Implementation of content::NotificationObserver.
619  virtual void Observe(int type,
620                       const content::NotificationSource& source,
621                       const content::NotificationDetails& details) OVERRIDE;
622
623  // Implementation of visitedlink::VisitedLinkDelegate.
624  virtual void RebuildTable(
625      const scoped_refptr<URLEnumerator>& enumerator) OVERRIDE;
626
627  // Low-level Init().  Same as the public version, but adds a |no_db| parameter
628  // that is only set by unittests which causes the backend to not init its DB.
629  bool Init(const base::FilePath& history_dir,
630            BookmarkService* bookmark_service,
631            bool no_db);
632
633  // Called by the HistoryURLProvider class to schedule an autocomplete, it
634  // will be called back on the internal history thread with the history
635  // database so it can query. See history_autocomplete.cc for a diagram.
636  void ScheduleAutocomplete(HistoryURLProvider* provider,
637                            HistoryURLProviderParams* params);
638
639  // Broadcasts the given notification. This is called by the backend so that
640  // the notification will be broadcast on the main thread.
641  //
642  // Compared to BroadcastNotifications(), this function does not take
643  // ownership of |details|.
644  void BroadcastNotificationsHelper(int type,
645                                    history::HistoryDetails* details);
646
647  // Initializes the backend.
648  void LoadBackendIfNecessary();
649
650  // Notification from the backend that it has finished loading. Sends
651  // notification (NOTIFY_HISTORY_LOADED) and sets backend_loaded_ to true.
652  void OnDBLoaded(int backend_id);
653
654  // Helper function for getting URL information.
655  // Reads a URLRow from in-memory database. Returns false if database is not
656  // available or the URL does not exist.
657  bool GetRowForURL(const GURL& url, history::URLRow* url_row);
658
659  // Favicon -------------------------------------------------------------------
660
661  // These favicon methods are exposed to the FaviconService. Instead of calling
662  // these methods directly you should call the respective method on the
663  // FaviconService.
664
665  // Used by FaviconService to get the favicon bitmaps from the history backend
666  // which most closely match |desired_size_in_dip| x |desired_size_in_dip| and
667  // |desired_scale_factors| for |icon_types|. If |desired_size_in_dip| is 0,
668  // the largest favicon bitmap for |icon_types| is returned. The returned
669  // FaviconBitmapResults will have at most one result for each of
670  // |desired_scale_factors|. If a favicon bitmap is determined to be the best
671  // candidate for multiple scale factors there will be less results.
672  // If |icon_types| has several types, results for only a single type will be
673  // returned in the priority of TOUCH_PRECOMPOSED_ICON, TOUCH_ICON, and
674  // FAVICON.
675  CancelableTaskTracker::TaskId GetFavicons(
676      const std::vector<GURL>& icon_urls,
677      int icon_types,
678      int desired_size_in_dip,
679      const std::vector<ui::ScaleFactor>& desired_scale_factors,
680      const FaviconService::FaviconResultsCallback& callback,
681      CancelableTaskTracker* tracker);
682
683  // Used by the FaviconService to get favicons mapped to |page_url| for
684  // |icon_types| which most closely match |desired_size_in_dip| and
685  // |desired_scale_factors|. If |desired_size_in_dip| is 0, the largest favicon
686  // bitmap for |icon_types| is returned. The returned FaviconBitmapResults will
687  // have at most one result for each of |desired_scale_factors|. If a favicon
688  // bitmap is determined to be the best candidate for multiple scale factors
689  // there will be less results. If |icon_types| has several types, results for
690  // only a single type will be returned in the priority of
691  // TOUCH_PRECOMPOSED_ICON, TOUCH_ICON, and FAVICON.
692  CancelableTaskTracker::TaskId GetFaviconsForURL(
693      const GURL& page_url,
694      int icon_types,
695      int desired_size_in_dip,
696      const std::vector<ui::ScaleFactor>& desired_scale_factors,
697      const FaviconService::FaviconResultsCallback& callback,
698      CancelableTaskTracker* tracker);
699
700  // Used by FaviconService to find the first favicon bitmap whose width and
701  // height are greater than that of |minimum_size_in_pixels|. This searches
702  // for icons by IconType. Each element of |icon_types| is a bitmask of
703  // IconTypes indicating the types to search for.
704  // If the largest icon of |icon_types[0]| is not larger than
705  // |minimum_size_in_pixel|, the next icon types of
706  // |icon_types| will be searched and so on.
707  // If no icon is larger than |minimum_size_in_pixel|, the largest one of all
708  // icon types in |icon_types| is returned.
709  // This feature is especially useful when some types of icon is perfered as
710  // long as its size is larger than a specific value.
711  CancelableTaskTracker::TaskId GetLargestFaviconForURL(
712      const GURL& page_url,
713      const std::vector<int>& icon_types,
714      int minimum_size_in_pixels,
715      const FaviconService::FaviconRawCallback& callback,
716      CancelableTaskTracker* tracker);
717
718  // Used by the FaviconService to get the favicon bitmap which most closely
719  // matches |desired_size_in_dip| and |desired_scale_factor| from the favicon
720  // with |favicon_id| from the history backend. If |desired_size_in_dip| is 0,
721  // the largest favicon bitmap for |favicon_id| is returned.
722  CancelableTaskTracker::TaskId GetFaviconForID(
723      chrome::FaviconID favicon_id,
724      int desired_size_in_dip,
725      ui::ScaleFactor desired_scale_factor,
726      const FaviconService::FaviconResultsCallback& callback,
727      CancelableTaskTracker* tracker);
728
729  // Used by the FaviconService to replace the favicon mappings to |page_url|
730  // for |icon_types| on the history backend.
731  // Sample |icon_urls|:
732  //  { ICON_URL1 -> TOUCH_ICON, known to the database,
733  //    ICON_URL2 -> TOUCH_ICON, not known to the database,
734  //    ICON_URL3 -> TOUCH_PRECOMPOSED_ICON, known to the database }
735  // The new mappings are computed from |icon_urls| with these rules:
736  // 1) Any urls in |icon_urls| which are not already known to the database are
737  //    rejected.
738  //    Sample new mappings to |page_url|: { ICON_URL1, ICON_URL3 }
739  // 2) If |icon_types| has multiple types, the mappings are only set for the
740  //    largest icon type.
741  //    Sample new mappings to |page_url|: { ICON_URL3 }
742  // |icon_types| can only have multiple IconTypes if
743  // |icon_types| == TOUCH_ICON | TOUCH_PRECOMPOSED_ICON.
744  // The favicon bitmaps which most closely match |desired_size_in_dip|
745  // and |desired_scale_factors| from the favicons which were just mapped
746  // to |page_url| are returned. If |desired_size_in_dip| is 0, the
747  // largest favicon bitmap is returned.
748  CancelableTaskTracker::TaskId UpdateFaviconMappingsAndFetch(
749      const GURL& page_url,
750      const std::vector<GURL>& icon_urls,
751      int icon_types,
752      int desired_size_in_dip,
753      const std::vector<ui::ScaleFactor>& desired_scale_factors,
754      const FaviconService::FaviconResultsCallback& callback,
755      CancelableTaskTracker* tracker);
756
757  // Used by FaviconService to set a favicon for |page_url| and |icon_url| with
758  // |pixel_size|.
759  // Example:
760  //   |page_url|: www.google.com
761  // 2 favicons in history for |page_url|:
762  //   www.google.com/a.ico  16x16
763  //   www.google.com/b.ico  32x32
764  // MergeFavicon(|page_url|, www.google.com/a.ico, ..., ..., 16x16)
765  //
766  // Merging occurs in the following manner:
767  // 1) |page_url| is set to map to only to |icon_url|. In order to not lose
768  //    data, favicon bitmaps mapped to |page_url| but not to |icon_url| are
769  //    copied to the favicon at |icon_url|.
770  //    For the example above, |page_url| will only be mapped to a.ico.
771  //    The 32x32 favicon bitmap at b.ico is copied to a.ico
772  // 2) |bitmap_data| is added to the favicon at |icon_url|, overwriting any
773  //    favicon bitmaps of |pixel_size|.
774  //    For the example above, |bitmap_data| overwrites the 16x16 favicon
775  //    bitmap for a.ico.
776  // TODO(pkotwicz): Remove once no longer required by sync.
777  void MergeFavicon(const GURL& page_url,
778                    const GURL& icon_url,
779                    chrome::IconType icon_type,
780                    scoped_refptr<base::RefCountedMemory> bitmap_data,
781                    const gfx::Size& pixel_size);
782
783  // Used by the FaviconService to set the favicons for a page on the history
784  // backend.
785  // |favicon_bitmap_data| replaces all the favicon bitmaps mapped to
786  // |page_url|.
787  // |expired| and |icon_type| fields in FaviconBitmapData are ignored.
788  // Use MergeFavicon() if |favicon_bitmap_data| is incomplete, and favicon
789  // bitmaps in the database should be preserved if possible. For instance,
790  // favicon bitmaps from sync are 1x only. MergeFavicon() is used to avoid
791  // deleting the 2x favicon bitmap if it is present in the history backend.
792  // See HistoryBackend::ValidateSetFaviconsParams() for more details on the
793  // criteria for |favicon_bitmap_data| to be valid.
794  void SetFavicons(
795      const GURL& page_url,
796      chrome::IconType icon_type,
797      const std::vector<chrome::FaviconBitmapData>& favicon_bitmap_data);
798
799  // Used by the FaviconService to mark the favicon for the page as being out
800  // of date.
801  void SetFaviconsOutOfDateForPage(const GURL& page_url);
802
803  // Used by the FaviconService to clone favicons from one page to another,
804  // provided that other page does not already have favicons.
805  void CloneFavicons(const GURL& old_page_url, const GURL& new_page_url);
806
807  // Used by the FaviconService for importing many favicons for many pages at
808  // once. The pages must exist, any favicon sets for unknown pages will be
809  // discarded. Existing favicons will not be overwritten.
810  void SetImportedFavicons(
811      const std::vector<ImportedFaviconUsage>& favicon_usage);
812
813  // Sets the in-memory URL database. This is called by the backend once the
814  // database is loaded to make it available.
815  void SetInMemoryBackend(
816      int backend_id,
817      scoped_ptr<history::InMemoryHistoryBackend> mem_backend);
818
819  // Called by our BackendDelegate when there is a problem reading the database.
820  void NotifyProfileError(int backend_id, sql::InitStatus init_status);
821
822  // Call to schedule a given task for running on the history thread with the
823  // specified priority. The task will have ownership taken.
824  void ScheduleTask(SchedulePriority priority, const base::Closure& task);
825
826  // Schedule ------------------------------------------------------------------
827  //
828  // Functions for scheduling operations on the history thread that have a
829  // handle and may be cancelable. For fire-and-forget operations, see
830  // ScheduleAndForget below.
831
832  template<typename BackendFunc, class RequestType>
833  Handle Schedule(SchedulePriority priority,
834                  BackendFunc func,  // Function to call on the HistoryBackend.
835                  CancelableRequestConsumerBase* consumer,
836                  RequestType* request) {
837    DCHECK(thread_) << "History service being called after cleanup";
838    DCHECK(thread_checker_.CalledOnValidThread());
839    LoadBackendIfNecessary();
840    if (consumer)
841      AddRequest(request, consumer);
842    ScheduleTask(priority,
843                 base::Bind(func, history_backend_.get(),
844                            scoped_refptr<RequestType>(request)));
845    return request->handle();
846  }
847
848  template<typename BackendFunc, class RequestType, typename ArgA>
849  Handle Schedule(SchedulePriority priority,
850                  BackendFunc func,  // Function to call on the HistoryBackend.
851                  CancelableRequestConsumerBase* consumer,
852                  RequestType* request,
853                  const ArgA& a) {
854    DCHECK(thread_) << "History service being called after cleanup";
855    DCHECK(thread_checker_.CalledOnValidThread());
856    LoadBackendIfNecessary();
857    if (consumer)
858      AddRequest(request, consumer);
859    ScheduleTask(priority,
860                 base::Bind(func, history_backend_.get(),
861                            scoped_refptr<RequestType>(request), a));
862    return request->handle();
863  }
864
865  template<typename BackendFunc,
866           class RequestType,  // Descendant of CancelableRequestBase.
867           typename ArgA,
868           typename ArgB>
869  Handle Schedule(SchedulePriority priority,
870                  BackendFunc func,  // Function to call on the HistoryBackend.
871                  CancelableRequestConsumerBase* consumer,
872                  RequestType* request,
873                  const ArgA& a,
874                  const ArgB& b) {
875    DCHECK(thread_) << "History service being called after cleanup";
876    DCHECK(thread_checker_.CalledOnValidThread());
877    LoadBackendIfNecessary();
878    if (consumer)
879      AddRequest(request, consumer);
880    ScheduleTask(priority,
881                 base::Bind(func, history_backend_.get(),
882                            scoped_refptr<RequestType>(request), a, b));
883    return request->handle();
884  }
885
886  template<typename BackendFunc,
887           class RequestType,  // Descendant of CancelableRequestBase.
888           typename ArgA,
889           typename ArgB,
890           typename ArgC>
891  Handle Schedule(SchedulePriority priority,
892                  BackendFunc func,  // Function to call on the HistoryBackend.
893                  CancelableRequestConsumerBase* consumer,
894                  RequestType* request,
895                  const ArgA& a,
896                  const ArgB& b,
897                  const ArgC& c) {
898    DCHECK(thread_) << "History service being called after cleanup";
899    DCHECK(thread_checker_.CalledOnValidThread());
900    LoadBackendIfNecessary();
901    if (consumer)
902      AddRequest(request, consumer);
903    ScheduleTask(priority,
904                 base::Bind(func, history_backend_.get(),
905                            scoped_refptr<RequestType>(request), a, b, c));
906    return request->handle();
907  }
908
909  template<typename BackendFunc,
910           class RequestType,  // Descendant of CancelableRequestBase.
911           typename ArgA,
912           typename ArgB,
913           typename ArgC,
914           typename ArgD>
915  Handle Schedule(SchedulePriority priority,
916                  BackendFunc func,  // Function to call on the HistoryBackend.
917                  CancelableRequestConsumerBase* consumer,
918                  RequestType* request,
919                  const ArgA& a,
920                  const ArgB& b,
921                  const ArgC& c,
922                  const ArgD& d) {
923    DCHECK(thread_) << "History service being called after cleanup";
924    DCHECK(thread_checker_.CalledOnValidThread());
925    LoadBackendIfNecessary();
926    if (consumer)
927      AddRequest(request, consumer);
928    ScheduleTask(priority,
929                 base::Bind(func, history_backend_.get(),
930                            scoped_refptr<RequestType>(request), a, b, c, d));
931    return request->handle();
932  }
933
934  // ScheduleAndForget ---------------------------------------------------------
935  //
936  // Functions for scheduling operations on the history thread that do not need
937  // any callbacks and are not cancelable.
938
939  template<typename BackendFunc>
940  void ScheduleAndForget(SchedulePriority priority,
941                         BackendFunc func) {  // Function to call on backend.
942    DCHECK(thread_) << "History service being called after cleanup";
943    DCHECK(thread_checker_.CalledOnValidThread());
944    LoadBackendIfNecessary();
945    ScheduleTask(priority, base::Bind(func, history_backend_.get()));
946  }
947
948  template<typename BackendFunc, typename ArgA>
949  void ScheduleAndForget(SchedulePriority priority,
950                         BackendFunc func,  // Function to call on backend.
951                         const ArgA& a) {
952    DCHECK(thread_) << "History service being called after cleanup";
953    DCHECK(thread_checker_.CalledOnValidThread());
954    LoadBackendIfNecessary();
955    ScheduleTask(priority, base::Bind(func, history_backend_.get(), a));
956  }
957
958  template<typename BackendFunc, typename ArgA, typename ArgB>
959  void ScheduleAndForget(SchedulePriority priority,
960                         BackendFunc func,  // Function to call on backend.
961                         const ArgA& a,
962                         const ArgB& b) {
963    DCHECK(thread_) << "History service being called after cleanup";
964    DCHECK(thread_checker_.CalledOnValidThread());
965    LoadBackendIfNecessary();
966    ScheduleTask(priority, base::Bind(func, history_backend_.get(), a, b));
967  }
968
969  template<typename BackendFunc, typename ArgA, typename ArgB, typename ArgC>
970  void ScheduleAndForget(SchedulePriority priority,
971                         BackendFunc func,  // Function to call on backend.
972                         const ArgA& a,
973                         const ArgB& b,
974                         const ArgC& c) {
975    DCHECK(thread_) << "History service being called after cleanup";
976    DCHECK(thread_checker_.CalledOnValidThread());
977    LoadBackendIfNecessary();
978    ScheduleTask(priority, base::Bind(func, history_backend_.get(), a, b, c));
979  }
980
981  template<typename BackendFunc,
982           typename ArgA,
983           typename ArgB,
984           typename ArgC,
985           typename ArgD>
986  void ScheduleAndForget(SchedulePriority priority,
987                         BackendFunc func,  // Function to call on backend.
988                         const ArgA& a,
989                         const ArgB& b,
990                         const ArgC& c,
991                         const ArgD& d) {
992    DCHECK(thread_) << "History service being called after cleanup";
993    DCHECK(thread_checker_.CalledOnValidThread());
994    LoadBackendIfNecessary();
995    ScheduleTask(priority, base::Bind(func, history_backend_.get(),
996                                      a, b, c, d));
997  }
998
999  template<typename BackendFunc,
1000           typename ArgA,
1001           typename ArgB,
1002           typename ArgC,
1003           typename ArgD,
1004           typename ArgE>
1005  void ScheduleAndForget(SchedulePriority priority,
1006                         BackendFunc func,  // Function to call on backend.
1007                         const ArgA& a,
1008                         const ArgB& b,
1009                         const ArgC& c,
1010                         const ArgD& d,
1011                         const ArgE& e) {
1012    DCHECK(thread_) << "History service being called after cleanup";
1013    DCHECK(thread_checker_.CalledOnValidThread());
1014    LoadBackendIfNecessary();
1015    ScheduleTask(priority, base::Bind(func, history_backend_.get(),
1016                                      a, b, c, d, e));
1017  }
1018
1019  // All vended weak pointers are invalidated in Cleanup().
1020  base::WeakPtrFactory<HistoryService> weak_ptr_factory_;
1021
1022  base::ThreadChecker thread_checker_;
1023
1024  content::NotificationRegistrar registrar_;
1025
1026  // Some void primitives require some internal processing in the main thread
1027  // when done. We use this internal consumer for this purpose.
1028  CancelableRequestConsumer internal_consumer_;
1029
1030  // The thread used by the history service to run complicated operations.
1031  // |thread_| is NULL once |Cleanup| is NULL.
1032  base::Thread* thread_;
1033
1034  // This class has most of the implementation and runs on the 'thread_'.
1035  // You MUST communicate with this class ONLY through the thread_'s
1036  // message_loop().
1037  //
1038  // This pointer will be NULL once Cleanup() has been called, meaning no
1039  // more calls should be made to the history thread.
1040  scoped_refptr<history::HistoryBackend> history_backend_;
1041
1042  // A cache of the user-typed URLs kept in memory that is used by the
1043  // autocomplete system. This will be NULL until the database has been created
1044  // on the background thread.
1045  // TODO(mrossetti): Consider changing ownership. See http://crbug.com/138321
1046  scoped_ptr<history::InMemoryHistoryBackend> in_memory_backend_;
1047
1048  // The profile, may be null when testing.
1049  Profile* profile_;
1050
1051  // Used for propagating link highlighting data across renderers. May be null
1052  // in tests.
1053  scoped_ptr<visitedlink::VisitedLinkMaster> visitedlink_master_;
1054
1055  // Has the backend finished loading? The backend is loaded once Init has
1056  // completed.
1057  bool backend_loaded_;
1058
1059  // The id of the current backend. This is only valid when history_backend_
1060  // is not NULL.
1061  int current_backend_id_;
1062
1063  // Cached values from Init(), used whenever we need to reload the backend.
1064  base::FilePath history_dir_;
1065  BookmarkService* bookmark_service_;
1066  bool no_db_;
1067
1068  // The index used for quick history lookups.
1069  // TODO(mrossetti): Move in_memory_url_index out of history_service.
1070  // See http://crbug.com/138321
1071  scoped_ptr<history::InMemoryURLIndex> in_memory_url_index_;
1072
1073  ObserverList<history::VisitDatabaseObserver> visit_database_observers_;
1074
1075  history::DeleteDirectiveHandler delete_directive_handler_;
1076
1077  DISALLOW_COPY_AND_ASSIGN(HistoryService);
1078};
1079
1080#endif  // CHROME_BROWSER_HISTORY_HISTORY_SERVICE_H_
1081