cc: De-templatize the OcclusionTracker class.
[chromium-blink-merge.git] / content / child / webmessageportchannel_impl.cc
blob1e10a245dbfe64e3a09020d91425fcecc692c0de
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/child/webmessageportchannel_impl.h"
7 #include "base/bind.h"
8 #include "base/values.h"
9 #include "content/child/child_process.h"
10 #include "content/child/child_thread_impl.h"
11 #include "content/common/message_port_messages.h"
12 #include "content/public/child/v8_value_converter.h"
13 #include "third_party/WebKit/public/platform/WebMessagePortChannelClient.h"
14 #include "third_party/WebKit/public/platform/WebString.h"
15 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
16 #include "v8/include/v8.h"
18 using blink::WebMessagePortChannel;
19 using blink::WebMessagePortChannelArray;
20 using blink::WebMessagePortChannelClient;
21 using blink::WebString;
23 namespace content {
25 WebMessagePortChannelImpl::WebMessagePortChannelImpl(
26 const scoped_refptr<base::SingleThreadTaskRunner>& main_thread_task_runner)
27 : client_(NULL),
28 route_id_(MSG_ROUTING_NONE),
29 message_port_id_(MSG_ROUTING_NONE),
30 send_messages_as_values_(false),
31 is_stashed_(false),
32 main_thread_task_runner_(main_thread_task_runner) {
33 AddRef();
34 Init();
37 WebMessagePortChannelImpl::WebMessagePortChannelImpl(
38 int route_id,
39 const TransferredMessagePort& port,
40 const scoped_refptr<base::SingleThreadTaskRunner>& main_thread_task_runner)
41 : client_(NULL),
42 route_id_(route_id),
43 message_port_id_(port.id),
44 send_messages_as_values_(port.send_messages_as_values),
45 is_stashed_(false),
46 main_thread_task_runner_(main_thread_task_runner) {
47 AddRef();
48 Init();
51 WebMessagePortChannelImpl::~WebMessagePortChannelImpl() {
52 // If we have any queued messages with attached ports, manually destroy them.
53 while (!message_queue_.empty()) {
54 const WebMessagePortChannelArray& channel_array =
55 message_queue_.front().ports;
56 for (size_t i = 0; i < channel_array.size(); i++) {
57 channel_array[i]->destroy();
59 message_queue_.pop();
62 // TODO(mek): Figure out if in case of a stashed port any messages remaining
63 // in the queue need to be send back to the browser process.
64 if (message_port_id_ != MSG_ROUTING_NONE && !is_stashed_)
65 Send(new MessagePortHostMsg_DestroyMessagePort(message_port_id_));
67 if (route_id_ != MSG_ROUTING_NONE)
68 ChildThreadImpl::current()->GetRouter()->RemoveRoute(route_id_);
71 // static
72 void WebMessagePortChannelImpl::CreatePair(
73 const scoped_refptr<base::SingleThreadTaskRunner>& main_thread_task_runner,
74 blink::WebMessagePortChannel** channel1,
75 blink::WebMessagePortChannel** channel2) {
76 WebMessagePortChannelImpl* impl1 =
77 new WebMessagePortChannelImpl(main_thread_task_runner);
78 WebMessagePortChannelImpl* impl2 =
79 new WebMessagePortChannelImpl(main_thread_task_runner);
81 impl1->Entangle(impl2);
82 impl2->Entangle(impl1);
84 *channel1 = impl1;
85 *channel2 = impl2;
88 // static
89 std::vector<TransferredMessagePort>
90 WebMessagePortChannelImpl::ExtractMessagePortIDs(
91 WebMessagePortChannelArray* channels) {
92 std::vector<TransferredMessagePort> message_ports;
93 if (channels) {
94 // Extract the port IDs from the source array, then free it.
95 message_ports = ExtractMessagePortIDs(*channels);
96 delete channels;
98 return message_ports;
101 // static
102 std::vector<TransferredMessagePort>
103 WebMessagePortChannelImpl::ExtractMessagePortIDs(
104 const WebMessagePortChannelArray& channels) {
105 std::vector<TransferredMessagePort> message_ports(channels.size());
106 for (size_t i = 0; i < channels.size(); ++i) {
107 WebMessagePortChannelImpl* webchannel =
108 static_cast<WebMessagePortChannelImpl*>(channels[i]);
109 // The message port ids might not be set up yet if this channel
110 // wasn't created on the main thread.
111 DCHECK(webchannel->main_thread_task_runner_->BelongsToCurrentThread());
112 message_ports[i].id = webchannel->message_port_id();
113 message_ports[i].send_messages_as_values =
114 webchannel->send_messages_as_values_;
115 webchannel->QueueMessages();
116 DCHECK(message_ports[i].id != MSG_ROUTING_NONE);
118 return message_ports;
121 // static
122 WebMessagePortChannelArray WebMessagePortChannelImpl::CreatePorts(
123 const std::vector<TransferredMessagePort>& message_ports,
124 const std::vector<int>& new_routing_ids,
125 const scoped_refptr<base::SingleThreadTaskRunner>&
126 main_thread_task_runner) {
127 DCHECK_EQ(message_ports.size(), new_routing_ids.size());
128 WebMessagePortChannelArray channels(message_ports.size());
129 for (size_t i = 0; i < message_ports.size() && i < new_routing_ids.size();
130 ++i) {
131 channels[i] = new WebMessagePortChannelImpl(
132 new_routing_ids[i], message_ports[i],
133 main_thread_task_runner);
135 return channels;
138 void WebMessagePortChannelImpl::setClient(WebMessagePortChannelClient* client) {
139 // Must lock here since client_ is called on the main thread.
140 base::AutoLock auto_lock(lock_);
141 client_ = client;
144 void WebMessagePortChannelImpl::destroy() {
145 setClient(NULL);
147 // Release the object on the main thread, since the destructor might want to
148 // send an IPC, and that has to happen on the main thread.
149 main_thread_task_runner_->ReleaseSoon(FROM_HERE, this);
152 void WebMessagePortChannelImpl::postMessage(
153 const WebString& message_as_string,
154 WebMessagePortChannelArray* channels) {
155 MessagePortMessage message(message_as_string);
156 if (send_messages_as_values_) {
157 blink::WebSerializedScriptValue serialized_value =
158 blink::WebSerializedScriptValue::fromString(message_as_string);
159 v8::Local<v8::Value> v8_value = serialized_value.deserialize();
160 scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
161 converter->SetDateAllowed(true);
162 converter->SetRegExpAllowed(true);
163 scoped_ptr<base::Value> message_as_value(converter->FromV8Value(
164 v8_value, v8::Isolate::GetCurrent()->GetCurrentContext()));
165 message = MessagePortMessage(message_as_value.Pass());
167 if (!main_thread_task_runner_->BelongsToCurrentThread()) {
168 main_thread_task_runner_->PostTask(
169 FROM_HERE, base::Bind(&WebMessagePortChannelImpl::PostMessage, this,
170 message, channels));
171 } else {
172 PostMessage(message, channels);
176 void WebMessagePortChannelImpl::PostMessage(
177 const MessagePortMessage& message,
178 WebMessagePortChannelArray* channels) {
179 IPC::Message* msg = new MessagePortHostMsg_PostMessage(
180 message_port_id_, message, ExtractMessagePortIDs(channels));
181 Send(msg);
184 bool WebMessagePortChannelImpl::tryGetMessage(
185 WebString* message,
186 WebMessagePortChannelArray& channels) {
187 base::AutoLock auto_lock(lock_);
188 if (message_queue_.empty())
189 return false;
191 const MessagePortMessage& data = message_queue_.front().message;
192 DCHECK(data.is_string() != data.is_value());
193 if (data.is_value()) {
194 v8::HandleScope handle_scope(client_->scriptIsolate());
195 v8::Context::Scope context_scope(
196 client_->scriptContextForMessageConversion());
197 scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
198 converter->SetDateAllowed(true);
199 converter->SetRegExpAllowed(true);
200 v8::Local<v8::Value> v8_value = converter->ToV8Value(
201 data.as_value(), client_->scriptContextForMessageConversion());
202 blink::WebSerializedScriptValue serialized_value =
203 blink::WebSerializedScriptValue::serialize(v8_value);
204 *message = serialized_value.toString();
205 } else {
206 *message = message_queue_.front().message.message_as_string;
208 channels = message_queue_.front().ports;
209 message_queue_.pop();
210 return true;
213 void WebMessagePortChannelImpl::Init() {
214 if (!main_thread_task_runner_->BelongsToCurrentThread()) {
215 main_thread_task_runner_->PostTask(
216 FROM_HERE, base::Bind(&WebMessagePortChannelImpl::Init, this));
217 return;
220 if (route_id_ == MSG_ROUTING_NONE) {
221 DCHECK(message_port_id_ == MSG_ROUTING_NONE);
222 Send(new MessagePortHostMsg_CreateMessagePort(
223 &route_id_, &message_port_id_));
224 } else if (message_port_id_ != MSG_ROUTING_NONE) {
225 Send(new MessagePortHostMsg_ReleaseMessages(message_port_id_));
228 ChildThreadImpl::current()->GetRouter()->AddRoute(route_id_, this);
231 void WebMessagePortChannelImpl::Entangle(
232 scoped_refptr<WebMessagePortChannelImpl> channel) {
233 // The message port ids might not be set up yet, if this channel wasn't
234 // created on the main thread. So need to wait until we're on the main thread
235 // before getting the other message port id.
236 if (!main_thread_task_runner_->BelongsToCurrentThread()) {
237 main_thread_task_runner_->PostTask(
238 FROM_HERE,
239 base::Bind(&WebMessagePortChannelImpl::Entangle, this, channel));
240 return;
243 Send(new MessagePortHostMsg_Entangle(
244 message_port_id_, channel->message_port_id()));
247 void WebMessagePortChannelImpl::QueueMessages() {
248 if (!main_thread_task_runner_->BelongsToCurrentThread()) {
249 main_thread_task_runner_->PostTask(
250 FROM_HERE, base::Bind(&WebMessagePortChannelImpl::QueueMessages, this));
251 return;
253 // This message port is being sent elsewhere (perhaps to another process).
254 // The new endpoint needs to receive the queued messages, including ones that
255 // could still be in-flight. So we tell the browser to queue messages, and it
256 // sends us an ack, whose receipt we know means that no more messages are
257 // in-flight. We then send the queued messages to the browser, which prepends
258 // them to the ones it queued and it sends them to the new endpoint.
259 Send(new MessagePortHostMsg_QueueMessages(message_port_id_));
261 // The process could potentially go away while we're still waiting for
262 // in-flight messages. Ensure it stays alive.
263 ChildProcess::current()->AddRefProcess();
266 void WebMessagePortChannelImpl::Send(IPC::Message* message) {
267 if (!main_thread_task_runner_->BelongsToCurrentThread()) {
268 DCHECK(!message->is_sync());
269 main_thread_task_runner_->PostTask(
270 FROM_HERE,
271 base::Bind(&WebMessagePortChannelImpl::Send, this, message));
272 return;
275 ChildThreadImpl::current()->GetRouter()->Send(message);
278 bool WebMessagePortChannelImpl::OnMessageReceived(const IPC::Message& message) {
279 bool handled = true;
280 IPC_BEGIN_MESSAGE_MAP(WebMessagePortChannelImpl, message)
281 IPC_MESSAGE_HANDLER(MessagePortMsg_Message, OnMessage)
282 IPC_MESSAGE_HANDLER(MessagePortMsg_MessagesQueued, OnMessagesQueued)
283 IPC_MESSAGE_UNHANDLED(handled = false)
284 IPC_END_MESSAGE_MAP()
285 return handled;
288 void WebMessagePortChannelImpl::OnMessage(
289 const MessagePortMessage& message,
290 const std::vector<TransferredMessagePort>& sent_message_ports,
291 const std::vector<int>& new_routing_ids) {
292 base::AutoLock auto_lock(lock_);
293 Message msg;
294 msg.message = message;
295 msg.ports = CreatePorts(sent_message_ports, new_routing_ids,
296 main_thread_task_runner_.get());
298 bool was_empty = message_queue_.empty();
299 message_queue_.push(msg);
300 if (client_ && was_empty)
301 client_->messageAvailable();
304 void WebMessagePortChannelImpl::OnMessagesQueued() {
305 std::vector<QueuedMessage> queued_messages;
308 base::AutoLock auto_lock(lock_);
309 queued_messages.reserve(message_queue_.size());
310 while (!message_queue_.empty()) {
311 MessagePortMessage message = message_queue_.front().message;
312 std::vector<TransferredMessagePort> ports =
313 ExtractMessagePortIDs(message_queue_.front().ports);
314 queued_messages.push_back(std::make_pair(message, ports));
315 message_queue_.pop();
319 Send(new MessagePortHostMsg_SendQueuedMessages(
320 message_port_id_, queued_messages));
322 message_port_id_ = MSG_ROUTING_NONE;
324 Release();
325 ChildProcess::current()->ReleaseProcess();
328 WebMessagePortChannelImpl::Message::Message() {}
330 WebMessagePortChannelImpl::Message::~Message() {}
332 } // namespace content