예제 #1
0
void
test_Exception()
{
  HandleScope handle_scope;

  Persistent<Context> context = Context::New();
  Handle<Script> script = Script::New(String::New("function foo(x) { throw x; };"));

  Context::Scope scope(context);
  TryCatch trycatch;

  Handle<Value> v = script->Run();
  do_check_true(!v.IsEmpty());
  do_check_true(!trycatch.HasCaught());
  Handle<Function> fn = context->Global()->Get(String::NewSymbol("foo")).As<Function>();
  do_check_true(!fn.IsEmpty());
  Local<Value> args[1] = { Integer::New(4) };
  v = fn->Call(context->Global(), 1, args);
  do_check_true(v.IsEmpty());
  do_check_true(trycatch.HasCaught());
  Handle<Value> exn = trycatch.Exception();
  do_check_true(exn->IsInt32());
  do_check_eq(exn->Int32Value(), 4);

  context.Dispose();
}
예제 #2
0
// Executes a string within the current v8 context.
bool ExecuteString(Handle<String> source) 
{
	TryCatch tryCatch;
    
	Handle<Script> script = Script::Compile(source);
    
	if (script.IsEmpty()) {
        ReportException(&tryCatch);
		return false;
        
	} else {
		Handle<Value> result = script->Run();
		if (result.IsEmpty()) {
            ReportException(&tryCatch);
			return false;
            
		} else {
//			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 = ToCString(str);
//				printf("%s\n", cstr);
//                delete cstr;
//			}
			return true;
		}
	}
}
예제 #3
0
// parse string returned by $self->to_js() into function
void
V8Context::fixup_prototype(Handle<Object> prototype) {
    Handle<Value> val = prototype->Get(string_to_js);

    if (val.IsEmpty() || !val->IsFunction())
        return;

    TryCatch try_catch;

    Handle<Value> to_js = Handle<Function>::Cast(val)->Call(context->Global(), 0, NULL);
    Handle<Script> script = Script::Compile(to_js->ToString());

    if (try_catch.HasCaught()) {
        set_perl_error(try_catch);
    } else {
        Handle<Value> val = script->Run();

        if (val.IsEmpty() || !val->IsFunction()) {
            set_perl_error(try_catch);
        }
        else {
            prototype->Set(string_to_js, val);
        }
    }
}
Handle<Value> Ti::TiProxy::_Setter (Local<String> property, Local<Value> value, const AccessorInfo& info)
{
	HandleScope handleScope;
	// Ti::TiHelper::LogInternal(QString("Property Setter: ").append(Ti::TiHelper::QStringFromValue(property)));

	// Todo: Come back to this later
	// if(value == info.Holder()->Get(property)) {
	//	 Ti::TiHelper::LogInternal(QString("Already set: ").append(Ti::TiHelper::QStringFromValue(property)));
	//	 return value;
	// }


	Handle<Object> obj = Handle<Object>::Cast(info.Holder());
	// Todo: come back to this - might not be allowing GC to collect proxies
	obj->ForceSet(property, value);
	// for example. scrollView.views = [a,b,c]
	// scrollView.remove(a) <--- removed from view, but still in array
	Handle<External> proxyObject = Handle<External>::Cast(obj->GetHiddenValue(String::New("module")));
	if(proxyObject.IsEmpty())
		proxyObject = Handle<External>::Cast(obj->GetHiddenValue(String::New("proxy")));

	if(proxyObject.IsEmpty())
		return value;

	Ti::TiProxy* tiProxy = static_cast<Ti::TiProxy*>(proxyObject->Value());
	if(tiProxy->properties.contains(Ti::TiHelper::QStringFromValue(property)))
	{

		Ti::TiProperty *prop = tiProxy->properties[Ti::TiHelper::QStringFromValue(property)];
		return handleScope.Close(prop->setValue(value));
	}

	return value;
}
예제 #5
0
파일: v8-gl.cpp 프로젝트: cscott/v8-gl
bool exec(string file) {
  HandleScope handle_scope;
  Handle<String> source = ReadFile(file);

  if (source.IsEmpty()) {
	fprintf(stderr, "Error reading '%s'.\n", file.c_str());
	return false;
  }

  // We're just about to compile the script; set up an error handler to
  // catch any exceptions the script might throw.
  TryCatch try_catch;

  // Compile the script and check for errors.
  Handle<Script> compiled_script = Script::Compile(source,
						   String::New(file.c_str()));
  if (compiled_script.IsEmpty()) {
	V8GL::ReportException(&try_catch);
	// The script failed to compile; bail out.
	return false;
  }

  // Run the script!
  Handle<Value> result = compiled_script->Run();
  if (result.IsEmpty()) {
	// The TryCatch above is still in effect and will have caught the error.
	assert(try_catch.HasCaught());
	V8GL::ReportException(&try_catch);
	// Running the script failed; bail out.
	return false;
  }
  return true;
}
예제 #6
0
파일: V8.cpp 프로젝트: kenahoo/V8
// [[Rcpp::export]]
std::string context_eval(std::string src, Rcpp::XPtr< v8::Persistent<v8::Context> > ctx){
  // Test if context still exists
  if(!ctx)
    throw std::runtime_error("Context has been disposed.");

  // Create a scope
  HandleScope handle_scope;
  Context::Scope context_scope(*ctx);

  // Compile source code
  TryCatch trycatch;
  Handle<Script> script = compile_source(src);
  if(script.IsEmpty()) {
    Local<Value> exception = trycatch.Exception();
    String::AsciiValue exception_str(exception);
    throw std::invalid_argument(*exception_str);
  }

  // Run the script to get the result.
  Handle<Value> result = script->Run();
  if(result.IsEmpty()){
    Local<Value> exception = trycatch.Exception();
    String::AsciiValue exception_str(exception);
    throw std::runtime_error(*exception_str);
  }

  // Convert result to UTF8.
  String::Utf8Value utf8(result);
  return *utf8;
}
예제 #7
0
파일: Interface.cpp 프로젝트: amolmk/anode
int Interface::UserInvoke(JNIEnv *jniEnv, Handle<Object> target, int opIdx, jobjectArray jArgs, jobject *jResult) {
  HandleScope scope;
  TryCatch tryCatch;
  Operation *op = operations->addr(opIdx);
  int result = OK;
  for(int i = 0; result == OK && i < op->argCount; i++) {
      result = conv->ToV8Value(jniEnv, jniEnv->GetObjectArrayElement(jArgs, i), op->argTypes[i], &op->vArgs[i]);
  }
  if(result == OK) {
    Handle<Value> vRes;
    if(target->IsFunction() && parent == 0 && operations->getLength() == 1) {
      /* invoke as function if target is a function, and interface delcares only one operation */
      vRes = (Handle<Function>::Cast(target))->Call(target, op->argCount, op->vArgs);
    } else {
      /* locate the method and invoke that */
      Handle<Value> vMethod = target->Get(op->name);
      if(!vMethod.IsEmpty() && vMethod->IsFunction()) {
        vRes = Handle<Function>::Cast(vMethod)->Call(target, op->argCount, op->vArgs);
      }
    }
    if(!vRes.IsEmpty() && op->type != TYPE_UNDEFINED) {
      jobject ob;
      result = conv->ToJavaObject(jniEnv, vRes, op->type, &ob);
      if(result == OK) {
        *jResult = ob;
      }
    }
  }
  if(tryCatch.HasCaught()) {
    result = ErrorJS;
    tryCatch.Reset();
  }
  return result;
}
예제 #8
0
bool SMJS_Plugin::RunString(const char* name, const char *source, bool asGlobal){
	HandleScope handle_scope(isolate);
	Context::Scope context_scope(context);

	TryCatch try_catch;
	v8::ScriptOrigin origin(String::New(name), v8::Integer::New(0), v8::Integer::New(0));
	Handle<Script> script;
	if(asGlobal){
		script = Script::Compile(v8::String::New(source), &origin);
	}else{
		char *buffer = new char[strlen(source) + 100];
		strcpy(buffer, "(function(global){");
		strcat(buffer, source);
		strcat(buffer, "})(this);");
		script = Script::Compile(v8::String::New(buffer), &origin);
		delete buffer;
	}

	if(script.IsEmpty()) {
		// Print errors that happened during compilation.
		ReportException(&try_catch);
		return false;
	} else {
		Handle<Value> result = script->Run();
		if (result.IsEmpty()) {
			ReportException(&try_catch);
			return false;
		}

		return true;
	}
}
예제 #9
0
Handle<Value> TypedArray::New(GDALDataType type, unsigned int length)  {
	NanEscapableScope();

	Handle<Value> val;
	Handle<Function> constructor;
	Local<Object> global = NanGetCurrentContext()->Global();

	const char *name;
	switch(type) {
		case GDT_Byte:    name = "Uint8Array";   break;
		case GDT_Int16:   name = "Int16Array";   break;
		case GDT_UInt16:  name = "Uint16Array";  break;
		case GDT_Int32:   name = "Int32Array";   break;
		case GDT_UInt32:  name = "Uint32Array";  break;
		case GDT_Float32: name = "Float32Array"; break;
		case GDT_Float64: name = "Float64Array"; break;
		default: 
			NanThrowError("Unsupported array type"); 
			return NanEscapeScope(NanUndefined());
	}


	// make ArrayBuffer
	val = global->Get(NanNew("ArrayBuffer"));

	if(val.IsEmpty() || !val->IsFunction()) {
		NanThrowError("Error getting ArrayBuffer constructor");
		return NanEscapeScope(NanUndefined());
	}

	constructor = val.As<Function>();
	Local<Value> size = NanNew<Integer>(length * GDALGetDataTypeSize(type) / 8);
	Local<Value> array_buffer = constructor->NewInstance(1, &size);

	if(array_buffer.IsEmpty() || !array_buffer->IsObject()) {
		NanThrowError("Error allocating ArrayBuffer");
		return NanEscapeScope(NanUndefined());
	}


	// make TypedArray
	val = global->Get(NanNew(name));

	if(val.IsEmpty() || !val->IsFunction()) {
		NanThrowError("Error getting typed array constructor");
		return NanEscapeScope(NanUndefined());
	}

	constructor = val.As<Function>();
	Local<Object> array = constructor->NewInstance(1, &array_buffer);

	if(array.IsEmpty() || !array->IsObject()) {
		NanThrowError("Error creating TypedArray");
		return NanEscapeScope(NanUndefined());
	}

	return NanEscapeScope(array);
}
예제 #10
0
bool IsFunctionTemplate(Handle<Value> v) {
  if (v.IsEmpty())
    return false;
  Handle<Object> o = v->ToObject();
  if (o.IsEmpty())
    return false;
  JSObject *obj = **o;
  return &gFunctionTemplateClass == JS_GET_CLASS(cx(), obj);
}
예제 #11
0
bool
FunctionTemplate::HasInstance(Handle<Value> v)
{
  Handle<Object> object = v->ToObject();
  if (object.IsEmpty())
    return false;
  Handle<Object> proto = object->GetPrototype().As<Object>();
  if (proto.IsEmpty()) {
    return false;
  }
  return InternalObject().Equals(proto);
}
예제 #12
0
Persistent<Context> Context::New(
      ExtensionConfiguration* config,
      Handle<ObjectTemplate> global_template,
      Handle<Value> global_object) {
  if (!global_template.IsEmpty() || !global_object.IsEmpty())
    UNIMPLEMENTEDAPI(Persistent<Context>());
  JSObject *global = JS_NewGlobalObject(cx(), &global_class);

  JS_InitStandardClasses(cx(), global);

  return Persistent<Context>(new Context(global));
}
예제 #13
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;
}
예제 #14
0
size_t FSCURL::FileCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
	FSCURL *obj = static_cast<FSCURL *>(data);
	register unsigned int realsize = (unsigned int) (size * nmemb);
	uint32_t argc = 0;
	Handle<Value> argv[4];

	if (!obj) {
		return 0;
	}

	HandleScope handle_scope(obj->GetIsolate());
	Handle<Function> func;
	
	if (!obj->_function.IsEmpty()) {
		func = Local<Function>::New(obj->GetIsolate(), obj->_function);
	}

	if (!func.IsEmpty()) {
		char *ret;
		if (ptr) {
			argv[argc++] = String::NewFromUtf8(obj->GetIsolate(), (char *)ptr);
		} else {
			argv[argc++] = String::NewFromUtf8(obj->GetIsolate(), "");
		}
		if (!obj->_user_data.IsEmpty()) {
			argv[argc++] = Local<Value>::New(obj->GetIsolate(), Persistent<Value>::Cast(obj->_user_data));
		}

		Handle<Value> res = func->Call(obj->GetIsolate()->GetCurrentContext()->Global(), argc, argv);

		if (!res.IsEmpty()){
			obj->_ret.Reset(obj->GetIsolate(), res);
		} else {
			obj->_ret.Reset();
		}

		String::Utf8Value str(Local<Value>::New(obj->GetIsolate(), res));

		if ((ret = *str)) {
			if (!strcmp(ret, "true") || !strcmp(ret, "undefined")) {
				return realsize;
			} else {
				return 0;
			}
		}
	}

	return realsize;
}
예제 #15
0
파일: v8.cpp 프로젝트: xk/v8monkey
Persistent<Context> Context::New(
      ExtensionConfiguration* config,
      Handle<ObjectTemplate> global_template,
      Handle<Value> global_object) {
  if (!global_object.IsEmpty())
    UNIMPLEMENTEDAPI(Persistent<Context>());
  JSObject *global = JS_NewGlobalObject(cx(), &global_class);

  JS_InitStandardClasses(cx(), global);
  if (!global_template.IsEmpty()) {
    JS_SetPrototype(cx(), global, JSVAL_TO_OBJECT(global_template->native()));
  }

  return Persistent<Context>(new Context(global));
}
예제 #16
0
bool bind_Signals_Signal(Handle<Object> parent)
{
    ScriptingManager* pManager = ScriptingManager::getSingletonPtr();

    Handle<FunctionTemplate> signal = pManager->getClassTemplate("Athena.Signals.Signal");

    if (signal.IsEmpty())
    {
        // Declaration of the class
        signal = FunctionTemplate::New(Signal_New);
        signal->InstanceTemplate()->SetInternalFieldCount(1);

        // Attributes
        AddAttribute(signal, "disconnected", Signal_IsDisconnected, 0);

        // Methods
        AddMethod(signal, "connect",         Signal_Connect);
        AddMethod(signal, "disconnect",      Signal_Disconnect);
        AddMethod(signal, "fire",            Signal_Fire);

        pManager->declareClassTemplate("Athena.Signals.Signal", signal);
    }

    // Add the class to the parent
    return parent->Set(String::New("Signal"), signal->GetFunction());
}
예제 #17
0
bool bind_Base(Handle<Object> parent)
{
    ScriptingManager* pManager = ScriptingManager::getSingletonPtr();

    Handle<FunctionTemplate> base = pManager->getClassTemplate("Tests.Base");

    if (base.IsEmpty())
    {
        // Declaration of the class
        base = FunctionTemplate::New(Base_New);
        base->InstanceTemplate()->SetInternalFieldCount(1);

        // Attributes
        AddAttribute(base, "a", Base_GetA, Base_SetA);

        // Methods
        AddMethod(base, "f", Base_F);
        AddMethod(base, "g", Base_G);

        // Register the class with the Scripting Manager
        pManager->declareClassTemplate("Tests.Base", base);
    }

    // Add the class to the parent
    return parent->Set(String::New("Base"), base->GetFunction());
}
예제 #18
0
   void ScriptSystem::Tick(const dtEntity::Message& m)
   {
      if(mGlobalTickFunction.IsEmpty())
      {
         return;
      }

      HandleScope scope;  
      Context::Scope context_scope(GetGlobalContext());

      const dtEntity::TickMessage& msg = static_cast<const dtEntity::TickMessage&>(m);

      TryCatch try_catch;
      Handle<Value> argv[3] = {
         Number::New(msg.GetDeltaSimTime()),
         Number::New(msg.GetSimulationTime()),
         Uint32::New(osg::Timer::instance()->time_m())
      };

      Handle<Value> ret = mGlobalTickFunction->Call(mGlobalTickFunction, 3, argv);

      if(ret.IsEmpty())
      {
         ReportException(&try_catch);
      }

   }
예제 #19
0
파일: v8_utils.cpp 프로젝트: lizalbin/mongo
    std::ostream& operator<<( std::ostream &s, const v8::TryCatch * try_catch ){
        HandleScope handle_scope;
        v8::String::Utf8Value exception(try_catch->Exception());
        Handle<v8::Message> message = try_catch->Message();
    
        if (message.IsEmpty()) {
            s << *exception << endl;
        } 
        else {

            v8::String::Utf8Value filename(message->GetScriptResourceName());
            int linenum = message->GetLineNumber();
            cout << *filename << ":" << linenum << " " << *exception << endl;

            v8::String::Utf8Value sourceline(message->GetSourceLine());
            cout << *sourceline << endl;

            int start = message->GetStartColumn();
            for (int i = 0; i < start; i++)
                cout << " ";

            int end = message->GetEndColumn();
            for (int i = start; i < end; i++)
                cout << "^";

            cout << endl;
        }    

        //if ( try_catch->next_ ) // disabled for v8 bleeding edge
        //    s << try_catch->next_;

        return s;
    }
예제 #20
0
void
test_obj_defprop() {
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();

  Context::Scope context_scope(context);

  Handle<Object> obj = Object::New();
  Handle<Value> data = Integer::New(2);
  obj->SetAccessor(String::New("myprop"), ReadTestVal, WriteTestVal, data);
  Local<Object> global = context->Global();
  global->Set(String::New("testobj"), obj);

  Handle<String> source = String::New("var n = testobj.myprop; testobj.myprop = (n+9); testobj.myprop");

  // Compile the source code.
  Handle<Script> script = Script::Compile(source);

  // Run the script to get the result.
  Handle<Value> result = script->Run();

  do_check_true(!result.IsEmpty());
  do_check_true(result->IsInt32());
  JSInt32 i = result->Int32Value();
  do_check_eq(12, i);
  context.Dispose();
}
예제 #21
0
void
test_obj_propexn() {
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();

  Context::Scope context_scope(context);

  Handle<Object> obj = Object::New();
  obj->SetAccessor(String::New("myprop"), ReadExn, WriteExn);
  Local<Object> global = context->Global();
  global->Set(String::New("testobj"), obj);

  Handle<String> source = String::New("var n = 0;"
                                      "try { testobj.myprop; } catch (e) { n += e; };"
                                      "try { testobj.myprop = (n+9); } catch (e) { n += e; }; n");

  // Compile the source code.
  Handle<Script> script = Script::Compile(source);

  TryCatch trycatch;
  // Run the script to get the result.
  Handle<Value> result = script->Run();

  do_check_false(result.IsEmpty());
  do_check_true(result->IsInt32());
  do_check_false(trycatch.HasCaught());
  JSInt32 i = result->Int32Value();
  do_check_eq(13, i);
  context.Dispose();
}
예제 #22
0
Persistent<Script> *JsEngine::CompileScript(const uint16_t* str, const uint16_t *resourceName, jsvalue *error) {
	Locker locker(isolate_);
	Isolate::Scope isolate_scope(isolate_);
	
    HandleScope scope;
	TryCatch trycatch;
		
	(*global_context_)->Enter();

	Handle<String> source = String::New(str);
	Handle<Script> script;

	if (resourceName != NULL) {
		Handle<String> name = String::New(resourceName);
		script = Script::New(source, name);  
	} else {
		script = Script::New(source);  
	}

	if (script.IsEmpty()) {
		*error = ErrorFromV8(trycatch);
	}
	
	(*global_context_)->Exit();
	
	Persistent<Script> *pScript = new Persistent<Script>(Persistent<Script>::New(script));

	return pScript;
}
예제 #23
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;
}
예제 #24
0
void TiV8Event::fire(void* fireDataObject)
{
    HandleScope handleScope;
    if (function_.IsEmpty())
    {
        return;
    }
    Handle<Context> context = function_->CreationContext();
    Context::Scope context_scope(context);
    Handle<Value> result;
    TryCatch tryCatch;
    if (fireDataObject == NULL)
    {
        //make a function call with no arguments
        result = function_->Call(context->Global(), 0, 0);
    }
    else
    {
        Handle<Object> dataObject = *((Persistent<Object>*) fireDataObject);
        dataObject->Set(String::New("source"), source_);
        // This calls the Javascript function that handles the event. It has
        // the form of: function(e) {...}
        // The "1" in the following function refers to the number of arguments that
        // are passed the the Javascript function. In this case there is one
        // argument: "e". The argument is an object with properties relating
        // to the event that was triggered.
        result = function_->Call(source_, 1, (Handle<Value>*) &dataObject);
    }
    if (result.IsEmpty())
    {
        Ti::TiErrorScreen::ShowWithTryCatch(tryCatch);
    }
}
예제 #25
0
파일: v8base.cpp 프로젝트: pgmsoul/GitLib
	//*,{
	//	"type":"function",
	//	"name":"setConfig(callback,[filename])",
	//	"text":"读取或设置配置文件,配置文件是一个 Json 格式的文本文件,可以是 utf-8 获取 ansi 编码。",
	//	"param":[
	//		{
	//			"type":"function",
	//			"name":"callback(cfg)",
	//			"text":"setConfig 函数如果成功,会触发这个回调函数,cfg 是一个对象,它的属性就是配置内容,对这个对象的任何更改最后都会作为 Json 格式保存到配置文件。"
	//		},
	//		{
	//			"type":"string",
	//			"name":"[filename]",
	//			"text":"配置文件名,缺省是和脚本同路径同名的一个后缀为“.json”的文本文件,如果指定了文件名,则读取和保存对应的文件。"
	//		}
	//	],
	//	"return":{
	//		"type":"boolean",
	//		"text":"如果成功打开了配置文件,函数返回 true,否则返回 undefined。"
	//	}
	//}//*
	Handle<Value> setConfig(const Arguments& args){
		HandleScope stack;
		while(true){
			if(args.Length()<1) break;
			if(!args[0]->IsFunction()) break;
			cs::String file;
			if(args.Length()>1)
				GetString(args[1],file);
			cs::Config cfg(file);
			cs::Json* json = cfg.Lock();
			if(!json) break;

			json->ToString(file,false);
			Handle<Object> glb = GetGlobal();
			Handle<Object> JSON = glb->Get(NEW_STR(JSON))->ToObject();
			Handle<Function> parse = Handle<Function>::Cast(JSON->Get(NEW_STR(parse)));
			Handle<Function> stringify = Handle<Function>::Cast(JSON->Get(NEW_STR(stringify)));
			Handle<Function> callback = Handle<Function>::Cast(args[0]);
			Handle<Value> argv[3];
			argv[0] = NEW_WSTR(file.Handle());
			Handle<Value> v = parse->Call(JSON,1,argv);
			if(v.IsEmpty()||!v->IsObject()) v = Object::New();
			argv[0] = v;
			CallFunc(glb,callback,1,argv);
			v = stringify->Call(JSON,1,argv);
			GetString(v,file);
			json->Parse(file);
			return True();
		}
		return Undefined();
	}
예제 #26
0
   v8::Handle<v8::Function> CreateDebugDrawManager(Handle<Context> context)
   {
      v8::HandleScope handle_scope;

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

        templt = FunctionTemplate::New();
        templt->SetClassName(String::New("DebugDrawManager"));
        templt->InstanceTemplate()->SetInternalFieldCount(1);

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

        proto->Set("addAABB", FunctionTemplate::New(DebugDrawManagerAddAABB));
        proto->Set("addCircle", FunctionTemplate::New(DebugDrawManagerAddCircle));
        proto->Set("addCross", FunctionTemplate::New(DebugDrawManagerAddCross));
        proto->Set("addLine", FunctionTemplate::New(DebugDrawManagerAddLine));
        proto->Set("addLines", FunctionTemplate::New(DebugDrawManagerAddLines));
        proto->Set("addSphere", FunctionTemplate::New(DebugDrawManagerAddSphere));
		  proto->Set("addString", FunctionTemplate::New(DebugDrawManagerAddString));
        proto->Set("addTriangle", FunctionTemplate::New(DebugDrawManagerAddTriangle));
        proto->Set("clear", FunctionTemplate::New(DebugDrawManagerClear));
        proto->Set("isEnabled", FunctionTemplate::New(DebugDrawManagerIsEnabled));
        proto->Set("setEnabled", FunctionTemplate::New(DebugDrawManagerSetEnabled));
        proto->Set("toString", FunctionTemplate::New(DebugDrawManagerToString));
        
        GetScriptSystem()->SetTemplateBySID(s_debugDrawWrapper, templt);
      }
      return handle_scope.Close(templt->GetFunction());
   }
예제 #27
0
파일: jscontext.cpp 프로젝트: killf/V8Net
jsvalue JsContext::Execute(JsScript *jsscript)
{
    jsvalue v;

    Locker locker(isolate_);
    Isolate::Scope isolate_scope(isolate_);
    (*context_)->Enter();
        
    HandleScope scope;
    TryCatch trycatch;
   
	Handle<Script> script = (*jsscript->GetScript());

	if (!script.IsEmpty()) {
		Local<Value> result = script->Run();
	
		if (result.IsEmpty())
			v = engine_->ErrorFromV8(trycatch);
		else
			v = engine_->AnyFromV8(result);        
	}

    (*context_)->Exit();
	return v;     
}
예제 #28
0
bool
WeechatJsV8::execScript()
{
    v8::TryCatch trycatch;

    this->context = Context::New(NULL, this->global);
    Context::Scope context_scope(this->context);
    Handle<Script> script = Script::Compile(this->source);

    if (script.IsEmpty())
    {
        PRINT_EXCEPTION;
        return false;
    }
    else
    {
        Local<Value> value = script->Run();
        if (value.IsEmpty())
        {
            PRINT_EXCEPTION;
            return false;
        }
    }

    return true;
}
예제 #29
0
SV*
V8Context::eval(SV* source, SV* origin) {
    HandleScope handle_scope;
    TryCatch try_catch;
    Context::Scope context_scope(context);

    Handle<Script> script = Script::Compile(
        sv2v8str(source),
        origin ? sv2v8str(origin) : String::New("EVAL")
    );

    if (try_catch.HasCaught()) {
        set_perl_error(try_catch);
        return &PL_sv_undef;
    } else {
        thread_canceller canceller(time_limit_);
        Handle<Value> val = script->Run();

        if (val.IsEmpty()) {
            set_perl_error(try_catch);
            return &PL_sv_undef;
        } else {
            sv_setsv(ERRSV,&PL_sv_undef);
            return v82sv(val);
        }
    }
}
예제 #30
0
파일: Conv.cpp 프로젝트: Armen138/anode
/* called by the Java environment for objects that have been finalized */
void Conv::releaseV8Handle(JNIEnv *jniEnv, Persistent<Object> val, int type) {
  HandleScope scope;
  Handle<String> sHiddenKey;
  Interface *interface = 0;
  ArrayType *arr = 0;
  if(type == -1) {
    sHiddenKey = sObjectHiddenKey;
  } else if(isArray(type)) {
    arrayConv->GetRefsForComponentType(jniEnv, getComponentType(type), &arr);
    sHiddenKey = arr->getHiddenKey();
  } else if(isInterface(type)) {
    interface = env->getInterface(getClassId(type));
    sHiddenKey = interface->getHiddenKey();
  }
  //LOGV("releaseV8Handle; interface = %p; getting hidden value; sHiddenKey = %p\n", interface, sHiddenKey);
  if(!sHiddenKey.IsEmpty()) {
    Local<Value> hiddenVal = val->GetHiddenValue(sHiddenKey);
    if(!hiddenVal.IsEmpty() && !hiddenVal->IsUndefined()) {
      jobject extRef = (jobject)External::Unwrap(hiddenVal);
      Conv::deleteGlobalRef(jniEnv, extRef);
      val->DeleteHiddenValue(sHiddenKey);
      if(interface) {
        while((interface = interface->getParent())) {
          val->DeleteHiddenValue(interface->getHiddenKey());
        }
      }
    }
  }
  val.Dispose();
}