• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
5var SendResponse = requireNative('pepper_request_natives').SendResponse;
6var GetAvailability = requireNative('v8_context').GetAvailability;
7var utils = require('utils');
8var schemaRegistry = requireNative('schema_registry');
9
10function takesCallback(targetName) {
11  var parts = $String.split(targetName, '.');
12  var schemaName = $Array.join($Array.slice(parts, 0, parts.length - 1), '.');
13  var functionName = parts[parts.length - 1];
14  var functions = schemaRegistry.GetSchema(schemaName).functions;
15  var parameters = utils.lookup(functions, 'name', functionName).parameters;
16  return parameters.length > 0 &&
17         parameters[parameters.length - 1].type == 'function';
18}
19
20function resolveName(name) {
21  var availability = GetAvailability(name);
22  if (!availability.is_available)
23    throw Error(availability.message);
24  var item = chrome;
25  var nameComponents = $String.split(name, '.');
26  for (var i = 0; i < nameComponents.length; i++) {
27    item = item[nameComponents[i]];
28  }
29  return item;
30}
31
32function startRequest(targetName, requestId) {
33  var args = $Array.slice(arguments, 2);
34  try {
35    var hasCallback = takesCallback(targetName);
36    if (hasCallback) {
37      args.push(function() {
38        var error = null;
39        if (chrome.runtime.lastError)
40          error = chrome.runtime.lastError.message;
41        SendResponse(requestId, $Array.slice(arguments), error);
42      });
43    }
44    var target = resolveName(targetName);
45    var result = $Function.apply(target, null, args);
46    if (!hasCallback)
47      SendResponse(requestId, [result], null);
48  } catch (e) {
49    // TODO(sammc): Catch this from C++.
50    return e.message;
51  }
52}
53
54exports.startRequest = startRequest;
55