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