history.h revision 3345a6884c488ff3a535c2c9acdd33d74b37e311
1// Copyright (c) 2010 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_H_ 6#define CHROME_BROWSER_HISTORY_HISTORY_H_ 7#pragma once 8 9#include <vector> 10 11#include "base/basictypes.h" 12#include "base/callback.h" 13#include "base/file_path.h" 14#include "base/ref_counted.h" 15#include "base/scoped_ptr.h" 16#include "base/string16.h" 17#include "base/task.h" 18#include "chrome/browser/cancelable_request.h" 19#include "chrome/browser/favicon_service.h" 20#include "chrome/browser/history/history_types.h" 21#include "chrome/browser/search_engines/template_url_id.h" 22#include "chrome/common/notification_registrar.h" 23#include "chrome/common/page_transition_types.h" 24#include "chrome/common/ref_counted_util.h" 25 26class BookmarkService; 27struct DownloadCreateInfo; 28class FilePath; 29class GURL; 30class HistoryURLProvider; 31struct HistoryURLProviderParams; 32class InMemoryURLDatabase; 33class MainPagesRequest; 34class PageUsageData; 35class PageUsageRequest; 36class Profile; 37class SkBitmap; 38struct ThumbnailScore; 39 40namespace base { 41class Thread; 42class Time; 43} 44 45namespace browser_sync { 46class HistoryModelWorker; 47class TypedUrlDataTypeController; 48} 49 50namespace history { 51class InMemoryHistoryBackend; 52class InMemoryURLIndex; 53class HistoryAddPageArgs; 54class HistoryBackend; 55class HistoryDatabase; 56struct HistoryDetails; 57class HistoryQueryTest; 58class URLDatabase; 59} // namespace history 60 61 62// HistoryDBTask can be used to process arbitrary work on the history backend 63// thread. HistoryDBTask is scheduled using HistoryService::ScheduleDBTask. 64// When HistoryBackend processes the task it invokes RunOnDBThread. Once the 65// task completes and has not been canceled, DoneRunOnMainThread is invoked back 66// on the main thread. 67class HistoryDBTask : public base::RefCountedThreadSafe<HistoryDBTask> { 68 public: 69 // Invoked on the database thread. The return value indicates whether the 70 // task is done. A return value of true signals the task is done and 71 // RunOnDBThread should NOT be invoked again. A return value of false 72 // indicates the task is not done, and should be run again after other 73 // tasks are given a chance to be processed. 74 virtual bool RunOnDBThread(history::HistoryBackend* backend, 75 history::HistoryDatabase* db) = 0; 76 77 // Invoked on the main thread once RunOnDBThread has returned false. This is 78 // only invoked if the request was not canceled and returned true from 79 // RunOnDBThread. 80 virtual void DoneRunOnMainThread() = 0; 81 82 protected: 83 friend class base::RefCountedThreadSafe<HistoryDBTask>; 84 85 virtual ~HistoryDBTask() {} 86}; 87 88// The history service records page titles, and visit times, as well as 89// (eventually) information about autocomplete. 90// 91// This service is thread safe. Each request callback is invoked in the 92// thread that made the request. 93class HistoryService : public CancelableRequestProvider, 94 public NotificationObserver, 95 public base::RefCountedThreadSafe<HistoryService> { 96 public: 97 // Miscellaneous commonly-used types. 98 typedef std::vector<PageUsageData*> PageUsageDataList; 99 100 // ID (both star_id and group_id) of the bookmark bar. 101 // This entry always exists. 102 static const history::StarID kBookmarkBarID; 103 104 // Must call Init after construction. 105 explicit HistoryService(Profile* profile); 106 // The empty constructor is provided only for testing. 107 HistoryService(); 108 109 // Initializes the history service, returning true on success. On false, do 110 // not call any other functions. The given directory will be used for storing 111 // the history files. The BookmarkService is used when deleting URLs to 112 // test if a URL is bookmarked; it may be NULL during testing. 113 bool Init(const FilePath& history_dir, BookmarkService* bookmark_service) { 114 return Init(history_dir, bookmark_service, false); 115 } 116 117 // Triggers the backend to load if it hasn't already, and then returns whether 118 // it's finished loading. 119 bool BackendLoaded(); 120 121 // Unloads the backend without actually shutting down the history service. 122 // This can be used to temporarily reduce the browser process' memory 123 // footprint. 124 void UnloadBackend(); 125 126 // Called on shutdown, this will tell the history backend to complete and 127 // will release pointers to it. No other functions should be called once 128 // cleanup has happened that may dispatch to the history thread (because it 129 // will be NULL). 130 // 131 // In practice, this will be called by the service manager (BrowserProcess) 132 // when it is being destroyed. Because that reference is being destroyed, it 133 // should be impossible for anybody else to call the service, even if it is 134 // still in memory (pending requests may be holding a reference to us). 135 void Cleanup(); 136 137 // RenderProcessHost pointers are used to scope page IDs (see AddPage). These 138 // objects must tell us when they are being destroyed so that we can clear 139 // out any cached data associated with that scope. 140 // 141 // The given pointer will not be dereferenced, it is only used for 142 // identification purposes, hence it is a void*. 143 void NotifyRenderProcessHostDestruction(const void* host); 144 145 // Triggers the backend to load if it hasn't already, and then returns the 146 // in-memory URL database. The returned pointer MAY BE NULL if the in-memory 147 // database has not been loaded yet. This pointer is owned by the history 148 // system. Callers should not store or cache this value. 149 // 150 // TODO(brettw) this should return the InMemoryHistoryBackend. 151 history::URLDatabase* InMemoryDatabase(); 152 153 history::InMemoryURLIndex* InMemoryIndex(); 154 155 // Navigation ---------------------------------------------------------------- 156 157 // Adds the given canonical URL to history with the current time as the visit 158 // time. Referrer may be the empty string. 159 // 160 // The supplied render process host is used to scope the given page ID. Page 161 // IDs are only unique inside a given render process, so we need that to 162 // differentiate them. This pointer should not be dereferenced by the history 163 // system. Since render view host pointers may be reused (if one gets deleted 164 // and a new one created at the same address), TabContents should notify 165 // us when they are being destroyed through NotifyTabContentsDestruction. 166 // 167 // The scope/ids can be NULL if there is no meaningful tracking information 168 // that can be performed on the given URL. The 'page_id' should be the ID of 169 // the current session history entry in the given process. 170 // 171 // 'redirects' is an array of redirect URLs leading to this page, with the 172 // page itself as the last item (so when there is no redirect, it will have 173 // one entry). If there are no redirects, this array may also be empty for 174 // the convenience of callers. 175 // 176 // 'did_replace_entry' is true when the navigation entry for this page has 177 // replaced the existing entry. A non-user initiated redirect causes such 178 // replacement. 179 // 180 // All "Add Page" functions will update the visited link database. 181 void AddPage(const GURL& url, 182 const void* id_scope, 183 int32 page_id, 184 const GURL& referrer, 185 PageTransition::Type transition, 186 const history::RedirectList& redirects, 187 history::VisitSource visit_source, 188 bool did_replace_entry); 189 190 // For adding pages to history with a specific time. This is for testing 191 // purposes. Call the previous one to use the current time. 192 void AddPage(const GURL& url, 193 base::Time time, 194 const void* id_scope, 195 int32 page_id, 196 const GURL& referrer, 197 PageTransition::Type transition, 198 const history::RedirectList& redirects, 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, history::VisitSource visit_source) { 204 AddPage(url, NULL, 0, GURL(), PageTransition::LINK, 205 history::RedirectList(), visit_source, false); 206 } 207 208 // All AddPage variants end up here. 209 void AddPage(const history::HistoryAddPageArgs& add_page_args); 210 211 // Sets the title for the given page. The page should be in history. If it 212 // is not, this operation is ignored. This call will not update the full 213 // text index. The last title set when the page is indexed will be the 214 // title in the full text index. 215 void SetPageTitle(const GURL& url, const string16& title); 216 217 // Indexing ------------------------------------------------------------------ 218 219 // Notifies history of the body text of the given recently-visited URL. 220 // If the URL was not visited "recently enough," the history system may 221 // discard it. 222 void SetPageContents(const GURL& url, const string16& contents); 223 224 // Querying ------------------------------------------------------------------ 225 226 // Callback class that a client can implement to iterate over URLs. The 227 // callbacks WILL BE CALLED ON THE BACKGROUND THREAD! Your implementation 228 // should handle this appropriately. 229 class URLEnumerator { 230 public: 231 virtual ~URLEnumerator() {} 232 233 // Indicates that a URL is available. There will be exactly one call for 234 // every URL in history. 235 virtual void OnURL(const GURL& url) = 0; 236 237 // Indicates we are done iterating over URLs. Once called, there will be no 238 // more callbacks made. This call is guaranteed to occur, even if there are 239 // no URLs. If all URLs were iterated, success will be true. 240 virtual void OnComplete(bool success) = 0; 241 }; 242 243 // Enumerate all URLs in history. The given iterator will be owned by the 244 // caller, so the caller should ensure it exists until OnComplete is called. 245 // You should not generally use this since it will be slow to slurp all URLs 246 // in from the database. It is designed for rebuilding the visited link 247 // database from history. 248 void IterateURLs(URLEnumerator* iterator); 249 250 // Returns the information about the requested URL. If the URL is found, 251 // success will be true and the information will be in the URLRow parameter. 252 // On success, the visits, if requested, will be sorted by date. If they have 253 // not been requested, the pointer will be valid, but the vector will be 254 // empty. 255 // 256 // If success is false, neither the row nor the vector will be valid. 257 typedef Callback4<Handle, 258 bool, // Success flag, when false, nothing else is valid. 259 const history::URLRow*, 260 history::VisitVector*>::Type 261 QueryURLCallback; 262 263 // Queries the basic information about the URL in the history database. If 264 // the caller is interested in the visits (each time the URL is visited), 265 // set |want_visits| to true. If these are not needed, the function will be 266 // faster by setting this to false. 267 Handle QueryURL(const GURL& url, 268 bool want_visits, 269 CancelableRequestConsumerBase* consumer, 270 QueryURLCallback* callback); 271 272 // Provides the result of a query. See QueryResults in history_types.h. 273 // The common use will be to use QueryResults.Swap to suck the contents of 274 // the results out of the passed in parameter and take ownership of them. 275 typedef Callback2<Handle, history::QueryResults*>::Type 276 QueryHistoryCallback; 277 278 // Queries all history with the given options (see QueryOptions in 279 // history_types.h). If non-empty, the full-text database will be queried with 280 // the given |text_query|. If empty, all results matching the given options 281 // will be returned. 282 // 283 // This isn't totally hooked up yet, this will query the "new" full text 284 // database (see SetPageContents) which won't generally be set yet. 285 Handle QueryHistory(const string16& text_query, 286 const history::QueryOptions& options, 287 CancelableRequestConsumerBase* consumer, 288 QueryHistoryCallback* callback); 289 290 // Called when the results of QueryRedirectsFrom are available. 291 // The given vector will contain a list of all redirects, not counting 292 // the original page. If A redirects to B, the vector will contain only B, 293 // and A will be in 'source_url'. 294 // 295 // If there is no such URL in the database or the most recent visit has no 296 // redirect, the vector will be empty. If the history system failed for 297 // some reason, success will additionally be false. If the given page 298 // has redirected to multiple destinations, this will pick a random one. 299 typedef Callback4<Handle, 300 GURL, // from_url 301 bool, // success 302 history::RedirectList*>::Type 303 QueryRedirectsCallback; 304 305 // Schedules a query for the most recent redirect coming out of the given 306 // URL. See the RedirectQuerySource above, which is guaranteed to be called 307 // if the request is not canceled. 308 Handle QueryRedirectsFrom(const GURL& from_url, 309 CancelableRequestConsumerBase* consumer, 310 QueryRedirectsCallback* callback); 311 312 // Schedules a query to get the most recent redirects ending at the given 313 // URL. 314 Handle QueryRedirectsTo(const GURL& to_url, 315 CancelableRequestConsumerBase* consumer, 316 QueryRedirectsCallback* callback); 317 318 typedef Callback4<Handle, 319 bool, // Were we able to determine the # of visits? 320 int, // Number of visits. 321 base::Time>::Type // Time of first visit. Only first bool is 322 // true and int is > 0. 323 GetVisitCountToHostCallback; 324 325 // Requests the number of visits to all urls on the scheme/host/post 326 // identified by url. This is only valid for http and https urls. 327 Handle GetVisitCountToHost(const GURL& url, 328 CancelableRequestConsumerBase* consumer, 329 GetVisitCountToHostCallback* callback); 330 331 // Called when QueryTopURLsAndRedirects completes. The vector contains a list 332 // of the top |result_count| URLs. For each of these URLs, there is an entry 333 // in the map containing redirects from the URL. For example, if we have the 334 // redirect chain A -> B -> C and A is a top visited URL, then A will be in 335 // the vector and "A => {B -> C}" will be in the map. 336 typedef Callback4<Handle, 337 bool, // Did we get the top urls and redirects? 338 std::vector<GURL>*, // List of top URLs. 339 history::RedirectMap*>::Type // Redirects for top URLs. 340 QueryTopURLsAndRedirectsCallback; 341 342 // Request the top |result_count| most visited URLs and the chain of redirects 343 // leading to each of these URLs. 344 // TODO(Nik): remove this. Use QueryMostVisitedURLs instead. 345 Handle QueryTopURLsAndRedirects(int result_count, 346 CancelableRequestConsumerBase* consumer, 347 QueryTopURLsAndRedirectsCallback* callback); 348 349 typedef Callback2<Handle, history::MostVisitedURLList>::Type 350 QueryMostVisitedURLsCallback; 351 352 // Request the |result_count| most visited URLs and the chain of 353 // redirects leading to each of these URLs. |days_back| is the 354 // number of days of history to use. Used by TopSites. 355 Handle QueryMostVisitedURLs(int result_count, int days_back, 356 CancelableRequestConsumerBase* consumer, 357 QueryMostVisitedURLsCallback* callback); 358 359 // Thumbnails ---------------------------------------------------------------- 360 361 // Implemented by consumers to get thumbnail data. Called when a request for 362 // the thumbnail data is complete. Once this callback is made, the request 363 // will be completed and no other calls will be made for that handle. 364 // 365 // This function will be called even on error conditions or if there is no 366 // thumbnail for that page. In these cases, the data pointer will be NULL. 367 typedef Callback2<Handle, scoped_refptr<RefCountedBytes> >::Type 368 ThumbnailDataCallback; 369 370 // Sets the thumbnail for a given URL. The URL must be in the history 371 // database or the request will be ignored. 372 void SetPageThumbnail(const GURL& url, 373 const SkBitmap& thumbnail, 374 const ThumbnailScore& score); 375 376 // Requests a page thumbnail. See ThumbnailDataCallback definition above. 377 Handle GetPageThumbnail(const GURL& page_url, 378 CancelableRequestConsumerBase* consumer, 379 ThumbnailDataCallback* callback); 380 381 // Database management operations -------------------------------------------- 382 383 // Delete all the information related to a single url. 384 void DeleteURL(const GURL& url); 385 386 // Implemented by the caller of ExpireHistoryBetween, and 387 // is called when the history service has deleted the history. 388 typedef Callback0::Type ExpireHistoryCallback; 389 390 // Removes all visits in the selected time range (including the start time), 391 // updating the URLs accordingly. This deletes the associated data, including 392 // the full text index. This function also deletes the associated favicons, 393 // if they are no longer referenced. |callback| runs when the expiration is 394 // complete. You may use null Time values to do an unbounded delete in 395 // either direction. 396 // If |restrict_urls| is not empty, only visits to the URLs in this set are 397 // removed. 398 void ExpireHistoryBetween(const std::set<GURL>& restrict_urls, 399 base::Time begin_time, base::Time end_time, 400 CancelableRequestConsumerBase* consumer, 401 ExpireHistoryCallback* callback); 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 Callback2<DownloadCreateInfo, int64>::Type DownloadCreateCallback; 408 409 // Begins a history request to create a new persistent entry for a download. 410 // 'info' contains all the download's creation state, and 'callback' runs 411 // when the history service request is complete. 412 Handle CreateDownload(const DownloadCreateInfo& info, 413 CancelableRequestConsumerBase* consumer, 414 DownloadCreateCallback* callback); 415 416 // Implemented by the caller of 'QueryDownloads' below, and is called when the 417 // history service has retrieved a list of all download state. The call 418 typedef Callback1<std::vector<DownloadCreateInfo>*>::Type 419 DownloadQueryCallback; 420 421 // Begins a history request to retrieve the state of all downloads in the 422 // history db. 'callback' runs when the history service request is complete, 423 // at which point 'info' contains an array of DownloadCreateInfo, one per 424 // download. 425 Handle QueryDownloads(CancelableRequestConsumerBase* consumer, 426 DownloadQueryCallback* callback); 427 428 // Begins a request to clean up entries that has been corrupted (because of 429 // the crash, for example). 430 void CleanUpInProgressEntries(); 431 432 // Called to update the history service about the current state of a download. 433 // This is a 'fire and forget' query, so just pass the relevant state info to 434 // the database with no need for a callback. 435 void UpdateDownload(int64 received_bytes, int32 state, int64 db_handle); 436 437 // Called to update the history service about the path of a download. 438 // This is a 'fire and forget' query. 439 void UpdateDownloadPath(const FilePath& path, int64 db_handle); 440 441 // Permanently remove a download from the history system. This is a 'fire and 442 // forget' operation. 443 void RemoveDownload(int64 db_handle); 444 445 // Permanently removes all completed download from the history system within 446 // the specified range. This function does not delete downloads that are in 447 // progress or in the process of being cancelled. This is a 'fire and forget' 448 // operation. You can pass is_null times to get unbounded time in either or 449 // both directions. 450 void RemoveDownloadsBetween(base::Time remove_begin, base::Time remove_end); 451 452 // Visit Segments ------------------------------------------------------------ 453 454 typedef Callback2<Handle, std::vector<PageUsageData*>*>::Type 455 SegmentQueryCallback; 456 457 // Query usage data for all visit segments since the provided time. 458 // 459 // The request is performed asynchronously and can be cancelled by using the 460 // returned handle. 461 // 462 // The vector provided to the callback and its contents is owned by the 463 // history system. It will be deeply deleted after the callback is invoked. 464 // If you want to preserve any PageUsageData instance, simply remove them 465 // from the vector. 466 // 467 // The vector contains a list of PageUsageData. Each PageUsageData ID is set 468 // to the segment ID. The URL and all the other information is set to the page 469 // representing the segment. 470 Handle QuerySegmentUsageSince(CancelableRequestConsumerBase* consumer, 471 const base::Time from_time, 472 int max_result_count, 473 SegmentQueryCallback* callback); 474 475 // Set the presentation index for the segment identified by |segment_id|. 476 void SetSegmentPresentationIndex(int64 segment_id, int index); 477 478 // Keyword search terms ----------------------------------------------------- 479 480 // Sets the search terms for the specified url and keyword. url_id gives the 481 // id of the url, keyword_id the id of the keyword and term the search term. 482 void SetKeywordSearchTermsForURL(const GURL& url, 483 TemplateURLID keyword_id, 484 const string16& term); 485 486 // Deletes all search terms for the specified keyword. 487 void DeleteAllSearchTermsForKeyword(TemplateURLID keyword_id); 488 489 typedef Callback2<Handle, std::vector<history::KeywordSearchTermVisit>*>::Type 490 GetMostRecentKeywordSearchTermsCallback; 491 492 // Returns up to max_count of the most recent search terms starting with the 493 // specified text. The matching is case insensitive. The results are ordered 494 // in descending order up to |max_count| with the most recent search term 495 // first. 496 Handle GetMostRecentKeywordSearchTerms( 497 TemplateURLID keyword_id, 498 const string16& prefix, 499 int max_count, 500 CancelableRequestConsumerBase* consumer, 501 GetMostRecentKeywordSearchTermsCallback* callback); 502 503 // Bookmarks ----------------------------------------------------------------- 504 505 // Notification that a URL is no longer bookmarked. 506 void URLsNoLongerBookmarked(const std::set<GURL>& urls); 507 508 // Generic Stuff ------------------------------------------------------------- 509 510 typedef Callback0::Type HistoryDBTaskCallback; 511 512 // Schedules a HistoryDBTask for running on the history backend thread. See 513 // HistoryDBTask for details on what this does. 514 virtual Handle ScheduleDBTask(HistoryDBTask* task, 515 CancelableRequestConsumerBase* consumer); 516 517 // Testing ------------------------------------------------------------------- 518 519 // Designed for unit tests, this passes the given task on to the history 520 // backend to be called once the history backend has terminated. This allows 521 // callers to know when the history thread is complete and the database files 522 // can be deleted and the next test run. Otherwise, the history thread may 523 // still be running, causing problems in subsequent tests. 524 // 525 // There can be only one closing task, so this will override any previously 526 // set task. We will take ownership of the pointer and delete it when done. 527 // The task will be run on the calling thread (this function is threadsafe). 528 void SetOnBackendDestroyTask(Task* task); 529 530 // Used for unit testing and potentially importing to get known information 531 // into the database. This assumes the URL doesn't exist in the database 532 // 533 // Calling this function many times may be slow because each call will 534 // dispatch to the history thread and will be a separate database 535 // transaction. If this functionality is needed for importing many URLs, a 536 // version that takes an array should probably be added. 537 void AddPageWithDetails(const GURL& url, 538 const string16& title, 539 int visit_count, 540 int typed_count, 541 base::Time last_visit, 542 bool hidden, 543 history::VisitSource visit_source); 544 545 // The same as AddPageWithDetails() but takes a vector. 546 void AddPagesWithDetails(const std::vector<history::URLRow>& info, 547 history::VisitSource visit_source); 548 549 // Starts the TopSites migration in the HistoryThread. Called by the 550 // BackendDelegate. 551 void StartTopSitesMigration(); 552 553 // Called by TopSites after the thumbnails were read and it is safe 554 // to delete the thumbnails DB. 555 void OnTopSitesReady(); 556 557 // Returns true if this looks like the type of URL we want to add to the 558 // history. We filter out some URLs such as JavaScript. 559 static bool CanAddURL(const GURL& url); 560 561 protected: 562 ~HistoryService(); 563 564 // These are not currently used, hopefully we can do something in the future 565 // to ensure that the most important things happen first. 566 enum SchedulePriority { 567 PRIORITY_UI, // The highest priority (must respond to UI events). 568 PRIORITY_NORMAL, // Normal stuff like adding a page. 569 PRIORITY_LOW, // Low priority things like indexing or expiration. 570 }; 571 572 private: 573 class BackendDelegate; 574 friend class base::RefCountedThreadSafe<HistoryService>; 575 friend class BackendDelegate; 576 friend class FaviconService; 577 friend class history::HistoryBackend; 578 friend class history::HistoryQueryTest; 579 friend class HistoryOperation; 580 friend class HistoryURLProvider; 581 friend class HistoryURLProviderTest; 582 template<typename Info, typename Callback> friend class DownloadRequest; 583 friend class PageUsageRequest; 584 friend class RedirectRequest; 585 friend class FavIconRequest; 586 friend class TestingProfile; 587 588 // Implementation of NotificationObserver. 589 virtual void Observe(NotificationType type, 590 const NotificationSource& source, 591 const NotificationDetails& details); 592 593 // Low-level Init(). Same as the public version, but adds a |no_db| parameter 594 // that is only set by unittests which causes the backend to not init its DB. 595 bool Init(const FilePath& history_dir, 596 BookmarkService* bookmark_service, 597 bool no_db); 598 599 // Called by the HistoryURLProvider class to schedule an autocomplete, it 600 // will be called back on the internal history thread with the history 601 // database so it can query. See history_autocomplete.cc for a diagram. 602 void ScheduleAutocomplete(HistoryURLProvider* provider, 603 HistoryURLProviderParams* params); 604 605 // Broadcasts the given notification. This is called by the backend so that 606 // the notification will be broadcast on the main thread. 607 // 608 // The |details_deleted| pointer will be sent as the "details" for the 609 // notification. The function takes ownership of the pointer and deletes it 610 // when the notification is sent (it is coming from another thread, so must 611 // be allocated on the heap). 612 void BroadcastNotifications(NotificationType type, 613 history::HistoryDetails* details_deleted); 614 615 // Initializes the backend. 616 void LoadBackendIfNecessary(); 617 618 // Notification from the backend that it has finished loading. Sends 619 // notification (NOTIFY_HISTORY_LOADED) and sets backend_loaded_ to true. 620 void OnDBLoaded(); 621 622 // FavIcon ------------------------------------------------------------------- 623 624 // These favicon methods are exposed to the FaviconService. Instead of calling 625 // these methods directly you should call the respective method on the 626 // FaviconService. 627 628 // Used by the FaviconService to get a favicon from the history backend. 629 void GetFavicon(FaviconService::GetFaviconRequest* request, 630 const GURL& icon_url); 631 632 // Used by the FaviconService to update the favicon mappings on the history 633 // backend. 634 void UpdateFaviconMappingAndFetch(FaviconService::GetFaviconRequest* request, 635 const GURL& page_url, 636 const GURL& icon_url); 637 638 // Used by the FaviconService to get a favicon from the history backend. 639 void GetFaviconForURL(FaviconService::GetFaviconRequest* request, 640 const GURL& page_url); 641 642 // Used by the FaviconService to mark the favicon for the page as being out 643 // of date. 644 void SetFaviconOutOfDateForPage(const GURL& page_url); 645 646 // Used by the FaviconService for importing many favicons for many pages at 647 // once. The pages must exist, any favicon sets for unknown pages will be 648 // discarded. Existing favicons will not be overwritten. 649 void SetImportedFavicons( 650 const std::vector<history::ImportedFavIconUsage>& favicon_usage); 651 652 // Used by the FaviconService to set the favicon for a page on the history 653 // backend. 654 void SetFavicon(const GURL& page_url, 655 const GURL& icon_url, 656 const std::vector<unsigned char>& image_data); 657 658 659 // Sets the in-memory URL database. This is called by the backend once the 660 // database is loaded to make it available. 661 void SetInMemoryBackend(history::InMemoryHistoryBackend* mem_backend); 662 663 // Called by our BackendDelegate when there is a problem reading the database. 664 // |message_id| is the relevant message in the string table to display. 665 void NotifyProfileError(int message_id); 666 667 // Call to schedule a given task for running on the history thread with the 668 // specified priority. The task will have ownership taken. 669 void ScheduleTask(SchedulePriority priority, Task* task); 670 671 // Schedule ------------------------------------------------------------------ 672 // 673 // Functions for scheduling operations on the history thread that have a 674 // handle and may be cancelable. For fire-and-forget operations, see 675 // ScheduleAndForget below. 676 677 template<typename BackendFunc, class RequestType> 678 Handle Schedule(SchedulePriority priority, 679 BackendFunc func, // Function to call on the HistoryBackend. 680 CancelableRequestConsumerBase* consumer, 681 RequestType* request) { 682 DCHECK(thread_) << "History service being called after cleanup"; 683 LoadBackendIfNecessary(); 684 if (consumer) 685 AddRequest(request, consumer); 686 ScheduleTask(priority, 687 NewRunnableMethod(history_backend_.get(), func, 688 scoped_refptr<RequestType>(request))); 689 return request->handle(); 690 } 691 692 template<typename BackendFunc, class RequestType, typename ArgA> 693 Handle Schedule(SchedulePriority priority, 694 BackendFunc func, // Function to call on the HistoryBackend. 695 CancelableRequestConsumerBase* consumer, 696 RequestType* request, 697 const ArgA& a) { 698 DCHECK(thread_) << "History service being called after cleanup"; 699 LoadBackendIfNecessary(); 700 if (consumer) 701 AddRequest(request, consumer); 702 ScheduleTask(priority, 703 NewRunnableMethod(history_backend_.get(), func, 704 scoped_refptr<RequestType>(request), 705 a)); 706 return request->handle(); 707 } 708 709 template<typename BackendFunc, 710 class RequestType, // Descendant of CancelableRequstBase. 711 typename ArgA, 712 typename ArgB> 713 Handle Schedule(SchedulePriority priority, 714 BackendFunc func, // Function to call on the HistoryBackend. 715 CancelableRequestConsumerBase* consumer, 716 RequestType* request, 717 const ArgA& a, 718 const ArgB& b) { 719 DCHECK(thread_) << "History service being called after cleanup"; 720 LoadBackendIfNecessary(); 721 if (consumer) 722 AddRequest(request, consumer); 723 ScheduleTask(priority, 724 NewRunnableMethod(history_backend_.get(), func, 725 scoped_refptr<RequestType>(request), 726 a, b)); 727 return request->handle(); 728 } 729 730 template<typename BackendFunc, 731 class RequestType, // Descendant of CancelableRequstBase. 732 typename ArgA, 733 typename ArgB, 734 typename ArgC> 735 Handle Schedule(SchedulePriority priority, 736 BackendFunc func, // Function to call on the HistoryBackend. 737 CancelableRequestConsumerBase* consumer, 738 RequestType* request, 739 const ArgA& a, 740 const ArgB& b, 741 const ArgC& c) { 742 DCHECK(thread_) << "History service being called after cleanup"; 743 LoadBackendIfNecessary(); 744 if (consumer) 745 AddRequest(request, consumer); 746 ScheduleTask(priority, 747 NewRunnableMethod(history_backend_.get(), func, 748 scoped_refptr<RequestType>(request), 749 a, b, c)); 750 return request->handle(); 751 } 752 753 // ScheduleAndForget --------------------------------------------------------- 754 // 755 // Functions for scheduling operations on the history thread that do not need 756 // any callbacks and are not cancelable. 757 758 template<typename BackendFunc> 759 void ScheduleAndForget(SchedulePriority priority, 760 BackendFunc func) { // Function to call on backend. 761 DCHECK(thread_) << "History service being called after cleanup"; 762 LoadBackendIfNecessary(); 763 ScheduleTask(priority, NewRunnableMethod(history_backend_.get(), func)); 764 } 765 766 template<typename BackendFunc, typename ArgA> 767 void ScheduleAndForget(SchedulePriority priority, 768 BackendFunc func, // Function to call on backend. 769 const ArgA& a) { 770 DCHECK(thread_) << "History service being called after cleanup"; 771 LoadBackendIfNecessary(); 772 ScheduleTask(priority, NewRunnableMethod(history_backend_.get(), func, a)); 773 } 774 775 template<typename BackendFunc, typename ArgA, typename ArgB> 776 void ScheduleAndForget(SchedulePriority priority, 777 BackendFunc func, // Function to call on backend. 778 const ArgA& a, 779 const ArgB& b) { 780 DCHECK(thread_) << "History service being called after cleanup"; 781 LoadBackendIfNecessary(); 782 ScheduleTask(priority, NewRunnableMethod(history_backend_.get(), func, 783 a, b)); 784 } 785 786 template<typename BackendFunc, typename ArgA, typename ArgB, typename ArgC> 787 void ScheduleAndForget(SchedulePriority priority, 788 BackendFunc func, // Function to call on backend. 789 const ArgA& a, 790 const ArgB& b, 791 const ArgC& c) { 792 DCHECK(thread_) << "History service being called after cleanup"; 793 LoadBackendIfNecessary(); 794 ScheduleTask(priority, NewRunnableMethod(history_backend_.get(), func, 795 a, b, c)); 796 } 797 798 template<typename BackendFunc, 799 typename ArgA, 800 typename ArgB, 801 typename ArgC, 802 typename ArgD> 803 void ScheduleAndForget(SchedulePriority priority, 804 BackendFunc func, // Function to call on backend. 805 const ArgA& a, 806 const ArgB& b, 807 const ArgC& c, 808 const ArgD& d) { 809 DCHECK(thread_) << "History service being called after cleanup"; 810 LoadBackendIfNecessary(); 811 ScheduleTask(priority, NewRunnableMethod(history_backend_.get(), func, 812 a, b, c, d)); 813 } 814 815 NotificationRegistrar registrar_; 816 817 // Some void primitives require some internal processing in the main thread 818 // when done. We use this internal consumer for this purpose. 819 CancelableRequestConsumer internal_consumer_; 820 821 // The thread used by the history service to run complicated operations 822 base::Thread* thread_; 823 824 // This class has most of the implementation and runs on the 'thread_'. 825 // You MUST communicate with this class ONLY through the thread_'s 826 // message_loop(). 827 // 828 // This pointer will be NULL once Cleanup() has been called, meaning no 829 // more calls should be made to the history thread. 830 scoped_refptr<history::HistoryBackend> history_backend_; 831 832 // A cache of the user-typed URLs kept in memory that is used by the 833 // autocomplete system. This will be NULL until the database has been created 834 // on the background thread. 835 scoped_ptr<history::InMemoryHistoryBackend> in_memory_backend_; 836 837 // The profile, may be null when testing. 838 Profile* profile_; 839 840 // Has the backend finished loading? The backend is loaded once Init has 841 // completed. 842 bool backend_loaded_; 843 844 // Cached values from Init(), used whenever we need to reload the backend. 845 FilePath history_dir_; 846 BookmarkService* bookmark_service_; 847 bool no_db_; 848 849 DISALLOW_COPY_AND_ASSIGN(HistoryService); 850}; 851 852#endif // CHROME_BROWSER_HISTORY_HISTORY_H_ 853