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