Ejemplo n.º 1
0
v8::Handle<v8::String> V8::toJson(v8::Handle<v8::Value> value) {
	HandleScope scope;

	Handle<Context> context = Context::GetCurrent();
	Handle<Object> global = context->Global();

	Handle<Object> JSON = global->Get(String::New("JSON"))->ToObject();
	Handle<Function> JSON_stringify = Handle<Function>::Cast(JSON->Get(String::New("stringify")));

	TryCatch exception;

	Handle<Value> argv[] = {
		value,
		v8::Null(),
		v8::String::New("\t")
	};

	if (exception.HasCaught()) {
		throw chi::Exception(chi::V8::ReportException(exception));
	}

	Handle<Value> stringified = JSON_stringify->Call(JSON_stringify, 3, argv);

	if (exception.HasCaught()) {
		throw chi::Exception(chi::V8::ReportException(exception));
	}

	return scope.Close(stringified.As<String>());
}
Ejemplo n.º 2
0
// Install the constructor in the global scope so Path2Ds can be constructed
// in JS.
void Path2D::AddToGlobal(Global* global) {
    gGlobal = global;

    // Create a stack-allocated handle scope.
    HandleScope handleScope(gGlobal->getIsolate());

    Handle<Context> context = gGlobal->getContext();

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

    Local<FunctionTemplate> constructor = FunctionTemplate::New(
            gGlobal->getIsolate(), Path2D::ConstructPath);
    constructor->InstanceTemplate()->SetInternalFieldCount(1);

    ADD_METHOD("closePath", ClosePath);
    ADD_METHOD("moveTo", MoveTo);
    ADD_METHOD("lineTo", LineTo);
    ADD_METHOD("quadraticCurveTo", QuadraticCurveTo);
    ADD_METHOD("bezierCurveTo", BezierCurveTo);
    ADD_METHOD("arc", Arc);
    ADD_METHOD("rect", Rect);
    ADD_METHOD("oval", Oval);
    ADD_METHOD("conicTo", ConicTo);

    context->Global()->Set(String::NewFromUtf8(
            gGlobal->getIsolate(), "Path2D"), constructor->GetFunction());
}
Ejemplo n.º 3
0
 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 );
 }
Ejemplo n.º 4
0
v8::Handle<v8::Value> toJson(v8::Handle<v8::Value> value) {
	HandleScope scope;

	Handle<Context> context = Context::GetCurrent();
	Handle<Object> global = context->Global();
	Handle<Object> JSON = global->Get(String::New("JSON"))->ToObject();
	Handle<Function> JSON_stringify = Handle<Function>::Cast(JSON->Get(String::New("stringify")));

	// JSON.stringify(values, null, '\t');
	Handle<Value> argv[] = {
		value,
		Null(),
		String::New("\t")
	};

	TryCatch exception;

	Handle<Value> stringified = JSON_stringify->Call(JSON_stringify, 3, argv);

	if (exception.HasCaught()) {
		return exception.ReThrow();
	}

	return scope.Close(stringified);
}
Ejemplo n.º 5
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);
    }
}
Ejemplo n.º 6
0
 Handle<Value> SCRGetLockCursor(Local<String> propname, const AccessorInfo& info)
 {
    HandleScope handle_scope;
    Handle<Context> context = info.Holder()->CreationContext();
    Handle<Value> ih = context->Global()->Get(String::New("Input"));
    dtEntity::InputInterface* input = UnwrapInputInterface(ih);
    return Boolean::New(input->GetLockCursor());
 }
Ejemplo n.º 7
0
Handle<ObjectTemplate> TiObject::getObjectTemplateFromJsObject(Handle<Value> value)
{
    HandleScope handleScope;
    Handle<Object> obj = Handle<Object>::Cast(value);
    Handle<Context> context = obj->CreationContext();
    Handle<External> globalTemplateExternal = Handle<External>::Cast(
                context->Global()->GetHiddenValue(String::New(HIDDEN_TEMP_OBJECT_PROPERTY)));
    Handle<ObjectTemplate>temp = *((Handle<ObjectTemplate>*) globalTemplateExternal->Value());
    return handleScope.Close(temp);
}
Ejemplo n.º 8
0
static Local<Value> ConstructError(const char *name, Handle<String> message) {
  // XXX: this probably isn't correct in all cases
  Handle<Context> ctx = Context::GetCurrent();
  Handle<Object> global = ctx->Global();
  Handle<Value> ctor = global->Get(String::New(name));
  if (ctor.IsEmpty() || !ctor->IsFunction())
    return Local<Value>();
  Handle<Function> fn = ctor.As<Function>();
  Handle<Value> args[] = { Handle<Value>(message) };
  return Local<Value>::New(fn->NewInstance(1, args));
}
Ejemplo n.º 9
0
   void ScriptSystem::FetchGlobalTickFunction()
   {
      HandleScope scope;
      Handle<Context> context = GetGlobalContext();

      mGlobalTickFunction.Clear();

      Handle<String> funcname = String::New("__executeTimeOuts");
      if(context->Global()->Has(funcname))
      {
         Handle<Value> func = context->Global()->Get(funcname);
         if(!func.IsEmpty())
         {
            Handle<Function> f = Handle<Function>::Cast(func);
            if(!f.IsEmpty())
            {
               mGlobalTickFunction = Persistent<Function>::New(f);
            }
         }
      }
   }
// TODO: move these to a util file
static Local<String> stringify(Handle<Value> object)
{
    HandleScope scope;

    Handle<Context> context = Context::GetCurrent();
    Handle<Object> global = context->Global();

    Handle<Object> JSON = global->Get(String::New("JSON"))->ToObject();
    Handle<Function> JSON_stringify = Handle<Function>::Cast(JSON->Get(String::New("stringify")));

    return scope.Close(JSON_stringify->Call(JSON, 1, &object)->ToString());
}
static Local<Value> parseJson(const QString& json)
{
    Handle<Context> context = Context::GetCurrent();
    Handle<Object> global = context->Global();

    Handle<Object> JSON = global->Get(String::New("JSON"))->ToObject();
    Handle<Function> JSON_parse = Handle<Function>::Cast(JSON->Get(String::New("parse")));

    Handle<Value> value = String::New(json.toUtf8());

    return JSON_parse->Call(JSON, 1, &value);
}
Ejemplo n.º 12
0
static JsonNode* toJsonNode(Handle<Value> object) {
  std::vector<char> buf;
  Handle<Context> context = Context::GetCurrent();
  Handle<Object> global = context->Global();
  Handle<Object> JSON = global->Get(String::New ("JSON"))->ToObject();
  Handle<Function> JSON_stringify = Handle<Function>::Cast(JSON->Get(String::New("stringify")));
  Handle<Value> argv[1] = {
    object
  };
  Handle<String> ret = JSON_stringify->Call(JSON, 1, argv)->ToString();

  buf.resize (ret->Utf8Length());
  ret->WriteUtf8 (buf.data());
  return json_decode (buf.data());
}
Ejemplo n.º 13
0
Handle<Value> V8::parseJson(Handle<String> jsonString) {
	HandleScope scope;

	Handle<Context> context = Context::GetCurrent();
	Handle<Object> global = context->Global();

	Handle<Object> JSON = global->Get(String::New("JSON"))->ToObject();
	Handle<Function> JSON_parse = Handle<Function>::Cast(JSON->Get(String::New("parse")));

	// return JSON.parse.apply(JSON, jsonString);
	Handle<Value> args[] = {
		jsonString
	};
	return scope.Close(JSON_parse->Call(JSON, 1, args));
}
Ejemplo n.º 14
0
static Handle<Value> fromJsonNode(JsonNode* node) {
  char* buf;
  Handle<Context> context = Context::GetCurrent();
  Handle<Object> global = context->Global();
  Handle<Object> JSON = global->Get(String::New ("JSON"))->ToObject();
  Handle<Function> JSON_parse = Handle<Function>::Cast(JSON->Get(String::New("parse")));

  buf = json_encode (node);
  Handle<Value> argv[1] = {
    String::New (buf)
  };
  Handle<Value> parsedObj = JSON_parse->Call(JSON, 1, argv);
  free (buf);

  return parsedObj;
}
Ejemplo n.º 15
0
void Point::Bind( Isolate* isolate, Handle< Context > context ) {
	// Get creation scope
	HandleScope scope( isolate );

	// Create constructor function and object template
	Local< FunctionTemplate > constructor = FunctionTemplate::New( Construct );
	Local< ObjectTemplate > templ = constructor->InstanceTemplate();
	templ->SetInternalFieldCount( 1 );

	// Set properties and methods
	templ->SetAccessor( String::New( "x" ), GetX, SetX );
	templ->SetAccessor( String::New( "y" ), GetY, SetY );
	templ->Set( String::New( "print" ), FunctionTemplate::New( Print ) );

	// Register constructor
	context->Global()->Set( String::New( "Point" ), constructor->GetFunction() );
}
Ejemplo n.º 16
0
   void ScriptSystem::SetupContext()
   {
      HandleScope handle_scope;
      if(!mGlobalContext.IsEmpty())
      {
         mGlobalContext.Dispose();
      }

      // create a template for the global object
      Handle<ObjectTemplate> global = ObjectTemplate::New();

      // create persistent global context
      mGlobalContext = Persistent<Context>::New(Context::New(NULL, global));

      // store pointer to script system into isolate data to have it globally available in javascript
      Isolate::GetCurrent()->SetData(this);

      RegisterGlobalFunctions(this, mGlobalContext);
      RegisterPropertyFunctions(this, mGlobalContext);

      InitializeAllWrappers(GetEntityManager());

      Handle<Context> context = GetGlobalContext();
      Context::Scope context_scope(context);
      Handle<FunctionTemplate> tmplt = FunctionTemplate::New();
      tmplt->InstanceTemplate()->SetInternalFieldCount(2);

      tmplt->SetClassName(String::New("ScriptSystem"));

      context->Global()->Set(String::New("Screen"), WrapScreen(this));

      dtEntity::InputInterface* ipiface = dtEntity::GetInputInterface();
      if(ipiface)
      {
         context->Global()->Set(String::New("Input"), WrapInputInterface(GetGlobalContext(), ipiface));
         context->Global()->Set(String::New("Axis"), WrapAxes(ipiface));
         context->Global()->Set(String::New("Key"), WrapKeys(ipiface));
      }

      context->Global()->Set(String::New("TouchPhase"), WrapTouchPhases());
      context->Global()->Set(String::New("Priority"), WrapPriorities());
      context->Global()->Set(String::New("Order"), WrapPriorities());

   }
Ejemplo n.º 17
0
extern "C" Handle<Value> apply_function_arr(Handle<Context> context,
					    Handle<Function> func, int argc,
					    Handle<Value>* argv, bool* is_exception) {
    HandleScope handle_scope;

    Context::Scope context_scope(context);

    TryCatch trycatch;
    
    Handle<Value> result = func->Call(context->Global(), argc, argv);

    if (result.IsEmpty()) {
	*is_exception = true;
	Handle<Value> exception = trycatch.Exception();
	// String::AsciiValue exception_str(exception);
	return Persistent<Value>::New(exception);
    }

    Persistent<Value> js_result = Persistent<Value>::New(result);

    return js_result;
}
Ejemplo n.º 18
0
Handle<Value> Susi::JS::Engine::convertFromCPP(Susi::Util::Any cppVal){
	if(cppVal.isNull()){
		return Handle<Value>{};
	}
	std::cout<<Susi::JS::engine->isolate<<std::endl;
	auto isolate = Susi::JS::engine->isolate;
	Handle<Context> context = isolate->GetCurrentContext();
    Handle<Object> global = context->Global();
 	Handle<Object> JSON = global->Get(String::NewFromUtf8(isolate,"JSON"))->ToObject();
    Handle<Function> JSON_parse = Handle<Function>::Cast(JSON->Get(String::NewFromUtf8(isolate,"parse")));
	Handle<Value> arguments[1];
	std::cout<<cppVal.toString()<<std::endl;

	arguments[0] = String::NewFromUtf8(isolate,cppVal.toString().c_str());
	TryCatch trycatch;
	auto res = JSON_parse->Call(JSON, 1, arguments);
	if (res.IsEmpty()) {
		Handle<Value> exception = trycatch.Exception();
		String::Utf8Value exception_str(exception);
		std::cout<<*exception_str<<std::endl;
		throw std::runtime_error{*exception_str};
	}
	return res;
}
Ejemplo n.º 19
0
   void InitializeAllWrappers(dtEntity::EntityManager& em)
   {
      
      dtEntity::MapSystem* mapsystem;
      if(!em.GetEntitySystem(dtEntity::MapComponent::TYPE, mapsystem))
      {
        LOG_ERROR("Could not get map system!");
        return;
      }

      ScriptSystem* scriptsystem;
      if(!em.GetEntitySystem(ScriptSystem::TYPE, scriptsystem))
      {
        LOG_ERROR("Could not get script system!");
        return;
      }

      HandleScope handle_scope;
      Handle<Context> context = scriptsystem->GetGlobalContext();      
      Context::Scope context_scope(context);
      
      context->Global()->Set(String::New("DebugDrawManager"), CreateDebugDrawManager(context));
      //context->Global()->Set(String::New("Layer"), FunctionTemplate::New(CreateNewLayer)->GetFunction());

      // make entity manager accessible as a global variable
      context->Global()->Set(String::New("EntityManager"), WrapEntityManager(scriptsystem, &em));

      context->Global()->Set(String::New("NodeMasks"), WrapNodeMasks());

      context->Global()->Set(String::New("Buffer"), CreateBuffer());
      context->Global()->Set(String::New("File"), CreateFile());
      context->Global()->Set(String::New("Log"), WrapLogger(context));

      InitMapSystemWrapper(scriptsystem);
      
#if BUILD_OPENAL
      InitSoundSystemWrapper(scriptsystem);
#endif

   }
Ejemplo n.º 20
0
Archivo: context.cpp Proyecto: sol/v8
void c_contextAddFunction(Handle<Context> context, char* name, const InvocationCallback f) {
  HandleScope scope;
  Local<Function> fun = FunctionTemplate::New(f)->GetFunction();
  context->Global()->Set(String::New(name), fun);
}
Ejemplo n.º 21
0
bool V8GL::initialize(int* pargc, char** argv, string scriptname) {
	  // Create a handle scope to hold the temporary references.
	  HandleScope handle_scope;

	  // Create a template for the global object where we set the
	  // built-in global functions.
	  Handle<ObjectTemplate> global = ObjectTemplate::New();

	  // Each processor gets its own context so different processors
	  // don't affect each other.
#ifdef BUILD_GL_BINDINGS
	  Handle<ObjectTemplate> Gl = GlFactory::createGl();
#endif
#ifdef BUILD_GLES_BINDINGS
	  Handle<ObjectTemplate> Gles = GlesFactory::createGles();
#endif
#ifdef BUILD_GLESUTIL_BINDINGS
	  Handle<ObjectTemplate> Glesutil = GlesutilFactory::createGlesutil();
#endif

	  //Set global objects and functions.
#ifdef BUILD_GL_BINDINGS
	  global->Set(String::New("Gl"), Gl);
#endif
#ifdef BUILD_GLES_BINDINGS
	  global->Set(String::New("Gles"), Gles);
#endif
#ifdef BUILD_GLESUTIL_BINDINGS
	  global->Set(String::New("Glesutil"), Glesutil);
#endif
#ifdef BUILD_GLU_BINDINGS
	  global->Set(String::New("Glu"), createGlu());
#endif
#ifdef BUILD_GLUT_BINDINGS
	  global->Set(String::New("Glut"), GlutFactory::createGlut(pargc, argv));
#endif
	  global->Set(String::New("log"), FunctionTemplate::New(log));
	  global->Set(String::New("load"), FunctionTemplate::New(load));
	  global->Set(String::New("read"), FunctionTemplate::New(read));

	  Handle<Context> context = Context::New(NULL, global);

	  //TODO(nico): should find another way to set the right context when calling a func.
	  V8GL::context = Persistent<Context>::New(context);
#ifdef BUILD_GLUT_BINDINGS
	  GlutFactory::glut_persistent_context = V8GL::context;
#endif
#ifdef BUILD_GLES_BINDINGS
	  GlesFactory::gles_persistent_context = V8GL::context;
#endif

	  // Enter the new context so all the following operations take place
	  // within it.
	  Context::Scope context_scope(context);
	  // hook up typed array support
	  v8_typed_array_init(context->Global());

	  //Append *this* as Gl static variable so we can do dot-this-dot-that stuff
#ifdef BUILD_GL_BINDINGS
	  GlFactory::self_ = Persistent<Object>::New(Gl->NewInstance());
#endif
#ifdef BUILD_GLES_BINDINGS
	  GlesFactory::self_ = Persistent<Object>::New(Gles->NewInstance());
#endif
#ifdef BUILD_GLESUTIL_BINDINGS
	  GlesFactory::self_ = Persistent<Object>::New(Glesutil->NewInstance());
#endif

	  //Set (only once) the absolute path for the .js file being executed.
	  V8GLUtils::setRootPath(argv[0], argv[1]);

	  // Compile and run the script
	  if (!executeScript(scriptname))
		return false;

	  return true;
}