コード例 #1
0
ファイル: v8_sprite.cpp プロジェクト: seobyeongky/gunman
JsSprite::JsSprite(Isolate * isolate, Local<Object> handle)
	: ObjectWrap(handle), _texture(nullptr), _sprite()
{
    assert(handle->InternalFieldCount() > 1);
	handle->SetInternalField(0, External::New(isolate, &_sprite));
	handle->SetInternalField(1, External::New(isolate, this));
}
コード例 #2
0
ファイル: JSZAttribute.cpp プロジェクト: paoloach/zdomus
    v8::Local<v8::Object>
    JSZAttribute::createInstance(v8::Isolate *isolate, std::shared_ptr<ZCLAttribute> &zclAttribute) {
        if (zclAttribute->getZCLType() != getZCLType()) {
            throw JSExceptionInvalidAttributeType(getName(), zclAttribute->getZCLType(), getZCLType());
        }
        Local<ObjectTemplate> zAttributeT = Local<FunctionTemplate>::New(isolate, functionTemplate)->InstanceTemplate();
        Local<Object> zAttributeInstance = zAttributeT->NewInstance();

        zAttributeInstance->SetInternalField(0, External::New(isolate, zclAttribute.get()));
        zAttributeInstance->SetInternalField(1, External::New(isolate, this));
        return zAttributeInstance;
    }
コード例 #3
0
ファイル: ItemObject.cpp プロジェクト: bagobor/BitRPG
Local<Object> ItemObject::createInstance()
{
	HandleScope handleScope;
	
	// Create the function template
	
	Local<FunctionTemplate> functionTemplate = FunctionTemplate::New();
	functionTemplate->SetClassName(String::New("Item"));
	
	// Create the object template
	
	Local<ObjectTemplate> objectTemplate = functionTemplate->InstanceTemplate();
	objectTemplate->SetInternalFieldCount(1);
	
	// Create an object instance
	
	Local<Object> objectInstance = objectTemplate->NewInstance();
	objectInstance->SetInternalField(0, External::New(this));
	
	// Add functions to object instance
	
	/*
	Local<FunctionTemplate> printTemplate = FunctionTemplate::New(print);
	Local<Function> printFunction = printTemplate->GetFunction();
	objectInstance->Set(String::New("print"), printFunction);
	
	Local<FunctionTemplate> inputTemplate = FunctionTemplate::New(input);
	Local<Function> inputFunction = inputTemplate->GetFunction();
	objectInstance->Set(String::New("input"), inputFunction);
	*/
	
	return handleScope.Close(objectInstance);
}
コード例 #4
0
void ObjectManager::Link(const Local<Object>& object, uint32_t javaObjectID, jclass clazz)
{
	auto isolate = Isolate::GetCurrent();

	DEBUG_WRITE("Linking js object: %d and java instance id: %d", object->GetIdentityHash(), javaObjectID);

	JEnv env;

	auto jsInstanceInfo = new JSInstanceInfo();
	jsInstanceInfo->JavaObjectID = javaObjectID;
	jsInstanceInfo->clazz = clazz;

	auto objectHandle = new Persistent<Object>(isolate, object);
	auto state = new ObjectWeakCallbackState(this, jsInstanceInfo, objectHandle);
	objectHandle->SetWeak(state, JSObjectWeakCallbackStatic);

	auto jsInfoIdx = static_cast<int>(MetadataNodeKeys::JsInfo);
	bool alreadyLinked = !object->GetInternalField(jsInfoIdx)->IsUndefined();
	//ASSERT_MESSAGE(alreadyLinked, "object should not have been linked before");

	auto jsInfo = External::New(isolate, jsInstanceInfo);
	object->SetInternalField(jsInfoIdx, jsInfo);

	idToObject.insert(make_pair(javaObjectID, objectHandle));
}
コード例 #5
0
ファイル: Image.cpp プロジェクト: davidlehn/node-image
Image *Image::New(FIBITMAP* dib) {

  HandleScope scope;

  Local<Value> arg = Integer::NewFromUnsigned(0);
  Local<Object> obj = constructor_template->GetFunction()->NewInstance(1, &arg);

  Image *image = ObjectWrap::Unwrap<Image>(obj);
  image->dib = dib;

  int w,h,pitch;
  FREE_IMAGE_TYPE type = FreeImage_GetImageType(dib);

  obj->SetInternalField(0, External::New(dib));
  obj->Set(JS_STR("width"), JS_INT(w=FreeImage_GetWidth(dib)));
  obj->Set(JS_STR("height"), JS_INT(h=FreeImage_GetHeight(dib)));
  obj->Set(JS_STR("bpp"), JS_INT((int)FreeImage_GetBPP(dib)));
  obj->Set(JS_STR("pitch"), JS_INT(pitch=FreeImage_GetPitch(dib)));
  obj->Set(JS_STR("type"), JS_INT(type));
  obj->Set(JS_STR("redMask"), JS_INT((int)FreeImage_GetRedMask(dib)));
  obj->Set(JS_STR("greenMask"), JS_INT((int)FreeImage_GetGreenMask(dib)));
  obj->Set(JS_STR("blueMask"), JS_INT((int)FreeImage_GetBlueMask(dib)));

  BYTE *bits=FreeImage_GetBits(dib);
  node::Buffer *buf = node::Buffer::New((char*)bits,h*pitch);
  obj->Set(JS_STR("buffer"), buf->handle_);

  return image;
}
コード例 #6
0
ファイル: V8_Process.cpp プロジェクト: ACEZLY/server
/**
 * Utility function that wraps a C++ http request object in a
 * JavaScript object.
 */
Local<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) {
  // Local scope for temporary handles.
  EscapableHandleScope handle_scope(GetIsolate());

  // Fetch the template for creating JavaScript http request wrappers.
  // It only has to be created once, which we do on demand.
  if (request_template_.IsEmpty()) {
    Local<ObjectTemplate> raw_template = MakeRequestTemplate(GetIsolate());
    request_template_.Reset(GetIsolate(), raw_template);
  }
  Local<ObjectTemplate> templ =
      Local<ObjectTemplate>::New(GetIsolate(), request_template_);

  // Create an empty http request wrapper.
  Local<Object> result =
      templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();

  // Wrap the raw C++ pointer in an External so it can be referenced
  // from within JavaScript.
  Local<External> request_ptr = External::New(GetIsolate(), request);

  // Store the request pointer in the JavaScript wrapper.
  result->SetInternalField(0, request_ptr);

  // Return the result through the current handle scope.  Since each
  // of these handles will go away when the handle scope is deleted
  // we need to call Close to let one, the result, escape into the
  // outer handle scope.
  return handle_scope.Escape(result);
}
コード例 #7
0
void ObjectManager::Link(const Local<Object>& object, uint32_t javaObjectID, jclass clazz)
{
	int internalFieldCound = NativeScriptExtension::GetInternalFieldCount(object);
	const int count = static_cast<int>(MetadataNodeKeys::END);
	if (internalFieldCound != count)
	{
		string errMsg("Trying to link invalid 'this' to a Java object");
		throw NativeScriptException(errMsg);
	}

	auto isolate = Isolate::GetCurrent();

	DEBUG_WRITE("Linking js object: %d and java instance id: %d", object->GetIdentityHash(), javaObjectID);

	auto jsInstanceInfo = new JSInstanceInfo();
	jsInstanceInfo->JavaObjectID = javaObjectID;
	jsInstanceInfo->clazz = clazz;

	auto objectHandle = new Persistent<Object>(isolate, object);
	auto state = new ObjectWeakCallbackState(this, jsInstanceInfo, objectHandle);
	objectHandle->SetWeak(state, JSObjectWeakCallbackStatic);

	auto jsInfoIdx = static_cast<int>(MetadataNodeKeys::JsInfo);
	bool alreadyLinked = !object->GetInternalField(jsInfoIdx)->IsUndefined();
	//TODO: fail if alreadyLinked is true?

	auto jsInfo = External::New(isolate, jsInstanceInfo);
	object->SetInternalField(jsInfoIdx, jsInfo);

	idToObject.insert(make_pair(javaObjectID, objectHandle));
}
コード例 #8
0
ファイル: BGJSView.cpp プロジェクト: thetuxkeeper/ejecta-v8
Handle<Value> BGJSView::startJS(const char* fnName, const char* configJson, Handle<Value> uiObj, long configId) {
	HandleScope scope;

	Handle<Value> config;

	if (configJson) {
		config = String::New(configJson);
	} else {
		config = v8::Undefined();
	}

	// bgjsgl->Set(String::New("log"), FunctionTemplate::New(BGJSGLModule::log));
	Local<Object> objInstance = this->jsViewOT->NewInstance();
	objInstance->SetInternalField(0, External::New(this));
	// Local<Object> instance = bgjsglft->GetFunction()->NewInstance();
	this->_jsObj = Persistent<Object>::New(objInstance);

	Handle<Value> argv[4] = { uiObj, this->_jsObj, config, Number::New(configId) };

	Handle<Value> res = this->_jsContext->callFunction(_jsContext->_context->Global(), fnName, 4,
			argv);
	if (res->IsNumber()) {
		_contentObj = res->ToNumber()->Value();
#ifdef DEBUG
		LOGD ("startJS return id %d", _contentObj);
#endif
	} else {
		LOGI ("Did not receive a return id from startJS");
	}
	return scope.Close(res);
}
コード例 #9
0
ファイル: JsContext.cpp プロジェクト: venkatarajasekhar/Qt
// Wraps 'this' in a Javascript object.
Handle<Object> JsContext::wrap() {
    // Handle scope for temporary handles.
    EscapableHandleScope handleScope(fGlobal->getIsolate());

    // Fetch the template for creating JavaScript JsContext wrappers.
    // It only has to be created once, which we do on demand.
    if (gContextTemplate.IsEmpty()) {
        Local<ObjectTemplate> localTemplate = ObjectTemplate::New();

        // Add a field to store the pointer to a JsContext instance.
        localTemplate->SetInternalFieldCount(1);

        this->addAttributesAndMethods(localTemplate);

        gContextTemplate.Reset(fGlobal->getIsolate(), localTemplate);
    }
    Handle<ObjectTemplate> templ =
            Local<ObjectTemplate>::New(fGlobal->getIsolate(), gContextTemplate);

    // Create an empty JsContext wrapper.
    Local<Object> result = templ->NewInstance();

    // Wrap the raw C++ pointer in an External so it can be referenced
    // from within JavaScript.
    Handle<External> contextPtr = External::New(fGlobal->getIsolate(), this);

    // Store the context pointer in the JavaScript wrapper.
    result->SetInternalField(0, contextPtr);

    // Return the result through the current handle scope.  Since each
    // of these handles will go away when the handle scope is deleted
    // we need to call Close to let one, the result, escape into the
    // outer handle scope.
    return handleScope.Escape(result);
}
コード例 #10
0
ファイル: Image.cpp プロジェクト: luismreis/node-image
Image *Image::New(FIBITMAP* dib) {
  NanScope();

  Local<Value> arg = NanNew<Integer>(0);
  Local<Object> obj = NanNew<FunctionTemplate>(constructor_template)->GetFunction()->NewInstance(1, &arg);

  Image *image = ObjectWrap::Unwrap<Image>(obj);

  int w,h,pitch;
  FREE_IMAGE_TYPE type = FreeImage_GetImageType(dib);

  obj->SetInternalField(0, NanNew<External>(dib));
  obj->Set(NanNew<String>("width"), NanNew<Integer>(w=FreeImage_GetWidth(dib)));
  obj->Set(NanNew<String>("height"), NanNew<Integer>(h=FreeImage_GetHeight(dib)));
  obj->Set(NanNew<String>("bpp"), NanNew<Integer>((int)FreeImage_GetBPP(dib)));
  obj->Set(NanNew<String>("pitch"), NanNew<Integer>(pitch=FreeImage_GetPitch(dib)));
  obj->Set(NanNew<String>("type"), NanNew<Integer>(type));
  obj->Set(NanNew<String>("redMask"), NanNew<Integer>((int)FreeImage_GetRedMask(dib)));
  obj->Set(NanNew<String>("greenMask"), NanNew<Integer>((int)FreeImage_GetGreenMask(dib)));
  obj->Set(NanNew<String>("blueMask"), NanNew<Integer>((int)FreeImage_GetBlueMask(dib)));

  BYTE *bits = FreeImage_GetBits(dib);
  obj->Set(NanNew<String>("buffer"), NanNewBufferHandle((char*) bits, h * pitch));

  return image;
}
コード例 #11
0
ファイル: main.cpp プロジェクト: chinnurtb/GoogleV8Tutorials
// Defines a Point() JS Object
void PointConstructor( const FunctionCallbackInfo<v8::Value>& args )
{
    //Locker lock;
    HandleScope scope;
	Handle<ObjectTemplate> t = v8::ObjectTemplate::New();

	//The JavaScript point object only has 1 C++ object
	t->SetInternalFieldCount(1);

	// Create x and y members with starting values of 0
	//t->Set(String::New("x"), Number::New(0));
	t->SetAccessor(String::New("x"), 
		(AccessorGetterCallback)GetPointX,
		(AccessorSetterCallback)SetPointX);

	//t->Set(String::New("y"), Number::New(0));
	t->SetAccessor(String::New("y"),
		(AccessorGetterCallback)GetPointY,
		(AccessorSetterCallback)SetPointY);

	// Create a mul(number) function that scales the point
	t->Set(String::New("mul"), FunctionTemplate::New(MulCallback));

	// for use in the if statement
	Point *p = NULL;
	Local<Object> obj;
	
	// If Point(x, y) ctor was passed in values assign them
	if(!args[0].IsEmpty() && args[0]->IsNumber() &&
		!args[1].IsEmpty() && args[1]->IsNumber()) {
			//t->Set(String::New("x"), args[0]);
			//t->Set(String::New("y"), args[1]);
			p = new Point(args[0]->Int32Value(), args[1]->Int32Value());
			obj = t->NewInstance();
			obj->SetInternalField(0, External::New(p));			
	} else {
		/**
		 * Wrap a point object
		 */
		p = new Point(0, 0);
		obj = t->NewInstance();
		obj->SetInternalField(0, External::New(p));
	}

	// Return this newly created object
	args.GetReturnValue().Set(obj);
}
コード例 #12
0
ファイル: JSZCluster.cpp プロジェクト: paoloach/zdomus
    v8::Local<v8::Object>
    JSZCluster::createInstance(v8::Isolate *isolate, const ExtAddress &extAddress, EndpointID endpointId,
                               ClusterID clusterId) {

        if (!zDevices->exists(extAddress)) {
            throw JSExceptionNoDevice(extAddress);
        }
        auto zDevice = zDevices->getDevice(extAddress);

        NwkAddr nwkAddress = zDevice->getNwkAddr();
        Key key(nwkAddress, endpointId, clusterId);
        if (usedCluster.count(key) > 0) {
            return Local<Object>::New(isolate, usedCluster[key].get<0>());
        }

        if (!zDevice->isEndpointPresents(endpointId)) {
            throw JSExceptionNoEndpoint(extAddress, endpointId);
        }

        ZEndpoint zEndpoint = zDevice->getEndpoint(endpointId);
        if (!zEndpoint.hasInCluster(clusterId)) {
            throw JSExceptionNoInCluster(extAddress, endpointId, clusterId);
        }

        Local<ObjectTemplate> zClusterTemplate = Local<FunctionTemplate>::New(isolate,
                                                                              functionTemplate)->InstanceTemplate();
        Local<Object> zClusterInstance = zClusterTemplate->NewInstance();

        zClusterInstance->SetInternalField(0, External::New(isolate, this));

        std::shared_ptr<Cluster> cluster = clusterFactory->getCluster(clusterId, zigbeeDevice, endpointId,
                                                                      zDevice->getNwkAddr());
        zClusterInstance->SetInternalField(1, External::New(isolate, cluster.get()));

        std::shared_ptr<ExtAddress> usedAddr = getPersistenceExtAddress(extAddress);
        zClusterInstance->SetInternalField(2, External::New(isolate, usedAddr.get()));

        Value value{};

        value.get<0>().Reset(isolate, zClusterInstance);
        boost::get<1>(value) = cluster;

        usedCluster.insert({key, value});

        return zClusterInstance;
    }
コード例 #13
0
ファイル: V8Script.cpp プロジェクト: Databean/ProgNet
void makeLine(const v8::FunctionCallbackInfo<v8::Value>& args) {
	if(args.Length() != 4) {
		args.GetReturnValue().Set(Boolean::New(Isolate::GetCurrent(), false));
		return;
	}
	Local<External> shapeManagerExternal = Local<External>::Cast(args.Callee()->Get(String::NewFromUtf8(Isolate::GetCurrent(), shapeManagerStr.c_str())));
	ShapeManager2d* shapeManager = static_cast<ShapeManager2d*>(shapeManagerExternal->Value());
	
	Point2d p1{args[0]->NumberValue(), args[1]->NumberValue()};
	Point2d p2{args[2]->NumberValue(), args[3]->NumberValue()};
	
	Local<Object> obj = initShape()->NewInstance();
	unsigned int shape = shapeManager->makeLine(p1, p2);
	obj->SetInternalField(0, shapeManagerExternal);
	obj->SetInternalField(1, Integer::NewFromUnsigned(Isolate::GetCurrent(), shape));
	
	args.GetReturnValue().Set(obj);
}
コード例 #14
0
bool ObjectManager::CloneLink(const Local<Object>& src, const Local<Object>& dest)
{
	auto jsInfo = GetJSInstanceInfo(src);

	auto success = jsInfo != nullptr;

	if (success)
	{
		auto jsInfoIdx = static_cast<int>(MetadataNodeKeys::JsInfo);
		auto jsInfo = src->GetInternalField(jsInfoIdx);
		dest->SetInternalField(jsInfoIdx, jsInfo);
	}

	return success;
}
コード例 #15
0
void CanvasRenderingContext2D::Create(const v8::FunctionCallbackInfo<v8::Value>& args)
{
	auto isolate = args.GetIsolate();
	HandleScope scope(isolate);

	Local<ObjectTemplate> contextTemplate = ObjectTemplate::New(isolate);
	contextTemplate->SetInternalFieldCount(1);

	contextTemplate->Set(ConvertToV8String("__draw"), FunctionTemplate::New(isolate, &Draw));
	contextTemplate->Set(ConvertToV8String("__sizeChanged"), FunctionTemplate::New(isolate, &SizeChanged));

	contextTemplate->SetAccessor(ConvertToV8String("fillStyle"), &GetFillStyle, &SetFillStyle);
	contextTemplate->SetAccessor(ConvertToV8String("strokeStyle"), &GetStrokeStyle, &SetStrokeStyle);

	contextTemplate->Set(ConvertToV8String("arc"), FunctionTemplate::New(isolate, &Arc));
	contextTemplate->Set(ConvertToV8String("beginPath"), FunctionTemplate::New(isolate, &BeginPath));
	contextTemplate->Set(ConvertToV8String("bezierCurveTo"), FunctionTemplate::New(isolate, &BezierCurveTo));
	contextTemplate->Set(ConvertToV8String("clearRect"), FunctionTemplate::New(isolate, &ClearRect));
	contextTemplate->Set(ConvertToV8String("closePath"), FunctionTemplate::New(isolate, &ClosePath));
	contextTemplate->Set(ConvertToV8String("drawImage"), FunctionTemplate::New(isolate, &DrawImage));
	contextTemplate->Set(ConvertToV8String("fill"), FunctionTemplate::New(isolate, &Fill));
	contextTemplate->Set(ConvertToV8String("fillRect"), FunctionTemplate::New(isolate, &FillRect));
	contextTemplate->Set(ConvertToV8String("fillText"), FunctionTemplate::New(isolate, &FillText));
	contextTemplate->Set(ConvertToV8String("getImageData"), FunctionTemplate::New(isolate, &GetImageData));
	contextTemplate->Set(ConvertToV8String("lineTo"), FunctionTemplate::New(isolate, &LineTo));
	contextTemplate->Set(ConvertToV8String("measureText"), FunctionTemplate::New(isolate, &MeasureText));
	contextTemplate->Set(ConvertToV8String("moveTo"), FunctionTemplate::New(isolate, &MoveTo));
	contextTemplate->Set(ConvertToV8String("quadraticCurveTo"), FunctionTemplate::New(isolate, &QuadraticCurveTo));
	contextTemplate->Set(ConvertToV8String("restore"), FunctionTemplate::New(isolate, &Restore));
	contextTemplate->Set(ConvertToV8String("rotate"), FunctionTemplate::New(isolate, &Rotate));
	contextTemplate->Set(ConvertToV8String("save"), FunctionTemplate::New(isolate, &Save));
	contextTemplate->Set(ConvertToV8String("stroke"), FunctionTemplate::New(isolate, &Stroke));
	contextTemplate->Set(ConvertToV8String("translate"), FunctionTemplate::New(isolate, &Translate));

	Local<Object> newContext = contextTemplate->NewInstance();
	newContext->ForceSet(ConvertToV8String("canvas"), args[0]);
	newContext->ForceSet(ConvertToV8String("__kind"), ConvertToV8String("2d"));

	auto nativeContext = new CanvasRenderingContext2D();
	newContext->SetInternalField(0, External::New(isolate, nativeContext));

	Persistent<Object> persistentHandle(isolate, newContext);
	persistentHandle.SetWeak(nativeContext, &Deallocate);

	args.GetReturnValue().Set(newContext);
}
コード例 #16
0
Local<Object> MetadataNode::CreateExtendedJSWrapper(Isolate *isolate, const string& proxyClassName)
{
	Local<Object> extInstance;

	auto cacheData = GetCachedExtendedClassData(isolate, proxyClassName);
	if (cacheData.node != nullptr)
	{
		extInstance = s_objectManager->GetEmptyObject(isolate);
		extInstance->SetInternalField(static_cast<int>(ObjectManager::MetadataNodeKeys::CallSuper), True(isolate));
		auto extdCtorFunc = Local<Function>::New(isolate, *cacheData.extendedCtorFunction);
		extInstance->SetPrototype(extdCtorFunc->Get(ConvertToV8String("prototype")));

		SetInstanceMetadata(isolate, extInstance, cacheData.node);
	}

	return extInstance;
}
コード例 #17
0
ファイル: ItemObject.cpp プロジェクト: bagobor/BitRPG
Handle<Value> ItemObject::constructor(const Arguments &args)
{
	HandleScope handleScope;
	
	// Make sure the constructor is called with the new keyword
	
	if (!args.IsConstructCall())
	{
		Local<String> message = String::New("Cannot call constructor as a function");
		return ThrowException(Exception::SyntaxError(message));
	}
	
	// Instantiate a new ScriptTemplate
	
	ItemObject *itemObject = new ItemObject();
	Local<Object> itemInstance = itemObject->createInstance();
	itemInstance->SetInternalField(0, External::New(itemObject));
	
	return handleScope.Close(itemInstance);
}
コード例 #18
0
ファイル: SUIPictureBox.cpp プロジェクト: denjones/spengine
Handle<Object> SUIPictureBox::GetV8Obj()
{
	Isolate* isolate = SPV8ScriptEngine::GetSingleton()->GetIsolate();

	if (!v8Obj)
	{
		Local<Object> obj = Handle<Object>();

		Handle<ObjectTemplate> handleTempl = SV8ScriptManager::GetSingleton()->GetPictureBoxTemplate();
		obj = handleTempl->NewInstance();

		if(!obj.IsEmpty())
		{
			obj->SetInternalField(0, External::New(this));
			v8Obj = new Persistent<Object>(isolate, obj);
		}
	}

	return Handle<Object>::New(isolate, *v8Obj);
}
コード例 #19
0
ファイル: NaObject.cpp プロジェクト: neoarc/NaMacroJS
Local<Object> NaObject::WrapObject(Isolate *isolate, NaObject * pObject)
{
	// Local scope for temporary handles.
	EscapableHandleScope handle_scope(isolate);

	// Fetch the template for creating JavaScript map wrappers.
	// It only has to be created once, which we do on demand.
	Global<ObjectTemplate> &_ObjectTemplate = pObject->GetObjectTemplate();
	if (_ObjectTemplate.IsEmpty())
	{
		Local<ObjectTemplate> RawTemplate = pObject->MakeObjectTemplate(isolate);
		_ObjectTemplate.Reset(isolate, RawTemplate);
	}

	Local<ObjectTemplate> templ = Local<ObjectTemplate>::New(isolate, _ObjectTemplate);

	// Create an empty NaObject wrapper.
	Local<Object> result = templ->NewInstance(isolate->GetCurrentContext()).ToLocalChecked();

	// Wrap the raw C++ pointer in an External so it can be referenced from within JavaScript.
	Local<External> obj_ptr = External::New(isolate, pObject);

	// Store the NaObject pointer in the JavaScript wrapper.
	result->SetInternalField(0, obj_ptr);

	pObject->AddRef();

	// Make weak
	Local<Object> handle = v8::Local<v8::Object>::New(isolate, pObject->m_Persistent);
	pObject->m_Persistent.Reset(isolate, result);
	pObject->MakeWeak();

	// Return the result through the current handle scope.  Since each
	// of these handles will go away when the handle scope is deleted
	// we need to call Close to let one, the result, escape into the
	// outer handle scope.
	return handle_scope.Escape(result);
}
コード例 #20
0
ファイル: Server.cpp プロジェクト: damospiderman/samp.js
void Server::Init(){

	JS_SCOPE(_isolate)
	JS_CONTEXT(_isolate,_context)

	Local<ObjectTemplate> sampjs_templ = ObjectTemplate::New(_isolate);
	sampjs_templ->SetInternalFieldCount(1);

	Local<Object> sampjs = sampjs_templ->NewInstance();
	sampjs->SetInternalField(0, External::New(_isolate, this));

	SetGlobalObject("$sampjs", sampjs);


	Local<ObjectTemplate> module_templ = ObjectTemplate::New(_isolate);

	Local<ObjectTemplate> cache_templ = ObjectTemplate::New(_isolate);

	module_templ->Set(String::NewFromUtf8(_isolate, "_cache"), cache_templ->NewInstance());

	Local<Object> module = module_templ->NewInstance();

	SetGlobalFunction("memory", Server::JS_GetMemory);

	SetGlobalFunction("require", Server::Require);
	SetGlobalFunction("include", Server::Include);
	SetGlobalFunction("CallNative", Server::CallNative);
	SetGlobalFunction("SetTimer", Server::SetTimer);
	SetGlobalFunction("CancelTimer", Server::CancelTimer);

	SetGlobalFunction("load", Server::JS_LoadScript);
	SetGlobalFunction("unload", Server::JS_UnloadScript);
	SetGlobalFunction("reload", Server::JS_ReloadScript);

	SetGlobalObject("$modules", module);

	_eventManager = make_shared<Events>(shared_from_this());
}
コード例 #21
0
   v8::Handle<v8::Object> WrapElementDocument(v8::Handle<v8::Context> context, Rocket::Core::ElementDocument* v)
   {
      
      v8::HandleScope handle_scope;

      Handle<FunctionTemplate> templt = GetScriptSystem()->GetTemplateBySID(s_elementDocumentWrapper);
      if(templt.IsEmpty())
      {

        templt = FunctionTemplate::New();
        templt->Inherit(GetElementTemplate());
        templt->SetClassName(String::New("ElementDocument"));
        templt->InstanceTemplate()->SetInternalFieldCount(1);
		  templt->InstanceTemplate()->SetNamedPropertyHandler(
           ELNamedPropertyGetter,
           ELNamedPropertySetter,
           ELNamedPropertyQuery,
           ELNamedPropertyDeleter,
           ELNamedPropertyEnumerator
        );

        Handle<ObjectTemplate> proto = templt->PrototypeTemplate();

		  proto->Set("hide", FunctionTemplate::New(EDHide));
        proto->Set("toString", FunctionTemplate::New(EDToString));
        proto->Set("show", FunctionTemplate::New(EDShow));
        proto->Set("hide", FunctionTemplate::New(EDHide));
        proto->Set("close", FunctionTemplate::New(EDClose));

        GetScriptSystem()->SetTemplateBySID(s_elementDocumentWrapper, templt);

      }
      Local<Object> instance = templt->GetFunction()->NewInstance();
      instance->SetInternalField(0, External::New(v));
      return handle_scope.Close(instance);

   }
コード例 #22
0
ファイル: AudioObject.cpp プロジェクト: bagobor/BitRPG
Local<Object> AudioObject::createInstance()
{
	HandleScope handleScope;
	
	Local<FunctionTemplate> functionTemplate = createClass("Audio");
	Local<ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
	
	// Create the methods
	
	addPrototypeMethod(prototypeTemplate, playMusic, "playMusic");
	addPrototypeMethod(prototypeTemplate, stopMusic, "stopMusic");
	
	// Create the object template
	
	Local<ObjectTemplate> objectTemplate = functionTemplate->InstanceTemplate();
	objectTemplate->SetInternalFieldCount(1);
	
	// Create an object instance
	
	Local<Object> objectInstance = objectTemplate->NewInstance();
	objectInstance->SetInternalField(0, External::New(this));
	
	return handleScope.Close(objectInstance);
}
コード例 #23
0
ファイル: V8Script.cpp プロジェクト: Databean/ProgNet
static Handle<ObjectTemplate> initShape() {
	HandleScope handleScope(Isolate::GetCurrent());
	
	auto getColor = [](Local<String> property, const v8::PropertyCallbackInfo<v8::Value>& info) {
		Local<Object> self = info.Holder();
		Local<External> managerWrap = Local<External>::Cast(self->GetInternalField(0));
		Local<Integer> shapeWrap = Local<Integer>::Cast(self->GetInternalField(1));
		
		ShapeManager2d* manager = static_cast<ShapeManager2d*>(managerWrap->Value());
		Shape2d& shape = (*manager)[shapeWrap->Value()];
		
		Local<Object> obj = initColor()->NewInstance();
		obj->SetInternalField(0, External::New(Isolate::GetCurrent(), static_cast<void*>(&shape.color())));
		
		info.GetReturnValue().Set(obj);
	};
	
	auto setColor = [](Local<String> property, Local<Value> value, const v8::PropertyCallbackInfo<void>& info) {
		Local<Object> self = info.Holder();
		Local<External> managerWrap = Local<External>::Cast(self->GetInternalField(0));
		Local<Integer> shapeWrap = Local<Integer>::Cast(self->GetInternalField(1));
		Local<External> colorWrap = Local<External>::Cast(value);
		
		ShapeManager2d* manager = static_cast<ShapeManager2d*>(managerWrap->Value());
		Shape2d& shape = (*manager)[shapeWrap->Value()];
		Color* newColor = static_cast<Color*>(colorWrap->Value());
		
		shape.setColor(*newColor);
	};
	
	auto getOffset = [](Local<String> property, const v8::PropertyCallbackInfo<v8::Value>& info) {
		Local<Object> self = info.Holder();
		Local<External> managerWrap = Local<External>::Cast(self->GetInternalField(0));
		Local<Integer> shapeWrap = Local<Integer>::Cast(self->GetInternalField(1));
		
		ShapeManager2d* manager = static_cast<ShapeManager2d*>(managerWrap->Value());
		Shape2d& shape = (*manager)[shapeWrap->Value()];
		
		Local<Object> obj = initPoint()->NewInstance();
		obj->SetInternalField(0, External::New(Isolate::GetCurrent(), static_cast<void*>(&shape.offset())));
		
		info.GetReturnValue().Set(obj);
	};
	
	auto setOffset = [](Local<String> property, Local<Value> value, const v8::PropertyCallbackInfo<void>& info) {
		Local<Object> self = info.Holder();
		Local<External> managerWrap = Local<External>::Cast(self->GetInternalField(0));
		Local<Integer> shapeWrap = Local<Integer>::Cast(self->GetInternalField(1));
		Local<External> pointWrap = Local<External>::Cast(value);
		
		ShapeManager2d* manager = static_cast<ShapeManager2d*>(managerWrap->Value());
		Shape2d& shape = (*manager)[shapeWrap->Value()];
		Point2d* newOffset = static_cast<Point2d*>(pointWrap->Value());
		
		shape.setOffset(*newOffset);
	};
	
	auto getRotation = [](Local<String> property, const v8::PropertyCallbackInfo<v8::Value>& info) {
		Local<Object> self = info.Holder();
		Local<External> managerWrap = Local<External>::Cast(self->GetInternalField(0));
		Local<Integer> shapeWrap = Local<Integer>::Cast(self->GetInternalField(1));
		
		ShapeManager2d* manager = static_cast<ShapeManager2d*>(managerWrap->Value());
		Shape2d& shape = (*manager)[shapeWrap->Value()];
		
		info.GetReturnValue().Set(Number::New(Isolate::GetCurrent(), shape.rotation()));
	};
	
	auto setRotation = [](Local<String> property, Local<Value> value, const v8::PropertyCallbackInfo<void>& info) {
		Local<Object> self = info.Holder();
		Local<External> managerWrap = Local<External>::Cast(self->GetInternalField(0));
		Local<Integer> shapeWrap = Local<Integer>::Cast(self->GetInternalField(1));
		
		ShapeManager2d* manager = static_cast<ShapeManager2d*>(managerWrap->Value());
		Shape2d& shape = (*manager)[shapeWrap->Value()];
		
		shape.setRotation(value->NumberValue());
	};
	
	auto getPoint = [](unsigned int index, const v8::PropertyCallbackInfo<v8::Value>& info) {
		Local<Object> self = info.Holder();
		Local<External> managerWrap = Local<External>::Cast(self->GetInternalField(0));
		Local<Integer> shapeWrap = Local<Integer>::Cast(self->GetInternalField(1));
		
		ShapeManager2d* manager = static_cast<ShapeManager2d*>(managerWrap->Value());
		Shape2d& shape = (*manager)[shapeWrap->Value()];
		
		Local<Object> obj = initPoint()->NewInstance();
		obj->SetInternalField(0, External::New(Isolate::GetCurrent(), static_cast<void*>(&shape[index])));
		
		info.GetReturnValue().Set(obj);
	};
	
	auto setPoint = [](unsigned int index, Local<Value > value, const v8::PropertyCallbackInfo<v8::Value>& info) {
		Local<Object> self = info.Holder();
		Local<External> managerWrap = Local<External>::Cast(self->GetInternalField(0));
		Local<Integer> shapeWrap = Local<Integer>::Cast(self->GetInternalField(1));
		Local<External> pointWrap = Local<External>::Cast(value);
		
		ShapeManager2d* manager = static_cast<ShapeManager2d*>(managerWrap->Value());
		Shape2d& shape = (*manager)[shapeWrap->Value()];
		Point2d* newOffset = static_cast<Point2d*>(pointWrap->Value());
		
		shape.setPoint(index, *newOffset);
		
		//Returns to indicate that the access was intercepted.
		//info.GetReturnValue() = value;
	};
	
	//Workaround (i think)
	Handle<FunctionTemplate> func_tmpl = FunctionTemplate::New(Isolate::GetCurrent());
	Handle<ObjectTemplate> shape_tmpl = func_tmpl->InstanceTemplate();
	shape_tmpl->SetAccessor(String::NewFromUtf8(Isolate::GetCurrent(), "color"), getColor, setColor);
	shape_tmpl->SetAccessor(String::NewFromUtf8(Isolate::GetCurrent(), "offset"), getOffset, setOffset);
	shape_tmpl->SetAccessor(String::NewFromUtf8(Isolate::GetCurrent(), "rotation"), getRotation, setRotation);
	shape_tmpl->SetIndexedPropertyHandler(getPoint, setPoint);
	
	shape_tmpl->SetInternalFieldCount(2);
	
	//Local<Object> o = shape_tmpl->NewInstance();
	//std::cout << o->InternalFieldCount() << std::endl;
	
	return shape_tmpl;
}
コード例 #24
0
void CanvasContextV8Bindings::loadScript(const std::string& _filename, OgreCanvas::CanvasContext* _canvasContext, OgreCanvas::CanvasLogger* _console)
{
	CanvasContextV8Bindings::context2D = _canvasContext;
	
	HandleScope handle_scope;
	
	//Console :
		
		//template
		Handle<FunctionTemplate> consoleTemplate = FunctionTemplate::New();
		consoleTemplate->SetClassName(v8::String::New("Console"));
		CanvasContextV8Bindings::consoleTemplate = Persistent<FunctionTemplate>::New(consoleTemplate);

		//prototype
		Handle<ObjectTemplate> consolePrototype = consoleTemplate->PrototypeTemplate();

		//attaching method
		consolePrototype->Set("log", FunctionTemplate::New(log));

		//creating instance
		Handle<ObjectTemplate> consoleInstance = consoleTemplate->InstanceTemplate();
		consoleInstance->SetInternalFieldCount(1);

	//Image :
		
		//template
		Handle<FunctionTemplate> imageTemplate = FunctionTemplate::New();
		imageTemplate->SetClassName(v8::String::New("Image"));
		CanvasContextV8Bindings::imageTemplate = Persistent<FunctionTemplate>::New(imageTemplate);

		//prototype
		Handle<ObjectTemplate> imagePrototype = imageTemplate->PrototypeTemplate();

		//creating instance
		Handle<ObjectTemplate> imageInstance = imageTemplate->InstanceTemplate();
		imageInstance->SetInternalFieldCount(1);

	//Canvas gradient :
		
		//template
		Handle<FunctionTemplate> canvasGradientTemplate = FunctionTemplate::New();
		canvasGradientTemplate->SetClassName(v8::String::New("CanvasGradient"));
		CanvasContextV8Bindings::canvasGradientTemplate = Persistent<FunctionTemplate>::New(canvasGradientTemplate);

		//prototype
		Handle<ObjectTemplate> canvasGradientPrototype = canvasGradientTemplate->PrototypeTemplate();

		//creating instance
		Handle<ObjectTemplate> canvasGradientInstance = canvasGradientTemplate->InstanceTemplate();
		canvasGradientInstance->SetInternalFieldCount(1);

		//attaching method
		canvasGradientPrototype->Set("addColorStop", FunctionTemplate::New(addColorStop));

	//Canvas Pattern :

		//template
		Handle<FunctionTemplate> canvasPatternTemplate = FunctionTemplate::New();
		canvasPatternTemplate->SetClassName(v8::String::New("CanvasPattern"));
		CanvasContextV8Bindings::canvasPatternTemplate = Persistent<FunctionTemplate>::New(canvasPatternTemplate);

		//prototype
		Handle<ObjectTemplate> canvasPatternPrototype = canvasPatternTemplate->PrototypeTemplate();
		
		//creating instance
		Handle<ObjectTemplate> canvasPatternInstance = canvasPatternTemplate->InstanceTemplate();
		canvasPatternInstance->SetInternalFieldCount(1);

	//Canvas context :

		//template
		Handle<FunctionTemplate> canvasContextTemplate = FunctionTemplate::New();
		canvasContextTemplate->SetClassName(v8::String::New("CanvasContext"));
	
		//prototype
		Handle<ObjectTemplate> canvasContextPrototype = canvasContextTemplate->PrototypeTemplate();

		//attaching method

			//2D Context
			canvasContextPrototype->Set("save",        FunctionTemplate::New(save));
			canvasContextPrototype->Set("restore",     FunctionTemplate::New(restore));

			//Transformation
			canvasContextPrototype->Set("scale",        FunctionTemplate::New(scale));
			canvasContextPrototype->Set("rotate",       FunctionTemplate::New(rotate));
			canvasContextPrototype->Set("translate",    FunctionTemplate::New(translate));
			canvasContextPrototype->Set("transform",    FunctionTemplate::New(transform));
			canvasContextPrototype->Set("setTransform", FunctionTemplate::New(setTransform));
			
			//Image drawing
			canvasContextPrototype->Set("drawImage",    FunctionTemplate::New(drawImage));		

			//Colors, styles and shadows
			canvasContextPrototype->Set("createLinearGradient", FunctionTemplate::New(createLinearGradient));
			canvasContextPrototype->Set("createRadialGradient", FunctionTemplate::New(createRadialGradient));
			canvasContextPrototype->Set("createPattern",        FunctionTemplate::New(createPattern));

			//Paths
			canvasContextPrototype->Set("beginPath",        FunctionTemplate::New(beginPath));
			canvasContextPrototype->Set("closePath",        FunctionTemplate::New(closePath));		
			canvasContextPrototype->Set("fill",             FunctionTemplate::New(fill));
			canvasContextPrototype->Set("stroke",           FunctionTemplate::New(stroke));
			canvasContextPrototype->Set("clip",             FunctionTemplate::New(clip));

			canvasContextPrototype->Set("moveTo",           FunctionTemplate::New(moveTo));
			canvasContextPrototype->Set("lineTo",           FunctionTemplate::New(lineTo));
			canvasContextPrototype->Set("quadraticCurveTo", FunctionTemplate::New(quadraticCurveTo));
			canvasContextPrototype->Set("bezierCurveTo",    FunctionTemplate::New(bezierCurveTo));
			canvasContextPrototype->Set("arcTo",            FunctionTemplate::New(arcTo));
			canvasContextPrototype->Set("arc",              FunctionTemplate::New(arc));
			canvasContextPrototype->Set("rect",             FunctionTemplate::New(rect));
			canvasContextPrototype->Set("isPointInPath",    FunctionTemplate::New(isPointInPath));

			//Text
			canvasContextPrototype->Set("fillText",    FunctionTemplate::New(fillText));
			canvasContextPrototype->Set("strokeText",  FunctionTemplate::New(strokeText));
			canvasContextPrototype->Set("measureText", FunctionTemplate::New(measureText));

			//Rectangles
			canvasContextPrototype->Set("clearRect",   FunctionTemplate::New(clearRect));
			canvasContextPrototype->Set("fillRect",    FunctionTemplate::New(fillRect));
			canvasContextPrototype->Set("strokeRect",  FunctionTemplate::New(strokeRect));

			//New
			canvasContextPrototype->Set("saveToPNG",   FunctionTemplate::New(saveToPNG));		
			canvasContextPrototype->Set("clear",       FunctionTemplate::New(clear));

		//creating instance
		Handle<ObjectTemplate> canvasContextInstance = canvasContextTemplate->InstanceTemplate();
		canvasContextInstance->SetInternalFieldCount(1);

		//attaching properties

			//Compositing
			canvasContextInstance->SetAccessor(v8::String::New("globalAlpha"), getterGlobalAlpha, setterGlobalAlpha);
			canvasContextInstance->SetAccessor(v8::String::New("globalCompositeOperation"), getterGlobalCompositeOperation, setterGlobalCompositeOperation);
			
			//Line styles
			canvasContextInstance->SetAccessor(v8::String::New("lineWidth"),   getterLineWidth,  setterLineWidth);
			canvasContextInstance->SetAccessor(v8::String::New("lineCap"),     getterLineCap,    setterLineCap);
			canvasContextInstance->SetAccessor(v8::String::New("lineJoin"),    getterLineJoin,   setterLineJoin);
			canvasContextInstance->SetAccessor(v8::String::New("miterLimit"),  getterMiterLimit, setterMiterLimit);
			canvasContextInstance->SetAccessor(v8::String::New("lineDash"),    getterLineDash,   setterLineDash);
			
			//Colors, styles and shadows
			canvasContextInstance->SetAccessor(v8::String::New("fillStyle"),     getterFillStyle,     setterFillStyle);
			canvasContextInstance->SetAccessor(v8::String::New("strokeStyle"),   getterStrokeStyle,   setterStrokeStyle);
			canvasContextInstance->SetAccessor(v8::String::New("shadowOffsetX"), getterShadowOffsetX, setterShadowOffsetX);
			canvasContextInstance->SetAccessor(v8::String::New("shadowOffsetY"), getterShadowOffsetY, setterShadowOffsetY);
			canvasContextInstance->SetAccessor(v8::String::New("shadowBlur"),    getterShadowBlur,    setterShadowBlur);
			canvasContextInstance->SetAccessor(v8::String::New("shadowColor"),   getterShadowColor,   setterShadowColor);

			//Text
			canvasContextInstance->SetAccessor(v8::String::New("font"),         getterFont,         setterFont);
			canvasContextInstance->SetAccessor(v8::String::New("textAlign"),    getterTextAlign,    setterTextAlign);
			canvasContextInstance->SetAccessor(v8::String::New("textBaseline"), getterTextBaseline, setterTextBaseline);
			
			//New
			canvasContextInstance->SetAccessor(v8::String::New("antialiasing"), getterAntiAliasing, setterAntiAliasing);

	//Image
	Handle<ObjectTemplate> global = ObjectTemplate::New();
	global->Set(String::New("loadImage"), FunctionTemplate::New(loadImage));

	Persistent<Context> context = Context::New(NULL, global);
	CanvasContextV8Bindings::contextV8 = context;

	Context::Scope context_scope(context);

		//building link between js 'ctx' variable and c++ _canvasContext variable
		Handle<Function> canvasContextConstructor = canvasContextTemplate->GetFunction();
		Local<Object> obj = canvasContextConstructor->NewInstance();
		obj->SetInternalField(0, External::New(_canvasContext));
		context->Global()->Set(v8::String::New("ctx"), obj);

		//building link between js 'console' variable and c++ _console variable
		Handle<Function> consoleConstructor = consoleTemplate->GetFunction();
		Local<Object> obj2 = consoleConstructor->NewInstance();
		obj2->SetInternalField(0, External::New(_console));
		context->Global()->Set(v8::String::New("console"), obj2);

	Handle<v8::String> source = v8::String::New(readScript(_filename).c_str());
	Handle<Script> script = Script::Compile(source);
	Handle<Value> result = script->Run();
	/*
	CanvasContextV8Bindings::canvasGradientTemplate.Dispose();
	CanvasContextV8Bindings::canvasPatternTemplate.Dispose();
	CanvasContextV8Bindings::imageTemplate.Dispose();
	*/
}
コード例 #25
0
   Handle<Object> WrapComponent(Handle<Object> wrappedes, ScriptSystem* scriptsys, dtEntity::EntityId eid, dtEntity::Component* v)
   {

      HandleScope handle_scope;

      Handle<Object> wrapped = scriptsys->GetFromComponentMap(v->GetType(), eid);
      if(!wrapped.IsEmpty())
      {
         return wrapped;
      }

      Handle<FunctionTemplate> templt = GetScriptSystem()->GetTemplateBySID(s_componentWrapper);
      if(templt.IsEmpty())
      {

         templt = FunctionTemplate::New();

         templt->SetClassName(String::New("Component"));
         templt->InstanceTemplate()->SetInternalFieldCount(1);

         Handle<ObjectTemplate> proto = templt->PrototypeTemplate();

         proto->Set("equals", FunctionTemplate::New(COEquals));
         proto->Set("getType", FunctionTemplate::New(COGetType));
         proto->Set("properties", FunctionTemplate::New(COProperties));
         proto->Set("toString", FunctionTemplate::New(COToString));
         proto->Set("finished", FunctionTemplate::New(COFinished));
         proto->Set("copyPropertyValues", FunctionTemplate::New(COCopyPropertyValues));

         GetScriptSystem()->SetTemplateBySID(s_componentWrapper, templt);
      }


      Local<Object> instance = templt->GetFunction()->NewInstance();
      instance->SetInternalField(0, External::New(v));
      instance->SetHiddenValue(scriptsys->GetEntityIdString(), Uint32::New(eid));

      // GetStringFromSID and conversion to v8::String is costly, create a 
      // hidden value in entity system wrapper that stores
      // strings and their string ids as name=>value pairs
      Handle<Value> propnamesval = wrappedes->GetHiddenValue(scriptsys->GetPropertyNamesString());
      if(propnamesval.IsEmpty())
      {
         Handle<Object> names = Object::New();
         dtEntity::PropertyGroup::const_iterator i;
         const dtEntity::PropertyGroup& props = v->Get();
         for(i = props.begin(); i != props.end(); ++i)
         {
            dtEntity::StringId sid = i->first;
            std::string propname = dtEntity::GetStringFromSID(sid);
            names->Set(String::New(propname.c_str()), WrapSID(sid));
         }
         wrappedes->SetHiddenValue(scriptsys->GetPropertyNamesString(), names);
         propnamesval = names;
      }

      Handle<Object> propnames = Handle<Object>::Cast(propnamesval);
      Handle<Array> keys = propnames->GetPropertyNames();
      for(unsigned int i = 0; i < keys->Length(); ++i)
      {
         Handle<String> str = keys->Get(i)->ToString();
         dtEntity::StringId sid = UnwrapSID(propnames->Get(str));
         dtEntity::Property* prop = v->Get(sid);
         if(prop == NULL)
         {
            LOG_ERROR("Could not find property in component: " << ToStdString(str));
            continue;
         }
         Handle<External> ext = v8::External::New(static_cast<void*>(prop));
         instance->SetAccessor(str, COPropertyGetter, COPropertySetter, ext);
      }
      
      // store wrapped component to script system
      scriptsys->AddToComponentMap(v->GetType(), eid, instance);
      return handle_scope.Close(instance);
   }
コード例 #26
0
ファイル: v8_wrapper.cpp プロジェクト: IlyaM/mongo
    Local<v8::Object> mongoToV8( const BSONObj& m , bool array, bool readOnly ){

        // handle DBRef. needs to come first. isn't it? (metagoto)
        static string ref = "$ref";
        if ( ref == m.firstElement().fieldName() ) {
            const BSONElement& id = m["$id"];
            if (!id.eoo()) { // there's no check on $id exitence in sm implementation. risky ?
                v8::Function* dbRef = getNamedCons( "DBRef" );
                v8::Handle<v8::Value> argv[2];
                argv[0] = mongoToV8Element(m.firstElement());
                argv[1] = mongoToV8Element(m["$id"]);
                return dbRef->NewInstance(2, argv);
            }
        }

        Local< v8::ObjectTemplate > readOnlyObjects;
        // Hoping template construction is fast...
        Local< v8::ObjectTemplate > internalFieldObjects = v8::ObjectTemplate::New();
        internalFieldObjects->SetInternalFieldCount( 1 );

        Local<v8::Object> o;
        if ( array ) {
            // NOTE Looks like it's impossible to add interceptors to non array objects in v8.
            o = v8::Array::New();
        } else if ( !readOnly ) {
            o = v8::Object::New();
        } else {
            // NOTE Our readOnly implemention relies on undocumented ObjectTemplate
            // functionality that may be fragile, but it still seems like the best option
            // for now -- fwiw, the v8 docs are pretty sparse.  I've determined experimentally
            // that when property handlers are set for an object template, they will attach
            // to objects previously created by that template.  To get this to work, though,
            // it is necessary to initialize the template's property handlers before
            // creating objects from the template (as I have in the following few lines
            // of code).
            // NOTE In my first attempt, I configured the permanent property handlers before
            // constructiong the object and replaced the Set() calls below with ForceSet().
            // However, it turns out that ForceSet() only bypasses handlers for named
            // properties and not for indexed properties.
            readOnlyObjects = v8::ObjectTemplate::New();
            // NOTE This internal field will store type info for special db types.  For
            // regular objects the field is unnecessary - for simplicity I'm creating just
            // one readOnlyObjects template for objects where the field is & isn't necessary,
            // assuming that the overhead of an internal field is slight.
            readOnlyObjects->SetInternalFieldCount( 1 );
            readOnlyObjects->SetNamedPropertyHandler( 0 );
            readOnlyObjects->SetIndexedPropertyHandler( 0 );
            o = readOnlyObjects->NewInstance();
        }
        
        mongo::BSONObj sub;

        for ( BSONObjIterator i(m); i.more(); ) {
            const BSONElement& f = i.next();
        
            Local<Value> v;
        
            switch ( f.type() ){

            case mongo::Code:
                o->Set( v8::String::New( f.fieldName() ), newFunction( f.valuestr() ) );
                break;

            case CodeWScope:
                if ( f.codeWScopeObject().isEmpty() )
                    log() << "warning: CodeWScope doesn't transfer to db.eval" << endl;
                o->Set( v8::String::New( f.fieldName() ), newFunction( f.codeWScopeCode() ) );
                break;
            
            case mongo::String: 
                o->Set( v8::String::New( f.fieldName() ) , v8::String::New( f.valuestr() ) );
                break;
            
            case mongo::jstOID: {
                v8::Function * idCons = getObjectIdCons();
                v8::Handle<v8::Value> argv[1];
                argv[0] = v8::String::New( f.__oid().str().c_str() );
                o->Set( v8::String::New( f.fieldName() ) , 
                            idCons->NewInstance( 1 , argv ) );
                break;
            }
            
            case mongo::NumberDouble:
            case mongo::NumberInt:
                o->Set( v8::String::New( f.fieldName() ) , v8::Number::New( f.number() ) );
                break;
            
            case mongo::Array:
            case mongo::Object:
                sub = f.embeddedObject();
                o->Set( v8::String::New( f.fieldName() ) , mongoToV8( sub , f.type() == mongo::Array, readOnly ) );
                break;
            
            case mongo::Date:
                o->Set( v8::String::New( f.fieldName() ) , v8::Date::New( f.date() ) );
                break;

            case mongo::Bool:
                o->Set( v8::String::New( f.fieldName() ) , v8::Boolean::New( f.boolean() ) );
                break;
            
            case mongo::jstNULL:
            case mongo::Undefined: // duplicate sm behavior
                o->Set( v8::String::New( f.fieldName() ) , v8::Null() );
                break;
            
            case mongo::RegEx: {
                v8::Function * regex = getNamedCons( "RegExp" );
            
                v8::Handle<v8::Value> argv[2];
                argv[0] = v8::String::New( f.regex() );
                argv[1] = v8::String::New( f.regexFlags() );
            
                o->Set( v8::String::New( f.fieldName() ) , regex->NewInstance( 2 , argv ) );
                break;
            }
            
            case mongo::BinData: {
                Local<v8::Object> b = readOnly ? readOnlyObjects->NewInstance() : internalFieldObjects->NewInstance();

                int len;
                const char *data = f.binData( len );
            
                v8::Function* binData = getNamedCons( "BinData" );
                v8::Handle<v8::Value> argv[3];
                argv[0] = v8::Number::New( len );
                argv[1] = v8::Number::New( f.binDataType() );
                argv[2] = v8::String::New( data, len );
                o->Set( v8::String::New( f.fieldName() ), binData->NewInstance(3, argv) );
                break;
            }
            
            case mongo::Timestamp: {
                Local<v8::Object> sub = readOnly ? readOnlyObjects->NewInstance() : internalFieldObjects->NewInstance();
                
                sub->Set( v8::String::New( "time" ) , v8::Date::New( f.timestampTime() ) );
                sub->Set( v8::String::New( "i" ) , v8::Number::New( f.timestampInc() ) );
                sub->SetInternalField( 0, v8::Uint32::New( f.type() ) );
                
                o->Set( v8::String::New( f.fieldName() ) , sub );
                break;
            }
            
            case mongo::NumberLong: {
                Local<v8::Object> sub = readOnly ? readOnlyObjects->NewInstance() : internalFieldObjects->NewInstance();
                unsigned long long val = f.numberLong();
                v8::Function* numberLong = getNamedCons( "NumberLong" );
                v8::Handle<v8::Value> argv[2];
                argv[0] = v8::Integer::New( val >> 32 );
                argv[1] = v8::Integer::New( (unsigned long)(val & 0x00000000ffffffff) );
                o->Set( v8::String::New( f.fieldName() ), numberLong->NewInstance(2, argv) );
                break;                
            }
                    
            case mongo::MinKey: {
                Local<v8::Object> sub = readOnly ? readOnlyObjects->NewInstance() : internalFieldObjects->NewInstance();
                sub->Set( v8::String::New( "$MinKey" ), v8::Boolean::New( true ) );
                sub->SetInternalField( 0, v8::Uint32::New( f.type() ) );
                o->Set( v8::String::New( f.fieldName() ) , sub );
                break;
            }
                    
            case mongo::MaxKey: {
                Local<v8::Object> sub = readOnly ? readOnlyObjects->NewInstance() : internalFieldObjects->NewInstance();
                sub->Set( v8::String::New( "$MaxKey" ), v8::Boolean::New( true ) );
                sub->SetInternalField( 0, v8::Uint32::New( f.type() ) );
                o->Set( v8::String::New( f.fieldName() ) , sub );
                break;
            }

            case mongo::DBRef: {
                v8::Function* dbPointer = getNamedCons( "DBPointer" );
                v8::Handle<v8::Value> argv[2];
                argv[0] = v8::String::New( f.dbrefNS() );
                argv[1] = newId( f.dbrefOID() );
                o->Set( v8::String::New( f.fieldName() ), dbPointer->NewInstance(2, argv) );
                break;
            }
                    
            default:
                cout << "can't handle type: ";
                cout  << f.type() << " ";
                cout  << f.toString();
                cout  << endl;
                break;
            }
        
        }

        if ( !array && readOnly ) {
            readOnlyObjects->SetNamedPropertyHandler( 0, NamedReadOnlySet, 0, NamedReadOnlyDelete );
            readOnlyObjects->SetIndexedPropertyHandler( 0, IndexedReadOnlySet, 0, IndexedReadOnlyDelete );            
        }
        
        return o;
    }
コード例 #27
0
ファイル: v8_wrapper.cpp プロジェクト: IlyaM/mongo
    Handle<v8::Value> mongoToV8Element( const BSONElement &f ) {
        Local< v8::ObjectTemplate > internalFieldObjects = v8::ObjectTemplate::New();
        internalFieldObjects->SetInternalFieldCount( 1 );

        switch ( f.type() ){

        case mongo::Code:
            return newFunction( f.valuestr() );
                
        case CodeWScope:
            if ( f.codeWScopeObject().isEmpty() )
                log() << "warning: CodeWScope doesn't transfer to db.eval" << endl;
            return newFunction( f.codeWScopeCode() );
                
        case mongo::String: 
            return v8::String::New( f.valuestr() );
            
        case mongo::jstOID:
            return newId( f.__oid() );
            
        case mongo::NumberDouble:
        case mongo::NumberInt:
            return v8::Number::New( f.number() );
            
        case mongo::Array:
        case mongo::Object:
            return mongoToV8( f.embeddedObject() , f.type() == mongo::Array );
            
        case mongo::Date:
            return v8::Date::New( f.date() );
            
        case mongo::Bool:
            return v8::Boolean::New( f.boolean() );

        case mongo::EOO:            
        case mongo::jstNULL:
        case mongo::Undefined: // duplicate sm behavior
            return v8::Null();
            
        case mongo::RegEx: {
            v8::Function * regex = getNamedCons( "RegExp" );
            
            v8::Handle<v8::Value> argv[2];
            argv[0] = v8::String::New( f.regex() );
            argv[1] = v8::String::New( f.regexFlags() );
            
            return regex->NewInstance( 2 , argv );
            break;
        }
            
        case mongo::BinData: {
            int len;
            const char *data = f.binData( len );
            
            v8::Function* binData = getNamedCons( "BinData" );
            v8::Handle<v8::Value> argv[3];
            argv[0] = v8::Number::New( len );
            argv[1] = v8::Number::New( f.binDataType() );
            argv[2] = v8::String::New( data, len );
            return binData->NewInstance( 3, argv );
        };
            
        case mongo::Timestamp: {
            Local<v8::Object> sub = internalFieldObjects->NewInstance();
            
            sub->Set( v8::String::New( "time" ) , v8::Date::New( f.timestampTime() ) );
            sub->Set( v8::String::New( "i" ) , v8::Number::New( f.timestampInc() ) );
            sub->SetInternalField( 0, v8::Uint32::New( f.type() ) );

            return sub;
        }
                
        case mongo::NumberLong: {
            Local<v8::Object> sub = internalFieldObjects->NewInstance();
            unsigned long long val = f.numberLong();
            v8::Function* numberLong = getNamedCons( "NumberLong" );
            v8::Handle<v8::Value> argv[2];
            argv[0] = v8::Integer::New( val >> 32 );
            argv[1] = v8::Integer::New( (unsigned long)(val & 0x00000000ffffffff) );
            return numberLong->NewInstance( 2, argv );
        }
            
        case mongo::MinKey: {
            Local<v8::Object> sub = internalFieldObjects->NewInstance();
            sub->Set( v8::String::New( "$MinKey" ), v8::Boolean::New( true ) );
            sub->SetInternalField( 0, v8::Uint32::New( f.type() ) );
            return sub;
        }
            
        case mongo::MaxKey: {
            Local<v8::Object> sub = internalFieldObjects->NewInstance();
            sub->Set( v8::String::New( "$MaxKey" ), v8::Boolean::New( true ) );
            sub->SetInternalField( 0, v8::Uint32::New( f.type() ) );
            return sub;
        }
                
        case mongo::DBRef: {
            v8::Function* dbPointer = getNamedCons( "DBPointer" );
            v8::Handle<v8::Value> argv[2];
            argv[0] = v8::String::New( f.dbrefNS() );
            argv[1] = newId( f.dbrefOID() );
            return dbPointer->NewInstance(2, argv);
        }
                       
        default:
            cout << "can't handle type: ";
			cout  << f.type() << " ";
			cout  << f.toString();
			cout  << endl;
            break;
        }    
        
        return v8::Undefined();
    }