Replace static_casts with to* functions for document types.
[WebKit-https.git] / Source / WebCore / loader / WorkerThreadableLoader.cpp
1 /*
2  * Copyright (C) 2009, 2010 Google 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 are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32
33 #if ENABLE(WORKERS)
34
35 #include "WorkerThreadableLoader.h"
36
37 #include "Document.h"
38 #include "DocumentThreadableLoader.h"
39 #include "CrossThreadTask.h"
40 #include "ResourceError.h"
41 #include "ResourceRequest.h"
42 #include "ResourceResponse.h"
43 #include "ThreadableLoader.h"
44 #include "WorkerContext.h"
45 #include "WorkerLoaderProxy.h"
46 #include "WorkerThread.h"
47 #include <wtf/MainThread.h>
48 #include <wtf/OwnPtr.h>
49 #include <wtf/Vector.h>
50
51 using namespace std;
52
53 namespace WebCore {
54
55 static const char loadResourceSynchronouslyMode[] = "loadResourceSynchronouslyMode";
56
57 WorkerThreadableLoader::WorkerThreadableLoader(WorkerContext* workerContext, ThreadableLoaderClient* client, const String& taskMode, const ResourceRequest& request, const ThreadableLoaderOptions& options)
58     : m_workerContext(workerContext)
59     , m_workerClientWrapper(ThreadableLoaderClientWrapper::create(client))
60     , m_bridge(*(new MainThreadBridge(m_workerClientWrapper, m_workerContext->thread()->workerLoaderProxy(), taskMode, request, options, workerContext->url().strippedForUseAsReferrer())))
61 {
62 }
63
64 WorkerThreadableLoader::~WorkerThreadableLoader()
65 {
66     m_bridge.destroy();
67 }
68
69 void WorkerThreadableLoader::loadResourceSynchronously(WorkerContext* workerContext, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
70 {
71     WorkerRunLoop& runLoop = workerContext->thread()->runLoop();
72
73     // Create a unique mode just for this synchronous resource load.
74     String mode = loadResourceSynchronouslyMode;
75     mode.append(String::number(runLoop.createUniqueId()));
76
77     RefPtr<WorkerThreadableLoader> loader = WorkerThreadableLoader::create(workerContext, &client, mode, request, options);
78     MessageQueueWaitResult result = MessageQueueMessageReceived;
79     while (!loader->done() && result != MessageQueueTerminated)
80         result = runLoop.runInMode(workerContext, mode);
81
82     if (!loader->done() && result == MessageQueueTerminated)
83         loader->cancel();
84 }
85
86 void WorkerThreadableLoader::cancel()
87 {
88     m_bridge.cancel();
89 }
90
91 WorkerThreadableLoader::MainThreadBridge::MainThreadBridge(PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, WorkerLoaderProxy& loaderProxy, const String& taskMode,
92                                                            const ResourceRequest& request, const ThreadableLoaderOptions& options, const String& outgoingReferrer)
93     : m_workerClientWrapper(workerClientWrapper)
94     , m_loaderProxy(loaderProxy)
95     , m_taskMode(taskMode.isolatedCopy())
96 {
97     ASSERT(m_workerClientWrapper.get());
98     m_loaderProxy.postTaskToLoader(
99         createCallbackTask(&MainThreadBridge::mainThreadCreateLoader, 
100                            AllowCrossThreadAccess(this), request, options, outgoingReferrer));
101 }
102
103 WorkerThreadableLoader::MainThreadBridge::~MainThreadBridge()
104 {
105 }
106
107 void WorkerThreadableLoader::MainThreadBridge::mainThreadCreateLoader(ScriptExecutionContext* context, MainThreadBridge* thisPtr, PassOwnPtr<CrossThreadResourceRequestData> requestData, ThreadableLoaderOptions options, const String& outgoingReferrer)
108 {
109     ASSERT(isMainThread());
110     Document* document = toDocument(context);
111
112     OwnPtr<ResourceRequest> request(ResourceRequest::adopt(requestData));
113     request->setHTTPReferrer(outgoingReferrer);
114     // FIXME: If the a site requests a local resource, then this will return a non-zero value but the sync path
115     // will return a 0 value.  Either this should return 0 or the other code path should do a callback with
116     // a failure.
117     thisPtr->m_mainThreadLoader = DocumentThreadableLoader::create(document, thisPtr, *request, options);
118     ASSERT(thisPtr->m_mainThreadLoader);
119 }
120
121 void WorkerThreadableLoader::MainThreadBridge::mainThreadDestroy(ScriptExecutionContext* context, MainThreadBridge* thisPtr)
122 {
123     ASSERT(isMainThread());
124     ASSERT_UNUSED(context, context->isDocument());
125     delete thisPtr;
126 }
127
128 void WorkerThreadableLoader::MainThreadBridge::destroy()
129 {
130     // Ensure that no more client callbacks are done in the worker context's thread.
131     clearClientWrapper();
132
133     // "delete this" and m_mainThreadLoader::deref() on the worker object's thread.
134     m_loaderProxy.postTaskToLoader(
135         createCallbackTask(&MainThreadBridge::mainThreadDestroy, AllowCrossThreadAccess(this)));
136 }
137
138 void WorkerThreadableLoader::MainThreadBridge::mainThreadCancel(ScriptExecutionContext* context, MainThreadBridge* thisPtr)
139 {
140     ASSERT(isMainThread());
141     ASSERT_UNUSED(context, context->isDocument());
142
143     if (!thisPtr->m_mainThreadLoader)
144         return;
145     thisPtr->m_mainThreadLoader->cancel();
146     thisPtr->m_mainThreadLoader = 0;
147 }
148
149 void WorkerThreadableLoader::MainThreadBridge::cancel()
150 {
151     m_loaderProxy.postTaskToLoader(
152         createCallbackTask(&MainThreadBridge::mainThreadCancel, AllowCrossThreadAccess(this)));
153     ThreadableLoaderClientWrapper* clientWrapper = m_workerClientWrapper.get();
154     if (!clientWrapper->done()) {
155         // If the client hasn't reached a termination state, then transition it by sending a cancellation error.
156         // Note: no more client callbacks will be done after this method -- the clearClientWrapper() call ensures that.
157         ResourceError error(String(), 0, String(), String());
158         error.setIsCancellation(true);
159         clientWrapper->didFail(error);
160     }
161     clearClientWrapper();
162 }
163
164 void WorkerThreadableLoader::MainThreadBridge::clearClientWrapper()
165 {
166     m_workerClientWrapper->clearClient();
167 }
168
169 static void workerContextDidSendData(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
170 {
171     ASSERT_UNUSED(context, context->isWorkerContext());
172     workerClientWrapper->didSendData(bytesSent, totalBytesToBeSent);
173 }
174
175 void WorkerThreadableLoader::MainThreadBridge::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
176 {
177     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidSendData, m_workerClientWrapper, bytesSent, totalBytesToBeSent), m_taskMode);
178 }
179
180 static void workerContextDidReceiveResponse(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData)
181 {
182     ASSERT_UNUSED(context, context->isWorkerContext());
183     OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
184     workerClientWrapper->didReceiveResponse(identifier, *response);
185 }
186
187 void WorkerThreadableLoader::MainThreadBridge::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
188 {
189     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveResponse, m_workerClientWrapper, identifier, response), m_taskMode);
190 }
191
192 static void workerContextDidReceiveData(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
193 {
194     ASSERT_UNUSED(context, context->isWorkerContext());
195     workerClientWrapper->didReceiveData(vectorData->data(), vectorData->size());
196 }
197
198 void WorkerThreadableLoader::MainThreadBridge::didReceiveData(const char* data, int dataLength)
199 {
200     OwnPtr<Vector<char> > vector = adoptPtr(new Vector<char>(dataLength)); // needs to be an OwnPtr for usage with createCallbackTask.
201     memcpy(vector->data(), data, dataLength);
202     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveData, m_workerClientWrapper, vector.release()), m_taskMode);
203 }
204
205 static void workerContextDidReceiveCachedMetadata(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
206 {
207     ASSERT_UNUSED(context, context->isWorkerContext());
208     workerClientWrapper->didReceiveCachedMetadata(vectorData->data(), vectorData->size());
209 }
210
211 void WorkerThreadableLoader::MainThreadBridge::didReceiveCachedMetadata(const char* data, int dataLength)
212 {
213     OwnPtr<Vector<char> > vector = adoptPtr(new Vector<char>(dataLength)); // needs to be an OwnPtr for usage with createCallbackTask.
214     memcpy(vector->data(), data, dataLength);
215     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveCachedMetadata, m_workerClientWrapper, vector.release()), m_taskMode);
216 }
217
218 static void workerContextDidFinishLoading(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, double finishTime)
219 {
220     ASSERT_UNUSED(context, context->isWorkerContext());
221     workerClientWrapper->didFinishLoading(identifier, finishTime);
222 }
223
224 void WorkerThreadableLoader::MainThreadBridge::didFinishLoading(unsigned long identifier, double finishTime)
225 {
226     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFinishLoading, m_workerClientWrapper, identifier, finishTime), m_taskMode);
227 }
228
229 static void workerContextDidFail(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
230 {
231     ASSERT_UNUSED(context, context->isWorkerContext());
232     workerClientWrapper->didFail(error);
233 }
234
235 void WorkerThreadableLoader::MainThreadBridge::didFail(const ResourceError& error)
236 {
237     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFail, m_workerClientWrapper, error), m_taskMode);
238 }
239
240 static void workerContextDidFailAccessControlCheck(ScriptExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
241 {
242     ASSERT_UNUSED(context, context->isWorkerContext());
243     workerClientWrapper->didFailAccessControlCheck(error);
244 }
245
246 void WorkerThreadableLoader::MainThreadBridge::didFailAccessControlCheck(const ResourceError& error)
247 {
248     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFailAccessControlCheck, m_workerClientWrapper, error), m_taskMode);
249 }
250
251 static void workerContextDidFailRedirectCheck(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper)
252 {
253     ASSERT_UNUSED(context, context->isWorkerContext());
254     workerClientWrapper->didFailRedirectCheck();
255 }
256
257 void WorkerThreadableLoader::MainThreadBridge::didFailRedirectCheck()
258 {
259     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFailRedirectCheck, m_workerClientWrapper), m_taskMode);
260 }
261
262 } // namespace WebCore
263
264 #endif // ENABLE(WORKERS)