1 // Copyright 2013 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.
4
5 #include "chrome/renderer/extensions/pepper_request_proxy.h"
6
7 #include "base/values.h"
8 #include "chrome/renderer/extensions/chrome_v8_context.h"
9 #include "content/public/renderer/v8_value_converter.h"
10
11 namespace extensions {
12
PepperRequestProxy(ChromeV8Context * context)13 PepperRequestProxy::PepperRequestProxy(ChromeV8Context* context)
14 : context_(context),
15 isolate_(context->v8_context()->GetIsolate()),
16 next_request_id_(0) {}
17
~PepperRequestProxy()18 PepperRequestProxy::~PepperRequestProxy() {}
19
StartRequest(const ResponseCallback & callback,const std::string & request_name,const base::ListValue & args,std::string * error)20 bool PepperRequestProxy::StartRequest(const ResponseCallback& callback,
21 const std::string& request_name,
22 const base::ListValue& args,
23 std::string* error) {
24 int request_id = next_request_id_++;
25 pending_request_map_[request_id] = callback;
26
27 // TODO(sammc): Converting from base::Value to v8::Value and then back to
28 // base::Value is not optimal. For most API calls the JS code doesn't do much.
29 // http://crbug.com/324115.
30 v8::HandleScope scope(isolate_);
31 scoped_ptr<content::V8ValueConverter> converter(
32 content::V8ValueConverter::create());
33 std::vector<v8::Handle<v8::Value> > v8_args;
34 v8_args.push_back(v8::String::NewFromUtf8(isolate_, request_name.c_str()));
35 v8_args.push_back(v8::Integer::New(request_id));
36 for (base::ListValue::const_iterator it = args.begin(); it != args.end();
37 ++it) {
38 v8_args.push_back(converter->ToV8Value(*it, context_->v8_context()));
39 }
40 v8::Handle<v8::Value> v8_error = context_->module_system()->CallModuleMethod(
41 "pepper_request", "startRequest", &v8_args);
42 if (v8_error->IsString()) {
43 if (error) {
44 *error = *v8::String::Utf8Value(v8_error);
45 pending_request_map_.erase(request_id);
46 }
47 return false;
48 }
49
50 return true;
51 }
52
OnResponseReceived(int request_id,bool success,const base::ListValue & args,const std::string & error)53 void PepperRequestProxy::OnResponseReceived(int request_id,
54 bool success,
55 const base::ListValue& args,
56 const std::string& error) {
57 PendingRequestMap::iterator it = pending_request_map_.find(request_id);
58 DCHECK(it != pending_request_map_.end());
59 it->second.Run(success, args, error);
60 pending_request_map_.erase(it);
61 }
62
63 } // namespace extensions
64