From 96727d6e63ca927f3c7b68d4baa4fe672a4dcd0b Mon Sep 17 00:00:00 2001 From: Akshay Nair Date: Wed, 2 Apr 2025 20:49:49 +0530 Subject: Add events system for lua runtime to dispatch and register events --- src/LuaRuntime.cpp | 58 ++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 52 insertions(+), 6 deletions(-) (limited to 'src/LuaRuntime.cpp') diff --git a/src/LuaRuntime.cpp b/src/LuaRuntime.cpp index 37349b0..f25b73b 100644 --- a/src/LuaRuntime.cpp +++ b/src/LuaRuntime.cpp @@ -1,4 +1,5 @@ #include "WindowActionRouter.hpp" +#include "lua.h" #include #include extern "C" { @@ -11,6 +12,7 @@ extern "C" { LuaRuntime::LuaRuntime() { state = luaL_newstate(); luaL_openlibs(state); + preserve_top(state, { init_web_lib(); }) } @@ -48,18 +50,12 @@ void LuaRuntime::evaluate(const QString &code) { emit evaluation_failed(value); } else { const QVariant value = get_lua_value(-1); - qDebug() << "result: " << value; emit evaluation_completed(value); } }) }); } -QVariant LuaRuntime::evaluate_sync(const QString &code) { - luaL_dostring(state, code.toStdString().c_str()); - return get_lua_value(-1); // TODO: error handling -} - void LuaRuntime::load_file(const QString &path) { queue_task([this, path]() { preserve_top(state, { @@ -70,9 +66,59 @@ void LuaRuntime::load_file(const QString &path) { }); } +int LuaRuntime::lua_event_register(lua_State *state) { + EventHandlerRequest event; + auto top = lua_gettop(state); + + lua_getfield(state, 1, "events"); + auto event_names = LuaRuntime::lua_tostringlist(state); + + event.event_names.swap(event_names); + if (event.event_names.size() == 0) { + lua_settop(state, top); + lua_pushboolean(state, false); + return 1; + } + + lua_getfield(state, 1, "patterns"); + auto patterns = LuaRuntime::lua_tostringlist(state); + event.patterns.swap(patterns); + + lua_getfield(state, 1, "callback"); + if (!lua_isfunction(state, -1)) { + lua_settop(state, top); + lua_pushboolean(state, false); + return 1; + } + + const int function_ref = luaL_ref(state, LUA_REGISTRYINDEX); + event.function_ref = function_ref; + // TODO: Delete ref on clear callback + event.handler = [state, function_ref](BrowserEvent &event) { + preserve_top(state, { + lua_rawgeti(state, LUA_REGISTRYINDEX, function_ref); + event.lua_push(state); + lua_call(state, 1, 0); + }) + }; + + WindowActionRouter::instance().register_event(event); + + lua_settop(state, top); + lua_pushboolean(state, true); + return 1; +} + void LuaRuntime::init_web_lib() { // NOLINTBEGIN(modernize-avoid-c-arrays) + luaL_Reg internals[] = { + {"register_event", &LuaRuntime::lua_event_register}, + {nullptr, nullptr}, + }; + luaL_newlib(state, internals); + lua_setglobal(state, internals_global_name); + // web luaL_Reg web[] = { /// @deprecated -- cgit v1.3.1