Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(281)

Side by Side Diff: content/renderer/pepper/message_channel.cc

Issue 400823004: gin (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 6 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "content/renderer/pepper/message_channel.h" 5 #include "content/renderer/pepper/message_channel.h"
6 6
7 #include <cstdlib> 7 #include <cstdlib>
8 #include <string> 8 #include <string>
9 9
10 #include "base/bind.h" 10 #include "base/bind.h"
11 #include "base/logging.h" 11 #include "base/logging.h"
12 #include "base/message_loop/message_loop.h" 12 #include "base/message_loop/message_loop.h"
13 #include "content/public/common/content_client.h" 13 #include "content/public/common/content_client.h"
14 #include "content/public/renderer/content_renderer_client.h" 14 #include "content/public/renderer/content_renderer_client.h"
15 #include "content/renderer/pepper/host_array_buffer_var.h" 15 #include "content/renderer/pepper/host_array_buffer_var.h"
16 #include "content/renderer/pepper/npapi_glue.h"
17 #include "content/renderer/pepper/pepper_plugin_instance_impl.h" 16 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
17 #include "content/renderer/pepper/pepper_try_catch.h"
18 #include "content/renderer/pepper/plugin_module.h" 18 #include "content/renderer/pepper/plugin_module.h"
19 #include "content/renderer/pepper/plugin_object.h"
19 #include "content/renderer/pepper/v8_var_converter.h" 20 #include "content/renderer/pepper/v8_var_converter.h"
21 #include "gin/arguments.h"
22 #include "gin/converter.h"
23 #include "gin/function_template.h"
24 #include "gin/object_template_builder.h"
25 #include "gin/public/gin_embedders.h"
20 #include "ppapi/shared_impl/ppapi_globals.h" 26 #include "ppapi/shared_impl/ppapi_globals.h"
21 #include "ppapi/shared_impl/scoped_pp_var.h" 27 #include "ppapi/shared_impl/scoped_pp_var.h"
22 #include "ppapi/shared_impl/var.h" 28 #include "ppapi/shared_impl/var.h"
23 #include "ppapi/shared_impl/var_tracker.h" 29 #include "ppapi/shared_impl/var_tracker.h"
24 #include "third_party/WebKit/public/web/WebBindings.h" 30 #include "third_party/WebKit/public/web/WebBindings.h"
25 #include "third_party/WebKit/public/web/WebDocument.h" 31 #include "third_party/WebKit/public/web/WebDocument.h"
26 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h" 32 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
27 #include "third_party/WebKit/public/web/WebElement.h" 33 #include "third_party/WebKit/public/web/WebElement.h"
28 #include "third_party/WebKit/public/web/WebLocalFrame.h" 34 #include "third_party/WebKit/public/web/WebLocalFrame.h"
29 #include "third_party/WebKit/public/web/WebNode.h" 35 #include "third_party/WebKit/public/web/WebNode.h"
(...skipping 20 matching lines...) Expand all
50 const char kPostMessageAndAwaitResponse[] = "postMessageAndAwaitResponse"; 56 const char kPostMessageAndAwaitResponse[] = "postMessageAndAwaitResponse";
51 const char kV8ToVarConversionError[] = 57 const char kV8ToVarConversionError[] =
52 "Failed to convert a PostMessage " 58 "Failed to convert a PostMessage "
53 "argument from a JavaScript value to a PP_Var. It may have cycles or be of " 59 "argument from a JavaScript value to a PP_Var. It may have cycles or be of "
54 "an unsupported type."; 60 "an unsupported type.";
55 const char kVarToV8ConversionError[] = 61 const char kVarToV8ConversionError[] =
56 "Failed to convert a PostMessage " 62 "Failed to convert a PostMessage "
57 "argument from a PP_Var to a Javascript value. It may have cycles or be of " 63 "argument from a PP_Var to a Javascript value. It may have cycles or be of "
58 "an unsupported type."; 64 "an unsupported type.";
59 65
60 // Helper function to get the MessageChannel that is associated with an 66 bool HasDevPermission() {
61 // NPObject*.
62 MessageChannel* ToMessageChannel(NPObject* object) {
63 return static_cast<MessageChannel::MessageChannelNPObject*>(object)
64 ->message_channel.get();
65 }
66
67 NPObject* ToPassThroughObject(NPObject* object) {
68 MessageChannel* channel = ToMessageChannel(object);
69 return channel ? channel->passthrough_object() : NULL;
70 }
71
72 // Return true iff |identifier| is equal to |string|.
73 bool IdentifierIs(NPIdentifier identifier, const char string[]) {
74 return WebBindings::getStringIdentifier(string) == identifier;
75 }
76
77 bool HasDevChannelPermission(NPObject* channel_object) {
78 MessageChannel* channel = ToMessageChannel(channel_object);
79 if (!channel)
80 return false;
81 return GetContentClient()->renderer()->IsPluginAllowedToUseDevChannelAPIs(); 67 return GetContentClient()->renderer()->IsPluginAllowedToUseDevChannelAPIs();
82 } 68 }
83 69
84 //------------------------------------------------------------------------------
85 // Implementations of NPClass functions. These are here to:
86 // - Implement postMessage behavior.
87 // - Forward calls to the 'passthrough' object to allow backwards-compatibility
88 // with GetInstanceObject() objects.
89 //------------------------------------------------------------------------------
90 NPObject* MessageChannelAllocate(NPP npp, NPClass* the_class) {
91 return new MessageChannel::MessageChannelNPObject;
92 }
93
94 void MessageChannelDeallocate(NPObject* object) {
95 MessageChannel::MessageChannelNPObject* instance =
96 static_cast<MessageChannel::MessageChannelNPObject*>(object);
97 delete instance;
98 }
99
100 bool MessageChannelHasMethod(NPObject* np_obj, NPIdentifier name) {
101 if (!np_obj)
102 return false;
103
104 if (IdentifierIs(name, kPostMessage))
105 return true;
106 if (IdentifierIs(name, kPostMessageAndAwaitResponse) &&
107 HasDevChannelPermission(np_obj)) {
108 return true;
109 }
110 // Other method names we will pass to the passthrough object, if we have one.
111 NPObject* passthrough = ToPassThroughObject(np_obj);
112 if (passthrough)
113 return WebBindings::hasMethod(NULL, passthrough, name);
114 return false;
115 }
116
117 bool MessageChannelInvoke(NPObject* np_obj,
118 NPIdentifier name,
119 const NPVariant* args,
120 uint32 arg_count,
121 NPVariant* result) {
122 if (!np_obj)
123 return false;
124
125 MessageChannel* message_channel = ToMessageChannel(np_obj);
126 if (!message_channel)
127 return false;
128
129 // Check to see if we should handle this function ourselves.
130 if (IdentifierIs(name, kPostMessage) && (arg_count == 1)) {
131 message_channel->PostMessageToNative(&args[0]);
132 return true;
133 } else if (IdentifierIs(name, kPostMessageAndAwaitResponse) &&
134 (arg_count == 1) &&
135 HasDevChannelPermission(np_obj)) {
136 message_channel->PostBlockingMessageToNative(&args[0], result);
137 return true;
138 }
139
140 // Other method calls we will pass to the passthrough object, if we have one.
141 NPObject* passthrough = ToPassThroughObject(np_obj);
142 if (passthrough) {
143 return WebBindings::invoke(
144 NULL, passthrough, name, args, arg_count, result);
145 }
146 return false;
147 }
148
149 bool MessageChannelInvokeDefault(NPObject* np_obj,
150 const NPVariant* args,
151 uint32 arg_count,
152 NPVariant* result) {
153 if (!np_obj)
154 return false;
155
156 // Invoke on the passthrough object, if we have one.
157 NPObject* passthrough = ToPassThroughObject(np_obj);
158 if (passthrough) {
159 return WebBindings::invokeDefault(
160 NULL, passthrough, args, arg_count, result);
161 }
162 return false;
163 }
164
165 bool MessageChannelHasProperty(NPObject* np_obj, NPIdentifier name) {
166 if (!np_obj)
167 return false;
168
169 MessageChannel* message_channel = ToMessageChannel(np_obj);
170 if (message_channel) {
171 if (message_channel->GetReadOnlyProperty(name, NULL))
172 return true;
173 }
174
175 // Invoke on the passthrough object, if we have one.
176 NPObject* passthrough = ToPassThroughObject(np_obj);
177 if (passthrough)
178 return WebBindings::hasProperty(NULL, passthrough, name);
179 return false;
180 }
181
182 bool MessageChannelGetProperty(NPObject* np_obj,
183 NPIdentifier name,
184 NPVariant* result) {
185 if (!np_obj)
186 return false;
187
188 // Don't allow getting the postMessage functions.
189 if (IdentifierIs(name, kPostMessage))
190 return false;
191 if (IdentifierIs(name, kPostMessageAndAwaitResponse) &&
192 HasDevChannelPermission(np_obj)) {
193 return false;
194 }
195 MessageChannel* message_channel = ToMessageChannel(np_obj);
196 if (message_channel) {
197 if (message_channel->GetReadOnlyProperty(name, result))
198 return true;
199 }
200
201 // Invoke on the passthrough object, if we have one.
202 NPObject* passthrough = ToPassThroughObject(np_obj);
203 if (passthrough)
204 return WebBindings::getProperty(NULL, passthrough, name, result);
205 return false;
206 }
207
208 bool MessageChannelSetProperty(NPObject* np_obj,
209 NPIdentifier name,
210 const NPVariant* variant) {
211 if (!np_obj)
212 return false;
213
214 // Don't allow setting the postMessage functions.
215 if (IdentifierIs(name, kPostMessage))
216 return false;
217 if (IdentifierIs(name, kPostMessageAndAwaitResponse) &&
218 HasDevChannelPermission(np_obj)) {
219 return false;
220 }
221 // Invoke on the passthrough object, if we have one.
222 NPObject* passthrough = ToPassThroughObject(np_obj);
223 if (passthrough)
224 return WebBindings::setProperty(NULL, passthrough, name, variant);
225 return false;
226 }
227
228 bool MessageChannelEnumerate(NPObject* np_obj,
229 NPIdentifier** value,
230 uint32_t* count) {
231 if (!np_obj)
232 return false;
233
234 // Invoke on the passthrough object, if we have one, to enumerate its
235 // properties.
236 NPObject* passthrough = ToPassThroughObject(np_obj);
237 if (passthrough) {
238 bool success = WebBindings::enumerate(NULL, passthrough, value, count);
239 if (success) {
240 // Add postMessage to the list and return it.
241 if (std::numeric_limits<size_t>::max() / sizeof(NPIdentifier) <=
242 static_cast<size_t>(*count) + 1) // Else, "always false" x64 warning.
243 return false;
244 NPIdentifier* new_array = static_cast<NPIdentifier*>(
245 std::malloc(sizeof(NPIdentifier) * (*count + 1)));
246 std::memcpy(new_array, *value, sizeof(NPIdentifier) * (*count));
247 new_array[*count] = WebBindings::getStringIdentifier(kPostMessage);
248 std::free(*value);
249 *value = new_array;
250 ++(*count);
251 return true;
252 }
253 }
254
255 // Otherwise, build an array that includes only postMessage.
256 *value = static_cast<NPIdentifier*>(malloc(sizeof(NPIdentifier)));
257 (*value)[0] = WebBindings::getStringIdentifier(kPostMessage);
258 *count = 1;
259 return true;
260 }
261
262 NPClass message_channel_class = {
263 NP_CLASS_STRUCT_VERSION, &MessageChannelAllocate,
264 &MessageChannelDeallocate, NULL,
265 &MessageChannelHasMethod, &MessageChannelInvoke,
266 &MessageChannelInvokeDefault, &MessageChannelHasProperty,
267 &MessageChannelGetProperty, &MessageChannelSetProperty,
268 NULL, &MessageChannelEnumerate, };
269
270 } // namespace 70 } // namespace
271 71
272 // MessageChannel -------------------------------------------------------------- 72 // MessageChannel --------------------------------------------------------------
273 struct MessageChannel::VarConversionResult { 73 struct MessageChannel::VarConversionResult {
274 VarConversionResult() : success_(false), conversion_completed_(false) {} 74 VarConversionResult() : success_(false), conversion_completed_(false) {}
275 void ConversionCompleted(const ScopedPPVar& var, 75 void ConversionCompleted(const ScopedPPVar& var,
276 bool success) { 76 bool success) {
277 conversion_completed_ = true; 77 conversion_completed_ = true;
278 var_ = var; 78 var_ = var;
279 success_ = success; 79 success_ = success;
280 } 80 }
281 const ScopedPPVar& var() const { return var_; } 81 const ScopedPPVar& var() const { return var_; }
282 bool success() const { return success_; } 82 bool success() const { return success_; }
283 bool conversion_completed() const { return conversion_completed_; } 83 bool conversion_completed() const { return conversion_completed_; }
284 84
285 private: 85 private:
286 ScopedPPVar var_; 86 ScopedPPVar var_;
287 bool success_; 87 bool success_;
288 bool conversion_completed_; 88 bool conversion_completed_;
289 }; 89 };
290 90
291 MessageChannel::MessageChannelNPObject::MessageChannelNPObject() {} 91 // static
92 gin::WrapperInfo MessageChannel::kWrapperInfo = {gin::kEmbedderNativeGin};
292 93
293 MessageChannel::MessageChannelNPObject::~MessageChannelNPObject() {} 94 // static
294 95 void MessageChannel::Create(PepperPluginInstanceImpl* instance,
295 MessageChannel::MessageChannel(PepperPluginInstanceImpl* instance) 96 v8::Persistent<v8::Object>* result) {
296 : instance_(instance), 97 PepperTryCatchVar try_catch(instance, false, NULL);
297 passthrough_object_(NULL), 98 gin::Handle<MessageChannel> message_channel =
298 np_object_(NULL), 99 gin::CreateHandle(instance->GetIsolate(), new MessageChannel(instance));
299 early_message_queue_state_(QUEUE_MESSAGES), 100 DCHECK(!try_catch.HasException());
300 weak_ptr_factory_(this) { 101 result->Reset(instance->GetIsolate(), message_channel.ToV8()->ToObject());
301 // Now create an NPObject for receiving calls to postMessage. This sets the
302 // reference count to 1. We release it in the destructor.
303 NPObject* obj = WebBindings::createObject(instance_->instanceNPP(),
304 &message_channel_class);
305 DCHECK(obj);
306 np_object_ = static_cast<MessageChannel::MessageChannelNPObject*>(obj);
307 np_object_->message_channel = weak_ptr_factory_.GetWeakPtr();
308 } 102 }
309 103
310 void MessageChannel::EnqueuePluginMessage(const NPVariant* variant) { 104 MessageChannel::~MessageChannel() {
311 plugin_message_queue_.push_back(VarConversionResult()); 105 }
312 if (variant->type == NPVariantType_Object) {
313 // Convert NPVariantType_Object in to an appropriate PP_Var like Dictionary,
314 // Array, etc. Note NPVariantToVar would convert to an "Object" PP_Var,
315 // which we don't support for Messaging.
316 106
317 // Calling WebBindings::toV8Value creates a wrapper around NPVariant so it 107 v8::Local<v8::Value> MessageChannel::GetNamedProperty(
318 // won't result in a deep copy. 108 v8::Isolate* isolate,
319 v8::Handle<v8::Value> v8_value = WebBindings::toV8Value(variant); 109 const std::string& identifier) {
320 V8VarConverter v8_var_converter(instance_->pp_instance()); 110 PepperTryCatchV8 try_catch(instance_, false, isolate);
321 V8VarConverter::VarResult conversion_result = 111 if (identifier == kPostMessage) {
322 v8_var_converter.FromV8Value( 112 return gin::CreateFunctionTemplate(isolate,
323 v8_value, 113 base::Bind(&MessageChannel::PostMessageToNative,
324 v8::Isolate::GetCurrent()->GetCurrentContext(), 114 weak_ptr_factory_.GetWeakPtr()))->GetFunction();
325 base::Bind(&MessageChannel::FromV8ValueComplete, 115 } else if (identifier == kPostMessageAndAwaitResponse && HasDevPermission()) {
326 weak_ptr_factory_.GetWeakPtr(), 116 return gin::CreateFunctionTemplate(isolate,
327 &plugin_message_queue_.back())); 117 base::Bind(&MessageChannel::PostBlockingMessageToNative,
328 if (conversion_result.completed_synchronously) { 118 weak_ptr_factory_.GetWeakPtr()))->GetFunction();
329 plugin_message_queue_.back().ConversionCompleted(
330 conversion_result.var,
331 conversion_result.success);
332 }
333 } else {
334 plugin_message_queue_.back().ConversionCompleted(
335 ScopedPPVar(ScopedPPVar::PassRef(),
336 NPVariantToPPVar(instance(), variant)),
337 true);
338 DCHECK(plugin_message_queue_.back().var().get().type != PP_VARTYPE_OBJECT);
339 } 119 }
120
121 std::map<std::string, ScopedPPVar>::const_iterator it =
122 internal_named_properties_.find(identifier);
123 if (it != internal_named_properties_.end()) {
124 v8::Handle<v8::Value> result = try_catch.ToV8(it->second.get());
125 if (try_catch.ThrowException())
126 return v8::Local<v8::Value>();
127 return result;
128 }
129
130 PluginObject* plugin_object = GetPluginObject(isolate);
131 if (plugin_object)
132 return plugin_object->GetNamedProperty(isolate, identifier);
133 return v8::Local<v8::Value>();
134 }
135
136 void MessageChannel::SetNamedProperty(v8::Isolate* isolate,
137 const std::string& identifier,
138 v8::Local<v8::Value> value) {
139 PepperTryCatchV8 try_catch(instance_, false, isolate);
140 if (identifier == kPostMessage ||
141 (identifier == kPostMessageAndAwaitResponse && HasDevPermission())) {
142 try_catch.ThrowException("Cannot set properties with the name postMessage"
143 "or postMessageAndAwaitResponse");
144 return;
145 }
146
147 PluginObject* plugin_object = GetPluginObject(isolate);
148 if (plugin_object)
149 plugin_object->SetNamedProperty(isolate, identifier, value);
150 }
151
152 std::vector<std::string> MessageChannel::EnumerateNamedProperties(
153 v8::Isolate* isolate) {
154 std::vector<std::string> result;
155 PluginObject* plugin_object = GetPluginObject(isolate);
156 if (plugin_object)
157 result = plugin_object->EnumerateNamedProperties(isolate);
158 result.push_back(kPostMessage);
159 if (HasDevPermission())
160 result.push_back(kPostMessageAndAwaitResponse);
161 return result;
162 }
163
164 v8::Local<v8::Value> MessageChannel::GetIndexedProperty(v8::Isolate* isolate,
165 uint32_t index) {
166 PepperTryCatchV8 try_catch(instance_, false, isolate);
167 std::map<uint32_t, ScopedPPVar>::const_iterator it =
168 internal_indexed_properties_.find(index);
169 if (it != internal_indexed_properties_.end()) {
170 v8::Handle<v8::Value> result = try_catch.ToV8(it->second.get());
171 if (try_catch.ThrowException())
172 return v8::Local<v8::Value>();
173 return result;
174 }
175
176 PluginObject* plugin_object = GetPluginObject(isolate);
177 if (plugin_object)
178 return plugin_object->GetIndexedProperty(isolate, index);
179 return v8::Local<v8::Value>();
180 }
181
182 void MessageChannel::SetIndexedProperty(v8::Isolate* isolate,
183 uint32_t index,
184 v8::Local<v8::Value> value) {
185 PluginObject* plugin_object = GetPluginObject(isolate);
186 if (plugin_object)
187 plugin_object->SetIndexedProperty(isolate, index, value);
188 }
189
190 std::vector<uint32_t> MessageChannel::EnumerateIndexedProperties(
191 v8::Isolate* isolate) {
192 PluginObject* plugin_object = GetPluginObject(isolate);
193 if (plugin_object)
194 return plugin_object->EnumerateIndexedProperties(isolate);
195 return std::vector<uint32_t>();
340 } 196 }
341 197
342 void MessageChannel::PostMessageToJavaScript(PP_Var message_data) { 198 void MessageChannel::PostMessageToJavaScript(PP_Var message_data) {
343 v8::HandleScope scope(v8::Isolate::GetCurrent()); 199 v8::HandleScope scope(v8::Isolate::GetCurrent());
344 200
345 // Because V8 is probably not on the stack for Native->JS calls, we need to 201 // Because V8 is probably not on the stack for Native->JS calls, we need to
346 // enter the appropriate context for the plugin. 202 // enter the appropriate context for the plugin.
347 WebPluginContainer* container = instance_->container(); 203 v8::Local<v8::Context> context = instance_->GetPluginContext();
348 // It's possible that container() is NULL if the plugin has been removed from 204 if (context.IsEmpty())
349 // the DOM (but the PluginInstance is not destroyed yet).
350 if (!container)
351 return; 205 return;
352 206
353 v8::Local<v8::Context> context =
354 container->element().document().frame()->mainWorldScriptContext();
355 // If the page is being destroyed, the context may be empty.
356 if (context.IsEmpty())
357 return;
358 v8::Context::Scope context_scope(context); 207 v8::Context::Scope context_scope(context);
359 208
360 v8::Handle<v8::Value> v8_val; 209 v8::Handle<v8::Value> v8_val;
210 // TODO(raymes): Possibly change this to use TryCatch to do the conversion and
211 // throw an exception if necessary.
361 if (!V8VarConverter(instance_->pp_instance()) 212 if (!V8VarConverter(instance_->pp_instance())
362 .ToV8Value(message_data, context, &v8_val)) { 213 .ToV8Value(message_data, context, &v8_val)) {
363 PpapiGlobals::Get()->LogWithSource(instance_->pp_instance(), 214 PpapiGlobals::Get()->LogWithSource(instance_->pp_instance(),
364 PP_LOGLEVEL_ERROR, 215 PP_LOGLEVEL_ERROR,
365 std::string(), 216 std::string(),
366 kVarToV8ConversionError); 217 kVarToV8ConversionError);
367 return; 218 return;
368 } 219 }
369 220
370 WebSerializedScriptValue serialized_val = 221 WebSerializedScriptValue serialized_val =
(...skipping 15 matching lines...) Expand all
386 void MessageChannel::Start() { 237 void MessageChannel::Start() {
387 // We PostTask here instead of draining the message queue directly 238 // We PostTask here instead of draining the message queue directly
388 // since we haven't finished initializing the PepperWebPluginImpl yet, so 239 // since we haven't finished initializing the PepperWebPluginImpl yet, so
389 // the plugin isn't available in the DOM. 240 // the plugin isn't available in the DOM.
390 base::MessageLoop::current()->PostTask( 241 base::MessageLoop::current()->PostTask(
391 FROM_HERE, 242 FROM_HERE,
392 base::Bind(&MessageChannel::DrainEarlyMessageQueue, 243 base::Bind(&MessageChannel::DrainEarlyMessageQueue,
393 weak_ptr_factory_.GetWeakPtr())); 244 weak_ptr_factory_.GetWeakPtr()));
394 } 245 }
395 246
247 void MessageChannel::SetPassthroughObject(v8::Handle<v8::Object> passthrough) {
248 passthrough_object_.Reset(instance_->GetIsolate(), passthrough);
249 }
250
251 void MessageChannel::SetReadOnlyProperty(PP_Var key, PP_Var value) {
252 StringVar* key_string = StringVar::FromPPVar(key);
253 if (key.type == PP_VARTYPE_INT32 && key.value.as_int >= 0) {
254 internal_indexed_properties_[key.value.as_int] = ScopedPPVar(value);
255 } else if (key_string) {
256 internal_named_properties_[key_string->value()] = ScopedPPVar(value);
257 } else {
258 NOTREACHED();
259 }
260 }
261
262 MessageChannel::MessageChannel(PepperPluginInstanceImpl* instance)
263 : gin::NamedPropertyInterceptor(instance->GetIsolate(), this),
264 gin::IndexedPropertyInterceptor(instance->GetIsolate(), this),
265 instance_(instance),
266 early_message_queue_state_(QUEUE_MESSAGES),
267 weak_ptr_factory_(this) {
268 }
269
270 gin::ObjectTemplateBuilder MessageChannel::GetObjectTemplateBuilder(
271 v8::Isolate* isolate) {
272 return Wrappable<MessageChannel>::GetObjectTemplateBuilder(isolate)
273 .AddNamedPropertyInterceptor()
274 .AddIndexedPropertyInterceptor();
275 }
276
277 void MessageChannel::PostMessageToNative(gin::Arguments* args) {
Krzysztof Olczyk 2014/07/31 07:12:57 If I'm not wrong, you could accept single argument
278 if (args->Length() != 1) {
279 // TODO(raymes): Consider throwing an exception here. We don't now for
280 // backward compatibility.
281 return;
282 }
283
284 v8::Handle<v8::Value> message_data;
285 if (!args->GetNext(&message_data)) {
286 NOTREACHED();
287 }
288
289 EnqueuePluginMessage(message_data);
290 DrainCompletedPluginMessages();
291 }
292
293 void MessageChannel::PostBlockingMessageToNative(gin::Arguments* args) {
294 PepperTryCatchV8 try_catch(instance_, false, args->isolate());
295 if (args->Length() != 1) {
296 try_catch.ThrowException(
297 "postMessageAndAwaitResponse requires one argument");
298 return;
299 }
300
301 v8::Handle<v8::Value> message_data;
302 if (!args->GetNext(&message_data)) {
303 NOTREACHED();
304 }
305
306 if (early_message_queue_state_ == QUEUE_MESSAGES) {
307 try_catch.ThrowException(
308 "Attempted to call a synchronous method on a plugin that was not "
309 "yet loaded.");
310 return;
311 }
312
313 // If the queue of messages to the plugin is non-empty, we're still waiting on
314 // pending Var conversions. This means at some point in the past, JavaScript
315 // called postMessage (the async one) and passed us something with a browser-
316 // side host (e.g., FileSystem) and we haven't gotten a response from the
317 // browser yet. We can't currently support sending a sync message if the
318 // plugin does this, because it will break the ordering of the messages
319 // arriving at the plugin.
320 // TODO(dmichael): Fix this.
321 // See https://code.google.com/p/chromium/issues/detail?id=367896#c4
322 if (!plugin_message_queue_.empty()) {
323 try_catch.ThrowException(
324 "Failed to convert parameter synchronously, because a prior "
325 "call to postMessage contained a type which required asynchronous "
326 "transfer which has not completed. Not all types are supported yet by "
327 "postMessageAndAwaitResponse. See crbug.com/367896.");
328 return;
329 }
330 ScopedPPVar param = try_catch.FromV8(message_data);
331 if (try_catch.ThrowException())
332 return;
333
334 ScopedPPVar pp_result;
335 bool was_handled = instance_->HandleBlockingMessage(param, &pp_result);
336 if (!was_handled) {
337 try_catch.ThrowException(
338 "The plugin has not registered a handler for synchronous messages. "
339 "See the documentation for PPB_Messaging::RegisterMessageHandler "
340 "and PPP_MessageHandler.");
341 return;
342 }
343 v8::Handle<v8::Value> v8_result = try_catch.ToV8(pp_result.get());
344 if (try_catch.ThrowException())
345 return;
346
347 args->Return(v8_result);
348 }
349
350 PluginObject* MessageChannel::GetPluginObject(v8::Isolate* isolate) {
351 return PluginObject::FromV8Object(isolate,
352 v8::Local<v8::Object>::New(isolate, passthrough_object_));
353 }
354
355 void MessageChannel::EnqueuePluginMessage(v8::Handle<v8::Value> v8_value) {
356 plugin_message_queue_.push_back(VarConversionResult());
357 // Convert NPVariantType_Object in to an appropriate PP_Var like Dictionary,
358 // Array, etc. Note NPVariantToVar would convert to an "Object" PP_Var,
359 // which we don't support for Messaging.
360 // TODO(raymes): Possibly change this to use TryCatch to do the conversion and
361 // throw an exception if necessary.
362 V8VarConverter v8_var_converter(instance_->pp_instance());
363 V8VarConverter::VarResult conversion_result =
364 v8_var_converter.FromV8Value(
365 v8_value,
366 v8::Isolate::GetCurrent()->GetCurrentContext(),
367 base::Bind(&MessageChannel::FromV8ValueComplete,
368 weak_ptr_factory_.GetWeakPtr(),
369 &plugin_message_queue_.back()));
370 if (conversion_result.completed_synchronously) {
371 plugin_message_queue_.back().ConversionCompleted(
372 conversion_result.var,
373 conversion_result.success);
374 }
375 }
376
396 void MessageChannel::FromV8ValueComplete(VarConversionResult* result_holder, 377 void MessageChannel::FromV8ValueComplete(VarConversionResult* result_holder,
397 const ScopedPPVar& result, 378 const ScopedPPVar& result,
398 bool success) { 379 bool success) {
399 result_holder->ConversionCompleted(result, success); 380 result_holder->ConversionCompleted(result, success);
400 DrainCompletedPluginMessages(); 381 DrainCompletedPluginMessages();
401 } 382 }
402 383
403 void MessageChannel::DrainCompletedPluginMessages() { 384 void MessageChannel::DrainCompletedPluginMessages() {
404 if (early_message_queue_state_ == QUEUE_MESSAGES) 385 if (early_message_queue_state_ == QUEUE_MESSAGES)
405 return; 386 return;
(...skipping 53 matching lines...) Expand 10 before | Expand all | Expand 10 after
459 // sent messages, while |source| is only specified for cross-document 440 // sent messages, while |source| is only specified for cross-document
460 // messages: 441 // messages:
461 // http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html 442 // http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html
462 // This currently behaves like Web Workers. On Firefox, Chrome, and Safari 443 // This currently behaves like Web Workers. On Firefox, Chrome, and Safari
463 // at least, postMessage on Workers does not provide the origin or source. 444 // at least, postMessage on Workers does not provide the origin or source.
464 // TODO(dmichael): Add origin if we change to a more iframe-like origin 445 // TODO(dmichael): Add origin if we change to a more iframe-like origin
465 // policy (see crbug.com/81537) 446 // policy (see crbug.com/81537)
466 container->element().dispatchEvent(msg_event); 447 container->element().dispatchEvent(msg_event);
467 } 448 }
468 449
469 void MessageChannel::PostMessageToNative(const NPVariant* message_data) {
470 EnqueuePluginMessage(message_data);
471 DrainCompletedPluginMessages();
472 }
473
474 void MessageChannel::PostBlockingMessageToNative(const NPVariant* message_data,
475 NPVariant* np_result) {
476 if (early_message_queue_state_ == QUEUE_MESSAGES) {
477 WebBindings::setException(
478 np_object_,
479 "Attempted to call a synchronous method on a plugin that was not "
480 "yet loaded.");
481 return;
482 }
483
484 // If the queue of messages to the plugin is non-empty, we're still waiting on
485 // pending Var conversions. This means at some point in the past, JavaScript
486 // called postMessage (the async one) and passed us something with a browser-
487 // side host (e.g., FileSystem) and we haven't gotten a response from the
488 // browser yet. We can't currently support sending a sync message if the
489 // plugin does this, because it will break the ordering of the messages
490 // arriving at the plugin.
491 // TODO(dmichael): Fix this.
492 // See https://code.google.com/p/chromium/issues/detail?id=367896#c4
493 if (!plugin_message_queue_.empty()) {
494 WebBindings::setException(
495 np_object_,
496 "Failed to convert parameter synchronously, because a prior "
497 "call to postMessage contained a type which required asynchronous "
498 "transfer which has not completed. Not all types are supported yet by "
499 "postMessageAndAwaitResponse. See crbug.com/367896.");
500 return;
501 }
502 ScopedPPVar param;
503 if (message_data->type == NPVariantType_Object) {
504 // Convert NPVariantType_Object in to an appropriate PP_Var like Dictionary,
505 // Array, etc. Note NPVariantToVar would convert to an "Object" PP_Var,
506 // which we don't support for Messaging.
507 v8::Handle<v8::Value> v8_value = WebBindings::toV8Value(message_data);
508 V8VarConverter v8_var_converter(instance_->pp_instance());
509 bool success = v8_var_converter.FromV8ValueSync(
510 v8_value,
511 v8::Isolate::GetCurrent()->GetCurrentContext(),
512 &param);
513 if (!success) {
514 WebBindings::setException(
515 np_object_,
516 "Failed to convert the given parameter to a PP_Var to send to "
517 "the plugin.");
518 return;
519 }
520 } else {
521 param = ScopedPPVar(ScopedPPVar::PassRef(),
522 NPVariantToPPVar(instance(), message_data));
523 }
524 ScopedPPVar pp_result;
525 bool was_handled = instance_->HandleBlockingMessage(param, &pp_result);
526 if (!was_handled) {
527 WebBindings::setException(
528 np_object_,
529 "The plugin has not registered a handler for synchronous messages. "
530 "See the documentation for PPB_Messaging::RegisterMessageHandler "
531 "and PPP_MessageHandler.");
532 return;
533 }
534 v8::Handle<v8::Value> v8_val;
535 if (!V8VarConverter(instance_->pp_instance()).ToV8Value(
536 pp_result.get(),
537 v8::Isolate::GetCurrent()->GetCurrentContext(),
538 &v8_val)) {
539 WebBindings::setException(
540 np_object_,
541 "Failed to convert the plugin's result to a JavaScript type.");
542 return;
543 }
544 // Success! Convert the result to an NPVariant.
545 WebBindings::toNPVariant(v8_val, NULL, np_result);
546 }
547
548 MessageChannel::~MessageChannel() {
549 WebBindings::releaseObject(np_object_);
550 if (passthrough_object_)
551 WebBindings::releaseObject(passthrough_object_);
552 }
553
554 void MessageChannel::SetPassthroughObject(NPObject* passthrough) {
555 // Retain the passthrough object; We need to ensure it lives as long as this
556 // MessageChannel.
557 if (passthrough)
558 WebBindings::retainObject(passthrough);
559
560 // If we had a passthrough set already, release it. Note that we retain the
561 // incoming passthrough object first, so that we behave correctly if anyone
562 // invokes:
563 // SetPassthroughObject(passthrough_object());
564 if (passthrough_object_)
565 WebBindings::releaseObject(passthrough_object_);
566
567 passthrough_object_ = passthrough;
568 }
569
570 bool MessageChannel::GetReadOnlyProperty(NPIdentifier key,
571 NPVariant* value) const {
572 std::map<NPIdentifier, ScopedPPVar>::const_iterator it =
573 internal_properties_.find(key);
574 if (it != internal_properties_.end()) {
575 if (value)
576 return PPVarToNPVariant(it->second.get(), value);
577 return true;
578 }
579 return false;
580 }
581
582 void MessageChannel::SetReadOnlyProperty(PP_Var key, PP_Var value) {
583 internal_properties_[PPVarToNPIdentifier(key)] = ScopedPPVar(value);
584 }
585
586 } // namespace content 450 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698