From 5ba33f846129f3e6c0505b19f94634b24505e828 Mon Sep 17 00:00:00 2001 From: Vaxry <43317083+vaxerski@users.noreply.github.com> Date: Sun, 26 Apr 2026 15:16:36 +0100 Subject: config/lua: init lua config manager, use lua if available (#13817) Adds a new lua config manager, which will automatically be used if there is a lua config present. --- src/config/lua/ConfigManager.cpp | 1116 +++++++++++++++++ src/config/lua/ConfigManager.hpp | 186 +++ src/config/lua/DefaultConfig.hpp | 18 + src/config/lua/Emergency.hpp | 47 + src/config/lua/LuaBindings.cpp | 7 + src/config/lua/LuaBindings.hpp | 13 + src/config/lua/LuaEventHandler.cpp | 233 ++++ src/config/lua/LuaEventHandler.hpp | 61 + src/config/lua/bindings/LuaBindingsConfigRules.cpp | 1224 ++++++++++++++++++ src/config/lua/bindings/LuaBindingsDispatchers.cpp | 1324 ++++++++++++++++++++ src/config/lua/bindings/LuaBindingsInternal.cpp | 502 ++++++++ src/config/lua/bindings/LuaBindingsInternal.hpp | 188 +++ .../lua/bindings/LuaBindingsNotification.cpp | 135 ++ src/config/lua/bindings/LuaBindingsQuery.cpp | 400 ++++++ .../lua/bindings/LuaBindingsRegistration.cpp | 66 + src/config/lua/bindings/LuaBindingsToplevel.cpp | 435 +++++++ src/config/lua/objects/LuaEventSubscription.cpp | 74 ++ src/config/lua/objects/LuaEventSubscription.hpp | 12 + src/config/lua/objects/LuaKeybind.cpp | 180 +++ src/config/lua/objects/LuaKeybind.hpp | 12 + src/config/lua/objects/LuaLayerRule.cpp | 80 ++ src/config/lua/objects/LuaLayerRule.hpp | 12 + src/config/lua/objects/LuaLayerSurface.cpp | 88 ++ src/config/lua/objects/LuaLayerSurface.hpp | 12 + src/config/lua/objects/LuaMonitor.cpp | 122 ++ src/config/lua/objects/LuaMonitor.hpp | 12 + src/config/lua/objects/LuaNotification.cpp | 377 ++++++ src/config/lua/objects/LuaNotification.hpp | 12 + src/config/lua/objects/LuaObjectHelpers.hpp | 51 + src/config/lua/objects/LuaTimer.cpp | 109 ++ src/config/lua/objects/LuaTimer.hpp | 12 + src/config/lua/objects/LuaWindow.cpp | 277 ++++ src/config/lua/objects/LuaWindow.hpp | 12 + src/config/lua/objects/LuaWindowRule.cpp | 80 ++ src/config/lua/objects/LuaWindowRule.hpp | 12 + src/config/lua/objects/LuaWorkspace.cpp | 87 ++ src/config/lua/objects/LuaWorkspace.hpp | 12 + src/config/lua/types/LuaConfigBool.cpp | 52 + src/config/lua/types/LuaConfigBool.hpp | 24 + src/config/lua/types/LuaConfigColor.cpp | 63 + src/config/lua/types/LuaConfigColor.hpp | 25 + src/config/lua/types/LuaConfigCssGap.cpp | 104 ++ src/config/lua/types/LuaConfigCssGap.hpp | 28 + src/config/lua/types/LuaConfigFloat.cpp | 80 ++ src/config/lua/types/LuaConfigFloat.hpp | 27 + src/config/lua/types/LuaConfigFontWeight.cpp | 69 + src/config/lua/types/LuaConfigFontWeight.hpp | 25 + src/config/lua/types/LuaConfigGradient.cpp | 133 ++ src/config/lua/types/LuaConfigGradient.hpp | 25 + src/config/lua/types/LuaConfigInt.cpp | 88 ++ src/config/lua/types/LuaConfigInt.hpp | 31 + src/config/lua/types/LuaConfigString.cpp | 56 + src/config/lua/types/LuaConfigString.hpp | 29 + src/config/lua/types/LuaConfigUtils.cpp | 51 + src/config/lua/types/LuaConfigUtils.hpp | 9 + src/config/lua/types/LuaConfigValue.cpp | 20 + src/config/lua/types/LuaConfigValue.hpp | 49 + src/config/lua/types/LuaConfigVec2.cpp | 100 ++ src/config/lua/types/LuaConfigVec2.hpp | 29 + 59 files changed, 8717 insertions(+) create mode 100644 src/config/lua/ConfigManager.cpp create mode 100644 src/config/lua/ConfigManager.hpp create mode 100644 src/config/lua/DefaultConfig.hpp create mode 100644 src/config/lua/Emergency.hpp create mode 100644 src/config/lua/LuaBindings.cpp create mode 100644 src/config/lua/LuaBindings.hpp create mode 100644 src/config/lua/LuaEventHandler.cpp create mode 100644 src/config/lua/LuaEventHandler.hpp create mode 100644 src/config/lua/bindings/LuaBindingsConfigRules.cpp create mode 100644 src/config/lua/bindings/LuaBindingsDispatchers.cpp create mode 100644 src/config/lua/bindings/LuaBindingsInternal.cpp create mode 100644 src/config/lua/bindings/LuaBindingsInternal.hpp create mode 100644 src/config/lua/bindings/LuaBindingsNotification.cpp create mode 100644 src/config/lua/bindings/LuaBindingsQuery.cpp create mode 100644 src/config/lua/bindings/LuaBindingsRegistration.cpp create mode 100644 src/config/lua/bindings/LuaBindingsToplevel.cpp create mode 100644 src/config/lua/objects/LuaEventSubscription.cpp create mode 100644 src/config/lua/objects/LuaEventSubscription.hpp create mode 100644 src/config/lua/objects/LuaKeybind.cpp create mode 100644 src/config/lua/objects/LuaKeybind.hpp create mode 100644 src/config/lua/objects/LuaLayerRule.cpp create mode 100644 src/config/lua/objects/LuaLayerRule.hpp create mode 100644 src/config/lua/objects/LuaLayerSurface.cpp create mode 100644 src/config/lua/objects/LuaLayerSurface.hpp create mode 100644 src/config/lua/objects/LuaMonitor.cpp create mode 100644 src/config/lua/objects/LuaMonitor.hpp create mode 100644 src/config/lua/objects/LuaNotification.cpp create mode 100644 src/config/lua/objects/LuaNotification.hpp create mode 100644 src/config/lua/objects/LuaObjectHelpers.hpp create mode 100644 src/config/lua/objects/LuaTimer.cpp create mode 100644 src/config/lua/objects/LuaTimer.hpp create mode 100644 src/config/lua/objects/LuaWindow.cpp create mode 100644 src/config/lua/objects/LuaWindow.hpp create mode 100644 src/config/lua/objects/LuaWindowRule.cpp create mode 100644 src/config/lua/objects/LuaWindowRule.hpp create mode 100644 src/config/lua/objects/LuaWorkspace.cpp create mode 100644 src/config/lua/objects/LuaWorkspace.hpp create mode 100644 src/config/lua/types/LuaConfigBool.cpp create mode 100644 src/config/lua/types/LuaConfigBool.hpp create mode 100644 src/config/lua/types/LuaConfigColor.cpp create mode 100644 src/config/lua/types/LuaConfigColor.hpp create mode 100644 src/config/lua/types/LuaConfigCssGap.cpp create mode 100644 src/config/lua/types/LuaConfigCssGap.hpp create mode 100644 src/config/lua/types/LuaConfigFloat.cpp create mode 100644 src/config/lua/types/LuaConfigFloat.hpp create mode 100644 src/config/lua/types/LuaConfigFontWeight.cpp create mode 100644 src/config/lua/types/LuaConfigFontWeight.hpp create mode 100644 src/config/lua/types/LuaConfigGradient.cpp create mode 100644 src/config/lua/types/LuaConfigGradient.hpp create mode 100644 src/config/lua/types/LuaConfigInt.cpp create mode 100644 src/config/lua/types/LuaConfigInt.hpp create mode 100644 src/config/lua/types/LuaConfigString.cpp create mode 100644 src/config/lua/types/LuaConfigString.hpp create mode 100644 src/config/lua/types/LuaConfigUtils.cpp create mode 100644 src/config/lua/types/LuaConfigUtils.hpp create mode 100644 src/config/lua/types/LuaConfigValue.cpp create mode 100644 src/config/lua/types/LuaConfigValue.hpp create mode 100644 src/config/lua/types/LuaConfigVec2.cpp create mode 100644 src/config/lua/types/LuaConfigVec2.hpp (limited to 'src/config/lua') diff --git a/src/config/lua/ConfigManager.cpp b/src/config/lua/ConfigManager.cpp new file mode 100644 index 00000000..fad187db --- /dev/null +++ b/src/config/lua/ConfigManager.cpp @@ -0,0 +1,1116 @@ +#include "ConfigManager.hpp" +#include "LuaBindings.hpp" +#include "DefaultConfig.hpp" +#include "Emergency.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "types/LuaConfigUtils.hpp" +#include "types/LuaConfigBool.hpp" + +#include "../values/ConfigValues.hpp" + +#include "../supplementary/jeremy/Jeremy.hpp" +#include "../shared/workspace/WorkspaceRuleManager.hpp" +#include "../shared/monitor/MonitorRuleManager.hpp" +#include "../shared/animation/AnimationTree.hpp" +#include "../shared/inotify/ConfigWatcher.hpp" + +#include "../../desktop/rule/Engine.hpp" +#include "../../helpers/MiscFunctions.hpp" + +#include "../../event/EventBus.hpp" +#include "../../Compositor.hpp" +#include "../../managers/input/InputManager.hpp" +#include "../../managers/KeybindManager.hpp" +#include "../../helpers/Monitor.hpp" +#include "../../layout/space/Space.hpp" +#include "../../layout/supplementary/WorkspaceAlgoMatcher.hpp" +#include "../../render/Renderer.hpp" +#include "../../errorOverlay/Overlay.hpp" +#include "../../xwayland/XWayland.hpp" +#include "../../plugins/PluginSystem.hpp" +#include "../../managers/EventManager.hpp" +#include "../../managers/eventLoop/EventLoopManager.hpp" +#include "../../managers/input/trackpad/TrackpadGestures.hpp" +#include "../../notification/NotificationOverlay.hpp" +#include "../../render/decorations/CHyprGroupBarDecoration.hpp" + +using namespace Config; +using namespace Config::Lua; +using namespace Hyprutils::String; + +static uint64_t nextPluginLuaFnID = 0x10000; + +// +static bool isValidLuaIdentifier(const std::string& value) { + if (value.empty()) + return false; + + if (!std::isalpha(value[0]) && value[0] != '_') + return false; + + return std::ranges::all_of(value, [](const char& c) { return std::isalnum(c) || c == '_'; }); +} + +static int pluginLuaFunctionDispatcher(lua_State* L) { + auto* mgr = CConfigManager::fromLuaState(L); + if (!mgr) + return luaL_error(L, "hl.plugin: internal error: config manager unavailable"); + + if (!lua_isinteger(L, lua_upvalueindex(1))) + return luaL_error(L, "hl.plugin: internal error: invalid callback id"); + + const auto id = sc(lua_tointeger(L, lua_upvalueindex(1))); + return mgr->invokePluginLuaFunctionByID(id, L); +} + +static void trackRequiredLuaModulePath(lua_State* L, CConfigManager* mgr, const std::string& moduleName) { + if (!L || !mgr || moduleName.empty()) + return; + + const int stackTop = lua_gettop(L); + + lua_getglobal(L, "package"); + if (!lua_istable(L, -1)) { + lua_settop(L, stackTop); + return; + } + + lua_getfield(L, -1, "searchpath"); + if (!lua_isfunction(L, -1)) { + lua_settop(L, stackTop); + return; + } + + lua_pushstring(L, moduleName.c_str()); + lua_getfield(L, -3, "path"); + if (!lua_isstring(L, -1)) { + lua_settop(L, stackTop); + return; + } + + if (lua_pcall(L, 2, 2, 0) == LUA_OK && lua_isstring(L, -2)) { + const auto* resolvedPath = lua_tostring(L, -2); + if (resolvedPath && std::ranges::find(mgr->m_configPaths, resolvedPath) == mgr->m_configPaths.end()) + mgr->m_configPaths.emplace_back(resolvedPath); + } + + lua_settop(L, stackTop); +} + +static int safeLuaRequire(lua_State* L) { + const int nargs = lua_gettop(L); + + std::string moduleName; + if (lua_isstring(L, 1)) + moduleName = lua_tostring(L, 1); + + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + + const int status = lua_pcall(L, nargs, LUA_MULTRET, 0); + if (status == LUA_OK) + return lua_gettop(L); + + std::string err; + { + size_t len = 0; + const char* str = luaL_tolstring(L, -1, &len); + if (str) + err.assign(str, len); + lua_pop(L, 1); + } + + if (auto* mgr = CConfigManager::fromLuaState(L); mgr) { + if (!moduleName.empty()) { + trackRequiredLuaModulePath(L, mgr, moduleName); + mgr->addError(std::format("require(\"{}\"): {}", moduleName, err)); + } else + mgr->addError(std::format("require: {}", err)); + } + + lua_pop(L, 1); // error object + + lua_newtable(L); // fallback module + const int fallbackIdx = lua_gettop(L); + + if (!moduleName.empty()) { + lua_getglobal(L, "package"); + if (lua_istable(L, -1)) { + lua_getfield(L, -1, "loaded"); + if (lua_istable(L, -1)) { + lua_pushstring(L, moduleName.c_str()); + lua_pushvalue(L, fallbackIdx); + lua_settable(L, -3); + } + lua_pop(L, 1); // loaded + } + lua_pop(L, 1); // package + } + + return 1; +} + +WP Lua::mgr() { + auto& mgr = Config::mgr(); + if (mgr->type() != CONFIG_LUA) + return nullptr; + + return dynamicPointerCast(WP(mgr)); +} + +CConfigManager::SDeviceConfig::SDeviceConfig() { + auto mgr = Lua::mgr(); + + for (const auto& valRaw : Values::CONFIG_DEVICE_VALUE_NAMES) { + auto generic = std::ranges::find_if(Values::CONFIG_VALUES, [&valRaw](const auto& g) { return g->name() == valRaw; }); + + RASSERT(generic != Values::CONFIG_VALUES.end(), "Lua: device value has no generic counterpart, what the fuck happened?"); + + auto valLua = mgr->luaConfigValueName(valRaw); + + auto valDevice = valLua.contains('.') ? valLua.substr(valLua.find_last_of('.') + 1) : valLua; + + if (values.contains(valDevice)) + continue; // some are duped + + values.emplace(valDevice, fromGenericValue(*generic)); + } + + // emplace the special keybinds one + values.emplace("keybinds", makeUnique(true)); +} + +CConfigManager::CConfigManager() : m_mainConfigPath(Supplementary::Jeremy::getMainConfigPath()->path) { + ; +} + +CConfigManager* CConfigManager::fromLuaState(lua_State* L) { + if (!L) + return nullptr; + + lua_getfield(L, LUA_REGISTRYINDEX, "hl_lua_manager"); + auto* mgr = sc(lua_touserdata(L, -1)); + lua_pop(L, 1); + return mgr; +} + +void CConfigManager::watchdogHook(lua_State* L, lua_Debug* /*ar*/) { + auto* mgr = fromLuaState(L); + if (!mgr || !mgr->m_watchdogActive) + return; + + if (std::chrono::steady_clock::now() <= mgr->m_watchdogDeadline) + return; + + const auto& context = mgr->m_watchdogContext; + if (context.empty()) + luaL_error(L, "[Lua] execution timed out"); + + luaL_error(L, "[Lua] execution timed out in %s", context.c_str()); +} + +int CConfigManager::guardedPCall(int nargs, int nresults, int errfunc, int timeoutMs, std::string_view context) { + if (!m_lua) + return LUA_ERRERR; + + const auto prevHook = lua_gethook(m_lua); + const int prevMask = lua_gethookmask(m_lua); + const int prevCount = lua_gethookcount(m_lua); + + const bool prevWatchdogActive = m_watchdogActive; + const std::chrono::steady_clock::time_point prevWatchdogDeadline = m_watchdogDeadline; + const std::string prevWatchdogContext = m_watchdogContext; + + m_watchdogActive = timeoutMs > 0; + m_watchdogDeadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(std::max(timeoutMs, 1)); + m_watchdogContext = context; + + lua_sethook(m_lua, &CConfigManager::watchdogHook, LUA_MASKCOUNT, LUA_WATCHDOG_INSTRUCTION_INTERVAL); + const int result = lua_pcall(m_lua, nargs, nresults, errfunc); + + lua_sethook(m_lua, prevHook, prevMask, prevCount); + m_watchdogActive = prevWatchdogActive; + m_watchdogDeadline = prevWatchdogDeadline; + m_watchdogContext = prevWatchdogContext; + + return result; +} + +eConfigManagerType CConfigManager::type() { + return CONFIG_LUA; +} + +void CConfigManager::registerValue(const char* name, ILuaConfigValue* val) { + m_configValues.emplace(name, UP(val)); +} + +void CConfigManager::cleanTimers() { + for (auto& t : m_luaTimers) { + t.timer->cancel(); + g_pEventLoopManager->removeTimer(t.timer); + + if (m_lua && t.luaRef != LUA_NOREF) { + luaL_unref(m_lua, LUA_REGISTRYINDEX, t.luaRef); + t.luaRef = LUA_NOREF; + } + } + m_luaTimers.clear(); +} + +void CConfigManager::reinitLuaState() { + // Destroy the event handler first so its luaL_unref calls happen while m_lua is still valid. + m_eventHandler.reset(); + + cleanTimers(); + + if (m_lua) { + lua_close(m_lua); + m_lua = nullptr; + } + + m_lua = luaL_newstate(); + luaL_openlibs(m_lua); + + lua_getglobal(m_lua, "debug"); + if (lua_istable(m_lua, -1)) { + lua_pushnil(m_lua); + lua_setfield(m_lua, -2, "sethook"); + lua_pushnil(m_lua); + lua_setfield(m_lua, -2, "gethook"); + } + lua_pop(m_lua, 1); + + lua_pushlightuserdata(m_lua, this); + lua_setfield(m_lua, LUA_REGISTRYINDEX, "hl_lua_manager"); + + std::filesystem::path configDir = std::filesystem::path(m_mainConfigPath).parent_path(); + const std::string luaPath = (configDir / "?.lua").string() + ";" + (configDir / "?/init.lua").string(); + lua_getglobal(m_lua, "package"); + lua_pushstring(m_lua, luaPath.c_str()); + lua_setfield(m_lua, -2, "path"); + lua_pop(m_lua, 1); + + lua_getglobal(m_lua, "require"); + if (lua_isfunction(m_lua, -1)) { + lua_pushcclosure(m_lua, safeLuaRequire, 1); + lua_setglobal(m_lua, "require"); + } else + lua_pop(m_lua, 1); + + Bindings::registerBindings(m_lua, this); + + m_eventHandler = makeUnique(m_lua); + + // Hook package.searchers[2] (the Lua file searcher) to track require()'d paths. + lua_getglobal(m_lua, "package"); + lua_getfield(m_lua, -1, "searchers"); + lua_rawgeti(m_lua, -1, 2); // original file searcher + lua_pushlightuserdata(m_lua, this); + lua_pushcclosure( + m_lua, + [](lua_State* L) -> int { + // upvalue 1: original searcher, upvalue 2: CConfigManager* + lua_pushvalue(L, lua_upvalueindex(1)); + lua_pushvalue(L, 1); // module name + lua_call(L, 1, 2); // -> loader?, filename? + if (lua_isfunction(L, -2) && lua_isstring(L, -1)) { + auto* self = sc(lua_touserdata(L, lua_upvalueindex(2))); + self->m_configPaths.emplace_back(lua_tostring(L, -1)); + } + return 2; + }, + 2); + lua_rawseti(m_lua, -2, 2); // replace package.searchers[2] + lua_pop(m_lua, 2); // pop searchers, package +} + +void CConfigManager::init() { + reinitLuaState(); + + for (const auto& v : Values::CONFIG_VALUES) { + m_configValues.emplace(luaConfigValueName(v->name()), fromGenericValue(v)); + } + + m_configValues["autogenerated"] = fromGenericValue(makeShared("autogenerated", "whether the config is autogenerated or not", 0)); + + Config::watcher()->setOnChange([this](const CConfigWatcher::SConfigWatchEvent& e) { + Log::logger->log(Log::DEBUG, "[lua] file {} modified, reloading", e.file); + reload(); + }); + + reload(); +} + +void CConfigManager::reload() { + Event::bus()->m_events.config.preReload.emit(); + + Hyprutils::Utils::CScopeGuard x([this] { + m_isParsingConfig = false; + m_isFirstLaunch = false; + }); + m_isParsingConfig = true; + + m_mainConfigPath = Supplementary::Jeremy::getMainConfigPath()->path; + + // reset tracked paths; the searcher hook will re-populate them as require() runs + m_configPaths.clear(); + m_configPaths.emplace_back(m_mainConfigPath); + + // phase 1: check syntax before clearing any state, so a broken syntax + // doesn't entirely fucking nuke the config and leave the user + // with no binds. + // + // this won't help if they are launching hyprland, + // which will be handled with emergency pcall + auto phase1Load = [this]() -> bool { + // clear package.loaded for user modules so require() re-executes them and + // the searcher hook can re-track their paths. + lua_getglobal(m_lua, "package"); + lua_getfield(m_lua, -1, "loaded"); + static constexpr std::string_view STDLIB[] = {"_G", "coroutine", "debug", "io", "math", "os", "package", "string", "table", "utf8", "bit32", "jit"}; + lua_pushnil(m_lua); + while (lua_next(m_lua, -2)) { + lua_pop(m_lua, 1); // pop value, keep key + if (lua_isstring(m_lua, -1)) { + std::string_view mod = lua_tostring(m_lua, -1); + bool skip = false; + for (const auto& s : STDLIB) { + if (mod == s) { + skip = true; + break; + } + } + if (!skip) { + lua_pushvalue(m_lua, -1); // dup key + lua_pushnil(m_lua); + lua_settable(m_lua, -4); // package.loaded[key] = nil + } + } + } + lua_pop(m_lua, 2); // pop loaded, package + + if (luaL_loadfile(m_lua, m_mainConfigPath.c_str()) != LUA_OK) { + m_errors.clear(); + addError(lua_tostring(m_lua, -1)); + lua_pop(m_lua, 1); + return false; + } + + return true; + }; + + if (!phase1Load()) { + m_lastConfigVerificationWasSuccessful = false; + postConfigReload(); + return; + } + + // phase 2: syntax is valid, reset and load. + Config::animationTree()->reset(); + Config::workspaceRuleMgr()->clear(); + Config::monitorRuleMgr()->clear(); + Desktop::Rule::ruleEngine()->clearAllRules(); + g_pTrackpadGestures->clearGestures(); + cleanTimers(); + m_luaWindowRules.clear(); + m_luaLayerRules.clear(); + m_errors.clear(); + m_deviceConfigs.clear(); + m_registeredPlugins.clear(); + m_eventHandler->clearEvents(); + clearHeldLuaRefs(); + + if (g_pKeybindManager) { + for (const auto& kb : g_pKeybindManager->m_keybinds) { + if (kb->handler == "__lua") + luaL_unref(m_lua, LUA_REGISTRYINDEX, std::stoi(kb->arg)); + } + g_pKeybindManager->clearKeybinds(); + } + + // refresh lua state so we get rid of any stale state + reinitLuaState(); + + // restart phase 1 load, because our state is gone now. + if (!phase1Load()) { + m_lastConfigVerificationWasSuccessful = false; + postConfigReload(); + return; + } + + // re-register plugin functions + reregisterLuaPluginFns(); + + for (const auto& v : m_configValues) { + v.second->reset(); + } + + lua_pushcfunction(m_lua, [](lua_State* L) -> int { + luaL_traceback(L, L, lua_tostring(L, 1), 1); + return 1; + }); + lua_insert(m_lua, 1); + + if (guardedPCall(0, 0, 1, LUA_TIMEOUT_CONFIG_RELOAD_MS, "config reload") != LUA_OK) { + addError(lua_tostring(m_lua, -1)); + lua_pop(m_lua, 1); + m_lastConfigVerificationWasSuccessful = false; + } else + m_lastConfigVerificationWasSuccessful = m_errors.empty(); + + lua_remove(m_lua, 1); + + // collect stale userdata after reload so HL.Notification __gc can + // promptly release pause leases from dropped references + lua_gc(m_lua, LUA_GCCOLLECT, 0); + + postConfigReload(); +} + +void CConfigManager::postConfigReload() { + + static auto PZOOMFACTOR = CConfigValue("cursor.zoom_factor"); + static auto PSUPPRESSERRORS = CConfigValue("debug.suppress_errors"); + static auto PXWAYLAND = CConfigValue("xwayland.enabled"); + static auto PMANUALCRASH = CConfigValue("debug.manual_crash"); + static auto PENABLESTDOUT = CConfigValue("debug.enable_stdout_logs"); + static auto PAUTOGENERATED = CConfigValue("autogenerated"); + + Config::watcher()->update(); + + for (auto const& w : g_pCompositor->m_windows) { + w->uncacheWindowDecos(); + } + + for (auto const& m : g_pCompositor->m_monitors) { + *(m->m_cursorZoom) = *PZOOMFACTOR; + if (m->m_activeWorkspace) + m->m_activeWorkspace->m_space->recalculate(); + } + + // Update the keyboard layout to the cfg'd one if this is not the first launch + if (!m_isFirstLaunch) { + g_pInputManager->setKeyboardLayout(); + g_pInputManager->setPointerConfigs(); + g_pInputManager->setTouchDeviceConfigs(); + g_pInputManager->setTabletConfigs(); + + g_pHyprRenderer->m_reloadScreenShader = true; + } + + const bool emergencyModeTripped = !m_errors.empty() && g_pKeybindManager->m_keybinds.empty(); + + if (emergencyModeTripped) + luaL_dostring(m_lua, EMERGENCY_PCALL); + + // parseError will be displayed next frame + if (!m_errors.empty() && !*PSUPPRESSERRORS) { + std::string errorStr; + + if (emergencyModeTripped) { + errorStr = "⚠ Emergency mode tripped: A lua config error resulted in no binds being registered. Emergency binds active: SUPER + Q → any known terminal, SUPER + R " + "→ hyprland-run, SUPER + M → Exit\n"; + } + + errorStr += "Your config has errors:\n"; + + for (const auto& e : m_errors) { + errorStr += e + "\n"; + + if (std::ranges::count(errorStr, '\n') > 15) { + errorStr += "... more"; + break; + } + } + + if (!errorStr.empty() && errorStr.back() == '\n') + errorStr.pop_back(); + + ErrorOverlay::overlay()->queueCreate(errorStr, ErrorOverlay::Colors::ERROR); + } else if (*PAUTOGENERATED) + ErrorOverlay::overlay()->queueCreate( + "Warning: You're using an autogenerated config! Edit the config file to get rid of this message. (config file: " + getMainConfigPath() + + " )\nSUPER+Q -> kitty (if it doesn't launch, make sure it's installed or choose a different terminal in the config)\nSUPER+M -> exit Hyprland", + ErrorOverlay::Colors::WARNING); + else + ErrorOverlay::overlay()->destroy(); + + // Set the modes for all monitors as we configured them + // not on first launch because monitors might not exist yet + // and they'll be taken care of in the newMonitor event + if (!m_isFirstLaunch) { + // check + Config::monitorRuleMgr()->scheduleReload(); + Config::monitorRuleMgr()->ensureMonitorStatus(); + Config::monitorRuleMgr()->ensureVRR(); + } + +#ifndef NO_XWAYLAND + g_pCompositor->m_wantsXwayland = *PXWAYLAND; + // enable/disable xwayland usage + if (!m_isFirstLaunch && + g_pXWayland /* XWayland has to be initialized by CCompositor::initManagers for this to make sense, and it doesn't have to be (e.g. very early plugin load) */) { + bool prevEnabledXwayland = g_pXWayland->enabled(); + if (g_pCompositor->m_wantsXwayland != prevEnabledXwayland) + g_pXWayland = makeUnique(g_pCompositor->m_wantsXwayland); + } else + g_pCompositor->m_wantsXwayland = *PXWAYLAND; +#endif + + if (!m_isFirstLaunch && !g_pCompositor->m_unsafeState) + refreshGroupBarGradients(); + + for (auto const& w : g_pCompositor->getWorkspaces()) { + if (w->inert()) + continue; + w->updateWindows(); + w->updateWindowData(); + } + + g_pCompositor->updateAllWindowsAnimatedDecorationValues(); + + if (*PMANUALCRASH && !m_manualCrashInitiated) { + m_manualCrashInitiated = true; + Notification::overlay()->addNotification("Manual crash has been set up. Set debug.manual_crash back to 0 in order to crash the compositor.", CHyprColor(0), 5000, + ICON_INFO); + } else if (m_manualCrashInitiated && !*PMANUALCRASH) { + // cowabunga it is + g_pHyprRenderer->initiateManualCrash(); + } + + auto disableStdout = !*PENABLESTDOUT; + if (disableStdout && m_isFirstLaunch) + Log::logger->log(Log::DEBUG, "Disabling stdout logs! Check the log for further logs."); + + for (auto const& m : g_pCompositor->m_monitors) { + // mark blur dirty + m->m_blurFBDirty = true; + + g_pCompositor->scheduleFrameForMonitor(m); + + // Force the compositor to fully re-render all monitors + m->m_forceFullFrames = 2; + + // also force mirrors, as the aspect ratio could've changed + for (auto const& mirror : m->m_mirrors) + mirror->m_forceFullFrames = 3; + } + + handlePluginLoads(); + + if (!m_isFirstLaunch) + g_pCompositor->ensurePersistentWorkspacesPresent(); + + Layout::Supplementary::algoMatcher()->updateWorkspaceLayouts(); + + Event::bus()->m_events.config.reloaded.emit(); + if (g_pEventManager) + g_pEventManager->postEvent(SHyprIPCEvent{"configreloaded", ""}); +} + +void CConfigManager::addError(std::string&& str) { + if (m_isParsingConfig) { + m_errors.emplace_back(std::move(str)); + return; + } + + if (m_isEvaluating) { + m_errors.emplace_back(std::move(str)); + return; + } + + // pop a notification + Notification::overlay()->addNotification(std::format("Runtime error in lua:\n{}", std::move(str)), 0, 5000, ICON_WARNING); +} + +std::optional CConfigManager::eval(const std::string& code) { + if (!m_lua) + return "lua state not initialized"; + + m_errors.clear(); + m_isEvaluating = true; + + Hyprutils::Utils::CScopeGuard x([this] { m_isEvaluating = false; }); + + if (luaL_loadstring(m_lua, code.c_str()) != LUA_OK) { + std::string err = lua_tostring(m_lua, -1); + lua_pop(m_lua, 1); + return err; + } + + if (guardedPCall(0, 0, 0, LUA_TIMEOUT_EVAL_MS, "hyprctl eval") != LUA_OK) { + std::string err = lua_tostring(m_lua, -1); + lua_pop(m_lua, 1); + return err; + } + + if (!m_errors.empty()) { + std::string out; + out.reserve(256); + + for (size_t i = 0; i < m_errors.size(); ++i) { + out += m_errors.at(i); + out += "\n"; + } + + out.pop_back(); + + return out; + } + + m_errors.clear(); + + return std::nullopt; +} + +std::string CConfigManager::verify() { + if (m_errors.empty()) + return "config ok"; + + std::string fullStr = ""; + for (const auto& e : m_errors) { + fullStr += e; + fullStr += "\n"; + } + + fullStr.pop_back(); + return fullStr; +} + +static std::string normalizeDeviceName(const std::string& dev) { + auto copy = dev; + std::ranges::replace(copy, ' ', '-'); + return copy; +} + +ILuaConfigValue* CConfigManager::findDeviceValue(const std::string& dev, const std::string& field) { + const auto devIt = m_deviceConfigs.find(dev); + if (devIt == m_deviceConfigs.end()) + return nullptr; + const auto valIt = devIt->second.values.find(field); + return valIt != devIt->second.values.end() ? valIt->second.get() : nullptr; +} + +int CConfigManager::getDeviceInt(const std::string& dev, const std::string& field, const std::string& fb) { + std::string fallback = luaConfigValueName(fb); + if (auto* v = findDeviceValue(normalizeDeviceName(dev), luaConfigValueName(field)); v && v->setByUser()) + return (int)*sc(v->data()); + if (!fallback.empty() && m_configValues.contains(fallback)) + return (int)*sc(m_configValues.at(fallback)->data()); + return 0; +} + +float CConfigManager::getDeviceFloat(const std::string& dev, const std::string& field, const std::string& fb) { + std::string fallback = luaConfigValueName(fb); + if (auto* v = findDeviceValue(normalizeDeviceName(dev), luaConfigValueName(field)); v && v->setByUser()) + return *sc(v->data()); + if (!fallback.empty() && m_configValues.contains(fallback)) + return *sc(m_configValues.at(fallback)->data()); + return 0.F; +} + +Vector2D CConfigManager::getDeviceVec(const std::string& dev, const std::string& field, const std::string& fb) { + std::string fallback = luaConfigValueName(fb); + auto toVec = [](const Config::VEC2& v) -> Vector2D { return {v.x, v.y}; }; + if (auto* v = findDeviceValue(normalizeDeviceName(dev), luaConfigValueName(field)); v && v->setByUser()) + return toVec(*sc(v->data())); + if (!fallback.empty() && m_configValues.contains(fallback)) + return toVec(*sc(m_configValues.at(fallback)->data())); + return {0, 0}; +} + +std::string CConfigManager::getDeviceString(const std::string& dev, const std::string& field, const std::string& fb) { + std::string fallback = luaConfigValueName(fb); + auto clean = [](const Config::STRING& s) -> std::string { return s == STRVAL_EMPTY ? "" : s; }; + if (auto* v = findDeviceValue(normalizeDeviceName(dev), luaConfigValueName(field)); v && v->setByUser()) + return clean(*sc(v->data())); + if (!fallback.empty() && m_configValues.contains(fallback)) + return clean(*sc(m_configValues.at(fallback)->data())); + return ""; +} + +bool CConfigManager::deviceConfigExplicitlySet(const std::string& dev, const std::string& field) { + auto v = findDeviceValue(normalizeDeviceName(dev), luaConfigValueName(field)); + return v && v->setByUser(); +} + +bool CConfigManager::deviceConfigExists(const std::string& dev) { + return m_deviceConfigs.contains(normalizeDeviceName(dev)); +} + +SConfigOptionReply CConfigManager::getConfigValue(const std::string& s) { + + if (m_configValues.contains(s)) { + + auto& cv = m_configValues[s]; + + m_configPtrMap[s] = cv->data(); + + return SConfigOptionReply{.dataptr = cc(&m_configPtrMap.at(s)), .type = cv->underlying(), .setByUser = cv->setByUser()}; + } + + // try replacing all . with : unless col. + std::string s2 = s; + + for (size_t i = 0; i < s2.length(); ++i) { + if (s2[i] != ':') + continue; + + if (i <= 3) { + s2[i] = '.'; + continue; + } + + if (s2[i - 1] == 'l' && s2[i - 2] == 'o' && s2[i - 3] == 'c') + continue; + + s2[i] = '.'; + } + + if (!m_configValues.contains(s2)) + return SConfigOptionReply{.dataptr = nullptr}; + + auto& cv = m_configValues[s2]; + + m_configPtrMap[s2] = cv->data(); + + return SConfigOptionReply{.dataptr = cc(&m_configPtrMap.at(s2)), .type = cv->underlying(), .setByUser = cv->setByUser()}; +} + +std::string CConfigManager::getMainConfigPath() { + return m_mainConfigPath; +} + +std::string CConfigManager::getErrors() { + std::string errStr; + for (const auto& e : m_errors) { + errStr += e + "\n"; + } + + if (!errStr.empty()) + errStr.pop_back(); + + return errStr; +} + +std::string CConfigManager::getConfigString() { + return "Not supported under lua"; +} + +std::string CConfigManager::currentConfigPath() { + return m_mainConfigPath; +} + +const std::vector& CConfigManager::getConfigPaths() { + return m_configPaths; +} + +std::expected CConfigManager::generateDefaultConfig(const std::filesystem::path& path, bool safeMode) { + std::string parentPath = std::filesystem::path(path).parent_path(); + + if (!parentPath.empty()) { + std::error_code ec; + bool created = std::filesystem::create_directories(parentPath, ec); + if (ec) { + Log::logger->log(Log::ERR, "Couldn't create config home directory ({}): {}", ec.message(), parentPath); + return std::unexpected("Config could not be generated."); + } + if (created) + Log::logger->log(Log::WARN, "Creating config home directory"); + } + + Log::logger->log(Log::WARN, "No config file found; attempting to generate."); + std::ofstream ofs; + ofs.open(path, std::ios::trunc); + + if (!ofs.good()) + return std::unexpected("Config could not be generated."); + + if (!safeMode) { + ofs << AUTOGENERATED_PREFIX; + ofs << EXAMPLE_CONFIG; + } else { + std::string n = std::string{EXAMPLE_CONFIG}; + replaceInString(n, "\nlocal menu = \"hyprlauncher\"\n", "\nlocal menu = \"hyprland-run\"\n"); + ofs << n; + } + + ofs.close(); + + if (ofs.fail()) + return std::unexpected("Config could not be generated."); + + return {}; +} + +void CConfigManager::handlePluginLoads() { + if (!g_pPluginSystem) + return; + + bool pluginsChanged = false; + g_pPluginSystem->updateConfigPlugins(m_registeredPlugins, pluginsChanged); + + if (pluginsChanged) { + ErrorOverlay::overlay()->destroy(); + reload(); + } +} + +bool CConfigManager::configVerifPassed() { + return m_lastConfigVerificationWasSuccessful; +} + +std::string CConfigManager::luaConfigValueName(const std::string& s) { + std::string cpy = s; + std::ranges::replace(cpy, ':', '.'); + std::ranges::replace(cpy, '-', '_'); + return cpy; +} + +bool CConfigManager::isFirstLaunch() const { + return m_isFirstLaunch; +} + +std::expected CConfigManager::registerPluginValue(void* handle, SP value) { + + const auto NAME = luaConfigValueName(value->name()); + + if (m_configValues.contains(NAME)) + return std::unexpected("name collision: already registered"); + + auto val = fromGenericValue(value); + + if (!val) + return std::unexpected("unsupported value type"); + + m_configValues.emplace(NAME, std::move(val)); + + m_pluginValues[handle].emplace_back(NAME); + + return {}; +} + +std::expected CConfigManager::registerPluginLuaFunctionInState(uint64_t id, const std::string& namespace_, const std::string& name) { + if (!m_lua) + return std::unexpected("lua state not initialized"); + + lua_getglobal(m_lua, "hl"); + if (!lua_istable(m_lua, -1)) { + lua_pop(m_lua, 1); + return std::unexpected("missing global table 'hl'"); + } + + lua_getfield(m_lua, -1, "plugin"); + if (!lua_istable(m_lua, -1)) { + lua_pop(m_lua, 2); + return std::unexpected("missing global table 'hl.plugin'"); + } + + const int pluginTableIdx = lua_gettop(m_lua); + + lua_getfield(m_lua, pluginTableIdx, namespace_.c_str()); + if (lua_isnil(m_lua, -1)) { + lua_pop(m_lua, 1); + lua_newtable(m_lua); + lua_pushvalue(m_lua, -1); + lua_setfield(m_lua, pluginTableIdx, namespace_.c_str()); + } else if (!lua_istable(m_lua, -1)) { + lua_pop(m_lua, 3); + return std::unexpected(std::format("hl.plugin.{} already exists and is not a namespace table", namespace_)); + } + + const int namespaceTableIdx = lua_gettop(m_lua); + + lua_getfield(m_lua, namespaceTableIdx, name.c_str()); + const bool exists = !lua_isnil(m_lua, -1); + lua_pop(m_lua, 1); + + if (exists) { + lua_pop(m_lua, 3); + return std::unexpected(std::format("hl.plugin.{}.{} already exists", namespace_, name)); + } + + lua_pushinteger(m_lua, sc(id)); + lua_pushcclosure(m_lua, pluginLuaFunctionDispatcher, 1); + lua_setfield(m_lua, namespaceTableIdx, name.c_str()); + + lua_pop(m_lua, 3); + return {}; +} + +std::expected CConfigManager::unregisterPluginLuaFunctionInState(const std::string& namespace_, const std::string& name) { + if (!m_lua) + return std::unexpected("lua state not initialized"); + + lua_getglobal(m_lua, "hl"); + if (!lua_istable(m_lua, -1)) { + lua_pop(m_lua, 1); + return {}; + } + + lua_getfield(m_lua, -1, "plugin"); + if (!lua_istable(m_lua, -1)) { + lua_pop(m_lua, 2); + return {}; + } + + const int pluginTableIdx = lua_gettop(m_lua); + + lua_getfield(m_lua, pluginTableIdx, namespace_.c_str()); + if (!lua_istable(m_lua, -1)) { + lua_pop(m_lua, 3); + return {}; + } + + const int namespaceTableIdx = lua_gettop(m_lua); + + lua_pushnil(m_lua); + lua_setfield(m_lua, namespaceTableIdx, name.c_str()); + + bool isEmpty = true; + lua_pushnil(m_lua); + if (lua_next(m_lua, namespaceTableIdx) != 0) { + isEmpty = false; + lua_pop(m_lua, 2); + } + + if (isEmpty) { + lua_pushnil(m_lua); + lua_setfield(m_lua, pluginTableIdx, namespace_.c_str()); + } + + lua_pop(m_lua, 3); + return {}; +} + +void CConfigManager::erasePluginLuaFunction(uint64_t id) { + std::erase_if(m_pluginLuaFunctions, [&id](const SPluginLuaFunction& f) { return f.id == id; }); +} + +int CConfigManager::invokePluginLuaFunctionByID(uint64_t id, lua_State* L) { + const auto REGIT = std::ranges::find_if(m_pluginLuaFunctions, [&id](const SPluginLuaFunction& r) { return r.id == id; }); + if (REGIT == m_pluginLuaFunctions.end()) + return luaL_error(L, "hl.plugin: this function is no longer available (plugin unloaded)"); + + const auto FN = REGIT->fn; + if (!FN) + return luaL_error(L, "hl.plugin: this function is not callable"); + + return FN(L); +} + +std::expected CConfigManager::registerPluginLuaFunction(void* handle, const std::string& namespace_, const std::string& name, Config::PLUGIN_LUA_FN fn) { + if (!handle) + return std::unexpected("invalid handle"); + + if (!fn) + return std::unexpected("function pointer cannot be null"); + + if (!isValidLuaIdentifier(namespace_)) + return std::unexpected("namespace must match [A-Za-z_][A-Za-z0-9_]*"); + + if (!isValidLuaIdentifier(name)) + return std::unexpected("name must match [A-Za-z_][A-Za-z0-9_]*"); + + if (namespace_ == "load") + return std::unexpected("namespace 'load' is reserved"); + + const auto key = namespace_ + "." + name; + if (std::ranges::find_if(m_pluginLuaFunctions, [&key](const SPluginLuaFunction& r) { return r.namespace_ + "." + r.name == key; }) != m_pluginLuaFunctions.end()) + return std::unexpected("name collision: already registered"); + + const uint64_t id = nextPluginLuaFnID++; + if (const auto REGISTERED = registerPluginLuaFunctionInState(id, namespace_, name); !REGISTERED) + return REGISTERED; + + m_pluginLuaFunctions.emplace_back(SPluginLuaFunction{.id = id, .handle = handle, .namespace_ = namespace_, .name = name, .fn = fn}); + + return {}; +} + +std::expected CConfigManager::unregisterPluginLuaFunction(void* handle, const std::string& namespace_, const std::string& name) { + if (!handle) + return std::unexpected("invalid handle"); + + const auto key = namespace_ + "." + name; + auto it = std::ranges::find_if(m_pluginLuaFunctions, [&key](const SPluginLuaFunction& r) { return r.namespace_ + "." + r.name == key; }); + + if (it == m_pluginLuaFunctions.end()) + return std::unexpected("no such function"); + + if (it->handle != handle) + return std::unexpected("function belongs to a different plugin"); + + const auto removedFromState = unregisterPluginLuaFunctionInState(namespace_, name); + erasePluginLuaFunction(it->id); + + if (!removedFromState) + return removedFromState; + + return {}; +} + +void CConfigManager::onPluginUnload(void* handle) { + if (!handle) + return; + + if (const auto it = m_pluginValues.find(handle); it != m_pluginValues.end()) { + for (const auto& name : it->second) { + m_configValues.erase(name); + } + + m_pluginValues.erase(it); + } + + std::erase_if(m_pluginLuaFunctions, [&handle, this](const SPluginLuaFunction& f) { + const bool NEEDS_REMOVE = f.handle == handle; + + if (NEEDS_REMOVE) // NOLINTNEXTLINE + unregisterPluginLuaFunctionInState(f.namespace_, f.name); + + return NEEDS_REMOVE; + }); +} + +void CConfigManager::registerLuaRef(int ref) { + m_heldLuaRefs.emplace_back(ref); +} + +void CConfigManager::callLuaFn(int ref) { + lua_rawgeti(m_lua, LUA_REGISTRYINDEX, ref); + + int status = guardedPCall(0, 0, 0, CConfigManager::LUA_TIMEOUT_KEYBIND_CALLBACK_MS, "keybind callback"); + + if (status != LUA_OK) { + addError(std::format("error in callLuaFn: {}", lua_tostring(m_lua, -1))); + lua_pop(m_lua, 1); + } +} + +void CConfigManager::clearHeldLuaRefs() { + for (const auto& r : m_heldLuaRefs) { + luaL_unref(m_lua, LUA_REGISTRYINDEX, r); + } + + m_heldLuaRefs.clear(); +} + +bool CConfigManager::isDynamicParse() const { + return !m_isParsingConfig || m_isEvaluating; +} + +void CConfigManager::reregisterLuaPluginFns() { + for (auto& fn : m_pluginLuaFunctions) { + auto ret = registerPluginLuaFunctionInState(fn.id, fn.namespace_, fn.name); + if (!ret) + Log::logger->log(Log::ERR, "[lua] failed to reregister plugin fn for {}.{}: {}", fn.namespace_, fn.name, ret.error()); + } +} diff --git a/src/config/lua/ConfigManager.hpp b/src/config/lua/ConfigManager.hpp new file mode 100644 index 00000000..2f9827d4 --- /dev/null +++ b/src/config/lua/ConfigManager.hpp @@ -0,0 +1,186 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +#include "../../helpers/memory/Memory.hpp" +#include "../ConfigManager.hpp" +#include "../../managers/eventLoop/EventLoopTimer.hpp" + +#include "./types/LuaConfigValue.hpp" +#include "./LuaEventHandler.hpp" + +#include "../../desktop/rule/windowRule/WindowRule.hpp" +#include "../../desktop/rule/layerRule/LayerRule.hpp" + +#include "../../SharedDefs.hpp" +#include "../../managers/KeybindManager.hpp" + +extern "C" { +#include +#include +#include +} + +namespace Config::Supplementary { + struct SConfigOptionDescription; +}; + +namespace Config::Lua { + class CConfigManager; + class CConfigManagerPluginLuaTestAccessor; +} + +namespace Config::Lua::Bindings { + void registerBindings(lua_State* L, CConfigManager* mgr); +} + +namespace Config::Lua { + + class CConfigManager : public Config::IConfigManager { + public: + CConfigManager(); + + virtual eConfigManagerType type() override; + + virtual void init() override; + virtual void reload() override; + virtual std::string verify() override; + + virtual int getDeviceInt(const std::string&, const std::string&, const std::string& fallback = "") override; + virtual float getDeviceFloat(const std::string&, const std::string&, const std::string& fallback = "") override; + virtual Vector2D getDeviceVec(const std::string&, const std::string&, const std::string& fallback = "") override; + virtual std::string getDeviceString(const std::string&, const std::string&, const std::string& fallback = "") override; + virtual bool deviceConfigExplicitlySet(const std::string&, const std::string&) override; + virtual bool deviceConfigExists(const std::string&) override; + + virtual SConfigOptionReply getConfigValue(const std::string&) override; + + virtual std::string getMainConfigPath() override; + virtual std::string getErrors() override; + virtual std::string getConfigString() override; + virtual std::string currentConfigPath() override; + virtual const std::vector& getConfigPaths() override; + + virtual std::expected generateDefaultConfig(const std::filesystem::path&, bool safeMode) override; + + virtual void handlePluginLoads() override; + virtual bool configVerifPassed() override; + + virtual std::expected registerPluginValue(void* handle, SP value) override; + virtual void onPluginUnload(void* handle) override; + + int invokePluginLuaFunctionByID(uint64_t id, lua_State* L); + + std::expected registerPluginLuaFunction(void* handle, const std::string& namespace_, const std::string& name, PLUGIN_LUA_FN fn); + std::expected unregisterPluginLuaFunction(void* handle, const std::string& namespace_, const std::string& name); + + void addError(std::string&& str); + + void registerLuaRef(int ref); + void callLuaFn(int ref); + + // execute an arbitrary lua string on the current state. + std::optional eval(const std::string& code); + + int guardedPCall(int nargs, int nresults, int errfunc, int timeoutMs, std::string_view context); + + static CConfigManager* fromLuaState(lua_State* L); + + static constexpr int LUA_WATCHDOG_INSTRUCTION_INTERVAL = 10000; + static constexpr int LUA_TIMEOUT_CONFIG_RELOAD_MS = 1500; + static constexpr int LUA_TIMEOUT_EVENT_CALLBACK_MS = 50; + static constexpr int LUA_TIMEOUT_KEYBIND_CALLBACK_MS = 100; + static constexpr int LUA_TIMEOUT_TIMER_CALLBACK_MS = 50; + static constexpr int LUA_TIMEOUT_EVAL_MS = 250; + static constexpr int LUA_TIMEOUT_DISPATCH_MS = 100; + + bool isFirstLaunch() const; + bool isDynamicParse() const; + + std::string m_currentSubmap; + std::string m_currentSubmapReset; + + UP m_eventHandler; + + struct SLuaTimer { + SP timer; + int luaRef = LUA_NOREF; // registry ref to the lua callback + }; + std::vector m_luaTimers; + + std::vector m_registeredPlugins; + + std::unordered_map> m_configValues; + + struct SDeviceConfig { + SDeviceConfig(); + + std::unordered_map> values; + }; + + std::unordered_map m_deviceConfigs; + std::vector m_errors, m_configPaths; + + // named window/layer rules for merge-on-redeclaration + std::unordered_map> m_luaWindowRules; + std::unordered_map> m_luaLayerRules; + + private: + void reinitLuaState(); + void postConfigReload(); + void registerValue(const char* name, ILuaConfigValue* val); + void cleanTimers(); + void clearHeldLuaRefs(); + std::string luaConfigValueName(const std::string& s); + std::expected registerPluginLuaFunctionInState(uint64_t id, const std::string& namespace_, const std::string& name); + std::expected unregisterPluginLuaFunctionInState(const std::string& namespace_, const std::string& name); + void erasePluginLuaFunction(uint64_t id); + void reregisterLuaPluginFns(); + + static void watchdogHook(lua_State* L, lua_Debug* ar); + + lua_State* m_lua = nullptr; + + bool m_lastConfigVerificationWasSuccessful = true; + bool m_isFirstLaunch = true; + bool m_manualCrashInitiated = false; + bool m_watchdogActive = false; + bool m_isParsingConfig = false; + bool m_isEvaluating = false; + + std::chrono::steady_clock::time_point m_watchdogDeadline; + std::string m_watchdogContext; + + std::string m_mainConfigPath; + + std::vector m_heldLuaRefs; + + // this is here for legacy reasons. + std::unordered_map m_configPtrMap; + + // this is here for plugin reasons. + std::unordered_map> m_pluginValues; + + struct SPluginLuaFunction { + uint64_t id = 0; + void* handle = nullptr; + std::string namespace_; + std::string name; + Config::PLUGIN_LUA_FN fn = nullptr; + }; + std::vector m_pluginLuaFunctions; + + ILuaConfigValue* findDeviceValue(const std::string& dev, const std::string& field); + + friend class CConfigManagerPluginLuaTestAccessor; + }; + + WP mgr(); +} diff --git a/src/config/lua/DefaultConfig.hpp b/src/config/lua/DefaultConfig.hpp new file mode 100644 index 00000000..6fe92679 --- /dev/null +++ b/src/config/lua/DefaultConfig.hpp @@ -0,0 +1,18 @@ +#pragma once + +#include + +inline constexpr std::string_view AUTOGENERATED_PREFIX = R"#( +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- AUTOGENERATED HYPRLAND CONFIG. -- +-- EDIT THIS CONFIG ACCORDING TO THE WIKI INSTRUCTIONS. -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + +hl.config({ autogenerated = true }) -- remove this line to remove the warning + +)#"; +inline constexpr char EXAMPLE_CONFIG_BYTES[] = { +#embed "../../../example/hyprland.lua" +}; + +inline constexpr std::string_view EXAMPLE_CONFIG = {EXAMPLE_CONFIG_BYTES, sizeof(EXAMPLE_CONFIG_BYTES)}; diff --git a/src/config/lua/Emergency.hpp b/src/config/lua/Emergency.hpp new file mode 100644 index 00000000..ef791d45 --- /dev/null +++ b/src/config/lua/Emergency.hpp @@ -0,0 +1,47 @@ +#pragma once + +namespace Config::Lua { + constexpr const char* EMERGENCY_PCALL = R"#( +local function shell_ok(cmd) + local a, b, c = os.execute(cmd) + if type(a) == "number" then + return a == 0 + end + return a == true and b == "exit" and c == 0 +end + +local function first_installed(candidates) + for _, bin in ipairs(candidates) do + if shell_ok(("command -v %q >/dev/null 2>&1"):format(bin)) then + return bin + end + end + return nil +end + +local function launch_first_installed(candidates) + local term = first_installed(candidates) + if not term then + return false + end + hl.dispatch(hl.dsp.exec_cmd(term)) + return true +end + +hl.bind("SUPER + Q", function() + launch_first_installed({ "kitty", "alacritty", "foot", "wezterm", "gnome-terminal", "xterm" }) +end) + +hl.bind("SUPER + R", hl.dsp.exec_cmd("hyprland-run")) +hl.bind("SUPER + M", hl.dsp.exit()) + +hl.window_rule({ + name = "move-hyprland-run", + match = { class = "hyprland-run" }, + + move = "20 monitor_h-120", + float = true, +}) + +)#"; +} \ No newline at end of file diff --git a/src/config/lua/LuaBindings.cpp b/src/config/lua/LuaBindings.cpp new file mode 100644 index 00000000..2121c33e --- /dev/null +++ b/src/config/lua/LuaBindings.cpp @@ -0,0 +1,7 @@ +#include "LuaBindings.hpp" + +#include "bindings/LuaBindingsInternal.hpp" + +void Config::Lua::Bindings::registerBindings(lua_State* L, CConfigManager* mgr) { + Internal::registerBindingsImpl(L, mgr); +} diff --git a/src/config/lua/LuaBindings.hpp b/src/config/lua/LuaBindings.hpp new file mode 100644 index 00000000..e8f307bd --- /dev/null +++ b/src/config/lua/LuaBindings.hpp @@ -0,0 +1,13 @@ +#pragma once + +extern "C" { +#include +} + +namespace Config::Lua { + class CConfigManager; +} + +namespace Config::Lua::Bindings { + void registerBindings(lua_State* L, CConfigManager* mgr); +} diff --git a/src/config/lua/LuaEventHandler.cpp b/src/config/lua/LuaEventHandler.cpp new file mode 100644 index 00000000..4fa138dd --- /dev/null +++ b/src/config/lua/LuaEventHandler.cpp @@ -0,0 +1,233 @@ +#include "LuaEventHandler.hpp" +#include "ConfigManager.hpp" +#include "objects/LuaWindow.hpp" +#include "objects/LuaWorkspace.hpp" +#include "objects/LuaMonitor.hpp" +#include "objects/LuaLayerSurface.hpp" + +#include "../../defines.hpp" +#include "../../event/EventBus.hpp" +#include "../../desktop/state/FocusState.hpp" + +extern "C" { +#include +} + +#include +#include + +using namespace Config::Lua; +using namespace Config::Lua::Objects; + +void CLuaEventHandler::dispatch(const std::string& name, int nargs, const std::function& pushArgs) { + auto it = m_callbacks.find(name); + if (it == m_callbacks.end() || it->second.empty()) + return; + + if (m_dispatchDepth >= MAX_DISPATCH_DEPTH) { + Log::logger->log(Log::WARN, "[LuaEvents] max dispatch depth ({}) reached while handling '{}'", MAX_DISPATCH_DEPTH, name); + return; + } + + const auto handles = it->second; + + for (const auto handle : handles) { + const auto sub = m_subscriptions.find(handle); + if (sub == m_subscriptions.end()) + continue; + + if (m_activeHandles.contains(handle)) { + if (m_reentrancyWarnedHandles.emplace(handle).second) + Log::logger->log(Log::WARN, "[LuaEvents] suppressed recursive hl.on(\"{}\") callback invocation", name); + continue; + } + + struct SDispatchScope { + CLuaEventHandler* self = nullptr; + uint64_t handle = 0; + + ~SDispatchScope() { + if (!self) + return; + + self->m_activeHandles.erase(handle); + if (self->m_dispatchDepth > 0) + --self->m_dispatchDepth; + } + } dispatchScope{.self = this, .handle = handle}; + + m_activeHandles.emplace(handle); + ++m_dispatchDepth; + + lua_rawgeti(m_lua, LUA_REGISTRYINDEX, sub->second.luaRef); + pushArgs(); + + int status = LUA_OK; + if (auto* mgr = CConfigManager::fromLuaState(m_lua); mgr) + status = mgr->guardedPCall(nargs, 0, 0, CConfigManager::LUA_TIMEOUT_EVENT_CALLBACK_MS, std::format("hl.on(\"{}\") callback", name)); + else + status = lua_pcall(m_lua, nargs, 0, 0); + + if (status != LUA_OK) { + const char* err = lua_tostring(m_lua, -1); + Config::Lua::mgr()->addError(std::format("hl.on(\"{}\") callback: {}", name, err ? err : "(unknown)")); + lua_pop(m_lua, 1); + } + } +} + +CLuaEventHandler::CLuaEventHandler(lua_State* L) : m_lua(L) { + CLuaWindow{}.setup(L); + CLuaWorkspace{}.setup(L); + CLuaMonitor{}.setup(L); + CLuaLayerSurface{}.setup(L); + + using namespace Event; + + m_listeners.push_back(bus()->m_events.window.open.listen([this](PHLWINDOW w) { dispatch("window.open", 1, [&] { CLuaWindow::push(m_lua, w); }); })); + m_listeners.push_back(bus()->m_events.window.openEarly.listen([this](PHLWINDOW w) { dispatch("window.open_early", 1, [&] { CLuaWindow::push(m_lua, w); }); })); + m_listeners.push_back(bus()->m_events.window.close.listen([this](PHLWINDOW w) { dispatch("window.close", 1, [&] { CLuaWindow::push(m_lua, w); }); })); + m_listeners.push_back(bus()->m_events.window.destroy.listen([this](PHLWINDOW w) { dispatch("window.destroy", 1, [&] { CLuaWindow::push(m_lua, w); }); })); + m_listeners.push_back(bus()->m_events.window.kill.listen([this](PHLWINDOW w) { dispatch("window.kill", 1, [&] { CLuaWindow::push(m_lua, w); }); })); + m_listeners.push_back(bus()->m_events.window.active.listen([this](PHLWINDOW w, Desktop::eFocusReason r) { + dispatch("window.active", 2, [&] { + CLuaWindow::push(m_lua, w); + lua_pushinteger(m_lua, sc(r)); + }); + })); + m_listeners.push_back(bus()->m_events.window.urgent.listen([this](PHLWINDOW w) { dispatch("window.urgent", 1, [&] { CLuaWindow::push(m_lua, w); }); })); + m_listeners.push_back(bus()->m_events.window.title.listen([this](PHLWINDOW w) { dispatch("window.title", 1, [&] { CLuaWindow::push(m_lua, w); }); })); + m_listeners.push_back(bus()->m_events.window.class_.listen([this](PHLWINDOW w) { dispatch("window.class", 1, [&] { CLuaWindow::push(m_lua, w); }); })); + m_listeners.push_back(bus()->m_events.window.pin.listen([this](PHLWINDOW w) { dispatch("window.pin", 1, [&] { CLuaWindow::push(m_lua, w); }); })); + m_listeners.push_back(bus()->m_events.window.fullscreen.listen([this](PHLWINDOW w) { dispatch("window.fullscreen", 1, [&] { CLuaWindow::push(m_lua, w); }); })); + m_listeners.push_back(bus()->m_events.window.updateRules.listen([this](PHLWINDOW w) { dispatch("window.update_rules", 1, [&] { CLuaWindow::push(m_lua, w); }); })); + m_listeners.push_back(bus()->m_events.window.moveToWorkspace.listen([this](PHLWINDOW w, PHLWORKSPACE ws) { + dispatch("window.move_to_workspace", 2, [&] { + CLuaWindow::push(m_lua, w); + CLuaWorkspace::push(m_lua, ws); + }); + })); + + m_listeners.push_back(bus()->m_events.layer.opened.listen([this](PHLLS ls) { dispatch("layer.opened", 1, [&] { CLuaLayerSurface::push(m_lua, ls); }); })); + m_listeners.push_back(bus()->m_events.layer.closed.listen([this](PHLLS ls) { dispatch("layer.closed", 1, [&] { CLuaLayerSurface::push(m_lua, ls); }); })); + + m_listeners.push_back(bus()->m_events.monitor.added.listen([this](PHLMONITOR mon) { dispatch("monitor.added", 1, [&] { CLuaMonitor::push(m_lua, mon); }); })); + m_listeners.push_back(bus()->m_events.monitor.removed.listen([this](PHLMONITOR mon) { dispatch("monitor.removed", 1, [&] { CLuaMonitor::push(m_lua, mon); }); })); + m_listeners.push_back(bus()->m_events.monitor.focused.listen([this](PHLMONITOR mon) { dispatch("monitor.focused", 1, [&] { CLuaMonitor::push(m_lua, mon); }); })); + m_listeners.push_back(bus()->m_events.monitor.layoutChanged.listen([this] { dispatch("monitor.layout_changed", 0, [] {}); })); + + m_listeners.push_back(bus()->m_events.workspace.active.listen([this](PHLWORKSPACE ws) { dispatch("workspace.active", 1, [&] { CLuaWorkspace::push(m_lua, ws); }); })); + m_listeners.push_back(bus()->m_events.workspace.created.listen([this](PHLWORKSPACEREF wsRef) { + const auto ws = wsRef.lock(); + if (!ws) + return; + dispatch("workspace.created", 1, [&] { CLuaWorkspace::push(m_lua, ws); }); + })); + m_listeners.push_back(bus()->m_events.workspace.removed.listen([this](PHLWORKSPACEREF wsRef) { + const auto ws = wsRef.lock(); + if (!ws) + return; + dispatch("workspace.removed", 1, [&] { CLuaWorkspace::push(m_lua, ws); }); + })); + m_listeners.push_back(bus()->m_events.workspace.moveToMonitor.listen([this](PHLWORKSPACE ws, PHLMONITOR mon) { + dispatch("workspace.move_to_monitor", 2, [&] { + CLuaWorkspace::push(m_lua, ws); + CLuaMonitor::push(m_lua, mon); + }); + })); + + m_listeners.push_back(bus()->m_events.config.reloaded.listen([this] { dispatch("config.reloaded", 0, [] {}); })); + m_listeners.push_back( + bus()->m_events.keybinds.submap.listen([this](const std::string& submap) { dispatch("keybinds.submap", 1, [&] { lua_pushstring(m_lua, submap.c_str()); }); })); + m_listeners.push_back(bus()->m_events.screenshare.state.listen([this](bool state, uint8_t type, const std::string& name) { + dispatch("screenshare.state", 3, [&] { + lua_pushboolean(m_lua, state); + lua_pushinteger(m_lua, sc(type)); + lua_pushstring(m_lua, name.c_str()); + }); + })); + + m_listeners.push_back(bus()->m_events.start.listen([this]() { dispatch("hyprland.start", 0, [] {}); })); + m_listeners.push_back(bus()->m_events.exit.listen([this]() { dispatch("hyprland.shutdown", 0, [] {}); })); +} + +CLuaEventHandler::~CLuaEventHandler() { + clearEvents(); +} + +std::optional CLuaEventHandler::registerEvent(const std::string& name, int luaRef) { + if (!knownEvents().contains(name)) + return std::nullopt; + + const auto handle = m_nextHandle++; + m_callbacks[name].push_back(handle); + m_subscriptions[handle] = {.eventName = name, .luaRef = luaRef}; + + return handle; +} + +bool CLuaEventHandler::unregisterEvent(uint64_t handle) { + const auto it = m_subscriptions.find(handle); + if (it == m_subscriptions.end()) + return false; + + luaL_unref(m_lua, LUA_REGISTRYINDEX, it->second.luaRef); + + auto callbacksIt = m_callbacks.find(it->second.eventName); + if (callbacksIt != m_callbacks.end()) { + std::erase(callbacksIt->second, handle); + if (callbacksIt->second.empty()) + m_callbacks.erase(callbacksIt); + } + + m_subscriptions.erase(it); + m_activeHandles.erase(handle); + m_reentrancyWarnedHandles.erase(handle); + + return true; +} + +void CLuaEventHandler::clearEvents() { + for (const auto& s : m_subscriptions) { + luaL_unref(m_lua, LUA_REGISTRYINDEX, s.second.luaRef); + } + + m_subscriptions.clear(); + m_activeHandles.clear(); + m_reentrancyWarnedHandles.clear(); + m_callbacks.clear(); +} + +const std::unordered_set& CLuaEventHandler::knownEvents() { + static const std::unordered_set EVENTS = { + "window.open", + "window.open_early", + "window.close", + "window.destroy", + "window.kill", + "window.active", + "window.urgent", + "window.title", + "window.class", + "window.pin", + "window.fullscreen", + "window.update_rules", + "window.move_to_workspace", + "layer.opened", + "layer.closed", + "monitor.added", + "monitor.removed", + "monitor.focused", + "monitor.layout_changed", + "workspace.active", + "workspace.created", + "workspace.removed", + "workspace.move_to_monitor", + "config.reloaded", + "keybinds.submap", + "screenshare.state", + "hyprland.start", + "hyprland.shutdown", + }; + return EVENTS; +} diff --git a/src/config/lua/LuaEventHandler.hpp b/src/config/lua/LuaEventHandler.hpp new file mode 100644 index 00000000..a48d7800 --- /dev/null +++ b/src/config/lua/LuaEventHandler.hpp @@ -0,0 +1,61 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "../../helpers/memory/Memory.hpp" +#include "../../helpers/signal/Signal.hpp" +#include "../../desktop/DesktopTypes.hpp" + +extern "C" { +#include +} + +namespace Config::Lua { + + // Manages hl.on() event subscriptions for a single Lua state lifetime. + // Destroyed (and recreated) on every config reload so callbacks never double-up. + // + // Hyprland objects (window, workspace, monitor, layer surface) are exposed to Lua + // as typed userdata holding a weak pointer. Field accesses read live C++ state via + // __index; accessing a field on a destroyed object raises a Lua error. + class CLuaEventHandler { + public: + explicit CLuaEventHandler(lua_State* L); + ~CLuaEventHandler(); + + // Store a Lua function (as a registry ref) to be called when `name` fires. + // Returns a subscription handle, or std::nullopt if the event name is unknown. + std::optional registerEvent(const std::string& name, int luaRef); + bool unregisterEvent(uint64_t handle); + + void clearEvents(); + + static const std::unordered_set& knownEvents(); + + private: + struct SSubscription { + std::string eventName; + int luaRef = -1; + }; + + lua_State* m_lua = nullptr; + std::unordered_map> m_callbacks; + std::unordered_map m_subscriptions; + std::unordered_set m_activeHandles; + std::unordered_set m_reentrancyWarnedHandles; + uint64_t m_nextHandle = 1; + size_t m_dispatchDepth = 0; + std::vector m_listeners; + + static constexpr size_t MAX_DISPATCH_DEPTH = 32; + + void dispatch(const std::string& name, int nargs, const std::function& pushArgs); + }; + +} diff --git a/src/config/lua/bindings/LuaBindingsConfigRules.cpp b/src/config/lua/bindings/LuaBindingsConfigRules.cpp new file mode 100644 index 00000000..2faab8c6 --- /dev/null +++ b/src/config/lua/bindings/LuaBindingsConfigRules.cpp @@ -0,0 +1,1224 @@ +#include "LuaBindingsInternal.hpp" + +#include "../objects/LuaLayerRule.hpp" +#include "../objects/LuaWindowRule.hpp" + +#include "../types/LuaConfigBool.hpp" +#include "../types/LuaConfigCssGap.hpp" +#include "../types/LuaConfigFloat.hpp" +#include "../types/LuaConfigGradient.hpp" +#include "../types/LuaConfigInt.hpp" +#include "../types/LuaConfigString.hpp" +#include "../types/LuaConfigVec2.hpp" + +#include "../../supplementary/executor/Executor.hpp" +#include "../../supplementary/propRefresher/PropRefresher.hpp" +#include "../../shared/animation/AnimationTree.hpp" +#include "../../shared/monitor/MonitorRuleManager.hpp" +#include "../../shared/monitor/Parser.hpp" +#include "../../shared/workspace/WorkspaceRuleManager.hpp" + +#include "../../../desktop/rule/Engine.hpp" +#include "../../../desktop/rule/layerRule/LayerRule.hpp" +#include "../../../desktop/rule/layerRule/LayerRuleEffectContainer.hpp" +#include "../../../desktop/rule/windowRule/WindowRule.hpp" +#include "../../../desktop/rule/windowRule/WindowRuleEffectContainer.hpp" +#include "../../../layout/LayoutManager.hpp" +#include "../../../layout/supplementary/WorkspaceAlgoMatcher.hpp" +#include "../../../managers/animation/AnimationManager.hpp" +#include "../../../managers/input/InputManager.hpp" +#include "../../../managers/input/trackpad/TrackpadGestures.hpp" +#include "../../../managers/input/trackpad/gestures/CloseGesture.hpp" +#include "../../../managers/input/trackpad/gestures/CursorZoomGesture.hpp" +#include "../../../managers/input/trackpad/gestures/DispatcherGesture.hpp" +#include "../../../managers/input/trackpad/gestures/FloatGesture.hpp" +#include "../../../managers/input/trackpad/gestures/FullscreenGesture.hpp" +#include "../../../managers/input/trackpad/gestures/LuaFunctionGesture.hpp" +#include "../../../managers/input/trackpad/gestures/MoveGesture.hpp" +#include "../../../managers/input/trackpad/gestures/ResizeGesture.hpp" +#include "../../../managers/input/trackpad/gestures/SpecialWorkspaceGesture.hpp" +#include "../../../managers/input/trackpad/gestures/WorkspaceSwipeGesture.hpp" +#include "../../../managers/permissions/DynamicPermissionManager.hpp" + +using namespace Config; +using namespace Config::Lua; +using namespace Config::Lua::Bindings; + +namespace { + struct SFieldDesc { + const char* name; + std::function factory; + }; + + struct SMonitorFieldDesc { + const char* name; + std::function factory; + std::function apply; + }; + + struct SLayerRuleEffectDesc { + const char* name; + std::function factory; + uint16_t effect; + }; + + struct SWorkspaceRuleFieldDesc { + const char* name; + std::function factory; + std::function apply; + }; + + using LE = Desktop::Rule::eLayerRuleEffect; + + inline const SMonitorFieldDesc MONITOR_FIELDS[] = { + {"mode", []() -> ILuaConfigValue* { return new CLuaConfigString("preferred"); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { return p.parseMode(*sc(v->data())); }}, + {"position", []() -> ILuaConfigValue* { return new CLuaConfigString("auto"); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { return p.parsePosition(*sc(v->data())); }}, + {"scale", []() -> ILuaConfigValue* { return new CLuaConfigString("auto"); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { return p.parseScale(*sc(v->data())); }}, + {"reserved", []() -> ILuaConfigValue* { return new CLuaConfigCssGap(0); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + const auto& gap = *sc(v->data()); + return p.setReserved(Desktop::CReservedArea(gap.m_top, gap.m_right, gap.m_bottom, gap.m_left)); + }}, + {"reserved_area", []() -> ILuaConfigValue* { return new CLuaConfigCssGap(0); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + const auto& gap = *sc(v->data()); + return p.setReserved(Desktop::CReservedArea(gap.m_top, gap.m_right, gap.m_bottom, gap.m_left)); + }}, + {"disabled", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + if (*sc(v->data())) + p.setDisabled(); + return true; + }}, + {"transform", []() -> ILuaConfigValue* { return new CLuaConfigInt(0, 0, 7); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.rule().m_transform = sc(*sc(v->data())); + return true; + }}, + {"mirror", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.setMirror(*sc(v->data())); + return true; + }}, + {"bitdepth", []() -> ILuaConfigValue* { return new CLuaConfigInt(8); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.rule().m_enable10bit = *sc(v->data()) == 10; + return true; + }}, + {"cm", []() -> ILuaConfigValue* { return new CLuaConfigString("srgb"); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { return p.parseCM(*sc(v->data())); }}, + {"sdr_eotf", []() -> ILuaConfigValue* { return new CLuaConfigString("default"); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.rule().m_sdrEotf = NTransferFunction::fromString(*sc(v->data())); + return true; + }}, + {"sdrbrightness", []() -> ILuaConfigValue* { return new CLuaConfigFloat(1.F); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.rule().m_sdrBrightness = *sc(v->data()); + return true; + }}, + {"sdrsaturation", []() -> ILuaConfigValue* { return new CLuaConfigFloat(1.F); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.rule().m_sdrSaturation = *sc(v->data()); + return true; + }}, + {"vrr", []() -> ILuaConfigValue* { return new CLuaConfigInt(0, 0, 3); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.rule().m_vrr = sc(*sc(v->data())); + return true; + }}, + {"icc", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { return p.parseICC(*sc(v->data())); }}, + {"supports_wide_color", []() -> ILuaConfigValue* { return new CLuaConfigInt(0, -1, 1); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.rule().m_supportsWideColor = sc(*sc(v->data())); + return true; + }}, + {"supports_hdr", []() -> ILuaConfigValue* { return new CLuaConfigInt(0, -1, 1); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.rule().m_supportsHDR = sc(*sc(v->data())); + return true; + }}, + {"sdr_min_luminance", []() -> ILuaConfigValue* { return new CLuaConfigFloat(0.2F); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.rule().m_sdrMinLuminance = *sc(v->data()); + return true; + }}, + {"sdr_max_luminance", []() -> ILuaConfigValue* { return new CLuaConfigInt(80); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.rule().m_sdrMaxLuminance = sc(*sc(v->data())); + return true; + }}, + {"min_luminance", []() -> ILuaConfigValue* { return new CLuaConfigFloat(-1.F); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.rule().m_minLuminance = *sc(v->data()); + return true; + }}, + {"max_luminance", []() -> ILuaConfigValue* { return new CLuaConfigInt(-1); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.rule().m_maxLuminance = sc(*sc(v->data())); + return true; + }}, + {"max_avg_luminance", []() -> ILuaConfigValue* { return new CLuaConfigInt(-1); }, + [](ILuaConfigValue* v, CMonitorRuleParser& p) { + p.rule().m_maxAvgLuminance = sc(*sc(v->data())); + return true; + }}, + }; + + static_assert(sizeof(Internal::WINDOW_RULE_EFFECT_DESCS) / sizeof(Internal::SWindowRuleEffectDesc) == Internal::WE::WINDOW_RULE_EFFECT_LAST_STATIC - 1); + + inline const SLayerRuleEffectDesc LAYER_RULE_EFFECT_DESCS[] = { + {"no_anim", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, LE::LAYER_RULE_EFFECT_NO_ANIM}, + {"blur", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, LE::LAYER_RULE_EFFECT_BLUR}, + {"blur_popups", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, LE::LAYER_RULE_EFFECT_BLUR_POPUPS}, + {"ignore_alpha", []() -> ILuaConfigValue* { return new CLuaConfigFloat(0.F, 0.F, 1.F); }, LE::LAYER_RULE_EFFECT_IGNORE_ALPHA}, + {"dim_around", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, LE::LAYER_RULE_EFFECT_DIM_AROUND}, + {"xray", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, LE::LAYER_RULE_EFFECT_XRAY}, + {"animation", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, LE::LAYER_RULE_EFFECT_ANIMATION}, + {"order", []() -> ILuaConfigValue* { return new CLuaConfigInt(0); }, LE::LAYER_RULE_EFFECT_ORDER}, + {"above_lock", []() -> ILuaConfigValue* { return new CLuaConfigInt(0, 0, 2); }, LE::LAYER_RULE_EFFECT_ABOVE_LOCK}, + {"no_screen_share", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, LE::LAYER_RULE_EFFECT_NO_SCREEN_SHARE}, + }; + + static_assert(sizeof(LAYER_RULE_EFFECT_DESCS) / sizeof(SLayerRuleEffectDesc) == LE::LAYER_RULE_EFFECT_LAST_STATIC - 1); + + inline const SWorkspaceRuleFieldDesc WORKSPACE_RULE_FIELDS[] = { + {"monitor", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_monitor = *sc(v->data()); }}, + {"default", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_isDefault = *sc(v->data()); }}, + {"persistent", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_isPersistent = *sc(v->data()); }}, + {"gaps_in", []() -> ILuaConfigValue* { return new CLuaConfigCssGap(5); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_gapsIn = *sc(v->data()); }}, + {"gaps_out", []() -> ILuaConfigValue* { return new CLuaConfigCssGap(20); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_gapsOut = *sc(v->data()); }}, + {"float_gaps", []() -> ILuaConfigValue* { return new CLuaConfigCssGap(0); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_floatGaps = *sc(v->data()); }}, + {"border_size", []() -> ILuaConfigValue* { return new CLuaConfigInt(-1); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_borderSize = *sc(v->data()); }}, + {"no_border", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_noBorder = *sc(v->data()); }}, + {"no_rounding", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_noRounding = *sc(v->data()); }}, + {"decorate", []() -> ILuaConfigValue* { return new CLuaConfigBool(true); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_decorate = *sc(v->data()); }}, + {"no_shadow", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_noShadow = *sc(v->data()); }}, + {"on_created_empty", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_onCreatedEmptyRunCmd = *sc(v->data()); }}, + {"default_name", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_defaultName = *sc(v->data()); }}, + {"layout", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_layout = *sc(v->data()); }}, + {"animation", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, + [](ILuaConfigValue* v, Config::CWorkspaceRule& r) { r.m_animationStyle = *sc(v->data()); }}, + }; + + inline const SFieldDesc DEVICE_FIELDS[] = { + {"sensitivity", []() -> ILuaConfigValue* { return new CLuaConfigFloat(0.F, -1.F, 1.F); }}, + {"accel_profile", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }}, + {"rotation", []() -> ILuaConfigValue* { return new CLuaConfigInt(0, 0, 359); }}, + {"kb_file", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }}, + {"kb_layout", []() -> ILuaConfigValue* { return new CLuaConfigString("us"); }}, + {"kb_variant", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }}, + {"kb_options", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }}, + {"kb_rules", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }}, + {"kb_model", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }}, + {"repeat_rate", []() -> ILuaConfigValue* { return new CLuaConfigInt(25, 0, 200); }}, + {"repeat_delay", []() -> ILuaConfigValue* { return new CLuaConfigInt(600, 0, 2000); }}, + {"natural_scroll", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }}, + {"tap_button_map", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }}, + {"numlock_by_default", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }}, + {"resolve_binds_by_sym", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }}, + {"disable_while_typing", []() -> ILuaConfigValue* { return new CLuaConfigBool(true); }}, + {"clickfinger_behavior", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }}, + {"middle_button_emulation", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }}, + {"tap_to_click", []() -> ILuaConfigValue* { return new CLuaConfigBool(true); }}, + {"tap_and_drag", []() -> ILuaConfigValue* { return new CLuaConfigBool(true); }}, + {"drag_lock", []() -> ILuaConfigValue* { return new CLuaConfigInt(0, 0, 2); }}, + {"left_handed", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }}, + {"scroll_method", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }}, + {"scroll_button", []() -> ILuaConfigValue* { return new CLuaConfigInt(0, 0, 300); }}, + {"scroll_button_lock", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }}, + {"scroll_points", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }}, + {"scroll_factor", []() -> ILuaConfigValue* { return new CLuaConfigFloat(1.F, 0.F, 100.F); }}, + {"transform", []() -> ILuaConfigValue* { return new CLuaConfigInt(-1); }}, + {"output", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }}, + {"enabled", []() -> ILuaConfigValue* { return new CLuaConfigBool(true); }}, + {"region_position", []() -> ILuaConfigValue* { return new CLuaConfigVec2({0, 0}); }}, + {"absolute_region_position", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }}, + {"region_size", []() -> ILuaConfigValue* { return new CLuaConfigVec2({0, 0}); }}, + {"relative_input", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }}, + {"active_area_position", []() -> ILuaConfigValue* { return new CLuaConfigVec2({0, 0}); }}, + {"active_area_size", []() -> ILuaConfigValue* { return new CLuaConfigVec2({0, 0}); }}, + {"flip_x", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }}, + {"flip_y", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }}, + {"drag_3fg", []() -> ILuaConfigValue* { return new CLuaConfigInt(0, 0, 2); }}, + {"keybinds", []() -> ILuaConfigValue* { return new CLuaConfigBool(true); }}, + {"share_states", []() -> ILuaConfigValue* { return new CLuaConfigInt(0, 0, 2); }}, + {"release_pressed_on_close", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }}, + }; + +} + +static int hlCurve(lua_State* L) { + CLuaConfigString nameParser(""); + lua_pushvalue(L, 1); + auto nameErr = nameParser.parse(L); + lua_pop(L, 1); + if (nameErr.errorCode != PARSE_ERROR_OK) + return Internal::configError(L, std::format("hl.curve: first argument (name) must be a string: {}", nameErr.message)); + + const auto& name = nameParser.parsed(); + + if (!lua_istable(L, 2)) + return Internal::configError(L, "hl.curve: second argument must be a table, e.g. { type = \"bezier\", points = { {0, 0}, {1, 1} } }"); + + CLuaConfigString typeParser(""); + auto typeErr = Internal::parseTableField(L, 2, "type", typeParser); + if (typeErr.errorCode != PARSE_ERROR_OK) + return Internal::configError(L, std::format("hl.curve(\"{}\"): {}", name, typeErr.message)); + + const auto& curveType = typeParser.parsed(); + + if (curveType != "bezier") + return Internal::configError(L, std::format("hl.curve(\"{}\"): unknown curve type \"{}\", expected \"bezier\"", name, curveType)); + + lua_getfield(L, 2, "points"); + if (!lua_istable(L, -1)) { + lua_pop(L, 1); + return Internal::configError(L, std::format("hl.curve(\"{}\"): missing or invalid \"points\" field, expected a table of two points", name)); + } + int pointsIdx = lua_gettop(L); + + if (luaL_len(L, pointsIdx) != 2) { + lua_pop(L, 1); + return Internal::configError(L, std::format("hl.curve(\"{}\"): \"points\" must contain exactly 2 points, e.g. {{ {{0, 0}}, {{1, 1}} }}", name)); + } + + float coords[4] = {}; + for (int pt = 1; pt <= 2; pt++) { + lua_rawgeti(L, pointsIdx, pt); + if (!lua_istable(L, -1) || luaL_len(L, -1) != 2) { + lua_pop(L, 2); + return Internal::configError(L, std::format("hl.curve(\"{}\"): point {} must be a table of 2 numbers, e.g. {{0.25, 0.1}}", name, pt)); + } + int ptIdx = lua_gettop(L); + + for (int comp = 0; comp < 2; comp++) { + lua_rawgeti(L, ptIdx, comp + 1); + CLuaConfigFloat coordParser(0.F, -1.F, 2.F); + auto coordErr = coordParser.parse(L); + lua_pop(L, 1); + if (coordErr.errorCode != PARSE_ERROR_OK) { + lua_pop(L, 2); + return Internal::configError(L, std::format("hl.curve(\"{}\"): point {}[{}]: {}", name, pt, comp + 1, coordErr.message)); + } + coords[((pt - 1) * 2) + comp] = coordParser.parsed(); + } + + lua_pop(L, 1); + } + lua_pop(L, 1); + + g_pAnimationManager->addBezierWithName(name, Vector2D(coords[0], coords[1]), Vector2D(coords[2], coords[3])); + return 0; +} + +static int hlAnimation(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.animation: expected a table, e.g. { leaf = \"global\", enabled = true, speed = 5, bezier = \"default\" }"); + + CLuaConfigString leafParser(""); + auto leafErr = Internal::parseTableField(L, 1, "leaf", leafParser); + if (leafErr.errorCode != PARSE_ERROR_OK) + return Internal::configError(L, std::format("hl.animation: {}", leafErr.message)); + + const auto leaf = leafParser.parsed(); + + if (!Config::animationTree()->nodeExists(leaf)) + return Internal::configError(L, std::format("hl.animation: no such animation leaf \"{}\"", leaf)); + + CLuaConfigBool enabledParser(true); + auto enabledErr = Internal::parseTableField(L, 1, "enabled", enabledParser); + if (enabledErr.errorCode != PARSE_ERROR_OK) + return Internal::configError(L, std::format("hl.animation(\"{}\"): {}", leaf, enabledErr.message)); + + bool enabled = enabledParser.parsed(); + + if (!enabled) { + Config::animationTree()->setConfigForNode(leaf, false, 1, "default"); + return 0; + } + + CLuaConfigFloat speedParser(0.F, 0.F, 100.F); + auto speedErr = Internal::parseTableField(L, 1, "speed", speedParser); + if (speedErr.errorCode != PARSE_ERROR_OK) + return Internal::configError(L, std::format("hl.animation(\"{}\"): {}", leaf, speedErr.message)); + + float speed = speedParser.parsed(); + + if (speed <= 0) + return Internal::configError(L, std::format("hl.animation(\"{}\"): speed must be greater than 0", leaf)); + + CLuaConfigString bezierParser(""); + auto bezierErr = Internal::parseTableField(L, 1, "bezier", bezierParser); + if (bezierErr.errorCode != PARSE_ERROR_OK) + return Internal::configError(L, std::format("hl.animation(\"{}\"): {}", leaf, bezierErr.message)); + + const auto& bezierName = bezierParser.parsed(); + + if (!g_pAnimationManager->bezierExists(bezierName)) + return Internal::configError(L, std::format("hl.animation(\"{}\"): no such bezier \"{}\"", leaf, bezierName)); + + std::string style; + lua_getfield(L, 1, "style"); + if (!lua_isnil(L, -1)) { + CLuaConfigString styleParser(""); + auto styleErr = styleParser.parse(L); + if (styleErr.errorCode != PARSE_ERROR_OK) { + lua_pop(L, 1); + return Internal::configError(L, std::format("hl.animation(\"{}\"): field \"style\": {}", leaf, styleErr.message)); + } + style = styleParser.parsed(); + } + lua_pop(L, 1); + + if (!style.empty()) { + auto err = g_pAnimationManager->styleValidInConfigVar(leaf, style); + if (!err.empty()) + return Internal::configError(L, std::format("hl.animation(\"{}\"): {}", leaf, err)); + } + + Config::animationTree()->setConfigForNode(leaf, true, speed, bezierName, style); + return 0; +} + +static int hlEnv(lua_State* L) { + auto* mgr = sc(lua_touserdata(L, lua_upvalueindex(1))); + + CLuaConfigString nameParser(""); + lua_pushvalue(L, 1); + auto nameErr = nameParser.parse(L); + lua_pop(L, 1); + if (nameErr.errorCode != PARSE_ERROR_OK) + return Internal::configError(L, std::format("hl.env: first argument (name) must be a string: {}", nameErr.message)); + + const auto& name = nameParser.parsed(); + + if (name.empty()) + return Internal::configError(L, "hl.env: name must not be empty"); + + CLuaConfigString valueParser(""); + lua_pushvalue(L, 2); + auto valueErr = valueParser.parse(L); + lua_pop(L, 1); + if (valueErr.errorCode != PARSE_ERROR_OK) + return Internal::configError(L, std::format("hl.env: second argument (value) must be a string: {}", valueErr.message)); + + const auto& value = valueParser.parsed(); + + if (!mgr->isFirstLaunch()) { + const auto* ENV = getenv(name.c_str()); + if (ENV && ENV == value) + return 0; + } + + setenv(name.c_str(), value.c_str(), 1); + + bool dbus = false; + if (!lua_isnoneornil(L, 3)) { + CLuaConfigBool dbusParser(false); + lua_pushvalue(L, 3); + auto dbusErr = dbusParser.parse(L); + lua_pop(L, 1); + if (dbusErr.errorCode != PARSE_ERROR_OK) + return Internal::configError(L, std::format("hl.env: third argument (dbus) must be a boolean: {}", dbusErr.message)); + + dbus = dbusParser.parsed(); + } + + if (dbus) { + std::string CMD; +#ifdef USES_SYSTEMD + CMD = "systemctl --user import-environment '" + name + "' && hash dbus-update-activation-environment 2>/dev/null && "; +#endif + CMD += "dbus-update-activation-environment --systemd '" + name + "'"; + if (mgr->isFirstLaunch()) + Config::Supplementary::executor()->addExecOnce({CMD, false}); + else + Config::Supplementary::executor()->spawnRaw(CMD); + } + + return 0; +} + +static int hlPluginLoad(lua_State* L) { + auto* mgr = sc(lua_touserdata(L, lua_upvalueindex(1))); + + CLuaConfigString pathParser(""); + lua_pushvalue(L, 1); + auto pathErr = pathParser.parse(L); + lua_pop(L, 1); + if (pathErr.errorCode != PARSE_ERROR_OK) + return Internal::configError(L, std::format("hl.plugin.load: first argument (path) must be a string: {}", pathErr.message)); + + const auto& path = pathParser.parsed(); + + if (path.empty()) + return Internal::configError(L, "hl.plugin.load: path must not be empty"); + + mgr->m_registeredPlugins.emplace_back(path); + return 0; +} + +static int hlPermission(lua_State* L) { + auto* mgr = sc(lua_touserdata(L, lua_upvalueindex(1))); + + std::string binary; + std::string typeStr; + std::string modeStr; + + if (lua_istable(L, 1)) { + auto b = Internal::tableOptStr(L, 1, "binary"); + if (!b) + b = Internal::tableOptStr(L, 1, "target"); + auto t = Internal::tableOptStr(L, 1, "type"); + auto m = Internal::tableOptStr(L, 1, "mode"); + + if (!b || !t || !m) + return Internal::configError(L, "hl.permission: expected { binary, type, mode }"); + + binary = *b; + typeStr = *t; + modeStr = *m; + } else { + binary = luaL_checkstring(L, 1); + typeStr = luaL_checkstring(L, 2); + modeStr = luaL_checkstring(L, 3); + } + + if (binary.empty()) + return Internal::configError(L, "hl.permission: binary must not be empty"); + + eDynamicPermissionType type = PERMISSION_TYPE_UNKNOWN; + eDynamicPermissionAllowMode mode = PERMISSION_RULE_ALLOW_MODE_UNKNOWN; + + if (typeStr == "screencopy") + type = PERMISSION_TYPE_SCREENCOPY; + else if (typeStr == "cursorpos") + type = PERMISSION_TYPE_CURSOR_POS; + else if (typeStr == "plugin") + type = PERMISSION_TYPE_PLUGIN; + else if (typeStr == "keyboard" || typeStr == "keeb") + type = PERMISSION_TYPE_KEYBOARD; + + if (modeStr == "ask") + mode = PERMISSION_RULE_ALLOW_MODE_ASK; + else if (modeStr == "allow") + mode = PERMISSION_RULE_ALLOW_MODE_ALLOW; + else if (modeStr == "deny") + mode = PERMISSION_RULE_ALLOW_MODE_DENY; + + if (type == PERMISSION_TYPE_UNKNOWN) + return Internal::configError(L, "hl.permission: unknown permission type"); + if (mode == PERMISSION_RULE_ALLOW_MODE_UNKNOWN) + return Internal::configError(L, "hl.permission: unknown permission allow mode"); + + if (mgr->isFirstLaunch() && g_pDynamicPermissionManager) + g_pDynamicPermissionManager->addConfigPermissionRule(binary, type, mode); + + return 0; +} + +static int hlWorkspaceRule(lua_State* L) { + auto* self = sc(lua_touserdata(L, lua_upvalueindex(1))); + + if (!lua_istable(L, 1)) { + self->addError("hl.workspace_rule: argument must be a table"); + return 0; + } + + const std::string sourceInfo = Internal::getSourceInfo(L); + + lua_getfield(L, 1, "workspace"); + if (!lua_isstring(L, -1)) { + self->addError(std::format("{}: hl.workspace_rule: 'workspace' field is required and must be a string", sourceInfo)); + lua_pop(L, 1); + return 0; + } + const std::string wsStr = lua_tostring(L, -1); + lua_pop(L, 1); + + bool enabled = true; + lua_getfield(L, 1, "enabled"); + if (lua_isboolean(L, -1)) + enabled = lua_toboolean(L, -1) != 0; + lua_pop(L, 1); + + const auto& [wsId, wsName, isAutoID] = getWorkspaceIDNameFromString(wsStr); + + Config::CWorkspaceRule wsRule; + wsRule.m_workspaceString = wsStr; + wsRule.m_workspaceName = wsName; + wsRule.m_workspaceId = isAutoID ? WORKSPACE_INVALID : wsId; + wsRule.m_enabled = enabled; + + lua_pushnil(L); + while (lua_next(L, 1) != 0) { + if (lua_type(L, -2) != LUA_TSTRING) { + lua_pop(L, 1); + continue; + } + + std::string_view key = lua_tostring(L, -2); + if (key == "workspace" || key == "enabled") { + lua_pop(L, 1); + continue; + } + + if (key == "layout_opts") { + if (!lua_istable(L, -1)) { + self->addError(std::format("{}: hl.workspace_rule: field 'layout_opts' must be a table", sourceInfo)); + lua_pop(L, 1); + continue; + } + + const int optsIdx = lua_gettop(L); + lua_pushnil(L); + while (lua_next(L, optsIdx) != 0) { + if (lua_type(L, -2) != LUA_TSTRING) { + self->addError(std::format("{}: hl.workspace_rule: field 'layout_opts' keys must be strings", sourceInfo)); + lua_pop(L, 1); + continue; + } + + std::string optKey = lua_tostring(L, -2); + std::string optVal; + + if (lua_type(L, -1) == LUA_TBOOLEAN) + optVal = lua_toboolean(L, -1) ? "true" : "false"; + else if (lua_type(L, -1) == LUA_TNUMBER) { + if (lua_isinteger(L, -1)) + optVal = std::to_string(lua_tointeger(L, -1)); + else + optVal = std::to_string(lua_tonumber(L, -1)); + } else if (lua_isstring(L, -1)) + optVal = lua_tostring(L, -1); + else { + self->addError(std::format("{}: hl.workspace_rule: field 'layout_opts.{}' must be string, bool, or number", sourceInfo, optKey)); + lua_pop(L, 1); + continue; + } + + wsRule.m_layoutopts[std::move(optKey)] = std::move(optVal); + lua_pop(L, 1); + } + + lua_pop(L, 1); + continue; + } + + const auto* desc = Internal::findDescByName(WORKSPACE_RULE_FIELDS, key); + if (!desc) { + self->addError(std::format("{}: hl.workspace_rule: unknown field '{}'", sourceInfo, key)); + lua_pop(L, 1); + continue; + } + + auto val = UP(desc->factory()); + auto err = val->parse(L); + if (err.errorCode != PARSE_ERROR_OK) + self->addError(std::format("{}: hl.workspace_rule: field '{}': {}", sourceInfo, key, err.message)); + else + desc->apply(val.get(), wsRule); + + lua_pop(L, 1); + } + + Config::workspaceRuleMgr()->replaceOrAdd(std::move(wsRule)); + + Supplementary::refresher()->scheduleRefresh(Supplementary::REFRESH_MONITOR_STATES | Config::Supplementary::REFRESH_WINDOW_STATES); + + return 0; +} + +static int hlGesture(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.gesture: expected a table, e.g. { fingers = 3, direction = \"horizontal\", action = \"workspace\" }"); + + CLuaConfigInt fingersParser(0, 2, 9); + auto fingersErr = Internal::parseTableField(L, 1, "fingers", fingersParser); + if (fingersErr.errorCode != PARSE_ERROR_OK) + return Internal::configError(L, std::format("hl.gesture: {}", fingersErr.message)); + + size_t fingerCount = fingersParser.parsed(); + + CLuaConfigString dirParser(""); + auto dirErr = Internal::parseTableField(L, 1, "direction", dirParser); + if (dirErr.errorCode != PARSE_ERROR_OK) + return Internal::configError(L, std::format("hl.gesture: {}", dirErr.message)); + + const auto direction = g_pTrackpadGestures->dirForString(dirParser.parsed()); + if (direction == TRACKPAD_GESTURE_DIR_NONE) + return Internal::configError(L, std::format("hl.gesture: invalid direction \"{}\"", dirParser.parsed())); + + int functionRef = LUA_NOREF; + + { + // check if the action arg is a lua fn, that's fine + // we can ref that fucker and call him later + lua_getfield(L, 1, "action"); + + if (lua_isfunction(L, -1)) { + lua_pushvalue(L, -1); + functionRef = luaL_ref(L, LUA_REGISTRYINDEX); + Lua::mgr()->registerLuaRef(functionRef); + } + + lua_pop(L, 1); + } + + // bitch ass macro because it's kinda long to get these things and it's ugly +#define GET_ACTION_STRING(var, name) \ + std::string var; \ + lua_getfield(L, 1, name); \ + if (!lua_isnil(L, -1)) { \ + CLuaConfigString argParser(""); \ + auto argErr = argParser.parse(L); \ + if (argErr.errorCode != PARSE_ERROR_OK) { \ + lua_pop(L, 1); \ + return Internal::configError(L, std::format("hl.gesture: field \"" name "\": {}", argErr.message)); \ + } \ + var = argParser.parsed(); \ + } \ + lua_pop(L, 1); + + GET_ACTION_STRING(zoomLevel, "zoom_level"); + GET_ACTION_STRING(workspaceName, "workspace_name"); + GET_ACTION_STRING(mode, "mode"); + +#undef GET_ACTION_STRING + + uint32_t modMask = 0; + lua_getfield(L, 1, "mods"); + if (!lua_isnil(L, -1)) { + CLuaConfigString modsParser(""); + auto modsErr = modsParser.parse(L); + if (modsErr.errorCode != PARSE_ERROR_OK) { + lua_pop(L, 1); + return Internal::configError(L, std::format("hl.gesture: field \"mods\": {}", modsErr.message)); + } + modMask = g_pKeybindManager->stringToModMask(modsParser.parsed()); + } + lua_pop(L, 1); + + float deltaScale = 1.F; + lua_getfield(L, 1, "scale"); + if (!lua_isnil(L, -1)) { + CLuaConfigFloat scaleParser(1.F, 0.1F, 10.F); + auto scaleErr = scaleParser.parse(L); + if (scaleErr.errorCode != PARSE_ERROR_OK) { + lua_pop(L, 1); + return Internal::configError(L, std::format("hl.gesture: field \"scale\": {}", scaleErr.message)); + } + deltaScale = scaleParser.parsed(); + } + lua_pop(L, 1); + + bool disableInhibit = false; + lua_getfield(L, 1, "disable_inhibit"); + if (!lua_isnil(L, -1)) { + CLuaConfigBool disableInhibitParser(false); + auto disableInhibitErr = disableInhibitParser.parse(L); + if (disableInhibitErr.errorCode != PARSE_ERROR_OK) { + lua_pop(L, 1); + return Internal::configError(L, std::format("hl.gesture: field \"disable_inhibit\": {}", disableInhibitErr.message)); + } + disableInhibit = disableInhibitParser.parsed(); + } + lua_pop(L, 1); + + std::expected result; + + if (functionRef != LUA_NOREF) { + // this is a lua fn gesture + result = g_pTrackpadGestures->addGesture(makeUnique(functionRef), fingerCount, direction, modMask, deltaScale, disableInhibit); + } else { + CLuaConfigString actionParser(""); + auto actionErr = Internal::parseTableField(L, 1, "action", actionParser); + if (actionErr.errorCode != PARSE_ERROR_OK) + return Internal::configError(L, std::format("hl.gesture: {}", actionErr.message)); + + const auto& action = actionParser.parsed(); + + if (action == "workspace") + result = g_pTrackpadGestures->addGesture(makeUnique(), fingerCount, direction, modMask, deltaScale, disableInhibit); + else if (action == "resize") + result = g_pTrackpadGestures->addGesture(makeUnique(), fingerCount, direction, modMask, deltaScale, disableInhibit); + else if (action == "move") + result = g_pTrackpadGestures->addGesture(makeUnique(), fingerCount, direction, modMask, deltaScale, disableInhibit); + else if (action == "special") + result = g_pTrackpadGestures->addGesture(makeUnique(workspaceName), fingerCount, direction, modMask, deltaScale, disableInhibit); + else if (action == "close") + result = g_pTrackpadGestures->addGesture(makeUnique(), fingerCount, direction, modMask, deltaScale, disableInhibit); + else if (action == "float") + result = g_pTrackpadGestures->addGesture(makeUnique(mode), fingerCount, direction, modMask, deltaScale, disableInhibit); + else if (action == "fullscreen") + result = g_pTrackpadGestures->addGesture(makeUnique(mode), fingerCount, direction, modMask, deltaScale, disableInhibit); + else if (action == "cursorZoom") + result = g_pTrackpadGestures->addGesture(makeUnique(zoomLevel, mode), fingerCount, direction, modMask, deltaScale, disableInhibit); + else if (action == "unset") + result = g_pTrackpadGestures->removeGesture(fingerCount, direction, modMask, deltaScale, disableInhibit); + else + return Internal::configError(L, std::format("hl.gesture: unknown action \"{}\"", action)); + } + + if (!result) + return Internal::configError(L, std::format("hl.gesture: {}", result.error())); + + return 0; +} + +static int hlConfig(lua_State* L) { + auto* self = sc(lua_touserdata(L, lua_upvalueindex(1))); + + if (!lua_istable(L, 1)) { + self->addError("hl.config: argument must be a table"); + return 0; + } + + const std::string sourceInfo = Internal::getSourceInfo(L); + + std::function walk = [&](const std::string& prefix, int tableIdx) { + lua_pushnil(L); + while (lua_next(L, tableIdx) != 0) { + if (lua_type(L, -2) != LUA_TSTRING) { + lua_pop(L, 1); + continue; + } + + const std::string key = lua_tostring(L, -2); + std::string fullKey; + if (!prefix.empty()) { + fullKey.reserve(prefix.size() + 1 + key.size()); + fullKey = prefix; + fullKey += '.'; + } + fullKey += key; + + auto it = self->m_configValues.find(fullKey); + + if (it == self->m_configValues.end() && lua_istable(L, -1)) + walk(fullKey, lua_gettop(L)); + else { + if (it == self->m_configValues.end()) + self->addError(std::format("{}: unknown config key '{}'", sourceInfo, fullKey)); + else { + const auto err = it->second->parse(L); + if (err.errorCode != PARSE_ERROR_OK) + self->addError(std::format("{}: error setting '{}': {}", sourceInfo, it->first, err.message)); + else if (self->isDynamicParse()) + Supplementary::refresher()->scheduleRefresh(it->second->refreshBits()); + } + } + + lua_pop(L, 1); + } + }; + + walk("", 1); + return 0; +} + +static int hlGetConfig(lua_State* L) { + auto* self = sc(lua_touserdata(L, lua_upvalueindex(1))); + + std::string key = luaL_checkstring(L, 1); + + auto it = self->m_configValues.find(key); + if (it == self->m_configValues.end()) { + std::ranges::replace(key, ':', '.'); + it = self->m_configValues.find(key); + } + + if (it == self->m_configValues.end()) { + lua_pushnil(L); + const auto msg = std::format("unknown config key '{}'", key); + lua_pushstring(L, msg.c_str()); + return 2; + } + + it->second->push(L); + return 1; +} + +static int hlDevice(lua_State* L) { + auto* self = sc(lua_touserdata(L, lua_upvalueindex(1))); + + if (!lua_istable(L, 1)) { + self->addError("hl.device: argument must be a table"); + return 0; + } + + const std::string sourceInfo = Internal::getSourceInfo(L); + + lua_getfield(L, 1, "name"); + if (!lua_isstring(L, -1)) { + self->addError(std::format("{}: hl.device: 'name' field is required and must be a string", sourceInfo)); + lua_pop(L, 1); + return 0; + } + std::string devName = lua_tostring(L, -1); + lua_pop(L, 1); + std::ranges::replace(devName, ' ', '-'); + + lua_pushnil(L); + while (lua_next(L, 1) != 0) { + if (lua_type(L, -2) != LUA_TSTRING) { + lua_pop(L, 1); + continue; + } + + const char* key = lua_tostring(L, -2); + + if (std::string_view{key} == "name") { + lua_pop(L, 1); + continue; + } + + const auto* desc = Internal::findDescByName(DEVICE_FIELDS, key); + + if (!desc) { + self->addError(std::format("{}: hl.device: unknown field '{}'", sourceInfo, key)); + lua_pop(L, 1); + continue; + } + + auto val = UP(desc->factory()); + auto err = val->parse(L); + if (err.errorCode != PARSE_ERROR_OK) + self->addError(std::format("{}: hl.device: field '{}': {}", sourceInfo, key, err.message)); + else + self->m_deviceConfigs[devName].values.insert_or_assign(key, std::move(val)); + + lua_pop(L, 1); + } + + Supplementary::refresher()->scheduleRefresh(Supplementary::REFRESH_INPUT_DEVICES); + + return 0; +} + +static int hlMonitor(lua_State* L) { + auto* self = sc(lua_touserdata(L, lua_upvalueindex(1))); + + if (!lua_istable(L, 1)) { + self->addError("hl.monitor: argument must be a table"); + return 0; + } + + const std::string sourceInfo = Internal::getSourceInfo(L); + + lua_getfield(L, 1, "output"); + if (!lua_isstring(L, -1)) { + self->addError(std::format("{}: hl.monitor: 'output' field is required and must be a string", sourceInfo)); + lua_pop(L, 1); + return 0; + } + const std::string output = lua_tostring(L, -1); + lua_pop(L, 1); + + CMonitorRuleParser parser(output); + + const auto existing = std::ranges::find_if(Config::monitorRuleMgr()->all(), [&output](const auto& rule) { return rule.m_name == output; }); + if (existing != Config::monitorRuleMgr()->all().end()) + parser.rule() = *existing; + + lua_pushnil(L); + while (lua_next(L, 1) != 0) { + if (lua_type(L, -2) != LUA_TSTRING) { + lua_pop(L, 1); + continue; + } + + const char* key = lua_tostring(L, -2); + + if (std::string_view{key} == "output") { + lua_pop(L, 1); + continue; + } + + const auto* desc = Internal::findDescByName(MONITOR_FIELDS, key); + + if (!desc) { + self->addError(std::format("{}: hl.monitor: unknown field '{}'", sourceInfo, key)); + lua_pop(L, 1); + continue; + } + + auto val = UP(desc->factory()); + auto err = val->parse(L); + if (err.errorCode != PARSE_ERROR_OK) + self->addError(std::format("{}: hl.monitor: field '{}': {}", sourceInfo, key, err.message)); + else if (!desc->apply(val.get(), parser)) + self->addError(std::format("{}: hl.monitor: error applying field '{}'", sourceInfo, key)); + + lua_pop(L, 1); + } + + Config::monitorRuleMgr()->add(std::move(parser.rule())); + + Supplementary::refresher()->scheduleRefresh(Supplementary::REFRESH_MONITOR_STATES); + + return 0; +} + +static int hlWindowRule(lua_State* L) { + auto* self = sc(lua_touserdata(L, lua_upvalueindex(1))); + + if (!lua_istable(L, 1)) { + self->addError("hl.window_rule: argument must be a table"); + return 0; + } + + const std::string sourceInfo = Internal::getSourceInfo(L); + + std::string name; + lua_getfield(L, 1, "name"); + if (lua_isstring(L, -1)) + name = lua_tostring(L, -1); + lua_pop(L, 1); + + bool enabled = true; + lua_getfield(L, 1, "enabled"); + if (lua_isboolean(L, -1)) + enabled = lua_toboolean(L, -1) != 0; + lua_pop(L, 1); + + SP rule; + if (!name.empty() && self->m_luaWindowRules.contains(name)) { + rule = self->m_luaWindowRules[name]; + } else { + rule = makeShared(name); + if (!name.empty()) + self->m_luaWindowRules[name] = rule; + Desktop::Rule::ruleEngine()->registerRule(SP(rule)); + } + rule->setEnabled(enabled); + + lua_getfield(L, 1, "match"); + if (lua_istable(L, -1)) { + int matchIdx = lua_gettop(L); + lua_pushnil(L); + while (lua_next(L, matchIdx) != 0) { + if (lua_type(L, -2) == LUA_TSTRING) { + std::string matchKey = lua_tostring(L, -2); + std::string matchVal; + if (lua_type(L, -1) == LUA_TBOOLEAN) + matchVal = lua_toboolean(L, -1) ? "true" : "false"; + else if (lua_type(L, -1) == LUA_TNUMBER) + matchVal = std::to_string(lua_tointeger(L, -1)); + else if (lua_isstring(L, -1)) + matchVal = lua_tostring(L, -1); + else { + self->addError(std::format("{}: hl.window_rule: match value for '{}' must be string, bool, or number", sourceInfo, matchKey)); + lua_pop(L, 1); + continue; + } + auto prop = Desktop::Rule::matchPropFromString(matchKey); + if (prop.has_value()) + rule->registerMatch(*prop, matchVal); + else + self->addError(std::format("{}: hl.window_rule: unknown match property '{}'", sourceInfo, matchKey)); + } + lua_pop(L, 1); + } + } + lua_pop(L, 1); + + lua_pushnil(L); + while (lua_next(L, 1) != 0) { + if (lua_type(L, -2) != LUA_TSTRING) { + lua_pop(L, 1); + continue; + } + std::string_view key = lua_tostring(L, -2); + if (key == "name" || key == "enabled" || key == "match") { + lua_pop(L, 1); + continue; + } + + const auto* desc = Internal::findDescByName(Internal::WINDOW_RULE_EFFECT_DESCS, key); + if (!desc) { + const auto dynamicEffect = Desktop::Rule::windowEffects()->get(key); + if (!dynamicEffect.has_value()) { + self->addError(std::format("{}: hl.window_rule: unknown field '{}'", sourceInfo, key)); + lua_pop(L, 1); + continue; + } + + auto val = Internal::ruleValueToString(L); + if (!val) + self->addError(std::format("{}: hl.window_rule: field '{}': {}", sourceInfo, key, val.error())); + else + rule->addEffect(*dynamicEffect, *val); + + lua_pop(L, 1); + continue; + } + + auto val = UP(desc->factory()); + auto err = val->parse(L); + if (err.errorCode != PARSE_ERROR_OK) { + const bool allowLegacyString = (key == "max_size" || key == "min_size" || key == "border_color") && lua_isstring(L, -1); + if (allowLegacyString) + rule->addEffect(desc->effect, lua_tostring(L, -1)); + else + self->addError(std::format("{}: hl.window_rule: field '{}': {}", sourceInfo, key, err.message)); + } else + rule->addEffect(desc->effect, val->toString()); + + lua_pop(L, 1); + } + + Supplementary::refresher()->scheduleRefresh(Supplementary::REFRESH_WINDOW_STATES); + + Objects::CLuaWindowRule::push(L, rule); + return 1; +} + +static int hlLayerRule(lua_State* L) { + auto* self = sc(lua_touserdata(L, lua_upvalueindex(1))); + + if (!lua_istable(L, 1)) { + self->addError("hl.layer_rule: argument must be a table"); + return 0; + } + + const std::string sourceInfo = Internal::getSourceInfo(L); + + std::string name; + lua_getfield(L, 1, "name"); + if (lua_isstring(L, -1)) + name = lua_tostring(L, -1); + lua_pop(L, 1); + + bool enabled = true; + lua_getfield(L, 1, "enabled"); + if (lua_isboolean(L, -1)) + enabled = lua_toboolean(L, -1) != 0; + lua_pop(L, 1); + + SP rule; + if (!name.empty() && self->m_luaLayerRules.contains(name)) { + rule = self->m_luaLayerRules[name]; + } else { + rule = makeShared(name); + if (!name.empty()) + self->m_luaLayerRules[name] = rule; + Desktop::Rule::ruleEngine()->registerRule(SP(rule)); + } + rule->setEnabled(enabled); + + lua_getfield(L, 1, "match"); + if (lua_istable(L, -1)) { + int matchIdx = lua_gettop(L); + lua_pushnil(L); + while (lua_next(L, matchIdx) != 0) { + if (lua_type(L, -2) == LUA_TSTRING) { + std::string matchKey = lua_tostring(L, -2); + std::string matchVal; + if (lua_type(L, -1) == LUA_TBOOLEAN) + matchVal = lua_toboolean(L, -1) ? "true" : "false"; + else if (lua_isstring(L, -1)) + matchVal = lua_tostring(L, -1); + else { + self->addError(std::format("{}: hl.layer_rule: match value for '{}' must be string or bool", sourceInfo, matchKey)); + lua_pop(L, 1); + continue; + } + auto prop = Desktop::Rule::matchPropFromString(matchKey); + if (prop.has_value()) + rule->registerMatch(*prop, matchVal); + else + self->addError(std::format("{}: hl.layer_rule: unknown match property '{}'", sourceInfo, matchKey)); + } + lua_pop(L, 1); + } + } + lua_pop(L, 1); + + lua_pushnil(L); + while (lua_next(L, 1) != 0) { + if (lua_type(L, -2) != LUA_TSTRING) { + lua_pop(L, 1); + continue; + } + std::string_view key = lua_tostring(L, -2); + if (key == "name" || key == "enabled" || key == "match") { + lua_pop(L, 1); + continue; + } + + const auto* desc = Internal::findDescByName(LAYER_RULE_EFFECT_DESCS, key); + if (!desc) { + const auto dynamicEffect = Desktop::Rule::layerEffects()->get(key); + if (!dynamicEffect.has_value()) { + self->addError(std::format("{}: hl.layer_rule: unknown field '{}'", sourceInfo, key)); + lua_pop(L, 1); + continue; + } + + auto val = Internal::ruleValueToString(L); + if (!val) + self->addError(std::format("{}: hl.layer_rule: field '{}': {}", sourceInfo, key, val.error())); + else + rule->addEffect(*dynamicEffect, *val); + + lua_pop(L, 1); + continue; + } + + auto val = UP(desc->factory()); + auto err = val->parse(L); + if (err.errorCode != PARSE_ERROR_OK) + self->addError(std::format("{}: hl.layer_rule: field '{}': {}", sourceInfo, key, err.message)); + else { + auto str = val->toString(); + rule->addEffect(desc->effect, str); + } + + lua_pop(L, 1); + } + + Supplementary::refresher()->scheduleRefresh(Supplementary::REFRESH_RULES); + + Objects::CLuaLayerRule::push(L, rule); + return 1; +} + +void Internal::registerConfigRuleBindings(lua_State* L, CConfigManager* mgr) { + Internal::setMgrFn(L, mgr, "config", hlConfig); + Internal::setMgrFn(L, mgr, "get_config", hlGetConfig); + Internal::setMgrFn(L, mgr, "device", hlDevice); + Internal::setMgrFn(L, mgr, "monitor", hlMonitor); + Internal::setMgrFn(L, mgr, "window_rule", hlWindowRule); + Internal::setMgrFn(L, mgr, "layer_rule", hlLayerRule); + Internal::setMgrFn(L, mgr, "workspace_rule", hlWorkspaceRule); + Internal::setMgrFn(L, mgr, "env", hlEnv); + Internal::setMgrFn(L, mgr, "permission", hlPermission); + + lua_newtable(L); + Internal::setMgrFn(L, mgr, "load", hlPluginLoad); + lua_setfield(L, -2, "plugin"); + + Internal::setFn(L, "gesture", hlGesture); + Internal::setFn(L, "curve", hlCurve); + Internal::setFn(L, "animation", hlAnimation); +} diff --git a/src/config/lua/bindings/LuaBindingsDispatchers.cpp b/src/config/lua/bindings/LuaBindingsDispatchers.cpp new file mode 100644 index 00000000..61270f9c --- /dev/null +++ b/src/config/lua/bindings/LuaBindingsDispatchers.cpp @@ -0,0 +1,1324 @@ +#include "LuaBindingsInternal.hpp" + +#include + +#include "../../supplementary/executor/Executor.hpp" + +#include "../../../managers/SeatManager.hpp" +#include "../../../devices/IKeyboard.hpp" +#include "../../../desktop/rule/windowRule/WindowRule.hpp" + +using namespace Config; +using namespace Config::Lua; +using namespace Config::Lua::Bindings; +using namespace Hyprutils::String; + +namespace CA = Config::Actions; + +static int dsp_moveCursorToCorner(lua_State* L) { + Internal::checkResult(L, CA::moveCursorToCorner((int)lua_tonumber(L, lua_upvalueindex(1)), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_moveCursor(lua_State* L) { + Internal::checkResult(L, CA::moveCursor(Vector2D{lua_tonumber(L, lua_upvalueindex(1)), lua_tonumber(L, lua_upvalueindex(2))})); + return 0; +} + +static int dsp_toggleGroup(lua_State* L) { + Internal::checkResult(L, CA::toggleGroup(Internal::windowFromUpval(L, 1))); + return 0; +} + +static int dsp_changeGroupActive(lua_State* L) { + Internal::checkResult(L, CA::changeGroupActive(lua_toboolean(L, lua_upvalueindex(1)), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_setGroupActive(lua_State* L) { + Internal::checkResult(L, CA::setGroupActive((int)lua_tonumber(L, lua_upvalueindex(1)), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_moveGroupWindow(lua_State* L) { + Internal::checkResult(L, CA::moveGroupWindow(lua_toboolean(L, lua_upvalueindex(1)))); + return 0; +} + +static int dsp_lockGroups(lua_State* L) { + Internal::checkResult(L, CA::lockGroups(sc((int)lua_tonumber(L, lua_upvalueindex(1))))); + return 0; +} + +static int dsp_lockActiveGroup(lua_State* L) { + Internal::checkResult(L, CA::lockActiveGroup(sc((int)lua_tonumber(L, lua_upvalueindex(1))))); + return 0; +} + +static int hlCursorMoveToCorner(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.cursor.move_to_corner: expected a table { corner, window? }"); + + lua_pushnumber(L, Internal::requireTableFieldNum(L, 1, "corner", "hl.cursor.move_to_corner")); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_moveCursorToCorner, 2); + return 1; +} + +static int hlCursorMove(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.cursor.move: expected a table { x, y }"); + + lua_pushnumber(L, Internal::requireTableFieldNum(L, 1, "x", "hl.cursor.move")); + lua_pushnumber(L, Internal::requireTableFieldNum(L, 1, "y", "hl.cursor.move")); + lua_pushcclosure(L, dsp_moveCursor, 2); + return 1; +} + +static int hlGroupToggle(lua_State* L) { + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_toggleGroup, 1); + return 1; +} + +static int hlGroupNext(lua_State* L) { + lua_pushboolean(L, true); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_changeGroupActive, 2); + return 1; +} + +static int hlGroupPrev(lua_State* L) { + lua_pushboolean(L, false); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_changeGroupActive, 2); + return 1; +} + +static int hlGroupMoveWindow(lua_State* L) { + bool forward = true; + if (lua_istable(L, 1)) { + auto f = Internal::tableOptBool(L, 1, "forward"); + if (f) + forward = *f; + } + lua_pushboolean(L, forward); + lua_pushcclosure(L, dsp_moveGroupWindow, 1); + return 1; +} + +static int hlGroupActive(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.group.active: expected a table { index, window? }"); + + lua_pushnumber(L, Internal::requireTableFieldNum(L, 1, "index", "hl.group.active")); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_setGroupActive, 2); + return 1; +} + +static int hlGroupLock(lua_State* L) { + const auto action = Internal::tableToggleAction(L, 1); + + lua_pushnumber(L, (int)action); + lua_pushcclosure(L, dsp_lockGroups, 1); + return 1; +} + +static int hlGroupLockActive(lua_State* L) { + const auto action = Internal::tableToggleAction(L, 1); + + lua_pushnumber(L, (int)action); + lua_pushcclosure(L, dsp_lockActiveGroup, 1); + return 1; +} + +static int dsp_execCmd(lua_State* L) { + auto proc = lua_tostring(L, lua_upvalueindex(1)); + + if (std::string_view{proc}.empty()) + return Internal::configError(L, "Invalid process string"); + + std::optional pid; + auto ruleRet = Internal::buildRuleFromTable(L, lua_upvalueindex(2)); + + if (!ruleRet) + return ruleRet.error(); + + if (*ruleRet) + pid = Config::Supplementary::executor()->spawn(Config::Supplementary::SExecRequest{.exec = proc, .rule = std::move(*ruleRet)}); + else + pid = Config::Supplementary::executor()->spawn(proc); + + if (!pid.has_value()) + return Internal::configError(L, "Failed to start process"); + return 0; +} + +static int dsp_execRaw(lua_State* L) { + auto proc = Config::Supplementary::executor()->spawnRaw(lua_tostring(L, lua_upvalueindex(1))); + if (!proc || !*proc) + return Internal::configError(L, "Failed to start process"); + return 0; +} + +static int dsp_exit(lua_State* L) { + Internal::checkResult(L, CA::exit()); + return 0; +} + +static int dsp_submap(lua_State* L) { + Internal::checkResult(L, CA::setSubmap(lua_tostring(L, lua_upvalueindex(1)))); + return 0; +} + +static int dsp_pass(lua_State* L) { + const auto PWINDOW = g_pCompositor->getWindowByRegex(lua_tostring(L, lua_upvalueindex(1))); + if (!PWINDOW) + return Internal::configError(L, "hl.pass: window not found"); + Internal::checkResult(L, CA::pass(PWINDOW)); + return 0; +} + +static int dsp_layoutMsg(lua_State* L) { + Internal::checkResult(L, CA::layoutMessage(lua_tostring(L, lua_upvalueindex(1)))); + return 0; +} + +static int dsp_dpms(lua_State* L) { + auto action = sc((int)lua_tonumber(L, lua_upvalueindex(1))); + std::optional mon = std::nullopt; + + if (!lua_isnil(L, lua_upvalueindex(2))) { + auto m = g_pCompositor->getMonitorFromString(lua_tostring(L, lua_upvalueindex(2))); + if (m) + mon = m; + } + + Internal::checkResult(L, CA::dpms(action, mon)); + return 0; +} + +static int dsp_event(lua_State* L) { + Internal::checkResult(L, CA::event(lua_tostring(L, lua_upvalueindex(1)))); + return 0; +} + +static int dsp_global(lua_State* L) { + Internal::checkResult(L, CA::global(lua_tostring(L, lua_upvalueindex(1)))); + return 0; +} + +static int dsp_forceRendererReload(lua_State* L) { + Internal::checkResult(L, CA::forceRendererReload()); + return 0; +} + +static int dsp_forceIdle(lua_State* L) { + Internal::checkResult(L, CA::forceIdle((float)lua_tonumber(L, lua_upvalueindex(1)))); + return 0; +} + +static int hlExecCmd(lua_State* L) { + const auto proc = luaL_checkstring(L, 1); + const bool hasRuleArg = !lua_isnoneornil(L, 2); + + lua_pushstring(L, proc); + + if (hasRuleArg) + lua_pushvalue(L, 2); + else + lua_pushnil(L); + + lua_pushcclosure(L, dsp_execCmd, 2); + return 1; +} + +static int hlExecRaw(lua_State* L) { + lua_pushstring(L, luaL_checkstring(L, 1)); + lua_pushcclosure(L, dsp_execRaw, 1); + return 1; +} + +static int hlExit(lua_State* L) { + lua_pushcclosure(L, dsp_exit, 0); + return 1; +} + +static int hlSubmap(lua_State* L) { + lua_pushstring(L, luaL_checkstring(L, 1)); + lua_pushcclosure(L, dsp_submap, 1); + return 1; +} + +static int hlPass(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.pass: expected a table { window }"); + + const auto w = Internal::requireTableFieldWindowSelector(L, 1, "window", "hl.pass"); + lua_pushstring(L, w.c_str()); + lua_pushcclosure(L, dsp_pass, 1); + return 1; +} + +static int hlLayout(lua_State* L) { + lua_pushstring(L, luaL_checkstring(L, 1)); + lua_pushcclosure(L, dsp_layoutMsg, 1); + return 1; +} + +static int hlDpms(lua_State* L) { + CA::eTogglableAction action = Internal::tableToggleAction(L, 1); + std::optional monStr; + + if (lua_istable(L, 1)) + monStr = Internal::tableOptMonitorSelector(L, 1, "monitor", "hl.dpms"); + + lua_pushnumber(L, (int)action); + if (monStr) + lua_pushstring(L, monStr->c_str()); + else + lua_pushnil(L); + lua_pushcclosure(L, dsp_dpms, 2); + return 1; +} + +static int hlEvent(lua_State* L) { + lua_pushstring(L, luaL_checkstring(L, 1)); + lua_pushcclosure(L, dsp_event, 1); + return 1; +} + +static int hlGlobal(lua_State* L) { + lua_pushstring(L, luaL_checkstring(L, 1)); + lua_pushcclosure(L, dsp_global, 1); + return 1; +} + +static int hlForceRendererReload(lua_State* L) { + lua_pushcclosure(L, dsp_forceRendererReload, 0); + return 1; +} + +static int hlForceIdle(lua_State* L) { + lua_pushnumber(L, luaL_checknumber(L, 1)); + lua_pushcclosure(L, dsp_forceIdle, 1); + return 1; +} + +static std::expected resolveKeycode(const std::string& key) { + if (isNumber(key) && std::stoi(key) > 9) + return (uint32_t)std::stoi(key); + + if (key.starts_with("code:") && isNumber(key.substr(5))) + return (uint32_t)std::stoi(key.substr(5)); + + if (key.starts_with("mouse:") && isNumber(key.substr(6))) { + uint32_t code = std::stoi(key.substr(6)); + if (code < 272) + return std::unexpected("invalid mouse button"); + return code; + } + + const auto KEYSYM = xkb_keysym_from_name(key.c_str(), XKB_KEYSYM_CASE_INSENSITIVE); + + const auto KB = g_pSeatManager->m_keyboard; + if (!KB) + return std::unexpected("no keyboard"); + + const auto KEYPAIRSTRING = std::format("{}{}", rc(KB.get()), key); + + if (g_pKeybindManager->m_keyToCodeCache.contains(KEYPAIRSTRING)) + return g_pKeybindManager->m_keyToCodeCache[KEYPAIRSTRING]; + + xkb_keymap* km = KB->m_xkbKeymap; + xkb_state* ks = KB->m_xkbState; + xkb_keycode_t keycode_min = xkb_keymap_min_keycode(km); + xkb_keycode_t keycode_max = xkb_keymap_max_keycode(km); + uint32_t keycode = 0; + + for (xkb_keycode_t kc = keycode_min; kc <= keycode_max; ++kc) { + xkb_keysym_t sym = xkb_state_key_get_one_sym(ks, kc); + if (sym == KEYSYM) { + keycode = kc; + g_pKeybindManager->m_keyToCodeCache[KEYPAIRSTRING] = keycode; + } + } + + if (!keycode) + return std::unexpected("key not found"); + + return keycode; +} + +static int dsp_sendShortcut(lua_State* L) { + const uint32_t modMask = g_pKeybindManager->stringToModMask(lua_tostring(L, lua_upvalueindex(1))); + const std::string key = lua_tostring(L, lua_upvalueindex(2)); + + auto keycodeResult = resolveKeycode(key); + if (!keycodeResult) + return Internal::configError(L, "send_shortcut: {}", keycodeResult.error()); + + PHLWINDOW window = nullptr; + if (!lua_isnil(L, lua_upvalueindex(3))) { + window = g_pCompositor->getWindowByRegex(lua_tostring(L, lua_upvalueindex(3))); + if (!window) + return Internal::configError(L, "send_shortcut: window not found"); + } + + Internal::checkResult(L, CA::pass(modMask, *keycodeResult, window)); + return 0; +} + +static int dsp_sendKeyState(lua_State* L) { + const uint32_t modMask = g_pKeybindManager->stringToModMask(lua_tostring(L, lua_upvalueindex(1))); + const std::string key = lua_tostring(L, lua_upvalueindex(2)); + const uint32_t keyState = (uint32_t)lua_tonumber(L, lua_upvalueindex(3)); + + auto keycodeResult = resolveKeycode(key); + if (!keycodeResult) + return Internal::configError(L, "send_key_state: {}", keycodeResult.error()); + + PHLWINDOW window = nullptr; + if (!lua_isnil(L, lua_upvalueindex(4))) { + window = g_pCompositor->getWindowByRegex(lua_tostring(L, lua_upvalueindex(4))); + if (!window) + return Internal::configError(L, "send_key_state: window not found"); + } + + Internal::checkResult(L, CA::sendKeyState(modMask, *keycodeResult, keyState, window)); + return 0; +} + +static int hlSendShortcut(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "send_shortcut: expected a table { mods, key, window? }"); + + const auto mods = Internal::requireTableFieldStr(L, 1, "mods", "hl.send_shortcut"); + const auto key = Internal::requireTableFieldStr(L, 1, "key", "hl.send_shortcut"); + + lua_pushstring(L, mods.c_str()); + lua_pushstring(L, key.c_str()); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_sendShortcut, 3); + return 1; +} + +static int hlSendKeyState(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "send_key_state: expected a table { mods, key, state, window? }"); + + const auto mods = Internal::requireTableFieldStr(L, 1, "mods", "hl.send_key_state"); + const auto key = Internal::requireTableFieldStr(L, 1, "key", "hl.send_key_state"); + const auto stateStr = Internal::requireTableFieldStr(L, 1, "state", "hl.send_key_state"); + + uint32_t keyState = 0; + if (stateStr == "down") + keyState = 1; + else if (stateStr == "repeat") + keyState = 2; + else if (stateStr != "up") + return Internal::configError(L, "send_key_state: 'state' must be \"down\", \"up\", or \"repeat\""); + + lua_pushstring(L, mods.c_str()); + lua_pushstring(L, key.c_str()); + lua_pushnumber(L, keyState); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_sendKeyState, 4); + return 1; +} + +static int dsp_moveToWorkspace(lua_State* L) { + auto ws = Internal::resolveWorkspaceStr(lua_tostring(L, lua_upvalueindex(1))); + if (!ws) + return Internal::configError(L, "Invalid workspace"); + + bool silent = lua_toboolean(L, lua_upvalueindex(2)); + Internal::checkResult(L, CA::moveToWorkspace(ws, silent, Internal::windowFromUpval(L, 3))); + return 0; +} + +static int dsp_moveToMonitor(lua_State* L) { + auto mon = Internal::resolveMonitorStr(lua_tostring(L, lua_upvalueindex(1))); + if (!mon) + return Internal::configError(L, "Invalid monitor / monitor doesn't exist"); + + bool silent = lua_toboolean(L, lua_upvalueindex(2)); + Internal::checkResult(L, CA::moveToWorkspace(mon->m_activeWorkspace, silent, Internal::windowFromUpval(L, 3))); + return 0; +} + +static int dsp_closeWindow(lua_State* L) { + Internal::checkResult(L, CA::closeWindow(Internal::windowFromUpval(L, 1))); + return 0; +} + +static int dsp_killWindow(lua_State* L) { + Internal::checkResult(L, CA::killWindow(Internal::windowFromUpval(L, 1))); + return 0; +} + +static int dsp_signalWindow(lua_State* L) { + Internal::checkResult(L, CA::signalWindow((int)lua_tonumber(L, lua_upvalueindex(1)), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_floatWindow(lua_State* L) { + Internal::checkResult(L, CA::floatWindow(sc((int)lua_tonumber(L, lua_upvalueindex(1))), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_fullscreenWindow(lua_State* L) { + Internal::checkResult(L, CA::fullscreenWindow(sc((int)lua_tonumber(L, lua_upvalueindex(1))), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_fullscreenWindowWithAction(lua_State* L) { + const auto mode = sc((int)lua_tonumber(L, lua_upvalueindex(1))); + const int actionRaw = (int)lua_tonumber(L, lua_upvalueindex(2)); + auto maybeW = Internal::windowFromUpval(L, 3); + + if (actionRaw == 0) { + Internal::checkResult(L, CA::fullscreenWindow(mode, maybeW)); + return 0; + } + + const auto target = maybeW.value_or(Desktop::focusState()->window()); + if (!target) + return Internal::configError(L, "No target found."); + + const bool currentlyMode = target->isEffectiveInternalFSMode(mode); + + if (actionRaw == 1) { + if (!currentlyMode) + Internal::checkResult(L, CA::fullscreenWindow(mode, maybeW)); + return 0; + } + + if (actionRaw == 2) { + if (currentlyMode) + Internal::checkResult(L, CA::fullscreenWindow(mode, maybeW)); + return 0; + } + + return Internal::configError(L, "hl.window.fullscreen: invalid action"); +} + +static int dsp_fullscreenState(lua_State* L) { + const auto desiredInternal = sc((int)lua_tonumber(L, lua_upvalueindex(1))); + const auto desiredClient = sc((int)lua_tonumber(L, lua_upvalueindex(2))); + const int actionRaw = (int)lua_tonumber(L, lua_upvalueindex(3)); // 0: toggle, 1: set, 2: unset + auto maybeW = Internal::windowFromUpval(L, 4); + + const auto target = maybeW.value_or(Desktop::focusState()->window()); + if (!target) + return Internal::configError(L, "No target found."); + + const auto CURRENT = target->m_fullscreenState; + const bool atDesiredState = CURRENT.internal == desiredInternal && CURRENT.client == desiredClient; + + if (actionRaw == 0) { + Internal::checkResult(L, CA::fullscreenWindow(desiredInternal, desiredClient, maybeW)); + return 0; + } + + if (actionRaw == 1) { + if (!atDesiredState) + Internal::checkResult(L, CA::fullscreenWindow(desiredInternal, desiredClient, maybeW)); + return 0; + } + + if (actionRaw == 2) { + if (atDesiredState) + Internal::checkResult(L, CA::fullscreenWindow(desiredInternal, desiredClient, maybeW)); + return 0; + } + + return Internal::configError(L, "hl.window.fullscreen_state: invalid action"); +} + +static int dsp_pseudoWindow(lua_State* L) { + Internal::checkResult(L, CA::pseudoWindow(sc((int)lua_tonumber(L, lua_upvalueindex(1))), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_moveInDirection(lua_State* L) { + Internal::checkResult(L, CA::moveInDirection(sc((int)lua_tonumber(L, lua_upvalueindex(1))), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_swapInDirection(lua_State* L) { + Internal::checkResult(L, CA::swapInDirection(sc((int)lua_tonumber(L, lua_upvalueindex(1))), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_center(lua_State* L) { + Internal::checkResult(L, CA::center(Internal::windowFromUpval(L, 1))); + return 0; +} + +static int dsp_cycleNext(lua_State* L) { + bool next = lua_toboolean(L, lua_upvalueindex(1)); + int tiledRaw = (int)lua_tonumber(L, lua_upvalueindex(2)); + int floatingRaw = (int)lua_tonumber(L, lua_upvalueindex(3)); + std::optional tiled = tiledRaw < 0 ? std::nullopt : std::optional(tiledRaw > 0); + std::optional floating = floatingRaw < 0 ? std::nullopt : std::optional(floatingRaw > 0); + Internal::checkResult(L, CA::cycleNext(next, tiled, floating, Internal::windowFromUpval(L, 4))); + return 0; +} + +static int dsp_swapNext(lua_State* L) { + Internal::checkResult(L, CA::swapNext(lua_toboolean(L, lua_upvalueindex(1)), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_swapWithWindow(lua_State* L) { + auto source = Internal::windowFromUpval(L, 1); + + const auto targetSelector = lua_tostring(L, lua_upvalueindex(2)); + const auto target = g_pCompositor->getWindowByRegex(targetSelector); + if (!target) + return Internal::configError(L, "hl.window.swap: target window not found"); + + Internal::checkResult(L, CA::swapWith(target, source)); + return 0; +} + +static int dsp_tagWindow(lua_State* L) { + Internal::checkResult(L, CA::tag(lua_tostring(L, lua_upvalueindex(1)), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_toggleSwallow(lua_State* L) { + Internal::checkResult(L, CA::toggleSwallow()); + return 0; +} + +static int dsp_resize(lua_State* L) { + Vector2D value{lua_tonumber(L, lua_upvalueindex(1)), lua_tonumber(L, lua_upvalueindex(2))}; + Internal::checkResult(L, CA::resize(value, lua_toboolean(L, lua_upvalueindex(3)), Internal::windowFromUpval(L, 4))); + return 0; +} + +static int dsp_move(lua_State* L) { + Vector2D value{lua_tonumber(L, lua_upvalueindex(1)), lua_tonumber(L, lua_upvalueindex(2))}; + Internal::checkResult(L, CA::move(value, lua_toboolean(L, lua_upvalueindex(3)), Internal::windowFromUpval(L, 4))); + return 0; +} + +static int dsp_pinWindow(lua_State* L) { + Internal::checkResult(L, CA::pinWindow(sc((int)lua_tonumber(L, lua_upvalueindex(1))), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_bringToTop(lua_State* L) { + Internal::checkResult(L, CA::alterZOrder("top")); + return 0; +} + +static int dsp_alterZOrder(lua_State* L) { + Internal::checkResult(L, CA::alterZOrder(lua_tostring(L, lua_upvalueindex(1)), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_setProp(lua_State* L) { + Internal::checkResult(L, CA::setProp(lua_tostring(L, lua_upvalueindex(1)), lua_tostring(L, lua_upvalueindex(2)), Internal::windowFromUpval(L, 3))); + return 0; +} + +static int dsp_moveIntoGroup(lua_State* L) { + Internal::checkResult(L, CA::moveIntoGroup(sc((int)lua_tonumber(L, lua_upvalueindex(1))), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_moveOutOfGroup(lua_State* L) { + Internal::checkResult(L, CA::moveOutOfGroup(sc((int)lua_tonumber(L, lua_upvalueindex(1))), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_moveWindowOrGroup(lua_State* L) { + Internal::checkResult(L, CA::moveWindowOrGroup(sc((int)lua_tonumber(L, lua_upvalueindex(1))), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_moveIntoOrCreateGroup(lua_State* L) { + Internal::checkResult(L, CA::moveIntoOrCreateGroup(sc((int)lua_tonumber(L, lua_upvalueindex(1))), Internal::windowFromUpval(L, 2))); + return 0; +} + +static int dsp_denyFromGroup(lua_State* L) { + Internal::checkResult(L, CA::denyWindowFromGroup(sc((int)lua_tonumber(L, lua_upvalueindex(1))))); + return 0; +} + +static int dsp_mouseDrag(lua_State* L) { + Internal::checkResult(L, CA::mouse("movewindow")); + return 0; +} + +static int dsp_mouseResize(lua_State* L) { + Internal::checkResult(L, CA::mouse("resizewindow")); + return 0; +} + +static int hlWindowClose(lua_State* L) { + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_closeWindow, 1); + return 1; +} + +static int hlWindowKill(lua_State* L) { + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_killWindow, 1); + return 1; +} + +static int hlWindowSignal(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.window.signal: expected a table { signal, window? }"); + + lua_pushnumber(L, Internal::requireTableFieldNum(L, 1, "signal", "hl.window.signal")); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_signalWindow, 2); + return 1; +} + +static int hlWindowFloat(lua_State* L) { + const auto action = Internal::tableToggleAction(L, 1); + + lua_pushnumber(L, (int)action); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_floatWindow, 2); + return 1; +} + +static int hlWindowFullscreen(lua_State* L) { + eFullscreenMode mode = FSMODE_FULLSCREEN; + int action = 0; // 0: toggle, 1: set, 2: unset + if (lua_istable(L, 1)) { + auto m = Internal::tableOptStr(L, 1, "mode"); + if (m) { + if (*m == "maximized" || *m == "1") + mode = FSMODE_MAXIMIZED; + else if (*m == "fullscreen" || *m == "0") + mode = FSMODE_FULLSCREEN; + else + return Internal::configError(L, "hl.window.fullscreen: invalid mode \"{}\" (expected fullscreen/maximized)", *m); + } + + auto a = Internal::tableOptStr(L, 1, "action"); + if (a) { + if (*a == "toggle") + action = 0; + else if (*a == "set") + action = 1; + else if (*a == "unset") + action = 2; + else + return Internal::configError(L, "hl.window.fullscreen: invalid action \"{}\" (expected toggle/set/unset)", *a); + } + } + lua_pushnumber(L, (int)mode); + if (action == 0) { + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_fullscreenWindow, 2); + } else { + lua_pushnumber(L, action); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_fullscreenWindowWithAction, 3); + } + return 1; +} + +static int hlWindowFullscreenState(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.window.fullscreen_state: expected a table { internal, client, action?, window? }"); + + int action = 1; // default to set semantics + if (auto a = Internal::tableOptStr(L, 1, "action"); a) { + if (*a == "toggle") + action = 0; + else if (*a == "set") + action = 1; + else if (*a == "unset") + action = 2; + else + return Internal::configError(L, "hl.window.fullscreen_state: invalid action \"{}\" (expected toggle/set/unset)", *a); + } + + auto im = Internal::tableOptNum(L, 1, "internal"); + auto cm = Internal::tableOptNum(L, 1, "client"); + if (!im || !cm) + return Internal::configError(L, "hl.window.fullscreen_state: 'internal' and 'client' are required"); + + lua_pushnumber(L, (int)*im); + lua_pushnumber(L, (int)*cm); + lua_pushnumber(L, action); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_fullscreenState, 4); + return 1; +} + +static int hlWindowPseudo(lua_State* L) { + const auto action = Internal::tableToggleAction(L, 1); + + lua_pushnumber(L, (int)action); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_pseudoWindow, 2); + return 1; +} + +static int hlWindowMove(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.window.move: expected a table, e.g. { direction = \"left\" }"); + + auto dirStr = Internal::tableOptStr(L, 1, "direction"); + if (dirStr) { + auto dir = Internal::parseDirectionStr(*dirStr); + if (dir == Math::DIRECTION_DEFAULT) + return Internal::configError(L, "hl.window.move: invalid direction \"{}\" (expected left/right/up/down)", *dirStr); + + auto groupAware = Internal::tableOptBool(L, 1, "group_aware"); + if (groupAware && *groupAware) { + lua_pushnumber(L, (int)dir); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_moveWindowOrGroup, 2); + return 1; + } + + lua_pushnumber(L, (int)dir); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_moveInDirection, 2); + return 1; + } + + auto x = Internal::tableOptNum(L, 1, "x"); + auto y = Internal::tableOptNum(L, 1, "y"); + if (x && y) { + bool relative = Internal::tableOptBool(L, 1, "relative").value_or(false); + lua_pushnumber(L, *x); + lua_pushnumber(L, *y); + lua_pushboolean(L, relative); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_move, 4); + return 1; + } + + auto ws = Internal::tableOptWorkspaceSelector(L, 1, "workspace", "hl.window.move"); + if (ws) { + auto follow = Internal::tableOptBool(L, 1, "follow"); + bool silent = follow.has_value() && !*follow; + lua_pushstring(L, ws->c_str()); + lua_pushboolean(L, silent); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_moveToWorkspace, 3); + return 1; + } + + auto mon = Internal::tableOptMonitorSelector(L, 1, "monitor", "hl.window.move"); + if (mon) { + auto follow = Internal::tableOptBool(L, 1, "follow"); + bool silent = follow.has_value() && !*follow; + lua_pushstring(L, mon->c_str()); + lua_pushboolean(L, silent); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_moveToMonitor, 3); + return 1; + } + + auto intoGroup = Internal::tableOptStr(L, 1, "into_group"); + if (intoGroup) { + auto dir = Internal::parseDirectionStr(*intoGroup); + if (dir == Math::DIRECTION_DEFAULT) + return Internal::configError(L, "hl.window.move: invalid into_group direction \"{}\"", *intoGroup); + lua_pushnumber(L, (int)dir); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_moveIntoGroup, 2); + return 1; + } + + auto intoOrCreateGroup = Internal::tableOptStr(L, 1, "into_or_create_group"); + if (intoOrCreateGroup) { + auto dir = Internal::parseDirectionStr(*intoOrCreateGroup); + if (dir == Math::DIRECTION_DEFAULT) + return Internal::configError(L, "hl.window.move: invalid into_or_create_group direction \"{}\"", *intoOrCreateGroup); + lua_pushnumber(L, (int)dir); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_moveIntoOrCreateGroup, 2); + return 1; + } + + auto outOfGroup = Internal::tableOptStr(L, 1, "out_of_group"); + if (outOfGroup) { + auto dir = Internal::parseDirectionStr(*outOfGroup); + lua_pushnumber(L, (int)dir); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_moveOutOfGroup, 2); + return 1; + } + + auto outOfGroupBool = Internal::tableOptBool(L, 1, "out_of_group"); + if (outOfGroupBool && *outOfGroupBool) { + lua_pushnumber(L, (int)Math::DIRECTION_DEFAULT); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_moveOutOfGroup, 2); + return 1; + } + + return Internal::configError(L, "hl.window.move: unrecognized arguments. Expected one of: direction, x+y(+relative), workspace, into_group, out_of_group"); +} + +static int hlWindowSwap(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.window.swap: expected a table, e.g. { direction = \"left\" }"); + + auto dirStr = Internal::tableOptStr(L, 1, "direction"); + if (dirStr) { + auto dir = Internal::parseDirectionStr(*dirStr); + if (dir == Math::DIRECTION_DEFAULT) + return Internal::configError(L, "hl.window.swap: invalid direction \"{}\" (expected left/right/up/down)", *dirStr); + lua_pushnumber(L, (int)dir); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_swapInDirection, 2); + return 1; + } + + auto target = Internal::tableOptWindowSelector(L, 1, "target", "hl.window.swap"); + if (!target) + target = Internal::tableOptWindowSelector(L, 1, "with", "hl.window.swap"); + if (!target) + target = Internal::tableOptWindowSelector(L, 1, "other", "hl.window.swap"); + + if (target) { + Internal::pushWindowUpval(L, 1); + lua_pushstring(L, target->c_str()); + lua_pushcclosure(L, dsp_swapWithWindow, 2); + return 1; + } + + auto next = Internal::tableOptBool(L, 1, "next"); + if (next && *next) { + lua_pushboolean(L, true); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_swapNext, 2); + return 1; + } + + auto prev = Internal::tableOptBool(L, 1, "prev"); + if (prev && *prev) { + lua_pushboolean(L, false); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_swapNext, 2); + return 1; + } + + return Internal::configError(L, "hl.window.swap: unrecognized arguments. Expected one of: direction, target/with/other, next, prev"); +} + +static int hlWindowCenter(lua_State* L) { + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_center, 1); + return 1; +} + +static int hlWindowCycleNext(lua_State* L) { + bool next = true; + int tiled = -1; + int floating = -1; + if (lua_istable(L, 1)) { + auto n = Internal::tableOptBool(L, 1, "next"); + if (n) + next = *n; + auto t = Internal::tableOptBool(L, 1, "tiled"); + if (t) + tiled = *t ? 1 : 0; + auto f = Internal::tableOptBool(L, 1, "floating"); + if (f) + floating = *f ? 1 : 0; + } + lua_pushboolean(L, next); + lua_pushnumber(L, tiled); + lua_pushnumber(L, floating); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_cycleNext, 4); + return 1; +} + +static int hlWindowTag(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.window.tag: expected a table { tag, window? }"); + + const auto tag = Internal::requireTableFieldStr(L, 1, "tag", "hl.window.tag"); + lua_pushstring(L, tag.c_str()); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_tagWindow, 2); + return 1; +} + +static int hlWindowToggleSwallow(lua_State* L) { + lua_pushcclosure(L, dsp_toggleSwallow, 0); + return 1; +} + +static int hlWindowResizeExact(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.window.resize: expected a table { x, y, relative?, window? }"); + auto x = Internal::tableOptNum(L, 1, "x"); + auto y = Internal::tableOptNum(L, 1, "y"); + bool relative = Internal::tableOptBool(L, 1, "relative").value_or(false); + if (!x || !y) + return Internal::configError(L, "hl.window.resize: 'x' and 'y' are required"); + lua_pushnumber(L, *x); + lua_pushnumber(L, *y); + lua_pushboolean(L, relative); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_resize, 4); + return 1; +} + +static int hlWindowPin(lua_State* L) { + const auto action = Internal::tableToggleAction(L, 1); + + lua_pushnumber(L, (int)action); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_pinWindow, 2); + return 1; +} + +static int hlWindowBringToTop(lua_State* L) { + lua_pushcclosure(L, dsp_bringToTop, 0); + return 1; +} + +static int hlWindowAlterZOrder(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.window.alter_zorder: expected a table { mode, window? }"); + + const auto mode = Internal::requireTableFieldStr(L, 1, "mode", "hl.window.alter_zorder"); + lua_pushstring(L, mode.c_str()); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_alterZOrder, 2); + return 1; +} + +static int hlWindowSetProp(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.window.set_prop: expected a table { prop, value, window? }"); + + const auto prop = Internal::requireTableFieldStr(L, 1, "prop", "hl.window.set_prop"); + const auto value = Internal::requireTableFieldStr(L, 1, "value", "hl.window.set_prop"); + lua_pushstring(L, prop.c_str()); + lua_pushstring(L, value.c_str()); + Internal::pushWindowUpval(L, 1); + lua_pushcclosure(L, dsp_setProp, 3); + return 1; +} + +static int hlWindowDenyFromGroup(lua_State* L) { + const auto action = Internal::tableToggleAction(L, 1); + + lua_pushnumber(L, (int)action); + lua_pushcclosure(L, dsp_denyFromGroup, 1); + return 1; +} + +static int hlWindowDrag(lua_State* L) { + lua_pushcclosure(L, dsp_mouseDrag, 0); + return 1; +} + +static int hlWindowResize(lua_State* L) { + if (lua_gettop(L) == 0 || lua_isnil(L, 1)) { + lua_pushcclosure(L, dsp_mouseResize, 0); + return 1; + } + + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.window.resize: expected no args, or a table { x, y, relative?, window? }"); + + return hlWindowResizeExact(L); +} + +static int dsp_moveFocus(lua_State* L) { + Internal::checkResult(L, CA::moveFocus(sc((int)lua_tonumber(L, lua_upvalueindex(1))))); + return 0; +} + +static int dsp_focusMonitor(lua_State* L) { + const auto PMONITOR = g_pCompositor->getMonitorFromString(lua_tostring(L, lua_upvalueindex(1))); + if (!PMONITOR) + return Internal::configError(L, "hl.focus.monitor: monitor not found"); + Internal::checkResult(L, CA::focusMonitor(PMONITOR)); + return 0; +} + +static int dsp_focusWindowBySelector(lua_State* L) { + const auto PWINDOW = g_pCompositor->getWindowByRegex(lua_tostring(L, lua_upvalueindex(1))); + if (!PWINDOW) + return Internal::configError(L, "hl.focus: window not found"); + Internal::checkResult(L, CA::focus(PWINDOW)); + return 0; +} + +static int dsp_focusUrgentOrLast(lua_State* L) { + Internal::checkResult(L, CA::focusUrgentOrLast()); + return 0; +} + +static int dsp_focusCurrentOrLast(lua_State* L) { + Internal::checkResult(L, CA::focusCurrentOrLast()); + return 0; +} + +static int dsp_changeWorkspace(lua_State* L) { + Internal::checkResult(L, CA::changeWorkspace(std::string(lua_tostring(L, lua_upvalueindex(1))))); + return 0; +} + +static int dsp_focusWorkspaceOnCurrentMonitor(lua_State* L) { + auto ws = Internal::resolveWorkspaceStr(lua_tostring(L, lua_upvalueindex(1))); + if (!ws) + return Internal::configError(L, "Invalid workspace"); + Internal::checkResult(L, CA::changeWorkspaceOnCurrentMonitor(ws)); + return 0; +} + +static int hlFocus(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.focus: expected a table, e.g. { direction = \"left\" }"); + + auto dirStr = Internal::tableOptStr(L, 1, "direction"); + if (dirStr) { + auto dir = Internal::parseDirectionStr(*dirStr); + if (dir == Math::DIRECTION_DEFAULT) + return Internal::configError(L, "hl.focus: invalid direction \"{}\" (expected left/right/up/down)", *dirStr); + lua_pushnumber(L, (int)dir); + lua_pushcclosure(L, dsp_moveFocus, 1); + return 1; + } + + auto monStr = Internal::tableOptMonitorSelector(L, 1, "monitor", "hl.focus"); + if (monStr) { + lua_pushstring(L, monStr->c_str()); + lua_pushcclosure(L, dsp_focusMonitor, 1); + return 1; + } + + auto wsStr = Internal::tableOptWorkspaceSelector(L, 1, "workspace", "hl.focus"); + if (wsStr) { + auto onCurrentMon = Internal::tableOptBool(L, 1, "on_current_monitor"); + + lua_pushstring(L, wsStr->c_str()); + + if (onCurrentMon.value_or(false)) + lua_pushcclosure(L, dsp_focusWorkspaceOnCurrentMonitor, 1); + else + lua_pushcclosure(L, dsp_changeWorkspace, 1); + + return 1; + } + + auto winStr = Internal::tableOptWindowSelector(L, 1, "window", "hl.focus"); + if (winStr) { + lua_pushstring(L, winStr->c_str()); + lua_pushcclosure(L, dsp_focusWindowBySelector, 1); + return 1; + } + + auto urgent = Internal::tableOptBool(L, 1, "urgent_or_last"); + if (urgent && *urgent) { + lua_pushcclosure(L, dsp_focusUrgentOrLast, 0); + return 1; + } + + auto last = Internal::tableOptBool(L, 1, "last"); + if (last && *last) { + lua_pushcclosure(L, dsp_focusCurrentOrLast, 0); + return 1; + } + + return Internal::configError(L, "hl.focus: unrecognized arguments. Expected one of: direction, monitor, window, urgent_or_last, last"); +} + +static int dsp_toggleSpecial(lua_State* L) { + std::string name = lua_isnil(L, lua_upvalueindex(1)) ? "" : lua_tostring(L, lua_upvalueindex(1)); + const auto& [workspaceID, workspaceName, isAutoID] = getWorkspaceIDNameFromString("special:" + name); + if (workspaceID == WORKSPACE_INVALID || !g_pCompositor->isWorkspaceSpecial(workspaceID)) + return Internal::configError(L, "Invalid special workspace"); + + auto ws = g_pCompositor->getWorkspaceByID(workspaceID); + if (!ws) { + const auto PMONITOR = Desktop::focusState()->monitor(); + if (PMONITOR) + ws = g_pCompositor->createNewWorkspace(workspaceID, PMONITOR->m_id, workspaceName); + } + if (!ws) + return Internal::configError(L, "Could not resolve special workspace"); + + Internal::checkResult(L, CA::toggleSpecial(ws)); + return 0; +} + +static int dsp_renameWorkspace(lua_State* L) { + const auto PWS = g_pCompositor->getWorkspaceByString(lua_tostring(L, lua_upvalueindex(1))); + if (!PWS) + return Internal::configError(L, "hl.workspace.rename: no such workspace"); + std::string name = lua_isnil(L, lua_upvalueindex(2)) ? "" : lua_tostring(L, lua_upvalueindex(2)); + Internal::checkResult(L, CA::renameWorkspace(PWS, name)); + return 0; +} + +static int dsp_moveWorkspaceToMonitor(lua_State* L) { + const auto WORKSPACEID = getWorkspaceIDNameFromString(lua_tostring(L, lua_upvalueindex(1))).id; + if (WORKSPACEID == WORKSPACE_INVALID) + return Internal::configError(L, "Invalid workspace"); + const auto PWORKSPACE = g_pCompositor->getWorkspaceByID(WORKSPACEID); + if (!PWORKSPACE) + return Internal::configError(L, "Workspace not found"); + const auto PMONITOR = g_pCompositor->getMonitorFromString(lua_tostring(L, lua_upvalueindex(2))); + if (!PMONITOR) + return Internal::configError(L, "Monitor not found"); + Internal::checkResult(L, CA::moveToMonitor(PWORKSPACE, PMONITOR)); + return 0; +} + +static int dsp_moveCurrentWorkspaceToMonitor(lua_State* L) { + const auto PMONITOR = g_pCompositor->getMonitorFromString(lua_tostring(L, lua_upvalueindex(1))); + if (!PMONITOR) + return Internal::configError(L, "Monitor not found"); + const auto PCURRENTWORKSPACE = Desktop::focusState()->monitor()->m_activeWorkspace; + if (!PCURRENTWORKSPACE) + return Internal::configError(L, "Invalid workspace"); + Internal::checkResult(L, CA::moveToMonitor(PCURRENTWORKSPACE, PMONITOR)); + return 0; +} + +static int dsp_swapActiveWorkspaces(lua_State* L) { + const auto PMON1 = g_pCompositor->getMonitorFromString(lua_tostring(L, lua_upvalueindex(1))); + const auto PMON2 = g_pCompositor->getMonitorFromString(lua_tostring(L, lua_upvalueindex(2))); + if (!PMON1 || !PMON2) + return Internal::configError(L, "Monitor not found"); + Internal::checkResult(L, CA::swapActiveWorkspaces(PMON1, PMON2)); + return 0; +} + +static int hlWorkspaceToggleSpecial(lua_State* L) { + lua_pushstring(L, lua_tostring(L, 1)); + lua_pushcclosure(L, dsp_toggleSpecial, 1); + return 1; +} + +static int hlWorkspaceRename(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.workspace.rename: expected a table { id, name? }"); + + const auto id = Internal::requireTableFieldWorkspaceSelector(L, 1, "id", "hl.workspace.rename"); + auto name = Internal::tableOptStr(L, 1, "name"); + + lua_pushstring(L, id.c_str()); + if (name) + lua_pushstring(L, name->c_str()); + else + lua_pushnil(L); + lua_pushcclosure(L, dsp_renameWorkspace, 2); + return 1; +} + +static int hlWorkspaceMove(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.workspace.move: expected a table, e.g. { monitor = \"DP-1\" }"); + + const auto mon = Internal::requireTableFieldMonitorSelector(L, 1, "monitor", "hl.workspace.move"); + + auto id = Internal::tableOptWorkspaceSelector(L, 1, "id", "hl.workspace.move"); + if (id) { + lua_pushstring(L, id->c_str()); + lua_pushstring(L, mon.c_str()); + lua_pushcclosure(L, dsp_moveWorkspaceToMonitor, 2); + return 1; + } + + lua_pushstring(L, mon.c_str()); + lua_pushcclosure(L, dsp_moveCurrentWorkspaceToMonitor, 1); + return 1; +} + +static int hlWorkspaceSwapMonitors(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.workspace.swap_monitors: expected a table { monitor1, monitor2 }"); + + const auto m1 = Internal::requireTableFieldMonitorSelector(L, 1, "monitor1", "hl.workspace.swap_monitors"); + const auto m2 = Internal::requireTableFieldMonitorSelector(L, 1, "monitor2", "hl.workspace.swap_monitors"); + lua_pushstring(L, m1.c_str()); + lua_pushstring(L, m2.c_str()); + lua_pushcclosure(L, dsp_swapActiveWorkspaces, 2); + return 1; +} + +void Internal::registerDispatcherBindings(lua_State* L) { + lua_newtable(L); + + { + lua_newtable(L); + Internal::setFn(L, "move_to_corner", hlCursorMoveToCorner); + Internal::setFn(L, "move", hlCursorMove); + lua_setfield(L, -2, "cursor"); + + lua_newtable(L); + Internal::setFn(L, "toggle", hlGroupToggle); + Internal::setFn(L, "next", hlGroupNext); + Internal::setFn(L, "prev", hlGroupPrev); + Internal::setFn(L, "active", hlGroupActive); + Internal::setFn(L, "move_window", hlGroupMoveWindow); + Internal::setFn(L, "lock", hlGroupLock); + Internal::setFn(L, "lock_active", hlGroupLockActive); + lua_setfield(L, -2, "group"); + + lua_newtable(L); + Internal::setFn(L, "close", hlWindowClose); + Internal::setFn(L, "kill", hlWindowKill); + Internal::setFn(L, "signal", hlWindowSignal); + Internal::setFn(L, "float", hlWindowFloat); + Internal::setFn(L, "fullscreen", hlWindowFullscreen); + Internal::setFn(L, "fullscreen_state", hlWindowFullscreenState); + Internal::setFn(L, "pseudo", hlWindowPseudo); + Internal::setFn(L, "move", hlWindowMove); + Internal::setFn(L, "swap", hlWindowSwap); + Internal::setFn(L, "center", hlWindowCenter); + Internal::setFn(L, "cycle_next", hlWindowCycleNext); + Internal::setFn(L, "tag", hlWindowTag); + Internal::setFn(L, "toggle_swallow", hlWindowToggleSwallow); + Internal::setFn(L, "pin", hlWindowPin); + Internal::setFn(L, "bring_to_top", hlWindowBringToTop); + Internal::setFn(L, "alter_zorder", hlWindowAlterZOrder); + Internal::setFn(L, "set_prop", hlWindowSetProp); + Internal::setFn(L, "deny_from_group", hlWindowDenyFromGroup); + Internal::setFn(L, "drag", hlWindowDrag); + Internal::setFn(L, "resize", hlWindowResize); + lua_setfield(L, -2, "window"); + + lua_newtable(L); + Internal::setFn(L, "rename", hlWorkspaceRename); + Internal::setFn(L, "move", hlWorkspaceMove); + Internal::setFn(L, "swap_monitors", hlWorkspaceSwapMonitors); + Internal::setFn(L, "toggle_special", hlWorkspaceToggleSpecial); + lua_setfield(L, -2, "workspace"); + + Internal::setFn(L, "exec_cmd", hlExecCmd); + Internal::setFn(L, "exec_raw", hlExecRaw); + Internal::setFn(L, "exit", hlExit); + Internal::setFn(L, "submap", hlSubmap); + Internal::setFn(L, "pass", hlPass); + Internal::setFn(L, "send_shortcut", hlSendShortcut); + Internal::setFn(L, "send_key_state", hlSendKeyState); + Internal::setFn(L, "layout", hlLayout); + Internal::setFn(L, "dpms", hlDpms); + Internal::setFn(L, "event", hlEvent); + Internal::setFn(L, "global", hlGlobal); + Internal::setFn(L, "force_renderer_reload", hlForceRendererReload); + Internal::setFn(L, "force_idle", hlForceIdle); + Internal::setFn(L, "focus", hlFocus); + } + + lua_setfield(L, -2, "dsp"); +} diff --git a/src/config/lua/bindings/LuaBindingsInternal.cpp b/src/config/lua/bindings/LuaBindingsInternal.cpp new file mode 100644 index 00000000..61a90823 --- /dev/null +++ b/src/config/lua/bindings/LuaBindingsInternal.cpp @@ -0,0 +1,502 @@ +#include "LuaBindingsInternal.hpp" + +using namespace Config; +using namespace Config::Lua; +using namespace Config::Lua::Bindings; + +namespace CA = Config::Actions; + +namespace { + constexpr const char* LUA_WINDOW_MT = "HL.Window"; + constexpr const char* LUA_WORKSPACE_MT = "HL.Workspace"; + constexpr const char* LUA_MONITOR_MT = "HL.Monitor"; +} + +std::string Internal::argStr(lua_State* L, int idx) { + if (lua_type(L, idx) == LUA_TNUMBER) + return std::to_string((long long)lua_tonumber(L, idx)); + + size_t n = 0; + const char* s = luaL_checklstring(L, idx, &n); + return {s, n}; +} + +std::optional Internal::tableOptStr(lua_State* L, int idx, const char* field) { + lua_getfield(L, idx, field); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + return std::nullopt; + } + + const char* s = lua_tostring(L, -1); + lua_pop(L, 1); + return s ? std::optional(std::string(s)) : std::nullopt; +} + +std::optional Internal::tableOptNum(lua_State* L, int idx, const char* field) { + lua_getfield(L, idx, field); + if (lua_isnil(L, -1) || !lua_isnumber(L, -1)) { + lua_pop(L, 1); + return std::nullopt; + } + + const double v = lua_tonumber(L, -1); + lua_pop(L, 1); + return v; +} + +std::optional Internal::tableOptBool(lua_State* L, int idx, const char* field) { + lua_getfield(L, idx, field); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + return std::nullopt; + } + + const bool v = lua_toboolean(L, -1); + lua_pop(L, 1); + return v; +} + +PHLMONITOR Internal::monitorFromLuaSelectorOrObject(lua_State* L, int idx, const char* fnName) { + idx = lua_absindex(L, idx); + + if (lua_isnil(L, idx)) + return nullptr; + + if (auto* ref = sc(luaL_testudata(L, idx, LUA_MONITOR_MT)); ref) + return ref->lock(); + + if (lua_isstring(L, idx) || lua_isnumber(L, idx)) + return g_pCompositor->getMonitorFromString(argStr(L, idx)); + + Internal::configError(L, "{}: expected a monitor object or selector", fnName); + return nullptr; +} + +PHLWORKSPACE Internal::workspaceFromLuaSelectorOrObject(lua_State* L, int idx, const char* fnName) { + idx = lua_absindex(L, idx); + + if (lua_isnil(L, idx)) + return nullptr; + + if (auto* ref = sc(luaL_testudata(L, idx, LUA_WORKSPACE_MT)); ref) { + auto ws = ref->lock(); + if (!ws || ws->inert()) + return nullptr; + + return ws; + } + + if (lua_isstring(L, idx) || lua_isnumber(L, idx)) + return g_pCompositor->getWorkspaceByString(argStr(L, idx)); + + Internal::configError(L, "{}: expected a workspace object or selector", fnName); + return nullptr; +} + +PHLWINDOW Internal::windowFromLuaSelectorOrObject(lua_State* L, int idx, const char* fnName) { + idx = lua_absindex(L, idx); + + if (lua_isnil(L, idx)) + return nullptr; + + if (auto* ref = sc(luaL_testudata(L, idx, LUA_WINDOW_MT)); ref) + return ref->lock(); + + if (lua_isstring(L, idx) || lua_isnumber(L, idx)) + return g_pCompositor->getWindowByRegex(argStr(L, idx)); + + Internal::configError(L, "{}: expected a window object or selector", fnName); + return nullptr; +} + +std::optional Internal::tableOptMonitor(lua_State* L, int idx, const char* field, const char* fnName) { + idx = lua_absindex(L, idx); + lua_getfield(L, idx, field); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + return std::nullopt; + } + + auto mon = monitorFromLuaSelectorOrObject(L, -1, fnName); + lua_pop(L, 1); + return mon; +} + +std::optional Internal::tableOptWorkspace(lua_State* L, int idx, const char* field, const char* fnName) { + idx = lua_absindex(L, idx); + lua_getfield(L, idx, field); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + return std::nullopt; + } + + auto ws = workspaceFromLuaSelectorOrObject(L, -1, fnName); + lua_pop(L, 1); + return ws; +} + +std::optional Internal::tableOptWindow(lua_State* L, int idx, const char* field, const char* fnName) { + idx = lua_absindex(L, idx); + lua_getfield(L, idx, field); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + return std::nullopt; + } + + auto window = windowFromLuaSelectorOrObject(L, -1, fnName); + lua_pop(L, 1); + return window; +} + +std::optional Internal::monitorSelectorFromLuaSelectorOrObject(lua_State* L, int idx, const char* fnName) { + idx = lua_absindex(L, idx); + + if (lua_isnil(L, idx)) + return std::nullopt; + + if (auto* ref = sc(luaL_testudata(L, idx, LUA_MONITOR_MT)); ref) { + const auto mon = ref->lock(); + if (!mon) { + Internal::configError(L, "{}: monitor object is expired", fnName); + return std::nullopt; + } + + return mon->m_name; + } + + if (lua_isstring(L, idx) || lua_isnumber(L, idx)) + return argStr(L, idx); + + Internal::configError(L, "{}: expected a monitor object or selector", fnName); + return std::nullopt; +} + +std::optional Internal::workspaceSelectorFromLuaSelectorOrObject(lua_State* L, int idx, const char* fnName) { + idx = lua_absindex(L, idx); + + if (lua_isnil(L, idx)) + return std::nullopt; + + if (auto* ref = sc(luaL_testudata(L, idx, LUA_WORKSPACE_MT)); ref) { + const auto ws = ref->lock(); + if (!ws || ws->inert()) { + Internal::configError(L, "{}: workspace object is expired", fnName); + return std::nullopt; + } + + return std::to_string(ws->m_id); + } + + if (lua_isstring(L, idx) || lua_isnumber(L, idx)) + return argStr(L, idx); + + Internal::configError(L, "{}: expected a workspace object or selector", fnName); + return std::nullopt; +} + +std::optional Internal::windowSelectorFromLuaSelectorOrObject(lua_State* L, int idx, const char* fnName) { + idx = lua_absindex(L, idx); + + if (lua_isnil(L, idx)) + return std::nullopt; + + if (auto* ref = sc(luaL_testudata(L, idx, LUA_WINDOW_MT)); ref) { + const auto w = ref->lock(); + if (!w) { + Internal::configError(L, "{}: window object is expired", fnName); + return std::nullopt; + } + + return std::format("0x{:x}", reinterpret_cast(w.get())); + } + + if (lua_isstring(L, idx) || lua_isnumber(L, idx)) + return argStr(L, idx); + + Internal::configError(L, "{}: expected a window object or selector", fnName); + return std::nullopt; +} + +std::optional Internal::tableOptMonitorSelector(lua_State* L, int idx, const char* field, const char* fnName) { + idx = lua_absindex(L, idx); + lua_getfield(L, idx, field); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + return std::nullopt; + } + + auto selector = monitorSelectorFromLuaSelectorOrObject(L, -1, fnName); + lua_pop(L, 1); + return selector; +} + +std::optional Internal::tableOptWorkspaceSelector(lua_State* L, int idx, const char* field, const char* fnName) { + idx = lua_absindex(L, idx); + lua_getfield(L, idx, field); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + return std::nullopt; + } + + auto selector = workspaceSelectorFromLuaSelectorOrObject(L, -1, fnName); + lua_pop(L, 1); + return selector; +} + +std::optional Internal::tableOptWindowSelector(lua_State* L, int idx, const char* field, const char* fnName) { + idx = lua_absindex(L, idx); + lua_getfield(L, idx, field); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + return std::nullopt; + } + + auto selector = windowSelectorFromLuaSelectorOrObject(L, -1, fnName); + lua_pop(L, 1); + return selector; +} + +std::string Internal::requireTableFieldMonitorSelector(lua_State* L, int idx, const char* field, const char* fnName) { + auto selector = tableOptMonitorSelector(L, idx, field, fnName); + if (!selector) { + Internal::configError(L, "{}: '{}' is required", fnName, field); + return ""; + } + + return *selector; +} + +std::string Internal::requireTableFieldWorkspaceSelector(lua_State* L, int idx, const char* field, const char* fnName) { + auto selector = tableOptWorkspaceSelector(L, idx, field, fnName); + if (!selector) { + Internal::configError(L, "{}: '{}' is required", fnName, field); + return ""; + } + + return *selector; +} + +std::string Internal::requireTableFieldWindowSelector(lua_State* L, int idx, const char* field, const char* fnName) { + auto selector = tableOptWindowSelector(L, idx, field, fnName); + if (!selector) { + Internal::configError(L, "{}: '{}' is required", fnName, field); + return ""; + } + + return *selector; +} + +Math::eDirection Internal::parseDirectionStr(const std::string& str) { + if (str == "left" || str == "l") + return Math::DIRECTION_LEFT; + if (str == "right" || str == "r") + return Math::DIRECTION_RIGHT; + if (str == "up" || str == "u" || str == "t") + return Math::DIRECTION_UP; + if (str == "down" || str == "d" || str == "b") + return Math::DIRECTION_DOWN; + return Math::DIRECTION_DEFAULT; +} + +CA::eTogglableAction Internal::parseToggleStr(const std::string& str) { + if (str.empty() || str == "toggle") + return CA::TOGGLE_ACTION_TOGGLE; + if (str == "enable" || str == "on") + return CA::TOGGLE_ACTION_ENABLE; + if (str == "disable" || str == "off") + return CA::TOGGLE_ACTION_DISABLE; + return CA::TOGGLE_ACTION_TOGGLE; +} + +std::optional Internal::windowFromUpval(lua_State* L, int idx) { + if (lua_isnil(L, lua_upvalueindex(idx))) + return std::nullopt; + + return g_pCompositor->getWindowByRegex(lua_tostring(L, lua_upvalueindex(idx))); +} + +void Internal::pushWindowUpval(lua_State* L, int tableIdx) { + if (lua_istable(L, tableIdx)) { + auto selector = tableOptWindowSelector(L, tableIdx, "window", "window selector"); + if (!selector) + lua_pushnil(L); + else + lua_pushstring(L, selector->c_str()); + } else + lua_pushnil(L); +} + +void Internal::checkResult(lua_State* L, const CA::ActionResult& r) { + if (!r) + Internal::configError(L, "{}", r.error()); +} + +PHLWORKSPACE Internal::resolveWorkspaceStr(const std::string& args) { + const auto& [id, name, isAutoID] = getWorkspaceIDNameFromString(args); + if (id == WORKSPACE_INVALID) + return nullptr; + + auto ws = g_pCompositor->getWorkspaceByID(id); + if (!ws) { + const auto PMONITOR = Desktop::focusState()->monitor(); + if (PMONITOR) + ws = g_pCompositor->createNewWorkspace(id, PMONITOR->m_id, name, false); + } + + return ws; +} + +PHLMONITOR Internal::resolveMonitorStr(const std::string& args) { + auto mon = g_pCompositor->getMonitorFromString(args); + return mon; +} + +std::string Internal::getSourceInfo(lua_State* L, int stackLevel) { + lua_Debug ar = {}; + std::string sourceInfo = "?:?"; + + if (lua_getstack(L, stackLevel, &ar) && lua_getinfo(L, "Sl", &ar)) { + const char* src = ar.source; + if (src && src[0] == '@') + src++; + + sourceInfo = std::format("{}:{}", src ? src : "?", ar.currentline); + } + + return sourceInfo; +} + +std::string Internal::requireTableFieldStr(lua_State* L, int idx, const char* field, const char* fnName) { + auto value = tableOptStr(L, idx, field); + if (!value) { + Internal::configError(L, "{}: '{}' is required", fnName, field); + return ""; + } + + return *value; +} + +double Internal::requireTableFieldNum(lua_State* L, int idx, const char* field, const char* fnName) { + auto value = tableOptNum(L, idx, field); + if (!value) { + Internal::configError(L, "{}: '{}' is required", fnName, field); + return 0; + } + + return *value; +} + +CA::eTogglableAction Internal::tableToggleAction(lua_State* L, int idx, const char* field) { + if (!lua_istable(L, idx)) + return CA::TOGGLE_ACTION_TOGGLE; + + if (const auto action = tableOptStr(L, idx, field); action.has_value()) + return parseToggleStr(*action); + + return CA::TOGGLE_ACTION_TOGGLE; +} + +void Internal::setFn(lua_State* L, const char* name, lua_CFunction fn) { + lua_pushcfunction(L, fn); + lua_setfield(L, -2, name); +} + +void Internal::setMgrFn(lua_State* L, CConfigManager* mgr, const char* name, lua_CFunction fn) { + lua_pushlightuserdata(L, mgr); + lua_pushcclosure(L, fn, 1); + lua_setfield(L, -2, name); +} + +int Internal::configError(lua_State* L, std::string s, int stackLevel) { + s = std::format("{}: {}", getSourceInfo(L, stackLevel), std::move(s)); + + Log::logger->log(Log::ERR, "Error in lua: {}", std::string_view{s}); + Config::Lua::mgr()->addError(std::move(s)); + return 0; +} + +std::expected Internal::ruleValueToString(lua_State* L) { + if (lua_type(L, -1) == LUA_TBOOLEAN) + return lua_toboolean(L, -1) ? "true" : "false"; + + if (lua_isinteger(L, -1)) + return std::to_string(lua_tointeger(L, -1)); + + if (lua_isnumber(L, -1)) + return std::to_string(lua_tonumber(L, -1)); + + if (lua_isstring(L, -1)) + return std::string(lua_tostring(L, -1)); + + return std::unexpected("value must be a string, bool, or number"); +} + +std::expected, int> Internal::buildRuleFromTable(lua_State* L, int idx) { + SP rule; + + if (!lua_isnoneornil(L, idx)) { + if (!lua_istable(L, idx)) + return std::unexpected(Internal::configError(L, "buildRuleFromTable: failed to build table for exec rules from argument")); + + int optsIdx = lua_absindex(L, idx); + bool hasRuleEffects = false; + + rule = makeShared(); + + lua_pushnil(L); + while (lua_next(L, optsIdx) != 0) { + if (lua_type(L, -2) != LUA_TSTRING) { + lua_pop(L, 1); + return std::unexpected(Internal::configError(L, "buildRuleFromTable: effect key must be a string")); + } + + std::string key = lua_tostring(L, -2); + + if (key == "floating") + key = "float"; + + const auto* desc = Internal::findDescByName(Internal::WINDOW_RULE_EFFECT_DESCS, key); + if (!desc) { + const auto dynamicEffect = Desktop::Rule::windowEffects()->get(key); + if (!dynamicEffect.has_value()) { + lua_pop(L, 1); + return std::unexpected(Internal::configError(L, "buildRuleFromTable: unknown effect '{}'", key)); + } + + auto val = ruleValueToString(L); + if (!val) { + lua_pop(L, 1); + return std::unexpected(Internal::configError(L, "buildRuleFromTable: effect '{}': {}", key, val.error())); + } + + rule->addEffect(*dynamicEffect, *val); + hasRuleEffects = true; + + lua_pop(L, 1); + continue; + } + + auto val = UP(desc->factory()); + auto err = val->parse(L); + if (err.errorCode != PARSE_ERROR_OK) { + const bool allowLegacyString = (key == "max_size" || key == "min_size" || key == "border_color") && lua_isstring(L, -1); + if (allowLegacyString) + rule->addEffect(desc->effect, lua_tostring(L, -1)); + else { + lua_pop(L, 1); + return std::unexpected(Internal::configError(L, "buildRuleFromTable: effect '{}': {}", key, err.message)); + } + } else + rule->addEffect(desc->effect, val->toString()); + + hasRuleEffects = true; + lua_pop(L, 1); + } + + if (!hasRuleEffects) + return nullptr; + } + + return rule; +} diff --git a/src/config/lua/bindings/LuaBindingsInternal.hpp b/src/config/lua/bindings/LuaBindingsInternal.hpp new file mode 100644 index 00000000..2cd65184 --- /dev/null +++ b/src/config/lua/bindings/LuaBindingsInternal.hpp @@ -0,0 +1,188 @@ +#pragma once + +#include "../LuaBindings.hpp" + +#include "../ConfigManager.hpp" +#include "../types/LuaConfigValue.hpp" +#include "../types/LuaConfigBool.hpp" +#include "../types/LuaConfigFloat.hpp" +#include "../types/LuaConfigGradient.hpp" +#include "../types/LuaConfigInt.hpp" +#include "../types/LuaConfigString.hpp" +#include "../types/LuaConfigVec2.hpp" + +#include "../../../Compositor.hpp" +#include "../../../helpers/MiscFunctions.hpp" +#include "../../../helpers/Monitor.hpp" +#include "../../../desktop/state/FocusState.hpp" +#include "../../../desktop/rule/windowRule/WindowRuleEffectContainer.hpp" +#include "../../../managers/KeybindManager.hpp" +#include "../../shared/actions/ConfigActions.hpp" + +#include +#include +#include +#include +#include +#include + +extern "C" { +#include +#include +} + +namespace Config::Lua::Bindings::Internal { + + struct SWindowRuleEffectDesc { + const char* name; + std::function factory; + uint16_t effect; + }; + + using WE = Desktop::Rule::eWindowRuleEffect; + + inline const SWindowRuleEffectDesc WINDOW_RULE_EFFECT_DESCS[] = { + {"float", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_FLOAT}, + {"tile", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_TILE}, + {"fullscreen", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_FULLSCREEN}, + {"maximize", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_MAXIMIZE}, + {"center", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_CENTER}, + {"pseudo", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_PSEUDO}, + {"no_initial_focus", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_NOINITIALFOCUS}, + {"pin", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_PIN}, + {"fullscreen_state", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, WE::WINDOW_RULE_EFFECT_FULLSCREENSTATE}, + {"move", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, WE::WINDOW_RULE_EFFECT_MOVE}, + {"size", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, WE::WINDOW_RULE_EFFECT_SIZE}, + {"monitor", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, WE::WINDOW_RULE_EFFECT_MONITOR}, + {"workspace", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, WE::WINDOW_RULE_EFFECT_WORKSPACE}, + {"group", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, WE::WINDOW_RULE_EFFECT_GROUP}, + {"suppress_event", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, WE::WINDOW_RULE_EFFECT_SUPPRESSEVENT}, + {"content", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, WE::WINDOW_RULE_EFFECT_CONTENT}, + {"no_close_for", []() -> ILuaConfigValue* { return new CLuaConfigInt(0); }, WE::WINDOW_RULE_EFFECT_NOCLOSEFOR}, + {"scrolling_width", []() -> ILuaConfigValue* { return new CLuaConfigFloat(0.F); }, WE::WINDOW_RULE_EFFECT_SCROLLING_WIDTH}, + {"rounding", []() -> ILuaConfigValue* { return new CLuaConfigInt(0, 0, 20); }, WE::WINDOW_RULE_EFFECT_ROUNDING}, + {"border_size", []() -> ILuaConfigValue* { return new CLuaConfigInt(0); }, WE::WINDOW_RULE_EFFECT_BORDER_SIZE}, + {"rounding_power", []() -> ILuaConfigValue* { return new CLuaConfigFloat(2.F, 1.F, 10.F); }, WE::WINDOW_RULE_EFFECT_ROUNDING_POWER}, + {"scroll_mouse", []() -> ILuaConfigValue* { return new CLuaConfigFloat(1.F, 0.01F, 10.F); }, WE::WINDOW_RULE_EFFECT_SCROLL_MOUSE}, + {"scroll_touchpad", []() -> ILuaConfigValue* { return new CLuaConfigFloat(1.F, 0.01F, 10.F); }, WE::WINDOW_RULE_EFFECT_SCROLL_TOUCHPAD}, + {"animation", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, WE::WINDOW_RULE_EFFECT_ANIMATION}, + {"idle_inhibit", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, WE::WINDOW_RULE_EFFECT_IDLE_INHIBIT}, + {"opacity", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, WE::WINDOW_RULE_EFFECT_OPACITY}, + {"tag", []() -> ILuaConfigValue* { return new CLuaConfigString(STRVAL_EMPTY); }, WE::WINDOW_RULE_EFFECT_TAG}, + {"max_size", []() -> ILuaConfigValue* { return new CLuaConfigVec2({0, 0}); }, WE::WINDOW_RULE_EFFECT_MAX_SIZE}, + {"min_size", []() -> ILuaConfigValue* { return new CLuaConfigVec2({0, 0}); }, WE::WINDOW_RULE_EFFECT_MIN_SIZE}, + {"border_color", []() -> ILuaConfigValue* { return new CLuaConfigGradient(CHyprColor(0xFF000000)); }, WE::WINDOW_RULE_EFFECT_BORDER_COLOR}, + {"persistent_size", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_PERSISTENT_SIZE}, + {"allows_input", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_ALLOWS_INPUT}, + {"dim_around", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_DIM_AROUND}, + {"decorate", []() -> ILuaConfigValue* { return new CLuaConfigBool(true); }, WE::WINDOW_RULE_EFFECT_DECORATE}, + {"focus_on_activate", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_FOCUS_ON_ACTIVATE}, + {"keep_aspect_ratio", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_KEEP_ASPECT_RATIO}, + {"nearest_neighbor", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_NEAREST_NEIGHBOR}, + {"no_anim", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_NO_ANIM}, + {"no_blur", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_NO_BLUR}, + {"no_dim", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_NO_DIM}, + {"no_focus", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_NO_FOCUS}, + {"no_follow_mouse", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_NO_FOLLOW_MOUSE}, + {"no_max_size", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_NO_MAX_SIZE}, + {"no_shadow", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_NO_SHADOW}, + {"no_shortcuts_inhibit", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_NO_SHORTCUTS_INHIBIT}, + {"opaque", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_OPAQUE}, + {"force_rgbx", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_FORCE_RGBX}, + {"sync_fullscreen", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_SYNC_FULLSCREEN}, + {"immediate", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_IMMEDIATE}, + {"xray", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_XRAY}, + {"render_unfocused", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_RENDER_UNFOCUSED}, + {"no_screen_share", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_NO_SCREEN_SHARE}, + {"no_vrr", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_NO_VRR}, + {"stay_focused", []() -> ILuaConfigValue* { return new CLuaConfigBool(false); }, WE::WINDOW_RULE_EFFECT_STAY_FOCUSED}, + }; + + std::string argStr(lua_State* L, int idx); + std::optional tableOptStr(lua_State* L, int idx, const char* field); + std::optional tableOptNum(lua_State* L, int idx, const char* field); + std::optional tableOptBool(lua_State* L, int idx, const char* field); + + PHLMONITOR monitorFromLuaSelectorOrObject(lua_State* L, int idx, const char* fnName); + PHLWORKSPACE workspaceFromLuaSelectorOrObject(lua_State* L, int idx, const char* fnName); + PHLWINDOW windowFromLuaSelectorOrObject(lua_State* L, int idx, const char* fnName); + std::optional tableOptMonitor(lua_State* L, int idx, const char* field, const char* fnName); + std::optional tableOptWorkspace(lua_State* L, int idx, const char* field, const char* fnName); + std::optional tableOptWindow(lua_State* L, int idx, const char* field, const char* fnName); + + std::optional monitorSelectorFromLuaSelectorOrObject(lua_State* L, int idx, const char* fnName); + std::optional workspaceSelectorFromLuaSelectorOrObject(lua_State* L, int idx, const char* fnName); + std::optional windowSelectorFromLuaSelectorOrObject(lua_State* L, int idx, const char* fnName); + + std::optional tableOptMonitorSelector(lua_State* L, int idx, const char* field, const char* fnName); + std::optional tableOptWorkspaceSelector(lua_State* L, int idx, const char* field, const char* fnName); + std::optional tableOptWindowSelector(lua_State* L, int idx, const char* field, const char* fnName); + + std::string requireTableFieldMonitorSelector(lua_State* L, int idx, const char* field, const char* fnName); + std::string requireTableFieldWorkspaceSelector(lua_State* L, int idx, const char* field, const char* fnName); + std::string requireTableFieldWindowSelector(lua_State* L, int idx, const char* field, const char* fnName); + + Math::eDirection parseDirectionStr(const std::string& str); + Config::Actions::eTogglableAction parseToggleStr(const std::string& str); + + std::optional windowFromUpval(lua_State* L, int idx); + void pushWindowUpval(lua_State* L, int tableIdx); + void checkResult(lua_State* L, const Config::Actions::ActionResult& r); + PHLWORKSPACE resolveWorkspaceStr(const std::string& args); + PHLMONITOR resolveMonitorStr(const std::string& args); + std::string getSourceInfo(lua_State* L, int stackLevel = 1); + + std::string requireTableFieldStr(lua_State* L, int idx, const char* field, const char* fnName); + double requireTableFieldNum(lua_State* L, int idx, const char* field, const char* fnName); + Config::Actions::eTogglableAction tableToggleAction(lua_State* L, int idx, const char* field = "action"); + + std::expected ruleValueToString(lua_State* L); + std::expected, int> buildRuleFromTable(lua_State* L, int idx); + + int configError(lua_State* L, std::string s, int stackLevel = 1); + + template + int configError(lua_State* L, std::format_string fmt, Args&&... args) { + return configError(L, std::format(fmt, std::forward(args)...)); + } + + template + int configError(lua_State* L, int stackLevel, std::format_string fmt, Args&&... args) { + return configError(L, std::format(fmt, std::forward(args)...), stackLevel); + } + + template + const T* findDescByName(const T (&descs)[N], std::string_view key) { + for (const auto& desc : descs) { + if (key == desc.name) + return &desc; + } + + return nullptr; + } + + void setFn(lua_State* L, const char* name, lua_CFunction fn); + void setMgrFn(lua_State* L, CConfigManager* mgr, const char* name, lua_CFunction fn); + + template + SParseError parseTableField(lua_State* L, int tableIdx, const char* field, T& parser) { + lua_getfield(L, tableIdx, field); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = std::format("missing required field \"{}\"", field)}; + } + + auto err = parser.parse(L); + lua_pop(L, 1); + if (err.errorCode != PARSE_ERROR_OK) + err.message = std::format("field \"{}\": {}", field, err.message); + return err; + } + + void registerToplevelBindings(lua_State* L, CConfigManager* mgr); + void registerQueryBindings(lua_State* L); + void registerNotificationBindings(lua_State* L); + void registerConfigRuleBindings(lua_State* L, CConfigManager* mgr); + void registerBindingsImpl(lua_State* L, CConfigManager* mgr); + void registerDispatcherBindings(lua_State* L); +} diff --git a/src/config/lua/bindings/LuaBindingsNotification.cpp b/src/config/lua/bindings/LuaBindingsNotification.cpp new file mode 100644 index 00000000..b7a54546 --- /dev/null +++ b/src/config/lua/bindings/LuaBindingsNotification.cpp @@ -0,0 +1,135 @@ +#include "LuaBindingsInternal.hpp" + +#include "../objects/LuaNotification.hpp" + +#include "../../../helpers/MiscFunctions.hpp" +#include "../../../notification/NotificationOverlay.hpp" + +#include +#include +#include +#include +#include + +using namespace Config; +using namespace Config::Lua; +using namespace Config::Lua::Bindings; + +static std::optional iconFromString(std::string iconName) { + std::ranges::transform(iconName, iconName.begin(), [](const unsigned char c) { return std::tolower(c); }); + + static constexpr std::array, 10> ICON_NAMES = { + std::pair{"warning", ICON_WARNING}, std::pair{"warn", ICON_WARNING}, std::pair{"info", ICON_INFO}, std::pair{"hint", ICON_HINT}, + std::pair{"error", ICON_ERROR}, std::pair{"err", ICON_ERROR}, std::pair{"confused", ICON_CONFUSED}, std::pair{"question", ICON_CONFUSED}, + std::pair{"ok", ICON_OK}, std::pair{"none", ICON_NONE}, + }; + + for (const auto& [name, icon] : ICON_NAMES) { + if (name == iconName) + return icon; + } + + return std::nullopt; +} + +static std::optional parseIconArg(lua_State* L, int idx) { + if (lua_isnumber(L, idx)) { + const auto raw = sc(lua_tonumber(L, idx)); + if (raw >= ICON_WARNING && raw <= ICON_NONE) + return sc(raw); + + return std::nullopt; + } + + if (lua_isstring(L, idx)) + return iconFromString(lua_tostring(L, idx)); + + return std::nullopt; +} + +static std::optional parseColorArg(lua_State* L, int idx) { + if (lua_isnumber(L, idx)) + return CHyprColor(sc(lua_tonumber(L, idx))); + + if (lua_isstring(L, idx)) { + auto parsed = configStringToInt(lua_tostring(L, idx)); + if (!parsed) + return std::nullopt; + + return CHyprColor(sc(*parsed)); + } + + return std::nullopt; +} + +static int hlNotificationCreate(lua_State* L) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.notification.create: expected a table { text, duration, icon?, color?, font_size? }"); + + const auto text = Internal::requireTableFieldStr(L, 1, "text", "hl.notification.create"); + + std::optional duration = Internal::tableOptNum(L, 1, "duration"); + if (!duration) + duration = Internal::tableOptNum(L, 1, "timeout"); + if (!duration) + duration = Internal::tableOptNum(L, 1, "time"); + + if (!duration) + return Internal::configError(L, "hl.notification.create: 'duration' (or 'timeout' / 'time') is required"); + if (*duration < 0) + return Internal::configError(L, "hl.notification.create: duration must be >= 0"); + + eIcons icon = ICON_NONE; + lua_getfield(L, 1, "icon"); + if (!lua_isnil(L, -1)) { + const auto parsedIcon = parseIconArg(L, -1); + if (!parsedIcon) + return Internal::configError(L, "hl.notification.create: invalid 'icon' (expected icon name or number)"); + + icon = *parsedIcon; + } + lua_pop(L, 1); + + CHyprColor color = CHyprColor(0); + lua_getfield(L, 1, "color"); + if (!lua_isnil(L, -1)) { + const auto parsedColor = parseColorArg(L, -1); + if (!parsedColor) + return Internal::configError(L, "hl.notification.create: invalid 'color' (expected color string or number)"); + + color = *parsedColor; + } + lua_pop(L, 1); + + float fontSize = 13.F; + if (const auto parsedFontSize = Internal::tableOptNum(L, 1, "font_size"); parsedFontSize.has_value()) { + if (*parsedFontSize <= 0) + return Internal::configError(L, "hl.notification.create: 'font_size' must be > 0"); + + fontSize = sc(*parsedFontSize); + } + + auto notification = Notification::overlay()->addNotification(text, color, sc(*duration), icon, fontSize); + Objects::CLuaNotification::push(L, notification); + return 1; +} + +static int hlGetNotifications(lua_State* L) { + lua_newtable(L); + + const auto notifications = Notification::overlay()->getNotifications(); + int i = 1; + for (const auto& notification : notifications) { + Objects::CLuaNotification::push(L, notification); + lua_rawseti(L, -2, i++); + } + + return 1; +} + +void Internal::registerNotificationBindings(lua_State* L) { + lua_newtable(L); + Internal::setFn(L, "create", hlNotificationCreate); + Internal::setFn(L, "get", hlGetNotifications); + lua_setfield(L, -2, "notification"); +} diff --git a/src/config/lua/bindings/LuaBindingsQuery.cpp b/src/config/lua/bindings/LuaBindingsQuery.cpp new file mode 100644 index 00000000..6e630388 --- /dev/null +++ b/src/config/lua/bindings/LuaBindingsQuery.cpp @@ -0,0 +1,400 @@ +#include "LuaBindingsInternal.hpp" + +#include "../objects/LuaLayerSurface.hpp" +#include "../objects/LuaMonitor.hpp" +#include "../objects/LuaWindow.hpp" +#include "../objects/LuaWorkspace.hpp" + +#include "../../../desktop/history/WindowHistoryTracker.hpp" +#include "../../../desktop/history/WorkspaceHistoryTracker.hpp" +#include "../../../desktop/rule/windowRule/WindowRuleEffectContainer.hpp" +#include "../../../desktop/view/LayerSurface.hpp" +#include "../../../desktop/view/Window.hpp" +#include "../../../managers/input/InputManager.hpp" + +using namespace Config; +using namespace Config::Lua; +using namespace Config::Lua::Bindings; + +namespace { + struct SWindowQuery { + std::optional monitor; + std::optional workspace; + std::optional floating; + std::optional mapped; + std::optional className; + std::optional title; + std::optional tag; + }; + + struct SLayerQuery { + std::optional monitor; + std::optional namespace_; + }; +} + +static bool windowMatchesQuery(const PHLWINDOW& w, const SWindowQuery& query) { + if (query.monitor) { + const auto mon = w->m_monitor.lock(); + if (mon != *query.monitor) + return false; + } + + if (query.workspace && w->m_workspace != *query.workspace) + return false; + + if (query.floating && w->m_isFloating != *query.floating) + return false; + + if (query.mapped && w->m_isMapped != *query.mapped) + return false; + + if (query.className && w->m_class != *query.className) + return false; + + if (query.title && w->m_title != *query.title) + return false; + + if (query.tag) { + if (!w->m_ruleApplicator || !w->m_ruleApplicator->m_tagKeeper.isTagged(*query.tag, true)) + return false; + } + + return true; +} + +static void pushWindowsMatchingQuery(lua_State* L, const SWindowQuery& query) { + lua_newtable(L); + + int i = 1; + for (const auto& w : g_pCompositor->m_windows) { + if (!windowMatchesQuery(w, query)) + continue; + + Objects::CLuaWindow::push(L, w); + lua_rawseti(L, -2, i++); + } +} + +static void parseWindowQueryFromTable(lua_State* L, int idx, const char* fnName, SWindowQuery& query) { + query.monitor = Internal::tableOptMonitor(L, idx, "monitor", fnName); + query.workspace = Internal::tableOptWorkspace(L, idx, "workspace", fnName); + + if (const auto floating = Internal::tableOptBool(L, idx, "floating"); floating.has_value()) + query.floating = floating; + + if (const auto mapped = Internal::tableOptBool(L, idx, "mapped"); mapped.has_value()) + query.mapped = mapped; + + query.className = Internal::tableOptStr(L, idx, "class"); + query.title = Internal::tableOptStr(L, idx, "title"); + query.tag = Internal::tableOptStr(L, idx, "tag"); +} + +static void parseLayerQueryFromTable(lua_State* L, int idx, const char* fnName, SLayerQuery& query) { + query.monitor = Internal::tableOptMonitor(L, idx, "monitor", fnName); + query.namespace_ = Internal::tableOptStr(L, idx, "namespace"); +} + +static PHLMONITOR monitorFromOptionalArg(lua_State* L, int idx, const char* fnName) { + if (lua_gettop(L) < idx || lua_isnil(L, idx)) + return Desktop::focusState()->monitor(); + + return Internal::monitorFromLuaSelectorOrObject(L, idx, fnName); +} + +static int hlGetWindows(lua_State* L) { + SWindowQuery query; + query.mapped = true; + + if (lua_gettop(L) >= 1 && !lua_isnil(L, 1)) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.get_windows: expected no args or a table of filters"); + + parseWindowQueryFromTable(L, 1, "hl.get_windows", query); + } + + pushWindowsMatchingQuery(L, query); + return 1; +} + +static int hlGetActiveWindow(lua_State* L) { + auto PWINDOW = Desktop::focusState()->window(); + if (!PWINDOW) { + lua_pushnil(L); + return 1; + } + + Config::Lua::Objects::CLuaWindow::push(L, PWINDOW); + return 1; +} + +static int hlGetWindow(lua_State* L) { + const auto PWINDOW = Internal::windowFromLuaSelectorOrObject(L, 1, "hl.get_window"); + if (!PWINDOW) { + lua_pushnil(L); + return 1; + } + + Objects::CLuaWindow::push(L, PWINDOW); + return 1; +} + +static int hlGetUrgentWindow(lua_State* L) { + const auto PWINDOW = g_pCompositor->getUrgentWindow(); + if (!PWINDOW) { + lua_pushnil(L); + return 1; + } + + Objects::CLuaWindow::push(L, PWINDOW); + return 1; +} + +static int hlGetWorkspaces(lua_State* L) { + lua_newtable(L); + int i = 1; + for (const auto& wsRef : g_pCompositor->getWorkspaces()) { + const auto ws = wsRef.lock(); + if (!ws || ws->inert()) + continue; + Objects::CLuaWorkspace::push(L, ws); + lua_rawseti(L, -2, i++); + } + return 1; +} + +static int hlGetWorkspace(lua_State* L) { + const auto PWORKSPACE = Internal::workspaceFromLuaSelectorOrObject(L, 1, "hl.get_workspace"); + if (!PWORKSPACE) { + lua_pushnil(L); + return 1; + } + + Objects::CLuaWorkspace::push(L, PWORKSPACE); + return 1; +} + +static int hlGetActiveWorkspace(lua_State* L) { + const auto PMONITOR = monitorFromOptionalArg(L, 1, "hl.get_active_workspace"); + if (!PMONITOR || !PMONITOR->m_activeWorkspace) { + lua_pushnil(L); + return 1; + } + + Objects::CLuaWorkspace::push(L, PMONITOR->m_activeWorkspace); + return 1; +} + +static int hlGetActiveSpecialWorkspace(lua_State* L) { + const auto PMONITOR = monitorFromOptionalArg(L, 1, "hl.get_active_special_workspace"); + if (!PMONITOR || !PMONITOR->m_activeSpecialWorkspace) { + lua_pushnil(L); + return 1; + } + + Objects::CLuaWorkspace::push(L, PMONITOR->m_activeSpecialWorkspace); + return 1; +} + +static int hlGetMonitors(lua_State* L) { + lua_newtable(L); + int i = 1; + for (const auto& mon : g_pCompositor->m_monitors) { + Objects::CLuaMonitor::push(L, mon); + lua_rawseti(L, -2, i++); + } + return 1; +} + +static int hlGetMonitor(lua_State* L) { + const auto PMONITOR = Internal::monitorFromLuaSelectorOrObject(L, 1, "hl.get_monitor"); + if (!PMONITOR) { + lua_pushnil(L); + return 1; + } + + Objects::CLuaMonitor::push(L, PMONITOR); + return 1; +} + +static int hlGetActiveMonitor(lua_State* L) { + const auto PMONITOR = Desktop::focusState()->monitor(); + if (!PMONITOR) { + lua_pushnil(L); + return 1; + } + + Objects::CLuaMonitor::push(L, PMONITOR); + return 1; +} + +static int hlGetMonitorAt(lua_State* L) { + double x = 0; + double y = 0; + + if (lua_istable(L, 1)) { + const auto tx = Internal::tableOptNum(L, 1, "x"); + const auto ty = Internal::tableOptNum(L, 1, "y"); + if (!tx || !ty) + return Internal::configError(L, "hl.get_monitor_at: expected a table { x, y }"); + + x = *tx; + y = *ty; + } else { + x = luaL_checknumber(L, 1); + y = luaL_checknumber(L, 2); + } + + const auto PMONITOR = g_pCompositor->getMonitorFromVector(Vector2D{x, y}); + if (!PMONITOR) { + lua_pushnil(L); + return 1; + } + + Objects::CLuaMonitor::push(L, PMONITOR); + return 1; +} + +static int hlGetMonitorAtCursor(lua_State* L) { + const auto PMONITOR = g_pCompositor->getMonitorFromCursor(); + if (!PMONITOR) { + lua_pushnil(L); + return 1; + } + + Objects::CLuaMonitor::push(L, PMONITOR); + return 1; +} + +static int hlGetCursorPos(lua_State* L) { + if (!g_pInputManager) { + lua_pushnil(L); + return 1; + } + + const auto pos = g_pInputManager->getMouseCoordsInternal(); + + lua_newtable(L); + lua_pushnumber(L, pos.x); + lua_setfield(L, -2, "x"); + lua_pushnumber(L, pos.y); + lua_setfield(L, -2, "y"); + return 1; +} + +static int hlGetLastWindow(lua_State* L) { + const auto current = Desktop::focusState()->window(); + const auto& fullHistory = Desktop::History::windowTracker()->fullHistory(); + + for (auto it = fullHistory.rbegin(); it != fullHistory.rend(); ++it) { + const auto candidate = it->lock(); + if (!candidate || !candidate->m_isMapped) + continue; + + if (current && candidate == current) + continue; + + Objects::CLuaWindow::push(L, candidate); + return 1; + } + + lua_pushnil(L); + return 1; +} + +static int hlGetLastWorkspace(lua_State* L) { + const bool hadMonitorArg = lua_gettop(L) >= 1 && !lua_isnil(L, 1); + const auto PMONITOR = hadMonitorArg ? Internal::monitorFromLuaSelectorOrObject(L, 1, "hl.get_last_workspace") : Desktop::focusState()->monitor(); + if (!PMONITOR || !PMONITOR->m_activeWorkspace) { + lua_pushnil(L); + return 1; + } + + const auto current = PMONITOR->m_activeWorkspace; + + auto previous = hadMonitorArg ? Desktop::History::workspaceTracker()->previousWorkspace(current, PMONITOR) : Desktop::History::workspaceTracker()->previousWorkspace(current); + + auto ws = previous.workspace.lock(); + if ((!ws || ws->inert()) && previous.id != WORKSPACE_INVALID) + ws = g_pCompositor->getWorkspaceByID(previous.id); + + if (!ws || ws->inert()) { + lua_pushnil(L); + return 1; + } + + Objects::CLuaWorkspace::push(L, ws); + return 1; +} + +static int hlGetLayers(lua_State* L) { + SLayerQuery query; + + if (lua_gettop(L) >= 1 && !lua_isnil(L, 1)) { + if (!lua_istable(L, 1)) + return Internal::configError(L, "hl.get_layers: expected no args or a table of filters"); + + parseLayerQueryFromTable(L, 1, "hl.get_layers", query); + } + + lua_newtable(L); + int i = 1; + for (const auto& mon : g_pCompositor->m_monitors) { + if (query.monitor && mon != *query.monitor) + continue; + + for (const auto& level : mon->m_layerSurfaceLayers) { + for (const auto& lsRef : level) { + const auto ls = lsRef.lock(); + if (!ls) + continue; + + if (query.namespace_ && ls->m_namespace != *query.namespace_) + continue; + + Objects::CLuaLayerSurface::push(L, ls); + lua_rawseti(L, -2, i++); + } + } + } + return 1; +} + +static int hlGetWorkspaceWindows(lua_State* L) { + const auto ws = Internal::workspaceFromLuaSelectorOrObject(L, 1, "hl.get_workspace_windows"); + + SWindowQuery query; + query.workspace = ws; + query.mapped = true; + + pushWindowsMatchingQuery(L, query); + return 1; +} + +static int hlGetCurrentSubmap(lua_State* L) { + lua_pushstring(L, Config::Actions::state()->m_currentSubmap.c_str()); + return 1; +} + +void Internal::registerQueryBindings(lua_State* L) { + Internal::setFn(L, "get_windows", hlGetWindows); + Internal::setFn(L, "get_window", hlGetWindow); + Internal::setFn(L, "get_active_window", hlGetActiveWindow); + Internal::setFn(L, "get_urgent_window", hlGetUrgentWindow); + Internal::setFn(L, "get_workspaces", hlGetWorkspaces); + Internal::setFn(L, "get_workspace", hlGetWorkspace); + Internal::setFn(L, "get_active_workspace", hlGetActiveWorkspace); + Internal::setFn(L, "get_active_special_workspace", hlGetActiveSpecialWorkspace); + Internal::setFn(L, "get_monitors", hlGetMonitors); + Internal::setFn(L, "get_monitor", hlGetMonitor); + Internal::setFn(L, "get_active_monitor", hlGetActiveMonitor); + Internal::setFn(L, "get_monitor_at", hlGetMonitorAt); + Internal::setFn(L, "get_monitor_at_cursor", hlGetMonitorAtCursor); + Internal::setFn(L, "get_layers", hlGetLayers); + Internal::setFn(L, "get_workspace_windows", hlGetWorkspaceWindows); + Internal::setFn(L, "get_cursor_pos", hlGetCursorPos); + Internal::setFn(L, "get_last_window", hlGetLastWindow); + Internal::setFn(L, "get_last_workspace", hlGetLastWorkspace); + Internal::setFn(L, "get_current_submap", hlGetCurrentSubmap); +} diff --git a/src/config/lua/bindings/LuaBindingsRegistration.cpp b/src/config/lua/bindings/LuaBindingsRegistration.cpp new file mode 100644 index 00000000..ba6804a9 --- /dev/null +++ b/src/config/lua/bindings/LuaBindingsRegistration.cpp @@ -0,0 +1,66 @@ +#include "LuaBindingsInternal.hpp" + +#include "../objects/LuaEventSubscription.hpp" +#include "../objects/LuaKeybind.hpp" +#include "../objects/LuaLayerRule.hpp" +#include "../objects/LuaNotification.hpp" +#include "../objects/LuaTimer.hpp" +#include "../objects/LuaWindowRule.hpp" + +using namespace Config; +using namespace Config::Lua; +using namespace Config::Lua::Bindings; + +static int hlPrint(lua_State* L) { + const int n = lua_gettop(L); + std::string out; + for (int i = 1; i <= n; i++) { + size_t len = 0; + const char* s = luaL_tolstring(L, i, &len); + if (i > 1) + out += '\t'; + out.append(s, len); + lua_pop(L, 1); + } + Log::logger->log(Log::INFO, "[Lua] {}", out); + return 0; +} + +void Internal::registerBindingsImpl(lua_State* L, CConfigManager* mgr) { + Objects::CLuaTimer{}.setup(L); + Objects::CLuaEventSubscription{}.setup(L); + Objects::CLuaWindowRule{}.setup(L); + Objects::CLuaLayerRule{}.setup(L); + Objects::CLuaKeybind{}.setup(L); + Objects::CLuaNotification{}.setup(L); + + g_pKeybindManager->m_dispatchers["__lua"] = [L](std::string arg) -> SDispatchResult { + int ref = std::stoi(arg); + lua_rawgeti(L, LUA_REGISTRYINDEX, ref); + + int status = LUA_OK; + if (auto* mgr = CConfigManager::fromLuaState(L); mgr) + status = mgr->guardedPCall(0, 0, 0, CConfigManager::LUA_TIMEOUT_KEYBIND_CALLBACK_MS, "keybind callback"); + else + status = lua_pcall(L, 0, 0, 0); + + if (status != LUA_OK) { + Config::Lua::mgr()->addError(std::format("error in keybind lambda: {}", lua_tostring(L, -1))); + lua_pop(L, 1); + } + return {}; + }; + + lua_newtable(L); + + Internal::registerConfigRuleBindings(L, mgr); + Internal::registerToplevelBindings(L, mgr); + Internal::registerQueryBindings(L); + Internal::registerDispatcherBindings(L); + Internal::registerNotificationBindings(L); + + lua_setglobal(L, "hl"); + + lua_pushcfunction(L, hlPrint); + lua_setglobal(L, "print"); +} diff --git a/src/config/lua/bindings/LuaBindingsToplevel.cpp b/src/config/lua/bindings/LuaBindingsToplevel.cpp new file mode 100644 index 00000000..d099c0a8 --- /dev/null +++ b/src/config/lua/bindings/LuaBindingsToplevel.cpp @@ -0,0 +1,435 @@ +#include "LuaBindingsInternal.hpp" + +#include "../objects/LuaEventSubscription.hpp" +#include "../objects/LuaKeybind.hpp" +#include "../objects/LuaTimer.hpp" + +#include "../../supplementary/executor/Executor.hpp" + +#include "../../../devices/IKeyboard.hpp" +#include "../../../managers/eventLoop/EventLoopManager.hpp" + +#include +#include + +using namespace Config; +using namespace Config::Lua; +using namespace Config::Lua::Bindings; +using namespace Hyprutils::String; + +static std::optional modFromSv(std::string_view sv) { + if (sv == "SHIFT") + return HL_MODIFIER_SHIFT; + if (sv == "CAPS") + return HL_MODIFIER_CAPS; + if (sv == "CTRL" || sv == "CONTROL") + return HL_MODIFIER_CTRL; + if (sv == "ALT" || sv == "MOD1") + return HL_MODIFIER_ALT; + if (sv == "MOD2") + return HL_MODIFIER_MOD2; + if (sv == "MOD3") + return HL_MODIFIER_MOD3; + if (sv == "SUPER" || sv == "WIN" || sv == "LOGO" || sv == "MOD4" || sv == "META") + return HL_MODIFIER_META; + if (sv == "MOD5") + return HL_MODIFIER_MOD5; + + return std::nullopt; +} + +static bool isSymSpecial(std::string_view sv) { + if (sv == "mouse_down" || sv == "mouse_up" || sv == "mouse_left" || sv == "mouse_right") + return true; + + return sv.starts_with("switch:") || sv.starts_with("mouse:"); +} + +static std::expected parseKeyString(SKeybind& kb, std::string_view sv) { + bool modsEnded = false, specialSym = false; + CVarList2 vl(sv, 0, '+', true); + + uint32_t modMask = 0; + std::vector keysyms; + std::string lastKeyArg; + + if (sv == "catchall") { + kb.catchAll = true; + return {}; + } + + for (const auto& a : vl) { + auto arg = Hyprutils::String::trim(a); + + auto mask = modFromSv(arg); + + if (!mask) + modsEnded = true; + + if (modsEnded && mask) + return std::unexpected("Modifiers must come first in the list"); + + if (mask) { + modMask |= *mask; + continue; + } + + if (specialSym) + return std::unexpected("Cannot combine special syms (e.g. mouse_down + Q)"); + + if (isSymSpecial(arg)) { + if (!keysyms.empty()) + return std::unexpected("Cannot combine special syms (e.g. mouse_down + Q)"); + + specialSym = true; + kb.key = arg; + continue; + } + + auto sym = xkb_keysym_from_name(std::string{arg}.c_str(), XKB_KEYSYM_CASE_INSENSITIVE); + + if (sym == XKB_KEY_NoSymbol) { + if (arg.contains(' ')) + return std::unexpected(std::format("Unknown keysym: \"{}\", did you forget a +?", arg)); + + if (arg == "Enter") + return std::unexpected(std::format(R"(Unknown keysym: "{}", did you mean "Return"?)", arg)); + + return std::unexpected(std::format("Unknown keysym: \"{}\"", arg)); + } + + lastKeyArg = arg; + keysyms.emplace_back(sym); + } + + kb.modmask = modMask; + kb.sMkKeys = std::move(keysyms); + if (!specialSym && !lastKeyArg.empty()) + kb.key = lastKeyArg; + return {}; +} + +static int hlBind(lua_State* L) { + auto* mgr = sc(lua_touserdata(L, lua_upvalueindex(1))); + + std::string_view keys = luaL_checkstring(L, 1); + + SKeybind kb; + kb.submap.name = mgr->m_currentSubmap; + kb.submap.reset = mgr->m_currentSubmapReset; + + if (auto res = parseKeyString(kb, keys); !res) + return Internal::configError(L, std::format("hl.bind: failed to parse key string: {}", res.error())); + + if (!lua_isfunction(L, 2)) + return Internal::configError(L, "hl.bind: dispatcher must be a dispatcher (e.g. hl.dsp.window.close()) or a lua function"); + + if (kb.catchAll && mgr->m_currentSubmap.empty()) + return Internal::configError(L, "hl.bind: catchall keybinds are only allowed in submaps."); + + lua_pushvalue(L, 2); + int ref = luaL_ref(L, LUA_REGISTRYINDEX); + kb.handler = "__lua"; + kb.arg = std::to_string(ref); + kb.displayKey = keys; + + int optsIdx = 3; + + if (lua_istable(L, optsIdx)) { + auto getBool = [&](const char* field) -> bool { + lua_getfield(L, optsIdx, field); + const bool v = lua_toboolean(L, -1); + lua_pop(L, 1); + return v; + }; + + auto readOptString = [&](const char* field) -> std::optional { + lua_getfield(L, optsIdx, field); + + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + return std::nullopt; + } + + if (!lua_isstring(L, -1)) { + lua_pop(L, 1); + Internal::configError(L, "hl.bind: opts.{} must be a string", field); + return std::nullopt; + } + + std::string result = lua_tostring(L, -1); + lua_pop(L, 1); + return result; + }; + + kb.repeat = getBool("repeating"); + kb.locked = getBool("locked"); + kb.release = getBool("release"); + kb.nonConsuming = getBool("non_consuming"); + kb.transparent = getBool("transparent"); + kb.ignoreMods = getBool("ignore_mods"); + kb.dontInhibit = getBool("dont_inhibit"); + kb.longPress = getBool("long_press"); + kb.submapUniversal = getBool("submap_universal"); + + if (auto description = readOptString("description"); description.has_value()) { + kb.description = *description; + kb.hasDescription = true; + } else if (auto desc = readOptString("desc"); desc.has_value()) { + kb.description = *desc; + kb.hasDescription = true; + } + + bool click = false; + bool drag = false; + + if (getBool("click")) { + click = true; + kb.release = true; + } + + if (getBool("drag")) { + drag = true; + kb.release = true; + } + + if (click && drag) + return Internal::configError(L, "hl.bind: click and drag are exclusive"); + + if ((kb.longPress || kb.release) && kb.repeat) + return Internal::configError(L, "hl.bind: long_press / release is incompatible with repeat"); + + if (kb.mouse && (kb.repeat || kb.release || kb.locked)) + return Internal::configError(L, "hl.bind: mouse is exclusive"); + + kb.click = click; + kb.drag = drag; + + lua_getfield(L, optsIdx, "device"); + if (lua_istable(L, -1)) { + lua_getfield(L, -1, "inclusive"); + kb.deviceInclusive = lua_isnil(L, -1) ? true : lua_toboolean(L, -1); + lua_pop(L, 1); + + lua_getfield(L, -1, "list"); + if (lua_istable(L, -1)) { + lua_pushnil(L); + while (lua_next(L, -2)) { + if (lua_isstring(L, -1)) + kb.devices.emplace(lua_tostring(L, -1)); + lua_pop(L, 1); + } + } + lua_pop(L, 1); + } + lua_pop(L, 1); + } + + const auto BIND = g_pKeybindManager->addKeybind(kb); + Objects::CLuaKeybind::push(L, BIND); + return 1; +} + +static int hlDefineSubmap(lua_State* L) { + auto* mgr = sc(lua_touserdata(L, lua_upvalueindex(1))); + const char* name = luaL_checkstring(L, 1); + + std::string reset; + int fnIdx = 2; + if (lua_gettop(L) >= 3 && lua_isstring(L, 2)) { + reset = lua_tostring(L, 2); + fnIdx = 3; + } + + luaL_checktype(L, fnIdx, LUA_TFUNCTION); + + std::string prev = mgr->m_currentSubmap; + std::string prevReset = mgr->m_currentSubmapReset; + mgr->m_currentSubmap = name; + mgr->m_currentSubmapReset = reset; + + lua_pushvalue(L, fnIdx); + if (mgr->guardedPCall(0, 0, 0, CConfigManager::LUA_TIMEOUT_DISPATCH_MS, std::format("hl.define_submap(\"{}\")", name)) != LUA_OK) { + mgr->addError(std::format("hl.define_submap: error in submap \"{}\": {}", name, lua_tostring(L, -1))); + lua_pop(L, 1); + } + + mgr->m_currentSubmap = prev; + mgr->m_currentSubmapReset = prevReset; + return 0; +} + +static int hlVersion(lua_State* L) { + lua_pushstring(L, HYPRLAND_VERSION); + return 1; +} + +static int hlExecCmd(lua_State* L) { + auto cmd = Internal::argStr(L, 1); + + if (cmd.empty()) + return Internal::configError(L, "hl.exec_cmd: expected command as first argument"); + + auto rule = Internal::buildRuleFromTable(L, 2); + + if (!rule) + return rule.error(); + + Config::Supplementary::executor()->spawn(Supplementary::SExecRequest{cmd, !*rule, *rule}); + + return 0; +} + +static int hlDispatch(lua_State* L) { + if (!lua_isfunction(L, 1)) + return Internal::configError(L, "hl.dispatch: expected a dispatcher function (e.g. hl.dsp.window.close())"); + + lua_pushvalue(L, 1); + int status = LUA_OK; + if (auto* mgr = CConfigManager::fromLuaState(L); mgr) + status = mgr->guardedPCall(0, 0, 0, CConfigManager::LUA_TIMEOUT_DISPATCH_MS, "hl.dispatch"); + else + status = lua_pcall(L, 0, 0, 0); + + if (status != LUA_OK) { + const char* err = lua_tostring(L, -1); + lua_pop(L, 1); + return Internal::configError(L, "hl.dispatch: {}", err ? err : "unknown error"); + } + + return 0; +} + +static int hlOn(lua_State* L) { + auto* mgr = sc(lua_touserdata(L, lua_upvalueindex(1))); + const char* eventName = luaL_checkstring(L, 1); + luaL_checktype(L, 2, LUA_TFUNCTION); + + lua_pushvalue(L, 2); + int ref = luaL_ref(L, LUA_REGISTRYINDEX); + + const auto handle = mgr->m_eventHandler->registerEvent(eventName, ref); + if (!handle.has_value()) { + luaL_unref(L, LUA_REGISTRYINDEX, ref); + const auto& known = CLuaEventHandler::knownEvents(); + std::string list; + for (const auto& e : known) { + list += e + ", "; + } + list.pop_back(); + list.pop_back(); + return Internal::configError(L, "hl.on: unknown event \"{}\". Known events:{}", eventName, list); + } + + Objects::CLuaEventSubscription::push(L, mgr->m_eventHandler.get(), *handle); + return 1; +} + +static int hlUnbind(lua_State* L) { + if (lua_isstring(L, 1) && std::string_view(lua_tostring(L, 1)) == "all" && lua_gettop(L) == 1) { + g_pKeybindManager->clearKeybinds(); + return 0; + } + + const char* mods = luaL_checkstring(L, 1); + const char* keyStr = luaL_checkstring(L, 2); + + uint32_t mod = g_pKeybindManager->stringToModMask(mods); + + SParsedKey key; + std::string k = keyStr; + if (Hyprutils::String::isNumber(k) && std::stoi(k) > 9) + key = {.keycode = (uint32_t)std::stoi(k)}; + else if (k.starts_with("code:") && Hyprutils::String::isNumber(k.substr(5))) + key = {.keycode = (uint32_t)std::stoi(k.substr(5))}; + else if (k == "catchall") + key = {.catchAll = true}; + else + key = {.key = k}; + + g_pKeybindManager->removeKeybind(mod, key); + return 0; +} + +static int hlTimer(lua_State* L) { + auto* mgr = sc(lua_touserdata(L, lua_upvalueindex(1))); + + luaL_checktype(L, 1, LUA_TFUNCTION); + luaL_checktype(L, 2, LUA_TTABLE); + + lua_getfield(L, 2, "timeout"); + if (!lua_isnumber(L, -1)) + return Internal::configError(L, "hl.timer: opts.timeout must be a number (ms)"); + int timeoutMs = (int)lua_tonumber(L, -1); + lua_pop(L, 1); + + if (timeoutMs <= 0) + return Internal::configError(L, "hl.timer: opts.timeout must be > 0"); + + lua_getfield(L, 2, "type"); + if (!lua_isstring(L, -1)) + return Internal::configError(L, "hl.timer: opts.type must be \"repeat\" or \"oneshot\""); + std::string type = lua_tostring(L, -1); + lua_pop(L, 1); + + bool repeat = false; + if (type == "repeat") + repeat = true; + else if (type != "oneshot") + return Internal::configError(L, "hl.timer: opts.type must be \"repeat\" or \"oneshot\""); + + lua_pushvalue(L, 1); + int ref = luaL_ref(L, LUA_REGISTRYINDEX); + + auto timer = makeShared( + std::chrono::milliseconds(timeoutMs), + [L, ref, repeat, timeoutMs, mgr](SP self, void* data) { + // update repeat already so that if we call set_timeout inside + // our timer it doesn't get overwritten + if (repeat) + self->updateTimeout(std::chrono::milliseconds(timeoutMs)); + + lua_rawgeti(L, LUA_REGISTRYINDEX, ref); + int status = LUA_OK; + if (mgr) + status = mgr->guardedPCall(0, 0, 0, CConfigManager::LUA_TIMEOUT_TIMER_CALLBACK_MS, "hl.timer callback"); + else + status = lua_pcall(L, 0, 0, 0); + + if (status != LUA_OK) { + Log::logger->log(Log::ERR, "[Lua] error in timer callback: {}", lua_tostring(L, -1)); + lua_pop(L, 1); + } + + if (!repeat) { + const auto HAS = std::ranges::find_if(mgr->m_luaTimers, [&self](const auto& lt) { return lt.timer == self; }) != mgr->m_luaTimers.end(); + + // avoid double-unref if this timer triggered a reload + if (HAS) { + luaL_unref(L, LUA_REGISTRYINDEX, ref); + std::erase_if(mgr->m_luaTimers, [&self](const auto& lt) { return lt.timer == self; }); + } + } + }, + nullptr); + + mgr->m_luaTimers.emplace_back(CConfigManager::SLuaTimer{timer, ref}); + if (g_pEventLoopManager) + g_pEventLoopManager->addTimer(timer); + + Objects::CLuaTimer::push(L, timer, timeoutMs); + return 1; +} + +void Internal::registerToplevelBindings(lua_State* L, CConfigManager* mgr) { + Internal::setMgrFn(L, mgr, "on", hlOn); + Internal::setMgrFn(L, mgr, "bind", hlBind); + Internal::setMgrFn(L, mgr, "define_submap", hlDefineSubmap); + Internal::setMgrFn(L, mgr, "timer", hlTimer); + + Internal::setFn(L, "dispatch", hlDispatch); + Internal::setFn(L, "version", hlVersion); + Internal::setFn(L, "exec_cmd", hlExecCmd); + + Internal::setFn(L, "unbind", hlUnbind); +} diff --git a/src/config/lua/objects/LuaEventSubscription.cpp b/src/config/lua/objects/LuaEventSubscription.cpp new file mode 100644 index 00000000..c37491d7 --- /dev/null +++ b/src/config/lua/objects/LuaEventSubscription.cpp @@ -0,0 +1,74 @@ +#include "LuaEventSubscription.hpp" + +#include +#include + +using namespace Config::Lua; + +static constexpr const char* MT = "HL.EventSubscription"; + +namespace { + struct SEventSubscriptionRef { + CLuaEventHandler* handler = nullptr; + uint64_t handle = 0; + bool active = false; + }; +} + +static int eventSubscriptionEq(lua_State* L) { + const auto* lhs = sc(luaL_checkudata(L, 1, MT)); + const auto* rhs = sc(luaL_checkudata(L, 2, MT)); + + lua_pushboolean(L, lhs->handler == rhs->handler && lhs->handle == rhs->handle); + return 1; +} + +static int eventSubscriptionToString(lua_State* L) { + const auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto str = std::format("HL.EventSubscription({},{})", ref->handle, ref->active ? "active" : "inactive"); + lua_pushstring(L, str.c_str()); + return 1; +} + +static int eventSubscriptionRemove(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + if (!ref->active || !ref->handler) + return 0; + + ref->handler->unregisterEvent(ref->handle); + ref->active = false; + return 0; +} + +static int eventSubscriptionIsActive(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + lua_pushboolean(L, ref->active); + return 1; +} + +static int eventSubscriptionIndex(lua_State* L) { + luaL_checkudata(L, 1, MT); + const std::string_view key = luaL_checkstring(L, 2); + + if (key == "remove") + lua_pushcfunction(L, eventSubscriptionRemove); + else if (key == "is_active") + lua_pushcfunction(L, eventSubscriptionIsActive); + else + lua_pushnil(L); + + return 1; +} + +void Objects::CLuaEventSubscription::setup(lua_State* L) { + registerMetatable(L, MT, eventSubscriptionIndex, gcRef, eventSubscriptionEq, eventSubscriptionToString); +} + +void Objects::CLuaEventSubscription::push(lua_State* L, CLuaEventHandler* handler, uint64_t handle) { + new (lua_newuserdata(L, sizeof(SEventSubscriptionRef))) SEventSubscriptionRef{.handler = handler, .handle = handle, .active = true}; + luaL_getmetatable(L, MT); + lua_setmetatable(L, -2); +} diff --git a/src/config/lua/objects/LuaEventSubscription.hpp b/src/config/lua/objects/LuaEventSubscription.hpp new file mode 100644 index 00000000..11cdfc62 --- /dev/null +++ b/src/config/lua/objects/LuaEventSubscription.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include "LuaObjectHelpers.hpp" +#include "../LuaEventHandler.hpp" + +namespace Config::Lua::Objects { + class CLuaEventSubscription : public ILuaObjectWrapper { + public: + void setup(lua_State* L) override; + static void push(lua_State* L, CLuaEventHandler* handler, uint64_t handle); + }; +} diff --git a/src/config/lua/objects/LuaKeybind.cpp b/src/config/lua/objects/LuaKeybind.cpp new file mode 100644 index 00000000..aab2735d --- /dev/null +++ b/src/config/lua/objects/LuaKeybind.cpp @@ -0,0 +1,180 @@ +#include "LuaKeybind.hpp" + +#include +#include + +using namespace Config::Lua; + +static constexpr const char* MT = "HL.Keybind"; + +namespace { + std::optional> getKeybindFromUserdata(lua_State* L) { + auto* ref = sc*>(luaL_checkudata(L, 1, MT)); + return ref->lock(); + } + + void pushDeviceList(lua_State* L, const SKeybind& keybind) { + lua_newtable(L); + int i = 1; + for (const auto& device : keybind.devices) { + lua_pushstring(L, device.c_str()); + lua_rawseti(L, -2, i++); + } + } +} + +static int keybindEq(lua_State* L) { + const auto* lhs = sc*>(luaL_checkudata(L, 1, MT)); + const auto* rhs = sc*>(luaL_checkudata(L, 2, MT)); + + lua_pushboolean(L, lhs->lock() == rhs->lock()); + return 1; +} + +static int keybindToString(lua_State* L) { + const auto* ref = sc*>(luaL_checkudata(L, 1, MT)); + const auto keybind = ref->lock(); + + if (!keybind) + lua_pushstring(L, "HL.Keybind(expired)"); + else + lua_pushfstring(L, "HL.Keybind(%p)", keybind.get()); + + return 1; +} + +static int keybindSetEnabled(lua_State* L) { + luaL_checktype(L, 2, LUA_TBOOLEAN); + + const auto keybind = getKeybindFromUserdata(L); + if (!keybind) + return 0; + + (*keybind)->enabled = lua_toboolean(L, 2); + return 0; +} + +static int keybindIsEnabled(lua_State* L) { + const auto keybind = getKeybindFromUserdata(L); + if (!keybind) { + lua_pushnil(L); + return 1; + } + + lua_pushboolean(L, (*keybind)->enabled); + return 1; +} + +static int keybindRemove(lua_State* L) { + const auto keybind = getKeybindFromUserdata(L); + if (!keybind || !g_pKeybindManager) + return 0; + + if ((*keybind)->handler == "__lua") { + try { + const int ref = std::stoi((*keybind)->arg); + if (ref > 0) + luaL_unref(L, LUA_REGISTRYINDEX, ref); + } catch (...) { + // invalid ref, ignore + } + + (*keybind)->arg = std::to_string(LUA_NOREF); + } + + g_pKeybindManager->removeKeybind((*keybind)->modmask, SParsedKey{.key = (*keybind)->key, .keycode = (*keybind)->keycode, .catchAll = (*keybind)->catchAll}); + return 0; +} + +static int keybindGetDescription(lua_State* L) { + const auto keybind = getKeybindFromUserdata(L); + if (!keybind) { + lua_pushnil(L); + return 1; + } + + if (!(*keybind)->hasDescription) + lua_pushnil(L); + else + lua_pushstring(L, (*keybind)->description.c_str()); + + return 1; +} + +static int keybindIndex(lua_State* L) { + const auto keybind = getKeybindFromUserdata(L); + const std::string_view key = luaL_checkstring(L, 2); + + if (key == "set_enabled") + lua_pushcfunction(L, keybindSetEnabled); + else if (key == "is_enabled") + lua_pushcfunction(L, keybindIsEnabled); + else if (key == "remove" || key == "unbind") + lua_pushcfunction(L, keybindRemove); + else if (!keybind) + lua_pushnil(L); + else if (key == "enabled") + lua_pushboolean(L, (*keybind)->enabled); + else if (key == "has_description") + lua_pushboolean(L, (*keybind)->hasDescription); + else if (key == "description") + return keybindGetDescription(L); + else if (key == "display_key") + lua_pushstring(L, (*keybind)->displayKey.c_str()); + else if (key == "submap") + lua_pushstring(L, (*keybind)->submap.name.c_str()); + else if (key == "handler") + lua_pushstring(L, (*keybind)->handler.c_str()); + else if (key == "arg") + lua_pushstring(L, (*keybind)->arg.c_str()); + else if (key == "modmask") + lua_pushinteger(L, sc((*keybind)->modmask)); + else if (key == "key") + lua_pushstring(L, (*keybind)->key.c_str()); + else if (key == "keycode") + lua_pushinteger(L, sc((*keybind)->keycode)); + else if (key == "catchall") + lua_pushboolean(L, (*keybind)->catchAll); + else if (key == "repeating") + lua_pushboolean(L, (*keybind)->repeat); + else if (key == "locked") + lua_pushboolean(L, (*keybind)->locked); + else if (key == "release") + lua_pushboolean(L, (*keybind)->release); + else if (key == "non_consuming") + lua_pushboolean(L, (*keybind)->nonConsuming); + else if (key == "transparent") + lua_pushboolean(L, (*keybind)->transparent); + else if (key == "ignore_mods") + lua_pushboolean(L, (*keybind)->ignoreMods); + else if (key == "long_press") + lua_pushboolean(L, (*keybind)->longPress); + else if (key == "dont_inhibit") + lua_pushboolean(L, (*keybind)->dontInhibit); + else if (key == "click") + lua_pushboolean(L, (*keybind)->click); + else if (key == "drag") + lua_pushboolean(L, (*keybind)->drag); + else if (key == "submap_universal") + lua_pushboolean(L, (*keybind)->submapUniversal); + else if (key == "mouse") + lua_pushboolean(L, (*keybind)->mouse); + else if (key == "device_inclusive") + lua_pushboolean(L, (*keybind)->deviceInclusive); + else if (key == "devices") + pushDeviceList(L, **keybind); + else + lua_pushnil(L); + + return 1; +} + +void Objects::CLuaKeybind::setup(lua_State* L) { + registerMetatable(L, MT, keybindIndex, gcRef>, keybindEq, keybindToString); +} + +void Objects::CLuaKeybind::push(lua_State* L, const SP& keybind) { + new (lua_newuserdata(L, sizeof(WP))) WP(keybind); + luaL_getmetatable(L, MT); + lua_setmetatable(L, -2); +} diff --git a/src/config/lua/objects/LuaKeybind.hpp b/src/config/lua/objects/LuaKeybind.hpp new file mode 100644 index 00000000..c55ed998 --- /dev/null +++ b/src/config/lua/objects/LuaKeybind.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include "LuaObjectHelpers.hpp" +#include "../../../managers/KeybindManager.hpp" + +namespace Config::Lua::Objects { + class CLuaKeybind : public ILuaObjectWrapper { + public: + void setup(lua_State* L) override; + static void push(lua_State* L, const SP& keybind); + }; +} diff --git a/src/config/lua/objects/LuaLayerRule.cpp b/src/config/lua/objects/LuaLayerRule.cpp new file mode 100644 index 00000000..22e06272 --- /dev/null +++ b/src/config/lua/objects/LuaLayerRule.cpp @@ -0,0 +1,80 @@ +#include "LuaLayerRule.hpp" + +#include "../../../desktop/rule/Engine.hpp" + +#include + +using namespace Config::Lua; + +static constexpr const char* MT = "HL.LayerRule"; + +// +static int layerRuleEq(lua_State* L) { + const auto* lhs = sc*>(luaL_checkudata(L, 1, MT)); + const auto* rhs = sc*>(luaL_checkudata(L, 2, MT)); + + lua_pushboolean(L, lhs->lock() == rhs->lock()); + return 1; +} + +static int layerRuleToString(lua_State* L) { + const auto* ref = sc*>(luaL_checkudata(L, 1, MT)); + const auto rule = ref->lock(); + + if (!rule) + lua_pushstring(L, "HL.LayerRule(expired)"); + else + lua_pushfstring(L, "HL.LayerRule(%p)", rule.get()); + + return 1; +} + +static int layerRuleSetEnabled(lua_State* L) { + auto* ref = sc*>(luaL_checkudata(L, 1, MT)); + luaL_checktype(L, 2, LUA_TBOOLEAN); + + const auto rule = ref->lock(); + if (!rule) + return 0; + + rule->setEnabled(lua_toboolean(L, 2)); + Desktop::Rule::ruleEngine()->updateAllRules(); + return 0; +} + +static int layerRuleIsEnabled(lua_State* L) { + auto* ref = sc*>(luaL_checkudata(L, 1, MT)); + + const auto rule = ref->lock(); + if (!rule) { + lua_pushnil(L); + return 1; + } + + lua_pushboolean(L, rule->isEnabled()); + return 1; +} + +static int layerRuleIndex(lua_State* L) { + luaL_checkudata(L, 1, MT); + const std::string_view key = luaL_checkstring(L, 2); + + if (key == "set_enabled") + lua_pushcfunction(L, layerRuleSetEnabled); + else if (key == "is_enabled") + lua_pushcfunction(L, layerRuleIsEnabled); + else + lua_pushnil(L); + + return 1; +} + +void Objects::CLuaLayerRule::setup(lua_State* L) { + registerMetatable(L, MT, layerRuleIndex, gcRef>, layerRuleEq, layerRuleToString); +} + +void Objects::CLuaLayerRule::push(lua_State* L, const SP& rule) { + new (lua_newuserdata(L, sizeof(WP))) WP(rule); + luaL_getmetatable(L, MT); + lua_setmetatable(L, -2); +} diff --git a/src/config/lua/objects/LuaLayerRule.hpp b/src/config/lua/objects/LuaLayerRule.hpp new file mode 100644 index 00000000..2e4d24e7 --- /dev/null +++ b/src/config/lua/objects/LuaLayerRule.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include "LuaObjectHelpers.hpp" +#include "../../../desktop/rule/layerRule/LayerRule.hpp" + +namespace Config::Lua::Objects { + class CLuaLayerRule : public ILuaObjectWrapper { + public: + void setup(lua_State* L) override; + static void push(lua_State* L, const SP& rule); + }; +} diff --git a/src/config/lua/objects/LuaLayerSurface.cpp b/src/config/lua/objects/LuaLayerSurface.cpp new file mode 100644 index 00000000..99b22154 --- /dev/null +++ b/src/config/lua/objects/LuaLayerSurface.cpp @@ -0,0 +1,88 @@ +#include "LuaLayerSurface.hpp" +#include "LuaMonitor.hpp" +#include "LuaObjectHelpers.hpp" + +#include "../../../desktop/view/LayerSurface.hpp" + +#include +#include + +using namespace Config::Lua; + +static constexpr const char* MT = "HL.LayerSurface"; + +// +static int layerSurfaceEq(lua_State* L) { + const auto* lhs = sc(luaL_checkudata(L, 1, MT)); + const auto* rhs = sc(luaL_checkudata(L, 2, MT)); + + lua_pushboolean(L, lhs->lock() == rhs->lock()); + return 1; +} + +static int layerSurfaceToString(lua_State* L) { + const auto* ref = sc(luaL_checkudata(L, 1, MT)); + const auto ls = ref->lock(); + + if (!ls) + lua_pushstring(L, "HL.LayerSurface(expired)"); + else + lua_pushfstring(L, "HL.LayerSurface(%p)", ls.get()); + + return 1; +} + +static int layerSurfaceIndex(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + const auto ls = ref->lock(); + if (!ls) { + Log::logger->log(Log::DEBUG, "[lua] Tried to access an expired object"); + lua_pushnil(L); + return 1; + } + + const std::string_view key = luaL_checkstring(L, 2); + + if (key == "address") + lua_pushstring(L, std::format("0x{:x}", reinterpret_cast(ls.get())).c_str()); + else if (key == "x") + lua_pushinteger(L, ls->m_geometry.x); + else if (key == "y") + lua_pushinteger(L, ls->m_geometry.y); + else if (key == "w") + lua_pushinteger(L, ls->m_geometry.width); + else if (key == "h") + lua_pushinteger(L, ls->m_geometry.height); + else if (key == "namespace") + lua_pushstring(L, ls->m_namespace.c_str()); + else if (key == "pid") + lua_pushinteger(L, sc(ls->getPID())); + else if (key == "monitor") { + const auto mon = ls->m_monitor.lock(); + if (mon) + Objects::CLuaMonitor::push(L, mon); + else + lua_pushnil(L); + } else if (key == "mapped") + lua_pushboolean(L, ls->m_mapped); + else if (key == "layer") + lua_pushinteger(L, sc(ls->m_layer)); + else if (key == "interactivity") + lua_pushinteger(L, sc(ls->m_interactivity)); + else if (key == "above_fullscreen") + lua_pushboolean(L, ls->m_aboveFullscreen); + else + lua_pushnil(L); + + return 1; +} + +void Objects::CLuaLayerSurface::setup(lua_State* L) { + registerMetatable(L, MT, layerSurfaceIndex, gcRef, layerSurfaceEq, layerSurfaceToString); +} + +void Objects::CLuaLayerSurface::push(lua_State* L, PHLLS ls) { + new (lua_newuserdata(L, sizeof(PHLLSREF))) PHLLSREF(ls ? ls->m_self : nullptr); + luaL_getmetatable(L, MT); + lua_setmetatable(L, -2); +} diff --git a/src/config/lua/objects/LuaLayerSurface.hpp b/src/config/lua/objects/LuaLayerSurface.hpp new file mode 100644 index 00000000..bfbd93e7 --- /dev/null +++ b/src/config/lua/objects/LuaLayerSurface.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include "LuaObjectHelpers.hpp" +#include "../../../desktop/DesktopTypes.hpp" + +namespace Config::Lua::Objects { + class CLuaLayerSurface : public ILuaObjectWrapper { + public: + void setup(lua_State* L) override; + static void push(lua_State* L, PHLLS ls); + }; +} diff --git a/src/config/lua/objects/LuaMonitor.cpp b/src/config/lua/objects/LuaMonitor.cpp new file mode 100644 index 00000000..9d0701c1 --- /dev/null +++ b/src/config/lua/objects/LuaMonitor.cpp @@ -0,0 +1,122 @@ +#include "LuaMonitor.hpp" +#include "LuaWorkspace.hpp" +#include "LuaObjectHelpers.hpp" + +#include "../../../helpers/Monitor.hpp" +#include "../../../desktop/state/FocusState.hpp" + +#include + +using namespace Config::Lua; + +static constexpr const char* MT = "HL.Monitor"; + +// +static int monitorEq(lua_State* L) { + const auto* lhs = sc(luaL_checkudata(L, 1, MT)); + const auto* rhs = sc(luaL_checkudata(L, 2, MT)); + + lua_pushboolean(L, lhs->lock() == rhs->lock()); + return 1; +} + +static int monitorToString(lua_State* L) { + const auto* ref = sc(luaL_checkudata(L, 1, MT)); + const auto mon = ref->lock(); + + if (!mon) + lua_pushstring(L, "HL.Monitor(expired)"); + else + lua_pushfstring(L, "HL.Monitor(%d:%s)", mon->m_id, mon->m_name.c_str()); + + return 1; +} + +static int monitorIndex(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + const auto mon = ref->lock(); + if (!mon) { + Log::logger->log(Log::DEBUG, "[lua] Tried to access an expired object"); + lua_pushnil(L); + return 1; + } + + const std::string_view key = luaL_checkstring(L, 2); + + if (key == "id") + lua_pushinteger(L, sc(mon->m_id)); + else if (key == "name") + lua_pushstring(L, mon->m_name.c_str()); + else if (key == "description") + lua_pushstring(L, mon->m_shortDescription.c_str()); + else if (key == "width") + lua_pushinteger(L, sc(mon->m_pixelSize.x)); + else if (key == "height") + lua_pushinteger(L, sc(mon->m_pixelSize.y)); + else if (key == "refresh_rate") + lua_pushnumber(L, mon->m_refreshRate); + else if (key == "x") + lua_pushinteger(L, sc(mon->m_position.x)); + else if (key == "y") + lua_pushinteger(L, sc(mon->m_position.y)); + else if (key == "active_workspace") { + if (mon->m_activeWorkspace) + Objects::CLuaWorkspace::push(L, mon->m_activeWorkspace); + else + lua_pushnil(L); + } else if (key == "active_special_workspace") { + if (mon->m_activeSpecialWorkspace) + Objects::CLuaWorkspace::push(L, mon->m_activeSpecialWorkspace); + else + lua_pushnil(L); + } else if (key == "position") { + lua_newtable(L); + lua_pushinteger(L, sc(mon->m_position.x)); + lua_setfield(L, -2, "x"); + lua_pushinteger(L, sc(mon->m_position.y)); + lua_setfield(L, -2, "y"); + } else if (key == "size") { + lua_newtable(L); + lua_pushinteger(L, sc(mon->m_pixelSize.x)); + lua_setfield(L, -2, "width"); + lua_pushinteger(L, sc(mon->m_pixelSize.y)); + lua_setfield(L, -2, "height"); + } else if (key == "scale") + lua_pushnumber(L, mon->m_scale); + else if (key == "transform") + lua_pushinteger(L, sc(mon->m_transform)); + else if (key == "dpms_status") + lua_pushboolean(L, mon->m_dpmsStatus); + else if (key == "vrr_active") + lua_pushboolean(L, mon->m_vrrActive); + else if (key == "is_mirror") + lua_pushboolean(L, mon->isMirror()); + else if (key == "mirrors") { + lua_newtable(L); + + int i = 1; + for (const auto& mirrorRef : mon->m_mirrors) { + const auto mirror = mirrorRef.lock(); + if (!mirror) + continue; + + Objects::CLuaMonitor::push(L, mirror); + lua_rawseti(L, -2, i++); + } + } else if (key == "focused") + lua_pushboolean(L, mon == Desktop::focusState()->monitor()); + else + lua_pushnil(L); + + return 1; +} + +void Objects::CLuaMonitor::setup(lua_State* L) { + registerMetatable(L, MT, monitorIndex, gcRef, monitorEq, monitorToString); +} + +void Objects::CLuaMonitor::push(lua_State* L, PHLMONITOR mon) { + new (lua_newuserdata(L, sizeof(PHLMONITORREF))) PHLMONITORREF(mon ? mon->m_self : nullptr); + luaL_getmetatable(L, MT); + lua_setmetatable(L, -2); +} diff --git a/src/config/lua/objects/LuaMonitor.hpp b/src/config/lua/objects/LuaMonitor.hpp new file mode 100644 index 00000000..585d51e8 --- /dev/null +++ b/src/config/lua/objects/LuaMonitor.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include "LuaObjectHelpers.hpp" +#include "../../../desktop/DesktopTypes.hpp" + +namespace Config::Lua::Objects { + class CLuaMonitor : public ILuaObjectWrapper { + public: + void setup(lua_State* L) override; + static void push(lua_State* L, PHLMONITOR mon); + }; +} diff --git a/src/config/lua/objects/LuaNotification.cpp b/src/config/lua/objects/LuaNotification.cpp new file mode 100644 index 00000000..f116e2eb --- /dev/null +++ b/src/config/lua/objects/LuaNotification.cpp @@ -0,0 +1,377 @@ +#include "LuaNotification.hpp" + +#include "../../../helpers/MiscFunctions.hpp" + +#include +#include +#include +#include +#include + +using namespace Config::Lua; + +static constexpr const char* MT = "HL.Notification"; + +namespace { + struct SNotificationRef { + WP notification; + bool paused = false; + }; + + std::optional parseColor(lua_State* L, int idx) { + if (lua_isnumber(L, idx)) + return CHyprColor(sc(lua_tonumber(L, idx))); + + if (lua_isstring(L, idx)) { + auto parsed = configStringToInt(lua_tostring(L, idx)); + if (!parsed) + return std::nullopt; + + return CHyprColor(sc(*parsed)); + } + + return std::nullopt; + } + + std::optional iconFromString(std::string iconName) { + std::ranges::transform(iconName, iconName.begin(), [](const unsigned char c) { return std::tolower(c); }); + + static constexpr std::array, 10> ICON_NAMES = { + std::pair{"warning", ICON_WARNING}, std::pair{"warn", ICON_WARNING}, std::pair{"info", ICON_INFO}, std::pair{"hint", ICON_HINT}, + std::pair{"error", ICON_ERROR}, std::pair{"err", ICON_ERROR}, std::pair{"confused", ICON_CONFUSED}, std::pair{"question", ICON_CONFUSED}, + std::pair{"ok", ICON_OK}, std::pair{"none", ICON_NONE}, + }; + + for (const auto& [name, icon] : ICON_NAMES) { + if (name == iconName) + return icon; + } + + return std::nullopt; + } + + std::optional parseIcon(lua_State* L, int idx) { + if (lua_isnumber(L, idx)) { + const auto raw = sc(lua_tonumber(L, idx)); + if (raw >= ICON_WARNING && raw <= ICON_NONE) + return sc(raw); + + return std::nullopt; + } + + if (lua_isstring(L, idx)) + return iconFromString(lua_tostring(L, idx)); + + return std::nullopt; + } +} + +static int notificationEq(lua_State* L) { + const auto* lhs = sc(luaL_checkudata(L, 1, MT)); + const auto* rhs = sc(luaL_checkudata(L, 2, MT)); + + lua_pushboolean(L, lhs->notification.lock() == rhs->notification.lock()); + return 1; +} + +static int notificationToString(lua_State* L) { + const auto* ref = sc(luaL_checkudata(L, 1, MT)); + const auto notification = ref->notification.lock(); + + if (!notification) + lua_pushstring(L, "HL.Notification(expired)"); + else + lua_pushfstring(L, "HL.Notification(%p)", notification.get()); + + return 1; +} + +static int notificationGC(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + if (ref->paused) { + if (const auto notification = ref->notification.lock(); notification) + notification->unlock(); + } + + ref->~SNotificationRef(); + return 0; +} + +static int notificationPause(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto notification = ref->notification.lock(); + if (!notification) + return 0; + + if (ref->paused) + return 0; + + notification->lock(); + ref->paused = true; + return 0; +} + +static int notificationResume(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto notification = ref->notification.lock(); + if (!notification) + return 0; + + if (!ref->paused) + return 0; + + notification->unlock(); + ref->paused = false; + return 0; +} + +static int notificationSetPaused(lua_State* L) { + luaL_checkudata(L, 1, MT); + luaL_checktype(L, 2, LUA_TBOOLEAN); + + if (lua_toboolean(L, 2)) + return notificationPause(L); + + return notificationResume(L); +} + +static int notificationIsPaused(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto notification = ref->notification.lock(); + if (!notification) { + lua_pushnil(L); + return 1; + } + + lua_pushboolean(L, notification->isLocked()); + return 1; +} + +static int notificationSetText(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + const auto* text = luaL_checkstring(L, 2); + + if (const auto notification = ref->notification.lock(); notification) + notification->setText(text); + + return 0; +} + +static int notificationSetTimeout(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto timeoutMs = sc(luaL_checknumber(L, 2)); + if (timeoutMs < 0.F) + return Config::Lua::Bindings::Internal::configError(L, "HL.Notification:set_timeout: timeout must be >= 0"); + + if (const auto notification = ref->notification.lock(); notification) + notification->resetTimeout(timeoutMs); + + return 0; +} + +static int notificationSetColor(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto color = parseColor(L, 2); + if (!color) + return Config::Lua::Bindings::Internal::configError(L, "HL.Notification:set_color: expected a color string or number"); + + if (const auto notification = ref->notification.lock(); notification) + notification->setColor(*color); + + return 0; +} + +static int notificationSetIcon(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto icon = parseIcon(L, 2); + if (!icon) + return Config::Lua::Bindings::Internal::configError(L, "HL.Notification:set_icon: expected an icon name or number"); + + if (const auto notification = ref->notification.lock(); notification) + notification->setIcon(*icon); + + return 0; +} + +static int notificationSetFontSize(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto fontSize = sc(luaL_checknumber(L, 2)); + if (fontSize <= 0.F) + return Config::Lua::Bindings::Internal::configError(L, "HL.Notification:set_font_size: font size must be > 0"); + + if (const auto notification = ref->notification.lock(); notification) + notification->setFontSize(fontSize); + + return 0; +} + +static int notificationDismiss(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + if (const auto notification = ref->notification.lock(); notification) + Notification::overlay()->dismissNotification(notification); + + return 0; +} + +static int notificationGetText(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto notification = ref->notification.lock(); + if (!notification) { + lua_pushnil(L); + return 1; + } + + lua_pushstring(L, notification->text().c_str()); + return 1; +} + +static int notificationGetTimeout(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto notification = ref->notification.lock(); + if (!notification) { + lua_pushnil(L); + return 1; + } + + lua_pushnumber(L, notification->timeMs()); + return 1; +} + +static int notificationGetColor(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto notification = ref->notification.lock(); + if (!notification) { + lua_pushnil(L); + return 1; + } + + lua_pushinteger(L, sc(notification->color().getAsHex())); + return 1; +} + +static int notificationGetIcon(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto notification = ref->notification.lock(); + if (!notification) { + lua_pushnil(L); + return 1; + } + + lua_pushinteger(L, sc(notification->icon())); + return 1; +} + +static int notificationGetFontSize(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto notification = ref->notification.lock(); + if (!notification) { + lua_pushnil(L); + return 1; + } + + lua_pushnumber(L, notification->fontSize()); + return 1; +} + +static int notificationGetElapsed(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto notification = ref->notification.lock(); + if (!notification) { + lua_pushnil(L); + return 1; + } + + lua_pushnumber(L, notification->timeElapsedMs()); + return 1; +} + +static int notificationGetElapsedSinceCreation(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto notification = ref->notification.lock(); + if (!notification) { + lua_pushnil(L); + return 1; + } + + lua_pushnumber(L, notification->timeElapsedSinceCreationMs()); + return 1; +} + +static int notificationIsAlive(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + lua_pushboolean(L, ref->notification.lock().get() != nullptr); + return 1; +} + +static int notificationIndex(lua_State* L) { + luaL_checkudata(L, 1, MT); + const std::string_view key = luaL_checkstring(L, 2); + + if (key == "pause") + lua_pushcfunction(L, notificationPause); + else if (key == "resume") + lua_pushcfunction(L, notificationResume); + else if (key == "set_paused") + lua_pushcfunction(L, notificationSetPaused); + else if (key == "is_paused") + lua_pushcfunction(L, notificationIsPaused); + else if (key == "set_text") + lua_pushcfunction(L, notificationSetText); + else if (key == "set_timeout") + lua_pushcfunction(L, notificationSetTimeout); + else if (key == "set_color") + lua_pushcfunction(L, notificationSetColor); + else if (key == "set_icon") + lua_pushcfunction(L, notificationSetIcon); + else if (key == "set_font_size") + lua_pushcfunction(L, notificationSetFontSize); + else if (key == "dismiss") + lua_pushcfunction(L, notificationDismiss); + else if (key == "get_text") + lua_pushcfunction(L, notificationGetText); + else if (key == "get_timeout") + lua_pushcfunction(L, notificationGetTimeout); + else if (key == "get_color") + lua_pushcfunction(L, notificationGetColor); + else if (key == "get_icon") + lua_pushcfunction(L, notificationGetIcon); + else if (key == "get_font_size") + lua_pushcfunction(L, notificationGetFontSize); + else if (key == "get_elapsed") + lua_pushcfunction(L, notificationGetElapsed); + else if (key == "get_elapsed_since_creation") + lua_pushcfunction(L, notificationGetElapsedSinceCreation); + else if (key == "is_alive") + lua_pushcfunction(L, notificationIsAlive); + else + lua_pushnil(L); + + return 1; +} + +void Objects::CLuaNotification::setup(lua_State* L) { + registerMetatable(L, MT, notificationIndex, notificationGC, notificationEq, notificationToString); +} + +void Objects::CLuaNotification::push(lua_State* L, const SP& notification) { + new (lua_newuserdata(L, sizeof(SNotificationRef))) SNotificationRef{.notification = WP(notification)}; + luaL_getmetatable(L, MT); + lua_setmetatable(L, -2); +} diff --git a/src/config/lua/objects/LuaNotification.hpp b/src/config/lua/objects/LuaNotification.hpp new file mode 100644 index 00000000..2ac8b0eb --- /dev/null +++ b/src/config/lua/objects/LuaNotification.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include "LuaObjectHelpers.hpp" +#include "../../../notification/NotificationOverlay.hpp" + +namespace Config::Lua::Objects { + class CLuaNotification : public ILuaObjectWrapper { + public: + void setup(lua_State* L) override; + static void push(lua_State* L, const SP& notification); + }; +} diff --git a/src/config/lua/objects/LuaObjectHelpers.hpp b/src/config/lua/objects/LuaObjectHelpers.hpp new file mode 100644 index 00000000..69c284ef --- /dev/null +++ b/src/config/lua/objects/LuaObjectHelpers.hpp @@ -0,0 +1,51 @@ +#pragma once + +#include "../bindings/LuaBindingsInternal.hpp" + +#include "../../../helpers/memory/Memory.hpp" + +extern "C" { +#include +} + +namespace Config::Lua::Objects { + + template + inline int gcRef(lua_State* L) { + sc(lua_touserdata(L, 1))->~T(); + return 0; + } + + inline int readOnlyNewIndex(lua_State* L) { + return Config::Lua::Bindings::Internal::configError(L, "attempt to modify read-only hl object"); + } + + inline void registerMetatable(lua_State* L, const char* name, lua_CFunction indexFn, lua_CFunction gcFn, lua_CFunction eqFn = nullptr, lua_CFunction toStringFn = nullptr) { + luaL_newmetatable(L, name); + lua_pushcfunction(L, indexFn); + lua_setfield(L, -2, "__index"); + lua_pushcfunction(L, readOnlyNewIndex); + lua_setfield(L, -2, "__newindex"); + lua_pushcfunction(L, gcFn); + lua_setfield(L, -2, "__gc"); + + if (eqFn) { + lua_pushcfunction(L, eqFn); + lua_setfield(L, -2, "__eq"); + } + + if (toStringFn) { + lua_pushcfunction(L, toStringFn); + lua_setfield(L, -2, "__tostring"); + } + + lua_pop(L, 1); + } + + class ILuaObjectWrapper { + public: + virtual ~ILuaObjectWrapper() = default; + virtual void setup(lua_State* L) = 0; + }; + +} diff --git a/src/config/lua/objects/LuaTimer.cpp b/src/config/lua/objects/LuaTimer.cpp new file mode 100644 index 00000000..46f9a519 --- /dev/null +++ b/src/config/lua/objects/LuaTimer.cpp @@ -0,0 +1,109 @@ +#include "LuaTimer.hpp" + +#include +#include + +using namespace Config::Lua; + +static constexpr const char* MT = "HL.Timer"; + +namespace { + struct STimerRef { + WP timer; + int timeoutMs = 0; + }; +} + +static int timerEq(lua_State* L) { + const auto* lhs = sc(luaL_checkudata(L, 1, MT)); + const auto* rhs = sc(luaL_checkudata(L, 2, MT)); + + lua_pushboolean(L, lhs->timer.lock() == rhs->timer.lock()); + return 1; +} + +static int timerToString(lua_State* L) { + const auto* ref = sc(luaL_checkudata(L, 1, MT)); + const auto timer = ref->timer.lock(); + + if (!timer) + lua_pushstring(L, "HL.Timer(expired)"); + else + lua_pushfstring(L, "HL.Timer(%p)", timer.get()); + + return 1; +} + +static int timerSetEnabled(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + luaL_checktype(L, 2, LUA_TBOOLEAN); + + const auto timer = ref->timer.lock(); + if (!timer) + return 0; + + if (lua_toboolean(L, 2)) + timer->updateTimeout(std::chrono::milliseconds(std::max(ref->timeoutMs, 1))); + else + timer->updateTimeout(std::nullopt); + + return 0; +} + +static int timerSetTimeout(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + luaL_checktype(L, 2, LUA_TNUMBER); + + const auto timer = ref->timer.lock(); + if (!timer) + return 0; + + uint64_t x = lua_tointeger(L, 2); + + if (x < 1) + return Config::Lua::Bindings::Internal::configError(L, "hl.timer:set_timeout: timeout must be greater or equal to 1ms"); + + timer->updateTimeout(std::chrono::milliseconds(x)); + ref->timeoutMs = x; + + return 0; +} + +static int timerIsEnabled(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + + const auto timer = ref->timer.lock(); + if (!timer) { + lua_pushnil(L); + return 1; + } + + lua_pushboolean(L, timer->armed()); + return 1; +} + +static int timerIndex(lua_State* L) { + luaL_checkudata(L, 1, MT); + const std::string_view key = luaL_checkstring(L, 2); + + if (key == "set_enabled") + lua_pushcfunction(L, timerSetEnabled); + else if (key == "is_enabled") + lua_pushcfunction(L, timerIsEnabled); + else if (key == "set_timeout") + lua_pushcfunction(L, timerSetTimeout); + else + lua_pushnil(L); + + return 1; +} + +void Objects::CLuaTimer::setup(lua_State* L) { + registerMetatable(L, MT, timerIndex, gcRef, timerEq, timerToString); +} + +void Objects::CLuaTimer::push(lua_State* L, const SP& timer, int timeoutMs) { + new (lua_newuserdata(L, sizeof(STimerRef))) STimerRef{WP(timer), timeoutMs}; + luaL_getmetatable(L, MT); + lua_setmetatable(L, -2); +} diff --git a/src/config/lua/objects/LuaTimer.hpp b/src/config/lua/objects/LuaTimer.hpp new file mode 100644 index 00000000..0a602848 --- /dev/null +++ b/src/config/lua/objects/LuaTimer.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include "LuaObjectHelpers.hpp" +#include "../../../managers/eventLoop/EventLoopTimer.hpp" + +namespace Config::Lua::Objects { + class CLuaTimer : public ILuaObjectWrapper { + public: + void setup(lua_State* L) override; + static void push(lua_State* L, const SP& timer, int timeoutMs); + }; +} diff --git a/src/config/lua/objects/LuaWindow.cpp b/src/config/lua/objects/LuaWindow.cpp new file mode 100644 index 00000000..bf332584 --- /dev/null +++ b/src/config/lua/objects/LuaWindow.cpp @@ -0,0 +1,277 @@ +#include "LuaWindow.hpp" +#include "LuaWorkspace.hpp" +#include "LuaMonitor.hpp" +#include "LuaObjectHelpers.hpp" + +#include "../../../desktop/view/Window.hpp" +#include "../../../desktop/view/Group.hpp" +#include "../../../desktop/Workspace.hpp" +#include "../../../desktop/state/FocusState.hpp" +#include "../../../desktop/history/WindowHistoryTracker.hpp" +#include "../../../layout/algorithm/Algorithm.hpp" +#include "../../../layout/algorithm/tiled/master/MasterAlgorithm.hpp" +#include "../../../layout/algorithm/tiled/scrolling/ScrollingAlgorithm.hpp" +#include "../../../layout/algorithm/tiled/dwindle/DwindleAlgorithm.hpp" +#include "../../../layout/space/Space.hpp" +#include "../../../layout/supplementary/WorkspaceAlgoMatcher.hpp" +#include "../../../managers/input/InputManager.hpp" + +#include +#include + +using namespace Config::Lua; + +static constexpr const char* MT = "HL.Window"; + +// +static int getFocusHistoryID(PHLWINDOW wnd) { + const auto& history = Desktop::History::windowTracker()->fullHistory(); + for (size_t i = 0; i < history.size(); ++i) { + if (history[i].lock() == wnd) + return sc(history.size() - i - 1); // reverse order for backwards compat + } + + return -1; +} + +static int windowEq(lua_State* L) { + const auto* lhs = sc(luaL_checkudata(L, 1, MT)); + const auto* rhs = sc(luaL_checkudata(L, 2, MT)); + + lua_pushboolean(L, lhs->lock() == rhs->lock()); + return 1; +} + +static int windowToString(lua_State* L) { + const auto* ref = sc(luaL_checkudata(L, 1, MT)); + const auto w = ref->lock(); + + if (!w) + lua_pushstring(L, "HL.Window(expired)"); + else + lua_pushfstring(L, "HL.Window(%p)", w.get()); + + return 1; +} + +static int windowIndex(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + const auto w = ref->lock(); + if (!w) { + Log::logger->log(Log::DEBUG, "[lua] Tried to access an expired object"); + lua_pushnil(L); + return 1; + } + + const std::string_view key = luaL_checkstring(L, 2); + + if (key == "address") + lua_pushstring(L, std::format("0x{:x}", reinterpret_cast(w.get())).c_str()); + else if (key == "mapped") + lua_pushboolean(L, w->m_isMapped); + else if (key == "hidden") + lua_pushboolean(L, w->isHidden()); + else if (key == "at") { + lua_newtable(L); + lua_pushinteger(L, sc(w->m_realPosition->goal().x)); + lua_setfield(L, -2, "x"); + lua_pushinteger(L, sc(w->m_realPosition->goal().y)); + lua_setfield(L, -2, "y"); + } else if (key == "size") { + lua_newtable(L); + lua_pushinteger(L, sc(w->m_realSize->goal().x)); + lua_setfield(L, -2, "x"); + lua_pushinteger(L, sc(w->m_realSize->goal().y)); + lua_setfield(L, -2, "y"); + } else if (key == "workspace") { + if (w->m_workspace) + Objects::CLuaWorkspace::push(L, w->m_workspace); + else + lua_pushnil(L); + } else if (key == "floating") + lua_pushboolean(L, w->m_isFloating); + else if (key == "monitor") { + const auto mon = w->m_monitor.lock(); + if (mon) + Objects::CLuaMonitor::push(L, mon); + else + lua_pushnil(L); + } else if (key == "class") + lua_pushstring(L, w->m_class.c_str()); + else if (key == "title") + lua_pushstring(L, w->m_title.c_str()); + else if (key == "initial_class") + lua_pushstring(L, w->m_initialClass.c_str()); + else if (key == "initial_title") + lua_pushstring(L, w->m_initialTitle.c_str()); + else if (key == "pid") + lua_pushinteger(L, sc(w->getPID())); + else if (key == "xwayland") + lua_pushboolean(L, w->m_isX11); + else if (key == "pinned") + lua_pushboolean(L, w->m_pinned); + else if (key == "fullscreen") + lua_pushinteger(L, sc(sc(w->m_fullscreenState.internal))); + else if (key == "fullscreen_client") + lua_pushinteger(L, sc(sc(w->m_fullscreenState.client))); + else if (key == "over_fullscreen") + lua_pushboolean(L, w->m_createdOverFullscreen); + else if (key == "group") { + if (!w->m_group) { + lua_pushnil(L); + return 1; + } + + lua_newtable(L); + + lua_pushboolean(L, w->m_group->locked()); + lua_setfield(L, -2, "locked"); + + lua_pushboolean(L, w->m_group->denied()); + lua_setfield(L, -2, "denied"); + + lua_pushinteger(L, sc(w->m_group->size())); + lua_setfield(L, -2, "size"); + + lua_pushinteger(L, sc(w->m_group->getCurrentIdx()) + 1); + lua_setfield(L, -2, "current_index"); + + const auto current = w->m_group->current(); + if (current) + Objects::CLuaWindow::push(L, current); + else + lua_pushnil(L); + lua_setfield(L, -2, "current"); + + lua_newtable(L); + int i = 1; + for (const auto& grouped : w->m_group->windows()) { + const auto groupedWindow = grouped.lock(); + if (!groupedWindow) + continue; + + Objects::CLuaWindow::push(L, groupedWindow); + lua_rawseti(L, -2, i++); + } + lua_setfield(L, -2, "members"); + } else if (key == "tags") { + lua_newtable(L); + + int i = 1; + for (const auto& tag : w->m_ruleApplicator->m_tagKeeper.getTags()) { + lua_pushstring(L, tag.c_str()); + lua_rawseti(L, -2, i++); + } + } else if (key == "swallowing") { + const auto swallowed = w->m_swallowed.lock(); + if (swallowed) + Objects::CLuaWindow::push(L, swallowed); + else + lua_pushnil(L); + } else if (key == "focus_history_id") + lua_pushinteger(L, sc(getFocusHistoryID(w))); + else if (key == "inhibiting_idle") + lua_pushboolean(L, g_pInputManager && g_pInputManager->isWindowInhibiting(w, false)); + else if (key == "xdg_tag") { + const auto xdgTag = w->xdgTag(); + if (xdgTag) + lua_pushstring(L, xdgTag->c_str()); + else + lua_pushnil(L); + } else if (key == "xdg_description") { + const auto xdgDescription = w->xdgDescription(); + if (xdgDescription) + lua_pushstring(L, xdgDescription->c_str()); + else + lua_pushnil(L); + } else if (key == "content_type") + lua_pushstring(L, NContentType::toString(w->getContentType()).c_str()); + else if (key == "stable_id") + lua_pushinteger(L, sc(w->m_stableID)); + else if (key == "layout") { + const auto target = w->layoutTarget(); + if (!target || target->floating() || !w->m_workspace || !w->m_workspace->m_space) { + lua_pushnil(L); + return 1; + } + + const auto& algo = w->m_workspace->m_space->algorithm(); + if (!algo || !algo->tiledAlgo()) { + lua_pushnil(L); + return 1; + } + + const auto& tiledAlgo = algo->tiledAlgo(); + const std::string name = Layout::Supplementary::algoMatcher()->getNameForTiledAlgo(&typeid(*tiledAlgo.get())); + + lua_newtable(L); + lua_pushstring(L, name.c_str()); + lua_setfield(L, -2, "name"); + + if (const auto* master = dynamic_cast(tiledAlgo.get())) { + const auto node = master->getNodeFromTarget(target); + if (node) { + lua_pushboolean(L, node->isMaster); + lua_setfield(L, -2, "is_master"); + + lua_pushnumber(L, node->percMaster); + lua_setfield(L, -2, "perc_master"); + + lua_pushnumber(L, node->percSize); + lua_setfield(L, -2, "perc_size"); + } + } else if (auto* scrolling = dynamic_cast(tiledAlgo.get())) { + const auto data = scrolling->dataFor(target); + if (data) { + const auto col = data->column.lock(); + if (col) { + const auto scrollingData = col->scrollingData.lock(); + + lua_newtable(L); + + if (scrollingData) { + lua_pushinteger(L, sc(scrollingData->idx(col))); + lua_setfield(L, -2, "index"); + } + + lua_pushnumber(L, col->getColumnWidth()); + lua_setfield(L, -2, "width"); + + lua_newtable(L); + int i = 1; + for (const auto& td : col->targetDatas) { + const auto t = td->target.lock(); + if (t) { + const auto win = t->window(); + if (win) { + Objects::CLuaWindow::push(L, win); + lua_rawseti(L, -2, i++); + } + } + } + lua_setfield(L, -2, "windows"); + + lua_setfield(L, -2, "column"); + + lua_pushinteger(L, sc(col->idx(target))); + lua_setfield(L, -2, "index_in_column"); + } + } + } + } else if (key == "active") { + lua_pushboolean(L, w == Desktop::focusState()->window()); + } else + lua_pushnil(L); + + return 1; +} + +void Objects::CLuaWindow::setup(lua_State* L) { + registerMetatable(L, MT, windowIndex, gcRef, windowEq, windowToString); +} + +void Objects::CLuaWindow::push(lua_State* L, PHLWINDOW w) { + new (lua_newuserdata(L, sizeof(PHLWINDOWREF))) PHLWINDOWREF(w ? w->m_self : nullptr); + luaL_getmetatable(L, MT); + lua_setmetatable(L, -2); +} diff --git a/src/config/lua/objects/LuaWindow.hpp b/src/config/lua/objects/LuaWindow.hpp new file mode 100644 index 00000000..49f86149 --- /dev/null +++ b/src/config/lua/objects/LuaWindow.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include "LuaObjectHelpers.hpp" +#include "../../../desktop/DesktopTypes.hpp" + +namespace Config::Lua::Objects { + class CLuaWindow : public ILuaObjectWrapper { + public: + void setup(lua_State* L) override; + static void push(lua_State* L, PHLWINDOW w); + }; +} diff --git a/src/config/lua/objects/LuaWindowRule.cpp b/src/config/lua/objects/LuaWindowRule.cpp new file mode 100644 index 00000000..63fd1a2c --- /dev/null +++ b/src/config/lua/objects/LuaWindowRule.cpp @@ -0,0 +1,80 @@ +#include "LuaWindowRule.hpp" + +#include "../../../desktop/rule/Engine.hpp" + +#include + +using namespace Config::Lua; + +static constexpr const char* MT = "HL.WindowRule"; + +// +static int windowRuleEq(lua_State* L) { + const auto* lhs = sc*>(luaL_checkudata(L, 1, MT)); + const auto* rhs = sc*>(luaL_checkudata(L, 2, MT)); + + lua_pushboolean(L, lhs->lock() == rhs->lock()); + return 1; +} + +static int windowRuleToString(lua_State* L) { + const auto* ref = sc*>(luaL_checkudata(L, 1, MT)); + const auto rule = ref->lock(); + + if (!rule) + lua_pushstring(L, "HL.WindowRule(expired)"); + else + lua_pushfstring(L, "HL.WindowRule(%p)", rule.get()); + + return 1; +} + +static int windowRuleSetEnabled(lua_State* L) { + auto* ref = sc*>(luaL_checkudata(L, 1, MT)); + luaL_checktype(L, 2, LUA_TBOOLEAN); + + const auto rule = ref->lock(); + if (!rule) + return 0; + + rule->setEnabled(lua_toboolean(L, 2)); + Desktop::Rule::ruleEngine()->updateAllRules(); + return 0; +} + +static int windowRuleIsEnabled(lua_State* L) { + auto* ref = sc*>(luaL_checkudata(L, 1, MT)); + + const auto rule = ref->lock(); + if (!rule) { + lua_pushnil(L); + return 1; + } + + lua_pushboolean(L, rule->isEnabled()); + return 1; +} + +static int windowRuleIndex(lua_State* L) { + luaL_checkudata(L, 1, MT); + const std::string_view key = luaL_checkstring(L, 2); + + if (key == "set_enabled") + lua_pushcfunction(L, windowRuleSetEnabled); + else if (key == "is_enabled") + lua_pushcfunction(L, windowRuleIsEnabled); + else + lua_pushnil(L); + + return 1; +} + +void Objects::CLuaWindowRule::setup(lua_State* L) { + registerMetatable(L, MT, windowRuleIndex, gcRef>, windowRuleEq, windowRuleToString); +} + +void Objects::CLuaWindowRule::push(lua_State* L, const SP& rule) { + new (lua_newuserdata(L, sizeof(WP))) WP(rule); + luaL_getmetatable(L, MT); + lua_setmetatable(L, -2); +} diff --git a/src/config/lua/objects/LuaWindowRule.hpp b/src/config/lua/objects/LuaWindowRule.hpp new file mode 100644 index 00000000..92d0651d --- /dev/null +++ b/src/config/lua/objects/LuaWindowRule.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include "LuaObjectHelpers.hpp" +#include "../../../desktop/rule/windowRule/WindowRule.hpp" + +namespace Config::Lua::Objects { + class CLuaWindowRule : public ILuaObjectWrapper { + public: + void setup(lua_State* L) override; + static void push(lua_State* L, const SP& rule); + }; +} diff --git a/src/config/lua/objects/LuaWorkspace.cpp b/src/config/lua/objects/LuaWorkspace.cpp new file mode 100644 index 00000000..84e4df0b --- /dev/null +++ b/src/config/lua/objects/LuaWorkspace.cpp @@ -0,0 +1,87 @@ +#include "LuaWorkspace.hpp" +#include "LuaMonitor.hpp" +#include "LuaObjectHelpers.hpp" + +#include "../../../desktop/Workspace.hpp" +#include "../../../helpers/Monitor.hpp" + +#include + +using namespace Config::Lua; + +static constexpr const char* MT = "HL.Workspace"; + +// +static int workspaceEq(lua_State* L) { + const auto* lhs = sc(luaL_checkudata(L, 1, MT)); + const auto* rhs = sc(luaL_checkudata(L, 2, MT)); + + lua_pushboolean(L, lhs->lock() == rhs->lock()); + return 1; +} + +static int workspaceToString(lua_State* L) { + const auto* ref = sc(luaL_checkudata(L, 1, MT)); + const auto ws = ref->lock(); + + if (!ws || ws->inert()) + lua_pushstring(L, "HL.Workspace(expired)"); + else + lua_pushfstring(L, "HL.Workspace(%d:%s)", ws->m_id, ws->m_name.c_str()); + + return 1; +} + +static int workspaceIndex(lua_State* L) { + auto* ref = sc(luaL_checkudata(L, 1, MT)); + const auto ws = ref->lock(); + if (!ws || ws->inert()) { + Log::logger->log(Log::DEBUG, "[lua] Tried to access an expired object"); + lua_pushnil(L); + return 1; + } + + const std::string_view key = luaL_checkstring(L, 2); + + if (key == "id") + lua_pushinteger(L, sc(ws->m_id)); + else if (key == "name") + lua_pushstring(L, ws->m_name.c_str()); + else if (key == "monitor") { + const auto mon = ws->m_monitor.lock(); + if (mon) + Objects::CLuaMonitor::push(L, mon); + else + lua_pushnil(L); + } else if (key == "windows") + lua_pushinteger(L, sc(ws->getWindows())); + else if (key == "visible") + lua_pushboolean(L, ws->isVisible()); + else if (key == "special") + lua_pushboolean(L, ws->m_isSpecialWorkspace); + else if (key == "active") { + const auto mon = ws->m_monitor.lock(); + lua_pushboolean(L, mon && (mon->m_activeWorkspace == ws || mon->m_activeSpecialWorkspace == ws)); + } else if (key == "has_urgent") + lua_pushboolean(L, ws->hasUrgentWindow()); + else if (key == "fullscreen_mode") + lua_pushinteger(L, sc(ws->m_fullscreenMode)); + else if (key == "has_fullscreen") + lua_pushboolean(L, ws->m_hasFullscreenWindow); + else if (key == "is_persistent") + lua_pushboolean(L, ws->isPersistent()); + else + lua_pushnil(L); + + return 1; +} + +void Objects::CLuaWorkspace::setup(lua_State* L) { + registerMetatable(L, MT, workspaceIndex, gcRef, workspaceEq, workspaceToString); +} + +void Objects::CLuaWorkspace::push(lua_State* L, PHLWORKSPACE ws) { + new (lua_newuserdata(L, sizeof(PHLWORKSPACEREF))) PHLWORKSPACEREF(ws ? ws->m_self : nullptr); + luaL_getmetatable(L, MT); + lua_setmetatable(L, -2); +} diff --git a/src/config/lua/objects/LuaWorkspace.hpp b/src/config/lua/objects/LuaWorkspace.hpp new file mode 100644 index 00000000..db07feba --- /dev/null +++ b/src/config/lua/objects/LuaWorkspace.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include "LuaObjectHelpers.hpp" +#include "../../../desktop/DesktopTypes.hpp" + +namespace Config::Lua::Objects { + class CLuaWorkspace : public ILuaObjectWrapper { + public: + void setup(lua_State* L) override; + static void push(lua_State* L, PHLWORKSPACE ws); + }; +} diff --git a/src/config/lua/types/LuaConfigBool.cpp b/src/config/lua/types/LuaConfigBool.cpp new file mode 100644 index 00000000..15413598 --- /dev/null +++ b/src/config/lua/types/LuaConfigBool.cpp @@ -0,0 +1,52 @@ +#include "LuaConfigBool.hpp" + +using namespace Config; +using namespace Config::Lua; + +CLuaConfigBool::CLuaConfigBool(Config::BOOL def) : m_default(def), m_data(def) { + ; +} + +SParseError CLuaConfigBool::parse(lua_State* s) { + if (lua_isnumber(s, -1)) { + auto number = lua_tonumber(s, -1); + if (number != 0 && number != 1) + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = "boolean type requires a bool, or 0/1."}; + + m_data = !!number; + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; + } + + if (lua_isboolean(s, -1)) { + m_data = lua_toboolean(s, -1); + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; + } + + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = "boolean type requires a bool"}; +} + +const std::type_info* CLuaConfigBool::underlying() { + return &typeid(decltype(m_data)); +} + +void const* CLuaConfigBool::data() { + return &m_data; +} + +std::string CLuaConfigBool::toString() { + return m_data ? "1" : "0"; +} + +void CLuaConfigBool::push(lua_State* s) { + lua_pushboolean(s, m_data); +} + +const Config::BOOL& CLuaConfigBool::parsed() { + return m_data; +} + +void CLuaConfigBool::reset() { + m_data = m_default; +} diff --git a/src/config/lua/types/LuaConfigBool.hpp b/src/config/lua/types/LuaConfigBool.hpp new file mode 100644 index 00000000..b4644aa4 --- /dev/null +++ b/src/config/lua/types/LuaConfigBool.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include "LuaConfigValue.hpp" + +namespace Config::Lua { + class CLuaConfigBool : public ILuaConfigValue { + public: + CLuaConfigBool(Config::BOOL def); + virtual ~CLuaConfigBool() = default; + + virtual SParseError parse(lua_State* s); + virtual const std::type_info* underlying(); + virtual void const* data(); + virtual std::string toString(); + virtual void push(lua_State* s); + virtual void reset(); + + const Config::BOOL& parsed(); + + private: + Config::BOOL m_default = false; + Config::BOOL m_data = false; + }; +}; diff --git a/src/config/lua/types/LuaConfigColor.cpp b/src/config/lua/types/LuaConfigColor.cpp new file mode 100644 index 00000000..c58b232b --- /dev/null +++ b/src/config/lua/types/LuaConfigColor.cpp @@ -0,0 +1,63 @@ +#include "LuaConfigColor.hpp" + +#include +#include + +#include "../../../helpers/Color.hpp" +#include "../../../helpers/MiscFunctions.hpp" + +using namespace Config; +using namespace Config::Lua; + +static std::expected parseColorString(const std::string& str) { + auto result = configStringToInt(str); + if (!result) + return std::unexpected(std::format("invalid color \"{}\"", str)); + return CHyprColor(sc(*result)); +} + +CLuaConfigColor::CLuaConfigColor(Config::INTEGER def) : m_default(def), m_data(def) { + ; +} + +SParseError CLuaConfigColor::parse(lua_State* s) { + if (lua_isstring(s, -1)) { + auto data = lua_tostring(s, -1); + + auto col = parseColorString(data); + + if (!col) + return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = col.error()}; + + m_data = col->getAsHex(); + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; + } + + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = "color type requires a color string"}; +} + +const std::type_info* CLuaConfigColor::underlying() { + return &typeid(decltype(m_data)); +} + +void const* CLuaConfigColor::data() { + return &m_data; +} + +std::string CLuaConfigColor::toString() { + return std::format("0x{:08X}", (uint32_t)m_data); +} + +void CLuaConfigColor::push(lua_State* s) { + const auto col = toString(); + lua_pushstring(s, col.c_str()); +} + +const Config::INTEGER& CLuaConfigColor::parsed() { + return m_data; +} + +void CLuaConfigColor::reset() { + m_data = m_default; +} diff --git a/src/config/lua/types/LuaConfigColor.hpp b/src/config/lua/types/LuaConfigColor.hpp new file mode 100644 index 00000000..15ff1ddf --- /dev/null +++ b/src/config/lua/types/LuaConfigColor.hpp @@ -0,0 +1,25 @@ +#pragma once + +#include "LuaConfigValue.hpp" + +namespace Config::Lua { + class CLuaConfigColor : public ILuaConfigValue { + public: + CLuaConfigColor(Config::INTEGER def); + virtual ~CLuaConfigColor() = default; + + virtual SParseError parse(lua_State* s); + virtual const std::type_info* underlying(); + virtual void const* data(); + virtual std::string toString(); + virtual void push(lua_State* s); + virtual void reset(); + + const Config::INTEGER& parsed(); + + private: + // colors are stored as ints for compat + Config::INTEGER m_default = 0; + Config::INTEGER m_data = 0; + }; +}; diff --git a/src/config/lua/types/LuaConfigCssGap.cpp b/src/config/lua/types/LuaConfigCssGap.cpp new file mode 100644 index 00000000..31f2fb21 --- /dev/null +++ b/src/config/lua/types/LuaConfigCssGap.cpp @@ -0,0 +1,104 @@ +#include "LuaConfigCssGap.hpp" + +using namespace Config; +using namespace Config::Lua; + +CLuaConfigCssGap::CLuaConfigCssGap(Config::INTEGER def, std::optional min, std::optional max) : m_default(def), m_data(def), m_min(min), m_max(max) { + ; +} + +static std::string checkRange(int64_t v, const std::string& field, std::optional min, std::optional max) { + if (min.has_value() && v < *min) + return std::format("gap \"{}\" value {} is less than the minimum of {}", field, v, *min); + if (max.has_value() && v > *max) + return std::format("gap \"{}\" value {} is more than the maximum of {}", field, v, *max); + return {}; +} + +SParseError CLuaConfigCssGap::parse(lua_State* s) { + // accept a plain integer + if (lua_isinteger(s, -1) || lua_isnumber(s, -1)) { + int64_t v = sc(lua_tonumber(s, -1)); + auto e = checkRange(v, "global", m_min, m_max); + if (!e.empty()) + return {.errorCode = PARSE_ERROR_OUT_OF_RANGE, .message = e}; + m_data.reset(v); + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; + } + + if (!lua_istable(s, -1)) + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = "css_gap type requires an integer or a table with optional \"top\", \"right\", \"bottom\", \"left\" fields"}; + + const auto readField = [&](const char* name, int64_t fallback) -> std::expected { + lua_getfield(s, -1, name); + int64_t val = fallback; + if (!lua_isnil(s, -1)) { + if (!lua_isinteger(s, -1) && !lua_isnumber(s, -1)) { + lua_pop(s, 1); + return std::unexpected(SParseError{.errorCode = PARSE_ERROR_BAD_TYPE, .message = std::format("css_gap \"{}\" must be an integer", name)}); + } + val = sc(lua_tointeger(s, -1)); + auto e = checkRange(val, name, m_min, m_max); + if (!e.empty()) { + lua_pop(s, 1); + return std::unexpected(SParseError{.errorCode = PARSE_ERROR_OUT_OF_RANGE, .message = e}); + } + } + lua_pop(s, 1); + return val; + }; + + auto top = readField("top", 0); + if (!top) + return top.error(); + auto right = readField("right", 0); + if (!right) + return right.error(); + auto bottom = readField("bottom", 0); + if (!bottom) + return bottom.error(); + auto left = readField("left", 0); + if (!left) + return left.error(); + + m_data = CCssGapData(*top, *right, *bottom, *left); + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; +} + +const std::type_info* CLuaConfigCssGap::underlying() { + return &typeid(decltype(m_data)); +} + +void const* CLuaConfigCssGap::data() { + return dc(&m_data); +} + +std::string CLuaConfigCssGap::toString() { + return m_data.toString(); +} + +void CLuaConfigCssGap::push(lua_State* s) { + lua_createtable(s, 0, 4); + + lua_pushinteger(s, m_data.m_top); + lua_setfield(s, -2, "top"); + + lua_pushinteger(s, m_data.m_right); + lua_setfield(s, -2, "right"); + + lua_pushinteger(s, m_data.m_bottom); + lua_setfield(s, -2, "bottom"); + + lua_pushinteger(s, m_data.m_left); + lua_setfield(s, -2, "left"); +} + +const CCssGapData& CLuaConfigCssGap::parsed() { + return m_data; +} + +void CLuaConfigCssGap::reset() { + m_data = CCssGapData(m_default); +} diff --git a/src/config/lua/types/LuaConfigCssGap.hpp b/src/config/lua/types/LuaConfigCssGap.hpp new file mode 100644 index 00000000..368c059b --- /dev/null +++ b/src/config/lua/types/LuaConfigCssGap.hpp @@ -0,0 +1,28 @@ +#pragma once + +#include "LuaConfigValue.hpp" +#include "../../shared/complex/ComplexDataTypes.hpp" + +#include + +namespace Config::Lua { + class CLuaConfigCssGap : public ILuaConfigValue { + public: + CLuaConfigCssGap(Config::INTEGER def, std::optional min = std::nullopt, std::optional max = std::nullopt); + virtual ~CLuaConfigCssGap() = default; + + virtual SParseError parse(lua_State* s); + virtual const std::type_info* underlying(); + virtual void const* data(); + virtual std::string toString(); + virtual void push(lua_State* s); + virtual void reset(); + + const CCssGapData& parsed(); + + private: + Config::INTEGER m_default = 0; + CCssGapData m_data; + std::optional m_min, m_max; + }; +}; diff --git a/src/config/lua/types/LuaConfigFloat.cpp b/src/config/lua/types/LuaConfigFloat.cpp new file mode 100644 index 00000000..9d2574b6 --- /dev/null +++ b/src/config/lua/types/LuaConfigFloat.cpp @@ -0,0 +1,80 @@ +#include "LuaConfigFloat.hpp" + +using namespace Config; +using namespace Config::Lua; + +CLuaConfigFloat::CLuaConfigFloat(Config::FLOAT def, std::optional min, std::optional max) : m_default(def), m_data(def), m_min(min), m_max(max) { + ; +} + +SParseError CLuaConfigFloat::parse(lua_State* s) { + if (lua_isboolean(s, -1)) { + auto data = lua_toboolean(s, -1) ? 1 : 0; + + if (m_min.has_value() && data < *m_min) + return {.errorCode = PARSE_ERROR_OUT_OF_RANGE, + .message = std::format("value {} (automatically casted from boolean) is less than the minimum of {}", data ? "true" : "false", *m_min)}; + + if (m_max.has_value() && data > *m_max) + return {.errorCode = PARSE_ERROR_OUT_OF_RANGE, + .message = std::format("value {} (automatically casted from boolean) is more than the maximum of {}", data ? "true" : "false", *m_max)}; + + m_data = data; + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; + } + + if (lua_isinteger(s, -1)) { + auto data = lua_tointeger(s, -1); + + if (m_min.has_value() && data < *m_min) + return {.errorCode = PARSE_ERROR_OUT_OF_RANGE, .message = std::format("value {} is less than the minimum of {:.2f}", data, *m_min)}; + + if (m_max.has_value() && data > *m_max) + return {.errorCode = PARSE_ERROR_OUT_OF_RANGE, .message = std::format("value {} is more than the maximum of {:.2f}", data, *m_max)}; + + m_data = data; + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; + } + + if (lua_isnumber(s, -1)) { + auto data = lua_tonumber(s, -1); + + if (m_min.has_value() && data < *m_min) + return {.errorCode = PARSE_ERROR_OUT_OF_RANGE, .message = std::format("value {:.2f} is less than the minimum of {:.2f}", data, *m_min)}; + + if (m_max.has_value() && data > *m_max) + return {.errorCode = PARSE_ERROR_OUT_OF_RANGE, .message = std::format("value {:.2f} is more than the maximum of {:.2f}", data, *m_max)}; + + m_data = data; + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; + } + + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = "float type requires a number"}; +} + +const std::type_info* CLuaConfigFloat::underlying() { + return &typeid(decltype(m_data)); +} + +void const* CLuaConfigFloat::data() { + return &m_data; +} + +std::string CLuaConfigFloat::toString() { + return std::to_string(m_data); +} + +void CLuaConfigFloat::push(lua_State* s) { + lua_pushnumber(s, m_data); +} + +const Config::FLOAT& CLuaConfigFloat::parsed() { + return m_data; +} + +void CLuaConfigFloat::reset() { + m_data = m_default; +} diff --git a/src/config/lua/types/LuaConfigFloat.hpp b/src/config/lua/types/LuaConfigFloat.hpp new file mode 100644 index 00000000..e6602b5a --- /dev/null +++ b/src/config/lua/types/LuaConfigFloat.hpp @@ -0,0 +1,27 @@ +#pragma once + +#include "LuaConfigValue.hpp" + +#include + +namespace Config::Lua { + class CLuaConfigFloat : public ILuaConfigValue { + public: + CLuaConfigFloat(Config::FLOAT def, std::optional min = std::nullopt, std::optional max = std::nullopt); + virtual ~CLuaConfigFloat() = default; + + virtual SParseError parse(lua_State* s); + virtual const std::type_info* underlying(); + virtual void const* data(); + virtual std::string toString(); + virtual void push(lua_State* s); + virtual void reset(); + + const Config::FLOAT& parsed(); + + private: + Config::FLOAT m_default = 0.F; + Config::FLOAT m_data = 0.F; + std::optional m_min, m_max; + }; +}; diff --git a/src/config/lua/types/LuaConfigFontWeight.cpp b/src/config/lua/types/LuaConfigFontWeight.cpp new file mode 100644 index 00000000..44deac5c --- /dev/null +++ b/src/config/lua/types/LuaConfigFontWeight.cpp @@ -0,0 +1,69 @@ +#include "LuaConfigFontWeight.hpp" + +#include +#include +#include + +#include "../../shared/complex/ComplexDataTypes.hpp" + +using namespace Config; +using namespace Config::Lua; + +CLuaConfigFontWeight::CLuaConfigFontWeight(Config::INTEGER def) : m_default(def), m_data(def) { + ; +} + +SParseError CLuaConfigFontWeight::parse(lua_State* s) { + if (lua_isinteger(s, -1) || lua_isnumber(s, -1)) { + int64_t v = sc(lua_tonumber(s, -1)); + if (v < 0) + return {.errorCode = PARSE_ERROR_OUT_OF_RANGE, .message = std::format("font weight {} must not be negative", v)}; + m_data.m_value = v; + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; + } + + if (lua_isstring(s, -1)) { + std::string str = lua_tostring(s, -1); + std::string lc = str; + std::ranges::transform(str, lc.begin(), ::tolower); + + auto it = CFontWeightConfigValueData::WEIGHTS.find(lc); + if (it != CFontWeightConfigValueData::WEIGHTS.end()) { + m_data.m_value = it->second; + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; + } + + if (Hyprutils::String::isNumber(str)) + return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = std::format("font weight \"{}\" was not found. Did you mean to put in an integer (without quotes?)", str)}; + + return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = std::format("font weight \"{}\" was not found", str)}; + } + + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = "font weight type requires a number or a weight name string"}; +} + +const std::type_info* CLuaConfigFontWeight::underlying() { + return &typeid(IComplexConfigValue*); +} + +void const* CLuaConfigFontWeight::data() { + return dc(&m_data); +} + +std::string CLuaConfigFontWeight::toString() { + return m_data.toString(); +} + +void CLuaConfigFontWeight::push(lua_State* s) { + lua_pushinteger(s, m_data.m_value); +} + +const CFontWeightConfigValueData& CLuaConfigFontWeight::parsed() { + return m_data; +} + +void CLuaConfigFontWeight::reset() { + m_data = CFontWeightConfigValueData(m_default); +} diff --git a/src/config/lua/types/LuaConfigFontWeight.hpp b/src/config/lua/types/LuaConfigFontWeight.hpp new file mode 100644 index 00000000..ab0c4a5b --- /dev/null +++ b/src/config/lua/types/LuaConfigFontWeight.hpp @@ -0,0 +1,25 @@ +#pragma once + +#include "LuaConfigValue.hpp" +#include "../../shared/complex/ComplexDataTypes.hpp" + +namespace Config::Lua { + class CLuaConfigFontWeight : public ILuaConfigValue { + public: + CLuaConfigFontWeight(Config::INTEGER def = 400); + virtual ~CLuaConfigFontWeight() = default; + + virtual SParseError parse(lua_State* s); + virtual const std::type_info* underlying(); + virtual void const* data(); + virtual std::string toString(); + virtual void push(lua_State* s); + virtual void reset(); + + const CFontWeightConfigValueData& parsed(); + + private: + Config::INTEGER m_default = 400; + CFontWeightConfigValueData m_data; + }; +}; diff --git a/src/config/lua/types/LuaConfigGradient.cpp b/src/config/lua/types/LuaConfigGradient.cpp new file mode 100644 index 00000000..6e5838a9 --- /dev/null +++ b/src/config/lua/types/LuaConfigGradient.cpp @@ -0,0 +1,133 @@ +#include "LuaConfigGradient.hpp" +#include "../../../helpers/MiscFunctions.hpp" + +#include + +using namespace Config; +using namespace Config::Lua; + +static std::expected parseColorString(const std::string& str) { + auto result = configStringToInt(str); + if (!result) + return std::unexpected(std::format("invalid color \"{}\"", str)); + return CHyprColor(sc(*result)); +} + +CLuaConfigGradient::CLuaConfigGradient(CHyprColor def) : m_default(def), m_data(def) { + ; +} + +SParseError CLuaConfigGradient::parse(lua_State* s) { + // accept a single color string + if (lua_isstring(s, -1)) { + std::string str = lua_tostring(s, -1); + auto col = parseColorString(str); + if (!col) + return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = col.error()}; + m_data.reset(*col); + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; + } + + if (!lua_istable(s, -1)) + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = R"(gradient type requires a color string or a table with "colors" and optional "angle")"}; + + // read colors array + lua_getfield(s, -1, "colors"); + if (!lua_istable(s, -1)) { + lua_pop(s, 1); + return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = "gradient table must have a \"colors\" array"}; + } + + std::vector colors; + int len = sc(lua_rawlen(s, -1)); + if (len == 0) { + lua_pop(s, 1); + return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = "gradient \"colors\" must not be empty"}; + } + + for (int i = 1; i <= len; ++i) { + lua_rawgeti(s, -1, i); + if (!lua_isstring(s, -1)) { + lua_pop(s, 2); + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = std::format("gradient color at index {} must be a string", i)}; + } + std::string str = lua_tostring(s, -1); + lua_pop(s, 1); + + auto col = parseColorString(str); + if (!col) { + lua_pop(s, 1); + return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = col.error()}; + } + colors.emplace_back(*col); + } + lua_pop(s, 1); // pop colors table + + // read optional angle (degrees) + float angle = 0.F; + lua_getfield(s, -1, "angle"); + if (!lua_isnil(s, -1)) { + if (!lua_isnumber(s, -1)) { + lua_pop(s, 1); + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = "gradient \"angle\" must be a number (degrees)"}; + } + angle = sc(lua_tonumber(s, -1) * std::numbers::pi / 180.0); + } + lua_pop(s, 1); + + m_data.m_colors = std::move(colors); + m_data.m_angle = angle; + m_data.updateColorsOk(); + m_bSetByUser = true; + + return {.errorCode = PARSE_ERROR_OK}; +} + +const std::type_info* CLuaConfigGradient::underlying() { + return &typeid(decltype(m_data)); +} + +void const* CLuaConfigGradient::data() { + return dc(&m_data); +} + +std::string CLuaConfigGradient::toString() { + std::string result; + + for (size_t i = 0; i < m_data.m_colors.size(); ++i) { + if (i > 0) + result += ' '; + result += std::format("0x{:08X}", m_data.m_colors[i].getAsHex()); + } + + if (!result.empty()) + result += ' '; + + result += std::format("{}deg", sc(m_data.m_angle * 180.0 / std::numbers::pi_v)); + + return result; +} + +void CLuaConfigGradient::push(lua_State* s) { + lua_createtable(s, 0, 2); + + lua_createtable(s, m_data.m_colors.size(), 0); + for (size_t i = 0; i < m_data.m_colors.size(); ++i) { + const auto col = std::format("0x{:08X}", m_data.m_colors[i].getAsHex()); + lua_pushstring(s, col.c_str()); + lua_rawseti(s, -2, i + 1); + } + lua_setfield(s, -2, "colors"); + + lua_pushnumber(s, m_data.m_angle * 180.0 / std::numbers::pi); + lua_setfield(s, -2, "angle"); +} + +const CGradientValueData& CLuaConfigGradient::parsed() { + return m_data; +} + +void CLuaConfigGradient::reset() { + m_data = CGradientValueData(m_default); +} diff --git a/src/config/lua/types/LuaConfigGradient.hpp b/src/config/lua/types/LuaConfigGradient.hpp new file mode 100644 index 00000000..a1ccd5a6 --- /dev/null +++ b/src/config/lua/types/LuaConfigGradient.hpp @@ -0,0 +1,25 @@ +#pragma once + +#include "LuaConfigValue.hpp" +#include "../../shared/complex/ComplexDataTypes.hpp" + +namespace Config::Lua { + class CLuaConfigGradient : public ILuaConfigValue { + public: + CLuaConfigGradient(CHyprColor def); + virtual ~CLuaConfigGradient() = default; + + virtual SParseError parse(lua_State* s); + virtual const std::type_info* underlying(); + virtual void const* data(); + virtual std::string toString(); + virtual void push(lua_State* s); + virtual void reset(); + + const CGradientValueData& parsed(); + + private: + CHyprColor m_default; + CGradientValueData m_data; + }; +}; diff --git a/src/config/lua/types/LuaConfigInt.cpp b/src/config/lua/types/LuaConfigInt.cpp new file mode 100644 index 00000000..ef96a056 --- /dev/null +++ b/src/config/lua/types/LuaConfigInt.cpp @@ -0,0 +1,88 @@ +#include "LuaConfigInt.hpp" + +using namespace Config; +using namespace Config::Lua; + +CLuaConfigInt::CLuaConfigInt(Config::INTEGER def, std::optional min, std::optional max, + std::optional> map) : m_default(def), m_data(def), m_min(min), m_max(max), m_map(std::move(map)) { + ; +} + +SParseError CLuaConfigInt::parse(lua_State* s) { + if (lua_isboolean(s, -1)) { + auto data = lua_toboolean(s, -1) ? 1 : 0; + + if (m_min.has_value() && data < *m_min) + return {.errorCode = PARSE_ERROR_OUT_OF_RANGE, + .message = std::format("value {} (automatically casted from boolean) is less than the minimum of {}", data ? "true" : "false", *m_min)}; + + if (m_max.has_value() && data > *m_max) + return {.errorCode = PARSE_ERROR_OUT_OF_RANGE, + .message = std::format("value {} (automatically casted from boolean) is more than the maximum of {}", data ? "true" : "false", *m_max)}; + + m_data = data; + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; + } + + if (lua_isstring(s, -1) && !lua_isinteger(s, -1)) { + if (!m_map.has_value()) + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = "integer type requires a bool or an integer"}; + + const std::string str = lua_tostring(s, -1); + const auto it = m_map->find(str); + if (it == m_map->end()) { + std::string keys; + for (const auto& [k, _] : *m_map) { + if (!keys.empty()) + keys += ", "; + keys += "\"" + k + "\""; + } + return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = std::format("unknown string value \"{}\", acceptable values are: {}", str, keys)}; + } + + m_data = it->second; + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; + } + + if (lua_isinteger(s, -1)) { + auto data = lua_tointeger(s, -1); + + if (m_min.has_value() && data < *m_min) + return {.errorCode = PARSE_ERROR_OUT_OF_RANGE, .message = std::format("value {} is less than the minimum of {}", data, *m_min)}; + + if (m_max.has_value() && data > *m_max) + return {.errorCode = PARSE_ERROR_OUT_OF_RANGE, .message = std::format("value {} is more than the maximum of {}", data, *m_max)}; + + m_data = data; + m_bSetByUser = true; + return {.errorCode = PARSE_ERROR_OK}; + } + + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = "integer type requires a bool or an integer"}; +} + +const std::type_info* CLuaConfigInt::underlying() { + return &typeid(decltype(m_data)); +} + +void const* CLuaConfigInt::data() { + return &m_data; +} + +std::string CLuaConfigInt::toString() { + return std::to_string(m_data); +} + +void CLuaConfigInt::push(lua_State* s) { + lua_pushinteger(s, m_data); +} + +const Config::INTEGER& CLuaConfigInt::parsed() { + return m_data; +} + +void CLuaConfigInt::reset() { + m_data = m_default; +} diff --git a/src/config/lua/types/LuaConfigInt.hpp b/src/config/lua/types/LuaConfigInt.hpp new file mode 100644 index 00000000..7ff2f39c --- /dev/null +++ b/src/config/lua/types/LuaConfigInt.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include "LuaConfigValue.hpp" + +#include +#include +#include + +namespace Config::Lua { + class CLuaConfigInt : public ILuaConfigValue { + public: + CLuaConfigInt(Config::INTEGER def, std::optional min = std::nullopt, std::optional max = std::nullopt, + std::optional> map = std::nullopt); + virtual ~CLuaConfigInt() = default; + + virtual SParseError parse(lua_State* s); + virtual const std::type_info* underlying(); + virtual void const* data(); + virtual std::string toString(); + virtual void push(lua_State* s); + virtual void reset(); + + const Config::INTEGER& parsed(); + + private: + Config::INTEGER m_default = 0; + Config::INTEGER m_data = 0; + std::optional m_min, m_max; + std::optional> m_map; + }; +}; diff --git a/src/config/lua/types/LuaConfigString.cpp b/src/config/lua/types/LuaConfigString.cpp new file mode 100644 index 00000000..c16a587b --- /dev/null +++ b/src/config/lua/types/LuaConfigString.cpp @@ -0,0 +1,56 @@ +#include "LuaConfigString.hpp" + +#include "../../../macros.hpp" + +using namespace Config; +using namespace Config::Lua; + +CLuaConfigString::CLuaConfigString(Config::STRING def, std::optional(const std::string&)>>&& validator) : + m_default(def), m_data(def), m_validator(std::move(validator)) { + ; +} + +SParseError CLuaConfigString::parse(lua_State* s) { + if (!lua_isstring(s, -1)) + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = "string type requires a string"}; + + std::string str = lua_tostring(s, -1); + + if (m_validator.has_value()) { + auto res = m_validator.value()(str); + if (!res) + return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = res.error()}; + } + + m_data = std::move(str); + m_bSetByUser = true; + + return {.errorCode = PARSE_ERROR_OK}; +} + +const std::type_info* CLuaConfigString::underlying() { + return &typeid(decltype(m_data)); +} + +void const* CLuaConfigString::data() { + return &m_data; +} + +std::string CLuaConfigString::toString() { + return m_data; +} + +void CLuaConfigString::push(lua_State* s) { + if (m_data == STRVAL_EMPTY) + lua_pushliteral(s, ""); + else + lua_pushstring(s, m_data.c_str()); +} + +const Config::STRING& CLuaConfigString::parsed() { + return m_data; +} + +void CLuaConfigString::reset() { + m_data = m_default; +} diff --git a/src/config/lua/types/LuaConfigString.hpp b/src/config/lua/types/LuaConfigString.hpp new file mode 100644 index 00000000..d976b6ab --- /dev/null +++ b/src/config/lua/types/LuaConfigString.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include "LuaConfigValue.hpp" + +#include +#include +#include + +namespace Config::Lua { + class CLuaConfigString : public ILuaConfigValue { + public: + CLuaConfigString(Config::STRING def, std::optional(const Config::STRING&)>>&& validator = std::nullopt); + virtual ~CLuaConfigString() = default; + + virtual SParseError parse(lua_State* s); + virtual const std::type_info* underlying(); + virtual void const* data(); + virtual std::string toString(); + virtual void push(lua_State* s); + virtual void reset(); + + const Config::STRING& parsed(); + + private: + Config::STRING m_default = "[[EMPTY]]"; + Config::STRING m_data = "[[EMPTY]]"; + std::optional(const std::string&)>> m_validator; + }; +}; diff --git a/src/config/lua/types/LuaConfigUtils.cpp b/src/config/lua/types/LuaConfigUtils.cpp new file mode 100644 index 00000000..91702aeb --- /dev/null +++ b/src/config/lua/types/LuaConfigUtils.cpp @@ -0,0 +1,51 @@ +#include "LuaConfigUtils.hpp" +#include "LuaConfigInt.hpp" +#include "LuaConfigFloat.hpp" +#include "LuaConfigBool.hpp" +#include "LuaConfigString.hpp" +#include "LuaConfigColor.hpp" +#include "LuaConfigVec2.hpp" +#include "LuaConfigCssGap.hpp" +#include "LuaConfigFontWeight.hpp" +#include "LuaConfigGradient.hpp" +#include "../../values/types/IntValue.hpp" +#include "../../values/types/FloatValue.hpp" +#include "../../values/types/BoolValue.hpp" +#include "../../values/types/StringValue.hpp" +#include "../../values/types/ColorValue.hpp" +#include "../../values/types/Vec2Value.hpp" +#include "../../values/types/CssGapValue.hpp" +#include "../../values/types/FontWeightValue.hpp" +#include "../../values/types/GradientValue.hpp" + +using namespace Config; +using namespace Config::Lua; + +UP Lua::fromGenericValue(SP v) { + const auto refreshBits = v->refreshBits(); + const auto withRefresh = [refreshBits](UP val) -> UP { + val->setRefreshBits(refreshBits); + return val; + }; + + if (auto p = dc(v.get())) + return withRefresh(makeUnique(p->defaultVal())); + if (auto p = dc(v.get())) + return withRefresh(makeUnique(p->defaultVal())); + if (auto p = dc(v.get())) + return withRefresh(makeUnique(p->defaultVal())); + if (auto p = dc(v.get())) + return withRefresh(makeUnique(p->defaultVal())); + if (auto p = dc(v.get())) + return withRefresh(makeUnique(p->defaultVal())); + if (auto p = dc(v.get())) + return withRefresh(makeUnique(p->defaultVal())); + if (auto p = dc(v.get())) + return withRefresh(makeUnique(p->defaultVal().m_top)); + if (auto p = dc(v.get())) + return withRefresh(makeUnique(p->defaultVal().m_value)); + if (auto p = dc(v.get())) + return withRefresh(makeUnique(p->defaultVal().m_colors.empty() ? CHyprColor{} : p->defaultVal().m_colors.front())); + + return nullptr; +} diff --git a/src/config/lua/types/LuaConfigUtils.hpp b/src/config/lua/types/LuaConfigUtils.hpp new file mode 100644 index 00000000..d61cf47a --- /dev/null +++ b/src/config/lua/types/LuaConfigUtils.hpp @@ -0,0 +1,9 @@ +#pragma once + +#include "LuaConfigValue.hpp" +#include "../../../helpers/memory/Memory.hpp" +#include "../../values/types/IValue.hpp" + +namespace Config::Lua { + UP fromGenericValue(SP v); +}; \ No newline at end of file diff --git a/src/config/lua/types/LuaConfigValue.cpp b/src/config/lua/types/LuaConfigValue.cpp new file mode 100644 index 00000000..38141baa --- /dev/null +++ b/src/config/lua/types/LuaConfigValue.cpp @@ -0,0 +1,20 @@ +#include "LuaConfigValue.hpp" + +using namespace Config; +using namespace Config::Lua; + +void ILuaConfigValue::resetSetByUser() { + m_bSetByUser = false; +} + +bool ILuaConfigValue::setByUser() { + return m_bSetByUser; +} + +void ILuaConfigValue::setRefreshBits(Supplementary::PropRefreshBits bits) { + m_refreshBits = bits; +} + +Supplementary::PropRefreshBits ILuaConfigValue::refreshBits() const { + return m_refreshBits; +} diff --git a/src/config/lua/types/LuaConfigValue.hpp b/src/config/lua/types/LuaConfigValue.hpp new file mode 100644 index 00000000..2cce98e3 --- /dev/null +++ b/src/config/lua/types/LuaConfigValue.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include +#include + +#include "../../shared/Types.hpp" +#include "../../supplementary/propRefresher/PropRefresher.hpp" + +extern "C" { +#include +} + +namespace Config::Lua { + enum eParseError : uint8_t { + PARSE_ERROR_OK = 0, + PARSE_ERROR_OUT_OF_RANGE, + PARSE_ERROR_BAD_VALUE, + PARSE_ERROR_BAD_TYPE, + }; + + struct SParseError { + eParseError errorCode = PARSE_ERROR_OK; + std::string message; + }; + + class ILuaConfigValue { + protected: + ILuaConfigValue() = default; + bool m_bSetByUser = false; + + private: + Supplementary::PropRefreshBits m_refreshBits = 0; + + public: + virtual ~ILuaConfigValue() = default; + + virtual SParseError parse(lua_State* s) = 0; + virtual const std::type_info* underlying() = 0; + virtual void const* data() = 0; + virtual std::string toString() = 0; + virtual void push(lua_State* s) = 0; + + virtual void reset() = 0; + virtual void resetSetByUser(); + virtual bool setByUser(); + virtual void setRefreshBits(Supplementary::PropRefreshBits bits); + virtual Supplementary::PropRefreshBits refreshBits() const; + }; +}; diff --git a/src/config/lua/types/LuaConfigVec2.cpp b/src/config/lua/types/LuaConfigVec2.cpp new file mode 100644 index 00000000..5e92de62 --- /dev/null +++ b/src/config/lua/types/LuaConfigVec2.cpp @@ -0,0 +1,100 @@ +#include "LuaConfigVec2.hpp" + +#include +#include + +using namespace Config; +using namespace Config::Lua; + +CLuaConfigVec2::CLuaConfigVec2(Config::VEC2 def, std::optional(const Config::VEC2&)>>&& validator) : + m_default(def), m_data(def), m_validator(std::move(validator)) { + ; +} + +SParseError CLuaConfigVec2::parse(lua_State* s) { + Config::VEC2 vec = {}; + + if (lua_isstring(s, -1)) { + std::string input = lua_tostring(s, -1); + std::ranges::replace(input, ',', ' '); + + std::istringstream in(input); + double x = 0.F, y = 0.F; + std::string tail; + if (!(in >> x >> y) || (in >> tail)) + return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = "vec2 string requires exactly 2 numbers (e.g. \"1 1\")"}; + + vec = {x, y}; + } else { + if (!lua_istable(s, -1)) + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = "vec2 type requires an array or string"}; + + if (lua_rawlen(s, -1) != 2) + return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = "vec2 type requires exactly 2 elements"}; + + lua_rawgeti(s, -1, 1); + if (!lua_isnumber(s, -1)) { + lua_pop(s, 1); + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = "vec2 elements must be numbers"}; + } + double x = lua_tonumber(s, -1); + lua_pop(s, 1); + + lua_rawgeti(s, -1, 2); + if (!lua_isnumber(s, -1)) { + lua_pop(s, 1); + return {.errorCode = PARSE_ERROR_BAD_TYPE, .message = "vec2 elements must be numbers"}; + } + double y = lua_tonumber(s, -1); + lua_pop(s, 1); + + vec = {x, y}; + } + + if (m_validator.has_value()) { + auto res = m_validator.value()(vec); + if (!res) + return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = res.error()}; + } + + m_data = vec; + m_bSetByUser = true; + + return {.errorCode = PARSE_ERROR_OK}; +} + +const std::type_info* CLuaConfigVec2::underlying() { + return &typeid(decltype(m_data)); +} + +void const* CLuaConfigVec2::data() { + return &m_data; +} + +std::string CLuaConfigVec2::toString() { + return std::format("{} {}", (int)m_data.x, (int)m_data.y); +} + +void CLuaConfigVec2::push(lua_State* s) { + lua_createtable(s, 2, 2); + + lua_pushnumber(s, m_data.x); + lua_rawseti(s, -2, 1); + + lua_pushnumber(s, m_data.y); + lua_rawseti(s, -2, 2); + + lua_pushnumber(s, m_data.x); + lua_setfield(s, -2, "x"); + + lua_pushnumber(s, m_data.y); + lua_setfield(s, -2, "y"); +} + +const Config::VEC2& CLuaConfigVec2::parsed() { + return m_data; +} + +void CLuaConfigVec2::reset() { + m_data = m_default; +} diff --git a/src/config/lua/types/LuaConfigVec2.hpp b/src/config/lua/types/LuaConfigVec2.hpp new file mode 100644 index 00000000..c6560121 --- /dev/null +++ b/src/config/lua/types/LuaConfigVec2.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include "LuaConfigValue.hpp" + +#include +#include +#include + +namespace Config::Lua { + class CLuaConfigVec2 : public ILuaConfigValue { + public: + CLuaConfigVec2(Config::VEC2 def, std::optional(const Config::VEC2&)>>&& validator = std::nullopt); + virtual ~CLuaConfigVec2() = default; + + virtual SParseError parse(lua_State* s); + virtual const std::type_info* underlying(); + virtual void const* data(); + virtual std::string toString(); + virtual void push(lua_State* s); + virtual void reset(); + + const Config::VEC2& parsed(); + + private: + Config::VEC2 m_default = {}; + Config::VEC2 m_data = {}; + std::optional(const Config::VEC2&)>> m_validator; + }; +}; -- cgit v1.2.3