long NativeWindow::JSResult(){ Local<Value> result = v8handle_->Get(String::NewSymbol("result")); if (result->IsUndefined() || result->IsNull()) { return 0; } else { v8handle_->Set(String::NewSymbol("result"), Undefined()); return result->Int32Value(); } }
//*,{ // "type":"class", // "name":"Point", // "text":"Point 对象是一个纯 Javascript 对象,包含两个数字属性。Size 和 Point 是同一个对象的两个名称。", // "member":[ // { // "type":"property", // "name":"x", // "objtype":"integer", // "text":"x 属性,一般表示横坐标位置或宽度。" // }, // { // "type":"property", // "name":"y", // "objtype":"integer", // "text":"y 属性,一般表示纵坐标位置或高度。" // }, // { // "type":"function", // "name":"move(dx,dy)", // "text":"调整 x 和 y 属性的值。", // "param":[ // { // "type":"integer", // "name":"dx", // "text":"x 将会加上这个值。" // }, // { // "type":"integer", // "name":"dy", // "text":"y 将会加上这个值。" // } // ], // "return":{ // "type":"void", // "text":"函数没有返回值。" // } // } // ] //} //,{ // "type":"class", // "name":"Rect", // "text":"Rect 对象是一个纯 Javascript 对象,包含四个数字属性。", // "member":[ // { // "type":"property", // "name":"left", // "objtype":"integer", // "text":"左边界。" // }, // { // "type":"property", // "name":"top", // "objtype":"integer", // "text":"上边界。" // }, // { // "type":"property", // "name":"right", // "objtype":"integer", // "text":"右边界。" // }, // { // "type":"property", // "name":"bottom", // "objtype":"integer", // "text":"下边界。" // }, // { // "type":"function", // "name":"ptInRect(x,[y])", // "text":"(x,y)所代表的点是否在这个矩形内,如果不传 y 参数,表示不考虑 y,只考虑 x。", // "param":[ // { // "type":"integer", // "name":"x", // "text":"点的 x 坐标。" // }, // { // "type":"integer", // "name":"[y]", // "text":"点的 y 坐标。" // } // ], // "return":{ // "type":"boolean", // "text":"如果点在矩形内返回 true,否则返回 false。" // }, // "remark":[ // "矩形的左边界和上边界上的点算矩形内部,但是右边界和下边界不算矩形内部。" // ] // }, // { // "type":"function", // "name":"getLocation()", // "text":"获取矩形的位置,也就是左上角的坐标。", // "param":[ // ], // "return":{ // "type":"Point", // "text":"返回一个 Point 对象。" // } // }, // { // "type":"function", // "name":"setLocation([x],[y])", // "text":"设置矩形的位置,这个函数会改变矩形 4 个属性的值,但是保持大小不变。", // "param":[ // { // "type":"integer", // "name":"[x]", // "text":"新位置的 x 坐标,如果此值为 undefined,矩形的 left 和 right 不变。" // }, // { // "type":"integer", // "name":"[y]", // "text":"新位置的 y 坐标,如果此值为 undefined,矩形的 top 和 bottom 不变。" // } // ], // "return":{ // "type":"void", // "text":"函数没有返回值。" // } // }, // { // "type":"function", // "name":"setSize", // "text":"设置矩形的大小,这个函数通过调整 right 和 bottom 来调整矩形的大小。", // "param":[ // { // "type":"integer", // "name":"[width]", // "text":"矩形新的宽度,如果此值为 undefined,矩形的宽度不变。" // }, // { // "type":"integer", // "name":"[height]", // "text":"矩形新的高度,如果此值为 undefined,矩形的高度不变。" // } // ], // "return":{ // "type":"void", // "text":"这个函数没有返回值。" // } // }, // { // "type":"function", // "name":"getSize", // "text":"获取矩形的大小。", // "param":[ // ], // "return":{ // "type":"Size", // "text":"返回一个 Size 对象。" // } // }, // { // "type":"function", // "name":"positive", // "text":"通过交换 left 和 right 或者 top 和 bottom 的值来保证,left 总是小于等于 right,top 总是小于等于 bottom。", // "param":[ // ], // "return":{ // "type":"void", // "text":"这个函数没有返回值。" // } // }, // { // "type":"function", // "name":"setValue(left,top,right,bottom)", // "text":"设置矩形的 4 个属性,这个函数直接设置,不做任何检测。", // "param":[ // { // "type":"integer", // "name":"left", // "text":"要设置的 left 属性值。" // }, // { // "type":"integer", // "name":"top", // "text":"要设置的 top 属性值。" // }, // { // "type":"integer", // "name":"right", // "text":"要设置的 right 属性值。" // }, // { // "type":"integer", // "name":"bottom", // "text":"要设置的 bottom 属性值。" // } // ], // "return":{ // "type":"void", // "text":"这个函数没有返回值。" // } // } // ] //}//* bool RectJsToC(v8::Handle<Value> value,cs::Rect* r){ HandleScope store; if(!value->IsObject()) return false; Local<Object> vObj = value->ToObject(); Local<Value> vl = vObj->Get(String::New("left")); if(vl->IsUndefined()) return false; Local<Value> vt = vObj->Get(String::New("top")); if(vt->IsUndefined()) return false; Local<Value> vr = vObj->Get(String::New("right")); if(vr->IsUndefined()) return false; Local<Value> vb = vObj->Get(String::New("bottom")); if(vb->IsUndefined()) return false; r->left = vl->Int32Value(); r->top = vt->Int32Value(); r->right = vr->Int32Value(); r->bottom = vb->Int32Value(); return true; }
Handle<Value> nj::ScriptEncapsulated::NewInstance(const Arguments& args) { HandleScope scope; const unsigned argc = 1; Handle<v8::Value> argv[argc] = { args[0] }; Local<Object> instance = constructor->NewInstance(argc,argv); if(instance.IsEmpty() || instance->IsUndefined()) return scope.Close(Undefined()); return scope.Close(instance); }
bool V8Value::hasProperty(std::string propertyName) { HandleScope handleScope; Local<Object> obj = value->ToObject(); Local<Value> val = obj->Get(String::New(propertyName.c_str())); return !(val->IsNull() || val->IsUndefined()); // These are not 'true' values, that we can return in e.g. getPropertyString // (we can't return 'Null' there - so this is for both undefined and null) }
Handle<Value> Feature::addAttributes(const Arguments& args) { HandleScope scope; Feature* fp = ObjectWrap::Unwrap<Feature>(args.This()); if (args.Length() > 0 ) { Local<Value> value = args[0]; if (value->IsNull() || value->IsUndefined()) { return ThrowException(Exception::TypeError(String::New("object expected"))); } else { Local<Object> attr = value->ToObject(); try { Local<Array> names = attr->GetPropertyNames(); uint32_t i = 0; uint32_t a_length = names->Length(); boost::scoped_ptr<mapnik::transcoder> tr(new mapnik::transcoder("utf8")); while (i < a_length) { Local<Value> name = names->Get(i)->ToString(); Local<Value> value = attr->Get(name); if (value->IsString()) { UnicodeString ustr = tr->transcode(TOSTR(value)); boost::put(*fp->get(),TOSTR(name),ustr); } else if (value->IsNumber()) { double num = value->NumberValue(); // todo - round if (num == value->IntegerValue()) { int integer = value->IntegerValue(); boost::put(*fp->get(),TOSTR(name),integer); } else { double dub_val = value->NumberValue(); boost::put(*fp->get(),TOSTR(name),dub_val); } } else { std::clog << "unhandled type for property: " << TOSTR(name) << "\n"; } i++; } } catch (const std::exception & ex ) { return ThrowException(Exception::Error( String::New(ex.what()))); } catch (...) { return ThrowException(Exception::Error( String::New("Unknown exception happended - please report bug"))); } } } return Undefined(); }
Handle<Value> TiRootObject::_require(void* userContext, TiObject* caller, const Arguments& args) { HandleScope scope; Local<Object> globalObject = TitaniumRuntime::getContenxt()->Global(); Handle<Value> nativeModule = TiModuleRegistry::GetModule(QString(*String::Utf8Value(args[0]->ToString()))); if(!nativeModule->IsUndefined()) { return scope.Close(nativeModule); } QString fileName = Ti::TiHelper::QStringFromValue(args[0]).append(".js"); QString filePath = Ti::TiHelper::getAssetPath(fileName).prepend("app/native/"); Local<Value> existingModule = globalObject->GetHiddenValue(Ti::TiHelper::ValueFromQString(fileName)->ToString()); if(!existingModule.IsEmpty() && !existingModule->IsUndefined()) { return scope.Close(existingModule); } QString js = readJsFile(filePath); if(js.isEmpty()) { ThrowException(String::New( QString("Module not found ").append(fileName).toLocal8Bit().constData() )); return scope.Close(Undefined()); } js.prepend("(function(){" "var __vars = {};" "__vars.exports = {};" "__vars.module = {exports:__vars.exports};" "var module = __vars.module;" "var exports = __vars.exports;"); js.append("\nreturn __vars.module.exports;" "})();"); Handle<Script> script = Script::Compile(Ti::TiHelper::ValueFromQString(js)->ToString() , Ti::TiHelper::ValueFromQString(fileName)); TryCatch tryCatch; if (script.IsEmpty()) { Ti::TiErrorScreen::ShowWithTryCatch(tryCatch); return scope.Close(Undefined()); } Persistent<Value> result = Persistent<Value>::New(script->Run()); result.MarkIndependent(); if (result.IsEmpty()) { Ti::TiErrorScreen::ShowWithTryCatch(tryCatch); return scope.Close(Undefined()); } globalObject->SetHiddenValue(Ti::TiHelper::ValueFromQString(fileName)->ToString(), result); return scope.Close(result); }
Handle<Value> MSRect::Project(const Arguments &args) { MSRect *rect = ObjectWrap::Unwrap<MSRect>(args.This()); Local<Object> obj; MSProjection *projIn; MSProjection *projOut; if (args.Length() != 2) { THROW_ERROR(Error, "projecting a point requires two projection arguments"); } if (!args[0]->IsObject()) { THROW_ERROR(TypeError, "first argument to project must be Projection object"); } obj = args[0]->ToObject(); if (obj->IsNull() || obj->IsUndefined() || !MSProjection::constructor->HasInstance(obj)) { THROW_ERROR(TypeError, "first argument to project must be Projection object"); } projIn = ObjectWrap::Unwrap<MSProjection>(obj); if (!args[1]->IsObject()) { THROW_ERROR(TypeError, "second argument to project must be Projection object"); } obj = args[1]->ToObject(); if (obj->IsNull() || obj->IsUndefined() || !MSProjection::constructor->HasInstance(obj)) { THROW_ERROR(TypeError, "first argument to project must be Projection object"); } projOut = ObjectWrap::Unwrap<MSProjection>(obj); msProjectRect(projIn->this_, projOut->this_, rect->this_); return Undefined(); }
/*----------------------------------------------------------------------------- * Get the current logger instance (will be created if it doesn't exist) * * var logger = tervela.getLogger({loggerOptions}); * * loggerOptions = { * filename : [log file name], (string, optional) * tagname : [tag for log messages in file], (string, optional (default: "TVA"[pid])) * }; */ Handle<Value> GetLogger(const Arguments& args) { HandleScope scope; static Local<Value> _logger; static bool _isCreated = false; if (!_isCreated) { // Ready arguments char* filename = NULL; char* tagname = NULL; if (args.Length() >= 1) { PARAM_REQ_OBJECT(0, args); // options Local<Object> options = Local<Object>::Cast(args[0]); std::vector<std::string> optionNames = cvv8::CastFromJS<std::vector<std::string> >(options->GetPropertyNames()); for (size_t i = 0; i < optionNames.size(); i++) { char* optionName = (char*)(optionNames[i].c_str()); Local<Value> optionValue = options->Get(String::NewSymbol(optionName)); if (optionValue->IsUndefined()) { continue; } if (tva_str_casecmp(optionName, "filename") == 0) { String::AsciiValue val(optionValue->ToString()); filename = strdup(*val); } else if (tva_str_casecmp(optionName, "tagname") == 0) { String::AsciiValue val(optionValue->ToString()); tagname = strdup(*val); } } } _logger = Local<Value>::New(Logger::NewInstance(filename, tagname)); _isCreated = true; if (filename) free(filename); if (tagname) free(tagname); } return scope.Close(_logger); }
void Geometry::srsSetter(Local<String> property, Local<Value> value, const AccessorInfo &info) { HandleScope scope; Geometry *geom = ObjectWrap::Unwrap<Geometry>(info.This()); OGRSpatialReference *srs = NULL; if (SpatialReference::constructor->HasInstance(value)) { SpatialReference *srs_obj = ObjectWrap::Unwrap<SpatialReference>(value->ToObject()); srs = srs_obj->get(); } else if (!value->IsNull() && !value->IsUndefined()) { NODE_THROW("srs must be SpatialReference object"); return; } geom->this_->assignSpatialReference(srs); }
Handle<Value> Image::setGrayScaleToAlpha(const Arguments& args) { HandleScope scope; Image* im = ObjectWrap::Unwrap<Image>(args.This()); if (args.Length() == 0) { im->this_->set_grayscale_to_alpha(); } else { if (!args[0]->IsObject()) return ThrowException(Exception::TypeError( String::New("optional second arg must be a mapnik.Color"))); Local<Object> obj = args[0]->ToObject(); if (obj->IsNull() || obj->IsUndefined() || !Color::constructor->HasInstance(obj)) return ThrowException(Exception::TypeError(String::New("mapnik.Color expected as second arg"))); Color * color = ObjectWrap::Unwrap<Color>(obj); mapnik::image_data_32 & data = im->this_->data(); for (unsigned int y = 0; y < data.height(); ++y) { unsigned int* row_from = data.getRow(y); for (unsigned int x = 0; x < data.width(); ++x) { unsigned rgba = row_from[x]; // TODO - big endian support unsigned r = rgba & 0xff; unsigned g = (rgba >> 8 ) & 0xff; unsigned b = (rgba >> 16) & 0xff; // magic numbers for grayscale unsigned a = (int)((r * .3) + (g * .59) + (b * .11)); row_from[x] = (a << 24) | (color->get()->blue() << 16) | (color->get()->green() << 8) | (color->get()->red()) ; } } } return Undefined(); }
void V8Util::reportException(TryCatch &tryCatch, bool showLine) { HandleScope scope; Handle<Message> message = tryCatch.Message(); if (nameSymbol.IsEmpty()) { nameSymbol = SYMBOL_LITERAL("name"); messageSymbol = SYMBOL_LITERAL("message"); } if (showLine) { Handle<Message> message = tryCatch.Message(); if (!message.IsEmpty()) { String::Utf8Value filename(message->GetScriptResourceName()); String::Utf8Value msg(message->Get()); int linenum = message->GetLineNumber(); LOGE(EXC_TAG, "Exception occurred at %s:%i: %s", *filename, linenum, *msg); } } Local<Value> stackTrace = tryCatch.StackTrace(); String::Utf8Value trace(tryCatch.StackTrace()); if (trace.length() > 0 && !stackTrace->IsUndefined()) { LOGD(EXC_TAG, *trace); } else { Local<Value> exception = tryCatch.Exception(); if (exception->IsObject()) { Handle<Object> exceptionObj = exception->ToObject(); Handle<Value> message = exceptionObj->Get(messageSymbol); Handle<Value> name = exceptionObj->Get(nameSymbol); if (!message->IsUndefined() && !name->IsUndefined()) { String::Utf8Value nameValue(name); String::Utf8Value messageValue(message); LOGE(EXC_TAG, "%s: %s", *nameValue, *messageValue); } } else { String::Utf8Value error(exception); LOGE(EXC_TAG, *error); } } }
void Image::set_prop(Local<String> property, Local<Value> value, const AccessorInfo& info) { HandleScope scope; Image* im = node::ObjectWrap::Unwrap<Image>(info.Holder()); std::string a = TOSTR(property); if (a == "background") { if (!value->IsObject()) ThrowException(Exception::TypeError( String::New("mapnik.Color expected"))); Local<Object> obj = value->ToObject(); if (obj->IsNull() || obj->IsUndefined() || !Color::constructor->HasInstance(obj)) ThrowException(Exception::TypeError(String::New("mapnik.Color expected"))); Color *c = node::ObjectWrap::Unwrap<Color>(obj); im->get()->set_background(*c->get()); } }
Handle<Value> Engine::run(Arguments const& args) { HandleScope scope; if (args.Length() == 1) { return runSync(args); } if (args.Length() < 1) { ThrowException(String::New("first argument must be a osrm.Query")); } if (!args[0]->IsObject()) { return ThrowException(String::New("first argument must be a osrm.Query object")); } Local<Object> obj = args[0]->ToObject(); if (obj->IsNull() || obj->IsUndefined() || !Query::constructor->HasInstance(obj)) { ThrowException(Exception::TypeError(String::New("osrm.Query object expected for first argument"))); } // ensure callback is a function Local<Value> callback = args[args.Length()-1]; if (!args[args.Length()-1]->IsFunction()) { return ThrowException(Exception::TypeError( String::New("last argument must be a callback function"))); } Query * query = ObjectWrap::Unwrap<Query>(obj); Engine * machine = ObjectWrap::Unwrap<Engine>(args.This()); run_query_baton_t *closure = new run_query_baton_t(); closure->request.data = closure; closure->machine = machine; closure->query = query; closure->error = false; closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback)); uv_queue_work(uv_default_loop(), &closure->request, AsyncRun, (uv_after_work_cb)AfterRun); closure->machine->_ref(); closure->query->_ref(); return Undefined(); }
// TODO void? Handle<Value> Feature::addGeometry(const Arguments& args) { HandleScope scope; Feature* fp = ObjectWrap::Unwrap<Feature>(args.This()); if (args.Length() >= 1 ) { Local<Value> value = args[0]; if (value->IsNull() || value->IsUndefined()) { return ThrowException(Exception::TypeError(String::New("mapnik.Geometry instance expected"))); } else { Local<Object> obj = value->ToObject(); if (Geometry::constructor->HasInstance(obj)) { Geometry* g = ObjectWrap::Unwrap<Geometry>(obj); try { std::auto_ptr<mapnik::geometry_type> geom_ptr = g->get(); if (geom_ptr.get()) { fp->get()->add_geometry(geom_ptr.get()); geom_ptr.release(); } else { return ThrowException(Exception::Error( String::New("empty geometry!"))); } } catch (const std::exception & ex ) { return ThrowException(Exception::Error( String::New(ex.what()))); } catch (...) { return ThrowException(Exception::Error( String::New("Unknown exception happended - please report bug"))); } } } } return Undefined(); }
Ti::TiValue Ti::TiViewProxy::add(Ti::TiValue value) { if(value.isProxy()) { Ti::TiViewProxy *childProxy = static_cast<Ti::TiViewProxy*>(value.toProxy()); childProxy->clearWeak(); _childViewsProxies.append(childProxy); Ti::TiView* childView = childProxy->getView(); Ti::TiView* thisView = getView(); thisView->add(childView); childProxy->_parentProxy = this; } else { TiObject* addObj = TiObject::getTiObjectFromJsObject(value.toJSValue()); TiUIBase* uiObj = (TiUIBase*) addObj; NativeObject* childNO = uiObj->getNativeObject(); getView()->addOldObject(childNO); Local<Value> children = _jsObject->Get(String::New("children")); Local<Array> array; if(children.IsEmpty() || children->IsUndefined()) { array = Array::New(); _jsObject->Set(String::New("children"), array); } else { array = Local<Array>::Cast(children); } array->Set(array->Length(), value.toJSValue()); childNO->release(); } Ti::TiValue val; val.setUndefined(); return val; }
Handle<Value> Engine::runSync(Arguments const& args) { HandleScope scope; if (args.Length() < 1) { ThrowException(Exception::TypeError(String::New("first argument must be a osrm.Query"))); } if (!args[0]->IsObject()) { return ThrowException(Exception::TypeError(String::New("first argument must be a osrm.Query object"))); } Local<Object> obj = args[0]->ToObject(); if (obj->IsNull() || obj->IsUndefined() || !Query::constructor->HasInstance(obj)) { return ThrowException(Exception::TypeError(String::New("osrm.Query object expected for first argument"))); } Query *query = ObjectWrap::Unwrap<Query>(obj); Engine* machine = ObjectWrap::Unwrap<Engine>(args.This()); http::Reply osrm_reply; machine->this_->RunQuery(*query->get(), osrm_reply); return scope.Close(String::New(osrm_reply.content.c_str())); }
Handle<Value> MSMap::InsertLayer (const Arguments& args) { HandleScope scope; MSMap *map = ObjectWrap::Unwrap<MSMap>(args.This()); MSLayer *layer; Local<Object> obj; int result; int position = -1; if (args.Length() < 1) { THROW_ERROR(Error, "insertLayer requires at least one argument"); } if (!args[0]->IsObject()) { THROW_ERROR(TypeError, "first argument to project must be Layer object"); } obj = args[0]->ToObject(); if (obj->IsNull() || obj->IsUndefined() || !MSLayer::constructor->HasInstance(obj)) { THROW_ERROR(TypeError, "first argument to project must be Layer object"); } layer = ObjectWrap::Unwrap<MSLayer>(obj); if (args.Length() == 2) { if (!args[1]->IsNumber()) { THROW_ERROR(TypeError, "second argument must be an integer"); } else { position = args[1]->ToInteger()->Value(); if (position >= map->this_->numlayers) { position = -1; } } } result = msInsertLayer(map->this_, layer->this_, position); return scope.Close(Number::New(result)); }
NativeString(const Local<Value> &value) { if (value->IsUndefined()) { data = nullptr; length = 0; } else if (value->IsString()) { utf8Value = new (utf8ValueMemory) String::Utf8Value(value); data = (**utf8Value); length = utf8Value->length(); } else if (node::Buffer::HasInstance(value)) { data = node::Buffer::Data(value); length = node::Buffer::Length(value); } else if (value->IsTypedArray()) { Local<ArrayBufferView> arrayBuffer = Local<ArrayBufferView>::Cast(value); ArrayBuffer::Contents contents = arrayBuffer->Buffer()->GetContents(); length = contents.ByteLength(); data = (char *) contents.Data(); } else { static char empty[] = ""; data = empty; length = 0; } }
int Conv::UnwrapObject(JNIEnv *jniEnv, Handle<Object> val, Handle<String> key, jobject *jVal) { int result = ErrorNotfound; Local<Value> hiddenVal = val->GetHiddenValue(key); if(!hiddenVal.IsEmpty() && !hiddenVal->IsUndefined()) { jobject extRef = (jobject)External::Unwrap(hiddenVal); if(jniEnv->GetObjectRefType(extRef) == JNIWeakGlobalRefType) { jobject localRef = jniEnv->NewLocalRef(extRef); if(localRef == 0) { /* the Java object died */ jniEnv->DeleteGlobalRef(extRef); val->DeleteHiddenValue(key); } else { /* the java object is alive */ *jVal = localRef; result = OK; } } else { /* the object is strongly referenced */ *jVal = extRef; result = OK; } } return result; }
void test_BasicCall() { HandleScope handle_scope; Handle<ObjectTemplate> templ = ObjectTemplate::New(); Handle<FunctionTemplate> fnT = v8::FunctionTemplate::New(AddOne); templ->Set("AddOne", fnT); Persistent<Context> context = Context::New(NULL, templ); Local<Value> addone = context->Global()->Get(String::New("AddOne")); do_check_true(!addone.IsEmpty()); do_check_true(!addone->IsUndefined()); do_check_true(addone->IsObject()); do_check_true(addone->IsFunction()); Local<Function> fn = addone.As<Function>(); do_check_eq(fn, fnT->GetFunction()); Local<Number> n = Number::New(0.5); Handle<Value> args[] = { n }; Local<Value> v = fn->Call(context->Global(), 1, args); do_check_true(!v.IsEmpty()); do_check_true(v->IsNumber()); Local<Number> n2 = v->ToNumber(); do_check_eq(n2->Value(), 1.5); }
Handle<Value> Expression::evaluate(const Arguments& args) { HandleScope scope; if (args.Length() < 1) { return ThrowException(Exception::Error( String::New("requires a mapnik.Feature as an argument"))); } Local<Object> obj = args[0]->ToObject(); if (obj->IsNull() || obj->IsUndefined()) { return ThrowException(Exception::TypeError(String::New("first argument is invalid, must be a mapnik.Feature not null/undefined"))); } if (!Feature::constructor->HasInstance(obj)) { return ThrowException(Exception::TypeError(String::New("first argument is invalid, must be a mapnik.Feature"))); } Feature* f = node::ObjectWrap::Unwrap<Feature>(obj); Expression* e = node::ObjectWrap::Unwrap<Expression>(args.This()); mapnik::value value_obj = boost::apply_visitor(mapnik::evaluate<mapnik::Feature,mapnik::value>(*(f->get())),*(e->get())); return scope.Close(boost::apply_visitor(node_mapnik::value_converter(),value_obj.base())); }
void SerializePart(google::protobuf::Message *message, Handle<Object> src) { Handle<Function> to_array = handle_->GetInternalField(3).As<Function>(); Handle<Array> properties = to_array->Call(src, 0, NULL).As<Array>(); const Reflection *r = message->GetReflection(); for (int i = 0; i < descriptor->field_count(); i++) { Local<Value> value = properties->Get(i); if (value->IsUndefined() || value->IsNull()) continue; const FieldDescriptor* field = descriptor->field(i); if (field->is_repeated()) { if (value->IsArray()) { Handle<Array> array = value.As<Array>(); int length = array->Length(); for (int j = 0; j < length; j++) SerializeField(message, r, field, array->Get(j)); } else if (value->IsObject() && field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && field->message_type()->name().compare(0, 20, "KeyValuePair_String_") == 0) { Local<Object> object = value.As<Object>(); Local<Array> subProperties = object->GetOwnPropertyNames(); int len = subProperties->Length(); for (int keyIdx = 0; keyIdx < len; keyIdx++) { Local<Object> keyValuePair = Object::New(); Local<Value> key = subProperties->Get(keyIdx); keyValuePair->Set(KeySymbol, key); keyValuePair->Set(ValueSymbol, object->Get(key)); SerializeField(message, r, field, keyValuePair); } } } else { SerializeField(message, r, field, value); } } }
static bool check_empty(Local<Value> obj) { return obj->IsUndefined() || obj->IsNull(); }
mapnik::feature_ptr next() { HandleScope scope; TryCatch try_catch; Local<Value> argv[2] = { Integer::New(feature_id_), obj_ }; Local<Value> val = ds_->cb_->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) { FatalException(try_catch); } else { if (!val->IsUndefined()) { if (val->IsObject()) { Local<Object> obj = val->ToObject(); if (obj->Has(String::New("x")) && obj->Has(String::New("y"))) { Local<Value> x = obj->Get(String::New("x")); Local<Value> y = obj->Get(String::New("y")); if (!x->IsUndefined() && x->IsNumber() && !y->IsUndefined() && y->IsNumber()) { mapnik::geometry_type * pt = new mapnik::geometry_type(mapnik::Point); pt->move_to(x->NumberValue(),y->NumberValue()); mapnik::feature_ptr feature(mapnik::feature_factory::create(feature_id_)); ++feature_id_; feature->add_geometry(pt); if (obj->Has(String::New("properties"))) { Local<Value> props = obj->Get(String::New("properties")); if (props->IsObject()) { Local<Object> p_obj = props->ToObject(); Local<Array> names = p_obj->GetPropertyNames(); uint32_t i = 0; uint32_t a_length = names->Length(); while (i < a_length) { Local<Value> name = names->Get(i)->ToString(); // if name in q.property_names() ? Local<Value> value = p_obj->Get(name); if (value->IsString()) { UnicodeString ustr = tr_->transcode(TOSTR(value)); boost::put(*feature,TOSTR(name),ustr); } else if (value->IsNumber()) { double num = value->NumberValue(); // todo - round if (num == value->IntegerValue()) { int integer = value->IntegerValue(); boost::put(*feature,TOSTR(name),integer); } else { double dub_val = value->NumberValue(); boost::put(*feature,TOSTR(name),dub_val); } } i++; } } } return feature; } } } } } return mapnik::feature_ptr(); }
Handle<Value> Query::New(Arguments const& args) { HandleScope scope; if (!args.IsConstructCall()) { return ThrowException(Exception::Error(String::New("Cannot call constructor as function, you need to use 'new' keyword"))); } try { if (args.Length() != 1) { return ThrowException(Exception::TypeError(String::New("please provide an object of options for the first argument"))); } if (!args[0]->IsObject()) { return ThrowException(Exception::TypeError(String::New("first argument must be an object"))); } Local<Object> obj = args[0]->ToObject(); if (obj->IsNull() || obj->IsUndefined()) { return ThrowException(Exception::TypeError(String::New("first arg must be an object"))); } if (!obj->Has(String::NewSymbol("coordinates"))) { return ThrowException(Exception::TypeError(String::New("must provide a coordinates property"))); } Local<Value> coordinates = obj->Get(String::New("coordinates")); if (!coordinates->IsArray()) { return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs"))); } Local<Array> coordinates_array = Local<Array>::Cast(coordinates); if (coordinates_array->Length() < 2) { return ThrowException(Exception::TypeError(String::New("at least two coordinates must be provided"))); } Query* q = new Query(); q->this_->zoomLevel = 18; //no generalization q->this_->printInstructions = true; //turn by turn instructions q->this_->alternateRoute = true; //get an alternate route, too q->this_->geometry = true; //retrieve geometry of route q->this_->compression = true; //polyline encoding q->this_->checkSum = UINT_MAX; //see wiki q->this_->service = "viaroute"; //that's routing q->this_->outputFormat = "json"; q->this_->jsonpParameter = ""; //set for jsonp wrapping q->this_->language = ""; //unused atm if (obj->Has(String::NewSymbol("alternateRoute"))) { q->this_->alternateRoute = obj->Get(String::New("alternateRoute"))->BooleanValue(); } for (uint32_t i = 0; i < coordinates_array->Length(); ++i) { Local<Value> coordinate = coordinates_array->Get(i); if (!coordinate->IsArray()) { return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs"))); } Local<Array> coordinate_array = Local<Array>::Cast(coordinate); if (coordinate_array->Length() != 2) { return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs"))); } q->this_->coordinates.push_back( FixedPointCoordinate(coordinate_array->Get(0)->NumberValue()*COORDINATE_PRECISION, coordinate_array->Get(1)->NumberValue()*COORDINATE_PRECISION)); } q->Wrap(args.This()); return args.This(); } catch (std::exception const& ex) { return ThrowException(Exception::TypeError(String::New(ex.what()))); } return Undefined(); }
Handle<Value> MSRect::New(const Arguments &args) { HandleScope scope; MSRect *obj; double t; if (!args.IsConstructCall()) { return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword")); } if (args[0]->IsExternal()) { Local<External> ext = Local<External>::Cast(args[0]); void* ptr = ext->Value(); obj = static_cast<MSRect*>(ptr); obj->Wrap(args.This()); return args.This(); } rectObj *rect = (rectObj *)calloc(1, sizeof(rectObj)); if(!rect) { return args.This(); } if (args.Length() == 0) { rect->minx = -1; rect->miny = -1; rect->maxx = -1; rect->maxy = -1; } else if (args.Length() == 1) { Local<Object> argObj; if (!args[0]->IsObject()) { THROW_ERROR(TypeError, "single argument constructor requires a Rect object"); } argObj = args[0]->ToObject(); if (argObj->IsNull() || argObj->IsUndefined() || !MSRect::constructor->HasInstance(argObj)) { THROW_ERROR(TypeError, "single argument to Rect constructor must be a Rect object"); } MSRect *inRect = ObjectWrap::Unwrap<MSRect>(argObj); memcpy(rect, inRect->this_, sizeof(rectObj)); } else if (args.Length() == 4) { REQ_DOUBLE_ARG(0, minx); REQ_DOUBLE_ARG(1, miny); REQ_DOUBLE_ARG(2, maxx); REQ_DOUBLE_ARG(3, maxy); /* coerce correct extent */ if (minx > maxx) { t = maxx; maxx = minx; minx = t; } if (miny > maxy) { t = maxy; maxy = miny; miny = t; } rect->minx = minx; rect->miny = miny; rect->maxx = maxx; rect->maxy = maxy; } else { THROW_ERROR(Error, "Rect objects take 0, 1 or 4 arguments."); } obj = new MSRect(rect); obj->owner = true; obj->Wrap(args.This()); return args.This(); }
bool JsArgToArrayConverter::ConvertArg(const Local<Value>& arg, int index) { bool success = false; stringstream s; JEnv env; Type returnType = JType::getClassType(m_return_type); if (arg.IsEmpty()) { s << "Cannot convert empty JavaScript object"; success = false; } else if (arg->IsInt32() && (returnType == Type::Int || returnType == Type::Null)) { jint value = arg->Int32Value(); JniLocalRef javaObject(JType::NewInt(env, value)); SetConvertedObject(env, index, javaObject); success = true; } else if (arg->IsNumber() || arg->IsNumberObject()) { double d = arg->NumberValue(); int64_t i = (int64_t)d; bool isInteger = d == i; if (isInteger) { jobject obj; //if returnType is long it will cast to long //if there is no return type specified it will cast to int //because default return type is null (ref type) if ((INT_MIN <= i) && (i <= INT_MAX) && (returnType == Type::Int || returnType == Type::Null)) { obj = JType::NewInt(env, (jint)d); } else /*isLong*/ { obj = JType::NewLong(env, (jlong)d); } JniLocalRef javaObject(obj); SetConvertedObject(env, index, javaObject); success = true; } else { jobject obj; //if returnType is double it will cast to double //if there is no return type specified it will cast to float //because default return type is null (ref type) if((FLT_MIN <= d) && (d <= FLT_MAX) && (returnType == Type::Float || returnType == Type::Null)) { obj = JType::NewFloat(env, (jfloat)d); } else {/*isDouble*/ obj = JType::NewDouble(env, (jdouble)d); } JniLocalRef javaObject(obj); SetConvertedObject(env, index, javaObject); success = true; } } else if (arg->IsBoolean()) { jboolean value = arg->BooleanValue(); JniLocalRef javaObject(JType::NewBoolean(env, value)); SetConvertedObject(env, index, javaObject); success = true; } else if (arg->IsBooleanObject()) { auto boolObj = Local<BooleanObject>::Cast(arg); jboolean value = boolObj->BooleanValue() ? JNI_TRUE : JNI_FALSE; JniLocalRef javaObject(JType::NewBoolean(env, value)); SetConvertedObject(env, index, javaObject); success = true; } else if (arg->IsString() || arg->IsStringObject()) { JniLocalRef stringObject(ConvertToJavaString(arg)); SetConvertedObject(env, index, stringObject); success = true; } else if (arg->IsObject()) { auto objectWithHiddenID = arg->ToObject(); auto hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsLong()); if (!hidden.IsEmpty()) { jlong value = 0; if (hidden->IsString()) { auto strValue = ConvertToString(hidden->ToString()); value = atoll(strValue.c_str()); } else if (hidden->IsInt32()) { value = hidden->ToInt32()->Int32Value(); } JniLocalRef javaObject(JType::NewLong(env, value)); SetConvertedObject(env, index, javaObject); return true; } hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsByte()); if (!hidden.IsEmpty()) { jbyte value = 0; if (hidden->IsString()) { string value = ConvertToString(hidden->ToString()); int byteArg = atoi(value.c_str()); value = (jbyte)byteArg; } else if (hidden->IsInt32()) { int byteArg = hidden->ToInt32()->Int32Value(); value = (jbyte)byteArg; } JniLocalRef javaObject(JType::NewByte(env, value)); SetConvertedObject(env, index, javaObject); return true; } hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsShort()); if (!hidden.IsEmpty()) { jshort value = 0; if (hidden->IsString()) { string value = ConvertToString(hidden->ToString()); int shortArg = atoi(value.c_str()); value = (jshort)shortArg; } else if (hidden->IsInt32()) { jlong shortArg = hidden->ToInt32()->Int32Value(); value = (jshort)shortArg; } JniLocalRef javaObject(JType::NewShort(env, value)); SetConvertedObject(env, index, javaObject); return true; } hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsDouble()); if (!hidden.IsEmpty()) { jdouble value = 0; if (hidden->IsNumber()) { double doubleArg = hidden->ToNumber()->NumberValue(); value = (jdouble)doubleArg; } JniLocalRef javaObject(JType::NewDouble(env, value)); SetConvertedObject(env, index, javaObject); return true; } hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsFloat()); if (!hidden.IsEmpty()) { jfloat value = 0; if (hidden->IsNumber()) { double floatArg = hidden->ToNumber()->NumberValue(); value = (jfloat)floatArg; } JniLocalRef javaObject(JType::NewFloat(env, value)); SetConvertedObject(env, index, javaObject); return true; } hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsChar()); if (!hidden.IsEmpty()) { jchar value = '\0'; if (hidden->IsString()) { string str = ConvertToString(hidden->ToString()); value = (jchar)str[0]; } JniLocalRef javaObject(JType::NewChar(env, value)); SetConvertedObject(env, index, javaObject); return true; } jweak obj = ObjectManager::GetJavaObjectByJsObjectStatic(objectWithHiddenID); success = obj != nullptr; if (success) { SetConvertedObject(env, index, obj, true); } else { s << "Cannot convert JavaScript object with id " << objectWithHiddenID->GetIdentityHash() << " at index " << index; } } else if (arg->IsUndefined() || arg->IsNull()) { SetConvertedObject(env, index, nullptr); success = true; } else { s << "Cannot convert JavaScript object at index " << index; success = false; } if (!success) { m_error.index = index; m_error.msg = s.str(); } return success; }
Handle<Value> ImageView::encodeSync(const Arguments& args) { HandleScope scope; ImageView* im = ObjectWrap::Unwrap<ImageView>(args.This()); std::string format = "png"; palette_ptr palette; // accept custom format if (args.Length() >= 1) { if (!args[0]->IsString()) return ThrowException(Exception::TypeError( String::New("first arg, 'format' must be a string"))); format = TOSTR(args[0]); } // options hash if (args.Length() >= 2) { if (!args[1]->IsObject()) return ThrowException(Exception::TypeError( String::New("optional second arg must be an options object"))); Local<Object> options = args[1]->ToObject(); if (options->Has(String::New("palette"))) { Local<Value> format_opt = options->Get(String::New("palette")); if (!format_opt->IsObject()) return ThrowException(Exception::TypeError( String::New("'palette' must be an object"))); Local<Object> obj = format_opt->ToObject(); if (obj->IsNull() || obj->IsUndefined() || !Palette::constructor->HasInstance(obj)) return ThrowException(Exception::TypeError(String::New("mapnik.Palette expected as second arg"))); palette = ObjectWrap::Unwrap<Palette>(obj)->palette(); } } try { std::string s; if (palette.get()) { s = save_to_string(*(im->this_), format, *palette); } else { s = save_to_string(*(im->this_), format); } #if NODE_VERSION_AT_LEAST(0,3,0) node::Buffer *retbuf = Buffer::New((char*)s.data(),s.size()); #else node::Buffer *retbuf = Buffer::New(s.size()); memcpy(retbuf->data(), s.data(), s.size()); #endif return scope.Close(retbuf->handle_); } catch (std::exception & ex) { return ThrowException(Exception::Error( String::New(ex.what()))); } catch (...) { return ThrowException(Exception::Error( String::New("unknown exception happened when encoding image: please file bug report"))); } }
Handle<Value> JSHandler::on(const Arguments& args) { HandleScope scope; if (args.Length() != 2 || !args[0]->IsString() || !args[1]->IsFunction()) { return ThrowException(Exception::TypeError(String::New("please provide an event name and callback function"))); } std::string callback_name = *String::Utf8Value(args[0]->ToString()); Local<Function> callback = Local<Function>::Cast(args[1]); if (callback->IsNull() || callback->IsUndefined()) { return ThrowException(Exception::TypeError(String::New("please provide a valid callback function for second arg"))); } JSHandler* handler = node::ObjectWrap::Unwrap<JSHandler>(args.This()); if (callback_name == "node") { if (!handler->node_cb.IsEmpty()) { handler->node_cb.Dispose(); } handler->node_cb = Persistent<Function>::New(callback); } else if (callback_name == "way") { if (!handler->way_cb.IsEmpty()) { handler->way_cb.Dispose(); } handler->way_cb = Persistent<Function>::New(callback); } else if (callback_name == "relation") { if (!handler->relation_cb.IsEmpty()) { handler->relation_cb.Dispose(); } handler->relation_cb = Persistent<Function>::New(callback); } else if (callback_name == "init") { if (!handler->init_cb.IsEmpty()) { handler->init_cb.Dispose(); } handler->init_cb = Persistent<Function>::New(callback); } else if (callback_name == "before_nodes") { if (!handler->before_nodes_cb.IsEmpty()) { handler->before_nodes_cb.Dispose(); } handler->before_nodes_cb = Persistent<Function>::New(callback); } else if (callback_name == "after_nodes") { if (!handler->after_nodes_cb.IsEmpty()) { handler->after_nodes_cb.Dispose(); } handler->after_nodes_cb = Persistent<Function>::New(callback); } else if (callback_name == "before_ways") { if (!handler->before_ways_cb.IsEmpty()) { handler->before_ways_cb.Dispose(); } handler->before_ways_cb = Persistent<Function>::New(callback); } else if (callback_name == "after_ways") { if (!handler->after_ways_cb.IsEmpty()) { handler->after_ways_cb.Dispose(); } handler->after_ways_cb = Persistent<Function>::New(callback); } else if (callback_name == "before_relations") { if (!handler->before_relations_cb.IsEmpty()) { handler->before_relations_cb.Dispose(); } handler->before_relations_cb = Persistent<Function>::New(callback); } else if (callback_name == "after_relations") { if (!handler->after_relations_cb.IsEmpty()) { handler->after_relations_cb.Dispose(); } handler->after_relations_cb = Persistent<Function>::New(callback); } else if (callback_name == "done") { if (!handler->done_cb.IsEmpty()) { handler->done_cb.Dispose(); } handler->done_cb = Persistent<Function>::New(callback); } return scope.Close(Undefined()); }
Handle<Value> Session::subscribe(const Arguments& args, bool resubscribe) { HandleScope scope; if (args.Length() < 1 || !args[0]->IsArray()) { return ThrowException(Exception::Error(String::New( "Array of subscription information must be provided."))); } if (args.Length() >= 2 && !args[1]->IsUndefined() && !args[1]->IsString()) { return ThrowException(Exception::Error(String::New( "Optional subscription label must be a string."))); } if (args.Length() > 2) { return ThrowException(Exception::Error(String::New( "Function expects at most two arguments."))); } blpapi::SubscriptionList sl; Local<Object> o = args[0]->ToObject(); for (std::size_t i = 0; i < Array::Cast(*(args[0]))->Length(); ++i) { Local<Value> v = o->Get(i); if (!v->IsObject()) { return ThrowException(Exception::Error(String::New( "Array elements must be objects " "containing subscription information."))); } Local<Object> io = v->ToObject(); // Process 'security' string Local<Value> iv = io->Get(String::New("security")); if (!iv->IsString()) { return ThrowException(Exception::Error(String::New( "Property 'security' must be a string."))); } String::Utf8Value secv(iv); if (0 == secv.length()) { return ThrowException(Exception::Error(String::New( "Property 'security' must be a string."))); } // Process 'fields' array iv = io->Get(String::New("fields")); if (!iv->IsArray()) { return ThrowException(Exception::Error(String::New( "Property 'fields' must be an array of strings."))); } std::string fields; formFields(&fields, iv->ToObject()); // Process 'options' array iv = io->Get(String::New("options")); if (!iv->IsUndefined() && !iv->IsNull() && !iv->IsObject()) { return ThrowException(Exception::Error(String::New( "Property 'options' must be an object containing " "whose keys and key values will be configured as " "options."))); } std::string options; formOptions(&options, iv); // Process 'correlation' int or string iv = io->Get(String::New("correlation")); if (!iv->IsInt32()) { return ThrowException(Exception::Error(String::New( "Property 'correlation' must be an integer."))); } int correlation = iv->Int32Value(); sl.add(*secv, fields.c_str(), options.c_str(), blpapi::CorrelationId(correlation)); } Session* session = ObjectWrap::Unwrap<Session>(args.This()); BLPAPI_EXCEPTION_TRY if (args.Length() == 2) { Local<String> s = args[1]->ToString(); String::Utf8Value labelv(s); if (resubscribe) session->d_session->resubscribe(sl, *labelv, labelv.length()); else session->d_session->subscribe(sl, *labelv, labelv.length()); } else { if (resubscribe) session->d_session->resubscribe(sl); else session->d_session->subscribe(sl); } BLPAPI_EXCEPTION_CATCH_RETURN return scope.Close(args.This()); }