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