initial import
[vuplus_webkit] / Source / WebCore / loader / DocumentLoader.cpp
1 /*
2  * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer. 
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution. 
13  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission. 
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include "config.h"
30 #include "DocumentLoader.h"
31
32 #include "ApplicationCacheHost.h"
33 #include "ArchiveResourceCollection.h"
34 #include "CachedPage.h"
35 #include "CachedResourceLoader.h"
36 #include "DOMWindow.h"
37 #include "Document.h"
38 #include "DocumentParser.h"
39 #include "DocumentWriter.h"
40 #include "Event.h"
41 #include "Frame.h"
42 #include "FrameLoader.h"
43 #include "FrameLoaderClient.h"
44 #include "FrameTree.h"
45 #include "HistoryItem.h"
46 #include "InspectorInstrumentation.h"
47 #include "Logging.h"
48 #include "MainResourceLoader.h"
49 #include "Page.h"
50 #include "PlatformString.h"
51 #include "Settings.h"
52 #include "SharedBuffer.h"
53 #include "TextResourceDecoder.h"
54 #include <wtf/Assertions.h>
55 #include <wtf/text/CString.h>
56 #include <wtf/unicode/Unicode.h>
57
58 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
59 #include "ArchiveFactory.h"
60 #endif
61
62 namespace WebCore {
63
64 static void cancelAll(const ResourceLoaderSet& loaders)
65 {
66     Vector<RefPtr<ResourceLoader> > loadersCopy;
67     copyToVector(loaders, loadersCopy);
68     size_t size = loadersCopy.size();
69     for (size_t i = 0; i < size; ++i)
70         loadersCopy[i]->cancel();
71 }
72
73 static void setAllDefersLoading(const ResourceLoaderSet& loaders, bool defers)
74 {
75     Vector<RefPtr<ResourceLoader> > loadersCopy;
76     copyToVector(loaders, loadersCopy);
77     size_t size = loadersCopy.size();
78     for (size_t i = 0; i < size; ++i)
79         loadersCopy[i]->setDefersLoading(defers);
80 }
81
82 DocumentLoader::DocumentLoader(const ResourceRequest& req, const SubstituteData& substituteData)
83     : m_deferMainResourceDataLoad(true)
84     , m_frame(0)
85     , m_writer(m_frame)
86     , m_originalRequest(req)
87     , m_substituteData(substituteData)
88     , m_originalRequestCopy(req)
89     , m_request(req)
90     , m_committed(false)
91     , m_isStopping(false)
92     , m_loading(false)
93     , m_gotFirstByte(false)
94     , m_primaryLoadComplete(false)
95     , m_isClientRedirect(false)
96     , m_wasOnloadHandled(false)
97     , m_stopRecordingResponses(false)
98     , m_substituteResourceDeliveryTimer(this, &DocumentLoader::substituteResourceDeliveryTimerFired)
99     , m_didCreateGlobalHistoryEntry(false)
100 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
101     , m_applicationCacheHost(adoptPtr(new ApplicationCacheHost(this)))
102 #endif
103 {
104 }
105
106 FrameLoader* DocumentLoader::frameLoader() const
107 {
108     if (!m_frame)
109         return 0;
110     return m_frame->loader();
111 }
112
113 DocumentLoader::~DocumentLoader()
114 {
115     ASSERT(!m_frame || frameLoader()->activeDocumentLoader() != this || !frameLoader()->isLoading());
116     if (m_iconLoadDecisionCallback)
117         m_iconLoadDecisionCallback->invalidate();
118     if (m_iconDataCallback)
119         m_iconDataCallback->invalidate();
120 }
121
122 PassRefPtr<SharedBuffer> DocumentLoader::mainResourceData() const
123 {
124     if (m_mainResourceData)
125         return m_mainResourceData;
126     if (m_mainResourceLoader)
127         return m_mainResourceLoader->resourceData();
128     return 0;
129 }
130
131 const ResourceRequest& DocumentLoader::originalRequest() const
132 {
133     return m_originalRequest;
134 }
135
136 const ResourceRequest& DocumentLoader::originalRequestCopy() const
137 {
138     return m_originalRequestCopy;
139 }
140
141 const ResourceRequest& DocumentLoader::request() const
142 {
143     return m_request;
144 }
145
146 ResourceRequest& DocumentLoader::request()
147 {
148     return m_request;
149 }
150
151 const KURL& DocumentLoader::url() const
152 {
153     return request().url();
154 }
155
156 void DocumentLoader::replaceRequestURLForSameDocumentNavigation(const KURL& url)
157 {
158     m_originalRequestCopy.setURL(url);
159     m_request.setURL(url);
160 }
161
162 void DocumentLoader::setRequest(const ResourceRequest& req)
163 {
164     // Replacing an unreachable URL with alternate content looks like a server-side
165     // redirect at this point, but we can replace a committed dataSource.
166     bool handlingUnreachableURL = false;
167
168     handlingUnreachableURL = m_substituteData.isValid() && !m_substituteData.failingURL().isEmpty();
169
170     if (handlingUnreachableURL)
171         m_committed = false;
172
173     // We should never be getting a redirect callback after the data
174     // source is committed, except in the unreachable URL case. It 
175     // would be a WebFoundation bug if it sent a redirect callback after commit.
176     ASSERT(!m_committed);
177
178     KURL oldURL = m_request.url();
179     m_request = req;
180
181     // Only dispatchDidReceiveServerRedirectForProvisionalLoad() if URL changed (and is non-null).
182     // Also, don't send it when replacing unreachable URLs with alternate content.
183     if (!handlingUnreachableURL && !req.url().isNull() && oldURL != req.url())
184         frameLoader()->client()->dispatchDidReceiveServerRedirectForProvisionalLoad();
185 }
186
187 void DocumentLoader::setMainDocumentError(const ResourceError& error)
188 {
189     m_mainDocumentError = error;    
190     frameLoader()->client()->setMainDocumentError(this, error);
191 }
192
193 void DocumentLoader::clearErrors()
194 {
195     m_mainDocumentError = ResourceError();
196 }
197
198 void DocumentLoader::mainReceivedError(const ResourceError& error, bool isComplete)
199 {
200     ASSERT(!error.isNull());
201
202 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
203     m_applicationCacheHost->failedLoadingMainResource();
204 #endif
205     
206     if (!frameLoader())
207         return;
208     setMainDocumentError(error);
209     if (isComplete)
210         frameLoader()->mainReceivedCompleteError(this, error);
211 }
212
213 // Cancels the data source's pending loads.  Conceptually, a data source only loads
214 // one document at a time, but one document may have many related resources. 
215 // stopLoading will stop all loads initiated by the data source, 
216 // but not loads initiated by child frames' data sources -- that's the WebFrame's job.
217 void DocumentLoader::stopLoading()
218 {
219     // In some rare cases, calling FrameLoader::stopLoading could set m_loading to false.
220     // (This can happen when there's a single XMLHttpRequest currently loading and stopLoading causes it
221     // to stop loading. Because of this, we need to save it so we don't return early.
222     bool loading = m_loading;
223     
224     if (m_committed) {
225         // Attempt to stop the frame if the document loader is loading, or if it is done loading but
226         // still  parsing. Failure to do so can cause a world leak.
227         Document* doc = m_frame->document();
228         
229         if (loading || doc->parsing())
230             m_frame->loader()->stopLoading(UnloadEventPolicyNone);
231     }
232
233     // Always cancel multipart loaders
234     cancelAll(m_multipartSubresourceLoaders);
235
236     // Appcache uses ResourceHandle directly, DocumentLoader doesn't count these loads.
237 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
238     m_applicationCacheHost->stopLoadingInFrame(m_frame);
239 #endif
240
241     if (!loading)
242         return;
243     
244     RefPtr<Frame> protectFrame(m_frame);
245     RefPtr<DocumentLoader> protectLoader(this);
246
247     m_isStopping = true;
248
249     FrameLoader* frameLoader = DocumentLoader::frameLoader();
250     
251     if (m_mainResourceLoader)
252         // Stop the main resource loader and let it send the cancelled message.
253         m_mainResourceLoader->cancel();
254     else if (!m_subresourceLoaders.isEmpty())
255         // The main resource loader already finished loading. Set the cancelled error on the 
256         // document and let the subresourceLoaders send individual cancelled messages below.
257         setMainDocumentError(frameLoader->cancelledError(m_request));
258     else
259         // If there are no resource loaders, we need to manufacture a cancelled message.
260         // (A back/forward navigation has no resource loaders because its resources are cached.)
261         mainReceivedError(frameLoader->cancelledError(m_request), true);
262     
263     stopLoadingSubresources();
264     stopLoadingPlugIns();
265     
266     m_isStopping = false;
267 }
268
269 void DocumentLoader::setupForReplace()
270 {
271     frameLoader()->setupForReplace();
272     m_committed = false;
273 }
274
275 void DocumentLoader::commitIfReady()
276 {
277     if (m_gotFirstByte && !m_committed) {
278         m_committed = true;
279         frameLoader()->commitProvisionalLoad();
280     }
281 }
282
283 void DocumentLoader::finishedLoading()
284 {
285     m_gotFirstByte = true;   
286     commitIfReady();
287     if (FrameLoader* loader = frameLoader()) {
288         loader->finishedLoadingDocument(this);
289         m_writer.end();
290     }
291 }
292
293 void DocumentLoader::commitLoad(const char* data, int length)
294 {
295     // Both unloading the old page and parsing the new page may execute JavaScript which destroys the datasource
296     // by starting a new load, so retain temporarily.
297     RefPtr<Frame> protectFrame(m_frame);
298     RefPtr<DocumentLoader> protectLoader(this);
299
300     commitIfReady();
301     FrameLoader* frameLoader = DocumentLoader::frameLoader();
302     if (!frameLoader)
303         return;
304 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
305     if (ArchiveFactory::isArchiveMimeType(response().mimeType()))
306         return;
307 #endif
308     frameLoader->client()->committedLoad(this, data, length);
309 }
310
311 void DocumentLoader::commitData(const char* bytes, size_t length)
312 {
313     // Set the text encoding.  This is safe to call multiple times.
314     bool userChosen = true;
315     String encoding = overrideEncoding();
316     if (encoding.isNull()) {
317         userChosen = false;
318         encoding = response().textEncodingName();
319     }
320     m_writer.setEncoding(encoding, userChosen);
321     ASSERT(m_frame->document()->parsing());
322     m_writer.addData(bytes, length);
323 }
324
325 bool DocumentLoader::doesProgressiveLoad(const String& MIMEType) const
326 {
327     return !frameLoader()->isReplacing() || MIMEType == "text/html";
328 }
329
330 void DocumentLoader::receivedData(const char* data, int length)
331 {    
332     m_gotFirstByte = true;
333     if (doesProgressiveLoad(m_response.mimeType()))
334         commitLoad(data, length);
335 }
336
337 void DocumentLoader::setupForReplaceByMIMEType(const String& newMIMEType)
338 {
339     if (!m_gotFirstByte)
340         return;
341     
342     String oldMIMEType = m_response.mimeType();
343     
344     if (!doesProgressiveLoad(oldMIMEType)) {
345         frameLoader()->client()->revertToProvisionalState(this);
346         setupForReplace();
347         RefPtr<SharedBuffer> resourceData = mainResourceData();
348         commitLoad(resourceData->data(), resourceData->size());
349     }
350     
351     frameLoader()->finishedLoadingDocument(this);
352     m_writer.end();
353     
354     frameLoader()->setReplacing();
355     m_gotFirstByte = false;
356     
357     if (doesProgressiveLoad(newMIMEType)) {
358         frameLoader()->client()->revertToProvisionalState(this);
359         setupForReplace();
360     }
361     
362     stopLoadingSubresources();
363     stopLoadingPlugIns();
364 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
365     clearArchiveResources();
366 #endif
367 }
368
369 void DocumentLoader::updateLoading()
370 {
371     if (!m_frame) {
372         setLoading(false);
373         return;
374     }
375     ASSERT(this == frameLoader()->activeDocumentLoader());
376     bool wasLoading = m_loading;
377     setLoading(frameLoader()->isLoading());
378
379     if (wasLoading && !m_loading) {
380         if (DOMWindow* window = m_frame->existingDOMWindow())
381             window->finishedLoading();
382     }
383 }
384
385 void DocumentLoader::setFrame(Frame* frame)
386 {
387     if (m_frame == frame)
388         return;
389     ASSERT(frame && !m_frame);
390     m_frame = frame;
391     m_writer.setFrame(frame);
392     attachToFrame();
393 }
394
395 void DocumentLoader::attachToFrame()
396 {
397     ASSERT(m_frame);
398 }
399
400 void DocumentLoader::detachFromFrame()
401 {
402     ASSERT(m_frame);
403
404 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
405     m_applicationCacheHost->setDOMApplicationCache(0);
406 #endif
407     InspectorInstrumentation::loaderDetachedFromFrame(m_frame, this);
408     m_frame = 0;
409 }
410
411 void DocumentLoader::prepareForLoadStart()
412 {
413     ASSERT(!m_isStopping);
414     setPrimaryLoadComplete(false);
415     ASSERT(frameLoader());
416     clearErrors();
417     
418     setLoading(true);
419     
420     frameLoader()->prepareForLoadStart();
421 }
422
423 void DocumentLoader::setPrimaryLoadComplete(bool flag)
424 {
425     m_primaryLoadComplete = flag;
426     if (flag) {
427         if (m_mainResourceLoader) {
428             m_mainResourceData = m_mainResourceLoader->resourceData();
429             m_mainResourceLoader = 0;
430         }
431
432         if (this == frameLoader()->activeDocumentLoader())
433             updateLoading();
434     }
435 }
436
437 bool DocumentLoader::isLoadingInAPISense() const
438 {
439     // Once a frame has loaded, we no longer need to consider subresources,
440     // but we still need to consider subframes.
441     if (frameLoader()->state() != FrameStateComplete) {
442         Document* doc = m_frame->document();
443         if ((!m_primaryLoadComplete || !m_frame->document()->loadEventFinished()) && isLoading())
444             return true;
445         if (doc->cachedResourceLoader()->requestCount())
446             return true;
447         if (DocumentParser* parser = doc->parser())
448             if (parser->processingData())
449                 return true;
450     }
451     return frameLoader()->subframeIsLoading();
452 }
453
454 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
455 void DocumentLoader::addAllArchiveResources(Archive* archive)
456 {
457     if (!m_archiveResourceCollection)
458         m_archiveResourceCollection = adoptPtr(new ArchiveResourceCollection);
459         
460     ASSERT(archive);
461     if (!archive)
462         return;
463         
464     m_archiveResourceCollection->addAllResources(archive);
465 }
466
467 // FIXME: Adding a resource directly to a DocumentLoader/ArchiveResourceCollection seems like bad design, but is API some apps rely on.
468 // Can we change the design in a manner that will let us deprecate that API without reducing functionality of those apps?
469 void DocumentLoader::addArchiveResource(PassRefPtr<ArchiveResource> resource)
470 {
471     if (!m_archiveResourceCollection)
472         m_archiveResourceCollection = adoptPtr(new ArchiveResourceCollection);
473         
474     ASSERT(resource);
475     if (!resource)
476         return;
477         
478     m_archiveResourceCollection->addResource(resource);
479 }
480
481 PassRefPtr<Archive> DocumentLoader::popArchiveForSubframe(const String& frameName, const KURL& url)
482 {
483     return m_archiveResourceCollection ? m_archiveResourceCollection->popSubframeArchive(frameName, url) : PassRefPtr<Archive>(0);
484 }
485
486 void DocumentLoader::clearArchiveResources()
487 {
488     m_archiveResourceCollection.clear();
489     m_substituteResourceDeliveryTimer.stop();
490 }
491
492 void DocumentLoader::setParsedArchiveData(PassRefPtr<SharedBuffer> data)
493 {
494     m_parsedArchiveData = data;
495 }
496
497 SharedBuffer* DocumentLoader::parsedArchiveData() const
498 {
499     return m_parsedArchiveData.get();
500 }
501 #endif // ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
502
503 ArchiveResource* DocumentLoader::archiveResourceForURL(const KURL& url) const
504 {
505     if (!m_archiveResourceCollection)
506         return 0;
507         
508     ArchiveResource* resource = m_archiveResourceCollection->archiveResourceForURL(url);
509
510     return resource && !resource->shouldIgnoreWhenUnarchiving() ? resource : 0;
511 }
512
513 PassRefPtr<ArchiveResource> DocumentLoader::mainResource() const
514 {
515     const ResourceResponse& r = response();
516     RefPtr<SharedBuffer> mainResourceBuffer = mainResourceData();
517     if (!mainResourceBuffer)
518         mainResourceBuffer = SharedBuffer::create();
519         
520     return ArchiveResource::create(mainResourceBuffer, r.url(), r.mimeType(), r.textEncodingName(), frame()->tree()->uniqueName());
521 }
522
523 PassRefPtr<ArchiveResource> DocumentLoader::subresource(const KURL& url) const
524 {
525     if (!isCommitted())
526         return 0;
527     
528     CachedResource* resource = m_frame->document()->cachedResourceLoader()->cachedResource(url);
529     if (!resource || !resource->isLoaded())
530         return archiveResourceForURL(url);
531
532     // FIXME: This has the side effect of making the resource non-purgeable.
533     // It would be better if it didn't have this permanent effect.
534     if (!resource->makePurgeable(false))
535         return 0;
536
537     RefPtr<SharedBuffer> data = resource->data();
538     if (!data)
539         return 0;
540
541     return ArchiveResource::create(data.release(), url, resource->response());
542 }
543
544 void DocumentLoader::getSubresources(Vector<PassRefPtr<ArchiveResource> >& subresources) const
545 {
546     if (!isCommitted())
547         return;
548
549     Document* document = m_frame->document();
550
551     const CachedResourceLoader::DocumentResourceMap& allResources = document->cachedResourceLoader()->allCachedResources();
552     CachedResourceLoader::DocumentResourceMap::const_iterator end = allResources.end();
553     for (CachedResourceLoader::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it) {
554         RefPtr<ArchiveResource> subresource = this->subresource(KURL(ParsedURLString, it->second->url()));
555         if (subresource)
556             subresources.append(subresource.release());
557     }
558
559     return;
560 }
561
562 void DocumentLoader::deliverSubstituteResourcesAfterDelay()
563 {
564     if (m_pendingSubstituteResources.isEmpty())
565         return;
566     ASSERT(m_frame && m_frame->page());
567     if (m_frame->page()->defersLoading())
568         return;
569     if (!m_substituteResourceDeliveryTimer.isActive())
570         m_substituteResourceDeliveryTimer.startOneShot(0);
571 }
572
573 void DocumentLoader::substituteResourceDeliveryTimerFired(Timer<DocumentLoader>*)
574 {
575     if (m_pendingSubstituteResources.isEmpty())
576         return;
577     ASSERT(m_frame && m_frame->page());
578     if (m_frame->page()->defersLoading())
579         return;
580
581     SubstituteResourceMap copy;
582     copy.swap(m_pendingSubstituteResources);
583
584     SubstituteResourceMap::const_iterator end = copy.end();
585     for (SubstituteResourceMap::const_iterator it = copy.begin(); it != end; ++it) {
586         RefPtr<ResourceLoader> loader = it->first;
587         SubstituteResource* resource = it->second.get();
588         
589         if (resource) {
590             SharedBuffer* data = resource->data();
591         
592             loader->didReceiveResponse(resource->response());
593
594             // Calling ResourceLoader::didReceiveResponse can end up cancelling the load,
595             // so we need to check if the loader has reached its terminal state.
596             if (loader->reachedTerminalState())
597                 return;
598
599             loader->didReceiveData(data->data(), data->size(), data->size(), true);
600
601             // Calling ResourceLoader::didReceiveData can end up cancelling the load,
602             // so we need to check if the loader has reached its terminal state.
603             if (loader->reachedTerminalState())
604                 return;
605
606             loader->didFinishLoading(0);
607         } else {
608             // A null resource means that we should fail the load.
609             // FIXME: Maybe we should use another error here - something like "not in cache".
610             loader->didFail(loader->cannotShowURLError());
611         }
612     }
613 }
614
615 #ifndef NDEBUG
616 bool DocumentLoader::isSubstituteLoadPending(ResourceLoader* loader) const
617 {
618     return m_pendingSubstituteResources.contains(loader);
619 }
620 #endif
621
622 void DocumentLoader::cancelPendingSubstituteLoad(ResourceLoader* loader)
623 {
624     if (m_pendingSubstituteResources.isEmpty())
625         return;
626     m_pendingSubstituteResources.remove(loader);
627     if (m_pendingSubstituteResources.isEmpty())
628         m_substituteResourceDeliveryTimer.stop();
629 }
630
631 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
632 bool DocumentLoader::scheduleArchiveLoad(ResourceLoader* loader, const ResourceRequest& request, const KURL& originalURL)
633 {
634     if (request.url() == originalURL) {
635         if (ArchiveResource* resource = archiveResourceForURL(originalURL)) {
636             m_pendingSubstituteResources.set(loader, resource);
637             deliverSubstituteResourcesAfterDelay();
638             return true;
639         }
640     }
641
642     Archive* archive = frameLoader()->archive();
643     if (!archive)
644         return false;
645
646     switch (archive->type()) {
647 #if ENABLE(WEB_ARCHIVE)
648     case Archive::WebArchive:
649         // WebArchiveDebugMode means we fail loads instead of trying to fetch them from the network if they're not in the archive.
650         return m_frame->settings()->webArchiveDebugModeEnabled() && ArchiveFactory::isArchiveMimeType(responseMIMEType());
651 #endif
652 #if ENABLE(MHTML)
653     case Archive::MHTML:
654         return true; // Always fail the load for resources not included in the MHTML.
655 #endif
656     default:
657         return false;
658     }
659 }
660 #endif // ENABLE(WEB_ARCHIVE)
661
662 void DocumentLoader::addResponse(const ResourceResponse& r)
663 {
664     if (!m_stopRecordingResponses)
665         m_responses.append(r);
666 }
667
668 void DocumentLoader::stopRecordingResponses()
669 {
670     m_stopRecordingResponses = true;
671 }
672
673 void DocumentLoader::setTitle(const StringWithDirection& title)
674 {
675     if (title.isEmpty())
676         return;
677
678     if (m_pageTitle != title) {
679         frameLoader()->willChangeTitle(this);
680         m_pageTitle = title;
681         frameLoader()->didChangeTitle(this);
682     }
683 }
684
685 IconURL DocumentLoader::iconURL(IconType iconType) const
686 {
687     return m_iconURLs[toIconIndex(iconType)];
688 }
689
690 void DocumentLoader::setIconURL(const IconURL& url)
691 {
692     if (url.m_iconURL.isEmpty())
693         return;
694
695     if (iconURL(url.m_iconType).m_iconURL != url.m_iconURL) {
696         m_iconURLs[toIconIndex(url.m_iconType)] = url;
697         frameLoader()->didChangeIcons(this, url.m_iconType);
698     }
699 }
700
701 KURL DocumentLoader::urlForHistory() const
702 {
703     // Return the URL to be used for history and B/F list.
704     // Returns nil for WebDataProtocol URLs that aren't alternates 
705     // for unreachable URLs, because these can't be stored in history.
706     if (m_substituteData.isValid())
707         return unreachableURL();
708
709     return m_originalRequestCopy.url();
710 }
711
712 bool DocumentLoader::urlForHistoryReflectsFailure() const
713 {
714     return m_substituteData.isValid() || m_response.httpStatusCode() >= 400;
715 }
716
717 const KURL& DocumentLoader::originalURL() const
718 {
719     return m_originalRequestCopy.url();
720 }
721
722 const KURL& DocumentLoader::requestURL() const
723 {
724     return request().url();
725 }
726
727 const KURL& DocumentLoader::responseURL() const
728 {
729     return m_response.url();
730 }
731
732 KURL DocumentLoader::documentURL() const
733 {
734     KURL url = substituteData().responseURL();
735     if (url.isEmpty())
736         url = requestURL();
737     if (url.isEmpty())
738         url = responseURL();
739     if (url.isEmpty())
740         url = blankURL();
741     return url;
742 }
743
744 const String& DocumentLoader::responseMIMEType() const
745 {
746     return m_response.mimeType();
747 }
748
749 const KURL& DocumentLoader::unreachableURL() const
750 {
751     return m_substituteData.failingURL();
752 }
753
754 void DocumentLoader::setDefersLoading(bool defers)
755 {
756     if (m_mainResourceLoader)
757         m_mainResourceLoader->setDefersLoading(defers);
758     setAllDefersLoading(m_subresourceLoaders, defers);
759     setAllDefersLoading(m_plugInStreamLoaders, defers);
760     if (!defers)
761         deliverSubstituteResourcesAfterDelay();
762 }
763
764 void DocumentLoader::stopLoadingPlugIns()
765 {
766     cancelAll(m_plugInStreamLoaders);
767 }
768
769 void DocumentLoader::stopLoadingSubresources()
770 {
771     cancelAll(m_subresourceLoaders);
772 }
773
774 void DocumentLoader::addSubresourceLoader(ResourceLoader* loader)
775 {
776     m_subresourceLoaders.add(loader);
777     setLoading(true);
778 }
779
780 void DocumentLoader::removeSubresourceLoader(ResourceLoader* loader)
781 {
782     m_subresourceLoaders.remove(loader);
783     updateLoading();
784     if (Frame* frame = m_frame)
785         frame->loader()->checkLoadComplete();
786 }
787
788 void DocumentLoader::addPlugInStreamLoader(ResourceLoader* loader)
789 {
790     m_plugInStreamLoaders.add(loader);
791     setLoading(true);
792 }
793
794 void DocumentLoader::removePlugInStreamLoader(ResourceLoader* loader)
795 {
796     m_plugInStreamLoaders.remove(loader);
797     updateLoading();
798 }
799
800 bool DocumentLoader::isLoadingMainResource() const
801 {
802     return !!m_mainResourceLoader;
803 }
804
805 bool DocumentLoader::isLoadingSubresources() const
806 {
807     return !m_subresourceLoaders.isEmpty();
808 }
809
810 bool DocumentLoader::isLoadingPlugIns() const
811 {
812     return !m_plugInStreamLoaders.isEmpty();
813 }
814
815 bool DocumentLoader::isLoadingMultipartContent() const
816 {
817     return m_mainResourceLoader && m_mainResourceLoader->isLoadingMultipartContent();
818 }
819
820 bool DocumentLoader::startLoadingMainResource(unsigned long identifier)
821 {
822     ASSERT(!m_mainResourceLoader);
823     m_mainResourceLoader = MainResourceLoader::create(m_frame);
824     m_mainResourceLoader->setIdentifier(identifier);
825
826     // FIXME: Is there any way the extra fields could have not been added by now?
827     // If not, it would be great to remove this line of code.
828     frameLoader()->addExtraFieldsToMainResourceRequest(m_request);
829
830     if (!m_mainResourceLoader->load(m_request, m_substituteData)) {
831         // FIXME: If this should really be caught, we should just ASSERT this doesn't happen;
832         // should it be caught by other parts of WebKit or other parts of the app?
833         LOG_ERROR("could not create WebResourceHandle for URL %s -- should be caught by policy handler level", m_request.url().string().ascii().data());
834         m_mainResourceLoader = 0;
835         return false;
836     }
837
838     return true;
839 }
840
841 void DocumentLoader::cancelMainResourceLoad(const ResourceError& error)
842 {
843     m_mainResourceLoader->cancel(error);
844 }
845
846 void DocumentLoader::subresourceLoaderFinishedLoadingOnePart(ResourceLoader* loader)
847 {
848     m_multipartSubresourceLoaders.add(loader);
849     m_subresourceLoaders.remove(loader);
850     updateLoading();
851     if (Frame* frame = m_frame)
852         frame->loader()->checkLoadComplete();    
853 }
854
855 void DocumentLoader::transferLoadingResourcesFromPage(Page* oldPage)
856 {
857     ASSERT(oldPage != m_frame->page());
858
859     FrameLoader* loader = frameLoader();
860     ASSERT(loader);
861
862     if (isLoadingMainResource())
863         loader->dispatchTransferLoadingResourceFromPage(m_mainResourceLoader.get(), originalRequest(), oldPage);
864
865     if (isLoadingSubresources()) {
866         ResourceLoaderSet::const_iterator it = m_subresourceLoaders.begin();
867         ResourceLoaderSet::const_iterator end = m_subresourceLoaders.end();
868         for (; it != end; ++it)
869             loader->dispatchTransferLoadingResourceFromPage((*it).get(), (*it)->originalRequest(), oldPage);
870     }
871 }
872
873 void DocumentLoader::iconLoadDecisionAvailable()
874 {
875     if (m_frame)
876         m_frame->loader()->icon()->loadDecisionReceived(iconDatabase().synchronousLoadDecisionForIconURL(frameLoader()->icon()->url(), this));
877 }
878
879 static void iconLoadDecisionCallback(IconLoadDecision decision, void* context)
880 {
881     static_cast<DocumentLoader*>(context)->continueIconLoadWithDecision(decision);
882 }
883
884 void DocumentLoader::getIconLoadDecisionForIconURL(const String& urlString)
885 {
886     if (m_iconLoadDecisionCallback)
887         m_iconLoadDecisionCallback->invalidate();
888     m_iconLoadDecisionCallback = IconLoadDecisionCallback::create(this, iconLoadDecisionCallback);
889     iconDatabase().loadDecisionForIconURL(urlString, m_iconLoadDecisionCallback);
890 }
891
892 void DocumentLoader::continueIconLoadWithDecision(IconLoadDecision decision)
893 {
894     ASSERT(m_iconLoadDecisionCallback);
895     m_iconLoadDecisionCallback = 0;
896     if (m_frame)
897         m_frame->loader()->icon()->continueLoadWithDecision(decision);
898 }
899
900 static void iconDataCallback(SharedBuffer*, void*)
901 {
902     // FIXME: Implement this once we know what parts of WebCore actually need the icon data returned.
903 }
904
905 void DocumentLoader::getIconDataForIconURL(const String& urlString)
906 {   
907     if (m_iconDataCallback)
908         m_iconDataCallback->invalidate();
909     m_iconDataCallback = IconDataCallback::create(this, iconDataCallback);
910     iconDatabase().iconDataForIconURL(urlString, m_iconDataCallback);
911 }
912
913 void DocumentLoader::handledOnloadEvents()
914 {
915     m_wasOnloadHandled = true;
916 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
917     applicationCacheHost()->stopDeferringEvents();
918 #endif
919 }
920
921 } // namespace WebCore