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