Tighten AbstractWorker and subclasses a bit.
[WebKit-https.git] / Source / WebCore / workers / Worker.cpp
1 /*
2  * Copyright (C) 2008, 2010 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 "Worker.h"
33
34 #include "DOMWindow.h"
35 #include "CachedResourceLoader.h"
36 #include "Document.h"
37 #include "EventException.h"
38 #include "EventListener.h"
39 #include "EventNames.h"
40 #include "ExceptionCode.h"
41 #include "FeatureObserver.h"
42 #include "Frame.h"
43 #include "FrameLoader.h"
44 #include "InspectorInstrumentation.h"
45 #include "MessageEvent.h"
46 #include "NetworkStateNotifier.h"
47 #include "TextEncoding.h"
48 #include "WorkerGlobalScopeProxy.h"
49 #include "WorkerScriptLoader.h"
50 #include "WorkerThread.h"
51 #include <wtf/HashSet.h>
52 #include <wtf/MainThread.h>
53
54 namespace WebCore {
55
56 static HashSet<Worker*>* allWorkers;
57
58 void networkStateChanged(bool isOnLine)
59 {
60     HashSet<Worker*>::iterator end = allWorkers->end();
61     for (HashSet<Worker*>::iterator it = allWorkers->begin(); it != end; ++it)
62         (*it)->notifyNetworkStateChange(isOnLine);
63 }
64
65 inline Worker::Worker(ScriptExecutionContext& context)
66     : AbstractWorker(context)
67     , m_contextProxy(WorkerGlobalScopeProxy::create(this))
68 {
69     if (!allWorkers) {
70         allWorkers = new HashSet<Worker*>;
71         networkStateNotifier().addNetworkStateChangeListener(networkStateChanged);
72     }
73
74     HashSet<Worker*>::AddResult addResult = allWorkers->add(this);
75     ASSERT_UNUSED(addResult, addResult.isNewEntry);
76 }
77
78 PassRefPtr<Worker> Worker::create(ScriptExecutionContext& context, const String& url, ExceptionCode& ec)
79 {
80     ASSERT(isMainThread());
81
82     // We don't currently support nested workers, so workers can only be created from documents.
83     ASSERT_WITH_SECURITY_IMPLICATION(context.isDocument());
84     Document& document = static_cast<Document&>(context);
85
86     FeatureObserver::observe(document.domWindow(), FeatureObserver::WorkerStart);
87
88     RefPtr<Worker> worker = adoptRef(new Worker(context));
89
90     worker->suspendIfNeeded();
91
92     URL scriptURL = worker->resolveURL(url, ec);
93     if (scriptURL.isEmpty())
94         return 0;
95
96     // The worker context does not exist while loading, so we must ensure that the worker object is not collected, nor are its event listeners.
97     worker->setPendingActivity(worker.get());
98
99     worker->m_scriptLoader = WorkerScriptLoader::create();
100 #if PLATFORM(BLACKBERRY)
101     worker->m_scriptLoader->setTargetType(ResourceRequest::TargetIsWorker);
102 #endif
103     worker->m_scriptLoader->loadAsynchronously(&context, scriptURL, DenyCrossOriginRequests, worker.get());
104
105     return worker.release();
106 }
107
108 Worker::~Worker()
109 {
110     ASSERT(isMainThread());
111     ASSERT(scriptExecutionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists.
112     allWorkers->remove(this);
113     m_contextProxy->workerObjectDestroyed();
114 }
115
116 void Worker::postMessage(PassRefPtr<SerializedScriptValue> message, MessagePort* port, ExceptionCode& ec)
117 {
118     MessagePortArray ports;
119     if (port)
120         ports.append(port);
121     postMessage(message, &ports, ec);
122 }
123
124 void Worker::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionCode& ec)
125 {
126     // Disentangle the port in preparation for sending it to the remote context.
127     OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, ec);
128     if (ec)
129         return;
130     m_contextProxy->postMessageToWorkerGlobalScope(message, channels.release());
131 }
132
133 void Worker::terminate()
134 {
135     m_contextProxy->terminateWorkerGlobalScope();
136 }
137
138 bool Worker::canSuspend() const
139 {
140     // FIXME: It is not currently possible to suspend a worker, so pages with workers can not go into page cache.
141     return false;
142 }
143
144 void Worker::stop()
145 {
146     terminate();
147 }
148
149 bool Worker::hasPendingActivity() const
150 {
151     return m_contextProxy->hasPendingActivity() || ActiveDOMObject::hasPendingActivity();
152 }
153
154 void Worker::notifyNetworkStateChange(bool isOnLine)
155 {
156     m_contextProxy->notifyNetworkStateChange(isOnLine);
157 }
158
159 void Worker::didReceiveResponse(unsigned long identifier, const ResourceResponse&)
160 {
161     InspectorInstrumentation::didReceiveScriptResponse(scriptExecutionContext(), identifier);
162 }
163
164 void Worker::notifyFinished()
165 {
166     if (m_scriptLoader->failed())
167         dispatchEvent(Event::create(eventNames().errorEvent, false, true));
168     else {
169         WorkerThreadStartMode startMode = DontPauseWorkerGlobalScopeOnStart;
170         if (InspectorInstrumentation::shouldPauseDedicatedWorkerOnStart(scriptExecutionContext()))
171             startMode = PauseWorkerGlobalScopeOnStart;
172         m_contextProxy->startWorkerGlobalScope(m_scriptLoader->url(), scriptExecutionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), startMode);
173         InspectorInstrumentation::scriptImported(scriptExecutionContext(), m_scriptLoader->identifier(), m_scriptLoader->script());
174     }
175     m_scriptLoader = nullptr;
176
177     unsetPendingActivity(this);
178 }
179
180 } // namespace WebCore
181
182 #endif // ENABLE(WORKERS)