Debian Codegraph @

hyprtester/clients/xdg-interactive.cpp

raw
1 #include <algorithm>
2 #include <array>
3 #include <cerrno>
4 #include <format>
5 #include <optional>
6 #include <print>
7 #include <sstream>
8 #include <string>
9 #include <sys/mman.h>
10 #include <sys/poll.h>
11 #include <utility>
12 #include <fcntl.h>
13 #include <unistd.h>
14
15 #include <wayland-client.h>
16 #include <wayland.hpp>
17 #include <xdg-shell.hpp>
18
19 #include <hyprutils/math/Vector2D.hpp>
20 #include <hyprutils/memory/SharedPtr.hpp>
21
22 using Hyprutils::Math::Vector2D;
23 using namespace Hyprutils::Memory;
24
25 struct SWlState {
26 wl_display* display = nullptr;
27 CSharedPointer<CCWlRegistry> registry;
28
29 CSharedPointer<CCWlCompositor> wlCompositor;
30 CSharedPointer<CCWlSeat> wlSeat;
31 CSharedPointer<CCWlShm> wlShm;
32 CSharedPointer<CCXdgWmBase> xdgShell;
33
34 CSharedPointer<CCWlShmPool> shmPool;
35 CSharedPointer<CCWlBuffer> shmBuf;
36 int shmFd = -1;
37 size_t shmBufSize = 0;
38 bool xrgb8888_support = false;
39
40 CSharedPointer<CCWlSurface> surf;
41 CSharedPointer<CCXdgSurface> xdgSurf;
42 CSharedPointer<CCXdgToplevel> xdgToplevel;
43 Vector2D geom = {500, 400};
44
45 CSharedPointer<CCWlPointer> pointer;
46 uint32_t enterSerial = 0;
47 uint32_t lastButtonSerial = 0;
48 bool requestActive = false;
49 bool resizing = false;
50 uint32_t leaveAfterRequest = 0;
51 uint32_t motionAfterRequest = 0;
52 uint32_t buttonPresses = 0;
53 };
54
55 static bool debug, started, shouldExit;
56
57 template <typename... Args>
58 //NOLINTNEXTLINE
59 static void clientLog(std::format_string<Args...> fmt, Args&&... args) {
60 std::println("{}", std::format(fmt, std::forward<Args>(args)...));
61 std::fflush(stdout);
62 }
63
64 template <typename... Args>
65 //NOLINTNEXTLINE
66 static void debugLog(std::format_string<Args...> fmt, Args&&... args) {
67 if (!debug)
68 return;
69
70 std::println("{}", std::format(fmt, std::forward<Args>(args)...));
71 std::fflush(stdout);
72 }
73
74 static bool stateArrayContains(wl_array* arr, uint32_t state) {
75 if (!arr || !arr->data)
76 return false;
77
78 const auto* states = static_cast<const uint32_t*>(arr->data);
79 for (size_t i = 0; i < arr->size / sizeof(uint32_t); ++i) {
80 if (states[i] == state)
81 return true;
82 }
83
84 return false;
85 }
86
87 static std::optional<xdgToplevelResizeEdge> edgeFromString(const std::string& edge) {
88 if (edge == "none")
89 return XDG_TOPLEVEL_RESIZE_EDGE_NONE;
90 if (edge == "top")
91 return XDG_TOPLEVEL_RESIZE_EDGE_TOP;
92 if (edge == "bottom")
93 return XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM;
94 if (edge == "left")
95 return XDG_TOPLEVEL_RESIZE_EDGE_LEFT;
96 if (edge == "right")
97 return XDG_TOPLEVEL_RESIZE_EDGE_RIGHT;
98 if (edge == "top_left")
99 return XDG_TOPLEVEL_RESIZE_EDGE_TOP_LEFT;
100 if (edge == "top_right")
101 return XDG_TOPLEVEL_RESIZE_EDGE_TOP_RIGHT;
102 if (edge == "bottom_left")
103 return XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_LEFT;
104 if (edge == "bottom_right")
105 return XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_RIGHT;
106
107 return std::nullopt;
108 }
109
110 static bool bindRegistry(SWlState& state) {
111 state.registry = makeShared<CCWlRegistry>((wl_proxy*)wl_display_get_registry(state.display));
112
113 state.registry->setGlobal([&](CCWlRegistry* r, uint32_t id, const char* name, uint32_t version) {
114 const std::string NAME = name;
115 if (NAME == "wl_compositor") {
116 debugLog(" > binding to global: {} (version {}) with id {}", name, version, id);
117 state.wlCompositor = makeShared<CCWlCompositor>((wl_proxy*)wl_registry_bind((wl_registry*)state.registry->resource(), id, &wl_compositor_interface, 6));
118 } else if (NAME == "wl_shm") {
119 debugLog(" > binding to global: {} (version {}) with id {}", name, version, id);
120 state.wlShm = makeShared<CCWlShm>((wl_proxy*)wl_registry_bind((wl_registry*)state.registry->resource(), id, &wl_shm_interface, 1));
121 } else if (NAME == "wl_seat") {
122 debugLog(" > binding to global: {} (version {}) with id {}", name, version, id);
123 state.wlSeat = makeShared<CCWlSeat>((wl_proxy*)wl_registry_bind((wl_registry*)state.registry->resource(), id, &wl_seat_interface, 9));
124 } else if (NAME == "xdg_wm_base") {
125 debugLog(" > binding to global: {} (version {}) with id {}", name, version, id);
126 state.xdgShell = makeShared<CCXdgWmBase>((wl_proxy*)wl_registry_bind((wl_registry*)state.registry->resource(), id, &xdg_wm_base_interface, 1));
127 }
128 });
129 state.registry->setGlobalRemove([](CCWlRegistry* r, uint32_t id) { debugLog("Global {} removed", id); });
130
131 wl_display_roundtrip(state.display);
132
133 if (!state.wlCompositor || !state.wlShm || !state.wlSeat || !state.xdgShell) {
134 clientLog("Failed to get protocols from Hyprland");
135 return false;
136 }
137
138 return true;
139 }
140
141 static bool createShm(SWlState& state, Vector2D geom) {
142 if (!state.xrgb8888_support)
143 return false;
144
145 const int width = std::max(1, static_cast<int>(geom.x));
146 const int height = std::max(1, static_cast<int>(geom.y));
147 size_t stride = width * 4;
148 size_t size = height * stride;
149
150 if (!state.shmPool) {
151 const std::string name = std::format("/wl-shm-xdg-interactive-{}", getpid());
152 state.shmFd = shm_open(name.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600);
153 if (state.shmFd < 0)
154 return false;
155
156 if (shm_unlink(name.c_str()) < 0 || ftruncate(state.shmFd, size) < 0) {
157 close(state.shmFd);
158 state.shmFd = -1;
159 return false;
160 }
161
162 state.shmPool = makeShared<CCWlShmPool>(state.wlShm->sendCreatePool(state.shmFd, size));
163 if (!state.shmPool->resource()) {
164 close(state.shmFd);
165 state.shmFd = -1;
166 state.shmPool.reset();
167 return false;
168 }
169
170 state.shmBufSize = size;
171 } else if (size > state.shmBufSize) {
172 if (ftruncate(state.shmFd, size) < 0) {
173 close(state.shmFd);
174 state.shmFd = -1;
175 state.shmPool.reset();
176 return false;
177 }
178
179 state.shmPool->sendResize(size);
180 state.shmBufSize = size;
181 }
182
183 auto buf = makeShared<CCWlBuffer>(state.shmPool->sendCreateBuffer(0, width, height, stride, WL_SHM_FORMAT_XRGB8888));
184 if (!buf->resource())
185 return false;
186
187 if (state.shmBuf) {
188 state.shmBuf->sendDestroy();
189 state.shmBuf.reset();
190 }
191
192 state.shmBuf = buf;
193
194 return true;
195 }
196
197 static bool setupToplevel(SWlState& state) {
198 state.wlShm->setFormat([&](CCWlShm* p, uint32_t format) {
199 if (format == WL_SHM_FORMAT_XRGB8888)
200 state.xrgb8888_support = true;
201 });
202
203 state.xdgShell->setPing([&](CCXdgWmBase* p, uint32_t serial) { state.xdgShell->sendPong(serial); });
204
205 state.surf = makeShared<CCWlSurface>(state.wlCompositor->sendCreateSurface());
206 if (!state.surf->resource())
207 return false;
208
209 state.xdgSurf = makeShared<CCXdgSurface>(state.xdgShell->sendGetXdgSurface(state.surf->resource()));
210 if (!state.xdgSurf->resource())
211 return false;
212
213 state.xdgToplevel = makeShared<CCXdgToplevel>(state.xdgSurf->sendGetToplevel());
214 if (!state.xdgToplevel->resource())
215 return false;
216
217 state.xdgToplevel->setClose([&](CCXdgToplevel* p) { shouldExit = true; });
218
219 state.xdgToplevel->setConfigure([&](CCXdgToplevel* p, int32_t w, int32_t h, wl_array* arr) {
220 if (w > 0)
221 state.geom.x = w;
222 if (h > 0)
223 state.geom.y = h;
224
225 if (!createShm(state, state.geom))
226 exit(-1);
227
228 const bool RESIZING = stateArrayContains(arr, XDG_TOPLEVEL_STATE_RESIZING);
229 if (started && RESIZING != state.resizing)
230 clientLog("configure resizing={}", RESIZING ? 1 : 0);
231
232 state.resizing = RESIZING;
233 });
234
235 state.xdgSurf->setConfigure([&](CCXdgSurface* p, uint32_t serial) {
236 if (!state.shmBuf)
237 debugLog("xdgSurf configure but no buf made yet?");
238
239 state.xdgSurf->sendSetWindowGeometry(0, 0, state.geom.x, state.geom.y);
240 state.xdgSurf->sendAckConfigure(serial);
241 state.surf->sendAttach(state.shmBuf.get(), 0, 0);
242 state.surf->sendCommit();
243
244 if (!started) {
245 started = true;
246 clientLog("started");
247 }
248 });
249
250 state.xdgToplevel->sendSetTitle("xdg interactive test client");
251 state.xdgToplevel->sendSetAppId("xdg-interactive");
252
253 state.surf->sendAttach(nullptr, 0, 0);
254 state.surf->sendCommit();
255
256 return true;
257 }
258
259 static bool setupSeat(SWlState& state) {
260 state.pointer = makeShared<CCWlPointer>(state.wlSeat->sendGetPointer());
261 if (!state.pointer->resource())
262 return false;
263
264 state.pointer->setEnter([&](CCWlPointer* p, uint32_t serial, wl_proxy* surf, wl_fixed_t x, wl_fixed_t y) {
265 debugLog("Got pointer enter event, serial {}, x {}, y {}", serial, x, y);
266 state.enterSerial = serial;
267 });
268
269 state.pointer->setLeave([&](CCWlPointer* p, uint32_t serial, wl_proxy* surf) {
270 debugLog("Got pointer leave event, serial {}", serial);
271 if (state.requestActive)
272 ++state.leaveAfterRequest;
273 });
274
275 state.pointer->setMotion([&](CCWlPointer* p, uint32_t time, wl_fixed_t x, wl_fixed_t y) {
276 debugLog("Got pointer motion event, time {}, x {}, y {}", time, x, y);
277 if (state.requestActive)
278 ++state.motionAfterRequest;
279 });
280
281 state.pointer->setButton([&](CCWlPointer* p, uint32_t serial, uint32_t time, uint32_t button, wl_pointer_button_state buttonState) {
282 debugLog("Got pointer button event, serial {}, button {}, state {}", serial, button, static_cast<uint32_t>(buttonState));
283 if (buttonState != WL_POINTER_BUTTON_STATE_PRESSED)
284 return;
285
286 state.lastButtonSerial = serial;
287 ++state.buttonPresses;
288 clientLog("button {}", serial);
289 });
290
291 return true;
292 }
293
294 static void resetRequestCounters(SWlState& state) {
295 state.requestActive = true;
296 state.leaveAfterRequest = 0;
297 state.motionAfterRequest = 0;
298 }
299
300 static void requestMove(SWlState& state, uint32_t serial) {
301 resetRequestCounters(state);
302 state.xdgToplevel->sendMove(state.wlSeat->resource(), serial);
303 wl_display_flush(state.display);
304 clientLog("requested move {}", serial);
305 }
306
307 static void requestResize(SWlState& state, uint32_t serial, xdgToplevelResizeEdge edge) {
308 resetRequestCounters(state);
309 state.xdgToplevel->sendResize(state.wlSeat->resource(), serial, edge);
310 wl_display_flush(state.display);
311 clientLog("requested resize {} {}", serial, static_cast<uint32_t>(edge));
312 }
313
314 static void parseRequest(SWlState& state, std::string req) {
315 const auto nl = req.find('\n');
316 if (nl != std::string::npos)
317 req = req.substr(0, nl);
318
319 std::istringstream iss(req);
320 std::string command;
321 iss >> command;
322
323 if (command == "exit") {
324 shouldExit = true;
325 } else if (command == "move") {
326 requestMove(state, state.lastButtonSerial);
327 } else if (command == "move-serial") {
328 uint32_t serial = 0;
329 iss >> serial;
330 requestMove(state, serial);
331 } else if (command == "resize") {
332 std::string edgeName;
333 iss >> edgeName;
334
335 const auto EDGE = edgeFromString(edgeName);
336 if (!EDGE) {
337 clientLog("unknown edge {}", edgeName);
338 return;
339 }
340
341 requestResize(state, state.lastButtonSerial, *EDGE);
342 } else if (command == "resize-serial") {
343 uint32_t serial = 0;
344 std::string edgeName;
345 iss >> serial >> edgeName;
346
347 const auto EDGE = edgeFromString(edgeName);
348 if (!EDGE) {
349 clientLog("unknown edge {}", edgeName);
350 return;
351 }
352
353 requestResize(state, serial, *EDGE);
354 } else if (command == "resize-raw") {
355 uint32_t edge = 0;
356 iss >> edge;
357 requestResize(state, state.lastButtonSerial, static_cast<xdgToplevelResizeEdge>(edge));
358 } else if (command == "status") {
359 clientLog("status leave={} motion_after_request={} last_button={} button_presses={} resizing={}", state.leaveAfterRequest, state.motionAfterRequest, state.lastButtonSerial,
360 state.buttonPresses, state.resizing ? 1 : 0);
361 }
362 }
363
364 static bool dispatchDisplay(SWlState& state) {
365 wl_display_flush(state.display);
366
367 if (wl_display_prepare_read(state.display) == 0) {
368 if (wl_display_read_events(state.display) == -1)
369 return false;
370 if (wl_display_dispatch_pending(state.display) == -1)
371 return false;
372 } else if (wl_display_dispatch_pending(state.display) == -1)
373 return false;
374
375 int ret = 0;
376 do {
377 ret = wl_display_dispatch_pending(state.display);
378 wl_display_flush(state.display);
379 } while (ret > 0);
380
381 return ret != -1;
382 }
383
384 int main(int argc, char** argv) {
385 if (argc != 1 && argc != 2)
386 clientLog("Only the \"--debug\" switch is allowed, it turns on debug logs.");
387
388 if (argc == 2 && std::string{argv[1]} == "--debug")
389 debug = true;
390
391 SWlState state;
392
393 state.display = wl_display_connect(nullptr);
394 if (!state.display) {
395 clientLog("Failed to connect to wayland display");
396 return -1;
397 }
398
399 if (!bindRegistry(state) || !setupSeat(state) || !setupToplevel(state))
400 return -1;
401
402 std::array<char, 1024> readBuf;
403 readBuf.fill(0);
404
405 wl_display_flush(state.display);
406
407 struct pollfd fds[2] = {{.fd = wl_display_get_fd(state.display), .events = POLLIN}, {.fd = STDIN_FILENO, .events = POLLIN}};
408 while (!shouldExit) {
409 const int RET = poll(fds, 2, 50);
410 if (RET == -1) {
411 if (errno == EINTR)
412 continue;
413 break;
414 }
415
416 if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL))
417 break;
418
419 if (fds[0].revents & POLLIN && !dispatchDisplay(state))
420 break;
421
422 if (fds[1].revents & (POLLERR | POLLHUP | POLLNVAL))
423 break;
424
425 if (fds[1].revents & POLLIN) {
426 ssize_t bytesRead = read(fds[1].fd, readBuf.data(), readBuf.size() - 1);
427 if (bytesRead <= 0)
428 continue;
429 readBuf[bytesRead] = 0;
430
431 parseRequest(state, std::string{readBuf.data()});
432 }
433 }
434
435 wl_display* display = state.display;
436 if (state.shmFd >= 0)
437 close(state.shmFd);
438 state = {};
439
440 wl_display_disconnect(display);
441 return 0;
442 }