#include "config.h"
#include "FrameLoader.h"
#include "Archive.h"
#include "ArchiveFactory.h"
#include "CString.h"
#include "Cache.h"
#include "CachedPage.h"
#include "Chrome.h"
#include "DOMImplementation.h"
#include "DOMWindow.h"
#include "DocLoader.h"
#include "Document.h"
#include "DocumentLoader.h"
#include "Editor.h"
#include "EditorClient.h"
#include "Element.h"
#include "Event.h"
#include "EventNames.h"
#include "FloatRect.h"
#include "FormState.h"
#include "Frame.h"
#include "FrameLoadRequest.h"
#include "FrameLoaderClient.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "HTMLAnchorElement.h"
#include "HTMLFormElement.h"
#include "HTMLFrameElement.h"
#include "HTMLNames.h"
#include "HTMLObjectElement.h"
#include "HTTPParsers.h"
#include "HistoryItem.h"
#include "IconDatabase.h"
#include "IconLoader.h"
#include "InspectorController.h"
#include "Logging.h"
#include "MIMETypeRegistry.h"
#include "MainResourceLoader.h"
#include "Page.h"
#include "PageCache.h"
#include "PageGroup.h"
#include "PluginData.h"
#include "PluginDocument.h"
#include "ProgressTracker.h"
#include "RenderPart.h"
#include "RenderView.h"
#include "RenderWidget.h"
#include "ResourceHandle.h"
#include "ResourceRequest.h"
#include "ScriptController.h"
#include "ScriptSourceCode.h"
#include "ScriptValue.h"
#include "SecurityOrigin.h"
#include "SegmentedString.h"
#include "Settings.h"
#include "TextResourceDecoder.h"
#include "WindowFeatures.h"
#include "XMLHttpRequest.h"
#include "XMLTokenizer.h"
#include <wtf/CurrentTime.h>
#include <wtf/StdLibExtras.h>
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
#include "ApplicationCache.h"
#include "ApplicationCacheResource.h"
#endif
#if ENABLE(SVG)
#include "SVGDocument.h"
#include "SVGLocatable.h"
#include "SVGNames.h"
#include "SVGPreserveAspectRatio.h"
#include "SVGSVGElement.h"
#include "SVGViewElement.h"
#include "SVGViewSpec.h"
#endif
#include "ChromeClient.h"
#include "WKContentObservation.h"
namespace WebCore {
#if ENABLE(SVG)
using namespace SVGNames;
#endif
using namespace HTMLNames;
const char* cMobileQuickLookProtocol = "x-apple-ql-id";
#if USE(LOW_BANDWIDTH_DISPLAY)
const unsigned int cMaxPendingSourceLengthInLowBandwidthDisplay = 128 * 1024;
#endif
typedef HashSet<String, CaseFoldingHash> LocalSchemesMap;
struct ScheduledRedirection {
enum Type { redirection, locationChange, historyNavigation, formSubmission };
const Type type;
const double delay;
const String url;
const String referrer;
const FrameLoadRequest frameRequest;
const RefPtr<Event> event;
const RefPtr<FormState> 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)
, delay(delay)
, url(url)
, historySteps(0)
, lockHistory(lockHistory)
, lockBackForwardList(lockBackForwardList)
, wasUserGesture(wasUserGesture)
, wasRefresh(refresh)
, wasDuringLoad(false)
{
ASSERT(!url.isEmpty());
}
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)
, historySteps(0)
, lockHistory(lockHistory)
, lockBackForwardList(lockBackForwardList)
, wasUserGesture(wasUserGesture)
, wasRefresh(refresh)
, wasDuringLoad(duringLoad)
{
ASSERT(!url.isEmpty());
}
explicit ScheduledRedirection(int historyNavigationSteps)
: type(historyNavigation)
, delay(0)
, historySteps(historyNavigationSteps)
, lockHistory(false)
, lockBackForwardList(false)
, wasUserGesture(false)
, wasRefresh(false)
, wasDuringLoad(false)
{
}
ScheduledRedirection(const FrameLoadRequest& frameRequest,
bool lockHistory, bool lockBackForwardList, PassRefPtr<Event> event, PassRefPtr<FormState> 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);
}
};
static double storedTimeOfLastCompletedLoad;
static FrameLoader::LocalLoadPolicy localLoadPolicy = FrameLoader::AllowLocalLoadsForLocalOnly;
bool isBackForwardLoadType(FrameLoadType type)
{
switch (type) {
case FrameLoadTypeStandard:
case FrameLoadTypeReload:
case FrameLoadTypeReloadFromOrigin:
case FrameLoadTypeSame:
case FrameLoadTypeRedirectWithLockedBackForwardList:
case FrameLoadTypeReplace:
return false;
case FrameLoadTypeBack:
case FrameLoadTypeForward:
case FrameLoadTypeIndexedBackForward:
return true;
}
ASSERT_NOT_REACHED();
return false;
}
static int numRequests(Document* document)
{
if (!document)
return 0;
return document->docLoader()->requestCount();
}
FrameLoader::FrameLoader(Frame* frame, FrameLoaderClient* client)
: m_frame(frame)
, m_client(client)
, m_state(FrameStateCommittedPage)
, m_loadType(FrameLoadTypeStandard)
, m_policyLoadType(FrameLoadTypeStandard)
, m_delegateIsHandlingProvisionalLoadError(false)
, m_delegateIsDecidingNavigationPolicy(false)
, m_delegateIsHandlingUnimplementablePolicy(false)
, m_firstLayoutDone(false)
, m_quickRedirectComing(false)
, m_sentRedirectNotification(false)
, m_inStopAllLoaders(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)
, m_needsClear(false)
, m_receivedData(false)
, m_encodingWasChosenByUser(false)
, m_containsPlugIns(false)
, m_redirectionTimer(this, &FrameLoader::redirectionTimerFired)
, m_checkCompletedTimer(this, &FrameLoader::checkCompletedTimerFired)
, m_checkLoadCompleteTimer(this, &FrameLoader::checkLoadCompleteTimerFired)
, m_opener(0)
, m_openedByDOM(false)
, m_creatingInitialEmptyDocument(false)
, m_isDisplayingInitialEmptyDocument(false)
, m_committedFirstRealDocumentLoad(false)
, m_didPerformFirstNavigation(false)
#ifndef NDEBUG
, m_didDispatchDidCommitLoad(false)
#endif
#if USE(LOW_BANDWIDTH_DISPLAY)
, m_useLowBandwidthDisplay(true)
, m_finishedParsingDuringLowBandwidthDisplay(false)
, m_needToSwitchOutLowBandwidthDisplay(false)
#endif
, m_loadsSynchronously(false)
#if ENABLE(WML)
, m_forceReloadWmlDeck(false)
#endif
{
}
FrameLoader::~FrameLoader()
{
setOpener(0);
HashSet<Frame*>::iterator end = m_openedFrames.end();
for (HashSet<Frame*>::iterator it = m_openedFrames.begin(); it != end; ++it)
(*it)->loader()->m_opener = 0;
m_client->frameLoaderDestroyed();
}
void FrameLoader::init()
{
m_isDisplayingInitialEmptyDocument = false;
m_creatingInitialEmptyDocument = true;
setPolicyDocumentLoader(m_client->createDocumentLoader(ResourceRequest(KURL("")), SubstituteData()).get());
setProvisionalDocumentLoader(m_policyDocumentLoader.get());
setState(FrameStateProvisional);
m_provisionalDocumentLoader->setResponse(ResourceResponse(KURL(), "text/html", 0, String(), String()));
m_provisionalDocumentLoader->finishedLoading();
begin(KURL(), false);
end();
m_frame->document()->cancelParsing();
m_creatingInitialEmptyDocument = false;
m_didCallImplicitClose = true;
}
void FrameLoader::initForSynthesizedDocument(const KURL& url)
{
RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(ResourceRequest(KURL("")), SubstituteData());
loader->setFrame(m_frame);
loader->setResponse(ResourceResponse(KURL(), "text/html", 0, String(), String()));
setDocumentLoader(loader.get());
m_URL = url;
m_committedFirstRealDocumentLoad = true;
m_client->transitionToCommittedForNewPage();
m_didCallImplicitClose = true;
m_isComplete = true;
m_state = FrameStateComplete;
m_needsClear = true;
}
void FrameLoader::setDefersLoading(bool defers)
{
if (m_documentLoader)
m_documentLoader->setDefersLoading(defers);
if (m_provisionalDocumentLoader)
m_provisionalDocumentLoader->setDefersLoading(defers);
if (m_policyDocumentLoader)
m_policyDocumentLoader->setDefersLoading(defers);
}
Frame* FrameLoader::createWindow(FrameLoader* frameLoaderForFrameLookup, const FrameLoadRequest& request, const WindowFeatures& features, bool& created, bool userGesture)
{
ASSERT(!features.dialog || request.frameName().isEmpty());
if (!request.frameName().isEmpty() && request.frameName() != "_blank") {
Frame* frame = frameLoaderForFrameLookup->frame()->tree()->find(request.frameName());
if (frame && shouldAllowNavigation(frame)) {
if (!request.resourceRequest().url().isEmpty())
frame->loader()->loadFrameRequest(request, false, false, userGesture, 0, 0);
if (Page* page = frame->page())
page->chrome()->focus(userGesture);
created = false;
return frame;
}
}
FrameLoadRequest requestWithReferrer = request;
requestWithReferrer.resourceRequest().setHTTPReferrer(m_outgoingReferrer);
addHTTPOriginIfNeeded(requestWithReferrer.resourceRequest(), outgoingOrigin());
Page* oldPage = m_frame->page();
if (!oldPage)
return 0;
Page* page = oldPage->chrome()->createWindow(m_frame, requestWithReferrer, features, userGesture);
if (!page)
return 0;
Frame* frame = page->mainFrame();
if (request.frameName() != "_blank")
frame->tree()->setName(request.frameName());
page->chrome()->setToolbarsVisible(features.toolBarVisible || features.locationBarVisible);
page->chrome()->setStatusbarVisible(features.statusBarVisible);
page->chrome()->setScrollbarsVisible(features.scrollbarsVisible);
page->chrome()->setMenubarVisible(features.menuBarVisible);
page->chrome()->setResizable(features.resizable);
FloatRect windowRect = page->chrome()->windowRect();
FloatSize pageSize = page->chrome()->pageRect().size();
if (features.xSet)
windowRect.setX(features.x);
if (features.ySet)
windowRect.setY(features.y);
ViewportArguments arguments;
if (features.widthSet)
arguments.width = features.width;
if (features.heightSet)
arguments.height = features.height;
frame->setViewportArguments(arguments);
page->chrome()->show();
created = true;
return frame;
}
bool FrameLoader::canHandleRequest(const ResourceRequest& request)
{
return m_client->canHandleRequest(request);
}
void FrameLoader::changeLocation(const KURL& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool userGesture, bool refresh)
{
RefPtr<Frame> protect(m_frame);
ResourceRequest request(url, referrer, refresh ? ReloadIgnoringCacheData : UseProtocolCachePolicy);
if (executeIfJavaScriptURL(request.url(), userGesture))
return;
urlSelected(request, "_self", 0, lockHistory, lockBackForwardList, userGesture);
}
void FrameLoader::urlSelected(const ResourceRequest& request, const String& passedTarget, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, bool userGesture)
{
if (executeIfJavaScriptURL(request.url(), userGesture, false))
return;
String target = passedTarget;
if (target.isEmpty() && m_frame->document())
target = m_frame->document()->baseTarget();
FrameLoadRequest frameRequest(request, target);
if (frameRequest.resourceRequest().httpReferrer().isEmpty())
frameRequest.resourceRequest().setHTTPReferrer(m_outgoingReferrer);
addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin());
loadFrameRequest(frameRequest, lockHistory, lockBackForwardList, userGesture, triggeringEvent, 0);
}
bool FrameLoader::requestFrame(HTMLFrameOwnerElement* ownerElement, const String& urlString, const AtomicString& frameName)
{
#if USE(LOW_BANDWIDTH_DISPLAY)
if (frame()->document()->inLowBandwidthDisplay()) {
m_needToSwitchOutLowBandwidthDisplay = true;
return false;
}
#endif
KURL scriptURL;
KURL url;
if (protocolIs(urlString, "javascript")) {
scriptURL = completeURL(urlString); url = blankURL();
} else
url = completeURL(urlString);
Frame* frame = ownerElement->contentFrame();
if (frame)
frame->loader()->scheduleLocationChange(url.string(), m_outgoingReferrer, true, true, userGestureHint());
else
frame = loadSubframe(ownerElement, url, frameName, m_outgoingReferrer);
if (!frame)
return false;
if (!scriptURL.isEmpty())
frame->loader()->executeIfJavaScriptURL(scriptURL);
return true;
}
Frame* FrameLoader::loadSubframe(HTMLFrameOwnerElement* ownerElement, const KURL& url, const String& name, const String& referrer)
{
bool allowsScrolling = true;
int marginWidth = -1;
int marginHeight = -1;
if (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag)) {
HTMLFrameElementBase* o = static_cast<HTMLFrameElementBase*>(ownerElement);
allowsScrolling = o->scrollingMode() != ScrollbarAlwaysOff;
marginWidth = o->getMarginWidth();
marginHeight = o->getMarginHeight();
}
if (!canLoad(url, referrer)) {
FrameLoader::reportLocalLoadFailed(m_frame, url.string());
return 0;
}
bool hideReferrer = shouldHideReferrer(url, referrer);
RefPtr<Frame> frame = m_client->createFrame(url, name, ownerElement, hideReferrer ? String() : referrer, allowsScrolling, marginWidth, marginHeight);
if (!frame) {
checkCallImplicitClose();
return 0;
}
frame->loader()->m_isComplete = false;
RenderObject* renderer = ownerElement->renderer();
FrameView* view = frame->view();
if (renderer && renderer->isWidget() && view)
static_cast<RenderWidget*>(renderer)->setWidget(view);
checkCallImplicitClose();
if (url.isEmpty() || url == blankURL()) {
frame->loader()->completed();
frame->loader()->checkCompleted();
}
return frame.get();
}
void FrameLoader::submitForm(const char* action, const String& url, PassRefPtr<FormData> formData,
const String& target, const String& contentType, const String& boundary,
bool lockHistory, bool lockBackForwardList, PassRefPtr<Event> event, PassRefPtr<FormState> 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);
if (u.isEmpty())
return;
if (u.protocolIs("javascript")) {
m_isExecutingJavaScriptFormAction = true;
executeIfJavaScriptURL(u, false, false);
m_isExecutingJavaScriptFormAction = false;
return;
}
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;
if (m_frame->tree()->isDescendantOf(targetFrame)) {
if (m_submittedFormURL == u)
return;
m_submittedFormURL = u;
}
formData->generateFiles(m_frame->page()->chrome()->client());
if (!m_outgoingReferrer.isEmpty())
frameRequest.resourceRequest().setHTTPReferrer(m_outgoingReferrer);
if (strcmp(action, "GET") == 0)
u.setQuery(formData->flattenToString());
else {
frameRequest.resourceRequest().setHTTPMethod("POST");
frameRequest.resourceRequest().setHTTPBody(formData);
if (contentType.isNull() || contentType == "application/x-www-form-urlencoded")
frameRequest.resourceRequest().setHTTPContentType(contentType);
else frameRequest.resourceRequest().setHTTPContentType(contentType + "; boundary=" + boundary);
}
frameRequest.resourceRequest().setURL(u);
addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin());
if (Page* targetPage = targetFrame->page()) {
Frame* mainFrame = targetPage->mainFrame();
if (mainFrame != targetFrame) {
HTMLFrameOwnerElement* owner = targetFrame->ownerElement();
Document* document = mainFrame->document();
if (owner && !owner->createdByParser() && (!mainFrame->loader()->isComplete() || document && document->processingLoadEvent()))
lockBackForwardList = true;
}
}
targetFrame->loader()->scheduleFormSubmission(frameRequest, lockHistory, lockBackForwardList, event, formState);
}
void FrameLoader::stopLoading(bool sendUnload)
{
if (m_frame->document() && m_frame->document()->tokenizer())
m_frame->document()->tokenizer()->stopParsing();
if (sendUnload) {
if (m_frame->document()) {
if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
Node* currentFocusedNode = m_frame->document()->focusedNode();
if (currentFocusedNode)
currentFocusedNode->aboutToUnload();
m_unloadEventBeingDispatched = true;
m_frame->document()->dispatchWindowEvent(eventNames().unloadEvent, false, false);
m_unloadEventBeingDispatched = false;
if (m_frame->document())
m_frame->document()->updateRendering();
m_wasUnloadEventEmitted = true;
if (m_frame->eventHandler()->pendingFrameUnloadEventCount())
m_frame->eventHandler()->clearPendingFrameUnloadEventCount();
if (m_frame->eventHandler()->pendingFrameBeforeUnloadEventCount())
m_frame->eventHandler()->clearPendingFrameBeforeUnloadEventCount();
}
}
if (m_frame->document() && !m_frame->document()->inPageCache())
m_frame->document()->removeAllEventListenersFromAllNodes();
}
m_isComplete = true; m_isLoadingMainResource = false;
m_didCallImplicitClose = true;
if (m_frame->document() && m_frame->document()->parsing()) {
finishedParsing();
m_frame->document()->setParsing(false);
}
m_workingURL = KURL();
if (Document* doc = m_frame->document()) {
if (DocLoader* docLoader = doc->docLoader())
cache()->loader()->cancelRequests(docLoader);
#if ENABLE(DATABASE)
doc->stopDatabases();
#endif
}
for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
child->loader()->stopLoading(sendUnload);
cancelRedirection();
#if USE(LOW_BANDWIDTH_DISPLAY)
if (m_frame->document() && m_frame->document()->inLowBandwidthDisplay()) {
m_needToSwitchOutLowBandwidthDisplay = false;
switchOutLowBandwidthDisplayIfReady();
}
#endif
}
void FrameLoader::stop()
{
RefPtr<Frame> protector(m_frame);
if (m_frame->document()) {
if (m_frame->document()->tokenizer())
m_frame->document()->tokenizer()->stopParsing();
m_frame->document()->finishParsing();
} else
checkCompleted();
if (m_iconLoader)
m_iconLoader->stopLoading();
}
bool FrameLoader::closeURL()
{
saveDocumentState();
stopLoading(true);
m_frame->editor()->clearUndoRedoOperations();
return true;
}
void FrameLoader::cancelRedirection(bool cancelWithLoadInProgress)
{
m_cancellingWithLoadInProgress = cancelWithLoadInProgress;
stopRedirectionTimer();
m_scheduledRedirection.clear();
}
KURL FrameLoader::iconURL()
{
if (m_frame->tree() && m_frame->tree()->parent())
return KURL();
if (m_frame->document() && !m_frame->document()->iconURL().isEmpty())
return KURL(m_frame->document()->iconURL());
if (!m_URL.protocolIs("http") && !m_URL.protocolIs("https"))
return KURL();
KURL url;
url.setProtocol(m_URL.protocol());
url.setHost(m_URL.host());
if (int port = m_URL.port())
url.setPort(port);
url.setPath("/favicon.ico");
return url;
}
bool FrameLoader::didOpenURL(const KURL& url)
{
if (m_scheduledRedirection && m_scheduledRedirection->wasDuringLoad) {
return false;
}
cancelRedirection();
m_frame->editor()->clearLastEditCommand();
closeURL();
m_isComplete = false;
m_isLoadingMainResource = true;
m_didCallImplicitClose = false;
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())
m_URL.setPath("/");
m_workingURL = m_URL;
started();
return true;
}
void FrameLoader::didExplicitOpen()
{
m_isComplete = false;
m_didCallImplicitClose = false;
m_committedFirstRealDocumentLoad = true;
cancelRedirection();
if (m_frame->document()->url() != blankURL())
m_URL = m_frame->document()->url();
}
bool FrameLoader::executeIfJavaScriptURL(const KURL& url, bool userGesture, bool replaceDocument)
{
if (!url.protocolIs("javascript"))
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);
String scriptResult;
if (!result.getString(scriptResult))
return true;
SecurityOrigin* currentSecurityOrigin = 0;
if (m_frame->document())
currentSecurityOrigin = m_frame->document()->securityOrigin();
if (replaceDocument) {
begin(m_URL, true, currentSecurityOrigin);
write(scriptResult);
end();
}
return true;
}
ScriptValue FrameLoader::executeScript(const String& script, bool forceUserGesture)
{
return executeScript(ScriptSourceCode(script, forceUserGesture ? KURL() : m_URL));
}
ScriptValue FrameLoader::executeScript(const ScriptSourceCode& sourceCode)
{
if (!m_frame->script()->isEnabled() || m_frame->script()->isPaused())
return ScriptValue();
bool wasRunningScript = m_isRunningScript;
m_isRunningScript = true;
ScriptValue result = m_frame->script()->evaluate(sourceCode);
if (!wasRunningScript) {
m_isRunningScript = false;
Document::updateDocumentsRendering();
}
return result;
}
void FrameLoader::cancelAndClear()
{
cancelRedirection();
if (!m_isComplete)
closeURL();
clear(false);
m_frame->script()->updatePlatformScriptObjects();
}
void FrameLoader::clear(bool clearWindowProperties, bool clearScriptObjects)
{
m_frame->editor()->clear();
if (!m_needsClear)
return;
m_needsClear = false;
if (m_frame->document() && !m_frame->document()->inPageCache()) {
m_frame->document()->cancelParsing();
m_frame->document()->stopActiveDOMObjects();
if (m_frame->document()->attached()) {
m_frame->document()->willRemove();
m_frame->document()->detach();
m_frame->document()->removeFocusedNodeOfSubtree(m_frame->document());
}
}
if (clearWindowProperties) {
m_frame->clearDOMWindow();
m_frame->script()->clearWindowShell();
}
m_frame->selection()->clear();
m_frame->eventHandler()->clear();
if (m_frame->view())
m_frame->view()->clear();
m_frame->setSelectionGranularity(CharacterGranularity);
m_frame->setDocument(0);
m_decoder = 0;
m_containsPlugIns = false;
if (clearScriptObjects)
m_frame->script()->clearScriptObjects();
m_redirectionTimer.stop();
m_scheduledRedirection.clear();
m_checkCompletedTimer.stop();
m_checkLoadCompleteTimer.stop();
m_receivedData = false;
m_isDisplayingInitialEmptyDocument = false;
if (!m_encodingWasChosenByUser)
m_encoding = String();
}
void FrameLoader::receivedFirstData()
{
begin(m_workingURL, false);
dispatchDidCommitLoad();
dispatchWindowObjectAvailable();
String ptitle = m_documentLoader->title();
if (!ptitle.isNull())
m_client->dispatchDidReceiveTitle(ptitle);
m_workingURL = KURL();
double delay;
String url;
if (!m_documentLoader)
return;
if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField("Refresh"), false, delay, url))
return;
if (url.isEmpty())
url = m_URL.string();
else
url = m_frame->document()->completeURL(url).string();
scheduleHTTPRedirection(delay, url);
}
const String& FrameLoader::responseMIMEType() const
{
return m_responseMIMEType;
}
void FrameLoader::setResponseMIMEType(const String& type)
{
m_responseMIMEType = type;
}
void FrameLoader::begin()
{
begin(KURL());
}
void FrameLoader::begin(const KURL& url, bool dispatch, SecurityOrigin* origin)
{
RefPtr<SecurityOrigin> forcedSecurityOrigin = origin;
bool resetScripting = !(m_isDisplayingInitialEmptyDocument && m_frame->document() && m_frame->document()->securityOrigin()->isSecureTransitionTo(url));
clear(resetScripting, resetScripting);
if (resetScripting)
m_frame->script()->updatePlatformScriptObjects();
if (dispatch)
dispatchWindowObjectAvailable();
m_needsClear = true;
m_isComplete = false;
m_didCallImplicitClose = false;
m_isLoadingMainResource = true;
m_isDisplayingInitialEmptyDocument = m_creatingInitialEmptyDocument;
KURL ref(url);
ref.setUser(String());
ref.setPass(String());
ref.setRef(String());
m_outgoingReferrer = ref.string();
m_URL = url;
RefPtr<Document> document;
if (!m_isDisplayingInitialEmptyDocument && m_client->shouldUsePluginDocument(m_responseMIMEType))
document = PluginDocument::create(m_frame);
else
document = DOMImplementation::createDocument(m_responseMIMEType, m_frame, m_frame->inViewSourceMode());
m_frame->setDocument(document);
document->setURL(m_URL);
if (m_decoder)
document->setDecoder(m_decoder.get());
if (forcedSecurityOrigin)
document->setSecurityOrigin(forcedSecurityOrigin.get());
m_frame->domWindow()->setURL(document->url());
m_frame->domWindow()->setSecurityOrigin(document->securityOrigin());
updatePolicyBaseURL();
Settings* settings = document->settings();
document->docLoader()->setAutoLoadImages(settings && settings->loadsImagesAutomatically());
if (m_documentLoader) {
String dnsPrefetchControl = m_documentLoader->response().httpHeaderField("X-DNS-Prefetch-Control");
if (!dnsPrefetchControl.isEmpty())
document->parseDNSPrefetchControlHeader(dnsPrefetchControl);
}
#if FRAME_LOADS_USER_STYLESHEET
KURL userStyleSheet = settings ? settings->userStyleSheetLocation() : KURL();
if (!userStyleSheet.isEmpty())
m_frame->setUserStyleSheetLocation(userStyleSheet);
#endif
restoreDocumentState();
document->implicitOpen();
if (m_frame->view())
m_frame->view()->setContentsSize(IntSize());
#if USE(LOW_BANDWIDTH_DISPLAY)
if (document->isHTMLDocument() && !m_frame->tree()->parent() && m_useLowBandwidthDisplay) {
m_pendingSourceInLowBandwidthDisplay = String();
m_finishedParsingDuringLowBandwidthDisplay = false;
m_needToSwitchOutLowBandwidthDisplay = false;
document->setLowBandwidthDisplay(true);
}
#endif
}
void FrameLoader::write(const char* str, int len, bool flush)
{
if (len == 0 && !flush)
return;
if (len == -1)
len = strlen(str);
Tokenizer* tokenizer = m_frame->document()->tokenizer();
if (tokenizer && tokenizer->wantsRawData()) {
if (len > 0)
tokenizer->writeRawData(str, len);
return;
}
if (!m_decoder) {
Settings* settings = m_frame->settings();
m_decoder = TextResourceDecoder::create(m_responseMIMEType, settings ? settings->defaultTextEncodingName() : String());
if (m_encoding.isEmpty()) {
Frame* parentFrame = m_frame->tree()->parent();
if (parentFrame && parentFrame->document()->securityOrigin()->canAccess(m_frame->document()->securityOrigin()))
m_decoder->setEncoding(parentFrame->document()->inputEncoding(), TextResourceDecoder::DefaultEncoding);
} else {
m_decoder->setEncoding(m_encoding,
m_encodingWasChosenByUser ? TextResourceDecoder::UserChosenEncoding : TextResourceDecoder::EncodingFromHTTPHeader);
}
m_frame->document()->setDecoder(m_decoder.get());
}
String decoded = m_decoder->decode(str, len);
if (flush)
decoded += m_decoder->flush();
if (decoded.isEmpty())
return;
#if USE(LOW_BANDWIDTH_DISPLAY)
if (m_frame->document()->inLowBandwidthDisplay())
m_pendingSourceInLowBandwidthDisplay.append(decoded);
#endif
if (!m_receivedData) {
m_receivedData = true;
if (m_decoder->encoding().usesVisualOrdering())
m_frame->document()->setVisuallyOrdered();
m_frame->document()->recalcStyle(Node::Force);
}
if (tokenizer) {
ASSERT(!tokenizer->wantsRawData());
tokenizer->write(decoded, true);
}
}
void FrameLoader::write(const String& str)
{
if (str.isNull())
return;
if (!m_receivedData) {
m_receivedData = true;
m_frame->document()->setParseMode(Document::Strict);
}
if (Tokenizer* tokenizer = m_frame->document()->tokenizer())
tokenizer->write(str, true);
}
void FrameLoader::end()
{
m_isLoadingMainResource = false;
endIfNotLoadingMainResource();
}
void FrameLoader::endIfNotLoadingMainResource()
{
if (m_isLoadingMainResource || !m_frame->page())
return;
RefPtr<Frame> protector(m_frame);
if (m_frame->document()) {
write(0, 0, true);
m_frame->document()->finishParsing();
#if USE(LOW_BANDWIDTH_DISPLAY)
if (m_frame->document()->inLowBandwidthDisplay()) {
m_finishedParsingDuringLowBandwidthDisplay = true;
switchOutLowBandwidthDisplayIfReady();
}
#endif
} else
checkCompleted();
}
void FrameLoader::iconLoadDecisionAvailable()
{
if (!m_mayLoadIconLater)
return;
LOG(IconDatabase, "FrameLoader %p was told a load decision is available for its icon", this);
startIconLoader();
m_mayLoadIconLater = false;
}
void FrameLoader::startIconLoader()
{
if (!isLoadingMainFrame())
return;
if (!iconDatabase() || !iconDatabase()->isEnabled())
return;
KURL url(iconURL());
String urlString(url.string());
if (urlString.isEmpty())
return;
if (loadType() != FrameLoadTypeReload && loadType() != FrameLoadTypeReloadFromOrigin) {
IconLoadDecision decision = iconDatabase()->loadDecisionForIconURL(urlString, m_documentLoader.get());
if (decision == IconLoadNo) {
LOG(IconDatabase, "FrameLoader::startIconLoader() - Told not to load this icon, committing iconURL %s to database for pageURL mapping", urlString.ascii().data());
commitIconURLToIconDatabase(url);
if (!iconDatabase()->iconDataKnownForIconURL(urlString)) {
LOG(IconDatabase, "Told not to load icon %s but icon data is not yet available - registering for notification and requesting load from disk", urlString.ascii().data());
m_client->registerForIconNotification();
iconDatabase()->iconForPageURL(m_URL.string(), IntSize(0, 0));
iconDatabase()->iconForPageURL(originalRequestURL().string(), IntSize(0, 0));
} else
m_client->dispatchDidReceiveIcon();
return;
}
if (decision == IconLoadUnknown) {
LOG(IconDatabase, "FrameLoader %p might load icon %s later", this, urlString.ascii().data());
m_mayLoadIconLater = true;
m_client->registerForIconNotification();
commitIconURLToIconDatabase(url);
return;
}
}
if (!m_iconLoader)
m_iconLoader.set(IconLoader::create(m_frame).release());
m_iconLoader->startLoading();
}
void FrameLoader::setLocalLoadPolicy(LocalLoadPolicy policy)
{
localLoadPolicy = policy;
}
bool FrameLoader::restrictAccessToLocal()
{
return localLoadPolicy != FrameLoader::AllowLocalLoadsForAll;
}
bool FrameLoader::allowSubstituteDataAccessToLocal()
{
return localLoadPolicy != FrameLoader::AllowLocalLoadsForLocalOnly;
}
static LocalSchemesMap& localSchemes()
{
DEFINE_STATIC_LOCAL(LocalSchemesMap, localSchemes, ());
if (localSchemes.isEmpty()) {
localSchemes.add("file");
#if PLATFORM(MAC)
localSchemes.add("applewebdata");
#endif
#if PLATFORM(QT)
localSchemes.add("qrc");
#endif
}
return localSchemes;
}
void FrameLoader::commitIconURLToIconDatabase(const KURL& icon)
{
ASSERT(iconDatabase());
LOG(IconDatabase, "Committing iconURL %s to database for pageURLs %s and %s", icon.string().ascii().data(), m_URL.string().ascii().data(), originalRequestURL().string().ascii().data());
iconDatabase()->setIconURLForPageURL(icon.string(), m_URL.string());
iconDatabase()->setIconURLForPageURL(icon.string(), originalRequestURL().string());
}
void FrameLoader::restoreDocumentState()
{
Document* doc = m_frame->document();
if (!doc)
return;
HistoryItem* itemToRestore = 0;
switch (loadType()) {
case FrameLoadTypeReload:
case FrameLoadTypeReloadFromOrigin:
case FrameLoadTypeSame:
case FrameLoadTypeReplace:
break;
case FrameLoadTypeBack:
case FrameLoadTypeForward:
case FrameLoadTypeIndexedBackForward:
case FrameLoadTypeRedirectWithLockedBackForwardList:
case FrameLoadTypeStandard:
itemToRestore = m_currentHistoryItem.get();
}
if (!itemToRestore)
return;
LOG(Loading, "WebCoreLoading %s: restoring form state from %p", m_frame->tree()->name().string().utf8().data(), itemToRestore);
doc->setStateForNewFormElements(itemToRestore->documentState());
}
void FrameLoader::gotoAnchor()
{
if (!m_URL.hasRef() && !(m_frame->document() && m_frame->document()->getCSSTarget()))
return;
String ref = m_URL.ref();
if (gotoAnchor(ref))
return;
if (m_decoder)
gotoAnchor(decodeURLEscapeSequences(ref, m_decoder->encoding()));
}
void FrameLoader::finishedParsing()
{
if (m_creatingInitialEmptyDocument)
return;
RefPtr<Frame> protector = m_frame->view() ? m_frame : 0;
m_client->dispatchDidFinishDocumentLoad();
checkCompleted();
if (!m_frame->view())
return;
m_frame->view()->restoreScrollbar();
gotoAnchor();
}
void FrameLoader::loadDone()
{
if (m_frame->document())
checkCompleted();
}
void FrameLoader::checkCompleted()
{
if (m_frame->view())
m_frame->view()->checkStopDelayingDeferredRepaints();
for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
if (!child->loader()->m_isComplete)
return;
if (m_isComplete)
return;
if (m_frame->document() && m_frame->document()->parsing())
return;
if (m_frame->document())
if (numRequests(m_frame->document()))
return;
#if USE(LOW_BANDWIDTH_DISPLAY)
if (m_frame->document() && m_frame->document()->inLowBandwidthDisplay() && m_needToSwitchOutLowBandwidthDisplay)
return;
#endif
m_isComplete = true;
RefPtr<Frame> protect(m_frame);
checkCallImplicitClose();
if (m_scheduledRedirection && !m_frame->tree()->parent())
startRedirectionTimer();
completed();
if (m_frame->page())
checkLoadComplete();
}
void FrameLoader::checkCompletedTimerFired(Timer<FrameLoader>*)
{
checkCompleted();
}
void FrameLoader::scheduleCheckCompleted()
{
if (!m_checkCompletedTimer.isActive())
m_checkCompletedTimer.startOneShot(0);
}
void FrameLoader::checkLoadCompleteTimerFired(Timer<FrameLoader>*)
{
if (!m_frame->page())
return;
checkLoadComplete();
}
void FrameLoader::scheduleCheckLoadComplete()
{
if (!m_checkLoadCompleteTimer.isActive())
m_checkLoadCompleteTimer.startOneShot(0);
}
void FrameLoader::checkCallImplicitClose()
{
if (m_didCallImplicitClose || !m_frame->document() || m_frame->document()->parsing())
return;
for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
if (!child->loader()->m_isComplete) return;
m_didCallImplicitClose = true;
m_wasUnloadEventEmitted = false;
if (m_frame->document())
m_frame->document()->implicitClose();
}
KURL FrameLoader::baseURL() const
{
ASSERT(m_frame->document());
return m_frame->document()->baseURL();
}
KURL FrameLoader::completeURL(const String& url)
{
ASSERT(m_frame->document());
return m_frame->document()->completeURL(url);
}
void FrameLoader::scheduleHTTPRedirection(double delay, const String& url)
{
if (delay < 0 || delay > INT_MAX / 1000)
return;
if (!m_frame->page())
return;
if (!m_scheduledRedirection || delay <= m_scheduledRedirection->delay)
scheduleRedirection(new ScheduledRedirection(delay, url, true, delay <= 1, false, false));
}
void FrameLoader::scheduleLocationChange(const String& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool wasUserGesture)
{
if (!m_frame->page())
return;
KURL parsedURL(url);
if (parsedURL.hasRef() && equalIgnoringRef(m_URL, parsedURL)) {
changeLocation(completeURL(url), referrer, lockHistory, lockBackForwardList, wasUserGesture);
return;
}
bool duringLoad = !m_committedFirstRealDocumentLoad;
scheduleRedirection(new ScheduledRedirection(url, referrer, lockHistory, lockBackForwardList, wasUserGesture, false, duringLoad));
}
void FrameLoader::scheduleFormSubmission(const FrameLoadRequest& frameRequest,
bool lockHistory, bool lockBackForwardList, PassRefPtr<Event> event, PassRefPtr<FormState> formState)
{
ASSERT(m_frame->page());
ASSERT(!frameRequest.isEmpty());
bool duringLoad = !m_committedFirstRealDocumentLoad;
scheduleRedirection(new ScheduledRedirection(frameRequest, lockHistory, lockBackForwardList, event, formState, duringLoad));
}
void FrameLoader::scheduleRefresh(bool wasUserGesture)
{
if (!m_frame->page())
return;
if (m_URL.isEmpty())
return;
scheduleRedirection(new ScheduledRedirection(m_URL.string(), m_outgoingReferrer, true, true, wasUserGesture, true, false));
}
bool FrameLoader::isLocationChange(const ScheduledRedirection& redirection)
{
switch (redirection.type) {
case ScheduledRedirection::redirection:
return false;
case ScheduledRedirection::historyNavigation:
case ScheduledRedirection::locationChange:
case ScheduledRedirection::formSubmission:
return true;
}
ASSERT_NOT_REACHED();
return false;
}
void FrameLoader::scheduleHistoryNavigation(int steps)
{
if (!m_frame->page())
return;
if (!canGoBackOrForward(steps)) {
cancelRedirection();
return;
}
if (steps != 0) {
KURL destination = historyURL(steps);
if (equalIgnoringRef(m_URL, destination) && m_URL != destination) {
goBackOrForward(steps);
return;
}
}
scheduleRedirection(new ScheduledRedirection(steps));
}
void FrameLoader::goBackOrForward(int distance)
{
if (distance == 0)
return;
Page* page = m_frame->page();
if (!page)
return;
BackForwardList* list = page->backForwardList();
if (!list)
return;
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);
}
}
ASSERT(item); if (item)
page->goToItem(item, FrameLoadTypeIndexedBackForward);
}
void FrameLoader::redirectionTimerFired(Timer<FrameLoader>*)
{
ASSERT(m_frame->page());
OwnPtr<ScheduledRedirection> redirection(m_scheduledRedirection.release());
switch (redirection->type) {
case ScheduledRedirection::redirection:
case ScheduledRedirection::locationChange:
changeLocation(KURL(redirection->url), redirection->referrer,
redirection->lockHistory, redirection->lockBackForwardList, redirection->wasUserGesture, redirection->wasRefresh);
return;
case ScheduledRedirection::historyNavigation:
if (redirection->historySteps == 0) {
urlSelected(m_URL, "", 0, redirection->lockHistory, redirection->lockBackForwardList, redirection->wasUserGesture);
return;
}
goBackOrForward(redirection->historySteps);
return;
case ScheduledRedirection::formSubmission:
if (!redirection->formState->sourceFrame()->loader()->shouldAllowNavigation(m_frame))
return;
loadFrameRequest(redirection->frameRequest, redirection->lockHistory, redirection->lockBackForwardList,
redirection->wasUserGesture, redirection->event, redirection->formState);
return;
}
ASSERT_NOT_REACHED();
}
void FrameLoader::loadURLIntoChildFrame(const KURL& url, const String& referer, Frame* childFrame)
{
ASSERT(childFrame);
HistoryItem* parentItem = currentHistoryItem();
FrameLoadType loadType = this->loadType();
FrameLoadType childLoadType = FrameLoadTypeRedirectWithLockedBackForwardList;
KURL workingURL = url;
if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType)) {
HistoryItem* childItem = parentItem->childItemWithTarget(childFrame->tree()->name());
if (childItem) {
workingURL = KURL(childItem->originalURLString());
childLoadType = loadType;
childFrame->loader()->m_provisionalHistoryItem = childItem;
}
}
RefPtr<Archive> subframeArchive = activeDocumentLoader()->popArchiveForSubframe(childFrame->tree()->name());
if (subframeArchive)
childFrame->loader()->loadArchive(subframeArchive.release());
else
childFrame->loader()->loadURL(workingURL, referer, String(), false, childLoadType, 0, 0);
}
void FrameLoader::loadArchive(PassRefPtr<Archive> prpArchive)
{
RefPtr<Archive> archive = prpArchive;
ArchiveResource* mainResource = archive->mainResource();
ASSERT(mainResource);
if (!mainResource)
return;
SubstituteData substituteData(mainResource->data(), mainResource->mimeType(), mainResource->textEncoding(), KURL());
ResourceRequest request(mainResource->url());
#if PLATFORM(MAC)
request.applyWebArchiveHackForMail();
#endif
RefPtr<DocumentLoader> documentLoader = m_client->createDocumentLoader(request, substituteData);
documentLoader->addAllArchiveResources(archive.get());
load(documentLoader.get());
}
String FrameLoader::encoding() const
{
if (m_encodingWasChosenByUser && !m_encoding.isEmpty())
return m_encoding;
if (m_decoder && m_decoder->encoding().isValid())
return m_decoder->encoding().name();
Settings* settings = m_frame->settings();
return settings ? settings->defaultTextEncodingName() : String();
}
bool FrameLoader::gotoAnchor(const String& name)
{
ASSERT(m_frame->document());
if (!m_frame->document()->haveStylesheetsLoaded()) {
m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(true);
return false;
}
m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(false);
Element* anchorNode = m_frame->document()->findAnchor(name);
#if ENABLE(SVG)
if (m_frame->document()->isSVGDocument()) {
if (name.startsWith("xpointer(")) {
} else if (name.startsWith("svgView(")) {
RefPtr<SVGSVGElement> svg = static_cast<SVGDocument*>(m_frame->document())->rootElement();
if (!svg->currentView()->parseViewSpec(name))
return false;
svg->setUseCurrentView(true);
} else {
if (anchorNode && anchorNode->hasTagName(SVGNames::viewTag)) {
RefPtr<SVGViewElement> viewElement = anchorNode->hasTagName(SVGNames::viewTag) ? static_cast<SVGViewElement*>(anchorNode) : 0;
if (viewElement.get()) {
RefPtr<SVGSVGElement> svg = static_cast<SVGSVGElement*>(SVGLocatable::nearestViewportElement(viewElement.get()));
svg->inheritViewAttributes(viewElement.get());
}
}
}
}
#endif
m_frame->document()->setCSSTarget(anchorNode);
if (!anchorNode && !(name.isEmpty() || equalIgnoringCase(name, "top")))
return false;
if (m_frame->document()) {
m_frame->document()->updateRendering();
if (m_frame->view() && m_frame->contentRenderer() && m_frame->contentRenderer()->needsLayout())
m_frame->view()->layout();
}
RenderObject* renderer;
IntRect rect;
if (!anchorNode)
renderer = m_frame->document()->renderer(); else {
renderer = anchorNode->renderer();
rect = anchorNode->getRect();
}
if (renderer)
renderer->enclosingLayer()->scrollRectToVisible(rect, true, RenderLayer::gAlignToEdgeIfNeeded, RenderLayer::gAlignTopAlways);
return true;
}
bool FrameLoader::requestObject(RenderPart* renderer, const String& url, const AtomicString& frameName,
const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues)
{
if (url.isEmpty() && mimeType.isEmpty())
return false;
#if USE(LOW_BANDWIDTH_DISPLAY)
if (frame()->document()->inLowBandwidthDisplay()) {
m_needToSwitchOutLowBandwidthDisplay = true;
return false;
}
#endif
KURL completedURL;
if (!url.isEmpty())
completedURL = completeURL(url);
bool useFallback;
if (shouldUsePlugin(completedURL, mimeType, renderer->hasFallbackContent(), useFallback)) {
Settings* settings = m_frame->settings();
if (!settings || !settings->arePluginsEnabled() ||
(!settings->isJavaEnabled() && MIMETypeRegistry::isJavaAppletMIMEType(mimeType)))
return false;
return loadPlugin(renderer, completedURL, mimeType, paramNames, paramValues, useFallback);
}
ASSERT(renderer->node()->hasTagName(objectTag) || renderer->node()->hasTagName(embedTag));
HTMLPlugInElement* element = static_cast<HTMLPlugInElement*>(renderer->node());
return loadSubframe(element, completedURL, frameName, m_outgoingReferrer);
}
bool FrameLoader::shouldUsePlugin(const KURL& url, const String& mimeType, bool hasFallback, bool& useFallback)
{
if (m_client->shouldUsePluginDocument(mimeType)) {
useFallback = false;
return true;
}
if (m_frame->page() && (mimeType == "image/tiff" || mimeType == "image/tif" || mimeType == "image/x-tiff")) {
const PluginData* pluginData = m_frame->page()->pluginData();
String pluginName = pluginData ? pluginData->pluginNameForMimeType(mimeType) : String();
if (!pluginName.isEmpty() && !pluginName.contains("QuickTime", false))
return true;
}
ObjectContentType objectType = m_client->objectContentType(url, mimeType);
useFallback = objectType == ObjectContentNone && hasFallback;
return objectType == ObjectContentNone || objectType == ObjectContentNetscapePlugin || objectType == ObjectContentOtherPlugin;
}
bool FrameLoader::loadPlugin(RenderPart* renderer, const KURL& url, const String& mimeType,
const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback)
{
Widget* widget = 0;
if (renderer && !useFallback) {
Element* pluginElement = 0;
if (renderer->node() && renderer->node()->isElementNode())
pluginElement = static_cast<Element*>(renderer->node());
if (!canLoad(url, String(), frame()->document())) {
FrameLoader::reportLocalLoadFailed(m_frame, url.string());
return false;
}
widget = m_client->createPlugin(IntSize(renderer->contentWidth(), renderer->contentHeight()),
pluginElement, url, paramNames, paramValues, mimeType,
m_frame->document()->isPluginDocument());
if (widget) {
renderer->setWidget(widget);
m_containsPlugIns = true;
}
}
return widget != 0;
}
void FrameLoader::parentCompleted()
{
if (m_scheduledRedirection && !m_redirectionTimer.isActive())
startRedirectionTimer();
}
String FrameLoader::outgoingReferrer() const
{
return m_outgoingReferrer;
}
String FrameLoader::outgoingOrigin() const
{
if (m_frame->document())
return m_frame->document()->securityOrigin()->toString();
return SecurityOrigin::createEmpty()->toString();
}
Frame* FrameLoader::opener()
{
return m_opener;
}
void FrameLoader::setOpener(Frame* opener)
{
if (m_opener)
m_opener->loader()->m_openedFrames.remove(m_frame);
if (opener)
opener->loader()->m_openedFrames.add(m_frame);
m_opener = opener;
if (m_frame->document()) {
m_frame->document()->initSecurityContext();
m_frame->domWindow()->setSecurityOrigin(m_frame->document()->securityOrigin());
}
}
bool FrameLoader::openedByDOM() const
{
return m_openedByDOM;
}
void FrameLoader::setOpenedByDOM()
{
m_openedByDOM = true;
}
void FrameLoader::handleFallbackContent()
{
HTMLFrameOwnerElement* owner = m_frame->ownerElement();
if (!owner || !owner->hasTagName(objectTag))
return;
static_cast<HTMLObjectElement*>(owner)->renderFallbackContent();
}
void FrameLoader::provisionalLoadStarted()
{
m_firstLayoutDone = false;
cancelRedirection(true);
m_client->provisionalLoadStarted();
}
bool FrameLoader::userGestureHint()
{
Frame* frame = m_frame->tree()->top();
if (!frame->script()->isEnabled())
return true; return frame->script()->processingUserGesture(); }
void FrameLoader::resetMultipleFormSubmissionProtection()
{
m_submittedFormURL = KURL();
}
void FrameLoader::setEncoding(const String& name, bool userChosen)
{
if (!m_workingURL.isEmpty())
receivedFirstData();
m_encoding = name;
m_encodingWasChosenByUser = userChosen;
}
void FrameLoader::addData(const char* bytes, int length)
{
ASSERT(m_workingURL.isEmpty());
ASSERT(m_frame->document());
ASSERT(m_frame->document()->parsing());
write(bytes, length);
}
bool FrameLoader::canCachePageContainingThisFrame()
{
return m_documentLoader
&& m_documentLoader->mainDocumentError().isNull()
&& !m_frame->tree()->childCount()
&& !m_containsPlugIns
&& !m_URL.protocolIs("https")
&& m_frame->document()
&& !m_frame->document()->hasWindowEventListener(eventNames().unloadEvent)
#if ENABLE(DATABASE)
&& !m_frame->document()->hasOpenDatabases()
#endif
&& !m_frame->document()->usingGeolocation()
&& m_currentHistoryItem
&& !m_quickRedirectComing
&& !m_documentLoader->isLoadingInAPISense()
&& !m_documentLoader->isStopping()
&& m_frame->document()->canSuspendActiveDOMObjects()
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
&& !m_documentLoader->applicationCache()
&& !m_documentLoader->candidateApplicationCacheGroup()
#endif
&& m_client->canCachePage()
;
}
bool FrameLoader::canCachePage()
{
#ifndef NDEBUG
logCanCachePageDecision();
#endif
FrameLoadType loadType = this->loadType();
return !m_frame->tree()->parent()
&& canCachePageContainingThisFrame()
&& m_frame->page()
&& m_frame->page()->backForwardList()->enabled()
&& m_frame->page()->backForwardList()->capacity() > 0
&& m_frame->page()->settings()->usesPageCache()
&& loadType != FrameLoadTypeReload
&& loadType != FrameLoadTypeReloadFromOrigin
&& loadType != FrameLoadTypeSame
;
}
#ifndef NDEBUG
static String& pageCacheLogPrefix(int indentLevel)
{
static int previousIndent = -1;
DEFINE_STATIC_LOCAL(String, prefix, ());
if (indentLevel != previousIndent) {
previousIndent = indentLevel;
prefix.truncate(0);
for (int i = 0; i < previousIndent; ++i)
prefix += " ";
}
return prefix;
}
static void pageCacheLog(const String& prefix, const String& message)
{
LOG(PageCache, "%s%s", prefix.utf8().data(), message.utf8().data());
}
#define PCLOG(...) pageCacheLog(pageCacheLogPrefix(indentLevel), String::format(__VA_ARGS__))
void FrameLoader::logCanCachePageDecision()
{
if (m_creatingInitialEmptyDocument)
return;
KURL currentURL = m_documentLoader ? m_documentLoader->url() : KURL();
if (currentURL.isEmpty())
return;
int indentLevel = 0;
PCLOG("--------\n Determining if page can be cached:");
bool cannotCache = !logCanCacheFrameDecision(1);
FrameLoadType loadType = this->loadType();
do {
if (m_frame->tree()->parent())
{ PCLOG(" -Frame has a parent frame"); cannotCache = true; }
if (!m_frame->page()) {
PCLOG(" -There is no Page object");
cannotCache = true;
break;
}
if (!m_frame->page()->backForwardList()->enabled())
{ PCLOG(" -The back/forward list is disabled"); cannotCache = true; }
if (!(m_frame->page()->backForwardList()->capacity() > 0))
{ PCLOG(" -The back/forward list has a 0 capacity"); cannotCache = true; }
if (!m_frame->page()->settings()->usesPageCache())
{ PCLOG(" -Page settings says b/f cache disabled"); cannotCache = true; }
if (loadType == FrameLoadTypeReload)
{ PCLOG(" -Load type is: Reload"); cannotCache = true; }
if (loadType == FrameLoadTypeReloadFromOrigin)
{ PCLOG(" -Load type is: Reload from origin"); cannotCache = true; }
if (loadType == FrameLoadTypeSame)
{ PCLOG(" -Load type is: Same"); cannotCache = true; }
} while (false);
PCLOG(cannotCache ? " Page CANNOT be cached\n--------" : " Page CAN be cached\n--------");
}
bool FrameLoader::logCanCacheFrameDecision(int indentLevel)
{
if (m_creatingInitialEmptyDocument)
return false;
KURL currentURL = m_documentLoader ? m_documentLoader->url() : KURL();
if (currentURL.isEmpty())
return false;
PCLOG("+---");
KURL newURL = m_provisionalDocumentLoader ? m_provisionalDocumentLoader->url() : KURL();
if (!newURL.isEmpty())
PCLOG(" Determining if frame can be cached navigating from (%s) to (%s):", currentURL.string().utf8().data(), newURL.string().utf8().data());
else
PCLOG(" Determining if subframe with URL (%s) can be cached:", currentURL.string().utf8().data());
bool cannotCache = false;
do {
if (!m_documentLoader) {
PCLOG(" -There is no DocumentLoader object");
cannotCache = true;
break;
}
if (!m_documentLoader->mainDocumentError().isNull())
{ PCLOG(" -Main document has an error"); cannotCache = true; }
if (m_frame->tree()->childCount())
{ PCLOG(" -Frame has child frames"); cannotCache = true; }
if (m_containsPlugIns)
{ PCLOG(" -Frame contains plugins"); cannotCache = true; }
if (m_URL.protocolIs("https"))
{ PCLOG(" -Frame is HTTPS"); cannotCache = true; }
if (!m_frame->document()) {
PCLOG(" -There is no Document object");
cannotCache = true;
break;
}
if (m_frame->document()->hasWindowEventListener(eventNames().unloadEvent))
{ PCLOG(" -Frame has an unload event listener"); cannotCache = true; }
#if ENABLE(DATABASE)
if (m_frame->document()->hasOpenDatabases())
{ PCLOG(" -Frame has open database handles"); cannotCache = true; }
#endif
if (m_frame->document()->usingGeolocation())
{ PCLOG(" -Frame uses Geolocation"); cannotCache = true; }
if (!m_currentHistoryItem)
{ PCLOG(" -No current history item"); cannotCache = true; }
if (m_quickRedirectComing)
{ PCLOG(" -Quick redirect is coming"); cannotCache = true; }
if (m_documentLoader->isLoadingInAPISense())
{ PCLOG(" -DocumentLoader is still loading in API sense"); cannotCache = true; }
if (m_documentLoader->isStopping())
{ PCLOG(" -DocumentLoader is in the middle of stopping"); cannotCache = true; }
if (!m_frame->document()->canSuspendActiveDOMObjects())
{ PCLOG(" -The document cannot suspect its active DOM Objects"); cannotCache = true; }
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
if (m_documentLoader->applicationCache())
{ PCLOG(" -The DocumentLoader has an active application cache"); cannotCache = true; }
if (m_documentLoader->candidateApplicationCacheGroup())
{ PCLOG(" -The DocumentLoader has a candidateApplicationCacheGroup"); cannotCache = true; }
#endif
if (!m_client->canCachePage())
{ PCLOG(" -The client says this frame cannot be cached"); cannotCache = true; }
} while (false);
for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
if (!child->loader()->logCanCacheFrameDecision(indentLevel + 1))
cannotCache = true;
PCLOG(cannotCache ? " Frame CANNOT be cached" : " Frame CAN be cached");
PCLOG("+---");
return !cannotCache;
}
#endif
void FrameLoader::updatePolicyBaseURL()
{
if (m_frame->tree()->parent() && m_frame->tree()->parent()->document())
setPolicyBaseURL(m_frame->tree()->parent()->document()->policyBaseURL());
else
setPolicyBaseURL(m_URL);
}
void FrameLoader::setPolicyBaseURL(const KURL& url)
{
if (m_frame->document())
m_frame->document()->setPolicyBaseURL(url);
for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
child->loader()->setPolicyBaseURL(url);
}
void FrameLoader::scrollToAnchor(const KURL& url)
{
m_URL = url;
updateHistoryForAnchorScroll();
m_frame->eventHandler()->stopAutoscrollTimer();
started();
gotoAnchor();
m_isComplete = false;
checkCompleted();
}
bool FrameLoader::isComplete() const
{
return m_isComplete;
}
void FrameLoader::scheduleRedirection(ScheduledRedirection* redirection)
{
ASSERT(m_frame->page());
if (redirection->wasDuringLoad) {
if (m_provisionalDocumentLoader)
m_provisionalDocumentLoader->stopLoading();
stopLoading(true);
}
stopRedirectionTimer();
m_scheduledRedirection.set(redirection);
if (!m_isComplete && redirection->type != ScheduledRedirection::redirection)
completed();
if (m_isComplete || redirection->type != ScheduledRedirection::redirection)
startRedirectionTimer();
}
void FrameLoader::startRedirectionTimer()
{
ASSERT(m_frame->page());
ASSERT(m_scheduledRedirection);
m_redirectionTimer.stop();
m_redirectionTimer.startOneShot(m_scheduledRedirection->delay);
switch (m_scheduledRedirection->type) {
case ScheduledRedirection::locationChange:
case ScheduledRedirection::redirection:
clientRedirected(KURL(m_scheduledRedirection->url),
m_scheduledRedirection->delay,
currentTime() + m_redirectionTimer.nextFireInterval(),
m_scheduledRedirection->lockBackForwardList);
return;
case ScheduledRedirection::formSubmission:
return;
case ScheduledRedirection::historyNavigation:
return;
}
ASSERT_NOT_REACHED();
}
void FrameLoader::stopRedirectionTimer()
{
if (!m_redirectionTimer.isActive())
return;
m_redirectionTimer.stop();
if (m_scheduledRedirection) {
switch (m_scheduledRedirection->type) {
case ScheduledRedirection::locationChange:
case ScheduledRedirection::redirection:
clientRedirectCancelledOrFinished(m_cancellingWithLoadInProgress);
return;
case ScheduledRedirection::formSubmission:
return;
case ScheduledRedirection::historyNavigation:
return;
}
ASSERT_NOT_REACHED();
}
}
void FrameLoader::completed()
{
RefPtr<Frame> protect(m_frame);
for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
child->loader()->parentCompleted();
if (Frame* parent = m_frame->tree()->parent())
parent->loader()->checkCompleted();
}
void FrameLoader::started()
{
for (Frame* frame = m_frame; frame; frame = frame->tree()->parent())
frame->loader()->m_isComplete = false;
}
bool FrameLoader::containsPlugins() const
{
return m_containsPlugIns;
}
void FrameLoader::prepareForLoadStart()
{
if (Page* page = m_frame->page())
page->progress()->progressStarted(m_frame);
m_client->dispatchDidStartProvisionalLoad();
}
void FrameLoader::setupForReplace()
{
setState(FrameStateProvisional);
m_provisionalDocumentLoader = m_documentLoader;
m_documentLoader = 0;
detachChildren();
}
void FrameLoader::setupForReplaceByMIMEType(const String& newMIMEType)
{
activeDocumentLoader()->setupForReplaceByMIMEType(newMIMEType);
}
void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, bool lockHistory, bool lockBackForwardList, bool userGesture,
PassRefPtr<Event> event, PassRefPtr<FormState> formState)
{
KURL url = request.resourceRequest().url();
String referrer;
String argsReferrer = request.resourceRequest().httpReferrer();
if (!argsReferrer.isEmpty())
referrer = argsReferrer;
else
referrer = m_outgoingReferrer;
ASSERT(frame()->document());
if (url.protocolIs("file")) {
if (!canLoad(url, String(), frame()->document()) && !canLoad(url, referrer)) {
FrameLoader::reportLocalLoadFailed(m_frame, url.string());
return;
}
}
if (shouldHideReferrer(url, referrer))
referrer = String();
FrameLoadType loadType;
if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
loadType = FrameLoadTypeReload;
else if (lockBackForwardList)
loadType = FrameLoadTypeRedirectWithLockedBackForwardList;
else
loadType = FrameLoadTypeStandard;
if (request.resourceRequest().httpMethod() == "POST")
loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
else
loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
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(userGesture);
}
}
void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType newLoadType,
PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
{
RefPtr<FormState> formState = prpFormState;
bool isFormSubmission = formState;
ResourceRequest request(newURL);
if (!referrer.isEmpty()) {
request.setHTTPReferrer(referrer);
RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
addHTTPOriginIfNeeded(request, referrerOrigin->toString());
}
addExtraFieldsToRequest(request, newLoadType, true, event || isFormSubmission);
if (newLoadType == FrameLoadTypeReload || newLoadType == FrameLoadTypeReloadFromOrigin)
request.setCachePolicy(ReloadIgnoringCacheData);
ASSERT(newLoadType != FrameLoadTypeSame);
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 (!targetFrame && !frameName.isEmpty()) {
checkNewWindowPolicy(action, request, formState.release(), frameName);
return;
}
RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
bool sameURL = shouldTreatURLAsSameAsCurrent(newURL);
if (shouldScrollToAnchor(isFormSubmission, newLoadType, newURL)) {
oldDocumentLoader->setTriggeringAction(action);
stopPolicyCheck();
checkNavigationPolicy(request, oldDocumentLoader.get(), formState.release(),
callContinueFragmentScrollAfterNavigationPolicy, this);
} else {
bool isRedirect = m_quickRedirectComing;
loadWithNavigationAction(request, action, lockHistory, newLoadType, formState.release());
if (isRedirect) {
m_quickRedirectComing = false;
if (m_provisionalDocumentLoader)
m_provisionalDocumentLoader->setIsClientRedirect(true);
} else if (sameURL)
m_loadType = FrameLoadTypeSame;
}
}
void FrameLoader::load(const ResourceRequest& request, bool lockHistory)
{
load(request, SubstituteData(), lockHistory);
}
void FrameLoader::load(const ResourceRequest& request, const SubstituteData& substituteData, bool lockHistory)
{
if (m_inStopAllLoaders)
return;
m_loadType = FrameLoadTypeStandard;
RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, substituteData);
loader->setURLForHistoryReflectsClientRedirect(lockHistory);
load(loader.get());
}
void FrameLoader::load(const ResourceRequest& request, const String& frameName, bool lockHistory)
{
if (frameName.isEmpty()) {
load(request, lockHistory);
return;
}
Frame* frame = findFrameForNavigation(frameName);
if (frame) {
frame->loader()->load(request, lockHistory);
return;
}
checkNewWindowPolicy(NavigationAction(request.url(), NavigationTypeOther), request, 0, frameName);
}
void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, bool lockHistory, FrameLoadType type, PassRefPtr<FormState> formState)
{
RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, SubstituteData());
loader->setURLForHistoryReflectsClientRedirect(lockHistory);
loader->setTriggeringAction(action);
if (m_documentLoader)
loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
loadWithDocumentLoader(loader.get(), type, formState);
}
void FrameLoader::load(DocumentLoader* newDocumentLoader)
{
ResourceRequest& r = newDocumentLoader->request();
addExtraFieldsToMainResourceRequest(r);
FrameLoadType type;
if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->originalRequest().url())) {
r.setCachePolicy(ReloadIgnoringCacheData);
type = FrameLoadTypeSame;
} else
type = FrameLoadTypeStandard;
if (m_documentLoader)
newDocumentLoader->setOverrideEncoding(m_documentLoader->overrideEncoding());
if (shouldReloadToHandleUnreachableURL(newDocumentLoader)) {
ASSERT(type == FrameLoadTypeStandard);
type = FrameLoadTypeReload;
}
loadWithDocumentLoader(newDocumentLoader, type, 0);
}
void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType type, PassRefPtr<FormState> prpFormState)
{
ASSERT(m_client->hasWebView());
ASSERT(m_frame->view());
m_policyLoadType = type;
RefPtr<FormState> formState = prpFormState;
bool isFormSubmission = formState;
const KURL& newURL = loader->request().url();
if (shouldScrollToAnchor(isFormSubmission, m_policyLoadType, newURL)) {
RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
NavigationAction action(newURL, m_policyLoadType, isFormSubmission);
oldDocumentLoader->setTriggeringAction(action);
stopPolicyCheck();
checkNavigationPolicy(loader->request(), oldDocumentLoader.get(), formState,
callContinueFragmentScrollAfterNavigationPolicy, this);
} else {
if (Frame* parent = m_frame->tree()->parent())
loader->setOverrideEncoding(parent->loader()->documentLoader()->overrideEncoding());
stopPolicyCheck();
setPolicyDocumentLoader(loader);
if (loader->triggeringAction().isEmpty())
loader->setTriggeringAction(NavigationAction(newURL, m_policyLoadType, isFormSubmission));
checkNavigationPolicy(loader->request(), loader, formState,
callContinueLoadAfterNavigationPolicy, this);
}
}
bool FrameLoader::canLoad(const KURL& url, const String& referrer, const Document* doc)
{
if (!shouldTreatURLAsLocal(url.string()))
return true;
if (doc)
return doc->securityOrigin()->canLoadLocalResources();
else if (!referrer.isEmpty())
return shouldTreatURLAsLocal(referrer);
else
return false;
}
void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
{
ASSERT(!url.isEmpty());
if (!frame)
return;
frame->domWindow()->console()->addMessage(JSMessageSource, ErrorMessageLevel, "Not allowed to load local resource: " + url, 0, String());
}
bool FrameLoader::shouldHideReferrer(const KURL& url, const String& referrer)
{
bool referrerIsSecureURL = protocolIs(referrer, "https");
bool referrerIsWebURL = referrerIsSecureURL || protocolIs(referrer, "http");
if (!referrerIsWebURL)
return true;
if (!referrerIsSecureURL)
return false;
bool URLIsSecureURL = url.protocolIs("https");
return !URLIsSecureURL;
}
const ResourceRequest& FrameLoader::initialRequest() const
{
return activeDocumentLoader()->originalRequest();
}
void FrameLoader::receivedData(const char* data, int length)
{
activeDocumentLoader()->receivedData(data, length);
}
bool FrameLoader::willLoadMediaElementURL(KURL& url)
{
ResourceRequest request(url);
unsigned long identifier;
ResourceError error;
requestFromDelegate(request, identifier, error);
sendRemainingDelegateMessages(identifier, ResourceResponse(url, String(), -1, String(), String()), -1, error);
url = request.url();
return error.isNull();
}
void FrameLoader::handleUnimplementablePolicy(const ResourceError& error)
{
m_delegateIsHandlingUnimplementablePolicy = true;
m_client->dispatchUnableToImplementPolicy(error);
m_delegateIsHandlingUnimplementablePolicy = false;
}
void FrameLoader::cannotShowMIMEType(const ResourceResponse& response)
{
handleUnimplementablePolicy(m_client->cannotShowMIMETypeError(response));
}
ResourceError FrameLoader::interruptionForPolicyChangeError(const ResourceRequest& request)
{
return m_client->interruptForPolicyChangeError(request);
}
void FrameLoader::checkNavigationPolicy(const ResourceRequest& newRequest, NavigationPolicyDecisionFunction function, void* argument)
{
checkNavigationPolicy(newRequest, activeDocumentLoader(), 0, function, argument);
}
void FrameLoader::checkContentPolicy(const String& MIMEType, ContentPolicyDecisionFunction function, void* argument)
{
ASSERT(activeDocumentLoader());
if (activeDocumentLoader()->substituteData().isValid()) {
function(argument, PolicyUse);
return;
}
#if ENABLE(FTPDIR)
Settings* settings = m_frame->settings();
if (settings && settings->forceFTPDirectoryListings() && MIMEType == "application/x-ftp-directory") {
function(argument, PolicyUse);
return;
}
#endif
m_policyCheck.set(function, argument);
m_client->dispatchDecidePolicyForMIMEType(&FrameLoader::continueAfterContentPolicy,
MIMEType, activeDocumentLoader()->request());
}
bool FrameLoader::shouldReloadToHandleUnreachableURL(DocumentLoader* docLoader)
{
KURL unreachableURL = docLoader->unreachableURL();
if (unreachableURL.isEmpty())
return false;
if (!isBackForwardLoadType(m_policyLoadType))
return false;
DocumentLoader* compareDocumentLoader = 0;
if (m_delegateIsDecidingNavigationPolicy || m_delegateIsHandlingUnimplementablePolicy)
compareDocumentLoader = m_policyDocumentLoader.get();
else if (m_delegateIsHandlingProvisionalLoadError)
compareDocumentLoader = m_provisionalDocumentLoader.get();
return compareDocumentLoader && unreachableURL == compareDocumentLoader->request().url();
}
void FrameLoader::reloadWithOverrideEncoding(const String& encoding)
{
if (!m_documentLoader)
return;
ResourceRequest request = m_documentLoader->request();
KURL unreachableURL = m_documentLoader->unreachableURL();
if (!unreachableURL.isEmpty())
request.setURL(unreachableURL);
request.setCachePolicy(ReturnCacheDataElseLoad);
RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, SubstituteData());
setPolicyDocumentLoader(loader.get());
loader->setOverrideEncoding(encoding);
loadWithDocumentLoader(loader.get(), FrameLoadTypeReload, 0);
}
void FrameLoader::reload(bool endToEndReload)
{
if (!m_documentLoader)
return;
if (m_documentLoader->request().url().isEmpty())
return;
ResourceRequest initialRequest = m_documentLoader->request();
KURL unreachableURL = m_documentLoader->unreachableURL();
if (!unreachableURL.isEmpty())
initialRequest.setURL(unreachableURL);
RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(initialRequest, SubstituteData());
ResourceRequest& request = loader->request();
request.setCachePolicy(ReloadIgnoringCacheData);
if (request.httpMethod() == "POST")
loader->setTriggeringAction(NavigationAction(request.url(), NavigationTypeFormResubmitted));
loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
loadWithDocumentLoader(loader.get(), endToEndReload ? FrameLoadTypeReloadFromOrigin : FrameLoadTypeReload, 0);
}
static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
{
if (!targetFrame)
return false;
for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree()->parent()) {
Document* ancestorDocument = ancestorFrame->document();
if (!ancestorDocument)
return true;
const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
return true;
}
return false;
}
bool FrameLoader::shouldAllowNavigation(Frame* targetFrame) const
{
if (!targetFrame)
return true;
if (m_frame == targetFrame)
return true;
if (targetFrame == m_frame->tree()->top())
return true;
Document* activeDocument = m_frame->document();
ASSERT(activeDocument);
const SecurityOrigin* activeSecurityOrigin = activeDocument->securityOrigin();
if (!targetFrame->tree()->parent() && canAccessAncestor(activeSecurityOrigin, targetFrame->loader()->opener()))
return true;
if (canAccessAncestor(activeSecurityOrigin, targetFrame))
return true;
Settings* settings = targetFrame->settings();
if (settings && !settings->privateBrowsingEnabled()) {
Document* targetDocument = targetFrame->document();
String message = String::format("Unsafe JavaScript attempt to initiate a navigation change for frame with URL %s from frame with URL %s.\n",
targetDocument->url().string().utf8().data(), activeDocument->url().string().utf8().data());
targetFrame->domWindow()->console()->addMessage(JSMessageSource, ErrorMessageLevel, message, 1, String());
}
return false;
}
void FrameLoader::stopLoadingSubframes()
{
for (RefPtr<Frame> child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
child->loader()->stopAllLoaders();
}
void FrameLoader::stopAllLoaders()
{
if (m_unloadEventBeingDispatched)
return;
if (m_inStopAllLoaders)
return;
m_inStopAllLoaders = true;
stopPolicyCheck();
stopLoadingSubframes();
if (m_provisionalDocumentLoader)
m_provisionalDocumentLoader->stopLoading();
if (m_documentLoader)
m_documentLoader->stopLoading();
setProvisionalDocumentLoader(0);
if (m_documentLoader)
m_documentLoader->clearArchiveResources();
m_inStopAllLoaders = false;
}
void FrameLoader::stopForUserCancel(bool deferCheckLoadComplete)
{
stopAllLoaders();
if (m_frame && m_frame->view() && !m_frame->view()->didFirstLayout())
m_frame->view()->layout();
if (deferCheckLoadComplete)
scheduleCheckLoadComplete();
else if (m_frame->page())
checkLoadComplete();
}
DocumentLoader* FrameLoader::activeDocumentLoader() const
{
if (m_state == FrameStateProvisional)
return m_provisionalDocumentLoader.get();
return m_documentLoader.get();
}
bool FrameLoader::isLoading() const
{
DocumentLoader* docLoader = activeDocumentLoader();
if (!docLoader)
return false;
return docLoader->isLoadingMainResource() || docLoader->isLoadingSubresources() || docLoader->isLoadingPlugIns();
}
bool FrameLoader::frameHasLoaded() const
{
return m_committedFirstRealDocumentLoad || (m_provisionalDocumentLoader && !m_creatingInitialEmptyDocument);
}
void FrameLoader::setDocumentLoader(DocumentLoader* loader)
{
if (!loader && !m_documentLoader)
return;
ASSERT(loader != m_documentLoader);
ASSERT(!loader || loader->frameLoader() == this);
m_client->prepareForDataSourceReplacement();
detachChildren();
if (m_documentLoader)
m_documentLoader->detachFromFrame();
m_documentLoader = loader;
}
DocumentLoader* FrameLoader::documentLoader() const
{
return m_documentLoader.get();
}
void FrameLoader::setPolicyDocumentLoader(DocumentLoader* loader)
{
if (m_policyDocumentLoader == loader)
return;
ASSERT(m_frame);
if (loader)
loader->setFrame(m_frame);
if (m_policyDocumentLoader
&& m_policyDocumentLoader != m_provisionalDocumentLoader
&& m_policyDocumentLoader != m_documentLoader)
m_policyDocumentLoader->detachFromFrame();
m_policyDocumentLoader = loader;
}
DocumentLoader* FrameLoader::provisionalDocumentLoader() const
{
return m_provisionalDocumentLoader.get();
}
void FrameLoader::setProvisionalDocumentLoader(DocumentLoader* loader)
{
ASSERT(!loader || !m_provisionalDocumentLoader);
ASSERT(!loader || loader->frameLoader() == this);
if (m_provisionalDocumentLoader && m_provisionalDocumentLoader != m_documentLoader)
m_provisionalDocumentLoader->detachFromFrame();
m_provisionalDocumentLoader = loader;
}
FrameState FrameLoader::state() const
{
return m_state;
}
double FrameLoader::timeOfLastCompletedLoad()
{
return storedTimeOfLastCompletedLoad;
}
void FrameLoader::setState(FrameState newState)
{
m_state = newState;
if (newState == FrameStateProvisional)
provisionalLoadStarted();
else if (newState == FrameStateComplete) {
frameLoadCompleted();
storedTimeOfLastCompletedLoad = currentTime();
if (m_documentLoader)
m_documentLoader->stopRecordingResponses();
}
}
void FrameLoader::clearProvisionalLoad()
{
setProvisionalDocumentLoader(0);
if (Page* page = m_frame->page())
page->progress()->progressCompleted(m_frame);
setState(FrameStateComplete);
}
void FrameLoader::markLoadComplete()
{
setState(FrameStateComplete);
}
void FrameLoader::commitProvisionalLoad(PassRefPtr<CachedPage> prpCachedPage)
{
RefPtr<CachedPage> cachedPage = prpCachedPage;
RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
LOG(Loading, "WebCoreLoading %s: About to commit provisional load from previous URL %s", m_frame->tree()->name().string().utf8().data(), m_URL.string().utf8().data());
if (canCachePage() && !m_currentHistoryItem->isInPageCache()) {
if (Document* document = m_frame->document())
document->suspendActiveDOMObjects();
cachePageForHistoryItem(m_currentHistoryItem.get());
}
if (m_loadType != FrameLoadTypeReplace)
closeOldDataSources();
if (!cachedPage && !m_creatingInitialEmptyDocument)
m_client->makeRepresentation(pdl.get());
transitionToCommitted(cachedPage);
if (m_sentRedirectNotification)
clientRedirectCancelledOrFinished(false);
if (cachedPage && cachedPage->document()) {
open(*cachedPage);
cachedPage->clear();
} else {
KURL url = pdl->substituteData().responseURL();
if (url.isEmpty())
url = pdl->url();
if (url.isEmpty())
url = pdl->responseURL();
if (url.isEmpty())
url = blankURL();
didOpenURL(url);
}
LOG(Loading, "WebCoreLoading %s: Finished committing provisional load to URL %s", m_frame->tree()->name().string().utf8().data(), m_URL.string().utf8().data());
opened();
}
void FrameLoader::transitionToCommitted(PassRefPtr<CachedPage> cachedPage)
{
ASSERT(m_client->hasWebView());
ASSERT(m_state == FrameStateProvisional);
if (m_state != FrameStateProvisional)
return;
m_client->setCopiesOnScroll();
updateHistoryForCommit();
DocumentLoader* pdl = m_provisionalDocumentLoader.get();
if (m_documentLoader)
closeURL();
if (pdl != m_provisionalDocumentLoader)
return;
if (m_documentLoader)
m_documentLoader->stopLoadingSubresources();
if (m_documentLoader)
m_documentLoader->stopLoadingPlugIns();
setDocumentLoader(m_provisionalDocumentLoader.get());
setProvisionalDocumentLoader(0);
setState(FrameStateCommittedPage);
DocumentLoader* dl = m_documentLoader.get();
String ptitle = dl->title();
switch (m_loadType) {
case FrameLoadTypeForward:
case FrameLoadTypeBack:
case FrameLoadTypeIndexedBackForward:
if (Page* page = m_frame->page())
if (page->backForwardList()) {
updateHistoryForBackForwardNavigation();
if (cachedPage) {
DocumentLoader* cachedDocumentLoader = cachedPage->documentLoader();
ASSERT(cachedDocumentLoader);
cachedDocumentLoader->setFrame(m_frame);
m_client->transitionToCommittedFromCachedFrame(cachedPage->cachedMainFrame());
} else
m_client->transitionToCommittedForNewPage();
}
break;
case FrameLoadTypeReload:
case FrameLoadTypeReloadFromOrigin:
case FrameLoadTypeSame:
case FrameLoadTypeReplace:
updateHistoryForReload();
m_client->transitionToCommittedForNewPage();
break;
case FrameLoadTypeStandard:
updateHistoryForStandardLoad();
#ifndef BUILDING_ON_TIGER
if (m_frame->view())
m_frame->view()->setScrollbarsSuppressed(true);
#endif
m_client->transitionToCommittedForNewPage();
break;
case FrameLoadTypeRedirectWithLockedBackForwardList:
updateHistoryForRedirectWithLockedBackForwardList();
m_client->transitionToCommittedForNewPage();
break;
default:
ASSERT_NOT_REACHED();
}
m_responseMIMEType = dl->responseMIMEType();
ASSERT(m_frame->view());
if (m_creatingInitialEmptyDocument)
return;
m_committedFirstRealDocumentLoad = true;
if (cachedPage || !m_client->hasHTMLView()) {
dispatchDidCommitLoad();
if (!ptitle.isNull())
m_client->dispatchDidReceiveTitle(ptitle);
}
}
void FrameLoader::clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress)
{
m_client->dispatchDidCancelClientRedirect();
if (!cancelWithLoadInProgress)
m_quickRedirectComing = false;
m_sentRedirectNotification = false;
}
void FrameLoader::clientRedirected(const KURL& url, double seconds, double fireDate, bool lockBackForwardList)
{
m_client->dispatchWillPerformClientRedirect(url, seconds, fireDate);
m_sentRedirectNotification = true;
m_quickRedirectComing = lockBackForwardList && m_documentLoader && !m_isExecutingJavaScriptFormAction;
}
#if ENABLE(WML)
void FrameLoader::setForceReloadWmlDeck(bool reload)
{
m_forceReloadWmlDeck = reload;
}
#endif
bool FrameLoader::shouldReload(const KURL& currentURL, const KURL& destinationURL)
{
#if ENABLE(WML)
if (m_forceReloadWmlDeck)
return true;
#endif
if (!destinationURL.hasRef())
return true;
return !equalIgnoringRef(currentURL, destinationURL);
}
void FrameLoader::closeOldDataSources()
{
for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
child->loader()->closeOldDataSources();
if (m_documentLoader)
m_client->dispatchWillClose();
m_client->setMainFrameDocumentReady(false); }
void FrameLoader::open(CachedPage& cachedPage)
{
ASSERT(m_frame->page());
ASSERT(m_frame->page()->mainFrame() == m_frame);
cancelRedirection();
closeURL();
m_isComplete = false;
m_didCallImplicitClose = true;
if (m_frame->script()->isEnabled()) {
m_frame->setJSStatusBarText(String());
m_frame->setJSDefaultStatusBarText(String());
}
KURL url = cachedPage.url();
if ((url.protocolIs("http") || url.protocolIs("https")) && !url.host().isEmpty() && url.path().isEmpty())
url.setPath("/");
m_URL = url;
m_workingURL = url;
started();
clear();
Document* document = cachedPage.document();
ASSERT(document);
document->setInPageCache(false);
m_needsClear = true;
m_isComplete = false;
m_didCallImplicitClose = false;
m_outgoingReferrer = url.string();
FrameView* view = cachedPage.view();
if (view)
view->setWasScrolledByUser(false);
m_frame->setView(view);
m_frame->setDocument(document);
m_frame->setDOMWindow(cachedPage.domWindow());
m_frame->domWindow()->setURL(document->url());
m_frame->domWindow()->setSecurityOrigin(document->securityOrigin());
m_decoder = document->decoder();
updatePolicyBaseURL();
cachedPage.restore(m_frame->page());
document->resumeActiveDOMObjects();
m_frame->script()->updatePlatformScriptObjects();
checkCompleted();
}
bool FrameLoader::isStopping() const
{
return activeDocumentLoader()->isStopping();
}
void FrameLoader::finishedLoading()
{
RefPtr<Frame> protect(m_frame);
RefPtr<DocumentLoader> dl = activeDocumentLoader();
dl->finishedLoading();
if (!dl->mainDocumentError().isNull() || !dl->frameLoader())
return;
dl->setPrimaryLoadComplete(true);
m_client->dispatchDidLoadMainResource(dl.get());
checkLoadComplete();
}
bool FrameLoader::isHostedByObjectElement() const
{
HTMLFrameOwnerElement* owner = m_frame->ownerElement();
return owner && owner->hasTagName(objectTag);
}
bool FrameLoader::isLoadingMainFrame() const
{
Page* page = m_frame->page();
return page && m_frame == page->mainFrame();
}
bool FrameLoader::canShowMIMEType(const String& MIMEType) const
{
return m_client->canShowMIMEType(MIMEType);
}
bool FrameLoader::representationExistsForURLScheme(const String& URLScheme)
{
return m_client->representationExistsForURLScheme(URLScheme);
}
String FrameLoader::generatedMIMETypeForURLScheme(const String& URLScheme)
{
return m_client->generatedMIMETypeForURLScheme(URLScheme);
}
void FrameLoader::cancelContentPolicyCheck()
{
m_client->cancelPolicyCheck();
m_policyCheck.clear();
}
void FrameLoader::didReceiveServerRedirectForProvisionalLoadForFrame()
{
m_client->dispatchDidReceiveServerRedirectForProvisionalLoad();
}
void FrameLoader::finishedLoadingDocument(DocumentLoader* loader)
{
#if PLATFORM(WIN) || PLATFORM(CHROMIUM)
if (m_creatingInitialEmptyDocument)
return;
#endif
const String& responseMIMEType = loader->responseMIMEType();
#if PLATFORM(MAC)
m_client->finishedLoading(loader);
if (!ArchiveFactory::isArchiveMimeType(responseMIMEType))
return;
#else
if (!ArchiveFactory::isArchiveMimeType(responseMIMEType)) {
m_client->finishedLoading(loader);
return;
}
#endif
RefPtr<Archive> archive(ArchiveFactory::create(loader->mainResourceData().get(), responseMIMEType));
if (!archive)
return;
loader->addAllArchiveResources(archive.get());
ArchiveResource* mainResource = archive->mainResource();
loader->setParsedArchiveData(mainResource->data());
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());
}
bool FrameLoader::isReplacing() const
{
return m_loadType == FrameLoadTypeReplace;
}
void FrameLoader::setReplacing()
{
m_loadType = FrameLoadTypeReplace;
}
void FrameLoader::revertToProvisional(DocumentLoader* loader)
{
m_client->revertToProvisionalState(loader);
}
bool FrameLoader::subframeIsLoading() const
{
for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling()) {
FrameLoader* childLoader = child->loader();
DocumentLoader* documentLoader = childLoader->documentLoader();
if (documentLoader && documentLoader->isLoadingInAPISense())
return true;
documentLoader = childLoader->provisionalDocumentLoader();
if (documentLoader && documentLoader->isLoadingInAPISense())
return true;
}
return false;
}
void FrameLoader::willChangeTitle(DocumentLoader* loader)
{
m_client->willChangeTitle(loader);
}
FrameLoadType FrameLoader::loadType() const
{
return m_loadType;
}
CachePolicy FrameLoader::cachePolicy() const
{
if (m_isComplete)
return CachePolicyVerify;
if (m_loadType == FrameLoadTypeReloadFromOrigin)
return CachePolicyReload;
if (Frame* parentFrame = m_frame->tree()->parent()) {
CachePolicy parentCachePolicy = parentFrame->loader()->cachePolicy();
if (parentCachePolicy != CachePolicyVerify)
return parentCachePolicy;
}
if (m_loadType == FrameLoadTypeReload)
return CachePolicyRevalidate;
return CachePolicyVerify;
}
void FrameLoader::stopPolicyCheck()
{
m_client->cancelPolicyCheck();
PolicyCheck check = m_policyCheck;
m_policyCheck.clear();
check.cancel();
}
void FrameLoader::checkLoadCompleteForThisFrame()
{
ASSERT(m_client->hasWebView());
switch (m_state) {
case FrameStateProvisional: {
if (m_delegateIsHandlingProvisionalLoadError)
return;
RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
if (!pdl)
return;
const ResourceError& error = pdl->mainDocumentError();
if (error.isNull())
return;
RefPtr<HistoryItem> item;
if (Page* page = m_frame->page())
if (isBackForwardLoadType(loadType()) && m_frame == page->mainFrame())
item = m_currentHistoryItem;
bool shouldReset = true;
if (!pdl->isLoadingInAPISense()) {
m_delegateIsHandlingProvisionalLoadError = true;
m_client->dispatchDidFailProvisionalLoad(error);
m_delegateIsHandlingProvisionalLoadError = false;
stopLoadingSubframes();
pdl->stopLoading();
if (pdl == m_provisionalDocumentLoader)
clearProvisionalLoad();
else if (m_provisionalDocumentLoader) {
KURL unreachableURL = m_provisionalDocumentLoader->unreachableURL();
if (!unreachableURL.isEmpty() && unreachableURL == pdl->request().url())
shouldReset = false;
}
}
if (shouldReset && item)
if (Page* page = m_frame->page()) {
page->backForwardList()->goToItem(item.get());
Settings* settings = m_frame->settings();
page->setGlobalHistoryItem((!settings || settings->privateBrowsingEnabled()) ? 0 : item.get());
}
return;
}
case FrameStateCommittedPage: {
DocumentLoader* dl = m_documentLoader.get();
if (!dl || dl->isLoadingInAPISense())
return;
markLoadComplete();
m_client->forceLayoutForNonHTML();
if (Page* page = m_frame->page())
if ((isBackForwardLoadType(m_loadType) || m_loadType == FrameLoadTypeReload || m_loadType == FrameLoadTypeReloadFromOrigin) && page->backForwardList())
restoreScrollPositionAndViewState();
if (m_creatingInitialEmptyDocument || !m_committedFirstRealDocumentLoad)
return;
const ResourceError& error = dl->mainDocumentError();
#ifndef NDEBUG
m_didDispatchDidCommitLoad = false;
#endif
if (!error.isNull())
m_client->dispatchDidFailLoad(error);
else
m_client->dispatchDidFinishLoad();
if (Page* page = m_frame->page())
page->progress()->progressCompleted(m_frame);
return;
}
case FrameStateComplete:
m_client->frameLoadCompleted();
return;
}
ASSERT_NOT_REACHED();
}
void FrameLoader::continueAfterContentPolicy(PolicyAction policy)
{
PolicyCheck check = m_policyCheck;
m_policyCheck.clear();
check.call(policy);
}
void FrameLoader::continueLoadAfterWillSubmitForm(PolicyAction)
{
if (!m_provisionalDocumentLoader)
return;
m_provisionalDocumentLoader->prepareForLoadStart();
if (!m_provisionalDocumentLoader)
return;
DocumentLoader* activeDocLoader = activeDocumentLoader();
if (activeDocLoader && activeDocLoader->isLoadingMainResource())
return;
m_provisionalDocumentLoader->setLoadingFromCachedPage(false);
unsigned long identifier = 0;
if (Page* page = m_frame->page()) {
identifier = page->progress()->createUniqueIdentifier();
dispatchAssignIdentifierToInitialRequest(identifier, m_provisionalDocumentLoader.get(), m_provisionalDocumentLoader->originalRequest());
}
if (!m_provisionalDocumentLoader->startLoadingMainResource(identifier))
m_provisionalDocumentLoader->updateLoading();
}
void FrameLoader::didFirstLayout()
{
if (Page* page = m_frame->page())
if (isBackForwardLoadType(m_loadType) && page->backForwardList())
restoreScrollPositionAndViewState();
m_firstLayoutDone = true;
m_client->dispatchDidFirstLayout();
}
void FrameLoader::didFirstVisuallyNonEmptyLayout()
{
m_client->dispatchDidFirstVisuallyNonEmptyLayout();
}
void FrameLoader::frameLoadCompleted()
{
m_client->frameLoadCompleted();
if (m_documentLoader)
m_firstLayoutDone = true;
}
bool FrameLoader::firstLayoutDone() const
{
return m_firstLayoutDone;
}
void FrameLoader::detachChildren()
{
Frame* previous;
for (Frame* child = m_frame->tree()->lastChild(); child; child = previous) {
previous = child->tree()->previousSibling();
child->loader()->detachFromParent();
}
}
void FrameLoader::recursiveCheckLoadComplete()
{
Vector<RefPtr<Frame>, 10> frames;
for (RefPtr<Frame> frame = m_frame->tree()->firstChild(); frame; frame = frame->tree()->nextSibling())
frames.append(frame);
unsigned size = frames.size();
for (unsigned i = 0; i < size; i++)
frames[i]->loader()->recursiveCheckLoadComplete();
checkLoadCompleteForThisFrame();
}
void FrameLoader::checkLoadComplete()
{
ASSERT(m_client->hasWebView());
if (Page* page = m_frame->page())
page->mainFrame()->loader()->recursiveCheckLoadComplete();
}
int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
{
if (!recurse)
return numRequests(m_frame->document());
int count = 0;
for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
count += numRequests(frame->document());
return count;
}
String FrameLoader::userAgent(const KURL& url) const
{
return m_client->userAgent(url);
}
void FrameLoader::tokenizerProcessedData()
{
checkCompleted();
}
void FrameLoader::handledOnloadEvents()
{
m_client->dispatchDidHandleOnloadEvents();
}
void FrameLoader::frameDetached()
{
stopAllLoaders();
if (Document* document = m_frame->document())
document->stopActiveDOMObjects();
detachFromParent();
}
void FrameLoader::detachFromParent()
{
RefPtr<Frame> protect(m_frame);
closeURL();
stopAllLoaders();
saveScrollPositionAndViewStateToItem(currentHistoryItem());
detachChildren();
m_client->detachedFromParent2();
setDocumentLoader(0);
m_client->detachedFromParent3();
if (Frame* parent = m_frame->tree()->parent()) {
parent->tree()->removeChild(m_frame);
parent->loader()->scheduleCheckCompleted();
} else {
m_frame->setView(0);
m_frame->pageDestroyed();
}
}
void FrameLoader::addExtraFieldsToSubresourceRequest(ResourceRequest& request)
{
addExtraFieldsToRequest(request, m_loadType, false, false);
}
void FrameLoader::addExtraFieldsToMainResourceRequest(ResourceRequest& request)
{
addExtraFieldsToRequest(request, m_loadType, true, false);
}
void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadType loadType, bool mainResource, bool cookiePolicyURLFromRequest)
{
applyUserAgent(request);
if (loadType == FrameLoadTypeReload) {
request.setCachePolicy(ReloadIgnoringCacheData);
request.setHTTPHeaderField("Cache-Control", "max-age=0");
} else if (loadType == FrameLoadTypeReloadFromOrigin) {
request.setCachePolicy(ReloadIgnoringCacheData);
request.setHTTPHeaderField("Cache-Control", "no-cache");
request.setHTTPHeaderField("Pragma", "no-cache");
}
if (request.mainDocumentURL().isEmpty()) {
if (mainResource && (isLoadingMainFrame() || cookiePolicyURLFromRequest))
request.setMainDocumentURL(request.url());
else if (Page* page = m_frame->page())
request.setMainDocumentURL(page->mainFrame()->loader()->url());
}
if (mainResource)
request.setHTTPAccept("application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
addHTTPOriginIfNeeded(request, String());
Settings* settings = m_frame->settings();
request.setResponseContentDispositionEncodingFallbackArray("UTF-8", m_URL.isEmpty() ? m_encoding : encoding(), settings ? settings->defaultTextEncodingName() : String());
}
void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, String origin)
{
if (!request.httpOrigin().isEmpty())
return;
if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
return;
if (origin.isEmpty()) {
origin = SecurityOrigin::createEmpty()->toString();
}
request.setHTTPOrigin(origin);
}
void FrameLoader::committedLoad(DocumentLoader* loader, const char* data, int length)
{
if (ArchiveFactory::isArchiveMimeType(loader->response().mimeType()))
return;
m_client->committedLoad(loader, data, length);
}
void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
{
RefPtr<FormState> formState = prpFormState;
const KURL& url = inRequest.url();
RefPtr<FormData> formData = inRequest.httpBody();
const String& contentType = inRequest.httpContentType();
String origin = inRequest.httpOrigin();
ResourceRequest workingResourceRequest(url);
if (!referrer.isEmpty())
workingResourceRequest.setHTTPReferrer(referrer);
workingResourceRequest.setHTTPOrigin(origin);
workingResourceRequest.setHTTPMethod("POST");
workingResourceRequest.setHTTPBody(formData);
workingResourceRequest.setHTTPContentType(contentType);
addExtraFieldsToRequest(workingResourceRequest, loadType, true, true);
NavigationAction action(url, loadType, true, event);
if (!frameName.isEmpty()) {
if (Frame* targetFrame = formState ? 0 : findFrameForNavigation(frameName))
targetFrame->loader()->loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
else
checkNewWindowPolicy(action, workingResourceRequest, formState.release(), frameName);
} else
loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
}
unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector<char>& data)
{
String referrer = m_outgoingReferrer;
if (shouldHideReferrer(request.url(), referrer))
referrer = String();
ResourceRequest initialRequest = request;
initialRequest.setTimeoutInterval(10);
if (initialRequest.isConditional())
initialRequest.setCachePolicy(ReloadIgnoringCacheData);
else
initialRequest.setCachePolicy(documentLoader()->request().cachePolicy());
if (!referrer.isEmpty())
initialRequest.setHTTPReferrer(referrer);
addHTTPOriginIfNeeded(initialRequest, outgoingOrigin());
if (Page* page = m_frame->page())
initialRequest.setMainDocumentURL(page->mainFrame()->loader()->documentLoader()->request().url());
initialRequest.setHTTPUserAgent(client()->userAgent(request.url()));
unsigned long identifier = 0;
ResourceRequest newRequest(initialRequest);
requestFromDelegate(newRequest, identifier, error);
if (error.isNull()) {
ASSERT(!newRequest.isNull());
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
ApplicationCacheResource* resource;
if (documentLoader()->shouldLoadResourceFromApplicationCache(newRequest, resource)) {
if (resource) {
response = resource->response();
data.append(resource->data()->data(), resource->data()->size());
} else
error = cannotShowURLError(newRequest);
} else {
#endif
ResourceHandle::loadResourceSynchronously(newRequest, error, response, data, m_frame);
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
if ((!error.isNull() && !error.isCancellation())
|| response.httpStatusCode() / 100 == 4 || response.httpStatusCode() / 100 == 5
|| !protocolHostAndPortAreEqual(newRequest.url(), response.url())) {
if (documentLoader()->getApplicationCacheFallbackResource(newRequest, resource)) {
response = resource->response();
data.clear();
data.append(resource->data()->data(), resource->data()->size());
}
}
}
#endif
}
sendRemainingDelegateMessages(identifier, response, data.size(), error);
return identifier;
}
void FrameLoader::assignIdentifierToInitialRequest(unsigned long identifier, const ResourceRequest& clientRequest)
{
return dispatchAssignIdentifierToInitialRequest(identifier, activeDocumentLoader(), clientRequest);
}
void FrameLoader::willSendRequest(ResourceLoader* loader, ResourceRequest& clientRequest, const ResourceResponse& redirectResponse)
{
applyUserAgent(clientRequest);
dispatchWillSendRequest(loader->documentLoader(), loader->identifier(), clientRequest, redirectResponse);
}
void FrameLoader::didReceiveResponse(ResourceLoader* loader, const ResourceResponse& r)
{
activeDocumentLoader()->addResponse(r);
if (Page* page = m_frame->page())
page->progress()->incrementProgress(loader->identifier(), r);
dispatchDidReceiveResponse(loader->documentLoader(), loader->identifier(), r);
}
void FrameLoader::didReceiveData(ResourceLoader* loader, const char* data, int length, int lengthReceived)
{
if (Page* page = m_frame->page())
page->progress()->incrementProgress(loader->identifier(), data, length);
dispatchDidReceiveContentLength(loader->documentLoader(), loader->identifier(), lengthReceived);
}
void FrameLoader::didFailToLoad(ResourceLoader* loader, const ResourceError& error)
{
if (Page* page = m_frame->page())
page->progress()->completeProgress(loader->identifier());
if (!error.isNull())
m_client->dispatchDidFailLoading(loader->documentLoader(), loader->identifier(), error);
}
const ResourceRequest& FrameLoader::originalRequest() const
{
return activeDocumentLoader()->originalRequestCopy();
}
void FrameLoader::receivedMainResourceError(const ResourceError& error, bool isComplete)
{
RefPtr<Frame> protect(m_frame);
RefPtr<DocumentLoader> loader = activeDocumentLoader();
if (isComplete) {
stop();
if (m_client->shouldFallBack(error))
handleFallbackContent();
}
if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url())
m_submittedFormURL = KURL();
invalidateCurrentItemCachedPage();
if (m_sentRedirectNotification)
clientRedirectCancelledOrFinished(false);
}
loader->mainReceivedError(error, isComplete);
}
void FrameLoader::callContinueFragmentScrollAfterNavigationPolicy(void* argument,
const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue)
{
FrameLoader* loader = static_cast<FrameLoader*>(argument);
loader->continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
}
void FrameLoader::continueFragmentScrollAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
{
bool isRedirect = m_quickRedirectComing || m_policyLoadType == FrameLoadTypeRedirectWithLockedBackForwardList;
m_quickRedirectComing = false;
if (!shouldContinue)
return;
KURL url = request.url();
m_documentLoader->replaceRequestURLForAnchorScroll(url);
if (!isRedirect && !shouldTreatURLAsSameAsCurrent(url)) {
addHistoryItemForFragmentScroll();
}
scrollToAnchor(url);
if (!isRedirect)
checkLoadComplete();
m_client->dispatchDidChangeLocationWithinPage();
m_client->didFinishLoad();
}
bool FrameLoader::shouldScrollToAnchor(bool isFormSubmission, FrameLoadType loadType, const KURL& url)
{
return !isFormSubmission
&& loadType != FrameLoadTypeReload
&& loadType != FrameLoadTypeReloadFromOrigin
&& loadType != FrameLoadTypeSame
&& !shouldReload(this->url(), url)
&& !m_frame->isFrameSet();
}
void FrameLoader::opened()
{
if (m_loadType == FrameLoadTypeStandard && m_documentLoader->isClientRedirect())
updateHistoryForClientRedirect();
if (m_documentLoader->isLoadingFromCachedPage()) {
if (m_frame->document()->doctype() && m_frame->page())
m_frame->page()->chrome()->client()->didReceiveDocType(m_frame);
m_frame->document()->documentDidBecomeActive();
m_client->forceLayout();
const ResponseVector& responses = m_documentLoader->responses();
size_t count = responses.size();
for (size_t i = 0; i < count; i++) {
const ResourceResponse& response = responses[i];
ResourceError error;
unsigned long identifier;
ResourceRequest request(response.url());
requestFromDelegate(request, identifier, error);
sendRemainingDelegateMessages(identifier, response, static_cast<int>(response.expectedContentLength()), error);
}
pageCache()->remove(m_currentHistoryItem.get());
m_documentLoader->setPrimaryLoadComplete(true);
checkLoadCompleteForThisFrame();
}
}
void FrameLoader::checkNewWindowPolicy(const NavigationAction& action, const ResourceRequest& request,
PassRefPtr<FormState> formState, const String& frameName)
{
m_policyCheck.set(request, formState, frameName,
callContinueLoadAfterNewWindowPolicy, this);
m_client->dispatchDecidePolicyForNewWindowAction(&FrameLoader::continueAfterNewWindowPolicy,
action, request, formState, frameName);
}
void FrameLoader::continueAfterNewWindowPolicy(PolicyAction policy)
{
PolicyCheck check = m_policyCheck;
m_policyCheck.clear();
switch (policy) {
case PolicyIgnore:
check.clearRequest();
break;
case PolicyDownload:
m_client->startDownload(check.request());
check.clearRequest();
break;
case PolicyUse:
break;
}
check.call(policy == PolicyUse);
}
void FrameLoader::checkNavigationPolicy(const ResourceRequest& request, DocumentLoader* loader,
PassRefPtr<FormState> formState, NavigationPolicyDecisionFunction function, void* argument)
{
NavigationAction action = loader->triggeringAction();
if (action.isEmpty()) {
action = NavigationAction(request.url(), NavigationTypeOther);
loader->setTriggeringAction(action);
}
if (equalIgnoringHeaderFields(request, loader->lastCheckedRequest()) || (!request.isNull() && request.url().isEmpty())) {
function(argument, request, 0, true);
loader->setLastCheckedRequest(request);
return;
}
if (loader->substituteData().isValid() && !loader->substituteData().failingURL().isEmpty()) {
if (isBackForwardLoadType(m_policyLoadType))
m_policyLoadType = FrameLoadTypeReload;
function(argument, request, 0, true);
return;
}
loader->setLastCheckedRequest(request);
m_policyCheck.set(request, formState.get(), function, argument);
if (!request.isNull() && request.url().protocolIs(cMobileQuickLookProtocol)) {
continueAfterNavigationPolicy(PolicyUse);
return;
}
m_delegateIsDecidingNavigationPolicy = true;
m_client->dispatchDecidePolicyForNavigationAction(&FrameLoader::continueAfterNavigationPolicy,
action, request, formState);
m_delegateIsDecidingNavigationPolicy = false;
}
void FrameLoader::continueAfterNavigationPolicy(PolicyAction policy)
{
PolicyCheck check = m_policyCheck;
m_policyCheck.clear();
bool shouldContinue = policy == PolicyUse;
switch (policy) {
case PolicyIgnore:
check.clearRequest();
break;
case PolicyDownload:
m_client->startDownload(check.request());
check.clearRequest();
break;
case PolicyUse: {
ResourceRequest request(check.request());
if (!m_client->canHandleRequest(request)) {
handleUnimplementablePolicy(m_client->cannotShowURLError(check.request()));
check.clearRequest();
shouldContinue = false;
}
break;
}
}
check.call(shouldContinue);
}
void FrameLoader::callContinueLoadAfterNavigationPolicy(void* argument,
const ResourceRequest& request, PassRefPtr<FormState> formState, bool shouldContinue)
{
FrameLoader* loader = static_cast<FrameLoader*>(argument);
loader->continueLoadAfterNavigationPolicy(request, formState, shouldContinue);
}
void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest&, PassRefPtr<FormState> formState, bool shouldContinue)
{
ASSERT(m_policyDocumentLoader || !m_provisionalDocumentLoader->unreachableURL().isEmpty());
bool isTargetItem = m_provisionalHistoryItem ? m_provisionalHistoryItem->isTargetItem() : false;
bool canContinue = shouldContinue && (!isLoadingMainFrame() || m_frame->shouldClose());
if (!canContinue) {
if (m_quickRedirectComing)
clientRedirectCancelledOrFinished(false);
setPolicyDocumentLoader(0);
if ((isTargetItem || isLoadingMainFrame()) && isBackForwardLoadType(m_policyLoadType))
if (Page* page = m_frame->page()) {
Frame* mainFrame = page->mainFrame();
if (HistoryItem* resetItem = mainFrame->loader()->m_currentHistoryItem.get()) {
page->backForwardList()->goToItem(resetItem);
Settings* settings = m_frame->settings();
page->setGlobalHistoryItem((!settings || settings->privateBrowsingEnabled()) ? 0 : resetItem);
}
}
return;
}
FrameLoadType type = m_policyLoadType;
stopAllLoaders();
if (!m_frame->page())
return;
setProvisionalDocumentLoader(m_policyDocumentLoader.get());
m_loadType = type;
setState(FrameStateProvisional);
setPolicyDocumentLoader(0);
if (isBackForwardLoadType(type) && loadProvisionalItemFromCachedPage())
return;
if (formState)
m_client->dispatchWillSubmitForm(&FrameLoader::continueLoadAfterWillSubmitForm, formState);
else
continueLoadAfterWillSubmitForm();
}
void FrameLoader::callContinueLoadAfterNewWindowPolicy(void* argument,
const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName, bool shouldContinue)
{
FrameLoader* loader = static_cast<FrameLoader*>(argument);
loader->continueLoadAfterNewWindowPolicy(request, formState, frameName, shouldContinue);
}
void FrameLoader::continueLoadAfterNewWindowPolicy(const ResourceRequest& request,
PassRefPtr<FormState> formState, const String& frameName, bool shouldContinue)
{
if (!shouldContinue)
return;
RefPtr<Frame> frame = m_frame;
RefPtr<Frame> mainFrame = m_client->dispatchCreatePage();
if (!mainFrame)
return;
if (frameName != "_blank")
mainFrame->tree()->setName(frameName);
mainFrame->loader()->setOpenedByDOM();
mainFrame->loader()->m_client->dispatchShow();
mainFrame->loader()->setOpener(frame.get());
mainFrame->loader()->loadWithNavigationAction(request, NavigationAction(), false, FrameLoadTypeStandard, formState);
}
void FrameLoader::sendRemainingDelegateMessages(unsigned long identifier, const ResourceResponse& response, int length, const ResourceError& error)
{
if (!response.isNull())
dispatchDidReceiveResponse(m_documentLoader.get(), identifier, response);
if (length > 0)
dispatchDidReceiveContentLength(m_documentLoader.get(), identifier, length);
if (error.isNull())
dispatchDidFinishLoading(m_documentLoader.get(), identifier);
else
m_client->dispatchDidFailLoading(m_documentLoader.get(), identifier, error);
}
void FrameLoader::requestFromDelegate(ResourceRequest& request, unsigned long& identifier, ResourceError& error)
{
ASSERT(!request.isNull());
identifier = 0;
if (Page* page = m_frame->page()) {
identifier = page->progress()->createUniqueIdentifier();
dispatchAssignIdentifierToInitialRequest(identifier, m_documentLoader.get(), request);
}
ResourceRequest newRequest(request);
dispatchWillSendRequest(m_documentLoader.get(), identifier, newRequest, ResourceResponse());
if (newRequest.isNull())
error = cancelledError(request);
else
error = ResourceError();
request = newRequest;
}
void FrameLoader::loadedResourceFromMemoryCache(const CachedResource* resource)
{
Page* page = m_frame->page();
if (!page)
return;
if (!resource->sendResourceLoadCallbacks() || m_documentLoader->haveToldClientAboutLoad(resource->url()))
return;
if (!page->areMemoryCacheClientCallsEnabled()) {
m_documentLoader->recordMemoryCacheLoadForFutureClientNotification(resource->url());
m_documentLoader->didTellClientAboutLoad(resource->url());
return;
}
ResourceRequest request(resource->url());
if (m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize())) {
m_documentLoader->didTellClientAboutLoad(resource->url());
return;
}
unsigned long identifier;
ResourceError error;
requestFromDelegate(request, identifier, error);
sendRemainingDelegateMessages(identifier, resource->response(), resource->encodedSize(), error);
}
void FrameLoader::applyUserAgent(ResourceRequest& request)
{
String userAgent = client()->userAgent(request.url());
ASSERT(!userAgent.isNull());
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<SecurityOrigin> 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()) {
if (distance == 0)
return true;
if (distance > 0 && distance <= page->backForwardList()->forwardListCount())
return true;
if (distance < 0 && -distance <= page->backForwardList()->backListCount())
return true;
}
return false;
}
int FrameLoader::getHistoryLength()
{
if (Page* page = m_frame->page())
return page->backForwardList()->backListCount() + 1;
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);
}
bool FrameLoader::loadProvisionalItemFromCachedPage()
{
RefPtr<CachedPage> cachedPage = pageCache()->get(m_provisionalHistoryItem.get());
if (!cachedPage || !cachedPage->document())
return false;
provisionalDocumentLoader()->loadFromCachedPage(cachedPage.release());
return true;
}
void FrameLoader::cachePageForHistoryItem(HistoryItem* item)
{
if (Page* page = m_frame->page()) {
RefPtr<CachedPage> cachedPage = CachedPage::create(page);
m_client->savePlatformDataToCachedFrame(cachedPage->cachedMainFrame());
pageCache()->add(item, cachedPage.release());
}
}
bool FrameLoader::shouldTreatURLAsSameAsCurrent(const KURL& url) const
{
if (!m_currentHistoryItem)
return false;
return url == m_currentHistoryItem->url() || url == m_currentHistoryItem->originalURL();
}
PassRefPtr<HistoryItem> FrameLoader::createHistoryItem(bool useOriginal)
{
DocumentLoader* docLoader = documentLoader();
KURL unreachableURL = docLoader ? docLoader->unreachableURL() : KURL();
KURL url;
KURL originalURL;
if (!unreachableURL.isEmpty()) {
url = unreachableURL;
originalURL = unreachableURL;
} else {
originalURL = docLoader ? docLoader->originalURL() : KURL();
if (useOriginal)
url = originalURL;
else if (docLoader)
url = docLoader->requestURL();
}
LOG(History, "WebCoreHistory: Creating item for %s", url.string().ascii().data());
if (url.isEmpty())
url = blankURL();
if (originalURL.isEmpty())
originalURL = blankURL();
Frame* parentFrame = m_frame->tree()->parent();
String parent = parentFrame ? parentFrame->tree()->name() : "";
String title = docLoader ? docLoader->title() : "";
RefPtr<HistoryItem> item = HistoryItem::create(url, m_frame->tree()->name(), parent, title);
item->setOriginalURLString(originalURL.string());
if (!unreachableURL.isEmpty() || !docLoader || docLoader->response().httpStatusCode() >= 400)
item->setLastVisitWasFailure(true);
if (docLoader) {
if (useOriginal)
item->setFormInfoFromRequest(docLoader->originalRequest());
else
item->setFormInfoFromRequest(docLoader->request());
}
m_previousHistoryItem = m_currentHistoryItem;
m_currentHistoryItem = item;
return item.release();
}
void FrameLoader::addBackForwardItemClippedAtTarget(bool doClip)
{
Page* page = m_frame->page();
if (!page)
return;
if (documentLoader()->urlForHistory().isEmpty())
return;
Frame* mainFrame = page->mainFrame();
ASSERT(mainFrame);
FrameLoader* frameLoader = mainFrame->loader();
if (!frameLoader->m_didPerformFirstNavigation && page->backForwardList()->entries().size() == 1) {
frameLoader->m_didPerformFirstNavigation = true;
m_client->didPerformFirstNavigation();
}
RefPtr<HistoryItem> item = frameLoader->createHistoryItemTree(m_frame, doClip);
LOG(BackForward, "WebCoreBackForward - Adding backforward item %p for frame %s", item.get(), documentLoader()->url().string().ascii().data());
page->backForwardList()->addItem(item);
}
PassRefPtr<HistoryItem> FrameLoader::createHistoryItemTree(Frame* targetFrame, bool clipAtTarget)
{
RefPtr<HistoryItem> bfItem = createHistoryItem(m_frame->tree()->parent() ? true : false);
if (m_previousHistoryItem)
saveScrollPositionAndViewStateToItem(m_previousHistoryItem.get());
if (!(clipAtTarget && m_frame == targetFrame)) {
saveDocumentState();
for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
FrameLoader* childLoader = child->loader();
bool hasChildLoaded = childLoader->frameHasLoaded();
if (!(!hasChildLoaded && childLoader->isHostedByObjectElement()))
bfItem->addChildItem(childLoader->createHistoryItemTree(targetFrame, clipAtTarget));
}
}
if (m_frame == targetFrame)
bfItem->setIsTargetItem(true);
return bfItem;
}
Frame* FrameLoader::findFrameForNavigation(const AtomicString& name)
{
Frame* frame = m_frame->tree()->find(name);
if (!shouldAllowNavigation(frame))
return 0;
return frame;
}
void FrameLoader::saveScrollPositionAndViewStateToItem(HistoryItem* item)
{
if (!item || !m_frame->view())
return;
item->setScrollPoint(m_frame->view()->scrollPosition());
m_client->saveViewStateToItem(item);
}
void FrameLoader::restoreScrollPositionAndViewState()
{
if (!m_committedFirstRealDocumentLoad)
return;
ASSERT(m_currentHistoryItem);
if (!m_currentHistoryItem)
return;
m_client->restoreViewState();
}
void FrameLoader::invalidateCurrentItemCachedPage()
{
CachedPage* cachedPage = pageCache()->get(m_currentHistoryItem.get());
ASSERT(!cachedPage || cachedPage->document() == m_frame->document());
if (cachedPage && cachedPage->document() == m_frame->document()) {
cachedPage->document()->setInPageCache(false);
cachedPage->clear();
}
if (cachedPage)
pageCache()->remove(m_currentHistoryItem.get());
}
void FrameLoader::saveDocumentState()
{
if (m_creatingInitialEmptyDocument)
return;
HistoryItem* item = m_previousHistoryItem ? m_previousHistoryItem.get() : m_currentHistoryItem.get();
if (!item)
return;
Document* document = m_frame->document();
ASSERT(document);
if (document && item->isCurrentDocument(document)) {
LOG(Loading, "WebCoreLoading %s: saving form state to %p", m_frame->tree()->name().string().utf8().data(), item);
item->setDocumentState(document->formElementsState());
}
}
void FrameLoader::loadItem(HistoryItem* item, FrameLoadType loadType)
{
if (!m_frame->page())
return;
KURL itemURL = item->url();
KURL itemOriginalURL = item->originalURL();
KURL currentURL;
if (documentLoader())
currentURL = documentLoader()->url();
RefPtr<FormData> formData = item->formData();
#if ENABLE(WML)
if (!formData && urlsMatchItem(item) && !m_frame->document()->isWMLDocument()) {
#else
if (!formData && urlsMatchItem(item)) {
#endif
saveScrollPositionAndViewStateToItem(m_currentHistoryItem.get());
if (FrameView* view = m_frame->view())
view->setWasScrolledByUser(false);
m_currentHistoryItem = item;
scrollToAnchor(item->url());
restoreScrollPositionAndViewState();
documentLoader()->replaceRequestURLForAnchorScroll(itemURL);
m_client->dispatchDidChangeLocationWithinPage();
m_client->didFinishLoad();
} else {
m_provisionalHistoryItem = item;
bool inPageCache = false;
if (RefPtr<CachedPage> cachedPage = pageCache()->get(item)) {
double interval = currentTime() - cachedPage->timeStamp();
if (interval <= 1800) {
loadWithDocumentLoader(cachedPage->documentLoader(), loadType, 0);
inPageCache = true;
} else {
LOG(PageCache, "Not restoring page for %s from back/forward cache because cache entry has expired", m_provisionalHistoryItem->url().string().ascii().data());
pageCache()->remove(item);
}
}
if (!inPageCache) {
bool addedExtraFields = false;
ResourceRequest request(itemURL);
if (!item->referrer().isNull())
request.setHTTPReferrer(item->referrer());
NavigationAction action;
if (formData) {
formData->generateFiles(m_frame->page()->chrome()->client());
request.setHTTPMethod("POST");
request.setHTTPBody(formData);
request.setHTTPContentType(item->formContentType());
RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::createFromString(item->referrer());
addHTTPOriginIfNeeded(request, securityOrigin->toString());
addExtraFieldsToRequest(request, m_loadType, true, formData);
addedExtraFields = true;
if (ResourceHandle::willLoadFromCache(request))
action = NavigationAction(itemURL, loadType, false);
else {
request.setCachePolicy(ReloadIgnoringCacheData);
action = NavigationAction(itemURL, NavigationTypeFormResubmitted);
}
} else {
switch (loadType) {
case FrameLoadTypeReload:
case FrameLoadTypeReloadFromOrigin:
request.setCachePolicy(ReloadIgnoringCacheData);
break;
case FrameLoadTypeBack:
case FrameLoadTypeForward:
case FrameLoadTypeIndexedBackForward:
if (itemURL.protocol() != "https")
request.setCachePolicy(ReturnCacheDataElseLoad);
break;
case FrameLoadTypeStandard:
case FrameLoadTypeRedirectWithLockedBackForwardList:
break;
case FrameLoadTypeSame:
default:
ASSERT_NOT_REACHED();
}
action = NavigationAction(itemOriginalURL, loadType, false);
}
if (!addedExtraFields)
addExtraFieldsToRequest(request, m_loadType, true, formData);
loadWithNavigationAction(request, action, false, loadType, 0);
}
}
}
bool FrameLoader::urlsMatchItem(HistoryItem* item) const
{
const KURL& currentURL = documentLoader()->url();
if (!equalIgnoringRef(currentURL, item->url()))
return false;
const HistoryItemVector& childItems = item->children();
unsigned size = childItems.size();
for (unsigned i = 0; i < size; ++i) {
Frame* childFrame = m_frame->tree()->child(childItems[i]->target());
if (childFrame && !childFrame->loader()->urlsMatchItem(childItems[i].get()))
return false;
}
return true;
}
void FrameLoader::goToItem(HistoryItem* targetItem, FrameLoadType type)
{
ASSERT(!m_frame->tree()->parent());
Page* page = m_frame->page();
if (!page)
return;
if (!m_client->shouldGoToHistoryItem(targetItem))
return;
BackForwardList* bfList = page->backForwardList();
HistoryItem* currentItem = bfList->currentItem();
bfList->goToItem(targetItem);
Settings* settings = m_frame->settings();
page->setGlobalHistoryItem((!settings || settings->privateBrowsingEnabled()) ? 0 : targetItem);
recursiveGoToItem(targetItem, currentItem, type);
}
void FrameLoader::recursiveGoToItem(HistoryItem* item, HistoryItem* fromItem, FrameLoadType type)
{
ASSERT(item);
ASSERT(fromItem);
KURL itemURL = item->url();
KURL currentURL;
if (documentLoader())
currentURL = documentLoader()->url();
if (!item->isTargetItem() &&
itemURL == currentURL &&
((m_frame->tree()->name().isEmpty() && item->target().isEmpty()) || m_frame->tree()->name() == item->target()) &&
childFramesMatchItem(item))
{
ASSERT(!m_previousHistoryItem);
saveDocumentState();
saveScrollPositionAndViewStateToItem(m_currentHistoryItem.get());
if (FrameView* view = m_frame->view())
view->setWasScrolledByUser(false);
m_currentHistoryItem = item;
restoreDocumentState();
restoreScrollPositionAndViewState();
const HistoryItemVector& childItems = item->children();
int size = childItems.size();
for (int i = 0; i < size; ++i) {
String childFrameName = childItems[i]->target();
HistoryItem* fromChildItem = fromItem->childItemWithTarget(childFrameName);
ASSERT(fromChildItem || fromItem->isTargetItem());
Frame* childFrame = m_frame->tree()->child(childFrameName);
ASSERT(childFrame);
childFrame->loader()->recursiveGoToItem(childItems[i].get(), fromChildItem, type);
}
} else {
loadItem(item, type);
}
}
bool FrameLoader::childFramesMatchItem(HistoryItem* item) const
{
const HistoryItemVector& childItems = item->children();
if (childItems.size() != m_frame->tree()->childCount())
return false;
unsigned size = childItems.size();
for (unsigned i = 0; i < size; ++i) {
if (!m_frame->tree()->child(childItems[i]->target()))
return false;
}
return true;
}
void FrameLoader::updateHistoryForStandardLoad()
{
LOG(History, "WebCoreHistory: Updating History for Standard Load in frame %s", documentLoader()->url().string().ascii().data());
Settings* settings = m_frame->settings();
bool needPrivacy = !settings || settings->privateBrowsingEnabled();
const KURL& historyURL = documentLoader()->urlForHistory();
bool didUpdateGlobalHistory = false;
if (!documentLoader()->isClientRedirect()) {
if (!historyURL.isEmpty()) {
addBackForwardItemClippedAtTarget(true);
if (!needPrivacy) {
m_client->updateGlobalHistory();
didUpdateGlobalHistory = true;
}
if (Page* page = m_frame->page())
page->setGlobalHistoryItem(needPrivacy ? 0 : page->backForwardList()->currentItem());
}
} else if (documentLoader()->unreachableURL().isEmpty() && m_currentHistoryItem) {
m_currentHistoryItem->setURL(documentLoader()->url());
m_currentHistoryItem->setFormInfoFromRequest(documentLoader()->request());
}
if (!historyURL.isEmpty() && !needPrivacy) {
if (Page* page = m_frame->page())
page->group().addVisitedLink(historyURL);
if (!didUpdateGlobalHistory && !url().isEmpty())
m_client->updateGlobalHistoryForRedirectWithoutHistoryItem();
}
}
void FrameLoader::updateHistoryForClientRedirect()
{
#if !LOG_DISABLED
if (documentLoader())
LOG(History, "WebCoreHistory: Updating History for client redirect in frame %s", documentLoader()->title().utf8().data());
#endif
if (m_currentHistoryItem) {
m_currentHistoryItem->clearDocumentState();
m_currentHistoryItem->clearScrollPoint();
}
Settings* settings = m_frame->settings();
bool needPrivacy = !settings || settings->privateBrowsingEnabled();
const KURL& historyURL = documentLoader()->urlForHistory();
if (!historyURL.isEmpty() && !needPrivacy) {
if (Page* page = m_frame->page())
page->group().addVisitedLink(historyURL);
}
}
void FrameLoader::updateHistoryForBackForwardNavigation()
{
#if !LOG_DISABLED
if (documentLoader())
LOG(History, "WebCoreHistory: Updating History for back/forward navigation in frame %s", documentLoader()->title().utf8().data());
#endif
saveScrollPositionAndViewStateToItem(m_previousHistoryItem.get());
}
void FrameLoader::updateHistoryForReload()
{
#if !LOG_DISABLED
if (documentLoader())
LOG(History, "WebCoreHistory: Updating History for reload in frame %s", documentLoader()->title().utf8().data());
#endif
if (m_currentHistoryItem) {
pageCache()->remove(m_currentHistoryItem.get());
if (loadType() == FrameLoadTypeReload || loadType() == FrameLoadTypeReloadFromOrigin)
saveScrollPositionAndViewStateToItem(m_currentHistoryItem.get());
if (documentLoader()->unreachableURL().isEmpty())
m_currentHistoryItem->setURL(documentLoader()->requestURL());
}
}
void FrameLoader::updateHistoryForRedirectWithLockedBackForwardList()
{
#if !LOG_DISABLED
if (documentLoader())
LOG(History, "WebCoreHistory: Updating History for redirect load in frame %s", documentLoader()->title().utf8().data());
#endif
Settings* settings = m_frame->settings();
bool needPrivacy = !settings || settings->privateBrowsingEnabled();
const KURL& historyURL = documentLoader()->urlForHistory();
bool didUpdateGlobalHistory = false;
if (documentLoader()->isClientRedirect()) {
if (!m_currentHistoryItem && !m_frame->tree()->parent()) {
if (!historyURL.isEmpty()) {
addBackForwardItemClippedAtTarget(true);
if (!needPrivacy) {
m_client->updateGlobalHistory();
didUpdateGlobalHistory = true;
}
if (Page* page = m_frame->page())
page->setGlobalHistoryItem(needPrivacy ? 0 : page->backForwardList()->currentItem());
}
}
if (m_currentHistoryItem) {
m_currentHistoryItem->setURL(documentLoader()->url());
m_currentHistoryItem->setFormInfoFromRequest(documentLoader()->request());
}
} else {
Frame* parentFrame = m_frame->tree()->parent();
if (parentFrame && parentFrame->loader()->m_currentHistoryItem)
parentFrame->loader()->m_currentHistoryItem->setChildItem(createHistoryItem(true));
}
if (!historyURL.isEmpty() && !needPrivacy) {
if (Page* page = m_frame->page())
page->group().addVisitedLink(historyURL);
if (!didUpdateGlobalHistory && !url().isEmpty())
m_client->updateGlobalHistoryForRedirectWithoutHistoryItem();
}
}
void FrameLoader::updateHistoryForCommit()
{
#if !LOG_DISABLED
if (documentLoader())
LOG(History, "WebCoreHistory: Updating History for commit in frame %s", documentLoader()->title().utf8().data());
#endif
FrameLoadType type = loadType();
if (isBackForwardLoadType(type) ||
((type == FrameLoadTypeReload || type == FrameLoadTypeReloadFromOrigin) && !provisionalDocumentLoader()->unreachableURL().isEmpty())) {
m_previousHistoryItem = m_currentHistoryItem;
ASSERT(m_provisionalHistoryItem);
m_currentHistoryItem = m_provisionalHistoryItem;
m_provisionalHistoryItem = 0;
}
}
void FrameLoader::updateHistoryForAnchorScroll()
{
if (m_URL.isEmpty())
return;
Settings* settings = m_frame->settings();
if (!settings || settings->privateBrowsingEnabled())
return;
Page* page = m_frame->page();
if (!page)
return;
page->group().addVisitedLink(m_URL);
}
void FrameLoader::saveDocumentAndScrollState()
{
for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame)) {
frame->loader()->saveDocumentState();
frame->loader()->saveScrollPositionAndViewStateToItem(frame->loader()->currentHistoryItem());
}
}
HistoryItem* FrameLoader::currentHistoryItem()
{
return m_currentHistoryItem.get();
}
HistoryItem* FrameLoader::previousHistoryItem()
{
return m_previousHistoryItem.get();
}
HistoryItem* FrameLoader::provisionalHistoryItem()
{
return m_provisionalHistoryItem.get();
}
void FrameLoader::setPreviousHistoryItem(PassRefPtr<HistoryItem> item)
{
m_previousHistoryItem = item;
}
void FrameLoader::setMainDocumentError(DocumentLoader* loader, const ResourceError& error)
{
m_client->setMainDocumentError(loader, error);
}
void FrameLoader::mainReceivedCompleteError(DocumentLoader* loader, const ResourceError&)
{
loader->setPrimaryLoadComplete(true);
m_client->dispatchDidLoadMainResource(activeDocumentLoader());
checkCompleted();
if (m_frame->page())
checkLoadComplete();
}
void FrameLoader::mainReceivedError(const ResourceError& error, bool isComplete)
{
activeDocumentLoader()->mainReceivedError(error, isComplete);
}
ResourceError FrameLoader::cancelledError(const ResourceRequest& request) const
{
ResourceError error = m_client->cancelledError(request);
error.setIsCancellation(true);
return error;
}
ResourceError FrameLoader::blockedError(const ResourceRequest& request) const
{
return m_client->blockedError(request);
}
ResourceError FrameLoader::cannotShowURLError(const ResourceRequest& request) const
{
return m_client->cannotShowURLError(request);
}
ResourceError FrameLoader::fileDoesNotExistError(const ResourceResponse& response) const
{
return m_client->fileDoesNotExistError(response);
}
void FrameLoader::didFinishLoad(ResourceLoader* loader)
{
if (Page* page = m_frame->page())
page->progress()->completeProgress(loader->identifier());
dispatchDidFinishLoading(loader->documentLoader(), loader->identifier());
}
bool FrameLoader::shouldUseCredentialStorage(ResourceLoader* loader)
{
return m_client->shouldUseCredentialStorage(loader->documentLoader(), loader->identifier());
}
void FrameLoader::didReceiveAuthenticationChallenge(ResourceLoader* loader, const AuthenticationChallenge& currentWebChallenge)
{
m_client->dispatchDidReceiveAuthenticationChallenge(loader->documentLoader(), loader->identifier(), currentWebChallenge);
}
void FrameLoader::didCancelAuthenticationChallenge(ResourceLoader* loader, const AuthenticationChallenge& currentWebChallenge)
{
m_client->dispatchDidCancelAuthenticationChallenge(loader->documentLoader(), loader->identifier(), currentWebChallenge);
}
bool FrameLoader::canAuthenticateAgainstProtectionSpace(ResourceLoader* loader, const ProtectionSpace& protectionSpace)
{
return m_client->canAuthenticateAgainstProtectionSpace(loader->documentLoader(), loader->identifier(), protectionSpace);
}
PolicyCheck::PolicyCheck()
: m_navigationFunction(0)
, m_newWindowFunction(0)
, m_contentFunction(0)
{
}
void PolicyCheck::clear()
{
clearRequest();
m_navigationFunction = 0;
m_newWindowFunction = 0;
m_contentFunction = 0;
}
void PolicyCheck::set(const ResourceRequest& request, PassRefPtr<FormState> formState,
NavigationPolicyDecisionFunction function, void* argument)
{
m_request = request;
m_formState = formState;
m_frameName = String();
m_navigationFunction = function;
m_newWindowFunction = 0;
m_contentFunction = 0;
m_argument = argument;
}
void PolicyCheck::set(const ResourceRequest& request, PassRefPtr<FormState> formState,
const String& frameName, NewWindowPolicyDecisionFunction function, void* argument)
{
m_request = request;
m_formState = formState;
m_frameName = frameName;
m_navigationFunction = 0;
m_newWindowFunction = function;
m_contentFunction = 0;
m_argument = argument;
}
void PolicyCheck::set(ContentPolicyDecisionFunction function, void* argument)
{
m_request = ResourceRequest();
m_formState = 0;
m_frameName = String();
m_navigationFunction = 0;
m_newWindowFunction = 0;
m_contentFunction = function;
m_argument = argument;
}
void PolicyCheck::call(bool shouldContinue)
{
if (m_navigationFunction)
m_navigationFunction(m_argument, m_request, m_formState.get(), shouldContinue);
if (m_newWindowFunction)
m_newWindowFunction(m_argument, m_request, m_formState.get(), m_frameName, shouldContinue);
ASSERT(!m_contentFunction);
}
void PolicyCheck::call(PolicyAction action)
{
ASSERT(!m_navigationFunction);
ASSERT(!m_newWindowFunction);
ASSERT(m_contentFunction);
m_contentFunction(m_argument, action);
}
void PolicyCheck::clearRequest()
{
m_request = ResourceRequest();
m_formState = 0;
m_frameName = String();
}
void PolicyCheck::cancel()
{
clearRequest();
if (m_navigationFunction)
m_navigationFunction(m_argument, m_request, m_formState.get(), false);
if (m_newWindowFunction)
m_newWindowFunction(m_argument, m_request, m_formState.get(), m_frameName, false);
if (m_contentFunction)
m_contentFunction(m_argument, PolicyIgnore);
}
void FrameLoader::setTitle(const String& title)
{
documentLoader()->setTitle(title);
}
KURL FrameLoader::originalRequestURL() const
{
return activeDocumentLoader()->originalRequest().url();
}
String FrameLoader::referrer() const
{
return documentLoader()->request().httpReferrer();
}
void FrameLoader::dispatchWindowObjectAvailable()
{
if (!m_frame->script()->isEnabled() || !m_frame->script()->haveWindowShell())
return;
m_client->windowObjectCleared();
}
Widget* FrameLoader::createJavaAppletWidget(const IntSize& size, Element* element, const HashMap<String, String>& args)
{
String baseURLString;
Vector<String> paramNames;
Vector<String> paramValues;
HashMap<String, String>::const_iterator end = args.end();
for (HashMap<String, String>::const_iterator it = args.begin(); it != end; ++it) {
if (equalIgnoringCase(it->first, "baseurl"))
baseURLString = it->second;
paramNames.append(it->first);
paramValues.append(it->second);
}
if (baseURLString.isEmpty())
baseURLString = m_frame->document()->baseURL().string();
KURL baseURL = completeURL(baseURLString);
Widget* widget = m_client->createJavaAppletWidget(size, element, baseURL, paramNames, paramValues);
if (widget)
m_containsPlugIns = true;
return widget;
}
void FrameLoader::didChangeTitle(DocumentLoader* loader)
{
m_client->didChangeTitle(loader);
if (loader->isCommitted()) {
if (m_currentHistoryItem)
m_currentHistoryItem->setTitle(loader->title());
m_client->setTitle(loader->title(), loader->urlForHistory());
m_client->setMainFrameDocumentReady(true); m_client->dispatchDidReceiveTitle(loader->title());
}
}
void FrameLoader::registerURLSchemeAsLocal(const String& scheme)
{
localSchemes().add(scheme);
}
bool FrameLoader::shouldTreatURLAsLocal(const String& url)
{
if (url.length() >= 5) {
const UChar* s = url.characters();
if (s[0] == 'h' && s[1] == 't' && s[2] == 't' && s[3] == 'p' && s[4] == ':')
return false;
if (s[0] == 'f' && s[1] == 'i' && s[2] == 'l' && s[3] == 'e' && s[4] == ':')
return true;
}
int loc = url.find(':');
if (loc == -1)
return false;
String scheme = url.left(loc);
return localSchemes().contains(scheme);
}
bool FrameLoader::shouldTreatSchemeAsLocal(const String& scheme)
{
if (scheme.length() == 4) {
const UChar* s = scheme.characters();
if (s[0] == 'h' && s[1] == 't' && s[2] == 't' && s[3] == 'p')
return false;
if (s[0] == 'f' && s[1] == 'i' && s[2] == 'l' && s[3] == 'e')
return true;
}
if (scheme.isEmpty())
return false;
return localSchemes().contains(scheme);
}
void FrameLoader::dispatchDidCommitLoad()
{
if (m_creatingInitialEmptyDocument)
return;
#ifndef NDEBUG
m_didDispatchDidCommitLoad = true;
#endif
m_client->dispatchDidCommitLoad();
}
void FrameLoader::dispatchAssignIdentifierToInitialRequest(unsigned long identifier, DocumentLoader* loader, const ResourceRequest& request)
{
m_client->assignIdentifierToInitialRequest(identifier, loader, request);
}
void FrameLoader::dispatchWillSendRequest(DocumentLoader* loader, unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse)
{
if (!request.isNull() && request.url().protocolIs(cMobileQuickLookProtocol))
return;
StringImpl* oldRequestURL = request.url().string().impl();
m_documentLoader->didTellClientAboutLoad(request.url());
m_client->dispatchWillSendRequest(loader, identifier, request, redirectResponse);
if (!request.isNull() && oldRequestURL != request.url().string().impl())
m_documentLoader->didTellClientAboutLoad(request.url());
}
void FrameLoader::dispatchDidReceiveResponse(DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r)
{
m_client->dispatchDidReceiveResponse(loader, identifier, r);
}
void FrameLoader::dispatchDidReceiveContentLength(DocumentLoader* loader, unsigned long identifier, int length)
{
m_client->dispatchDidReceiveContentLength(loader, identifier, length);
}
void FrameLoader::dispatchDidFinishLoading(DocumentLoader* loader, unsigned long identifier)
{
m_client->dispatchDidFinishLoading(loader, identifier);
}
void FrameLoader::tellClientAboutPastMemoryCacheLoads()
{
ASSERT(m_frame->page());
ASSERT(m_frame->page()->areMemoryCacheClientCallsEnabled());
if (!m_documentLoader)
return;
Vector<String> pastLoads;
m_documentLoader->takeMemoryCacheLoadsForClientNotification(pastLoads);
size_t size = pastLoads.size();
for (size_t i = 0; i < size; ++i) {
CachedResource* resource = cache()->resourceForURL(pastLoads[i]);
if (!resource)
continue;
ResourceRequest request(resource->url());
m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize());
}
}
#if USE(LOW_BANDWIDTH_DISPLAY)
bool FrameLoader::addLowBandwidthDisplayRequest(CachedResource* cache)
{
if (m_frame->document()->inLowBandwidthDisplay() == false)
return false;
if (cache->isLoaded())
return false;
switch (cache->type()) {
case CachedResource::CSSStyleSheet:
case CachedResource::Script:
m_needToSwitchOutLowBandwidthDisplay = true;
m_externalRequestsInLowBandwidthDisplay.add(cache);
cache->addClient(this);
return true;
case CachedResource::ImageResource:
case CachedResource::FontResource:
#if ENABLE(XSLT)
case CachedResource::XSLStyleSheet:
#endif
#if ENABLE(XBL)
case CachedResource::XBLStyleSheet:
#endif
return false;
}
ASSERT_NOT_REACHED();
return false;
}
void FrameLoader::removeAllLowBandwidthDisplayRequests()
{
HashSet<CachedResource*>::iterator end = m_externalRequestsInLowBandwidthDisplay.end();
for (HashSet<CachedResource*>::iterator it = m_externalRequestsInLowBandwidthDisplay.begin(); it != end; ++it)
(*it)->removeClient(this);
m_externalRequestsInLowBandwidthDisplay.clear();
}
void FrameLoader::notifyFinished(CachedResource* script)
{
HashSet<CachedResource*>::iterator it = m_externalRequestsInLowBandwidthDisplay.find(script);
if (it != m_externalRequestsInLowBandwidthDisplay.end()) {
(*it)->removeClient(this);
m_externalRequestsInLowBandwidthDisplay.remove(it);
switchOutLowBandwidthDisplayIfReady();
}
}
void FrameLoader::switchOutLowBandwidthDisplayIfReady()
{
RefPtr<Document> oldDoc = m_frame->document();
if (oldDoc->inLowBandwidthDisplay()) {
if (!m_needToSwitchOutLowBandwidthDisplay) {
oldDoc->setLowBandwidthDisplay(false);
removeAllLowBandwidthDisplayRequests();
m_pendingSourceInLowBandwidthDisplay = String();
m_finishedParsingDuringLowBandwidthDisplay = false;
return;
} else if (m_externalRequestsInLowBandwidthDisplay.isEmpty() ||
m_pendingSourceInLowBandwidthDisplay.length() > cMaxPendingSourceLengthInLowBandwidthDisplay) {
oldDoc->setLowBandwidthDisplay(false);
oldDoc->cancelParsing();
oldDoc->detach();
if (m_frame->script()->isEnabled())
m_frame->script()->clearWindowShell();
if (m_frame->view())
m_frame->view()->clear();
RefPtr<Document> newDoc = DOMImplementation::createDocument(m_responseMIMEType, m_frame, m_frame->inViewSourceMode());
m_frame->setDocument(newDoc);
newDoc->setURL(m_URL);
if (m_decoder)
newDoc->setDecoder(m_decoder.get());
restoreDocumentState();
dispatchWindowObjectAvailable();
newDoc->implicitOpen();
DocLoader* docLoader = newDoc->docLoader();
newDoc->setDocLoader(oldDoc->docLoader());
newDoc->docLoader()->replaceDocument(newDoc.get());
docLoader->replaceDocument(oldDoc.get());
oldDoc->setDocLoader(docLoader);
oldDoc = 0;
if (m_pendingSourceInLowBandwidthDisplay.length()) {
if (m_decoder->encoding().usesVisualOrdering())
newDoc->setVisuallyOrdered();
newDoc->recalcStyle(Node::Force);
newDoc->tokenizer()->write(m_pendingSourceInLowBandwidthDisplay, true);
if (m_finishedParsingDuringLowBandwidthDisplay)
newDoc->finishParsing();
}
newDoc->updateRendering();
removeAllLowBandwidthDisplayRequests();
m_pendingSourceInLowBandwidthDisplay = String();
m_finishedParsingDuringLowBandwidthDisplay = false;
m_needToSwitchOutLowBandwidthDisplay = false;
}
}
}
#endif
}