history_service.h revision 2a99a7e74a7f215066514fe81d2bfa6639d9eddd
1// Copyright (c) 2012 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#ifndef CHROME_BROWSER_HISTORY_HISTORY_SERVICE_H_ 6#define CHROME_BROWSER_HISTORY_HISTORY_SERVICE_H_ 7 8#include <set> 9#include <vector> 10 11#include "base/basictypes.h" 12#include "base/bind.h" 13#include "base/callback.h" 14#include "base/files/file_path.h" 15#include "base/logging.h" 16#include "base/memory/ref_counted.h" 17#include "base/memory/scoped_ptr.h" 18#include "base/memory/weak_ptr.h" 19#include "base/observer_list.h" 20#include "base/string16.h" 21#include "base/threading/thread_checker.h" 22#include "base/time.h" 23#include "chrome/browser/common/cancelable_request.h" 24#include "chrome/browser/favicon/favicon_service.h" 25#include "chrome/browser/history/delete_directive_handler.h" 26#include "chrome/browser/history/history_types.h" 27#include "chrome/browser/profiles/profile_keyed_service.h" 28#include "chrome/browser/search_engines/template_url_id.h" 29#include "chrome/common/cancelable_task_tracker.h" 30#include "chrome/common/ref_counted_util.h" 31#include "components/visitedlink/browser/visitedlink_delegate.h" 32#include "content/public/browser/notification_observer.h" 33#include "content/public/browser/notification_registrar.h" 34#include "content/public/common/page_transition_types.h" 35#include "sql/init_status.h" 36#include "sync/api/syncable_service.h" 37#include "ui/base/layout.h" 38 39#if defined(OS_ANDROID) 40#include "chrome/browser/history/android/android_history_provider_service.h" 41#endif 42 43class BookmarkService; 44class GURL; 45class HistoryURLProvider; 46class PageUsageData; 47class PageUsageRequest; 48class Profile; 49struct HistoryURLProviderParams; 50 51namespace base { 52class FilePath; 53class Thread; 54} 55 56namespace components { 57class VisitedLinkMaster; 58} // namespace components 59 60 61namespace history { 62 63class HistoryBackend; 64class HistoryDatabase; 65class HistoryDBTask; 66class HistoryQueryTest; 67class InMemoryHistoryBackend; 68class InMemoryURLIndex; 69class InMemoryURLIndexTest; 70class URLDatabase; 71class VisitDatabaseObserver; 72class VisitFilter; 73struct DownloadRow; 74struct HistoryAddPageArgs; 75struct HistoryDetails; 76 77} // namespace history 78 79// The history service records page titles, and visit times, as well as 80// (eventually) information about autocomplete. 81// 82// This service is thread safe. Each request callback is invoked in the 83// thread that made the request. 84class HistoryService : public CancelableRequestProvider, 85 public content::NotificationObserver, 86 public syncer::SyncableService, 87 public ProfileKeyedService, 88 public components::VisitedLinkDelegate { 89 public: 90 // Miscellaneous commonly-used types. 91 typedef std::vector<PageUsageData*> PageUsageDataList; 92 93 // Must call Init after construction. 94 explicit HistoryService(Profile* profile); 95 // The empty constructor is provided only for testing. 96 HistoryService(); 97 98 virtual ~HistoryService(); 99 100 // Initializes the history service, returning true on success. On false, do 101 // not call any other functions. The given directory will be used for storing 102 // the history files. The BookmarkService is used when deleting URLs to 103 // test if a URL is bookmarked; it may be NULL during testing. 104 bool Init(const base::FilePath& history_dir, BookmarkService* bookmark_service) { 105 return Init(history_dir, bookmark_service, false); 106 } 107 108 // Triggers the backend to load if it hasn't already, and then returns whether 109 // it's finished loading. 110 // Note: Virtual needed for mocking. 111 virtual bool BackendLoaded(); 112 113 // Returns true if the backend has finished loading. 114 bool backend_loaded() const { return backend_loaded_; } 115 116 // Unloads the backend without actually shutting down the history service. 117 // This can be used to temporarily reduce the browser process' memory 118 // footprint. 119 void UnloadBackend(); 120 121 // Called on shutdown, this will tell the history backend to complete and 122 // will release pointers to it. No other functions should be called once 123 // cleanup has happened that may dispatch to the history thread (because it 124 // will be NULL). 125 // 126 // In practice, this will be called by the service manager (BrowserProcess) 127 // when it is being destroyed. Because that reference is being destroyed, it 128 // should be impossible for anybody else to call the service, even if it is 129 // still in memory (pending requests may be holding a reference to us). 130 void Cleanup(); 131 132 // RenderProcessHost pointers are used to scope page IDs (see AddPage). These 133 // objects must tell us when they are being destroyed so that we can clear 134 // out any cached data associated with that scope. 135 // 136 // The given pointer will not be dereferenced, it is only used for 137 // identification purposes, hence it is a void*. 138 void NotifyRenderProcessHostDestruction(const void* host); 139 140 // Triggers the backend to load if it hasn't already, and then returns the 141 // in-memory URL database. The returned pointer MAY BE NULL if the in-memory 142 // database has not been loaded yet. This pointer is owned by the history 143 // system. Callers should not store or cache this value. 144 // 145 // TODO(brettw) this should return the InMemoryHistoryBackend. 146 history::URLDatabase* InMemoryDatabase(); 147 148 // Following functions get URL information from in-memory database. 149 // They return false if database is not available (e.g. not loaded yet) or the 150 // URL does not exist. 151 152 // Reads the number of times the user has typed the given URL. 153 bool GetTypedCountForURL(const GURL& url, int* typed_count); 154 155 // Reads the last visit time for the given URL. 156 bool GetLastVisitTimeForURL(const GURL& url, base::Time* last_visit); 157 158 // Reads the number of times this URL has been visited. 159 bool GetVisitCountForURL(const GURL& url, int* visit_count); 160 161 // Return the quick history index. 162 history::InMemoryURLIndex* InMemoryIndex() const { 163 return in_memory_url_index_.get(); 164 } 165 166 // ProfileKeyedService: 167 virtual void Shutdown() OVERRIDE; 168 169 // Navigation ---------------------------------------------------------------- 170 171 // Adds the given canonical URL to history with the given time as the visit 172 // time. Referrer may be the empty string. 173 // 174 // The supplied render process host is used to scope the given page ID. Page 175 // IDs are only unique inside a given render process, so we need that to 176 // differentiate them. This pointer should not be dereferenced by the history 177 // system. 178 // 179 // The scope/ids can be NULL if there is no meaningful tracking information 180 // that can be performed on the given URL. The 'page_id' should be the ID of 181 // the current session history entry in the given process. 182 // 183 // 'redirects' is an array of redirect URLs leading to this page, with the 184 // page itself as the last item (so when there is no redirect, it will have 185 // one entry). If there are no redirects, this array may also be empty for 186 // the convenience of callers. 187 // 188 // 'did_replace_entry' is true when the navigation entry for this page has 189 // replaced the existing entry. A non-user initiated redirect causes such 190 // replacement. 191 // 192 // All "Add Page" functions will update the visited link database. 193 void AddPage(const GURL& url, 194 base::Time time, 195 const void* id_scope, 196 int32 page_id, 197 const GURL& referrer, 198 const history::RedirectList& redirects, 199 content::PageTransition transition, 200 history::VisitSource visit_source, 201 bool did_replace_entry); 202 203 // For adding pages to history where no tracking information can be done. 204 void AddPage(const GURL& url, 205 base::Time time, 206 history::VisitSource visit_source); 207 208 // All AddPage variants end up here. 209 void AddPage(const history::HistoryAddPageArgs& add_page_args); 210 211 // Adds an entry for the specified url without creating a visit. This should 212 // only be used when bookmarking a page, otherwise the row leaks in the 213 // history db (it never gets cleaned). 214 void AddPageNoVisitForBookmark(const GURL& url, const string16& title); 215 216 // Sets the title for the given page. The page should be in history. If it 217 // is not, this operation is ignored. This call will not update the full 218 // text index. The last title set when the page is indexed will be the 219 // title in the full text index. 220 void SetPageTitle(const GURL& url, const string16& title); 221 222 // Updates the history database with a page's ending time stamp information. 223 // The page can be identified by the combination of the pointer to 224 // a RenderProcessHost, the page id and the url. 225 // 226 // The given pointer will not be dereferenced, it is only used for 227 // identification purposes, hence it is a void*. 228 void UpdateWithPageEndTime(const void* host, 229 int32 page_id, 230 const GURL& url, 231 base::Time end_ts); 232 233 // Indexing ------------------------------------------------------------------ 234 235 // Notifies history of the body text of the given recently-visited URL. 236 // If the URL was not visited "recently enough," the history system may 237 // discard it. 238 void SetPageContents(const GURL& url, const string16& contents); 239 240 // Querying ------------------------------------------------------------------ 241 242 // Returns the information about the requested URL. If the URL is found, 243 // success will be true and the information will be in the URLRow parameter. 244 // On success, the visits, if requested, will be sorted by date. If they have 245 // not been requested, the pointer will be valid, but the vector will be 246 // empty. 247 // 248 // If success is false, neither the row nor the vector will be valid. 249 typedef base::Callback<void( 250 Handle, 251 bool, // Success flag, when false, nothing else is valid. 252 const history::URLRow*, 253 history::VisitVector*)> QueryURLCallback; 254 255 // Queries the basic information about the URL in the history database. If 256 // the caller is interested in the visits (each time the URL is visited), 257 // set |want_visits| to true. If these are not needed, the function will be 258 // faster by setting this to false. 259 Handle QueryURL(const GURL& url, 260 bool want_visits, 261 CancelableRequestConsumerBase* consumer, 262 const QueryURLCallback& callback); 263 264 // Provides the result of a query. See QueryResults in history_types.h. 265 // The common use will be to use QueryResults.Swap to suck the contents of 266 // the results out of the passed in parameter and take ownership of them. 267 typedef base::Callback<void(Handle, history::QueryResults*)> 268 QueryHistoryCallback; 269 270 // Queries all history with the given options (see QueryOptions in 271 // history_types.h). If non-empty, the full-text database will be queried with 272 // the given |text_query|. If empty, all results matching the given options 273 // will be returned. 274 // 275 // This isn't totally hooked up yet, this will query the "new" full text 276 // database (see SetPageContents) which won't generally be set yet. 277 Handle QueryHistory(const string16& text_query, 278 const history::QueryOptions& options, 279 CancelableRequestConsumerBase* consumer, 280 const QueryHistoryCallback& callback); 281 282 // Called when the results of QueryRedirectsFrom are available. 283 // The given vector will contain a list of all redirects, not counting 284 // the original page. If A redirects to B, the vector will contain only B, 285 // and A will be in 'source_url'. 286 // 287 // If there is no such URL in the database or the most recent visit has no 288 // redirect, the vector will be empty. If the history system failed for 289 // some reason, success will additionally be false. If the given page 290 // has redirected to multiple destinations, this will pick a random one. 291 typedef base::Callback<void(Handle, 292 GURL, // from_url 293 bool, // success 294 history::RedirectList*)> QueryRedirectsCallback; 295 296 // Schedules a query for the most recent redirect coming out of the given 297 // URL. See the RedirectQuerySource above, which is guaranteed to be called 298 // if the request is not canceled. 299 Handle QueryRedirectsFrom(const GURL& from_url, 300 CancelableRequestConsumerBase* consumer, 301 const QueryRedirectsCallback& callback); 302 303 // Schedules a query to get the most recent redirects ending at the given 304 // URL. 305 Handle QueryRedirectsTo(const GURL& to_url, 306 CancelableRequestConsumerBase* consumer, 307 const QueryRedirectsCallback& callback); 308 309 typedef base::Callback< 310 void(Handle, 311 bool, // Were we able to determine the # of visits? 312 int, // Number of visits. 313 base::Time)> // Time of first visit. Only set if bool 314 // is true and int is > 0. 315 GetVisibleVisitCountToHostCallback; 316 317 // Requests the number of user-visible visits (i.e. no redirects or subframes) 318 // to all urls on the same scheme/host/port as |url|. This is only valid for 319 // HTTP and HTTPS URLs. 320 Handle GetVisibleVisitCountToHost( 321 const GURL& url, 322 CancelableRequestConsumerBase* consumer, 323 const GetVisibleVisitCountToHostCallback& callback); 324 325 // Called when QueryTopURLsAndRedirects completes. The vector contains a list 326 // of the top |result_count| URLs. For each of these URLs, there is an entry 327 // in the map containing redirects from the URL. For example, if we have the 328 // redirect chain A -> B -> C and A is a top visited URL, then A will be in 329 // the vector and "A => {B -> C}" will be in the map. 330 typedef base::Callback< 331 void(Handle, 332 bool, // Did we get the top urls and redirects? 333 std::vector<GURL>*, // List of top URLs. 334 history::RedirectMap*)> // Redirects for top URLs. 335 QueryTopURLsAndRedirectsCallback; 336 337 // Request the top |result_count| most visited URLs and the chain of redirects 338 // leading to each of these URLs. 339 // TODO(Nik): remove this. Use QueryMostVisitedURLs instead. 340 Handle QueryTopURLsAndRedirects( 341 int result_count, 342 CancelableRequestConsumerBase* consumer, 343 const QueryTopURLsAndRedirectsCallback& callback); 344 345 typedef base::Callback<void(Handle, history::MostVisitedURLList)> 346 QueryMostVisitedURLsCallback; 347 348 typedef base::Callback<void(Handle, const history::FilteredURLList&)> 349 QueryFilteredURLsCallback; 350 351 // Request the |result_count| most visited URLs and the chain of 352 // redirects leading to each of these URLs. |days_back| is the 353 // number of days of history to use. Used by TopSites. 354 Handle QueryMostVisitedURLs(int result_count, int days_back, 355 CancelableRequestConsumerBase* consumer, 356 const QueryMostVisitedURLsCallback& callback); 357 358 // Request the |result_count| URLs filtered and sorted based on the |filter|. 359 // If |extended_info| is true, additional data will be provided in the 360 // results. Computing this additional data is expensive, likely to become 361 // more expensive as additional data points are added in future changes, and 362 // not useful in most cases. Set |extended_info| to true only if you 363 // explicitly require the additional data. 364 Handle QueryFilteredURLs( 365 int result_count, 366 const history::VisitFilter& filter, 367 bool extended_info, 368 CancelableRequestConsumerBase* consumer, 369 const QueryFilteredURLsCallback& callback); 370 371 // Thumbnails ---------------------------------------------------------------- 372 373 // Implemented by consumers to get thumbnail data. Called when a request for 374 // the thumbnail data is complete. Once this callback is made, the request 375 // will be completed and no other calls will be made for that handle. 376 // 377 // This function will be called even on error conditions or if there is no 378 // thumbnail for that page. In these cases, the data pointer will be NULL. 379 typedef base::Callback<void(Handle, scoped_refptr<base::RefCountedBytes>)> 380 ThumbnailDataCallback; 381 382 // Requests a page thumbnail. See ThumbnailDataCallback definition above. 383 Handle GetPageThumbnail(const GURL& page_url, 384 CancelableRequestConsumerBase* consumer, 385 const ThumbnailDataCallback& callback); 386 387 // Database management operations -------------------------------------------- 388 389 // Delete all the information related to a single url. 390 void DeleteURL(const GURL& url); 391 392 // Delete all the information related to a list of urls. (Deleting 393 // URLs one by one is slow as it has to flush to disk each time.) 394 void DeleteURLsForTest(const std::vector<GURL>& urls); 395 396 // Removes all visits in the selected time range (including the start time), 397 // updating the URLs accordingly. This deletes the associated data, including 398 // the full text index. This function also deletes the associated favicons, 399 // if they are no longer referenced. |callback| runs when the expiration is 400 // complete. You may use null Time values to do an unbounded delete in 401 // either direction. 402 // If |restrict_urls| is not empty, only visits to the URLs in this set are 403 // removed. 404 void ExpireHistoryBetween(const std::set<GURL>& restrict_urls, 405 base::Time begin_time, 406 base::Time end_time, 407 const base::Closure& callback, 408 CancelableTaskTracker* tracker); 409 410 // Removes all visits to specified URLs in specific time ranges. 411 // This is the equivalent ExpireHistoryBetween() once for each element in the 412 // vector. The fields of |ExpireHistoryArgs| map directly to the arguments of 413 // of ExpireHistoryBetween(). 414 void ExpireHistory(const std::vector<history::ExpireHistoryArgs>& expire_list, 415 const base::Closure& callback, 416 CancelableTaskTracker* tracker); 417 418 // Removes all visits to the given URLs in the specified time range. Calls 419 // ExpireHistoryBetween() to delete local visits, and handles deletion of 420 // synced visits if appropriate. 421 void ExpireLocalAndRemoteHistoryBetween( 422 const std::set<GURL>& restrict_urls, 423 base::Time begin_time, 424 base::Time end_time, 425 const base::Closure& callback, 426 CancelableTaskTracker* tracker); 427 428 // Processes the given |delete_directive| and sends it to the 429 // SyncChangeProcessor (if it exists). Returns any error resulting 430 // from sending the delete directive to sync. 431 syncer::SyncError ProcessLocalDeleteDirective( 432 const sync_pb::HistoryDeleteDirectiveSpecifics& delete_directive); 433 434 // Downloads ----------------------------------------------------------------- 435 436 // Implemented by the caller of 'CreateDownload' below, and is called when the 437 // history service has created a new entry for a download in the history db. 438 typedef base::Callback<void(int64)> DownloadCreateCallback; 439 440 // Begins a history request to create a new row for a download. 'info' 441 // contains all the download's creation state, and 'callback' runs when the 442 // history service request is complete. The callback is called on the thread 443 // that calls CreateDownload(). 444 void CreateDownload( 445 const history::DownloadRow& info, 446 const DownloadCreateCallback& callback); 447 448 // Implemented by the caller of 'GetNextDownloadId' below. 449 typedef base::Callback<void(int)> DownloadNextIdCallback; 450 451 // Runs the callback with the next available download id. The callback is 452 // called on the thread that calls GetNextDownloadId(). 453 void GetNextDownloadId(const DownloadNextIdCallback& callback); 454 455 // Implemented by the caller of 'QueryDownloads' below, and is called when the 456 // history service has retrieved a list of all download state. The call 457 typedef base::Callback<void( 458 scoped_ptr<std::vector<history::DownloadRow> >)> 459 DownloadQueryCallback; 460 461 // Begins a history request to retrieve the state of all downloads in the 462 // history db. 'callback' runs when the history service request is complete, 463 // at which point 'info' contains an array of history::DownloadRow, one per 464 // download. The callback is called on the thread that calls QueryDownloads(). 465 void QueryDownloads(const DownloadQueryCallback& callback); 466 467 // Begins a request to clean up entries that has been corrupted (because of 468 // the crash, for example). 469 void CleanUpInProgressEntries(); 470 471 // Called to update the history service about the current state of a download. 472 // This is a 'fire and forget' query, so just pass the relevant state info to 473 // the database with no need for a callback. 474 void UpdateDownload(const history::DownloadRow& data); 475 476 // Permanently remove some downloads from the history system. This is a 'fire 477 // and forget' operation. 478 void RemoveDownloads(const std::set<int64>& db_handles); 479 480 // Visit Segments ------------------------------------------------------------ 481 482 typedef base::Callback<void(Handle, std::vector<PageUsageData*>*)> 483 SegmentQueryCallback; 484 485 // Query usage data for all visit segments since the provided time. 486 // 487 // The request is performed asynchronously and can be cancelled by using the 488 // returned handle. 489 // 490 // The vector provided to the callback and its contents is owned by the 491 // history system. It will be deeply deleted after the callback is invoked. 492 // If you want to preserve any PageUsageData instance, simply remove them 493 // from the vector. 494 // 495 // The vector contains a list of PageUsageData. Each PageUsageData ID is set 496 // to the segment ID. The URL and all the other information is set to the page 497 // representing the segment. 498 Handle QuerySegmentUsageSince(CancelableRequestConsumerBase* consumer, 499 const base::Time from_time, 500 int max_result_count, 501 const SegmentQueryCallback& callback); 502 503 // Increases the amount of time the user actively viewed the url. 504 void IncreaseSegmentDuration(const GURL& url, 505 base::Time time, 506 base::TimeDelta delta); 507 508 // Queries segments based on active time viewed. 509 Handle QuerySegmentDurationSince(CancelableRequestConsumerBase* consumer, 510 base::Time from_time, 511 int max_result_count, 512 const SegmentQueryCallback& callback); 513 514 // Keyword search terms ----------------------------------------------------- 515 516 // Sets the search terms for the specified url and keyword. url_id gives the 517 // id of the url, keyword_id the id of the keyword and term the search term. 518 void SetKeywordSearchTermsForURL(const GURL& url, 519 TemplateURLID keyword_id, 520 const string16& term); 521 522 // Deletes all search terms for the specified keyword. 523 void DeleteAllSearchTermsForKeyword(TemplateURLID keyword_id); 524 525 typedef base::Callback< 526 void(Handle, std::vector<history::KeywordSearchTermVisit>*)> 527 GetMostRecentKeywordSearchTermsCallback; 528 529 // Returns up to max_count of the most recent search terms starting with the 530 // specified text. The matching is case insensitive. The results are ordered 531 // in descending order up to |max_count| with the most recent search term 532 // first. 533 Handle GetMostRecentKeywordSearchTerms( 534 TemplateURLID keyword_id, 535 const string16& prefix, 536 int max_count, 537 CancelableRequestConsumerBase* consumer, 538 const GetMostRecentKeywordSearchTermsCallback& callback); 539 540 // Bookmarks ----------------------------------------------------------------- 541 542 // Notification that a URL is no longer bookmarked. 543 void URLsNoLongerBookmarked(const std::set<GURL>& urls); 544 545 // Generic Stuff ------------------------------------------------------------- 546 547 // Schedules a HistoryDBTask for running on the history backend thread. See 548 // HistoryDBTask for details on what this does. 549 virtual void ScheduleDBTask(history::HistoryDBTask* task, 550 CancelableRequestConsumerBase* consumer); 551 552 // Returns true if top sites needs to be migrated out of history into its own 553 // db. 554 bool needs_top_sites_migration() const { return needs_top_sites_migration_; } 555 556 // Adds or removes observers for the VisitDatabase. 557 void AddVisitDatabaseObserver(history::VisitDatabaseObserver* observer); 558 void RemoveVisitDatabaseObserver(history::VisitDatabaseObserver* observer); 559 560 void NotifyVisitDBObserversOnAddVisit(const history::BriefVisitInfo& info); 561 562 // Testing ------------------------------------------------------------------- 563 564 // Designed for unit tests, this passes the given task on to the history 565 // backend to be called once the history backend has terminated. This allows 566 // callers to know when the history thread is complete and the database files 567 // can be deleted and the next test run. Otherwise, the history thread may 568 // still be running, causing problems in subsequent tests. 569 // 570 // There can be only one closing task, so this will override any previously 571 // set task. We will take ownership of the pointer and delete it when done. 572 // The task will be run on the calling thread (this function is threadsafe). 573 void SetOnBackendDestroyTask(const base::Closure& task); 574 575 // Used for unit testing and potentially importing to get known information 576 // into the database. This assumes the URL doesn't exist in the database 577 // 578 // Calling this function many times may be slow because each call will 579 // dispatch to the history thread and will be a separate database 580 // transaction. If this functionality is needed for importing many URLs, 581 // callers should use AddPagesWithDetails() instead. 582 // 583 // Note that this routine (and AddPageWithDetails()) always adds a single 584 // visit using the |last_visit| timestamp, and a PageTransition type of LINK, 585 // if |visit_source| != SYNCED. 586 void AddPageWithDetails(const GURL& url, 587 const string16& title, 588 int visit_count, 589 int typed_count, 590 base::Time last_visit, 591 bool hidden, 592 history::VisitSource visit_source); 593 594 // The same as AddPageWithDetails() but takes a vector. 595 void AddPagesWithDetails(const history::URLRows& info, 596 history::VisitSource visit_source); 597 598 // Starts the TopSites migration in the HistoryThread. Called by the 599 // BackendDelegate. 600 void StartTopSitesMigration(int backend_id); 601 602 // Called by TopSites after the thumbnails were read and it is safe 603 // to delete the thumbnails DB. 604 void OnTopSitesReady(); 605 606 // Returns true if this looks like the type of URL we want to add to the 607 // history. We filter out some URLs such as JavaScript. 608 static bool CanAddURL(const GURL& url); 609 610 base::WeakPtr<HistoryService> AsWeakPtr(); 611 612 // syncer::SyncableService implementation. 613 virtual syncer::SyncMergeResult MergeDataAndStartSyncing( 614 syncer::ModelType type, 615 const syncer::SyncDataList& initial_sync_data, 616 scoped_ptr<syncer::SyncChangeProcessor> sync_processor, 617 scoped_ptr<syncer::SyncErrorFactory> error_handler) OVERRIDE; 618 virtual void StopSyncing(syncer::ModelType type) OVERRIDE; 619 virtual syncer::SyncDataList GetAllSyncData( 620 syncer::ModelType type) const OVERRIDE; 621 virtual syncer::SyncError ProcessSyncChanges( 622 const tracked_objects::Location& from_here, 623 const syncer::SyncChangeList& change_list) OVERRIDE; 624 625 protected: 626 // These are not currently used, hopefully we can do something in the future 627 // to ensure that the most important things happen first. 628 enum SchedulePriority { 629 PRIORITY_UI, // The highest priority (must respond to UI events). 630 PRIORITY_NORMAL, // Normal stuff like adding a page. 631 PRIORITY_LOW, // Low priority things like indexing or expiration. 632 }; 633 634 private: 635 class BackendDelegate; 636#if defined(OS_ANDROID) 637 friend class AndroidHistoryProviderService; 638#endif 639 friend class base::RefCountedThreadSafe<HistoryService>; 640 friend class BackendDelegate; 641 friend class FaviconService; 642 friend class history::HistoryBackend; 643 friend class history::HistoryQueryTest; 644 friend class HistoryOperation; 645 friend class HistoryURLProvider; 646 friend class HistoryURLProviderTest; 647 friend class history::InMemoryURLIndexTest; 648 template<typename Info, typename Callback> friend class DownloadRequest; 649 friend class PageUsageRequest; 650 friend class RedirectRequest; 651 friend class TestingProfile; 652 653 // Implementation of content::NotificationObserver. 654 virtual void Observe(int type, 655 const content::NotificationSource& source, 656 const content::NotificationDetails& details) OVERRIDE; 657 658 // Implementation of components::VisitedLinkDelegate. 659 virtual void RebuildTable( 660 const scoped_refptr<URLEnumerator>& enumerator) OVERRIDE; 661 662 // Low-level Init(). Same as the public version, but adds a |no_db| parameter 663 // that is only set by unittests which causes the backend to not init its DB. 664 bool Init(const base::FilePath& history_dir, 665 BookmarkService* bookmark_service, 666 bool no_db); 667 668 // Called by the HistoryURLProvider class to schedule an autocomplete, it 669 // will be called back on the internal history thread with the history 670 // database so it can query. See history_autocomplete.cc for a diagram. 671 void ScheduleAutocomplete(HistoryURLProvider* provider, 672 HistoryURLProviderParams* params); 673 674 // Broadcasts the given notification. This is called by the backend so that 675 // the notification will be broadcast on the main thread. 676 // 677 // Compared to BroadcastNotifications(), this function does not take 678 // ownership of |details|. 679 void BroadcastNotificationsHelper(int type, 680 history::HistoryDetails* details); 681 682 // Initializes the backend. 683 void LoadBackendIfNecessary(); 684 685 // Notification from the backend that it has finished loading. Sends 686 // notification (NOTIFY_HISTORY_LOADED) and sets backend_loaded_ to true. 687 void OnDBLoaded(int backend_id); 688 689 // Helper function for getting URL information. 690 // Reads a URLRow from in-memory database. Returns false if database is not 691 // available or the URL does not exist. 692 bool GetRowForURL(const GURL& url, history::URLRow* url_row); 693 694 // Favicon ------------------------------------------------------------------- 695 696 // These favicon methods are exposed to the FaviconService. Instead of calling 697 // these methods directly you should call the respective method on the 698 // FaviconService. 699 700 // Used by FaviconService to get the favicon bitmaps from the history backend 701 // which most closely match |desired_size_in_dip| x |desired_size_in_dip| and 702 // |desired_scale_factors| for |icon_types|. If |desired_size_in_dip| is 0, 703 // the largest favicon bitmap for |icon_types| is returned. The returned 704 // FaviconBitmapResults will have at most one result for each of 705 // |desired_scale_factors|. If a favicon bitmap is determined to be the best 706 // candidate for multiple scale factors there will be less results. 707 // If |icon_types| has several types, results for only a single type will be 708 // returned in the priority of TOUCH_PRECOMPOSED_ICON, TOUCH_ICON, and 709 // FAVICON. 710 CancelableTaskTracker::TaskId GetFavicons( 711 const std::vector<GURL>& icon_urls, 712 int icon_types, 713 int desired_size_in_dip, 714 const std::vector<ui::ScaleFactor>& desired_scale_factors, 715 const FaviconService::FaviconResultsCallback& callback, 716 CancelableTaskTracker* tracker); 717 718 // Used by the FaviconService to get favicons mapped to |page_url| for 719 // |icon_types| which most closely match |desired_size_in_dip| and 720 // |desired_scale_factors|. If |desired_size_in_dip| is 0, the largest favicon 721 // bitmap for |icon_types| is returned. The returned FaviconBitmapResults will 722 // have at most one result for each of |desired_scale_factors|. If a favicon 723 // bitmap is determined to be the best candidate for multiple scale factors 724 // there will be less results. If |icon_types| has several types, results for 725 // only a single type will be returned in the priority of 726 // TOUCH_PRECOMPOSED_ICON, TOUCH_ICON, and FAVICON. 727 CancelableTaskTracker::TaskId GetFaviconsForURL( 728 const GURL& page_url, 729 int icon_types, 730 int desired_size_in_dip, 731 const std::vector<ui::ScaleFactor>& desired_scale_factors, 732 const FaviconService::FaviconResultsCallback& callback, 733 CancelableTaskTracker* tracker); 734 735 // Used by the FaviconService to get the favicon bitmap which most closely 736 // matches |desired_size_in_dip| and |desired_scale_factor| from the favicon 737 // with |favicon_id| from the history backend. If |desired_size_in_dip| is 0, 738 // the largest favicon bitmap for |favicon_id| is returned. 739 CancelableTaskTracker::TaskId GetFaviconForID( 740 history::FaviconID favicon_id, 741 int desired_size_in_dip, 742 ui::ScaleFactor desired_scale_factor, 743 const FaviconService::FaviconResultsCallback& callback, 744 CancelableTaskTracker* tracker); 745 746 // Used by the FaviconService to replace the favicon mappings to |page_url| 747 // for |icon_types| on the history backend. 748 // Sample |icon_urls|: 749 // { ICON_URL1 -> TOUCH_ICON, known to the database, 750 // ICON_URL2 -> TOUCH_ICON, not known to the database, 751 // ICON_URL3 -> TOUCH_PRECOMPOSED_ICON, known to the database } 752 // The new mappings are computed from |icon_urls| with these rules: 753 // 1) Any urls in |icon_urls| which are not already known to the database are 754 // rejected. 755 // Sample new mappings to |page_url|: { ICON_URL1, ICON_URL3 } 756 // 2) If |icon_types| has multiple types, the mappings are only set for the 757 // largest icon type. 758 // Sample new mappings to |page_url|: { ICON_URL3 } 759 // |icon_types| can only have multiple IconTypes if 760 // |icon_types| == TOUCH_ICON | TOUCH_PRECOMPOSED_ICON. 761 // The favicon bitmaps which most closely match |desired_size_in_dip| 762 // and |desired_scale_factors| from the favicons which were just mapped 763 // to |page_url| are returned. If |desired_size_in_dip| is 0, the 764 // largest favicon bitmap is returned. 765 CancelableTaskTracker::TaskId UpdateFaviconMappingsAndFetch( 766 const GURL& page_url, 767 const std::vector<GURL>& icon_urls, 768 int icon_types, 769 int desired_size_in_dip, 770 const std::vector<ui::ScaleFactor>& desired_scale_factors, 771 const FaviconService::FaviconResultsCallback& callback, 772 CancelableTaskTracker* tracker); 773 774 // Used by FaviconService to set a favicon for |page_url| and |icon_url| with 775 // |pixel_size|. 776 // Example: 777 // |page_url|: www.google.com 778 // 2 favicons in history for |page_url|: 779 // www.google.com/a.ico 16x16 780 // www.google.com/b.ico 32x32 781 // MergeFavicon(|page_url|, www.google.com/a.ico, ..., ..., 16x16) 782 // 783 // Merging occurs in the following manner: 784 // 1) |page_url| is set to map to only to |icon_url|. In order to not lose 785 // data, favicon bitmaps mapped to |page_url| but not to |icon_url| are 786 // copied to the favicon at |icon_url|. 787 // For the example above, |page_url| will only be mapped to a.ico. 788 // The 32x32 favicon bitmap at b.ico is copied to a.ico 789 // 2) |bitmap_data| is added to the favicon at |icon_url|, overwriting any 790 // favicon bitmaps of |pixel_size|. 791 // For the example above, |bitmap_data| overwrites the 16x16 favicon 792 // bitmap for a.ico. 793 // TODO(pkotwicz): Remove once no longer required by sync. 794 void MergeFavicon(const GURL& page_url, 795 const GURL& icon_url, 796 history::IconType icon_type, 797 scoped_refptr<base::RefCountedMemory> bitmap_data, 798 const gfx::Size& pixel_size); 799 800 // Used by the FaviconService to set the favicons for a page on the history 801 // backend. 802 // |favicon_bitmap_data| replaces all the favicon bitmaps mapped to 803 // |page_url|. 804 // |expired| and |icon_type| fields in FaviconBitmapData are ignored. 805 // Use MergeFavicon() if |favicon_bitmap_data| is incomplete, and favicon 806 // bitmaps in the database should be preserved if possible. For instance, 807 // favicon bitmaps from sync are 1x only. MergeFavicon() is used to avoid 808 // deleting the 2x favicon bitmap if it is present in the history backend. 809 // See HistoryBackend::ValidateSetFaviconsParams() for more details on the 810 // criteria for |favicon_bitmap_data| to be valid. 811 void SetFavicons( 812 const GURL& page_url, 813 history::IconType icon_type, 814 const std::vector<history::FaviconBitmapData>& favicon_bitmap_data); 815 816 // Used by the FaviconService to mark the favicon for the page as being out 817 // of date. 818 void SetFaviconsOutOfDateForPage(const GURL& page_url); 819 820 // Used by the FaviconService to clone favicons from one page to another, 821 // provided that other page does not already have favicons. 822 void CloneFavicons(const GURL& old_page_url, const GURL& new_page_url); 823 824 // Used by the FaviconService for importing many favicons for many pages at 825 // once. The pages must exist, any favicon sets for unknown pages will be 826 // discarded. Existing favicons will not be overwritten. 827 void SetImportedFavicons( 828 const std::vector<history::ImportedFaviconUsage>& favicon_usage); 829 830 // Sets the in-memory URL database. This is called by the backend once the 831 // database is loaded to make it available. 832 void SetInMemoryBackend(int backend_id, 833 history::InMemoryHistoryBackend* mem_backend); 834 835 // Called by our BackendDelegate when there is a problem reading the database. 836 void NotifyProfileError(int backend_id, sql::InitStatus init_status); 837 838 // Call to schedule a given task for running on the history thread with the 839 // specified priority. The task will have ownership taken. 840 void ScheduleTask(SchedulePriority priority, const base::Closure& task); 841 842 // Schedule ------------------------------------------------------------------ 843 // 844 // Functions for scheduling operations on the history thread that have a 845 // handle and may be cancelable. For fire-and-forget operations, see 846 // ScheduleAndForget below. 847 848 template<typename BackendFunc, class RequestType> 849 Handle Schedule(SchedulePriority priority, 850 BackendFunc func, // Function to call on the HistoryBackend. 851 CancelableRequestConsumerBase* consumer, 852 RequestType* request) { 853 DCHECK(thread_) << "History service being called after cleanup"; 854 DCHECK(thread_checker_.CalledOnValidThread()); 855 LoadBackendIfNecessary(); 856 if (consumer) 857 AddRequest(request, consumer); 858 ScheduleTask(priority, 859 base::Bind(func, history_backend_.get(), 860 scoped_refptr<RequestType>(request))); 861 return request->handle(); 862 } 863 864 template<typename BackendFunc, class RequestType, typename ArgA> 865 Handle Schedule(SchedulePriority priority, 866 BackendFunc func, // Function to call on the HistoryBackend. 867 CancelableRequestConsumerBase* consumer, 868 RequestType* request, 869 const ArgA& a) { 870 DCHECK(thread_) << "History service being called after cleanup"; 871 DCHECK(thread_checker_.CalledOnValidThread()); 872 LoadBackendIfNecessary(); 873 if (consumer) 874 AddRequest(request, consumer); 875 ScheduleTask(priority, 876 base::Bind(func, history_backend_.get(), 877 scoped_refptr<RequestType>(request), a)); 878 return request->handle(); 879 } 880 881 template<typename BackendFunc, 882 class RequestType, // Descendant of CancelableRequestBase. 883 typename ArgA, 884 typename ArgB> 885 Handle Schedule(SchedulePriority priority, 886 BackendFunc func, // Function to call on the HistoryBackend. 887 CancelableRequestConsumerBase* consumer, 888 RequestType* request, 889 const ArgA& a, 890 const ArgB& b) { 891 DCHECK(thread_) << "History service being called after cleanup"; 892 DCHECK(thread_checker_.CalledOnValidThread()); 893 LoadBackendIfNecessary(); 894 if (consumer) 895 AddRequest(request, consumer); 896 ScheduleTask(priority, 897 base::Bind(func, history_backend_.get(), 898 scoped_refptr<RequestType>(request), a, b)); 899 return request->handle(); 900 } 901 902 template<typename BackendFunc, 903 class RequestType, // Descendant of CancelableRequestBase. 904 typename ArgA, 905 typename ArgB, 906 typename ArgC> 907 Handle Schedule(SchedulePriority priority, 908 BackendFunc func, // Function to call on the HistoryBackend. 909 CancelableRequestConsumerBase* consumer, 910 RequestType* request, 911 const ArgA& a, 912 const ArgB& b, 913 const ArgC& c) { 914 DCHECK(thread_) << "History service being called after cleanup"; 915 DCHECK(thread_checker_.CalledOnValidThread()); 916 LoadBackendIfNecessary(); 917 if (consumer) 918 AddRequest(request, consumer); 919 ScheduleTask(priority, 920 base::Bind(func, history_backend_.get(), 921 scoped_refptr<RequestType>(request), a, b, c)); 922 return request->handle(); 923 } 924 925 template<typename BackendFunc, 926 class RequestType, // Descendant of CancelableRequestBase. 927 typename ArgA, 928 typename ArgB, 929 typename ArgC, 930 typename ArgD> 931 Handle Schedule(SchedulePriority priority, 932 BackendFunc func, // Function to call on the HistoryBackend. 933 CancelableRequestConsumerBase* consumer, 934 RequestType* request, 935 const ArgA& a, 936 const ArgB& b, 937 const ArgC& c, 938 const ArgD& d) { 939 DCHECK(thread_) << "History service being called after cleanup"; 940 DCHECK(thread_checker_.CalledOnValidThread()); 941 LoadBackendIfNecessary(); 942 if (consumer) 943 AddRequest(request, consumer); 944 ScheduleTask(priority, 945 base::Bind(func, history_backend_.get(), 946 scoped_refptr<RequestType>(request), a, b, c, d)); 947 return request->handle(); 948 } 949 950 // ScheduleAndForget --------------------------------------------------------- 951 // 952 // Functions for scheduling operations on the history thread that do not need 953 // any callbacks and are not cancelable. 954 955 template<typename BackendFunc> 956 void ScheduleAndForget(SchedulePriority priority, 957 BackendFunc func) { // Function to call on backend. 958 DCHECK(thread_) << "History service being called after cleanup"; 959 DCHECK(thread_checker_.CalledOnValidThread()); 960 LoadBackendIfNecessary(); 961 ScheduleTask(priority, base::Bind(func, history_backend_.get())); 962 } 963 964 template<typename BackendFunc, typename ArgA> 965 void ScheduleAndForget(SchedulePriority priority, 966 BackendFunc func, // Function to call on backend. 967 const ArgA& a) { 968 DCHECK(thread_) << "History service being called after cleanup"; 969 DCHECK(thread_checker_.CalledOnValidThread()); 970 LoadBackendIfNecessary(); 971 ScheduleTask(priority, base::Bind(func, history_backend_.get(), a)); 972 } 973 974 template<typename BackendFunc, typename ArgA, typename ArgB> 975 void ScheduleAndForget(SchedulePriority priority, 976 BackendFunc func, // Function to call on backend. 977 const ArgA& a, 978 const ArgB& b) { 979 DCHECK(thread_) << "History service being called after cleanup"; 980 DCHECK(thread_checker_.CalledOnValidThread()); 981 LoadBackendIfNecessary(); 982 ScheduleTask(priority, base::Bind(func, history_backend_.get(), a, b)); 983 } 984 985 template<typename BackendFunc, typename ArgA, typename ArgB, typename ArgC> 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 DCHECK(thread_) << "History service being called after cleanup"; 992 DCHECK(thread_checker_.CalledOnValidThread()); 993 LoadBackendIfNecessary(); 994 ScheduleTask(priority, base::Bind(func, history_backend_.get(), a, b, c)); 995 } 996 997 template<typename BackendFunc, 998 typename ArgA, 999 typename ArgB, 1000 typename ArgC, 1001 typename ArgD> 1002 void ScheduleAndForget(SchedulePriority priority, 1003 BackendFunc func, // Function to call on backend. 1004 const ArgA& a, 1005 const ArgB& b, 1006 const ArgC& c, 1007 const ArgD& d) { 1008 DCHECK(thread_) << "History service being called after cleanup"; 1009 DCHECK(thread_checker_.CalledOnValidThread()); 1010 LoadBackendIfNecessary(); 1011 ScheduleTask(priority, base::Bind(func, history_backend_.get(), 1012 a, b, c, d)); 1013 } 1014 1015 template<typename BackendFunc, 1016 typename ArgA, 1017 typename ArgB, 1018 typename ArgC, 1019 typename ArgD, 1020 typename ArgE> 1021 void ScheduleAndForget(SchedulePriority priority, 1022 BackendFunc func, // Function to call on backend. 1023 const ArgA& a, 1024 const ArgB& b, 1025 const ArgC& c, 1026 const ArgD& d, 1027 const ArgE& e) { 1028 DCHECK(thread_) << "History service being called after cleanup"; 1029 DCHECK(thread_checker_.CalledOnValidThread()); 1030 LoadBackendIfNecessary(); 1031 ScheduleTask(priority, base::Bind(func, history_backend_.get(), 1032 a, b, c, d, e)); 1033 } 1034 1035 // All vended weak pointers are invalidated in Cleanup(). 1036 base::WeakPtrFactory<HistoryService> weak_ptr_factory_; 1037 1038 base::ThreadChecker thread_checker_; 1039 1040 content::NotificationRegistrar registrar_; 1041 1042 // Some void primitives require some internal processing in the main thread 1043 // when done. We use this internal consumer for this purpose. 1044 CancelableRequestConsumer internal_consumer_; 1045 1046 // The thread used by the history service to run complicated operations. 1047 // |thread_| is NULL once |Cleanup| is NULL. 1048 base::Thread* thread_; 1049 1050 // This class has most of the implementation and runs on the 'thread_'. 1051 // You MUST communicate with this class ONLY through the thread_'s 1052 // message_loop(). 1053 // 1054 // This pointer will be NULL once Cleanup() has been called, meaning no 1055 // more calls should be made to the history thread. 1056 scoped_refptr<history::HistoryBackend> history_backend_; 1057 1058 // A cache of the user-typed URLs kept in memory that is used by the 1059 // autocomplete system. This will be NULL until the database has been created 1060 // on the background thread. 1061 // TODO(mrossetti): Consider changing ownership. See http://crbug.com/138321 1062 scoped_ptr<history::InMemoryHistoryBackend> in_memory_backend_; 1063 1064 // The profile, may be null when testing. 1065 Profile* profile_; 1066 1067 // Used for propagating link highlighting data across renderers. May be null 1068 // in tests. 1069 scoped_ptr<components::VisitedLinkMaster> visitedlink_master_; 1070 1071 // Has the backend finished loading? The backend is loaded once Init has 1072 // completed. 1073 bool backend_loaded_; 1074 1075 // The id of the current backend. This is only valid when history_backend_ 1076 // is not NULL. 1077 int current_backend_id_; 1078 1079 // Cached values from Init(), used whenever we need to reload the backend. 1080 base::FilePath history_dir_; 1081 BookmarkService* bookmark_service_; 1082 bool no_db_; 1083 1084 // True if needs top site migration. 1085 bool needs_top_sites_migration_; 1086 1087 // The index used for quick history lookups. 1088 // TODO(mrossetti): Move in_memory_url_index out of history_service. 1089 // See http://crbug.com/138321 1090 scoped_ptr<history::InMemoryURLIndex> in_memory_url_index_; 1091 1092 ObserverList<history::VisitDatabaseObserver> visit_database_observers_; 1093 1094 history::DeleteDirectiveHandler delete_directive_handler_; 1095 1096 DISALLOW_COPY_AND_ASSIGN(HistoryService); 1097}; 1098 1099#endif // CHROME_BROWSER_HISTORY_HISTORY_SERVICE_H_ 1100