Esempio n. 1
2
void CRF::New(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
    
    if (args.IsConstructCall()) {
        // Invoked as constructor: `new CRF(...)`
        
        CRF* obj = new CRF();
        
        CRFPP::Tagger* tag = CRFPP::createTagger(get(args[0]));
        if(!tag){
            
            isolate->ThrowException(Exception::TypeError(
                                                       String::NewFromUtf8(isolate, (const char *) CRFPP::getTaggerError())));
            return;
            
        }
        
        v8::Local<v8::External> handle = v8::External::New(isolate, tag);
        v8::Persistent<v8::External, v8::CopyablePersistentTraits<v8::External> > tagger(isolate, handle);
        
        obj -> tagger = tagger;
        
        obj->Wrap(args.This());
        args.GetReturnValue().Set(args.This());
    } else {
        const int argc = 1;
        Local<Value> argv[argc] = { args[0] };
        Local<Function> cons = Local<Function>::New(isolate, constructor);
        args.GetReturnValue().Set(cons->NewInstance(argc, argv));
    }
}
Esempio n. 2
1
void jsCreateMyClass(const FunctionCallbackInfo<Value>& args)
{
	if (args.Length() != 1)
	{
		args.GetIsolate()->ThrowException(
			String::NewFromUtf8(args.GetIsolate(), "Bad parameters",
			NewStringType::kNormal).ToLocalChecked());
		return;
	}

	Isolate* isolate = args.GetIsolate();

	Local<ObjectTemplate> myClassTemplate =
		Local<ObjectTemplate>::New(isolate, gMyClassTemplate);

	Local<Object> myClassObj = myClassTemplate->NewInstance(
		isolate->GetCurrentContext()).ToLocalChecked();

	int numValue =
		args[0]->Int32Value(isolate->GetCurrentContext()).FromMaybe(0);

	gMyClass = new ObjectWrap(numValue);
	gMyClass->Wrap(myClassObj);

	args.GetReturnValue().Set(myClassObj);
}
Esempio n. 3
0
	static
	NAN_METHOD(New) {
		SHA3Hash *obj;
		int32_t hashlen;

		hashlen = info[0]->IsUndefined() ? 512 : info[0]->Int32Value();
		switch (hashlen) {
			case 224:
			case 256:
			case 384:
			case 512:
				break;
			default:
				return Nan::ThrowTypeError("Unsupported hash length");
		}

		if (info.IsConstructCall()) {
			// Invoked as constructor.
			obj = new SHA3Hash();
			obj->Wrap(info.This());
			obj->bitlen = hashlen;
			::FIPS202_SHA3_Init(&obj->state, hashlen);
			info.GetReturnValue().Set(info.This());
		} else {
			// Invoked as a plain function.
			const int argc = 1;
			Local<Value> argv[argc] = { Nan::New<Number>(hashlen) };
			Local<Function> cons = Nan::New<Function>(constructor);
			info.GetReturnValue().Set(cons->NewInstance(argc, argv));
		}
	}
Esempio n. 4
0
/**
 * 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);
}
// Used by LSHandle to create a "Message" object that wraps a particular
// LSMessage structure.
Local<Value> LS2Message::NewFromMessage(LSMessage* message)
{
    TryCatch try_catch;

    Local<Function> function = gMessageTemplate->GetFunction();
    Local<Object> messageObject = function->NewInstance();

    // If we get an exception in LS2Message::New, then it will return
    // v8::ThrowException which adds a pending exception.
    // Function::NewInstance checks to see if the callee set an exception.
    // If it did, it returns an empty handle 
    if (!messageObject.IsEmpty()) {
        LS2Message *m = node::ObjectWrap::Unwrap<LS2Message>(messageObject);
        if (!m) {
            return Local<Value>::New(v8::ThrowException(v8::String::New("Unable to unwrap native object.")));
        }
        m->SetMessage(message);
    } else {
        // We got an exception; If we try to continue we're going to lose
        // a message, so just crash
        v8::String::Utf8Value exception(try_catch.Exception());
        syslog(LOG_USER | LOG_CRIT, "%s: exception: %s; aborting", __PRETTY_FUNCTION__, 
                                    *exception ? *exception : "no exception string");
        abort();
    }
    return messageObject;
}
Esempio n. 6
0
void ETW::New(const FunctionCallbackInfo<Value>& args)
{
    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);

    if (args.IsConstructCall()) 
    {
        if (args[0]->IsUndefined())
        {
            Nan::ThrowTypeError("Session name is required.");
            return;
        }

        int wchars_num =  MultiByteToWideChar(CP_UTF8 , 0 , *String::Utf8Value(args[0]), -1, NULL , 0 );
        wchar_t* szSessionName = new wchar_t[wchars_num];
        MultiByteToWideChar(CP_UTF8, 0, *String::Utf8Value(args[0]), -1, szSessionName, wchars_num);

        // Invoked as constructor: `new ETW(...)`
        ETW* obj = new ETW(szSessionName);
        obj->Wrap(args.This());
        args.GetReturnValue().Set(args.This());
    } 
    else 
    {
        // Invoked as plain function `ETW(...)`, turn into construct call.
        const int argc = 1;
        Local<Value> argv[argc] = { args[0] };
        Local<Function> cons = Local<Function>::New(isolate, constructor);
        args.GetReturnValue().Set(cons->NewInstance(argc, argv));
    }
}
Esempio n. 7
0
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);
}
Esempio n. 8
0
Handle<Value> node_packet_client_encode(const Arguments& args)
{
    V8_CHECK_ARGUMENT_COUNT(2)
    V8_CHECK_ARGUMENT(0, Object)
    V8_CHECK_ARGUMENT(1, Number)

    Local<Object> buffer = args[0]->ToObject();
    int32_t serial = args[1]->Int32Value();
    unsigned char* buffer_ptr = (unsigned char*) node::Buffer::Data(buffer);
    int length = (int) node::Buffer::Length(buffer);

    packet pkt = packet_encode_client(buffer_ptr, serial);
    if (pkt.empty())
    {
        return scope.Close(Null());
    }

    int s = (int) pkt.size();
    Local<Object> globalObj = Context::GetCurrent()->Global();
    Local<Function> bufferConstructor = Local<Function>::Cast(globalObj->Get(String::New("Buffer")));
    Handle<Value> constructorArgs[1] = { v8::Integer::New(s)};
    Local<Object> actualBuffer = bufferConstructor->NewInstance(1, constructorArgs);
    memcpy(Buffer::Data(actualBuffer), pkt.data(), s);
    return scope.Close(actualBuffer);
}
Esempio n. 9
0
    void IdPool::New(const FunctionCallbackInfo<Value>& args)
    {
        Isolate* isolate = args.GetIsolate();

        if (args.IsConstructCall()) {
            // Invoked as constructor: `new IdPool(...)`
            double value = args[0]->IsUndefined() || !args[0]->IsNumber()?
                0 : args[0]->NumberValue() / 8;

            if (value > DEFAULT_CTOR_MAX_POSSIBLE_SIZE) {
                JS_THROW(isolate, "Size too large");
                return;
            }

            // ceil
            size_t poolSize = value + (size_t)((size_t)value != value);

            try {
                IdPool* obj = new IdPool(poolSize);
                obj->Wrap(args.This());
                args.GetReturnValue().Set(args.This());
            }
            catch (std::Exception e) {
                JS_THROW(isolate, e.what());
                return;
            }
        } else {
            // Invoked as plain function `IdPool(...)`, turn into construct call.
            const int argc = 1;
            Local<Value> argv[argc] = { args[0] };
            Local<Function> cons = Local<Function>::New(isolate, constructor);
            args.GetReturnValue().Set(cons->NewInstance(argc, argv));
        }
    }
Esempio n. 10
0
Local<Object> wrap_master_player(Isolate* isolate, Master_Player *player) {
	EscapableHandleScope handle_scope(isolate);

	Local<ObjectTemplate> localTemplate = ObjectTemplate::New(isolate);
	localTemplate->SetInternalFieldCount(1);
	Local<External> player_ptr = External::New(isolate, player);
	//将指针存在V8对象内部
	Local<Object> player_obj = localTemplate->NewInstance(isolate->GetCurrentContext()).ToLocalChecked();
	player_obj->SetInternalField(0, player_ptr);

	// 为当前对象设置其对外函数接口
	player_obj->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "get_save_data_buffer", NewStringType::kNormal).ToLocalChecked(),
		                    FunctionTemplate::New(isolate, get_master_player_save_data_buffer)->GetFunction()) ;

	player_obj->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "respond_success_result", NewStringType::kNormal).ToLocalChecked(),
	                    FunctionTemplate::New(isolate, master_player_respond_success_result)->GetFunction()) ;

	player_obj->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "respond_error_result", NewStringType::kNormal).ToLocalChecked(),
	                    FunctionTemplate::New(isolate, master_player_respond_error_result)->GetFunction()) ;

	player_obj->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "sync_data_to_game", NewStringType::kNormal).ToLocalChecked(),
			                    FunctionTemplate::New(isolate, sync_data_to_game)->GetFunction()) ;

	return handle_scope.Escape(player_obj);
}
Esempio n. 11
0
// コンストラクタ呼び出し共通処理
tjs_error
TJSInstance::createMethod(Isolate *isolate, Local<Object> &obj, const tjs_char *membername, iTJSDispatch2 **result, tjs_int numparams, tTJSVariant **param)
{
	if (membername) {
		return TJS_E_MEMBERNOTFOUND;
	}

	HandleScope handle_scope(isolate);
	Context::Scope context_scope(getContext());
	TryCatch try_catch;

	if (!obj->IsFunction()) {
		return TJS_E_NOTIMPL;
	}
	
	// 関数抽出
	Local<Function> func = Local<Function>::Cast(obj->ToObject());
	// 引数
	Handle<Value> *argv = new Handle<Value>[numparams];
	for (int i=0;i<numparams;i++) {
		argv[i] = toJSValue(isolate, *param[i]);
	}
	Local<Object> ret = func->NewInstance(numparams, argv);
	delete argv;
	
	if (ret.IsEmpty()) {
		JSEXCEPTION(isolate, &try_catch);
	} else {
		if (result) {
			*result = toVariant(isolate, ret);
		}
	}
	return TJS_S_OK;
}
Esempio n. 12
0
v8::Local<v8::Object> Msg_Struct::build_msg_object(Isolate* isolate, int cid, int player_cid, int msg_id, int status, Block_Buffer &buffer) {
    EscapableHandleScope handle_scope(isolate);

    Local<ObjectTemplate> localTemplate = ObjectTemplate::New(isolate);
    Local<Object> buf_obj = localTemplate->NewInstance(isolate->GetCurrentContext()).ToLocalChecked();
    buf_obj->Set(isolate->GetCurrentContext(),
                 String::NewFromUtf8(isolate, "cid", NewStringType::kNormal).ToLocalChecked(),
                 Int32::New(isolate, cid)).FromJust();
    buf_obj->Set(isolate->GetCurrentContext(),
                 String::NewFromUtf8(isolate, "player_cid", NewStringType::kNormal).ToLocalChecked(),
                 Int32::New(isolate, player_cid)).FromJust();
    buf_obj->Set(isolate->GetCurrentContext(),
                 String::NewFromUtf8(isolate, "msg_id", NewStringType::kNormal).ToLocalChecked(),
                 Int32::New(isolate, msg_id)).FromJust();
    buf_obj->Set(isolate->GetCurrentContext(),
                 String::NewFromUtf8(isolate, "status", NewStringType::kNormal).ToLocalChecked(),
                 Int32::New(isolate, status)).FromJust();
    if (msg_id == SYNC_DB_GAME_LOAD_PLAYER || msg_id == SYNC_DB_GAME_CREATE_PLAYER) {
        std::string account = "";
        buffer.read_string(account);
        buf_obj->Set(isolate->GetCurrentContext(),
                     String::NewFromUtf8(isolate, "account", NewStringType::kNormal).ToLocalChecked(),
                     String::NewFromUtf8(isolate, account.c_str(), NewStringType::kNormal).ToLocalChecked()).FromJust();
    }

    //消息返回成功加载数据
    if (status == 0) {
        for(std::vector<Field_Info>::const_iterator iter = field_vec().begin();
                iter != field_vec().end(); iter++) {
            if(iter->field_label == "arg") {
                Local<Value> value = build_object_arg(*iter, buffer, isolate);
                buf_obj->Set(isolate->GetCurrentContext(),
                             String::NewFromUtf8(isolate, iter->field_name.c_str(), NewStringType::kNormal).ToLocalChecked(),
                             value).FromJust();
            }
            else if(iter->field_label == "vector") {
                Local<Array> array = build_object_vector(*iter, buffer, isolate);
                buf_obj->Set(isolate->GetCurrentContext(),
                             String::NewFromUtf8(isolate, iter->field_name.c_str(), NewStringType::kNormal).ToLocalChecked(),
                             array).FromJust();
            }
            else if(iter->field_label == "map") {
                Local<Map> map = build_object_map(*iter, buffer, isolate);
                buf_obj->Set(isolate->GetCurrentContext(),
                             String::NewFromUtf8(isolate, iter->field_name.c_str(), NewStringType::kNormal).ToLocalChecked(),
                             map).FromJust();
            }
            else if(iter->field_label == "struct") {
                Local<Object> object = build_object_struct(*iter, buffer, isolate);
                buf_obj->Set(isolate->GetCurrentContext(),
                             String::NewFromUtf8(isolate, iter->field_name.c_str(), NewStringType::kNormal).ToLocalChecked(),
                             object).FromJust();
            }
        }
    }
    return handle_scope.Escape(buf_obj);
}
Esempio n. 13
0
// tTJSVariant をオブジェクト化
Local<Object>
TJSObject::toJSObject(Isolate *isolate, const tTJSVariant &variant)
{
	EscapableHandleScope handle_scope(isolate);
	Local<ObjectTemplate> templ = Local<ObjectTemplate>::New(isolate, objectTemplate);
	Local<Object> obj = templ->NewInstance();
	new TJSObject(isolate, obj, variant);
	return handle_scope.Escape(obj);
}
Esempio n. 14
0
	void Buffer::NewInstance(const FunctionCallbackInfo<Value>& args) {
		Isolate* isolate = args.GetIsolate();
		HandleScope handle_scope(isolate);

		std::array<Local<Value>, 1> argv{ args[0] };
		Local<Function> cons = Local<Function>::New(isolate, constructor.Get(isolate));
		Local<Object> instance = cons->NewInstance(SafeInt<int>(argv.size()), argv.data());

		args.GetReturnValue().Set(instance);
	}
Esempio n. 15
0
Handle<Value> PrecisionModel::New(const geos::geom::PrecisionModel *m) {
    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);

    PrecisionModel *model = new PrecisionModel(m);
    Handle<Value> ext = External::New(isolate, model);
    Local<Function> cons = Local<Function>::New(isolate, constructor);
    Handle<Object> obj = cons->NewInstance(1, &ext);
    model->Wrap(obj);
    return obj;
}
Esempio n. 16
0
void DeviceNode::NewInstance(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  const unsigned argc = 1;
  Handle<Value> argv[argc] = { args[0] };
  Local<Function> cons = Local<Function>::New(isolate, constructor);
  Local<Object> instance = cons->NewInstance(argc, argv);

  args.GetReturnValue().Set(instance);
}
Esempio n. 17
0
    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;
    }
Esempio n. 18
0
 //! New JS::Quaternion from Ogre::Quaternion
 Local<v8::Object> Quaternion::newFrom( const Ogre::Quaternion& qtn )
 {
   Local<v8::Function> constFunc = constructor.Get(
     Isolate::GetCurrent() )->GetFunction();
   Local<v8::Object> object = constFunc->NewInstance();
   Quaternion* ret = unwrap( object );
   // Ugly this way, but the Ogre::Quaternion assignment operator silently fails.
   ret->w = qtn.w;
   ret->x = qtn.x;
   ret->y = qtn.y;
   ret->z = qtn.z;
   return object;
 }
void PushbotsModule::bindProxy(Handle<Object> exports)
{
	if (proxyTemplate.IsEmpty()) {
		getProxyTemplate();
	}

	// use symbol over string for efficiency
	Handle<String> nameSymbol = String::NewSymbol("Pushbots");

	Local<Function> proxyConstructor = proxyTemplate->GetFunction();
	Local<Object> moduleInstance = proxyConstructor->NewInstance();
	exports->Set(nameSymbol, moduleInstance);
}
Esempio n. 20
0
	void Buffer::New(const FunctionCallbackInfo<Value>& args) {
		Isolate* isolate = args.GetIsolate();
		HandleScope handle_scope(isolate);

		if (args.IsConstructCall()) {
			Buffer* obj = new Buffer(args);
			args.GetReturnValue().Set(args.This());
		}
		else {
			std::array<Local<Value>, 1> argv{ args[0] };
			Local<Function> cons = Local<Function>::New(isolate, constructor.Get(isolate));
			args.GetReturnValue().Set(cons->NewInstance(SafeInt<int>(argv.size()), argv.data()));
		}
	}
Esempio n. 21
0
v8::UniquePersistent<v8::Object> JsVlcVideo::create( JsVlcPlayer& player )
{
    using namespace v8;

    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope( isolate );

    Local<Function> constructor =
        Local<Function>::New( isolate, _jsConstructor );

    Local<Value> argv[] = { player.handle() };

    return { isolate, constructor->NewInstance( sizeof( argv ) / sizeof( argv[0] ), argv ) };
}
Esempio n. 22
0
Handle<Value> createJsBuffer(node::Buffer *b, int len) {
  HandleScope scope;
  Local<Object> global = v8::Context::GetCurrent()->Global();
  Local<Function> bufferConstructor = 
    Local<Function>::Cast(global->Get(String::New("Buffer")));
  Handle<Value> args[3];
  args[0] = b->handle_;
  args[1] = Integer::New(len);
  args[2] = Integer::New(0);
  
  Local<Object> jsBuffer = bufferConstructor->NewInstance(3, args);

  return scope.Close(jsBuffer);
}
Esempio n. 23
0
void DeviceNode::New(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new DeviceNode()`
    DeviceNode* obj = new DeviceNode();
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `DeviceNode(...)`, turn into construct call.
    Local<Function> cons = Local<Function>::New(isolate, constructor);
    args.GetReturnValue().Set(cons->NewInstance());
  }
}
Esempio n. 24
0
Local<Object> ModuleByteArray::wrapByteArray(Isolate* isolate, const QByteArray& data)
{
	EscapableHandleScope handle_scope(isolate);

	// Fetch the template for creating ByteArray wrappers.
	Local<ObjectTemplate> localTemplate = Local<ObjectTemplate>::New(isolate, ByteArrayTemplate);

	// Create an empty ByteArray wrapper.
	Local<Object> wrapper = localTemplate->NewInstance(isolate->GetCurrentContext()).ToLocalChecked();

	// Store data in ArrayBuffer
	wrapper->Set(String::NewFromUtf8(isolate, "buffer"), Utility::toV8ArrayBuffer(isolate, data));

	return handle_scope.Escape(wrapper);
}
Esempio n. 25
0
Local<Value> FastBuffer::New(unsigned char *data, int length) 
{
	Nan::EscapableHandleScope scope;

	Local<Object> slowBuffer = Nan::NewBuffer(length).ToLocalChecked();

	memcpy(node::Buffer::Data(slowBuffer), data, length);

	Local<Object> globalObj = Nan::GetCurrentContext()->Global();
	Local<Function> bufferConstructor = globalObj->Get(Nan::New("Buffer").ToLocalChecked()).As<Function>();
	Local<Value> constructorArgs[3] = { slowBuffer, Nan::New<Integer>(length), Nan::New<Integer>(0) };
	
	Local<Object> actualBuffer = bufferConstructor->NewInstance(3, constructorArgs);

	return scope.Escape(actualBuffer);
}
void ABPFilterParserWrap::New(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new ABPFilterParser(...)`
    ABPFilterParserWrap* obj = new ABPFilterParserWrap();
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `ABPFilterParser(...)`,
    // turn into construct call.
    const int argc = 1;
    Local<Value> argv[argc] = { args[0] };
    Local<Function> cons = Local<Function>::New(isolate, constructor);
    args.GetReturnValue().Set(cons->NewInstance(argc, argv));
  }
}
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);
}
Esempio n. 28
0
    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;
    }
Esempio n. 29
0
    Local <Object> Data::NewInstance(OBGenericData *data) {
        NanEscapableScope();
        for(unsigned int i = 0; i < container.size(); i++) {
            Local<Object> ins = Local<Object>::New(container.at(i));
            if(Unwrap(ins)->ob == data) {
                return NanEscapeScope(ins);
            }
        }
        const unsigned argc = 0;
        Local <Value> argv[argc] = {};
        Local <Function> cons = NanNew<Function>(constructor);
        Local <Object> instance = cons->NewInstance(argc, argv);

        Data *obj = Unwrap(instance);
        obj->ob = data;

        return NanEscapeScope(instance);
    }
Esempio n. 30
0
void Main(Local<Object> exports)
{
    Isolate *isolate = exports->GetIsolate();
    Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, constructor);
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(tpl, "on", on);
    NODE_SET_PROTOTYPE_METHOD(tpl, "send", send);
    NODE_SET_PROTOTYPE_METHOD(tpl, "setUserData", setUserData);
    NODE_SET_PROTOTYPE_METHOD(tpl, "getUserData", getUserData);
    NODE_SET_PROTOTYPE_METHOD(tpl, "getFd", getFd);

    exports->Set(String::NewFromUtf8(isolate, "Server"), tpl->GetFunction());

    Local<ObjectTemplate> socketTemplate = ObjectTemplate::New(isolate);
    socketTemplate->SetInternalFieldCount(2);
    persistentSocket.Reset(isolate, socketTemplate->NewInstance());
}