From 1813552b5e58ef870e8196bab38770b3fcc2bb8c Mon Sep 17 00:00:00 2001 From: Eric House Date: Wed, 10 Feb 2021 13:21:28 -0800 Subject: [PATCH] use native js for idle (timers next) --- xwords4/wasm/Makefile | 2 +- xwords4/wasm/main.c | 44 ++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/xwords4/wasm/Makefile b/xwords4/wasm/Makefile index f973ffa3a..dd327cb5e 100644 --- a/xwords4/wasm/Makefile +++ b/xwords4/wasm/Makefile @@ -48,7 +48,7 @@ main.html: ${INPUTS} $(MAKEFILE) shell_minimal.html --preload-file assets_dir --shell-file shell_minimal.html \ -s USE_SDL_TTF=2 -s USE_SDL_IMAGE=2 -s SDL2_IMAGE_FORMATS='["png"]' \ -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall']" \ - -s EXPORTED_FUNCTIONS='["_main", "_button", "_newgame", "_gotMQTTMsg"]' -s WASM=0 \ + -s EXPORTED_FUNCTIONS='["_main", "_button", "_newgame", "_gotMQTTMsg", "_jscallback"]' \ -s WASM=1 \ ${INPUTS} -o $@ diff --git a/xwords4/wasm/main.c b/xwords4/wasm/main.c index 8cd13db4c..6cbdbc0da 100644 --- a/xwords4/wasm/main.c +++ b/xwords4/wasm/main.c @@ -69,6 +69,15 @@ EM_JS(bool, call_mqttSend, (const char* topic, const uint8_t* ptr, int len), { return mqttSend(topStr, buffer); }); +typedef void (*JSCallback)(void* closure); + +EM_JS(void, jscallback_set, (JSCallback proc, void* closure, int inMS), { + let timerproc = function(closure) { + ccall('jscallback', null, ['number', 'number'], [proc, closure]); + }; + setTimeout( timerproc, inMS, closure ); + }); + static void updateScreen( Globals* globals, bool doSave ); static Globals* sGlobals; @@ -388,12 +397,34 @@ main_alert( Globals* globals, const XP_UCHAR* msg ) call_alert( msg ); } +typedef struct _IdleClosure { + Globals* globals; + IdleProc proc; + void* closure; +} IdleClosure; + +static void +onIdleFired( void* closure ) +{ + LOG_FUNC(); + IdleClosure* ic = (IdleClosure*)closure; + XP_Bool draw = (*ic->proc)(ic->closure); + if ( draw ) { + updateScreen( ic->globals, true ); + } + XP_FREE( ic->globals->mpool, ic ); +} + void main_set_idle( Globals* globals, IdleProc proc, void* closure ) { - XP_ASSERT( !globals->idleProc || globals->idleProc == proc ); - globals->idleProc = proc; - globals->idleClosure = closure; + LOG_FUNC(); + IdleClosure* ic = XP_MALLOC( globals->mpool, sizeof(*ic) ); + ic->globals = globals; + ic->proc = proc; + ic->closure = closure; + + jscallback_set( onIdleFired, ic, 0 ); } static XP_Bool @@ -615,6 +646,13 @@ gotMQTTMsg( void* closure, int len, const uint8_t* msg ) dvc_parseMQTTPacket( globals->dutil, NULL, msg, len ); } +void +jscallback( JSCallback proc, void* closure ) +{ + LOG_FUNC(); + (*proc)(closure); +} + int main( int argc, const char** argv ) {