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(WorkerScriptLoader::create(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 RefPtr<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 // Keep the worker + JS wrapper alive until the resource load is complete in case we need to dispatch an error event.
138 m_worker->setPendingActivity(m_worker.get());
141 m_scriptLoader->loadAsynchronously(m_worker->scriptExecutionContext(), m_url, DenyCrossOriginRequests, this);
145 // Extracts a WebMessagePortChannel from a MessagePortChannel.
146 static WebMessagePortChannel* getWebPort(PassOwnPtr<MessagePortChannel> port)
148 // Extract the WebMessagePortChannel to send to the worker.
149 PlatformMessagePortChannel* platformChannel = port->channel();
150 WebMessagePortChannel* webPort = platformChannel->webChannelRelease();
151 webPort->setClient(0);
155 void SharedWorkerScriptLoader::didReceiveResponse(const ResourceResponse& response)
157 m_responseAppCacheID = response.appCacheID();
160 void SharedWorkerScriptLoader::notifyFinished()
162 if (m_scriptLoader->failed()) {
163 m_worker->dispatchEvent(Event::create(eventNames().errorEvent, false, true));
166 InspectorInstrumentation::scriptImported(m_worker->scriptExecutionContext(), m_scriptLoader->identifier(), m_scriptLoader->script());
167 // Pass the script off to the worker, then send a connect event.
168 m_webWorker->startWorkerContext(m_url, m_name, m_worker->scriptExecutionContext()->userAgent(m_url), m_scriptLoader->script(), m_responseAppCacheID);
173 void SharedWorkerScriptLoader::sendConnect()
175 // Send the connect event off, and linger until it is done sending.
176 m_webWorker->connect(getWebPort(m_port.release()), this);
179 void SharedWorkerScriptLoader::connected()
181 // Connect event has been sent, so free ourselves (this releases the SharedWorker so it can be freed as well if unreferenced).
185 bool SharedWorkerRepository::isAvailable()
187 // Allow the WebKitClient to determine if SharedWorkers are available.
188 return WebKit::webKitClient()->sharedWorkerRepository();
191 static WebSharedWorkerRepository::DocumentID getId(void* document)
194 return reinterpret_cast<WebSharedWorkerRepository::DocumentID>(document);
197 void SharedWorkerRepository::connect(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, const KURL& url, const String& name, ExceptionCode& ec)
199 // This should not be callable unless there's a SharedWorkerRepository for
200 // this context (since isAvailable() should have returned null).
201 ASSERT(WebKit::webKitClient()->sharedWorkerRepository());
203 // No nested workers (for now) - connect() should only be called from document context.
204 ASSERT(worker->scriptExecutionContext()->isDocument());
205 Document* document = static_cast<Document*>(worker->scriptExecutionContext());
206 WebFrameImpl* webFrame = WebFrameImpl::fromFrame(document->frame());
207 OwnPtr<WebSharedWorker> webWorker;
208 webWorker = adoptPtr(webFrame->client()->createSharedWorker(webFrame, url, name, getId(document)));
211 // Existing worker does not match this url, so return an error back to the caller.
212 ec = URL_MISMATCH_ERR;
216 WebKit::webKitClient()->sharedWorkerRepository()->addSharedWorker(
217 webWorker.get(), getId(document));
219 // The loader object manages its own lifecycle (and the lifecycles of the two worker objects).
220 // It will free itself once loading is completed.
221 SharedWorkerScriptLoader* loader = new SharedWorkerScriptLoader(worker, url, name, port, webWorker.release());
225 void SharedWorkerRepository::documentDetached(Document* document)
227 WebSharedWorkerRepository* repo = WebKit::webKitClient()->sharedWorkerRepository();
229 repo->documentDetached(getId(document));
231 // Stop the creation of any pending SharedWorkers for this context.
232 // FIXME: Need a way to invoke this for WorkerContexts as well when we support for nested workers.
233 SharedWorkerScriptLoader::stopAllLoadersForContext(document);
236 bool SharedWorkerRepository::hasSharedWorkers(Document* document)
238 WebSharedWorkerRepository* repo = WebKit::webKitClient()->sharedWorkerRepository();
239 return repo && repo->hasSharedWorkers(getId(document));
244 } // namespace WebCore
246 #endif // ENABLE(SHARED_WORKERS)