void V8Engine::init()
{
    Logging::log(Logging::DEBUG, "V8Engine::init:\r\n");
    INDENT_LOG(Logging::DEBUG);

    HandleScope handleScope;

    // Create a template for the global object.
    Logging::log(Logging::DEBUG, "Creating global\r\n");

//    _global = ObjectTemplate::New();

    Logging::log(Logging::DEBUG, "Creating context\r\n");

    context = Context::New(); //NULL, _global);

    context->Enter();

    // Create our internal wrappers

    Logging::log(Logging::DEBUG, "Creating wrapper for global\r\n");

    globalValue = ScriptValuePtr(new V8Value(this, context->Global()));

#if 0
    // Setup debugger, if required - XXX Doesn't work

//    Debug::SetDebugEventListener(debuggerListener);
//    runFile("src/thirdparty/v8/src/debug-delay.js"); // FIXME: remove hardcoded src/..
    runFile("src/javascript/intensity/V8Debugger.js"); // FIXME: remove hardcoded src/javascript
             
    v8::Handle<v8::Value> result =
        ((V8Value*)(getGlobal()->getProperty("__debuggerListener").get()))->value;
    assert(result->IsObject());
    Local<Object> debuggerListener = result->ToObject();
    assert(debuggerListener->IsFunction());

    Debug::SetDebugEventListener(debuggerListener);

    runScript("Debug.setBrzzzzzzzzzeakOnException()");

    Local<String> source = String::New(
        "temp = function () { Debug.setBreakOnException(); return 5098; } "
    );
    Local<Script> code = Script::Compile(source);
    Local<Value> result2 = code->Run();
    printV8Value(result2, true);
    assert(result2->IsObject());
    Local<Object> obj = result2->ToObject();
    assert(obj->IsFunction());
    Local<Function> func = Function::Cast(*obj);
    Handle<Value> output = Debug::Call(func);
    printV8Value(output, true);
assert(0);
#endif

    Logging::log(Logging::DEBUG, "V8Engine::init complete.\r\n");
}
Beispiel #2
0
/* zipfile.save(callback) */
Handle<Value> ZipFile::Save(const Arguments& args)
{
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    if (zf->Busy())
      return ThrowException(Exception::Error(String::New("Zipfile already in use..")));

    Local<Value> cb = args[0];
    if (!cb->IsFunction())
      return ThrowException(Exception::Error(
            String::New("Second argument should be a callback function.")));

    save_closure_t *save = new save_closure_t;

    save->done = false;
    save->zf = zf;
    save->error = NULL;
    save->save_cb = Persistent<Function>::New(Handle<Function>::Cast(cb));
    pthread_mutex_init(&save->mutex, NULL);

    saving_closures.insert(save);

    zf->saving = true;
    zf->Ref();

    ev_ref(EV_DEFAULT_UC);
    pthread_create(&save->thread, NULL, Save_Thread, save);
    
    return Undefined();
}
Beispiel #3
0
JNIEXPORT void JNICALL
Java_org_appcelerator_kroll_runtime_v8_V8Object_nativeSetWindow
	(JNIEnv *env, jobject javaKrollWindow, jlong ptr, jobject javaWindow)
{
	HandleScope scope(V8Runtime::v8_isolate);
	titanium::JNIScope jniScope(env);

	Local<Object> jsKrollWindow;
	if (ptr != 0) {
		titanium::Proxy* proxy = (titanium::Proxy*) ptr;
		jsKrollWindow = proxy->handle(V8Runtime::v8_isolate);
	} else {
		jsKrollWindow = TypeConverter::javaObjectToJsValue(V8Runtime::v8_isolate, env, javaKrollWindow).As<Object>();
	}

	Local<Value> setWindowValue = jsKrollWindow->Get(STRING_NEW(V8Runtime::v8_isolate, "setWindow"));
	if (!setWindowValue->IsFunction()) {
		return;
	}

	Local<Function> setWindow = setWindowValue.As<Function>();

	Local<Value> jsWindow = TypeConverter::javaObjectToJsValue(V8Runtime::v8_isolate, env, javaWindow);

	TryCatch tryCatch(V8Runtime::v8_isolate);
	if (!jsWindow->IsNull()) {
		Local<Value> args[] = { jsWindow };
		setWindow->Call(V8Runtime::v8_isolate->GetCurrentContext(), jsKrollWindow, 1, args);
	}

	if (tryCatch.HasCaught()) {
		V8Util::openJSErrorDialog(V8Runtime::v8_isolate, tryCatch);
		V8Util::reportException(V8Runtime::v8_isolate, tryCatch);
	}
}
Beispiel #4
0
void ScriptGame::_mouseMoved( const float x, const float y )
{
	HandleScope hs;
	PersistentContext ctx = MagnetiteCore::Singleton->getScriptManager()->getContext();
	Context::Scope scope( ctx );
	
	bool eval = false;
	if( !mScriptObject.IsEmpty() && mScriptObject->Has( String::New("mouseMoved") ) )
	{
		Local<Value> onLoadVal = mScriptObject->Get( String::New("mouseMoved") );
		if( onLoadVal->IsFunction() )
		{
			TryCatch ct;
			Local<Function> onLoad = Local<Function>::Cast( onLoadVal );
			Handle<Value> args[2];
			args[0] = Number::New(x);
			args[1] = Number::New(y);
			auto r = onLoad->Call( mScriptObject, 2, args );
			if( r.IsEmpty() ) {
				Util::log(strize(ct.StackTrace()));
			}
			else 
			{
				eval = r->BooleanValue();
			}
		}
	}
	if(!eval && getLocalPlayer() ) {
		mPlayer->getCamera()->pitch( y );
		mPlayer->getCamera()->yaw( x );
	}
}
Beispiel #5
0
// コンストラクタ呼び出し共通処理
tjs_error
TJSInstance::createMethod(Isolate *isolate, Local<Object> &obj, const tjs_char *membername, iTJSDispatch2 **result, tjs_int numparams, tTJSVariant **param)
{
	if (membername) {
		return TJS_E_MEMBERNOTFOUND;
	}

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

	if (!obj->IsFunction()) {
		return TJS_E_NOTIMPL;
	}
	
	// 関数抽出
	Local<Function> func = Local<Function>::Cast(obj->ToObject());
	// 引数
	Handle<Value> *argv = new Handle<Value>[numparams];
	for (int i=0;i<numparams;i++) {
		argv[i] = toJSValue(isolate, *param[i]);
	}
	Local<Object> ret = func->NewInstance(numparams, argv);
	delete argv;
	
	if (ret.IsEmpty()) {
		JSEXCEPTION(isolate, &try_catch);
	} else {
		if (result) {
			*result = toVariant(isolate, ret);
		}
	}
	return TJS_S_OK;
}
Beispiel #6
0
/**
 * TJSオブジェクトのオーバライド処理
 * @param args 引数
 * @return 結果
 */
void
TJSInstance::tjsOverride(const FunctionCallbackInfo<Value>& args)
{
	Isolate *isolate = args.GetIsolate();
	HandleScope handle_scope(isolate);
	tTJSVariant instance;
	if (getVariant(isolate, instance, args.This())) {
		if (args.Length() > 0) {
			Local<Value> func = args.Length() > 1 ? args[1] : args.This()->Get(args[0]);
			if (func->IsFunction()) {
				tTJSVariant value = toVariant(isolate, func->ToObject(), args.This());
				String::Value methodName(args[0]);
				tjs_error error;
				if (TJS_FAILED(error = instance.AsObjectClosureNoAddRef().PropSet(TJS_MEMBERENSURE, *methodName, NULL, &value, NULL))) {
					args.GetReturnValue().Set(ERROR_KRKR(isolate, error));
					return;
				}
				args.GetReturnValue().Set(Undefined(isolate));
				return;
			}
		}
		args.GetReturnValue().Set(isolate->ThrowException(String::NewFromUtf8(isolate, "not function")));
		return;
	}
	args.GetReturnValue().Set(ERROR_BADINSTANCE(isolate));
}
Beispiel #7
0
// プロパティ取得共通処理
tjs_error
TJSInstance::getProp(Isolate *isolate, Local<Object> &obj, const tjs_char *membername, tTJSVariant *result)
{
	if (!membername) {
		return TJS_E_NOTIMPL;
	}
	
	HandleScope handle_scope(isolate);
	Context::Scope context_scope(getContext());
	TryCatch try_catch;
	
	Local<Value> ret = obj->Get(String::NewFromTwoByte(isolate, membername));
	if (ret.IsEmpty()) {
		return TJS_E_MEMBERNOTFOUND;
	} else {
		if (result) {
			if (ret->IsFunction()) {
				*result = toVariant(isolate, ret->ToObject(), obj);
			} else {
				*result = toVariant(isolate, ret);
			}
		}
	}
	return TJS_S_OK;
}
Beispiel #8
0
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);
  Context::Scope context_scope(context);
  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);
  context.Dispose();
}
Beispiel #9
0
// メソッド呼び出し共通処理
tjs_error
TJSInstance::callMethod(Isolate *isolate, Local<Object> &obj, const tjs_char *membername, tTJSVariant *result, tjs_int numparams, tTJSVariant **param, iTJSDispatch2 *objthis)
{
	HandleScope handle_scope(isolate);
	Context::Scope context_scope(getContext());
	TryCatch try_catch;

	Local<Object> context = membername ? obj : objthis ? toJSValue(isolate, tTJSVariant(objthis))->ToObject() : getContext()->Global();
	Local<Object> method  = membername ? obj->Get(String::NewFromTwoByte(isolate, membername))->ToObject() : obj;

	if (!method->IsFunction()) {
		return TJS_E_NOTIMPL;
	}
	
	// 関数抽出
	Local<Function> func = Local<Function>::Cast(method);
	// 引数
	Handle<Value> *argv = new Handle<Value>[numparams];
	for (int i=0;i<numparams;i++) {
		argv[i] = toJSValue(isolate, *param[i]);
	}
	Local<Value> ret = func->Call(context, numparams, argv);
	delete argv;
	
	if (ret.IsEmpty()) {
		JSEXCEPTION(isolate, &try_catch);
	} else {
		if (result) {
			*result = toVariant(isolate, ret);
		}
	}
	return TJS_S_OK;
}
Beispiel #10
0
int __stdcall wWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPTSTR lpCmdLine,int nCmdShow){
	int rt = -1;
	initContext();
	HandleScope store;
	runJSRes(IDR_JS_STRUCT,L"app.lib");
	Handle<Value> result = runJSFile(L"main.js",L"utf-8");
	if(!result.IsEmpty()){//只有出错的时候才会返回Empty, 否则即使没有返回值, result仍然是Undefined.
		Local<Object> gObj = getGlobal();
		Local<Function> main = GetJSVariant<Function>(gObj,L"main");
		if(main.IsEmpty()){
			//InnerMsg(L"没有发现 main 函数",MT_ERROR);
		}else if(!main->IsFunction()){
			//InnerMsg(L"main 不是函数",MT_ERROR);
		}else{
			TryCatch err;
			Handle<Value> args[1];
			args[0] = String::New((uint16_t*)lpCmdLine);
			Local<Value> r = main->Call(gObj,1,args);
			if(!err.Exception().IsEmpty()){
				ReportError(err);
			}else
				rt = r->Int32Value();
		}
	}
	releaseContext();
	return rt;
}
Beispiel #11
0
void
Image::SetOnerror(Local<String>, Local<Value> val, const AccessorInfo &info) {
  if (val->IsFunction()) {
    Image *img = ObjectWrap::Unwrap<Image>(info.This());
    img->onerror = Persistent<Function>::New(Handle<Function>::Cast(val));
  }
}
Beispiel #12
0
jsvalue JsContext::InvokeProperty(Persistent<Object>* obj, const uint16_t* name, jsvalue args)
{
    jsvalue v;

    Locker locker(isolate_);
    Isolate::Scope isolate_scope(isolate_);
    (*context_)->Enter();
        
    HandleScope scope;    
    TryCatch trycatch;
        
    Local<Value> prop = (*obj)->Get(String::New(name));
    if (prop.IsEmpty() || !prop->IsFunction()) {
        v = engine_->StringFromV8(String::New("property not found or isn't a function"));
        v.type = JSVALUE_TYPE_STRING_ERROR;   
    }
    else {
        std::vector<Local<Value> > argv(args.length);
        engine_->ArrayToV8Args(args, id_, &argv[0]);
        // TODO: Check ArrayToV8Args return value (but right now can't fail, right?)                   
        Local<Function> func = Local<Function>::Cast(prop);
        Local<Value> value = func->Call(*obj, args.length, &argv[0]);
        if (!value.IsEmpty()) {
            v = engine_->AnyFromV8(value);        
        }
        else {
            v = engine_->ErrorFromV8(trycatch);
        }         
    }
    
    (*context_)->Exit();
    
    return v;
}
Beispiel #13
0
	Handle<Value> Texture::On(const Arguments &args)
	{
		HandleScope scope;
		Local<Value> Event;
		Local<Value> Options;
		Local<Value> Callback;
		ClutterActor *instance = ObjectWrap::Unwrap<Texture>(args.This())->_actor;
#if 0
		/* Check arguments */
		if (args.Length() == 2) {
			Event = args[0];
			Callback = args[1];
		} else if (args.Length() == 3) {
			Event = args[0];
			Options = args[1];
			Callback = args[2];
		} else
			return args.This();

		if (!Event->IsNumber()) {
			return ThrowException(Exception::TypeError(
				String::New("first argument must be integer")));
		}

		if (!Callback->IsFunction()) {
			return ThrowException(Exception::TypeError(
				String::New("Second argument must be a callback function")));
		}
#endif
		Actor::On(args);

		return args.This();
	}
Beispiel #14
0
/* static */
void V8Runtime::bootstrap(Local<Context> context)
{
	Isolate* isolate = context->GetIsolate();
	EventEmitter::initTemplate(context);

	Local<Object> kroll = Object::New(isolate);
	krollGlobalObject.Reset(isolate, kroll);
	Local<Array> mc = Array::New(isolate);
	moduleContexts.Reset(isolate, mc);

	KrollBindings::initFunctions(kroll, context);

	SetMethod(isolate, kroll, "log", krollLog);
	// Move this into the EventEmitter::initTemplate call?
	Local<FunctionTemplate> eect = Local<FunctionTemplate>::New(isolate, EventEmitter::constructorTemplate);
	{
		v8::TryCatch tryCatch(isolate);
		Local<Function> eventEmitterConstructor;
		MaybeLocal<Function> maybeEventEmitterConstructor = eect->GetFunction(context);
		if (!maybeEventEmitterConstructor.ToLocal(&eventEmitterConstructor)) {
			titanium::V8Util::fatalException(isolate, tryCatch);
			return;
		}
		kroll->Set(NEW_SYMBOL(isolate, "EventEmitter"), eventEmitterConstructor);
	}

	kroll->Set(NEW_SYMBOL(isolate, "runtime"), STRING_NEW(isolate, "v8"));
	kroll->Set(NEW_SYMBOL(isolate, "DBG"), v8::Boolean::New(isolate, V8Runtime::DBG));
	kroll->Set(NEW_SYMBOL(isolate, "moduleContexts"), mc);

	LOG_TIMER(TAG, "Executing kroll.js");

	TryCatch tryCatch(isolate);
	Local<Value> result = V8Util::executeString(isolate, KrollBindings::getMainSource(isolate), STRING_NEW(isolate, "ti:/kroll.js"));

	if (tryCatch.HasCaught()) {
		V8Util::reportException(isolate, tryCatch, true);
	}
	if (!result->IsFunction()) {
		LOGF(TAG, "kroll.js result is not a function");
		V8Util::reportException(isolate, tryCatch, true);
	}

	// Add a reference to the global object
	Local<Object> global = context->Global();

	// Expose the global object as a property on itself
	// (Allows you to set stuff on `global` from anywhere in JavaScript.)
	global->Set(NEW_SYMBOL(isolate, "global"), global);

	Local<Function> mainFunction = result.As<Function>();
	Local<Value> args[] = { kroll };
	mainFunction->Call(context, global, 1, args);

	if (tryCatch.HasCaught()) {
		V8Util::reportException(isolate, tryCatch, true);
		LOGE(TAG, "Caught exception while bootstrapping Kroll");
	}
}
Beispiel #15
0
	Handle<Object> SorrowContext::SetupInternals(int argc, const char *argv[]) {
		HandleScope scope;
		Local<FunctionTemplate> internals_template = FunctionTemplate::New();
		internals = Persistent<Object>::New(internals_template->GetFunction()->NewInstance());
		
		Local<Object> global = Context::GetCurrent()->Global();
		SET_METHOD(global, "quit",    Quit)
		SET_METHOD(global, "version", Version)
		SET_METHOD(internals, "compile", CompileScript)
        
		if (argc) {
			Local<Array> lineArgs = Array::New(argc-1);
			for (int i = 0; i +1 < argc; i++) {
				lineArgs->Set(Integer::New(i), V8_STR(argv[i+1]));
			}
			internals->Set(V8_STR("args"), lineArgs);
		} else {
			internals->Set(V8_STR("args"), Array::New());
		}

		Handle<Object> libsObject = Object::New();
		LoadNativeLibraries(libsObject);
		internals->Set(V8_STR("stdlib"), libsObject);
        
		Handle<ObjectTemplate> env = ObjectTemplate::New();
		env->SetNamedPropertyHandler(EnvGetter);
		internals->Set(V8_STR("env"), env->NewInstance());
        
		internals->Set(V8_STR("global"), global);
		
		binarytypes = new BinaryTypes(internals);
		iostreams = new IOStreams(internals);

		Filesystem::Initialize(internals);
		Extensions::Initialize(internals);
		

		TryCatch tryCatch;
		Local<Value> func = ExecuteString(V8_STR(sorrow_native), V8_STR("sorrow.js"));
		
		if (tryCatch.HasCaught()) {
			ReportException(&tryCatch);
			exit(10);
		}

		ASSERT_PIN(func->IsFunction(), "sorrow.js main function not found");
		Local<Function> f = Local<Function>::Cast(func);
		
		Local<Value> args[1] = { Local<Value>::New(internals) };
		
		f->Call(global, 1, args);
		
		if (tryCatch.HasCaught())  {
			ReportException(&tryCatch);
			exit(11);
		}

		return internals;
	} // SetupInternals
Beispiel #16
0
void UiWindow::SetOnMessage(Local<String> property, Local<Value> value, const PropertyCallbackInfo<void>& info) {
    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);
    UiWindow* _this = Unwrap<UiWindow>(info.This());
    if (value->IsFunction()) {
        _this->_onMessageFn.Reset(isolate, Local<Function>::Cast(value));
    }
    else {
        _this->_onMessageFn.Reset();
    }
}
Beispiel #17
0
static void setPropertyOnProxy(Isolate* isolate, Local<Name> property, Local<Value> value, Local<Object> proxy)
{
    // Call Proxy.prototype.setProperty.
    Local<Value> setProperty = proxy->Get(STRING_NEW(isolate, "setProperty"));
    if (!setProperty.IsEmpty() && setProperty->IsFunction()) {
        Local<Value> argv[2] = { property, value };
        setProperty.As<Function>()->Call(isolate->GetCurrentContext(), proxy, 2, argv);
        return;
    }

    LOGE(TAG, "Unable to lookup Proxy.prototype.setProperty");
}
Beispiel #18
0
static void setPropertyOnProxy(Local<String> property, Local<Value> value, Local<Object> proxy)
{
	// Call Proxy.prototype.setProperty.
	Local<Value> setProperty = proxy->Get(String::New("setProperty"));
	if (!setProperty.IsEmpty() && setProperty->IsFunction()) {
		Local<Value> argv[2] = { property, value };
		Handle<Function>::Cast(setProperty)->Call(proxy, 2, argv);
		return;
	}

	LOGE(TAG, "Unable to lookup Proxy.prototype.setProperty");
}
Beispiel #19
0
void Module::Init(Isolate *isolate)
{
	JEnv env;

	MODULE_CLASS = env.FindClass("com/tns/Module");
	assert(MODULE_CLASS != nullptr);

	RESOLVE_PATH_METHOD_ID = env.GetStaticMethodID(MODULE_CLASS, "resolvePath", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
	assert(RESOLVE_PATH_METHOD_ID != nullptr);

	string requireFactoryScript =
	"(function () { "
	"	function require_factory(requireInternal, dirName) { "
	"		return function require(modulePath) { "
	"			if(global.__requireOverride) { "
	"				var result = global.__requireOverride(modulePath, dirName); "
	"				if(result) { "
	"					return result; "
	"				} "
	"			} "
	"			return requireInternal(modulePath, dirName); "
	"		} "
	"	} "
	"	return require_factory; "
	"})()";

	auto source = ConvertToV8String(requireFactoryScript);
	auto context = isolate->GetCurrentContext();

	Local<Script> script;
	auto maybeScript = Script::Compile(context, source).ToLocal(&script);

	assert(!script.IsEmpty());

	Local<Value> result;
	auto maybeResult = script->Run(context).ToLocal(&result);

	assert(!result.IsEmpty() && result->IsFunction());

	auto requireFactoryFunction = result.As<Function>();

	auto cache = GetCache(isolate);

	cache->RequireFactoryFunction = new Persistent<Function>(isolate, requireFactoryFunction);

	auto requireFuncTemplate = FunctionTemplate::New(isolate, RequireCallback);
	auto requireFunc = requireFuncTemplate->GetFunction();
	cache->RequireFunction = new Persistent<Function>(isolate, requireFunc);

	auto global = isolate->GetCurrentContext()->Global();
	auto globalRequire = GetRequireFunction(isolate, Constants::APP_ROOT_FOLDER_PATH);
	global->Set(ConvertToV8String("require"), globalRequire);
}
Beispiel #20
0
static Handle<Value> getPropertyForProxy(Local<String> property, Local<Object> proxy)
{
	// Call getProperty on the Proxy to get the property.
	// We define this method in JavaScript on the Proxy prototype.
	Local<Value> getProperty = proxy->Get(String::New("getProperty"));
	if (!getProperty.IsEmpty() && getProperty->IsFunction()) {
		Local<Value> argv[1] = { property };
		return Handle<Function>::Cast(getProperty)->Call(proxy, 1, argv);
	}

	LOGE(TAG, "Unable to lookup Proxy.prototype.getProperty");
	return Undefined();
}
Handle<Value> FdbError::NewInstance(fdb_error_t code, const char *description) {
	HandleScope scope;

	Local<Value> constructor = module->Get( String::NewSymbol("FDBError") );
	Local<Object> instance;
	if (!constructor.IsEmpty() && constructor->IsFunction()) {
		Local<Value> constructorArgs[] = { String::New(description), Integer::New(code) };
		instance = Local<Function>::Cast(constructor)->NewInstance(2, constructorArgs);
	} else {
		// We can't find the (javascript) FDBError class, so construct and throw *something*
		instance = Exception::Error(String::New("FDBError class not found.  Unable to deliver error."))->ToObject();
	}

	return scope.Close(instance);
}
Beispiel #22
0
	void SorrowContext::FireExit() {
		HandleScope scope;
		TryCatch tryCatch;
		Local<Value> func = internals->Get(V8_STR("fire"));
		
		if (tryCatch.HasCaught() || func == Undefined()) {
			return;
		}
		ASSERT_PIN(func->IsFunction(), "FireExit");
		Local<Function> f = Local<Function>::Cast(func);
        
		Local<Object> global = Context::GetCurrent()->Global();
		Local<Value> args[1] = { V8_STR("exit") };
		f->Call(global, 1, args);
	}
Beispiel #23
0
void ScriptGame::_loadGame()
{
	HandleScope hs;
	PersistentContext ctx = MagnetiteCore::Singleton->getScriptManager()->getContext();
	Context::Scope scope( ctx );
	if( !mScriptObject.IsEmpty() && mScriptObject->Has( String::New("onLoad") ) )
	{
		Local<Value> onLoadVal = mScriptObject->Get( String::New("onLoad") );
		if( onLoadVal->IsFunction() )
		{
			Local<Function> onLoad = Local<Function>::Cast( onLoadVal );
			onLoad->Call( mScriptObject, 0, NULL );
		}
	}
}
Beispiel #24
0
void ScriptGame::_startGame()
{
	HandleScope hs;
	PersistentContext ctx = MagnetiteCore::Singleton->getScriptManager()->getContext();
	Context::Scope scope( ctx );
	Util::log("#== " + getName() + " ==================");
	if( !mScriptObject.IsEmpty() && mScriptObject->Has( String::New("onStart") ) )
	{
		Local<Value> onStartVal = mScriptObject->Get( String::New("onStart") );
		if( onStartVal->IsFunction() )
		{
			Local<Function> onStart = Local<Function>::Cast( onStartVal );
			onStart->Call( mScriptObject, 0, NULL );
		}
	}
}
Beispiel #25
0
static Local<Value> getPropertyForProxy(Isolate* isolate, Local<Name> property, Local<Object> proxy)
{
    // Call getProperty on the Proxy to get the property.
    // We define this method in JavaScript on the Proxy prototype.
    Local<Value> getProperty = proxy->Get(STRING_NEW(isolate, "getProperty"));
    if (!getProperty.IsEmpty() && getProperty->IsFunction()) {
        Local<Value> argv[1] = { property };
        MaybeLocal<Value> value = getProperty.As<Function>()->Call(isolate->GetCurrentContext(), proxy, 1, argv);
        if (value.IsEmpty()) {
            return Undefined(isolate);
        }
        return value.ToLocalChecked();
    }

    LOGE(TAG, "Unable to lookup Proxy.prototype.getProperty");
    return Undefined(isolate);
}
Beispiel #26
0
void ScriptGame::playerAltClick( Player* player )
{
	HandleScope hs;
	PersistentContext ctx = MagnetiteCore::Singleton->getScriptManager()->getContext();
	Context::Scope scope( ctx );
	if( !mScriptObject.IsEmpty() && mScriptObject->Has( String::New("onAlt") ) )
	{
		Local<Value> onLoadVal = mScriptObject->Get( String::New("onAlt") );
		if( onLoadVal->IsFunction() )
		{
			Local<Function> onLoad = Local<Function>::Cast( onLoadVal );
			Handle<Value> args[1];
			args[0] = wrapPlayer( player );
			onLoad->Call( mScriptObject, 1, args );
		}
	}
}
Beispiel #27
0
SV*
V8Context::object2blessed(Handle<Object> obj) {
    char package[128];

    snprintf(
        package,
        128,
        "%s%s::N%d",
        bless_prefix.c_str(),
        *String::AsciiValue(obj->Get(String::New("__perlPackage"))->ToString()),
        number
    );

    HV *stash = gv_stashpv(package, 0);

    if (!stash) {
        Local<Object> prototype = obj->GetPrototype()->ToObject();

        stash = gv_stashpv(package, GV_ADD);

        Local<Array> properties = prototype->GetPropertyNames();
        for (int i = 0; i < properties->Length(); i++) {
            Local<String> name = properties->Get(i)->ToString();
            Local<Value> property = prototype->Get(name);

            if (!property->IsFunction())
                continue;

            Local<Function> fn = Local<Function>::Cast(property);

            CV *code = newXS(NULL, v8method, __FILE__);
            V8ObjectData *data = new V8FunctionData(this, fn, (SV*)code);

            GV* gv = (GV*)*hv_fetch(stash, *String::AsciiValue(name), name->Length(), TRUE);
            gv_init(gv, stash, *String::AsciiValue(name), name->Length(), GV_ADDMULTI); /* vivify */
            my_gv_setsv(aTHX_ gv, (SV*)code);
        }
    }

    SV* rv = newSV(0);
    SV* sv = newSVrv(rv, package);
    V8ObjectData *data = new V8ObjectData(this, obj, sv);
    sv_setiv(sv, PTR2IV(data));

    return rv;
}
Beispiel #28
0
void ScriptGame::keyUp( size_t evt )
{
	HandleScope hs;
	PersistentContext ctx = MagnetiteCore::Singleton->getScriptManager()->getContext();
	Context::Scope scope( ctx );
	if( !mScriptObject.IsEmpty() && mScriptObject->Has( String::New("keyUp") ) )
	{
		Local<Value> onLoadVal = mScriptObject->Get( String::New("keyUp") );
		if( onLoadVal->IsFunction() )
		{
			Local<Function> onLoad = Local<Function>::Cast( onLoadVal );
			Handle<Value> args[1];
			args[0] = Number::New( evt );
			onLoad->Call( mScriptObject, 1, args );
		}
	}
}
Local<Value> CallV8ObjectProperty(Handle<Object> object,
                                  const char* propertyName,
                                  int argc,
                                  Handle<Value> argv[]) {
    HandleScope scope;

    // Lookup a property by name on the object.
    // If the property is undefined or not a function then
    // return an empty handle to indicate the error.
    Local<Value> property = object->Get(String::NewSymbol(propertyName));
    if (property.IsEmpty() || !property->IsFunction()) {
        return Local<Value>();
    }

    Local<Function> callback = Local<Function>::Cast(property);
    Local<Value> result = callback->Call(object, argc, argv);
    return scope.Close(result);
}
Beispiel #30
0
	void SorrowContext::LoadMain() {
		HandleScope handle_scope;
		TryCatch tryCatch;

		Local<Value> func = internals->Get(String::New("loadMain"));
		
		ASSERT_PIN(func->IsFunction(), "loadMain not found");
		Local<Function> f = Local<Function>::Cast(func);
		
		Local<Object> global = Context::GetCurrent()->Global();
		
		f->Call(global, 0, NULL);
		
		if (tryCatch.HasCaught())  {
			ReportException(&tryCatch);
			KillPinTool();
		}
	}