- add third_party src.
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / web / WebSharedWorkerImpl.cpp
1 /*
2  * Copyright (C) 2009 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
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
13  * distribution.
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.
17  *
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.
29  */
30
31 #include "config.h"
32 #include "WebSharedWorkerImpl.h"
33
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"
45 #include "WebView.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"
72
73 using namespace WebCore;
74
75 namespace WebKit {
76
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()
83 {
84     static bool initialized = false;
85     if (!initialized) {
86         initialized = true;
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"));
91         origin.release();
92     }
93 }
94
95 WebSharedWorkerImpl::WebSharedWorkerImpl(WebSharedWorkerClient* client)
96     : m_webView(0)
97     , m_mainFrame(0)
98     , m_askedToTerminate(false)
99     , m_client(WeakReference<WebSharedWorkerClient>::create(client))
100     , m_clientWeakPtr(WeakPtr<WebSharedWorkerClient>(m_client))
101     , m_pauseWorkerContextOnStart(false)
102 {
103     initializeWebKitStaticValues();
104 }
105
106 WebSharedWorkerImpl::~WebSharedWorkerImpl()
107 {
108     ASSERT(m_webView);
109     // Detach the client before closing the view to avoid getting called back.
110     toWebFrameImpl(m_mainFrame)->setClient(0);
111
112     m_webView->close();
113     m_mainFrame->close();
114 }
115
116 void WebSharedWorkerImpl::stopWorkerThread()
117 {
118     if (m_askedToTerminate)
119         return;
120     m_askedToTerminate = true;
121     if (m_workerThread)
122         m_workerThread->stop();
123 }
124
125 void WebSharedWorkerImpl::initializeLoader(const WebURL& url)
126 {
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
129     // infrastructure.
130     ASSERT(!m_webView);
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);
137
138     WebFrameImpl* webFrame = toWebFrameImpl(m_webView->mainFrame());
139
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.
142     CString content("");
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())));
146
147     // This document will be used as 'loading context' for the worker.
148     m_loadingDocument = webFrame->frame()->document();
149 }
150
151 void WebSharedWorkerImpl::didCreateDataSource(WebFrame*, WebDataSource* ds)
152 {
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);
156 }
157
158 WebApplicationCacheHost* WebSharedWorkerImpl::createApplicationCacheHost(WebFrame*, WebApplicationCacheHostClient* appcacheHostClient)
159 {
160     if (client())
161         return client()->createApplicationCacheHost(appcacheHostClient);
162     return 0;
163 }
164
165 // WorkerReportingProxy --------------------------------------------------------
166
167 void WebSharedWorkerImpl::postExceptionToWorkerObject(const String& errorMessage,
168                                                       int lineNumber,
169                                                       int columnNumber,
170                                                       const String& sourceURL)
171 {
172     // Not suppported in SharedWorker.
173 }
174
175 void WebSharedWorkerImpl::postConsoleMessageToWorkerObject(MessageSource source,
176                                                            MessageLevel level,
177                                                            const String& message,
178                                                            int lineNumber,
179                                                            const String& sourceURL)
180 {
181     // Not supported in SharedWorker.
182 }
183
184 void WebSharedWorkerImpl::postMessageToPageInspector(const String& message)
185 {
186     callOnMainThread(bind(&WebSharedWorkerClient::dispatchDevToolsMessage, m_clientWeakPtr, message.isolatedCopy()));
187 }
188
189 void WebSharedWorkerImpl::updateInspectorStateCookie(const String& cookie)
190 {
191     callOnMainThread(bind(&WebSharedWorkerClient::saveDevToolsAgentState, m_clientWeakPtr, cookie.isolatedCopy()));
192 }
193
194 void WebSharedWorkerImpl::workerGlobalScopeClosed()
195 {
196     callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread, this));
197 }
198
199 void WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread()
200 {
201     if (client())
202         client()->workerContextClosed();
203
204     stopWorkerThread();
205 }
206
207 void WebSharedWorkerImpl::workerGlobalScopeDestroyed()
208 {
209     callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeDestroyedOnMainThread, this));
210 }
211
212 void WebSharedWorkerImpl::workerGlobalScopeDestroyedOnMainThread()
213 {
214     if (client())
215         client()->workerContextDestroyed();
216     // The lifetime of this proxy is controlled by the worker context.
217     delete this;
218 }
219
220 // WorkerLoaderProxy -----------------------------------------------------------
221
222 void WebSharedWorkerImpl::postTaskToLoader(PassOwnPtr<ExecutionContextTask> task)
223 {
224     ASSERT(m_loadingDocument->isDocument());
225     m_loadingDocument->postTask(task);
226 }
227
228 bool WebSharedWorkerImpl::postTaskForModeToWorkerGlobalScope(
229     PassOwnPtr<ExecutionContextTask> task, const String& mode)
230 {
231     m_workerThread->runLoop().postTaskForMode(task, mode);
232     return true;
233 }
234
235 WebWorkerBase* WebSharedWorkerImpl::toWebWorkerBase()
236 {
237     return this;
238 }
239
240
241 bool WebSharedWorkerImpl::isStarted()
242 {
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();
246 }
247
248 void WebSharedWorkerImpl::connect(WebMessagePortChannel* webChannel, ConnectListener* listener)
249 {
250     OwnPtr<MessagePortChannel> channel = MessagePortChannel::create(webChannel);
251     workerThread()->runLoop().postTask(
252         createCallbackTask(&connectTask, channel.release()));
253     if (listener)
254         listener->connected();
255 }
256
257 void WebSharedWorkerImpl::connectTask(ExecutionContext* context, PassOwnPtr<MessagePortChannel> channel)
258 {
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));
265 }
266
267 void WebSharedWorkerImpl::startWorkerContext(const WebURL& url, const WebString& name, const WebString& userAgent, const WebString& sourceCode, const WebString& contentSecurityPolicy, WebContentSecurityPolicyType policyType, long long)
268 {
269     initializeLoader(url);
270
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()));
278
279     workerThread()->start();
280 }
281
282 void WebSharedWorkerImpl::terminateWorkerContext()
283 {
284     stopWorkerThread();
285 }
286
287 void WebSharedWorkerImpl::clientDestroyed()
288 {
289     m_client.clear();
290 }
291
292 void WebSharedWorkerImpl::pauseWorkerContextOnStart()
293 {
294     m_pauseWorkerContextOnStart = true;
295 }
296
297 static void resumeWorkerContextTask(ExecutionContext* context, bool)
298 {
299     toWorkerGlobalScope(context)->workerInspectorController()->resume();
300 }
301
302 void WebSharedWorkerImpl::resumeWorkerContext()
303 {
304     m_pauseWorkerContextOnStart = false;
305     if (workerThread())
306         workerThread()->runLoop().postTaskForMode(createCallbackTask(resumeWorkerContextTask, true), WorkerDebuggerAgent::debuggerTaskMode);
307 }
308
309 static void connectToWorkerContextInspectorTask(ExecutionContext* context, bool)
310 {
311     toWorkerGlobalScope(context)->workerInspectorController()->connectFrontend();
312 }
313
314 void WebSharedWorkerImpl::attachDevTools()
315 {
316     workerThread()->runLoop().postTaskForMode(createCallbackTask(connectToWorkerContextInspectorTask, true), WorkerDebuggerAgent::debuggerTaskMode);
317 }
318
319 static void reconnectToWorkerContextInspectorTask(ExecutionContext* context, const String& savedState)
320 {
321     WorkerInspectorController* ic = toWorkerGlobalScope(context)->workerInspectorController();
322     ic->restoreInspectorStateFromCookie(savedState);
323     ic->resume();
324 }
325
326 void WebSharedWorkerImpl::reattachDevTools(const WebString& savedState)
327 {
328     workerThread()->runLoop().postTaskForMode(createCallbackTask(reconnectToWorkerContextInspectorTask, String(savedState)), WorkerDebuggerAgent::debuggerTaskMode);
329 }
330
331 static void disconnectFromWorkerContextInspectorTask(ExecutionContext* context, bool)
332 {
333     toWorkerGlobalScope(context)->workerInspectorController()->disconnectFrontend();
334 }
335
336 void WebSharedWorkerImpl::detachDevTools()
337 {
338     workerThread()->runLoop().postTaskForMode(createCallbackTask(disconnectFromWorkerContextInspectorTask, true), WorkerDebuggerAgent::debuggerTaskMode);
339 }
340
341 static void dispatchOnInspectorBackendTask(ExecutionContext* context, const String& message)
342 {
343     toWorkerGlobalScope(context)->workerInspectorController()->dispatchMessageFromFrontend(message);
344 }
345
346 void WebSharedWorkerImpl::dispatchDevToolsMessage(const WebString& message)
347 {
348     workerThread()->runLoop().postTaskForMode(createCallbackTask(dispatchOnInspectorBackendTask, String(message)), WorkerDebuggerAgent::debuggerTaskMode);
349     WorkerDebuggerAgent::interruptAndDispatchInspectorCommands(workerThread());
350 }
351
352 WebSharedWorker* WebSharedWorker::create(WebSharedWorkerClient* client)
353 {
354     return new WebSharedWorkerImpl(client);
355 }
356
357 } // namespace WebKit