2009-06-16 Jian Li <jianli@chromium.org>
[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& sourceCode)
202 {
203     RefPtr<WorkerThread> thread = WorkerThread::create(scriptURL, userAgent, sourceCode, *this, *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::postTaskForModeToWorkerContext(PassRefPtr<ScriptExecutionContext::Task> task, const String& mode)
226 {
227     if (m_askedToTerminate)
228         return;
229
230     ASSERT(m_workerThread);
231     m_workerThread->runLoop().postTaskForMode(task, mode);
232 }
233
234 void WorkerMessagingProxy::postTaskToLoader(PassRefPtr<ScriptExecutionContext::Task> task)
235 {
236     // FIXME: In case of nested workers, this should go directly to the root Document context.
237     ASSERT(m_scriptExecutionContext->isDocument());
238     m_scriptExecutionContext->postTask(task);
239 }
240
241 void WorkerMessagingProxy::postExceptionToWorkerObject(const String& errorMessage, int lineNumber, const String& sourceURL)
242 {
243     m_scriptExecutionContext->postTask(WorkerExceptionTask::create(errorMessage, lineNumber, sourceURL, this));
244 }
245     
246 static void postConsoleMessageTask(ScriptExecutionContext* context, WorkerMessagingProxy* messagingProxy, MessageDestination destination, MessageSource source, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceURL)
247 {
248     if (messagingProxy->askedToTerminate())
249         return;
250     context->addMessage(destination, source, level, message, lineNumber, sourceURL);
251 }
252
253 void WorkerMessagingProxy::postConsoleMessageToWorkerObject(MessageDestination destination, MessageSource source, MessageLevel level, const String& message, int lineNumber, const String& sourceURL)
254 {
255     m_scriptExecutionContext->postTask(createCallbackTask(&postConsoleMessageTask, this, destination, source, level, message, lineNumber, sourceURL));
256 }
257
258 void WorkerMessagingProxy::workerThreadCreated(PassRefPtr<WorkerThread> workerThread)
259 {
260     m_workerThread = workerThread;
261
262     if (m_askedToTerminate) {
263         // Worker.terminate() could be called from JS before the thread was created.
264         m_workerThread->stop();
265     } else {
266         unsigned taskCount = m_queuedEarlyTasks.size();
267         ASSERT(!m_unconfirmedMessageCount);
268         m_unconfirmedMessageCount = taskCount;
269         m_workerThreadHadPendingActivity = true; // Worker initialization means a pending activity.
270
271         for (unsigned i = 0; i < taskCount; ++i)
272             m_workerThread->runLoop().postTask(m_queuedEarlyTasks[i]);
273         m_queuedEarlyTasks.clear();
274     }
275 }
276
277 void WorkerMessagingProxy::workerObjectDestroyed()
278 {
279     m_workerObject = 0;
280     if (m_workerThread)
281         terminateWorkerContext();
282     else
283         workerContextDestroyedInternal();
284 }
285
286 void WorkerMessagingProxy::workerContextDestroyed()
287 {
288     m_scriptExecutionContext->postTask(WorkerContextDestroyedTask::create(this));
289     // Will execute workerContextDestroyedInternal() on context's thread.
290 }
291
292 void WorkerMessagingProxy::workerContextDestroyedInternal()
293 {
294     // WorkerContextDestroyedTask is always the last to be performed, so the proxy is not needed for communication
295     // in either side any more. However, the Worker object may still exist, and it assumes that the proxy exists, too.
296     m_askedToTerminate = true;
297     m_workerThread = 0;
298     if (!m_workerObject)
299         delete this;
300 }
301
302 void WorkerMessagingProxy::terminateWorkerContext()
303 {
304     if (m_askedToTerminate)
305         return;
306     m_askedToTerminate = true;
307
308     if (m_workerThread)
309         m_workerThread->stop();
310 }
311
312 void WorkerMessagingProxy::confirmMessageFromWorkerObject(bool hasPendingActivity)
313 {
314     m_scriptExecutionContext->postTask(WorkerThreadActivityReportTask::create(this, true, hasPendingActivity));
315     // Will execute reportPendingActivityInternal() on context's thread.
316 }
317
318 void WorkerMessagingProxy::reportPendingActivity(bool hasPendingActivity)
319 {
320     m_scriptExecutionContext->postTask(WorkerThreadActivityReportTask::create(this, false, hasPendingActivity));
321     // Will execute reportPendingActivityInternal() on context's thread.
322 }
323
324 void WorkerMessagingProxy::reportPendingActivityInternal(bool confirmingMessage, bool hasPendingActivity)
325 {
326     if (confirmingMessage && !m_askedToTerminate) {
327         ASSERT(m_unconfirmedMessageCount);
328         --m_unconfirmedMessageCount;
329     }
330
331     m_workerThreadHadPendingActivity = hasPendingActivity;
332 }
333
334 bool WorkerMessagingProxy::hasPendingActivity() const
335 {
336     return (m_unconfirmedMessageCount || m_workerThreadHadPendingActivity) && !m_askedToTerminate;
337 }
338
339 } // namespace WebCore
340
341 #endif // ENABLE(WORKERS)