Ejemplo n.º 1
0
PyObject*
js2py_with_parent(Context* cx, jsval val, jsval parent)
{
    JSType vtype = JS_TypeOfValue(cx->cx, val);
    PyObject* unwrapped;

    /*
        There's not JSType for null. Or rather, its
        reported as Object which causes segfaults.
    */
    if(JSVAL_IS_NULL(val) || JSVAL_IS_VOID(val))
    {
        Py_RETURN_NONE;
    }
    else if(vtype == JSTYPE_BOOLEAN)
    {
        if(JSVAL_TO_BOOLEAN(val))
        {
            Py_RETURN_TRUE;
        }
        else
        {
            Py_RETURN_FALSE;
        }
    }
    else if(vtype == JSTYPE_STRING)
    {
        return js2py_string(cx, val);
    }
    else if(vtype == JSTYPE_NUMBER)
    {
        if(JSVAL_IS_INT(val)) return js2py_integer(cx, val);
        else return js2py_double(cx, val);
    }

    /* Now try to unwrap any incoming object in so we don't rewrap our own objects being passed around. */

    unwrapped = unwrap_pyobject(val);

    if (unwrapped != NULL)
	return unwrapped;

    if(vtype == JSTYPE_FUNCTION)
    {
        return js2py_function(cx, val, parent);
    }
    else if(vtype == JSTYPE_OBJECT)
    {
        JSObject* obj = JSVAL_TO_OBJECT(val);
        if(JS_IsArrayObject(cx->cx, obj))
        {
            return js2py_array(cx, val);
        }
        
        return js2py_object(cx, val);
    }
    
    PyErr_SetString(PyExc_RuntimeError, "Unknown JSVAL type.");
    return NULL;
}
Ejemplo n.º 2
0
/*
 * call-seq:
 *   function_property?(name)
 *
 * Returns <code>true</code> if this JavaScript object's +name+ property
 * is a function.
 */
static VALUE
function_property_p(VALUE self, VALUE name)
{
  if (TYPE(name) == T_SYMBOL)
    name = rb_funcall(name, rb_intern("to_s"), 0);

  rb_string_value_cstr(&name);

  RubyLandProxy* proxy;
  Data_Get_Struct(self, RubyLandProxy, proxy);
  JSContext * context = johnson_get_current_context(proxy->runtime);

  PREPARE_RUBY_JROOTS(context, 2);

  jsval proxy_value;
  JCHECK(get_jsval_for_proxy(proxy, &proxy_value));
  JROOT(proxy_value);

  jsval js_value;  

  JCHECK(JS_GetProperty(context,
      JSVAL_TO_OBJECT(proxy_value), StringValueCStr(name), &js_value));

  JROOT(js_value);

  JSType type = JS_TypeOfValue(context, js_value);

  JRETURN_RUBY(type == JSTYPE_FUNCTION ? Qtrue : Qfalse);
}
Ejemplo n.º 3
0
    void append( BSONObjBuilder& b , string name , jsval val , BSONType oldType = EOO , int depth=0 ) {
        //cout << "name: " << name << "\t" << typeString( val ) << " oldType: " << oldType << endl;
        switch ( JS_TypeOfValue( _context , val ) ) {

        case JSTYPE_VOID:
            b.appendUndefined( name.c_str() );
            break;
        case JSTYPE_NULL:
            b.appendNull( name.c_str() );
            break;

        case JSTYPE_NUMBER: {
            double d = toNumber( val );
            if ( oldType == NumberInt && ((int)d) == d )
                b.append( name.c_str() , (int)d );
            else
                b.append( name.c_str() , d );
            break;
        }
        case JSTYPE_STRING:
            b.append( name.c_str() , toString( val ) );
            break;
        case JSTYPE_BOOLEAN:
            b.appendBool( name.c_str() , toBoolean( val ) );
            break;

        case JSTYPE_OBJECT: {
            JSObject * o = JSVAL_TO_OBJECT( val );
            if ( ! o || o == JSVAL_NULL ) {
                b.appendNull( name.c_str() );
            }
            else if ( ! appendSpecialDBObject( this , b , name , val , o ) ) {
                BSONObj sub = toObject( o , depth );
                if ( JS_IsArrayObject( _context , o ) ) {
                    b.appendArray( name.c_str() , sub );
                }
                else {
                    b.append( name.c_str() , sub );
                }
            }
            break;
        }

        case JSTYPE_FUNCTION: {
            string s = toString(val);
            if ( s[0] == '/' ) {
                appendRegex( b , name , s );
            }
            else {
                b.appendCode( name.c_str() , getFunctionCode( val ).c_str() );
            }
            break;
        }

        default:
            uassert( 10217 ,  (string)"can't append field.  name:" + name + " type: " + typeString( val ) , 0 );
        }
    }
Ejemplo n.º 4
0
nsresult
nsJSON::EncodeInternal(JSContext* cx, const JS::Value& aValue,
                       nsJSONWriter* writer)
{
  JSAutoRequest ar(cx);

  // Backward compatibility:
  // nsIJSON does not allow to serialize anything other than objects
  if (!aValue.isObject()) {
    return NS_ERROR_INVALID_ARG;
  }

  JSObject* obj = &aValue.toObject();

  JS::Value val = aValue;

  /* Backward compatibility:
   * Manually call toJSON if implemented by the object and check that
   * the result is still an object
   * Note: It is perfectly fine to not implement toJSON, so it is
   * perfectly fine for GetMethod to fail
   */
  JS::Value toJSON;
  if (JS_GetMethod(cx, obj, "toJSON", NULL, &toJSON) &&
      !JSVAL_IS_PRIMITIVE(toJSON) &&
      JS_ObjectIsCallable(cx, JSVAL_TO_OBJECT(toJSON))) {
    // If toJSON is implemented, it must not throw
    if (!JS_CallFunctionValue(cx, obj, toJSON, 0, NULL, &val)) {
      if (JS_IsExceptionPending(cx))
        // passing NS_OK will throw the pending exception
        return NS_OK;

      // No exception, but still failed
      return NS_ERROR_FAILURE;
    }

    // Backward compatibility:
    // nsIJSON does not allow to serialize anything other than objects
    if (JSVAL_IS_PRIMITIVE(val))
      return NS_ERROR_INVALID_ARG;
  }
  // GetMethod may have thrown
  else if (JS_IsExceptionPending(cx))
    // passing NS_OK will throw the pending exception
    return NS_OK;

  // Backward compatibility:
  // function shall not pass, just "plain" objects and arrays
  JSType type = JS_TypeOfValue(cx, val);
  if (type == JSTYPE_FUNCTION)
    return NS_ERROR_INVALID_ARG;

  // We're good now; try to stringify
  if (!JS_Stringify(cx, &val, NULL, JSVAL_NULL, WriteCallback, writer))
    return NS_ERROR_FAILURE;

  return NS_OK;
}
Ejemplo n.º 5
0
bool js_util_DirectoryUtils_walkFiles(JSContext *cx, uint32_t argc, jsval *vp)
{
    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);

    JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
    js_proxy_t *proxy = jsb_get_js_proxy(obj);
    auto cobj = (Utils::DirectoryUtils *)(proxy ? proxy->ptr : NULL);
    JSB_PRECONDITION2( cobj, cx, false, "js_util_DirectoryUtils_walkFiles : Invalid Native Object");

    if (argc == 4) {
        std::string arg0;
        bool arg1;
        std::string arg2;
        Utils::DirectoryUtils::walkCallback arg3;

        bool ok = true;
        do {
            ok = jsval_to_std_string(cx, args.get(0), &arg0);
            if (!ok) break;

            ok = jsval_to_bool(cx, args.get(1), &arg1);
            if (!ok) break;

            ok = jsval_to_std_string(cx, args.get(2), &arg2);
            if (!ok) break;

            ok = JS_TypeOfValue(cx, args.get(3)) == JSTYPE_FUNCTION;
            if (!ok) break;

            JSObject* thisObj = JS_THIS_OBJECT(cx, vp); // TODO 其它用法
            std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, thisObj, args.get(3)));
            arg3 = [=](const char* arg0, const char* arg1, const char* arg2) -> void {
                JS::RootedValue rval(cx);
                JS::AutoValueVector args(cx);
                args.reserve(3);
                args.append(STRING_TO_JSVAL(c_str_to_js_str(cx, arg0)));
                args.append(STRING_TO_JSVAL(c_str_to_js_str(cx, arg1)));
                args.append(STRING_TO_JSVAL(c_str_to_js_str(cx, arg2)));
                bool ok = func->invoke(args, &rval);
                if (!ok && JS_IsExceptionPending(cx)) {
                    JS_ReportPendingException(cx);
                }
            };

            cobj->walkFiles(arg0.c_str(), arg1, arg2.c_str(), arg3);

        } while (0);

        JSB_PRECONDITION2(ok, cx, false, "js_util_DirectoryUtils_walkFiles : Error processing arguments");

        args.rval().setUndefined();
        return true;
    }

    JS_ReportError(cx, "js_util_DirectoryUtils_walkFiles : wrong number of arguments");
    return false;
}
Ejemplo n.º 6
0
int
to_erl_intern(ErlNifEnv* env, JSContext* cx, jsval val, ERL_NIF_TERM* term)
{
    JSObject* obj = NULL;
    JSType type = JS_TypeOfValue(cx, val);
        
    if(val == JSVAL_NULL)
    {
        return to_erl_atom(env, "null", term);
    }
    else if(val == JSVAL_VOID)
    {
        // return ERROR;
        return to_erl_atom(env, "undefined", term);
    }
    else if(type == JSTYPE_BOOLEAN)
    {
        if(val == JSVAL_TRUE)
            return to_erl_atom(env, "true", term);
        else
            return to_erl_atom(env, "false", term);
    }
    else if(type == JSTYPE_STRING)
    {
        return to_erl_string(env, cx, val, term);
    }
    else if(type == JSTYPE_XML)
    {
        return to_erl_string(env, cx, val, term);
    }
    else if(type == JSTYPE_NUMBER)
    {
        if(JSVAL_IS_INT(val))
            return to_erl_int(env, cx, val, term);
        else
            return to_erl_float(env, cx, val, term);
    }
    else if(type == JSTYPE_OBJECT)
    {
        obj = JSVAL_TO_OBJECT(val);

        if(OK == to_erl_convert(env, cx, obj, term))
        {
            return OK;
        }
        
        if(JS_IsArrayObject(cx, obj))
        {
            return to_erl_array(env, cx, obj, term);
        }

        return to_erl_object(env, cx, obj, term);
    }

    return ERROR;
}
bool js_EventDispatcher_addCustomEventListener(JSContext *cx, uint32_t argc, jsval *vp)
{
    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
    bool ok = true;
    JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
    js_proxy_t *proxy = jsb_get_js_proxy(obj);
    cocos2d::EventDispatcher* cobj = (cocos2d::EventDispatcher *)(proxy ? proxy->ptr : NULL);
    JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_EventDispatcher_addCustomEventListener : Invalid Native Object");
    if (argc == 2) {
        std::string arg0;
        std::function<void (cocos2d::EventCustom *)> arg1;
        ok &= jsval_to_std_string(cx, args.get(0), &arg0);
        do {
            if(JS_TypeOfValue(cx, args.get(1)) == JSTYPE_FUNCTION)
            {
                JS::RootedObject jstarget(cx, args.thisv().toObjectOrNull());
                std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, jstarget, args.get(1), args.thisv()));
                auto lambda = [=](cocos2d::EventCustom* event) -> void {
                    JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
                    jsval largv[1];
                    if (event) {
                        js_type_class_t *typeClassEvent = js_get_type_from_native<EventCustom>(event);
                        largv[0] = OBJECT_TO_JSVAL(jsb_get_or_create_weak_jsobject(cx, event, typeClassEvent));
                    } else {
                        largv[0] = JSVAL_NULL;
                    };
                    JS::RootedValue rval(cx);
                    bool succeed = func->invoke(JS::HandleValueArray::fromMarkedLocation(1, largv), &rval);
                    if (!succeed && JS_IsExceptionPending(cx)) {
                        JS_ReportPendingException(cx);
                    }
                };
                arg1 = lambda;
            }
            else
            {
                arg1 = nullptr;
            }
        } while(0);
        JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_EventDispatcher_addCustomEventListener : Error processing arguments");
        cocos2d::EventListenerCustom* ret = cobj->addCustomEventListener(arg0, arg1);
        JS::RootedValue jsret(cx);
        if (ret) {
            jsret = OBJECT_TO_JSVAL(js_get_or_create_jsobject<EventListenerCustom>(cx, ret));
            args.rval().set(jsret);
        } else {
            jsret = JSVAL_NULL;
        };
        args.rval().set(jsret);
        return true;
    }
    
    JS_ReportError(cx, "js_cocos2dx_EventDispatcher_addCustomEventListener : wrong number of arguments: %d, was expecting %d", argc, 2);
    return false;
}
Ejemplo n.º 8
0
nsresult
nsJSON::EncodeInternal(nsJSONWriter *writer)
{
  nsresult rv;
  nsIXPConnect *xpc = nsContentUtils::XPConnect();
  if (!xpc)
    return NS_ERROR_FAILURE;

  nsAXPCNativeCallContext *cc = nsnull;
  rv = xpc->GetCurrentNativeCallContext(&cc);
  NS_ENSURE_SUCCESS(rv, rv);

  JSContext *cx = nsnull;
  rv = cc->GetJSContext(&cx);
  NS_ENSURE_SUCCESS(rv, rv);

  JSAutoRequest ar(cx);

  PRUint32 argc = 0;
  rv = cc->GetArgc(&argc);
  NS_ENSURE_SUCCESS(rv, rv);

  // Now fish for the JS arguments. If it's a call to encode, we'll
  // want the first two arguments. If it's a call to encodeToStream,
  // we'll want the fourth and fifth;
  PRUint32 firstArg = writer->mStream ? 3 : 0;

  // Get the object we're going to serialize.
  JSObject *inputObj = nsnull;
  jsval *argv = nsnull;
  rv = cc->GetArgvPtr(&argv);
  NS_ENSURE_SUCCESS(rv, rv);

  if (argc <= firstArg ||
      !(JSVAL_IS_OBJECT(argv[firstArg]) &&
        (inputObj = JSVAL_TO_OBJECT(argv[firstArg])))) {
    // return if it's not something we can deal with
    return NS_ERROR_INVALID_ARG;
  }

  jsval *vp = &argv[firstArg];
  JSBool ok = JS_TryJSON(cx, vp);
  JSType type;
  if (!(ok && !JSVAL_IS_PRIMITIVE(*vp) &&
        (type = JS_TypeOfValue(cx, *vp)) != JSTYPE_FUNCTION &&
        type != JSTYPE_XML)) {
    return NS_ERROR_INVALID_ARG;
  }

  ok = JS_Stringify(cx, vp, NULL, JSVAL_NULL, WriteCallback, writer);
  if (!ok)
    return NS_ERROR_FAILURE;
    
  return NS_OK;
}
Ejemplo n.º 9
0
JSBool
Core_print (JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
    JS_BeginRequest(cx);
    JS_EnterLocalRootScope(cx);

    char*     separator = " ";
    char*     end       = "\n";
    int       fd        = fileno(stdout);
    FILE*     fp        = NULL;
    jsval     property;
    JSObject* options;

    if (argc > 1 && JS_TypeOfValue(cx, argv[argc-1]) == JSTYPE_OBJECT) {
        JS_ValueToObject(cx, argv[argc-1], &options);
        argc--;

        JS_GetProperty(cx, options, "separator", &property);
        if (JSVAL_IS_VOID(property) || JSVAL_IS_NULL(property)) {
            JS_GetProperty(cx, options, "sep", &property);
        }

        if (JSVAL_IS_STRING(property)) {
            separator = JS_GetStringBytes(JS_ValueToString(cx, property));
        }

        JS_GetProperty(cx, options, "end", &property);
        if (JSVAL_IS_STRING(property)) {
            end = JS_GetStringBytes(JS_ValueToString(cx, property));
        }

        JS_GetProperty(cx, options, "file", &property);
        if (JSVAL_IS_NUMBER(property)) {
            fd = JSVAL_TO_INT(property);
        }
    }

    fp = fdopen(fd, "a+");

    uintN i;
    for (i = 0; i < argc; i++) {
        fprintf(fp, "%s", JS_GetStringBytes(JS_ValueToString(cx, argv[i])));

        if (i != argc-1) {
            fprintf(fp, "%s", separator);
        }
    }
    fprintf(fp, "%s", end);

    JS_LeaveLocalRootScope(cx);
    JS_EndRequest(cx);

    return JS_TRUE;
}
Ejemplo n.º 10
0
nsresult
nsJSON::EncodeInternal(JSContext* cx, const JS::Value& aValue,
                       nsJSONWriter* writer)
{
  // Backward compatibility:
  // nsIJSON does not allow to serialize anything other than objects
  if (!aValue.isObject()) {
    return NS_ERROR_INVALID_ARG;
  }
  JS::Rooted<JSObject*> obj(cx, &aValue.toObject());

  /* Backward compatibility:
   * Manually call toJSON if implemented by the object and check that
   * the result is still an object
   * Note: It is perfectly fine to not implement toJSON, so it is
   * perfectly fine for GetMethod to fail
   */
  JS::Rooted<JS::Value> val(cx, aValue);
  JS::Rooted<JS::Value> toJSON(cx);
  if (JS_GetProperty(cx, obj, "toJSON", &toJSON) &&
      toJSON.isObject() &&
      JS_ObjectIsCallable(cx, &toJSON.toObject())) {
    // If toJSON is implemented, it must not throw
    if (!JS_CallFunctionValue(cx, obj, toJSON, 0, nullptr, val.address())) {
      if (JS_IsExceptionPending(cx))
        // passing NS_OK will throw the pending exception
        return NS_OK;

      // No exception, but still failed
      return NS_ERROR_FAILURE;
    }

    // Backward compatibility:
    // nsIJSON does not allow to serialize anything other than objects
    if (val.isPrimitive())
      return NS_ERROR_INVALID_ARG;
  }
  // GetMethod may have thrown
  else if (JS_IsExceptionPending(cx))
    // passing NS_OK will throw the pending exception
    return NS_OK;

  // Backward compatibility:
  // function shall not pass, just "plain" objects and arrays
  JSType type = JS_TypeOfValue(cx, val);
  if (type == JSTYPE_FUNCTION)
    return NS_ERROR_INVALID_ARG;

  // We're good now; try to stringify
  if (!JS_Stringify(cx, &val, JS::NullPtr(), JS::NullHandleValue, WriteCallback, writer))
    return NS_ERROR_FAILURE;

  return NS_OK;
}
Ejemplo n.º 11
0
/*
 * call-seq:
 *   function?()
 *
 * Returns <code>true</code> if this JavaScript object is a function.
 */
static VALUE
function_p(VALUE self)
{
  RubyLandProxy* proxy;
  Data_Get_Struct(self, RubyLandProxy, proxy);
  JSContext * context = johnson_get_current_context(proxy->runtime);
  PREPARE_RUBY_JROOTS(context, 1);
  jsval proxy_value;
  JCHECK(get_jsval_for_proxy(proxy, &proxy_value));
  JROOT(proxy_value);
  JRETURN_RUBY(JS_TypeOfValue(context, proxy_value) == JSTYPE_FUNCTION ? Qtrue : Qfalse);
}
Ejemplo n.º 12
0
int
to_erl_intern(emonk_buf_t* buf, JSContext* cx, jsval val)
{
    JSObject* obj = NULL;
    JSType type = JS_TypeOfValue(cx, val);
    int status = ERROR;
        
    if(val == JSVAL_NULL)
    {
        return to_erl_atom(buf, "null", 4);
    }
    else if(val == JSVAL_VOID)
    {
        JS_ReportError(cx, "Cannot encode 'undefined' value as JSON");
        return ERROR;
    }
    else if(type == JSTYPE_BOOLEAN)
    {
        if(val == JSVAL_TRUE)
            return to_erl_atom(buf, "true", 4);
        else
            return to_erl_atom(buf, "false", 5);
    }
    else if(type == JSTYPE_STRING)
    {
        return to_erl_string(buf, cx, val);
    }
    else if(type == JSTYPE_XML)
    {
        return to_erl_string(buf, cx, val);
    }
    else if(type == JSTYPE_NUMBER)
    {
        if(JSVAL_IS_INT(val))
            return to_erl_int(buf, cx, val);
        else
            return to_erl_float(buf, cx, val);
    }
    else if(type == JSTYPE_OBJECT)
    {
        obj = JSVAL_TO_OBJECT(val);
        status = to_erl_from_handler(buf, cx, obj);
        if(status != IGNORE) return status;
        
        if(JS_IsArrayObject(cx, obj))
        {
            return to_erl_array(buf, cx, obj);
        }
        return to_erl_object(buf, cx, obj);
    }
    
    return ERROR;
}
Ejemplo n.º 13
0
static JSBool xgg_label_propop_bold_set(JSContext *pcxa, JSObject *pobja, jsval id, jsval *vp)
{
	//XGG_LABEL_PRIV*	pv0 = JS_GetPrivate(pcxa, pobja);
	//XJSEXADGELEM*	pe0 = pv0->hdr.pxadgelem;
	//XJSECTX*		pjsectx = (XJSECTX*)JS_GetContextPrivate(pcxa);

	JSType			type1 = JS_TypeOfValue(pcxa, vp[0]);
	if(type1 == JSTYPE_VOID)	// "undefined"
		goto	cleanup;

cleanup:
	return	JS_TRUE;
}
bool js_cocos2dx_audioengine_AudioEngine_preload(JSContext *cx, uint32_t argc, jsval *vp)
{
    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
    bool ok = true;
    
    do {
        if (argc == 2) {
            std::string arg0;
            ok &= jsval_to_std_string(cx, args.get(0), &arg0);
            if (!ok) { ok = true; break; }
            std::function<void (bool)> arg1;
            do {
			    if(JS_TypeOfValue(cx, args.get(1)) == JSTYPE_FUNCTION)
			    {
			        std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, args.thisv().toObjectOrNull(), args.get(1)));
			        auto lambda = [=](bool larg0) -> void {
			            JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
			            jsval largv[1];
			            largv[0] = BOOLEAN_TO_JSVAL(larg0);
			            JS::RootedValue rval(cx);
			            bool succeed = func->invoke(1, &largv[0], &rval);
			            if (!succeed && JS_IsExceptionPending(cx)) {
			                JS_ReportPendingException(cx);
			            }
			        };
			        arg1 = lambda;
			    }
			    else
			    {
			        arg1 = nullptr;
			    }
			} while(0)
			;
            if (!ok) { ok = true; break; }
            cocos2d::experimental::AudioEngine::preload(arg0, arg1);
            return true;
        }
    } while (0);
    
    do {
        if (argc == 1) {
            std::string arg0;
            ok &= jsval_to_std_string(cx, args.get(0), &arg0);
            if (!ok) { ok = true; break; }
            cocos2d::experimental::AudioEngine::preload(arg0);
            return true;
        }
    } while (0);
    JS_ReportError(cx, "js_cocos2dx_audioengine_AudioEngine_preload : wrong number of arguments");
    return false;
}
bool js_EventListenerAcceleration_create(JSContext *cx, uint32_t argc, jsval *vp)
{
    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
    bool ok = true;
    if (argc == 1) {
        std::function<void (Acceleration *, Event *)> arg0;
        JSFunctionWrapper *wrapper = nullptr;
        do {
            if(JS_TypeOfValue(cx, args.get(0)) == JSTYPE_FUNCTION)
            {
                JS::RootedObject jstarget(cx, args.thisv().toObjectOrNull());
                std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, jstarget, args.get(0)));
                wrapper = func.get();
                auto lambda = [=](Acceleration* acc, Event* event) -> void {
                    JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
                    jsval largv[2];
                    largv[0] = ccacceleration_to_jsval(cx, *acc);
                    if (event) {
                        js_type_class_t *typeClassEvent = js_get_type_from_native<Event>(event);
                        largv[1] = OBJECT_TO_JSVAL(jsb_get_or_create_weak_jsobject(cx, event, typeClassEvent));
                    } else {
                        largv[1] = JSVAL_NULL;
                    };
                    JS::RootedValue rval(cx);
                    bool succeed = func->invoke(2, &largv[0], &rval);
                    if (!succeed && JS_IsExceptionPending(cx)) {
                        JS_ReportPendingException(cx);
                    }
                };
                arg0 = lambda;
            }
            else
            {
                arg0 = nullptr;
            }
        } while(0);
        JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_EventListenerAcceleration_create : Error processing arguments");
        
        auto ret = EventListenerAcceleration::create(arg0);
        JS::RootedValue jsret(cx, OBJECT_TO_JSVAL(js_get_or_create_jsobject<EventListenerAcceleration>(cx, ret)));
        if (wrapper)
        {
            wrapper->setOwner(cx, jsret);
        }
        args.rval().set(jsret);
        return true;
    }
    JS_ReportError(cx, "js_cocos2dx_EventListenerAcceleration_create : wrong number of arguments");
    return false;
}
Ejemplo n.º 16
0
char *js_get_message(jsval v) {
	jsval messages, msg, rval;
	uint32_t messages_len;
	char *c_str;
	int i;
	struct string_buffer sb = STRING_BUFFER_INITIALIZER;

	if (!JS_GetProperty(js_context, JSVAL_TO_OBJECT(v), "messages", &messages)) {
		return NULL;
	}

	switch(JS_TypeOfValue(js_context, messages)) {
		case JSTYPE_STRING:
			c_str = JS_EncodeString(js_context, JSVAL_TO_STRING(messages));
			return c_str;

		case JSTYPE_OBJECT:
			if (!JS_GetArrayLength(js_context, JSVAL_TO_OBJECT(messages), &messages_len)) {
				return NULL;
			}

			for (i = 0; i < (int) messages_len; i++) {
				if (!JS_GetElement(js_context, JSVAL_TO_OBJECT(messages), i, &msg)) {
					goto out_err;
				}

				c_str = JS_EncodeString(js_context, JSVAL_TO_STRING(msg));

				if (string_buffer_append_string(&sb, c_str))
					goto out_err;

				if (i < (int) messages_len - 1) {
					if (string_buffer_append_char(&sb, '\n'))
						goto out_err;
				}

				free(c_str);
			}

			return sb.s;
		default:
			break;
	}

out_err:
	free(c_str);
	string_buffer_cleanup(&sb);
	return NULL;
}
Ejemplo n.º 17
0
VALUE convert_to_ruby(JohnsonRuntime* runtime, jsval js)
{
  if (JSVAL_NULL == js) return Qnil;

  JSContext * context = johnson_get_current_context(runtime);

  PREPARE_RUBY_JROOTS(context, 1);
  JROOT(js);
  
  switch (JS_TypeOfValue(context, js))
  {
    case JSTYPE_VOID:
      JRETURN_RUBY(Qnil);
      
    case JSTYPE_FUNCTION: 
    case JSTYPE_OBJECT:
      if (OBJECT_TO_JSVAL(runtime->global) == js)
        // global gets special treatment, since the Prelude might not be loaded
        JRETURN_RUBY(make_ruby_land_proxy(runtime, js, "GlobalProxy"));
      
      // this conditional requires the Prelude
      if (js_value_is_symbol(runtime, js))
        JRETURN_RUBY(ID2SYM(rb_intern(JS_GetStringBytes(JS_ValueToString(context, js)))));
    
      if (js_value_is_proxy(runtime, js))
        JRETURN_RUBY(unwrap_js_land_proxy(runtime, js));

      if (js_value_is_regexp(runtime, js))
        JRETURN_RUBY(convert_regexp_to_ruby(runtime, js));
    
      JRETURN_RUBY(make_ruby_land_proxy(runtime, js, "RubyLandProxy"));
        
    case JSTYPE_BOOLEAN:
      JRETURN_RUBY(JSVAL_TRUE == js ? Qtrue : Qfalse);
      
    case JSTYPE_STRING:
      JRETURN_RUBY(convert_js_string_to_ruby(runtime, JSVAL_TO_STRING(js)));
      
    case JSTYPE_NUMBER:
      if (JSVAL_IS_INT(js)) JRETURN_RUBY(INT2FIX(JSVAL_TO_INT(js)));
      else JRETURN_RUBY(rb_float_new(*JSVAL_TO_DOUBLE(js)));

    default:
      JERROR("unknown js type in switch");
  }
  
  JRETURN_RUBY(Qnil);
}
Ejemplo n.º 18
0
static JSBool
jsOnWheel( JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval )
{
   *rval = JSVAL_FALSE ;
   if( (1 == argc) && (JSTYPE_FUNCTION == JS_TypeOfValue(cx, argv[0]))){
      if( JSVAL_VOID != onWheelCode_ ){
         JS_RemoveRoot( cx, &onWheelCode_ );
      }
      onWheelCode_ = argv[0];
      JS_AddRoot( cx, &onWheelCode_ );
      *rval = JSVAL_TRUE ;
   } else
      JS_ReportError(cx,"Usage: onWheel(function);\n" );

   return JS_TRUE ;
}
Ejemplo n.º 19
0
int add_header_properties(jsval *header, jsval *name, jsval *parts_recv) {
	int i;
	uint32_t arr_len;
	JSObject *parts_obj;
	jsval parts;

	// Set name property
	if (!JS_SetProperty(js_context, JSVAL_TO_OBJECT(*header), "hname", name)) {
		return -1;
	}

	// Add parts property
	switch(JS_TypeOfValue(js_context, *parts_recv)) {
		case JSTYPE_STRING:
			// Create the messages array property
			parts_obj = JS_NewArrayObject(js_context, 0, NULL);

			if (!parts_obj) {
				return -1;
			}

			// Add message to messages array
			if (!JS_SetElement(js_context, parts_obj, 0, parts_recv)) {
				return -1;
			}

			// Copy the messages to the property
			parts = OBJECT_TO_JSVAL(parts_obj);

			if (!JS_SetProperty(js_context, JSVAL_TO_OBJECT(*header), "parts", &parts)) {
				return -1;
			}

			break;
		case JSTYPE_OBJECT:
			// Copy the messages to the property
			if (!JS_SetProperty(js_context, JSVAL_TO_OBJECT(*header), "parts", parts_recv)) {
				return -1;
			}
			break;
		default:
			return -1;
	}

	return 0;
}
Ejemplo n.º 20
0
void jsPort_t :: onChar( void )
{
   jsval handler ;
   if( JS_GetProperty( execContext_, scope_, "onChar", &handler ) 
       &&
       ( JSTYPE_FUNCTION == JS_TypeOfValue( execContext_, handler ) ) )
   {
      executeCode( scope_, handler, "onChar", 0, 0 );
   } // have handler
   else
   {
      printf( "no raw data handler\n" );
      // clear input
      std::string sData ;
      read(sData);
   } // no handler defined
}
bool js_cocos2dx_cocosAds_CocosAds_addInterstitialAdListener(JSContext *cx, uint32_t argc, jsval *vp)
{
    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
    bool ok = true;
    JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
    js_proxy_t *proxy = jsb_get_js_proxy(obj);
    CocosAds* cobj = (CocosAds *)(proxy ? proxy->ptr : NULL);
    JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_cocosAds_CocosAds_addInterstitialAdListener : Invalid Native Object");
    if (argc == 1) {
        std::function<void (int, std::basic_string<char>)> arg0;
        do {
            if(JS_TypeOfValue(cx, args.get(0)) == JSTYPE_FUNCTION)
            {
                std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, args.thisv().toObjectOrNull(), args.get(0)));
                auto lambda = [=](int larg0, std::basic_string<char> larg1) -> void
                {
                    cocos2d::Director::getInstance()->getScheduler()->performFunctionInCocosThread([=]{
                        JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
                        jsval largv[2];
                        largv[0] = int32_to_jsval(cx, larg0);
                        largv[1] = std_string_to_jsval(cx, larg1);
                        JS::RootedValue rval(cx);
                        bool succeed = func->invoke(2, &largv[0], &rval);
                        if (!succeed && JS_IsExceptionPending(cx)) {
                            JS_ReportPendingException(cx);
                        }
                    });
                };
                arg0 = lambda;
            }
            else
            {
                arg0 = nullptr;
            }
        } while(0)
            ;
        JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_cocosAds_CocosAds_addInterstitialAdListener : Error processing arguments");
        cobj->addInterstitialAdListener(arg0);
        args.rval().setUndefined();
        return true;
    }
    
    JS_ReportError(cx, "js_cocos2dx_cocosAds_CocosAds_addInterstitialAdListener : wrong number of arguments: %d, was expecting %d", argc, 1);
    return false;
}
Ejemplo n.º 22
0
void jsUsblpPoll_t::onDataIn( void )
{
    jsval handler ;
    if( JS_GetProperty( execContext_, obj_, "onDataIn", &handler )
            &&
            ( JSTYPE_FUNCTION == JS_TypeOfValue( execContext_, handler ) ) )
    {
        executeCode( obj_, handler, "onDataIn", 0, 0 );
    } // have handler
    else
    {
        printf( "no raw data handler\n" );
        char temp[256];
        unsigned numRead ;
        while( read( temp, sizeof(temp), numRead ) )
            ;
    } // no handler defined
}
Ejemplo n.º 23
0
void jsPort_t :: onLineIn( void )
{
   jsval handler ;
   if( JS_GetProperty( execContext_, scope_, "onLineIn", &handler ) 
       &&
       ( JSTYPE_FUNCTION == JS_TypeOfValue( execContext_, handler ) ) )
   {
      executeCode( scope_, handler, "onLineIn", 0, 0 );
   } // have handler
   else
   {
      printf( "no line input handler\n" );
      // clear input
      std::string sData ;
      while( readln( sData ) )
         ;
   } // no handler defined, purge input
}
Ejemplo n.º 24
0
/*
 * Log a given jsval with a prefix.
 *  cx - JSContext for the JS execution context to use
 *  val - jsval to print
 *  prefix - string to print before the value, defaults to empty string
 *
 * TODO(jat): this whole printf-style logging needs to be replaced, but we
 * run into library version issues if we use C++ iostreams so we would need
 * to implement our own equivalent.  Given that this code is all likely to
 * be rewritten for out-of-process hosted mode, it seems unlikely to be worth
 * the effort until that is completed.
 */
void PrintJSValue(JSContext* cx, jsval val, char* prefix="") {
    JSType type = JS_TypeOfValue(cx, val);
    const char* typeString=JS_GetTypeName(cx, type);
    static const int BUF_SIZE = 256;
    char buf[BUF_SIZE];
    const char *bufEnd = buf + BUF_SIZE;
    char* p = buf;
    p += append_sprintf(p, bufEnd, "%s%s", prefix, typeString);
    switch(type) {
    case JSTYPE_VOID:
        break;
    case JSTYPE_BOOLEAN:
        p += append_sprintf(p, bufEnd, ": %s",
                            JSVAL_TO_BOOLEAN(val) ? "true" : "false");
        break;
    case JSTYPE_NUMBER:
        if (JSVAL_IS_INT(val)) {
            p += append_sprintf(p, bufEnd, ": %d", JSVAL_TO_INT(val));
        } else {
            p += append_sprintf(p, bufEnd, ": %lf", (double)*JSVAL_TO_DOUBLE(val));
        }
        break;
    case JSTYPE_OBJECT: {
        JSObject* obj = JSVAL_TO_OBJECT(val);
        if (!JSVAL_IS_OBJECT(val)) break;
        JSClass* clazz = obj ? JS_GET_CLASS(cx, obj) : 0;
        p += append_sprintf(p, bufEnd, " @ %08x, class %s",
                            (unsigned)obj, clazz ? clazz->name : "<null>");
        break;
    }
    case JSTYPE_FUNCTION:
    case JSTYPE_LIMIT:
        break;
    case JSTYPE_STRING: {
        /*
         * TODO(jat): support JS strings with international characters
         */
        JsStringWrap str(cx, JSVAL_TO_STRING(val));
        p += append_sprintf(p, bufEnd, ": %.*s", str.length(), str.bytes());
        break;
    }
    }
    Tracer::log("%s", buf);
}
Ejemplo n.º 25
0
static JSBool
ReceiverCommon(JSContext* cx, uintN argc, jsval* vp,
               const char* methodName, uintN arity,
               ReceiverResult* result)
{
  if (argc != arity) {
    JS_ReportError(cx, "%s requires exactly %d arguments", methodName, arity);
    return JS_FALSE;
  }

  // Not currently possible, but think of the future.
  if (arity < 1)
    return JS_TRUE;

  jsval* argv = JS_ARGV(cx, vp);

  JSString* str = JS_ValueToString(cx, argv[0]);
  if (!str) {
    JS_ReportError(cx, "%s expects a stringifiable value as its first argument",
                   methodName);
    return JS_FALSE;
  }

  size_t length;
  const jschar* chars = JS_GetStringCharsAndLength(cx, str, &length);
  if (!chars)
      return JS_FALSE;

  result->msgName.Assign(chars, length);

  if (arity < 2)
    return JS_TRUE;

  if (JS_TypeOfValue(cx, argv[1]) != JSTYPE_FUNCTION) {
    JS_ReportError(cx, "%s expects a function as its second argument",
                   methodName);
    return JS_FALSE;
  }

  // GC-safe because argv is rooted.
  result->receiver = argv[1];

  return JS_TRUE;
}
Ejemplo n.º 26
0
ScriptArrayJsapiSource ScriptArrayJsapiSource::Create(const rs::jsapi::Value& obj) {
    ScriptArrayJsapiSource source;
    
    auto cx = obj.getContext();
    JSAutoRequest ar{cx};    
    
    uint32_t length = 0;
    if (JS_GetArrayLength(cx, obj, &length) && length > 0) {
        source.stringValues_.resize(length);
        
        for (decltype(length) i = 0; i < length; ++i) {
            rs::jsapi::Value value{cx};
            if (JS_GetElement(cx, obj, i, value)) {                
                source.values_.emplace_back(value);
                
                switch (JS_TypeOfValue(cx, value)) {
                    case JSTYPE_OBJECT: 
                        if (source.values_[i].isArray() || rs::jsapi::DynamicArray::IsDynamicArray(source.values_[i])) {
                            source.types_.push_back(ScriptObjectType::Array);
                        } else if (!source.values_[i].isNull()) {
                            source.types_.push_back(ScriptObjectType::Object);
                        } else {
                            source.types_.push_back(ScriptObjectType::Null);
                        }
                        break;
                    
                    case JSTYPE_STRING: 
                        source.types_.push_back(ScriptObjectType::String); 
                        source.stringValues_[i] = source.values_[i].ToString(); 
                        break;
                    
                    case JSTYPE_NUMBER: source.types_.push_back(ScriptObjectType::Double); break;
                    case JSTYPE_BOOLEAN: source.types_.push_back(ScriptObjectType::Boolean); break;
                    default: source.types_.push_back(ScriptObjectType::Null); break;
                }
            } else {
                source.values_.emplace_back(cx);
            }
        }
    }
    
    return source;
}
bool js_cocos2dx_nativehelper_NativeHelper_setPacketAssembler(JSContext *cx, uint32_t argc, jsval *vp)
{
    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
    bool ok = true;
    JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
    js_proxy_t *proxy = jsb_get_js_proxy(obj);
    cocos2d::NativeHelper* cobj = (cocos2d::NativeHelper *)(proxy ? proxy->ptr : NULL);
    JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_nativehelper_NativeHelper_setPacketAssembler : Invalid Native Object");
    if (argc == 1) {
        std::function<void (std::basic_string<char>, int)> arg0;
        do {
		    if(JS_TypeOfValue(cx, args.get(0)) == JSTYPE_FUNCTION)
		    {
		        std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, args.thisv().toObjectOrNull(), args.get(0)));
		        auto lambda = [=](std::basic_string<char> larg0, int larg1) -> void {
		            JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
		            jsval largv[2];
		            largv[0] = std_string_to_jsval(cx, larg0);
		            largv[1] = int32_to_jsval(cx, larg1);
		            JS::RootedValue rval(cx);
		            bool ok = func->invoke(2, &largv[0], &rval);
		            if (!ok && JS_IsExceptionPending(cx)) {
		                JS_ReportPendingException(cx);
		            }
		        };
		        arg0 = lambda;
		    }
		    else
		    {
		        arg0 = nullptr;
		    }
		} while(0)
		;
        JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_nativehelper_NativeHelper_setPacketAssembler : Error processing arguments");
        cobj->setPacketAssembler(arg0);
        args.rval().setUndefined();
        return true;
    }

    JS_ReportError(cx, "js_cocos2dx_nativehelper_NativeHelper_setPacketAssembler : wrong number of arguments: %d, was expecting %d", argc, 1);
    return false;
}
Ejemplo n.º 28
0
/**
 * Callback for functions
 * This callback is called by JS when a function on a JSObject proxying
 * for an IDispatch instance
 * @param cx A pointer to a JS context
 * @param obj JS object that the parameterized property is on
 * @param argc Number of arguments in this call
 * @param argv The parameters passed in if any
 * @param vp The return value
 * @return Returns JS_TRUE if the operation succeeded
 */
JSBool JS_DLL_CALLBACK
XPC_IDispatch_CallMethod(JSContext* cx, JSObject* obj, uintN argc,
                         jsval* argv, jsval* vp)
{
    NS_ASSERTION(JS_TypeOfValue(cx, argv[-2]) == JSTYPE_FUNCTION, "bad function");
    JSObject* funobj = JSVAL_TO_OBJECT(argv[-2]);
    XPCCallContext ccx(JS_CALLER, cx, obj, funobj, 0, argc, argv, vp);
    XPCWrappedNative* wrapper = ccx.GetWrapper();
    THROW_AND_RETURN_IF_BAD_WRAPPER(cx, wrapper);
    ccx.SetArgsAndResultPtr(argc, argv, vp);

    XPCDispInterface::Member* member;
    XPCNativeInterface* iface;
#ifdef DEBUG
    PRBool ok =
#endif
    GetMember(ccx, funobj, iface, member);
    NS_ASSERTION(ok, "GetMember faild in XPC_IDispatch_CallMethod");
    ccx.SetIDispatchInfo(iface, member);

    return XPCDispObject::Invoke(ccx, XPCDispObject::CALL_METHOD);
}
bool js_cocos2dx_audioengine_AudioEngine_setFinishCallback(JSContext *cx, uint32_t argc, jsval *vp)
{
    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
    bool ok = true;
    if (argc == 2) {
        int arg0;
        std::function<void (int, const std::basic_string<char> &)> arg1;
        ok &= jsval_to_int32(cx, args.get(0), (int32_t *)&arg0);
        do {
		    if(JS_TypeOfValue(cx, args.get(1)) == JSTYPE_FUNCTION)
		    {
		        std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, args.thisv().toObjectOrNull(), args.get(1)));
		        auto lambda = [=](int larg0, const std::basic_string<char> & larg1) -> void {
		            JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
		            jsval largv[2];
		            largv[0] = int32_to_jsval(cx, larg0);
		            largv[1] = std_string_to_jsval(cx, larg1);
		            JS::RootedValue rval(cx);
		            bool succeed = func->invoke(2, &largv[0], &rval);
		            if (!succeed && JS_IsExceptionPending(cx)) {
		                JS_ReportPendingException(cx);
		            }
		        };
		        arg1 = lambda;
		    }
		    else
		    {
		        arg1 = nullptr;
		    }
		} while(0)
		;
        JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_audioengine_AudioEngine_setFinishCallback : Error processing arguments");
        cocos2d::experimental::AudioEngine::setFinishCallback(arg0, arg1);
        args.rval().setUndefined();
        return true;
    }
    JS_ReportError(cx, "js_cocos2dx_audioengine_AudioEngine_setFinishCallback : wrong number of arguments");
    return false;
}
Ejemplo n.º 30
0
Archivo: flim.c Proyecto: mrdg/flim
static JSBool at(JSContext *cx, uintN argc, jsval *vp)
{
    if (argc < 2) {
        flm_log("'at' requires at least 2 arguments: <time> <function>");
        return JS_FALSE;
    }

    jsval *arguments = JS_ARGV(cx, vp);

    uint32_t time;
    JS_ValueToECMAUint32(cx, arguments[0], &time);
    struct task *t = task_create(time);

    t->js_argc = 0;

    if (JS_TypeOfValue(cx, arguments[1]) == JSTYPE_FUNCTION) {
        t->js_function = arguments[1];
    } else {
        flm_log("2nd argument of 'at' should be a function");
        return JS_FALSE;
    }

    t->js_argc = (argc > 2 ? argc - 2 : 1);
    jsval *fn_args = malloc(t->js_argc * sizeof(jsval));
    if (argc > 2) {
        int i;
        for (i = 2; i < argc; i++) {
            fn_args[i - 2] = arguments[i];
        }
    } else {
        fn_args[0] = time;
    }

    t->js_args = fn_args;
    t->task_type = JS_FUNCTION;
    schedule_task(flim->scheduler, t);
    return JS_TRUE;
}