Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / extensions / renderer / messaging_bindings.cc
blob281f27641fab51c568e06f357161d5aba163d9f7
1 // Copyright 2014 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 "extensions/renderer/messaging_bindings.h"
7 #include <map>
8 #include <string>
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/lazy_instance.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/values.h"
16 #include "content/public/renderer/render_thread.h"
17 #include "content/public/renderer/render_view.h"
18 #include "content/public/renderer/v8_value_converter.h"
19 #include "extensions/common/api/messaging/message.h"
20 #include "extensions/common/extension_messages.h"
21 #include "extensions/common/manifest_handlers/externally_connectable.h"
22 #include "extensions/renderer/dispatcher.h"
23 #include "extensions/renderer/event_bindings.h"
24 #include "extensions/renderer/object_backed_native_handler.h"
25 #include "extensions/renderer/scoped_persistent.h"
26 #include "extensions/renderer/script_context.h"
27 #include "extensions/renderer/script_context_set.h"
28 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
29 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
30 #include "third_party/WebKit/public/web/WebScopedWindowFocusAllowedIndicator.h"
31 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
32 #include "third_party/WebKit/public/web/WebUserGestureToken.h"
33 #include "v8/include/v8.h"
35 // Message passing API example (in a content script):
36 // var extension =
37 // new chrome.Extension('00123456789abcdef0123456789abcdef0123456');
38 // var port = runtime.connect();
39 // port.postMessage('Can you hear me now?');
40 // port.onmessage.addListener(function(msg, port) {
41 // alert('response=' + msg);
42 // port.postMessage('I got your reponse');
43 // });
45 using content::RenderThread;
46 using content::V8ValueConverter;
48 namespace extensions {
50 namespace {
52 struct ExtensionData {
53 struct PortData {
54 int ref_count; // how many contexts have a handle to this port
55 PortData() : ref_count(0) {}
57 std::map<int, PortData> ports; // port ID -> data
60 base::LazyInstance<ExtensionData> g_extension_data = LAZY_INSTANCE_INITIALIZER;
62 bool HasPortData(int port_id) {
63 return g_extension_data.Get().ports.find(port_id) !=
64 g_extension_data.Get().ports.end();
67 ExtensionData::PortData& GetPortData(int port_id) {
68 return g_extension_data.Get().ports[port_id];
71 void ClearPortData(int port_id) {
72 g_extension_data.Get().ports.erase(port_id);
75 const char kPortClosedError[] = "Attempting to use a disconnected port object";
76 const char kReceivingEndDoesntExistError[] =
77 "Could not establish connection. Receiving end does not exist.";
79 class ExtensionImpl : public ObjectBackedNativeHandler {
80 public:
81 ExtensionImpl(Dispatcher* dispatcher, ScriptContext* context)
82 : ObjectBackedNativeHandler(context), dispatcher_(dispatcher) {
83 RouteFunction(
84 "CloseChannel",
85 base::Bind(&ExtensionImpl::CloseChannel, base::Unretained(this)));
86 RouteFunction(
87 "PortAddRef",
88 base::Bind(&ExtensionImpl::PortAddRef, base::Unretained(this)));
89 RouteFunction(
90 "PortRelease",
91 base::Bind(&ExtensionImpl::PortRelease, base::Unretained(this)));
92 RouteFunction(
93 "PostMessage",
94 base::Bind(&ExtensionImpl::PostMessage, base::Unretained(this)));
95 // TODO(fsamuel, kalman): Move BindToGC out of messaging natives.
96 RouteFunction("BindToGC",
97 base::Bind(&ExtensionImpl::BindToGC, base::Unretained(this)));
100 virtual ~ExtensionImpl() {}
102 private:
103 void ClearPortDataAndNotifyDispatcher(int port_id) {
104 ClearPortData(port_id);
105 dispatcher_->ClearPortData(port_id);
108 bool ShouldForwardUserGesture() {
109 return blink::WebUserGestureIndicator::isProcessingUserGesture() &&
110 !blink::WebUserGestureIndicator::currentUserGestureToken()
111 .wasForwarded();
114 // Sends a message along the given channel.
115 void PostMessage(const v8::FunctionCallbackInfo<v8::Value>& args) {
116 content::RenderView* renderview = context()->GetRenderView();
117 if (!renderview)
118 return;
120 // Arguments are (int32 port_id, string message).
121 CHECK(args.Length() == 2 && args[0]->IsInt32() && args[1]->IsString());
123 int port_id = args[0]->Int32Value();
124 if (!HasPortData(port_id)) {
125 args.GetIsolate()->ThrowException(v8::Exception::Error(
126 v8::String::NewFromUtf8(args.GetIsolate(), kPortClosedError)));
127 return;
130 renderview->Send(new ExtensionHostMsg_PostMessage(
131 renderview->GetRoutingID(),
132 port_id,
133 Message(*v8::String::Utf8Value(args[1]), ShouldForwardUserGesture())));
136 // Forcefully disconnects a port.
137 void CloseChannel(const v8::FunctionCallbackInfo<v8::Value>& args) {
138 // Arguments are (int32 port_id, boolean notify_browser).
139 CHECK_EQ(2, args.Length());
140 CHECK(args[0]->IsInt32());
141 CHECK(args[1]->IsBoolean());
143 int port_id = args[0]->Int32Value();
144 if (!HasPortData(port_id))
145 return;
147 // Send via the RenderThread because the RenderView might be closing.
148 bool notify_browser = args[1]->BooleanValue();
149 if (notify_browser) {
150 content::RenderThread::Get()->Send(
151 new ExtensionHostMsg_CloseChannel(port_id, std::string()));
154 ClearPortDataAndNotifyDispatcher(port_id);
157 // A new port has been created for a context. This occurs both when script
158 // opens a connection, and when a connection is opened to this script.
159 void PortAddRef(const v8::FunctionCallbackInfo<v8::Value>& args) {
160 // Arguments are (int32 port_id).
161 CHECK_EQ(1, args.Length());
162 CHECK(args[0]->IsInt32());
164 int port_id = args[0]->Int32Value();
165 ++GetPortData(port_id).ref_count;
168 // The frame a port lived in has been destroyed. When there are no more
169 // frames with a reference to a given port, we will disconnect it and notify
170 // the other end of the channel.
171 void PortRelease(const v8::FunctionCallbackInfo<v8::Value>& args) {
172 // Arguments are (int32 port_id).
173 CHECK_EQ(1, args.Length());
174 CHECK(args[0]->IsInt32());
176 int port_id = args[0]->Int32Value();
177 if (HasPortData(port_id) && --GetPortData(port_id).ref_count == 0) {
178 // Send via the RenderThread because the RenderView might be closing.
179 content::RenderThread::Get()->Send(
180 new ExtensionHostMsg_CloseChannel(port_id, std::string()));
181 ClearPortDataAndNotifyDispatcher(port_id);
185 // Holds a |callback| to run sometime after |object| is GC'ed. |callback| will
186 // not be executed re-entrantly to avoid running JS in an unexpected state.
187 class GCCallback {
188 public:
189 static void Bind(v8::Handle<v8::Object> object,
190 v8::Handle<v8::Function> callback,
191 v8::Isolate* isolate) {
192 GCCallback* cb = new GCCallback(object, callback, isolate);
193 cb->object_.SetWeak(cb, NearDeathCallback);
196 private:
197 static void NearDeathCallback(
198 const v8::WeakCallbackData<v8::Object, GCCallback>& data) {
199 // v8 says we need to explicitly reset weak handles from their callbacks.
200 // It's not implicit as one might expect.
201 data.GetParameter()->object_.reset();
202 base::MessageLoop::current()->PostTask(
203 FROM_HERE,
204 base::Bind(&GCCallback::RunCallback,
205 base::Owned(data.GetParameter())));
208 GCCallback(v8::Handle<v8::Object> object,
209 v8::Handle<v8::Function> callback,
210 v8::Isolate* isolate)
211 : object_(object), callback_(callback), isolate_(isolate) {}
213 void RunCallback() {
214 v8::HandleScope handle_scope(isolate_);
215 v8::Handle<v8::Function> callback = callback_.NewHandle(isolate_);
216 v8::Handle<v8::Context> context = callback->CreationContext();
217 if (context.IsEmpty())
218 return;
219 v8::Context::Scope context_scope(context);
220 blink::WebScopedMicrotaskSuppression suppression;
221 callback->Call(context->Global(), 0, NULL);
224 ScopedPersistent<v8::Object> object_;
225 ScopedPersistent<v8::Function> callback_;
226 v8::Isolate* isolate_;
228 DISALLOW_COPY_AND_ASSIGN(GCCallback);
231 // void BindToGC(object, callback)
233 // Binds |callback| to be invoked *sometime after* |object| is garbage
234 // collected. We don't call the method re-entrantly so as to avoid executing
235 // JS in some bizarro undefined mid-GC state.
236 void BindToGC(const v8::FunctionCallbackInfo<v8::Value>& args) {
237 CHECK(args.Length() == 2 && args[0]->IsObject() && args[1]->IsFunction());
238 GCCallback::Bind(args[0].As<v8::Object>(),
239 args[1].As<v8::Function>(),
240 args.GetIsolate());
243 // Dispatcher handle. Not owned.
244 Dispatcher* dispatcher_;
247 } // namespace
249 ObjectBackedNativeHandler* MessagingBindings::Get(Dispatcher* dispatcher,
250 ScriptContext* context) {
251 return new ExtensionImpl(dispatcher, context);
254 // static
255 void MessagingBindings::DispatchOnConnect(
256 const ScriptContextSet::ContextSet& contexts,
257 int target_port_id,
258 const std::string& channel_name,
259 const base::DictionaryValue& source_tab,
260 const std::string& source_extension_id,
261 const std::string& target_extension_id,
262 const GURL& source_url,
263 const std::string& tls_channel_id,
264 content::RenderView* restrict_to_render_view) {
265 v8::Isolate* isolate = v8::Isolate::GetCurrent();
266 v8::HandleScope handle_scope(isolate);
268 scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
270 bool port_created = false;
271 std::string source_url_spec = source_url.spec();
273 // TODO(kalman): pass in the full ScriptContextSet; call ForEach.
274 for (ScriptContextSet::ContextSet::const_iterator it = contexts.begin();
275 it != contexts.end();
276 ++it) {
277 if (restrict_to_render_view &&
278 restrict_to_render_view != (*it)->GetRenderView()) {
279 continue;
282 // TODO(kalman): remove when ContextSet::ForEach is available.
283 if ((*it)->v8_context().IsEmpty())
284 continue;
286 v8::Handle<v8::Value> tab = v8::Null(isolate);
287 v8::Handle<v8::Value> tls_channel_id_value = v8::Undefined(isolate);
288 const Extension* extension = (*it)->extension();
289 if (extension) {
290 if (!source_tab.empty() && !extension->is_platform_app())
291 tab = converter->ToV8Value(&source_tab, (*it)->v8_context());
293 ExternallyConnectableInfo* externally_connectable =
294 ExternallyConnectableInfo::Get(extension);
295 if (externally_connectable &&
296 externally_connectable->accepts_tls_channel_id) {
297 tls_channel_id_value =
298 v8::String::NewFromUtf8(isolate,
299 tls_channel_id.c_str(),
300 v8::String::kNormalString,
301 tls_channel_id.size());
305 v8::Handle<v8::Value> arguments[] = {
306 // portId
307 v8::Integer::New(isolate, target_port_id),
308 // channelName
309 v8::String::NewFromUtf8(isolate,
310 channel_name.c_str(),
311 v8::String::kNormalString,
312 channel_name.size()),
313 // sourceTab
314 tab,
315 // sourceExtensionId
316 v8::String::NewFromUtf8(isolate,
317 source_extension_id.c_str(),
318 v8::String::kNormalString,
319 source_extension_id.size()),
320 // targetExtensionId
321 v8::String::NewFromUtf8(isolate,
322 target_extension_id.c_str(),
323 v8::String::kNormalString,
324 target_extension_id.size()),
325 // sourceUrl
326 v8::String::NewFromUtf8(isolate,
327 source_url_spec.c_str(),
328 v8::String::kNormalString,
329 source_url_spec.size()),
330 // tlsChannelId
331 tls_channel_id_value,
334 v8::Handle<v8::Value> retval = (*it)->module_system()->CallModuleMethod(
335 "messaging", "dispatchOnConnect", arraysize(arguments), arguments);
337 if (retval.IsEmpty()) {
338 LOG(ERROR) << "Empty return value from dispatchOnConnect.";
339 continue;
342 CHECK(retval->IsBoolean());
343 port_created |= retval->BooleanValue();
346 // If we didn't create a port, notify the other end of the channel (treat it
347 // as a disconnect).
348 if (!port_created) {
349 content::RenderThread::Get()->Send(new ExtensionHostMsg_CloseChannel(
350 target_port_id, kReceivingEndDoesntExistError));
354 // static
355 void MessagingBindings::DeliverMessage(
356 const ScriptContextSet::ContextSet& contexts,
357 int target_port_id,
358 const Message& message,
359 content::RenderView* restrict_to_render_view) {
360 scoped_ptr<blink::WebScopedUserGesture> web_user_gesture;
361 scoped_ptr<blink::WebScopedWindowFocusAllowedIndicator> allow_window_focus;
362 if (message.user_gesture) {
363 web_user_gesture.reset(new blink::WebScopedUserGesture);
364 blink::WebUserGestureIndicator::currentUserGestureToken().setForwarded();
365 allow_window_focus.reset(new blink::WebScopedWindowFocusAllowedIndicator);
368 v8::Isolate* isolate = v8::Isolate::GetCurrent();
369 v8::HandleScope handle_scope(isolate);
371 // TODO(kalman): pass in the full ScriptContextSet; call ForEach.
372 for (ScriptContextSet::ContextSet::const_iterator it = contexts.begin();
373 it != contexts.end();
374 ++it) {
375 if (restrict_to_render_view &&
376 restrict_to_render_view != (*it)->GetRenderView()) {
377 continue;
380 // TODO(kalman): remove when ContextSet::ForEach is available.
381 if ((*it)->v8_context().IsEmpty())
382 continue;
384 // Check to see whether the context has this port before bothering to create
385 // the message.
386 v8::Handle<v8::Value> port_id_handle =
387 v8::Integer::New(isolate, target_port_id);
388 v8::Handle<v8::Value> has_port = (*it)->module_system()->CallModuleMethod(
389 "messaging", "hasPort", 1, &port_id_handle);
391 CHECK(!has_port.IsEmpty());
392 if (!has_port->BooleanValue())
393 continue;
395 std::vector<v8::Handle<v8::Value> > arguments;
396 arguments.push_back(v8::String::NewFromUtf8(isolate,
397 message.data.c_str(),
398 v8::String::kNormalString,
399 message.data.size()));
400 arguments.push_back(port_id_handle);
401 (*it)->module_system()->CallModuleMethod(
402 "messaging", "dispatchOnMessage", &arguments);
406 // static
407 void MessagingBindings::DispatchOnDisconnect(
408 const ScriptContextSet::ContextSet& contexts,
409 int port_id,
410 const std::string& error_message,
411 content::RenderView* restrict_to_render_view) {
412 v8::Isolate* isolate = v8::Isolate::GetCurrent();
413 v8::HandleScope handle_scope(isolate);
415 // TODO(kalman): pass in the full ScriptContextSet; call ForEach.
416 for (ScriptContextSet::ContextSet::const_iterator it = contexts.begin();
417 it != contexts.end();
418 ++it) {
419 if (restrict_to_render_view &&
420 restrict_to_render_view != (*it)->GetRenderView()) {
421 continue;
424 // TODO(kalman): remove when ContextSet::ForEach is available.
425 if ((*it)->v8_context().IsEmpty())
426 continue;
428 std::vector<v8::Handle<v8::Value> > arguments;
429 arguments.push_back(v8::Integer::New(isolate, port_id));
430 if (!error_message.empty()) {
431 arguments.push_back(
432 v8::String::NewFromUtf8(isolate, error_message.c_str()));
433 } else {
434 arguments.push_back(v8::Null(isolate));
436 (*it)->module_system()->CallModuleMethod(
437 "messaging", "dispatchOnDisconnect", &arguments);
441 } // namespace extensions