history_service.cc revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
1// Copyright (c) 2012 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5// The history system runs on a background thread so that potentially slow 6// database operations don't delay the browser. This backend processing is 7// represented by HistoryBackend. The HistoryService's job is to dispatch to 8// that thread. 9// 10// Main thread History thread 11// ----------- -------------- 12// HistoryService <----------------> HistoryBackend 13// -> HistoryDatabase 14// -> SQLite connection to History 15// -> ArchivedDatabase 16// -> SQLite connection to Archived History 17// -> ThumbnailDatabase 18// -> SQLite connection to Thumbnails 19// (and favicons) 20 21#include "chrome/browser/history/history_service.h" 22 23#include "base/bind_helpers.h" 24#include "base/callback.h" 25#include "base/command_line.h" 26#include "base/compiler_specific.h" 27#include "base/location.h" 28#include "base/memory/ref_counted.h" 29#include "base/message_loop/message_loop.h" 30#include "base/path_service.h" 31#include "base/prefs/pref_service.h" 32#include "base/thread_task_runner_handle.h" 33#include "base/threading/thread.h" 34#include "base/time/time.h" 35#include "chrome/browser/autocomplete/history_url_provider.h" 36#include "chrome/browser/bookmarks/bookmark_model.h" 37#include "chrome/browser/bookmarks/bookmark_model_factory.h" 38#include "chrome/browser/browser_process.h" 39#include "chrome/browser/chrome_notification_types.h" 40#include "chrome/browser/history/download_row.h" 41#include "chrome/browser/history/history_backend.h" 42#include "chrome/browser/history/history_notifications.h" 43#include "chrome/browser/history/history_types.h" 44#include "chrome/browser/history/in_memory_database.h" 45#include "chrome/browser/history/in_memory_history_backend.h" 46#include "chrome/browser/history/in_memory_url_index.h" 47#include "chrome/browser/history/top_sites.h" 48#include "chrome/browser/history/visit_database.h" 49#include "chrome/browser/history/visit_filter.h" 50#include "chrome/browser/history/web_history_service.h" 51#include "chrome/browser/history/web_history_service_factory.h" 52#include "chrome/browser/profiles/profile.h" 53#include "chrome/browser/ui/profile_error_dialog.h" 54#include "chrome/common/chrome_constants.h" 55#include "chrome/common/chrome_switches.h" 56#include "chrome/common/importer/imported_favicon_usage.h" 57#include "chrome/common/pref_names.h" 58#include "chrome/common/thumbnail_score.h" 59#include "chrome/common/url_constants.h" 60#include "components/visitedlink/browser/visitedlink_master.h" 61#include "content/public/browser/browser_thread.h" 62#include "content/public/browser/download_item.h" 63#include "content/public/browser/notification_service.h" 64#include "grit/chromium_strings.h" 65#include "grit/generated_resources.h" 66#include "sync/api/sync_error_factory.h" 67#include "third_party/skia/include/core/SkBitmap.h" 68 69using base::Time; 70using history::HistoryBackend; 71 72namespace { 73 74static const char* kHistoryThreadName = "Chrome_HistoryThread"; 75 76template<typename PODType> void DerefPODType( 77 const base::Callback<void(PODType)>& callback, PODType* pod_value) { 78 callback.Run(*pod_value); 79} 80 81void RunWithFaviconResults( 82 const FaviconService::FaviconResultsCallback& callback, 83 std::vector<chrome::FaviconBitmapResult>* bitmap_results) { 84 callback.Run(*bitmap_results); 85} 86 87void RunWithFaviconResult( 88 const FaviconService::FaviconRawCallback& callback, 89 chrome::FaviconBitmapResult* bitmap_result) { 90 callback.Run(*bitmap_result); 91} 92 93// Extract history::URLRows into GURLs for VisitedLinkMaster. 94class URLIteratorFromURLRows 95 : public visitedlink::VisitedLinkMaster::URLIterator { 96 public: 97 explicit URLIteratorFromURLRows(const history::URLRows& url_rows) 98 : itr_(url_rows.begin()), 99 end_(url_rows.end()) { 100 } 101 102 virtual const GURL& NextURL() OVERRIDE { 103 return (itr_++)->url(); 104 } 105 106 virtual bool HasNextURL() const OVERRIDE { 107 return itr_ != end_; 108 } 109 110 private: 111 history::URLRows::const_iterator itr_; 112 history::URLRows::const_iterator end_; 113 114 DISALLOW_COPY_AND_ASSIGN(URLIteratorFromURLRows); 115}; 116 117// Callback from WebHistoryService::ExpireWebHistory(). 118void ExpireWebHistoryComplete( 119 history::WebHistoryService::Request* request, 120 bool success) { 121 // Ignore the result and delete the request. 122 delete request; 123} 124 125} // namespace 126 127// Sends messages from the backend to us on the main thread. This must be a 128// separate class from the history service so that it can hold a reference to 129// the history service (otherwise we would have to manually AddRef and 130// Release when the Backend has a reference to us). 131class HistoryService::BackendDelegate : public HistoryBackend::Delegate { 132 public: 133 BackendDelegate( 134 const base::WeakPtr<HistoryService>& history_service, 135 const scoped_refptr<base::SequencedTaskRunner>& service_task_runner, 136 Profile* profile) 137 : history_service_(history_service), 138 service_task_runner_(service_task_runner), 139 profile_(profile) { 140 } 141 142 virtual void NotifyProfileError(int backend_id, 143 sql::InitStatus init_status) OVERRIDE { 144 // Send to the history service on the main thread. 145 service_task_runner_->PostTask( 146 FROM_HERE, 147 base::Bind(&HistoryService::NotifyProfileError, history_service_, 148 backend_id, init_status)); 149 } 150 151 virtual void SetInMemoryBackend(int backend_id, 152 history::InMemoryHistoryBackend* backend) OVERRIDE { 153 // Send the backend to the history service on the main thread. 154 scoped_ptr<history::InMemoryHistoryBackend> in_memory_backend(backend); 155 service_task_runner_->PostTask( 156 FROM_HERE, 157 base::Bind(&HistoryService::SetInMemoryBackend, history_service_, 158 backend_id, base::Passed(&in_memory_backend))); 159 } 160 161 virtual void BroadcastNotifications( 162 int type, 163 history::HistoryDetails* details) OVERRIDE { 164 // Send the notification on the history thread. 165 if (content::NotificationService::current()) { 166 content::Details<history::HistoryDetails> det(details); 167 content::NotificationService::current()->Notify( 168 type, content::Source<Profile>(profile_), det); 169 } 170 // Send the notification to the history service on the main thread. 171 service_task_runner_->PostTask( 172 FROM_HERE, 173 base::Bind(&HistoryService::BroadcastNotificationsHelper, 174 history_service_, type, base::Owned(details))); 175 } 176 177 virtual void DBLoaded(int backend_id) OVERRIDE { 178 service_task_runner_->PostTask( 179 FROM_HERE, 180 base::Bind(&HistoryService::OnDBLoaded, history_service_, 181 backend_id)); 182 } 183 184 virtual void NotifyVisitDBObserversOnAddVisit( 185 const history::BriefVisitInfo& info) OVERRIDE { 186 service_task_runner_->PostTask( 187 FROM_HERE, 188 base::Bind(&HistoryService::NotifyVisitDBObserversOnAddVisit, 189 history_service_, info)); 190 } 191 192 private: 193 const base::WeakPtr<HistoryService> history_service_; 194 const scoped_refptr<base::SequencedTaskRunner> service_task_runner_; 195 Profile* const profile_; 196}; 197 198// The history thread is intentionally not a BrowserThread because the 199// sync integration unit tests depend on being able to create more than one 200// history thread. 201HistoryService::HistoryService() 202 : weak_ptr_factory_(this), 203 thread_(new base::Thread(kHistoryThreadName)), 204 profile_(NULL), 205 backend_loaded_(false), 206 current_backend_id_(-1), 207 bookmark_service_(NULL), 208 no_db_(false) { 209} 210 211HistoryService::HistoryService(Profile* profile) 212 : weak_ptr_factory_(this), 213 thread_(new base::Thread(kHistoryThreadName)), 214 profile_(profile), 215 visitedlink_master_(new visitedlink::VisitedLinkMaster( 216 profile, this, true)), 217 backend_loaded_(false), 218 current_backend_id_(-1), 219 bookmark_service_(NULL), 220 no_db_(false) { 221 DCHECK(profile_); 222 registrar_.Add(this, chrome::NOTIFICATION_HISTORY_URLS_DELETED, 223 content::Source<Profile>(profile_)); 224 registrar_.Add(this, chrome::NOTIFICATION_TEMPLATE_URL_REMOVED, 225 content::Source<Profile>(profile_)); 226} 227 228HistoryService::~HistoryService() { 229 DCHECK(thread_checker_.CalledOnValidThread()); 230 // Shutdown the backend. This does nothing if Cleanup was already invoked. 231 Cleanup(); 232} 233 234bool HistoryService::BackendLoaded() { 235 DCHECK(thread_checker_.CalledOnValidThread()); 236 // NOTE: We start the backend loading even though it completes asynchronously 237 // and thus won't affect the return value of this function. This is because 238 // callers of this assume that if the backend isn't yet loaded it will be 239 // soon, so they will either listen for notifications or just retry this call 240 // later. If we've purged the backend, we haven't necessarily restarted it 241 // loading by now, so we need to trigger the load in order to maintain that 242 // expectation. 243 LoadBackendIfNecessary(); 244 return backend_loaded_; 245} 246 247void HistoryService::UnloadBackend() { 248 DCHECK(thread_checker_.CalledOnValidThread()); 249 if (!history_backend_.get()) 250 return; // Already unloaded. 251 252 // Get rid of the in-memory backend. 253 in_memory_backend_.reset(); 254 255 // Give the InMemoryURLIndex a chance to shutdown. 256 if (in_memory_url_index_) 257 in_memory_url_index_->ShutDown(); 258 259 // The backend's destructor must run on the history thread since it is not 260 // threadsafe. So this thread must not be the last thread holding a reference 261 // to the backend, or a crash could happen. 262 // 263 // We have a reference to the history backend. There is also an extra 264 // reference held by our delegate installed in the backend, which 265 // HistoryBackend::Closing will release. This means if we scheduled a call 266 // to HistoryBackend::Closing and *then* released our backend reference, there 267 // will be a race between us and the backend's Closing function to see who is 268 // the last holder of a reference. If the backend thread's Closing manages to 269 // run before we release our backend refptr, the last reference will be held 270 // by this thread and the destructor will be called from here. 271 // 272 // Therefore, we create a closure to run the Closing operation first. This 273 // holds a reference to the backend. Then we release our reference, then we 274 // schedule the task to run. After the task runs, it will delete its reference 275 // from the history thread, ensuring everything works properly. 276 // 277 // TODO(ajwong): Cleanup HistoryBackend lifetime issues. 278 // See http://crbug.com/99767. 279 history_backend_->AddRef(); 280 base::Closure closing_task = 281 base::Bind(&HistoryBackend::Closing, history_backend_.get()); 282 ScheduleTask(PRIORITY_NORMAL, closing_task); 283 closing_task.Reset(); 284 HistoryBackend* raw_ptr = history_backend_.get(); 285 history_backend_ = NULL; 286 thread_->message_loop()->ReleaseSoon(FROM_HERE, raw_ptr); 287} 288 289void HistoryService::Cleanup() { 290 DCHECK(thread_checker_.CalledOnValidThread()); 291 if (!thread_) { 292 // We've already cleaned up. 293 return; 294 } 295 296 weak_ptr_factory_.InvalidateWeakPtrs(); 297 298 // Unload the backend. 299 UnloadBackend(); 300 301 // Delete the thread, which joins with the background thread. We defensively 302 // NULL the pointer before deleting it in case somebody tries to use it 303 // during shutdown, but this shouldn't happen. 304 base::Thread* thread = thread_; 305 thread_ = NULL; 306 delete thread; 307} 308 309void HistoryService::NotifyRenderProcessHostDestruction(const void* host) { 310 DCHECK(thread_checker_.CalledOnValidThread()); 311 ScheduleAndForget(PRIORITY_NORMAL, 312 &HistoryBackend::NotifyRenderProcessHostDestruction, host); 313} 314 315history::URLDatabase* HistoryService::InMemoryDatabase() { 316 DCHECK(thread_checker_.CalledOnValidThread()); 317 // NOTE: See comments in BackendLoaded() as to why we call 318 // LoadBackendIfNecessary() here even though it won't affect the return value 319 // for this call. 320 LoadBackendIfNecessary(); 321 if (in_memory_backend_) 322 return in_memory_backend_->db(); 323 return NULL; 324} 325 326bool HistoryService::GetTypedCountForURL(const GURL& url, int* typed_count) { 327 DCHECK(thread_checker_.CalledOnValidThread()); 328 history::URLRow url_row; 329 if (!GetRowForURL(url, &url_row)) 330 return false; 331 *typed_count = url_row.typed_count(); 332 return true; 333} 334 335bool HistoryService::GetLastVisitTimeForURL(const GURL& url, 336 base::Time* last_visit) { 337 DCHECK(thread_checker_.CalledOnValidThread()); 338 history::URLRow url_row; 339 if (!GetRowForURL(url, &url_row)) 340 return false; 341 *last_visit = url_row.last_visit(); 342 return true; 343} 344 345bool HistoryService::GetVisitCountForURL(const GURL& url, int* visit_count) { 346 DCHECK(thread_checker_.CalledOnValidThread()); 347 history::URLRow url_row; 348 if (!GetRowForURL(url, &url_row)) 349 return false; 350 *visit_count = url_row.visit_count(); 351 return true; 352} 353 354history::TypedUrlSyncableService* HistoryService::GetTypedUrlSyncableService() 355 const { 356 return history_backend_->GetTypedUrlSyncableService(); 357} 358 359void HistoryService::Shutdown() { 360 DCHECK(thread_checker_.CalledOnValidThread()); 361 // It's possible that bookmarks haven't loaded and history is waiting for 362 // bookmarks to complete loading. In such a situation history can't shutdown 363 // (meaning if we invoked history_service_->Cleanup now, we would 364 // deadlock). To break the deadlock we tell BookmarkModel it's about to be 365 // deleted so that it can release the signal history is waiting on, allowing 366 // history to shutdown (history_service_->Cleanup to complete). In such a 367 // scenario history sees an incorrect view of bookmarks, but it's better 368 // than a deadlock. 369 BookmarkModel* bookmark_model = static_cast<BookmarkModel*>( 370 BookmarkModelFactory::GetForProfileIfExists(profile_)); 371 if (bookmark_model) 372 bookmark_model->Shutdown(); 373 374 Cleanup(); 375} 376 377void HistoryService::SetKeywordSearchTermsForURL(const GURL& url, 378 TemplateURLID keyword_id, 379 const base::string16& term) { 380 DCHECK(thread_checker_.CalledOnValidThread()); 381 ScheduleAndForget(PRIORITY_UI, 382 &HistoryBackend::SetKeywordSearchTermsForURL, 383 url, keyword_id, term); 384} 385 386void HistoryService::DeleteAllSearchTermsForKeyword( 387 TemplateURLID keyword_id) { 388 DCHECK(thread_checker_.CalledOnValidThread()); 389 ScheduleAndForget(PRIORITY_UI, 390 &HistoryBackend::DeleteAllSearchTermsForKeyword, 391 keyword_id); 392} 393 394HistoryService::Handle HistoryService::GetMostRecentKeywordSearchTerms( 395 TemplateURLID keyword_id, 396 const base::string16& prefix, 397 int max_count, 398 CancelableRequestConsumerBase* consumer, 399 const GetMostRecentKeywordSearchTermsCallback& callback) { 400 DCHECK(thread_checker_.CalledOnValidThread()); 401 return Schedule(PRIORITY_UI, &HistoryBackend::GetMostRecentKeywordSearchTerms, 402 consumer, 403 new history::GetMostRecentKeywordSearchTermsRequest(callback), 404 keyword_id, prefix, max_count); 405} 406 407void HistoryService::DeleteKeywordSearchTermForURL(const GURL& url) { 408 DCHECK(thread_checker_.CalledOnValidThread()); 409 ScheduleAndForget(PRIORITY_UI, &HistoryBackend::DeleteKeywordSearchTermForURL, 410 url); 411} 412 413void HistoryService::DeleteMatchingURLsForKeyword(TemplateURLID keyword_id, 414 const base::string16& term) { 415 DCHECK(thread_checker_.CalledOnValidThread()); 416 ScheduleAndForget(PRIORITY_UI, &HistoryBackend::DeleteMatchingURLsForKeyword, 417 keyword_id, term); 418} 419 420void HistoryService::URLsNoLongerBookmarked(const std::set<GURL>& urls) { 421 DCHECK(thread_checker_.CalledOnValidThread()); 422 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::URLsNoLongerBookmarked, 423 urls); 424} 425 426void HistoryService::ScheduleDBTask(history::HistoryDBTask* task, 427 CancelableRequestConsumerBase* consumer) { 428 DCHECK(thread_checker_.CalledOnValidThread()); 429 history::HistoryDBTaskRequest* request = new history::HistoryDBTaskRequest( 430 base::Bind(&history::HistoryDBTask::DoneRunOnMainThread, task)); 431 request->value = task; // The value is the task to execute. 432 Schedule(PRIORITY_UI, &HistoryBackend::ProcessDBTask, consumer, request); 433} 434 435HistoryService::Handle HistoryService::QuerySegmentUsageSince( 436 CancelableRequestConsumerBase* consumer, 437 const Time from_time, 438 int max_result_count, 439 const SegmentQueryCallback& callback) { 440 DCHECK(thread_checker_.CalledOnValidThread()); 441 return Schedule(PRIORITY_UI, &HistoryBackend::QuerySegmentUsage, 442 consumer, new history::QuerySegmentUsageRequest(callback), 443 from_time, max_result_count); 444} 445 446void HistoryService::FlushForTest(const base::Closure& flushed) { 447 thread_->message_loop_proxy()->PostTaskAndReply( 448 FROM_HERE, base::Bind(&base::DoNothing), flushed); 449} 450 451void HistoryService::SetOnBackendDestroyTask(const base::Closure& task) { 452 DCHECK(thread_checker_.CalledOnValidThread()); 453 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::SetOnBackendDestroyTask, 454 base::MessageLoop::current(), task); 455} 456 457void HistoryService::AddPage(const GURL& url, 458 Time time, 459 const void* id_scope, 460 int32 page_id, 461 const GURL& referrer, 462 const history::RedirectList& redirects, 463 content::PageTransition transition, 464 history::VisitSource visit_source, 465 bool did_replace_entry) { 466 DCHECK(thread_checker_.CalledOnValidThread()); 467 AddPage( 468 history::HistoryAddPageArgs(url, time, id_scope, page_id, referrer, 469 redirects, transition, visit_source, 470 did_replace_entry)); 471} 472 473void HistoryService::AddPage(const GURL& url, 474 base::Time time, 475 history::VisitSource visit_source) { 476 DCHECK(thread_checker_.CalledOnValidThread()); 477 AddPage( 478 history::HistoryAddPageArgs(url, time, NULL, 0, GURL(), 479 history::RedirectList(), 480 content::PAGE_TRANSITION_LINK, 481 visit_source, false)); 482} 483 484void HistoryService::AddPage(const history::HistoryAddPageArgs& add_page_args) { 485 DCHECK(thread_checker_.CalledOnValidThread()); 486 DCHECK(thread_) << "History service being called after cleanup"; 487 488 // Filter out unwanted URLs. We don't add auto-subframe URLs. They are a 489 // large part of history (think iframes for ads) and we never display them in 490 // history UI. We will still add manual subframes, which are ones the user 491 // has clicked on to get. 492 if (!CanAddURL(add_page_args.url)) 493 return; 494 495 // Add link & all redirects to visited link list. 496 if (visitedlink_master_) { 497 visitedlink_master_->AddURL(add_page_args.url); 498 499 if (!add_page_args.redirects.empty()) { 500 // We should not be asked to add a page in the middle of a redirect chain. 501 DCHECK_EQ(add_page_args.url, 502 add_page_args.redirects[add_page_args.redirects.size() - 1]); 503 504 // We need the !redirects.empty() condition above since size_t is unsigned 505 // and will wrap around when we subtract one from a 0 size. 506 for (size_t i = 0; i < add_page_args.redirects.size() - 1; i++) 507 visitedlink_master_->AddURL(add_page_args.redirects[i]); 508 } 509 } 510 511 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::AddPage, add_page_args); 512} 513 514void HistoryService::AddPageNoVisitForBookmark(const GURL& url, 515 const base::string16& title) { 516 DCHECK(thread_checker_.CalledOnValidThread()); 517 if (!CanAddURL(url)) 518 return; 519 520 ScheduleAndForget(PRIORITY_NORMAL, 521 &HistoryBackend::AddPageNoVisitForBookmark, url, title); 522} 523 524void HistoryService::SetPageTitle(const GURL& url, 525 const base::string16& title) { 526 DCHECK(thread_checker_.CalledOnValidThread()); 527 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::SetPageTitle, url, title); 528} 529 530void HistoryService::UpdateWithPageEndTime(const void* host, 531 int32 page_id, 532 const GURL& url, 533 Time end_ts) { 534 DCHECK(thread_checker_.CalledOnValidThread()); 535 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::UpdateWithPageEndTime, 536 host, page_id, url, end_ts); 537} 538 539void HistoryService::AddPageWithDetails(const GURL& url, 540 const base::string16& title, 541 int visit_count, 542 int typed_count, 543 Time last_visit, 544 bool hidden, 545 history::VisitSource visit_source) { 546 DCHECK(thread_checker_.CalledOnValidThread()); 547 // Filter out unwanted URLs. 548 if (!CanAddURL(url)) 549 return; 550 551 // Add to the visited links system. 552 if (visitedlink_master_) 553 visitedlink_master_->AddURL(url); 554 555 history::URLRow row(url); 556 row.set_title(title); 557 row.set_visit_count(visit_count); 558 row.set_typed_count(typed_count); 559 row.set_last_visit(last_visit); 560 row.set_hidden(hidden); 561 562 history::URLRows rows; 563 rows.push_back(row); 564 565 ScheduleAndForget(PRIORITY_NORMAL, 566 &HistoryBackend::AddPagesWithDetails, rows, visit_source); 567} 568 569void HistoryService::AddPagesWithDetails(const history::URLRows& info, 570 history::VisitSource visit_source) { 571 DCHECK(thread_checker_.CalledOnValidThread()); 572 // Add to the visited links system. 573 if (visitedlink_master_) { 574 std::vector<GURL> urls; 575 urls.reserve(info.size()); 576 for (history::URLRows::const_iterator i = info.begin(); i != info.end(); 577 ++i) 578 urls.push_back(i->url()); 579 580 visitedlink_master_->AddURLs(urls); 581 } 582 583 ScheduleAndForget(PRIORITY_NORMAL, 584 &HistoryBackend::AddPagesWithDetails, info, visit_source); 585} 586 587base::CancelableTaskTracker::TaskId HistoryService::GetFavicons( 588 const std::vector<GURL>& icon_urls, 589 int icon_types, 590 int desired_size_in_dip, 591 const std::vector<ui::ScaleFactor>& desired_scale_factors, 592 const FaviconService::FaviconResultsCallback& callback, 593 base::CancelableTaskTracker* tracker) { 594 DCHECK(thread_checker_.CalledOnValidThread()); 595 LoadBackendIfNecessary(); 596 597 std::vector<chrome::FaviconBitmapResult>* results = 598 new std::vector<chrome::FaviconBitmapResult>(); 599 return tracker->PostTaskAndReply( 600 thread_->message_loop_proxy().get(), 601 FROM_HERE, 602 base::Bind(&HistoryBackend::GetFavicons, 603 history_backend_.get(), 604 icon_urls, 605 icon_types, 606 desired_size_in_dip, 607 desired_scale_factors, 608 results), 609 base::Bind(&RunWithFaviconResults, callback, base::Owned(results))); 610} 611 612base::CancelableTaskTracker::TaskId HistoryService::GetFaviconsForURL( 613 const GURL& page_url, 614 int icon_types, 615 int desired_size_in_dip, 616 const std::vector<ui::ScaleFactor>& desired_scale_factors, 617 const FaviconService::FaviconResultsCallback& callback, 618 base::CancelableTaskTracker* tracker) { 619 DCHECK(thread_checker_.CalledOnValidThread()); 620 LoadBackendIfNecessary(); 621 622 std::vector<chrome::FaviconBitmapResult>* results = 623 new std::vector<chrome::FaviconBitmapResult>(); 624 return tracker->PostTaskAndReply( 625 thread_->message_loop_proxy().get(), 626 FROM_HERE, 627 base::Bind(&HistoryBackend::GetFaviconsForURL, 628 history_backend_.get(), 629 page_url, 630 icon_types, 631 desired_size_in_dip, 632 desired_scale_factors, 633 results), 634 base::Bind(&RunWithFaviconResults, callback, base::Owned(results))); 635} 636 637base::CancelableTaskTracker::TaskId HistoryService::GetLargestFaviconForURL( 638 const GURL& page_url, 639 const std::vector<int>& icon_types, 640 int minimum_size_in_pixels, 641 const FaviconService::FaviconRawCallback& callback, 642 base::CancelableTaskTracker* tracker) { 643 DCHECK(thread_checker_.CalledOnValidThread()); 644 LoadBackendIfNecessary(); 645 646 chrome::FaviconBitmapResult* result = new chrome::FaviconBitmapResult(); 647 return tracker->PostTaskAndReply( 648 thread_->message_loop_proxy().get(), 649 FROM_HERE, 650 base::Bind(&HistoryBackend::GetLargestFaviconForURL, 651 history_backend_.get(), 652 page_url, 653 icon_types, 654 minimum_size_in_pixels, 655 result), 656 base::Bind(&RunWithFaviconResult, callback, base::Owned(result))); 657} 658 659base::CancelableTaskTracker::TaskId HistoryService::GetFaviconForID( 660 chrome::FaviconID favicon_id, 661 int desired_size_in_dip, 662 ui::ScaleFactor desired_scale_factor, 663 const FaviconService::FaviconResultsCallback& callback, 664 base::CancelableTaskTracker* tracker) { 665 DCHECK(thread_checker_.CalledOnValidThread()); 666 LoadBackendIfNecessary(); 667 668 std::vector<chrome::FaviconBitmapResult>* results = 669 new std::vector<chrome::FaviconBitmapResult>(); 670 return tracker->PostTaskAndReply( 671 thread_->message_loop_proxy().get(), 672 FROM_HERE, 673 base::Bind(&HistoryBackend::GetFaviconForID, 674 history_backend_.get(), 675 favicon_id, 676 desired_size_in_dip, 677 desired_scale_factor, 678 results), 679 base::Bind(&RunWithFaviconResults, callback, base::Owned(results))); 680} 681 682base::CancelableTaskTracker::TaskId 683HistoryService::UpdateFaviconMappingsAndFetch( 684 const GURL& page_url, 685 const std::vector<GURL>& icon_urls, 686 int icon_types, 687 int desired_size_in_dip, 688 const std::vector<ui::ScaleFactor>& desired_scale_factors, 689 const FaviconService::FaviconResultsCallback& callback, 690 base::CancelableTaskTracker* tracker) { 691 DCHECK(thread_checker_.CalledOnValidThread()); 692 LoadBackendIfNecessary(); 693 694 std::vector<chrome::FaviconBitmapResult>* results = 695 new std::vector<chrome::FaviconBitmapResult>(); 696 return tracker->PostTaskAndReply( 697 thread_->message_loop_proxy().get(), 698 FROM_HERE, 699 base::Bind(&HistoryBackend::UpdateFaviconMappingsAndFetch, 700 history_backend_.get(), 701 page_url, 702 icon_urls, 703 icon_types, 704 desired_size_in_dip, 705 desired_scale_factors, 706 results), 707 base::Bind(&RunWithFaviconResults, callback, base::Owned(results))); 708} 709 710void HistoryService::MergeFavicon( 711 const GURL& page_url, 712 const GURL& icon_url, 713 chrome::IconType icon_type, 714 scoped_refptr<base::RefCountedMemory> bitmap_data, 715 const gfx::Size& pixel_size) { 716 DCHECK(thread_checker_.CalledOnValidThread()); 717 if (!CanAddURL(page_url)) 718 return; 719 720 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::MergeFavicon, page_url, 721 icon_url, icon_type, bitmap_data, pixel_size); 722} 723 724void HistoryService::SetFavicons( 725 const GURL& page_url, 726 chrome::IconType icon_type, 727 const std::vector<chrome::FaviconBitmapData>& favicon_bitmap_data) { 728 DCHECK(thread_checker_.CalledOnValidThread()); 729 if (!CanAddURL(page_url)) 730 return; 731 732 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::SetFavicons, page_url, 733 icon_type, favicon_bitmap_data); 734} 735 736void HistoryService::SetFaviconsOutOfDateForPage(const GURL& page_url) { 737 DCHECK(thread_checker_.CalledOnValidThread()); 738 ScheduleAndForget(PRIORITY_NORMAL, 739 &HistoryBackend::SetFaviconsOutOfDateForPage, page_url); 740} 741 742void HistoryService::CloneFavicons(const GURL& old_page_url, 743 const GURL& new_page_url) { 744 DCHECK(thread_checker_.CalledOnValidThread()); 745 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::CloneFavicons, 746 old_page_url, new_page_url); 747} 748 749void HistoryService::SetImportedFavicons( 750 const std::vector<ImportedFaviconUsage>& favicon_usage) { 751 DCHECK(thread_checker_.CalledOnValidThread()); 752 ScheduleAndForget(PRIORITY_NORMAL, 753 &HistoryBackend::SetImportedFavicons, favicon_usage); 754} 755 756HistoryService::Handle HistoryService::QueryURL( 757 const GURL& url, 758 bool want_visits, 759 CancelableRequestConsumerBase* consumer, 760 const QueryURLCallback& callback) { 761 DCHECK(thread_checker_.CalledOnValidThread()); 762 return Schedule(PRIORITY_UI, &HistoryBackend::QueryURL, consumer, 763 new history::QueryURLRequest(callback), url, want_visits); 764} 765 766// Downloads ------------------------------------------------------------------- 767 768// Handle creation of a download by creating an entry in the history service's 769// 'downloads' table. 770void HistoryService::CreateDownload( 771 const history::DownloadRow& create_info, 772 const HistoryService::DownloadCreateCallback& callback) { 773 DCHECK(thread_) << "History service being called after cleanup"; 774 DCHECK(thread_checker_.CalledOnValidThread()); 775 LoadBackendIfNecessary(); 776 bool* success = new bool(false); 777 thread_->message_loop_proxy()->PostTaskAndReply( 778 FROM_HERE, 779 base::Bind(&HistoryBackend::CreateDownload, 780 history_backend_.get(), 781 create_info, 782 success), 783 base::Bind(&DerefPODType<bool>, callback, base::Owned(success))); 784} 785 786void HistoryService::GetNextDownloadId( 787 const content::DownloadIdCallback& callback) { 788 DCHECK(thread_) << "History service being called after cleanup"; 789 DCHECK(thread_checker_.CalledOnValidThread()); 790 LoadBackendIfNecessary(); 791 uint32* next_id = new uint32(content::DownloadItem::kInvalidId); 792 thread_->message_loop_proxy()->PostTaskAndReply( 793 FROM_HERE, 794 base::Bind(&HistoryBackend::GetNextDownloadId, 795 history_backend_.get(), 796 next_id), 797 base::Bind(&DerefPODType<uint32>, callback, base::Owned(next_id))); 798} 799 800// Handle queries for a list of all downloads in the history database's 801// 'downloads' table. 802void HistoryService::QueryDownloads( 803 const DownloadQueryCallback& callback) { 804 DCHECK(thread_) << "History service being called after cleanup"; 805 DCHECK(thread_checker_.CalledOnValidThread()); 806 LoadBackendIfNecessary(); 807 std::vector<history::DownloadRow>* rows = 808 new std::vector<history::DownloadRow>(); 809 scoped_ptr<std::vector<history::DownloadRow> > scoped_rows(rows); 810 // Beware! The first Bind() does not simply |scoped_rows.get()| because 811 // base::Passed(&scoped_rows) nullifies |scoped_rows|, and compilers do not 812 // guarantee that the first Bind's arguments are evaluated before the second 813 // Bind's arguments. 814 thread_->message_loop_proxy()->PostTaskAndReply( 815 FROM_HERE, 816 base::Bind(&HistoryBackend::QueryDownloads, history_backend_.get(), rows), 817 base::Bind(callback, base::Passed(&scoped_rows))); 818} 819 820// Handle updates for a particular download. This is a 'fire and forget' 821// operation, so we don't need to be called back. 822void HistoryService::UpdateDownload(const history::DownloadRow& data) { 823 DCHECK(thread_checker_.CalledOnValidThread()); 824 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::UpdateDownload, data); 825} 826 827void HistoryService::RemoveDownloads(const std::set<uint32>& ids) { 828 DCHECK(thread_checker_.CalledOnValidThread()); 829 ScheduleAndForget(PRIORITY_NORMAL, 830 &HistoryBackend::RemoveDownloads, ids); 831} 832 833HistoryService::Handle HistoryService::QueryHistory( 834 const base::string16& text_query, 835 const history::QueryOptions& options, 836 CancelableRequestConsumerBase* consumer, 837 const QueryHistoryCallback& callback) { 838 DCHECK(thread_checker_.CalledOnValidThread()); 839 return Schedule(PRIORITY_UI, &HistoryBackend::QueryHistory, consumer, 840 new history::QueryHistoryRequest(callback), 841 text_query, options); 842} 843 844HistoryService::Handle HistoryService::QueryRedirectsFrom( 845 const GURL& from_url, 846 CancelableRequestConsumerBase* consumer, 847 const QueryRedirectsCallback& callback) { 848 DCHECK(thread_checker_.CalledOnValidThread()); 849 return Schedule(PRIORITY_UI, &HistoryBackend::QueryRedirectsFrom, consumer, 850 new history::QueryRedirectsRequest(callback), from_url); 851} 852 853HistoryService::Handle HistoryService::QueryRedirectsTo( 854 const GURL& to_url, 855 CancelableRequestConsumerBase* consumer, 856 const QueryRedirectsCallback& callback) { 857 DCHECK(thread_checker_.CalledOnValidThread()); 858 return Schedule(PRIORITY_NORMAL, &HistoryBackend::QueryRedirectsTo, consumer, 859 new history::QueryRedirectsRequest(callback), to_url); 860} 861 862HistoryService::Handle HistoryService::GetVisibleVisitCountToHost( 863 const GURL& url, 864 CancelableRequestConsumerBase* consumer, 865 const GetVisibleVisitCountToHostCallback& callback) { 866 DCHECK(thread_checker_.CalledOnValidThread()); 867 return Schedule(PRIORITY_UI, &HistoryBackend::GetVisibleVisitCountToHost, 868 consumer, new history::GetVisibleVisitCountToHostRequest(callback), url); 869} 870 871HistoryService::Handle HistoryService::QueryTopURLsAndRedirects( 872 int result_count, 873 CancelableRequestConsumerBase* consumer, 874 const QueryTopURLsAndRedirectsCallback& callback) { 875 DCHECK(thread_checker_.CalledOnValidThread()); 876 return Schedule(PRIORITY_NORMAL, &HistoryBackend::QueryTopURLsAndRedirects, 877 consumer, new history::QueryTopURLsAndRedirectsRequest(callback), 878 result_count); 879} 880 881HistoryService::Handle HistoryService::QueryMostVisitedURLs( 882 int result_count, 883 int days_back, 884 CancelableRequestConsumerBase* consumer, 885 const QueryMostVisitedURLsCallback& callback) { 886 DCHECK(thread_checker_.CalledOnValidThread()); 887 return Schedule(PRIORITY_NORMAL, &HistoryBackend::QueryMostVisitedURLs, 888 consumer, 889 new history::QueryMostVisitedURLsRequest(callback), 890 result_count, days_back); 891} 892 893HistoryService::Handle HistoryService::QueryFilteredURLs( 894 int result_count, 895 const history::VisitFilter& filter, 896 bool extended_info, 897 CancelableRequestConsumerBase* consumer, 898 const QueryFilteredURLsCallback& callback) { 899 DCHECK(thread_checker_.CalledOnValidThread()); 900 return Schedule(PRIORITY_NORMAL, 901 &HistoryBackend::QueryFilteredURLs, 902 consumer, 903 new history::QueryFilteredURLsRequest(callback), 904 result_count, filter, extended_info); 905} 906 907void HistoryService::Observe(int type, 908 const content::NotificationSource& source, 909 const content::NotificationDetails& details) { 910 DCHECK(thread_checker_.CalledOnValidThread()); 911 if (!thread_) 912 return; 913 914 switch (type) { 915 case chrome::NOTIFICATION_HISTORY_URLS_DELETED: { 916 // Update the visited link system for deleted URLs. We will update the 917 // visited link system for added URLs as soon as we get the add 918 // notification (we don't have to wait for the backend, which allows us to 919 // be faster to update the state). 920 // 921 // For deleted URLs, we don't typically know what will be deleted since 922 // delete notifications are by time. We would also like to be more 923 // respectful of privacy and never tell the user something is gone when it 924 // isn't. Therefore, we update the delete URLs after the fact. 925 if (visitedlink_master_) { 926 content::Details<history::URLsDeletedDetails> deleted_details(details); 927 928 if (deleted_details->all_history) { 929 visitedlink_master_->DeleteAllURLs(); 930 } else { 931 URLIteratorFromURLRows iterator(deleted_details->rows); 932 visitedlink_master_->DeleteURLs(&iterator); 933 } 934 } 935 break; 936 } 937 938 case chrome::NOTIFICATION_TEMPLATE_URL_REMOVED: 939 DeleteAllSearchTermsForKeyword( 940 *(content::Details<TemplateURLID>(details).ptr())); 941 break; 942 943 default: 944 NOTREACHED(); 945 } 946} 947 948void HistoryService::RebuildTable( 949 const scoped_refptr<URLEnumerator>& enumerator) { 950 DCHECK(thread_checker_.CalledOnValidThread()); 951 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::IterateURLs, enumerator); 952} 953 954bool HistoryService::Init(const base::FilePath& history_dir, 955 BookmarkService* bookmark_service, 956 bool no_db) { 957 DCHECK(thread_checker_.CalledOnValidThread()); 958 if (!thread_->Start()) { 959 Cleanup(); 960 return false; 961 } 962 963 history_dir_ = history_dir; 964 bookmark_service_ = bookmark_service; 965 no_db_ = no_db; 966 967 if (profile_) { 968 std::string languages = 969 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages); 970 in_memory_url_index_.reset( 971 new history::InMemoryURLIndex(profile_, history_dir_, languages)); 972 in_memory_url_index_->Init(); 973 } 974 975 // Create the history backend. 976 LoadBackendIfNecessary(); 977 978 if (visitedlink_master_) { 979 bool result = visitedlink_master_->Init(); 980 DCHECK(result); 981 } 982 983 return true; 984} 985 986void HistoryService::ScheduleAutocomplete(HistoryURLProvider* provider, 987 HistoryURLProviderParams* params) { 988 DCHECK(thread_checker_.CalledOnValidThread()); 989 ScheduleAndForget(PRIORITY_UI, &HistoryBackend::ScheduleAutocomplete, 990 scoped_refptr<HistoryURLProvider>(provider), params); 991} 992 993void HistoryService::ScheduleTask(SchedulePriority priority, 994 const base::Closure& task) { 995 DCHECK(thread_checker_.CalledOnValidThread()); 996 CHECK(thread_); 997 CHECK(thread_->message_loop()); 998 // TODO(brettw): Do prioritization. 999 thread_->message_loop()->PostTask(FROM_HERE, task); 1000} 1001 1002// static 1003bool HistoryService::CanAddURL(const GURL& url) { 1004 if (!url.is_valid()) 1005 return false; 1006 1007 // TODO: We should allow kChromeUIScheme URLs if they have been explicitly 1008 // typed. Right now, however, these are marked as typed even when triggered 1009 // by a shortcut or menu action. 1010 if (url.SchemeIs(content::kJavaScriptScheme) || 1011 url.SchemeIs(content::kChromeDevToolsScheme) || 1012 url.SchemeIs(content::kChromeUIScheme) || 1013 url.SchemeIs(content::kViewSourceScheme) || 1014 url.SchemeIs(chrome::kChromeNativeScheme) || 1015 url.SchemeIs(chrome::kChromeSearchScheme) || 1016 url.SchemeIs(chrome::kDomDistillerScheme)) 1017 return false; 1018 1019 // Allow all about: and chrome: URLs except about:blank, since the user may 1020 // like to see "chrome://memory/", etc. in their history and autocomplete. 1021 if (url == GURL(content::kAboutBlankURL)) 1022 return false; 1023 1024 return true; 1025} 1026 1027base::WeakPtr<HistoryService> HistoryService::AsWeakPtr() { 1028 DCHECK(thread_checker_.CalledOnValidThread()); 1029 return weak_ptr_factory_.GetWeakPtr(); 1030} 1031 1032syncer::SyncMergeResult HistoryService::MergeDataAndStartSyncing( 1033 syncer::ModelType type, 1034 const syncer::SyncDataList& initial_sync_data, 1035 scoped_ptr<syncer::SyncChangeProcessor> sync_processor, 1036 scoped_ptr<syncer::SyncErrorFactory> error_handler) { 1037 DCHECK(thread_checker_.CalledOnValidThread()); 1038 DCHECK_EQ(type, syncer::HISTORY_DELETE_DIRECTIVES); 1039 delete_directive_handler_.Start(this, initial_sync_data, 1040 sync_processor.Pass()); 1041 return syncer::SyncMergeResult(type); 1042} 1043 1044void HistoryService::StopSyncing(syncer::ModelType type) { 1045 DCHECK(thread_checker_.CalledOnValidThread()); 1046 DCHECK_EQ(type, syncer::HISTORY_DELETE_DIRECTIVES); 1047 delete_directive_handler_.Stop(); 1048} 1049 1050syncer::SyncDataList HistoryService::GetAllSyncData( 1051 syncer::ModelType type) const { 1052 DCHECK(thread_checker_.CalledOnValidThread()); 1053 DCHECK_EQ(type, syncer::HISTORY_DELETE_DIRECTIVES); 1054 // TODO(akalin): Keep track of existing delete directives. 1055 return syncer::SyncDataList(); 1056} 1057 1058syncer::SyncError HistoryService::ProcessSyncChanges( 1059 const tracked_objects::Location& from_here, 1060 const syncer::SyncChangeList& change_list) { 1061 delete_directive_handler_.ProcessSyncChanges(this, change_list); 1062 return syncer::SyncError(); 1063} 1064 1065syncer::SyncError HistoryService::ProcessLocalDeleteDirective( 1066 const sync_pb::HistoryDeleteDirectiveSpecifics& delete_directive) { 1067 DCHECK(thread_checker_.CalledOnValidThread()); 1068 return delete_directive_handler_.ProcessLocalDeleteDirective( 1069 delete_directive); 1070} 1071 1072void HistoryService::SetInMemoryBackend( 1073 int backend_id, scoped_ptr<history::InMemoryHistoryBackend> mem_backend) { 1074 DCHECK(thread_checker_.CalledOnValidThread()); 1075 if (!history_backend_.get() || current_backend_id_ != backend_id) { 1076 DVLOG(1) << "Message from obsolete backend"; 1077 // mem_backend is deleted. 1078 return; 1079 } 1080 DCHECK(!in_memory_backend_) << "Setting mem DB twice"; 1081 in_memory_backend_.reset(mem_backend.release()); 1082 1083 // The database requires additional initialization once we own it. 1084 in_memory_backend_->AttachToHistoryService(profile_); 1085} 1086 1087void HistoryService::NotifyProfileError(int backend_id, 1088 sql::InitStatus init_status) { 1089 DCHECK(thread_checker_.CalledOnValidThread()); 1090 if (!history_backend_.get() || current_backend_id_ != backend_id) { 1091 DVLOG(1) << "Message from obsolete backend"; 1092 return; 1093 } 1094 ShowProfileErrorDialog( 1095 PROFILE_ERROR_HISTORY, 1096 (init_status == sql::INIT_FAILURE) ? 1097 IDS_COULDNT_OPEN_PROFILE_ERROR : IDS_PROFILE_TOO_NEW_ERROR); 1098} 1099 1100void HistoryService::DeleteURL(const GURL& url) { 1101 DCHECK(thread_checker_.CalledOnValidThread()); 1102 // We will update the visited links when we observe the delete notifications. 1103 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::DeleteURL, url); 1104} 1105 1106void HistoryService::DeleteURLsForTest(const std::vector<GURL>& urls) { 1107 DCHECK(thread_checker_.CalledOnValidThread()); 1108 // We will update the visited links when we observe the delete 1109 // notifications. 1110 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::DeleteURLs, urls); 1111} 1112 1113void HistoryService::ExpireHistoryBetween( 1114 const std::set<GURL>& restrict_urls, 1115 Time begin_time, 1116 Time end_time, 1117 const base::Closure& callback, 1118 base::CancelableTaskTracker* tracker) { 1119 DCHECK(thread_); 1120 DCHECK(thread_checker_.CalledOnValidThread()); 1121 DCHECK(history_backend_.get()); 1122 tracker->PostTaskAndReply(thread_->message_loop_proxy().get(), 1123 FROM_HERE, 1124 base::Bind(&HistoryBackend::ExpireHistoryBetween, 1125 history_backend_, 1126 restrict_urls, 1127 begin_time, 1128 end_time), 1129 callback); 1130} 1131 1132void HistoryService::ExpireHistory( 1133 const std::vector<history::ExpireHistoryArgs>& expire_list, 1134 const base::Closure& callback, 1135 base::CancelableTaskTracker* tracker) { 1136 DCHECK(thread_); 1137 DCHECK(thread_checker_.CalledOnValidThread()); 1138 DCHECK(history_backend_.get()); 1139 tracker->PostTaskAndReply( 1140 thread_->message_loop_proxy().get(), 1141 FROM_HERE, 1142 base::Bind(&HistoryBackend::ExpireHistory, history_backend_, expire_list), 1143 callback); 1144} 1145 1146void HistoryService::ExpireLocalAndRemoteHistoryBetween( 1147 const std::set<GURL>& restrict_urls, 1148 Time begin_time, 1149 Time end_time, 1150 const base::Closure& callback, 1151 base::CancelableTaskTracker* tracker) { 1152 // TODO(dubroy): This should be factored out into a separate class that 1153 // dispatches deletions to the proper places. 1154 1155 history::WebHistoryService* web_history = 1156 WebHistoryServiceFactory::GetForProfile(profile_); 1157 if (web_history) { 1158 // TODO(dubroy): This API does not yet support deletion of specific URLs. 1159 DCHECK(restrict_urls.empty()); 1160 1161 delete_directive_handler_.CreateDeleteDirectives( 1162 std::set<int64>(), begin_time, end_time); 1163 1164 // Attempt online deletion from the history server, but ignore the result. 1165 // Deletion directives ensure that the results will eventually be deleted. 1166 // Pass ownership of the request to the callback. 1167 scoped_ptr<history::WebHistoryService::Request> request = 1168 web_history->ExpireHistoryBetween( 1169 restrict_urls, begin_time, end_time, 1170 base::Bind(&ExpireWebHistoryComplete)); 1171 1172 // The request will be freed when the callback is called. 1173 CHECK(request.release()); 1174 } 1175 ExpireHistoryBetween(restrict_urls, begin_time, end_time, callback, tracker); 1176} 1177 1178void HistoryService::BroadcastNotificationsHelper( 1179 int type, 1180 history::HistoryDetails* details) { 1181 DCHECK(thread_checker_.CalledOnValidThread()); 1182 // TODO(evanm): this is currently necessitated by generate_profile, which 1183 // runs without a browser process. generate_profile should really create 1184 // a browser process, at which point this check can then be nuked. 1185 if (!g_browser_process) 1186 return; 1187 1188 if (!thread_) 1189 return; 1190 1191 // The source of all of our notifications is the profile. Note that this 1192 // pointer is NULL in unit tests. 1193 content::Source<Profile> source(profile_); 1194 1195 // The details object just contains the pointer to the object that the 1196 // backend has allocated for us. The receiver of the notification will cast 1197 // this to the proper type. 1198 content::Details<history::HistoryDetails> det(details); 1199 1200 content::NotificationService::current()->Notify(type, source, det); 1201} 1202 1203void HistoryService::LoadBackendIfNecessary() { 1204 DCHECK(thread_checker_.CalledOnValidThread()); 1205 if (!thread_ || history_backend_.get()) 1206 return; // Failed to init, or already started loading. 1207 1208 ++current_backend_id_; 1209 scoped_refptr<HistoryBackend> backend( 1210 new HistoryBackend(history_dir_, 1211 current_backend_id_, 1212 new BackendDelegate( 1213 weak_ptr_factory_.GetWeakPtr(), 1214 base::ThreadTaskRunnerHandle::Get(), 1215 profile_), 1216 bookmark_service_)); 1217 history_backend_.swap(backend); 1218 1219 // There may not be a profile when unit testing. 1220 std::string languages; 1221 if (profile_) { 1222 PrefService* prefs = profile_->GetPrefs(); 1223 languages = prefs->GetString(prefs::kAcceptLanguages); 1224 } 1225 ScheduleAndForget(PRIORITY_UI, &HistoryBackend::Init, languages, no_db_); 1226} 1227 1228void HistoryService::OnDBLoaded(int backend_id) { 1229 DCHECK(thread_checker_.CalledOnValidThread()); 1230 if (!history_backend_.get() || current_backend_id_ != backend_id) { 1231 DVLOG(1) << "Message from obsolete backend"; 1232 return; 1233 } 1234 backend_loaded_ = true; 1235 content::NotificationService::current()->Notify( 1236 chrome::NOTIFICATION_HISTORY_LOADED, 1237 content::Source<Profile>(profile_), 1238 content::Details<HistoryService>(this)); 1239} 1240 1241bool HistoryService::GetRowForURL(const GURL& url, history::URLRow* url_row) { 1242 DCHECK(thread_checker_.CalledOnValidThread()); 1243 history::URLDatabase* db = InMemoryDatabase(); 1244 return db && (db->GetRowForURL(url, url_row) != 0); 1245} 1246 1247void HistoryService::AddVisitDatabaseObserver( 1248 history::VisitDatabaseObserver* observer) { 1249 DCHECK(thread_checker_.CalledOnValidThread()); 1250 visit_database_observers_.AddObserver(observer); 1251} 1252 1253void HistoryService::RemoveVisitDatabaseObserver( 1254 history::VisitDatabaseObserver* observer) { 1255 DCHECK(thread_checker_.CalledOnValidThread()); 1256 visit_database_observers_.RemoveObserver(observer); 1257} 1258 1259void HistoryService::NotifyVisitDBObserversOnAddVisit( 1260 const history::BriefVisitInfo& info) { 1261 DCHECK(thread_checker_.CalledOnValidThread()); 1262 FOR_EACH_OBSERVER(history::VisitDatabaseObserver, visit_database_observers_, 1263 OnAddVisit(info)); 1264} 1265