예제 #1
0
Handle<Value> js_haptics_vibrate(const Arguments &args) {
	Handle<Object> opts = Handle<Object>::Cast(args[0]);
	Handle<Value> milliseconds = opts->Get(STRING_CACHE_milliseconds);

	if ( milliseconds->IsUndefined() ) {
	
		Handle<Object> pattern = Handle<Array>::Cast( opts->Get(STRING_CACHE_pattern) );
		int repeat = opts->Get(STRING_CACHE_repeat)->Int32Value();

		int patternLen = pattern->Get(STRING_CACHE_length)->Int32Value();
		long long* patternArr = (long long*)malloc(sizeof(long long) * patternLen);
	
		for ( int i = 0; i < patternLen; i++ ) {	
			patternArr[i] = pattern->Get(Number::New(i))->IntegerValue();
		}
		
		haptics_vibrate(patternArr, repeat, patternLen);

		free(patternArr);
	
	} else {

		haptics_vibrate(milliseconds->IntegerValue());	
	
	}

	return Undefined();
}
예제 #2
0
 BSONObj V8Scope::getObject( const char * field ){
     Handle<Value> v = get( field );
     if ( v->IsNull() || v->IsUndefined() )
         return BSONObj();
     uassert( "not an object" , v->IsObject() );
     return v8ToMongo( v->ToObject() );
 }
IOBasicTypes::LongBufferSizeType ObjectByteReaderWithPosition::Read(IOBasicTypes::Byte* inBuffer,IOBasicTypes::LongBufferSizeType inBufferSize)
{
	CREATE_ISOLATE_CONTEXT;
	CREATE_ESCAPABLE_SCOPE;

	Handle<Value> value = OBJECT_FROM_PERSISTENT(mObject)->Get(NEW_STRING("read"));
    if(value->IsUndefined())
        return 0;
    Handle<Function> func = Handle<Function>::Cast(value);
    
    Handle<Value> args[1];
    args[0] = NEW_NUMBER(inBufferSize);
    
	Handle<Value> result = func->Call(OBJECT_FROM_PERSISTENT(mObject), 1, args);
    
    if(!result->IsArray())
        return 0;
    
    IOBasicTypes::LongBufferSizeType bufferLength = result->ToObject()->Get(NEW_STRING("length"))->ToObject()->Uint32Value();
    for(IOBasicTypes::LongBufferSizeType i=0;i < bufferLength;++i)
        inBuffer[i] = (IOBasicTypes::Byte)(result->ToObject()->Get((uint32_t)i)->ToNumber()->Uint32Value());
    
    return bufferLength;
    
}
IOBasicTypes::LongBufferSizeType ObjectByteWriterWithPosition::Write(const IOBasicTypes::Byte* inBuffer,IOBasicTypes::LongBufferSizeType inBufferSize)
{
    HandleScope handle;
    
    Handle<Object> anArray = Array::New((int)inBufferSize);
    for(int i=0;i<(int)inBufferSize;++i)
        anArray->Set(Number::New(i),Number::New(inBuffer[i]));
    
    Handle<Value> value = mObject->Get(String::New("write"));
    if(value->IsUndefined() || !value->IsFunction())
    {
		ThrowException(Exception::TypeError(String::New("write is not a function, it should be you know...")));
        return 0;
    }
    Handle<Function> func = Handle<Function>::Cast(value);
    
    Handle<Value> args[1];
    args[0] = anArray;
    
    Handle<Value> result = func->Call(mObject, 1, args);
    if(result.IsEmpty())
    {
		ThrowException(Exception::TypeError(String::New("wrong return value. it's empty. return the number of written characters")));
		return 0;
    }
    else if(result->IsNumber())
    {
        return result->ToNumber()->Uint32Value();
    }
    else
    {
		ThrowException(Exception::TypeError(String::New("wrong return value. write should return the number of written characters")));
		return 0;
    }
}
예제 #5
0
파일: engine_v8.cpp 프로젝트: IlyaM/mongo
    int V8Scope::type( const char *field ){
        V8_SIMPLE_HEADER
        Handle<Value> v = get( field );
        if ( v->IsNull() )
            return jstNULL;
        if ( v->IsUndefined() )
            return Undefined;
        if ( v->IsString() )
            return String;
        if ( v->IsFunction() )
            return Code;
        if ( v->IsArray() )
            return Array;
        if ( v->IsBoolean() )
            return Bool;
        if ( v->IsInt32() )
            return NumberInt;
        if ( v->IsNumber() )
            return NumberDouble;
        if ( v->IsExternal() ){
            uassert( 10230 ,  "can't handle external yet" , 0 );
            return -1;
        }
        if ( v->IsDate() )
            return Date;
        if ( v->IsObject() )
            return Object;

        throw UserException( 12509, (string)"don't know what this is: " + field );
    }
예제 #6
0
static std::string* findApplicationDir() {
	Handle<Value> mainModule = getProcessObject()->Get(Nan::New<String>("mainModule").ToLocalChecked());
	if (!mainModule->IsUndefined()) {
		return getModuleDir(mainModule->ToObject());
	}
	return NULL;
}
예제 #7
0
파일: Conv.cpp 프로젝트: Armen138/anode
int Conv::ToJavaMap(JNIEnv *jniEnv, Handle<Value> val, int componentType, jobject *jVal) {
  Local<Object> oVal;
  Local<Array> aPropertyNames;
  if(val.IsEmpty() || val->IsNull() || val->IsUndefined()) {
    *jVal = 0;
    return OK;
  }
  if(!val->IsObject())
    return ErrorType;
  
  oVal = val->ToObject();
  aPropertyNames = oVal->GetOwnPropertyNames();
  int len = aPropertyNames->Length();

  jobject ob = jniEnv->NewObject(mapClass, mapCtor);
  if(ob) {
    int res = OK;
    for(int i = 0; i < len; i++) {
      Local<String> key = Local<String>::Cast(aPropertyNames->Get(i));
      jstring jKey; jobject item;
      res = ToJavaString(jniEnv, key, &jKey);
      if(res != OK) break;
      res = ToJavaObject(jniEnv, oVal->Get(key), componentType, &item);
      if(res != OK) break;
      jniEnv->CallObjectMethod(ob, mapPut, jKey, item);
    }
  }
  if(ob) {
    *jVal = ob;
    return OK;
  }
  if(jniEnv->ExceptionCheck())
    jniEnv->ExceptionClear();
  return ErrorVM;
}
void printV8Value(Handle<Value> value, bool force=false)
{
    Logging::Level level = force ? Logging::ERROR : Logging::INFO;

    if (!Logging::shouldShow(level)) return;

    HandleScope handleScope;

    if (value.IsEmpty())
        Logging::log(level, "Empty handle\r\n");
    else if (value->IsInt32())
        Logging::log(level, "INT: %d\r\n", value->IntegerValue());
    else if (value->IsNull())
        Logging::log(level, "NULL (null)\r\n");
    else if (value->IsUndefined())
        Logging::log(level, "VOID (undefined)\r\n");
    else if (value->IsBoolean())
        Logging::log(level, "BOOLEAN: %d\r\n", value->BooleanValue());
    else if (value->IsNumber())
        Logging::log(level, "NUMBER: %f\r\n", value->NumberValue());
    else if (value->IsString())
        Logging::log(level, "STRING: ?\r\n");
    else if (value->IsObject())
        Logging::log(level, "OBJECT (object)\r\n");
    else
        Logging::log(level, "Uncertain V8 value\n");
}
예제 #9
0
static string get_env(Handle<Function> require) {
    HandleScope hs;
    Handle<Object> env = Handle<Object>::Cast(Context::GetCalling()->Global()->Get(String::New("_env")));
    if(env->IsUndefined()) return "/usr/lib/purple/js";
    String::Utf8Value cwd (env->Get(String::New("cwd")));
    cerr << "found cwd = " << *cwd << endl;
    return string(*cwd);
}
예제 #10
0
/* Create a V8 execution context, execute a script and return the feature
 * style. */
char* msV8GetFeatureStyle(mapObj *map, const char *filename, layerObj *layer, shapeObj *shape)
{
  TryCatch try_catch;
  V8Context* v8context = V8CONTEXT(map);
  char *ret = NULL;
    
  if (!v8context) {
    msSetError(MS_V8ERR, "V8 Persistent Context is not created.", "msV8ReportException()");
    return NULL;
  }

  Isolate::Scope isolate_scope(v8context->isolate);
  HandleScope handle_scope(v8context->isolate);

  /* execution context */
  Local<Context> context = Local<Context>::New(v8context->isolate, v8context->context);
  Context::Scope context_scope(context);
  Handle<Object> global = context->Global();

  Shape *shape_ = new Shape(shape);
  shape_->setLayer(layer); // hack to set the attribute names, should change in future.
  shape_->disableMemoryHandler(); /* the internal object should not be freed by the v8 GC */
  Handle<Value> ext = External::New(shape_);
  global->Set(String::New("shape"),
              Shape::Constructor()->NewInstance(1, &ext));
  
  msV8ExecuteScript(filename);
  Handle<Value> value = global->Get(String::New("styleitem"));
  if (value->IsUndefined()) {
    msDebug("msV8GetFeatureStyle: Function 'styleitem' is missing.\n");
    return ret;
  }
  Handle<Function> func = Handle<Function>::Cast(value);
  Handle<Value> result = func->Call(global, 0, 0);
  if (result.IsEmpty() && try_catch.HasCaught()) {
    msV8ReportException(&try_catch);
  }

  if (!result.IsEmpty() && !result->IsUndefined()) {
     String::AsciiValue ascii(result);
     ret = msStrdup(*ascii);
  }

  return ret;
}
예제 #11
0
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);
		}
	}
}
예제 #12
0
파일: v8base.cpp 프로젝트: pgmsoul/GitLib
	void setPersistentFunc(Persistent<Function>& pf,Handle<Value>& v){
		if(v->IsFunction()){
			if(!pf.IsEmpty()) pf.Dispose();
			pf = Persistent<Function>::New(Handle<Function>::Cast(v));
		}else if(v->IsNull()||v->IsUndefined()){
			if(pf.IsEmpty()) return;
			pf.Dispose();
			pf.Clear();
		}
	}
예제 #13
0
파일: Conv.cpp 프로젝트: Armen138/anode
int Conv::GetNaturalType(Handle<Value> val) {
  if(val.IsEmpty()) return TYPE_INVALID;
  if(val->IsUndefined()) return TYPE_UNDEFINED;
  if(val->IsNull()) return TYPE_NULL;
  if(val->IsBoolean() || val->IsBooleanObject()) return TYPE_BOOL;
  if(val->IsInt32()) return TYPE_INT;
  if(val->IsUint32()) return TYPE_LONG;
  if(val->IsNumber() || val->IsNumberObject()) return TYPE_DOUBLE;
  if(val->IsString() || val->IsStringObject()) return TYPE_STRING;
  return GetNaturalType(Handle<Object>::Cast(val));
}
예제 #14
0
IOBasicTypes::LongFilePositionType ObjectByteWriterWithPosition::GetCurrentPosition()
{
    HandleScope handle;
    
    Handle<Value> value = mObject->Get(String::New("getCurrentPosition"));
    if(value->IsUndefined())
        return true;
    Handle<Function> func = Handle<Function>::Cast(value);
    
    return (func->Call(mObject, 0, NULL)->ToNumber()->Value());
}
예제 #15
0
bool ObjectByteReader::NotEnded()
{
    HandleScope handle;

    Handle<Value> value = mObject->Get(String::New("notEnded"));
    if(value->IsUndefined())
        return true;
    Handle<Function> func = Handle<Function>::Cast(value);
    
    return (func->Call(mObject, 0, NULL)->ToBoolean()->Value());
}
LongFilePositionType ObjectByteReaderWithPosition::GetCurrentPosition()
{
	CREATE_ISOLATE_CONTEXT;
	CREATE_ESCAPABLE_SCOPE;

	Handle<Value> value = OBJECT_FROM_PERSISTENT(mObject)->Get(NEW_STRING("getCurrentPosition"));
    if(value->IsUndefined())
        return true;
    Handle<Function> func = Handle<Function>::Cast(value);
    
	return (func->Call(OBJECT_FROM_PERSISTENT(mObject), 0, NULL)->ToNumber()->Value());
}
bool ObjectByteReaderWithPosition::NotEnded()
{
	CREATE_ISOLATE_CONTEXT;
	CREATE_ESCAPABLE_SCOPE;

	Handle<Value> value = OBJECT_FROM_PERSISTENT(mObject)->Get(NEW_STRING("notEnded"));
    if(value->IsUndefined())
        return true;
    Handle<Function> func = Handle<Function>::Cast(value);
    
	return (func->Call(OBJECT_FROM_PERSISTENT(mObject), 0, NULL)->ToBoolean()->Value());
}
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);
}
예제 #19
0
/* for geomtransform, we don't have the mapObj */
shapeObj *msV8TransformShape(shapeObj *shape, const char* filename)
{
  TryCatch try_catch;
  Isolate *isolate = Isolate::GetCurrent();
  V8Context *v8context = (V8Context*)isolate->GetData();

  HandleScope handle_scope(v8context->isolate);

  /* execution context */
  Local<Context> context = Local<Context>::New(v8context->isolate, v8context->context);
  Context::Scope context_scope(context);
  Handle<Object> global = context->Global();

  Shape* shape_ = new Shape(shape);
  shape_->setLayer(v8context->layer);
  shape_->disableMemoryHandler();
  Handle<Value> ext = External::New(shape_);
  global->Set(String::New("shape"),
              Shape::Constructor()->NewInstance(1, &ext));

  msV8ExecuteScript(filename);
  Handle<Value> value = global->Get(String::New("geomtransform"));
  if (value->IsUndefined()) {
    msDebug("msV8TransformShape: Function 'geomtransform' is missing.\n");
    return NULL;
  }
  Handle<Function> func = Handle<Function>::Cast(value);
  Handle<Value> result = func->Call(global, 0, 0);
  if (result.IsEmpty() && try_catch.HasCaught()) {
    msV8ReportException(&try_catch);
  }

  if (!result.IsEmpty() && result->IsObject()) {
    Handle<Object> obj = result->ToObject();
    if (obj->GetConstructorName()->Equals(String::New("shapeObj"))) {
      Shape* new_shape = ObjectWrap::Unwrap<Shape>(result->ToObject());
      if (shape == new_shape->get()) {
        shapeObj *new_shape_ = (shapeObj *)msSmallMalloc(sizeof(shapeObj));
        msInitShape(new_shape_);
        msCopyShape(shape, new_shape_);
        return new_shape_;
      }
      else {
        new_shape->disableMemoryHandler();
        return new_shape->get();
      }
    }
  }

  return NULL;
}
예제 #20
0
파일: JSEngine.cpp 프로젝트: Spacefish/susi
Susi::Util::Any Susi::JS::Engine::convertFromJS(Handle<Value> jsVal){
	if(jsVal->IsArray()){
		Susi::Util::Any::Array result;
		auto obj = jsVal->ToObject();
		const Local<Array> props = obj->GetPropertyNames();
		const uint32_t length = props->Length();
		for (uint32_t i=0 ; i<length ; ++i){
			const Local<Value> key = props->Get(i);
			const Local<Value> value = obj->Get(key);
			result.push_back(Susi::JS::Engine::convertFromJS(value));
		}
		return result;
	}
	if(jsVal->IsObject()){
		Susi::Util::Any result = Susi::Util::Any::Object{};
		auto obj = jsVal->ToObject();
		const Local<Array> props = obj->GetPropertyNames();
		const uint32_t length = props->Length();
		for (uint32_t i=0 ; i<length ; ++i){
			const Local<Value> key = props->Get(i);
			const Local<Value> value = obj->Get(key);
			String::Utf8Value keyStr(key);
			result[std::string(*keyStr)] = Susi::JS::Engine::convertFromJS(value);
		}
		return result;
	}
	if(jsVal->IsString()){
		String::Utf8Value val(jsVal);
		Susi::Util::Any result{std::string(*val)};
		return result;
	}
	if(jsVal->IsNumber()){
		Susi::Util::Any result{jsVal->ToNumber()->Value()};
		return result;
	}
	if(jsVal->IsBoolean()){
		Susi::Util::Any result{jsVal->ToBoolean()->Value()};
		return result;
	}
	if(jsVal->IsNativeError()){
		String::Utf8Value val(jsVal);
		Susi::Util::Any result{std::string(*val)};
		return result;
	}
	if(jsVal->IsUndefined()){
		Susi::Util::Any result;
		return result;
	}
	return Susi::Util::Any{"type not known"};
}
void ObjectByteReaderWithPosition::SetPositionFromEnd(LongFilePositionType inOffsetFromStart)
{
	CREATE_ISOLATE_CONTEXT;
	CREATE_ESCAPABLE_SCOPE;

	Handle<Value> value = OBJECT_FROM_PERSISTENT(mObject)->Get(NEW_STRING("setPositionFromEnd"));
    if(value->IsUndefined())
        return;
    Handle<Function> func = Handle<Function>::Cast(value);
    
    Handle<Value> args[1];
    args[0] = NEW_NUMBER(inOffsetFromStart);
	func->Call(OBJECT_FROM_PERSISTENT(mObject), 1, args);
}
void ObjectByteReaderWithPosition::Skip(LongBufferSizeType inSkipSize)
{
	CREATE_ISOLATE_CONTEXT;
	CREATE_ESCAPABLE_SCOPE;

	Handle<Value> value = OBJECT_FROM_PERSISTENT(mObject)->Get(NEW_STRING("skip"));
    if(value->IsUndefined())
        return;
    Handle<Function> func = Handle<Function>::Cast(value);
    
    Handle<Value> args[1];
    args[0] = NEW_NUMBER(inSkipSize);
	func->Call(OBJECT_FROM_PERSISTENT(mObject), 1, args);
}
예제 #23
0
inline bool setField(OGRFeature* f, int field_index, Handle<Value> val){
	if (val->IsInt32()) {
		f->SetField(field_index, val->Int32Value());
	} else if (val->IsNumber()) {
		f->SetField(field_index, val->NumberValue());
	} else if (val->IsString()) {
		std::string str = *NanUtf8String(val);
		f->SetField(field_index, str.c_str());
	} else if(val->IsNull() || val->IsUndefined()) {
		f->UnsetField(field_index);
	} else {
		return true;
	}
	return false;
}
예제 #24
0
void
Session::formOptions(std::string* str, Handle<Value> value)
{
    // Use the HandleScope of the calling function for speed.

    if (value->IsUndefined() || value->IsNull())
        return;

    assert(value->IsObject());

    std::stringstream ss;

    if (value->IsArray()) {
        // Format each array value into the options string "V[&V]"
        Local<Object> object = value->ToObject();
        for (std::size_t i = 0; i < Array::Cast(*object)->Length(); ++i) {
            Local<String> key = object->Get(i)->ToString();
            String::Utf8Value valv(key);
            if (valv.length()) {
                if (i > 0)
                    ss << "&";
                ss << *valv;
            }
        }
    } else {
        // Format each KV pair into the options string "K=V[&K=V]"
        Local<Object> object = value->ToObject();
        Local<Array> keys = object->GetPropertyNames();
        for (std::size_t i = 0; i < keys->Length(); ++i) {
            Local<String> key = keys->Get(i)->ToString();
            String::Utf8Value keyv(key);
            if (keyv.length()) {
                if (i > 0)
                    ss << "&";
                ss << *keyv << "=";
            }

            Local<String> val = object->Get(key)->ToString();
            String::Utf8Value valv(val);
            if (valv.length())
                ss << *valv;
        }
    }

    *str = ss.str();
}
예제 #25
0
    bool V8Scope::exec( const string& code , const string& name , bool printResult , bool reportError , bool assertOnError, int timeoutMs ){

        if ( timeoutMs ){
            static bool t = 1;
            if ( t ){
                log() << "timeoutMs not support for v8 yet" << endl;
                t = 0;
            }
        }
        
        HandleScope handle_scope;
        TryCatch try_catch;
    
        Handle<Script> script = v8::Script::Compile( v8::String::New( code.c_str() ) , 
                                                     v8::String::New( name.c_str() ) );
        if (script.IsEmpty()) {
            stringstream ss;
            ss << "compile error: " << toSTLString( &try_catch );
            _error = ss.str();
            if (reportError)
                log() << _error << endl;
            if ( assertOnError )
                uassert( _error , 0 );
            return false;
        } 
    
        Handle<v8::Value> result = script->Run();
        if ( result.IsEmpty() ){
            _error = (string)"exec error: " + toSTLString( &try_catch );
            if ( reportError )
                log() << _error << endl;
            if ( assertOnError )
                uassert( _error , 0 );
            return false;
        } 
        
        _global->Set( v8::String::New( "__lastres__" ) , result );

        if ( printResult && ! result->IsUndefined() ){
            cout << toSTLString( result ) << endl;
        }
        
        return true;
    }
예제 #26
0
void JsContext::onDraw(SkCanvas* canvas) {
    // Record canvas and window in this.
    fCanvas = canvas;

    // Create a handle scope to keep the temporary object references.
    HandleScope handleScope(fGlobal->getIsolate());

    // Create a local context from our global context.
    Local<Context> context = fGlobal->getContext();

    // Enter the context so all the remaining operations take place there.
    Context::Scope contextScope(context);

    // Wrap the C++ this pointer in a JavaScript wrapper.
    Handle<Object> contextObj = this->wrap();

    // Set up an exception handler before calling the Process function.
    TryCatch tryCatch;

    // Invoke the process function, giving the global object as 'this'
    // and one argument, this JsContext.
    const int argc = 1;
    Handle<Value> argv[argc] = { contextObj };
    Local<Function> onDraw =
            Local<Function>::New(fGlobal->getIsolate(), fOnDraw);
    Handle<Value> result = onDraw->Call(context->Global(), argc, argv);

    // Handle any exceptions or output.
    if (result.IsEmpty()) {
        SkASSERT(tryCatch.HasCaught());
        // Print errors that happened during execution.
        fGlobal->reportException(&tryCatch);
    } else {
        SkASSERT(!tryCatch.HasCaught());
        if (!result->IsUndefined()) {
            // If all went well and the result wasn't undefined then print
            // the returned value.
            String::Utf8Value str(result);
            const char* cstr = to_cstring(str);
            printf("%s\n", cstr);
        }
    }
}
예제 #27
0
Handle<Value> GeoJSONReader::getCoordsArray(Handle<Object> geojson) {
    Isolate* isolate = Isolate::GetCurrent();

    Handle<String> coordsKey = String::NewFromUtf8(isolate, "coordinates");
    if (!geojson->HasOwnProperty(coordsKey))
        throw "Property \"coordinates\" is missing";


    Handle<Value> coords = geojson->Get(coordsKey);
    if (
        !coords->IsArray()
        && !coords->IsNull()
        && !coords->IsUndefined()
    )
        throw "Property \"coordinates\" must be an instance of Array or null";


    return coords;
}
예제 #28
0
파일: Global.cpp 프로젝트: Coolred/skia
// Callback function for SkEvents used to implement timeouts.
bool Global::TimeOutProc(const SkEvent& evt) {
    // Create a handle scope to keep the temporary object references.
    HandleScope handleScope(gGlobal->getIsolate());

    // Create a local context from our global context.
    Local<Context> context = gGlobal->getContext();

    // Enter the context so all the remaining operations take place there.
    Context::Scope contextScope(context);

    // Set up an exception handler before calling the Process function.
    TryCatch tryCatch;

    int32_t id = evt.getFast32();
    if (gGlobal->fTimeouts.find(gGlobal->fLastTimerID) == gGlobal->fTimeouts.end()) {
        printf("Not a valid timer ID.\n");
        return true;
    }

    const int argc = 0;
    Local<Function> onTimeout =
            Local<Function>::New(gGlobal->getIsolate(), gGlobal->fTimeouts[id]);
    Handle<Value> result = onTimeout->Call(context->Global(), argc, NULL);
    gGlobal->fTimeouts.erase(id);

    // Handle any exceptions or output.
    if (result.IsEmpty()) {
        SkASSERT(tryCatch.HasCaught());
        // Print errors that happened during execution.
        gGlobal->reportException(&tryCatch);
    } else {
        SkASSERT(!tryCatch.HasCaught());
        if (!result->IsUndefined()) {
            // If all went well and the result wasn't undefined then print the
            // returned value.
            String::Utf8Value str(result);
            const char* cstr = to_cstring(str);
            printf("%s\n", cstr);
        }
    }
    return true;
}
예제 #29
0
  ScriptMatchVisitor(const ConstOsmMapPtr& map, vector<const Match*>& result,
    ConstMatchThresholdPtr mt, boost::shared_ptr<PluginContext> script,
                     ElementCriterionPtr filter = ElementCriterionPtr()) :
    _map(map),
    _result(result),
    _mt(mt),
    _script(script),
    _filter(filter),
    _customSearchRadius(-1.0)
  {
    _neighborCountMax = -1;
    _neighborCountSum = 0;
    _elementsEvaluated = 0;
    _maxGroupSize = 0;
    _numElementsVisited = 0;
    _numMatchCandidatesVisited = 0;
    _taskStatusUpdateInterval = ConfigOptions().getTaskStatusUpdateInterval();

    Isolate* current = v8::Isolate::GetCurrent();
    HandleScope handleScope(current);
    Context::Scope context_scope(_script->getContext(current));
    Handle<Object> plugin = getPlugin();
    _candidateDistanceSigma = getNumber(plugin, "candidateDistanceSigma", 0.0, 1.0);

    //this is meant to have been set externally in a js rules file
    _customSearchRadius = getNumber(plugin, "searchRadius", -1.0, 15.0);
    LOG_VART(_customSearchRadius);

    Handle<Value> value = plugin->Get(toV8("getSearchRadius"));
    if (value->IsUndefined())
    {
      // pass
    }
    else if (value->IsFunction() == false)
    {
      throw HootException("getSearchRadius is not a function.");
    }
    else
    {
      _getSearchRadius.Reset(current, Handle<Function>::Cast(value));
    }
  }
예제 #30
0
geos::geom::Coordinate GeoJSONReader::getCoordinate(Handle<Value> value, bool acceptArrayOnly) {

    bool isArray = value->IsArray();

    if (acceptArrayOnly) {
        if (!isArray)
            throw "A coordinate must be an instance of Array";


    }
    else {
        if (
            !isArray
            && !value->IsNull()
            && !value->IsUndefined()
        )
            throw "A coordinate must be an instance of Array or null";


        if (!isArray)
            return geos::geom::Coordinate::getNull();
    }


    Handle<Array> array = Handle<Array>::Cast(value);
    uint32_t length = array->Length();
    if (length < 2)
        throw "A coordinate's length must be >= 2";


    geos::geom::Coordinate coord;

    coord.x = valueToDouble(array->Get(0));
    coord.y = valueToDouble(array->Get(1));
    if (length > 2) {
        coord.z = valueToDouble(array->Get(2));
    }
    precisionModel->makePrecise(&coord);

    return coord;
}