WebCore:
[WebKit-https.git] / WebCore / workers / WorkerMessagingProxy.cpp
1 /*
2  * Copyright (C) 2008 Apple Inc. All Rights Reserved.
3  * Copyright (C) 2009 Google Inc. All Rights Reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
25  *
26  */
27
28 #include "config.h"
29
30 #if ENABLE(WORKERS)
31
32 #include "WorkerMessagingProxy.h"
33
34 #include "DOMWindow.h"
35 #include "Document.h"
36 #include "GenericWorkerTask.h"
37 #include "MessageEvent.h"
38 #include "ScriptExecutionContext.h"
39 #include "Worker.h"
40 #include "WorkerContext.h"
41 #include "WorkerThread.h"
42
43 namespace WebCore {
44
45 class MessageWorkerContextTask : public ScriptExecutionContext::Task {
46 public:
47     static PassRefPtr<MessageWorkerContextTask> create(const String& message)
48     {
49         return adoptRef(new MessageWorkerContextTask(message));
50     }
51
52 private:
53     MessageWorkerContextTask(const String& message)
54         : m_message(message.copy())
55     {
56     }
57
58     virtual void performTask(ScriptExecutionContext* scriptContext)
59     {
60         ASSERT(scriptContext->isWorkerContext());
61         WorkerContext* context = static_cast<WorkerContext*>(scriptContext);
62
63         context->dispatchMessage(m_message);
64
65         context->thread()->workerObjectProxy()->confirmMessageFromWorkerObject(context->hasPendingActivity());
66     }
67
68 private:
69     String m_message;
70 };
71
72 class MessageWorkerTask : public ScriptExecutionContext::Task {
73 public:
74     static PassRefPtr<MessageWorkerTask> create(const String& message, WorkerMessagingProxy* messagingProxy)
75     {
76         return adoptRef(new MessageWorkerTask(message, messagingProxy));
77     }
78
79 private:
80     MessageWorkerTask(const String& message, WorkerMessagingProxy* messagingProxy)
81         : m_message(message.copy())
82         , m_messagingProxy(messagingProxy)
83     {
84     }
85
86     virtual void performTask(ScriptExecutionContext*)
87     {
88         Worker* workerObject = m_messagingProxy->workerObject();
89         if (!workerObject || m_messagingProxy->askedToTerminate())
90             return;
91
92         workerObject->dispatchMessage(m_message);
93     }
94
95 private:
96     String m_message;
97     WorkerMessagingProxy* m_messagingProxy;
98 };
99
100 class WorkerExceptionTask : public ScriptExecutionContext::Task {
101 public:
102     static PassRefPtr<WorkerExceptionTask> create(const String& errorMessage, int lineNumber, const String& sourceURL, WorkerMessagingProxy* messagingProxy)
103     {
104         return adoptRef(new WorkerExceptionTask(errorMessage, lineNumber, sourceURL, messagingProxy));
105     }
106
107 private:
108     WorkerExceptionTask(const String& errorMessage, int lineNumber, const String& sourceURL, WorkerMessagingProxy* messagingProxy)
109         : m_errorMessage(errorMessage.copy())
110         , m_lineNumber(lineNumber)
111         , m_sourceURL(sourceURL.copy())
112         , m_messagingProxy(messagingProxy)
113     {
114     }
115
116     virtual void performTask(ScriptExecutionContext* context)
117     {
118         if (!m_messagingProxy->askedToTerminate())
119             context->reportException(m_errorMessage, m_lineNumber, m_sourceURL);
120     }
121
122     String m_errorMessage;
123     int m_lineNumber;
124     String m_sourceURL;
125     WorkerMessagingProxy* m_messagingProxy;
126 };
127
128 class WorkerContextDestroyedTask : public ScriptExecutionContext::Task {
129 public:
130     static PassRefPtr<WorkerContextDestroyedTask> create(WorkerMessagingProxy* messagingProxy)
131     {
132         return adoptRef(new WorkerContextDestroyedTask(messagingProxy));
133     }
134
135 private:
136     WorkerContextDestroyedTask(WorkerMessagingProxy* messagingProxy)
137         : m_messagingProxy(messagingProxy)
138     {
139     }
140
141     virtual void performTask(ScriptExecutionContext*)
142     {
143         m_messagingProxy->workerContextDestroyedInternal();
144     }
145
146     WorkerMessagingProxy* m_messagingProxy;
147 };
148
149 class WorkerThreadActivityReportTask : public ScriptExecutionContext::Task {
150 public:
151     static PassRefPtr<WorkerThreadActivityReportTask> create(WorkerMessagingProxy* messagingProxy, bool confirmingMessage, bool hasPendingActivity)
152     {
153         return adoptRef(new WorkerThreadActivityReportTask(messagingProxy, confirmingMessage, hasPendingActivity));
154     }
155
156 private:
157     WorkerThreadActivityReportTask(WorkerMessagingProxy* messagingProxy, bool confirmingMessage, bool hasPendingActivity)
158         : m_messagingProxy(messagingProxy)
159         , m_confirmingMessage(confirmingMessage)
160         , m_hasPendingActivity(hasPendingActivity)
161     {
162     }
163
164     virtual void performTask(ScriptExecutionContext*)
165     {
166         m_messagingProxy->reportPendingActivityInternal(m_confirmingMessage, m_hasPendingActivity);
167     }
168
169     WorkerMessagingProxy* m_messagingProxy;
170     bool m_confirmingMessage;
171     bool m_hasPendingActivity;
172 };
173
174
175 #if !PLATFORM(CHROMIUM)
176 WorkerContextProxy* WorkerContextProxy::create(Worker* worker)
177 {
178     return new WorkerMessagingProxy(worker);
179 }
180 #endif
181
182 WorkerMessagingProxy::WorkerMessagingProxy(Worker* workerObject)
183     : m_scriptExecutionContext(workerObject->scriptExecutionContext())
184     , m_workerObject(workerObject)
185     , m_unconfirmedMessageCount(0)
186     , m_workerThreadHadPendingActivity(false)
187     , m_askedToTerminate(false)
188 {
189     ASSERT(m_workerObject);
190     ASSERT((m_scriptExecutionContext->isDocument() && isMainThread())
191            || (m_scriptExecutionContext->isWorkerContext() && currentThread() == static_cast<WorkerContext*>(m_scriptExecutionContext.get())->thread()->threadID()));
192 }
193
194 WorkerMessagingProxy::~WorkerMessagingProxy()
195 {
196     ASSERT(!m_workerObject);
197     ASSERT((m_scriptExecutionContext->isDocument() && isMainThread())
198            || (m_scriptExecutionContext->isWorkerContext() && currentThread() == static_cast<WorkerContext*>(m_scriptExecutionContext.get())->thread()->threadID()));
199 }
200
201 void WorkerMessagingProxy::startWorkerContext(const KURL& scriptURL, const String& userAgent, const String& encoding, const String& sourceCode)
202 {
203     RefPtr<WorkerThread> thread = WorkerThread::create(scriptURL, userAgent, encoding, sourceCode, this);
204     workerThreadCreated(thread);
205     thread->start();
206 }
207
208 void WorkerMessagingProxy::postMessageToWorkerObject(const String& message)
209 {
210     m_scriptExecutionContext->postTask(MessageWorkerTask::create(message, this));
211 }
212
213 void WorkerMessagingProxy::postMessageToWorkerContext(const String& message)
214 {
215     if (m_askedToTerminate)
216         return;
217
218     if (m_workerThread) {
219         ++m_unconfirmedMessageCount;
220         m_workerThread->runLoop().postTask(MessageWorkerContextTask::create(message));
221     } else
222         m_queuedEarlyTasks.append(MessageWorkerContextTask::create(message));
223 }
224
225 void WorkerMessagingProxy::postTaskToWorkerContext(PassRefPtr<ScriptExecutionContext::Task> task)
226 {
227     postTaskForModeToWorkerContext(task, WorkerRunLoop::defaultMode());
228 }
229
230 void WorkerMessagingProxy::postTaskForModeToWorkerContext(PassRefPtr<ScriptExecutionContext::Task> task, const String& mode)
231 {
232     if (m_askedToTerminate)
233         return;
234
235     ASSERT(m_workerThread);
236     m_workerThread->runLoop().postTaskForMode(task, mode);
237 }
238
239 void WorkerMessagingProxy::postTaskToWorkerObject(PassRefPtr<ScriptExecutionContext::Task> task)
240 {
241     m_scriptExecutionContext->postTask(task);
242 }
243
244 void WorkerMessagingProxy::postExceptionToWorkerObject(const String& errorMessage, int lineNumber, const String& sourceURL)
245 {
246     m_scriptExecutionContext->postTask(WorkerExceptionTask::create(errorMessage, lineNumber, sourceURL, this));
247 }
248     
249 static void postConsoleMessageTask(ScriptExecutionContext* context, WorkerMessagingProxy* messagingProxy, MessageDestination destination, MessageSource source, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceURL)
250 {
251     if (messagingProxy->askedToTerminate())
252         return;
253     context->addMessage(destination, source, level, message, lineNumber, sourceURL);
254 }
255
256 void WorkerMessagingProxy::postConsoleMessageToWorkerObject(MessageDestination destination, MessageSource source, MessageLevel level, const String& message, int lineNumber, const String& sourceURL)
257 {
258     m_scriptExecutionContext->postTask(createCallbackTask(&postConsoleMessageTask, this, destination, source, level, message, lineNumber, sourceURL));
259 }
260
261 void WorkerMessagingProxy::workerThreadCreated(PassRefPtr<WorkerThread> workerThread)
262 {
263     m_workerThread = workerThread;
264
265     if (m_askedToTerminate) {
266         // Worker.terminate() could be called from JS before the thread was created.
267         m_workerThread->stop();
268     } else {
269         unsigned taskCount = m_queuedEarlyTasks.size();
270         ASSERT(!m_unconfirmedMessageCount);
271         m_unconfirmedMessageCount = taskCount;
272         m_workerThreadHadPendingActivity = true; // Worker initialization means a pending activity.
273
274         for (unsigned i = 0; i < taskCount; ++i)
275             m_workerThread->runLoop().postTask(m_queuedEarlyTasks[i]);
276         m_queuedEarlyTasks.clear();
277     }
278 }
279
280 void WorkerMessagingProxy::workerObjectDestroyed()
281 {
282     m_workerObject = 0;
283     if (m_workerThread)
284         terminateWorkerContext();
285     else
286         workerContextDestroyedInternal();
287 }
288
289 void WorkerMessagingProxy::workerContextDestroyed()
290 {
291     m_scriptExecutionContext->postTask(WorkerContextDestroyedTask::create(this));
292     // Will execute workerContextDestroyedInternal() on context's thread.
293 }
294
295 void WorkerMessagingProxy::workerContextDestroyedInternal()
296 {
297     // WorkerContextDestroyedTask is always the last to be performed, so the proxy is not needed for communication
298     // in either side any more. However, the Worker object may still exist, and it assumes that the proxy exists, too.
299     m_workerThread = 0;
300     if (!m_workerObject)
301         delete this;
302 }
303
304 void WorkerMessagingProxy::terminateWorkerContext()
305 {
306     if (m_askedToTerminate)
307         return;
308     m_askedToTerminate = true;
309
310     if (m_workerThread)
311         m_workerThread->stop();
312 }
313
314 void WorkerMessagingProxy::confirmMessageFromWorkerObject(bool hasPendingActivity)
315 {
316     m_scriptExecutionContext->postTask(WorkerThreadActivityReportTask::create(this, true, hasPendingActivity));
317     // Will execute reportPendingActivityInternal() on context's thread.
318 }
319
320 void WorkerMessagingProxy::reportPendingActivity(bool hasPendingActivity)
321 {
322     m_scriptExecutionContext->postTask(WorkerThreadActivityReportTask::create(this, false, hasPendingActivity));
323     // Will execute reportPendingActivityInternal() on context's thread.
324 }
325
326 void WorkerMessagingProxy::reportPendingActivityInternal(bool confirmingMessage, bool hasPendingActivity)
327 {
328     if (confirmingMessage && !m_askedToTerminate) {
329         ASSERT(m_unconfirmedMessageCount);
330         --m_unconfirmedMessageCount;
331     }
332
333     m_workerThreadHadPendingActivity = hasPendingActivity;
334 }
335
336 bool WorkerMessagingProxy::hasPendingActivity() const
337 {
338     return (m_unconfirmedMessageCount || m_workerThreadHadPendingActivity) && !m_askedToTerminate;
339 }
340
341 } // namespace WebCore
342
343 #endif // ENABLE(WORKERS)