Debian Codegraph @

tests/config/lua/LuaBindingsInternal.cpp

raw symbols SCIP
1 #include <config/lua/bindings/LuaBindingsInternal.hpp>
2 #include <config/lua/ConfigManager.hpp>
3
4 #include <Compositor.hpp>
5
6 #include <config/lua/types/LuaConfigInt.hpp>
7
8 #include <gtest/gtest.h>
9
10 #include <algorithm>
11 #include <chrono>
12 #include <filesystem>
13 #include <format>
14 #include <fstream>
15
16 extern "C" {
17 #include <lualib.h>
18 #include <lauxlib.h>
19 }
20
21 using namespace Config::Lua;
22 using namespace Config::Lua::Bindings;
23
24 namespace Config::Lua {
25 class CConfigManagerPluginLuaTestAccessor {
26 public:
27 static void initializeLuaState(CConfigManager& mgr, lua_State* L) {
28 mgr.m_lua = L;
29 lua_pushlightuserdata(L, &mgr);
30 lua_setfield(L, LUA_REGISTRYINDEX, "hl_lua_manager");
31 }
32
33 static void initializeOwnedLuaState(CConfigManager& mgr, const std::filesystem::path& mainConfigPath) {
34 mgr.m_mainConfigPath = mainConfigPath.string();
35 mgr.m_configPaths.clear();
36 mgr.m_configPaths.emplace_back(mgr.m_mainConfigPath);
37 mgr.reinitLuaState();
38 }
39
40 static lua_State* luaState(CConfigManager& mgr) {
41 return mgr.m_lua;
42 }
43 };
44 }
45
46 namespace {
47 class CLuaState {
48 public:
49 CLuaState() : m_lua(luaL_newstate()) {
50 luaL_openlibs(m_lua);
51 }
52
53 ~CLuaState() {
54 if (m_lua)
55 lua_close(m_lua);
56 }
57
58 lua_State* get() const {
59 return m_lua;
60 }
61
62 private:
63 lua_State* m_lua = nullptr;
64 };
65
66 int testPluginFn(lua_State* L) {
67 lua_pushstring(L, "pong");
68 return 1;
69 }
70
71 class CTempDir {
72 public:
73 CTempDir() {
74 const auto NOW = std::chrono::steady_clock::now().time_since_epoch().count();
75 m_path = std::filesystem::temp_directory_path() / std::format("hyprland-lua-require-{}", NOW);
76 std::filesystem::create_directories(m_path);
77 }
78
79 ~CTempDir() {
80 std::error_code ec;
81 std::filesystem::remove_all(m_path, ec);
82 }
83
84 const std::filesystem::path& path() const {
85 return m_path;
86 }
87
88 private:
89 std::filesystem::path m_path;
90 };
91
92 class CScopedCompositor {
93 public:
94 CScopedCompositor() : m_prevCompositor(std::move(g_pCompositor)), m_prevKeybindManager(std::move(g_pKeybindManager)) {
95 g_pCompositor = makeUnique<CCompositor>(true);
96 g_pKeybindManager = makeUnique<CKeybindManager>();
97 }
98
99 ~CScopedCompositor() {
100 g_pKeybindManager = std::move(m_prevKeybindManager);
101 g_pCompositor = std::move(m_prevCompositor);
102 }
103
104 private:
105 UP<CCompositor> m_prevCompositor;
106 UP<CKeybindManager> m_prevKeybindManager;
107 };
108
109 std::string luaString(const std::string& value) {
110 std::string out = "\"";
111 for (const auto& c : value) {
112 if (c == '\\' || c == '"')
113 out += '\\';
114 out += c;
115 }
116 out += '"';
117 return out;
118 }
119
120 void writeFile(const std::filesystem::path& path, const std::string& content) {
121 std::filesystem::create_directories(path.parent_path());
122 std::ofstream file(path);
123 file << content;
124 }
125
126 std::string normalizedPath(const std::filesystem::path& path) {
127 return path.lexically_normal().string();
128 }
129
130 std::string packagePath(lua_State* L) {
131 lua_getglobal(L, "package");
132 lua_getfield(L, -1, "path");
133
134 std::string path;
135 if (const auto* value = lua_tostring(L, -1); value)
136 path = value;
137
138 lua_pop(L, 2);
139 return path;
140 }
141
142 void expectTracked(CConfigManager& mgr, const std::filesystem::path& path) {
143 const auto& paths = mgr.getConfigPaths();
144 EXPECT_NE(std::ranges::find(paths, normalizedPath(path)), paths.end());
145 }
146 }
147
148 TEST(ConfigLuaBindingsInternal, parseDirectionAliases) {
149 EXPECT_EQ(Internal::parseDirectionStr("left"), Math::DIRECTION_LEFT);
150 EXPECT_EQ(Internal::parseDirectionStr("l"), Math::DIRECTION_LEFT);
151 EXPECT_EQ(Internal::parseDirectionStr("right"), Math::DIRECTION_RIGHT);
152 EXPECT_EQ(Internal::parseDirectionStr("r"), Math::DIRECTION_RIGHT);
153 EXPECT_EQ(Internal::parseDirectionStr("up"), Math::DIRECTION_UP);
154 EXPECT_EQ(Internal::parseDirectionStr("t"), Math::DIRECTION_UP);
155 EXPECT_EQ(Internal::parseDirectionStr("down"), Math::DIRECTION_DOWN);
156 EXPECT_EQ(Internal::parseDirectionStr("b"), Math::DIRECTION_DOWN);
157 EXPECT_EQ(Internal::parseDirectionStr("???"), Math::DIRECTION_DEFAULT);
158 }
159
160 TEST(ConfigLuaBindingsInternal, parseToggleAliases) {
161 EXPECT_EQ(Internal::parseToggleStr(""), Config::Actions::TOGGLE_ACTION_TOGGLE);
162 EXPECT_EQ(Internal::parseToggleStr("toggle"), Config::Actions::TOGGLE_ACTION_TOGGLE);
163 EXPECT_EQ(Internal::parseToggleStr("enable"), Config::Actions::TOGGLE_ACTION_ENABLE);
164 EXPECT_EQ(Internal::parseToggleStr("on"), Config::Actions::TOGGLE_ACTION_ENABLE);
165 EXPECT_EQ(Internal::parseToggleStr("disable"), Config::Actions::TOGGLE_ACTION_DISABLE);
166 EXPECT_EQ(Internal::parseToggleStr("off"), Config::Actions::TOGGLE_ACTION_DISABLE);
167 }
168
169 TEST(ConfigLuaBindingsInternal, argStrConvertsStringsAndNumbers) {
170 CLuaState S;
171 const auto L = S.get();
172
173 lua_pushstring(L, "abc");
174 EXPECT_EQ(Internal::argStr(L, -1), "abc");
175 lua_pop(L, 1);
176
177 lua_pushnumber(L, 42);
178 EXPECT_EQ(Internal::argStr(L, -1), "42");
179 lua_pop(L, 1);
180 }
181
182 TEST(ConfigLuaBindingsInternal, tableOptHelpersReadOptionalFields) {
183 CLuaState S;
184 const auto L = S.get();
185
186 lua_createtable(L, 0, 5);
187 lua_pushstring(L, "value");
188 lua_setfield(L, -2, "s");
189 lua_pushnumber(L, 5.5);
190 lua_setfield(L, -2, "n");
191 lua_pushboolean(L, true);
192 lua_setfield(L, -2, "b");
193 lua_pushstring(L, "not-number");
194 lua_setfield(L, -2, "n2");
195 lua_pushnil(L);
196 lua_setfield(L, -2, "nilv");
197
198 EXPECT_EQ(Internal::tableOptStr(L, -1, "s").value_or(""), "value");
199 EXPECT_DOUBLE_EQ(Internal::tableOptNum(L, -1, "n").value_or(0), 5.5);
200 EXPECT_EQ(Internal::tableOptBool(L, -1, "b").value_or(false), true);
201 EXPECT_FALSE(Internal::tableOptNum(L, -1, "n2").has_value());
202 EXPECT_FALSE(Internal::tableOptStr(L, -1, "missing").has_value());
203 EXPECT_FALSE(Internal::tableOptBool(L, -1, "nilv").has_value());
204
205 lua_pop(L, 1);
206 }
207
208 TEST(ConfigLuaBindingsInternal, selectorHelpersAcceptStringAndNumberSelectors) {
209 CLuaState S;
210 const auto L = S.get();
211
212 lua_createtable(L, 0, 4);
213 lua_pushstring(L, "DP-1");
214 lua_setfield(L, -2, "monitor");
215 lua_pushnumber(L, 7);
216 lua_setfield(L, -2, "workspace");
217 lua_pushnumber(L, 1337);
218 lua_setfield(L, -2, "window");
219
220 EXPECT_EQ(Internal::tableOptMonitorSelector(L, -1, "monitor", "test.fn").value_or(""), "DP-1");
221 EXPECT_EQ(Internal::tableOptWorkspaceSelector(L, -1, "workspace", "test.fn").value_or(""), "7");
222 EXPECT_EQ(Internal::tableOptWindowSelector(L, -1, "window", "test.fn").value_or(""), "1337");
223
224 EXPECT_FALSE(Internal::tableOptMonitorSelector(L, -1, "missing", "test.fn").has_value());
225 EXPECT_FALSE(Internal::tableOptWorkspaceSelector(L, -1, "missing", "test.fn").has_value());
226 EXPECT_FALSE(Internal::tableOptWindowSelector(L, -1, "missing", "test.fn").has_value());
227
228 EXPECT_EQ(Internal::requireTableFieldMonitorSelector(L, -1, "monitor", "test.fn"), "DP-1");
229 EXPECT_EQ(Internal::requireTableFieldWorkspaceSelector(L, -1, "workspace", "test.fn"), "7");
230 EXPECT_EQ(Internal::requireTableFieldWindowSelector(L, -1, "window", "test.fn"), "1337");
231
232 lua_pop(L, 1);
233 }
234
235 TEST(ConfigLuaBindingsInternal, pushWindowUpvalAcceptsNumberAndStringSelectors) {
236 CLuaState S;
237 const auto L = S.get();
238
239 lua_createtable(L, 0, 1);
240 lua_pushnumber(L, 42);
241 lua_setfield(L, -2, "window");
242
243 Internal::pushWindowUpval(L, -1);
244 ASSERT_TRUE(lua_isstring(L, -1));
245 EXPECT_STREQ(lua_tostring(L, -1), "42");
246 lua_pop(L, 1);
247
248 lua_pushstring(L, "0xabc");
249 lua_setfield(L, -2, "window");
250
251 Internal::pushWindowUpval(L, -1);
252 ASSERT_TRUE(lua_isstring(L, -1));
253 EXPECT_STREQ(lua_tostring(L, -1), "0xabc");
254 lua_pop(L, 1);
255
256 lua_pushnil(L);
257 lua_setfield(L, -2, "window");
258
259 Internal::pushWindowUpval(L, -1);
260 EXPECT_TRUE(lua_isnil(L, -1));
261 lua_pop(L, 1);
262
263 lua_pop(L, 1);
264 }
265
266 TEST(ConfigLuaBindingsInternal, parseTableFieldMissingFieldAndPrefixedErrors) {
267 CLuaState S;
268 const auto L = S.get();
269
270 CLuaConfigInt parser(0);
271
272 lua_newtable(L);
273 auto err = Internal::parseTableField(L, -1, "required", parser);
274 EXPECT_EQ(err.errorCode, PARSE_ERROR_BAD_VALUE);
275 EXPECT_NE(err.message.find("missing required field"), std::string::npos);
276 lua_pop(L, 1);
277
278 lua_createtable(L, 0, 1);
279 lua_pushstring(L, "bad");
280 lua_setfield(L, -2, "count");
281
282 err = Internal::parseTableField(L, -1, "count", parser);
283 EXPECT_EQ(err.errorCode, PARSE_ERROR_BAD_TYPE);
284 EXPECT_NE(err.message.find("field \"count\":"), std::string::npos);
285 lua_pop(L, 1);
286 }
287
288 TEST(ConfigLuaBindingsInternal, pluginBindingIsTableWithLoadFunction) {
289 CLuaState S;
290 const auto L = S.get();
291
292 lua_newtable(L);
293 Internal::registerConfigRuleBindings(L, nullptr);
294
295 lua_getfield(L, -1, "plugin");
296 ASSERT_TRUE(lua_istable(L, -1));
297
298 lua_getfield(L, -1, "load");
299 EXPECT_TRUE(lua_isfunction(L, -1));
300 lua_pop(L, 1);
301
302 lua_pop(L, 2);
303 }
304
305 TEST(ConfigLuaBindingsInternal, pluginLuaFnIsUnloadedWithoutDanglingCall) {
306 CLuaState S;
307 const auto L = S.get();
308
309 auto PREVCOMPOSITOR = std::move(g_pCompositor);
310 g_pCompositor = makeUnique<CCompositor>(true);
311
312 CConfigManager mgr;
313 CConfigManagerPluginLuaTestAccessor::initializeLuaState(mgr, L);
314
315 lua_newtable(L);
316 Internal::registerConfigRuleBindings(L, &mgr);
317 lua_setglobal(L, "hl");
318
319 const auto HANDLE = reinterpret_cast<void*>(0x1BADB002);
320
321 const auto regResult = mgr.registerPluginLuaFunction(HANDLE, "demo", "ping", testPluginFn);
322 ASSERT_TRUE(regResult.has_value()) << regResult.error();
323
324 ASSERT_EQ(luaL_dostring(L, R"(
325 local f = hl.plugin.demo.ping
326 assert(type(f) == "function")
327 captured = f
328 local v = f()
329 assert(v == "pong")
330 )"),
331 LUA_OK);
332
333 mgr.onPluginUnload(HANDLE);
334
335 ASSERT_EQ(luaL_dostring(L, R"(
336 assert(hl.plugin.demo == nil)
337 )"),
338 LUA_OK);
339
340 ASSERT_EQ(luaL_dostring(L, R"(
341 local ok, err = pcall(captured)
342 assert(ok == false)
343 assert(type(err) == "string")
344 assert(string.find(err, "no longer available", 1, true) ~= nil)
345 )"),
346 LUA_OK);
347
348 g_pCompositor = std::move(PREVCOMPOSITOR);
349 }
350
351 TEST(ConfigLuaRequire, absolutePathLoadsAndTracksFile) {
352 CScopedCompositor compositor;
353 CTempDir tmp;
354 const auto mainConfig = tmp.path() / "hyprland.lua";
355 const auto module = tmp.path() / "absolute.lua";
356 writeFile(mainConfig, "");
357 writeFile(module, "return { value = 42 }");
358
359 CConfigManager mgr;
360 CConfigManagerPluginLuaTestAccessor::initializeOwnedLuaState(mgr, mainConfig);
361 const auto L = CConfigManagerPluginLuaTestAccessor::luaState(mgr);
362
363 const auto CODE = "mod = require(" + luaString(module.string()) + ")";
364 ASSERT_EQ(luaL_dostring(L, CODE.c_str()), LUA_OK) << lua_tostring(L, -1);
365
366 lua_getglobal(L, "mod");
367 ASSERT_TRUE(lua_istable(L, -1));
368 lua_getfield(L, -1, "value");
369 EXPECT_EQ(lua_tointeger(L, -1), 42);
370 lua_pop(L, 2);
371
372 expectTracked(mgr, module);
373 }
374
375 TEST(ConfigLuaRequire, relativePathResolvesFromConfigDirectory) {
376 CScopedCompositor compositor;
377 CTempDir tmp;
378 const auto mainConfig = tmp.path() / "hyprland.lua";
379 const auto module = tmp.path() / "modules" / "relative.lua";
380 writeFile(mainConfig, "");
381 writeFile(module, "return 'relative-ok'");
382
383 CConfigManager mgr;
384 CConfigManagerPluginLuaTestAccessor::initializeOwnedLuaState(mgr, mainConfig);
385 const auto L = CConfigManagerPluginLuaTestAccessor::luaState(mgr);
386
387 ASSERT_EQ(luaL_dostring(L, R"(
388 mod = require("./modules/relative.lua")
389 )"),
390 LUA_OK)
391 << lua_tostring(L, -1);
392
393 lua_getglobal(L, "mod");
394 ASSERT_TRUE(lua_isstring(L, -1));
395 EXPECT_STREQ(lua_tostring(L, -1), "relative-ok");
396 lua_pop(L, 1);
397
398 expectTracked(mgr, module);
399 }
400
401 TEST(ConfigLuaRequire, wildcardLoadsSortedTableAndTracksFilesAndDirectory) {
402 CScopedCompositor compositor;
403 CTempDir tmp;
404 const auto mainConfig = tmp.path() / "hyprland.lua";
405 const auto modulesDir = tmp.path() / "modules";
406 const auto moduleA = modulesDir / "a.lua";
407 const auto moduleB = modulesDir / "b.lua";
408 writeFile(mainConfig, "");
409 writeFile(moduleB, "return 'b'");
410 writeFile(moduleA, "return 'a'");
411
412 CConfigManager mgr;
413 CConfigManagerPluginLuaTestAccessor::initializeOwnedLuaState(mgr, mainConfig);
414 const auto L = CConfigManagerPluginLuaTestAccessor::luaState(mgr);
415
416 ASSERT_EQ(luaL_dostring(L, R"(
417 mods = require("./modules/*")
418 assert(#mods == 2)
419 assert(mods[1] == "a")
420 assert(mods[2] == "b")
421 )"),
422 LUA_OK)
423 << lua_tostring(L, -1);
424
425 expectTracked(mgr, modulesDir);
426 expectTracked(mgr, moduleA);
427 expectTracked(mgr, moduleB);
428 }
429
430 TEST(ConfigLuaRequire, wildcardNoMatchIsCatchableError) {
431 CScopedCompositor compositor;
432 CTempDir tmp;
433 const auto mainConfig = tmp.path() / "hyprland.lua";
434 writeFile(mainConfig, "");
435
436 CConfigManager mgr;
437 CConfigManagerPluginLuaTestAccessor::initializeOwnedLuaState(mgr, mainConfig);
438 const auto L = CConfigManagerPluginLuaTestAccessor::luaState(mgr);
439
440 ASSERT_EQ(luaL_dostring(L, R"(
441 ok, err = pcall(require, "./missing/*")
442 assert(ok == false)
443 assert(type(err) == "string")
444 assert(string.find(err, "module './missing/*' not found", 1, true) ~= nil)
445 )"),
446 LUA_OK)
447 << lua_tostring(L, -1);
448 }
449
450 TEST(ConfigLuaRequire, normalModuleRequireStillUsesConfigDirectoryPackagePath) {
451 CScopedCompositor compositor;
452 CTempDir tmp;
453 const auto mainConfig = tmp.path() / "hyprland.lua";
454 const auto module = tmp.path() / "colors.lua";
455 writeFile(mainConfig, "");
456 writeFile(module, "return 'normal-ok'");
457
458 CConfigManager mgr;
459 CConfigManagerPluginLuaTestAccessor::initializeOwnedLuaState(mgr, mainConfig);
460 const auto L = CConfigManagerPluginLuaTestAccessor::luaState(mgr);
461
462 ASSERT_EQ(luaL_dostring(L, R"(
463 mod = require("colors")
464 )"),
465 LUA_OK)
466 << lua_tostring(L, -1);
467
468 lua_getglobal(L, "mod");
469 ASSERT_TRUE(lua_isstring(L, -1));
470 EXPECT_STREQ(lua_tostring(L, -1), "normal-ok");
471 lua_pop(L, 1);
472
473 expectTracked(mgr, module);
474 }
475
476 TEST(ConfigLuaRequire, packagePathPreservesLuaDefaultsAfterConfigDirectory) {
477 CScopedCompositor compositor;
478 CLuaState defaultState;
479 CTempDir tmp;
480 const auto mainConfig = tmp.path() / "hyprland.lua";
481 writeFile(mainConfig, "");
482
483 const auto defaultPath = packagePath(defaultState.get());
484 ASSERT_FALSE(defaultPath.empty());
485
486 CConfigManager mgr;
487 CConfigManagerPluginLuaTestAccessor::initializeOwnedLuaState(mgr, mainConfig);
488
489 const auto configPath = (tmp.path() / "?.lua").string() + ";" + (tmp.path() / "?/init.lua").string();
490 EXPECT_EQ(packagePath(CConfigManagerPluginLuaTestAccessor::luaState(mgr)), configPath + ";" + defaultPath);
491 }