history_service.cc revision 8bcbed890bc3ce4d7a057a8f32cab53fa534672e
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 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 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::URLsNoLongerBookmarked(const std::set<GURL>& urls) { 408 DCHECK(thread_checker_.CalledOnValidThread()); 409 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::URLsNoLongerBookmarked, 410 urls); 411} 412 413void HistoryService::ScheduleDBTask(history::HistoryDBTask* task, 414 CancelableRequestConsumerBase* consumer) { 415 DCHECK(thread_checker_.CalledOnValidThread()); 416 history::HistoryDBTaskRequest* request = new history::HistoryDBTaskRequest( 417 base::Bind(&history::HistoryDBTask::DoneRunOnMainThread, task)); 418 request->value = task; // The value is the task to execute. 419 Schedule(PRIORITY_UI, &HistoryBackend::ProcessDBTask, consumer, request); 420} 421 422HistoryService::Handle HistoryService::QuerySegmentUsageSince( 423 CancelableRequestConsumerBase* consumer, 424 const Time from_time, 425 int max_result_count, 426 const SegmentQueryCallback& callback) { 427 DCHECK(thread_checker_.CalledOnValidThread()); 428 return Schedule(PRIORITY_UI, &HistoryBackend::QuerySegmentUsage, 429 consumer, new history::QuerySegmentUsageRequest(callback), 430 from_time, max_result_count); 431} 432 433void HistoryService::IncreaseSegmentDuration(const GURL& url, 434 Time time, 435 base::TimeDelta delta) { 436 DCHECK(thread_checker_.CalledOnValidThread()); 437 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::IncreaseSegmentDuration, 438 url, time, delta); 439} 440 441HistoryService::Handle HistoryService::QuerySegmentDurationSince( 442 CancelableRequestConsumerBase* consumer, 443 base::Time from_time, 444 int max_result_count, 445 const SegmentQueryCallback& callback) { 446 DCHECK(thread_checker_.CalledOnValidThread()); 447 return Schedule(PRIORITY_UI, &HistoryBackend::QuerySegmentDuration, 448 consumer, new history::QuerySegmentUsageRequest(callback), 449 from_time, max_result_count); 450} 451 452void HistoryService::FlushForTest(const base::Closure& flushed) { 453 thread_->message_loop_proxy()->PostTaskAndReply( 454 FROM_HERE, base::Bind(&base::DoNothing), flushed); 455} 456 457void HistoryService::SetOnBackendDestroyTask(const base::Closure& task) { 458 DCHECK(thread_checker_.CalledOnValidThread()); 459 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::SetOnBackendDestroyTask, 460 base::MessageLoop::current(), task); 461} 462 463void HistoryService::AddPage(const GURL& url, 464 Time time, 465 const void* id_scope, 466 int32 page_id, 467 const GURL& referrer, 468 const history::RedirectList& redirects, 469 content::PageTransition transition, 470 history::VisitSource visit_source, 471 bool did_replace_entry) { 472 DCHECK(thread_checker_.CalledOnValidThread()); 473 AddPage( 474 history::HistoryAddPageArgs(url, time, id_scope, page_id, referrer, 475 redirects, transition, visit_source, 476 did_replace_entry)); 477} 478 479void HistoryService::AddPage(const GURL& url, 480 base::Time time, 481 history::VisitSource visit_source) { 482 DCHECK(thread_checker_.CalledOnValidThread()); 483 AddPage( 484 history::HistoryAddPageArgs(url, time, NULL, 0, GURL(), 485 history::RedirectList(), 486 content::PAGE_TRANSITION_LINK, 487 visit_source, false)); 488} 489 490void HistoryService::AddPage(const history::HistoryAddPageArgs& add_page_args) { 491 DCHECK(thread_checker_.CalledOnValidThread()); 492 DCHECK(thread_) << "History service being called after cleanup"; 493 494 // Filter out unwanted URLs. We don't add auto-subframe URLs. They are a 495 // large part of history (think iframes for ads) and we never display them in 496 // history UI. We will still add manual subframes, which are ones the user 497 // has clicked on to get. 498 if (!CanAddURL(add_page_args.url)) 499 return; 500 501 // Add link & all redirects to visited link list. 502 if (visitedlink_master_) { 503 visitedlink_master_->AddURL(add_page_args.url); 504 505 if (!add_page_args.redirects.empty()) { 506 // We should not be asked to add a page in the middle of a redirect chain. 507 DCHECK_EQ(add_page_args.url, 508 add_page_args.redirects[add_page_args.redirects.size() - 1]); 509 510 // We need the !redirects.empty() condition above since size_t is unsigned 511 // and will wrap around when we subtract one from a 0 size. 512 for (size_t i = 0; i < add_page_args.redirects.size() - 1; i++) 513 visitedlink_master_->AddURL(add_page_args.redirects[i]); 514 } 515 } 516 517 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::AddPage, add_page_args); 518} 519 520void HistoryService::AddPageNoVisitForBookmark(const GURL& url, 521 const string16& title) { 522 DCHECK(thread_checker_.CalledOnValidThread()); 523 if (!CanAddURL(url)) 524 return; 525 526 ScheduleAndForget(PRIORITY_NORMAL, 527 &HistoryBackend::AddPageNoVisitForBookmark, url, title); 528} 529 530void HistoryService::SetPageTitle(const GURL& url, 531 const string16& title) { 532 DCHECK(thread_checker_.CalledOnValidThread()); 533 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::SetPageTitle, url, title); 534} 535 536void HistoryService::UpdateWithPageEndTime(const void* host, 537 int32 page_id, 538 const GURL& url, 539 Time end_ts) { 540 DCHECK(thread_checker_.CalledOnValidThread()); 541 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::UpdateWithPageEndTime, 542 host, page_id, url, end_ts); 543} 544 545void HistoryService::AddPageWithDetails(const GURL& url, 546 const string16& title, 547 int visit_count, 548 int typed_count, 549 Time last_visit, 550 bool hidden, 551 history::VisitSource visit_source) { 552 DCHECK(thread_checker_.CalledOnValidThread()); 553 // Filter out unwanted URLs. 554 if (!CanAddURL(url)) 555 return; 556 557 // Add to the visited links system. 558 if (visitedlink_master_) 559 visitedlink_master_->AddURL(url); 560 561 history::URLRow row(url); 562 row.set_title(title); 563 row.set_visit_count(visit_count); 564 row.set_typed_count(typed_count); 565 row.set_last_visit(last_visit); 566 row.set_hidden(hidden); 567 568 history::URLRows rows; 569 rows.push_back(row); 570 571 ScheduleAndForget(PRIORITY_NORMAL, 572 &HistoryBackend::AddPagesWithDetails, rows, visit_source); 573} 574 575void HistoryService::AddPagesWithDetails(const history::URLRows& info, 576 history::VisitSource visit_source) { 577 DCHECK(thread_checker_.CalledOnValidThread()); 578 // Add to the visited links system. 579 if (visitedlink_master_) { 580 std::vector<GURL> urls; 581 urls.reserve(info.size()); 582 for (history::URLRows::const_iterator i = info.begin(); i != info.end(); 583 ++i) 584 urls.push_back(i->url()); 585 586 visitedlink_master_->AddURLs(urls); 587 } 588 589 ScheduleAndForget(PRIORITY_NORMAL, 590 &HistoryBackend::AddPagesWithDetails, info, visit_source); 591} 592 593void HistoryService::SetPageContents(const GURL& url, 594 const string16& contents) { 595 DCHECK(thread_checker_.CalledOnValidThread()); 596 if (!CanAddURL(url)) 597 return; 598 599 ScheduleAndForget(PRIORITY_LOW, &HistoryBackend::SetPageContents, 600 url, contents); 601} 602 603CancelableTaskTracker::TaskId HistoryService::GetFavicons( 604 const std::vector<GURL>& icon_urls, 605 int icon_types, 606 int desired_size_in_dip, 607 const std::vector<ui::ScaleFactor>& desired_scale_factors, 608 const FaviconService::FaviconResultsCallback& callback, 609 CancelableTaskTracker* tracker) { 610 DCHECK(thread_checker_.CalledOnValidThread()); 611 LoadBackendIfNecessary(); 612 613 std::vector<chrome::FaviconBitmapResult>* results = 614 new std::vector<chrome::FaviconBitmapResult>(); 615 return tracker->PostTaskAndReply( 616 thread_->message_loop_proxy().get(), 617 FROM_HERE, 618 base::Bind(&HistoryBackend::GetFavicons, 619 history_backend_.get(), 620 icon_urls, 621 icon_types, 622 desired_size_in_dip, 623 desired_scale_factors, 624 results), 625 base::Bind(&RunWithFaviconResults, callback, base::Owned(results))); 626} 627 628CancelableTaskTracker::TaskId HistoryService::GetFaviconsForURL( 629 const GURL& page_url, 630 int icon_types, 631 int desired_size_in_dip, 632 const std::vector<ui::ScaleFactor>& desired_scale_factors, 633 const FaviconService::FaviconResultsCallback& callback, 634 CancelableTaskTracker* tracker) { 635 DCHECK(thread_checker_.CalledOnValidThread()); 636 LoadBackendIfNecessary(); 637 638 std::vector<chrome::FaviconBitmapResult>* results = 639 new std::vector<chrome::FaviconBitmapResult>(); 640 return tracker->PostTaskAndReply( 641 thread_->message_loop_proxy().get(), 642 FROM_HERE, 643 base::Bind(&HistoryBackend::GetFaviconsForURL, 644 history_backend_.get(), 645 page_url, 646 icon_types, 647 desired_size_in_dip, 648 desired_scale_factors, 649 results), 650 base::Bind(&RunWithFaviconResults, callback, base::Owned(results))); 651} 652 653CancelableTaskTracker::TaskId HistoryService::GetLargestFaviconForURL( 654 const GURL& page_url, 655 const std::vector<int>& icon_types, 656 int minimum_size_in_pixels, 657 const FaviconService::FaviconRawCallback& callback, 658 CancelableTaskTracker* tracker) { 659 DCHECK(thread_checker_.CalledOnValidThread()); 660 LoadBackendIfNecessary(); 661 662 chrome::FaviconBitmapResult* result = new chrome::FaviconBitmapResult(); 663 return tracker->PostTaskAndReply( 664 thread_->message_loop_proxy().get(), 665 FROM_HERE, 666 base::Bind(&HistoryBackend::GetLargestFaviconForURL, 667 history_backend_.get(), 668 page_url, 669 icon_types, 670 minimum_size_in_pixels, 671 result), 672 base::Bind(&RunWithFaviconResult, callback, base::Owned(result))); 673} 674 675CancelableTaskTracker::TaskId HistoryService::GetFaviconForID( 676 chrome::FaviconID favicon_id, 677 int desired_size_in_dip, 678 ui::ScaleFactor desired_scale_factor, 679 const FaviconService::FaviconResultsCallback& callback, 680 CancelableTaskTracker* tracker) { 681 DCHECK(thread_checker_.CalledOnValidThread()); 682 LoadBackendIfNecessary(); 683 684 std::vector<chrome::FaviconBitmapResult>* results = 685 new std::vector<chrome::FaviconBitmapResult>(); 686 return tracker->PostTaskAndReply( 687 thread_->message_loop_proxy().get(), 688 FROM_HERE, 689 base::Bind(&HistoryBackend::GetFaviconForID, 690 history_backend_.get(), 691 favicon_id, 692 desired_size_in_dip, 693 desired_scale_factor, 694 results), 695 base::Bind(&RunWithFaviconResults, callback, base::Owned(results))); 696} 697 698CancelableTaskTracker::TaskId HistoryService::UpdateFaviconMappingsAndFetch( 699 const GURL& page_url, 700 const std::vector<GURL>& icon_urls, 701 int icon_types, 702 int desired_size_in_dip, 703 const std::vector<ui::ScaleFactor>& desired_scale_factors, 704 const FaviconService::FaviconResultsCallback& callback, 705 CancelableTaskTracker* tracker) { 706 DCHECK(thread_checker_.CalledOnValidThread()); 707 LoadBackendIfNecessary(); 708 709 std::vector<chrome::FaviconBitmapResult>* results = 710 new std::vector<chrome::FaviconBitmapResult>(); 711 return tracker->PostTaskAndReply( 712 thread_->message_loop_proxy().get(), 713 FROM_HERE, 714 base::Bind(&HistoryBackend::UpdateFaviconMappingsAndFetch, 715 history_backend_.get(), 716 page_url, 717 icon_urls, 718 icon_types, 719 desired_size_in_dip, 720 desired_scale_factors, 721 results), 722 base::Bind(&RunWithFaviconResults, callback, base::Owned(results))); 723} 724 725void HistoryService::MergeFavicon( 726 const GURL& page_url, 727 const GURL& icon_url, 728 chrome::IconType icon_type, 729 scoped_refptr<base::RefCountedMemory> bitmap_data, 730 const gfx::Size& pixel_size) { 731 DCHECK(thread_checker_.CalledOnValidThread()); 732 if (!CanAddURL(page_url)) 733 return; 734 735 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::MergeFavicon, page_url, 736 icon_url, icon_type, bitmap_data, pixel_size); 737} 738 739void HistoryService::SetFavicons( 740 const GURL& page_url, 741 chrome::IconType icon_type, 742 const std::vector<chrome::FaviconBitmapData>& favicon_bitmap_data) { 743 DCHECK(thread_checker_.CalledOnValidThread()); 744 if (!CanAddURL(page_url)) 745 return; 746 747 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::SetFavicons, page_url, 748 icon_type, favicon_bitmap_data); 749} 750 751void HistoryService::SetFaviconsOutOfDateForPage(const GURL& page_url) { 752 DCHECK(thread_checker_.CalledOnValidThread()); 753 ScheduleAndForget(PRIORITY_NORMAL, 754 &HistoryBackend::SetFaviconsOutOfDateForPage, page_url); 755} 756 757void HistoryService::CloneFavicons(const GURL& old_page_url, 758 const GURL& new_page_url) { 759 DCHECK(thread_checker_.CalledOnValidThread()); 760 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::CloneFavicons, 761 old_page_url, new_page_url); 762} 763 764void HistoryService::SetImportedFavicons( 765 const std::vector<ImportedFaviconUsage>& favicon_usage) { 766 DCHECK(thread_checker_.CalledOnValidThread()); 767 ScheduleAndForget(PRIORITY_NORMAL, 768 &HistoryBackend::SetImportedFavicons, favicon_usage); 769} 770 771HistoryService::Handle HistoryService::QueryURL( 772 const GURL& url, 773 bool want_visits, 774 CancelableRequestConsumerBase* consumer, 775 const QueryURLCallback& callback) { 776 DCHECK(thread_checker_.CalledOnValidThread()); 777 return Schedule(PRIORITY_UI, &HistoryBackend::QueryURL, consumer, 778 new history::QueryURLRequest(callback), url, want_visits); 779} 780 781// Downloads ------------------------------------------------------------------- 782 783// Handle creation of a download by creating an entry in the history service's 784// 'downloads' table. 785void HistoryService::CreateDownload( 786 const history::DownloadRow& create_info, 787 const HistoryService::DownloadCreateCallback& callback) { 788 DCHECK(thread_) << "History service being called after cleanup"; 789 DCHECK(thread_checker_.CalledOnValidThread()); 790 LoadBackendIfNecessary(); 791 bool* success = new bool(false); 792 thread_->message_loop_proxy()->PostTaskAndReply( 793 FROM_HERE, 794 base::Bind(&HistoryBackend::CreateDownload, 795 history_backend_.get(), 796 create_info, 797 success), 798 base::Bind(&DerefPODType<bool>, callback, base::Owned(success))); 799} 800 801void HistoryService::GetNextDownloadId( 802 const content::DownloadIdCallback& callback) { 803 DCHECK(thread_) << "History service being called after cleanup"; 804 DCHECK(thread_checker_.CalledOnValidThread()); 805 LoadBackendIfNecessary(); 806 uint32* next_id = new uint32(content::DownloadItem::kInvalidId); 807 thread_->message_loop_proxy()->PostTaskAndReply( 808 FROM_HERE, 809 base::Bind(&HistoryBackend::GetNextDownloadId, 810 history_backend_.get(), 811 next_id), 812 base::Bind(&DerefPODType<uint32>, callback, base::Owned(next_id))); 813} 814 815// Handle queries for a list of all downloads in the history database's 816// 'downloads' table. 817void HistoryService::QueryDownloads( 818 const DownloadQueryCallback& callback) { 819 DCHECK(thread_) << "History service being called after cleanup"; 820 DCHECK(thread_checker_.CalledOnValidThread()); 821 LoadBackendIfNecessary(); 822 std::vector<history::DownloadRow>* rows = 823 new std::vector<history::DownloadRow>(); 824 scoped_ptr<std::vector<history::DownloadRow> > scoped_rows(rows); 825 // Beware! The first Bind() does not simply |scoped_rows.get()| because 826 // base::Passed(&scoped_rows) nullifies |scoped_rows|, and compilers do not 827 // guarantee that the first Bind's arguments are evaluated before the second 828 // Bind's arguments. 829 thread_->message_loop_proxy()->PostTaskAndReply( 830 FROM_HERE, 831 base::Bind(&HistoryBackend::QueryDownloads, history_backend_.get(), rows), 832 base::Bind(callback, base::Passed(&scoped_rows))); 833} 834 835// Handle updates for a particular download. This is a 'fire and forget' 836// operation, so we don't need to be called back. 837void HistoryService::UpdateDownload(const history::DownloadRow& data) { 838 DCHECK(thread_checker_.CalledOnValidThread()); 839 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::UpdateDownload, data); 840} 841 842void HistoryService::RemoveDownloads(const std::set<uint32>& ids) { 843 DCHECK(thread_checker_.CalledOnValidThread()); 844 ScheduleAndForget(PRIORITY_NORMAL, 845 &HistoryBackend::RemoveDownloads, ids); 846} 847 848HistoryService::Handle HistoryService::QueryHistory( 849 const string16& text_query, 850 const history::QueryOptions& options, 851 CancelableRequestConsumerBase* consumer, 852 const QueryHistoryCallback& callback) { 853 DCHECK(thread_checker_.CalledOnValidThread()); 854 return Schedule(PRIORITY_UI, &HistoryBackend::QueryHistory, consumer, 855 new history::QueryHistoryRequest(callback), 856 text_query, options); 857} 858 859HistoryService::Handle HistoryService::QueryRedirectsFrom( 860 const GURL& from_url, 861 CancelableRequestConsumerBase* consumer, 862 const QueryRedirectsCallback& callback) { 863 DCHECK(thread_checker_.CalledOnValidThread()); 864 return Schedule(PRIORITY_UI, &HistoryBackend::QueryRedirectsFrom, consumer, 865 new history::QueryRedirectsRequest(callback), from_url); 866} 867 868HistoryService::Handle HistoryService::QueryRedirectsTo( 869 const GURL& to_url, 870 CancelableRequestConsumerBase* consumer, 871 const QueryRedirectsCallback& callback) { 872 DCHECK(thread_checker_.CalledOnValidThread()); 873 return Schedule(PRIORITY_NORMAL, &HistoryBackend::QueryRedirectsTo, consumer, 874 new history::QueryRedirectsRequest(callback), to_url); 875} 876 877HistoryService::Handle HistoryService::GetVisibleVisitCountToHost( 878 const GURL& url, 879 CancelableRequestConsumerBase* consumer, 880 const GetVisibleVisitCountToHostCallback& callback) { 881 DCHECK(thread_checker_.CalledOnValidThread()); 882 return Schedule(PRIORITY_UI, &HistoryBackend::GetVisibleVisitCountToHost, 883 consumer, new history::GetVisibleVisitCountToHostRequest(callback), url); 884} 885 886HistoryService::Handle HistoryService::QueryTopURLsAndRedirects( 887 int result_count, 888 CancelableRequestConsumerBase* consumer, 889 const QueryTopURLsAndRedirectsCallback& callback) { 890 DCHECK(thread_checker_.CalledOnValidThread()); 891 return Schedule(PRIORITY_NORMAL, &HistoryBackend::QueryTopURLsAndRedirects, 892 consumer, new history::QueryTopURLsAndRedirectsRequest(callback), 893 result_count); 894} 895 896HistoryService::Handle HistoryService::QueryMostVisitedURLs( 897 int result_count, 898 int days_back, 899 CancelableRequestConsumerBase* consumer, 900 const QueryMostVisitedURLsCallback& callback) { 901 DCHECK(thread_checker_.CalledOnValidThread()); 902 return Schedule(PRIORITY_NORMAL, &HistoryBackend::QueryMostVisitedURLs, 903 consumer, 904 new history::QueryMostVisitedURLsRequest(callback), 905 result_count, days_back); 906} 907 908HistoryService::Handle HistoryService::QueryFilteredURLs( 909 int result_count, 910 const history::VisitFilter& filter, 911 bool extended_info, 912 CancelableRequestConsumerBase* consumer, 913 const QueryFilteredURLsCallback& callback) { 914 DCHECK(thread_checker_.CalledOnValidThread()); 915 return Schedule(PRIORITY_NORMAL, 916 &HistoryBackend::QueryFilteredURLs, 917 consumer, 918 new history::QueryFilteredURLsRequest(callback), 919 result_count, filter, extended_info); 920} 921 922void HistoryService::Observe(int type, 923 const content::NotificationSource& source, 924 const content::NotificationDetails& details) { 925 DCHECK(thread_checker_.CalledOnValidThread()); 926 if (!thread_) 927 return; 928 929 switch (type) { 930 case chrome::NOTIFICATION_HISTORY_URLS_DELETED: { 931 // Update the visited link system for deleted URLs. We will update the 932 // visited link system for added URLs as soon as we get the add 933 // notification (we don't have to wait for the backend, which allows us to 934 // be faster to update the state). 935 // 936 // For deleted URLs, we don't typically know what will be deleted since 937 // delete notifications are by time. We would also like to be more 938 // respectful of privacy and never tell the user something is gone when it 939 // isn't. Therefore, we update the delete URLs after the fact. 940 if (visitedlink_master_) { 941 content::Details<history::URLsDeletedDetails> deleted_details(details); 942 943 if (deleted_details->all_history) { 944 visitedlink_master_->DeleteAllURLs(); 945 } else { 946 URLIteratorFromURLRows iterator(deleted_details->rows); 947 visitedlink_master_->DeleteURLs(&iterator); 948 } 949 } 950 break; 951 } 952 953 case chrome::NOTIFICATION_TEMPLATE_URL_REMOVED: 954 DeleteAllSearchTermsForKeyword( 955 *(content::Details<TemplateURLID>(details).ptr())); 956 break; 957 958 default: 959 NOTREACHED(); 960 } 961} 962 963void HistoryService::RebuildTable( 964 const scoped_refptr<URLEnumerator>& enumerator) { 965 DCHECK(thread_checker_.CalledOnValidThread()); 966 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::IterateURLs, enumerator); 967} 968 969bool HistoryService::Init(const base::FilePath& history_dir, 970 BookmarkService* bookmark_service, 971 bool no_db) { 972 DCHECK(thread_checker_.CalledOnValidThread()); 973 if (!thread_->Start()) { 974 Cleanup(); 975 return false; 976 } 977 978 history_dir_ = history_dir; 979 bookmark_service_ = bookmark_service; 980 no_db_ = no_db; 981 982 if (profile_) { 983 std::string languages = 984 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages); 985 in_memory_url_index_.reset( 986 new history::InMemoryURLIndex(profile_, history_dir_, languages)); 987 in_memory_url_index_->Init(); 988 } 989 990 // Create the history backend. 991 LoadBackendIfNecessary(); 992 993 if (visitedlink_master_) { 994 bool result = visitedlink_master_->Init(); 995 DCHECK(result); 996 } 997 998 return true; 999} 1000 1001void HistoryService::ScheduleAutocomplete(HistoryURLProvider* provider, 1002 HistoryURLProviderParams* params) { 1003 DCHECK(thread_checker_.CalledOnValidThread()); 1004 ScheduleAndForget(PRIORITY_UI, &HistoryBackend::ScheduleAutocomplete, 1005 scoped_refptr<HistoryURLProvider>(provider), params); 1006} 1007 1008void HistoryService::ScheduleTask(SchedulePriority priority, 1009 const base::Closure& task) { 1010 DCHECK(thread_checker_.CalledOnValidThread()); 1011 CHECK(thread_); 1012 CHECK(thread_->message_loop()); 1013 // TODO(brettw): Do prioritization. 1014 thread_->message_loop()->PostTask(FROM_HERE, task); 1015} 1016 1017// static 1018bool HistoryService::CanAddURL(const GURL& url) { 1019 if (!url.is_valid()) 1020 return false; 1021 1022 // TODO: We should allow kChromeUIScheme URLs if they have been explicitly 1023 // typed. Right now, however, these are marked as typed even when triggered 1024 // by a shortcut or menu action. 1025 if (url.SchemeIs(content::kJavaScriptScheme) || 1026 url.SchemeIs(chrome::kChromeDevToolsScheme) || 1027 url.SchemeIs(chrome::kChromeNativeScheme) || 1028 url.SchemeIs(chrome::kChromeUIScheme) || 1029 url.SchemeIs(chrome::kChromeSearchScheme) || 1030 url.SchemeIs(content::kViewSourceScheme) || 1031 url.SchemeIs(chrome::kChromeInternalScheme)) 1032 return false; 1033 1034 // Allow all about: and chrome: URLs except about:blank, since the user may 1035 // like to see "chrome://memory/", etc. in their history and autocomplete. 1036 if (url == GURL(content::kAboutBlankURL)) 1037 return false; 1038 1039 return true; 1040} 1041 1042base::WeakPtr<HistoryService> HistoryService::AsWeakPtr() { 1043 DCHECK(thread_checker_.CalledOnValidThread()); 1044 return weak_ptr_factory_.GetWeakPtr(); 1045} 1046 1047syncer::SyncMergeResult HistoryService::MergeDataAndStartSyncing( 1048 syncer::ModelType type, 1049 const syncer::SyncDataList& initial_sync_data, 1050 scoped_ptr<syncer::SyncChangeProcessor> sync_processor, 1051 scoped_ptr<syncer::SyncErrorFactory> error_handler) { 1052 DCHECK(thread_checker_.CalledOnValidThread()); 1053 DCHECK_EQ(type, syncer::HISTORY_DELETE_DIRECTIVES); 1054 delete_directive_handler_.Start(this, initial_sync_data, 1055 sync_processor.Pass()); 1056 return syncer::SyncMergeResult(type); 1057} 1058 1059void HistoryService::StopSyncing(syncer::ModelType type) { 1060 DCHECK(thread_checker_.CalledOnValidThread()); 1061 DCHECK_EQ(type, syncer::HISTORY_DELETE_DIRECTIVES); 1062 delete_directive_handler_.Stop(); 1063} 1064 1065syncer::SyncDataList HistoryService::GetAllSyncData( 1066 syncer::ModelType type) const { 1067 DCHECK(thread_checker_.CalledOnValidThread()); 1068 DCHECK_EQ(type, syncer::HISTORY_DELETE_DIRECTIVES); 1069 // TODO(akalin): Keep track of existing delete directives. 1070 return syncer::SyncDataList(); 1071} 1072 1073syncer::SyncError HistoryService::ProcessSyncChanges( 1074 const tracked_objects::Location& from_here, 1075 const syncer::SyncChangeList& change_list) { 1076 delete_directive_handler_.ProcessSyncChanges(this, change_list); 1077 return syncer::SyncError(); 1078} 1079 1080syncer::SyncError HistoryService::ProcessLocalDeleteDirective( 1081 const sync_pb::HistoryDeleteDirectiveSpecifics& delete_directive) { 1082 DCHECK(thread_checker_.CalledOnValidThread()); 1083 return delete_directive_handler_.ProcessLocalDeleteDirective( 1084 delete_directive); 1085} 1086 1087void HistoryService::SetInMemoryBackend( 1088 int backend_id, scoped_ptr<history::InMemoryHistoryBackend> mem_backend) { 1089 DCHECK(thread_checker_.CalledOnValidThread()); 1090 if (!history_backend_.get() || current_backend_id_ != backend_id) { 1091 DVLOG(1) << "Message from obsolete backend"; 1092 // mem_backend is deleted. 1093 return; 1094 } 1095 DCHECK(!in_memory_backend_) << "Setting mem DB twice"; 1096 in_memory_backend_.reset(mem_backend.release()); 1097 1098 // The database requires additional initialization once we own it. 1099 in_memory_backend_->AttachToHistoryService(profile_); 1100} 1101 1102void HistoryService::NotifyProfileError(int backend_id, 1103 sql::InitStatus init_status) { 1104 DCHECK(thread_checker_.CalledOnValidThread()); 1105 if (!history_backend_.get() || current_backend_id_ != backend_id) { 1106 DVLOG(1) << "Message from obsolete backend"; 1107 return; 1108 } 1109 ShowProfileErrorDialog( 1110 (init_status == sql::INIT_FAILURE) ? 1111 IDS_COULDNT_OPEN_PROFILE_ERROR : IDS_PROFILE_TOO_NEW_ERROR); 1112} 1113 1114void HistoryService::DeleteURL(const GURL& url) { 1115 DCHECK(thread_checker_.CalledOnValidThread()); 1116 // We will update the visited links when we observe the delete notifications. 1117 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::DeleteURL, url); 1118} 1119 1120void HistoryService::DeleteURLsForTest(const std::vector<GURL>& urls) { 1121 DCHECK(thread_checker_.CalledOnValidThread()); 1122 // We will update the visited links when we observe the delete 1123 // notifications. 1124 ScheduleAndForget(PRIORITY_NORMAL, &HistoryBackend::DeleteURLs, urls); 1125} 1126 1127void HistoryService::ExpireHistoryBetween( 1128 const std::set<GURL>& restrict_urls, 1129 Time begin_time, 1130 Time end_time, 1131 const base::Closure& callback, 1132 CancelableTaskTracker* tracker) { 1133 DCHECK(thread_); 1134 DCHECK(thread_checker_.CalledOnValidThread()); 1135 DCHECK(history_backend_.get()); 1136 tracker->PostTaskAndReply(thread_->message_loop_proxy().get(), 1137 FROM_HERE, 1138 base::Bind(&HistoryBackend::ExpireHistoryBetween, 1139 history_backend_, 1140 restrict_urls, 1141 begin_time, 1142 end_time), 1143 callback); 1144} 1145 1146void HistoryService::ExpireHistory( 1147 const std::vector<history::ExpireHistoryArgs>& expire_list, 1148 const base::Closure& callback, 1149 CancelableTaskTracker* tracker) { 1150 DCHECK(thread_); 1151 DCHECK(thread_checker_.CalledOnValidThread()); 1152 DCHECK(history_backend_.get()); 1153 tracker->PostTaskAndReply( 1154 thread_->message_loop_proxy().get(), 1155 FROM_HERE, 1156 base::Bind(&HistoryBackend::ExpireHistory, history_backend_, expire_list), 1157 callback); 1158} 1159 1160void HistoryService::ExpireLocalAndRemoteHistoryBetween( 1161 const std::set<GURL>& restrict_urls, 1162 Time begin_time, 1163 Time end_time, 1164 const base::Closure& callback, 1165 CancelableTaskTracker* tracker) { 1166 // TODO(dubroy): This should be factored out into a separate class that 1167 // dispatches deletions to the proper places. 1168 1169 history::WebHistoryService* web_history = 1170 WebHistoryServiceFactory::GetForProfile(profile_); 1171 if (web_history) { 1172 // TODO(dubroy): This API does not yet support deletion of specific URLs. 1173 DCHECK(restrict_urls.empty()); 1174 1175 delete_directive_handler_.CreateDeleteDirectives( 1176 std::set<int64>(), begin_time, end_time); 1177 1178 // Attempt online deletion from the history server, but ignore the result. 1179 // Deletion directives ensure that the results will eventually be deleted. 1180 // Pass ownership of the request to the callback. 1181 scoped_ptr<history::WebHistoryService::Request> request = 1182 web_history->ExpireHistoryBetween( 1183 restrict_urls, begin_time, end_time, 1184 base::Bind(&ExpireWebHistoryComplete)); 1185 1186 // The request will be freed when the callback is called. 1187 CHECK(request.release()); 1188 } 1189 ExpireHistoryBetween(restrict_urls, begin_time, end_time, callback, tracker); 1190} 1191 1192void HistoryService::BroadcastNotificationsHelper( 1193 int type, 1194 history::HistoryDetails* details) { 1195 DCHECK(thread_checker_.CalledOnValidThread()); 1196 // TODO(evanm): this is currently necessitated by generate_profile, which 1197 // runs without a browser process. generate_profile should really create 1198 // a browser process, at which point this check can then be nuked. 1199 if (!g_browser_process) 1200 return; 1201 1202 if (!thread_) 1203 return; 1204 1205 // The source of all of our notifications is the profile. Note that this 1206 // pointer is NULL in unit tests. 1207 content::Source<Profile> source(profile_); 1208 1209 // The details object just contains the pointer to the object that the 1210 // backend has allocated for us. The receiver of the notification will cast 1211 // this to the proper type. 1212 content::Details<history::HistoryDetails> det(details); 1213 1214 content::NotificationService::current()->Notify(type, source, det); 1215} 1216 1217void HistoryService::LoadBackendIfNecessary() { 1218 DCHECK(thread_checker_.CalledOnValidThread()); 1219 if (!thread_ || history_backend_.get()) 1220 return; // Failed to init, or already started loading. 1221 1222 ++current_backend_id_; 1223 scoped_refptr<HistoryBackend> backend( 1224 new HistoryBackend(history_dir_, 1225 current_backend_id_, 1226 new BackendDelegate( 1227 weak_ptr_factory_.GetWeakPtr(), 1228 base::ThreadTaskRunnerHandle::Get(), 1229 profile_), 1230 bookmark_service_)); 1231 history_backend_.swap(backend); 1232 1233 // There may not be a profile when unit testing. 1234 std::string languages; 1235 if (profile_) { 1236 PrefService* prefs = profile_->GetPrefs(); 1237 languages = prefs->GetString(prefs::kAcceptLanguages); 1238 } 1239 ScheduleAndForget(PRIORITY_UI, &HistoryBackend::Init, languages, no_db_); 1240} 1241 1242void HistoryService::OnDBLoaded(int backend_id) { 1243 DCHECK(thread_checker_.CalledOnValidThread()); 1244 if (!history_backend_.get() || current_backend_id_ != backend_id) { 1245 DVLOG(1) << "Message from obsolete backend"; 1246 return; 1247 } 1248 backend_loaded_ = true; 1249 content::NotificationService::current()->Notify( 1250 chrome::NOTIFICATION_HISTORY_LOADED, 1251 content::Source<Profile>(profile_), 1252 content::Details<HistoryService>(this)); 1253} 1254 1255bool HistoryService::GetRowForURL(const GURL& url, history::URLRow* url_row) { 1256 DCHECK(thread_checker_.CalledOnValidThread()); 1257 history::URLDatabase* db = InMemoryDatabase(); 1258 return db && (db->GetRowForURL(url, url_row) != 0); 1259} 1260 1261void HistoryService::AddVisitDatabaseObserver( 1262 history::VisitDatabaseObserver* observer) { 1263 DCHECK(thread_checker_.CalledOnValidThread()); 1264 visit_database_observers_.AddObserver(observer); 1265} 1266 1267void HistoryService::RemoveVisitDatabaseObserver( 1268 history::VisitDatabaseObserver* observer) { 1269 DCHECK(thread_checker_.CalledOnValidThread()); 1270 visit_database_observers_.RemoveObserver(observer); 1271} 1272 1273void HistoryService::NotifyVisitDBObserversOnAddVisit( 1274 const history::BriefVisitInfo& info) { 1275 DCHECK(thread_checker_.CalledOnValidThread()); 1276 FOR_EACH_OBSERVER(history::VisitDatabaseObserver, visit_database_observers_, 1277 OnAddVisit(info)); 1278} 1279