示例#1
0
文件: v8_utils.cpp 项目: IlyaM/mongo
 void operator()() {
     Locker l;
     HandleScope handle_scope;
     Handle< Context > context;
     Handle< v8::Function > fun;
     auto_ptr< V8Scope > scope;
     if ( config_.newScope_ ) {
         scope.reset( dynamic_cast< V8Scope * >( globalScriptEngine->newScope() ) );
         context = scope->context();
         // A v8::Function tracks the context in which it was created, so we have to
         // create a new function in the new context.
         Context::Scope baseScope( baseContext_ );
         string fCode = toSTLString( config_.f_->ToString() );
         Context::Scope context_scope( context );
         fun = scope->__createFunction( fCode.c_str() );
     } else {
         context = baseContext_;
         Context::Scope context_scope( context );
         fun = config_.f_;
     }
     Context::Scope context_scope( context );
     boost::scoped_array< Local< Value > > argv( new Local< Value >[ config_.args_.size() ] );
     for( unsigned int i = 0; i < config_.args_.size(); ++i )
         argv[ i ] = Local< Value >::New( config_.args_[ i ] );
     TryCatch try_catch;
     Handle< Value > ret = fun->Call( context->Global(), config_.args_.size(), 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();
     }
     config_.returnData_ = Persistent< Value >::New( ret );
 }
示例#2
0
/* Create and return a v8 context. Thread safe. */
void msV8CreateContext(mapObj *map)
{

  Isolate *isolate = Isolate::GetCurrent();
  Isolate::Scope isolate_scope(isolate);
  HandleScope handle_scope(isolate);

  V8Context *v8context = new V8Context(isolate);

  Handle<ObjectTemplate> global_templ = ObjectTemplate::New();
  global_templ->Set(String::New("require"), FunctionTemplate::New(msV8Require));
  global_templ->Set(String::New("print"), FunctionTemplate::New(msV8Print));
  global_templ->Set(String::New("alert"), FunctionTemplate::New(msV8Print));

  Handle<Context> context_ = Context::New(v8context->isolate, NULL, global_templ);
  v8context->context.Reset(v8context->isolate, context_);

  /* we have to enter the context before getting global instance */
  Context::Scope context_scope(context_);
  Handle<Object> global = context_->Global();
  Shape::Initialize(global);
  Point::Initialize(global);
  Line::Initialize(global);

  v8context->paths.push(map->mappath);
  v8context->isolate->SetData(v8context);
  v8context->layer = NULL;

  map->v8context = (void*)v8context;
}
示例#3
0
int main() {
    flusspferd::current_context_scope context_scope(
        flusspferd::context::create());

    flusspferd::object g = flusspferd::global();

    // Create a method of the global object (= global function) with name print
    // that calls print().
    flusspferd::create_native_function(g, "print", &print);

    // Create a global function that calls exp_i().
    flusspferd::create_native_function(g, "exp", &exp_i);

    flusspferd::object p = flusspferd::evaluate("Object.prototype").to_object();

    // Create a method of Object.prototype that calls print_object().
    // The difference between create_native_function and create_native_method is
    // that the latter passes Javascript's 'this' as parameter to the function.
    //
    // (Note that every normal object ultimately has as prototype the value of
    // Object.prototype. However create_native_method and create_native_function
    // create the properties with dont_enum, so doing this is safe.)
    flusspferd::create_native_method(p, "print", &print_object);

    // Print e.
    // (Note that 1.2 is rounded down to 1.)
    flusspferd::evaluate("print(exp(1.2))");

    // Print the contents of a literal object.
    flusspferd::evaluate("({a:1, b:2}).print()");
}
示例#4
0
   void InitMapSystemWrapper(ScriptSystem* ss)
   {
      HandleScope scope;
      Context::Scope context_scope(ss->GetGlobalContext());

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

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

      proto->Set("addEmptyMap", FunctionTemplate::New(MSAddEmptyMap));
      proto->Set("getEntityIdByUniqueId", FunctionTemplate::New(MSGetEntityIdByUniqueId));
      proto->Set("isSpawnOf", FunctionTemplate::New(MSIsSpawnOf));
      proto->Set("toString", FunctionTemplate::New(MSToString));
      proto->Set("loadMap", FunctionTemplate::New(MSLoadMap));
      proto->Set("loadScene", FunctionTemplate::New(MSLoadScene));
      proto->Set("unloadScene", FunctionTemplate::New(MSUnloadScene));
      proto->Set("saveScene", FunctionTemplate::New(MSSaveScene));
      proto->Set("unloadMap", FunctionTemplate::New(MSUnloadMap));
      proto->Set("getLoadedMaps", FunctionTemplate::New(MSGetLoadedMaps));
      proto->Set("spawn", FunctionTemplate::New(MSSpawn));
      proto->Set("deleteEntitiesByMap", FunctionTemplate::New(MSDeleteEntitiesByMap));
      proto->Set("addSpawner", FunctionTemplate::New(MSAddSpawner));
      proto->Set("addToScene", FunctionTemplate::New(MSAddToScene));
      proto->Set("deleteSpawner", FunctionTemplate::New(MSDeleteSpawner));
      proto->Set("getSpawner", FunctionTemplate::New(MSGetSpawner));
      proto->Set("MSGetSpawnerComponents", FunctionTemplate::New(MSGetSpawnerComponents));
      proto->Set("getSpawnerCreatedEntities", FunctionTemplate::New(MSGetSpawnerCreatedEntities));
      proto->Set("getAllSpawnerNames", FunctionTemplate::New(MSGetAllSpawnerNames));
      proto->Set("getEntitiesInMap", FunctionTemplate::New(MSGetEntitiesInMap));
      proto->Set("removeFromScene", FunctionTemplate::New(MSRemoveFromScene));
      
      RegisterEntitySystempWrapper(ss, dtEntity::MapComponent::TYPE, templt);
   }
示例#5
0
            void operator()() {
                _config._scope.reset(static_cast<V8Scope*>(globalScriptEngine->newScope()));
                v8::Locker v8lock(_config._scope->getIsolate());
                v8::Isolate::Scope iscope(_config._scope->getIsolate());
                v8::HandleScope handle_scope;
                v8::Context::Scope context_scope(_config._scope->getContext());

                BSONObj args = _config._args;
                v8::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
                v8::Local<v8::Value> argv[24];
                BSONObjIterator it(args);
                it.next();
                for(int i = 0; i < argc && i < 24; ++i) {
                    argv[i] = v8::Local<v8::Value>::New(
                            _config._scope->mongoToV8Element(*it, true));
                    it.next();
                }
                v8::TryCatch try_catch;
                v8::Handle<v8::Value> ret =
                        f->Call(_config._scope->getContext()->Global(), argc, argv);
                if (ret.IsEmpty() || try_catch.HasCaught()) {
                    string e = _config._scope->v8ExceptionToSTLString(&try_catch);
                    log() << "js thread raised exception: " << e << endl;
                    ret = v8::Undefined();
                }
                // ret is translated to BSON to switch isolate
                BSONObjBuilder b;
                _config._scope->v8ToMongoElement(b, "ret", ret);
                _config._returnData = b.obj();
            }
示例#6
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;
}
MatchCreator::Description ScriptMatchCreator::_getScriptDescription(QString path) const
{
  MatchCreator::Description result;
  result.experimental = true;

  shared_ptr<PluginContext> script(new PluginContext());
  HandleScope handleScope;
  Context::Scope context_scope(script->getContext());
  script->loadScript(path, "plugin");

  Persistent<Object> plugin = ScriptMatchVisitor::getPlugin(script);
  Handle<String> descriptionStr = String::New("description");
  if (plugin->Has(descriptionStr))
  {
    Handle<v8::Value> value = plugin->Get(descriptionStr);
    result.description = toCpp<QString>(value);
  }
  Handle<String> experimentalStr = String::New("experimental");
  if (plugin->Has(experimentalStr))
  {
    Handle<v8::Value> value = plugin->Get(experimentalStr);
    result.experimental = toCpp<bool>(value);
  }

  QFileInfo fi(path);
  result.className = (QString::fromStdString(className()) + "," + fi.fileName()).toStdString();

  return result;
}
  /*
   * This is meant to run one time when the match creator is initialized.
   */
  void customScriptInit()
  {
    Context::Scope context_scope(_script->getContext());
    HandleScope handleScope;

    Persistent<Object> plugin = getPlugin();
    Handle<String> initStr = String::New("init");
    if (plugin->Has(initStr) == false)
    {
      throw HootException("Error finding 'init' function.");
    }
    Handle<v8::Value> value = plugin->Get(initStr);
    if (value->IsFunction() == false)
    {
      throw HootException("init is not a function.");
    }

    Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(value);
    Handle<Value> jsArgs[1];
    int argc = 0;
    HandleScope scope;
    assert(_map.get());
    OsmMapPtr copiedMap(new OsmMap(_map));
    jsArgs[argc++] = OsmMapJs::create(copiedMap);

    func->Call(plugin, argc, jsArgs);

    //this is meant to have been set externally in a js rules file
    _searchRadius = getNumber(plugin, "searchRadius", -1.0, 15.0);
  }
示例#9
0
文件: v8-gl.cpp 项目: cscott/v8-gl
//loads a js file
Handle<Value> load(const Arguments& args) {
  //if less that nbr of formal parameters then do nothing
  int len = args.Length();
  int i;

  if (len < 1) return v8::Undefined();
  //define handle scope
  HandleScope scope;

  // Enter the new context so all the following operations take place
  // within it.
  Context::Scope context_scope(V8GL::context);

  for (i = 0; i < len; ++i) {
	  //get argument
	  String::Utf8Value value0(args[i]);
	  char* arg0 = *value0;
	  char* filepath = V8GLUtils::getRealPath(arg0);

	  char *old_path = V8GLUtils::pushRootPath(filepath);
	  bool success = exec(string(filepath));
	  V8GLUtils::popRootPath(old_path);

	  if(!success) {
		  fprintf(stderr, "Error reading '%s'.\n", arg0);
		  return ThrowException(String::New("Failed to load script"));
	  }
  }

  return v8::Undefined();
}
示例#10
0
void JS_ReleaseRuntime(IJS_Runtime* pJSRuntime, v8::Persistent<v8::Context>& v8PersistentContext)
{
	v8::Isolate* isolate = (v8::Isolate*)pJSRuntime;
	v8::Isolate::Scope isolate_scope(isolate);
	v8::HandleScope handle_scope(isolate);
	v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, v8PersistentContext);
	v8::Context::Scope context_scope(context);

	CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(0);
	if(!pArray) return ;

	for(int i=0; i<pArray->GetSize(); i++)
	{
		CJS_ObjDefintion* pObjDef = (CJS_ObjDefintion*)pArray->GetAt(i);
		if(!pObjDef->m_StaticObj.IsEmpty())
		{
			v8::Local<v8::Object> pObj = v8::Local<v8::Object>::New(isolate, pObjDef->m_StaticObj);
			if(pObjDef->m_pDestructor)
				pObjDef->m_pDestructor(pObj);
			JS_FreePrivate(pObj);
		}
		delete pObjDef;
	}
	delete pArray;
	isolate->SetData(0,NULL);
}
示例#11
0
void ScriptEnv::ForceGC()
{
    v8::HandleScope current_scope;
    v8::Context::Scope context_scope(mContext);
    
    while(!v8::V8::IdleNotification()) {};
}
示例#12
0
	Status ModuleScript::try_run()
	{
		v8::Context::Scope context_scope(get_context());
		module_object.reset();

		if (prelude != NULL)
			if (!prelude->enter_cancellable_region()) 
				return S_TERMINATED;
		v8::Handle<v8::Value> result = run_script(get_context());
		if (prelude != NULL) 
			if (!prelude->exit_cancellable_region())
				return S_TERMINATED;

		if (result->IsObject())
		{
			module_object = std::shared_ptr<v8::Persistent<v8::Object>>(
				new v8::Persistent<v8::Object>(v8::Isolate::GetCurrent(), result.As<v8::Object>()));
		}
		else 
		{
			set_last_error("Module script must return an object");
			return S_ERROR;
		}
		return S_OK;
	}
示例#13
0
JNIEXPORT void JNICALL Java_org_adblockplus_android_JSEngine_nativeCallback
  (JNIEnv *pEnv, jobject pObj, jlong pCallback, jobjectArray pParams, jlong pContext)
{
  D(D_WARN, "nativeCallback()");
  v8::HandleScope handle_scope;

  v8::Persistent<v8::Context> context((v8::Context *) pContext);
  v8::Context::Scope context_scope(context);

  v8::Persistent<v8::Function> callback((v8::Function *) pCallback);

  jsize pnum = pEnv->GetArrayLength(pParams);
  v8::Handle<v8::Value> *args = new v8::Handle<v8::Value>[pnum];

  for (int i = 0; i < pnum; i++)
  {
    jobject param = pEnv->GetObjectArrayElement(pParams, i);
    args[i] = wrapJavaObject(pEnv, param);
    pEnv->DeleteLocalRef(param);
  }

  {
    v8::TryCatch try_catch;
    callback->Call(context->Global(), pnum, args);
    callback.Dispose();
    delete [] args;
    if (try_catch.HasCaught())
      reportException(&try_catch);
  }
}
示例#14
0
JNIEXPORT jobject JNICALL Java_org_adblockplus_android_JSEngine_nativeGet
  (JNIEnv *pEnv, jobject pObj, jstring pKey, jlong pContext)
{
  D(D_WARN, "nativeGet()");
  v8::HandleScope handle_scope;

  v8::Persistent<v8::Context> context((v8::Context *) pContext);
  v8::Context::Scope context_scope(context);

  v8::Persistent<v8::Object> obj(v8::Persistent<v8::Object>::New(context->Global()));
  const std::string key = getString(pEnv, pKey);

  {
    v8::TryCatch try_catch;
    v8::Handle<v8::Value> value = obj->Get(v8::String::New(key.c_str(), key.size()));
    if (try_catch.HasCaught())
    {
      reportException(&try_catch);
      return NULL;
    }
    else
    {
      return wrapJSObject(pEnv, value);
    }
  }
}
示例#15
0
JNIEXPORT jobject JNICALL Java_org_adblockplus_android_JSEngine_nativeExecute
  (JNIEnv *pEnv, jobject pObj, jstring pScript, jlong pContext)
{
  D(D_WARN, "nativeExecute()");
  v8::HandleScope handle_scope;

  v8::Persistent<v8::Context> context((v8::Context *) pContext);
  v8::Context::Scope context_scope(context);

  const std::string script = getString(pEnv, pScript);

  v8::Handle<v8::String> source = v8::String::New(script.c_str(), script.size());
  {
    v8::TryCatch try_catch;
    v8::Handle<v8::Script> compiledScript = v8::Script::Compile(source);
    v8::Handle<v8::Value> result = compiledScript->Run();
    if (try_catch.HasCaught())
    {
      reportException(&try_catch);
      return NULL;
    }
    else
    {
      return wrapJSObject(pEnv, result);
    }
  }
}
示例#16
0
void
test_obj_setprop()
{
  HandleScope handle_scope;

  Persistent<Context> context = Context::New();

  Context::Scope context_scope(context);

  Handle<Object> obj = Object::New();

  Handle<String> k = String::New("someprop");
  Handle<String> v = String::New("somevalue");

  obj->Set(k, v);

  Handle<Value> v2 = obj->Get(k);

  String::AsciiValue vs(v);
  String::AsciiValue vs2(v2);

  do_check_eq(vs.length(), vs2.length());
  do_check_eq(0, strcmp(*vs,*vs2));

  context.Dispose();
}
示例#17
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;
	}
}
示例#18
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();
}
  bool isMatchCandidate(ConstElementPtr e)
  {
    Context::Scope context_scope(_script->getContext());
    HandleScope handleScope;
    Persistent<Object> plugin = getPlugin();
    Handle<String> isMatchCandidateStr = String::New("isMatchCandidate");
    if (plugin->Has(isMatchCandidateStr) == false)
    {
      throw HootException("Error finding 'isMatchCandidate' function.");
    }
    Handle<v8::Value> value = plugin->Get(isMatchCandidateStr);
    if (value->IsFunction() == false)
    {
      throw HootException("isMatchCandidate is not a function.");
    }
    Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(value);
    Handle<Value> jsArgs[2];

    int argc = 0;
    jsArgs[argc++] = OsmMapJs::create(_map);
    jsArgs[argc++] = ElementJs::New(e);

    Handle<Value> f = func->Call(plugin, argc, jsArgs);

    return f->BooleanValue();
  }
示例#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
// プロパティ取得共通処理
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;
}
示例#22
0
void
test_WriteAscii()
{
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  char TEST_STRING[] = "this is a UTF-8 test!  This is pi: π";
  int TEST_LENGTH = strlen(TEST_STRING);
  Handle<String> str = String::New(TEST_STRING);
  char* buf = new char[TEST_LENGTH * 2];

  // Iterate over the entire string and use it as the start.
  int EXPECTED_LENGTH = TEST_LENGTH - 1; // We should drop the UTF-8 char.
  for (int start = 0; start < TEST_LENGTH; start++) {
    // Fill the buffer with 'a' to ensure there are no NULLs to start with.
    fill_string(buf, 'a', TEST_LENGTH * 2);
    int copied = str->WriteAscii(buf, start, TEST_LENGTH * 2);
    do_check_eq(copied, EXPECTED_LENGTH - start);
    do_check_eq(strlen(buf), EXPECTED_LENGTH - start);
  }

  delete[] buf;
  context.Dispose();
}
示例#23
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;
}
示例#24
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);
      }

   }
示例#25
0
 TEST_F(JSDeviceTest, createTemplate) {
     HandleScope handle_scope(isolate);
     Local<Context> context = Context::New(isolate, nullptr);
     Context::Scope context_scope(context);
     Handle<Object> global = context->Global();
     jsDevice->initJsObjectsTemplate(isolate, global);
 }
示例#26
0
   Handle<Value> ScriptSystem::ExecuteJS(const std::string& code, const std::string& path)
   {
       // Init JavaScript context
      HandleScope handle_scope;
      Context::Scope context_scope(GetGlobalContext());

      // 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 source code.
      Local<Script> compiled_script = Script::Compile(ToJSString(code), ToJSString(path));

      // if an exception occured
      if(try_catch.HasCaught())
      {
         ReportException(&try_catch);
   //      return try_catch;
      }

      // Run the script!
      Local<Value> ret = compiled_script->Run();
      if(try_catch.HasCaught())
      {
         ReportException(&try_catch);
   //      return try_catch;
      }

      FetchGlobalTickFunction();

      return handle_scope.Close(ret);
   }
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);
    }
}
示例#28
0
int Fragment::Script::ScriptEngine::Init(int argc, char* argv[]) {
    v8::V8::InitializeICU();
    v8::V8::InitializeExternalStartupData(argv[0]);
    v8::Platform *platform = v8::platform::CreateDefaultPlatform();
    v8::V8::InitializePlatform(platform);
    v8::V8::Initialize();
    v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
    ShellArrayBufferAllocator array_buffer_allocator;
    v8::Isolate::CreateParams create_params;
    create_params.array_buffer_allocator = &array_buffer_allocator;
    v8::Isolate *isolate = v8::Isolate::New(create_params);
    run_shell = (argc == 1);

    int result;
    {
        v8::Isolate::Scope isolate_scope(isolate);
        v8::HandleScope handle_scope(isolate);
        v8::Local<v8::Context> context = CreateShellContext(isolate);
        if (context.IsEmpty()) {
            fprintf(stderr, "Error creating context\n");
            return 1;
        }
        v8::Context::Scope context_scope(context);
        result = RunMain(isolate, platform, argc, argv);
        if (run_shell) RunShell(context, platform);
    }

    isolate->Dispose();
    v8::V8::Dispose();
    v8::V8::ShutdownPlatform();
    delete platform;
    return result;
}
示例#29
0
	Status PreludeScript::try_run()
	{
		v8::Context::Scope context_scope(get_context());
		global_template_factory.reset();

		if (!enter_cancellable_region()) 
			return S_TERMINATED;

		v8::Handle<v8::Value> prelude_result = run_script(get_context());
		if (!exit_cancellable_region())
			return S_TERMINATED;

		if (prelude_result.IsEmpty()) 
		{
			set_last_error("Prelude script did not return any value");
			return S_ERROR;
		}
		if (!prelude_result->IsFunction()) 
		{
			set_last_error("Prelude script must return a function");
			return S_ERROR;
		}
		global_template_factory = std::shared_ptr<v8::Persistent<v8::Function>>(
			new v8::Persistent<v8::Function>(v8::Isolate::GetCurrent(), prelude_result.As<v8::Function>()));
		return S_OK;
	}
示例#30
0
//performs the initialization and population of util object, system object,
//and system object's presences array.
void JSContextStruct::createContextObjects()
{
    v8::HandleScope handle_scope;
    v8::Context::Scope context_scope(mContext);

    v8::Local<v8::Object> global_obj = mContext->Global();
    // NOTE: See v8 bug 162 (http://code.google.com/p/v8/issues/detail?id=162)
    // The template actually generates the root objects prototype, not the root
    // itself.
    v8::Handle<v8::Object> global_proto = v8::Handle<v8::Object>::Cast(global_obj->GetPrototype());

    // And we add an internal field to the system object as well to make it
    // easier to find the pointer in different calls. Note that in this case we
    // don't use the prototype -- non-global objects work as we would expect.
    v8::Local<v8::Object> system_obj = v8::Local<v8::Object>::Cast(global_proto->Get(v8::String::New(JSSystemNames::SYSTEM_OBJECT_NAME)));
    system_obj->SetInternalField(SYSTEM_TEMPLATE_SYSTEM_FIELD, v8::External::New(mSystem));
    system_obj->SetInternalField(TYPEID_FIELD, v8::External::New(new String(SYSTEM_TYPEID_STRING)));




    v8::Local<v8::Array> arrayObj = v8::Array::New();
    system_obj->Set(v8::String::New(JSSystemNames::PRESENCES_ARRAY_NAME), arrayObj);

    //populates internal jscontextstruct field
    systemObj = v8::Persistent<v8::Object>::New(system_obj);

    JSUtilStruct* mUtil = new JSUtilStruct(this,jsObjScript);
    Local<Object> util_obj = Local<Object>::Cast(global_proto->Get(v8::String::New(JSSystemNames::UTIL_OBJECT_NAME)));
    util_obj->SetInternalField(UTIL_TEMPLATE_UTILSTRUCT_FIELD,External::New(mUtil));
    util_obj->SetInternalField(TYPEID_FIELD,External::New(new String(UTIL_TYPEID_STRING)));
}