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