2 * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "WebKitDLL.h"
28 #include "WebHistory.h"
30 #include "CFDictionaryPropertyBag.h"
31 #include "MemoryStream.h"
33 #include "MarshallingHelpers.h"
34 #include "WebHistoryItem.h"
36 #include "WebNotificationCenter.h"
37 #include "WebPreferences.h"
38 #include <CoreFoundation/CoreFoundation.h>
39 #include <WebCore/HistoryItem.h>
40 #include <WebCore/HistoryPropertyList.h>
41 #include <WebCore/KURL.h>
42 #include <WebCore/PageGroup.h>
43 #include <WebCore/SharedBuffer.h>
45 #include <wtf/StdLibExtras.h>
46 #include <wtf/Vector.h>
48 using namespace WebCore;
51 CFStringRef DatesArrayKey = CFSTR("WebHistoryDates");
52 CFStringRef FileVersionKey = CFSTR("WebHistoryFileVersion");
54 #define currentFileVersion 1
56 class WebHistoryWriter : public HistoryPropertyListWriter {
58 WebHistoryWriter(const WebHistory::DateToEntriesMap&);
61 virtual void writeHistoryItems(BinaryPropertyListObjectStream&);
63 const WebHistory::DateToEntriesMap& m_entriesByDate;
64 Vector<WebHistory::DateKey> m_dateKeys;
67 WebHistoryWriter::WebHistoryWriter(const WebHistory::DateToEntriesMap& entriesByDate)
68 : m_entriesByDate(entriesByDate)
70 copyKeysToVector(m_entriesByDate, m_dateKeys);
71 sort(m_dateKeys.begin(), m_dateKeys.end());
74 void WebHistoryWriter::writeHistoryItems(BinaryPropertyListObjectStream& stream)
76 for (int dateIndex = m_dateKeys.size() - 1; dateIndex >= 0; --dateIndex) {
77 // get the entries for that date
78 CFArrayRef entries = m_entriesByDate.get(m_dateKeys[dateIndex]).get();
79 CFIndex entriesCount = CFArrayGetCount(entries);
80 for (CFIndex j = entriesCount - 1; j >= 0; --j) {
81 IWebHistoryItem* item = (IWebHistoryItem*) CFArrayGetValueAtIndex(entries, j);
82 COMPtr<WebHistoryItem> webItem(Query, item);
86 writeHistoryItem(stream, webItem->historyItem());
91 static bool areEqualOrClose(double d1, double d2)
94 return (diff < .000001 && diff > -.000001);
97 static COMPtr<CFDictionaryPropertyBag> createUserInfoFromArray(BSTR notificationStr, CFArrayRef arrayItem)
99 RetainPtr<CFMutableDictionaryRef> dictionary(AdoptCF,
100 CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
102 RetainPtr<CFStringRef> key(AdoptCF, MarshallingHelpers::BSTRToCFStringRef(notificationStr));
103 CFDictionaryAddValue(dictionary.get(), key.get(), arrayItem);
105 COMPtr<CFDictionaryPropertyBag> result = CFDictionaryPropertyBag::createInstance();
106 result->setDictionary(dictionary.get());
110 static COMPtr<CFDictionaryPropertyBag> createUserInfoFromHistoryItem(BSTR notificationStr, IWebHistoryItem* item)
112 // reference counting of item added to the array is managed by the CFArray value callbacks
113 RetainPtr<CFArrayRef> itemList(AdoptCF, CFArrayCreate(0, (const void**) &item, 1, &MarshallingHelpers::kIUnknownArrayCallBacks));
114 COMPtr<CFDictionaryPropertyBag> info = createUserInfoFromArray(notificationStr, itemList.get());
118 // WebHistory -----------------------------------------------------------------
120 WebHistory::WebHistory()
125 gClassNameCount.add("WebHistory");
127 m_entriesByURL.adoptCF(CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &MarshallingHelpers::kIUnknownDictionaryValueCallBacks));
129 m_preferences = WebPreferences::sharedStandardPreferences();
132 WebHistory::~WebHistory()
135 gClassNameCount.remove("WebHistory");
138 WebHistory* WebHistory::createInstance()
140 WebHistory* instance = new WebHistory();
145 HRESULT WebHistory::postNotification(NotificationType notifyType, IPropertyBag* userInfo /*=0*/)
147 IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
148 HRESULT hr = nc->postNotificationName(getNotificationString(notifyType), static_cast<IWebHistory*>(this), userInfo);
155 BSTR WebHistory::getNotificationString(NotificationType notifyType)
157 static BSTR keys[6] = {0};
159 keys[0] = SysAllocString(WebHistoryItemsAddedNotification);
160 keys[1] = SysAllocString(WebHistoryItemsRemovedNotification);
161 keys[2] = SysAllocString(WebHistoryAllItemsRemovedNotification);
162 keys[3] = SysAllocString(WebHistoryLoadedNotification);
163 keys[4] = SysAllocString(WebHistoryItemsDiscardedWhileLoadingNotification);
164 keys[5] = SysAllocString(WebHistorySavedNotification);
166 return keys[notifyType];
169 // IUnknown -------------------------------------------------------------------
171 HRESULT STDMETHODCALLTYPE WebHistory::QueryInterface(REFIID riid, void** ppvObject)
174 if (IsEqualGUID(riid, CLSID_WebHistory))
176 else if (IsEqualGUID(riid, IID_IUnknown))
177 *ppvObject = static_cast<IWebHistory*>(this);
178 else if (IsEqualGUID(riid, IID_IWebHistory))
179 *ppvObject = static_cast<IWebHistory*>(this);
180 else if (IsEqualGUID(riid, IID_IWebHistoryPrivate))
181 *ppvObject = static_cast<IWebHistoryPrivate*>(this);
183 return E_NOINTERFACE;
189 ULONG STDMETHODCALLTYPE WebHistory::AddRef(void)
194 ULONG STDMETHODCALLTYPE WebHistory::Release(void)
196 ULONG newRef = --m_refCount;
203 // IWebHistory ----------------------------------------------------------------
205 static inline COMPtr<WebHistory>& sharedHistoryStorage()
207 DEFINE_STATIC_LOCAL(COMPtr<WebHistory>, sharedHistory, ());
208 return sharedHistory;
211 WebHistory* WebHistory::sharedHistory()
213 return sharedHistoryStorage().get();
216 HRESULT STDMETHODCALLTYPE WebHistory::optionalSharedHistory(
217 /* [retval][out] */ IWebHistory** history)
219 *history = sharedHistory();
221 (*history)->AddRef();
225 HRESULT STDMETHODCALLTYPE WebHistory::setOptionalSharedHistory(
226 /* [in] */ IWebHistory* history)
228 if (sharedHistoryStorage() == history)
230 sharedHistoryStorage().query(history);
231 PageGroup::setShouldTrackVisitedLinks(sharedHistoryStorage());
232 PageGroup::removeAllVisitedLinks();
236 HRESULT STDMETHODCALLTYPE WebHistory::loadFromURL(
238 /* [out] */ IWebError** error,
239 /* [retval][out] */ BOOL* succeeded)
242 RetainPtr<CFMutableArrayRef> discardedItems(AdoptCF,
243 CFArrayCreateMutable(0, 0, &MarshallingHelpers::kIUnknownArrayCallBacks));
245 RetainPtr<CFURLRef> urlRef(AdoptCF, MarshallingHelpers::BSTRToCFURLRef(url));
247 hr = loadHistoryGutsFromURL(urlRef.get(), discardedItems.get(), error);
251 hr = postNotification(kWebHistoryLoadedNotification);
255 if (CFArrayGetCount(discardedItems.get()) > 0) {
256 COMPtr<CFDictionaryPropertyBag> userInfo = createUserInfoFromArray(getNotificationString(kWebHistoryItemsDiscardedWhileLoadingNotification), discardedItems.get());
257 hr = postNotification(kWebHistoryItemsDiscardedWhileLoadingNotification, userInfo.get());
264 *succeeded = SUCCEEDED(hr);
268 static CFDictionaryRef createHistoryListFromStream(CFReadStreamRef stream, CFPropertyListFormat format)
270 return (CFDictionaryRef)CFPropertyListCreateFromStream(0, stream, 0, kCFPropertyListImmutable, &format, 0);
273 HRESULT WebHistory::loadHistoryGutsFromURL(CFURLRef url, CFMutableArrayRef discardedItems, IWebError** /*error*/) //FIXME
275 CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0 | kCFPropertyListXMLFormat_v1_0;
277 int numberOfItemsLoaded = 0;
279 RetainPtr<CFReadStreamRef> stream(AdoptCF, CFReadStreamCreateWithFile(0, url));
283 if (!CFReadStreamOpen(stream.get()))
286 RetainPtr<CFDictionaryRef> historyList(AdoptCF, createHistoryListFromStream(stream.get(), format));
287 CFReadStreamClose(stream.get());
292 CFNumberRef fileVersionObject = (CFNumberRef)CFDictionaryGetValue(historyList.get(), FileVersionKey);
294 if (!CFNumberGetValue(fileVersionObject, kCFNumberIntType, &fileVersion))
297 if (fileVersion > currentFileVersion)
300 CFArrayRef datesArray = (CFArrayRef)CFDictionaryGetValue(historyList.get(), DatesArrayKey);
303 hr = historyItemLimit(&itemCountLimit);
307 CFAbsoluteTime limitDate;
308 hr = ageLimitDate(&limitDate);
312 bool ageLimitPassed = false;
313 bool itemLimitPassed = false;
315 CFIndex itemCount = CFArrayGetCount(datesArray);
316 for (CFIndex i = 0; i < itemCount; ++i) {
317 CFDictionaryRef itemAsDictionary = (CFDictionaryRef)CFArrayGetValueAtIndex(datesArray, i);
318 COMPtr<WebHistoryItem> item(AdoptCOM, WebHistoryItem::createInstance());
319 hr = item->initFromDictionaryRepresentation((void*)itemAsDictionary);
323 // item without URL is useless; data on disk must have been bad; ignore
325 hr = item->hasURLString(&hasURL);
330 // Test against date limit. Since the items are ordered newest to oldest, we can stop comparing
331 // once we've found the first item that's too old.
332 if (!ageLimitPassed) {
333 DATE lastVisitedTime;
334 hr = item->lastVisitedTimeInterval(&lastVisitedTime);
337 if (timeToDate(MarshallingHelpers::DATEToCFAbsoluteTime(lastVisitedTime)) <= limitDate)
338 ageLimitPassed = true;
340 if (ageLimitPassed || itemLimitPassed)
341 CFArrayAppendValue(discardedItems, item.get());
344 addItem(item.get(), true, &added); // ref is added inside addItem
346 ++numberOfItemsLoaded;
347 if (numberOfItemsLoaded == itemCountLimit)
348 itemLimitPassed = true;
355 HRESULT STDMETHODCALLTYPE WebHistory::saveToURL(
357 /* [out] */ IWebError** error,
358 /* [retval][out] */ BOOL* succeeded)
361 RetainPtr<CFURLRef> urlRef(AdoptCF, MarshallingHelpers::BSTRToCFURLRef(url));
363 hr = saveHistoryGuts(urlRef.get(), error);
366 *succeeded = SUCCEEDED(hr);
368 hr = postNotification(kWebHistorySavedNotification);
373 HRESULT WebHistory::saveHistoryGuts(CFURLRef url, IWebError** error)
377 // FIXME: Correctly report error when new API is ready.
381 RetainPtr<CFDataRef> data = this->data();
383 RetainPtr<CFWriteStreamRef> stream(AdoptCF, CFWriteStreamCreateWithFile(kCFAllocatorDefault, url));
387 if (!CFWriteStreamOpen(stream.get()))
390 const UInt8* dataPtr = CFDataGetBytePtr(data.get());
391 CFIndex length = CFDataGetLength(data.get());
394 CFIndex bytesWritten = CFWriteStreamWrite(stream.get(), dataPtr, length);
395 if (bytesWritten <= 0) {
399 dataPtr += bytesWritten;
400 length -= bytesWritten;
403 CFWriteStreamClose(stream.get());
408 HRESULT STDMETHODCALLTYPE WebHistory::addItems(
409 /* [in] */ int itemCount,
410 /* [in] */ IWebHistoryItem** items)
412 // There is no guarantee that the incoming entries are in any particular
413 // order, but if this is called with a set of entries that were created by
414 // iterating through the results of orderedLastVisitedDays and orderedItemsLastVisitedOnDay
415 // then they will be ordered chronologically from newest to oldest. We can make adding them
416 // faster (fewer compares) by inserting them from oldest to newest.
419 for (int i = itemCount - 1; i >= 0; --i) {
420 hr = addItem(items[i], false, 0);
428 HRESULT STDMETHODCALLTYPE WebHistory::removeItems(
429 /* [in] */ int itemCount,
430 /* [in] */ IWebHistoryItem** items)
433 for (int i = 0; i < itemCount; ++i) {
434 hr = removeItem(items[i]);
442 HRESULT STDMETHODCALLTYPE WebHistory::removeAllItems( void)
444 m_entriesByDate.clear();
445 m_orderedLastVisitedDays.clear();
447 CFIndex itemCount = CFDictionaryGetCount(m_entriesByURL.get());
448 Vector<IWebHistoryItem*> itemsVector(itemCount);
449 CFDictionaryGetKeysAndValues(m_entriesByURL.get(), 0, (const void**)itemsVector.data());
450 RetainPtr<CFArrayRef> allItems(AdoptCF, CFArrayCreate(kCFAllocatorDefault, (const void**)itemsVector.data(), itemCount, &MarshallingHelpers::kIUnknownArrayCallBacks));
452 CFDictionaryRemoveAllValues(m_entriesByURL.get());
454 PageGroup::removeAllVisitedLinks();
456 COMPtr<CFDictionaryPropertyBag> userInfo = createUserInfoFromArray(getNotificationString(kWebHistoryAllItemsRemovedNotification), allItems.get());
457 return postNotification(kWebHistoryAllItemsRemovedNotification, userInfo.get());
460 HRESULT STDMETHODCALLTYPE WebHistory::orderedLastVisitedDays(
461 /* [out][in] */ int* count,
462 /* [in] */ DATE* calendarDates)
464 int dateCount = m_entriesByDate.size();
465 if (!calendarDates) {
470 if (*count < dateCount) {
476 if (!m_orderedLastVisitedDays) {
477 m_orderedLastVisitedDays = adoptArrayPtr(new DATE[dateCount]);
478 DateToEntriesMap::const_iterator::Keys end = m_entriesByDate.end().keys();
480 for (DateToEntriesMap::const_iterator::Keys it = m_entriesByDate.begin().keys(); it != end; ++it, ++i)
481 m_orderedLastVisitedDays[i] = MarshallingHelpers::CFAbsoluteTimeToDATE(*it);
482 // Use std::greater to sort the days in descending order (i.e., most-recent first).
483 sort(m_orderedLastVisitedDays.get(), m_orderedLastVisitedDays.get() + dateCount, greater<DATE>());
486 memcpy(calendarDates, m_orderedLastVisitedDays.get(), dateCount * sizeof(DATE));
490 HRESULT STDMETHODCALLTYPE WebHistory::orderedItemsLastVisitedOnDay(
491 /* [out][in] */ int* count,
492 /* [in] */ IWebHistoryItem** items,
493 /* [in] */ DATE calendarDate)
496 if (!findKey(&dateKey, MarshallingHelpers::DATEToCFAbsoluteTime(calendarDate))) {
501 CFArrayRef entries = m_entriesByDate.get(dateKey).get();
507 int newCount = CFArrayGetCount(entries);
514 if (*count < newCount) {
520 for (int i = 0; i < newCount; i++) {
521 IWebHistoryItem* item = (IWebHistoryItem*)CFArrayGetValueAtIndex(entries, i);
529 HRESULT STDMETHODCALLTYPE WebHistory::allItems(
530 /* [out][in] */ int* count,
531 /* [out][retval] */ IWebHistoryItem** items)
533 int entriesByURLCount = CFDictionaryGetCount(m_entriesByURL.get());
536 *count = entriesByURLCount;
540 if (*count < entriesByURLCount) {
541 *count = entriesByURLCount;
545 *count = entriesByURLCount;
546 CFDictionaryGetKeysAndValues(m_entriesByURL.get(), 0, (const void**)items);
547 for (int i = 0; i < entriesByURLCount; i++)
553 HRESULT WebHistory::data(IStream** stream)
560 RetainPtr<CFDataRef> historyData = data();
564 COMPtr<MemoryStream> result = MemoryStream::createInstance(SharedBuffer::wrapCFData(historyData.get()));
565 return result.copyRefTo(stream);
568 HRESULT WebHistory::setVisitedLinkTrackingEnabled(BOOL visitedLinkTrackingEnabled)
570 PageGroup::setShouldTrackVisitedLinks(visitedLinkTrackingEnabled);
574 HRESULT WebHistory::removeAllVisitedLinks()
576 PageGroup::removeAllVisitedLinks();
580 HRESULT STDMETHODCALLTYPE WebHistory::setHistoryItemLimit(
581 /* [in] */ int limit)
585 return m_preferences->setHistoryItemLimit(limit);
588 HRESULT STDMETHODCALLTYPE WebHistory::historyItemLimit(
589 /* [retval][out] */ int* limit)
593 return m_preferences->historyItemLimit(limit);
596 HRESULT STDMETHODCALLTYPE WebHistory::setHistoryAgeInDaysLimit(
597 /* [in] */ int limit)
601 return m_preferences->setHistoryAgeInDaysLimit(limit);
604 HRESULT STDMETHODCALLTYPE WebHistory::historyAgeInDaysLimit(
605 /* [retval][out] */ int* limit)
609 return m_preferences->historyAgeInDaysLimit(limit);
612 HRESULT WebHistory::removeItem(IWebHistoryItem* entry)
617 hr = entry->URLString(&urlBStr);
621 RetainPtr<CFStringRef> urlString(AdoptCF, MarshallingHelpers::BSTRToCFStringRef(urlBStr));
622 SysFreeString(urlBStr);
624 // If this exact object isn't stored, then make no change.
625 // FIXME: Is this the right behavior if this entry isn't present, but another entry for the same URL is?
626 // Maybe need to change the API to make something like removeEntryForURLString public instead.
627 IWebHistoryItem *matchingEntry = (IWebHistoryItem*)CFDictionaryGetValue(m_entriesByURL.get(), urlString.get());
628 if (matchingEntry != entry)
631 hr = removeItemForURLString(urlString.get());
635 COMPtr<CFDictionaryPropertyBag> userInfo = createUserInfoFromHistoryItem(
636 getNotificationString(kWebHistoryItemsRemovedNotification), entry);
637 hr = postNotification(kWebHistoryItemsRemovedNotification, userInfo.get());
642 HRESULT WebHistory::addItem(IWebHistoryItem* entry, bool discardDuplicate, bool* added)
650 hr = entry->URLString(&urlBStr);
654 RetainPtr<CFStringRef> urlString(AdoptCF, MarshallingHelpers::BSTRToCFStringRef(urlBStr));
655 SysFreeString(urlBStr);
657 COMPtr<IWebHistoryItem> oldEntry((IWebHistoryItem*) CFDictionaryGetValue(
658 m_entriesByURL.get(), urlString.get()));
661 if (discardDuplicate) {
667 removeItemForURLString(urlString.get());
669 // If we already have an item with this URL, we need to merge info that drives the
670 // URL autocomplete heuristics from that item into the new one.
671 IWebHistoryItemPrivate* entryPriv;
672 hr = entry->QueryInterface(IID_IWebHistoryItemPrivate, (void**)&entryPriv);
674 entryPriv->mergeAutoCompleteHints(oldEntry.get());
675 entryPriv->Release();
679 hr = addItemToDateCaches(entry);
683 CFDictionarySetValue(m_entriesByURL.get(), urlString.get(), entry);
685 COMPtr<CFDictionaryPropertyBag> userInfo = createUserInfoFromHistoryItem(
686 getNotificationString(kWebHistoryItemsAddedNotification), entry);
687 hr = postNotification(kWebHistoryItemsAddedNotification, userInfo.get());
695 void WebHistory::visitedURL(const KURL& url, const String& title, const String& httpMethod, bool wasFailure, bool increaseVisitCount)
697 RetainPtr<CFStringRef> urlString(AdoptCF, url.string().createCFString());
699 IWebHistoryItem* entry = (IWebHistoryItem*) CFDictionaryGetValue(m_entriesByURL.get(), urlString.get());
701 COMPtr<IWebHistoryItemPrivate> entryPrivate(Query, entry);
705 // Remove the item from date caches before changing its last visited date. Otherwise we might get duplicate entries
706 // as seen in <rdar://problem/6570573>.
707 removeItemFromDateCaches(entry);
708 entryPrivate->visitedWithTitle(BString(title), increaseVisitCount);
710 COMPtr<WebHistoryItem> item(AdoptCOM, WebHistoryItem::createInstance());
716 SYSTEMTIME currentTime;
717 GetSystemTime(¤tTime);
719 if (!SystemTimeToVariantTime(¤tTime, &lastVisited))
722 if (FAILED(entry->initWithURLString(BString(url.string()), BString(title), lastVisited)))
725 item->recordInitialVisit();
727 CFDictionarySetValue(m_entriesByURL.get(), urlString.get(), entry);
730 addItemToDateCaches(entry);
732 COMPtr<IWebHistoryItemPrivate> entryPrivate(Query, entry);
736 entryPrivate->setLastVisitWasFailure(wasFailure);
737 if (!httpMethod.isEmpty())
738 entryPrivate->setLastVisitWasHTTPNonGet(!equalIgnoringCase(httpMethod, "GET") && url.protocolIsInHTTPFamily());
740 COMPtr<WebHistoryItem> item(Query, entry);
741 item->historyItem()->setRedirectURLs(nullptr);
743 COMPtr<CFDictionaryPropertyBag> userInfo = createUserInfoFromHistoryItem(
744 getNotificationString(kWebHistoryItemsAddedNotification), entry);
745 postNotification(kWebHistoryItemsAddedNotification, userInfo.get());
748 HRESULT WebHistory::itemForURLString(
749 /* [in] */ CFStringRef urlString,
750 /* [retval][out] */ IWebHistoryItem** item) const
756 IWebHistoryItem* foundItem = (IWebHistoryItem*) CFDictionaryGetValue(m_entriesByURL.get(), urlString);
765 HRESULT STDMETHODCALLTYPE WebHistory::itemForURL(
767 /* [retval][out] */ IWebHistoryItem** item)
769 RetainPtr<CFStringRef> urlString(AdoptCF, MarshallingHelpers::BSTRToCFStringRef(url));
770 return itemForURLString(urlString.get(), item);
773 HRESULT WebHistory::removeItemForURLString(CFStringRef urlString)
775 IWebHistoryItem* entry = (IWebHistoryItem*) CFDictionaryGetValue(m_entriesByURL.get(), urlString);
779 HRESULT hr = removeItemFromDateCaches(entry);
780 CFDictionaryRemoveValue(m_entriesByURL.get(), urlString);
782 if (!CFDictionaryGetCount(m_entriesByURL.get()))
783 PageGroup::removeAllVisitedLinks();
788 COMPtr<IWebHistoryItem> WebHistory::itemForURLString(const String& urlString) const
790 RetainPtr<CFStringRef> urlCFString(AdoptCF, urlString.createCFString());
793 COMPtr<IWebHistoryItem> item;
794 if (FAILED(itemForURLString(urlCFString.get(), &item)))
799 HRESULT WebHistory::addItemToDateCaches(IWebHistoryItem* entry)
803 DATE lastVisitedCOMTime;
804 entry->lastVisitedTimeInterval(&lastVisitedCOMTime);
807 if (findKey(&dateKey, MarshallingHelpers::DATEToCFAbsoluteTime(lastVisitedCOMTime))) {
808 // other entries already exist for this date
809 hr = insertItem(entry, dateKey);
811 ASSERT(!m_entriesByDate.contains(dateKey));
812 // no other entries exist for this date
813 RetainPtr<CFMutableArrayRef> entryArray(AdoptCF,
814 CFArrayCreateMutable(0, 0, &MarshallingHelpers::kIUnknownArrayCallBacks));
815 CFArrayAppendValue(entryArray.get(), entry);
816 m_entriesByDate.set(dateKey, entryArray);
817 // Clear m_orderedLastVisitedDays so it will be regenerated when next requested.
818 m_orderedLastVisitedDays.clear();
824 HRESULT WebHistory::removeItemFromDateCaches(IWebHistoryItem* entry)
828 DATE lastVisitedCOMTime;
829 entry->lastVisitedTimeInterval(&lastVisitedCOMTime);
832 if (!findKey(&dateKey, MarshallingHelpers::DATEToCFAbsoluteTime(lastVisitedCOMTime)))
835 DateToEntriesMap::iterator found = m_entriesByDate.find(dateKey);
836 ASSERT(found != m_entriesByDate.end());
837 CFMutableArrayRef entriesForDate = found->second.get();
839 CFIndex count = CFArrayGetCount(entriesForDate);
840 for (int i = count - 1; i >= 0; --i) {
841 if ((IWebHistoryItem*)CFArrayGetValueAtIndex(entriesForDate, i) == entry)
842 CFArrayRemoveValueAtIndex(entriesForDate, i);
845 // remove this date entirely if there are no other entries on it
846 if (CFArrayGetCount(entriesForDate) == 0) {
847 m_entriesByDate.remove(found);
848 // Clear m_orderedLastVisitedDays so it will be regenerated when next requested.
849 m_orderedLastVisitedDays.clear();
855 static void getDayBoundaries(CFAbsoluteTime day, CFAbsoluteTime& beginningOfDay, CFAbsoluteTime& beginningOfNextDay)
857 RetainPtr<CFTimeZoneRef> timeZone(AdoptCF, CFTimeZoneCopyDefault());
858 CFGregorianDate date = CFAbsoluteTimeGetGregorianDate(day, timeZone.get());
862 beginningOfDay = CFGregorianDateGetAbsoluteTime(date, timeZone.get());
864 beginningOfNextDay = CFGregorianDateGetAbsoluteTime(date, timeZone.get());
867 static inline CFAbsoluteTime beginningOfDay(CFAbsoluteTime date)
869 static CFAbsoluteTime cachedBeginningOfDay = numeric_limits<CFAbsoluteTime>::quiet_NaN();
870 static CFAbsoluteTime cachedBeginningOfNextDay;
871 if (!(date >= cachedBeginningOfDay && date < cachedBeginningOfNextDay))
872 getDayBoundaries(date, cachedBeginningOfDay, cachedBeginningOfNextDay);
873 return cachedBeginningOfDay;
876 static inline WebHistory::DateKey dateKey(CFAbsoluteTime date)
878 // Converting from double (CFAbsoluteTime) to int64_t (WebHistoryDateKey) is
879 // safe here because all sensible dates are in the range -2**48 .. 2**47 which
880 // safely fits in an int64_t.
881 return beginningOfDay(date);
884 // Returns whether the day is already in the list of days,
885 // and fills in *key with the found or proposed key.
886 bool WebHistory::findKey(DateKey* key, CFAbsoluteTime forDay)
888 ASSERT_ARG(key, key);
890 *key = dateKey(forDay);
891 return m_entriesByDate.contains(*key);
894 HRESULT WebHistory::insertItem(IWebHistoryItem* entry, DateKey dateKey)
896 ASSERT_ARG(entry, entry);
897 ASSERT_ARG(dateKey, m_entriesByDate.contains(dateKey));
905 entry->lastVisitedTimeInterval(&entryTime);
906 CFMutableArrayRef entriesForDate = m_entriesByDate.get(dateKey).get();
907 unsigned count = CFArrayGetCount(entriesForDate);
909 // The entries for each day are stored in a sorted array with the most recent entry first
910 // Check for the common cases of the entry being newer than all existing entries or the first entry of the day
911 bool isNewerThanAllEntries = false;
913 IWebHistoryItem* item = const_cast<IWebHistoryItem*>(static_cast<const IWebHistoryItem*>(CFArrayGetValueAtIndex(entriesForDate, 0)));
915 isNewerThanAllEntries = SUCCEEDED(item->lastVisitedTimeInterval(&itemTime)) && itemTime < entryTime;
917 if (!count || isNewerThanAllEntries) {
918 CFArrayInsertValueAtIndex(entriesForDate, 0, entry);
922 // .. or older than all existing entries
923 bool isOlderThanAllEntries = false;
925 IWebHistoryItem* item = const_cast<IWebHistoryItem*>(static_cast<const IWebHistoryItem*>(CFArrayGetValueAtIndex(entriesForDate, count - 1)));
927 isOlderThanAllEntries = SUCCEEDED(item->lastVisitedTimeInterval(&itemTime)) && itemTime >= entryTime;
929 if (isOlderThanAllEntries) {
930 CFArrayInsertValueAtIndex(entriesForDate, count, entry);
935 unsigned high = count;
937 unsigned mid = low + (high - low) / 2;
938 IWebHistoryItem* item = const_cast<IWebHistoryItem*>(static_cast<const IWebHistoryItem*>(CFArrayGetValueAtIndex(entriesForDate, mid)));
940 if (FAILED(item->lastVisitedTimeInterval(&itemTime)))
943 if (itemTime >= entryTime)
949 // low is now the index of the first entry that is older than entryDate
950 CFArrayInsertValueAtIndex(entriesForDate, low, entry);
954 CFAbsoluteTime WebHistory::timeToDate(CFAbsoluteTime time)
956 // can't just divide/round since the day boundaries depend on our current time zone
957 const double secondsPerDay = 60 * 60 * 24;
958 CFTimeZoneRef timeZone = CFTimeZoneCopySystem();
959 CFGregorianDate date = CFAbsoluteTimeGetGregorianDate(time, timeZone);
960 date.hour = date.minute = 0;
962 CFAbsoluteTime timeInDays = CFGregorianDateGetAbsoluteTime(date, timeZone);
963 if (areEqualOrClose(time - timeInDays, secondsPerDay))
964 timeInDays += secondsPerDay;
968 // Return a date that marks the age limit for history entries saved to or
969 // loaded from disk. Any entry older than this item should be rejected.
970 HRESULT WebHistory::ageLimitDate(CFAbsoluteTime* time)
972 // get the current date as a CFAbsoluteTime
973 CFAbsoluteTime currentDate = timeToDate(CFAbsoluteTimeGetCurrent());
975 CFGregorianUnits ageLimit = {0};
976 int historyLimitDays;
977 HRESULT hr = historyAgeInDaysLimit(&historyLimitDays);
980 ageLimit.days = -historyLimitDays;
981 *time = CFAbsoluteTimeAddGregorianUnits(currentDate, CFTimeZoneCopySystem(), ageLimit);
985 static void addVisitedLinkToPageGroup(const void* key, const void*, void* context)
987 CFStringRef url = static_cast<CFStringRef>(key);
988 PageGroup* group = static_cast<PageGroup*>(context);
990 CFIndex length = CFStringGetLength(url);
991 const UChar* characters = reinterpret_cast<const UChar*>(CFStringGetCharactersPtr(url));
993 group->addVisitedLink(characters, length);
995 Vector<UChar, 512> buffer(length);
996 CFStringGetCharacters(url, CFRangeMake(0, length), reinterpret_cast<UniChar*>(buffer.data()));
997 group->addVisitedLink(buffer.data(), length);
1001 void WebHistory::addVisitedLinksToPageGroup(PageGroup& group)
1003 CFDictionaryApplyFunction(m_entriesByURL.get(), addVisitedLinkToPageGroup, &group);
1006 RetainPtr<CFDataRef> WebHistory::data() const
1008 if (m_entriesByDate.isEmpty())
1011 WebHistoryWriter writer(m_entriesByDate);
1012 writer.writePropertyList();
1013 return writer.releaseData();