Debian Codegraph @

hyprtester/src/tests/clients/xdg-interactive.cpp

raw
1 #include "../../Log.hpp"
2 #include "../../hyprctlCompat.hpp"
3 #include "../shared.hpp"
4 #include "tests.hpp"
5 #include "build.hpp"
6
7 #include <hyprutils/os/FileDescriptor.hpp>
8 #include <hyprutils/os/Process.hpp>
9
10 #include <array>
11 #include <chrono>
12 #include <csignal>
13 #include <deque>
14 #include <optional>
15 #include <string>
16 #include <sys/poll.h>
17 #include <thread>
18 #include <unistd.h>
19
20 using namespace Hyprutils::OS;
21 using namespace Hyprutils::Memory;
22
23 #define SP CSharedPointer
24
25 namespace {
26 struct SGeometry {
27 int x = 0;
28 int y = 0;
29 int w = 0;
30 int h = 0;
31 };
32
33 struct SStatus {
34 int leave = 0;
35 int motionAfterRequest = 0;
36 uint32_t lastButton = 0;
37 int buttonPresses = 0;
38 bool resizing = false;
39 };
40
41 class CClient {
42 SP<CProcess> proc;
43 std::array<char, 2048> readBuf;
44 CFileDescriptor readFd, writeFd;
45 std::string pending;
46 std::deque<std::string> lines;
47 bool disconnected = false;
48
49 void parseLines();
50 bool readOnce(int timeoutMs);
51 std::optional<std::string> takeLineContaining(const std::string& marker);
52
53 public:
54 CClient();
55 ~CClient();
56
57 bool sendCommand(const std::string& command);
58 std::optional<std::string> waitLineContaining(const std::string& marker, int timeoutMs = 1500);
59 std::optional<uint32_t> waitButtonSerial();
60 std::optional<SStatus> status();
61 bool requestMove();
62 bool requestResize(const std::string& edge);
63 bool requestResizeWithSerial(uint32_t serial, const std::string& edge);
64 bool requestRawResize(uint32_t edge);
65 bool waitResizing(bool resizing);
66 bool waitForDisconnect(int timeoutMs = 1500);
67 pid_t pid() const;
68 };
69 }
70
71 static std::pair<int, int> parsePair(const std::string& str) {
72 const auto COMMA = str.find(',');
73 if (COMMA == std::string::npos)
74 return {0, 0};
75
76 return {std::stoi(str.substr(0, COMMA)), std::stoi(str.substr(COMMA + 1))};
77 }
78
79 static SGeometry activeGeometry() {
80 const auto RESPONSE = getFromSocket("/activewindow");
81 const auto AT = parsePair(Tests::getAttribute(RESPONSE, "at"));
82 const auto SIZE = parsePair(Tests::getAttribute(RESPONSE, "size"));
83 return {
84 .x = AT.first,
85 .y = AT.second,
86 .w = SIZE.first,
87 .h = SIZE.second,
88 };
89 }
90
91 static bool focusClient(pid_t pid) {
92 return getFromSocket(std::format("/dispatch hl.dsp.focus({{ window = 'pid:{}' }})", pid)) == "ok";
93 }
94
95 static bool setClientGeometry(pid_t pid, const SGeometry& geometry) {
96 if (!focusClient(pid)) {
97 NLog::log("{}Failed to focus xdg-interactive pid {}", Colors::RED, pid);
98 return false;
99 }
100
101 if (const auto RESPONSE = getFromSocket(std::format("/dispatch hl.dsp.window.float({{ action = 'enable', window = 'pid:{}' }})", pid)); RESPONSE != "ok") {
102 NLog::log("{}Failed to float xdg-interactive pid {}: {}", Colors::RED, pid, RESPONSE);
103 return false;
104 }
105
106 if (const auto RESPONSE = getFromSocket(std::format("/dispatch hl.dsp.window.resize({{ x = {}, y = {}, window = 'pid:{}' }})", geometry.w, geometry.h, pid));
107 RESPONSE != "ok") {
108 NLog::log("{}Failed to resize xdg-interactive pid {}: {}", Colors::RED, pid, RESPONSE);
109 return false;
110 }
111
112 if (const auto RESPONSE = getFromSocket(std::format("/dispatch hl.dsp.window.move({{ x = {}, y = {}, window = 'pid:{}' }})", geometry.x, geometry.y, pid)); RESPONSE != "ok") {
113 NLog::log("{}Failed to move xdg-interactive pid {}: {}", Colors::RED, pid, RESPONSE);
114 return false;
115 }
116
117 for (size_t i = 0; i < 50; ++i) {
118 if (!focusClient(pid))
119 return false;
120
121 const auto CURRENT = activeGeometry();
122 if (CURRENT.x == geometry.x && CURRENT.y == geometry.y && CURRENT.w == geometry.w && CURRENT.h == geometry.h)
123 return true;
124
125 std::this_thread::sleep_for(std::chrono::milliseconds(50));
126 }
127
128 const auto CURRENT = activeGeometry();
129 NLog::log("{}Timed out waiting for xdg-interactive geometry, expected {},{} {}x{}, got {},{} {}x{}", Colors::RED, geometry.x, geometry.y, geometry.w, geometry.h, CURRENT.x,
130 CURRENT.y, CURRENT.w, CURRENT.h);
131 return false;
132 }
133
134 static bool moveCursor(int x, int y) {
135 return getFromSocket(std::format("/dispatch hl.dsp.cursor.move({{ x = {}, y = {} }})", x, y)) == "ok";
136 }
137
138 static bool click(uint32_t button, bool pressed) {
139 return getFromSocket(std::format("/eval hl.plugin.test.click({}, {})", button, pressed ? 1 : 0)) == "ok";
140 }
141
142 static std::optional<int> statusValue(const std::string& line, const std::string& key) {
143 const auto KEY = key + "=";
144 auto pos = line.find(KEY);
145 if (pos == std::string::npos)
146 return std::nullopt;
147
148 pos += KEY.size();
149 auto end = line.find(' ', pos);
150 if (end == std::string::npos)
151 end = line.size();
152
153 try {
154 return std::stoi(line.substr(pos, end - pos));
155 } catch (...) { return std::nullopt; }
156 }
157
158 void CClient::parseLines() {
159 auto pos = pending.find('\n');
160 while (pos != std::string::npos) {
161 lines.emplace_back(pending.substr(0, pos));
162 pending.erase(0, pos + 1);
163 pos = pending.find('\n');
164 }
165 }
166
167 bool CClient::readOnce(int timeoutMs) {
168 if (disconnected)
169 return false;
170
171 pollfd fd = {.fd = readFd.get(), .events = POLLIN};
172 const int RET = poll(&fd, 1, timeoutMs);
173 if (RET <= 0)
174 return false;
175
176 if (!(fd.revents & POLLIN)) {
177 if (fd.revents & (POLLERR | POLLHUP | POLLNVAL))
178 disconnected = true;
179 return false;
180 }
181
182 const ssize_t BYTES = read(readFd.get(), readBuf.data(), readBuf.size() - 1);
183 if (BYTES <= 0) {
184 disconnected = true;
185 return false;
186 }
187
188 readBuf[BYTES] = 0;
189 pending += readBuf.data();
190 parseLines();
191 if (fd.revents & (POLLERR | POLLHUP | POLLNVAL))
192 disconnected = true;
193 return true;
194 }
195
196 std::optional<std::string> CClient::takeLineContaining(const std::string& marker) {
197 for (auto it = lines.begin(); it != lines.end(); ++it) {
198 if (!it->contains(marker))
199 continue;
200
201 auto line = *it;
202 lines.erase(it);
203 return line;
204 }
205
206 return std::nullopt;
207 }
208
209 CClient::CClient() {
210 NLog::log("{}Attempting to start xdg-interactive client", Colors::YELLOW);
211
212 proc = makeShared<CProcess>(binaryDir + "/xdg-interactive", std::vector<std::string>{});
213 proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY);
214
215 int procInPipeFd[2], procOutPipeFd[2];
216 if (pipe(procInPipeFd) != 0 || pipe(procOutPipeFd) != 0) {
217 NLog::log("{}Unable to open pipe to client", Colors::RED);
218 throw std::exception();
219 }
220
221 writeFd = CFileDescriptor(procInPipeFd[1]);
222 proc->setStdinFD(procInPipeFd[0]);
223
224 readFd = CFileDescriptor(procOutPipeFd[0]);
225 proc->setStdoutFD(procOutPipeFd[1]);
226
227 const int COUNT_BEFORE = Tests::windowCount();
228 if (!proc->runAsync()) {
229 NLog::log("{}Failed to run xdg-interactive client", Colors::RED);
230 throw std::exception();
231 }
232
233 close(procInPipeFd[0]);
234 close(procOutPipeFd[1]);
235
236 if (!waitLineContaining("started", 2000)) {
237 NLog::log("{}xdg-interactive client did not report startup", Colors::RED);
238 throw std::exception();
239 }
240
241 int counter = 0;
242 while (Tests::processAlive(proc->pid()) && Tests::windowCount() == COUNT_BEFORE) {
243 ++counter;
244 std::this_thread::sleep_for(std::chrono::milliseconds(100));
245
246 if (counter > 50) {
247 NLog::log("{}xdg-interactive client took too long to open", Colors::RED);
248 throw std::exception();
249 }
250 }
251
252 if (getFromSocket(std::format("/dispatch hl.dsp.window.set_prop({{ window = 'pid:{}', prop = 'no_anim', value = '1' }})", proc->pid())) != "ok") {
253 NLog::log("{}Failed to disable animations for xdg-interactive client", Colors::RED);
254 throw std::exception();
255 }
256
257 if (!focusClient(proc->pid())) {
258 NLog::log("{}Failed to focus xdg-interactive client", Colors::RED);
259 throw std::exception();
260 }
261
262 NLog::log("{}Started xdg-interactive client", Colors::YELLOW);
263 }
264
265 CClient::~CClient() {
266 if (!disconnected) {
267 std::string cmd = "exit\n";
268 write(writeFd.get(), cmd.c_str(), cmd.length());
269 }
270
271 if (proc)
272 kill(proc->pid(), SIGKILL);
273 proc.reset();
274 }
275
276 bool CClient::sendCommand(const std::string& command) {
277 if (disconnected)
278 return false;
279
280 return (size_t)write(writeFd.get(), command.c_str(), command.length()) == command.length();
281 }
282
283 std::optional<std::string> CClient::waitLineContaining(const std::string& marker, int timeoutMs) {
284 if (auto line = takeLineContaining(marker); line)
285 return line;
286
287 const auto START = std::chrono::steady_clock::now();
288 while (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - START).count() < timeoutMs) {
289 readOnce(50);
290 if (auto line = takeLineContaining(marker); line)
291 return line;
292
293 if (disconnected)
294 return std::nullopt;
295 }
296
297 return std::nullopt;
298 }
299
300 std::optional<uint32_t> CClient::waitButtonSerial() {
301 const auto LINE = waitLineContaining("button ");
302 if (!LINE)
303 return std::nullopt;
304
305 try {
306 return std::stoul(LINE->substr(LINE->find("button ") + 7));
307 } catch (...) { return std::nullopt; }
308 }
309
310 std::optional<SStatus> CClient::status() {
311 if (!sendCommand("status\n"))
312 return std::nullopt;
313
314 const auto LINE = waitLineContaining("status ");
315 if (!LINE)
316 return std::nullopt;
317
318 const auto LEAVE = statusValue(*LINE, "leave");
319 const auto MOTION = statusValue(*LINE, "motion_after_request");
320 const auto BUTTON = statusValue(*LINE, "last_button");
321 const auto PRESSES = statusValue(*LINE, "button_presses");
322 const auto RESIZING = statusValue(*LINE, "resizing");
323
324 if (!LEAVE || !MOTION || !BUTTON || !PRESSES || !RESIZING)
325 return std::nullopt;
326
327 return SStatus{
328 .leave = *LEAVE,
329 .motionAfterRequest = *MOTION,
330 .lastButton = static_cast<uint32_t>(*BUTTON),
331 .buttonPresses = *PRESSES,
332 .resizing = *RESIZING == 1,
333 };
334 }
335
336 bool CClient::requestMove() {
337 return sendCommand("move\n") && !!waitLineContaining("requested move");
338 }
339
340 bool CClient::requestResize(const std::string& edge) {
341 return sendCommand(std::format("resize {}\n", edge)) && !!waitLineContaining("requested resize");
342 }
343
344 bool CClient::requestResizeWithSerial(uint32_t serial, const std::string& edge) {
345 return sendCommand(std::format("resize-serial {} {}\n", serial, edge)) && !!waitLineContaining("requested resize");
346 }
347
348 bool CClient::requestRawResize(uint32_t edge) {
349 return sendCommand(std::format("resize-raw {}\n", edge)) && !!waitLineContaining("requested resize", 500);
350 }
351
352 bool CClient::waitResizing(bool resizing) {
353 return !!waitLineContaining(std::format("configure resizing={}", resizing ? 1 : 0), 2000);
354 }
355
356 bool CClient::waitForDisconnect(int timeoutMs) {
357 const auto START = std::chrono::steady_clock::now();
358 while (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - START).count() < timeoutMs) {
359 if (disconnected)
360 return true;
361
362 readOnce(50);
363 }
364
365 return disconnected;
366 }
367
368 pid_t CClient::pid() const {
369 return proc->pid();
370 }
371
372 TEST_CASE(xdgInteractive) {
373 Tests::killAllWindows();
374
375 std::optional<CClient> client;
376 try {
377 client.emplace();
378 } catch (...) { FAIL_TEST("Couldn't start the xdg-interactive client"); }
379
380 ASSERT(setClientGeometry(client->pid(), SGeometry{.x = 300, .y = 300, .w = 500, .h = 400}), true);
381
382 NLog::log("{}Testing xdg_toplevel.move", Colors::GREEN);
383 const auto START_MOVE_GEOMETRY = activeGeometry();
384 ASSERT(moveCursor(START_MOVE_GEOMETRY.x + 100, START_MOVE_GEOMETRY.y + 100), true);
385 Tests::sync(1);
386 ASSERT(click(272, true), true);
387 ASSERT(client->waitButtonSerial().has_value(), true);
388 ASSERT(client->requestMove(), true);
389 ASSERT(moveCursor(START_MOVE_GEOMETRY.x + 220, START_MOVE_GEOMETRY.y + 180), true);
390
391 const auto MOVE_STATUS = client->status();
392 ASSERT(MOVE_STATUS.has_value(), true);
393 if (MOVE_STATUS->leave < 1)
394 MARK_TEST_FAILED("xdg move should clear pointer focus and send leave, got {} leave events", MOVE_STATUS->leave);
395 else
396 LOG_OK("xdg move sent {} leave events", MOVE_STATUS->leave);
397 EXPECT(MOVE_STATUS->motionAfterRequest, 0);
398
399 ASSERT(click(272, false), true);
400 const auto END_MOVE_GEOMETRY = activeGeometry();
401 EXPECT_MAX_DELTA(END_MOVE_GEOMETRY.x, START_MOVE_GEOMETRY.x + 120, 5);
402 EXPECT_MAX_DELTA(END_MOVE_GEOMETRY.y, START_MOVE_GEOMETRY.y + 80, 5);
403 EXPECT_MAX_DELTA(END_MOVE_GEOMETRY.w, START_MOVE_GEOMETRY.w, 2);
404 EXPECT_MAX_DELTA(END_MOVE_GEOMETRY.h, START_MOVE_GEOMETRY.h, 2);
405
406 NLog::log("{}Testing xdg_toplevel.resize right", Colors::GREEN);
407 ASSERT(setClientGeometry(client->pid(), SGeometry{.x = 400, .y = 300, .w = 500, .h = 400}), true);
408 ASSERT_CONTAINS(getFromSocket("/activewindow"), "floating: 1");
409 const auto START_RESIZE_GEOMETRY = activeGeometry();
410 ASSERT(moveCursor(START_RESIZE_GEOMETRY.x + 250, START_RESIZE_GEOMETRY.y + 200), true);
411 Tests::sync(1);
412 ASSERT(click(272, true), true);
413 ASSERT(client->waitButtonSerial().has_value(), true);
414 ASSERT(client->requestResize("right"), true);
415 ASSERT(client->waitResizing(true), true);
416 ASSERT(moveCursor(START_RESIZE_GEOMETRY.x + 410, START_RESIZE_GEOMETRY.y + 200), true);
417
418 bool resized = false;
419 for (size_t i = 0; i < 50; ++i) {
420 moveCursor(START_RESIZE_GEOMETRY.x + 410, START_RESIZE_GEOMETRY.y + 200);
421
422 if (activeGeometry().w >= START_RESIZE_GEOMETRY.w + 150) {
423 resized = true;
424 break;
425 }
426
427 std::this_thread::sleep_for(std::chrono::milliseconds(50));
428 }
429
430 if (!resized)
431 MARK_TEST_FAILED("xdg resize did not update geometry before release");
432
433 ASSERT(click(272, false), true);
434 ASSERT(client->waitResizing(false), true);
435
436 const auto END_RESIZE_GEOMETRY = activeGeometry();
437 EXPECT_MAX_DELTA(END_RESIZE_GEOMETRY.x, START_RESIZE_GEOMETRY.x, 2);
438 EXPECT_MAX_DELTA(END_RESIZE_GEOMETRY.y, START_RESIZE_GEOMETRY.y, 2);
439 EXPECT_MAX_DELTA(END_RESIZE_GEOMETRY.w, START_RESIZE_GEOMETRY.w + 160, 5);
440 EXPECT_MAX_DELTA(END_RESIZE_GEOMETRY.h, START_RESIZE_GEOMETRY.h, 2);
441
442 NLog::log("{}Testing stale xdg resize serial is ignored", Colors::GREEN);
443 ASSERT(setClientGeometry(client->pid(), SGeometry{.x = 500, .y = 300, .w = 500, .h = 400}), true);
444 const auto STALE_GEOMETRY = activeGeometry();
445 ASSERT(moveCursor(STALE_GEOMETRY.x + 250, STALE_GEOMETRY.y + 200), true);
446 Tests::sync(1);
447 ASSERT(click(272, true), true);
448 const auto STALE_SERIAL = client->waitButtonSerial();
449 ASSERT(STALE_SERIAL.has_value(), true);
450 ASSERT(click(272, false), true);
451 ASSERT(client->requestResizeWithSerial(*STALE_SERIAL, "right"), true);
452 ASSERT(moveCursor(STALE_GEOMETRY.x + 380, STALE_GEOMETRY.y + 200), true);
453
454 const auto AFTER_STALE_GEOMETRY = activeGeometry();
455 EXPECT_MAX_DELTA(AFTER_STALE_GEOMETRY.x, STALE_GEOMETRY.x, 2);
456 EXPECT_MAX_DELTA(AFTER_STALE_GEOMETRY.y, STALE_GEOMETRY.y, 2);
457 EXPECT_MAX_DELTA(AFTER_STALE_GEOMETRY.w, STALE_GEOMETRY.w, 2);
458 EXPECT_MAX_DELTA(AFTER_STALE_GEOMETRY.h, STALE_GEOMETRY.h, 2);
459
460 NLog::log("{}Testing invalid xdg resize edge causes protocol disconnect", Colors::GREEN);
461 ASSERT(moveCursor(AFTER_STALE_GEOMETRY.x + 250, AFTER_STALE_GEOMETRY.y + 200), true);
462 Tests::sync(1);
463 ASSERT(click(272, true), true);
464 ASSERT(client->waitButtonSerial().has_value(), true);
465 ASSERT(client->requestRawResize(123), true);
466 ASSERT(client->waitForDisconnect(), true);
467 EXPECT_NOT(getFromSocket("/clients"), "");
468
469 client.reset();
470 Tests::killAllWindows();
471 }