2 * Copyright (C) 2008 Apple 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
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "MessagePort.h"
30 #include "DOMWindow.h"
32 #include "EventException.h"
33 #include "EventNames.h"
34 #include "ExceptionCode.h"
35 #include "MessageEvent.h"
36 #include "SecurityOrigin.h"
38 #include "WorkerContext.h"
39 #include <wtf/text/AtomicString.h>
43 MessagePort::MessagePort(ScriptExecutionContext& scriptExecutionContext)
46 , m_scriptExecutionContext(&scriptExecutionContext)
48 m_scriptExecutionContext->createdMessagePort(this);
50 // Don't need to call processMessagePortMessagesSoon() here, because the port will not be opened until start() is invoked.
53 MessagePort::~MessagePort()
56 if (m_scriptExecutionContext)
57 m_scriptExecutionContext->destroyedMessagePort(this);
60 // FIXME: remove this when we update the ObjC bindings (bug #28774).
61 void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, MessagePort* port, ExceptionCode& ec)
63 MessagePortArray ports;
66 postMessage(message, &ports, ec);
69 void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, ExceptionCode& ec)
71 postMessage(message, static_cast<MessagePortArray*>(0), ec);
74 void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionCode& ec)
78 ASSERT(m_scriptExecutionContext);
80 OwnPtr<MessagePortChannelArray> channels;
81 // Make sure we aren't connected to any of the passed-in ports.
83 for (unsigned int i = 0; i < ports->size(); ++i) {
84 MessagePort* dataPort = (*ports)[i].get();
85 if (dataPort == this || m_entangledChannel->isConnectedTo(dataPort)) {
90 channels = MessagePort::disentanglePorts(ports, ec);
94 m_entangledChannel->postMessageToRemote(MessagePortChannel::EventData::create(message, channels.release()));
97 PassOwnPtr<MessagePortChannel> MessagePort::disentangle(ExceptionCode& ec)
99 if (!m_entangledChannel)
100 ec = INVALID_STATE_ERR;
102 m_entangledChannel->disentangle();
104 // We can't receive any messages or generate any events, so remove ourselves from the list of active ports.
105 ASSERT(m_scriptExecutionContext);
106 m_scriptExecutionContext->destroyedMessagePort(this);
107 m_scriptExecutionContext = 0;
109 return m_entangledChannel.release();
112 // Invoked to notify us that there are messages available for this port.
113 // This code may be called from another thread, and so should not call any non-threadsafe APIs (i.e. should not call into the entangled channel or access mutable variables).
114 void MessagePort::messageAvailable()
116 ASSERT(m_scriptExecutionContext);
117 m_scriptExecutionContext->processMessagePortMessagesSoon();
120 void MessagePort::start()
122 // Do nothing if we've been cloned or closed.
126 ASSERT(m_scriptExecutionContext);
131 m_scriptExecutionContext->processMessagePortMessagesSoon();
134 void MessagePort::close()
139 m_entangledChannel->close();
142 void MessagePort::entangle(PassOwnPtr<MessagePortChannel> remote)
144 // Only invoked to set our initial entanglement.
145 ASSERT(!m_entangledChannel);
146 ASSERT(m_scriptExecutionContext);
148 // Don't entangle the ports if the channel is closed.
149 if (remote->entangleIfOpen(this))
150 m_entangledChannel = remote;
153 void MessagePort::contextDestroyed()
155 ASSERT(m_scriptExecutionContext);
156 // Must be closed before blowing away the cached context, to ensure that we get no more calls to messageAvailable().
157 // ScriptExecutionContext::closeMessagePorts() takes care of that.
159 m_scriptExecutionContext = 0;
162 ScriptExecutionContext* MessagePort::scriptExecutionContext() const
164 return m_scriptExecutionContext;
167 void MessagePort::dispatchMessages()
169 // Messages for contexts that are not fully active get dispatched too, but JSAbstractEventListener::handleEvent() doesn't call handlers for these.
170 // The HTML5 spec specifies that any messages sent to a document that is not fully active should be dropped, so this behavior is OK.
173 OwnPtr<MessagePortChannel::EventData> eventData;
174 while (m_entangledChannel && m_entangledChannel->tryGetMessageFromRemote(eventData)) {
177 // close() in Worker onmessage handler should prevent next message from dispatching.
178 if (m_scriptExecutionContext->isWorkerContext() && static_cast<WorkerContext*>(m_scriptExecutionContext)->isClosing())
182 OwnPtr<MessagePortArray> ports = MessagePort::entanglePorts(*m_scriptExecutionContext, eventData->channels());
183 RefPtr<Event> evt = MessageEvent::create(ports.release(), eventData->message());
185 ExceptionCode ec = 0;
186 dispatchEvent(evt.release(), ec);
191 bool MessagePort::hasPendingActivity()
193 // The spec says that entangled message ports should always be treated as if they have a strong reference.
194 // We'll also stipulate that the queue needs to be open (if the app drops its reference to the port before start()-ing it, then it's not really entangled as it's unreachable).
195 if (m_started && m_entangledChannel && m_entangledChannel->hasPendingActivity())
197 if (isEntangled() && !locallyEntangledPort())
202 MessagePort* MessagePort::locallyEntangledPort()
204 return m_entangledChannel ? m_entangledChannel->locallyEntangledPort(m_scriptExecutionContext) : 0;
207 PassOwnPtr<MessagePortChannelArray> MessagePort::disentanglePorts(const MessagePortArray* ports, ExceptionCode& ec)
209 if (!ports || !ports->size())
212 // HashSet used to efficiently check for duplicates in the passed-in array.
213 HashSet<MessagePort*> portSet;
215 // Walk the incoming array - if there are any duplicate ports, or null ports or cloned ports, throw an error (per section 8.3.3 of the HTML5 spec).
216 for (unsigned int i = 0; i < ports->size(); ++i) {
217 MessagePort* port = (*ports)[i].get();
218 if (!port || port->isCloned() || portSet.contains(port)) {
225 // Passed-in ports passed validity checks, so we can disentangle them.
226 OwnPtr<MessagePortChannelArray> portArray = adoptPtr(new MessagePortChannelArray(ports->size()));
227 for (unsigned int i = 0 ; i < ports->size() ; ++i) {
228 OwnPtr<MessagePortChannel> channel = (*ports)[i]->disentangle(ec);
229 ASSERT(!ec); // Can't generate exception here if passed above checks.
230 (*portArray)[i] = channel.release();
232 return portArray.release();
235 PassOwnPtr<MessagePortArray> MessagePort::entanglePorts(ScriptExecutionContext& context, PassOwnPtr<MessagePortChannelArray> channels)
237 if (!channels || !channels->size())
240 OwnPtr<MessagePortArray> portArray = adoptPtr(new MessagePortArray(channels->size()));
241 for (unsigned int i = 0; i < channels->size(); ++i) {
242 RefPtr<MessagePort> port = MessagePort::create(context);
243 port->entangle((*channels)[i].release());
244 (*portArray)[i] = port.release();
246 return portArray.release();
249 EventTargetData* MessagePort::eventTargetData()
251 return &m_eventTargetData;
254 EventTargetData* MessagePort::ensureEventTargetData()
256 return &m_eventTargetData;
259 } // namespace WebCore