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.
32 #include "WebSharedWorkerImpl.h"
34 #include "public/platform/WebFileError.h"
35 #include "public/platform/WebMessagePortChannel.h"
36 #include "public/platform/WebString.h"
37 #include "public/platform/WebURL.h"
38 #include "wtf/MainThread.h"
39 #include "WebDataSourceImpl.h"
40 #include "WebFrameClient.h"
41 #include "WebFrameImpl.h"
42 #include "WebRuntimeFeatures.h"
43 #include "WebSettings.h"
44 #include "WebSharedWorkerClient.h"
46 #include "WorkerFileSystemClient.h"
47 #include "WorkerPermissionClient.h"
48 #include "core/dom/CrossThreadTask.h"
49 #include "core/dom/Document.h"
50 #include "core/dom/ExecutionContext.h"
51 #include "core/dom/MessagePortChannel.h"
52 #include "core/events/MessageEvent.h"
53 #include "core/html/HTMLFormElement.h"
54 #include "core/inspector/WorkerDebuggerAgent.h"
55 #include "core/inspector/WorkerInspectorController.h"
56 #include "core/loader/FrameLoadRequest.h"
57 #include "core/loader/FrameLoader.h"
58 #include "core/page/Page.h"
59 #include "core/page/PageGroup.h"
60 #include "core/workers/SharedWorkerGlobalScope.h"
61 #include "core/workers/SharedWorkerThread.h"
62 #include "core/workers/WorkerClients.h"
63 #include "core/workers/WorkerGlobalScope.h"
64 #include "core/workers/WorkerLoaderProxy.h"
65 #include "core/workers/WorkerThread.h"
66 #include "core/workers/WorkerThreadStartupData.h"
67 #include "modules/webdatabase/DatabaseTask.h"
68 #include "public/web/WebWorkerPermissionClientProxy.h"
69 #include "weborigin/KURL.h"
70 #include "weborigin/SecurityOrigin.h"
71 #include "wtf/Functional.h"
73 using namespace WebCore;
77 // This function is called on the main thread to force to initialize some static
78 // values used in WebKit before any worker thread is started. This is because in
79 // our worker processs, we do not run any WebKit code in main thread and thus
80 // when multiple workers try to start at the same time, we might hit crash due
81 // to contention for initializing static values.
82 static void initializeWebKitStaticValues()
84 static bool initialized = false;
87 // Note that we have to pass a URL with valid protocol in order to follow
88 // the path to do static value initializations.
89 RefPtr<SecurityOrigin> origin =
90 SecurityOrigin::create(KURL(ParsedURLString, "http://localhost"));
95 WebSharedWorkerImpl::WebSharedWorkerImpl(WebSharedWorkerClient* client)
98 , m_askedToTerminate(false)
99 , m_client(WeakReference<WebSharedWorkerClient>::create(client))
100 , m_clientWeakPtr(WeakPtr<WebSharedWorkerClient>(m_client))
101 , m_pauseWorkerContextOnStart(false)
103 initializeWebKitStaticValues();
106 WebSharedWorkerImpl::~WebSharedWorkerImpl()
109 // Detach the client before closing the view to avoid getting called back.
110 toWebFrameImpl(m_mainFrame)->setClient(0);
113 m_mainFrame->close();
116 void WebSharedWorkerImpl::stopWorkerThread()
118 if (m_askedToTerminate)
120 m_askedToTerminate = true;
122 m_workerThread->stop();
125 void WebSharedWorkerImpl::initializeLoader(const WebURL& url)
127 // Create 'shadow page'. This page is never displayed, it is used to proxy the
128 // loading requests from the worker context to the rest of WebKit and Chromium
131 m_webView = WebView::create(0);
132 m_webView->settings()->setOfflineWebApplicationCacheEnabled(WebRuntimeFeatures::isApplicationCacheEnabled());
133 // FIXME: Settings information should be passed to the Worker process from Browser process when the worker
134 // is created (similar to RenderThread::OnCreateNewView).
135 m_mainFrame = WebFrame::create(this);
136 m_webView->setMainFrame(m_mainFrame);
138 WebFrameImpl* webFrame = toWebFrameImpl(m_webView->mainFrame());
140 // Construct substitute data source for the 'shadow page'. We only need it
141 // to have same origin as the worker so the loading checks work correctly.
143 int length = static_cast<int>(content.length());
144 RefPtr<SharedBuffer> buffer(SharedBuffer::create(content.data(), length));
145 webFrame->frame()->loader().load(FrameLoadRequest(0, ResourceRequest(url), SubstituteData(buffer, "text/html", "UTF-8", KURL())));
147 // This document will be used as 'loading context' for the worker.
148 m_loadingDocument = webFrame->frame()->document();
151 void WebSharedWorkerImpl::didCreateDataSource(WebFrame*, WebDataSource* ds)
153 // Tell the loader to load the data into the 'shadow page' synchronously,
154 // so we can grab the resulting Document right after load.
155 static_cast<WebDataSourceImpl*>(ds)->setDeferMainResourceDataLoad(false);
158 WebApplicationCacheHost* WebSharedWorkerImpl::createApplicationCacheHost(WebFrame*, WebApplicationCacheHostClient* appcacheHostClient)
161 return client()->createApplicationCacheHost(appcacheHostClient);
165 // WorkerReportingProxy --------------------------------------------------------
167 void WebSharedWorkerImpl::postExceptionToWorkerObject(const String& errorMessage,
170 const String& sourceURL)
172 // Not suppported in SharedWorker.
175 void WebSharedWorkerImpl::postConsoleMessageToWorkerObject(MessageSource source,
177 const String& message,
179 const String& sourceURL)
181 // Not supported in SharedWorker.
184 void WebSharedWorkerImpl::postMessageToPageInspector(const String& message)
186 callOnMainThread(bind(&WebSharedWorkerClient::dispatchDevToolsMessage, m_clientWeakPtr, message.isolatedCopy()));
189 void WebSharedWorkerImpl::updateInspectorStateCookie(const String& cookie)
191 callOnMainThread(bind(&WebSharedWorkerClient::saveDevToolsAgentState, m_clientWeakPtr, cookie.isolatedCopy()));
194 void WebSharedWorkerImpl::workerGlobalScopeClosed()
196 callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread, this));
199 void WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread()
202 client()->workerContextClosed();
207 void WebSharedWorkerImpl::workerGlobalScopeDestroyed()
209 callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeDestroyedOnMainThread, this));
212 void WebSharedWorkerImpl::workerGlobalScopeDestroyedOnMainThread()
215 client()->workerContextDestroyed();
216 // The lifetime of this proxy is controlled by the worker context.
220 // WorkerLoaderProxy -----------------------------------------------------------
222 void WebSharedWorkerImpl::postTaskToLoader(PassOwnPtr<ExecutionContextTask> task)
224 ASSERT(m_loadingDocument->isDocument());
225 m_loadingDocument->postTask(task);
228 bool WebSharedWorkerImpl::postTaskForModeToWorkerGlobalScope(
229 PassOwnPtr<ExecutionContextTask> task, const String& mode)
231 m_workerThread->runLoop().postTaskForMode(task, mode);
235 WebWorkerBase* WebSharedWorkerImpl::toWebWorkerBase()
241 bool WebSharedWorkerImpl::isStarted()
243 // Should not ever be called from the worker thread (this API is only called on WebSharedWorkerProxy on the renderer thread).
244 ASSERT_NOT_REACHED();
245 return workerThread();
248 void WebSharedWorkerImpl::connect(WebMessagePortChannel* webChannel, ConnectListener* listener)
250 OwnPtr<MessagePortChannel> channel = MessagePortChannel::create(webChannel);
251 workerThread()->runLoop().postTask(
252 createCallbackTask(&connectTask, channel.release()));
254 listener->connected();
257 void WebSharedWorkerImpl::connectTask(ExecutionContext* context, PassOwnPtr<MessagePortChannel> channel)
259 // Wrap the passed-in channel in a MessagePort, and send it off via a connect event.
260 RefPtr<MessagePort> port = MessagePort::create(*context);
261 port->entangle(channel);
262 WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
263 ASSERT_WITH_SECURITY_IMPLICATION(workerGlobalScope->isSharedWorkerGlobalScope());
264 workerGlobalScope->dispatchEvent(createConnectEvent(port));
267 void WebSharedWorkerImpl::startWorkerContext(const WebURL& url, const WebString& name, const WebString& userAgent, const WebString& sourceCode, const WebString& contentSecurityPolicy, WebContentSecurityPolicyType policyType, long long)
269 initializeLoader(url);
271 WorkerThreadStartMode startMode = m_pauseWorkerContextOnStart ? PauseWorkerGlobalScopeOnStart : DontPauseWorkerGlobalScopeOnStart;
272 OwnPtr<WorkerClients> workerClients = WorkerClients::create();
273 provideLocalFileSystemToWorker(workerClients.get(), WorkerFileSystemClient::create());
274 WebSecurityOrigin webSecurityOrigin(m_loadingDocument->securityOrigin());
275 providePermissionClientToWorker(workerClients.get(), adoptPtr(client()->createWorkerPermissionClientProxy(webSecurityOrigin)));
276 OwnPtr<WorkerThreadStartupData> startupData = WorkerThreadStartupData::create(url, userAgent, sourceCode, startMode, contentSecurityPolicy, static_cast<WebCore::ContentSecurityPolicy::HeaderType>(policyType), workerClients.release());
277 setWorkerThread(SharedWorkerThread::create(name, *this, *this, startupData.release()));
279 workerThread()->start();
282 void WebSharedWorkerImpl::terminateWorkerContext()
287 void WebSharedWorkerImpl::clientDestroyed()
292 void WebSharedWorkerImpl::pauseWorkerContextOnStart()
294 m_pauseWorkerContextOnStart = true;
297 static void resumeWorkerContextTask(ExecutionContext* context, bool)
299 toWorkerGlobalScope(context)->workerInspectorController()->resume();
302 void WebSharedWorkerImpl::resumeWorkerContext()
304 m_pauseWorkerContextOnStart = false;
306 workerThread()->runLoop().postTaskForMode(createCallbackTask(resumeWorkerContextTask, true), WorkerDebuggerAgent::debuggerTaskMode);
309 static void connectToWorkerContextInspectorTask(ExecutionContext* context, bool)
311 toWorkerGlobalScope(context)->workerInspectorController()->connectFrontend();
314 void WebSharedWorkerImpl::attachDevTools()
316 workerThread()->runLoop().postTaskForMode(createCallbackTask(connectToWorkerContextInspectorTask, true), WorkerDebuggerAgent::debuggerTaskMode);
319 static void reconnectToWorkerContextInspectorTask(ExecutionContext* context, const String& savedState)
321 WorkerInspectorController* ic = toWorkerGlobalScope(context)->workerInspectorController();
322 ic->restoreInspectorStateFromCookie(savedState);
326 void WebSharedWorkerImpl::reattachDevTools(const WebString& savedState)
328 workerThread()->runLoop().postTaskForMode(createCallbackTask(reconnectToWorkerContextInspectorTask, String(savedState)), WorkerDebuggerAgent::debuggerTaskMode);
331 static void disconnectFromWorkerContextInspectorTask(ExecutionContext* context, bool)
333 toWorkerGlobalScope(context)->workerInspectorController()->disconnectFrontend();
336 void WebSharedWorkerImpl::detachDevTools()
338 workerThread()->runLoop().postTaskForMode(createCallbackTask(disconnectFromWorkerContextInspectorTask, true), WorkerDebuggerAgent::debuggerTaskMode);
341 static void dispatchOnInspectorBackendTask(ExecutionContext* context, const String& message)
343 toWorkerGlobalScope(context)->workerInspectorController()->dispatchMessageFromFrontend(message);
346 void WebSharedWorkerImpl::dispatchDevToolsMessage(const WebString& message)
348 workerThread()->runLoop().postTaskForMode(createCallbackTask(dispatchOnInspectorBackendTask, String(message)), WorkerDebuggerAgent::debuggerTaskMode);
349 WorkerDebuggerAgent::interruptAndDispatchInspectorCommands(workerThread());
352 WebSharedWorker* WebSharedWorker::create(WebSharedWorkerClient* client)
354 return new WebSharedWorkerImpl(client);
357 } // namespace WebKit