Esempio n. 1
0
void Server::FireEvent(std::string name, const int argc, Local<Value> argv[] ){
	Locker v8Locker(isolate);
	Isolate::Scope isoscope(isolate);
	HandleScope hs(isolate);
	Local<Context> ctx = Local<Context>::New(isolate, context);
	Context::Scope cs(ctx);
	TryCatch try_catch;

	JS_Object global(ctx->Global());

	Local<Object> serverjs = global.getObject("$server");
	Local<Value> fire = serverjs->Get(String::NewFromUtf8(isolate, "fire"));
	Local<Function> fn = Local<Function>::Cast(fire);

	if (name == "ScriptInit"){
		Local<Value> check = serverjs->Get(String::NewFromUtf8(isolate, "checkPlayers"));
		Local<Function> cpfn = Local<Function>::Cast(check);
		cpfn->Call(serverjs, 0, NULL);
	}
	Local<Value> *args = new Local<Value>[argc + 1];
	args[0] = String::NewFromUtf8(isolate, name.c_str());
	if (argc > 0){
		for (int i = 0; i < argc; i++){
			args[i + 1] = argv[i];
		}
	}
	fn->Call(serverjs, argc + 1, args);

	delete[] args;

	if (try_catch.HasCaught()){
		Utils::PrintException(&try_catch);
	}
}
Esempio n. 2
0
void MySQL::ConnectAsync(int id, string host, string user, string password, string database, Persistent<Function, CopyablePersistentTraits<Function>> callback){
	//connections[id]->mysql = mysql_init(NULL);
	if (mysql_real_connect(
		connections[id]->mysql,
		host.c_str(),
		user.c_str(),
		password.c_str(),
		database.c_str(),
		0,
		NULL,
		0) == NULL){
		V8PCONTEXT(isolate, context);
		Local<Function> func = Local<Function>::New(isolate, callback);
		sjs::logger::debug("Could not connect");
		Local<String> err = String::NewFromUtf8(isolate, mysql_error(connections[id]->mysql));
		Local<Value> argv[1] = { err };
		func->Call(func, 1, argv );
		sjs::logger::debug("Called Function");
		return;
	}
	
	V8PCONTEXT(isolate, context);
	Local<Function> func = Local<Function>::New(isolate, callback);
	func->Call(func, 0, NULL);
}
Esempio n. 3
0
void JsVlcPlayer::callCallback( Callbacks_e callback,
                                std::initializer_list<v8::Local<v8::Value> > list )
{
    using namespace v8;

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

    std::vector<v8::Local<v8::Value> > argList;
    argList.reserve( list.size() );
    argList.push_back(
        String::NewFromUtf8( isolate,
                             callbackNames[callback],
                             v8::String::kInternalizedString ) );
    if( list.size() > 0 )
        argList.insert( argList.end(), list );

    if( !_jsCallbacks[callback].IsEmpty() ) {
        Local<Function> callbackFunc =
            Local<Function>::New( isolate, _jsCallbacks[callback] );

        callbackFunc->Call( handle(), argList.size() - 1, argList.data() + 1 );
    }

    Local<Object> eventEmitter = getEventEmitter();
    Local<Function> emitFunction =
        v8::Local<v8::Function>::Cast(
            eventEmitter->Get(
                String::NewFromUtf8( isolate, "emit", v8::String::kInternalizedString ) ) );

    emitFunction->Call( eventEmitter, argList.size(), argList.data() );
}
Esempio n. 4
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();
}
Esempio n. 5
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 );
	}
}
Esempio n. 6
0
            void operator()() {
                V8Scope* scope = config_._scope.get();
                v8::Isolate::Scope iscope(scope->getIsolate());
                v8::Locker l(scope->getIsolate());
                HandleScope handle_scope;
                Context::Scope context_scope( scope->getContext() );

                BSONObj args = config_.args_;
                Local< v8::Function > f = v8::Function::Cast( *(scope->mongoToV8Element(args.firstElement(), true)) );
                int argc = args.nFields() - 1;

                boost::scoped_array< Local< Value > > argv( new Local< Value >[ argc ] );
                BSONObjIterator it(args);
                it.next();
                for( int i = 0; i < argc; ++i ) {
                    argv[ i ] = Local< Value >::New( scope->mongoToV8Element(*it, true) );
                    it.next();
                }
                TryCatch try_catch;
                Handle< Value > ret = f->Call( scope->getContext()->Global(), argc, argv.get() );
                if ( ret.IsEmpty() ) {
                    string e = toSTLString( &try_catch );
                    log() << "js thread raised exception: " << e << endl;
                    // v8 probably does something sane if ret is empty, but not going to assume that for now
                    ret = v8::Undefined();
                }
                // ret is translated to BSON to switch isolate
                BSONObjBuilder b;
                scope->v8ToMongoElement(b, "ret", ret);
                config_.returnData_ = b.obj();
            }
Esempio n. 7
0
static gboolean
gum_v8_exception_handler_on_exception (GumExceptionDetails * details,
                                       gpointer user_data)
{
  GumV8ExceptionHandler * handler = (GumV8ExceptionHandler *) user_data;
  GumV8Core * core = handler->core;

  ScriptScope scope (core->script);
  Isolate * isolate = core->isolate;

  Local<Function> callback (Local<Function>::New (isolate, *handler->callback));

  Local<Object> ex, context;
  _gum_v8_parse_exception_details (details, ex, context, core);

  Handle<Value> argv[] = { ex };
  Local<Value> result = callback->Call (Null (isolate), 1, argv);

  _gum_v8_cpu_context_free_later (
      new GumPersistent<Object>::type (isolate, context),
      core);

  if (!result.IsEmpty () && result->IsBoolean ())
  {
    bool handled = result.As<Boolean> ()->Value ();
    return handled ? TRUE : FALSE;
  }

  return FALSE;
}
extern "C" void
init(Handle<Object> target)
{
    HandleScope scope;
    Local<FunctionTemplate> logFunction = FunctionTemplate::New(LogWrapper);
    target->Set(String::NewSymbol("_logString"), logFunction->GetFunction());
    Local<FunctionTemplate> logKeyValueFunction = FunctionTemplate::New(LogKeyValueWrapper);
    target->Set(String::NewSymbol("_logKeyValueString"), logKeyValueFunction->GetFunction());
    target->Set(String::NewSymbol("LOG_CRITICAL"), Integer::New(kPmLogLevel_Critical));
    target->Set(String::NewSymbol("LOG_ERR"), Integer::New(kPmLogLevel_Error));
    target->Set(String::NewSymbol("LOG_WARNING"), Integer::New(kPmLogLevel_Warning));
    target->Set(String::NewSymbol("LOG_INFO"), Integer::New(kPmLogLevel_Info));
    target->Set(String::NewSymbol("LOG_DEBUG"), Integer::New(kPmLogLevel_Debug));
    Local<String> scriptText = String::New((const char*)pmloglib_js, pmloglib_js_len);
    Local<Script> script = Script::New(scriptText, String::New("pmloglib.js"));
    if (!script.IsEmpty()) {
        Local<Value> v = script->Run();
        Local<Function> f = Local<Function>::Cast(v);
        Local<Context> current = Context::GetCurrent();
        Handle<Value> argv[1];
        argv[0] = target;
        f->Call(current->Global(), 1, &argv[0]);
    } else {
        cerr << "Script was empty." << endl;
    }
}
Esempio n. 9
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;
}
Esempio n. 10
0
extern "C" void Java_io_neft_Native_renderer_1callAnimationFrame(JNIEnv * env, jobject obj) {
    using namespace renderer;

    // enter isolate
    Isolate* isolate = JS::GetIsolate();
    Locker locker(isolate);
    Isolate::Scope isolate_scope(isolate);
    HandleScope handle_scope(isolate);

    // get local context and enter it
    Local<Context> context = Local<Context>::New(isolate, JS::GetContext());
    Context::Scope context_scope(context);

    // call all registered functions
    const int length = animationFrameCalls.size();
    for (int i = 0; i < length; i++){
        Persistent<Function, CopyablePersistentTraits<Function>> func = animationFrameCalls[i];

        // get local function
        Local<Function> localFunc = Local<Function>::New(isolate, func);

        // call function
        localFunc->Call(context->Global(), 0, NULL);

        // clear persistent
        func.Reset();
    }

    // remove called functions
    animationFrameCalls.erase(animationFrameCalls.begin(), animationFrameCalls.begin() + length);
}
Esempio n. 11
0
            void operator()() {
                config_._scope.reset( dynamic_cast< V8Scope * >( globalScriptEngine->newScope() ) );
                v8::Locker v8lock(config_._scope->getIsolate());
                v8::Isolate::Scope iscope(config_._scope->getIsolate());
                HandleScope handle_scope;
                Context::Scope context_scope(config_._scope->getContext());

                BSONObj args = config_.args_;
                Local< v8::Function > f = v8::Function::Cast( *(config_._scope->mongoToV8Element(args.firstElement(), true)) );
                int argc = args.nFields() - 1;

                // TODO SERVER-8016: properly allocate handles on the stack
                Local<Value> argv[24];
                BSONObjIterator it(args);
                it.next();
                for(int i = 0; i < argc && i < 24; ++i) {
                    argv[i] = Local< Value >::New(config_._scope->mongoToV8Element(*it, true));
                    it.next();
                }
                TryCatch try_catch;
                Handle<Value> ret = f->Call(config_._scope->getContext()->Global(), argc, argv);
                if (ret.IsEmpty() || try_catch.HasCaught()) {
                    string e = toSTLString( &try_catch );
                    log() << "js thread raised exception: " << e << endl;
                    // v8 probably does something sane if ret is empty, but not going to assume that for now
                    ret = v8::Undefined();
                }
                // ret is translated to BSON to switch isolate
                BSONObjBuilder b;
                config_._scope->v8ToMongoElement(b, "ret", ret);
                config_.returnData_ = b.obj();
            }
Esempio n. 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;
}
Esempio n. 13
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;
}
Esempio n. 14
0
void Method(const FunctionCallbackInfo<Value>& args) {
	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);
	const char * cstr;
	String::Utf8Value str(args[0]->ToString());
	cstr = *str;

	CTime curTime;
	CRTime deliLimit;
	vector<CDriver> drivers;
	vector<CTask> tasks;
	vector<CPath> paths;
	vector<CScheduleItem> schedule;
	schedule.clear();
	if (parseInput(cstr, curTime, deliLimit, drivers, tasks, paths)) {
		int ret = ALG::findScheduleGreedy(curTime, deliLimit, drivers, tasks, paths, schedule);
		if (ret != E_NORMAL) {
			printf("search algorithm returned %d.\n", ret);
		}
	}
	Local<String> schd_string = String::NewFromUtf8(isolate, prepareOutput(schedule).c_str());
	//args.GetReturnValue().Set(schd_string);
	Local<Function> cb = Local<Function>::Cast(args[1]);
	const unsigned int argc = 1;
	Local<Value> argv[argc] = {schd_string};
	cb->Call(isolate->GetCurrentContext()->Global(), argc, argv);
}
Esempio n. 15
0
void BookWrap::Each(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
    HandleScope scope(isolate);

    Book* book = ObjectWrap::Unwrap<BookWrap>(args.This())->m_book;

    if (args.Length() == 1) {
        if (args[0]->IsFunction()) {
            Local<Function> fun = Local<Function>::Cast(args[0]);
            for(uint32_t i = 0; i < book->size(); ++i) {
                Local<Object> pw = PersonWrap::New(isolate, book, i);
                Local<Value> argv[1] = { pw };
                fun->Call(Null(isolate), 1, argv);
            }
            args.GetReturnValue().SetUndefined();
            return;
        }
        else {
            isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Function expected")));
            args.GetReturnValue().SetUndefined();
            return;
        }
    }
    else {
        isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "One argument expected")));
        args.GetReturnValue().SetUndefined();
        return;
            
    }
}
Esempio n. 16
0
Handle<Value> parseHandler(const Arguments& args) {
    HandleScope scope;

	bool validArguments = 
		args[0]->IsString() &&
		args[1]->IsString() && 
		args[2]->IsNumber() && 
		args[3]->IsFunction();

	if (!validArguments) {
        return ThrowException(Exception::TypeError(
			String::New("Invalid arguments! Pass the arguments in the following order: {string} text, {string} title, {int} outputlength, {function} callback.")));
    }

	Local<Array> nodes = Parser(std::string(*String::Utf8Value(args[0]->ToString())),
								std::string(*String::Utf8Value(args[1]->ToString())), 
								int(args[2]->Int32Value()),
								false);

	const unsigned argc = 2;
	Local<Value> argv[argc] = {
		Local<Value>::New(Null()),
		nodes
	};

	Local<Function> callback = Local<Function>::Cast(args[3]);

	callback->Call(Context::GetCurrent()->Global(), argc, argv);

    return Undefined();
}
Esempio n. 17
0
void Susi::JS::Engine::RegisterProcessor(const v8::FunctionCallbackInfo<v8::Value>& args) {
	if (args.Length() < 2) return;
	Handle<Value> callbackValue = args[1];
	if(callbackValue->IsFunction()){
		Handle<Value> topicValue = args[0];
		std::string topic{Susi::JS::Engine::convertFromJS(topicValue).toString()};
		std::shared_ptr<Persistent<Function>> jsCallback{new Persistent<Function>(Isolate::GetCurrent(),Handle<Function>::Cast(callbackValue))};
		Susi::Events::Processor callback = [jsCallback](Susi::Events::EventPtr event){
			Local<Function> func = Local<Function>::New(Isolate::GetCurrent(),*jsCallback);
			Handle<Value> callbackArguments[1];
			callbackArguments[0] = Susi::JS::Engine::convertFromCPP(event->toAny());
			TryCatch trycatch;
			auto res = func->Call(func,1,callbackArguments);
			if (res.IsEmpty()) {
				Handle<Value> exception = trycatch.Exception();
				String::Utf8Value exception_str(exception);
				std::cout<<*exception_str<<std::endl;
			}
		};
		long id = Susi::JS::engine->susi_client.subscribe(topic,callback);
		args.GetReturnValue().Set((double)id);
	}else{
		args.GetReturnValue().Set(false);
	}
}
Esempio n. 18
0
//	DISCONNECT SYNC
void disconnectSync(const FunctionCallbackInfo<Value>& args) {
	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);
	
	SQLRETURN retcode;

	// define callback
	Local<Function> cb = Local<Function>::Cast(args[0]);
	
    // Free handles
    // Statement
    if (hstmt != SQL_NULL_HSTMT)
        SQLFreeHandle(SQL_HANDLE_STMT, hstmt);

    // Connection
	retcode = SQLDisconnect(hdbc);
	if(!SQL_SUCCEEDED(retcode)){
		printf("ERROR AT SQLDISCONNECT\n");
		extract_error(hdbc, SQL_HANDLE_DBC);
	}
    SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
/*
    // Environment
    if (henv != SQL_NULL_HENV)
        SQLFreeHandle(SQL_HANDLE_ENV, henv);
*/	

	Local<Value> argv[1] = { Number::New(isolate, retcode)};
	cb->Call(isolate->GetCurrentContext()->Global(), 1, argv);
}
Esempio n. 19
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);
	}
}
Esempio n. 20
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
Esempio n. 21
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");
	}
}
Esempio n. 22
0
void
Session::emit(int argc, Handle<Value> argv[])
{
    HandleScope scope;

    Local<Function> emit = Local<Function>::Cast(handle_->Get(s_emit));
    emit->Call(handle_, argc, argv);
}
Esempio n. 23
0
void js_proxy::scatter(icontext_type& context, const vertex_type& vertex, edge_type& edge) const {
  HandleScope handle_scope;
  Local<Function> f = Function::Cast(*jsobj->Get(JSTR("scatter")));
  Handle<Value> args[] = {
    cv::CastToJS(context), cv::CastToJS(vertex), cv::CastToJS(edge)
  };
  f->Call(jsobj, 3, args);
}
 /**
  * Raw invocation base specification for invoking V8 function (w/o type conversion).
  */
 inline Handle<Value> rawInvoke()
 {
     HandleScope handle_scope(this->m_isolationScope);
     
     Local<Function> callback = this->getCtorFunction();
     Handle<Value> argv[] = {};
     
     return callback->Call(callback, 0, argv);
 }
Esempio n. 25
0
Handle<Value> status(const Arguments& args) {
    HandleScope scope;
    if (args.Length() < 2) {
        ThrowException(Exception::TypeError(String::New("Usage:  status(<directory>, <callback>);")));
        return scope.Close(Undefined());
    }

    if (!args[0]->IsString()) {
        ThrowException(Exception::TypeError(String::New("Usage status(<directory>, <callback>)")));
        return scope.Close(Undefined());
    }
    Local<Function> cb = Local<Function>::Cast(args[1]);

    // Get the V8 param and convert it to a string.
    String::Utf8Value param1(args[0]->ToString());
    string dir = string(*param1);
    string err;
    long bytesTotal, bytesAvail, bytesUsed;
    float pctUsed;

    FileSystemSpace fsspace;
    if (fsspace.status(dir, err, bytesTotal, bytesAvail, bytesUsed, pctUsed))
    {
        const unsigned argc = 5;
        Local<Value> argv[argc] = { 
            Local<Value>::New(String::New(err.c_str())),
            Local<Value>::New(Number::New(bytesTotal)),
            Local<Value>::New(Number::New(bytesAvail)),
            Local<Value>::New(Number::New(bytesUsed)),
            Local<Value>::New(Number::New(pctUsed))
        }; 

        cb->Call(Context::GetCurrent()->Global(), argc, argv);

    }
    else // fsspace.status() Error
    {
        const unsigned argc = 1;
        Local<Value> argv[argc] = { Local<Value>::New(String::New(err.c_str()))};
        cb->Call(Context::GetCurrent()->Global(), argc, argv);
    }

    return scope.Close(Undefined());
}
Esempio n. 26
0
// callback signaled from file watching threadproc that allows us to asynchronously post changes back to JS
void NodeFSEvents::Callback(uv_async_t *handle, int status)
{
    NodeFSEvents *This = static_cast<NodeFSEvents*>(handle->data);
    if (This->m_pChangeInfo != NULL)
    {
        HandleScope scope;

        // initialize wrapper to call back into JS
        Local<Value> callback_v = This->handle_->Get(emit_sym);
        Local<Function> callback = Local<Function>::Cast(callback_v);
        Handle<Value> args[3];
        args[0] = change_sym;

        // iterate thru each queued file watching entry
        CFileNotifyChangeInfo::LPEntry lpEntry = NULL;
        while ((lpEntry = This->m_pChangeInfo->Peek()) != NULL)
        {
            // concatenate the root search path and the file notification path
            std::wstring wstrFullPath = This->m_wstrRootPath.c_str();
            wstrFullPath += lpEntry->m_wstrFilename;

            // normalize path separators from '\' to '/'
            std::replace(wstrFullPath.begin(), wstrFullPath.end(), '\\', '/');

            // convert the full pathname to utf8
            int iLen = ::WideCharToMultiByte(CP_UTF8, 0, wstrFullPath.c_str(), -1, NULL, 0, NULL, NULL);
            std::string strFullPath(iLen + 1, 0x00);
            ::WideCharToMultiByte(CP_UTF8, 0, wstrFullPath.c_str(), -1, &strFullPath[0], iLen + 1, NULL, NULL);

            // map the FILE_NOTIFY_INFORMATION 'Action' to a node fs-event.c 'enum uv_fs_event' type
            int iAction;
            switch(lpEntry->m_dwAction)
            {
            case FILE_ACTION_ADDED:
            case FILE_ACTION_REMOVED:
            case FILE_ACTION_RENAMED_OLD_NAME:
            case FILE_ACTION_RENAMED_NEW_NAME:
                iAction = UV_RENAME;
                break;
            case FILE_ACTION_MODIFIED:
            default:
                iAction = UV_CHANGE;
            }

            // call back into JS with each change.
            args[1] = String::New(strFullPath.c_str());
            args[2] = Integer::New(iAction);
            callback->Call(This->handle_, 3, args);

            // discard the now-processed entry
            This->m_pChangeInfo->Pop();
            delete lpEntry;
        }
    }
}
Esempio n. 27
0
	void AsyncAfter(uv_work_t* req, int status) {
#else
	void AsyncAfter(uv_work_t* req) {
#endif
    Nan::HandleScope scope;
    Baton* baton = static_cast<Baton*>(req->data);
    Local<Function> cb = Nan::New<Function>(baton->callback);
    cb->Call(Nan::GetCurrentContext()->Global(), 0, 0);
    baton->callback.Reset();
    delete baton;
}
 inline typename boost::enable_if<
 boost::is_same<TResult, void>, TResult >::type
 invoke()
 {
     HandleScope handle_scope(this->m_isolationScope);
     
     Local<Function> callback = this->getCtorFunction();
     Handle<Value> argv[] = {};
     
     callback->Call(callback, 0, argv);
 }
Esempio n. 29
0
Handle<Value> Fn2(const Arguments& args) {
    HandleScope scope;
    int answer = 133.7f / M_PI;
    Local<Value> argv[] = {
        Local<Value>::New(Null()),
        Local<Value>::New(Integer::New(answer))
    };
    Local<Function> callback = Local<Function>::Cast(args[0]);
    callback->Call(Context::GetCurrent()->Global(), 2, argv);
    return Undefined();
}
Esempio n. 30
0
void BookWrap::Apply(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
    HandleScope scope(isolate);

    Local<Function> fun = Local<Function>::Cast(args[0]);
    Handle<Value> argv[] = { args.This() };
    TryCatch trycatch;
    Handle<Value> v = fun->Call(Null(isolate), 1, argv);
    if (trycatch.HasCaught()) {
        trycatch.ReThrow();
    }
    args.GetReturnValue().Set(v);
}