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