Make setTimeout callable from ssb.js by moving it into util.js.c.

git-svn-id: https://www.unprompted.com/svn/projects/tildefriends/trunk@3705 ed5197a5-7fde-0310-b194-c3ffbd925b24
This commit is contained in:
2021-12-27 20:49:07 +00:00
parent 5fbe9c42bc
commit 05b55c849a
3 changed files with 64 additions and 54 deletions

View File

@ -1,9 +1,14 @@
#include "util.js.h"
#include "task.h"
#include "trace.h"
#include "quickjs-libc.h"
#include <uv.h>
#include <string.h>
static JSValue _util_utf8_decode(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
{
JSValue result = JS_NULL;
@ -121,10 +126,62 @@ void tf_util_report_error(JSContext* context, JSValue value)
}
}
typedef struct _timeout_t {
tf_task_t* _task;
JSValue _callback;
} timeout_t;
static void _handle_closed(uv_handle_t* handle)
{
free(handle);
}
static void _util_timeoutCallback(uv_timer_t* handle)
{
timeout_t* timeout = handle->data;
tf_trace_begin(tf_task_get_trace(timeout->_task), "_util_timeoutCallback");
JSContext* context = tf_task_get_context(timeout->_task);
JSValue result = JS_Call(
context,
timeout->_callback,
JS_NULL,
0,
NULL);
tf_util_report_error(context, result);
JS_FreeValue(context, result);
tf_task_run_jobs(timeout->_task);
tf_trace_end(tf_task_get_trace(timeout->_task));
free(timeout);
uv_close((uv_handle_t*)handle, _handle_closed);
}
static JSValue _util_setTimeout(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
{
tf_task_t* task = JS_GetContextOpaque(context);
timeout_t* timeout = malloc(sizeof(timeout_t));
*timeout = (timeout_t)
{
._task = task,
._callback = JS_DupValue(context, argv[0]),
};
uv_timer_t* timer = malloc(sizeof(uv_timer_t));
memset(timer, 0, sizeof(uv_timer_t));
uv_timer_init(tf_task_get_loop(task), timer);
timer->data = timeout;
int64_t duration;
JS_ToInt64(context, &duration, argv[1]);
uv_timer_start(timer, _util_timeoutCallback, duration, 0);
return JS_NULL;
}
void tf_util_register(JSContext* context)
{
JSValue global = JS_GetGlobalObject(context);
JS_SetPropertyStr(context, global, "utf8Decode", JS_NewCFunction(context, _util_utf8_decode, "utf8Decode", 1));
JS_SetPropertyStr(context, global, "print", JS_NewCFunction(context, _util_print, "print", 1));
JS_SetPropertyStr(context, global, "setTimeout", JS_NewCFunction(context, _util_setTimeout, "setTimeout", 2));
JS_FreeValue(context, global);
}