initial import
[vuplus_webkit] / Source / WebCore / loader / FrameLoader.cpp
1 /*
2  * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
4  * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
5  * Copyright (C) 2008 Alp Toker <alp@atoker.com>
6  * Copyright (C) Research In Motion Limited 2009. All rights reserved.
7  * Copyright (C) 2011 Kris Jordan <krisjordan@gmail.com>
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1.  Redistributions of source code must retain the above copyright
14  *     notice, this list of conditions and the following disclaimer. 
15  * 2.  Redistributions in binary form must reproduce the above copyright
16  *     notice, this list of conditions and the following disclaimer in the
17  *     documentation and/or other materials provided with the distribution. 
18  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
19  *     its contributors may be used to endorse or promote products derived
20  *     from this software without specific prior written permission. 
21  *
22  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
23  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
24  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
26  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
27  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
29  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include "config.h"
35 #include "FrameLoader.h"
36
37 #include "ApplicationCacheHost.h"
38 #include "BackForwardController.h"
39 #include "BeforeUnloadEvent.h"
40 #include "MemoryCache.h"
41 #include "CachedPage.h"
42 #include "CachedResourceLoader.h"
43 #include "Chrome.h"
44 #include "ChromeClient.h"
45 #include "Console.h"
46 #include "ContentSecurityPolicy.h"
47 #include "DOMImplementation.h"
48 #include "DOMWindow.h"
49 #include "Document.h"
50 #include "DocumentLoadTiming.h"
51 #include "DocumentLoader.h"
52 #include "Editor.h"
53 #include "EditorClient.h"
54 #include "Element.h"
55 #include "Event.h"
56 #include "EventNames.h"
57 #include "FloatRect.h"
58 #include "FormState.h"
59 #include "FormSubmission.h"
60 #include "Frame.h"
61 #include "FrameLoadRequest.h"
62 #include "FrameLoaderClient.h"
63 #include "FrameNetworkingContext.h"
64 #include "FrameTree.h"
65 #include "FrameView.h"
66 #include "HTMLAnchorElement.h"
67 #include "HTMLFormElement.h"
68 #include "HTMLNames.h"
69 #include "HTMLObjectElement.h"
70 #include "HTTPParsers.h"
71 #include "HistoryItem.h"
72 #include "InspectorController.h"
73 #include "InspectorInstrumentation.h"
74 #include "Logging.h"
75 #include "MIMETypeRegistry.h"
76 #include "MainResourceLoader.h"
77 #include "Page.h"
78 #include "PageCache.h"
79 #include "PageGroup.h"
80 #include "PageTransitionEvent.h"
81 #include "PluginData.h"
82 #include "PluginDatabase.h"
83 #include "PluginDocument.h"
84 #include "ProgressTracker.h"
85 #include "ResourceHandle.h"
86 #include "ResourceRequest.h"
87 #include "SchemeRegistry.h"
88 #include "ScrollAnimator.h"
89 #include "ScriptController.h"
90 #include "ScriptSourceCode.h"
91 #include "SecurityOrigin.h"
92 #include "SegmentedString.h"
93 #include "SerializedScriptValue.h"
94 #include "Settings.h"
95 #include "TextResourceDecoder.h"
96 #include "WindowFeatures.h"
97 #include "XMLDocumentParser.h"
98 #include <wtf/CurrentTime.h>
99 #include <wtf/StdLibExtras.h>
100 #include <wtf/text/CString.h>
101 #include <wtf/text/WTFString.h>
102
103 #if ENABLE(INPUT_COLOR)
104 #include "ColorChooser.h"
105 #include "ColorInputType.h"
106 #endif
107
108 #if ENABLE(SHARED_WORKERS)
109 #include "SharedWorkerRepository.h"
110 #endif
111
112 #if ENABLE(SVG)
113 #include "SVGDocument.h"
114 #include "SVGLocatable.h"
115 #include "SVGNames.h"
116 #include "SVGPreserveAspectRatio.h"
117 #include "SVGSVGElement.h"
118 #include "SVGViewElement.h"
119 #include "SVGViewSpec.h"
120 #endif
121
122 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
123 #include "Archive.h"
124 #include "ArchiveFactory.h"
125 #endif
126
127 namespace WebCore {
128
129 using namespace HTMLNames;
130
131 #if ENABLE(SVG)
132 using namespace SVGNames;
133 #endif
134
135 #if ENABLE(XHTMLMP)
136 static const char defaultAcceptHeader[] = "application/vnd.wap.xhtml+xml,application/xhtml+xml;profile='http://www.wapforum.org/xhtml',text/html,application/xml;q=0.9,*/*;q=0.8";
137 #else
138 static const char defaultAcceptHeader[] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
139 #endif
140
141 static double storedTimeOfLastCompletedLoad;
142
143 bool isBackForwardLoadType(FrameLoadType type)
144 {
145     switch (type) {
146         case FrameLoadTypeStandard:
147         case FrameLoadTypeReload:
148         case FrameLoadTypeReloadFromOrigin:
149         case FrameLoadTypeSame:
150         case FrameLoadTypeRedirectWithLockedBackForwardList:
151         case FrameLoadTypeReplace:
152             return false;
153         case FrameLoadTypeBack:
154         case FrameLoadTypeForward:
155         case FrameLoadTypeIndexedBackForward:
156             return true;
157     }
158     ASSERT_NOT_REACHED();
159     return false;
160 }
161
162 // This is not in the FrameLoader class to emphasize that it does not depend on
163 // private FrameLoader data, and to avoid increasing the number of public functions
164 // with access to private data.  Since only this .cpp file needs it, making it
165 // non-member lets us exclude it from the header file, thus keeping FrameLoader.h's
166 // API simpler.
167 //
168 // FIXME: isDocumentSandboxed should eventually replace isSandboxed.
169 static bool isDocumentSandboxed(Frame* frame, SandboxFlags mask)
170 {
171     return frame->document() && frame->document()->securityOrigin()->isSandboxed(mask);
172 }
173
174 FrameLoader::FrameLoader(Frame* frame, FrameLoaderClient* client)
175     : m_frame(frame)
176     , m_client(client)
177     , m_policyChecker(frame)
178     , m_history(frame)
179     , m_notifer(frame)
180     , m_subframeLoader(frame)
181     , m_icon(frame)
182     , m_state(FrameStateCommittedPage)
183     , m_loadType(FrameLoadTypeStandard)
184     , m_delegateIsHandlingProvisionalLoadError(false)
185     , m_quickRedirectComing(false)
186     , m_sentRedirectNotification(false)
187     , m_inStopAllLoaders(false)
188     , m_isExecutingJavaScriptFormAction(false)
189     , m_didCallImplicitClose(false)
190     , m_wasUnloadEventEmitted(false)
191     , m_pageDismissalEventBeingDispatched(NoDismissal)
192     , m_isComplete(false)
193     , m_isLoadingMainResource(false)
194     , m_hasReceivedFirstData(false)
195     , m_needsClear(false)
196     , m_checkTimer(this, &FrameLoader::checkTimerFired)
197     , m_shouldCallCheckCompleted(false)
198     , m_shouldCallCheckLoadComplete(false)
199     , m_opener(0)
200     , m_didPerformFirstNavigation(false)
201     , m_loadingFromCachedPage(false)
202     , m_suppressOpenerInNewFrame(false)
203     , m_sandboxFlags(SandboxAll)
204     , m_forcedSandboxFlags(SandboxNone)
205 {
206 }
207
208 FrameLoader::~FrameLoader()
209 {
210     setOpener(0);
211
212     HashSet<Frame*>::iterator end = m_openedFrames.end();
213     for (HashSet<Frame*>::iterator it = m_openedFrames.begin(); it != end; ++it)
214         (*it)->loader()->m_opener = 0;
215
216     m_client->frameLoaderDestroyed();
217
218     if (m_networkingContext)
219         m_networkingContext->invalidate();
220 }
221
222 void FrameLoader::init()
223 {
224     // Propagate sandbox attributes to this Frameloader and its descendants.
225     // This needs to be done early, so that an initial document gets correct sandbox flags in its SecurityOrigin.
226     updateSandboxFlags();
227
228     // This somewhat odd set of steps gives the frame an initial empty document.
229     // It would be better if this could be done with even fewer steps.
230     m_stateMachine.advanceTo(FrameLoaderStateMachine::CreatingInitialEmptyDocument);
231     setPolicyDocumentLoader(m_client->createDocumentLoader(ResourceRequest(KURL(ParsedURLString, "")), SubstituteData()).get());
232     setProvisionalDocumentLoader(m_policyDocumentLoader.get());
233     setState(FrameStateProvisional);
234     m_provisionalDocumentLoader->setResponse(ResourceResponse(KURL(), "text/html", 0, String(), String()));
235     m_provisionalDocumentLoader->finishedLoading();
236     ASSERT(!m_frame->document());
237     m_documentLoader->writer()->begin(KURL(), false);
238     m_documentLoader->writer()->end();
239     m_frame->document()->cancelParsing();
240     m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
241     m_didCallImplicitClose = true;
242
243     m_networkingContext = m_client->createNetworkingContext();
244 }
245
246 void FrameLoader::setDefersLoading(bool defers)
247 {
248     if (m_documentLoader)
249         m_documentLoader->setDefersLoading(defers);
250     if (m_provisionalDocumentLoader)
251         m_provisionalDocumentLoader->setDefersLoading(defers);
252     if (m_policyDocumentLoader)
253         m_policyDocumentLoader->setDefersLoading(defers);
254     history()->setDefersLoading(defers);
255
256     if (!defers) {
257         m_frame->navigationScheduler()->startTimer();
258         startCheckCompleteTimer();
259     }
260 }
261
262 void FrameLoader::changeLocation(SecurityOrigin* securityOrigin, const KURL& url, const String& referrer, bool lockHistory, bool lockBackForwardList, bool refresh)
263 {
264     RefPtr<Frame> protect(m_frame);
265     urlSelected(FrameLoadRequest(securityOrigin, ResourceRequest(url, referrer, refresh ? ReloadIgnoringCacheData : UseProtocolCachePolicy), "_self"),
266         0, lockHistory, lockBackForwardList, SendReferrer, ReplaceDocumentIfJavaScriptURL);
267 }
268
269 void FrameLoader::urlSelected(const KURL& url, const String& passedTarget, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, ReferrerPolicy referrerPolicy)
270 {
271     urlSelected(FrameLoadRequest(m_frame->document()->securityOrigin(), ResourceRequest(url), passedTarget),
272         triggeringEvent, lockHistory, lockBackForwardList, referrerPolicy, DoNotReplaceDocumentIfJavaScriptURL);
273 }
274
275 // The shouldReplaceDocumentIfJavaScriptURL parameter will go away when the FIXME to eliminate the
276 // corresponding parameter from ScriptController::executeIfJavaScriptURL() is addressed.
277 void FrameLoader::urlSelected(const FrameLoadRequest& passedRequest, PassRefPtr<Event> triggeringEvent, bool lockHistory, bool lockBackForwardList, ReferrerPolicy referrerPolicy, ShouldReplaceDocumentIfJavaScriptURL shouldReplaceDocumentIfJavaScriptURL)
278 {
279     ASSERT(!m_suppressOpenerInNewFrame);
280
281     FrameLoadRequest frameRequest(passedRequest);
282
283     if (m_frame->script()->executeIfJavaScriptURL(frameRequest.resourceRequest().url(), shouldReplaceDocumentIfJavaScriptURL))
284         return;
285
286     if (frameRequest.frameName().isEmpty())
287         frameRequest.setFrameName(m_frame->document()->baseTarget());
288
289     if (referrerPolicy == NoReferrer)
290         m_suppressOpenerInNewFrame = true;
291     if (frameRequest.resourceRequest().httpReferrer().isEmpty())
292         frameRequest.resourceRequest().setHTTPReferrer(m_outgoingReferrer);
293     addHTTPOriginIfNeeded(frameRequest.resourceRequest(), outgoingOrigin());
294
295     loadFrameRequest(frameRequest, lockHistory, lockBackForwardList, triggeringEvent, 0, referrerPolicy);
296
297     m_suppressOpenerInNewFrame = false;
298 }
299
300 void FrameLoader::submitForm(PassRefPtr<FormSubmission> submission)
301 {
302     ASSERT(submission->method() == FormSubmission::PostMethod || submission->method() == FormSubmission::GetMethod);
303
304     // FIXME: Find a good spot for these.
305     ASSERT(submission->data());
306     ASSERT(submission->state());
307     ASSERT(submission->state()->sourceFrame() == m_frame);
308     
309     if (!m_frame->page())
310         return;
311     
312     if (submission->action().isEmpty())
313         return;
314
315     if (isDocumentSandboxed(m_frame, SandboxForms))
316         return;
317
318     if (protocolIsJavaScript(submission->action())) {
319         m_isExecutingJavaScriptFormAction = true;
320         m_frame->script()->executeIfJavaScriptURL(submission->action(), DoNotReplaceDocumentIfJavaScriptURL);
321         m_isExecutingJavaScriptFormAction = false;
322         return;
323     }
324
325     Frame* targetFrame = m_frame->tree()->find(submission->target());
326     if (!shouldAllowNavigation(targetFrame))
327         return;
328     if (!targetFrame) {
329         if (!DOMWindow::allowPopUp(m_frame) && !ScriptController::processingUserGesture())
330             return;
331
332         targetFrame = m_frame;
333     } else
334         submission->clearTarget();
335
336     if (!targetFrame->page())
337         return;
338
339     // FIXME: We'd like to remove this altogether and fix the multiple form submission issue another way.
340
341     // We do not want to submit more than one form from the same page, nor do we want to submit a single
342     // form more than once. This flag prevents these from happening; not sure how other browsers prevent this.
343     // The flag is reset in each time we start handle a new mouse or key down event, and
344     // also in setView since this part may get reused for a page from the back/forward cache.
345     // The form multi-submit logic here is only needed when we are submitting a form that affects this frame.
346
347     // FIXME: Frame targeting is only one of the ways the submission could end up doing something other
348     // than replacing this frame's content, so this check is flawed. On the other hand, the check is hardly
349     // needed any more now that we reset m_submittedFormURL on each mouse or key down event.
350
351     if (m_frame->tree()->isDescendantOf(targetFrame)) {
352         if (m_submittedFormURL == submission->action())
353             return;
354         m_submittedFormURL = submission->action();
355     }
356
357     submission->data()->generateFiles(m_frame->document());
358     submission->setReferrer(m_outgoingReferrer);
359     submission->setOrigin(outgoingOrigin());
360
361     targetFrame->navigationScheduler()->scheduleFormSubmission(submission);
362 }
363
364 void FrameLoader::stopLoading(UnloadEventPolicy unloadEventPolicy)
365 {
366     if (m_frame->document() && m_frame->document()->parser())
367         m_frame->document()->parser()->stopParsing();
368
369     if (unloadEventPolicy != UnloadEventPolicyNone) {
370         if (m_frame->document()) {
371             if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
372                 Node* currentFocusedNode = m_frame->document()->focusedNode();
373                 if (currentFocusedNode)
374                     currentFocusedNode->aboutToUnload();
375                 if (m_frame->domWindow() && m_pageDismissalEventBeingDispatched == NoDismissal) {
376                     if (unloadEventPolicy == UnloadEventPolicyUnloadAndPageHide) {
377                         m_pageDismissalEventBeingDispatched = PageHideDismissal;
378                         m_frame->domWindow()->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, m_frame->document()->inPageCache()), m_frame->document());
379                     }
380                     if (!m_frame->document()->inPageCache()) {
381                         RefPtr<Event> unloadEvent(Event::create(eventNames().unloadEvent, false, false));
382                         // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
383                         // while dispatching the event, so protect it to prevent writing the end
384                         // time into freed memory.
385                         RefPtr<DocumentLoader> documentLoader = m_provisionalDocumentLoader;
386                         m_pageDismissalEventBeingDispatched = UnloadDismissal;
387                         if (documentLoader && !documentLoader->timing()->unloadEventStart && !documentLoader->timing()->unloadEventEnd) {
388                             DocumentLoadTiming* timing = documentLoader->timing();
389                             ASSERT(timing->navigationStart);
390                             m_frame->domWindow()->dispatchTimedEvent(unloadEvent, m_frame->domWindow()->document(), &timing->unloadEventStart, &timing->unloadEventEnd);
391                         } else
392                             m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->domWindow()->document());
393                     }
394                 }
395                 m_pageDismissalEventBeingDispatched = NoDismissal;
396                 if (m_frame->document())
397                     m_frame->document()->updateStyleIfNeeded();
398                 m_wasUnloadEventEmitted = true;
399             }
400         }
401
402         // Dispatching the unload event could have made m_frame->document() null.
403         if (m_frame->document() && !m_frame->document()->inPageCache()) {
404             // Don't remove event listeners from a transitional empty document (see bug 28716 for more information).
405             bool keepEventListeners = m_stateMachine.isDisplayingInitialEmptyDocument() && m_provisionalDocumentLoader
406                 && m_frame->document()->securityOrigin()->isSecureTransitionTo(m_provisionalDocumentLoader->url());
407
408             if (!keepEventListeners)
409                 m_frame->document()->removeAllEventListeners();
410         }
411     }
412
413     m_isComplete = true; // to avoid calling completed() in finishedParsing()
414     m_isLoadingMainResource = false;
415     m_didCallImplicitClose = true; // don't want that one either
416
417     if (m_frame->document() && m_frame->document()->parsing()) {
418         finishedParsing();
419         m_frame->document()->setParsing(false);
420     }
421
422     m_hasReceivedFirstData = true;
423
424     if (Document* doc = m_frame->document()) {
425         // FIXME: HTML5 doesn't tell us to set the state to complete when aborting, but we do anyway to match legacy behavior.
426         // http://www.w3.org/Bugs/Public/show_bug.cgi?id=10537
427         doc->setReadyState(Document::Complete);
428
429 #if ENABLE(DATABASE)
430         doc->stopDatabases(0);
431 #endif
432     }
433
434     // FIXME: This will cancel redirection timer, which really needs to be restarted when restoring the frame from b/f cache.
435     m_frame->navigationScheduler()->cancel();
436 }
437
438 void FrameLoader::stop()
439 {
440     // http://bugs.webkit.org/show_bug.cgi?id=10854
441     // The frame's last ref may be removed and it will be deleted by checkCompleted().
442     RefPtr<Frame> protector(m_frame);
443
444     if (DocumentParser* parser = m_frame->document()->parser()) {
445         parser->stopParsing();
446         parser->finish();
447     }
448     
449     icon()->stopLoader();
450 }
451
452 bool FrameLoader::closeURL()
453 {
454     history()->saveDocumentState();
455     
456     // Should only send the pagehide event here if the current document exists and has not been placed in the page cache.    
457     Document* currentDocument = m_frame->document();
458     stopLoading(currentDocument && !currentDocument->inPageCache() ? UnloadEventPolicyUnloadAndPageHide : UnloadEventPolicyUnloadOnly);
459     
460     m_frame->editor()->clearUndoRedoOperations();
461     return true;
462 }
463
464 bool FrameLoader::didOpenURL()
465 {
466     if (m_frame->navigationScheduler()->redirectScheduledDuringLoad()) {
467         // A redirect was scheduled before the document was created.
468         // This can happen when one frame changes another frame's location.
469         return false;
470     }
471
472     m_frame->navigationScheduler()->cancel();
473     m_frame->editor()->clearLastEditCommand();
474
475     m_isComplete = false;
476     m_isLoadingMainResource = true;
477     m_didCallImplicitClose = false;
478
479     // If we are still in the process of initializing an empty document then
480     // its frame is not in a consistent state for rendering, so avoid setJSStatusBarText
481     // since it may cause clients to attempt to render the frame.
482     if (!m_stateMachine.creatingInitialEmptyDocument()) {
483         if (DOMWindow* window = m_frame->existingDOMWindow()) {
484             window->setStatus(String());
485             window->setDefaultStatus(String());
486         }
487     }
488     m_hasReceivedFirstData = false;
489
490     started();
491
492     return true;
493 }
494
495 void FrameLoader::didExplicitOpen()
496 {
497     m_isComplete = false;
498     m_didCallImplicitClose = false;
499
500     // Calling document.open counts as committing the first real document load.
501     if (!m_stateMachine.committedFirstRealDocumentLoad())
502         m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
503     
504     // Prevent window.open(url) -- eg window.open("about:blank") -- from blowing away results
505     // from a subsequent window.document.open / window.document.write call. 
506     // Canceling redirection here works for all cases because document.open 
507     // implicitly precedes document.write.
508     m_frame->navigationScheduler()->cancel();
509 }
510
511
512 void FrameLoader::cancelAndClear()
513 {
514     m_frame->navigationScheduler()->cancel();
515
516     if (!m_isComplete)
517         closeURL();
518
519     clear(false);
520     m_frame->script()->updatePlatformScriptObjects();
521 }
522
523 void FrameLoader::clear(bool clearWindowProperties, bool clearScriptObjects, bool clearFrameView)
524 {
525     m_frame->editor()->clear();
526
527     if (!m_needsClear)
528         return;
529     m_needsClear = false;
530     
531     if (!m_frame->document()->inPageCache()) {
532         m_frame->document()->cancelParsing();
533         m_frame->document()->stopActiveDOMObjects();
534         if (m_frame->document()->attached()) {
535             m_frame->document()->willRemove();
536             m_frame->document()->detach();
537             
538             m_frame->document()->removeFocusedNodeOfSubtree(m_frame->document());
539         }
540     }
541
542     // Do this after detaching the document so that the unload event works.
543     if (clearWindowProperties) {
544         m_frame->clearDOMWindow();
545         m_frame->script()->clearWindowShell(m_frame->document()->inPageCache());
546     }
547
548     m_frame->selection()->clear();
549     m_frame->eventHandler()->clear();
550     if (clearFrameView && m_frame->view())
551         m_frame->view()->clear();
552
553     // Do not drop the document before the ScriptController and view are cleared
554     // as some destructors might still try to access the document.
555     m_frame->setDocument(0);
556
557     m_subframeLoader.clear();
558
559     if (clearScriptObjects)
560         m_frame->script()->clearScriptObjects();
561
562     m_frame->navigationScheduler()->clear();
563
564     m_checkTimer.stop();
565     m_shouldCallCheckCompleted = false;
566     m_shouldCallCheckLoadComplete = false;
567
568     if (m_stateMachine.isDisplayingInitialEmptyDocument() && m_stateMachine.committedFirstRealDocumentLoad())
569         m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
570 }
571
572 void FrameLoader::receivedFirstData()
573 {
574     KURL workingURL = activeDocumentLoader()->documentURL();
575 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
576     // FIXME: The document loader, not the frame loader, should be in charge of loading web archives.
577     // Once this is done, we can just make DocumentLoader::documentURL() return the right URL
578     // based on whether it has a non-null archive or not.
579     if (m_archive && activeDocumentLoader()->parsedArchiveData())
580         workingURL = m_archive->mainResource()->url();
581 #endif
582
583     activeDocumentLoader()->writer()->begin(workingURL, false);
584     activeDocumentLoader()->writer()->setDocumentWasLoadedAsPartOfNavigation();
585
586     dispatchDidCommitLoad();
587     dispatchDidClearWindowObjectsInAllWorlds();
588     
589     if (m_documentLoader) {
590         StringWithDirection ptitle = m_documentLoader->title();
591         // If we have a title let the WebView know about it.
592         if (!ptitle.isNull())
593             m_client->dispatchDidReceiveTitle(ptitle);
594     }
595
596     m_hasReceivedFirstData = true;
597
598     if (!m_documentLoader)
599         return;
600     if (m_frame->document()->isViewSource())
601         return;
602
603     double delay;
604     String url;
605     if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField("Refresh"), false, delay, url))
606         return;
607     if (url.isEmpty())
608         url = m_frame->document()->url().string();
609     else
610         url = m_frame->document()->completeURL(url).string();
611
612     m_frame->navigationScheduler()->scheduleRedirect(delay, url);
613 }
614
615 void FrameLoader::setOutgoingReferrer(const KURL& url)
616 {
617     m_outgoingReferrer = url.strippedForUseAsReferrer();
618 }
619
620 void FrameLoader::didBeginDocument(bool dispatch)
621 {
622     m_needsClear = true;
623     m_isComplete = false;
624     m_didCallImplicitClose = false;
625     m_isLoadingMainResource = true;
626     m_frame->document()->setReadyState(Document::Loading);
627
628     if (m_pendingStateObject) {
629         m_frame->document()->statePopped(m_pendingStateObject.get());
630         m_pendingStateObject.clear();
631     }
632
633     if (dispatch)
634         dispatchDidClearWindowObjectsInAllWorlds();
635
636     updateFirstPartyForCookies();
637
638     Settings* settings = m_frame->document()->settings();
639     m_frame->document()->cachedResourceLoader()->setAutoLoadImages(settings && settings->loadsImagesAutomatically());
640
641     if (m_documentLoader) {
642         String dnsPrefetchControl = m_documentLoader->response().httpHeaderField("X-DNS-Prefetch-Control");
643         if (!dnsPrefetchControl.isEmpty())
644             m_frame->document()->parseDNSPrefetchControlHeader(dnsPrefetchControl);
645
646         String contentSecurityPolicy = m_documentLoader->response().httpHeaderField("X-WebKit-CSP");
647         if (!contentSecurityPolicy.isEmpty())
648             m_frame->document()->contentSecurityPolicy()->didReceiveHeader(contentSecurityPolicy, ContentSecurityPolicy::EnforcePolicy);
649
650         String reportOnlyContentSecurityPolicy = m_documentLoader->response().httpHeaderField("X-WebKit-CSP-Report-Only");
651         if (!contentSecurityPolicy.isEmpty())
652             m_frame->document()->contentSecurityPolicy()->didReceiveHeader(reportOnlyContentSecurityPolicy, ContentSecurityPolicy::ReportOnly);
653     }
654
655     history()->restoreDocumentState();
656 }
657
658 void FrameLoader::didEndDocument()
659 {
660     m_isLoadingMainResource = false;
661 }
662
663 void FrameLoader::finishedParsing()
664 {
665     m_frame->injectUserScripts(InjectAtDocumentEnd);
666
667     if (m_stateMachine.creatingInitialEmptyDocument())
668         return;
669
670     // This can be called from the Frame's destructor, in which case we shouldn't protect ourselves
671     // because doing so will cause us to re-enter the destructor when protector goes out of scope.
672     // Null-checking the FrameView indicates whether or not we're in the destructor.
673     RefPtr<Frame> protector = m_frame->view() ? m_frame : 0;
674
675     m_client->dispatchDidFinishDocumentLoad();
676
677     checkCompleted();
678
679     if (!m_frame->view())
680         return; // We are being destroyed by something checkCompleted called.
681
682     // Check if the scrollbars are really needed for the content.
683     // If not, remove them, relayout, and repaint.
684     m_frame->view()->restoreScrollbar();
685     m_frame->view()->scrollToFragment(m_frame->document()->url());
686 }
687
688 void FrameLoader::loadDone()
689 {
690     checkCompleted();
691 }
692
693 bool FrameLoader::allChildrenAreComplete() const
694 {
695     for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
696         if (!child->loader()->m_isComplete)
697             return false;
698     }
699     return true;
700 }
701
702 bool FrameLoader::allAncestorsAreComplete() const
703 {
704     for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree()->parent()) {
705         if (!ancestor->loader()->m_isComplete)
706             return false;
707     }
708     return true;
709 }
710
711 void FrameLoader::checkCompleted()
712 {
713     m_shouldCallCheckCompleted = false;
714
715     if (m_frame->view())
716         m_frame->view()->checkStopDelayingDeferredRepaints();
717
718     // Have we completed before?
719     if (m_isComplete)
720         return;
721
722     // Are we still parsing?
723     if (m_frame->document()->parsing())
724         return;
725
726     // Still waiting for images/scripts?
727     if (m_frame->document()->cachedResourceLoader()->requestCount())
728         return;
729
730     // Still waiting for elements that don't go through a FrameLoader?
731     if (m_frame->document()->isDelayingLoadEvent())
732         return;
733
734     // Any frame that hasn't completed yet?
735     if (!allChildrenAreComplete())
736         return;
737
738     // OK, completed.
739     m_isComplete = true;
740     m_frame->document()->setReadyState(Document::Complete);
741
742     RefPtr<Frame> protect(m_frame);
743     checkCallImplicitClose(); // if we didn't do it before
744
745     m_frame->navigationScheduler()->startTimer();
746
747     completed();
748     if (m_frame->page())
749         checkLoadComplete();
750 }
751
752 void FrameLoader::checkTimerFired(Timer<FrameLoader>*)
753 {
754     if (Page* page = m_frame->page()) {
755         if (page->defersLoading())
756             return;
757     }
758     if (m_shouldCallCheckCompleted)
759         checkCompleted();
760     if (m_shouldCallCheckLoadComplete)
761         checkLoadComplete();
762 }
763
764 void FrameLoader::startCheckCompleteTimer()
765 {
766     if (!(m_shouldCallCheckCompleted || m_shouldCallCheckLoadComplete))
767         return;
768     if (m_checkTimer.isActive())
769         return;
770     m_checkTimer.startOneShot(0);
771 }
772
773 void FrameLoader::scheduleCheckCompleted()
774 {
775     m_shouldCallCheckCompleted = true;
776     startCheckCompleteTimer();
777 }
778
779 void FrameLoader::scheduleCheckLoadComplete()
780 {
781     m_shouldCallCheckLoadComplete = true;
782     startCheckCompleteTimer();
783 }
784
785 void FrameLoader::checkCallImplicitClose()
786 {
787     if (m_didCallImplicitClose || m_frame->document()->parsing() || m_frame->document()->isDelayingLoadEvent())
788         return;
789
790     if (!allChildrenAreComplete())
791         return; // still got a frame running -> too early
792
793     m_didCallImplicitClose = true;
794     m_wasUnloadEventEmitted = false;
795     m_frame->document()->implicitClose();
796 }
797
798 void FrameLoader::loadURLIntoChildFrame(const KURL& url, const String& referer, Frame* childFrame)
799 {
800     ASSERT(childFrame);
801
802 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
803     RefPtr<Archive> subframeArchive = activeDocumentLoader()->popArchiveForSubframe(childFrame->tree()->uniqueName(), url);    
804     if (subframeArchive) {
805         childFrame->loader()->loadArchive(subframeArchive.release());
806         return;
807     }
808 #endif // ENABLE(WEB_ARCHIVE)
809
810     HistoryItem* parentItem = history()->currentItem();
811     // If we're moving in the back/forward list, we might want to replace the content
812     // of this child frame with whatever was there at that point.
813     if (parentItem && parentItem->children().size() && isBackForwardLoadType(loadType()) 
814         && !m_frame->document()->loadEventFinished()) {
815         HistoryItem* childItem = parentItem->childItemWithTarget(childFrame->tree()->uniqueName());
816         if (childItem) {
817             childFrame->loader()->loadDifferentDocumentItem(childItem, loadType());
818             return;
819         }
820     }
821
822     childFrame->loader()->loadURL(url, referer, String(), false, FrameLoadTypeRedirectWithLockedBackForwardList, 0, 0);
823 }
824
825 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
826 void FrameLoader::loadArchive(PassRefPtr<Archive> archive)
827 {
828     m_archive = archive;
829     
830     ArchiveResource* mainResource = m_archive->mainResource();
831     ASSERT(mainResource);
832     if (!mainResource)
833         return;
834         
835     SubstituteData substituteData(mainResource->data(), mainResource->mimeType(), mainResource->textEncoding(), KURL());
836     
837     ResourceRequest request(mainResource->url());
838 #if PLATFORM(MAC)
839     request.applyWebArchiveHackForMail();
840 #endif
841
842     RefPtr<DocumentLoader> documentLoader = m_client->createDocumentLoader(request, substituteData);
843     documentLoader->addAllArchiveResources(m_archive.get());
844     load(documentLoader.get());
845 }
846 #endif // ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
847
848 ObjectContentType FrameLoader::defaultObjectContentType(const KURL& url, const String& mimeTypeIn, bool shouldPreferPlugInsForImages)
849 {
850     String mimeType = mimeTypeIn;
851     String extension = url.path().substring(url.path().reverseFind('.') + 1);
852
853     // We don't use MIMETypeRegistry::getMIMETypeForPath() because it returns "application/octet-stream" upon failure
854     if (mimeType.isEmpty())
855         mimeType = MIMETypeRegistry::getMIMETypeForExtension(extension);
856
857 #if !PLATFORM(MAC) && !PLATFORM(CHROMIUM) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does Chromium or EFL
858     if (mimeType.isEmpty())
859         mimeType = PluginDatabase::installedPlugins()->MIMETypeForExtension(extension);
860 #endif
861
862     if (mimeType.isEmpty())
863         return ObjectContentFrame; // Go ahead and hope that we can display the content.
864
865 #if !PLATFORM(MAC) && !PLATFORM(CHROMIUM) && !PLATFORM(EFL) // Mac has no PluginDatabase, nor does Chromium or EFL
866     bool plugInSupportsMIMEType = PluginDatabase::installedPlugins()->isMIMETypeRegistered(mimeType);
867 #else
868     bool plugInSupportsMIMEType = false;
869 #endif
870
871     if (MIMETypeRegistry::isSupportedImageMIMEType(mimeType))
872         return shouldPreferPlugInsForImages && plugInSupportsMIMEType ? WebCore::ObjectContentNetscapePlugin : WebCore::ObjectContentImage;
873
874     if (plugInSupportsMIMEType)
875         return WebCore::ObjectContentNetscapePlugin;
876
877     if (MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType))
878         return WebCore::ObjectContentFrame;
879
880     return WebCore::ObjectContentNone;
881 }
882
883 String FrameLoader::outgoingReferrer() const
884 {
885     return m_outgoingReferrer;
886 }
887
888 String FrameLoader::outgoingOrigin() const
889 {
890     return m_frame->document()->securityOrigin()->toString();
891 }
892
893 bool FrameLoader::isMixedContent(SecurityOrigin* context, const KURL& url)
894 {
895     if (context->protocol() != "https")
896         return false;  // We only care about HTTPS security origins.
897
898     if (!url.isValid() || SchemeRegistry::shouldTreatURLSchemeAsSecure(url.protocol()))
899         return false;  // Loading these protocols is secure.
900
901     return true;
902 }
903
904 bool FrameLoader::checkIfDisplayInsecureContent(SecurityOrigin* context, const KURL& url)
905 {
906     if (!isMixedContent(context, url))
907         return true;
908
909     Settings* settings = m_frame->settings();
910     bool allowed = m_client->allowDisplayingInsecureContent(settings && settings->allowDisplayOfInsecureContent(), context, url);
911     String message = (allowed ? emptyString() : "[blocked] ") + "The page at " +
912         m_frame->document()->url().string() + " displayed insecure content from " + url.string() + ".\n";
913         
914     m_frame->domWindow()->console()->addMessage(HTMLMessageSource, LogMessageType, WarningMessageLevel, message, 1, String());
915
916     if (allowed)
917         m_client->didDisplayInsecureContent();
918
919     return allowed;
920 }
921
922 bool FrameLoader::checkIfRunInsecureContent(SecurityOrigin* context, const KURL& url)
923 {
924     if (!isMixedContent(context, url))
925         return true;
926
927     Settings* settings = m_frame->settings();
928     bool allowed = m_client->allowRunningInsecureContent(settings && settings->allowRunningOfInsecureContent(), context, url);
929     String message = (allowed ? emptyString() : "[blocked] ") + "The page at " +
930         m_frame->document()->url().string() + " ran insecure content from " + url.string() + ".\n";
931        
932     m_frame->domWindow()->console()->addMessage(HTMLMessageSource, LogMessageType, WarningMessageLevel, message, 1, String());
933
934     if (allowed)
935         m_client->didRunInsecureContent(context, url);
936
937     return allowed;
938 }
939
940 Frame* FrameLoader::opener()
941 {
942     return m_opener;
943 }
944
945 void FrameLoader::setOpener(Frame* opener)
946 {
947     if (m_opener)
948         m_opener->loader()->m_openedFrames.remove(m_frame);
949     if (opener)
950         opener->loader()->m_openedFrames.add(m_frame);
951     m_opener = opener;
952
953     if (m_frame->document()) {
954         m_frame->document()->initSecurityContext();
955         m_frame->domWindow()->setSecurityOrigin(m_frame->document()->securityOrigin());
956     }
957 }
958
959 // FIXME: This does not belong in FrameLoader!
960 void FrameLoader::handleFallbackContent()
961 {
962     HTMLFrameOwnerElement* owner = m_frame->ownerElement();
963     if (!owner || !owner->hasTagName(objectTag))
964         return;
965     static_cast<HTMLObjectElement*>(owner)->renderFallbackContent();
966 }
967
968 void FrameLoader::provisionalLoadStarted()
969 {
970     if (m_stateMachine.firstLayoutDone())
971         m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
972     m_frame->navigationScheduler()->cancel(true);
973     m_client->provisionalLoadStarted();
974 }
975
976 void FrameLoader::resetMultipleFormSubmissionProtection()
977 {
978     m_submittedFormURL = KURL();
979 }
980
981 void FrameLoader::willSetEncoding()
982 {
983     if (!m_hasReceivedFirstData)
984         receivedFirstData();
985 }
986
987 void FrameLoader::updateFirstPartyForCookies()
988 {
989     if (m_frame->tree()->parent())
990         setFirstPartyForCookies(m_frame->tree()->parent()->document()->firstPartyForCookies());
991     else
992         setFirstPartyForCookies(m_frame->document()->url());
993 }
994
995 void FrameLoader::setFirstPartyForCookies(const KURL& url)
996 {
997     for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
998         frame->document()->setFirstPartyForCookies(url);
999 }
1000
1001 // This does the same kind of work that didOpenURL does, except it relies on the fact
1002 // that a higher level already checked that the URLs match and the scrolling is the right thing to do.
1003 void FrameLoader::loadInSameDocument(const KURL& url, SerializedScriptValue* stateObject, bool isNewNavigation)
1004 {
1005     // If we have a state object, we cannot also be a new navigation.
1006     ASSERT(!stateObject || (stateObject && !isNewNavigation));
1007
1008     // Update the data source's request with the new URL to fake the URL change
1009     KURL oldURL = m_frame->document()->url();
1010     m_frame->document()->setURL(url);
1011     documentLoader()->replaceRequestURLForSameDocumentNavigation(url);
1012     if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject) {
1013         // NB: must happen after replaceRequestURLForSameDocumentNavigation(), since we add 
1014         // based on the current request. Must also happen before we openURL and displace the 
1015         // scroll position, since adding the BF item will save away scroll state.
1016         
1017         // NB2:  If we were loading a long, slow doc, and the user anchor nav'ed before
1018         // it was done, currItem is now set the that slow doc, and prevItem is whatever was
1019         // before it.  Adding the b/f item will bump the slow doc down to prevItem, even
1020         // though its load is not yet done.  I think this all works out OK, for one because
1021         // we have already saved away the scroll and doc state for the long slow load,
1022         // but it's not an obvious case.
1023
1024         history()->updateBackForwardListForFragmentScroll();
1025     }
1026     
1027     bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
1028     
1029     history()->updateForSameDocumentNavigation();
1030
1031     // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
1032     if (hashChange)
1033         m_frame->eventHandler()->stopAutoscrollTimer();
1034     
1035     // It's important to model this as a load that starts and immediately finishes.
1036     // Otherwise, the parent frame may think we never finished loading.
1037     started();
1038
1039     // We need to scroll to the fragment whether or not a hash change occurred, since
1040     // the user might have scrolled since the previous navigation.
1041     if (FrameView* view = m_frame->view())
1042         view->scrollToFragment(url);
1043     
1044     m_isComplete = false;
1045     checkCompleted();
1046
1047     if (isNewNavigation) {
1048         // This will clear previousItem from the rest of the frame tree that didn't
1049         // doing any loading. We need to make a pass on this now, since for anchor nav
1050         // we'll not go through a real load and reach Completed state.
1051         checkLoadComplete();
1052     }
1053
1054     m_client->dispatchDidNavigateWithinPage();
1055
1056     m_frame->document()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
1057     m_client->dispatchDidPopStateWithinPage();
1058     
1059     if (hashChange) {
1060         m_frame->document()->enqueueHashchangeEvent(oldURL, url);
1061         m_client->dispatchDidChangeLocationWithinPage();
1062     }
1063     
1064     // FrameLoaderClient::didFinishLoad() tells the internal load delegate the load finished with no error
1065     m_client->didFinishLoad();
1066 }
1067
1068 bool FrameLoader::isComplete() const
1069 {
1070     return m_isComplete;
1071 }
1072
1073 void FrameLoader::completed()
1074 {
1075     RefPtr<Frame> protect(m_frame);
1076
1077     for (Frame* descendant = m_frame->tree()->traverseNext(m_frame); descendant; descendant = descendant->tree()->traverseNext(m_frame))
1078         descendant->navigationScheduler()->startTimer();
1079
1080     if (Frame* parent = m_frame->tree()->parent())
1081         parent->loader()->checkCompleted();
1082
1083     if (m_frame->view())
1084         m_frame->view()->maintainScrollPositionAtAnchor(0);
1085 }
1086
1087 void FrameLoader::started()
1088 {
1089     for (Frame* frame = m_frame; frame; frame = frame->tree()->parent())
1090         frame->loader()->m_isComplete = false;
1091 }
1092
1093 void FrameLoader::prepareForHistoryNavigation()
1094 {
1095     // If there is no currentItem, but we still want to engage in 
1096     // history navigation we need to manufacture one, and update
1097     // the state machine of this frame to impersonate having
1098     // loaded it.
1099     RefPtr<HistoryItem> currentItem = history()->currentItem();
1100     if (!currentItem) {
1101         currentItem = HistoryItem::create();
1102         currentItem->setLastVisitWasFailure(true);
1103         history()->setCurrentItem(currentItem.get());
1104         frame()->page()->backForward()->setCurrentItem(currentItem.get());
1105
1106         ASSERT(stateMachine()->isDisplayingInitialEmptyDocument());
1107         stateMachine()->advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
1108         stateMachine()->advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
1109     }
1110 }
1111
1112 void FrameLoader::prepareForLoadStart()
1113 {
1114     if (Page* page = m_frame->page())
1115         page->progress()->progressStarted(m_frame);
1116     m_client->dispatchDidStartProvisionalLoad();
1117 }
1118
1119 void FrameLoader::setupForReplace()
1120 {
1121     setState(FrameStateProvisional);
1122     m_provisionalDocumentLoader = m_documentLoader;
1123     m_documentLoader = 0;
1124     detachChildren();
1125 }
1126
1127 // This is a hack to allow keep navigation to http/https feeds working. To remove this
1128 // we need to introduce new API akin to registerURLSchemeAsLocal, that registers a
1129 // protocols navigation policy.
1130 static bool isFeedWithNestedProtocolInHTTPFamily(const KURL& url)
1131 {
1132     const String& urlString = url.string();
1133     if (!urlString.startsWith("feed", false))
1134         return false;
1135
1136     return urlString.startsWith("feed://", false) 
1137         || urlString.startsWith("feed:http:", false) || urlString.startsWith("feed:https:", false)
1138         || urlString.startsWith("feeds:http:", false) || urlString.startsWith("feeds:https:", false)
1139         || urlString.startsWith("feedsearch:http:", false) || urlString.startsWith("feedsearch:https:", false);
1140 }
1141
1142 void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, bool lockHistory, bool lockBackForwardList,
1143     PassRefPtr<Event> event, PassRefPtr<FormState> formState, ReferrerPolicy referrerPolicy)
1144 {    
1145     // Protect frame from getting blown away inside dispatchBeforeLoadEvent in loadWithDocumentLoader.
1146     RefPtr<Frame> protect(m_frame);
1147
1148     KURL url = request.resourceRequest().url();
1149
1150     ASSERT(m_frame->document());
1151     // FIXME: Should we move the isFeedWithNestedProtocolInHTTPFamily logic inside SecurityOrigin::canDisplay?
1152     if (!isFeedWithNestedProtocolInHTTPFamily(url) && !request.requester()->canDisplay(url)) {
1153         reportLocalLoadFailed(m_frame, url.string());
1154         return;
1155     }
1156
1157     String referrer;
1158     String argsReferrer = request.resourceRequest().httpReferrer();
1159     if (!argsReferrer.isEmpty())
1160         referrer = argsReferrer;
1161     else
1162         referrer = m_outgoingReferrer;
1163
1164     if (SecurityOrigin::shouldHideReferrer(url, referrer) || referrerPolicy == NoReferrer)
1165         referrer = String();
1166     
1167     FrameLoadType loadType;
1168     if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
1169         loadType = FrameLoadTypeReload;
1170     else if (lockBackForwardList)
1171         loadType = FrameLoadTypeRedirectWithLockedBackForwardList;
1172     else
1173         loadType = FrameLoadTypeStandard;
1174
1175     if (request.resourceRequest().httpMethod() == "POST")
1176         loadPostRequest(request.resourceRequest(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
1177     else
1178         loadURL(request.resourceRequest().url(), referrer, request.frameName(), lockHistory, loadType, event, formState.get());
1179
1180     // FIXME: It's possible this targetFrame will not be the same frame that was targeted by the actual
1181     // load if frame names have changed.
1182     Frame* sourceFrame = formState ? formState->sourceFrame() : m_frame;
1183     Frame* targetFrame = sourceFrame->loader()->findFrameForNavigation(request.frameName());
1184     if (targetFrame && targetFrame != sourceFrame) {
1185         if (Page* page = targetFrame->page())
1186             page->chrome()->focus();
1187     }
1188 }
1189
1190 void FrameLoader::loadURL(const KURL& newURL, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType newLoadType,
1191     PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
1192 {
1193     if (m_inStopAllLoaders)
1194         return;
1195
1196     RefPtr<FormState> formState = prpFormState;
1197     bool isFormSubmission = formState;
1198     
1199     ResourceRequest request(newURL);
1200     if (!referrer.isEmpty()) {
1201         request.setHTTPReferrer(referrer);
1202         RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
1203         addHTTPOriginIfNeeded(request, referrerOrigin->toString());
1204     }
1205     addExtraFieldsToRequest(request, newLoadType, true);
1206     if (newLoadType == FrameLoadTypeReload || newLoadType == FrameLoadTypeReloadFromOrigin)
1207         request.setCachePolicy(ReloadIgnoringCacheData);
1208
1209     ASSERT(newLoadType != FrameLoadTypeSame);
1210
1211     // The search for a target frame is done earlier in the case of form submission.
1212     Frame* targetFrame = isFormSubmission ? 0 : findFrameForNavigation(frameName);
1213     if (targetFrame && targetFrame != m_frame) {
1214         targetFrame->loader()->loadURL(newURL, referrer, String(), lockHistory, newLoadType, event, formState.release());
1215         return;
1216     }
1217
1218     if (m_pageDismissalEventBeingDispatched != NoDismissal)
1219         return;
1220
1221     NavigationAction action(newURL, newLoadType, isFormSubmission, event);
1222
1223     if (!targetFrame && !frameName.isEmpty()) {
1224         policyChecker()->checkNewWindowPolicy(action, FrameLoader::callContinueLoadAfterNewWindowPolicy,
1225             request, formState.release(), frameName, this);
1226         return;
1227     }
1228
1229     RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1230
1231     bool sameURL = shouldTreatURLAsSameAsCurrent(newURL);
1232     const String& httpMethod = request.httpMethod();
1233     
1234     // Make sure to do scroll to anchor processing even if the URL is
1235     // exactly the same so pages with '#' links and DHTML side effects
1236     // work properly.
1237     if (shouldScrollToAnchor(isFormSubmission, httpMethod, newLoadType, newURL)) {
1238         oldDocumentLoader->setTriggeringAction(action);
1239         policyChecker()->stopCheck();
1240         policyChecker()->setLoadType(newLoadType);
1241         policyChecker()->checkNavigationPolicy(request, oldDocumentLoader.get(), formState.release(),
1242             callContinueFragmentScrollAfterNavigationPolicy, this);
1243     } else {
1244         // must grab this now, since this load may stop the previous load and clear this flag
1245         bool isRedirect = m_quickRedirectComing;
1246         loadWithNavigationAction(request, action, lockHistory, newLoadType, formState.release());
1247         if (isRedirect) {
1248             m_quickRedirectComing = false;
1249             if (m_provisionalDocumentLoader)
1250                 m_provisionalDocumentLoader->setIsClientRedirect(true);
1251         } else if (sameURL && newLoadType != FrameLoadTypeReload && newLoadType != FrameLoadTypeReloadFromOrigin)
1252             // Example of this case are sites that reload the same URL with a different cookie
1253             // driving the generated content, or a master frame with links that drive a target
1254             // frame, where the user has clicked on the same link repeatedly.
1255             m_loadType = FrameLoadTypeSame;
1256     }
1257 }
1258
1259 void FrameLoader::load(const ResourceRequest& request, bool lockHistory)
1260 {
1261     load(request, SubstituteData(), lockHistory);
1262 }
1263
1264 void FrameLoader::load(const ResourceRequest& request, const SubstituteData& substituteData, bool lockHistory)
1265 {
1266     if (m_inStopAllLoaders)
1267         return;
1268         
1269     // FIXME: is this the right place to reset loadType? Perhaps this should be done after loading is finished or aborted.
1270     m_loadType = FrameLoadTypeStandard;
1271     RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, substituteData);
1272     if (lockHistory && m_documentLoader)
1273         loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1274     load(loader.get());
1275 }
1276
1277 void FrameLoader::load(const ResourceRequest& request, const String& frameName, bool lockHistory)
1278 {
1279     if (frameName.isEmpty()) {
1280         load(request, lockHistory);
1281         return;
1282     }
1283
1284     Frame* frame = findFrameForNavigation(frameName);
1285     if (frame) {
1286         frame->loader()->load(request, lockHistory);
1287         return;
1288     }
1289
1290     policyChecker()->checkNewWindowPolicy(NavigationAction(request.url(), NavigationTypeOther), FrameLoader::callContinueLoadAfterNewWindowPolicy, request, 0, frameName, this);
1291 }
1292
1293 void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, bool lockHistory, FrameLoadType type, PassRefPtr<FormState> formState)
1294 {
1295     RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, SubstituteData());
1296     if (lockHistory && m_documentLoader)
1297         loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory());
1298
1299     loader->setTriggeringAction(action);
1300     if (m_documentLoader)
1301         loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1302
1303     loadWithDocumentLoader(loader.get(), type, formState);
1304 }
1305
1306 void FrameLoader::load(DocumentLoader* newDocumentLoader)
1307 {
1308     ResourceRequest& r = newDocumentLoader->request();
1309     addExtraFieldsToMainResourceRequest(r);
1310     FrameLoadType type;
1311
1312     if (shouldTreatURLAsSameAsCurrent(newDocumentLoader->originalRequest().url())) {
1313         r.setCachePolicy(ReloadIgnoringCacheData);
1314         type = FrameLoadTypeSame;
1315     } else
1316         type = FrameLoadTypeStandard;
1317
1318     if (m_documentLoader)
1319         newDocumentLoader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1320     
1321     // When we loading alternate content for an unreachable URL that we're
1322     // visiting in the history list, we treat it as a reload so the history list 
1323     // is appropriately maintained.
1324     //
1325     // FIXME: This seems like a dangerous overloading of the meaning of "FrameLoadTypeReload" ...
1326     // shouldn't a more explicit type of reload be defined, that means roughly 
1327     // "load without affecting history" ? 
1328     if (shouldReloadToHandleUnreachableURL(newDocumentLoader)) {
1329         // shouldReloadToHandleUnreachableURL() returns true only when the original load type is back-forward.
1330         // In this case we should save the document state now. Otherwise the state can be lost because load type is
1331         // changed and updateForBackForwardNavigation() will not be called when loading is committed.
1332         history()->saveDocumentAndScrollState();
1333
1334         ASSERT(type == FrameLoadTypeStandard);
1335         type = FrameLoadTypeReload;
1336     }
1337
1338     loadWithDocumentLoader(newDocumentLoader, type, 0);
1339 }
1340
1341 void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType type, PassRefPtr<FormState> prpFormState)
1342 {
1343     // Retain because dispatchBeforeLoadEvent may release the last reference to it.
1344     RefPtr<Frame> protect(m_frame);
1345
1346     ASSERT(m_client->hasWebView());
1347
1348     // Unfortunately the view must be non-nil, this is ultimately due
1349     // to parser requiring a FrameView.  We should fix this dependency.
1350
1351     ASSERT(m_frame->view());
1352
1353     if (m_pageDismissalEventBeingDispatched != NoDismissal)
1354         return;
1355
1356     if (m_frame->document())
1357         m_previousUrl = m_frame->document()->url();
1358
1359     policyChecker()->setLoadType(type);
1360     RefPtr<FormState> formState = prpFormState;
1361     bool isFormSubmission = formState;
1362
1363     const KURL& newURL = loader->request().url();
1364     const String& httpMethod = loader->request().httpMethod();
1365
1366     if (shouldScrollToAnchor(isFormSubmission,  httpMethod, policyChecker()->loadType(), newURL)) {
1367         RefPtr<DocumentLoader> oldDocumentLoader = m_documentLoader;
1368         NavigationAction action(newURL, policyChecker()->loadType(), isFormSubmission);
1369
1370         oldDocumentLoader->setTriggeringAction(action);
1371         policyChecker()->stopCheck();
1372         policyChecker()->checkNavigationPolicy(loader->request(), oldDocumentLoader.get(), formState,
1373             callContinueFragmentScrollAfterNavigationPolicy, this);
1374     } else {
1375         if (Frame* parent = m_frame->tree()->parent())
1376             loader->setOverrideEncoding(parent->loader()->documentLoader()->overrideEncoding());
1377
1378         policyChecker()->stopCheck();
1379         setPolicyDocumentLoader(loader);
1380         if (loader->triggeringAction().isEmpty())
1381             loader->setTriggeringAction(NavigationAction(newURL, policyChecker()->loadType(), isFormSubmission));
1382
1383         if (Element* ownerElement = m_frame->ownerElement()) {
1384             // We skip dispatching the beforeload event if we've already
1385             // committed a real document load because the event would leak
1386             // subsequent activity by the frame which the parent frame isn't
1387             // supposed to learn. For example, if the child frame navigated to
1388             // a new URL, the parent frame shouldn't learn the URL.
1389             if (!m_stateMachine.committedFirstRealDocumentLoad()
1390                 && !ownerElement->dispatchBeforeLoadEvent(loader->request().url().string())) {
1391                 continueLoadAfterNavigationPolicy(loader->request(), formState, false);
1392                 return;
1393             }
1394         }
1395
1396         policyChecker()->checkNavigationPolicy(loader->request(), loader, formState,
1397             callContinueLoadAfterNavigationPolicy, this);
1398     }
1399 }
1400
1401 void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
1402 {
1403     ASSERT(!url.isEmpty());
1404     if (!frame)
1405         return;
1406
1407     frame->domWindow()->console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Not allowed to load local resource: " + url, 0, String());
1408 }
1409
1410 const ResourceRequest& FrameLoader::initialRequest() const
1411 {
1412     return activeDocumentLoader()->originalRequest();
1413 }
1414
1415 bool FrameLoader::willLoadMediaElementURL(KURL& url)
1416 {
1417     ResourceRequest request(url);
1418
1419     unsigned long identifier;
1420     ResourceError error;
1421     requestFromDelegate(request, identifier, error);
1422     notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, ResourceResponse(url, String(), -1, String(), String()), 0, -1, -1, error);
1423
1424     url = request.url();
1425
1426     return error.isNull();
1427 }
1428
1429 bool FrameLoader::shouldReloadToHandleUnreachableURL(DocumentLoader* docLoader)
1430 {
1431     KURL unreachableURL = docLoader->unreachableURL();
1432
1433     if (unreachableURL.isEmpty())
1434         return false;
1435
1436     if (!isBackForwardLoadType(policyChecker()->loadType()))
1437         return false;
1438
1439     // We only treat unreachableURLs specially during the delegate callbacks
1440     // for provisional load errors and navigation policy decisions. The former
1441     // case handles well-formed URLs that can't be loaded, and the latter
1442     // case handles malformed URLs and unknown schemes. Loading alternate content
1443     // at other times behaves like a standard load.
1444     DocumentLoader* compareDocumentLoader = 0;
1445     if (policyChecker()->delegateIsDecidingNavigationPolicy() || policyChecker()->delegateIsHandlingUnimplementablePolicy())
1446         compareDocumentLoader = m_policyDocumentLoader.get();
1447     else if (m_delegateIsHandlingProvisionalLoadError)
1448         compareDocumentLoader = m_provisionalDocumentLoader.get();
1449
1450     return compareDocumentLoader && unreachableURL == compareDocumentLoader->request().url();
1451 }
1452
1453 void FrameLoader::reloadWithOverrideEncoding(const String& encoding)
1454 {
1455     if (!m_documentLoader)
1456         return;
1457
1458     ResourceRequest request = m_documentLoader->request();
1459     KURL unreachableURL = m_documentLoader->unreachableURL();
1460     if (!unreachableURL.isEmpty())
1461         request.setURL(unreachableURL);
1462
1463     request.setCachePolicy(ReturnCacheDataElseLoad);
1464
1465     RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, SubstituteData());
1466     setPolicyDocumentLoader(loader.get());
1467
1468     loader->setOverrideEncoding(encoding);
1469
1470     loadWithDocumentLoader(loader.get(), FrameLoadTypeReload, 0);
1471 }
1472
1473 void FrameLoader::reload(bool endToEndReload)
1474 {
1475     if (!m_documentLoader)
1476         return;
1477
1478     // If a window is created by javascript, its main frame can have an empty but non-nil URL.
1479     // Reloading in this case will lose the current contents (see 4151001).
1480     if (m_documentLoader->request().url().isEmpty())
1481         return;
1482
1483     ResourceRequest initialRequest = m_documentLoader->request();
1484
1485     // Replace error-page URL with the URL we were trying to reach.
1486     KURL unreachableURL = m_documentLoader->unreachableURL();
1487     if (!unreachableURL.isEmpty())
1488         initialRequest.setURL(unreachableURL);
1489     
1490     // Create a new document loader for the reload, this will become m_documentLoader eventually,
1491     // but first it has to be the "policy" document loader, and then the "provisional" document loader.
1492     RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(initialRequest, SubstituteData());
1493
1494     ResourceRequest& request = loader->request();
1495
1496     // FIXME: We don't have a mechanism to revalidate the main resource without reloading at the moment.
1497     request.setCachePolicy(ReloadIgnoringCacheData);
1498
1499     // If we're about to re-post, set up action so the application can warn the user.
1500     if (request.httpMethod() == "POST")
1501         loader->setTriggeringAction(NavigationAction(request.url(), NavigationTypeFormResubmitted));
1502
1503     loader->setOverrideEncoding(m_documentLoader->overrideEncoding());
1504     
1505     loadWithDocumentLoader(loader.get(), endToEndReload ? FrameLoadTypeReloadFromOrigin : FrameLoadTypeReload, 0);
1506 }
1507
1508 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
1509 {
1510     // targetFrame can be NULL when we're trying to navigate a top-level frame
1511     // that has a NULL opener.
1512     if (!targetFrame)
1513         return false;
1514
1515     const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
1516     for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree()->parent()) {
1517         Document* ancestorDocument = ancestorFrame->document();
1518         if (!ancestorDocument)
1519             return true;
1520
1521         const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
1522         if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
1523             return true;
1524         
1525         // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
1526         if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
1527             return true;
1528     }
1529
1530     return false;
1531 }
1532
1533 bool FrameLoader::shouldAllowNavigation(Frame* targetFrame) const
1534 {
1535     // The navigation change is safe if the active frame is:
1536     //   - in the same security origin as the target or one of the target's
1537     //     ancestors.
1538     //
1539     // Or the target frame is:
1540     //   - a top-level frame in the frame hierarchy and the active frame can
1541     //     navigate the target frame's opener per above or it is the opener of
1542     //     the target frame.
1543
1544     if (!targetFrame)
1545         return true;
1546
1547     // Performance optimization.
1548     if (m_frame == targetFrame)
1549         return true;
1550
1551     // Let a frame navigate the top-level window that contains it.  This is
1552     // important to allow because it lets a site "frame-bust" (escape from a
1553     // frame created by another web site).
1554     if (!isDocumentSandboxed(m_frame, SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
1555         return true;
1556
1557     // A sandboxed frame can only navigate itself and its descendants.
1558     if (isDocumentSandboxed(m_frame, SandboxNavigation) && !targetFrame->tree()->isDescendantOf(m_frame))
1559         return false;
1560
1561     // Let a frame navigate its opener if the opener is a top-level window.
1562     if (!targetFrame->tree()->parent() && m_frame->loader()->opener() == targetFrame)
1563         return true;
1564
1565     Document* activeDocument = m_frame->document();
1566     ASSERT(activeDocument);
1567     const SecurityOrigin* activeSecurityOrigin = activeDocument->securityOrigin();
1568
1569     // For top-level windows, check the opener.
1570     if (!targetFrame->tree()->parent() && canAccessAncestor(activeSecurityOrigin, targetFrame->loader()->opener()))
1571         return true;
1572
1573     // In general, check the frame's ancestors.
1574     if (canAccessAncestor(activeSecurityOrigin, targetFrame))
1575         return true;
1576
1577     Settings* settings = targetFrame->settings();
1578     if (settings && !settings->privateBrowsingEnabled()) {
1579         Document* targetDocument = targetFrame->document();
1580         // FIXME: this error message should contain more specifics of why the navigation change is not allowed.
1581         String message = "Unsafe JavaScript attempt to initiate a navigation change for frame with URL " +
1582                          targetDocument->url().string() + " from frame with URL " + activeDocument->url().string() + ".\n";
1583
1584         // FIXME: should we print to the console of the activeFrame as well?
1585         targetFrame->domWindow()->console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, 1, String());
1586     }
1587     
1588     return false;
1589 }
1590
1591 void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItemPolicy)
1592 {
1593     ASSERT(!m_frame->document() || !m_frame->document()->inPageCache());
1594     if (m_pageDismissalEventBeingDispatched != NoDismissal)
1595         return;
1596
1597     // If this method is called from within this method, infinite recursion can occur (3442218). Avoid this.
1598     if (m_inStopAllLoaders)
1599         return;
1600
1601     m_inStopAllLoaders = true;
1602
1603     policyChecker()->stopCheck();
1604
1605     // If no new load is in progress, we should clear the provisional item from history
1606     // before we call stopLoading.
1607     if (clearProvisionalItemPolicy == ShouldClearProvisionalItem)
1608         history()->setProvisionalItem(0);
1609
1610     for (RefPtr<Frame> child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
1611         child->loader()->stopAllLoaders(clearProvisionalItemPolicy);
1612     if (m_provisionalDocumentLoader)
1613         m_provisionalDocumentLoader->stopLoading();
1614     if (m_documentLoader)
1615         m_documentLoader->stopLoading();
1616
1617     setProvisionalDocumentLoader(0);
1618     
1619 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
1620     if (m_documentLoader)
1621         m_documentLoader->clearArchiveResources();
1622 #endif
1623
1624     m_checkTimer.stop();
1625
1626     m_inStopAllLoaders = false;    
1627 }
1628
1629 void FrameLoader::stopForUserCancel(bool deferCheckLoadComplete)
1630 {
1631     stopAllLoaders();
1632     
1633     if (deferCheckLoadComplete)
1634         scheduleCheckLoadComplete();
1635     else if (m_frame->page())
1636         checkLoadComplete();
1637 }
1638
1639 DocumentLoader* FrameLoader::activeDocumentLoader() const
1640 {
1641     if (m_state == FrameStateProvisional)
1642         return m_provisionalDocumentLoader.get();
1643     return m_documentLoader.get();
1644 }
1645
1646 bool FrameLoader::isLoading() const
1647 {
1648     DocumentLoader* docLoader = activeDocumentLoader();
1649     if (!docLoader)
1650         return false;
1651     return docLoader->isLoadingMainResource() || docLoader->isLoadingSubresources() || docLoader->isLoadingPlugIns();
1652 }
1653
1654 bool FrameLoader::frameHasLoaded() const
1655 {
1656     return m_stateMachine.committedFirstRealDocumentLoad() || (m_provisionalDocumentLoader && !m_stateMachine.creatingInitialEmptyDocument()); 
1657 }
1658
1659 void FrameLoader::transferLoadingResourcesFromPage(Page* oldPage)
1660 {
1661     ASSERT(oldPage != m_frame->page());
1662     if (isLoading()) {
1663         activeDocumentLoader()->transferLoadingResourcesFromPage(oldPage);
1664         oldPage->progress()->progressCompleted(m_frame);
1665         if (m_frame->page())
1666             m_frame->page()->progress()->progressStarted(m_frame);
1667     }
1668 }
1669
1670 void FrameLoader::dispatchTransferLoadingResourceFromPage(ResourceLoader* loader, const ResourceRequest& request, Page* oldPage)
1671 {
1672     notifier()->dispatchTransferLoadingResourceFromPage(loader, request, oldPage);
1673 }
1674
1675 void FrameLoader::setDocumentLoader(DocumentLoader* loader)
1676 {
1677     if (!loader && !m_documentLoader)
1678         return;
1679     
1680     ASSERT(loader != m_documentLoader);
1681     ASSERT(!loader || loader->frameLoader() == this);
1682
1683     m_client->prepareForDataSourceReplacement();
1684     detachChildren();
1685     if (m_documentLoader)
1686         m_documentLoader->detachFromFrame();
1687
1688     m_documentLoader = loader;
1689
1690     // The following abomination is brought to you by the unload event.
1691     // The detachChildren() call above may trigger a child frame's unload event,
1692     // which could do something obnoxious like call document.write("") on
1693     // the main frame, which results in detaching children while detaching children.
1694     // This can cause the new m_documentLoader to be detached from its Frame*, but still
1695     // be alive. To make matters worse, DocumentLoaders with a null Frame* aren't supposed
1696     // to happen when they're still alive (and many places below us on the stack think the
1697     // DocumentLoader is still usable). Ergo, we reattach loader to its Frame, and pretend
1698     // like nothing ever happened.
1699     if (m_documentLoader && !m_documentLoader->frame()) {
1700         ASSERT(!m_documentLoader->isLoading());
1701         m_documentLoader->setFrame(m_frame);
1702     }
1703 }
1704
1705 void FrameLoader::setPolicyDocumentLoader(DocumentLoader* loader)
1706 {
1707     if (m_policyDocumentLoader == loader)
1708         return;
1709
1710     ASSERT(m_frame);
1711     if (loader)
1712         loader->setFrame(m_frame);
1713     if (m_policyDocumentLoader
1714             && m_policyDocumentLoader != m_provisionalDocumentLoader
1715             && m_policyDocumentLoader != m_documentLoader)
1716         m_policyDocumentLoader->detachFromFrame();
1717
1718     m_policyDocumentLoader = loader;
1719 }
1720
1721 void FrameLoader::setProvisionalDocumentLoader(DocumentLoader* loader)
1722 {
1723     ASSERT(!loader || !m_provisionalDocumentLoader);
1724     ASSERT(!loader || loader->frameLoader() == this);
1725
1726     if (m_provisionalDocumentLoader && m_provisionalDocumentLoader != m_documentLoader)
1727         m_provisionalDocumentLoader->detachFromFrame();
1728
1729     m_provisionalDocumentLoader = loader;
1730 }
1731
1732 double FrameLoader::timeOfLastCompletedLoad()
1733 {
1734     return storedTimeOfLastCompletedLoad;
1735 }
1736
1737 void FrameLoader::setState(FrameState newState)
1738 {    
1739     m_state = newState;
1740     
1741     if (newState == FrameStateProvisional)
1742         provisionalLoadStarted();
1743     else if (newState == FrameStateComplete) {
1744         frameLoadCompleted();
1745         storedTimeOfLastCompletedLoad = currentTime();
1746         if (m_documentLoader)
1747             m_documentLoader->stopRecordingResponses();
1748     }
1749 }
1750
1751 void FrameLoader::clearProvisionalLoad()
1752 {
1753     setProvisionalDocumentLoader(0);
1754     if (Page* page = m_frame->page())
1755         page->progress()->progressCompleted(m_frame);
1756     setState(FrameStateComplete);
1757 }
1758
1759 void FrameLoader::commitProvisionalLoad()
1760 {
1761     RefPtr<CachedPage> cachedPage = m_loadingFromCachedPage ? pageCache()->get(history()->provisionalItem()) : 0;
1762     RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
1763
1764     LOG(PageCache, "WebCoreLoading %s: About to commit provisional load from previous URL '%s' to new URL '%s'", m_frame->tree()->uniqueName().string().utf8().data(),
1765         m_frame->document() ? m_frame->document()->url().string().utf8().data() : "", 
1766         pdl ? pdl->url().string().utf8().data() : "<no provisional DocumentLoader>");
1767
1768     // Check to see if we need to cache the page we are navigating away from into the back/forward cache.
1769     // We are doing this here because we know for sure that a new page is about to be loaded.
1770     HistoryItem* item = history()->currentItem();
1771     if (!m_frame->tree()->parent() && PageCache::canCache(m_frame->page()) && !item->isInPageCache())
1772         pageCache()->add(item, m_frame->page());
1773
1774     if (m_loadType != FrameLoadTypeReplace)
1775         closeOldDataSources();
1776
1777     if (!cachedPage && !m_stateMachine.creatingInitialEmptyDocument())
1778         m_client->makeRepresentation(pdl.get());
1779
1780     transitionToCommitted(cachedPage);
1781
1782     if (pdl) {
1783         // Check if the destination page is allowed to access the previous page's timing information.
1784         RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(pdl->request().url());
1785         m_documentLoader->timing()->hasSameOriginAsPreviousDocument = securityOrigin->canRequest(m_previousUrl);
1786     }
1787
1788     // Call clientRedirectCancelledOrFinished() here so that the frame load delegate is notified that the redirect's
1789     // status has changed, if there was a redirect.  The frame load delegate may have saved some state about
1790     // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:.  Since we are
1791     // just about to commit a new page, there cannot possibly be a pending redirect at this point.
1792     if (m_sentRedirectNotification)
1793         clientRedirectCancelledOrFinished(false);
1794     
1795     if (cachedPage && cachedPage->document()) {
1796         prepareForCachedPageRestore();
1797         cachedPage->restore(m_frame->page());
1798
1799         dispatchDidCommitLoad();
1800
1801         // If we have a title let the WebView know about it. 
1802         StringWithDirection title = m_documentLoader->title();
1803         if (!title.isNull())
1804             m_client->dispatchDidReceiveTitle(title);
1805
1806         checkCompleted();
1807     } else
1808         didOpenURL();
1809
1810     LOG(Loading, "WebCoreLoading %s: Finished committing provisional load to URL %s", m_frame->tree()->uniqueName().string().utf8().data(),
1811         m_frame->document() ? m_frame->document()->url().string().utf8().data() : "");
1812
1813     if (m_loadType == FrameLoadTypeStandard && m_documentLoader->isClientRedirect())
1814         history()->updateForClientRedirect();
1815
1816     if (m_loadingFromCachedPage) {
1817         m_frame->document()->documentDidBecomeActive();
1818         
1819         // Force a layout to update view size and thereby update scrollbars.
1820         m_frame->view()->forceLayout();
1821
1822         const ResponseVector& responses = m_documentLoader->responses();
1823         size_t count = responses.size();
1824         for (size_t i = 0; i < count; i++) {
1825             const ResourceResponse& response = responses[i];
1826             // FIXME: If the WebKit client changes or cancels the request, this is not respected.
1827             ResourceError error;
1828             unsigned long identifier;
1829             ResourceRequest request(response.url());
1830             requestFromDelegate(request, identifier, error);
1831             // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
1832             // However, with today's computers and networking speeds, this won't happen in practice.
1833             // Could be an issue with a giant local file.
1834             notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, response, 0, static_cast<int>(response.expectedContentLength()), 0, error);
1835         }
1836         
1837         pageCache()->remove(history()->currentItem());
1838
1839         m_documentLoader->setPrimaryLoadComplete(true);
1840
1841         // FIXME: Why only this frame and not parent frames?
1842         checkLoadCompleteForThisFrame();
1843     }
1844 }
1845
1846 void FrameLoader::transitionToCommitted(PassRefPtr<CachedPage> cachedPage)
1847 {
1848     ASSERT(m_client->hasWebView());
1849     ASSERT(m_state == FrameStateProvisional);
1850
1851     if (m_state != FrameStateProvisional)
1852         return;
1853
1854     if (m_frame->view())
1855         m_frame->view()->scrollAnimator()->cancelAnimations();
1856
1857     m_client->setCopiesOnScroll();
1858     history()->updateForCommit();
1859
1860     // The call to closeURL() invokes the unload event handler, which can execute arbitrary
1861     // JavaScript. If the script initiates a new load, we need to abandon the current load,
1862     // or the two will stomp each other.
1863     DocumentLoader* pdl = m_provisionalDocumentLoader.get();
1864     if (m_documentLoader)
1865         closeURL();
1866     if (pdl != m_provisionalDocumentLoader)
1867         return;
1868
1869     // Nothing else can interupt this commit - set the Provisional->Committed transition in stone
1870     if (m_documentLoader)
1871         m_documentLoader->stopLoadingSubresources();
1872     if (m_documentLoader)
1873         m_documentLoader->stopLoadingPlugIns();
1874
1875     setDocumentLoader(m_provisionalDocumentLoader.get());
1876     setProvisionalDocumentLoader(0);
1877     setState(FrameStateCommittedPage);
1878
1879 #if ENABLE(TOUCH_EVENTS)
1880     if (isLoadingMainFrame())
1881         m_frame->page()->chrome()->client()->needTouchEvents(false);
1882 #endif
1883
1884     // Handle adding the URL to the back/forward list.
1885     DocumentLoader* dl = m_documentLoader.get();
1886
1887     switch (m_loadType) {
1888         case FrameLoadTypeForward:
1889         case FrameLoadTypeBack:
1890         case FrameLoadTypeIndexedBackForward:
1891             if (m_frame->page()) {
1892                 // If the first load within a frame is a navigation within a back/forward list that was attached
1893                 // without any of the items being loaded then we need to update the history in a similar manner as
1894                 // for a standard load with the exception of updating the back/forward list (<rdar://problem/8091103>).
1895                 if (!m_stateMachine.committedFirstRealDocumentLoad() && isLoadingMainFrame())
1896                     history()->updateForStandardLoad(HistoryController::UpdateAllExceptBackForwardList);
1897
1898                 history()->updateForBackForwardNavigation();
1899
1900                 // For cached pages, CachedFrame::restore will take care of firing the popstate event with the history item's state object
1901                 if (history()->currentItem() && !cachedPage)
1902                     m_pendingStateObject = history()->currentItem()->stateObject();
1903
1904                 // Create a document view for this document, or used the cached view.
1905                 if (cachedPage) {
1906                     DocumentLoader* cachedDocumentLoader = cachedPage->documentLoader();
1907                     ASSERT(cachedDocumentLoader);
1908                     cachedDocumentLoader->setFrame(m_frame);
1909                     m_client->transitionToCommittedFromCachedFrame(cachedPage->cachedMainFrame());
1910
1911                 } else
1912                     m_client->transitionToCommittedForNewPage();
1913             }
1914             break;
1915
1916         case FrameLoadTypeReload:
1917         case FrameLoadTypeReloadFromOrigin:
1918         case FrameLoadTypeSame:
1919         case FrameLoadTypeReplace:
1920             history()->updateForReload();
1921             m_client->transitionToCommittedForNewPage();
1922             break;
1923
1924         case FrameLoadTypeStandard:
1925             history()->updateForStandardLoad();
1926             if (m_frame->view())
1927                 m_frame->view()->setScrollbarsSuppressed(true);
1928             m_client->transitionToCommittedForNewPage();
1929             break;
1930
1931         case FrameLoadTypeRedirectWithLockedBackForwardList:
1932             history()->updateForRedirectWithLockedBackForwardList();
1933             m_client->transitionToCommittedForNewPage();
1934             break;
1935
1936         // FIXME Remove this check when dummy ds is removed (whatever "dummy ds" is).
1937         // An exception should be thrown if we're in the FrameLoadTypeUninitialized state.
1938         default:
1939             ASSERT_NOT_REACHED();
1940     }
1941
1942     m_documentLoader->writer()->setMIMEType(dl->responseMIMEType());
1943
1944     // Tell the client we've committed this URL.
1945     ASSERT(m_frame->view());
1946
1947     if (m_stateMachine.creatingInitialEmptyDocument())
1948         return;
1949
1950     if (!m_stateMachine.committedFirstRealDocumentLoad())
1951         m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocumentPostCommit);
1952
1953     if (!m_client->hasHTMLView())
1954         receivedFirstData();
1955 }
1956
1957 void FrameLoader::clientRedirectCancelledOrFinished(bool cancelWithLoadInProgress)
1958 {
1959     // Note that -webView:didCancelClientRedirectForFrame: is called on the frame load delegate even if
1960     // the redirect succeeded.  We should either rename this API, or add a new method, like
1961     // -webView:didFinishClientRedirectForFrame:
1962     m_client->dispatchDidCancelClientRedirect();
1963
1964     if (!cancelWithLoadInProgress)
1965         m_quickRedirectComing = false;
1966
1967     m_sentRedirectNotification = false;
1968 }
1969
1970 void FrameLoader::clientRedirected(const KURL& url, double seconds, double fireDate, bool lockBackForwardList)
1971 {
1972     m_client->dispatchWillPerformClientRedirect(url, seconds, fireDate);
1973     
1974     // Remember that we sent a redirect notification to the frame load delegate so that when we commit
1975     // the next provisional load, we can send a corresponding -webView:didCancelClientRedirectForFrame:
1976     m_sentRedirectNotification = true;
1977     
1978     // If a "quick" redirect comes in, we set a special mode so we treat the next
1979     // load as part of the original navigation. If we don't have a document loader, we have
1980     // no "original" load on which to base a redirect, so we treat the redirect as a normal load.
1981     // Loads triggered by JavaScript form submissions never count as quick redirects.
1982     m_quickRedirectComing = (lockBackForwardList || history()->currentItemShouldBeReplaced()) && m_documentLoader && !m_isExecutingJavaScriptFormAction;
1983 }
1984
1985 bool FrameLoader::shouldReload(const KURL& currentURL, const KURL& destinationURL)
1986 {
1987     // This function implements the rule: "Don't reload if navigating by fragment within
1988     // the same URL, but do reload if going to a new URL or to the same URL with no
1989     // fragment identifier at all."
1990     if (!destinationURL.hasFragmentIdentifier())
1991         return true;
1992     return !equalIgnoringFragmentIdentifier(currentURL, destinationURL);
1993 }
1994
1995 void FrameLoader::closeOldDataSources()
1996 {
1997     // FIXME: Is it important for this traversal to be postorder instead of preorder?
1998     // If so, add helpers for postorder traversal, and use them. If not, then lets not
1999     // use a recursive algorithm here.
2000     for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
2001         child->loader()->closeOldDataSources();
2002     
2003     if (m_documentLoader)
2004         m_client->dispatchWillClose();
2005
2006     m_client->setMainFrameDocumentReady(false); // stop giving out the actual DOMDocument to observers
2007 }
2008
2009 void FrameLoader::prepareForCachedPageRestore()
2010 {
2011     ASSERT(!m_frame->tree()->parent());
2012     ASSERT(m_frame->page());
2013     ASSERT(m_frame->page()->mainFrame() == m_frame);
2014
2015     m_frame->navigationScheduler()->cancel();
2016
2017     // We still have to close the previous part page.
2018     closeURL();
2019     
2020     // Delete old status bar messages (if it _was_ activated on last URL).
2021     if (m_frame->script()->canExecuteScripts(NotAboutToExecuteScript)) {
2022         if (DOMWindow* window = m_frame->existingDOMWindow()) {
2023             window->setStatus(String());
2024             window->setDefaultStatus(String());
2025         }
2026     }
2027 }
2028
2029 void FrameLoader::open(CachedFrameBase& cachedFrame)
2030 {
2031     m_isComplete = false;
2032     
2033     // Don't re-emit the load event.
2034     m_didCallImplicitClose = true;
2035
2036     KURL url = cachedFrame.url();
2037
2038     // FIXME: I suspect this block of code doesn't do anything.
2039     if (url.protocolInHTTPFamily() && !url.host().isEmpty() && url.path().isEmpty())
2040         url.setPath("/");
2041
2042     m_hasReceivedFirstData = false;
2043
2044     started();
2045     clear(true, true, cachedFrame.isMainFrame());
2046
2047     Document* document = cachedFrame.document();
2048     ASSERT(document);
2049     document->setInPageCache(false);
2050
2051     m_needsClear = true;
2052     m_isComplete = false;
2053     m_didCallImplicitClose = false;
2054     m_outgoingReferrer = url.string();
2055
2056     FrameView* view = cachedFrame.view();
2057     
2058     // When navigating to a CachedFrame its FrameView should never be null.  If it is we'll crash in creative ways downstream.
2059     ASSERT(view);
2060     view->setWasScrolledByUser(false);
2061
2062     // Use the current ScrollView's frame rect.
2063     if (m_frame->view()) {
2064         IntRect rect = m_frame->view()->frameRect();
2065         view->setFrameRect(rect);
2066         view->setBoundsSize(rect.size());
2067     }
2068     m_frame->setView(view);
2069     
2070     m_frame->setDocument(document);
2071     m_frame->setDOMWindow(cachedFrame.domWindow());
2072     m_frame->domWindow()->setURL(document->url());
2073     m_frame->domWindow()->setSecurityOrigin(document->securityOrigin());
2074
2075     updateFirstPartyForCookies();
2076
2077     cachedFrame.restore();
2078 }
2079
2080 void FrameLoader::finishedLoading()
2081 {
2082     // Retain because the stop may release the last reference to it.
2083     RefPtr<Frame> protect(m_frame);
2084
2085     RefPtr<DocumentLoader> dl = activeDocumentLoader();
2086     dl->finishedLoading();
2087     if (!dl->mainDocumentError().isNull() || !dl->frameLoader())
2088         return;
2089     dl->setPrimaryLoadComplete(true);
2090     m_client->dispatchDidLoadMainResource(dl.get());
2091     checkLoadComplete();
2092 }
2093
2094 bool FrameLoader::isHostedByObjectElement() const
2095 {
2096     HTMLFrameOwnerElement* owner = m_frame->ownerElement();
2097     return owner && owner->hasTagName(objectTag);
2098 }
2099
2100 bool FrameLoader::isLoadingMainFrame() const
2101 {
2102     Page* page = m_frame->page();
2103     return page && m_frame == page->mainFrame();
2104 }
2105
2106 void FrameLoader::finishedLoadingDocument(DocumentLoader* loader)
2107 {
2108     if (m_stateMachine.creatingInitialEmptyDocument())
2109         return;
2110
2111 #if !ENABLE(WEB_ARCHIVE) && !ENABLE(MHTML)
2112     m_client->finishedLoading(loader);
2113 #else
2114     // Give archive machinery a crack at this document. If the MIME type is not an archive type, it will return 0.
2115     m_archive = ArchiveFactory::create(loader->response().url(), loader->mainResourceData().get(), loader->responseMIMEType());
2116     if (!m_archive) {
2117         m_client->finishedLoading(loader);
2118         return;
2119     }
2120
2121     // FIXME: The remainder of this function should be moved to DocumentLoader.
2122
2123     loader->addAllArchiveResources(m_archive.get());
2124
2125     ArchiveResource* mainResource = m_archive->mainResource();
2126     loader->setParsedArchiveData(mainResource->data());
2127
2128     loader->writer()->setMIMEType(mainResource->mimeType());
2129
2130     closeURL();
2131     didOpenURL();
2132
2133     ASSERT(m_frame->document());
2134     String userChosenEncoding = documentLoader()->overrideEncoding();
2135     bool encodingIsUserChosen = !userChosenEncoding.isNull();
2136     loader->writer()->setEncoding(encodingIsUserChosen ? userChosenEncoding : mainResource->textEncoding(), encodingIsUserChosen);
2137     loader->writer()->addData(mainResource->data()->data(), mainResource->data()->size());
2138 #endif // ENABLE(WEB_ARCHIVE)
2139 }
2140
2141 bool FrameLoader::isReplacing() const
2142 {
2143     return m_loadType == FrameLoadTypeReplace;
2144 }
2145
2146 void FrameLoader::setReplacing()
2147 {
2148     m_loadType = FrameLoadTypeReplace;
2149 }
2150
2151 bool FrameLoader::subframeIsLoading() const
2152 {
2153     // It's most likely that the last added frame is the last to load so we walk backwards.
2154     for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling()) {
2155         FrameLoader* childLoader = child->loader();
2156         DocumentLoader* documentLoader = childLoader->documentLoader();
2157         if (documentLoader && documentLoader->isLoadingInAPISense())
2158             return true;
2159         documentLoader = childLoader->provisionalDocumentLoader();
2160         if (documentLoader && documentLoader->isLoadingInAPISense())
2161             return true;
2162         documentLoader = childLoader->policyDocumentLoader();
2163         if (documentLoader)
2164             return true;
2165     }
2166     return false;
2167 }
2168
2169 void FrameLoader::willChangeTitle(DocumentLoader* loader)
2170 {
2171     m_client->willChangeTitle(loader);
2172 }
2173
2174 FrameLoadType FrameLoader::loadType() const
2175 {
2176     return m_loadType;
2177 }
2178     
2179 CachePolicy FrameLoader::subresourceCachePolicy() const
2180 {
2181     if (m_isComplete)
2182         return CachePolicyVerify;
2183
2184     if (m_loadType == FrameLoadTypeReloadFromOrigin)
2185         return CachePolicyReload;
2186
2187     if (Frame* parentFrame = m_frame->tree()->parent()) {
2188         CachePolicy parentCachePolicy = parentFrame->loader()->subresourceCachePolicy();
2189         if (parentCachePolicy != CachePolicyVerify)
2190             return parentCachePolicy;
2191     }
2192     
2193     if (m_loadType == FrameLoadTypeReload)
2194         return CachePolicyRevalidate;
2195
2196     const ResourceRequest& request(documentLoader()->request());
2197 #if PLATFORM(MAC)
2198     if (request.cachePolicy() == ReloadIgnoringCacheData && !equalIgnoringCase(request.httpMethod(), "post") && ResourceRequest::useQuickLookResourceCachingQuirks())
2199         return CachePolicyRevalidate;
2200 #endif
2201
2202     if (request.cachePolicy() == ReturnCacheDataElseLoad)
2203         return CachePolicyHistoryBuffer;
2204
2205     return CachePolicyVerify;
2206 }
2207
2208 void FrameLoader::checkLoadCompleteForThisFrame()
2209 {
2210     ASSERT(m_client->hasWebView());
2211
2212     switch (m_state) {
2213         case FrameStateProvisional: {
2214             if (m_delegateIsHandlingProvisionalLoadError)
2215                 return;
2216
2217             RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
2218             if (!pdl)
2219                 return;
2220                 
2221             // If we've received any errors we may be stuck in the provisional state and actually complete.
2222             const ResourceError& error = pdl->mainDocumentError();
2223             if (error.isNull())
2224                 return;
2225
2226             // Check all children first.
2227             RefPtr<HistoryItem> item;
2228             if (Page* page = m_frame->page())
2229                 if (isBackForwardLoadType(loadType()))
2230                     // Reset the back forward list to the last committed history item at the top level.
2231                     item = page->mainFrame()->loader()->history()->currentItem();
2232                 
2233             // Only reset if we aren't already going to a new provisional item.
2234             bool shouldReset = !history()->provisionalItem();
2235             if (!pdl->isLoadingInAPISense() || pdl->isStopping()) {
2236                 m_delegateIsHandlingProvisionalLoadError = true;
2237                 m_client->dispatchDidFailProvisionalLoad(error);
2238                 m_delegateIsHandlingProvisionalLoadError = false;
2239
2240                 ASSERT(!pdl->isLoading());
2241                 ASSERT(!pdl->isLoadingMainResource());
2242                 ASSERT(!pdl->isLoadingSubresources());
2243                 ASSERT(!pdl->isLoadingPlugIns());
2244
2245                 // If we're in the middle of loading multipart data, we need to restore the document loader.
2246                 if (isReplacing() && !m_documentLoader.get())
2247                     setDocumentLoader(m_provisionalDocumentLoader.get());
2248
2249                 // Finish resetting the load state, but only if another load hasn't been started by the
2250                 // delegate callback.
2251                 if (pdl == m_provisionalDocumentLoader)
2252                     clearProvisionalLoad();
2253                 else if (activeDocumentLoader()) {
2254                     KURL unreachableURL = activeDocumentLoader()->unreachableURL();
2255                     if (!unreachableURL.isEmpty() && unreachableURL == pdl->request().url())
2256                         shouldReset = false;
2257                 }
2258             }
2259             if (shouldReset && item)
2260                 if (Page* page = m_frame->page()) {
2261                     page->backForward()->setCurrentItem(item.get());
2262                     m_frame->loader()->client()->updateGlobalHistoryItemForPage();
2263                 }
2264             return;
2265         }
2266         
2267         case FrameStateCommittedPage: {
2268             DocumentLoader* dl = m_documentLoader.get();            
2269             if (!dl || (dl->isLoadingInAPISense() && !dl->isStopping()))
2270                 return;
2271
2272             setState(FrameStateComplete);
2273
2274             // FIXME: Is this subsequent work important if we already navigated away?
2275             // Maybe there are bugs because of that, or extra work we can skip because
2276             // the new page is ready.
2277
2278             m_client->forceLayoutForNonHTML();
2279              
2280             // If the user had a scroll point, scroll to it, overriding the anchor point if any.
2281             if (m_frame->page()) {
2282                 if (isBackForwardLoadType(m_loadType) || m_loadType == FrameLoadTypeReload || m_loadType == FrameLoadTypeReloadFromOrigin)
2283                     history()->restoreScrollPositionAndViewState();
2284             }
2285
2286             if (m_stateMachine.creatingInitialEmptyDocument() || !m_stateMachine.committedFirstRealDocumentLoad())
2287                 return;
2288
2289             if (Page* page = m_frame->page())
2290                 page->progress()->progressCompleted(m_frame);
2291
2292             const ResourceError& error = dl->mainDocumentError();
2293             if (!error.isNull())
2294                 m_client->dispatchDidFailLoad(error);
2295             else
2296                 m_client->dispatchDidFinishLoad();
2297
2298             return;
2299         }
2300         
2301         case FrameStateComplete:
2302             frameLoadCompleted();
2303             return;
2304     }
2305
2306     ASSERT_NOT_REACHED();
2307 }
2308
2309 void FrameLoader::continueLoadAfterWillSubmitForm()
2310 {
2311     if (!m_provisionalDocumentLoader)
2312         return;
2313
2314     // DocumentLoader calls back to our prepareForLoadStart
2315     m_provisionalDocumentLoader->prepareForLoadStart();
2316     
2317     // The load might be cancelled inside of prepareForLoadStart(), nulling out the m_provisionalDocumentLoader, 
2318     // so we need to null check it again.
2319     if (!m_provisionalDocumentLoader)
2320         return;
2321
2322     DocumentLoader* activeDocLoader = activeDocumentLoader();
2323     if (activeDocLoader && activeDocLoader->isLoadingMainResource())
2324         return;
2325
2326     m_loadingFromCachedPage = false;
2327
2328     unsigned long identifier = 0;
2329
2330     if (Page* page = m_frame->page()) {
2331         identifier = page->progress()->createUniqueIdentifier();
2332         notifier()->assignIdentifierToInitialRequest(identifier, m_provisionalDocumentLoader.get(), m_provisionalDocumentLoader->originalRequest());
2333     }
2334
2335     ASSERT(!m_provisionalDocumentLoader->timing()->navigationStart);
2336     m_provisionalDocumentLoader->timing()->navigationStart = currentTime();
2337
2338     if (!m_provisionalDocumentLoader->startLoadingMainResource(identifier))
2339         m_provisionalDocumentLoader->updateLoading();
2340 }
2341
2342 void FrameLoader::didFirstLayout()
2343 {
2344     if (m_frame->page() && isBackForwardLoadType(m_loadType))
2345         history()->restoreScrollPositionAndViewState();
2346
2347     if (m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2348         m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2349
2350     m_client->dispatchDidFirstLayout();
2351 }
2352
2353 void FrameLoader::didFirstVisuallyNonEmptyLayout()
2354 {
2355     m_client->dispatchDidFirstVisuallyNonEmptyLayout();
2356 }
2357
2358 void FrameLoader::frameLoadCompleted()
2359 {
2360     // Note: Can be called multiple times.
2361
2362     m_client->frameLoadCompleted();
2363
2364     history()->updateForFrameLoadCompleted();
2365
2366     // After a canceled provisional load, firstLayoutDone is false.
2367     // Reset it to true if we're displaying a page.
2368     if (m_documentLoader && m_stateMachine.committedFirstRealDocumentLoad() && !m_stateMachine.isDisplayingInitialEmptyDocument() && !m_stateMachine.firstLayoutDone())
2369         m_stateMachine.advanceTo(FrameLoaderStateMachine::FirstLayoutDone);
2370 }
2371
2372 void FrameLoader::detachChildren()
2373 {
2374     typedef Vector<RefPtr<Frame> > FrameVector;
2375     FrameVector childrenToDetach;
2376     childrenToDetach.reserveCapacity(m_frame->tree()->childCount());
2377     for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling())
2378         childrenToDetach.append(child);
2379     FrameVector::iterator end = childrenToDetach.end();
2380     for (FrameVector::iterator it = childrenToDetach.begin(); it != end; it++)
2381         (*it)->loader()->detachFromParent();
2382 }
2383
2384 void FrameLoader::closeAndRemoveChild(Frame* child)
2385 {
2386     child->tree()->detachFromParent();
2387
2388     child->setView(0);
2389     if (child->ownerElement() && child->page())
2390         child->page()->decrementFrameCount();
2391     // FIXME: The page isn't being destroyed, so it's not right to call a function named pageDestroyed().
2392     child->pageDestroyed();
2393
2394     m_frame->tree()->removeChild(child);
2395 }
2396
2397 // Called every time a resource is completely loaded or an error is received.
2398 void FrameLoader::checkLoadComplete()
2399 {
2400     ASSERT(m_client->hasWebView());
2401     
2402     m_shouldCallCheckLoadComplete = false;
2403
2404     // FIXME: Always traversing the entire frame tree is a bit inefficient, but 
2405     // is currently needed in order to null out the previous history item for all frames.
2406     if (Page* page = m_frame->page()) {
2407         Vector<RefPtr<Frame>, 10> frames;
2408         for (RefPtr<Frame> frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
2409             frames.append(frame);
2410         // To process children before their parents, iterate the vector backwards.
2411         for (size_t i = frames.size(); i; --i)
2412             frames[i - 1]->loader()->checkLoadCompleteForThisFrame();
2413     }
2414 }
2415
2416 int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
2417 {
2418     if (!recurse)
2419         return m_frame->document()->cachedResourceLoader()->requestCount();
2420
2421     int count = 0;
2422     for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
2423         count += frame->document()->cachedResourceLoader()->requestCount();
2424     return count;
2425 }
2426
2427 String FrameLoader::userAgent(const KURL& url) const
2428 {
2429     String userAgent = m_client->userAgent(url);
2430     InspectorInstrumentation::applyUserAgentOverride(m_frame, &userAgent);
2431     return userAgent;
2432 }
2433
2434 void FrameLoader::handledOnloadEvents()
2435 {
2436     m_client->dispatchDidHandleOnloadEvents();
2437
2438     if (documentLoader())
2439         documentLoader()->handledOnloadEvents();
2440 }
2441
2442 void FrameLoader::frameDetached()
2443 {
2444     stopAllLoaders();
2445     m_frame->document()->stopActiveDOMObjects();
2446     detachFromParent();
2447 }
2448
2449 void FrameLoader::detachFromParent()
2450 {
2451     RefPtr<Frame> protect(m_frame);
2452
2453     closeURL();
2454     history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
2455     detachChildren();
2456     // stopAllLoaders() needs to be called after detachChildren(), because detachedChildren()
2457     // will trigger the unload event handlers of any child frames, and those event
2458     // handlers might start a new subresource load in this frame.
2459     stopAllLoaders();
2460
2461     InspectorInstrumentation::frameDetachedFromParent(m_frame);
2462
2463     detachViewsAndDocumentLoader();
2464
2465     if (Frame* parent = m_frame->tree()->parent()) {
2466         parent->loader()->closeAndRemoveChild(m_frame);
2467         parent->loader()->scheduleCheckCompleted();
2468     } else {
2469         m_frame->setView(0);
2470         // FIXME: The page isn't being destroyed, so it's not right to call a function named pageDestroyed().
2471         m_frame->pageDestroyed();
2472     }
2473 }
2474
2475 void FrameLoader::detachViewsAndDocumentLoader()
2476 {
2477     m_client->detachedFromParent2();
2478     setDocumentLoader(0);
2479     m_client->detachedFromParent3();
2480 }
2481     
2482 void FrameLoader::addExtraFieldsToSubresourceRequest(ResourceRequest& request)
2483 {
2484     addExtraFieldsToRequest(request, m_loadType, false);
2485 }
2486
2487 void FrameLoader::addExtraFieldsToMainResourceRequest(ResourceRequest& request)
2488 {
2489     addExtraFieldsToRequest(request, m_loadType, true);
2490 }
2491
2492 void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request, FrameLoadType loadType, bool mainResource)
2493 {
2494     // Don't set the cookie policy URL if it's already been set.
2495     // But make sure to set it on all requests, as it has significance beyond the cookie policy for all protocols (<rdar://problem/6616664>).
2496     if (request.firstPartyForCookies().isEmpty()) {
2497         if (mainResource && isLoadingMainFrame())
2498             request.setFirstPartyForCookies(request.url());
2499         else if (Document* document = m_frame->document())
2500             request.setFirstPartyForCookies(document->firstPartyForCookies());
2501     }
2502
2503     // The remaining modifications are only necessary for HTTP and HTTPS.
2504     if (!request.url().isEmpty() && !request.url().protocolInHTTPFamily())
2505         return;
2506
2507     applyUserAgent(request);
2508     
2509     // If we inherit cache policy from a main resource, we use the DocumentLoader's 
2510     // original request cache policy for two reasons:
2511     // 1. For POST requests, we mutate the cache policy for the main resource,
2512     //    but we do not want this to apply to subresources
2513     // 2. Delegates that modify the cache policy using willSendRequest: should
2514     //    not affect any other resources. Such changes need to be done
2515     //    per request.
2516     if (!mainResource) {
2517         if (request.isConditional())
2518             request.setCachePolicy(ReloadIgnoringCacheData);
2519         else if (documentLoader()->isLoadingInAPISense())
2520             request.setCachePolicy(documentLoader()->originalRequest().cachePolicy());
2521         else
2522             request.setCachePolicy(UseProtocolCachePolicy);
2523     } else if (loadType == FrameLoadTypeReload || loadType == FrameLoadTypeReloadFromOrigin || request.isConditional())
2524         request.setCachePolicy(ReloadIgnoringCacheData);
2525     else if (isBackForwardLoadType(loadType) && m_stateMachine.committedFirstRealDocumentLoad())
2526         request.setCachePolicy(ReturnCacheDataElseLoad);
2527         
2528     if (request.cachePolicy() == ReloadIgnoringCacheData) {
2529         if (loadType == FrameLoadTypeReload)
2530             request.setHTTPHeaderField("Cache-Control", "max-age=0");
2531         else if (loadType == FrameLoadTypeReloadFromOrigin) {
2532             request.setHTTPHeaderField("Cache-Control", "no-cache");
2533             request.setHTTPHeaderField("Pragma", "no-cache");
2534         }
2535     }
2536     
2537     if (mainResource)
2538         request.setHTTPAccept(defaultAcceptHeader);
2539
2540     // Make sure we send the Origin header.
2541     addHTTPOriginIfNeeded(request, String());
2542
2543 #if PLATFORM(MAC) || PLATFORM(WIN)
2544     // The Apple Mac and Windows ports have decided not to behave like other
2545     // browsers and instead use a quirky fallback array.
2546     // FIXME: We should remove this code once CFNetwork implements RFC 6266.
2547     Settings* settings = m_frame->settings();
2548     request.setResponseContentDispositionEncodingFallbackArray("UTF-8", activeDocumentLoader()->writer()->deprecatedFrameEncoding(), settings ? settings->defaultTextEncodingName() : String());
2549 #endif
2550 }
2551
2552 void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const String& origin)
2553 {
2554     if (!request.httpOrigin().isEmpty())
2555         return;  // Request already has an Origin header.
2556
2557     // Don't send an Origin header for GET or HEAD to avoid privacy issues.
2558     // For example, if an intranet page has a hyperlink to an external web
2559     // site, we don't want to include the Origin of the request because it
2560     // will leak the internal host name. Similar privacy concerns have lead
2561     // to the widespread suppression of the Referer header at the network
2562     // layer.
2563     if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
2564         return;
2565
2566     // For non-GET and non-HEAD methods, always send an Origin header so the
2567     // server knows we support this feature.
2568
2569     if (origin.isEmpty()) {
2570         // If we don't know what origin header to attach, we attach the value
2571         // for an empty origin.
2572         request.setHTTPOrigin(SecurityOrigin::createEmpty()->toString());
2573         return;
2574     }
2575
2576     request.setHTTPOrigin(origin);
2577 }
2578
2579 void FrameLoader::loadPostRequest(const ResourceRequest& inRequest, const String& referrer, const String& frameName, bool lockHistory, FrameLoadType loadType, PassRefPtr<Event> event, PassRefPtr<FormState> prpFormState)
2580 {
2581     RefPtr<FormState> formState = prpFormState;
2582
2583     // Previously when this method was reached, the original FrameLoadRequest had been deconstructed to build a 
2584     // bunch of parameters that would come in here and then be built back up to a ResourceRequest.  In case
2585     // any caller depends on the immutability of the original ResourceRequest, I'm rebuilding a ResourceRequest
2586     // from scratch as it did all along.
2587     const KURL& url = inRequest.url();
2588     RefPtr<FormData> formData = inRequest.httpBody();
2589     const String& contentType = inRequest.httpContentType();
2590     String origin = inRequest.httpOrigin();
2591
2592     ResourceRequest workingResourceRequest(url);    
2593
2594     if (!referrer.isEmpty())
2595         workingResourceRequest.setHTTPReferrer(referrer);
2596     workingResourceRequest.setHTTPOrigin(origin);
2597     workingResourceRequest.setHTTPMethod("POST");
2598     workingResourceRequest.setHTTPBody(formData);
2599     workingResourceRequest.setHTTPContentType(contentType);
2600     addExtraFieldsToRequest(workingResourceRequest, loadType, true);
2601
2602     NavigationAction action(url, loadType, true, event);
2603
2604     if (!frameName.isEmpty()) {
2605         // The search for a target frame is done earlier in the case of form submission.
2606         if (Frame* targetFrame = formState ? 0 : findFrameForNavigation(frameName))
2607             targetFrame->loader()->loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());
2608         else
2609             policyChecker()->checkNewWindowPolicy(action, FrameLoader::callContinueLoadAfterNewWindowPolicy, workingResourceRequest, formState.release(), frameName, this);
2610     } else
2611         loadWithNavigationAction(workingResourceRequest, action, lockHistory, loadType, formState.release());    
2612 }
2613
2614 unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, StoredCredentials storedCredentials, ResourceError& error, ResourceResponse& response, Vector<char>& data)
2615 {
2616     String referrer = m_outgoingReferrer;
2617     if (SecurityOrigin::shouldHideReferrer(request.url(), referrer))
2618         referrer = String();
2619     
2620     ResourceRequest initialRequest = request;
2621     initialRequest.setTimeoutInterval(10);
2622     
2623     if (!referrer.isEmpty())
2624         initialRequest.setHTTPReferrer(referrer);
2625     addHTTPOriginIfNeeded(initialRequest, outgoingOrigin());
2626
2627     if (Page* page = m_frame->page())
2628         initialRequest.setFirstPartyForCookies(page->mainFrame()->loader()->documentLoader()->request().url());
2629     
2630     addExtraFieldsToSubresourceRequest(initialRequest);
2631
2632     unsigned long identifier = 0;    
2633     ResourceRequest newRequest(initialRequest);
2634     requestFromDelegate(newRequest, identifier, error);
2635
2636     if (error.isNull()) {
2637         ASSERT(!newRequest.isNull());
2638         
2639 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
2640         if (!documentLoader()->applicationCacheHost()->maybeLoadSynchronously(newRequest, error, response, data)) {
2641 #endif
2642             ResourceHandle::loadResourceSynchronously(networkingContext(), newRequest, storedCredentials, error, response, data);
2643 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
2644             documentLoader()->applicationCacheHost()->maybeLoadFallbackSynchronously(newRequest, error, response, data);
2645         }
2646 #endif
2647     }
2648     int encodedDataLength = response.resourceLoadInfo() ? static_cast<int>(response.resourceLoadInfo()->encodedDataLength) : -1;
2649     notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, response, data.data(), data.size(), encodedDataLength, error);
2650     return identifier;
2651 }
2652
2653 const ResourceRequest& FrameLoader::originalRequest() const
2654 {
2655     return activeDocumentLoader()->originalRequestCopy();
2656 }
2657
2658 void FrameLoader::receivedMainResourceError(const ResourceError& error, bool isComplete)
2659 {
2660     // Retain because the stop may release the last reference to it.
2661     RefPtr<Frame> protect(m_frame);
2662
2663     RefPtr<DocumentLoader> loader = activeDocumentLoader();
2664
2665     if (isComplete) {
2666         // FIXME: Don't want to do this if an entirely new load is going, so should check
2667         // that both data sources on the frame are either this or nil.
2668         stop();
2669         if (m_client->shouldFallBack(error))
2670             handleFallbackContent();
2671     }
2672
2673     if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
2674         if (m_submittedFormURL == m_provisionalDocumentLoader->originalRequestCopy().url())
2675             m_submittedFormURL = KURL();
2676             
2677         // We might have made a page cache item, but now we're bailing out due to an error before we ever
2678         // transitioned to the new page (before WebFrameState == commit).  The goal here is to restore any state
2679         // so that the existing view (that wenever got far enough to replace) can continue being used.
2680         history()->invalidateCurrentItemCachedPage();
2681         
2682         // Call clientRedirectCancelledOrFinished here so that the frame load delegate is notified that the redirect's
2683         // status has changed, if there was a redirect. The frame load delegate may have saved some state about
2684         // the redirect in its -webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:. Since we are definitely
2685         // not going to use this provisional resource, as it was cancelled, notify the frame load delegate that the redirect
2686         // has ended.
2687         if (m_sentRedirectNotification)
2688             clientRedirectCancelledOrFinished(false);
2689     }
2690
2691     loader->mainReceivedError(error, isComplete);
2692 }
2693
2694 void FrameLoader::callContinueFragmentScrollAfterNavigationPolicy(void* argument,
2695     const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue)
2696 {
2697     FrameLoader* loader = static_cast<FrameLoader*>(argument);
2698     loader->continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
2699 }
2700
2701 void FrameLoader::continueFragmentScrollAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
2702 {
2703     m_quickRedirectComing = false;
2704
2705     if (!shouldContinue)
2706         return;
2707
2708     bool isRedirect = m_quickRedirectComing || policyChecker()->loadType() == FrameLoadTypeRedirectWithLockedBackForwardList;    
2709     loadInSameDocument(request.url(), 0, !isRedirect);
2710 }
2711
2712 bool FrameLoader::shouldScrollToAnchor(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const KURL& url)
2713 {
2714     // Should we do anchor navigation within the existing content?
2715
2716     // We don't do this if we are submitting a form with method other than "GET", explicitly reloading,
2717     // currently displaying a frameset, or if the URL does not have a fragment.
2718     // These rules were originally based on what KHTML was doing in KHTMLPart::openURL.
2719
2720     // FIXME: What about load types other than Standard and Reload?
2721
2722     return (!isFormSubmission || equalIgnoringCase(httpMethod, "GET"))
2723         && loadType != FrameLoadTypeReload
2724         && loadType != FrameLoadTypeReloadFromOrigin
2725         && loadType != FrameLoadTypeSame
2726         && !shouldReload(m_frame->document()->url(), url)
2727         // We don't want to just scroll if a link from within a
2728         // frameset is trying to reload the frameset into _top.
2729         && !m_frame->document()->isFrameSet();
2730 }
2731
2732 void FrameLoader::callContinueLoadAfterNavigationPolicy(void* argument,
2733     const ResourceRequest& request, PassRefPtr<FormState> formState, bool shouldContinue)
2734 {
2735     FrameLoader* loader = static_cast<FrameLoader*>(argument);
2736     loader->continueLoadAfterNavigationPolicy(request, formState, shouldContinue);
2737 }
2738
2739 bool FrameLoader::shouldClose()
2740 {
2741     Page* page = m_frame->page();
2742     Chrome* chrome = page ? page->chrome() : 0;
2743     if (!chrome || !chrome->canRunBeforeUnloadConfirmPanel())
2744         return true;
2745
2746     // Store all references to each subframe in advance since beforeunload's event handler may modify frame
2747     Vector<RefPtr<Frame> > targetFrames;
2748     targetFrames.append(m_frame);
2749     for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->traverseNext(m_frame))
2750         targetFrames.append(child);
2751
2752     bool shouldClose = false;
2753     {
2754         NavigationDisablerForBeforeUnload navigationDisabler;
2755         size_t i;
2756
2757         for (i = 0; i < targetFrames.size(); i++) {
2758             if (!targetFrames[i]->tree()->isDescendantOf(m_frame))
2759                 continue;
2760             if (!targetFrames[i]->loader()->fireBeforeUnloadEvent(chrome))
2761                 break;
2762         }
2763
2764         if (i == targetFrames.size())
2765             shouldClose = true;
2766     }
2767
2768     if (!shouldClose)
2769         m_submittedFormURL = KURL();
2770
2771     return shouldClose;
2772 }
2773
2774 bool FrameLoader::fireBeforeUnloadEvent(Chrome* chrome)
2775 {
2776     DOMWindow* domWindow = m_frame->existingDOMWindow();
2777     if (!domWindow)
2778         return true;
2779
2780     RefPtr<Document> document = m_frame->document();
2781     if (!document->body())
2782         return true;
2783
2784     RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2785     m_pageDismissalEventBeingDispatched = BeforeUnloadDismissal;
2786     domWindow->dispatchEvent(beforeUnloadEvent.get(), domWindow->document());
2787     m_pageDismissalEventBeingDispatched = NoDismissal;
2788
2789     if (!beforeUnloadEvent->defaultPrevented())
2790         document->defaultEventHandler(beforeUnloadEvent.get());
2791     if (beforeUnloadEvent->result().isNull())
2792         return true;
2793
2794     String text = document->displayStringModifiedByEncoding(beforeUnloadEvent->result());
2795     return chrome->runBeforeUnloadConfirmPanel(text, m_frame);
2796 }
2797
2798 void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest&, PassRefPtr<FormState> formState, bool shouldContinue)
2799 {
2800     // If we loaded an alternate page to replace an unreachableURL, we'll get in here with a
2801     // nil policyDataSource because loading the alternate page will have passed
2802     // through this method already, nested; otherwise, policyDataSource should still be set.
2803     ASSERT(m_policyDocumentLoader || !m_provisionalDocumentLoader->unreachableURL().isEmpty());
2804
2805     bool isTargetItem = history()->provisionalItem() ? history()->provisionalItem()->isTargetItem() : false;
2806
2807     // Two reasons we can't continue:
2808     //    1) Navigation policy delegate said we can't so request is nil. A primary case of this 
2809     //       is the user responding Cancel to the form repost nag sheet.
2810     //    2) User responded Cancel to an alert popped up by the before unload event handler.
2811     bool canContinue = shouldContinue && shouldClose();
2812
2813     if (!canContinue) {
2814         // If we were waiting for a quick redirect, but the policy delegate decided to ignore it, then we 
2815         // need to report that the client redirect was cancelled.
2816         if (m_quickRedirectComing)
2817             clientRedirectCancelledOrFinished(false);
2818
2819         setPolicyDocumentLoader(0);
2820
2821         // If the navigation request came from the back/forward menu, and we punt on it, we have the 
2822         // problem that we have optimistically moved the b/f cursor already, so move it back.  For sanity, 
2823         // we only do this when punting a navigation for the target frame or top-level frame.  
2824         if ((isTargetItem || isLoadingMainFrame()) && isBackForwardLoadType(policyChecker()->loadType())) {
2825             if (Page* page = m_frame->page()) {
2826                 Frame* mainFrame = page->mainFrame();
2827                 if (HistoryItem* resetItem = mainFrame->loader()->history()->currentItem()) {
2828                     page->backForward()->setCurrentItem(resetItem);
2829                     m_frame->loader()->client()->updateGlobalHistoryItemForPage();
2830                 }
2831             }
2832         }
2833         return;
2834     }
2835
2836     FrameLoadType type = policyChecker()->loadType();
2837     // A new navigation is in progress, so don't clear the history's provisional item.
2838     stopAllLoaders(ShouldNotClearProvisionalItem);
2839     
2840     // <rdar://problem/6250856> - In certain circumstances on pages with multiple frames, stopAllLoaders()
2841     // might detach the current FrameLoader, in which case we should bail on this newly defunct load. 
2842     if (!m_frame->page())
2843         return;
2844
2845 #if ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(INSPECTOR)
2846     if (Page* page = m_frame->page()) {
2847         if (page->mainFrame() == m_frame)
2848             m_frame->page()->inspectorController()->resume();
2849     }
2850 #endif
2851
2852     setProvisionalDocumentLoader(m_policyDocumentLoader.get());
2853     m_loadType = type;
2854     setState(FrameStateProvisional);
2855
2856     setPolicyDocumentLoader(0);
2857
2858     if (isBackForwardLoadType(type) && history()->provisionalItem()->isInPageCache()) {
2859         loadProvisionalItemFromCachedPage();
2860         return;
2861     }
2862
2863     if (formState)
2864         m_client->dispatchWillSubmitForm(&PolicyChecker::continueLoadAfterWillSubmitForm, formState);
2865     else
2866         continueLoadAfterWillSubmitForm();
2867 }
2868
2869 void FrameLoader::callContinueLoadAfterNewWindowPolicy(void* argument,
2870     const ResourceRequest& request, PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue)
2871 {
2872     FrameLoader* loader = static_cast<FrameLoader*>(argument);
2873     loader->continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue);
2874 }
2875
2876 void FrameLoader::continueLoadAfterNewWindowPolicy(const ResourceRequest& request,
2877     PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action, bool shouldContinue)
2878 {
2879     if (!shouldContinue)
2880         return;
2881
2882     RefPtr<Frame> frame = m_frame;
2883     RefPtr<Frame> mainFrame = m_client->dispatchCreatePage(action);
2884     if (!mainFrame)
2885         return;
2886
2887     if (frameName != "_blank")
2888         mainFrame->tree()->setName(frameName);
2889
2890     mainFrame->page()->setOpenedByDOM();
2891     mainFrame->loader()->m_client->dispatchShow();
2892     if (!m_suppressOpenerInNewFrame)
2893         mainFrame->loader()->setOpener(frame.get());
2894     mainFrame->loader()->loadWithNavigationAction(request, NavigationAction(), false, FrameLoadTypeStandard, formState);
2895 }
2896
2897 void FrameLoader::requestFromDelegate(ResourceRequest& request, unsigned long& identifier, ResourceError& error)
2898 {
2899     ASSERT(!request.isNull());
2900
2901     identifier = 0;
2902     if (Page* page = m_frame->page()) {
2903         identifier = page->progress()->createUniqueIdentifier();
2904         notifier()->assignIdentifierToInitialRequest(identifier, m_documentLoader.get(), request);
2905     }
2906
2907     ResourceRequest newRequest(request);
2908     notifier()->dispatchWillSendRequest(m_documentLoader.get(), identifier, newRequest, ResourceResponse());
2909
2910     if (newRequest.isNull())
2911         error = cancelledError(request);
2912     else
2913         error = ResourceError();
2914
2915     request = newRequest;
2916 }
2917
2918 void FrameLoader::loadedResourceFromMemoryCache(CachedResource* resource)
2919 {
2920     Page* page = m_frame->page();
2921     if (!page)
2922         return;
2923
2924     if (!resource->sendResourceLoadCallbacks() || m_documentLoader->haveToldClientAboutLoad(resource->url()))
2925         return;
2926
2927     if (!page->areMemoryCacheClientCallsEnabled()) {
2928         InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
2929         m_documentLoader->recordMemoryCacheLoadForFutureClientNotification(resource->url());
2930         m_documentLoader->didTellClientAboutLoad(resource->url());
2931         return;
2932     }
2933
2934     ResourceRequest request(resource->url());
2935     if (m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize())) {
2936         InspectorInstrumentation::didLoadResourceFromMemoryCache(page, m_documentLoader.get(), resource);
2937         m_documentLoader->didTellClientAboutLoad(resource->url());
2938         return;
2939     }
2940
2941     unsigned long identifier;
2942     ResourceError error;
2943     requestFromDelegate(request, identifier, error);
2944     InspectorInstrumentation::markResourceAsCached(page, identifier);
2945     notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, resource->response(), 0, resource->encodedSize(), 0, error);
2946 }
2947
2948 void FrameLoader::applyUserAgent(ResourceRequest& request)
2949 {
2950     String userAgent = this->userAgent(request.url());
2951     ASSERT(!userAgent.isNull());
2952     request.setHTTPUserAgent(userAgent);
2953 }
2954
2955 bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const KURL& url)
2956 {
2957     Frame* topFrame = m_frame->tree()->top();
2958     if (m_frame == topFrame)
2959         return false;
2960
2961     if (equalIgnoringCase(content, "deny"))
2962         return true;
2963
2964     if (equalIgnoringCase(content, "sameorigin")) {
2965         RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
2966         if (!origin->isSameSchemeHostPort(topFrame->document()->securityOrigin()))
2967             return true;
2968     }
2969
2970     return false;
2971 }
2972
2973 void FrameLoader::loadProvisionalItemFromCachedPage()
2974 {
2975     DocumentLoader* provisionalLoader = provisionalDocumentLoader();
2976     LOG(PageCache, "WebCorePageCache: Loading provisional DocumentLoader %p with URL '%s' from CachedPage", provisionalDocumentLoader(), provisionalDocumentLoader()->url().string().utf8().data());
2977
2978     provisionalLoader->prepareForLoadStart();
2979
2980     m_loadingFromCachedPage = true;
2981     
2982     // Should have timing data from previous time(s) the page was shown.
2983     ASSERT(provisionalLoader->timing()->navigationStart);
2984     provisionalLoader->resetTiming();
2985     provisionalLoader->timing()->navigationStart = currentTime();    
2986
2987     provisionalLoader->setCommitted(true);
2988     commitProvisionalLoad();
2989 }
2990
2991 bool FrameLoader::shouldTreatURLAsSameAsCurrent(const KURL& url) const
2992 {
2993     if (!history()->currentItem())
2994         return false;
2995     return url == history()->currentItem()->url() || url == history()->currentItem()->originalURL();
2996 }
2997
2998 void FrameLoader::checkDidPerformFirstNavigation()
2999 {
3000     Page* page = m_frame->page();
3001     if (!page)
3002         return;
3003
3004     if (!m_didPerformFirstNavigation && page->backForward()->currentItem() && !page->backForward()->backItem() && !page->backForward()->forwardItem()) {
3005         m_didPerformFirstNavigation = true;
3006         m_client->didPerformFirstNavigation();
3007     }
3008 }
3009
3010 Frame* FrameLoader::findFrameForNavigation(const AtomicString& name)
3011 {
3012     Frame* frame = m_frame->tree()->find(name);
3013     if (!shouldAllowNavigation(frame))
3014         return 0;
3015     return frame;
3016 }
3017
3018 void FrameLoader::loadSameDocumentItem(HistoryItem* item)
3019 {
3020     ASSERT(item->documentSequenceNumber() == history()->currentItem()->documentSequenceNumber());
3021
3022     // Save user view state to the current history item here since we don't do a normal load.
3023     // FIXME: Does form state need to be saved here too?
3024     history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
3025     if (FrameView* view = m_frame->view())
3026         view->setWasScrolledByUser(false);
3027
3028     history()->setCurrentItem(item);
3029         
3030     // loadInSameDocument() actually changes the URL and notifies load delegates of a "fake" load
3031     loadInSameDocument(item->url(), item->stateObject(), false);
3032
3033     // Restore user view state from the current history item here since we don't do a normal load.
3034     history()->restoreScrollPositionAndViewState();
3035 }
3036
3037 // FIXME: This function should really be split into a couple pieces, some of
3038 // which should be methods of HistoryController and some of which should be
3039 // methods of FrameLoader.
3040 void FrameLoader::loadDifferentDocumentItem(HistoryItem* item, FrameLoadType loadType)
3041 {
3042     // Remember this item so we can traverse any child items as child frames load
3043     history()->setProvisionalItem(item);
3044
3045     if (CachedPage* cachedPage = pageCache()->get(item)) {
3046         loadWithDocumentLoader(cachedPage->documentLoader(), loadType, 0);   
3047         return;
3048     }
3049
3050     KURL itemURL = item->url();
3051     KURL itemOriginalURL = item->originalURL();
3052     KURL currentURL;
3053     if (documentLoader())
3054         currentURL = documentLoader()->url();
3055     RefPtr<FormData> formData = item->formData();
3056
3057     bool addedExtraFields = false;
3058     ResourceRequest request(itemURL);
3059
3060     if (!item->referrer().isNull())
3061         request.setHTTPReferrer(item->referrer());
3062     
3063     // If this was a repost that failed the page cache, we might try to repost the form.
3064     NavigationAction action;
3065     if (formData) {
3066         formData->generateFiles(m_frame->document());
3067
3068         request.setHTTPMethod("POST");
3069         request.setHTTPBody(formData);
3070         request.setHTTPContentType(item->formContentType());
3071         RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::createFromString(item->referrer());
3072         addHTTPOriginIfNeeded(request, securityOrigin->toString());
3073
3074         // Make sure to add extra fields to the request after the Origin header is added for the FormData case.
3075         // See https://bugs.webkit.org/show_bug.cgi?id=22194 for more discussion.
3076         addExtraFieldsToRequest(request, m_loadType, true);
3077         addedExtraFields = true;
3078         
3079         // FIXME: Slight hack to test if the NSURL cache contains the page we're going to.
3080         // We want to know this before talking to the policy delegate, since it affects whether 
3081         // we show the DoYouReallyWantToRepost nag.
3082         //
3083         // This trick has a small bug (3123893) where we might find a cache hit, but then
3084         // have the item vanish when we try to use it in the ensuing nav.  This should be
3085         // extremely rare, but in that case the user will get an error on the navigation.
3086         
3087         if (ResourceHandle::willLoadFromCache(request, m_frame))
3088             action = NavigationAction(itemURL, loadType, false);
3089         else {
3090             request.setCachePolicy(ReloadIgnoringCacheData);
3091             action = NavigationAction(itemURL, NavigationTypeFormResubmitted);
3092         }
3093     } else {
3094         switch (loadType) {
3095             case FrameLoadTypeReload:
3096             case FrameLoadTypeReloadFromOrigin:
3097                 request.setCachePolicy(ReloadIgnoringCacheData);
3098                 break;
3099             case FrameLoadTypeBack:
3100             case FrameLoadTypeForward:
3101             case FrameLoadTypeIndexedBackForward:
3102                 // If the first load within a frame is a navigation within a back/forward list that was attached 
3103                 // without any of the items being loaded then we should use the default caching policy (<rdar://problem/8131355>).
3104                 if (m_stateMachine.committedFirstRealDocumentLoad() && !itemURL.protocolIs("https"))
3105                     request.setCachePolicy(ReturnCacheDataElseLoad);
3106                 break;
3107             case FrameLoadTypeStandard:
3108             case FrameLoadTypeRedirectWithLockedBackForwardList:
3109                 break;
3110             case FrameLoadTypeSame:
3111             default:
3112                 ASSERT_NOT_REACHED();
3113         }
3114
3115         action = NavigationAction(itemOriginalURL, loadType, false);
3116     }
3117     
3118     if (!addedExtraFields)
3119         addExtraFieldsToRequest(request, m_loadType, true);
3120
3121     loadWithNavigationAction(request, action, false, loadType, 0);
3122 }
3123
3124 // Loads content into this frame, as specified by history item
3125 void FrameLoader::loadItem(HistoryItem* item, FrameLoadType loadType)
3126 {
3127     HistoryItem* currentItem = history()->currentItem();
3128     bool sameDocumentNavigation = currentItem && item->shouldDoSameDocumentNavigationTo(currentItem);
3129
3130     if (sameDocumentNavigation)
3131         loadSameDocumentItem(item);
3132     else
3133         loadDifferentDocumentItem(item, loadType);
3134 }
3135
3136 void FrameLoader::mainReceivedCompleteError(DocumentLoader* loader, const ResourceError&)
3137 {
3138     loader->setPrimaryLoadComplete(true);
3139     m_client->dispatchDidLoadMainResource(activeDocumentLoader());
3140     checkCompleted();
3141     if (m_frame->page())
3142         checkLoadComplete();
3143 }
3144
3145 ResourceError FrameLoader::cancelledError(const ResourceRequest& request) const
3146 {
3147     ResourceError error = m_client->cancelledError(request);
3148     error.setIsCancellation(true);
3149     return error;
3150 }
3151
3152 void FrameLoader::setTitle(const StringWithDirection& title)
3153 {
3154     documentLoader()->setTitle(title);
3155 }
3156
3157 String FrameLoader::referrer() const
3158 {
3159     return m_documentLoader ? m_documentLoader->request().httpReferrer() : "";
3160 }
3161
3162 void FrameLoader::dispatchDocumentElementAvailable()
3163 {
3164     m_frame->injectUserScripts(InjectAtDocumentStart);
3165     m_client->documentElementAvailable();
3166 }
3167
3168 void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
3169 {
3170     if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
3171         return;
3172
3173     Vector<DOMWrapperWorld*> worlds;
3174     ScriptController::getAllWorlds(worlds);
3175     for (size_t i = 0; i < worlds.size(); ++i)
3176         dispatchDidClearWindowObjectInWorld(worlds[i]);
3177 }
3178
3179 void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld* world)
3180 {
3181     if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript) || !m_frame->script()->existingWindowShell(world))
3182         return;
3183
3184     m_client->dispatchDidClearWindowObjectInWorld(world);
3185
3186 #if ENABLE(INSPECTOR)
3187     if (Page* page = m_frame->page())
3188         page->inspectorController()->didClearWindowObjectInWorld(m_frame, world);
3189 #endif
3190
3191     InspectorInstrumentation::didClearWindowObjectInWorld(m_frame, world);
3192 }
3193
3194 void FrameLoader::updateSandboxFlags()
3195 {
3196     SandboxFlags flags = m_forcedSandboxFlags;
3197     if (Frame* parentFrame = m_frame->tree()->parent())
3198         flags |= parentFrame->loader()->sandboxFlags();
3199     if (HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement())
3200         flags |= ownerElement->sandboxFlags();
3201
3202     if (m_sandboxFlags == flags)
3203         return;
3204
3205     m_sandboxFlags = flags;
3206
3207     for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
3208         child->loader()->updateSandboxFlags();
3209 }
3210
3211 void FrameLoader::didChangeTitle(DocumentLoader* loader)
3212 {
3213     m_client->didChangeTitle(loader);
3214
3215     if (loader == m_documentLoader) {
3216         // Must update the entries in the back-forward list too.
3217         history()->setCurrentItemTitle(loader->title());
3218         // This must go through the WebFrame because it has the right notion of the current b/f item.
3219         m_client->setTitle(loader->title(), loader->urlForHistory());
3220         m_client->setMainFrameDocumentReady(true); // update observers with new DOMDocument
3221         m_client->dispatchDidReceiveTitle(loader->title());
3222     }
3223 }
3224
3225 void FrameLoader::didChangeIcons(DocumentLoader* loader, IconType type)
3226 {
3227     if (loader == m_documentLoader)
3228         m_client->dispatchDidChangeIcons(type);
3229 }
3230
3231 void FrameLoader::dispatchDidCommitLoad()
3232 {
3233     if (m_stateMachine.creatingInitialEmptyDocument())
3234         return;
3235
3236     m_client->dispatchDidCommitLoad();
3237
3238     InspectorInstrumentation::didCommitLoad(m_frame, m_documentLoader.get());
3239 }
3240
3241 void FrameLoader::tellClientAboutPastMemoryCacheLoads()
3242 {
3243     ASSERT(m_frame->page());
3244     ASSERT(m_frame->page()->areMemoryCacheClientCallsEnabled());
3245
3246     if (!m_documentLoader)
3247         return;
3248
3249     Vector<String> pastLoads;
3250     m_documentLoader->takeMemoryCacheLoadsForClientNotification(pastLoads);
3251
3252     size_t size = pastLoads.size();
3253     for (size_t i = 0; i < size; ++i) {
3254         CachedResource* resource = memoryCache()->resourceForURL(KURL(ParsedURLString, pastLoads[i]));
3255
3256         // FIXME: These loads, loaded from cache, but now gone from the cache by the time
3257         // Page::setMemoryCacheClientCallsEnabled(true) is called, will not be seen by the client.
3258         // Consider if there's some efficient way of remembering enough to deliver this client call.
3259         // We have the URL, but not the rest of the response or the length.
3260         if (!resource)
3261             continue;
3262
3263         ResourceRequest request(resource->url());
3264         m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize());
3265     }
3266 }
3267
3268 NetworkingContext* FrameLoader::networkingContext() const
3269 {
3270     return m_networkingContext.get();
3271 }
3272
3273 bool FrameLoaderClient::hasHTMLView() const
3274 {
3275     return true;
3276 }
3277
3278 Frame* createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, bool& created)
3279 {
3280     ASSERT(!features.dialog || request.frameName().isEmpty());
3281
3282     if (!request.frameName().isEmpty() && request.frameName() != "_blank") {
3283         Frame* frame = lookupFrame->tree()->find(request.frameName());
3284         if (frame && openerFrame->loader()->shouldAllowNavigation(frame)) {
3285             if (Page* page = frame->page())
3286                 page->chrome()->focus();
3287             created = false;
3288             return frame;
3289         }
3290     }
3291
3292     // Sandboxed frames cannot open new auxiliary browsing contexts.
3293     if (isDocumentSandboxed(openerFrame, SandboxNavigation))
3294         return 0;
3295
3296     // FIXME: Setting the referrer should be the caller's responsibility.
3297     FrameLoadRequest requestWithReferrer = request;
3298     requestWithReferrer.resourceRequest().setHTTPReferrer(openerFrame->loader()->outgoingReferrer());
3299     FrameLoader::addHTTPOriginIfNeeded(requestWithReferrer.resourceRequest(), openerFrame->loader()->outgoingOrigin());
3300
3301     Page* oldPage = openerFrame->page();
3302     if (!oldPage)
3303         return 0;
3304
3305     NavigationAction action;
3306     Page* page = oldPage->chrome()->createWindow(openerFrame, requestWithReferrer, features, action);
3307     if (!page)
3308         return 0;
3309
3310     Frame* frame = page->mainFrame();
3311     if (request.frameName() != "_blank")
3312         frame->tree()->setName(request.frameName());
3313
3314     page->chrome()->setToolbarsVisible(features.toolBarVisible || features.locationBarVisible);
3315     page->chrome()->setStatusbarVisible(features.statusBarVisible);
3316     page->chrome()->setScrollbarsVisible(features.scrollbarsVisible);
3317     page->chrome()->setMenubarVisible(features.menuBarVisible);
3318     page->chrome()->setResizable(features.resizable);
3319
3320     // 'x' and 'y' specify the location of the window, while 'width' and 'height'
3321     // specify the size of the page. We can only resize the window, so
3322     // adjust for the difference between the window size and the page size.
3323
3324     FloatRect windowRect = page->chrome()->windowRect();
3325     FloatSize pageSize = page->chrome()->pageRect().size();
3326     if (features.xSet)
3327         windowRect.setX(features.x);
3328     if (features.ySet)
3329         windowRect.setY(features.y);
3330     if (features.widthSet)
3331         windowRect.setWidth(features.width + (windowRect.width() - pageSize.width()));
3332     if (features.heightSet)
3333         windowRect.setHeight(features.height + (windowRect.height() - pageSize.height()));
3334     page->chrome()->setWindowRect(windowRect);
3335
3336     page->chrome()->show();
3337
3338     created = true;
3339     return frame;
3340 }
3341
3342 } // namespace WebCore