From 5f1ab04193ad0130ca8204aadaceae083aca9881 Mon Sep 17 00:00:00 2001 From: Feng Qian Date: Wed, 17 Jun 2009 12:12:20 -0700 Subject: Get WebKit r44544. --- WebCore/loader/Cache.cpp | 12 +- WebCore/loader/CachedCSSStyleSheet.cpp | 11 +- WebCore/loader/CachedFont.h | 3 +- WebCore/loader/CachedImage.cpp | 3 + WebCore/loader/CachedImage.h | 6 +- WebCore/loader/CachedResource.cpp | 68 +- WebCore/loader/CachedResource.h | 22 +- WebCore/loader/DocLoader.cpp | 15 +- WebCore/loader/DocumentLoader.cpp | 23 +- WebCore/loader/DocumentThreadableLoader.cpp | 66 +- WebCore/loader/DocumentThreadableLoader.h | 11 +- WebCore/loader/EmptyClients.h | 40 +- WebCore/loader/FTPDirectoryDocument.cpp | 4 + WebCore/loader/FTPDirectoryParser.cpp | 4 + WebCore/loader/FormState.cpp | 14 +- WebCore/loader/FormState.h | 16 +- WebCore/loader/FrameLoader.cpp | 791 ++++++++++----------- WebCore/loader/FrameLoader.h | 201 +++--- WebCore/loader/FrameLoaderClient.h | 2 + WebCore/loader/ImageDocument.cpp | 14 +- WebCore/loader/MainResourceLoader.cpp | 32 +- WebCore/loader/MediaDocument.cpp | 71 ++ WebCore/loader/MediaDocument.h | 6 + WebCore/loader/ProgressTracker.cpp | 8 +- WebCore/loader/SubresourceLoader.cpp | 9 +- WebCore/loader/ThreadableLoader.cpp | 12 +- WebCore/loader/ThreadableLoader.h | 14 +- WebCore/loader/WorkerThreadableLoader.cpp | 50 +- WebCore/loader/WorkerThreadableLoader.h | 18 +- WebCore/loader/appcache/ApplicationCache.cpp | 2 +- WebCore/loader/appcache/ApplicationCache.h | 3 +- WebCore/loader/appcache/ApplicationCacheGroup.cpp | 50 +- WebCore/loader/appcache/ApplicationCacheGroup.h | 2 + .../loader/appcache/ApplicationCacheStorage.cpp | 54 +- WebCore/loader/appcache/ApplicationCacheStorage.h | 3 +- WebCore/loader/appcache/DOMApplicationCache.idl | 2 +- WebCore/loader/icon/IconDatabase.cpp | 122 ++-- WebCore/loader/icon/IconDatabase.h | 10 +- WebCore/loader/loader.cpp | 97 ++- WebCore/loader/loader.h | 34 +- 40 files changed, 1150 insertions(+), 775 deletions(-) (limited to 'WebCore/loader') diff --git a/WebCore/loader/Cache.cpp b/WebCore/loader/Cache.cpp index 539c5fc..6eeba77 100644 --- a/WebCore/loader/Cache.cpp +++ b/WebCore/loader/Cache.cpp @@ -182,6 +182,7 @@ CachedCSSStyleSheet* Cache::requestUserCSSStyleSheet(DocLoader* docLoader, const void Cache::revalidateResource(CachedResource* resource, DocLoader* docLoader) { ASSERT(resource); + ASSERT(resource->inCache()); ASSERT(!disabled()); if (resource->resourceToRevalidate()) return; @@ -211,7 +212,7 @@ void Cache::revalidationSucceeded(CachedResource* revalidatingResource, const Re ASSERT(!m_resources.get(resource->url())); m_resources.set(resource->url(), resource); resource->setInCache(true); - resource->setExpirationDate(response.expirationDate()); + resource->updateResponseAfterRevalidation(response); insertInLRUList(resource); int delta = resource->size(); if (resource->decodedSize() && resource->hasClients()) @@ -391,15 +392,6 @@ void Cache::evict(CachedResource* resource) // The resource may have already been removed by someone other than our caller, // who needed a fresh copy for a reload. See . if (resource->inCache()) { - if (!resource->isCacheValidator()) { - // Notify all doc loaders that might be observing this object still that it has been - // extracted from the set of resources. - // No need to do this for cache validator resources, they are replaced automatically by using CachedResourceHandles. - HashSet::iterator end = m_docLoaders.end(); - for (HashSet::iterator itr = m_docLoaders.begin(); itr != end; ++itr) - (*itr)->removeCachedResource(resource); - } - // Remove from the resource map. m_resources.remove(resource->url()); resource->setInCache(false); diff --git a/WebCore/loader/CachedCSSStyleSheet.cpp b/WebCore/loader/CachedCSSStyleSheet.cpp index 1fb1a9180..11d1213 100644 --- a/WebCore/loader/CachedCSSStyleSheet.cpp +++ b/WebCore/loader/CachedCSSStyleSheet.cpp @@ -29,6 +29,7 @@ #include "CachedResourceClient.h" #include "CachedResourceClientWalker.h" +#include "HTTPParsers.h" #include "TextResourceDecoder.h" #include "loader.h" #include @@ -131,8 +132,14 @@ bool CachedCSSStyleSheet::canUseSheet(bool enforceMIMEType) const if (!enforceMIMEType) return true; - // This check exactly matches Firefox. - String mimeType = response().mimeType(); + // This check exactly matches Firefox. Note that we grab the Content-Type + // header directly because we want to see what the value is BEFORE content + // sniffing. Firefox does this by setting a "type hint" on the channel. + // This implementation should be observationally equivalent. + // + // This code defaults to allowing the stylesheet for non-HTTP protocols so + // folks can use standards mode for local HTML documents. + String mimeType = extractMIMETypeFromMediaType(response().httpHeaderField("Content-Type")); return mimeType.isEmpty() || equalIgnoringCase(mimeType, "text/css") || equalIgnoringCase(mimeType, "application/x-unknown-content-type"); } diff --git a/WebCore/loader/CachedFont.h b/WebCore/loader/CachedFont.h index fd19cdb..e4414c6 100644 --- a/WebCore/loader/CachedFont.h +++ b/WebCore/loader/CachedFont.h @@ -39,10 +39,11 @@ namespace WebCore { class DocLoader; class Cache; -class FontCustomPlatformData; class FontPlatformData; class SVGFontElement; +struct FontCustomPlatformData; + class CachedFont : public CachedResource { public: CachedFont(const String& url); diff --git a/WebCore/loader/CachedImage.cpp b/WebCore/loader/CachedImage.cpp index 5e06eb4..eac02dc 100644 --- a/WebCore/loader/CachedImage.cpp +++ b/WebCore/loader/CachedImage.cpp @@ -53,6 +53,7 @@ CachedImage::CachedImage(const String& url) : CachedResource(url, ImageResource) , m_image(0) , m_decodedDataDeletionTimer(this, &CachedImage::decodedDataDeletionTimerFired) + , m_httpStatusCodeErrorOccurred(false) { m_status = Unknown; } @@ -61,6 +62,7 @@ CachedImage::CachedImage(Image* image) : CachedResource(String(), ImageResource) , m_image(image) , m_decodedDataDeletionTimer(this, &CachedImage::decodedDataDeletionTimerFired) + , m_httpStatusCodeErrorOccurred(false) { m_status = Cached; m_loading = false; @@ -312,6 +314,7 @@ void CachedImage::error() { clear(); m_errorOccurred = true; + m_data.clear(); notifyObservers(); m_loading = false; checkNotify(); diff --git a/WebCore/loader/CachedImage.h b/WebCore/loader/CachedImage.h index 9c3442f..22a3774 100644 --- a/WebCore/loader/CachedImage.h +++ b/WebCore/loader/CachedImage.h @@ -67,7 +67,10 @@ public: virtual void data(PassRefPtr data, bool allDataReceived); virtual void error(); - + + virtual void httpStatusCodeError() { m_httpStatusCodeErrorOccurred = true; } + bool httpStatusCodeErrorOccurred() const { return m_httpStatusCodeErrorOccurred; } + virtual bool schedule() const { return true; } void checkNotify(); @@ -96,6 +99,7 @@ private: RefPtr m_image; Timer m_decodedDataDeletionTimer; + bool m_httpStatusCodeErrorOccurred; }; } diff --git a/WebCore/loader/CachedResource.cpp b/WebCore/loader/CachedResource.cpp index b4ee533..a2eaa2c 100644 --- a/WebCore/loader/CachedResource.cpp +++ b/WebCore/loader/CachedResource.cpp @@ -32,7 +32,10 @@ #include "KURL.h" #include "PurgeableBuffer.h" #include "Request.h" +#include +#include #include +#include #include using namespace WTF; @@ -45,6 +48,7 @@ static RefCountedLeakCounter cachedResourceLeakCounter("CachedResource"); CachedResource::CachedResource(const String& url, Type type) : m_url(url) + , m_responseTimestamp(currentTime()) , m_lastDecodedAccessTime(0) , m_sendResourceLoadCallbacks(true) , m_preloadCount(0) @@ -56,7 +60,6 @@ CachedResource::CachedResource(const String& url, Type type) , m_handleCount(0) , m_resourceToRevalidate(0) , m_isBeingRevalidated(false) - , m_expirationDate(0) { #ifndef NDEBUG cachedResourceLeakCounter.increment(); @@ -115,16 +118,50 @@ void CachedResource::finish() bool CachedResource::isExpired() const { - if (!m_expirationDate) + if (m_response.isNull()) return false; - time_t now = time(0); - return difftime(now, m_expirationDate) >= 0; + + return currentAge() > freshnessLifetime(); +} + +double CachedResource::currentAge() const +{ + // RFC2616 13.2.3 + // No compensation for latency as that is not terribly important in practice + double dateValue = m_response.date(); + double apparentAge = isfinite(dateValue) ? max(0., m_responseTimestamp - dateValue) : 0; + double ageValue = m_response.age(); + double correctedReceivedAge = isfinite(ageValue) ? max(apparentAge, ageValue) : apparentAge; + double residentTime = currentTime() - m_responseTimestamp; + return correctedReceivedAge + residentTime; +} + +double CachedResource::freshnessLifetime() const +{ + // Cache non-http resources liberally + if (!m_response.url().protocolInHTTPFamily()) + return std::numeric_limits::max(); + + // RFC2616 13.2.4 + double maxAgeValue = m_response.cacheControlMaxAge(); + if (isfinite(maxAgeValue)) + return maxAgeValue; + double expiresValue = m_response.expires(); + double dateValue = m_response.date(); + double creationTime = isfinite(dateValue) ? dateValue : m_responseTimestamp; + if (isfinite(expiresValue)) + return expiresValue - creationTime; + double lastModifiedValue = m_response.lastModified(); + if (isfinite(lastModifiedValue)) + return (creationTime - lastModifiedValue) * 0.1; + // If no cache headers are present, the specification leaves the decision to the UA. Other browsers seem to opt for 0. + return 0; } void CachedResource::setResponse(const ResourceResponse& response) { m_response = response; - m_expirationDate = response.expirationDate(); + m_responseTimestamp = currentTime(); } void CachedResource::setRequest(Request* request) @@ -258,7 +295,6 @@ void CachedResource::setResourceToRevalidate(CachedResource* resource) void CachedResource::clearResourceToRevalidate() { ASSERT(m_resourceToRevalidate); - ASSERT(m_resourceToRevalidate->m_isBeingRevalidated); m_resourceToRevalidate->m_isBeingRevalidated = false; m_resourceToRevalidate->deleteIfPossible(); m_handlesToRevalidate.clear(); @@ -269,6 +305,7 @@ void CachedResource::clearResourceToRevalidate() void CachedResource::switchClientsToRevalidatedResource() { ASSERT(m_resourceToRevalidate); + ASSERT(m_resourceToRevalidate->inCache()); ASSERT(!inCache()); HashSet::iterator end = m_handlesToRevalidate.end(); @@ -299,6 +336,23 @@ void CachedResource::switchClientsToRevalidatedResource() m_resourceToRevalidate->addClient(clientsToMove[n]); } +void CachedResource::updateResponseAfterRevalidation(const ResourceResponse& validatingResponse) +{ + m_responseTimestamp = currentTime(); + + DEFINE_STATIC_LOCAL(const AtomicString, contentHeaderPrefix, ("content-")); + // RFC2616 10.3.5 + // Update cached headers from the 304 response + const HTTPHeaderMap& newHeaders = validatingResponse.httpHeaderFields(); + HTTPHeaderMap::const_iterator end = newHeaders.end(); + for (HTTPHeaderMap::const_iterator it = newHeaders.begin(); it != end; ++it) { + // Don't allow 304 response to update content headers, these can't change but some servers send wrong values. + if (it->first.startsWith(contentHeaderPrefix, false)) + continue; + m_response.setHTTPHeaderField(it->first, it->second); + } +} + bool CachedResource::canUseCacheValidator() const { return !m_loading && (!m_response.httpHeaderField("Last-Modified").isEmpty() || !m_response.httpHeaderField("ETag").isEmpty()); @@ -309,9 +363,9 @@ bool CachedResource::mustRevalidate(CachePolicy cachePolicy) const if (m_loading) return false; - // FIXME: Also look at max-age, min-fresh, max-stale in Cache-Control if (cachePolicy == CachePolicyCache) return m_response.cacheControlContainsNoCache() || (isExpired() && m_response.cacheControlContainsMustRevalidate()); + return isExpired() || m_response.cacheControlContainsNoCache(); } diff --git a/WebCore/loader/CachedResource.h b/WebCore/loader/CachedResource.h index 63c250b..16cce26 100644 --- a/WebCore/loader/CachedResource.h +++ b/WebCore/loader/CachedResource.h @@ -82,6 +82,7 @@ public: virtual String encoding() const { return String(); } virtual void data(PassRefPtr data, bool allDataReceived) = 0; virtual void error() = 0; + virtual void httpStatusCodeError() { error(); } // Images keep loading in spite of HTTP errors (for legacy compat with , etc.). const String &url() const { return m_url; } Type type() const { return m_type; } @@ -126,7 +127,8 @@ public: // Called by the cache if the object has been removed from the cache // while still being referenced. This means the object should delete itself // if the number of clients observing it ever drops to 0. - void setInCache(bool b) { m_inCache = b; } + // The resource can be brought back to cache after successful revalidation. + void setInCache(bool b) { m_inCache = b; if (b) m_isBeingRevalidated = false; } bool inCache() const { return m_inCache; } void setInLiveDecodedResourcesList(bool b) { m_inLiveDecodedResourcesList = b; } @@ -162,7 +164,7 @@ public: void decreasePreloadCount() { ASSERT(m_preloadCount); --m_preloadCount; } void registerHandle(CachedResourceHandleBase* h) { ++m_handleCount; if (m_resourceToRevalidate) m_handlesToRevalidate.add(h); } - void unregisterHandle(CachedResourceHandleBase* h) { --m_handleCount; if (m_resourceToRevalidate) m_handlesToRevalidate.remove(h); if (!m_handleCount) deleteIfPossible(); } + void unregisterHandle(CachedResourceHandleBase* h) { ASSERT(m_handleCount > 0); --m_handleCount; if (m_resourceToRevalidate) m_handlesToRevalidate.remove(h); if (!m_handleCount) deleteIfPossible(); } bool canUseCacheValidator() const; bool mustRevalidate(CachePolicy) const; @@ -172,12 +174,16 @@ public: bool isPurgeable() const; bool wasPurged() const; + // This is used by the archive machinery to get at a purged resource without + // triggering a load. We should make it protected again if we can find a + // better way to handle the archive case. + bool makePurgeable(bool purgeable); + protected: void setEncodedSize(unsigned); void setDecodedSize(unsigned); void didAccessDecodedData(double timeStamp); - bool makePurgeable(bool purgeable); bool isSafeToMakePurgeable() const; HashCountedSet m_clients; @@ -187,6 +193,8 @@ protected: Request* m_request; ResourceResponse m_response; + double m_responseTimestamp; + RefPtr m_data; OwnPtr m_purgeableData; @@ -200,7 +208,10 @@ private: void setResourceToRevalidate(CachedResource*); void switchClientsToRevalidatedResource(); void clearResourceToRevalidate(); - void setExpirationDate(time_t expirationDate) { m_expirationDate = expirationDate; } + void updateResponseAfterRevalidation(const ResourceResponse& validatingResponse); + + double currentAge() const; + double freshnessLifetime() const; unsigned m_encodedSize; unsigned m_decodedSize; @@ -217,7 +228,6 @@ private: protected: bool m_inCache; bool m_loading; - bool m_expireDateChanged; #ifndef NDEBUG bool m_deleted; unsigned m_lruIndex; @@ -241,8 +251,6 @@ private: bool m_isBeingRevalidated; // These handles will need to be updated to point to the m_resourceToRevalidate in case we get 304 response. HashSet m_handlesToRevalidate; - - time_t m_expirationDate; }; } diff --git a/WebCore/loader/DocLoader.cpp b/WebCore/loader/DocLoader.cpp index c96348d..7b62074 100644 --- a/WebCore/loader/DocLoader.cpp +++ b/WebCore/loader/DocLoader.cpp @@ -37,6 +37,7 @@ #include "CString.h" #include "Document.h" #include "DOMWindow.h" +#include "HTMLElement.h" #include "Frame.h" #include "FrameLoader.h" #include "loader.h" @@ -63,6 +64,9 @@ DocLoader::DocLoader(Document* doc) DocLoader::~DocLoader() { + if (m_requestCount) + m_cache->loader()->cancelRequests(this); + clearPreloads(); DocumentResourceMap::iterator end = m_documentResources.end(); for (DocumentResourceMap::iterator it = m_documentResources.begin(); it != end; ++it) @@ -316,11 +320,16 @@ void DocLoader::setBlockNetworkImage(bool block) CachePolicy DocLoader::cachePolicy() const { - return frame() ? frame()->loader()->cachePolicy() : CachePolicyVerify; + return frame() ? frame()->loader()->subresourceCachePolicy() : CachePolicyVerify; } void DocLoader::removeCachedResource(CachedResource* resource) const { +#ifndef NDEBUG + DocumentResourceMap::iterator it = m_documentResources.find(resource->url()); + if (it != m_documentResources.end()) + ASSERT(it->second.get() == resource); +#endif m_documentResources.remove(resource->url()); } @@ -389,7 +398,9 @@ void DocLoader::checkForPendingPreloads() return; for (unsigned i = 0; i < count; ++i) { PendingPreload& preload = m_pendingPreloads[i]; - requestPreload(preload.m_type, preload.m_url, preload.m_charset); + // Don't request preload if the resource already loaded normally (this will result in double load if the page is being reloaded with cached results ignored). + if (!cachedResource(m_doc->completeURL(preload.m_url))) + requestPreload(preload.m_type, preload.m_url, preload.m_charset); } m_pendingPreloads.clear(); } diff --git a/WebCore/loader/DocumentLoader.cpp b/WebCore/loader/DocumentLoader.cpp index d0443e8..ffc61df 100644 --- a/WebCore/loader/DocumentLoader.cpp +++ b/WebCore/loader/DocumentLoader.cpp @@ -411,6 +411,10 @@ void DocumentLoader::setupForReplaceByMIMEType(const String& newMIMEType) void DocumentLoader::updateLoading() { + if (!m_frame) { + setLoading(false); + return; + } ASSERT(this == frameLoader()->activeDocumentLoader()); setLoading(frameLoader()->isLoading()); } @@ -556,13 +560,20 @@ PassRefPtr DocumentLoader::subresource(const KURL& url) const if (!isCommitted()) return 0; - Document* doc = m_frame->document(); - - CachedResource* resource = doc->docLoader()->cachedResource(url); - if (!resource || resource->preloadResult() == CachedResource::PreloadReferenced) + CachedResource* resource = m_frame->document()->docLoader()->cachedResource(url); + if (!resource || !resource->isLoaded()) return archiveResourceForURL(url); - - return ArchiveResource::create(resource->data(), url, resource->response()); + + // FIXME: This has the side effect of making the resource non-purgeable. + // It would be better if it didn't have this permanent effect. + if (!resource->makePurgeable(false)) + return 0; + + RefPtr data = resource->data(); + if (!data) + return 0; + + return ArchiveResource::create(data.release(), url, resource->response()); } void DocumentLoader::getSubresources(Vector >& subresources) const diff --git a/WebCore/loader/DocumentThreadableLoader.cpp b/WebCore/loader/DocumentThreadableLoader.cpp index 685db8c..0de62ce 100644 --- a/WebCore/loader/DocumentThreadableLoader.cpp +++ b/WebCore/loader/DocumentThreadableLoader.cpp @@ -43,7 +43,7 @@ namespace WebCore { -void DocumentThreadableLoader::loadResourceSynchronously(Document* document, const ResourceRequest& request, ThreadableLoaderClient& client) +void DocumentThreadableLoader::loadResourceSynchronously(Document* document, const ResourceRequest& request, ThreadableLoaderClient& client, StoredCredentials storedCredentials) { bool sameOriginRequest = document->securityOrigin()->canRequest(request.url()); @@ -52,7 +52,7 @@ void DocumentThreadableLoader::loadResourceSynchronously(Document* document, con ResourceResponse response; unsigned long identifier = std::numeric_limits::max(); if (document->frame()) - identifier = document->frame()->loader()->loadResourceSynchronously(request, error, response, data); + identifier = document->frame()->loader()->loadResourceSynchronously(request, storedCredentials, error, response, data); // No exception for file:/// resources, see . // Also, if we have an HTTP response, then it wasn't a network error in fact. @@ -77,21 +77,26 @@ void DocumentThreadableLoader::loadResourceSynchronously(Document* document, con client.didFinishLoading(identifier); } -PassRefPtr DocumentThreadableLoader::create(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff) +PassRefPtr DocumentThreadableLoader::create(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff, StoredCredentials storedCredentials, RedirectOriginCheck redirectOriginCheck) { ASSERT(document); - RefPtr loader = adoptRef(new DocumentThreadableLoader(document, client, request, callbacksSetting, contentSniff)); + RefPtr loader = adoptRef(new DocumentThreadableLoader(document, client, request, callbacksSetting, contentSniff, storedCredentials, redirectOriginCheck)); if (!loader->m_loader) loader = 0; return loader.release(); } -DocumentThreadableLoader::DocumentThreadableLoader(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff) +DocumentThreadableLoader::DocumentThreadableLoader(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff, StoredCredentials storedCredentials, RedirectOriginCheck redirectOriginCheck) : m_client(client) , m_document(document) + , m_allowStoredCredentials(storedCredentials == AllowStoredCredentials) + , m_sameOriginRequest(document->securityOrigin()->canRequest(request.url())) + , m_checkRedirectOrigin(redirectOriginCheck == RequireSameRedirectOrigin) { ASSERT(document); ASSERT(client); + ASSERT(storedCredentials == AllowStoredCredentials || storedCredentials == DoNotAllowStoredCredentials); + ASSERT(redirectOriginCheck == RequireSameRedirectOrigin || redirectOriginCheck == AllowDifferentRedirectOrigin); m_loader = SubresourceLoader::create(document->frame(), this, request, false, callbacksSetting == SendLoadCallbacks, contentSniff == SniffContent); } @@ -112,52 +117,85 @@ void DocumentThreadableLoader::cancel() m_client = 0; } -void DocumentThreadableLoader::willSendRequest(SubresourceLoader*, ResourceRequest& request, const ResourceResponse&) +void DocumentThreadableLoader::willSendRequest(SubresourceLoader* loader, ResourceRequest& request, const ResourceResponse&) { ASSERT(m_client); + ASSERT_UNUSED(loader, loader == m_loader); // FIXME: This needs to be fixed to follow the redirect correctly even for cross-domain requests. - if (!m_document->securityOrigin()->canRequest(request.url())) { + if (m_checkRedirectOrigin && !m_document->securityOrigin()->canRequest(request.url())) { RefPtr protect(this); m_client->didFailRedirectCheck(); - cancel(); + request = ResourceRequest(); } } -void DocumentThreadableLoader::didSendData(SubresourceLoader*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) +void DocumentThreadableLoader::didSendData(SubresourceLoader* loader, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) { ASSERT(m_client); + ASSERT_UNUSED(loader, loader == m_loader); + m_client->didSendData(bytesSent, totalBytesToBeSent); } -void DocumentThreadableLoader::didReceiveResponse(SubresourceLoader*, const ResourceResponse& response) +void DocumentThreadableLoader::didReceiveResponse(SubresourceLoader* loader, const ResourceResponse& response) { ASSERT(m_client); + ASSERT_UNUSED(loader, loader == m_loader); + m_client->didReceiveResponse(response); } -void DocumentThreadableLoader::didReceiveData(SubresourceLoader*, const char* data, int lengthReceived) +void DocumentThreadableLoader::didReceiveData(SubresourceLoader* loader, const char* data, int lengthReceived) { ASSERT(m_client); + ASSERT_UNUSED(loader, loader == m_loader); + m_client->didReceiveData(data, lengthReceived); } void DocumentThreadableLoader::didFinishLoading(SubresourceLoader* loader) { - ASSERT(loader); + ASSERT(loader == m_loader); ASSERT(m_client); m_client->didFinishLoading(loader->identifier()); } -void DocumentThreadableLoader::didFail(SubresourceLoader*, const ResourceError& error) +void DocumentThreadableLoader::didFail(SubresourceLoader* loader, const ResourceError& error) { ASSERT(m_client); + ASSERT_UNUSED(loader, loader == m_loader); + m_client->didFail(error); } -void DocumentThreadableLoader::receivedCancellation(SubresourceLoader*, const AuthenticationChallenge& challenge) +bool DocumentThreadableLoader::getShouldUseCredentialStorage(SubresourceLoader* loader, bool& shouldUseCredentialStorage) +{ + ASSERT_UNUSED(loader, loader == m_loader); + + if (!m_allowStoredCredentials) { + shouldUseCredentialStorage = false; + return true; + } + + return false; // Only FrameLoaderClient can ultimately permit credential use. +} + +void DocumentThreadableLoader::didReceiveAuthenticationChallenge(SubresourceLoader* loader, const AuthenticationChallenge&) +{ + ASSERT(loader == m_loader); + // Users are not prompted for credentials for cross-origin requests. + if (!m_sameOriginRequest) { + RefPtr protect(this); + m_client->didFail(loader->blockedError()); + cancel(); + } +} + +void DocumentThreadableLoader::receivedCancellation(SubresourceLoader* loader, const AuthenticationChallenge& challenge) { ASSERT(m_client); + ASSERT_UNUSED(loader, loader == m_loader); m_client->didReceiveAuthenticationCancellation(challenge.failureResponse()); } diff --git a/WebCore/loader/DocumentThreadableLoader.h b/WebCore/loader/DocumentThreadableLoader.h index ddf8570..079c725 100644 --- a/WebCore/loader/DocumentThreadableLoader.h +++ b/WebCore/loader/DocumentThreadableLoader.h @@ -44,8 +44,8 @@ namespace WebCore { class DocumentThreadableLoader : public RefCounted, public ThreadableLoader, private SubresourceLoaderClient { public: - static void loadResourceSynchronously(Document*, const ResourceRequest&, ThreadableLoaderClient&); - static PassRefPtr create(Document*, ThreadableLoaderClient*, const ResourceRequest&, LoadCallbacks, ContentSniff); + static void loadResourceSynchronously(Document*, const ResourceRequest&, ThreadableLoaderClient&, StoredCredentials); + static PassRefPtr create(Document*, ThreadableLoaderClient*, const ResourceRequest&, LoadCallbacks, ContentSniff, StoredCredentials, RedirectOriginCheck); virtual ~DocumentThreadableLoader(); virtual void cancel(); @@ -58,7 +58,7 @@ namespace WebCore { virtual void derefThreadableLoader() { deref(); } private: - DocumentThreadableLoader(Document*, ThreadableLoaderClient*, const ResourceRequest&, LoadCallbacks, ContentSniff); + DocumentThreadableLoader(Document*, ThreadableLoaderClient*, const ResourceRequest&, LoadCallbacks, ContentSniff, StoredCredentials, RedirectOriginCheck); virtual void willSendRequest(SubresourceLoader*, ResourceRequest&, const ResourceResponse& redirectResponse); virtual void didSendData(SubresourceLoader*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent); @@ -67,11 +67,16 @@ namespace WebCore { virtual void didFinishLoading(SubresourceLoader*); virtual void didFail(SubresourceLoader*, const ResourceError&); + virtual bool getShouldUseCredentialStorage(SubresourceLoader*, bool& shouldUseCredentialStorage); + virtual void didReceiveAuthenticationChallenge(SubresourceLoader*, const AuthenticationChallenge&); virtual void receivedCancellation(SubresourceLoader*, const AuthenticationChallenge&); RefPtr m_loader; ThreadableLoaderClient* m_client; Document* m_document; + bool m_allowStoredCredentials; + bool m_sameOriginRequest; + bool m_checkRedirectOrigin; }; } // namespace WebCore diff --git a/WebCore/loader/EmptyClients.h b/WebCore/loader/EmptyClients.h index 4d75b7a..f6916ef 100644 --- a/WebCore/loader/EmptyClients.h +++ b/WebCore/loader/EmptyClients.h @@ -1,5 +1,6 @@ /* * Copyright (C) 2006 Eric Seidel (eric@webkit.org) + * Copyright (C) 2008, 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -28,12 +29,14 @@ #include "ChromeClient.h" #include "ContextMenuClient.h" -#include "DragClient.h" +#include "Console.h" #include "DocumentLoader.h" +#include "DragClient.h" #include "EditCommand.h" #include "EditorClient.h" -#include "FocusDirection.h" #include "FloatRect.h" +#include "FocusDirection.h" +#include "FormState.h" #include "FrameLoaderClient.h" #include "InspectorClient.h" #include "ResourceError.h" @@ -92,7 +95,7 @@ public: virtual void setResizable(bool) { } - virtual void addMessageToConsole(const String&, unsigned, const String&) { } + virtual void addMessageToConsole(MessageSource, MessageLevel, const String&, unsigned, const String&) { } virtual bool canRunBeforeUnloadConfirmPanel() { return false; } virtual bool runBeforeUnloadConfirmPanel(const String&, Frame*) { return true; } @@ -133,6 +136,14 @@ public: virtual void runOpenPanel(Frame*, PassRefPtr) { } virtual void formStateDidChange(const Node*) { } + + virtual PassOwnPtr createHTMLParserQuirks() { return 0; } + + virtual bool setCursor(PlatformCursorHandle) { return false; } + + virtual void scrollRectIntoView(const IntRect&, const ScrollView*) const {} + + virtual void requestGeolocationPermissionForFrame(Frame*, Geolocation*) {} }; class EmptyFrameLoaderClient : public FrameLoaderClient { @@ -163,6 +174,7 @@ public: virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long) { } virtual void dispatchDidFailLoading(DocumentLoader*, unsigned long, const ResourceError&) { } virtual bool dispatchDidLoadResourceFromMemoryCache(DocumentLoader*, const ResourceRequest&, const ResourceResponse&, int) { return false; } + virtual void dispatchDidLoadResourceByXMLHttpRequest(unsigned long, const ScriptString&) { } virtual void dispatchDidHandleOnloadEvents() { } virtual void dispatchDidReceiveServerRedirectForProvisionalLoad() { } @@ -347,12 +359,31 @@ public: virtual NSArray* pasteboardTypesForSelection(Frame*) { return 0; } #endif #endif +#if PLATFORM(MAC) && !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD) + virtual void uppercaseWord() { } + virtual void lowercaseWord() { } + virtual void capitalizeWord() { } + virtual void showSubstitutionsPanel(bool) { } + virtual bool substitutionsPanelIsShowing() { return false; } + virtual void toggleSmartInsertDelete() { } + virtual bool isAutomaticQuoteSubstitutionEnabled() { return false; } + virtual void toggleAutomaticQuoteSubstitution() { } + virtual bool isAutomaticLinkDetectionEnabled() { return false; } + virtual void toggleAutomaticLinkDetection() { } + virtual bool isAutomaticDashSubstitutionEnabled() { return false; } + virtual void toggleAutomaticDashSubstitution() { } + virtual bool isAutomaticTextReplacementEnabled() { return false; } + virtual void toggleAutomaticTextReplacement() { } + virtual bool isAutomaticSpellingCorrectionEnabled() { return false; } + virtual void toggleAutomaticSpellingCorrection() { } +#endif virtual void ignoreWordInSpellDocument(const String&) { } virtual void learnWord(const String&) { } virtual void checkSpellingOfString(const UChar*, int, int*, int*) { } + virtual String getAutoCorrectSuggestionForMisspelledWord(const String&) { return String(); } virtual void checkGrammarOfString(const UChar*, int, Vector&, int*, int*) { } #if PLATFORM(MAC) && !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD) - virtual void checkSpellingAndGrammarOfParagraph(const UChar*, int, bool, Vector&) { } + virtual void checkTextOfParagraph(const UChar*, int, uint64_t, Vector&) { }; #endif virtual void updateSpellingUIWithGrammarString(const String&, const GrammarDetail&) { } virtual void updateSpellingUIWithMisspelledWord(const String&) { } @@ -428,3 +459,4 @@ public: } #endif // EmptyClients_h + diff --git a/WebCore/loader/FTPDirectoryDocument.cpp b/WebCore/loader/FTPDirectoryDocument.cpp index 188c84c..ace4cfe 100644 --- a/WebCore/loader/FTPDirectoryDocument.cpp +++ b/WebCore/loader/FTPDirectoryDocument.cpp @@ -235,7 +235,11 @@ static struct tm *localTimeQt(const time_t *const timep, struct tm *result) #define localtime_r(x, y) localTimeQt(x, y) #elif PLATFORM(WIN_OS) && !defined(localtime_r) +#if defined(_MSC_VER) && (_MSC_VER >= 1400) #define localtime_r(x, y) localtime_s((y), (x)) +#else /* !_MSC_VER */ +#define localtime_r(x,y) (localtime(x)?(*(y)=*localtime(x),(y)):0) +#endif #endif static String processFileDateString(const FTPTime& fileTime) diff --git a/WebCore/loader/FTPDirectoryParser.cpp b/WebCore/loader/FTPDirectoryParser.cpp index 8c76e97..6573fb6 100644 --- a/WebCore/loader/FTPDirectoryParser.cpp +++ b/WebCore/loader/FTPDirectoryParser.cpp @@ -50,7 +50,11 @@ static struct tm *gmtimeQt(const time_t *const timep, struct tm *result) #define gmtime_r(x, y) gmtimeQt(x, y) #elif PLATFORM(WIN_OS) && !defined(gmtime_r) +#if defined(_MSC_VER) && (_MSC_VER >= 1400) #define gmtime_r(x, y) gmtime_s((y), (x)) +#else /* !_MSC_VER */ +#define gmtime_r(x,y) (gmtime(x)?(*(y)=*gmtime(x),(y)):0) +#endif #endif FTPEntryType parseOneFTPLine(const char* line, ListState& state, ListResult& result) diff --git a/WebCore/loader/FormState.cpp b/WebCore/loader/FormState.cpp index c55b8ac..bd37086 100644 --- a/WebCore/loader/FormState.cpp +++ b/WebCore/loader/FormState.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2006, 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -34,16 +34,16 @@ namespace WebCore { -PassRefPtr FormState::create(PassRefPtr form, const HashMap& values, PassRefPtr sourceFrame) +inline FormState::FormState(PassRefPtr form, StringPairVector& textFieldValuesToAdopt, PassRefPtr sourceFrame) + : m_form(form) + , m_sourceFrame(sourceFrame) { - return adoptRef(new FormState(form, values, sourceFrame)); + m_textFieldValues.swap(textFieldValuesToAdopt); } -FormState::FormState(PassRefPtr form, const HashMap& values, PassRefPtr sourceFrame) - : m_form(form) - , m_values(values) - , m_sourceFrame(sourceFrame) +PassRefPtr FormState::create(PassRefPtr form, StringPairVector& textFieldValuesToAdopt, PassRefPtr sourceFrame) { + return adoptRef(new FormState(form, textFieldValuesToAdopt, sourceFrame)); } } diff --git a/WebCore/loader/FormState.h b/WebCore/loader/FormState.h index 5370e8a..03317b1 100644 --- a/WebCore/loader/FormState.h +++ b/WebCore/loader/FormState.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2006, 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,28 +29,28 @@ #ifndef FormState_h #define FormState_h -#include -#include "StringHash.h" -#include +#include "PlatformString.h" namespace WebCore { class Frame; class HTMLFormElement; + typedef Vector > StringPairVector; + class FormState : public RefCounted { public: - static PassRefPtr create(PassRefPtr form, const HashMap& values, PassRefPtr sourceFrame); + static PassRefPtr create(PassRefPtr, StringPairVector& textFieldValuesToAdopt, PassRefPtr); HTMLFormElement* form() const { return m_form.get(); } - const HashMap& values() const { return m_values; } + const StringPairVector& textFieldValues() const { return m_textFieldValues; } Frame* sourceFrame() const { return m_sourceFrame.get(); } private: - FormState(PassRefPtr form, const HashMap& values, PassRefPtr sourceFrame); + FormState(PassRefPtr, StringPairVector& textFieldValuesToAdopt, PassRefPtr); RefPtr m_form; - HashMap m_values; + StringPairVector m_textFieldValues; RefPtr m_sourceFrame; }; diff --git a/WebCore/loader/FrameLoader.cpp b/WebCore/loader/FrameLoader.cpp index e5ce94a..88beb24 100644 --- a/WebCore/loader/FrameLoader.cpp +++ b/WebCore/loader/FrameLoader.cpp @@ -1,7 +1,7 @@ /* * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) - * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) + * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -83,6 +83,7 @@ #include "ResourceRequest.h" #include "ScriptController.h" #include "ScriptSourceCode.h" +#include "ScriptString.h" #include "ScriptValue.h" #include "SecurityOrigin.h" #include "SegmentedString.h" @@ -154,45 +155,22 @@ static URLSchemesMap& noAccessSchemes() return noAccessSchemes; } -struct FormSubmission { - FormSubmission(const char* action, const String& url, PassRefPtr formData, - const String& target, const String& contentType, const String& boundary, - PassRefPtr event, bool lockHistory, bool lockBackForwardList) - : action(action) - , url(url) - , formData(formData) - , target(target) - , contentType(contentType) - , boundary(boundary) - , event(event) - , lockHistory(lockHistory) - , lockBackForwardList(lockBackForwardList) - { - } - - const char* action; - String url; - RefPtr formData; - String target; - String contentType; - String boundary; - RefPtr event; - bool lockHistory; - bool lockBackForwardList; -}; - struct ScheduledRedirection { - enum Type { redirection, locationChange, historyNavigation, locationChangeDuringLoad }; + enum Type { redirection, locationChange, historyNavigation, formSubmission }; const Type type; const double delay; const String url; const String referrer; + const FrameLoadRequest frameRequest; + const RefPtr event; + const RefPtr formState; const int historySteps; const bool lockHistory; const bool lockBackForwardList; const bool wasUserGesture; const bool wasRefresh; + const bool wasDuringLoad; ScheduledRedirection(double delay, const String& url, bool lockHistory, bool lockBackForwardList, bool wasUserGesture, bool refresh) : type(redirection) @@ -203,12 +181,13 @@ struct ScheduledRedirection { , lockBackForwardList(lockBackForwardList) , wasUserGesture(wasUserGesture) , wasRefresh(refresh) + , wasDuringLoad(false) { ASSERT(!url.isEmpty()); } - ScheduledRedirection(Type locationChangeType, const String& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool wasUserGesture, bool refresh) - : type(locationChangeType) + ScheduledRedirection(const String& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool wasUserGesture, bool refresh, bool duringLoad) + : type(locationChange) , delay(0) , url(url) , referrer(referrer) @@ -217,8 +196,8 @@ struct ScheduledRedirection { , lockBackForwardList(lockBackForwardList) , wasUserGesture(wasUserGesture) , wasRefresh(refresh) + , wasDuringLoad(duringLoad) { - ASSERT(locationChangeType == locationChange || locationChangeType == locationChangeDuringLoad); ASSERT(!url.isEmpty()); } @@ -230,10 +209,35 @@ struct ScheduledRedirection { , lockBackForwardList(false) , wasUserGesture(false) , wasRefresh(false) + , wasDuringLoad(false) { } -}; + ScheduledRedirection(const FrameLoadRequest& frameRequest, + bool lockHistory, bool lockBackForwardList, PassRefPtr event, PassRefPtr formState, + bool duringLoad) + : type(formSubmission) + , delay(0) + , frameRequest(frameRequest) + , event(event) + , formState(formState) + , historySteps(0) + , lockHistory(lockHistory) + , lockBackForwardList(lockBackForwardList) + , wasUserGesture(false) + , wasRefresh(false) + , wasDuringLoad(duringLoad) + { + ASSERT(!frameRequest.isEmpty()); + ASSERT(this->formState); + } +}; + +#if ENABLE(XHTMLMP) +static const char defaultAcceptHeader[] = "application/xml,application/vnd.wap.xhtml+xml,application/xhtml+xml;profile='http://www.wapforum.org/xhtml',text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; +#else +static const char defaultAcceptHeader[] = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; +#endif static double storedTimeOfLastCompletedLoad; static FrameLoader::LocalLoadPolicy localLoadPolicy = FrameLoader::AllowLocalLoadsForLocalOnly; @@ -282,11 +286,11 @@ FrameLoader::FrameLoader(Frame* frame, FrameLoaderClient* client) , m_quickRedirectComing(false) , m_sentRedirectNotification(false) , m_inStopAllLoaders(false) - , m_navigationDuringLoad(false) , m_isExecutingJavaScriptFormAction(false) , m_isRunningScript(false) , m_didCallImplicitClose(false) , m_wasUnloadEventEmitted(false) + , m_unloadEventBeingDispatched(false) , m_isComplete(false) , m_isLoadingMainResource(false) , m_cancellingWithLoadInProgress(false) @@ -358,7 +362,7 @@ Frame* FrameLoader::createWindow(FrameLoader* frameLoaderForFrameLookup, const F Frame* frame = frameLoaderForFrameLookup->frame()->tree()->find(request.frameName()); if (frame && shouldAllowNavigation(frame)) { if (!request.resourceRequest().url().isEmpty()) - frame->loader()->loadFrameRequestWithFormAndValues(request, false, false, 0, 0, HashMap()); + frame->loader()->loadFrameRequest(request, false, false, 0, 0); if (Page* page = frame->page()) page->chrome()->focus(); created = false; @@ -416,11 +420,6 @@ bool FrameLoader::canHandleRequest(const ResourceRequest& request) return m_client->canHandleRequest(request); } -void FrameLoader::changeLocation(const String& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool userGesture, bool refresh) -{ - changeLocation(completeURL(url), referrer, lockHistory, lockBackForwardList, userGesture, refresh); -} - void FrameLoader::changeLocation(const KURL& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool userGesture, bool refresh) { RefPtr protect(m_frame); @@ -436,22 +435,12 @@ void FrameLoader::changeLocation(const KURL& url, const String& referrer, bool l urlSelected(request, "_self", 0, lockHistory, lockBackForwardList, userGesture); } -void FrameLoader::urlSelected(const FrameLoadRequest& request, Event* event, bool lockHistory, bool lockBackForwardList) -{ - FrameLoadRequest copy = request; - if (copy.resourceRequest().httpReferrer().isEmpty()) - copy.resourceRequest().setHTTPReferrer(m_outgoingReferrer); - addHTTPOriginIfNeeded(copy.resourceRequest(), outgoingOrigin()); - - loadFrameRequestWithFormAndValues(copy, lockHistory, lockBackForwardList, event, 0, HashMap()); -} - -void FrameLoader::urlSelected(const ResourceRequest& request, const String& _target, Event* triggeringEvent, bool lockHistory, bool lockBackForwardList, bool userGesture) +void FrameLoader::urlSelected(const ResourceRequest& request, const String& passedTarget, PassRefPtr triggeringEvent, bool lockHistory, bool lockBackForwardList, bool userGesture) { if (executeIfJavaScriptURL(request.url(), userGesture, false)) return; - String target = _target; + String target = passedTarget; if (target.isEmpty()) target = m_frame->document()->baseTarget(); @@ -460,7 +449,11 @@ void FrameLoader::urlSelected(const ResourceRequest& request, const String& _tar frameRequest.setWasUserGesture(userGesture); #endif - urlSelected(frameRequest, triggeringEvent, lockHistory, lockBackForwardList); + if (frameRequest.resourceRequest().httpReferrer().isEmpty()) + frameRequest.resourceRequest().setHTTPReferrer(m_outgoingReferrer); + addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin()); + + loadFrameRequest(frameRequest, lockHistory, lockBackForwardList, triggeringEvent, 0); } bool FrameLoader::requestFrame(HTMLFrameOwnerElement* ownerElement, const String& urlString, const AtomicString& frameName) @@ -468,7 +461,7 @@ bool FrameLoader::requestFrame(HTMLFrameOwnerElement* ownerElement, const String // Support for KURL scriptURL; KURL url; - if (protocolIs(urlString, "javascript")) { + if (protocolIsJavaScript(urlString)) { scriptURL = completeURL(urlString); // completeURL() encodes the URL. url = blankURL(); } else @@ -507,8 +500,7 @@ Frame* FrameLoader::loadSubframe(HTMLFrameOwnerElement* ownerElement, const KURL } bool hideReferrer = shouldHideReferrer(url, referrer); - RefPtr frame = m_client->createFrame(url, name, ownerElement, hideReferrer ? String() : referrer, - allowsScrolling, marginWidth, marginHeight); + RefPtr frame = m_client->createFrame(url, name, ownerElement, hideReferrer ? String() : referrer, allowsScrolling, marginWidth, marginHeight); if (!frame) { checkCallImplicitClose(); @@ -538,47 +530,61 @@ Frame* FrameLoader::loadSubframe(HTMLFrameOwnerElement* ownerElement, const KURL return frame.get(); } -void FrameLoader::submitFormAgain() -{ - if (m_isRunningScript) - return; - OwnPtr form(m_deferredFormSubmission.release()); - if (!form) - return; - submitForm(form->action, form->url, form->formData, form->target, form->contentType, form->boundary, form->event.get(), form->lockHistory, form->lockBackForwardList); -} - void FrameLoader::submitForm(const char* action, const String& url, PassRefPtr formData, - const String& target, const String& contentType, const String& boundary, Event* event, bool lockHistory, bool lockBackForwardList) + const String& target, const String& contentType, const String& boundary, + bool lockHistory, bool lockBackForwardList, PassRefPtr event, PassRefPtr formState) { + ASSERT(action); + ASSERT(strcmp(action, "GET") == 0 || strcmp(action, "POST") == 0); ASSERT(formData); + ASSERT(formState); + ASSERT(formState->sourceFrame() == m_frame); if (!m_frame->page()) return; KURL u = completeURL(url.isNull() ? "" : url); - // FIXME: Do we really need to special-case an empty URL? - // Would it be better to just go on with the form submisson and let the I/O fail? if (u.isEmpty()) return; - if (u.protocolIs("javascript")) { + if (protocolIsJavaScript(u)) { m_isExecutingJavaScriptFormAction = true; executeIfJavaScriptURL(u, false, false); m_isExecutingJavaScriptFormAction = false; return; } - if (m_isRunningScript) { - if (m_deferredFormSubmission) - return; - m_deferredFormSubmission.set(new FormSubmission(action, url, formData, target, contentType, boundary, event, lockHistory, lockBackForwardList)); + FrameLoadRequest frameRequest; + + String targetOrBaseTarget = target.isEmpty() ? m_frame->document()->baseTarget() : target; + Frame* targetFrame = findFrameForNavigation(targetOrBaseTarget); + if (!targetFrame) { + targetFrame = m_frame; + frameRequest.setFrameName(targetOrBaseTarget); + } + if (!targetFrame->page()) return; + + // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way. + + // We do not want to submit more than one form from the same page, nor do we want to submit a single + // form more than once. This flag prevents these from happening; not sure how other browsers prevent this. + // The flag is reset in each time we start handle a new mouse or key down event, and + // also in setView since this part may get reused for a page from the back/forward cache. + // The form multi-submit logic here is only needed when we are submitting a form that affects this frame. + + // FIXME: Frame targeting is only one of the ways the submission could end up doing something other + // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly + // needed any more now that we reset m_submittedFormURL on each mouse or key down event. + + if (m_frame->tree()->isDescendantOf(targetFrame)) { + if (m_submittedFormURL == u) + return; + m_submittedFormURL = u; } formData->generateFiles(m_frame->page()->chrome()->client()); - FrameLoadRequest frameRequest; #ifdef ANDROID_USER_GESTURE frameRequest.setWasUserGesture(userGestureHint()); #endif @@ -586,25 +592,11 @@ void FrameLoader::submitForm(const char* action, const String& url, PassRefPtrdocument()->baseTarget() : target); - - // Handle mailto: forms - bool isMailtoForm = equalIgnoringCase(u.protocol(), "mailto"); - if (isMailtoForm && strcmp(action, "GET") != 0) { - // Append body= for POST mailto, replace the whole query string for GET one. - String body = formData->flattenToString(); - String query = u.query(); - if (!query.isEmpty()) - query.append('&'); - u.setQuery(query + body); - } - - if (strcmp(action, "GET") == 0) { + if (strcmp(action, "GET") == 0) u.setQuery(formData->flattenToString()); - } else { - if (!isMailtoForm) - frameRequest.resourceRequest().setHTTPBody(formData.get()); + else { frameRequest.resourceRequest().setHTTPMethod("POST"); + frameRequest.resourceRequest().setHTTPBody(formData); // construct some user headers if necessary if (contentType.isNull() || contentType == "application/x-www-form-urlencoded") @@ -616,7 +608,20 @@ void FrameLoader::submitForm(const char* action, const String& url, PassRefPtrpage()) { + Frame* mainFrame = targetPage->mainFrame(); + if (mainFrame != targetFrame) { + Document* document = mainFrame->document(); + if (!mainFrame->loader()->isComplete() || (document && document->processingLoadEvent())) + lockBackForwardList = true; + } + } + + targetFrame->loader()->scheduleFormSubmission(frameRequest, lockHistory, lockBackForwardList, event, formState); } void FrameLoader::stopLoading(bool sendUnload, DatabasePolicy databasePolicy) @@ -630,18 +635,19 @@ void FrameLoader::stopLoading(bool sendUnload, DatabasePolicy databasePolicy) Node* currentFocusedNode = m_frame->document()->focusedNode(); if (currentFocusedNode) currentFocusedNode->aboutToUnload(); - m_frame->document()->dispatchWindowEvent(eventNames().unloadEvent, false, false); + m_unloadEventBeingDispatched = true; + if (m_frame->domWindow()) + m_frame->domWindow()->dispatchUnloadEvent(); + m_unloadEventBeingDispatched = false; if (m_frame->document()) - m_frame->document()->updateRendering(); + m_frame->document()->updateStyleIfNeeded(); m_wasUnloadEventEmitted = true; - if (m_frame->eventHandler()->pendingFrameUnloadEventCount()) - m_frame->eventHandler()->clearPendingFrameUnloadEventCount(); - if (m_frame->eventHandler()->pendingFrameBeforeUnloadEventCount()) - m_frame->eventHandler()->clearPendingFrameBeforeUnloadEventCount(); } } + + // Dispatching the unload event could have made m_frame->document() null. if (m_frame->document() && !m_frame->document()->inPageCache()) - m_frame->document()->removeAllEventListenersFromAllNodes(); + m_frame->document()->removeAllEventListeners(); } m_isComplete = true; // to avoid calling completed() in finishedParsing() (David) @@ -714,7 +720,7 @@ KURL FrameLoader::iconURL() return KURL(m_frame->document()->iconURL()); // Don't return a favicon iconURL unless we're http or https - if (!m_URL.protocolIs("http") && !m_URL.protocolIs("https")) + if (!m_URL.protocolInHTTPFamily()) return KURL(); KURL url; @@ -728,10 +734,11 @@ KURL FrameLoader::iconURL() bool FrameLoader::didOpenURL(const KURL& url) { - if (m_scheduledRedirection && m_scheduledRedirection->type == ScheduledRedirection::locationChangeDuringLoad) + if (m_scheduledRedirection && m_scheduledRedirection->wasDuringLoad) { // A redirect was scheduled before the document was created. // This can happen when one frame changes another frame's location. return false; + } cancelRedirection(); m_frame->editor()->clearLastEditCommand(); @@ -741,11 +748,15 @@ bool FrameLoader::didOpenURL(const KURL& url) m_isLoadingMainResource = true; m_didCallImplicitClose = false; - m_frame->setJSStatusBarText(String()); - m_frame->setJSDefaultStatusBarText(String()); - + // If we are still in the process of initializing an empty document then + // its frame is not in a consistent state for rendering, so avoid setJSStatusBarText + // since it may cause clients to attempt to render the frame. + if (!m_creatingInitialEmptyDocument) { + m_frame->setJSStatusBarText(String()); + m_frame->setJSDefaultStatusBarText(String()); + } m_URL = url; - if ((m_URL.protocolIs("http") || m_URL.protocolIs("https")) && !m_URL.host().isEmpty() && m_URL.path().isEmpty()) + if (m_URL.protocolInHTTPFamily() && !m_URL.host().isEmpty() && m_URL.path().isEmpty()) m_URL.setPath("/"); m_workingURL = m_URL; @@ -773,9 +784,12 @@ void FrameLoader::didExplicitOpen() bool FrameLoader::executeIfJavaScriptURL(const KURL& url, bool userGesture, bool replaceDocument) { - if (!url.protocolIs("javascript")) + if (!protocolIsJavaScript(url)) return false; + if (m_frame->page() && !m_frame->page()->javaScriptURLsAreAllowed()) + return true; + String script = decodeURLEscapeSequences(url.string().substring(strlen("javascript:"))); ScriptValue result = executeScript(script, userGesture); @@ -816,8 +830,7 @@ ScriptValue FrameLoader::executeScript(const ScriptSourceCode& sourceCode) if (!wasRunningScript) { m_isRunningScript = false; - submitFormAgain(); - Document::updateDocumentsRendering(); + Document::updateStyleForAllDocuments(); } return result; @@ -896,10 +909,12 @@ void FrameLoader::receivedFirstData() dispatchDidCommitLoad(); dispatchWindowObjectAvailable(); - String ptitle = m_documentLoader->title(); - // If we have a title let the WebView know about it. - if (!ptitle.isNull()) - m_client->dispatchDidReceiveTitle(ptitle); + if (m_documentLoader) { + String ptitle = m_documentLoader->title(); + // If we have a title let the WebView know about it. + if (!ptitle.isNull()) + m_client->dispatchDidReceiveTitle(ptitle); + } m_workingURL = KURL(); @@ -979,7 +994,7 @@ void FrameLoader::begin(const KURL& url, bool dispatch, SecurityOrigin* origin) m_frame->domWindow()->setURL(document->url()); m_frame->domWindow()->setSecurityOrigin(document->securityOrigin()); - updatePolicyBaseURL(); + updateFirstPartyForCookies(); Settings* settings = document->settings(); document->docLoader()->setAutoLoadImages(settings && settings->loadsImagesAutomatically()); @@ -1351,12 +1366,6 @@ KURL FrameLoader::baseURL() const return m_frame->document()->baseURL(); } -String FrameLoader::baseTarget() const -{ - ASSERT(m_frame->document()); - return m_frame->document()->baseTarget(); -} - KURL FrameLoader::completeURL(const String& url) { ASSERT(m_frame->document()); @@ -1401,7 +1410,7 @@ void FrameLoader::scheduleLocationChange(const String& url, const String& referr // fragment part, we don't need to schedule the location change. KURL parsedURL(url); if (parsedURL.hasRef() && equalIgnoringRef(m_URL, parsedURL)) { - changeLocation(url, referrer, lockHistory, lockBackForwardList, wasUserGesture); + changeLocation(completeURL(url), referrer, lockHistory, lockBackForwardList, wasUserGesture); return; } @@ -1409,18 +1418,23 @@ void FrameLoader::scheduleLocationChange(const String& url, const String& referr // This may happen when a frame changes the location of another frame. bool duringLoad = !m_committedFirstRealDocumentLoad; - // If a redirect was scheduled during a load, then stop the current load. - // Otherwise when the current load transitions from a provisional to a - // committed state, pending redirects may be cancelled. - if (duringLoad) { - if (m_provisionalDocumentLoader) - m_provisionalDocumentLoader->stopLoading(); - stopLoading(true); - } + scheduleRedirection(new ScheduledRedirection(url, referrer, lockHistory, lockBackForwardList, wasUserGesture, false, duringLoad)); +} - ScheduledRedirection::Type type = duringLoad - ? ScheduledRedirection::locationChangeDuringLoad : ScheduledRedirection::locationChange; - scheduleRedirection(new ScheduledRedirection(type, url, referrer, lockHistory, lockBackForwardList, wasUserGesture, false)); +void FrameLoader::scheduleFormSubmission(const FrameLoadRequest& frameRequest, + bool lockHistory, bool lockBackForwardList, PassRefPtr event, PassRefPtr formState) +{ + ASSERT(m_frame->page()); + ASSERT(!frameRequest.isEmpty()); + + // FIXME: Do we need special handling for form submissions where the URL is the same + // as the current one except for the fragment part? See scheduleLocationChange above. + + // Handle a location change of a page with no document as a special case. + // This may happen when a frame changes the location of another frame. + bool duringLoad = !m_committedFirstRealDocumentLoad; + + scheduleRedirection(new ScheduledRedirection(frameRequest, lockHistory, lockBackForwardList, event, formState, duringLoad)); } void FrameLoader::scheduleRefresh(bool wasUserGesture) @@ -1431,8 +1445,7 @@ void FrameLoader::scheduleRefresh(bool wasUserGesture) if (m_URL.isEmpty()) return; - ScheduledRedirection::Type type = ScheduledRedirection::locationChange; - scheduleRedirection(new ScheduledRedirection(type, m_URL.string(), m_outgoingReferrer, true, true, wasUserGesture, true)); + scheduleRedirection(new ScheduledRedirection(m_URL.string(), m_outgoingReferrer, true, true, wasUserGesture, true, false)); } bool FrameLoader::isLocationChange(const ScheduledRedirection& redirection) @@ -1442,7 +1455,7 @@ bool FrameLoader::isLocationChange(const ScheduledRedirection& redirection) return false; case ScheduledRedirection::historyNavigation: case ScheduledRedirection::locationChange: - case ScheduledRedirection::locationChangeDuringLoad: + case ScheduledRedirection::formSubmission: return true; } ASSERT_NOT_REACHED(); @@ -1460,18 +1473,6 @@ void FrameLoader::scheduleHistoryNavigation(int steps) return; } - // If the steps to navigate is not zero (which needs to force a reload), and if we think the navigation is going to be a fragment load - // (when the URL we're going to navigate to is the same as the current one, except for the fragment part - but not exactly the same because that's a reload), - // then we don't need to schedule the navigation. - if (steps != 0) { - KURL destination = historyURL(steps); - // FIXME: This doesn't seem like a reliable way to tell whether or not the load will be a fragment load. - if (equalIgnoringRef(m_URL, destination) && m_URL != destination) { - goBackOrForward(steps); - return; - } - } - scheduleRedirection(new ScheduledRedirection(steps)); } @@ -1514,8 +1515,7 @@ void FrameLoader::redirectionTimerFired(Timer*) switch (redirection->type) { case ScheduledRedirection::redirection: case ScheduledRedirection::locationChange: - case ScheduledRedirection::locationChangeDuringLoad: - changeLocation(redirection->url, redirection->referrer, + changeLocation(KURL(redirection->url), redirection->referrer, redirection->lockHistory, redirection->lockBackForwardList, redirection->wasUserGesture, redirection->wasRefresh); return; case ScheduledRedirection::historyNavigation: @@ -1528,17 +1528,21 @@ void FrameLoader::redirectionTimerFired(Timer*) // in both IE and NS (but not in Mozilla). We can't easily do that. goBackOrForward(redirection->historySteps); return; + case ScheduledRedirection::formSubmission: + // The submitForm function will find a target frame before using the redirection timer. + // Now that the timer has fired, we need to repeat the security check which normally is done when + // selecting a target, in case conditions have changed. Other code paths avoid this by targeting + // without leaving a time window. If we fail the check just silently drop the form submission. + if (!redirection->formState->sourceFrame()->loader()->shouldAllowNavigation(m_frame)) + return; + loadFrameRequest(redirection->frameRequest, redirection->lockHistory, redirection->lockBackForwardList, + redirection->event, redirection->formState); + return; } ASSERT_NOT_REACHED(); } -/* - In the case of saving state about a page with frames, we store a tree of items that mirrors the frame tree. - The item that was the target of the user's navigation is designated as the "targetItem". - When this method is called with doClip=YES we're able to create the whole tree except for the target's children, - which will be loaded in the future. That part of the tree will be filled out as the child loads are committed. -*/ void FrameLoader::loadURLIntoChildFrame(const KURL& url, const String& referer, Frame* childFrame) { ASSERT(childFrame); @@ -1552,14 +1556,14 @@ void FrameLoader::loadURLIntoChildFrame(const KURL& url, const String& referer, // If we're moving in the back/forward list, we might want to replace the content // of this child frame with whatever was there at that point. if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType)) { - HistoryItem* childItem = parentItem->childItemWithName(childFrame->tree()->name()); + HistoryItem* childItem = parentItem->childItemWithTarget(childFrame->tree()->name()); if (childItem) { // Use the original URL to ensure we get all the side-effects, such as // onLoad handlers, of any redirects that happened. An example of where // this is needed is Radar 3213556. workingURL = KURL(childItem->originalURLString()); childLoadType = loadType; - childFrame->loader()->setProvisionalHistoryItem(childItem); + childFrame->loader()->m_provisionalHistoryItem = childItem; } } @@ -1570,11 +1574,7 @@ void FrameLoader::loadURLIntoChildFrame(const KURL& url, const String& referer, childFrame->loader()->loadArchive(subframeArchive.release()); else #endif -#ifdef ANDROID_USER_GESTURE - childFrame->loader()->loadURL(workingURL, referer, String(), false, childLoadType, 0, 0, false); -#else childFrame->loader()->loadURL(workingURL, referer, String(), false, childLoadType, 0, 0); -#endif } #if ENABLE(ARCHIVE) // ANDROID extension: disabled to reduce code size @@ -1654,7 +1654,7 @@ bool FrameLoader::gotoAnchor(const String& name) // We need to update the layout before scrolling, otherwise we could // really mess things up if an anchor scroll comes at a bad moment. - m_frame->document()->updateRendering(); + m_frame->document()->updateStyleIfNeeded(); // Only do a layout if changes have occurred that make it necessary. if (m_frame->view() && m_frame->contentRenderer() && m_frame->contentRenderer()->needsLayout()) m_frame->view()->layout(); @@ -1672,8 +1672,11 @@ bool FrameLoader::gotoAnchor(const String& name) #ifdef ANDROID_SCROLL_ON_GOTO_ANCHOR android::WebFrame::getWebFrame(m_frame)->setUserInitiatedClick(true); #endif - if (renderer) + if (renderer) { renderer->enclosingLayer()->scrollRectToVisible(rect, true, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways); + if (m_frame->view()) + m_frame->view()->setLockedToAnchor(true); + } #ifdef ANDROID_SCROLL_ON_GOTO_ANCHOR android::WebFrame::getWebFrame(m_frame)->setUserInitiatedClick(false); #endif @@ -1760,9 +1763,9 @@ bool FrameLoader::loadPlugin(RenderPart* renderer, const KURL& url, const String return false; } - widget = m_client->createPlugin(IntSize(renderer->contentWidth(), renderer->contentHeight()), + widget = m_client->createPlugin(IntSize(renderer->contentWidth(), renderer->contentHeight()), element, url, paramNames, paramValues, mimeType, - m_frame->document()->isPluginDocument()); + m_frame->document()->isPluginDocument() && !m_containsPlugIns); if (widget) { renderer->setWidget(widget); m_containsPlugIns = true; @@ -1772,22 +1775,6 @@ bool FrameLoader::loadPlugin(RenderPart* renderer, const KURL& url, const String return widget != 0; } -void FrameLoader::clearRecordedFormValues() -{ - m_formAboutToBeSubmitted = 0; - m_formValuesAboutToBeSubmitted.clear(); -} - -void FrameLoader::setFormAboutToBeSubmitted(PassRefPtr element) -{ - m_formAboutToBeSubmitted = element; -} - -void FrameLoader::recordFormValue(const String& name, const String& value) -{ - m_formValuesAboutToBeSubmitted.set(name, value); -} - void FrameLoader::parentCompleted() { if (m_scheduledRedirection && !m_redirectionTimer.isActive()) @@ -1842,22 +1829,11 @@ void FrameLoader::handleFallbackContent() } void FrameLoader::provisionalLoadStarted() -{ +{ #ifdef ANDROID_INSTRUMENT if (!m_frame->tree()->parent()) android::TimeCounter::reset(); #endif - - Page* page = m_frame->page(); - - // this is used to update the current history item - // in the event of a navigation aytime during loading - m_navigationDuringLoad = false; - if (page) { - Document *document = page->mainFrame()->document(); - m_navigationDuringLoad = !page->mainFrame()->loader()->isComplete() || (document && document->processingLoadEvent()); - } - m_firstLayoutDone = false; cancelRedirection(true); m_client->provisionalLoadStarted(); @@ -1871,12 +1847,6 @@ bool FrameLoader::userGestureHint() return frame->script()->processingUserGesture(); // FIXME: Use pageIsProcessingUserGesture. } -void FrameLoader::didNotOpenURL(const KURL& url) -{ - if (m_submittedFormURL == url) - m_submittedFormURL = KURL(); -} - void FrameLoader::resetMultipleFormSubmissionProtection() { m_submittedFormURL = KURL(); @@ -1910,13 +1880,13 @@ bool FrameLoader::canCachePageContainingThisFrame() // the right NPObjects. See for more information. && !m_containsPlugIns && !m_URL.protocolIs("https") - && !m_frame->document()->hasWindowEventListener(eventNames().unloadEvent) + && (!m_frame->domWindow() || !m_frame->domWindow()->hasEventListener(eventNames().unloadEvent)) #if ENABLE(DATABASE) && !m_frame->document()->hasOpenDatabases() #endif && !m_frame->document()->usingGeolocation() && m_currentHistoryItem - && !isQuickRedirectComing() + && !m_quickRedirectComing && !m_documentLoader->isLoadingInAPISense() && !m_documentLoader->isStopping() && m_frame->document()->canSuspendActiveDOMObjects() @@ -2052,7 +2022,7 @@ bool FrameLoader::logCanCacheFrameDecision(int indentLevel) { PCLOG(" -Frame contains plugins"); cannotCache = true; } if (m_URL.protocolIs("https")) { PCLOG(" -Frame is HTTPS"); cannotCache = true; } - if (m_frame->document()->hasWindowEventListener(eventNames().unloadEvent)) + if (m_frame->domWindow() && m_frame->domWindow()->hasEventListener(eventNames().unloadEvent)) { PCLOG(" -Frame has an unload event listener"); cannotCache = true; } #if ENABLE(DATABASE) if (m_frame->document()->hasOpenDatabases()) @@ -2062,7 +2032,7 @@ bool FrameLoader::logCanCacheFrameDecision(int indentLevel) { PCLOG(" -Frame uses Geolocation"); cannotCache = true; } if (!m_currentHistoryItem) { PCLOG(" -No current history item"); cannotCache = true; } - if (isQuickRedirectComing()) + if (m_quickRedirectComing) { PCLOG(" -Quick redirect is coming"); cannotCache = true; } if (m_documentLoader->isLoadingInAPISense()) { PCLOG(" -DocumentLoader is still loading in API sense"); cannotCache = true; } @@ -2091,19 +2061,19 @@ bool FrameLoader::logCanCacheFrameDecision(int indentLevel) } #endif -void FrameLoader::updatePolicyBaseURL() +void FrameLoader::updateFirstPartyForCookies() { if (m_frame->tree()->parent()) - setPolicyBaseURL(m_frame->tree()->parent()->document()->policyBaseURL()); + setFirstPartyForCookies(m_frame->tree()->parent()->document()->firstPartyForCookies()); else - setPolicyBaseURL(m_URL); + setFirstPartyForCookies(m_URL); } -void FrameLoader::setPolicyBaseURL(const KURL& url) +void FrameLoader::setFirstPartyForCookies(const KURL& url) { - m_frame->document()->setPolicyBaseURL(url); + m_frame->document()->setFirstPartyForCookies(url); for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) - child->loader()->setPolicyBaseURL(url); + child->loader()->setFirstPartyForCookies(url); } // This does the same kind of work that didOpenURL does, except it relies on the fact @@ -2133,6 +2103,15 @@ void FrameLoader::scheduleRedirection(ScheduledRedirection* redirection) { ASSERT(m_frame->page()); + // If a redirect was scheduled during a load, then stop the current load. + // Otherwise when the current load transitions from a provisional to a + // committed state, pending redirects may be cancelled. + if (redirection->wasDuringLoad) { + if (m_provisionalDocumentLoader) + m_provisionalDocumentLoader->stopLoading(); + stopLoading(true); + } + stopRedirectionTimer(); m_scheduledRedirection.set(redirection); if (!m_isComplete && redirection->type != ScheduledRedirection::redirection) @@ -2150,14 +2129,17 @@ void FrameLoader::startRedirectionTimer() m_redirectionTimer.startOneShot(m_scheduledRedirection->delay); switch (m_scheduledRedirection->type) { - case ScheduledRedirection::redirection: case ScheduledRedirection::locationChange: - case ScheduledRedirection::locationChangeDuringLoad: + case ScheduledRedirection::redirection: clientRedirected(KURL(m_scheduledRedirection->url), m_scheduledRedirection->delay, currentTime() + m_redirectionTimer.nextFireInterval(), - m_scheduledRedirection->lockBackForwardList, - m_isExecutingJavaScriptFormAction); + m_scheduledRedirection->lockBackForwardList); + return; + case ScheduledRedirection::formSubmission: + // FIXME: It would make sense to report form submissions as client redirects too. + // But we didn't do that in the past when form submission used a separate delay + // mechanism, so doing it will be a behavior change. return; case ScheduledRedirection::historyNavigation: // Don't report history navigations. @@ -2175,11 +2157,15 @@ void FrameLoader::stopRedirectionTimer() if (m_scheduledRedirection) { switch (m_scheduledRedirection->type) { - case ScheduledRedirection::redirection: case ScheduledRedirection::locationChange: - case ScheduledRedirection::locationChangeDuringLoad: + case ScheduledRedirection::redirection: clientRedirectCancelledOrFinished(m_cancellingWithLoadInProgress); return; + case ScheduledRedirection::formSubmission: + // FIXME: It would make sense to report form submissions as client redirects too. + // But we didn't do that in the past when form submission used a separate delay + // mechanism, so doing it will be a behavior change. + return; case ScheduledRedirection::historyNavigation: // Don't report history navigations. return; @@ -2195,7 +2181,8 @@ void FrameLoader::completed() child->loader()->parentCompleted(); if (Frame* parent = m_frame->tree()->parent()) parent->loader()->checkCompleted(); - submitFormAgain(); + if (m_frame->view()) + m_frame->view()->setLockedToAnchor(false); } void FrameLoader::started() @@ -2229,13 +2216,24 @@ void FrameLoader::setupForReplaceByMIMEType(const String& newMIMEType) activeDocumentLoader()->setupForReplaceByMIMEType(newMIMEType); } -void FrameLoader::loadFrameRequestWithFormAndValues(const FrameLoadRequest& request, bool lockHistory, bool lockBackForwardList, Event* event, - HTMLFormElement* submitForm, const HashMap& formValues) +// This is a hack to allow keep navigation to http/https feeds working. To remove this +// we need to introduce new API akin to registerURLSchemeAsLocal, that registers a +// protocols navigation policy. +static bool isFeedWithNestedProtocolInHTTPFamily(const KURL& url) { - RefPtr formState; - if (submitForm) - formState = FormState::create(submitForm, formValues, m_frame); - + const String& urlString = url.string(); + if (!urlString.startsWith("feed", false)) + return false; + + return urlString.startsWith("feed://", false) + || urlString.startsWith("feed:http:", false) || urlString.startsWith("feed:https:", false) + || urlString.startsWith("feeds:http:", false) || urlString.startsWith("feeds:https:", false) + || urlString.startsWith("feedsearch:http:", false) || urlString.startsWith("feedsearch:https:", false); +} + +void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, bool lockHistory, bool lockBackForwardList, + PassRefPtr event, PassRefPtr formState) +{ KURL url = request.resourceRequest().url(); String referrer; @@ -2246,7 +2244,7 @@ void FrameLoader::loadFrameRequestWithFormAndValues(const FrameLoadRequest& requ referrer = m_outgoingReferrer; ASSERT(frame()->document()); - if (url.protocolIs("file")) { + if (shouldTreatURLAsLocal(url.string()) && !isFeedWithNestedProtocolInHTTPFamily(url)) { if (!canLoad(url, String(), frame()->document()) && !canLoad(url, referrer)) { FrameLoader::reportLocalLoadFailed(m_frame, url.string()); return; @@ -2265,30 +2263,37 @@ void FrameLoader::loadFrameRequestWithFormAndValues(const FrameLoadRequest& requ loadType = FrameLoadTypeStandard; if (request.resourceRequest().httpMethod() == "POST") -#ifdef ANDROID_USER_GESTURE - loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.release(), request.wasUserGesture()); -#else - loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.release()); -#endif + loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.get()); else -#ifdef ANDROID_USER_GESTURE - loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.release(), request.wasUserGesture()); -#else - loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.release()); -#endif + loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.get()); - Frame* targetFrame = findFrameForNavigation(request.frameName()); - if (targetFrame && targetFrame != m_frame) + // FIXME: It's possible this targetFrame will not be the same frame that was targeted by the actual + // load if frame names have changed. + Frame* sourceFrame = formState ? formState->sourceFrame() : m_frame; + Frame* targetFrame = sourceFrame->loader()->findFrameForNavigation(request.frameName()); + if (targetFrame && targetFrame != sourceFrame) { if (Page* page = targetFrame->page()) page->chrome()->focus(); + } } #ifdef ANDROID_USER_GESTURE +void FrameLoader::loadPostRequest(const ResourceRequest& request, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType type, PassRefPtr event, PassRefPtr state) +{ + loadPostRequest(request, referrer, frameName, lockHistory, type, event, state, false); +} + +void FrameLoader::loadURL(const KURL& url, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType type, PassRefPtr event, PassRefPtr state) +{ + loadURL(url, referrer, frameName, lockHistory, type, event, state, false); +} + void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType newLoadType, - Event* event, PassRefPtr prpFormState, bool userGesture) + PassRefPtr event, PassRefPtr prpFormState, + bool userGesture) #else void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType newLoadType, - Event* event, PassRefPtr prpFormState) + PassRefPtr event, PassRefPtr prpFormState) #endif { RefPtr formState = prpFormState; @@ -2309,17 +2314,17 @@ void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const Stri ASSERT(newLoadType != FrameLoadTypeSame); + // The search for a target frame is done earlier in the case of form submission. + Frame* targetFrame = isFormSubmission ? 0 : findFrameForNavigation(frameName); + if (targetFrame && targetFrame != m_frame) { + targetFrame->loader()->loadURL(newURL, referrer, String(), lockHistory, newLoadType, event, formState.release()); + return; + } + NavigationAction action(newURL, newLoadType, isFormSubmission, event); - if (!frameName.isEmpty()) { - if (Frame* targetFrame = findFrameForNavigation(frameName)) -#ifdef ANDROID_USER_GESTURE - targetFrame->loader()->loadURL(newURL, referrer, String(), lockHistory, newLoadType, event, formState, userGesture); -#else - targetFrame->loader()->loadURL(newURL, referrer, String(), lockHistory, newLoadType, event, formState); -#endif - else - checkNewWindowPolicy(action, request, formState, frameName); + if (!targetFrame && !frameName.isEmpty()) { + checkNewWindowPolicy(action, request, formState.release(), frameName); return; } @@ -2333,12 +2338,12 @@ void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const Stri if (shouldScrollToAnchor(isFormSubmission, newLoadType, newURL)) { oldDocumentLoader->setTriggeringAction(action); stopPolicyCheck(); - checkNavigationPolicy(request, oldDocumentLoader.get(), formState, + checkNavigationPolicy(request, oldDocumentLoader.get(), formState.release(), callContinueFragmentScrollAfterNavigationPolicy, this); } else { // must grab this now, since this load may stop the previous load and clear this flag bool isRedirect = m_quickRedirectComing; - loadWithNavigationAction(request, action, lockHistory, newLoadType, formState); + loadWithNavigationAction(request, action, lockHistory, newLoadType, formState.release()); if (isRedirect) { m_quickRedirectComing = false; if (m_provisionalDocumentLoader) @@ -2457,6 +2462,8 @@ void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType t stopPolicyCheck(); setPolicyDocumentLoader(loader); + if (loader->triggeringAction().isEmpty()) + loader->setTriggeringAction(NavigationAction(newURL, m_policyLoadType, isFormSubmission)); checkNavigationPolicy(loader->request(), loader, formState, callContinueLoadAfterNavigationPolicy, this); @@ -2465,18 +2472,22 @@ void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType t bool FrameLoader::canLoad(const KURL& url, const String& referrer, const Document* doc) { - // We can always load any URL that isn't considered local (e.g. http URLs) + return canLoad(url, referrer, doc ? doc->securityOrigin() : 0); +} + +bool FrameLoader::canLoad(const KURL& url, const String& referrer, const SecurityOrigin* securityOrigin) +{ + // We can always load any URL that isn't considered local (e.g. http URLs). if (!shouldTreatURLAsLocal(url.string())) return true; // If we were provided a document, we let its local file policy dictate the result, // otherwise we allow local loads only if the supplied referrer is also local. - if (doc) - return doc->securityOrigin()->canLoadLocalResources(); - else if (!referrer.isEmpty()) + if (securityOrigin) + return securityOrigin->canLoadLocalResources(); + if (!referrer.isEmpty()) return shouldTreatURLAsLocal(referrer); - else - return false; + return false; } void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url) @@ -2716,6 +2727,9 @@ void FrameLoader::stopLoadingSubframes() void FrameLoader::stopAllLoaders(DatabasePolicy databasePolicy) { + if (m_unloadEventBeingDispatched) + return; + // If this method is called from within this method, infinite recursion can occur (3442218). Avoid this. if (m_inStopAllLoaders) return; @@ -3038,7 +3052,7 @@ void FrameLoader::clientRedirectCancelledOrFinished(bool cancelWithLoadInProgres m_sentRedirectNotification = false; } -void FrameLoader::clientRedirected(const KURL& url, double seconds, double fireDate, bool lockBackForwardList, bool isJavaScriptFormAction) +void FrameLoader::clientRedirected(const KURL& url, double seconds, double fireDate, bool lockBackForwardList) { m_client->dispatchWillPerformClientRedirect(url, seconds, fireDate); @@ -3046,10 +3060,11 @@ void FrameLoader::clientRedirected(const KURL& url, double seconds, double fireD // the next provisional load, we can send a corresponding -webView:didCancelClientRedirectForFrame: m_sentRedirectNotification = true; - // If a "quick" redirect comes in an, we set a special mode so we treat the next - // load as part of the same navigation. If we don't have a document loader, we have + // If a "quick" redirect comes in, we set a special mode so we treat the next + // load as part of the original navigation. If we don't have a document loader, we have // no "original" load on which to base a redirect, so we treat the redirect as a normal load. - m_quickRedirectComing = lockBackForwardList && m_documentLoader && !isJavaScriptFormAction; + // Loads triggered by JavaScript form submissions never count as quick redirects. + m_quickRedirectComing = lockBackForwardList && m_documentLoader && !m_isExecutingJavaScriptFormAction; } #if ENABLE(WML) @@ -3120,7 +3135,7 @@ void FrameLoader::open(CachedFrame& cachedFrame) KURL url = cachedFrame.url(); - if ((url.protocolIs("http") || url.protocolIs("https")) && !url.host().isEmpty() && url.path().isEmpty()) + if (url.protocolInHTTPFamily() && !url.host().isEmpty() && url.path().isEmpty()) url.setPath("/"); m_URL = url; @@ -3154,7 +3169,7 @@ void FrameLoader::open(CachedFrame& cachedFrame) m_decoder = document->decoder(); - updatePolicyBaseURL(); + updateFirstPartyForCookies(); cachedFrame.restore(); } @@ -3250,10 +3265,20 @@ void FrameLoader::finishedLoadingDocument(DocumentLoader* loader) ArchiveResource* mainResource = archive->mainResource(); loader->setParsedArchiveData(mainResource->data()); - continueLoadWithData(mainResource->data(), mainResource->mimeType(), mainResource->textEncoding(), mainResource->url()); + + m_responseMIMEType = mainResource->mimeType(); + didOpenURL(mainResource->url()); + + String userChosenEncoding = documentLoader()->overrideEncoding(); + bool encodingIsUserChosen = !userChosenEncoding.isNull(); + setEncoding(encodingIsUserChosen ? userChosenEncoding : mainResource->textEncoding(), encodingIsUserChosen); + + ASSERT(m_frame->document()); + + addData(mainResource->data()->data(), mainResource->data()->size()); #else m_client->finishedLoading(loader); -#endif +#endif // ARCHIVE } bool FrameLoader::isReplacing() const @@ -3296,20 +3321,28 @@ FrameLoadType FrameLoader::loadType() const return m_loadType; } -CachePolicy FrameLoader::cachePolicy() const +CachePolicy FrameLoader::subresourceCachePolicy() const { if (m_isComplete) return CachePolicyVerify; - - if (m_loadType == FrameLoadTypeReloadFromOrigin || documentLoader()->request().cachePolicy() == ReloadIgnoringCacheData) + + if (m_loadType == FrameLoadTypeReloadFromOrigin) return CachePolicyReload; - + if (Frame* parentFrame = m_frame->tree()->parent()) { - CachePolicy parentCachePolicy = parentFrame->loader()->cachePolicy(); + CachePolicy parentCachePolicy = parentFrame->loader()->subresourceCachePolicy(); if (parentCachePolicy != CachePolicyVerify) return parentCachePolicy; } + // FIXME: POST documents are always Reloads, but their subresources should still be Revalidate. + // If we bring the CachePolicy.h and ResourceRequest cache policy enums in sync with each other and + // remember "Revalidate" in ResourceRequests, we can remove this "POST" check and return either "Reload" + // or "Revalidate" if the DocumentLoader was requested with either. + const ResourceRequest& request(documentLoader()->request()); + if (request.cachePolicy() == ReloadIgnoringCacheData && !equalIgnoringCase(request.httpMethod(), "post")) + return CachePolicyRevalidate; + if (m_loadType == FrameLoadTypeReload) return CachePolicyRevalidate; @@ -3349,7 +3382,7 @@ void FrameLoader::checkLoadCompleteForThisFrame() item = m_currentHistoryItem; bool shouldReset = true; - if (!pdl->isLoadingInAPISense()) { + if (!(pdl->isLoadingInAPISense() && !pdl->isStopping())) { m_delegateIsHandlingProvisionalLoadError = true; m_client->dispatchDidFailProvisionalLoad(error); m_delegateIsHandlingProvisionalLoadError = false; @@ -3381,7 +3414,7 @@ void FrameLoader::checkLoadCompleteForThisFrame() case FrameStateCommittedPage: { DocumentLoader* dl = m_documentLoader.get(); - if (!dl || dl->isLoadingInAPISense()) + if (!dl || (dl->isLoadingInAPISense() && !dl->isStopping())) return; markLoadComplete(); @@ -3501,11 +3534,6 @@ bool FrameLoader::firstLayoutDone() const return m_firstLayoutDone; } -bool FrameLoader::isQuickRedirectComing() const -{ - return m_quickRedirectComing; -} - void FrameLoader::detachChildren() { // FIXME: Is it really necessary to do this in reverse order? @@ -3564,30 +3592,6 @@ int FrameLoader::numPendingOrLoadingRequests(bool recurse) const return count; } -void FrameLoader::submitForm(const FrameLoadRequest& request, Event* event, bool lockHistory, bool lockBackForwardList) -{ - // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way. - // We do not want to submit more than one form from the same page, - // nor do we want to submit a single form more than once. - // This flag prevents these from happening; not sure how other browsers prevent this. - // The flag is reset in each time we start handle a new mouse or key down event, and - // also in setView since this part may get reused for a page from the back/forward cache. - // The form multi-submit logic here is only needed when we are submitting a form that affects this frame. - // FIXME: Frame targeting is only one of the ways the submission could end up doing something other - // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly - // needed any more now that we reset m_submittedFormURL on each mouse or key down event. - Frame* target = m_frame->tree()->find(request.frameName()); - if (m_frame->tree()->isDescendantOf(target)) { - if (m_submittedFormURL == request.resourceRequest().url()) - return; - m_submittedFormURL = request.resourceRequest().url(); - } - - loadFrameRequestWithFormAndValues(request, lockHistory, lockBackForwardList, event, m_formAboutToBeSubmitted.get(), m_formValuesAboutToBeSubmitted); - - clearRecordedFormValues(); -} - String FrameLoader::userAgent(const KURL& url) const { return m_client->userAgent(url); @@ -3595,9 +3599,6 @@ String FrameLoader::userAgent(const KURL& url) const void FrameLoader::tokenizerProcessedData() { -// ASSERT(m_frame->page()); -// ASSERT(m_frame->document()); - checkCompleted(); } @@ -3651,13 +3652,13 @@ void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadTyp { // Don't set the cookie policy URL if it's already been set. // But make sure to set it on all requests, as it has significance beyond the cookie policy for all protocols (). - if (request.mainDocumentURL().isEmpty()) { + if (request.firstPartyForCookies().isEmpty()) { if (mainResource && (isLoadingMainFrame() || cookiePolicyURLFromRequest)) - request.setMainDocumentURL(request.url()); - else if (Page* page = m_frame->page()) - request.setMainDocumentURL(page->mainFrame()->loader()->url()); + request.setFirstPartyForCookies(request.url()); + else if (Document* document = m_frame->document()) + request.setFirstPartyForCookies(document->firstPartyForCookies()); } - + // The remaining modifications are only necessary for HTTP and HTTPS. if (!request.url().isEmpty() && !request.url().protocolInHTTPFamily()) return; @@ -3674,7 +3675,7 @@ void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadTyp } if (mainResource) - request.setHTTPAccept("application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); + request.setHTTPAccept(defaultAcceptHeader); // Make sure we send the Origin header. addHTTPOriginIfNeeded(request, String()); @@ -3721,9 +3722,9 @@ void FrameLoader::committedLoad(DocumentLoader* loader, const char* data, int le } #ifdef ANDROID_USER_GESTURE -void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, Event* event, PassRefPtr prpFormState, bool userGesture) +void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, PassRefPtr event, PassRefPtr prpFormState, bool userGesture) #else -void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, Event* event, PassRefPtr prpFormState) +void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, PassRefPtr event, PassRefPtr prpFormState) #endif { RefPtr formState = prpFormState; @@ -3759,7 +3760,8 @@ void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String NavigationAction action(url, loadType, true, event); if (!frameName.isEmpty()) { - if (Frame* targetFrame = findFrameForNavigation(frameName)) + // The search for a target frame is done earlier in the case of form submission. + if (Frame* targetFrame = formState ? 0 : findFrameForNavigation(frameName)) targetFrame->loader()->loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release()); else checkNewWindowPolicy(action, workingResourceRequest, formState.release(), frameName); @@ -3767,16 +3769,8 @@ void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release()); } -void FrameLoader::loadEmptyDocumentSynchronously() -{ - ResourceRequest request(KURL("")); - load(request, false); -} - -unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector& data) +unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, StoredCredentials storedCredentials, ResourceError& error, ResourceResponse& response, Vector& data) { - // Since this is a subresource, we can load any URL (we ignore the return value). - // But we still want to know whether we should hide the referrer or not, so we call the canLoad method. String referrer = m_outgoingReferrer; if (shouldHideReferrer(request.url(), referrer)) referrer = String(); @@ -3794,7 +3788,7 @@ unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& requ addHTTPOriginIfNeeded(initialRequest, outgoingOrigin()); if (Page* page = m_frame->page()) - initialRequest.setMainDocumentURL(page->mainFrame()->loader()->documentLoader()->request().url()); + initialRequest.setFirstPartyForCookies(page->mainFrame()->loader()->documentLoader()->request().url()); initialRequest.setHTTPUserAgent(client()->userAgent(request.url())); unsigned long identifier = 0; @@ -3814,7 +3808,7 @@ unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& requ error = cannotShowURLError(newRequest); } else { #endif - ResourceHandle::loadResourceSynchronously(newRequest, error, response, data, m_frame); + ResourceHandle::loadResourceSynchronously(newRequest, storedCredentials, error, response, data, m_frame); #if ENABLE(OFFLINE_WEB_APPLICATIONS) // If normal loading results in a redirect to a resource with another origin (indicative of a captive portal), or a 4xx or 5xx status code or equivalent, @@ -3872,6 +3866,11 @@ void FrameLoader::didFailToLoad(ResourceLoader* loader, const ResourceError& err m_client->dispatchDidFailLoading(loader->documentLoader(), loader->identifier(), error); } +void FrameLoader::didLoadResourceByXMLHttpRequest(unsigned long identifier, const ScriptString& sourceString) +{ + m_client->dispatchDidLoadResourceByXMLHttpRequest(identifier, sourceString); +} + const ResourceRequest& FrameLoader::originalRequest() const { return activeDocumentLoader()->originalRequestCopy(); @@ -3893,8 +3892,8 @@ void FrameLoader::receivedMainResourceError(const ResourceError& error, bool isC } if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) { - KURL failedURL = m_provisionalDocumentLoader->originalRequestCopy().url(); - didNotOpenURL(failedURL); + if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url()) + m_submittedFormURL = KURL(); // We might have made a page cache item, but now we're bailing out due to an error before we ever // transitioned to the new page (before WebFrameState == commit). The goal here is to restore any state @@ -4127,7 +4126,14 @@ void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest&, Pass // might detach the current FrameLoader, in which case we should bail on this newly defunct load. if (!m_frame->page()) return; - + +#if ENABLE(JAVASCRIPT_DEBUGGER) + if (Page* page = m_frame->page()) { + if (page->mainFrame() == m_frame) + page->inspectorController()->resumeDebugger(); + } +#endif + setProvisionalDocumentLoader(m_policyDocumentLoader.get()); m_loadType = type; setState(FrameStateProvisional); @@ -4242,6 +4248,24 @@ void FrameLoader::applyUserAgent(ResourceRequest& request) request.setHTTPUserAgent(userAgent); } +bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const KURL& url) +{ + Frame* topFrame = m_frame->tree()->top(); + if (m_frame == topFrame) + return false; + + if (equalIgnoringCase(content, "deny")) + return true; + + if (equalIgnoringCase(content, "sameorigin")) { + RefPtr origin = SecurityOrigin::create(url); + if (!origin->isSameSchemeHostPort(topFrame->document()->securityOrigin())) + return true; + } + + return false; +} + bool FrameLoader::canGoBackOrForward(int distance) const { if (Page* page = m_frame->page()) { @@ -4262,28 +4286,6 @@ int FrameLoader::getHistoryLength() return 0; } -KURL FrameLoader::historyURL(int distance) -{ - if (Page* page = m_frame->page()) { - BackForwardList* list = page->backForwardList(); - HistoryItem* item = list->itemAtIndex(distance); - if (!item) { - if (distance > 0) { - int forwardListCount = list->forwardListCount(); - if (forwardListCount > 0) - item = list->itemAtIndex(forwardListCount); - } else { - int backListCount = list->backListCount(); - if (backListCount > 0) - item = list->itemAtIndex(-backListCount); - } - } - if (item) - return item->url(); - } - return KURL(); -} - void FrameLoader::addHistoryItemForFragmentScroll() { addBackForwardItemClippedAtTarget(false); @@ -4375,6 +4377,11 @@ PassRefPtr FrameLoader::createHistoryItem(bool useOriginal) void FrameLoader::addBackForwardItemClippedAtTarget(bool doClip) { + // In the case of saving state about a page with frames, we store a tree of items that mirrors the frame tree. + // The item that was the target of the user's navigation is designated as the "targetItem". + // When this function is called with doClip=true we're able to create the whole tree except for the target's children, + // which will be loaded in the future. That part of the tree will be filled out as the child loads are committed. + Page* page = m_frame->page(); if (!page) return; @@ -4424,9 +4431,9 @@ PassRefPtr FrameLoader::createHistoryItemTree(Frame* targetFrame, b Frame* FrameLoader::findFrameForNavigation(const AtomicString& name) { Frame* frame = m_frame->tree()->find(name); - if (shouldAllowNavigation(frame)) - return frame; - return 0; + if (!shouldAllowNavigation(frame)) + return 0; + return frame; } void FrameLoader::saveScrollPositionAndViewStateToItem(HistoryItem* item) @@ -4539,13 +4546,16 @@ void FrameLoader::loadItem(HistoryItem* item, FrameLoadType loadType) // Note if we have child frames we do a real reload, since the child frames might not // match our current frame structure, or they might not have the right content. We could // check for all that as an additional optimization. - // We also do not do anchor-style navigation if we're posting a form. - + // We also do not do anchor-style navigation if we're posting a form or navigating from + // a page that was resulted from a form post. + bool shouldScroll = !formData && !(m_currentHistoryItem && m_currentHistoryItem->formData()) && urlsMatchItem(item); + #if ENABLE(WML) - if (!formData && urlsMatchItem(item) && !m_frame->document()->isWMLDocument()) { -#else - if (!formData && urlsMatchItem(item)) { + if (m_frame->document()->isWMLDocument()) + shouldScroll = false; #endif + + if (shouldScroll) { // Must do this maintenance here, since we don't go through a real page reload saveScrollPositionAndViewStateToItem(m_currentHistoryItem.get()); @@ -4756,10 +4766,10 @@ void FrameLoader::recursiveGoToItem(HistoryItem* item, HistoryItem* fromItem, Fr int size = childItems.size(); for (int i = 0; i < size; ++i) { - String childName = childItems[i]->target(); - HistoryItem* fromChildItem = fromItem->childItemWithName(childName); + String childFrameName = childItems[i]->target(); + HistoryItem* fromChildItem = fromItem->childItemWithTarget(childFrameName); ASSERT(fromChildItem || fromItem->isTargetItem()); - Frame* childFrame = m_frame->tree()->child(childName); + Frame* childFrame = m_frame->tree()->child(childFrameName); ASSERT(childFrame); childFrame->loader()->recursiveGoToItem(childItems[i].get(), fromChildItem, type); } @@ -4777,9 +4787,10 @@ bool FrameLoader::childFramesMatchItem(HistoryItem* item) const return false; unsigned size = childItems.size(); - for (unsigned i = 0; i < size; ++i) + for (unsigned i = 0; i < size; ++i) { if (!m_frame->tree()->child(childItems[i]->target())) return false; + } // Found matches for all item targets return true; @@ -4799,22 +4810,14 @@ void FrameLoader::updateHistoryForStandardLoad() bool needPrivacy = !settings || settings->privateBrowsingEnabled(); const KURL& historyURL = documentLoader()->urlForHistory(); - // If the navigation occured during load and this is a subframe, update the current - // back/forward item rather than adding a new one and don't add the new URL to global - // history at all. But do add it to visited links. - bool frameNavigationDuringLoad = false; - if (m_navigationDuringLoad) { - HTMLFrameOwnerElement* owner = m_frame->ownerElement(); - frameNavigationDuringLoad = owner && !owner->createdByParser(); - m_navigationDuringLoad = false; - } - - if (!frameNavigationDuringLoad && !documentLoader()->isClientRedirect()) { + if (!documentLoader()->isClientRedirect()) { if (!historyURL.isEmpty()) { addBackForwardItemClippedAtTarget(true); if (!needPrivacy) { m_client->updateGlobalHistory(); m_documentLoader->setDidCreateGlobalHistoryEntry(true); + if (m_documentLoader->unreachableURL().isEmpty()) + m_client->updateGlobalHistoryRedirectLinks(); } if (Page* page = m_frame->page()) page->setGlobalHistoryItem(needPrivacy ? 0 : page->backForwardList()->currentItem()); @@ -4905,6 +4908,8 @@ void FrameLoader::updateHistoryForRedirectWithLockedBackForwardList() if (!needPrivacy) { m_client->updateGlobalHistory(); m_documentLoader->setDidCreateGlobalHistoryEntry(true); + if (m_documentLoader->unreachableURL().isEmpty()) + m_client->updateGlobalHistoryRedirectLinks(); } if (Page* page = m_frame->page()) page->setGlobalHistoryItem(needPrivacy ? 0 : page->backForwardList()->currentItem()); @@ -4917,7 +4922,7 @@ void FrameLoader::updateHistoryForRedirectWithLockedBackForwardList() } else { Frame* parentFrame = m_frame->tree()->parent(); if (parentFrame && parentFrame->loader()->m_currentHistoryItem) - parentFrame->loader()->m_currentHistoryItem->addChildItem(createHistoryItem(true)); + parentFrame->loader()->m_currentHistoryItem->setChildItem(createHistoryItem(true)); } if (!historyURL.isEmpty() && !needPrivacy) { @@ -4975,8 +4980,6 @@ void FrameLoader::saveDocumentAndScrollState() } } -// FIXME: These 3 setter/getters are here for a dwindling number of users in WebKit, WebFrame -// being the primary one. After they're no longer needed there, they can be removed! HistoryItem* FrameLoader::currentHistoryItem() { return m_currentHistoryItem.get(); @@ -4987,11 +4990,6 @@ void FrameLoader::setCurrentHistoryItem(PassRefPtr item) m_currentHistoryItem = item; } -void FrameLoader::setProvisionalHistoryItem(PassRefPtr item) -{ - m_provisionalHistoryItem = item; -} - void FrameLoader::setMainDocumentError(DocumentLoader* loader, const ResourceError& error) { m_client->setMainDocumentError(loader, error); @@ -5193,19 +5191,24 @@ Widget* FrameLoader::createJavaAppletWidget(const IntSize& size, HTMLAppletEleme paramNames.append(it->first); paramValues.append(it->second); } - + + if (!codeBaseURLString.isEmpty()) { + KURL codeBaseURL = completeURL(codeBaseURLString); + if (!canLoad(codeBaseURL, String(), element->document())) { + FrameLoader::reportLocalLoadFailed(m_frame, codeBaseURL.string()); + return 0; + } + } + if (baseURLString.isEmpty()) baseURLString = m_frame->document()->baseURL().string(); KURL baseURL = completeURL(baseURLString); - Widget* widget = 0; - KURL codeBaseURL = completeURL(codeBaseURLString); - if (canLoad(codeBaseURL, String(), element->document())) { - widget = m_client->createJavaAppletWidget(size, element, baseURL, paramNames, paramValues); - if (widget) - m_containsPlugIns = true; - } + Widget* widget = m_client->createJavaAppletWidget(size, element, baseURL, paramNames, paramValues); + if (!widget) + return 0; + m_containsPlugIns = true; return widget; } @@ -5225,24 +5228,6 @@ void FrameLoader::didChangeTitle(DocumentLoader* loader) } } -void FrameLoader::continueLoadWithData(SharedBuffer* buffer, const String& mimeType, const String& textEncoding, const KURL& url) -{ - m_responseMIMEType = mimeType; - didOpenURL(url); - - String encoding; - if (m_frame) - encoding = documentLoader()->overrideEncoding(); - bool userChosen = !encoding.isNull(); - if (encoding.isNull()) - encoding = textEncoding; - setEncoding(encoding, userChosen); - - ASSERT(m_frame->document()); - - addData(buffer->data(), buffer->size()); -} - void FrameLoader::registerURLSchemeAsLocal(const String& scheme) { localSchemes().add(scheme); diff --git a/WebCore/loader/FrameLoader.h b/WebCore/loader/FrameLoader.h index 07acff3..07e530e 100644 --- a/WebCore/loader/FrameLoader.h +++ b/WebCore/loader/FrameLoader.h @@ -31,9 +31,9 @@ #define FrameLoader_h #include "CachePolicy.h" -#include "FormState.h" #include "FrameLoaderTypes.h" #include "ResourceRequest.h" +#include "ThreadableLoader.h" #include "Timer.h" namespace WebCore { @@ -47,9 +47,9 @@ namespace WebCore { class CachedResource; class Document; class DocumentLoader; - class Element; class Event; class FormData; + class FormState; class Frame; class FrameLoaderClient; class HistoryItem; @@ -64,6 +64,7 @@ namespace WebCore { class ResourceLoader; class ResourceResponse; class ScriptSourceCode; + class ScriptString; class ScriptValue; class SecurityOrigin; class SharedBuffer; @@ -71,7 +72,6 @@ namespace WebCore { class TextResourceDecoder; class Widget; - struct FormSubmission; struct FrameLoadRequest; struct ScheduledRedirection; struct WindowFeatures; @@ -122,56 +122,40 @@ namespace WebCore { Frame* frame() const { return m_frame; } - // FIXME: This is not cool, people. We should aim to consolidate these variety of loading related methods into a smaller set, - // and try to reuse more of the same logic by extracting common code paths. + // FIXME: This is not cool, people. There are too many different functions that all start loads. + // We should aim to consolidate these into a smaller set of functions, and try to reuse more of + // the logic by extracting common code paths. + void prepareForLoadStart(); void setupForReplace(); void setupForReplaceByMIMEType(const String& newMIMEType); - void loadWithDocumentLoader(DocumentLoader*, FrameLoadType, PassRefPtr); // Calls continueLoadAfterNavigationPolicy - void load(DocumentLoader*); // Calls loadWithDocumentLoader - - void loadWithNavigationAction(const ResourceRequest&, const NavigationAction&, // Calls loadWithDocumentLoader() - bool lockHistory, FrameLoadType, PassRefPtr); - -#ifdef ANDROID_USER_GESTURE - void loadPostRequest(const ResourceRequest&, const String& referrer, // Called by loadFrameRequestWithFormAndValues(), calls loadWithNavigationAction - const String& frameName, bool lockHistory, FrameLoadType, Event*, PassRefPtr, bool userGesture); - - void loadURL(const KURL& newURL, const String& referrer, const String& frameName, // Called by loadFrameRequestWithFormAndValues(), calls loadWithNavigationAction or else dispatches to navigation policy delegate - bool lockHistory, FrameLoadType, Event*, PassRefPtr, bool userGesture); -#else - void loadPostRequest(const ResourceRequest&, const String& referrer, // Called by loadFrameRequestWithFormAndValues(), calls loadWithNavigationAction - const String& frameName, bool lockHistory, FrameLoadType, Event*, PassRefPtr); - - void loadURL(const KURL& newURL, const String& referrer, const String& frameName, // Called by loadFrameRequestWithFormAndValues(), calls loadWithNavigationAction or else dispatches to navigation policy delegate - bool lockHistory, FrameLoadType, Event*, PassRefPtr); -#endif void loadURLIntoChildFrame(const KURL&, const String& referer, Frame*); - void loadFrameRequestWithFormAndValues(const FrameLoadRequest&, bool lockHistory, bool lockBackForwardList, // Called by submitForm, calls loadPostRequest() - Event*, HTMLFormElement*, const HashMap& formValues); + void loadFrameRequest(const FrameLoadRequest&, bool lockHistory, bool lockBackForwardList, // Called by submitForm, calls loadPostRequest and loadURL. + PassRefPtr, PassRefPtr); - void load(const ResourceRequest&, bool lockHistory); // Called by WebFrame, calls (ResourceRequest, SubstituteData) - void load(const ResourceRequest&, const SubstituteData&, bool lockHistory); // Called both by WebFrame and internally, calls (DocumentLoader*) - void load(const ResourceRequest&, const String& frameName, bool lockHistory); // Called by WebPluginController + void load(const ResourceRequest&, bool lockHistory); // Called by WebFrame, calls load(ResourceRequest, SubstituteData). + void load(const ResourceRequest&, const SubstituteData&, bool lockHistory); // Called both by WebFrame and internally, calls load(DocumentLoader*). + void load(const ResourceRequest&, const String& frameName, bool lockHistory); // Called by WebPluginController. #if ENABLE(ARCHIVE) // ANDROID extension: disabled to reduce code size - void loadArchive(PassRefPtr archive); + void loadArchive(PassRefPtr); #endif - // Returns true for any non-local URL. If Document parameter is supplied, its local load policy dictates, + // Returns true for any non-local URL. If document parameter is supplied, its local load policy dictates, // otherwise if referrer is non-empty and represents a local file, then the local load is allowed. - static bool canLoad(const KURL&, const String& referrer, const Document* theDocument = 0); + static bool canLoad(const KURL&, const String& referrer, const Document*); + static bool canLoad(const KURL&, const String& referrer, const SecurityOrigin* = 0); static void reportLocalLoadFailed(Frame*, const String& url); - static bool shouldHideReferrer(const KURL& url, const String& referrer); + static bool shouldHideReferrer(const KURL&, const String& referrer); // Called by createWindow in JSDOMWindowBase.cpp, e.g. to fulfill a modal dialog creation Frame* createWindow(FrameLoader* frameLoaderForFrameLookup, const FrameLoadRequest&, const WindowFeatures&, bool& created); - unsigned long loadResourceSynchronously(const ResourceRequest&, ResourceError&, ResourceResponse&, Vector& data); + unsigned long loadResourceSynchronously(const ResourceRequest&, StoredCredentials, ResourceError&, ResourceResponse&, Vector& data); bool canHandleRequest(const ResourceRequest&); @@ -187,7 +171,6 @@ namespace WebCore { String referrer() const; String outgoingReferrer() const; String outgoingOrigin() const; - void loadEmptyDocumentSynchronously(); DocumentLoader* activeDocumentLoader() const; DocumentLoader* documentLoader() const { return m_documentLoader.get(); } @@ -206,6 +189,7 @@ namespace WebCore { void didReceiveData(ResourceLoader*, const char*, int, int lengthReceived); void didFinishLoad(ResourceLoader*); void didFailToLoad(ResourceLoader*, const ResourceError&); + void didLoadResourceByXMLHttpRequest(unsigned long identifier, const ScriptString& sourceString); const ResourceRequest& originalRequest() const; const ResourceRequest& initialRequest() const; void receivedMainResourceError(const ResourceError&, bool isComplete); @@ -230,8 +214,6 @@ namespace WebCore { bool representationExistsForURLScheme(const String& URLScheme); String generatedMIMETypeForURLScheme(const String& URLScheme); - void notifyIconChanged(); - void checkNavigationPolicy(const ResourceRequest&, NavigationPolicyDecisionFunction function, void* argument); void checkContentPolicy(const String& MIMEType, ContentPolicyDecisionFunction, void* argument); void cancelContentPolicyCheck(); @@ -252,32 +234,22 @@ namespace WebCore { void didChangeTitle(DocumentLoader*); FrameLoadType loadType() const; - CachePolicy cachePolicy() const; + CachePolicy subresourceCachePolicy() const; void didFirstLayout(); bool firstLayoutDone() const; void didFirstVisuallyNonEmptyLayout(); - void clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress); - void clientRedirected(const KURL&, double delay, double fireDate, bool lockBackForwardList, bool isJavaScriptFormAction); - bool shouldReload(const KURL& currentURL, const KURL& destinationURL); #if ENABLE(WML) void setForceReloadWmlDeck(bool); #endif - bool isQuickRedirectComing() const; - - void sendRemainingDelegateMessages(unsigned long identifier, const ResourceResponse&, int length, const ResourceError&); - void requestFromDelegate(ResourceRequest&, unsigned long& identifier, ResourceError&); void loadedResourceFromMemoryCache(const CachedResource*); void tellClientAboutPastMemoryCacheLoads(); - void recursiveCheckLoadComplete(); void checkLoadComplete(); void detachFromParent(); - void detachChildren(); - void closeAndRemoveChild(Frame*); void addExtraFieldsToSubresourceRequest(ResourceRequest&); void addExtraFieldsToMainResourceRequest(ResourceRequest&); @@ -288,17 +260,13 @@ namespace WebCore { void setDefersLoading(bool); - void changeLocation(const String& url, const String& referrer, bool lockHistory = true, bool lockBackForwardList = true, bool userGesture = false, bool refresh = false); void changeLocation(const KURL&, const String& referrer, bool lockHistory = true, bool lockBackForwardList = true, bool userGesture = false, bool refresh = false); - void urlSelected(const ResourceRequest&, const String& target, Event*, bool lockHistory, bool lockBackForwardList, bool userGesture); - void urlSelected(const FrameLoadRequest&, Event*, bool lockHistory, bool lockBackForwardList); - + void urlSelected(const ResourceRequest&, const String& target, PassRefPtr, bool lockHistory, bool lockBackForwardList, bool userGesture); bool requestFrame(HTMLFrameOwnerElement*, const String& url, const AtomicString& frameName); - Frame* loadSubframe(HTMLFrameOwnerElement*, const KURL&, const String& name, const String& referrer); - void submitForm(const char* action, const String& url, PassRefPtr, const String& target, const String& contentType, const String& boundary, Event*, bool lockHistory, bool lockBackForwardList); - void submitFormAgain(); - void submitForm(const FrameLoadRequest&, Event*, bool lockHistory, bool lockBackForwardList); + void submitForm(const char* action, const String& url, + PassRefPtr, const String& target, const String& contentType, const String& boundary, + bool lockHistory, bool lockBackForwardList, PassRefPtr, PassRefPtr); void stop(); void stopLoading(bool sendUnload, DatabasePolicy = DatabasePolicyStop); @@ -310,8 +278,6 @@ namespace WebCore { void commitIconURLToIconDatabase(const KURL&); KURL baseURL() const; - String baseTarget() const; - KURL dataURLBaseFromRequest(const ResourceRequest& request) const; bool isScheduledLocationChangePending() const { return m_scheduledRedirection && isLocationChange(*m_scheduledRedirection); } void scheduleHTTPRedirection(double delay, const String& url); @@ -322,12 +288,11 @@ namespace WebCore { bool canGoBackOrForward(int distance) const; void goBackOrForward(int distance); int getHistoryLength(); - KURL historyURL(int distance); void begin(); void begin(const KURL&, bool dispatchWindowObjectAvailable = true, SecurityOrigin* forcedSecurityOrigin = 0); - void write(const char* str, int len = -1, bool flush = false); + void write(const char* string, int length = -1, bool flush = false); void write(const String&); void end(); void endIfNotLoadingMainResource(); @@ -335,15 +300,10 @@ namespace WebCore { void setEncoding(const String& encoding, bool userChosen); String encoding() const; - // Returns true if url is a JavaScript URL. - bool executeIfJavaScriptURL(const KURL& url, bool userGesture = false, bool replaceDocument = true); - ScriptValue executeScript(const ScriptSourceCode&); ScriptValue executeScript(const String& script, bool forceUserGesture = false); void gotoAnchor(); - bool gotoAnchor(const String& name); // returns true if the anchor was found - void scrollToAnchor(const KURL&); void tokenizerProcessedData(); @@ -361,26 +321,18 @@ namespace WebCore { bool openedByDOM() const; void setOpenedByDOM(); - void provisionalLoadStarted(); - bool userGestureHint(); void resetMultipleFormSubmissionProtection(); - void didNotOpenURL(const KURL&); void addData(const char* bytes, int length); - bool canCachePage(); - void checkCallImplicitClose(); - bool didOpenURL(const KURL&); void frameDetached(); const KURL& url() const { return m_URL; } - void updateBaseURLForEmptyDocument(); - void setResponseMIMEType(const String&); const String& responseMIMEType() const; @@ -389,12 +341,6 @@ namespace WebCore { void loadDone(); void finishedParsing(); void checkCompleted(); - void scheduleCheckCompleted(); - void scheduleCheckLoadComplete(); - - void clearRecordedFormValues(); - void setFormAboutToBeSubmitted(PassRefPtr element); - void recordFormValue(const String& name, const String& value); bool isComplete() const; @@ -403,32 +349,22 @@ namespace WebCore { KURL completeURL(const String& url); - KURL originalRequestURL() const; - void cancelAndClear(); void setTitle(const String&); - - bool shouldTreatURLAsSameAsCurrent(const KURL&) const; void commitProvisionalLoad(PassRefPtr); void goToItem(HistoryItem*, FrameLoadType); void saveDocumentAndScrollState(); - void saveScrollPositionAndViewStateToItem(HistoryItem*); - // FIXME: These accessors are here for a dwindling number of users in WebKit, WebFrame - // being the primary one. After they're no longer needed there, they can be removed! HistoryItem* currentHistoryItem(); void setCurrentHistoryItem(PassRefPtr); - void setProvisionalHistoryItem(PassRefPtr); - - void continueLoadWithData(SharedBuffer*, const String& mimeType, const String& textEncoding, const KURL&); enum LocalLoadPolicy { - AllowLocalLoadsForAll, // No restriction on local loads. - AllowLocalLoadsForLocalAndSubstituteData, - AllowLocalLoadsForLocalOnly, + AllowLocalLoadsForAll, // No restriction on local loads. + AllowLocalLoadsForLocalAndSubstituteData, + AllowLocalLoadsForLocalOnly, }; static void setLocalLoadPolicy(LocalLoadPolicy); static bool restrictAccessToLocal(); @@ -452,6 +388,8 @@ namespace WebCore { void applyUserAgent(ResourceRequest& request); + bool shouldInterruptLoadForXFrameOptions(const String&, const KURL&); + private: PassRefPtr createHistoryItem(bool useOriginal); PassRefPtr createHistoryItemTree(Frame* targetFrame, bool clipAtTarget); @@ -499,8 +437,8 @@ namespace WebCore { void receivedFirstData(); - void updatePolicyBaseURL(); - void setPolicyBaseURL(const KURL&); + void updateFirstPartyForCookies(); + void setFirstPartyForCookies(const KURL&); void addExtraFieldsToRequest(ResourceRequest&, FrameLoadType loadType, bool isMainResource, bool cookiePolicyURLFromRequest); @@ -516,10 +454,8 @@ namespace WebCore { void setLoadType(FrameLoadType); - void checkNavigationPolicy(const ResourceRequest&, DocumentLoader*, PassRefPtr, - NavigationPolicyDecisionFunction, void* argument); - void checkNewWindowPolicy(const NavigationAction&, const ResourceRequest&, - PassRefPtr, const String& frameName); + void checkNavigationPolicy(const ResourceRequest&, DocumentLoader*, PassRefPtr, NavigationPolicyDecisionFunction, void* argument); + void checkNewWindowPolicy(const NavigationAction&, const ResourceRequest&, PassRefPtr, const String& frameName); void continueAfterNavigationPolicy(PolicyAction); void continueAfterNewWindowPolicy(PolicyAction); @@ -532,13 +468,11 @@ namespace WebCore { void continueLoadAfterNewWindowPolicy(const ResourceRequest&, PassRefPtr, const String& frameName, bool shouldContinue); static void callContinueFragmentScrollAfterNavigationPolicy(void*, const ResourceRequest&, PassRefPtr, bool shouldContinue); void continueFragmentScrollAfterNavigationPolicy(const ResourceRequest&, bool shouldContinue); - bool shouldScrollToAnchor(bool isFormSubmission, FrameLoadType loadType, const KURL& url); + bool shouldScrollToAnchor(bool isFormSubmission, FrameLoadType, const KURL&); void addHistoryItemForFragmentScroll(); void stopPolicyCheck(); - void closeDocument(); - void checkLoadCompleteForThisFrame(); void setDocumentLoader(DocumentLoader*); @@ -570,6 +504,65 @@ namespace WebCore { void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier); static bool isLocationChange(const ScheduledRedirection&); + void scheduleFormSubmission(const FrameLoadRequest&, bool lockHistory, bool lockBackForwardList, PassRefPtr, PassRefPtr); + + void loadWithDocumentLoader(DocumentLoader*, FrameLoadType, PassRefPtr); // Calls continueLoadAfterNavigationPolicy + void load(DocumentLoader*); // Calls loadWithDocumentLoader + + void loadWithNavigationAction(const ResourceRequest&, const NavigationAction&, // Calls loadWithDocumentLoader + bool lockHistory, FrameLoadType, PassRefPtr); + +#ifdef ANDROID_USER_GESTURE +// FIXME (klobag): WebKit/android/jni/WebCoreFrameBridge.cpp uses +// loadPostRequest, figure out if we can use load(...) instead of +// making loadPostRequest public. +public: + void loadPostRequest(const ResourceRequest&, const String& referrer, // Called by loadFrameRequest, calls loadWithNavigationAction + const String& frameName, bool lockHistory, FrameLoadType, PassRefPtr, PassRefPtr, bool userGesture); +private: + void loadURL(const KURL&, const String& referrer, const String& frameName, // Called by loadFrameRequest, calls loadWithNavigationAction or dispatches to navigation policy delegate + bool lockHistory, FrameLoadType, PassRefPtr, PassRefPtr, bool userGesture); +#endif // ANDROID_USER_GESTURE + + void loadPostRequest(const ResourceRequest&, const String& referrer, // Called by loadFrameRequest, calls loadWithNavigationAction + const String& frameName, bool lockHistory, FrameLoadType, PassRefPtr, PassRefPtr); + void loadURL(const KURL&, const String& referrer, const String& frameName, // Called by loadFrameRequest, calls loadWithNavigationAction or dispatches to navigation policy delegate + bool lockHistory, FrameLoadType, PassRefPtr, PassRefPtr); + + void clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress); + void clientRedirected(const KURL&, double delay, double fireDate, bool lockBackForwardList); + bool shouldReload(const KURL& currentURL, const KURL& destinationURL); + + void sendRemainingDelegateMessages(unsigned long identifier, const ResourceResponse&, int length, const ResourceError&); + void requestFromDelegate(ResourceRequest&, unsigned long& identifier, ResourceError&); + + void recursiveCheckLoadComplete(); + + void detachChildren(); + void closeAndRemoveChild(Frame*); + + Frame* loadSubframe(HTMLFrameOwnerElement*, const KURL&, const String& name, const String& referrer); + + // Returns true if argument is a JavaScript URL. + bool executeIfJavaScriptURL(const KURL&, bool userGesture = false, bool replaceDocument = true); + + bool gotoAnchor(const String& name); // returns true if the anchor was found + void scrollToAnchor(const KURL&); + + void provisionalLoadStarted(); + + bool canCachePage(); + + bool didOpenURL(const KURL&); + + void scheduleCheckCompleted(); + void scheduleCheckLoadComplete(); + + KURL originalRequestURL() const; + + bool shouldTreatURLAsSameAsCurrent(const KURL&) const; + + void saveScrollPositionAndViewStateToItem(HistoryItem*); Frame* m_frame; FrameLoaderClient* m_client; @@ -599,12 +592,9 @@ namespace WebCore { bool m_quickRedirectComing; bool m_sentRedirectNotification; bool m_inStopAllLoaders; - bool m_navigationDuringLoad; String m_outgoingReferrer; - OwnPtr m_deferredFormSubmission; - bool m_isExecutingJavaScriptFormAction; bool m_isRunningScript; @@ -612,6 +602,7 @@ namespace WebCore { bool m_didCallImplicitClose; bool m_wasUnloadEventEmitted; + bool m_unloadEventBeingDispatched; bool m_isComplete; bool m_isLoadingMainResource; @@ -634,8 +625,6 @@ namespace WebCore { bool m_containsPlugIns; - RefPtr m_formAboutToBeSubmitted; - HashMap m_formValuesAboutToBeSubmitted; KURL m_submittedFormURL; Timer m_redirectionTimer; diff --git a/WebCore/loader/FrameLoaderClient.h b/WebCore/loader/FrameLoaderClient.h index 4f2b86e..5e5191b 100644 --- a/WebCore/loader/FrameLoaderClient.h +++ b/WebCore/loader/FrameLoaderClient.h @@ -64,6 +64,7 @@ namespace WebCore { class ResourceLoader; struct ResourceRequest; class ResourceResponse; + class ScriptString; class SharedBuffer; class SubstituteData; class String; @@ -109,6 +110,7 @@ namespace WebCore { virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier) = 0; virtual void dispatchDidFailLoading(DocumentLoader*, unsigned long identifier, const ResourceError&) = 0; virtual bool dispatchDidLoadResourceFromMemoryCache(DocumentLoader*, const ResourceRequest&, const ResourceResponse&, int length) = 0; + virtual void dispatchDidLoadResourceByXMLHttpRequest(unsigned long identifier, const ScriptString&) = 0; virtual void dispatchDidHandleOnloadEvents() = 0; virtual void dispatchDidReceiveServerRedirectForProvisionalLoad() = 0; diff --git a/WebCore/loader/ImageDocument.cpp b/WebCore/loader/ImageDocument.cpp index ca3f785..08f2e9a 100644 --- a/WebCore/loader/ImageDocument.cpp +++ b/WebCore/loader/ImageDocument.cpp @@ -25,6 +25,7 @@ #include "config.h" #include "ImageDocument.h" +#include "CSSStyleDeclaration.h" #include "CachedImage.h" #include "DocumentLoader.h" #include "Element.h" @@ -37,6 +38,7 @@ #include "HTMLNames.h" #include "LocalizedStrings.h" #include "MouseEvent.h" +#include "NotImplemented.h" #include "Page.h" #include "SegmentedString.h" #include "Settings.h" @@ -93,7 +95,8 @@ private: void ImageTokenizer::write(const SegmentedString&, bool) { - ASSERT_NOT_REACHED(); + // : JS code can always call document.write, we need to handle it. + notImplemented(); } bool ImageTokenizer::writeRawData(const char*, int) @@ -124,9 +127,9 @@ void ImageTokenizer::finish() IntSize size = cachedImage->imageSize(m_doc->frame()->pageZoomFactor()); if (size.width()) { - // Compute the title, we use the filename of the resource, falling - // back on the hostname if there is no path. - String fileName = m_doc->url().lastPathComponent(); + // Compute the title, we use the decoded filename of the resource, falling + // back on the (decoded) hostname if there is no path. + String fileName = decodeURLEscapeSequences(m_doc->url().lastPathComponent()); if (fileName.isEmpty()) fileName = m_doc->url().host(); m_doc->setTitle(imageTitle(fileName, size)); @@ -184,7 +187,8 @@ void ImageDocument::createDocumentStructure() if (shouldShrinkToFit()) { // Add event listeners RefPtr listener = ImageEventListener::create(this); - addWindowEventListener("resize", listener, false); + if (DOMWindow* domWindow = this->domWindow()) + domWindow->addEventListener("resize", listener, false); imageElement->addEventListener("click", listener.release(), false); } diff --git a/WebCore/loader/MainResourceLoader.cpp b/WebCore/loader/MainResourceLoader.cpp index 5aa1cde..39e5b90 100644 --- a/WebCore/loader/MainResourceLoader.cpp +++ b/WebCore/loader/MainResourceLoader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * * Redistribution and use in source and binary forms, with or without @@ -30,12 +30,8 @@ #include "config.h" #include "MainResourceLoader.h" -#if ENABLE(OFFLINE_WEB_APPLICATIONS) -#include "ApplicationCache.h" -#include "ApplicationCacheGroup.h" -#include "ApplicationCacheResource.h" -#endif #include "DocumentLoader.h" +#include "FormState.h" #include "Frame.h" #include "FrameLoader.h" #include "FrameLoaderClient.h" @@ -45,6 +41,12 @@ #include "ResourceHandle.h" #include "Settings.h" +#if ENABLE(OFFLINE_WEB_APPLICATIONS) +#include "ApplicationCache.h" +#include "ApplicationCacheGroup.h" +#include "ApplicationCacheResource.h" +#endif + // FIXME: More that is in common with SubresourceLoader should move up into ResourceLoader. namespace WebCore { @@ -161,7 +163,7 @@ void MainResourceLoader::willSendRequest(ResourceRequest& newRequest, const Reso // Update cookie policy base URL as URL changes, except for subframes, which use the // URL of the main frame which doesn't change when we redirect. if (frameLoader()->isLoadingMainFrame()) - newRequest.setMainDocumentURL(newRequest.url()); + newRequest.setFirstPartyForCookies(newRequest.url()); // If we're fielding a redirect in response to a POST, force a load from origin, since // this is a common site technique to return to a page viewing some data that the POST @@ -179,9 +181,10 @@ void MainResourceLoader::willSendRequest(ResourceRequest& newRequest, const Reso // listener. But there's no way to do that in practice. So instead we cancel later if the // listener tells us to. In practice that means the navigation policy needs to be decided // synchronously for these redirect cases. - - ref(); // balanced by deref in continueAfterNavigationPolicy - frameLoader()->checkNavigationPolicy(newRequest, callContinueAfterNavigationPolicy, this); + if (!redirectResponse.isNull()) { + ref(); // balanced by deref in continueAfterNavigationPolicy + frameLoader()->checkNavigationPolicy(newRequest, callContinueAfterNavigationPolicy, this); + } } static bool shouldLoadAsEmptyDocument(const KURL& url) @@ -291,6 +294,15 @@ void MainResourceLoader::didReceiveResponse(const ResourceResponse& r) } #endif + HTTPHeaderMap::const_iterator it = r.httpHeaderFields().find(AtomicString("x-frame-options")); + if (it != r.httpHeaderFields().end()) { + String content = it->second; + if (m_frame->loader()->shouldInterruptLoadForXFrameOptions(content, r.url())) { + cancel(); + return; + } + } + // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred. // See for more details. #if !PLATFORM(CF) diff --git a/WebCore/loader/MediaDocument.cpp b/WebCore/loader/MediaDocument.cpp index b89ac10..0b1fd59 100644 --- a/WebCore/loader/MediaDocument.cpp +++ b/WebCore/loader/MediaDocument.cpp @@ -38,7 +38,9 @@ #include "HTMLEmbedElement.h" #include "HTMLNames.h" #include "HTMLVideoElement.h" +#include "KeyboardEvent.h" #include "MainResourceLoader.h" +#include "NodeList.h" #include "Page.h" #include "SegmentedString.h" #include "Settings.h" @@ -133,10 +135,16 @@ bool MediaTokenizer::isWaitingForScripts() const MediaDocument::MediaDocument(Frame* frame) : HTMLDocument(frame) + , m_replaceMediaElementTimer(this, &MediaDocument::replaceMediaElementTimerFired) { setParseMode(Compat); } +MediaDocument::~MediaDocument() +{ + ASSERT(!m_replaceMediaElementTimer.isActive()); +} + Tokenizer* MediaDocument::createTokenizer() { return new MediaTokenizer(this); @@ -161,6 +169,69 @@ void MediaDocument::defaultEventHandler(Event* event) } } } + + if (event->type() == eventNames().keydownEvent && event->isKeyboardEvent()) { + HTMLVideoElement* video = 0; + if (targetNode) { + if (targetNode->hasTagName(videoTag)) + video = static_cast(targetNode); + else { + RefPtr nodeList = targetNode->getElementsByTagName("video"); + if (nodeList.get()->length() > 0) + video = static_cast(nodeList.get()->item(0)); + } + } + if (video) { + KeyboardEvent* keyboardEvent = static_cast(event); + if (keyboardEvent->keyIdentifier() == "U+0020") { // space + if (video->paused()) { + if (video->canPlay()) + video->play(); + } else + video->pause(); + event->setDefaultHandled(); + } + } + } +} + +void MediaDocument::mediaElementSawUnsupportedTracks() +{ + // The HTMLMediaElement was told it has something that the underlying + // MediaPlayer cannot handle so we should switch from