[BlackBerry] Set correct ResourceRequest target type.
[WebKit-https.git] / Source / WebCore / loader / appcache / ApplicationCacheGroup.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2010 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  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27 #include "ApplicationCacheGroup.h"
28
29 #include "ApplicationCache.h"
30 #include "ApplicationCacheHost.h"
31 #include "ApplicationCacheResource.h"
32 #include "ApplicationCacheStorage.h"
33 #include "Chrome.h"
34 #include "ChromeClient.h"
35 #include "Console.h"
36 #include "DOMApplicationCache.h"
37 #include "DOMWindow.h"
38 #include "DocumentLoader.h"
39 #include "Frame.h"
40 #include "FrameLoader.h"
41 #include "FrameLoaderClient.h"
42 #include "InspectorInstrumentation.h"
43 #include "MainResourceLoader.h"
44 #include "ManifestParser.h"
45 #include "Page.h"
46 #include "ScriptProfile.h"
47 #include "SecurityOrigin.h"
48 #include "Settings.h"
49 #include <wtf/HashMap.h>
50 #include <wtf/MainThread.h>
51 #include <wtf/UnusedParam.h>
52
53 #if ENABLE(INSPECTOR)
54 #include "ProgressTracker.h"
55 #endif
56
57 namespace WebCore {
58
59 ApplicationCacheGroup::ApplicationCacheGroup(const KURL& manifestURL, bool isCopy)
60     : m_manifestURL(manifestURL)
61     , m_origin(SecurityOrigin::create(manifestURL))
62     , m_updateStatus(Idle)
63     , m_downloadingPendingMasterResourceLoadersCount(0)
64     , m_progressTotal(0)
65     , m_progressDone(0)
66     , m_frame(0)
67     , m_storageID(0)
68     , m_isObsolete(false)
69     , m_completionType(None)
70     , m_isCopy(isCopy)
71     , m_calledReachedMaxAppCacheSize(false)
72     , m_availableSpaceInQuota(ApplicationCacheStorage::unknownQuota())
73     , m_originQuotaExceededPreviously(false)
74 {
75 }
76
77 ApplicationCacheGroup::~ApplicationCacheGroup()
78 {
79     if (m_isCopy) {
80         ASSERT(m_newestCache);
81         ASSERT(m_caches.size() == 1);
82         ASSERT(m_caches.contains(m_newestCache.get()));
83         ASSERT(!m_cacheBeingUpdated);
84         ASSERT(m_associatedDocumentLoaders.isEmpty());
85         ASSERT(m_pendingMasterResourceLoaders.isEmpty());
86         ASSERT(m_newestCache->group() == this);
87         
88         return;
89     }
90                
91     ASSERT(!m_newestCache);
92     ASSERT(m_caches.isEmpty());
93     
94     stopLoading();
95     
96     cacheStorage().cacheGroupDestroyed(this);
97 }
98     
99 ApplicationCache* ApplicationCacheGroup::cacheForMainRequest(const ResourceRequest& request, DocumentLoader*)
100 {
101     if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request))
102         return 0;
103
104     KURL url(request.url());
105     if (url.hasFragmentIdentifier())
106         url.removeFragmentIdentifier();
107
108     if (ApplicationCacheGroup* group = cacheStorage().cacheGroupForURL(url)) {
109         ASSERT(group->newestCache());
110         ASSERT(!group->isObsolete());
111         
112         return group->newestCache();
113     }
114     
115     return 0;
116 }
117     
118 ApplicationCache* ApplicationCacheGroup::fallbackCacheForMainRequest(const ResourceRequest& request, DocumentLoader*)
119 {
120     if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request))
121         return 0;
122
123     KURL url(request.url());
124     if (url.hasFragmentIdentifier())
125         url.removeFragmentIdentifier();
126
127     if (ApplicationCacheGroup* group = cacheStorage().fallbackCacheGroupForURL(url)) {
128         ASSERT(group->newestCache());
129         ASSERT(!group->isObsolete());
130
131         return group->newestCache();
132     }
133     
134     return 0;
135 }
136
137 void ApplicationCacheGroup::selectCache(Frame* frame, const KURL& passedManifestURL)
138 {
139     ASSERT(frame && frame->page());
140     
141     if (!frame->settings() || !frame->settings()->offlineWebApplicationCacheEnabled())
142         return;
143     
144     DocumentLoader* documentLoader = frame->loader()->documentLoader();
145     ASSERT(!documentLoader->applicationCacheHost()->applicationCache());
146
147     if (passedManifestURL.isNull()) {
148         selectCacheWithoutManifestURL(frame);        
149         return;
150     }
151
152     KURL manifestURL(passedManifestURL);
153     if (manifestURL.hasFragmentIdentifier())
154         manifestURL.removeFragmentIdentifier();
155
156     ApplicationCache* mainResourceCache = documentLoader->applicationCacheHost()->mainResourceApplicationCache();
157     
158     if (mainResourceCache) {
159         if (manifestURL == mainResourceCache->group()->m_manifestURL) {
160             // The cache may have gotten obsoleted after we've loaded from it, but before we parsed the document and saw cache manifest.
161             if (mainResourceCache->group()->isObsolete())
162                 return;
163             mainResourceCache->group()->associateDocumentLoaderWithCache(documentLoader, mainResourceCache);
164             mainResourceCache->group()->update(frame, ApplicationCacheUpdateWithBrowsingContext);
165         } else {
166             // The main resource was loaded from cache, so the cache must have an entry for it. Mark it as foreign.
167             KURL resourceURL(documentLoader->responseURL());
168             if (resourceURL.hasFragmentIdentifier())
169                 resourceURL.removeFragmentIdentifier();
170             ApplicationCacheResource* resource = mainResourceCache->resourceForURL(resourceURL);
171             bool inStorage = resource->storageID();
172             resource->addType(ApplicationCacheResource::Foreign);
173             if (inStorage)
174                 cacheStorage().storeUpdatedType(resource, mainResourceCache);
175
176             // Restart the current navigation from the top of the navigation algorithm, undoing any changes that were made
177             // as part of the initial load.
178             // The navigation will not result in the same resource being loaded, because "foreign" entries are never picked during navigation.
179             frame->navigationScheduler()->scheduleLocationChange(frame->document()->securityOrigin(), documentLoader->url(), frame->loader()->referrer());
180         }
181         
182         return;
183     }
184     
185     // The resource was loaded from the network, check if it is a HTTP/HTTPS GET.    
186     const ResourceRequest& request = frame->loader()->activeDocumentLoader()->request();
187
188     if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request))
189         return;
190
191     // Check that the resource URL has the same scheme/host/port as the manifest URL.
192     if (!protocolHostAndPortAreEqual(manifestURL, request.url()))
193         return;
194
195     // Don't change anything on disk if private browsing is enabled.
196     if (frame->settings()->privateBrowsingEnabled()) {
197         postListenerTask(ApplicationCacheHost::CHECKING_EVENT, documentLoader);
198         postListenerTask(ApplicationCacheHost::ERROR_EVENT, documentLoader);
199         return;
200     }
201
202     ApplicationCacheGroup* group = cacheStorage().findOrCreateCacheGroup(manifestURL);
203
204     documentLoader->applicationCacheHost()->setCandidateApplicationCacheGroup(group);
205     group->m_pendingMasterResourceLoaders.add(documentLoader);
206     group->m_downloadingPendingMasterResourceLoadersCount++;
207
208     ASSERT(!group->m_cacheBeingUpdated || group->m_updateStatus != Idle);
209     group->update(frame, ApplicationCacheUpdateWithBrowsingContext);
210 }
211
212 void ApplicationCacheGroup::selectCacheWithoutManifestURL(Frame* frame)
213 {
214     if (!frame->settings() || !frame->settings()->offlineWebApplicationCacheEnabled())
215         return;
216
217     DocumentLoader* documentLoader = frame->loader()->documentLoader();
218     ASSERT(!documentLoader->applicationCacheHost()->applicationCache());
219
220     ApplicationCache* mainResourceCache = documentLoader->applicationCacheHost()->mainResourceApplicationCache();
221
222     if (mainResourceCache) {
223         mainResourceCache->group()->associateDocumentLoaderWithCache(documentLoader, mainResourceCache);
224         mainResourceCache->group()->update(frame, ApplicationCacheUpdateWithBrowsingContext);
225     }
226 }
227
228 void ApplicationCacheGroup::finishedLoadingMainResource(DocumentLoader* loader)
229 {
230     ASSERT(m_pendingMasterResourceLoaders.contains(loader));
231     ASSERT(m_completionType == None || m_pendingEntries.isEmpty());
232     KURL url = loader->url();
233     if (url.hasFragmentIdentifier())
234         url.removeFragmentIdentifier();
235
236     switch (m_completionType) {
237     case None:
238         // The main resource finished loading before the manifest was ready. It will be handled via dispatchMainResources() later.
239         return;
240     case NoUpdate:
241         ASSERT(!m_cacheBeingUpdated);
242         associateDocumentLoaderWithCache(loader, m_newestCache.get());
243
244         if (ApplicationCacheResource* resource = m_newestCache->resourceForURL(url)) {
245             if (!(resource->type() & ApplicationCacheResource::Master)) {
246                 resource->addType(ApplicationCacheResource::Master);
247                 ASSERT(!resource->storageID());
248             }
249         } else
250             m_newestCache->addResource(ApplicationCacheResource::create(url, loader->response(), ApplicationCacheResource::Master, loader->mainResourceData()));
251
252         break;
253     case Failure:
254         // Cache update has been a failure, so there is no reason to keep the document associated with the incomplete cache
255         // (its main resource was not cached yet, so it is likely that the application changed significantly server-side).
256         ASSERT(!m_cacheBeingUpdated); // Already cleared out by stopLoading().
257         loader->applicationCacheHost()->setApplicationCache(0); // Will unset candidate, too.
258         m_associatedDocumentLoaders.remove(loader);
259         postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader);
260         break;
261     case Completed:
262         ASSERT(m_associatedDocumentLoaders.contains(loader));
263
264         if (ApplicationCacheResource* resource = m_cacheBeingUpdated->resourceForURL(url)) {
265             if (!(resource->type() & ApplicationCacheResource::Master)) {
266                 resource->addType(ApplicationCacheResource::Master);
267                 ASSERT(!resource->storageID());
268             }
269         } else
270             m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, loader->response(), ApplicationCacheResource::Master, loader->mainResourceData()));
271         // The "cached" event will be posted to all associated documents once update is complete.
272         break;
273     }
274
275     ASSERT(m_downloadingPendingMasterResourceLoadersCount > 0);
276     m_downloadingPendingMasterResourceLoadersCount--;
277     checkIfLoadIsComplete();
278 }
279
280 void ApplicationCacheGroup::failedLoadingMainResource(DocumentLoader* loader)
281 {
282     ASSERT(m_pendingMasterResourceLoaders.contains(loader));
283     ASSERT(m_completionType == None || m_pendingEntries.isEmpty());
284
285     switch (m_completionType) {
286     case None:
287         // The main resource finished loading before the manifest was ready. It will be handled via dispatchMainResources() later.
288         return;
289     case NoUpdate:
290         ASSERT(!m_cacheBeingUpdated);
291
292         // The manifest didn't change, and we have a relevant cache - but the main resource download failed mid-way, so it cannot be stored to the cache,
293         // and the loader does not get associated to it. If there are other main resources being downloaded for this cache group, they may still succeed.
294         postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader);
295
296         break;
297     case Failure:
298         // Cache update failed, too.
299         ASSERT(!m_cacheBeingUpdated); // Already cleared out by stopLoading().
300         ASSERT(!loader->applicationCacheHost()->applicationCache() || loader->applicationCacheHost()->applicationCache() == m_cacheBeingUpdated);
301
302         loader->applicationCacheHost()->setApplicationCache(0); // Will unset candidate, too.
303         m_associatedDocumentLoaders.remove(loader);
304         postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader);
305         break;
306     case Completed:
307         // The cache manifest didn't list this main resource, and all cache entries were already updated successfully - but the main resource failed to load,
308         // so it cannot be stored to the cache. If there are other main resources being downloaded for this cache group, they may still succeed.
309         ASSERT(m_associatedDocumentLoaders.contains(loader));
310         ASSERT(loader->applicationCacheHost()->applicationCache() == m_cacheBeingUpdated);
311         ASSERT(!loader->applicationCacheHost()->candidateApplicationCacheGroup());
312         m_associatedDocumentLoaders.remove(loader);
313         loader->applicationCacheHost()->setApplicationCache(0);
314
315         postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader);
316
317         break;
318     }
319
320     ASSERT(m_downloadingPendingMasterResourceLoadersCount > 0);
321     m_downloadingPendingMasterResourceLoadersCount--;
322     checkIfLoadIsComplete();
323 }
324
325 void ApplicationCacheGroup::stopLoading()
326 {
327     if (m_manifestHandle) {
328         ASSERT(!m_currentHandle);
329
330         ASSERT(m_manifestHandle->client() == this);
331         m_manifestHandle->setClient(0);
332
333         m_manifestHandle->cancel();
334         m_manifestHandle = 0;
335     }
336     
337     if (m_currentHandle) {
338         ASSERT(!m_manifestHandle);
339         ASSERT(m_cacheBeingUpdated);
340
341         ASSERT(m_currentHandle->client() == this);
342         m_currentHandle->setClient(0);
343
344         m_currentHandle->cancel();
345         m_currentHandle = 0;
346     }    
347
348     // FIXME: Resetting just a tiny part of the state in this function is confusing. Callers have to take care of a lot more.
349     m_cacheBeingUpdated = 0;
350     m_pendingEntries.clear();
351 }    
352
353 void ApplicationCacheGroup::disassociateDocumentLoader(DocumentLoader* loader)
354 {
355     HashSet<DocumentLoader*>::iterator it = m_associatedDocumentLoaders.find(loader);
356     if (it != m_associatedDocumentLoaders.end())
357         m_associatedDocumentLoaders.remove(it);
358
359     m_pendingMasterResourceLoaders.remove(loader);
360
361     loader->applicationCacheHost()->setApplicationCache(0); // Will set candidate to 0, too.
362
363     if (!m_associatedDocumentLoaders.isEmpty() || !m_pendingMasterResourceLoaders.isEmpty())
364         return;
365
366     if (m_caches.isEmpty()) {
367         // There is an initial cache attempt in progress.
368         ASSERT(!m_newestCache);
369         // Delete ourselves, causing the cache attempt to be stopped.
370         delete this;
371         return;
372     }
373
374     ASSERT(m_caches.contains(m_newestCache.get()));
375
376     // Release our reference to the newest cache. This could cause us to be deleted.
377     // Any ongoing updates will be stopped from destructor.
378     m_newestCache.release();
379 }
380
381 void ApplicationCacheGroup::cacheDestroyed(ApplicationCache* cache)
382 {
383     if (!m_caches.contains(cache))
384         return;
385     
386     m_caches.remove(cache);
387
388     if (m_caches.isEmpty()) {
389         ASSERT(m_associatedDocumentLoaders.isEmpty());
390         ASSERT(m_pendingMasterResourceLoaders.isEmpty());
391         delete this;
392     }
393 }
394
395 void ApplicationCacheGroup::stopLoadingInFrame(Frame* frame)
396 {
397     if (frame != m_frame)
398         return;
399
400     cacheUpdateFailed();
401 }
402
403 void ApplicationCacheGroup::setNewestCache(PassRefPtr<ApplicationCache> newestCache)
404 {
405     m_newestCache = newestCache;
406
407     m_caches.add(m_newestCache.get());
408     m_newestCache->setGroup(this);
409 }
410
411 void ApplicationCacheGroup::makeObsolete()
412 {
413     if (isObsolete())
414         return;
415
416     m_isObsolete = true;
417     cacheStorage().cacheGroupMadeObsolete(this);
418     ASSERT(!m_storageID);
419 }
420
421 void ApplicationCacheGroup::update(Frame* frame, ApplicationCacheUpdateOption updateOption)
422 {
423     if (m_updateStatus == Checking || m_updateStatus == Downloading) {
424         if (updateOption == ApplicationCacheUpdateWithBrowsingContext) {
425             postListenerTask(ApplicationCacheHost::CHECKING_EVENT, frame->loader()->documentLoader());
426             if (m_updateStatus == Downloading)
427                 postListenerTask(ApplicationCacheHost::DOWNLOADING_EVENT, frame->loader()->documentLoader());
428         }
429         return;
430     }
431
432     // Don't change anything on disk if private browsing is enabled.
433     if (!frame->settings() || frame->settings()->privateBrowsingEnabled()) {
434         ASSERT(m_pendingMasterResourceLoaders.isEmpty());
435         ASSERT(m_pendingEntries.isEmpty());
436         ASSERT(!m_cacheBeingUpdated);
437         postListenerTask(ApplicationCacheHost::CHECKING_EVENT, frame->loader()->documentLoader());
438         postListenerTask(ApplicationCacheHost::NOUPDATE_EVENT, frame->loader()->documentLoader());
439         return;
440     }
441
442     ASSERT(!m_frame);
443     m_frame = frame;
444
445     setUpdateStatus(Checking);
446
447     postListenerTask(ApplicationCacheHost::CHECKING_EVENT, m_associatedDocumentLoaders);
448     if (!m_newestCache) {
449         ASSERT(updateOption == ApplicationCacheUpdateWithBrowsingContext);
450         postListenerTask(ApplicationCacheHost::CHECKING_EVENT, frame->loader()->documentLoader());
451     }
452     
453     ASSERT(!m_manifestHandle);
454     ASSERT(!m_manifestResource);
455     ASSERT(!m_currentHandle);
456     ASSERT(!m_currentResource);
457     ASSERT(m_completionType == None);
458
459     // FIXME: Handle defer loading
460     m_manifestHandle = createResourceHandle(m_manifestURL, m_newestCache ? m_newestCache->manifestResource() : 0);
461 }
462
463 void ApplicationCacheGroup::abort(Frame* frame)
464 {
465     if (m_updateStatus == Idle)
466         return;
467     ASSERT(m_updateStatus == Checking || (m_updateStatus == Downloading && m_cacheBeingUpdated));
468
469     if (m_completionType != None)
470         return;
471
472     frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, TipMessageLevel, "Application Cache download process was aborted.");
473     cacheUpdateFailed();
474 }
475
476 PassRefPtr<ResourceHandle> ApplicationCacheGroup::createResourceHandle(const KURL& url, ApplicationCacheResource* newestCachedResource)
477 {
478     ResourceRequest request(url);
479     m_frame->loader()->applyUserAgent(request);
480     request.setHTTPHeaderField("Cache-Control", "max-age=0");
481
482     if (newestCachedResource) {
483         const String& lastModified = newestCachedResource->response().httpHeaderField("Last-Modified");
484         const String& eTag = newestCachedResource->response().httpHeaderField("ETag");
485         if (!lastModified.isEmpty() || !eTag.isEmpty()) {
486             if (!lastModified.isEmpty())
487                 request.setHTTPHeaderField("If-Modified-Since", lastModified);
488             if (!eTag.isEmpty())
489                 request.setHTTPHeaderField("If-None-Match", eTag);
490         }
491     }
492
493 #if PLATFORM(BLACKBERRY)
494     ResourceRequest::TargetType target = ResourceRequest::TargetIsUnspecified;
495     if (newestCachedResource) {
496         const String& mimeType = newestCachedResource->response().mimeType();
497         if (!mimeType.isEmpty())
498             target = ResourceRequest::targetTypeFromMimeType(mimeType);
499     }
500     if (target == ResourceRequest::TargetIsUnspecified) {
501         String mimeType = mimeTypeFromDataURL(url);
502         if (!mimeType.isEmpty())
503             target = ResourceRequest::targetTypeFromMimeType(mimeType);
504     }
505
506     request.setTargetType(target);
507 #endif
508
509     RefPtr<ResourceHandle> handle = ResourceHandle::create(m_frame->loader()->networkingContext(), request, this, false, true);
510 #if ENABLE(INSPECTOR)
511     // Because willSendRequest only gets called during redirects, we initialize
512     // the identifier and the first willSendRequest here.
513     m_currentResourceIdentifier = m_frame->page()->progress()->createUniqueIdentifier();
514     ResourceResponse redirectResponse = ResourceResponse();
515     InspectorInstrumentation::willSendRequest(m_frame, m_currentResourceIdentifier, m_frame->loader()->documentLoader(), request, redirectResponse);
516 #endif
517     return handle;
518 }
519
520 void ApplicationCacheGroup::didReceiveResponse(ResourceHandle* handle, const ResourceResponse& response)
521 {
522 #if ENABLE(INSPECTOR)
523     DocumentLoader* loader = (handle == m_manifestHandle) ? 0 : m_frame->loader()->documentLoader();
524     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_frame, m_currentResourceIdentifier, response);
525     InspectorInstrumentation::didReceiveResourceResponse(cookie, m_currentResourceIdentifier, loader, response);
526 #endif
527
528     if (handle == m_manifestHandle) {
529         didReceiveManifestResponse(response);
530         return;
531     }
532     
533     ASSERT(handle == m_currentHandle);
534
535     KURL url(handle->firstRequest().url());
536     if (url.hasFragmentIdentifier())
537         url.removeFragmentIdentifier();
538     
539     ASSERT(!m_currentResource);
540     ASSERT(m_pendingEntries.contains(url));
541     
542     unsigned type = m_pendingEntries.get(url);
543     
544     // If this is an initial cache attempt, we should not get master resources delivered here.
545     if (!m_newestCache)
546         ASSERT(!(type & ApplicationCacheResource::Master));
547
548     if (m_newestCache && response.httpStatusCode() == 304) { // Not modified.
549         ApplicationCacheResource* newestCachedResource = m_newestCache->resourceForURL(url);
550         if (newestCachedResource) {
551             m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, newestCachedResource->response(), type, newestCachedResource->data(), newestCachedResource->path()));
552             m_pendingEntries.remove(m_currentHandle->firstRequest().url());
553             m_currentHandle->cancel();
554             m_currentHandle = 0;
555             // Load the next resource, if any.
556             startLoadingEntry();
557             return;
558         }
559         // The server could return 304 for an unconditional request - in this case, we handle the response as a normal error.
560     }
561
562     if (response.httpStatusCode() / 100 != 2 || response.url() != m_currentHandle->firstRequest().url()) {
563         if ((type & ApplicationCacheResource::Explicit) || (type & ApplicationCacheResource::Fallback)) {
564             m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache update failed, because " + m_currentHandle->firstRequest().url().string() + 
565                 ((response.httpStatusCode() / 100 != 2) ? " could not be fetched." : " was redirected."));
566             // Note that cacheUpdateFailed() can cause the cache group to be deleted.
567             cacheUpdateFailed();
568         } else if (response.httpStatusCode() == 404 || response.httpStatusCode() == 410) {
569             // Skip this resource. It is dropped from the cache.
570             m_currentHandle->cancel();
571             m_currentHandle = 0;
572             m_pendingEntries.remove(url);
573             // Load the next resource, if any.
574             startLoadingEntry();
575         } else {
576             // Copy the resource and its metadata from the newest application cache in cache group whose completeness flag is complete, and act
577             // as if that was the fetched resource, ignoring the resource obtained from the network.
578             ASSERT(m_newestCache);
579             ApplicationCacheResource* newestCachedResource = m_newestCache->resourceForURL(handle->firstRequest().url());
580             ASSERT(newestCachedResource);
581             m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, newestCachedResource->response(), type, newestCachedResource->data(), newestCachedResource->path()));
582             m_pendingEntries.remove(m_currentHandle->firstRequest().url());
583             m_currentHandle->cancel();
584             m_currentHandle = 0;
585             // Load the next resource, if any.
586             startLoadingEntry();
587         }
588         return;
589     }
590     
591     m_currentResource = ApplicationCacheResource::create(url, response, type);
592 }
593
594 void ApplicationCacheGroup::didReceiveData(ResourceHandle* handle, const char* data, int length, int encodedDataLength)
595 {
596     UNUSED_PARAM(encodedDataLength);
597
598 #if ENABLE(INSPECTOR)
599     InspectorInstrumentation::didReceiveData(m_frame, m_currentResourceIdentifier, 0, length, 0);
600 #endif
601
602     if (handle == m_manifestHandle) {
603         didReceiveManifestData(data, length);
604         return;
605     }
606     
607     ASSERT(handle == m_currentHandle);
608     
609     ASSERT(m_currentResource);
610     m_currentResource->data()->append(data, length);
611 }
612
613 void ApplicationCacheGroup::didFinishLoading(ResourceHandle* handle, double finishTime)
614 {
615 #if ENABLE(INSPECTOR)
616     InspectorInstrumentation::didFinishLoading(m_frame, m_frame->loader()->documentLoader(), m_currentResourceIdentifier, finishTime);
617 #endif
618
619     if (handle == m_manifestHandle) {
620         didFinishLoadingManifest();
621         return;
622     }
623
624     ASSERT(m_currentHandle == handle);
625     ASSERT(m_pendingEntries.contains(handle->firstRequest().url()));
626     
627     m_pendingEntries.remove(handle->firstRequest().url());
628     
629     ASSERT(m_cacheBeingUpdated);
630
631     m_cacheBeingUpdated->addResource(m_currentResource.release());
632     m_currentHandle = 0;
633
634     // While downloading check to see if we have exceeded the available quota.
635     // We can stop immediately if we have already previously failed
636     // due to an earlier quota restriction. The client was already notified
637     // of the quota being reached and decided not to increase it then.
638     // FIXME: Should we break earlier and prevent redownloading on later page loads?
639     if (m_originQuotaExceededPreviously && m_availableSpaceInQuota < m_cacheBeingUpdated->estimatedSizeInStorage()) {
640         m_currentResource = 0;
641         m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache update failed, because size quota was exceeded.");
642         cacheUpdateFailed();
643         return;
644     }
645     
646     // Load the next resource, if any.
647     startLoadingEntry();
648 }
649
650 void ApplicationCacheGroup::didFail(ResourceHandle* handle, const ResourceError& error)
651 {
652 #if ENABLE(INSPECTOR)
653     InspectorInstrumentation::didFailLoading(m_frame, m_frame->loader()->documentLoader(), m_currentResourceIdentifier, error);
654 #endif
655
656     if (handle == m_manifestHandle) {
657         // A network error is logged elsewhere, no need to log again. Also, it's normal for manifest fetching to fail when working offline.
658         cacheUpdateFailed();
659         return;
660     }
661
662     ASSERT(handle == m_currentHandle);
663
664     unsigned type = m_currentResource ? m_currentResource->type() : m_pendingEntries.get(handle->firstRequest().url());
665     KURL url(handle->firstRequest().url());
666     if (url.hasFragmentIdentifier())
667         url.removeFragmentIdentifier();
668
669     ASSERT(!m_currentResource || !m_pendingEntries.contains(url));
670     m_currentResource = 0;
671     m_pendingEntries.remove(url);
672
673     if ((type & ApplicationCacheResource::Explicit) || (type & ApplicationCacheResource::Fallback)) {
674         m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache update failed, because " + url.string() + " could not be fetched.");
675         // Note that cacheUpdateFailed() can cause the cache group to be deleted.
676         cacheUpdateFailed();
677     } else {
678         // Copy the resource and its metadata from the newest application cache in cache group whose completeness flag is complete, and act
679         // as if that was the fetched resource, ignoring the resource obtained from the network.
680         ASSERT(m_newestCache);
681         ApplicationCacheResource* newestCachedResource = m_newestCache->resourceForURL(url);
682         ASSERT(newestCachedResource);
683         m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, newestCachedResource->response(), type, newestCachedResource->data(), newestCachedResource->path()));
684         // Load the next resource, if any.
685         startLoadingEntry();
686     }
687 }
688
689 void ApplicationCacheGroup::didReceiveManifestResponse(const ResourceResponse& response)
690 {
691     ASSERT(!m_manifestResource);
692     ASSERT(m_manifestHandle);
693
694     if (response.httpStatusCode() == 404 || response.httpStatusCode() == 410) {
695         manifestNotFound();
696         return;
697     }
698
699     if (response.httpStatusCode() == 304)
700         return;
701
702     if (response.httpStatusCode() / 100 != 2) {
703         m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache manifest could not be fetched.");
704         cacheUpdateFailed();
705         return;
706     }
707
708     if (response.url() != m_manifestHandle->firstRequest().url()) {
709         m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache manifest could not be fetched, because a redirection was attempted.");
710         cacheUpdateFailed();
711         return;
712     }
713
714     m_manifestResource = ApplicationCacheResource::create(m_manifestHandle->firstRequest().url(), response, ApplicationCacheResource::Manifest);
715 }
716
717 void ApplicationCacheGroup::didReceiveManifestData(const char* data, int length)
718 {
719     if (m_manifestResource)
720         m_manifestResource->data()->append(data, length);
721 }
722
723 void ApplicationCacheGroup::didFinishLoadingManifest()
724 {
725     bool isUpgradeAttempt = m_newestCache;
726
727     if (!isUpgradeAttempt && !m_manifestResource) {
728         // The server returned 304 Not Modified even though we didn't send a conditional request.
729         m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache manifest could not be fetched because of an unexpected 304 Not Modified server response.");
730         cacheUpdateFailed();
731         return;
732     }
733
734     m_manifestHandle = 0;
735
736     // Check if the manifest was not modified.
737     if (isUpgradeAttempt) {
738         ApplicationCacheResource* newestManifest = m_newestCache->manifestResource();
739         ASSERT(newestManifest);
740     
741         if (!m_manifestResource || // The resource will be null if HTTP response was 304 Not Modified.
742             (newestManifest->data()->size() == m_manifestResource->data()->size() && !memcmp(newestManifest->data()->data(), m_manifestResource->data()->data(), newestManifest->data()->size()))) {
743
744             m_completionType = NoUpdate;
745             m_manifestResource = 0;
746             deliverDelayedMainResources();
747
748             return;
749         }
750     }
751     
752     Manifest manifest;
753     if (!parseManifest(m_manifestURL, m_manifestResource->data()->data(), m_manifestResource->data()->size(), manifest)) {
754         // At the time of this writing, lack of "CACHE MANIFEST" signature is the only reason for parseManifest to fail.
755         m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache manifest could not be parsed. Does it start with CACHE MANIFEST?");
756         cacheUpdateFailed();
757         return;
758     }
759
760     ASSERT(!m_cacheBeingUpdated);
761     m_cacheBeingUpdated = ApplicationCache::create();
762     m_cacheBeingUpdated->setGroup(this);
763
764     HashSet<DocumentLoader*>::const_iterator masterEnd = m_pendingMasterResourceLoaders.end();
765     for (HashSet<DocumentLoader*>::const_iterator iter = m_pendingMasterResourceLoaders.begin(); iter != masterEnd; ++iter)
766         associateDocumentLoaderWithCache(*iter, m_cacheBeingUpdated.get());
767
768     // We have the manifest, now download the resources.
769     setUpdateStatus(Downloading);
770     
771     postListenerTask(ApplicationCacheHost::DOWNLOADING_EVENT, m_associatedDocumentLoaders);
772
773     ASSERT(m_pendingEntries.isEmpty());
774
775     if (isUpgradeAttempt) {
776         ApplicationCache::ResourceMap::const_iterator end = m_newestCache->end();
777         for (ApplicationCache::ResourceMap::const_iterator it = m_newestCache->begin(); it != end; ++it) {
778             unsigned type = it->second->type();
779             if (type & ApplicationCacheResource::Master)
780                 addEntry(it->first, type);
781         }
782     }
783     
784     HashSet<String>::const_iterator end = manifest.explicitURLs.end();
785     for (HashSet<String>::const_iterator it = manifest.explicitURLs.begin(); it != end; ++it)
786         addEntry(*it, ApplicationCacheResource::Explicit);
787
788     size_t fallbackCount = manifest.fallbackURLs.size();
789     for (size_t i = 0; i  < fallbackCount; ++i)
790         addEntry(manifest.fallbackURLs[i].second, ApplicationCacheResource::Fallback);
791     
792     m_cacheBeingUpdated->setOnlineWhitelist(manifest.onlineWhitelistedURLs);
793     m_cacheBeingUpdated->setFallbackURLs(manifest.fallbackURLs);
794     m_cacheBeingUpdated->setAllowsAllNetworkRequests(manifest.allowAllNetworkRequests);
795
796     m_progressTotal = m_pendingEntries.size();
797     m_progressDone = 0;
798
799     recalculateAvailableSpaceInQuota();
800
801     startLoadingEntry();
802 }
803
804 void ApplicationCacheGroup::didReachMaxAppCacheSize()
805 {
806     ASSERT(m_frame);
807     ASSERT(m_cacheBeingUpdated);
808     m_frame->page()->chrome()->client()->reachedMaxAppCacheSize(cacheStorage().spaceNeeded(m_cacheBeingUpdated->estimatedSizeInStorage()));
809     m_calledReachedMaxAppCacheSize = true;
810     checkIfLoadIsComplete();
811 }
812
813 void ApplicationCacheGroup::didReachOriginQuota(int64_t totalSpaceNeeded)
814 {
815     // Inform the client the origin quota has been reached, they may decide to increase the quota.
816     // We expect quota to be increased synchronously while waiting for the call to return.
817     m_frame->page()->chrome()->client()->reachedApplicationCacheOriginQuota(m_origin.get(), totalSpaceNeeded);
818 }
819
820 void ApplicationCacheGroup::cacheUpdateFailed()
821 {
822     stopLoading();
823     m_manifestResource = 0;
824
825     // Wait for master resource loads to finish.
826     m_completionType = Failure;
827     deliverDelayedMainResources();
828 }
829
830 void ApplicationCacheGroup::recalculateAvailableSpaceInQuota()
831 {
832     if (!cacheStorage().calculateRemainingSizeForOriginExcludingCache(m_origin.get(), m_newestCache.get(), m_availableSpaceInQuota)) {
833         // Failed to determine what is left in the quota. Fallback to allowing anything.
834         m_availableSpaceInQuota = ApplicationCacheStorage::noQuota();
835     }
836 }
837     
838 void ApplicationCacheGroup::manifestNotFound()
839 {
840     makeObsolete();
841
842     postListenerTask(ApplicationCacheHost::OBSOLETE_EVENT, m_associatedDocumentLoaders);
843     postListenerTask(ApplicationCacheHost::ERROR_EVENT, m_pendingMasterResourceLoaders);
844
845     stopLoading();
846
847     ASSERT(m_pendingEntries.isEmpty());
848     m_manifestResource = 0;
849
850     while (!m_pendingMasterResourceLoaders.isEmpty()) {
851         HashSet<DocumentLoader*>::iterator it = m_pendingMasterResourceLoaders.begin();
852         
853         ASSERT((*it)->applicationCacheHost()->candidateApplicationCacheGroup() == this);
854         ASSERT(!(*it)->applicationCacheHost()->applicationCache());
855         (*it)->applicationCacheHost()->setCandidateApplicationCacheGroup(0);
856         m_pendingMasterResourceLoaders.remove(it);
857     }
858
859     m_downloadingPendingMasterResourceLoadersCount = 0;
860     setUpdateStatus(Idle);    
861     m_frame = 0;
862     
863     if (m_caches.isEmpty()) {
864         ASSERT(m_associatedDocumentLoaders.isEmpty());
865         ASSERT(!m_cacheBeingUpdated);
866         delete this;
867     }
868 }
869
870 void ApplicationCacheGroup::checkIfLoadIsComplete()
871 {
872     if (m_manifestHandle || !m_pendingEntries.isEmpty() || m_downloadingPendingMasterResourceLoadersCount)
873         return;
874     
875     // We're done, all resources have finished downloading (successfully or not).
876
877     bool isUpgradeAttempt = m_newestCache;
878
879     switch (m_completionType) {
880     case None:
881         ASSERT_NOT_REACHED();
882         return;
883     case NoUpdate:
884         ASSERT(isUpgradeAttempt);
885         ASSERT(!m_cacheBeingUpdated);
886
887         // The storage could have been manually emptied by the user.
888         if (!m_storageID)
889             cacheStorage().storeNewestCache(this);
890
891         postListenerTask(ApplicationCacheHost::NOUPDATE_EVENT, m_associatedDocumentLoaders);
892         break;
893     case Failure:
894         ASSERT(!m_cacheBeingUpdated);
895         postListenerTask(ApplicationCacheHost::ERROR_EVENT, m_associatedDocumentLoaders);
896         if (m_caches.isEmpty()) {
897             ASSERT(m_associatedDocumentLoaders.isEmpty());
898             delete this;
899             return;
900         }
901         break;
902     case Completed: {
903         // FIXME: Fetch the resource from manifest URL again, and check whether it is identical to the one used for update (in case the application was upgraded server-side in the meanwhile). (<rdar://problem/6467625>)
904
905         ASSERT(m_cacheBeingUpdated);
906         if (m_manifestResource)
907             m_cacheBeingUpdated->setManifestResource(m_manifestResource.release());
908         else {
909             // We can get here as a result of retrying the Complete step, following
910             // a failure of the cache storage to save the newest cache due to hitting
911             // the maximum size. In such a case, m_manifestResource may be 0, as
912             // the manifest was already set on the newest cache object.
913             ASSERT(cacheStorage().isMaximumSizeReached() && m_calledReachedMaxAppCacheSize);
914         }
915
916         RefPtr<ApplicationCache> oldNewestCache = (m_newestCache == m_cacheBeingUpdated) ? RefPtr<ApplicationCache>() : m_newestCache;
917
918         // If we exceeded the origin quota while downloading we can request a quota
919         // increase now, before we attempt to store the cache.
920         int64_t totalSpaceNeeded;
921         if (!cacheStorage().checkOriginQuota(this, oldNewestCache.get(), m_cacheBeingUpdated.get(), totalSpaceNeeded))
922             didReachOriginQuota(totalSpaceNeeded);
923
924         ApplicationCacheStorage::FailureReason failureReason;
925         setNewestCache(m_cacheBeingUpdated.release());
926         if (cacheStorage().storeNewestCache(this, oldNewestCache.get(), failureReason)) {
927             // New cache stored, now remove the old cache.
928             if (oldNewestCache)
929                 cacheStorage().remove(oldNewestCache.get());
930
931             // Fire the final progress event.
932             ASSERT(m_progressDone == m_progressTotal);
933             postListenerTask(ApplicationCacheHost::PROGRESS_EVENT, m_progressTotal, m_progressDone, m_associatedDocumentLoaders);
934
935             // Fire the success event.
936             postListenerTask(isUpgradeAttempt ? ApplicationCacheHost::UPDATEREADY_EVENT : ApplicationCacheHost::CACHED_EVENT, m_associatedDocumentLoaders);
937             // It is clear that the origin quota was not reached, so clear the flag if it was set.
938             m_originQuotaExceededPreviously = false;
939         } else {
940             if (failureReason == ApplicationCacheStorage::OriginQuotaReached) {
941                 // We ran out of space for this origin. Fall down to the normal error handling
942                 // after recording this state.
943                 m_originQuotaExceededPreviously = true;
944                 m_frame->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, ErrorMessageLevel, "Application Cache update failed, because size quota was exceeded.");
945             }
946
947             if (failureReason == ApplicationCacheStorage::TotalQuotaReached && !m_calledReachedMaxAppCacheSize) {
948                 // FIXME: Should this be handled more like Origin Quotas? Does this fail properly?
949
950                 // We ran out of space. All the changes in the cache storage have
951                 // been rolled back. We roll back to the previous state in here,
952                 // as well, call the chrome client asynchronously and retry to
953                 // save the new cache.
954
955                 // Save a reference to the new cache.
956                 m_cacheBeingUpdated = m_newestCache.release();
957                 if (oldNewestCache) {
958                     // Reinstate the oldNewestCache.
959                     setNewestCache(oldNewestCache.release());
960                 }
961                 scheduleReachedMaxAppCacheSizeCallback();
962                 return;
963             }
964
965             // Run the "cache failure steps"
966             // Fire the error events to all pending master entries, as well any other cache hosts
967             // currently associated with a cache in this group.
968             postListenerTask(ApplicationCacheHost::ERROR_EVENT, m_associatedDocumentLoaders);
969             // Disassociate the pending master entries from the failed new cache. Note that
970             // all other loaders in the m_associatedDocumentLoaders are still associated with
971             // some other cache in this group. They are not associated with the failed new cache.
972
973             // Need to copy loaders, because the cache group may be destroyed at the end of iteration.
974             Vector<DocumentLoader*> loaders;
975             copyToVector(m_pendingMasterResourceLoaders, loaders);
976             size_t count = loaders.size();
977             for (size_t i = 0; i != count; ++i)
978                 disassociateDocumentLoader(loaders[i]); // This can delete this group.
979
980             // Reinstate the oldNewestCache, if there was one.
981             if (oldNewestCache) {
982                 // This will discard the failed new cache.
983                 setNewestCache(oldNewestCache.release());
984             } else {
985                 // We must have been deleted by the last call to disassociateDocumentLoader().
986                 return;
987             }
988         }
989         break;
990     }
991     }
992
993     // Empty cache group's list of pending master entries.
994     m_pendingMasterResourceLoaders.clear();
995     m_completionType = None;
996     setUpdateStatus(Idle);
997     m_frame = 0;
998     m_availableSpaceInQuota = ApplicationCacheStorage::unknownQuota();
999     m_calledReachedMaxAppCacheSize = false;
1000 }
1001
1002 void ApplicationCacheGroup::startLoadingEntry()
1003 {
1004     ASSERT(m_cacheBeingUpdated);
1005
1006     if (m_pendingEntries.isEmpty()) {
1007         m_completionType = Completed;
1008         deliverDelayedMainResources();
1009         return;
1010     }
1011     
1012     EntryMap::const_iterator it = m_pendingEntries.begin();
1013
1014     postListenerTask(ApplicationCacheHost::PROGRESS_EVENT, m_progressTotal, m_progressDone, m_associatedDocumentLoaders);
1015     m_progressDone++;
1016
1017     ASSERT(!m_currentHandle);
1018     
1019     m_currentHandle = createResourceHandle(KURL(ParsedURLString, it->first), m_newestCache ? m_newestCache->resourceForURL(it->first) : 0);
1020 }
1021
1022 void ApplicationCacheGroup::deliverDelayedMainResources()
1023 {
1024     // Need to copy loaders, because the cache group may be destroyed at the end of iteration.
1025     Vector<DocumentLoader*> loaders;
1026     copyToVector(m_pendingMasterResourceLoaders, loaders);
1027     size_t count = loaders.size();
1028     for (size_t i = 0; i != count; ++i) {
1029         DocumentLoader* loader = loaders[i];
1030         if (loader->isLoadingMainResource())
1031             continue;
1032
1033         const ResourceError& error = loader->mainDocumentError();
1034         if (error.isNull())
1035             finishedLoadingMainResource(loader);
1036         else
1037             failedLoadingMainResource(loader);
1038     }
1039     if (!count)
1040         checkIfLoadIsComplete();
1041 }
1042
1043 void ApplicationCacheGroup::addEntry(const String& url, unsigned type)
1044 {
1045     ASSERT(m_cacheBeingUpdated);
1046     ASSERT(!KURL(ParsedURLString, url).hasFragmentIdentifier());
1047     
1048     // Don't add the URL if we already have an master resource in the cache
1049     // (i.e., the main resource finished loading before the manifest).
1050     if (ApplicationCacheResource* resource = m_cacheBeingUpdated->resourceForURL(url)) {
1051         ASSERT(resource->type() & ApplicationCacheResource::Master);
1052         ASSERT(!m_frame->loader()->documentLoader()->isLoadingMainResource());
1053     
1054         resource->addType(type);
1055         return;
1056     }
1057
1058     // Don't add the URL if it's the same as the manifest URL.
1059     ASSERT(m_manifestResource);
1060     if (m_manifestResource->url() == url) {
1061         m_manifestResource->addType(type);
1062         return;
1063     }
1064     
1065     pair<EntryMap::iterator, bool> result = m_pendingEntries.add(url, type);
1066     
1067     if (!result.second)
1068         result.first->second |= type;
1069 }
1070
1071 void ApplicationCacheGroup::associateDocumentLoaderWithCache(DocumentLoader* loader, ApplicationCache* cache)
1072 {
1073     // If teardown started already, revive the group.
1074     if (!m_newestCache && !m_cacheBeingUpdated)
1075         m_newestCache = cache;
1076
1077     ASSERT(!m_isObsolete);
1078
1079     loader->applicationCacheHost()->setApplicationCache(cache);
1080
1081     ASSERT(!m_associatedDocumentLoaders.contains(loader));
1082     m_associatedDocumentLoaders.add(loader);
1083 }
1084
1085 class ChromeClientCallbackTimer: public TimerBase {
1086 public:
1087     ChromeClientCallbackTimer(ApplicationCacheGroup* cacheGroup)
1088         : m_cacheGroup(cacheGroup)
1089     {
1090     }
1091
1092 private:
1093     virtual void fired()
1094     {
1095         m_cacheGroup->didReachMaxAppCacheSize();
1096         delete this;
1097     }
1098     // Note that there is no need to use a RefPtr here. The ApplicationCacheGroup instance is guaranteed
1099     // to be alive when the timer fires since invoking the ChromeClient callback is part of its normal
1100     // update machinery and nothing can yet cause it to get deleted.
1101     ApplicationCacheGroup* m_cacheGroup;
1102 };
1103
1104 void ApplicationCacheGroup::scheduleReachedMaxAppCacheSizeCallback()
1105 {
1106     ASSERT(isMainThread());
1107     ChromeClientCallbackTimer* timer = new ChromeClientCallbackTimer(this);
1108     timer->startOneShot(0);
1109     // The timer will delete itself once it fires.
1110 }
1111
1112 class CallCacheListenerTask : public ScriptExecutionContext::Task {
1113 public:
1114     static PassOwnPtr<CallCacheListenerTask> create(PassRefPtr<DocumentLoader> loader, ApplicationCacheHost::EventID eventID, int progressTotal, int progressDone)
1115     {
1116         return adoptPtr(new CallCacheListenerTask(loader, eventID, progressTotal, progressDone));
1117     }
1118
1119     virtual void performTask(ScriptExecutionContext* context)
1120     {
1121         
1122         ASSERT_UNUSED(context, context->isDocument());
1123         Frame* frame = m_documentLoader->frame();
1124         if (!frame)
1125             return;
1126     
1127         ASSERT(frame->loader()->documentLoader() == m_documentLoader.get());
1128
1129         m_documentLoader->applicationCacheHost()->notifyDOMApplicationCache(m_eventID, m_progressTotal, m_progressDone);
1130     }
1131
1132 private:
1133     CallCacheListenerTask(PassRefPtr<DocumentLoader> loader, ApplicationCacheHost::EventID eventID, int progressTotal, int progressDone)
1134         : m_documentLoader(loader)
1135         , m_eventID(eventID)
1136         , m_progressTotal(progressTotal)
1137         , m_progressDone(progressDone)
1138     {
1139     }
1140
1141     RefPtr<DocumentLoader> m_documentLoader;
1142     ApplicationCacheHost::EventID m_eventID;
1143     int m_progressTotal;
1144     int m_progressDone;
1145 };
1146
1147 void ApplicationCacheGroup::postListenerTask(ApplicationCacheHost::EventID eventID, int progressTotal, int progressDone, const HashSet<DocumentLoader*>& loaderSet)
1148 {
1149     HashSet<DocumentLoader*>::const_iterator loaderSetEnd = loaderSet.end();
1150     for (HashSet<DocumentLoader*>::const_iterator iter = loaderSet.begin(); iter != loaderSetEnd; ++iter)
1151         postListenerTask(eventID, progressTotal, progressDone, *iter);
1152 }
1153
1154 void ApplicationCacheGroup::postListenerTask(ApplicationCacheHost::EventID eventID, int progressTotal, int progressDone, DocumentLoader* loader)
1155 {
1156     Frame* frame = loader->frame();
1157     if (!frame)
1158         return;
1159     
1160     ASSERT(frame->loader()->documentLoader() == loader);
1161
1162     frame->document()->postTask(CallCacheListenerTask::create(loader, eventID, progressTotal, progressDone));
1163 }
1164
1165 void ApplicationCacheGroup::setUpdateStatus(UpdateStatus status)
1166 {
1167     m_updateStatus = status;
1168 }
1169
1170 void ApplicationCacheGroup::clearStorageID()
1171 {
1172     m_storageID = 0;
1173     
1174     HashSet<ApplicationCache*>::const_iterator end = m_caches.end();
1175     for (HashSet<ApplicationCache*>::const_iterator it = m_caches.begin(); it != end; ++it)
1176         (*it)->clearStorageID();
1177 }
1178
1179 }