2 * Copyright (C) 2009 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
33 #if ENABLE(SHARED_WORKERS)
35 #include "SharedWorkerRepository.h"
38 #include "EventNames.h"
39 #include "InspectorInstrumentation.h"
40 #include "MessagePortChannel.h"
41 #include "PlatformMessagePortChannel.h"
42 #include "ScriptExecutionContext.h"
43 #include "SharedWorker.h"
44 #include "WebFrameClient.h"
45 #include "WebFrameImpl.h"
47 #include "WebKitClient.h"
48 #include "WebMessagePortChannel.h"
49 #include "WebSharedWorker.h"
50 #include "WebSharedWorkerRepository.h"
51 #include "WebString.h"
53 #include "WorkerScriptLoader.h"
54 #include "WorkerScriptLoaderClient.h"
59 using WebKit::WebFrameImpl;
60 using WebKit::WebMessagePortChannel;
61 using WebKit::WebSharedWorker;
62 using WebKit::WebSharedWorkerRepository;
64 // Callback class that keeps the SharedWorker and WebSharedWorker objects alive while loads are potentially happening, and also translates load errors into error events on the worker.
65 class SharedWorkerScriptLoader : private WorkerScriptLoaderClient, private WebSharedWorker::ConnectListener {
67 SharedWorkerScriptLoader(PassRefPtr<SharedWorker> worker, const KURL& url, const String& name, PassOwnPtr<MessagePortChannel> port, PassOwnPtr<WebSharedWorker> webWorker)
71 , m_webWorker(webWorker)
73 , m_scriptLoader(ResourceRequestBase::TargetIsSharedWorker)
75 , m_responseAppCacheID(0)
79 ~SharedWorkerScriptLoader();
81 static void stopAllLoadersForContext(ScriptExecutionContext*);
84 // WorkerScriptLoaderClient callback
85 virtual void didReceiveResponse(const ResourceResponse&);
86 virtual void notifyFinished();
88 virtual void connected();
90 const ScriptExecutionContext* loadingContext() { return m_worker->scriptExecutionContext(); }
94 RefPtr<SharedWorker> m_worker;
97 OwnPtr<WebSharedWorker> m_webWorker;
98 OwnPtr<MessagePortChannel> m_port;
99 WorkerScriptLoader m_scriptLoader;
101 long long m_responseAppCacheID;
104 static Vector<SharedWorkerScriptLoader*>& pendingLoaders()
106 AtomicallyInitializedStatic(Vector<SharedWorkerScriptLoader*>&, loaders = *new Vector<SharedWorkerScriptLoader*>);
110 void SharedWorkerScriptLoader::stopAllLoadersForContext(ScriptExecutionContext* context)
112 // Walk our list of pending loaders and shutdown any that belong to this context.
113 Vector<SharedWorkerScriptLoader*>& loaders = pendingLoaders();
114 for (unsigned i = 0; i < loaders.size(); ) {
115 SharedWorkerScriptLoader* loader = loaders[i];
116 if (context == loader->loadingContext()) {
124 SharedWorkerScriptLoader::~SharedWorkerScriptLoader()
127 m_worker->unsetPendingActivity(m_worker.get());
130 void SharedWorkerScriptLoader::load()
133 // If the shared worker is not yet running, load the script resource for it, otherwise just send it a connect event.
134 if (m_webWorker->isStarted())
137 m_scriptLoader.loadAsynchronously(m_worker->scriptExecutionContext(), m_url, DenyCrossOriginRequests, this);
138 // Keep the worker + JS wrapper alive until the resource load is complete in case we need to dispatch an error event.
139 m_worker->setPendingActivity(m_worker.get());
144 // Extracts a WebMessagePortChannel from a MessagePortChannel.
145 static WebMessagePortChannel* getWebPort(PassOwnPtr<MessagePortChannel> port)
147 // Extract the WebMessagePortChannel to send to the worker.
148 PlatformMessagePortChannel* platformChannel = port->channel();
149 WebMessagePortChannel* webPort = platformChannel->webChannelRelease();
150 webPort->setClient(0);
154 void SharedWorkerScriptLoader::didReceiveResponse(const ResourceResponse& response)
156 m_responseAppCacheID = response.appCacheID();
159 void SharedWorkerScriptLoader::notifyFinished()
161 if (m_scriptLoader.failed()) {
162 m_worker->dispatchEvent(Event::create(eventNames().errorEvent, false, true));
165 InspectorInstrumentation::scriptImported(m_worker->scriptExecutionContext(), m_scriptLoader.identifier(), m_scriptLoader.script());
166 // Pass the script off to the worker, then send a connect event.
167 m_webWorker->startWorkerContext(m_url, m_name, m_worker->scriptExecutionContext()->userAgent(m_url), m_scriptLoader.script(), m_responseAppCacheID);
172 void SharedWorkerScriptLoader::sendConnect()
174 // Send the connect event off, and linger until it is done sending.
175 m_webWorker->connect(getWebPort(m_port.release()), this);
178 void SharedWorkerScriptLoader::connected()
180 // Connect event has been sent, so free ourselves (this releases the SharedWorker so it can be freed as well if unreferenced).
184 bool SharedWorkerRepository::isAvailable()
186 // Allow the WebKitClient to determine if SharedWorkers are available.
187 return WebKit::webKitClient()->sharedWorkerRepository();
190 static WebSharedWorkerRepository::DocumentID getId(void* document)
193 return reinterpret_cast<WebSharedWorkerRepository::DocumentID>(document);
196 void SharedWorkerRepository::connect(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, const KURL& url, const String& name, ExceptionCode& ec)
198 // This should not be callable unless there's a SharedWorkerRepository for
199 // this context (since isAvailable() should have returned null).
200 ASSERT(WebKit::webKitClient()->sharedWorkerRepository());
202 // No nested workers (for now) - connect() should only be called from document context.
203 ASSERT(worker->scriptExecutionContext()->isDocument());
204 Document* document = static_cast<Document*>(worker->scriptExecutionContext());
205 WebFrameImpl* webFrame = WebFrameImpl::fromFrame(document->frame());
206 OwnPtr<WebSharedWorker> webWorker;
207 webWorker = adoptPtr(webFrame->client()->createSharedWorker(webFrame, url, name, getId(document)));
210 // Existing worker does not match this url, so return an error back to the caller.
211 ec = URL_MISMATCH_ERR;
215 WebKit::webKitClient()->sharedWorkerRepository()->addSharedWorker(
216 webWorker.get(), getId(document));
218 // The loader object manages its own lifecycle (and the lifecycles of the two worker objects).
219 // It will free itself once loading is completed.
220 SharedWorkerScriptLoader* loader = new SharedWorkerScriptLoader(worker, url, name, port, webWorker.release());
224 void SharedWorkerRepository::documentDetached(Document* document)
226 WebSharedWorkerRepository* repo = WebKit::webKitClient()->sharedWorkerRepository();
228 repo->documentDetached(getId(document));
230 // Stop the creation of any pending SharedWorkers for this context.
231 // FIXME: Need a way to invoke this for WorkerContexts as well when we support for nested workers.
232 SharedWorkerScriptLoader::stopAllLoadersForContext(document);
235 bool SharedWorkerRepository::hasSharedWorkers(Document* document)
237 WebSharedWorkerRepository* repo = WebKit::webKitClient()->sharedWorkerRepository();
238 return repo && repo->hasSharedWorkers(getId(document));
243 } // namespace WebCore
245 #endif // ENABLE(SHARED_WORKERS)