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.
5 #ifndef CHROME_BROWSER_HISTORY_HISTORY_BACKEND_H_
6 #define CHROME_BROWSER_HISTORY_HISTORY_BACKEND_H_
13 #include "base/containers/mru_cache.h"
14 #include "base/files/file_path.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/memory/memory_pressure_listener.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "chrome/browser/history/archived_database.h"
19 #include "chrome/browser/history/expire_history_backend.h"
20 #include "chrome/browser/history/history_database.h"
21 #include "chrome/browser/history/history_marshaling.h"
22 #include "chrome/browser/history/history_types.h"
23 #include "chrome/browser/history/thumbnail_database.h"
24 #include "chrome/browser/history/visit_tracker.h"
25 #include "chrome/browser/search_engines/template_url_id.h"
26 #include "sql/init_status.h"
27 #include "ui/base/layout.h"
29 class BookmarkService;
31 class TypedUrlSyncableService;
32 struct ThumbnailScore;
35 #if defined(OS_ANDROID)
36 class AndroidProviderBackend;
39 class CommitLaterTask;
40 class HistoryPublisher;
45 // The maximum number of icons URLs per page which can be stored in the
46 // thumbnail database.
47 static const size_t kMaxFaviconsPerPage = 8;
49 // The maximum number of bitmaps for a single icon URL which can be stored in
50 // the thumbnail database.
51 static const size_t kMaxFaviconBitmapsPerIconURL = 8;
53 // *See the .cc file for more information on the design.*
55 // Internal history implementation which does most of the work of the history
56 // system. This runs on a background thread (to not block the browser when we
57 // do expensive operations) and is NOT threadsafe, so it must only be called
58 // from message handlers on the background thread. Invoking on another thread
59 // requires threadsafe refcounting.
61 // Most functions here are just the implementations of the corresponding
62 // functions in the history service. These functions are not documented
63 // here, see the history service for behavior.
64 class HistoryBackend : public base::RefCountedThreadSafe<HistoryBackend>,
65 public BroadcastNotificationDelegate {
67 // Interface implemented by the owner of the HistoryBackend object. Normally,
68 // the history service implements this to send stuff back to the main thread.
69 // The unit tests can provide a different implementation if they don't have
70 // a history service object.
73 virtual ~Delegate() {}
75 // Called when the database cannot be read correctly for some reason.
76 virtual void NotifyProfileError(int backend_id,
77 sql::InitStatus init_status) = 0;
79 // Sets the in-memory history backend. The in-memory backend is created by
80 // the main backend. For non-unit tests, this happens on the background
81 // thread. It is to be used on the main thread, so this would transfer
82 // it to the history service. Unit tests can override this behavior.
84 // This function is NOT guaranteed to be called. If there is an error,
85 // there may be no in-memory database.
87 // Ownership of the backend pointer is transferred to this function.
88 virtual void SetInMemoryBackend(int backend_id,
89 InMemoryHistoryBackend* backend) = 0;
91 // Broadcasts the specified notification to the notification service.
92 // This is implemented here because notifications must only be sent from
93 // the main thread. This is the only method that doesn't identify the
94 // caller because notifications must always be sent.
96 // Ownership of the HistoryDetails is transferred to this function.
97 virtual void BroadcastNotifications(int type,
98 HistoryDetails* details) = 0;
100 // Invoked when the backend has finished loading the db.
101 virtual void DBLoaded(int backend_id) = 0;
103 virtual void NotifyVisitDBObserversOnAddVisit(
104 const history::BriefVisitInfo& info) = 0;
107 // Init must be called to complete object creation. This object can be
108 // constructed on any thread, but all other functions including Init() must
109 // be called on the history thread.
111 // |history_dir| is the directory where the history files will be placed.
112 // See the definition of BroadcastNotificationsCallback above. This function
113 // takes ownership of the callback pointer.
115 // |id| is used to communicate with the delegate, to identify which
116 // backend is calling the method.
118 // |bookmark_service| is used to determine bookmarked URLs when deleting and
121 // This constructor is fast and does no I/O, so can be called at any time.
122 HistoryBackend(const base::FilePath& history_dir,
125 BookmarkService* bookmark_service);
127 // Must be called after creation but before any objects are created. If this
128 // fails, all other functions will fail as well. (Since this runs on another
129 // thread, we don't bother returning failure.)
131 // |languages| gives a list of language encodings with which the history
132 // URLs and omnibox searches are interpreted.
133 // |force_fail| can be set during unittests to unconditionally fail to init.
134 void Init(const std::string& languages, bool force_fail);
136 // Notification that the history system is shutting down. This will break
137 // the refs owned by the delegate and any pending transaction so it will
138 // actually be deleted.
141 // See NotifyRenderProcessHostDestruction.
142 void NotifyRenderProcessHostDestruction(const void* host);
144 // Navigation ----------------------------------------------------------------
146 // |request.time| must be unique with high probability.
147 void AddPage(const HistoryAddPageArgs& request);
148 virtual void SetPageTitle(const GURL& url, const string16& title);
149 void AddPageNoVisitForBookmark(const GURL& url, const string16& title);
151 // Updates the database backend with a page's ending time stamp information.
152 // The page can be identified by the combination of the pointer to
153 // a RenderProcessHost, the page id and the url.
155 // The given pointer will not be dereferenced, it is only used for
156 // identification purposes, hence it is a void*.
157 void UpdateWithPageEndTime(const void* host,
163 // Indexing ------------------------------------------------------------------
165 void SetPageContents(const GURL& url, const string16& contents);
167 // Querying ------------------------------------------------------------------
169 // ScheduleAutocomplete() never frees |provider| (which is globally live).
170 // It passes |params| on to the autocomplete system which will eventually
172 void ScheduleAutocomplete(HistoryURLProvider* provider,
173 HistoryURLProviderParams* params);
176 const scoped_refptr<visitedlink::VisitedLinkDelegate::URLEnumerator>&
178 void QueryURL(scoped_refptr<QueryURLRequest> request,
181 void QueryHistory(scoped_refptr<QueryHistoryRequest> request,
182 const string16& text_query,
183 const QueryOptions& options);
184 void QueryRedirectsFrom(scoped_refptr<QueryRedirectsRequest> request,
186 void QueryRedirectsTo(scoped_refptr<QueryRedirectsRequest> request,
189 void GetVisibleVisitCountToHost(
190 scoped_refptr<GetVisibleVisitCountToHostRequest> request,
193 // TODO(Nik): remove. Use QueryMostVisitedURLs instead.
194 void QueryTopURLsAndRedirects(
195 scoped_refptr<QueryTopURLsAndRedirectsRequest> request,
198 // Request the |result_count| most visited URLs and the chain of
199 // redirects leading to each of these URLs. |days_back| is the
200 // number of days of history to use. Used by TopSites.
201 void QueryMostVisitedURLs(
202 scoped_refptr<QueryMostVisitedURLsRequest> request,
206 // Request the |result_count| URLs and the chain of redirects
207 // leading to each of these URLs, filterd and sorted based on the |filter|.
208 // If |debug| is enabled, additional data will be computed and provided.
209 void QueryFilteredURLs(
210 scoped_refptr<QueryFilteredURLsRequest> request,
212 const history::VisitFilter& filter,
215 // QueryMostVisitedURLs without the request.
216 void QueryMostVisitedURLsImpl(int result_count,
218 MostVisitedURLList* result);
220 // Computes the most recent URL(s) that the given canonical URL has
221 // redirected to and returns true on success. There may be more than one
222 // redirect in a row, so this function will fill the given array with the
223 // entire chain. If there are no redirects for the most recent visit of the
224 // URL, or the URL is not in history, returns false.
226 // Backend for QueryRedirectsFrom.
227 bool GetMostRecentRedirectsFrom(const GURL& url,
228 history::RedirectList* redirects);
230 // Similar to above function except computes a chain of redirects to the
231 // given URL. Stores the most recent list of redirects ending at |url| in the
232 // given RedirectList. For example, if we have the redirect list A -> B -> C,
233 // then calling this function with url=C would fill redirects with {B, A}.
234 bool GetMostRecentRedirectsTo(const GURL& url,
235 history::RedirectList* redirects);
237 // Favicon -------------------------------------------------------------------
239 void GetFavicons(const std::vector<GURL>& icon_urls,
241 int desired_size_in_dip,
242 const std::vector<ui::ScaleFactor>& desired_scale_factors,
243 std::vector<chrome::FaviconBitmapResult>* bitmap_results);
245 void GetLargestFaviconForURL(
246 const GURL& page_url,
247 const std::vector<int>& icon_types,
248 int minimum_size_in_pixels,
249 chrome::FaviconBitmapResult* bitmap_result);
251 void GetFaviconsForURL(
252 const GURL& page_url,
254 int desired_size_in_dip,
255 const std::vector<ui::ScaleFactor>& desired_scale_factors,
256 std::vector<chrome::FaviconBitmapResult>* bitmap_results);
258 void GetFaviconForID(
259 chrome::FaviconID favicon_id,
260 int desired_size_in_dip,
261 ui::ScaleFactor desired_scale_factor,
262 std::vector<chrome::FaviconBitmapResult>* bitmap_results);
264 void UpdateFaviconMappingsAndFetch(
265 const GURL& page_url,
266 const std::vector<GURL>& icon_urls,
268 int desired_size_in_dip,
269 const std::vector<ui::ScaleFactor>& desired_scale_factors,
270 std::vector<chrome::FaviconBitmapResult>* bitmap_results);
272 void MergeFavicon(const GURL& page_url,
273 const GURL& icon_url,
274 chrome::IconType icon_type,
275 scoped_refptr<base::RefCountedMemory> bitmap_data,
276 const gfx::Size& pixel_size);
279 const GURL& page_url,
280 chrome::IconType icon_type,
281 const std::vector<chrome::FaviconBitmapData>& favicon_bitmap_data);
283 void SetFaviconsOutOfDateForPage(const GURL& page_url);
285 void CloneFavicons(const GURL& old_page_url, const GURL& new_page_url);
287 void SetImportedFavicons(
288 const std::vector<ImportedFaviconUsage>& favicon_usage);
290 // Downloads -----------------------------------------------------------------
292 void GetNextDownloadId(uint32* next_id);
293 void QueryDownloads(std::vector<DownloadRow>* rows);
294 void UpdateDownload(const DownloadRow& data);
295 void CreateDownload(const history::DownloadRow& history_info,
297 void RemoveDownloads(const std::set<uint32>& ids);
299 // Segment usage -------------------------------------------------------------
301 void QuerySegmentUsage(scoped_refptr<QuerySegmentUsageRequest> request,
302 const base::Time from_time,
303 int max_result_count);
304 void DeleteOldSegmentData();
306 void IncreaseSegmentDuration(const GURL& url,
308 base::TimeDelta delta);
310 void QuerySegmentDuration(scoped_refptr<QuerySegmentUsageRequest> request,
311 const base::Time from_time,
312 int max_result_count);
314 // Keyword search terms ------------------------------------------------------
316 void SetKeywordSearchTermsForURL(const GURL& url,
317 TemplateURLID keyword_id,
318 const string16& term);
320 void DeleteAllSearchTermsForKeyword(TemplateURLID keyword_id);
322 void GetMostRecentKeywordSearchTerms(
323 scoped_refptr<GetMostRecentKeywordSearchTermsRequest> request,
324 TemplateURLID keyword_id,
325 const string16& prefix,
328 void DeleteKeywordSearchTermForURL(const GURL& url);
330 #if defined(OS_ANDROID)
331 // Android Provider ---------------------------------------------------------
333 // History and bookmarks ----------------------------------------------------
334 void InsertHistoryAndBookmark(scoped_refptr<InsertRequest> request,
335 const HistoryAndBookmarkRow& row);
337 void QueryHistoryAndBookmarks(
338 scoped_refptr<QueryRequest> request,
339 const std::vector<HistoryAndBookmarkRow::ColumnID>& projections,
340 const std::string& selection,
341 const std::vector<string16>& selection_args,
342 const std::string& sort_order);
344 void UpdateHistoryAndBookmarks(scoped_refptr<UpdateRequest> request,
345 const HistoryAndBookmarkRow& row,
346 const std::string& selection,
347 const std::vector<string16>& selection_args);
349 void DeleteHistoryAndBookmarks(scoped_refptr<DeleteRequest> request,
350 const std::string& selection,
351 const std::vector<string16>& selection_args);
353 void DeleteHistory(scoped_refptr<DeleteRequest> request,
354 const std::string& selection,
355 const std::vector<string16>& selection_args);
357 // Statement ----------------------------------------------------------------
358 // Move the statement's current position.
359 void MoveStatement(scoped_refptr<MoveStatementRequest> request,
360 history::AndroidStatement* statement,
364 // Close the given statement. The ownership is transfered.
365 void CloseStatement(AndroidStatement* statement);
367 // Search terms -------------------------------------------------------------
368 void InsertSearchTerm(scoped_refptr<InsertRequest> request,
369 const SearchRow& row);
371 void UpdateSearchTerms(scoped_refptr<UpdateRequest> request,
372 const SearchRow& row,
373 const std::string& selection,
374 const std::vector<string16> selection_args);
376 void DeleteSearchTerms(scoped_refptr<DeleteRequest> request,
377 const std::string& selection,
378 const std::vector<string16> selection_args);
380 void QuerySearchTerms(scoped_refptr<QueryRequest> request,
381 const std::vector<SearchRow::ColumnID>& projections,
382 const std::string& selection,
383 const std::vector<string16>& selection_args,
384 const std::string& sort_order);
386 #endif // defined(OS_ANDROID)
388 // Generic operations --------------------------------------------------------
390 void ProcessDBTask(scoped_refptr<HistoryDBTaskRequest> request);
392 virtual bool GetAllTypedURLs(URLRows* urls);
394 virtual bool GetVisitsForURL(URLID id, VisitVector* visits);
396 // Fetches up to |max_visits| most recent visits for the passed URL.
397 virtual bool GetMostRecentVisitsForURL(URLID id,
399 VisitVector* visits);
401 virtual bool UpdateURL(URLID id, const history::URLRow& url);
403 // While adding visits in batch, the source needs to be provided.
404 virtual bool AddVisits(const GURL& url,
405 const std::vector<history::VisitInfo>& visits,
406 VisitSource visit_source);
408 virtual bool RemoveVisits(const VisitVector& visits);
410 // Returns the VisitSource associated with each one of the passed visits.
411 // If there is no entry in the map for a given visit, that means the visit
412 // was SOURCE_BROWSED. Returns false if there is no HistoryDatabase..
413 bool GetVisitsSource(const VisitVector& visits, VisitSourceMap* sources);
415 virtual bool GetURL(const GURL& url, history::URLRow* url_row);
417 // Returns the syncable service for syncing typed urls. The returned service
418 // is owned by |this| object.
419 virtual TypedUrlSyncableService* GetTypedUrlSyncableService() const;
421 // Deleting ------------------------------------------------------------------
423 virtual void DeleteURLs(const std::vector<GURL>& urls);
425 virtual void DeleteURL(const GURL& url);
427 // Calls ExpireHistoryBackend::ExpireHistoryBetween and commits the change.
428 void ExpireHistoryBetween(
429 const std::set<GURL>& restrict_urls,
430 base::Time begin_time,
431 base::Time end_time);
433 // Finds the URLs visited at |times| and expires all their visits within
434 // [|begin_time|, |end_time|). All times in |times| should be in
435 // [|begin_time|, |end_time|). This is used when expiration request is from
436 // server side, i.e. web history deletes, where only visit times (possibly
437 // incomplete) are transmitted to protect user's privacy.
438 void ExpireHistoryForTimes(const std::set<base::Time>& times,
439 base::Time begin_time, base::Time end_time);
441 // Calls ExpireHistoryBetween() once for each element in the vector.
442 // The fields of |ExpireHistoryArgs| map directly to the arguments of
443 // of ExpireHistoryBetween().
444 void ExpireHistory(const std::vector<ExpireHistoryArgs>& expire_list);
446 // Bookmarks -----------------------------------------------------------------
448 // Notification that a URL is no longer bookmarked. If there are no visits
449 // for the specified url, it is deleted.
450 void URLsNoLongerBookmarked(const std::set<GURL>& urls);
452 // Callbacks To Kill Database When It Gets Corrupted -------------------------
454 // Called by the database to report errors. Schedules one call to
455 // KillHistoryDatabase() in case of corruption.
456 void DatabaseErrorCallback(int error, sql::Statement* stmt);
458 // Raze the history database. It will be recreated in a future run. Hopefully
459 // things go better then. Continue running but without reading or storing any
460 // state into the HistoryBackend databases. Close all of the databases managed
461 // HistoryBackend as there are no provisions for accessing the other databases
462 // managed by HistoryBackend when the history database cannot be accessed.
463 void KillHistoryDatabase();
465 // Testing -------------------------------------------------------------------
467 // Sets the task to run and the message loop to run it on when this object
468 // is destroyed. See HistoryService::SetOnBackendDestroyTask for a more
469 // complete description.
470 void SetOnBackendDestroyTask(base::MessageLoop* message_loop,
471 const base::Closure& task);
473 // Adds the given rows to the database if it doesn't exist. A visit will be
474 // added for each given URL at the last visit time in the URLRow if the
475 // passed visit type != SOURCE_SYNCED (the sync code manages visits itself).
476 // Each visit will have the visit_source type set.
477 void AddPagesWithDetails(const URLRows& info, VisitSource visit_source);
479 #if defined(UNIT_TEST)
480 HistoryDatabase* db() const { return db_.get(); }
482 ExpireHistoryBackend* expire_backend() { return &expirer_; }
485 // Returns true if the passed visit time is already expired (used by the sync
486 // code to avoid syncing visits that would immediately be expired).
487 virtual bool IsExpiredVisitTime(const base::Time& time);
489 base::Time GetFirstRecordedTimeForTest() {
490 return first_recorded_time_;
494 virtual ~HistoryBackend();
497 friend class base::RefCountedThreadSafe<HistoryBackend>;
498 friend class CommitLaterTask; // The commit task needs to call Commit().
499 friend class HistoryBackendTest;
500 friend class HistoryBackendDBTest; // So the unit tests can poke our innards.
501 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, DeleteAll);
502 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, DeleteAllThenAddData);
503 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, ImportedFaviconsTest);
504 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, URLsNoLongerBookmarked);
505 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, StripUsernamePasswordTest);
506 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, DeleteThumbnailsDatabaseTest);
507 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, AddPageVisitSource);
508 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, AddPageVisitNotLastVisit);
509 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, AddPageArgsSource);
510 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, AddVisitsSource);
511 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, GetMostRecentVisits);
512 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, RemoveVisitsSource);
513 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, RemoveVisitsTransitions);
514 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, MigrationVisitSource);
515 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest,
516 SetFaviconMappingsForPageAndRedirects);
517 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest,
518 SetFaviconMappingsForPageDuplicates);
519 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, SetFaviconsDeleteBitmaps);
520 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, SetFaviconsReplaceBitmapData);
521 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest,
522 SetFaviconsSameFaviconURLForTwoPages);
523 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest,
524 UpdateFaviconMappingsAndFetchNoChange);
525 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, MergeFaviconPageURLNotInDB);
526 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, MergeFaviconPageURLInDB);
527 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, MergeFaviconMaxFaviconsPerPage);
528 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest,
529 MergeFaviconIconURLMappedToDifferentPageURL);
530 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest,
531 MergeFaviconMaxFaviconBitmapsPerIconURL);
532 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest,
533 UpdateFaviconMappingsAndFetchMultipleIconTypes);
534 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, GetFaviconsFromDBEmpty);
535 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest,
536 GetFaviconsFromDBNoFaviconBitmaps);
537 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest,
538 GetFaviconsFromDBSelectClosestMatch);
539 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, GetFaviconsFromDBSingleIconURL);
540 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, GetFaviconsFromDBIconType);
541 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, GetFaviconsFromDBExpired);
542 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest,
543 UpdateFaviconMappingsAndFetchNoDB);
544 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest,
545 CloneFaviconIsRestrictedToSameDomain);
546 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, QueryFilteredURLs);
547 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, UpdateVisitDuration);
548 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, ExpireHistoryForTimes);
549 FRIEND_TEST_ALL_PREFIXES(HistoryBackendTest, DeleteFTSIndexDatabases);
551 friend class ::TestingProfile;
553 // Computes the name of the specified database on disk.
554 base::FilePath GetArchivedFileName() const;
555 base::FilePath GetThumbnailFileName() const;
557 // Returns the name of the Favicons database. This is the new name
558 // of the Thumbnails database.
559 base::FilePath GetFaviconsFileName() const;
561 #if defined(OS_ANDROID)
562 // Returns the name of android cache database.
563 base::FilePath GetAndroidCacheFileName() const;
565 // Populate a map from a |MostVisitedURLList|. The map assigns a rank to each
566 // top URL and its redirects. This should only be done once at backend
568 // This can be removed for M31. (See issue 248761.)
570 void PopulateMostVisitedURLMap();
571 // Record counts of page visits by rank. If a url is not ranked, record the
572 // page visit in a slot corresponding to |max_top_url_count|, which should
573 // be one greater than the largest rank of any url in |top_urls|.
574 // This can be removed for M31. (See issue 248761.)
575 void RecordTopPageVisitStats(const GURL& url);
579 friend class URLQuerier;
581 // Does the work of Init.
582 void InitImpl(const std::string& languages);
584 // Called when the system is under memory pressure.
585 void OnMemoryPressure(
586 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
588 // Closes all databases managed by HistoryBackend. Commits any pending
590 void CloseAllDatabases();
592 // Adds a single visit to the database, updating the URL information such
593 // as visit and typed count. The visit ID of the added visit and the URL ID
594 // of the associated URL (whether added or not) is returned. Both values will
597 // This does not schedule database commits, it is intended to be used as a
598 // subroutine for AddPage only. It also assumes the database is valid.
599 std::pair<URLID, VisitID> AddPageVisit(const GURL& url,
601 VisitID referring_visit,
602 content::PageTransition transition,
603 VisitSource visit_source);
605 // Returns a redirect chain in |redirects| for the VisitID
606 // |cur_visit|. |cur_visit| is assumed to be valid. Assumes that
607 // this HistoryBackend object has been Init()ed successfully.
608 void GetRedirectsFromSpecificVisit(
609 VisitID cur_visit, history::RedirectList* redirects);
611 // Similar to the above function except returns a redirect list ending
613 void GetRedirectsToSpecificVisit(
614 VisitID cur_visit, history::RedirectList* redirects);
616 // Update the visit_duration information in visits table.
617 void UpdateVisitDuration(VisitID visit_id, const base::Time end_ts);
619 // Querying ------------------------------------------------------------------
621 // Backends for QueryHistory. *Basic() handles queries that are not
622 // text search queries and can just be given directly to the history DB.
623 // The *Text() version performs a brute force query of the history DB to
624 // search for results which match the given text query.
625 // Both functions assume QueryHistory already checked the DB for validity.
626 void QueryHistoryBasic(URLDatabase* url_db, VisitDatabase* visit_db,
627 const QueryOptions& options, QueryResults* result);
628 void QueryHistoryText(URLDatabase* url_db,
629 VisitDatabase* visit_db,
630 const string16& text_query,
631 const QueryOptions& options,
632 QueryResults* result);
634 // Committing ----------------------------------------------------------------
636 // We always keep a transaction open on the history database so that multiple
637 // transactions can be batched. Periodically, these are flushed (use
638 // ScheduleCommit). This function does the commit to write any new changes to
639 // disk and opens a new transaction. This will be called automatically by
640 // ScheduleCommit, or it can be called explicitly if a caller really wants
641 // to write something to disk.
644 // Schedules a commit to happen in the future. We do this so that many
645 // operations over a period of time will be batched together. If there is
646 // already a commit scheduled for the future, this will do nothing.
647 void ScheduleCommit();
649 // Cancels the scheduled commit, if any. If there is no scheduled commit,
651 void CancelScheduledCommit();
653 // Segments ------------------------------------------------------------------
655 // Walks back a segment chain to find the last visit with a non null segment
656 // id and returns it. If there is none found, returns 0.
657 SegmentID GetLastSegmentID(VisitID from_visit);
659 // Update the segment information. This is called internally when a page is
660 // added. Return the segment id of the segment that has been updated.
661 SegmentID UpdateSegments(const GURL& url,
664 content::PageTransition transition_type,
665 const base::Time ts);
667 // Favicons ------------------------------------------------------------------
669 // Used by both UpdateFaviconMappingsAndFetch and GetFavicons.
670 // If |page_url| is non-null, the icon urls for |page_url| (and all
671 // redirects) are set to the subset of |icon_urls| for which icons are
672 // already stored in the database.
673 // If |page_url| is non-null, |icon_types| can be multiple icon types
674 // only if |icon_types| == TOUCH_ICON | TOUCH_PRECOMPOSED_ICON.
675 // If multiple icon types are specified, |page_url| will be mapped to the
676 // icon URLs of the largest type available in the database.
677 void UpdateFaviconMappingsAndFetchImpl(
678 const GURL* page_url,
679 const std::vector<GURL>& icon_urls,
681 int desired_size_in_dip,
682 const std::vector<ui::ScaleFactor>& desired_scale_factors,
683 std::vector<chrome::FaviconBitmapResult>* results);
685 // Set the favicon bitmaps for |icon_id|.
686 // For each entry in |favicon_bitmap_data|, if a favicon bitmap already
687 // exists at the entry's pixel size, replace the favicon bitmap's data with
688 // the entry's bitmap data. Otherwise add a new favicon bitmap.
689 // Any favicon bitmaps already mapped to |icon_id| whose pixel sizes are not
690 // in |favicon_bitmap_data| are deleted.
691 // If not NULL, |favicon_bitmaps_changed| is set to whether any of the bitmap
692 // data at |icon_id| is changed as a result of calling this method.
693 // Computing |favicon_bitmaps_changed| requires additional database queries
694 // so should be avoided if unnecessary.
695 void SetFaviconBitmaps(
696 chrome::FaviconID icon_id,
697 const std::vector<chrome::FaviconBitmapData>& favicon_bitmap_data,
698 bool* favicon_bitmaps_changed);
700 // Returns true if |favicon_bitmap_data| passed to SetFavicons() is valid.
702 // 1) |favicon_bitmap_data| contains no more than
703 // kMaxFaviconsPerPage unique icon URLs.
704 // kMaxFaviconBitmapsPerIconURL favicon bitmaps for each icon URL.
705 // 2) FaviconBitmapData::bitmap_data contains non NULL bitmap data.
706 bool ValidateSetFaviconsParams(
707 const std::vector<chrome::FaviconBitmapData>& favicon_bitmap_data) const;
709 // Returns true if the bitmap data at |bitmap_id| equals |new_bitmap_data|.
710 bool IsFaviconBitmapDataEqual(
711 FaviconBitmapID bitmap_id,
712 const scoped_refptr<base::RefCountedMemory>& new_bitmap_data);
714 // Returns true if there are favicons for |page_url| and one of the types in
716 // |favicon_bitmap_results| is set to the favicon bitmaps which most closely
717 // match |desired_size_in_dip| and |desired_scale_factors|. If
718 // |desired_size_in_dip| is 0, the largest favicon bitmap with one of the icon
719 // types in |icon_types| is returned. If |icon_types| contains multiple icon
720 // types and there are several matched icon types in the database, results
721 // will only be returned for a single icon type in the priority of
722 // TOUCH_PRECOMPOSED_ICON, TOUCH_ICON, and FAVICON. See the comment for
723 // GetFaviconResultsForBestMatch() for more details on how
724 // |favicon_bitmap_results| is constructed.
725 bool GetFaviconsFromDB(
726 const GURL& page_url,
728 const int desired_size_in_dip,
729 const std::vector<ui::ScaleFactor>& desired_scale_factors,
730 std::vector<chrome::FaviconBitmapResult>* favicon_bitmap_results);
732 // Returns the favicon bitmaps which most closely match |desired_size_in_dip|
733 // and |desired_scale_factors| in |favicon_bitmap_results|. If
734 // |desired_size_in_dip| is 0, only the largest favicon bitmap is returned.
735 // Goodness is computed via SelectFaviconBitmapIDs(). It is computed on a
736 // per favicon id basis, thus all |favicon_bitmap_results| are guaranteed to
737 // be for the same FaviconID. |favicon_bitmap_results| will have at most one
738 // entry for each desired scale factor. There will be less entries if the same
739 // favicon bitmap is the best result for multiple scale factors.
740 // Returns true if there were no errors.
741 bool GetFaviconBitmapResultsForBestMatch(
742 const std::vector<chrome::FaviconID>& candidate_favicon_ids,
743 int desired_size_in_dip,
744 const std::vector<ui::ScaleFactor>& desired_scale_factors,
745 std::vector<chrome::FaviconBitmapResult>* favicon_bitmap_results);
747 // Maps the favicon ids in |icon_ids| to |page_url| (and all redirects)
749 // Returns true if the mappings for the page or any of its redirects were
751 bool SetFaviconMappingsForPageAndRedirects(
752 const GURL& page_url,
753 chrome::IconType icon_type,
754 const std::vector<chrome::FaviconID>& icon_ids);
756 // Maps the favicon ids in |icon_ids| to |page_url| for |icon_type|.
757 // Returns true if the function changed some of |page_url|'s mappings.
758 bool SetFaviconMappingsForPage(
759 const GURL& page_url,
760 chrome::IconType icon_type,
761 const std::vector<chrome::FaviconID>& icon_ids);
763 // Returns all the page URLs in the redirect chain for |page_url|. If there
764 // are no known redirects for |page_url|, returns a vector with |page_url|.
765 void GetCachedRecentRedirects(const GURL& page_url,
766 history::RedirectList* redirect_list);
768 // Send notification that the favicon has changed for |page_url| and all its
770 void SendFaviconChangedNotificationForPageAndRedirects(
771 const GURL& page_url);
773 // Generic stuff -------------------------------------------------------------
775 // Processes the next scheduled HistoryDBTask, scheduling this method
776 // to be invoked again if there are more tasks that need to run.
777 void ProcessDBTaskImpl();
779 // Release all tasks in history_db_tasks_ and clears it.
780 void ReleaseDBTasks();
782 // Schedules a broadcast of the given notification on the main thread. The
783 // details argument will have ownership taken by this function (it will be
784 // sent to the main thread and deleted there).
785 virtual void BroadcastNotifications(int type,
786 HistoryDetails* details_deleted) OVERRIDE;
788 virtual void NotifySyncURLsDeleted(bool all_history,
790 URLRows* rows) OVERRIDE;
792 // Deleting all history ------------------------------------------------------
794 // Deletes all history. This is a special case of deleting that is separated
795 // from our normal dependency-following method for performance reasons. The
796 // logic lives here instead of ExpireHistoryBackend since it will cause
797 // re-initialization of some databases such as Thumbnails or Archived that
798 // could fail. When these databases are not valid, our pointers must be NULL,
799 // so we need to handle this type of operation to keep the pointers in sync.
800 void DeleteAllHistory();
802 // Given a vector of all URLs that we will keep, removes all thumbnails
803 // referenced by any URL, and also all favicons that aren't used by those
805 bool ClearAllThumbnailHistory(const URLRows& kept_urls);
807 // Deletes all information in the history database, except for the supplied
808 // set of URLs in the URL table (these should correspond to the bookmarked
811 // The IDs of the URLs may change.
812 bool ClearAllMainHistory(const URLRows& kept_urls);
814 // Deletes the FTS index database files, which are no longer used.
815 void DeleteFTSIndexDatabases();
817 // Returns the BookmarkService, blocking until it is loaded. This may return
818 // NULL during testing.
819 BookmarkService* GetBookmarkService();
821 // Notify any observers of an addition to the visit database.
822 void NotifyVisitObservers(const VisitRow& visit);
824 // Data ----------------------------------------------------------------------
826 // Delegate. See the class definition above for more information. This will
827 // be NULL before Init is called and after Cleanup, but is guaranteed
828 // non-NULL in between.
829 scoped_ptr<Delegate> delegate_;
831 // The id of this class, given in creation and used for identifying the
832 // backend when calling the delegate.
835 // Directory where database files will be stored.
836 base::FilePath history_dir_;
838 // The history/thumbnail databases. Either MAY BE NULL if the database could
839 // not be opened, all users must first check for NULL and return immediately
840 // if it is. The thumbnail DB may be NULL when the history one isn't, but not
842 scoped_ptr<HistoryDatabase> db_;
843 bool scheduled_kill_db_; // Database is being killed due to error.
844 scoped_ptr<ThumbnailDatabase> thumbnail_db_;
846 // Stores old history in a larger, slower database.
847 scoped_ptr<ArchivedDatabase> archived_db_;
849 // Helper to collect page data for vending to history_publisher_.
850 scoped_ptr<PageCollector> page_collector_;
852 // Manages expiration between the various databases.
853 ExpireHistoryBackend expirer_;
855 // A commit has been scheduled to occur sometime in the future. We can check
856 // non-null-ness to see if there is a commit scheduled in the future, and we
857 // can use the pointer to cancel the scheduled commit. There can be only one
858 // scheduled commit at a time (see ScheduleCommit).
859 scoped_refptr<CommitLaterTask> scheduled_commit_;
861 // Maps recent redirect destination pages to the chain of redirects that
862 // brought us to there. Pages that did not have redirects or were not the
863 // final redirect in a chain will not be in this list, as well as pages that
864 // redirected "too long" ago (as determined by ExpireOldRedirects above).
865 // It is used to set titles & favicons for redirects to that of the
868 // As with AddPage, the last item in the redirect chain will be the
869 // destination of the redirect (i.e., the key into recent_redirects_);
870 typedef base::MRUCache<GURL, history::RedirectList> RedirectCache;
871 RedirectCache recent_redirects_;
873 // Timestamp of the first entry in our database.
874 base::Time first_recorded_time_;
876 // When set, this is the task that should be invoked on destruction.
877 base::MessageLoop* backend_destroy_message_loop_;
878 base::Closure backend_destroy_task_;
880 // Tracks page transition types.
881 VisitTracker tracker_;
883 // A boolean variable to track whether we have already purged obsolete segment
885 bool segment_queried_;
887 // HistoryDBTasks to run. Be sure to AddRef when adding, and Release when
889 std::list<HistoryDBTaskRequest*> db_task_requests_;
891 // Used to determine if a URL is bookmarked. This is owned by the Profile and
892 // may be NULL (during testing).
894 // Use GetBookmarkService to access this, which makes sure the service is
896 BookmarkService* bookmark_service_;
898 // Publishes the history to all indexers which are registered to receive
899 // history data from us. Can be NULL if there are no listeners.
900 scoped_ptr<HistoryPublisher> history_publisher_;
902 #if defined(OS_ANDROID)
903 // Used to provide the Android ContentProvider APIs.
904 scoped_ptr<AndroidProviderBackend> android_provider_backend_;
906 // Used to provide UMA on the number of page visits that are to the most
907 // visited URLs. This is here because the backend both has access to this
908 // information and is notified of page visits. The top sites service should
909 // be used instead whenever possible.
910 std::map<GURL, int> most_visited_urls_map_;
913 // Used to manage syncing of the typed urls datatype. This will be NULL
914 // before Init is called.
915 scoped_ptr<TypedUrlSyncableService> typed_url_syncable_service_;
917 // Listens for the system being under memory pressure.
918 scoped_ptr<base::MemoryPressureListener> memory_pressure_listener_;
920 DISALLOW_COPY_AND_ASSIGN(HistoryBackend);
923 } // namespace history
925 #endif // CHROME_BROWSER_HISTORY_HISTORY_BACKEND_H_