Example #1
0
static void ctx_get_nested_prop(struct state *state, VALUE props)
{
  duk_context *ctx = state->ctx;

  switch (TYPE(props)) {
    case T_STRING:
      duk_push_global_object(ctx);
      ctx_get_one_prop(state, props, 1);
      return;

    case T_ARRAY:
      duk_push_global_object(ctx);

      long len = RARRAY_LEN(props);
      for (int i = 0; i < len; i++) {
        VALUE item = rb_ary_entry(props, i);
        Check_Type(item, T_STRING);

        // Only do a strict check on the first item
        ctx_get_one_prop(state, item, i == 0);
      }
      return;

    default:
      clean_raise(ctx, rb_eTypeError, "wrong argument type %s (expected String or Array)", rb_obj_classname(props));
      return;
  }
}
Example #2
0
/* strict: error
 * (non-strict: return 0)
 */
static duk_ret_t test_ex_nonwritable(duk_context *ctx) {
	duk_ret_t rc;

	printf("strict: %d\n", (int) duk_is_strict_call(ctx));

	/* Math.PI is not writable */

	duk_set_top(ctx, 0);
	duk_push_global_object(ctx);
	rc = duk_get_prop_string(ctx, -1, "Math");  /* -> [ global Math ] */
	printf("get Math -> rc=%d\n", (int) rc);

	rc = duk_get_prop_string(ctx, -1, "PI");
	printf("Math.PI=%s\n", duk_to_string(ctx, -1));
	duk_pop(ctx);

	duk_push_string(ctx, "PI");
	duk_push_string(ctx, "bar");
	rc = duk_put_prop(ctx, -3);
	printf("put rc=%d\n", (int) rc);

	rc = duk_get_prop_string(ctx, -1, "PI");
	printf("Math.PI=%s\n", duk_to_string(ctx, -1));
	duk_pop(ctx);

	printf("final top: %ld\n", (long) duk_get_top(ctx));
	return 0;
}
Example #3
0
File: vm.c Project: joegen/sjs
static int sjs__compile_execute(duk_context *ctx) {
    const char *code;
    const char* filename;
    duk_size_t len;
    bool use_strict;
    int flags;

    /* [ ... use_strict code len filename ] */

    use_strict = duk_require_boolean(ctx, -4);
    code = duk_require_pointer(ctx, -3);
    len = duk_require_uint(ctx, -2);
    filename = duk_require_string(ctx, -1);

    flags = 0;
    if (use_strict) {
        flags |= DUK_COMPILE_STRICT;
    }

    /* remove shebang if present */
    if (strncmp(code, "#!", 2) == 0) {
        memcpy((void*) code, "//", 2);
    }

    duk_compile_lstring_filename(ctx, flags, code, len);

    /* [ ... use_strict code len function ] */

    duk_push_global_object(ctx);  /* 'this' binding */
    duk_push_string(ctx, filename);
    duk_put_prop_string(ctx, -2, "__file__");
    duk_call_method(ctx, 0);

    return 1;    /* either the result or error are on the stack top */
}
Example #4
0
void Engine::registerGlobal(const char* id,
                            Function getter, Function setter)
{
  ContextHandle handle = m_ctx.handle();

  duk_push_global_object(handle);
  duk_push_string(handle, id);

  duk_idx_t objidx = -2;
  duk_uint_t flags = 0;

  if (getter) {
    flags |= DUK_DEFPROP_HAVE_GETTER;
    duk_push_c_function(handle, getter, 0);
    --objidx;
  }

  if (setter) {
    flags |= DUK_DEFPROP_HAVE_SETTER;
    duk_push_c_function(handle, setter, 1);
    --objidx;
  }

  duk_def_prop(handle, objidx, flags);
}
Example #5
0
int wrapped_compile_execute(duk_context *ctx) {
	int comp_flags;

	comp_flags = 0;
	duk_compile(ctx, comp_flags);

#if 0
	/* FIXME: something similar with public API */
	if (interactive_mode) {
		duk_hcompiledfunction *f = (duk_hcompiledfunction *) duk_get_hobject(ctx, -1);

		if (f && DUK_HOBJECT_IS_COMPILEDFUNCTION((duk_hobject *) f)) {
			fprintf(stdout, "[bytecode length %d opcodes, registers %d, constants %d, inner functions %d]\n",
				(int) DUK_HCOMPILEDFUNCTION_GET_CODE_COUNT(f),
				(int) f->nregs,
				(int) DUK_HCOMPILEDFUNCTION_GET_CONSTS_COUNT(f),
				(int) DUK_HCOMPILEDFUNCTION_GET_FUNCS_COUNT(f));
			fflush(stdout);
		} else {
			fprintf(stdout, "[invalid compile result]\n");
			fflush(stdout);
		}
	}
#endif

	duk_push_global_object(ctx);  /* 'this' binding */
	duk_call_method(ctx, 0);

	if (interactive_mode) {
		/*
		 *  In interactive mode, write to stdout so output won't interleave as easily.
		 *
		 *  NOTE: the ToString() coercion may fail in some cases; for instance,
		 *  if you evaluate:
		 *
		 *    ( {valueOf: function() {return {}}, toString: function() {return {}}});
		 *
		 *  The error is:
		 *
		 *    TypeError: failed to coerce with [[DefaultValue]]
		 *            duk_api.c:1420
		 *
		 *  These errors are caught and printed out as errors although
		 *  the errors are not generated by user code as such.  Changing
		 *  duk_to_string() to duk_safe_to_string() would avoid these
		 *  errors.
		 */

		fprintf(stdout, "= %s\n", duk_to_string(ctx, -1));
		fflush(stdout);
	} else {
		/* In non-interactive mode, success results are not written at all.
		 * It is important that the result value is not string coerced,
		 * as the string coercion may cause an error in some cases.
		 */
	}

	duk_pop(ctx);
	return 0;
}
Example #6
0
JNIEXPORT jobject JNICALL Java_com_furture_react_DuktapeEngine_nativeCallJs
  (JNIEnv *env, jobject thisObject, jlong ptr, jstring jsTarget, jstring jsMethod, jobjectArray args){
	duk_context *ctx  = convert_to_context(ptr);
	jboolean iscopy = JNI_FALSE;
    const char* targetName = ((*env)->GetStringUTFChars(env, jsTarget, &iscopy));
    DEBUG_LOG("ScriptEngine","Java_com_furture_react_DuktapeEngine_nativeCallJs call on %s", targetName);
	duk_push_global_object(ctx);
    if(duk_get_prop_string(ctx, -1, targetName)){
    	    const char* methodName = ((*env)->GetStringUTFChars(env, jsMethod, &iscopy));
	    duk_push_string(ctx, methodName);
	    jsize length = duk_push_java_object_array(ctx, env, args);
	    DEBUG_LOG("ScriptEngine","Java_com_furture_react_DuktapeEngine_nativeCallJs call  Function %d", length);
	    if(duk_pcall_prop(ctx, -2 - length, length) != DUK_EXEC_SUCCESS){
	     	LOGE("ScriptEngine","ScriptEngine CallJS %s.%s() method %s", targetName, methodName, duk_js_error_to_string(ctx, -1));
	        duk_pop(ctx);
	        duk_push_null(ctx);
	    }
 	    (*env)->ReleaseStringUTFChars(env, jsTarget, targetName);
	    (*env)->ReleaseStringUTFChars(env, jsMethod, methodName);
	    jobject  value =  duk_to_java_object(ctx, env, -1);
	    duk_pop_2(ctx);
	    return value;
    }
    (*env)->ReleaseStringUTFChars(env, jsTarget, targetName);
    duk_pop_2(ctx);
    return NULL;

}
Example #7
0
int duk_import_java_class(duk_context *ctx){
	DEBUG_LOG("DuktapeEngine", "className duk_import_java_class");
	int n = duk_get_top(ctx);
	const char* className = duk_to_string(ctx, 0);
	const char*  shortName = NULL;
	if(n > 1){
		shortName = duk_to_string(ctx, 1);
	}else{
		shortName = strrchr(className, '.');
		shortName++;
	}
	DEBUG_LOG("DuktapeEngine", "className %s  shorName %s",className, shortName);

	duk_push_global_object(ctx);
	duk_push_c_function(ctx, duk_new_java_class,  DUK_VARARGS);

	JNIEnv *env = get_java_jni_env();
	jstring  fullClassName = (*env)->NewStringUTF(env, className);
    jobject  value =  (*env)->CallStaticObjectMethod(env, java_api_class, java_import_class_method, fullClassName);
	duk_mark_jsobject_to_java_object(ctx, -1, env, value);
    (*env)->DeleteLocalRef(env, value);
	(*env)->DeleteLocalRef(env, fullClassName);
	duk_push_object(ctx);
    duk_push_string(ctx, className);
    duk_put_prop_string(ctx, -2, "className");
    duk_put_prop_string(ctx, -2, "prototype");
    duk_put_prop_string(ctx, -2, shortName);
    duk_pop(ctx);
    return 0;
}
Example #8
0
void duk_eval_file(duk_context *ctx, const char *path) {
	duk_push_string_file_raw(ctx, path, 0);
	duk_push_string(ctx, path);
	duk_compile(ctx, DUK_COMPILE_EVAL);
	duk_push_global_object(ctx);  /* 'this' binding */
	duk_call_method(ctx, 0);
}
 void OnSignal(Entity * param0, Entity * param1, const float3 & param2, const float3 & param3, float param4, float param5, bool param6)
 {
     duk_context* ctx = ctx_;
     duk_push_global_object(ctx);
     duk_get_prop_string(ctx, -1, "_OnSignal");
     duk_remove(ctx, -2);
     duk_push_number(ctx, (size_t)key_);
     duk_push_array(ctx);
     PushWeakObject(ctx, param0);
     duk_put_prop_index(ctx, -2, 0);
     PushWeakObject(ctx, param1);
     duk_put_prop_index(ctx, -2, 1);
     PushValueObjectCopy<float3>(ctx, param2, float3_ID, float3_Finalizer);
     duk_put_prop_index(ctx, -2, 2);
     PushValueObjectCopy<float3>(ctx, param3, float3_ID, float3_Finalizer);
     duk_put_prop_index(ctx, -2, 3);
     duk_push_number(ctx, param4);
     duk_put_prop_index(ctx, -2, 4);
     duk_push_number(ctx, param5);
     duk_put_prop_index(ctx, -2, 5);
     duk_push_boolean(ctx, param6);
     duk_put_prop_index(ctx, -2, 6);
     bool success = duk_pcall(ctx, 2) == 0;
     if (!success) LogError("[JavaScript] OnSignal: " + GetErrorString(ctx));
     duk_pop(ctx);
 }
Example #10
0
void duk_push_java_object(duk_context *ctx, JNIEnv *env, jobject object){
	if(object == NULL){
		duk_push_null(ctx);
		return;
	}
	if((*env)->IsInstanceOf(env, object, js_ref_class)){
		jint  ref = (*env)->CallIntMethod(env, object, js_ref_get_ref_method);
		duk_push_js_ref(ctx, ref);
		return;
	}
	if((*env)->IsInstanceOf(env, object, java_number_class)){
		jdouble num = (*env)->CallDoubleMethod(env, object, java_number_get_double_value_method);
		duk_push_global_object(ctx);
		duk_get_prop_string(ctx, -1, "Number");
		duk_push_number(ctx, num);
		duk_new(ctx, 1);
		duk_mark_jsobject_to_java_object(ctx, -1, env, object);
		duk_remove(ctx, -2);
        return;
	}
	if((*env)->IsInstanceOf(env, object, java_boolean_class)){
		jboolean value = (*env)->CallBooleanMethod(env, object, java_boolean_get_boolean_value_method);
		if(value){
			duk_push_true(ctx);
		}else{
			duk_push_false(ctx);
		}
		return;
	}
	duk_push_object(ctx);  //empty target
	duk_mark_jsobject_to_java_object(ctx, -1, env, object);
}
Example #11
0
DuktapeJSE::Status DuktapeJSE::analyzeSNSS(const std::string& strJsFileName,
        const std::string& strSNSSFileName,
        const std::string& strJsonParams,
        std::string& strResult)
{
    if( !FileExists(strJsFileName) )
        return Status::JSFILE_NOT_EXISTS;

    if( !FileExists(strSNSSFileName) )
        return Status::SNSS_FILE_NOT_VALID;

    if( !isJsonValid(strJsonParams))
        return Status::INVALID_JSON_PARAMS;

    duk_context* ctx = duk_create_heap_default();
    if(!ctx)
        return Status::HEAP_CREATION_ERROR;

    duk_push_global_object(ctx);
    SnssFileAPI snssFileApi(ctx, strSNSSFileName);

    if( duk_peval_file(ctx, strJsFileName.c_str()) != 0 )
    {
        LOG_MSG(ILogger::default(), LOG_LEVEL_WARN, "DuktapeJSE: %s", duk_safe_to_string(ctx, -1));
        duk_destroy_heap(ctx);
        return Status::INVALID_SOURCE_CODE;
    }
Example #12
0
void
duk_push_sphere_bytearray(duk_context* ctx, bytearray_t* array)
{
	duk_push_object(ctx);
	duk_push_string(ctx, "bytearray"); duk_put_prop_string(ctx, -2, "\xFF" "sphere_type");
	duk_push_pointer(ctx, array); duk_put_prop_string(ctx, -2, "\xFF" "ptr");
	duk_push_c_function(ctx, js_ByteArray_finalize, DUK_VARARGS); duk_set_finalizer(ctx, -2);
	duk_push_c_function(ctx, js_ByteArray_toString, DUK_VARARGS); duk_put_prop_string(ctx, -2, "toString");
	duk_push_c_function(ctx, js_ByteArray_concat, DUK_VARARGS); duk_put_prop_string(ctx, -2, "concat");
	duk_push_c_function(ctx, js_ByteArray_slice, DUK_VARARGS); duk_put_prop_string(ctx, -2, "slice");
	duk_push_string(ctx, "length"); duk_push_int(ctx, array->size);
	duk_def_prop(ctx, -3,
		DUK_DEFPROP_HAVE_CONFIGURABLE | 0
		| DUK_DEFPROP_HAVE_WRITABLE | 0
		| DUK_DEFPROP_HAVE_VALUE);

	// return proxy object so we can catch array accesses
	duk_push_global_object(ctx);
	duk_get_prop_string(ctx, -1, "Proxy");
	duk_dup(ctx, -3);
	duk_push_object(ctx);
	duk_push_c_function(ctx, js_ByteArray_getProp, DUK_VARARGS); duk_put_prop_string(ctx, -2, "get");
	duk_push_c_function(ctx, js_ByteArray_setProp, DUK_VARARGS); duk_put_prop_string(ctx, -2, "set");
	duk_new(ctx, 2);
	duk_remove(ctx, -2);
	duk_remove(ctx, -2);
}
Example #13
0
/* duk_get_prop(), test in API doc (more or less) */
static duk_ret_t test_1d(duk_context *ctx) {
	int cfg_idx;

	prep(ctx);

	/* reading [global object].Math.PI */
	duk_push_global_object(ctx);    /* -> [ global ] */
	duk_push_string(ctx, "Math");   /* -> [ global "Math" ] */
	duk_get_prop(ctx, -2);          /* -> [ global Math ] */
	duk_push_string(ctx, "PI");     /* -> [ global Math "PI" ] */
	duk_get_prop(ctx, -2);          /* -> [ global Math PI ] */
	printf("Math.PI is %lf\n", duk_get_number(ctx, -1));
	duk_pop_n(ctx, 3);

	/* fake config object */
	cfg_idx = duk_get_top(ctx);
	duk_push_string(ctx, "{\"mySetting\": \"setting value\"}");
	duk_json_decode(ctx, cfg_idx);

	/* reading a configuration value, cfg_idx is normalized
	 * index of a configuration object.
	 */
	duk_push_string(ctx, "mySetting");
	if (duk_get_prop(ctx, cfg_idx)) {
	    const char *str_value = duk_to_string(ctx, -1);
	    printf("configuration setting present, value: %s\n", str_value);
	} else {
	    printf("configuration setting missing\n");
	}
	duk_pop(ctx);  /* remember to pop, regardless of whether or not present */

	printf("final top: %ld\n", (long) duk_get_top(ctx));
	return 0;
}
Example #14
0
    static Box * PrivatePush( duk_context * ctx, const size_t class_index, const size_t object_size, finalizer_t finalizer )
    {
        duk_push_global_object( ctx );
        duk_get_prop_string( ctx, -1, "Proxy" );
        duk_remove( ctx, -2 );

        duk_push_object( ctx );

        size_t require_size = sizeof( Box ) + object_size;

        Box * box = reinterpret_cast<Box*>( duk_push_fixed_buffer( ctx, require_size ) );
        box->ClassIndex = class_index;
        box->Finalizer = finalizer;

        duk_put_prop_string( ctx, -2, "\xFF" "Box" );

        duk_push_c_function( ctx, &internal::ClassFinalizer, 1 );
        duk_set_finalizer( ctx, -2 );

        duk_push_heap_stash( ctx );
        duk_get_prop_string( ctx, -1, "InstanceHandler" );
        duk_remove( ctx, -2 );
        duk_new( ctx, 2 );

        return box;
    }
Example #15
0
void
_gum_duk_create_subclass (duk_context * ctx,
                          const gchar * parent,
                          const gchar * name,
                          duk_c_function constructor,
                          gint constructor_nargs,
                          duk_c_function finalize)
{
  duk_push_global_object (ctx);
  duk_get_prop_string (ctx, -1, "Object");
  duk_get_prop_string (ctx, -1, "create");

  duk_get_prop_string (ctx, -3, parent);
  duk_get_prop_string (ctx, -1, "prototype");
  duk_dup (ctx, -3);
  duk_dup (ctx, -2);
  duk_call (ctx, 1);

  if (constructor != NULL)
    duk_push_c_function (ctx, constructor, constructor_nargs);
  else
    duk_push_object (ctx);

  duk_dup (ctx, -2);
  if (finalize != NULL)
  {
    duk_push_c_function (ctx, finalize, 2);
    duk_set_finalizer (ctx, -2);
  }
  duk_put_prop_string (ctx, -2, "prototype");
  duk_put_prop_string (ctx, -7, name);
  duk_pop_n (ctx, 6);
}
Example #16
0
void ncurses_register(duk_context *ctx) {
	duk_push_global_object(ctx);
	duk_push_string(ctx, "Ncurses");
	duk_push_object(ctx);

	duk_push_c_function(ctx, ncurses_initscr, 0);
	duk_put_prop_string(ctx, -2, "initscr");

	duk_push_c_function(ctx, ncurses_endwin, 0);
	duk_put_prop_string(ctx, -2, "endwin");

	duk_push_c_function(ctx, ncurses_delscreen, 0);
	duk_put_prop_string(ctx, -2, "delscreen");

	duk_push_c_function(ctx, ncurses_getmaxyx, 0);
	duk_put_prop_string(ctx, -2, "getmaxyx");

	duk_push_c_function(ctx, ncurses_printw, 1);
	duk_put_prop_string(ctx, -2, "printw");

	duk_push_c_function(ctx, ncurses_mvprintw, 3);
	duk_put_prop_string(ctx, -2, "mvprintw");

	duk_push_c_function(ctx, ncurses_refresh, 0);
	duk_put_prop_string(ctx, -2, "refresh");

	duk_push_c_function(ctx, ncurses_getch, 0);
	duk_put_prop_string(ctx, -2, "getch");

	duk_put_prop(ctx, -3);
	duk_pop(ctx);
}
Example #17
0
int main(int argc, const char *argv[]) {
    duk_context *ctx = NULL;

    ctx = duk_create_heap_default();
    if (!ctx) {
        printf("Failed to create a Duktape heap.\n");
        exit(1);
    }

    duk_push_global_object(ctx);
    duk_push_c_function(ctx, native_prime_check, 2 /*nargs*/);
    duk_put_prop_string(ctx, -2, "primeCheckNative");

    if (duk_peval_file(ctx, "prime.js") != 0) {
        printf("Error: %s\n", duk_safe_to_string(ctx, -1));
        goto finished;
    }
    duk_pop(ctx);  /* ignore result */

    duk_get_prop_string(ctx, -1, "primeTest");
    if (duk_pcall(ctx, 0) != 0) {
        printf("Error: %s\n", duk_safe_to_string(ctx, -1));
    }
    duk_pop(ctx);  /* ignore result */

 finished:
    duk_destroy_heap(ctx);

    exit(0);
}
Example #18
0
/*
 * call-seq:
 *   ctx_define_function(name, &block) -> nil
 *
 * Define a function defined in the global scope and identified by a name.
 *
 *     ctx.ctx_define_function("hello_world") { |ctx| 'Hello world' } #=> nil
 *
 */
static VALUE ctx_define_function(VALUE self, VALUE prop)
{
  VALUE block;
  struct state *state;
  duk_context *ctx;

  // a block is required
  if (!rb_block_given_p())
    rb_raise(rb_eArgError, "Expected block");

  // get the context
  Data_Get_Struct(self, struct state, state);
  ctx = state->ctx;

  // the c function is available in the global scope
  duk_push_global_object(ctx);

  duk_push_c_function(ctx, ctx_call_pushed_function, DUK_VARARGS);

  block = rb_block_proc();
  rb_ary_push(state->blocks, block); // block will be properly garbage collected

  // both block and state are required by the pushed function
  duk_push_string(ctx, "block");
  duk_push_pointer(ctx, (void *) block);
  duk_def_prop(ctx, -3,  DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_HAVE_WRITABLE | 0);

  duk_push_string(ctx, "state");
  duk_push_pointer(ctx, (void *) state);
  duk_def_prop(ctx, -3,  DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_HAVE_WRITABLE | 0);

  duk_put_prop_string(ctx, -2, StringValueCStr(prop));

  return Qnil;
}
Example #19
0
void fileio_register(duk_context *ctx) {
	/* Set global 'FileIo'. */
	duk_push_global_object(ctx);
	duk_push_object(ctx);
	duk_put_function_list(ctx, -1, fileio_funcs);
	duk_put_prop_string(ctx, -2, "FileIo");
	duk_pop(ctx);
}
Example #20
0
void Engine::registerFunction(const char* id, Function function, int nargs)
{
  ContextHandle handle = m_ctx.handle();

  duk_push_global_object(handle);
  duk_push_c_function(handle, function, nargs);
  duk_put_prop_string(handle, -2, id);
}
Example #21
0
static int wrapped_compile_execute(duk_context *ctx) {
	duk_compile (ctx, 0);
	duk_push_global_object (ctx);
	duk_call_method (ctx, 0);
// return value is stored here	duk_to_string(ctx, -1);
	duk_pop (ctx);
	return 0;
}
Example #22
0
File: main.c Project: dzzie/duk4vb
void RegisterNativeHandlers(duk_context *ctx){
	
	duk_push_global_object(ctx);
	duk_push_c_function(ctx, comResolver, DUK_VARARGS);
	duk_put_prop_string(ctx, -2, "resolver");
	duk_pop(ctx);  /* pop global */

	duk_push_global_object(ctx);
	duk_push_c_function(ctx, prompt, 2);
	duk_put_prop_string(ctx, -2, "prompt");
	duk_pop(ctx);  /* pop global */

	duk_push_global_object(ctx);
	duk_push_c_function(ctx, my_alert, 2);
	duk_put_prop_string(ctx, -2, "alert");
	duk_pop(ctx);  /* pop global */

	//duk_eval_string(ctx, "Duktape.Logger.clog.l = 0;");duk_pop(ctx); //change log level
	duk_eval_string(ctx, "Duktape.Logger.prototype.raw = print");
	duk_pop(ctx);

	/* ReferenceError: does not include a line number
	   SyntaxError: always include line number.
	   err type is not part of err.message, (line is not part of err.message either not sure how to detect type, but 
	   easy answer is to just always add it for standardization... but sometimes we get a 2x display bug with this code.. 
	   this is easy enough..we will just detect it in the ocx and strip it.
	*/
	duk_eval_string(ctx,"Duktape.errCreate = function (err) "
		              " {\n"  
					  "  try { \n"
					  "   if (typeof err === 'object' &&\n"
					  "       typeof err.message !== 'undefined' &&\n"
					  "        typeof err.lineNumber === 'number')"
	                  "      { \n"
					  "        //alert(err.message.indexOf('ReferenceError:')+' '+err.message);\n"
					  "		   err.message = err.message + ' (line ' + err.lineNumber + ')';\n"
					  "      } \n"
					  "  } catch (e) { \n"
					  "    // ignore; for cases such as where message is not writable etc\n"
					  "  } \n"
					  "  return err;\n"
					  " }");
	duk_pop(ctx);   

}
Example #23
0
void JsLibrarian::Register(duk_context* duktapeContext)
{
   duk_push_global_object(duktapeContext);

   duk_push_c_function(duktapeContext, JsLibrarian::Constructor, DUK_VARARGS);
   duk_put_prop_string(duktapeContext, -2, "Librarian");

   duk_pop(duktapeContext);
}
void DuktapeContext::set(JNIEnv *env, jstring name, jobject object, jobjectArray methods) {
  CHECK_STACK(m_context);
  duk_push_global_object(m_context);
  const JString instanceName(env, name);
  if (duk_has_prop_string(m_context, -1, instanceName)) {
    duk_pop(m_context);
    queueIllegalArgumentException(env,
       "A global object called " + instanceName.str() + " already exists");
    return;
  }
  const duk_idx_t objIndex = duk_require_normalize_index(m_context, duk_push_object(m_context));

  // Hook up a finalizer to decrement the refcount and clean up our JavaMethods.
  duk_push_c_function(m_context, javaObjectFinalizer, 1);
  duk_set_finalizer(m_context, objIndex);

  const jsize numMethods = env->GetArrayLength(methods);
  for (jsize i = 0; i < numMethods; ++i) {
    jobject method = env->GetObjectArrayElement(methods, i);

    const jmethodID getName =
        env->GetMethodID(env->GetObjectClass(method), "getName", "()Ljava/lang/String;");
    const JString methodName(env, static_cast<jstring>(env->CallObjectMethod(method, getName)));

    std::unique_ptr<JavaMethod> javaMethod;
    try {
      javaMethod.reset(new JavaMethod(m_javaValues, env, method));
    } catch (const std::invalid_argument& e) {
      queueIllegalArgumentException(env, "In bound method \"" +
          instanceName.str() + "." + methodName.str() + "\": " + e.what());
      // Pop the object being bound and the duktape global object.
      duk_pop_2(m_context);
      return;
    }

    // Use VARARGS here to allow us to manually validate that the proper number of arguments are
    // given in the call.  If we specify the actual number of arguments needed, Duktape will try to
    // be helpful by discarding extra or providing missing arguments. That's not quite what we want.
    // See http://duktape.org/api.html#duk_push_c_function for details.
    const duk_idx_t func = duk_push_c_function(m_context, javaMethodHandler, DUK_VARARGS);
    duk_push_pointer(m_context, javaMethod.release());
    duk_put_prop_string(m_context, func, JAVA_METHOD_PROP_NAME);

    // Add this method to the bound object.
    duk_put_prop_string(m_context, objIndex, methodName);
  }

  // Keep a reference in JavaScript to the object being bound.
  duk_push_pointer(m_context, env->NewGlobalRef(object));
  duk_put_prop_string(m_context, objIndex, JAVA_THIS_PROP_NAME);

  // Make our bound Java object a property of the Duktape global object (so it's a JS global).
  duk_put_prop_string(m_context, -2, instanceName);
  // Pop the Duktape global object off the stack.
  duk_pop(m_context);
}
Example #25
0
int main(int argc, const char *argv[]) {
    duk_context *ctx = NULL;
    char line[4096];
    size_t idx;
    int ch;

    (void) argc; (void) argv;

    ctx = duk_create_heap_default();
    if (!ctx) {
        printf("Failed to create a Duktape heap.\n");
        exit(1);
    }

    push_file_as_string(ctx, "process.js");
    if (duk_peval(ctx) != 0) {
        printf("Error: %s\n", duk_safe_to_string(ctx, -1));
        goto finished;
    }
    duk_pop(ctx);  /* ignore result */

    memset(line, 0, sizeof(line));
    idx = 0;
    for (;;) {
        if (idx >= sizeof(line)) {
            printf("Line too long\n");
            exit(1);
        }

        ch = fgetc(stdin);
        if (ch == 0x0a) {
            line[idx++] = '\0';

            duk_push_global_object(ctx);
            duk_get_prop_string(ctx, -1 /*index*/, "processLine");
            duk_push_string(ctx, line);
            if (duk_pcall(ctx, 1 /*nargs*/) != 0) {
                printf("Error: %s\n", duk_safe_to_string(ctx, -1));
            } else {
                printf("%s\n", duk_safe_to_string(ctx, -1));
            }
            duk_pop(ctx);  /* pop result/error */

            idx = 0;
        } else if (ch == EOF) {
            break;
        } else {
            line[idx++] = (char) ch;
        }
    }

 finished:
    duk_destroy_heap(ctx);

    exit(0);
}
Example #26
0
jobject get_engine_from_context(duk_context *ctx){
	    duk_push_global_object(ctx);
		if(duk_get_prop_string(ctx, -1, JAVA_ENGINE_MARK)){
			jobject  engine =  duk_to_pointer(ctx, -1);
		    duk_pop_2(ctx);
		    return engine;
		}
		duk_pop_2(ctx);
		return NULL;
}
Example #27
0
JNIEXPORT void JNICALL Java_com_furture_react_DuktapeEngine_nativeRegister
  (JNIEnv *env, jobject thisObject, jlong ptr, jstring key, jobject value){
	duk_context *ctx  = convert_to_context(ptr);
	jboolean iscopy = JNI_FALSE;
	const char* src =  ((*env)->GetStringUTFChars(env, key, &iscopy));
	duk_push_global_object(ctx);
	duk_push_java_object(ctx, env, value);
 	duk_put_prop_string(ctx, -2, src);
	duk_pop(ctx);
	(*env)->ReleaseStringUTFChars(env, key, src);
}
void SetupProxy(duk_context* ctx, const duk_function_list_entry* funcs)
{
    duk_push_global_object(ctx);
    duk_get_prop_string(ctx, -1, "Proxy");
    duk_dup(ctx, -3); // Duplicate target at stack top
    duk_remove(ctx, -4); // Remove original target
    duk_push_object(ctx); // Handler
    duk_put_function_list(ctx, -1, funcs);
    duk_new(ctx, 2); // Create proxy
    duk_remove(ctx, -2); // Remove global object
}
 void OnSignal()
 {
     duk_context* ctx = ctx_;
     duk_push_global_object(ctx);
     duk_get_prop_string(ctx, -1, "_OnSignal");
     duk_remove(ctx, -2);
     duk_push_number(ctx, (size_t)key_);
     duk_push_array(ctx);
     bool success = duk_pcall(ctx, 2) == 0;
     if (!success) LogError("[JavaScript] OnSignal: " + GetErrorString(ctx));
     duk_pop(ctx);
 }
void CallConnectSignal(duk_context* ctx, void* signal)
{
    int numArgs = duk_get_top(ctx);
    duk_push_number(ctx, (size_t)signal);
    duk_insert(ctx, 0);
    duk_push_global_object(ctx);
    duk_get_prop_string(ctx, -1, "_ConnectSignal");
    duk_remove(ctx, -2); // Global object
    duk_insert(ctx, 0);
    duk_pcall(ctx, numArgs + 1);
    duk_pop(ctx);
}