daeae5ab997b306a5d7452c1e67c8ee37179ac10
[WebKit-https.git] / WebCore / dom / WorkerMessagingProxy.cpp
1 /*
2  * Copyright (C) 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  * 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 COMPUTER, 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 COMPUTER, 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
27 #include "config.h"
28
29 #if ENABLE(WORKERS)
30
31 #include "WorkerMessagingProxy.h"
32
33 #include "DOMWindow.h"
34 #include "Document.h"
35 #include "MessageEvent.h"
36 #include "Worker.h"
37 #include "WorkerContext.h"
38 #include "WorkerTask.h"
39 #include "WorkerThread.h"
40
41 namespace WebCore {
42
43 class MessageWorkerContextTask : public WorkerTask {
44 public:
45     static PassRefPtr<MessageWorkerContextTask> create(const String& message)
46     {
47         return adoptRef(new MessageWorkerContextTask(message));
48     }
49
50 private:
51     MessageWorkerContextTask(const String& message)
52         : m_message(message.copy())
53     {
54     }
55
56     virtual void performTask(WorkerContext* context)
57     {
58         RefPtr<Event> evt = MessageEvent::create(m_message, "", "", 0, 0);
59
60         if (context->onmessage()) {
61             evt->setTarget(context);
62             evt->setCurrentTarget(context);
63             context->onmessage()->handleEvent(evt.get(), false);
64         }
65
66         ExceptionCode ec = 0;
67         context->dispatchEvent(evt.release(), ec);
68         ASSERT(!ec);
69
70         context->thread()->messagingProxy()->confirmWorkerThreadMessage(context->hasPendingActivity());
71     }
72
73 private:
74     String m_message;
75 };
76
77 class MessageWorkerTask : public ScriptExecutionContext::Task {
78 public:
79     static PassRefPtr<MessageWorkerTask> create(const String& message, WorkerMessagingProxy* messagingProxy)
80     {
81         return adoptRef(new MessageWorkerTask(message, messagingProxy));
82     }
83
84 private:
85     MessageWorkerTask(const String& message, WorkerMessagingProxy* messagingProxy)
86         : m_message(message.copy())
87         , m_messagingProxy(messagingProxy)
88     {
89     }
90
91     virtual void performTask(ScriptExecutionContext*)
92     {
93         Worker* workerObject = m_messagingProxy->workerObject();
94         if (!workerObject || m_messagingProxy->askedToTerminate())
95             return;
96
97         RefPtr<Event> evt = MessageEvent::create(m_message, "", "", 0, 0);
98
99         if (workerObject->onmessage()) {
100             evt->setTarget(workerObject);
101             evt->setCurrentTarget(workerObject);
102             workerObject->onmessage()->handleEvent(evt.get(), false);
103         }
104
105         ExceptionCode ec = 0;
106         workerObject->dispatchEvent(evt.release(), ec);
107         ASSERT(!ec);
108     }
109
110 private:
111     String m_message;
112     WorkerMessagingProxy* m_messagingProxy;
113 };
114
115 class WorkerExceptionTask : public ScriptExecutionContext::Task {
116 public:
117     static PassRefPtr<WorkerExceptionTask> create(const String& errorMessage, int lineNumber, const String& sourceURL, WorkerMessagingProxy* messagingProxy)
118     {
119         return adoptRef(new WorkerExceptionTask(errorMessage, lineNumber, sourceURL, messagingProxy));
120     }
121
122 private:
123     WorkerExceptionTask(const String& errorMessage, int lineNumber, const String& sourceURL, WorkerMessagingProxy* messagingProxy)
124         : m_errorMessage(errorMessage.copy())
125         , m_lineNumber(lineNumber)
126         , m_sourceURL(sourceURL.copy())
127         , m_messagingProxy(messagingProxy)
128     {
129     }
130
131     virtual void performTask(ScriptExecutionContext* context)
132     {
133         if (!m_messagingProxy->askedToTerminate())
134             context->reportException(m_errorMessage, m_lineNumber, m_sourceURL);
135     }
136
137     String m_errorMessage;
138     int m_lineNumber;
139     String m_sourceURL;
140     WorkerMessagingProxy* m_messagingProxy;
141 };
142
143 class WorkerContextDestroyedTask : public ScriptExecutionContext::Task {
144 public:
145     static PassRefPtr<WorkerContextDestroyedTask> create(WorkerMessagingProxy* messagingProxy)
146     {
147         return adoptRef(new WorkerContextDestroyedTask(messagingProxy));
148     }
149
150 private:
151     WorkerContextDestroyedTask(WorkerMessagingProxy* messagingProxy)
152         : m_messagingProxy(messagingProxy)
153     {
154     }
155
156     virtual void performTask(ScriptExecutionContext*)
157     {
158         m_messagingProxy->workerContextDestroyedInternal();
159     }
160
161     WorkerMessagingProxy* m_messagingProxy;
162 };
163
164 class WorkerThreadActivityReportTask : public ScriptExecutionContext::Task {
165 public:
166     static PassRefPtr<WorkerThreadActivityReportTask> create(WorkerMessagingProxy* messagingProxy, bool confirmingMessage, bool hasPendingActivity)
167     {
168         return adoptRef(new WorkerThreadActivityReportTask(messagingProxy, confirmingMessage, hasPendingActivity));
169     }
170
171 private:
172     WorkerThreadActivityReportTask(WorkerMessagingProxy* messagingProxy, bool confirmingMessage, bool hasPendingActivity)
173         : m_messagingProxy(messagingProxy)
174         , m_confirmingMessage(confirmingMessage)
175         , m_hasPendingActivity(hasPendingActivity)
176     {
177     }
178
179     virtual void performTask(ScriptExecutionContext*)
180     {
181         m_messagingProxy->reportWorkerThreadActivityInternal(m_confirmingMessage, m_hasPendingActivity);
182     }
183
184     WorkerMessagingProxy* m_messagingProxy;
185     bool m_confirmingMessage;
186     bool m_hasPendingActivity;
187 };
188
189
190 WorkerMessagingProxy::WorkerMessagingProxy(PassRefPtr<ScriptExecutionContext> scriptExecutionContext, Worker* workerObject)
191     : m_scriptExecutionContext(scriptExecutionContext)
192     , m_workerObject(workerObject)
193     , m_unconfirmedMessageCount(0)
194     , m_workerThreadHadPendingActivity(false)
195     , m_askedToTerminate(false)
196 {
197     ASSERT(m_workerObject);
198     ASSERT((m_scriptExecutionContext->isDocument() && isMainThread())
199         || (m_scriptExecutionContext->isWorkerContext() && currentThread() == static_cast<WorkerContext*>(m_scriptExecutionContext.get())->thread()->threadID()));
200 }
201
202 WorkerMessagingProxy::~WorkerMessagingProxy()
203 {
204     ASSERT(!m_workerObject);
205     ASSERT((m_scriptExecutionContext->isDocument() && isMainThread())
206         || (m_scriptExecutionContext->isWorkerContext() && currentThread() == static_cast<WorkerContext*>(m_scriptExecutionContext.get())->thread()->threadID()));
207 }
208
209 void WorkerMessagingProxy::postMessageToWorkerObject(const String& message)
210 {
211     m_scriptExecutionContext->postTask(MessageWorkerTask::create(message, this));
212 }
213
214 void WorkerMessagingProxy::postMessageToWorkerContext(const String& message)
215 {
216     if (m_askedToTerminate)
217         return;
218
219     if (m_workerThread) {
220         ++m_unconfirmedMessageCount;
221         m_workerThread->runLoop().postTask(MessageWorkerContextTask::create(message));
222     } else
223         m_queuedEarlyTasks.append(MessageWorkerContextTask::create(message));
224 }
225
226 void WorkerMessagingProxy::postTaskToParentContext(PassRefPtr<ScriptExecutionContext::Task> task)
227 {
228     m_scriptExecutionContext->postTask(task);
229 }
230
231 void WorkerMessagingProxy::postWorkerException(const String& errorMessage, int lineNumber, const String& sourceURL)
232 {
233     m_scriptExecutionContext->postTask(WorkerExceptionTask::create(errorMessage, lineNumber, sourceURL, this));
234 }
235
236 void WorkerMessagingProxy::workerThreadCreated(PassRefPtr<WorkerThread> workerThread)
237 {
238     m_workerThread = workerThread;
239
240     if (m_askedToTerminate) {
241         // Worker.terminate() could be called from JS before the thread was created.
242         m_workerThread->stop();
243     } else {
244         unsigned taskCount = m_queuedEarlyTasks.size();
245         ASSERT(!m_unconfirmedMessageCount);
246         m_unconfirmedMessageCount = taskCount + 1; // Worker initialization counts as a pending message.
247
248         for (unsigned i = 0; i < taskCount; ++i)
249             m_workerThread->runLoop().postTask(m_queuedEarlyTasks[i]);
250         m_queuedEarlyTasks.clear();
251     }
252 }
253
254 void WorkerMessagingProxy::workerObjectDestroyed()
255 {
256     m_workerObject = 0;
257     if (m_workerThread)
258         terminate();
259     else
260         workerContextDestroyedInternal();
261 }
262
263 void WorkerMessagingProxy::workerContextDestroyed()
264 {
265     m_scriptExecutionContext->postTask(WorkerContextDestroyedTask::create(this));
266     // Will execute workerContextDestroyedInternal() on context's thread.
267 }
268
269 void WorkerMessagingProxy::workerContextDestroyedInternal()
270 {
271     // WorkerContextDestroyedTask is always the last to be performed, so the proxy is not needed for communication
272     // in either side any more. However, the Worker object may still exist, and it assumes that the proxy exists, too.
273     m_workerThread = 0;
274     if (!m_workerObject)
275         delete this;
276 }
277
278 void WorkerMessagingProxy::terminate()
279 {
280     if (m_askedToTerminate)
281         return;
282     m_askedToTerminate = true;
283
284     if (m_workerThread)
285         m_workerThread->stop();
286 }
287
288 void WorkerMessagingProxy::confirmWorkerThreadMessage(bool hasPendingActivity)
289 {
290     m_scriptExecutionContext->postTask(WorkerThreadActivityReportTask::create(this, true, hasPendingActivity));
291     // Will execute reportWorkerThreadActivityInternal() on context's thread.
292 }
293
294 void WorkerMessagingProxy::reportWorkerThreadActivity(bool hasPendingActivity)
295 {
296     m_scriptExecutionContext->postTask(WorkerThreadActivityReportTask::create(this, false, hasPendingActivity));
297     // Will execute reportWorkerThreadActivityInternal() on context's thread.
298 }
299
300 void WorkerMessagingProxy::reportWorkerThreadActivityInternal(bool confirmingMessage, bool hasPendingActivity)
301 {
302     if (confirmingMessage && !m_askedToTerminate) {
303         ASSERT(m_unconfirmedMessageCount);
304         --m_unconfirmedMessageCount;
305     }
306
307     m_workerThreadHadPendingActivity = hasPendingActivity;
308 }
309
310 bool WorkerMessagingProxy::workerThreadHasPendingActivity() const
311 {
312     return (m_unconfirmedMessageCount || m_workerThreadHadPendingActivity) && !m_askedToTerminate;
313 }
314
315 } // namespace WebCore
316
317 #endif // ENABLE(WORKERS)