Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
virtual_display.cpp
Go to the documentation of this file.
1
12
13// standard includes
14#include <atomic>
15#include <algorithm>
16#include <array>
17#include <chrono>
18#include <cctype>
19#include <cerrno>
20#include <cstdarg>
21#include <cstddef>
22#include <cmath>
23#include <cstdio>
24#include <cstdlib>
25#include <cstring>
26#include <dlfcn.h>
27#include <filesystem>
28#include <fstream>
29#include <limits>
30#include <map>
31#include <mutex>
32#include <optional>
33#include <set>
34#include <sstream>
35#include <thread>
36#include <vector>
37
38// third-party includes
39#include <nlohmann/json.hpp>
40
41// platform includes
42#include <csignal>
43#include <fcntl.h>
44#include <linux/i2c-dev.h>
45#include <poll.h>
46#include <sys/wait.h>
47#include <sys/ioctl.h>
48#include <sys/socket.h>
49#include <sys/stat.h>
50#include <sys/sysmacros.h>
51#include <sys/un.h>
52#include <sys/utsname.h>
53#include <unistd.h>
54#ifdef HERMES_BUILD_SDBUS
55 #include <systemd/sd-bus.h>
56 #include <systemd/sd-login.h>
57#endif
58#include <xf86drm.h>
59#include <xf86drmMode.h>
60
61// local includes
62#include "bounded_command.h"
63#include "card_broker.h"
64#include "hermes_kms_capture.h"
65#include "misc.h"
66#include "src/config.h"
67#include "src/logging.h"
68#include "src/utility.h"
69#include "virtual_display.h"
70#include "window_placement.h"
71#ifdef HERMES_BUILD_WAYLAND
72 #include "wayland.h"
73#endif
74
75using namespace std::literals;
76namespace fs = std::filesystem;
77
78namespace VDISPLAY {
79
80 std::string systemdUserBusAddress(uint32_t uid) {
81 return "unix:path=/run/user/" + std::to_string(uid) + "/bus";
82 }
83
85 static bool unix_socket_answers(const std::string &path, bool abstract_namespace = false) {
86 sockaddr_un address {};
87 address.sun_family = AF_UNIX;
88 // An abstract name starts with a NUL byte and is not NUL-terminated.
89 const size_t offset = abstract_namespace ? 1 : 0;
90 if (path.empty() || path.size() + offset >= sizeof(address.sun_path)) {
91 return false;
92 }
93 std::memcpy(address.sun_path + offset, path.data(), path.size());
94 const auto length = static_cast<socklen_t>(offsetof(sockaddr_un, sun_path) + offset + path.size());
95
96 const int fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
97 if (fd < 0) {
98 return false;
99 }
100 // A listening Unix socket accepts at once or refuses at once; EAGAIN means
101 // its backlog is full, which still means somebody is there.
102 const bool answers = ::connect(fd, reinterpret_cast<const sockaddr *>(&address), length) == 0 || errno == EAGAIN;
103 ::close(fd);
104 return answers;
105 }
106
107 bool displayServerReachable(const std::string &wayland_display, const std::string &x_display, const std::string &runtime_dir) {
108 if (!wayland_display.empty()) {
109 const auto socket_path = wayland_display.front() == '/' ? wayland_display : runtime_dir + "/" + wayland_display;
110 if (unix_socket_answers(socket_path)) {
111 return true;
112 }
113 }
114 if (!x_display.empty()) {
115 // "host:display.screen". Only a local display has a socket to try; a
116 // remote one is the business of whoever set it.
117 const auto colon = x_display.rfind(':');
118 if (colon == std::string::npos) {
119 return false;
120 }
121 const auto host = x_display.substr(0, colon);
122 if (!host.empty() && host != "unix") {
123 return true;
124 }
125 const auto number = x_display.substr(colon + 1, x_display.find('.', colon) - colon - 1);
126 if (number.empty() || number.find_first_not_of("0123456789") != std::string::npos) {
127 return false;
128 }
129 const auto socket_path = "/tmp/.X11-unix/X" + number;
130 return unix_socket_answers(socket_path) || unix_socket_answers(socket_path, true);
131 }
132 return false;
133 }
134
135 std::optional<bool> graphicalSessionPresent() {
136#ifdef HERMES_BUILD_SDBUS
137 char *session_raw = nullptr;
138 const int status = sd_uid_get_display(::getuid(), &session_raw);
139 const std::unique_ptr<char, decltype(&std::free)> session {session_raw, &std::free};
140 if (status == -ENODATA || status == -ENXIO) {
141 return false; // logind knows this user and has no graphical session for it.
142 }
143 if (status < 0) {
144 return std::nullopt;
145 }
146 if (!session || !*session) {
147 return false;
148 }
149 // With no desktop, logind names whatever session the user has as its
150 // display, an SSH login included. Only a Wayland or X11 one is graphical.
151 char *type_raw = nullptr;
152 if (sd_session_get_type(session.get(), &type_raw) < 0) {
153 return std::nullopt;
154 }
155 const std::unique_ptr<char, decltype(&std::free)> type {type_raw, &std::free};
156 const std::string_view kind {type.get() ? type.get() : ""};
157 return kind == "wayland" || kind == "x11" || kind == "mir";
158#else
159 return std::nullopt;
160#endif
161 }
162
164#ifdef HERMES_BUILD_SDBUS
165 char *session_raw = nullptr;
166 const int status = sd_pid_get_session(0, &session_raw);
167 std::free(session_raw);
168 return status >= 0;
169#else
170 return false;
171#endif
172 }
173
174 std::optional<std::vector<std::string>> userManagerEnvironment() {
175#ifdef HERMES_BUILD_SDBUS
176 sd_bus *bus = nullptr;
177 if (platf::open_user_bus(&bus) < 0 || !bus) {
178 return std::nullopt;
179 }
180 const std::unique_ptr<sd_bus, decltype(&sd_bus_unref)> bus_guard {bus, &sd_bus_unref};
181
182 sd_bus_error error = SD_BUS_ERROR_NULL;
183 sd_bus_message *reply = nullptr;
184 const int status = sd_bus_get_property(
185 bus,
186 "org.freedesktop.systemd1",
187 "/org/freedesktop/systemd1",
188 "org.freedesktop.systemd1.Manager",
189 "Environment",
190 &error,
191 &reply,
192 "as"
193 );
194 sd_bus_error_free(&error);
195 const std::unique_ptr<sd_bus_message, decltype(&sd_bus_message_unref)> reply_guard {reply, &sd_bus_message_unref};
196 if (status < 0 || !reply || sd_bus_message_enter_container(reply, 'a', "s") < 0) {
197 return std::nullopt;
198 }
199
200 std::vector<std::string> environment;
201 const char *assignment = nullptr;
202 while (sd_bus_message_read_basic(reply, 's', &assignment) > 0) {
203 environment.emplace_back(assignment);
204 }
205 return environment;
206#else
207 return std::nullopt;
208#endif
209 }
210
212#ifdef HERMES_BUILD_SDBUS
213 // Hermes normally runs as a systemd user service, so its own PID is not a
214 // reliable way to identify the graphical login session. Ask sd-login for
215 // this uid's display session instead; this is the same session loginctl
216 // reports in the user's Display= field.
217 char *session_id_raw = nullptr;
218 const int display_status = sd_uid_get_display(::getuid(), &session_id_raw);
219 if (display_status < 0 || !session_id_raw || !*session_id_raw) {
220 BOOST_LOG(warning) << "[Session] Could not identify the active graphical login session: "
221 << (display_status < 0 ? std::strerror(-display_status) : "no display session was returned");
222 std::free(session_id_raw);
223 return false;
224 }
225 const std::string session_id {session_id_raw};
226 std::free(session_id_raw);
227
228 sd_bus *bus = nullptr;
229 int status = sd_bus_open_system(&bus);
230 if (status < 0 || !bus) {
231 BOOST_LOG(warning) << "[Session] Could not connect to systemd-logind: "
232 << (status < 0 ? std::strerror(-status) : "no system bus connection was returned");
233 if (bus) {
234 sd_bus_unref(bus);
235 }
236 return false;
237 }
238
239 constexpr const char *service = "org.freedesktop.login1";
240 constexpr const char *manager_path = "/org/freedesktop/login1";
241 constexpr const char *manager_interface = "org.freedesktop.login1.Manager";
242 constexpr const char *session_interface = "org.freedesktop.login1.Session";
243
244 sd_bus_error error = SD_BUS_ERROR_NULL;
245 sd_bus_message *reply = nullptr;
246 status = sd_bus_call_method(
247 bus, service, manager_path, manager_interface, "GetSession",
248 &error, &reply, "s", session_id.c_str()
249 );
250 if (status < 0) {
251 BOOST_LOG(warning) << "[Session] Could not resolve graphical session " << session_id << ": "
252 << (error.message ? error.message : std::strerror(-status));
253 sd_bus_error_free(&error);
254 sd_bus_message_unref(reply);
255 sd_bus_unref(bus);
256 return false;
257 }
258
259 const char *session_path_raw = nullptr;
260 status = sd_bus_message_read(reply, "o", &session_path_raw);
261 const std::string session_path = session_path_raw ? session_path_raw : "";
262 sd_bus_message_unref(reply);
263 reply = nullptr;
264 if (status < 0 || session_path.empty()) {
265 BOOST_LOG(warning) << "[Session] systemd-logind returned no object path for graphical session "
266 << session_id << '.';
267 sd_bus_error_free(&error);
268 sd_bus_unref(bus);
269 return false;
270 }
271
272 int locked = 0;
273 status = sd_bus_get_property_trivial(
274 bus, service, session_path.c_str(), session_interface, "LockedHint",
275 &error, 'b', &locked
276 );
277 if (status < 0) {
278 BOOST_LOG(warning) << "[Session] Could not read LockedHint for graphical session " << session_id << ": "
279 << (error.message ? error.message : std::strerror(-status));
280 sd_bus_error_free(&error);
281 sd_bus_unref(bus);
282 return false;
283 }
284
285 if (!locked) {
286 BOOST_LOG(info) << "[Session] Graphical session " << session_id << " is already unlocked.";
287 sd_bus_error_free(&error);
288 sd_bus_unref(bus);
289 return true;
290 }
291
292 // Call logind directly rather than spawning loginctl. Unlock() emits the
293 // standard session Unlock signal consumed by Plasma/GNOME screen lockers.
294 // This setting is opt-in because it unlocks the entire host desktop session,
295 // not just the virtual output.
296 status = sd_bus_call_method(
297 bus, service, session_path.c_str(), session_interface, "Unlock",
298 &error, &reply, ""
299 );
300 if (status < 0) {
301 BOOST_LOG(warning) << "[Session] Could not unlock graphical session " << session_id << ": "
302 << (error.message ? error.message : std::strerror(-status));
303 sd_bus_error_free(&error);
304 sd_bus_message_unref(reply);
305 sd_bus_unref(bus);
306 return false;
307 }
308
309 BOOST_LOG(info) << "[Session] Requested unlock of graphical session " << session_id
310 << " before application launch.";
311 sd_bus_error_free(&error);
312 sd_bus_message_unref(reply);
313 sd_bus_unref(bus);
314 return true;
315#else
316 BOOST_LOG(warning) << "[Session] Host-session unlock was requested, but this build has no sd-bus support.";
317 return false;
318#endif
319 }
320
321 // ============================================================================
322 // EVDI Types and Function Pointers (loaded dynamically)
323 // ============================================================================
324
325 // EVDI structures (matching evdi_lib.h)
327 int version_major;
328 int version_minor;
329 int version_patchlevel;
330 };
331
332 struct evdi_device_context;
333 typedef struct evdi_device_context *evdi_handle;
334
335 enum evdi_device_status {
336 EVDI_AVAILABLE,
337 EVDI_UNRECOGNIZED,
338 EVDI_NOT_PRESENT
339 };
340
341 struct evdi_mode {
342 int width;
343 int height;
344 int refresh_rate;
345 int bits_per_pixel;
346 unsigned int pixel_format;
347 };
348
349 struct evdi_rect {
350 int x1, y1, x2, y2;
351 };
352
353 struct evdi_buffer {
354 int id;
355 void *buffer;
356 int width;
357 int height;
358 int stride;
359 struct evdi_rect *rects;
360 int rect_count;
361 };
362
364 int32_t hot_x;
365 int32_t hot_y;
366 uint32_t width;
367 uint32_t height;
368 uint8_t enabled;
369 uint32_t buffer_length;
370 uint32_t *buffer;
371 uint32_t pixel_format;
372 uint32_t stride;
373 };
374
376 int32_t x;
377 int32_t y;
378 };
379
381 uint16_t address;
382 uint16_t flags;
383 uint32_t buffer_length;
384 uint8_t *buffer;
385 };
386
388 void (*dpms_handler)(int dpms_mode, void *user_data);
389 void (*mode_changed_handler)(struct evdi_mode mode, void *user_data);
390 void (*update_ready_handler)(int buffer_to_be_updated, void *user_data);
391 void (*crtc_state_handler)(int state, void *user_data);
392 void (*cursor_set_handler)(struct evdi_cursor_set cursor_set, void *user_data);
393 void (*cursor_move_handler)(struct evdi_cursor_move cursor_move, void *user_data);
394 void (*ddcci_data_handler)(struct evdi_ddcci_data ddcci_data, void *user_data);
395 void *user_data;
396 };
397
398 // EVDI function pointer types
399 typedef evdi_device_status (*fn_evdi_check_device)(int device);
400 typedef evdi_handle (*fn_evdi_open)(int device);
401 typedef int (*fn_evdi_add_device)(void);
402 typedef void (*fn_evdi_close)(evdi_handle handle);
403 typedef void (*fn_evdi_connect)(evdi_handle handle, const unsigned char *edid,
404 const unsigned int edid_length,
405 const uint32_t sku_area_limit);
406 typedef void (*fn_evdi_disconnect)(evdi_handle handle);
407 typedef void (*fn_evdi_grab_pixels)(evdi_handle handle, struct evdi_rect *rects, int *num_rects);
408 typedef void (*fn_evdi_register_buffer)(evdi_handle handle, struct evdi_buffer buffer);
409 typedef void (*fn_evdi_unregister_buffer)(evdi_handle handle, int bufferId);
410 typedef bool (*fn_evdi_request_update)(evdi_handle handle, int bufferId);
411 typedef void (*fn_evdi_handle_events)(evdi_handle handle, struct evdi_event_context *evtctx);
412 typedef int (*fn_evdi_get_event_ready)(evdi_handle handle);
413 typedef void (*fn_evdi_get_lib_version)(struct evdi_lib_version *version);
414
415 // EVDI function pointers (loaded at runtime)
416 static struct {
417 void *lib_handle;
418 fn_evdi_check_device check_device;
419 fn_evdi_open open;
420 fn_evdi_add_device add_device;
421 fn_evdi_close close;
422 fn_evdi_connect connect;
423 fn_evdi_disconnect disconnect;
424 fn_evdi_grab_pixels grab_pixels;
425 fn_evdi_register_buffer register_buffer;
426 fn_evdi_unregister_buffer unregister_buffer;
427 fn_evdi_request_update request_update;
428 fn_evdi_handle_events handle_events;
429 fn_evdi_get_event_ready get_event_ready;
430 fn_evdi_get_lib_version get_lib_version;
431 bool loaded;
432 } evdi = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
433 nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false};
434
435 // ============================================================================
436 // Standard 1920x1080 EDID (used for virtual display)
437 // ============================================================================
438
439 // EDID for a generic 1920x1080@60Hz monitor
440 static const unsigned char default_edid[] = {
441 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, // Header
442 0x1E, 0x6D, // Manufacturer ID (LG Display)
443 0x00, 0x00, // Product code
444 0x01, 0x01, 0x01, 0x01, // Serial number
445 0x00, 0x1D, // Week/Year of manufacture
446 0x01, 0x04, // EDID version 1.4
447 0xB5, // Video input (digital, 8-bit color depth, DisplayPort)
448 0x3C, 0x22, // Width/height in cm (60x34 = approx 27")
449 0x78, // Gamma 2.2
450 0x3A, // Features (RGB, preferred timing)
451 // Chromaticity
452 0xFC, 0x81, 0xA4, 0x55, 0x4D, 0x9D, 0x25, 0x12, 0x50, 0x54,
453 // Established timings
454 0x21, 0x08, 0x00,
455 // Standard timings
456 0xD1, 0xC0, // 1920x1080@60Hz
457 0x81, 0x80, // 1280x1024@60Hz
458 0x81, 0xC0, // 1280x720@60Hz
459 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
460 // Detailed timing descriptor: 1920x1080@60Hz
461 0x02, 0x3A, // Pixel clock: 148.5 MHz
462 0x80, 0x18, 0x71, 0x38, 0x2D, 0x40,
463 0x58, 0x2C, 0x45, 0x00,
464 0x56, 0x50, 0x21, 0x00, 0x00, 0x1E,
465 // Display name descriptor
466 0x00, 0x00, 0x00, 0xFC, 0x00,
467 'A', 'P', 'O', 'L', 'L', 'O', ' ', 'V', 'D', 'I', 'S', 'P', '\n',
468 // Display range limits
469 0x00, 0x00, 0x00, 0xFD, 0x00,
470 0x32, 0x4B, 0x1E, 0x51, 0x11, 0x00, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
471 // Extension flag and checksum (calculated)
472 0x00, 0x00
473 };
474
475 // ============================================================================
476 // Global State
477 // ============================================================================
478
479 static std::mutex vdisplay_mutex;
480 static DRIVER_STATUS driver_status = DRIVER_STATUS::UNKNOWN;
481 // Serialize display creation/removal while allowing event delivery during compositor RPCs.
482 static std::mutex vdisplay_lifecycle_mutex;
483 static std::atomic<bool> watchdog_running {false};
484 // Guards closeVDisplayDevice() against running its teardown more than once.
485 static std::atomic<bool> device_open {false};
486 static std::thread watchdog_thread;
487 static bool evdi_available = false;
488 static bool exclusive_virtual_display_active = false;
489 static std::string evdi_library_version;
490
491
492 enum class VirtualDisplayBackend {
493 NONE,
494 EVDI,
495 HERMES_KMS,
496 HYPRLAND_HEADLESS,
497 };
498
512 static VirtualDisplayBackend selected_backend() {
513 // Asking for no backend is a decision, not an absence of one, and it comes
514 // before the compositor is consulted: a host that streams an output it
515 // already has - the container image's own headless sway session is the
516 // standing example - wants none of this machinery, and Hyprland is no
517 // exception to that.
518 if (config::video.virtual_display_backend == "none") {
519 return VirtualDisplayBackend::NONE;
520 }
522 return VirtualDisplayBackend::HYPRLAND_HEADLESS;
523 }
524 return config::video.virtual_display_backend == "hermes_kms" ? VirtualDisplayBackend::HERMES_KMS : VirtualDisplayBackend::EVDI;
525 }
526
527 static const char *backend_name(VirtualDisplayBackend backend) {
528 switch (backend) {
529 case VirtualDisplayBackend::HERMES_KMS:
530 return "Hermes-KMS";
531 case VirtualDisplayBackend::HYPRLAND_HEADLESS:
532 return "Hyprland headless output";
533 case VirtualDisplayBackend::NONE:
534 return "no";
535 case VirtualDisplayBackend::EVDI:
536 break;
537 }
538 return "EVDI";
539 }
540
541 // Defined with the KScreen backend below; the Hyprland one interpolates
542 // output names into its socket commands too.
543 static bool safe_output_name(const std::string &name);
544
555 namespace hyprland {
556 static std::string socket_path() {
557 const char *signature = std::getenv("HYPRLAND_INSTANCE_SIGNATURE");
558 if (!signature || !signature[0]) {
559 return {};
560 }
561 const char *runtime_dir = std::getenv("XDG_RUNTIME_DIR");
562 std::string base = runtime_dir && runtime_dir[0] ? runtime_dir : "/run/user/" + std::to_string(getuid());
563 return base + "/hypr/" + signature + "/.socket.sock";
564 }
565
566 static bool available() {
567 const auto path = socket_path();
568 return !path.empty() && std::filesystem::exists(path);
569 }
570
572 static std::optional<std::string> request(const std::string &command) {
573 const auto path = socket_path();
574 if (path.empty() || path.size() >= sizeof(sockaddr_un::sun_path)) {
575 return std::nullopt;
576 }
577
578 const int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
579 if (fd < 0) {
580 return std::nullopt;
581 }
582 auto close_fd = util::fail_guard([fd]() {
583 close(fd);
584 });
585
586 sockaddr_un addr {};
587 addr.sun_family = AF_UNIX;
588 std::memcpy(addr.sun_path, path.c_str(), path.size() + 1);
589 if (connect(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) < 0) {
590 return std::nullopt;
591 }
592
593 size_t written = 0;
594 while (written < command.size()) {
595 const ssize_t n = write(fd, command.data() + written, command.size() - written);
596 if (n <= 0) {
597 if (n < 0 && errno == EINTR) {
598 continue;
599 }
600 return std::nullopt;
601 }
602 written += static_cast<size_t>(n);
603 }
604
605 std::string reply;
606 char buffer[4096];
607 while (true) {
608 const ssize_t n = read(fd, buffer, sizeof(buffer));
609 if (n < 0) {
610 if (errno == EINTR) {
611 continue;
612 }
613 return std::nullopt;
614 }
615 if (n == 0) {
616 break;
617 }
618 reply.append(buffer, static_cast<size_t>(n));
619 }
620 return reply;
621 }
622
624 static std::vector<std::string> monitor_names() {
625 std::vector<std::string> names;
626 const auto reply = request("j/monitors");
627 if (!reply) {
628 return names;
629 }
630 try {
631 const auto monitors = nlohmann::json::parse(*reply);
632 for (const auto &monitor : monitors) {
633 if (const auto name = monitor.find("name"); name != monitor.end() && name->is_string()) {
634 names.emplace_back(name->get<std::string>());
635 }
636 }
637 } catch (const nlohmann::json::exception &e) {
638 BOOST_LOG(warning) << "[VDISPLAY] Could not read Hyprland's monitor list: " << e.what();
639 }
640 return names;
641 }
642
652 static std::optional<std::string> create_headless() {
653 std::set<std::string> before;
654 for (auto &name : monitor_names()) {
655 before.insert(std::move(name));
656 }
657
658 const auto reply = request("/output create headless");
659 if (!reply || reply->rfind("ok", 0) != 0) {
660 BOOST_LOG(error) << "[VDISPLAY] Hyprland refused to create a headless output"
661 << (reply ? ": " + *reply : " (no reply from its socket).");
662 return std::nullopt;
663 }
664
665 // The output appears on Hyprland's own event loop, not on the reply.
666 for (int attempt = 0; attempt < 40; ++attempt) {
667 for (const auto &name : monitor_names()) {
668 if (!before.contains(name)) {
669 return name;
670 }
671 }
672 std::this_thread::sleep_for(std::chrono::milliseconds(25));
673 }
674
675 BOOST_LOG(error) << "[VDISPLAY] Hyprland accepted the headless output but never published it.";
676 return std::nullopt;
677 }
678
710 static void pin_output(const std::string &name, int width, int height, int refresh_mhz) {
711 if (width <= 0 || height <= 0) {
712 return;
713 }
714 // The name is interpolated into a Lua expression and a config line.
715 if (!safe_output_name(name)) {
716 BOOST_LOG(warning) << "[VDISPLAY] Refusing to pin a Hyprland monitor rule for an unsafe output name.";
717 return;
718 }
719 std::string mode = std::to_string(width) + "x" + std::to_string(height);
720 if (refresh_mhz > 0) {
721 char refresh[32];
722 std::snprintf(refresh, sizeof(refresh), "@%.3f", refresh_mhz / 1000.0);
723 mode += refresh;
724 }
725
726 std::string rule = "hl.monitor({ output = \"" + name + "\", mode = \"" + mode + "\", position = \"auto\", scale = 1 })";
727 auto reply = request("/eval " + rule);
728 if (!reply || reply->rfind("ok", 0) != 0) {
729 BOOST_LOG(info) << "[VDISPLAY] Hyprland did not take the monitor rule through eval"
730 << (reply ? " (" + *reply + ")" : " (no reply from its socket)") << "; trying keyword.";
731 rule = name + "," + mode + ",auto,1";
732 reply = request("/keyword monitor " + rule);
733 }
734 if (!reply || reply->rfind("ok", 0) != 0) {
735 BOOST_LOG(warning) << "[VDISPLAY] Hyprland refused the monitor rule '" << rule << "'"
736 << (reply ? ": " + *reply : " (no reply from its socket).");
737 return;
738 }
739 BOOST_LOG(info) << "[VDISPLAY] Pinned Hyprland monitor rule '" << rule << "'";
740 }
741
742 static bool remove_output(const std::string &name) {
743 if (name.empty()) {
744 return false;
745 }
746 const auto reply = request("/output remove " + name);
747 if (!reply || reply->rfind("ok", 0) != 0) {
748 BOOST_LOG(warning) << "[VDISPLAY] Hyprland refused to remove output " << name
749 << (reply ? ": " + *reply : " (no reply from its socket).");
750 return false;
751 }
752 return true;
753 }
763 static void log_unreachable(bool fatal) {
764 BOOST_LOG(fatal ? error : warning)
765 << "[VDISPLAY] The session is Hyprland but its control socket is not reachable. "
766 "Hermes reads HYPRLAND_INSTANCE_SIGNATURE from its own environment, so a "
767 "service started outside the session will not find it.";
768 }
769
770 } // namespace hyprland
771
772 namespace hermes_kms {
773 constexpr uint32_t multi_output_uapi_version = 8;
774 constexpr uint32_t multi_device_uapi_version = 9;
775 constexpr uint32_t session_device_uapi_version = 10;
776 constexpr uint32_t session_access_uapi_version = 11;
777 constexpr uint32_t dynamic_devices_uapi_version = 12;
778 constexpr uint32_t session_lifecycle_uapi_version = 13;
782 constexpr uint32_t newest_known_uapi_version = 14;
783 constexpr size_t name_len = 32;
784
785 constexpr uint64_t cap_virtual_output = 1ULL << 0;
786 constexpr uint64_t cap_output_control = 1ULL << 1;
787 constexpr uint64_t cap_frame_acquire = 1ULL << 5;
788 constexpr uint64_t cap_dmabuf_export = 1ULL << 6;
789 constexpr uint64_t cap_output_identity = 1ULL << 7;
790 constexpr uint64_t cap_session_owner = 1ULL << 8;
791 constexpr uint64_t cap_frame_wait = 1ULL << 9;
792 constexpr uint64_t cap_metrics = 1ULL << 10;
793 constexpr uint64_t cap_multi_output = 1ULL << 11;
794 constexpr uint64_t cap_multi_device = 1ULL << 12;
795 constexpr uint64_t cap_session_token = 1ULL << 14;
796 constexpr uint64_t cap_cursor_capture = 1ULL << 15;
797 // Cards come and go at runtime through the driver's configfs group, so
798 // device_index is neither dense nor stable; a card is identified by its
799 // role and session index instead.
800 constexpr uint64_t cap_dynamic_devices = 1ULL << 16;
801 // SESSION_ACCESS takes ROTATE_TOKEN and REVOKE_BINDINGS, GET_STATUS reports
802 // bound_fd_count, and GET_METRICS reports the binding counters.
803 constexpr uint64_t cap_session_lifecycle = 1ULL << 17;
804 constexpr uint64_t cap_zero_copy_target = 1ULL << 33;
805 constexpr uint64_t cap_sync_file = 1ULL << 35;
806
807 constexpr uint32_t set_output_connected = 1U << 0;
808 constexpr uint32_t set_output_owner_assigned = 1U << 1;
809 constexpr uint32_t device_role_session = 2U;
810
811 struct version_t {
812 uint32_t uapi_version;
813 uint32_t driver_major;
814 uint32_t driver_minor;
815 uint32_t driver_patch;
816 char driver_name[name_len];
817 };
818
819 struct caps_t {
820 uint64_t flags;
821 uint32_t min_width;
822 uint32_t min_height;
823 uint32_t max_width;
824 uint32_t max_height;
825 uint32_t preferred_width;
826 uint32_t preferred_height;
827 uint32_t max_refresh_hz;
828 uint32_t output_count;
829 };
830
831 struct identity_t {
832 char driver_name[name_len];
833 char output_name[name_len];
834 char connector_name[name_len];
835 uint32_t connector_id;
836 uint32_t crtc_id;
837 uint32_t plane_id;
838 uint32_t encoder_id;
839 uint32_t output_index;
840 uint32_t output_count;
841 uint32_t device_index;
842 uint32_t device_count;
843 uint32_t device_role;
844 uint32_t session_index;
845 uint32_t session_device_count;
846 uint32_t cursor_plane_id;
847 };
848
850 uint32_t output_index;
851 uint32_t flags;
852 uint32_t selected_output_index;
853 uint32_t output_count;
854 char output_name[name_len];
855 uint32_t reserved[8];
856 };
857
859 uint32_t enabled;
860 uint32_t width;
861 uint32_t height;
862 uint32_t refresh_hz;
863 uint32_t flags;
864 uint32_t result_flags;
865 uint64_t session_id;
866 };
867
868 struct alignas(8) acquire_frame_t {
869 uint64_t flags;
870 uint64_t sequence;
871 uint64_t timestamp_ns;
872 uint64_t modifier;
873 uint32_t framebuffer_id;
874 uint32_t width;
875 uint32_t height;
876 uint32_t format;
877 uint32_t plane_count;
878 uint32_t pitch[4];
879 uint32_t offset[4];
880 int32_t dma_buf_fd[4];
881 int32_t sync_file_fd;
882 uint32_t reserved0;
883 uint32_t damage_x1;
884 uint32_t damage_y1;
885 uint32_t damage_x2;
886 uint32_t damage_y2;
887 alignas(8) uint64_t reserved[6];
888 };
889
891 acquire_frame_t frame;
892 color_t color;
893 };
894 static_assert(sizeof(acquire_frame_t) == 176);
895 static_assert(sizeof(acquire_frame2_t) == 224);
896 static_assert(offsetof(acquire_frame2_t, color) == 176);
897
899 uint64_t flags;
900 uint64_t after_sequence;
901 uint64_t sequence;
902 uint64_t timestamp_ns;
903 uint64_t status_flags;
904 uint32_t timeout_ms;
905 uint32_t reserved0;
906 uint64_t reserved[6];
907 };
908
910 uint64_t flags;
911 uint64_t after_frame_sequence;
912 uint64_t after_cursor_sequence;
913 uint64_t frame_sequence;
914 uint64_t cursor_sequence;
915 uint64_t frame_timestamp_ns;
916 uint64_t cursor_timestamp_ns;
917 uint64_t status_flags;
918 uint32_t timeout_ms;
919 uint32_t reserved0;
920 uint64_t reserved[5];
921 };
922
924 uint64_t flags;
925 uint64_t sequence;
926 uint64_t image_sequence;
927 uint64_t timestamp_ns;
928 uint64_t modifier;
929 uint64_t session_id;
930 int32_t position_x;
931 int32_t position_y;
932 int32_t crtc_x;
933 int32_t crtc_y;
934 uint32_t crtc_w;
935 uint32_t crtc_h;
936 uint32_t src_x;
937 uint32_t src_y;
938 uint32_t src_w;
939 uint32_t src_h;
940 int32_t hotspot_x;
941 int32_t hotspot_y;
942 uint32_t framebuffer_id;
943 uint32_t width;
944 uint32_t height;
945 uint32_t format;
946 uint32_t plane_count;
947 uint32_t pitch[4];
948 uint32_t offset[4];
949 int32_t dma_buf_fd[4];
950 int32_t sync_file_fd;
951 uint32_t reserved0;
952 uint32_t reserved_alignment;
953 uint64_t reserved[6];
954 };
955
956 static_assert(sizeof(caps_t) == 40);
957 static_assert(sizeof(identity_t) == 144);
958 static_assert(sizeof(select_output_t) == 80);
959 static_assert(sizeof(acquire_frame_t) == 176);
960 static_assert(sizeof(wait_frame_t) == 96);
961 static_assert(sizeof(wait_update_t) == 112);
962 static_assert(sizeof(acquire_cursor_t) == 224);
963 static_assert(offsetof(identity_t, cursor_plane_id) == 140);
964 static_assert(offsetof(wait_update_t, timeout_ms) == 64);
965 static_assert(offsetof(acquire_cursor_t, dma_buf_fd) == 148);
966 static_assert(offsetof(acquire_cursor_t, reserved) == 176);
967
968 // Mirrors `struct drm_hermes_kms_metrics` in the driver UAPI header
969 // (include/uapi/drm/hermes_kms_drm.h). Field order and size must match
970 // exactly. Read-only counters maintained by the driver for the lifetime of
971 // the device; they are not per-session.
972 struct metrics_t {
973 uint64_t frame_sequence;
974 uint64_t frame_update_count;
975 uint64_t acquire_count;
976 uint64_t acquire_no_frame_count;
977 uint64_t dmabuf_export_count;
978 uint64_t dmabuf_export_fail_count;
979 uint64_t sync_file_export_count;
980 uint64_t sync_file_export_fail_count;
981 uint64_t wait_count;
982 uint64_t wait_ready_count;
983 uint64_t wait_timeout_count;
984 uint64_t wait_interrupted_count;
985 uint64_t output_enable_count;
986 uint64_t output_disable_count;
987 uint64_t hotplug_event_count;
988 uint64_t owner_close_disconnect_count;
989 uint64_t last_update_ns;
990 uint64_t last_acquire_ns;
991 uint64_t last_wait_start_ns;
992 uint64_t last_wait_end_ns;
993 uint64_t last_wait_duration_ns;
994 uint64_t last_dmabuf_export_ns;
995 uint64_t last_sync_file_export_ns;
996 uint64_t vblank_count;
997 uint64_t vblank_overrun_count;
998 // Session-capability lifecycle (uapi >= 13), taken from reserved slots,
999 // so the structure keeps its size.
1000 uint64_t bind_count;
1001 uint64_t bind_reject_count;
1002 uint64_t unbind_count;
1003 uint64_t binding_revoke_count;
1004 uint64_t cross_session_buffer_export_count;
1005 uint64_t reserved[9];
1006 };
1007
1009 uint64_t token[2];
1010 uint64_t session_id;
1011 uint32_t operation;
1012 uint32_t output_index;
1013 uint32_t flags;
1014 uint32_t result_flags;
1015 uint64_t reserved[4];
1016 };
1017
1018 // Frame request/result flags (must match the UAPI header).
1019 constexpr uint64_t frame_request_dmabuf = 1ULL << 0;
1020 constexpr uint64_t frame_dmabuf_valid = 1ULL << 2;
1021 constexpr uint64_t frame_sync_file_valid = 1ULL << 3;
1022 constexpr uint64_t frame_request_sync_file = 1ULL << 5;
1023 constexpr uint64_t wait_frame_ready = 1ULL << 0;
1024 constexpr uint64_t wait_update_frame_ready = 1ULL << 0;
1025 constexpr uint64_t wait_update_cursor_ready = 1ULL << 1;
1026 constexpr uint64_t cursor_request_dmabuf = 1ULL << 0;
1027 constexpr uint64_t cursor_request_sync_file = 1ULL << 1;
1028 constexpr uint64_t cursor_metadata_valid = 1ULL << 2;
1029 constexpr uint64_t cursor_visible = 1ULL << 3;
1030 constexpr uint64_t cursor_position_valid = 1ULL << 4;
1031 constexpr uint64_t cursor_buffer_valid = 1ULL << 6;
1032 constexpr uint64_t cursor_dmabuf_valid = 1ULL << 7;
1033 constexpr uint64_t cursor_sync_file_valid = 1ULL << 8;
1034 constexpr uint64_t cursor_geometry_valid = 1ULL << 9;
1035
1036 constexpr uint32_t session_access_get_token = 1U;
1037 constexpr uint32_t session_access_bind = 2U;
1038 // ROTATE_TOKEN is part of the uapi but unused here: the capture worker
1039 // re-binds from the stored token whenever it reinitialises, so rotating
1040 // behind its back would fail a bind that is already under way.
1041 constexpr uint32_t session_access_rotate_token [[maybe_unused]] = 4U;
1042 constexpr uint32_t session_access_revoke_bindings = 5U;
1043 constexpr uint32_t session_access_result_bound = 1U << 0;
1044 constexpr uint32_t session_access_result_token_valid = 1U << 1;
1045 constexpr uint32_t session_access_result_revoked = 1U << 2;
1046
1047 constexpr unsigned long ioctl_get_version = DRM_IOR(DRM_COMMAND_BASE + 0x00, version_t);
1048 constexpr unsigned long ioctl_get_caps = DRM_IOR(DRM_COMMAND_BASE + 0x01, caps_t);
1049 constexpr unsigned long ioctl_get_status = DRM_IOR(DRM_COMMAND_BASE + 0x02, status_t);
1050 constexpr unsigned long ioctl_set_output = DRM_IOWR(DRM_COMMAND_BASE + 0x03, set_output_t);
1051 constexpr unsigned long ioctl_acquire_frame2 = DRM_IOWR(DRM_COMMAND_BASE + 0x0c, acquire_frame2_t);
1052 constexpr unsigned long ioctl_acquire_frame = DRM_IOWR(DRM_COMMAND_BASE + 0x04, acquire_frame_t);
1053 constexpr unsigned long ioctl_get_identity = DRM_IOR(DRM_COMMAND_BASE + 0x05, identity_t);
1054 constexpr unsigned long ioctl_wait_frame = DRM_IOWR(DRM_COMMAND_BASE + 0x06, wait_frame_t);
1055 constexpr unsigned long ioctl_get_metrics = DRM_IOR(DRM_COMMAND_BASE + 0x07, metrics_t);
1056 constexpr unsigned long ioctl_select_output = DRM_IOWR(DRM_COMMAND_BASE + 0x08, select_output_t);
1057 constexpr unsigned long ioctl_session_access = DRM_IOWR(DRM_COMMAND_BASE + 0x09, session_access_t);
1058 constexpr unsigned long ioctl_acquire_cursor = DRM_IOWR(DRM_COMMAND_BASE + 0x0a, acquire_cursor_t);
1059 constexpr unsigned long ioctl_wait_update = DRM_IOWR(DRM_COMMAND_BASE + 0x0b, wait_update_t);
1060
1061 static_assert(sizeof(status_t) == 208);
1062 static_assert(offsetof(status_t, framebuffer_modifier) == 136);
1063 static_assert(offsetof(status_t, bound_fd_count) == 160);
1064 static_assert(sizeof(metrics_t) == 312);
1065 static_assert(offsetof(metrics_t, bind_count) == 200);
1066 static_assert(offsetof(metrics_t, cross_session_buffer_export_count) == 232);
1067 static_assert(sizeof(session_access_t) == 72);
1068
1069 struct device_t {
1070 int fd {-1};
1071 int card_index {-1};
1072 uint32_t selected_output_index {0};
1073 version_t version {};
1074 caps_t caps {};
1075 identity_t identity {};
1076 };
1077
1078 static std::string cstr(const char *value) {
1079 return value && value[0] ? std::string {value, strnlen(value, name_len)} : std::string {};
1080 }
1081
1082 static void forget_secret(void *data, size_t size) {
1083 auto *byte = static_cast<volatile unsigned char *>(data);
1084 while (size--) {
1085 *byte++ = 0;
1086 }
1087 }
1088
1089 static int numbered_node_index(const fs::path &path, std::string_view prefix) {
1090 const auto name = path.filename().string();
1091 if (!name.starts_with(prefix) || name.size() == prefix.size()) {
1092 return -1;
1093 }
1094
1095 int index = 0;
1096 for (const unsigned char ch : std::string_view {name}.substr(prefix.size())) {
1097 const int digit = ch - static_cast<unsigned char>('0');
1098 if (!std::isdigit(ch) || index > (std::numeric_limits<int>::max() - digit) / 10) {
1099 return -1;
1100 }
1101 index = index * 10 + digit;
1102 }
1103 return index;
1104 }
1105
1106 static int card_index_from_path(const fs::path &path) {
1107 return numbered_node_index(path, "card");
1108 }
1109
1110 static bool is_render_node(const fs::path &path) {
1111 return numbered_node_index(path, "renderD") >= 0;
1112 }
1113
1114 static bool is_hermes_device(int fd) {
1115 if (fd < 0) {
1116 return false;
1117 }
1118
1119 drmVersionPtr version = drmGetVersion(fd);
1120 if (!version) {
1121 return false;
1122 }
1123 const bool matches = version->name && version->name_len > 0 &&
1124 std::string_view {
1125 version->name,
1126 static_cast<size_t>(version->name_len),
1127 } == "hermes-kms";
1128 drmFreeVersion(version);
1129 return matches;
1130 }
1131
1144 static int primary_card_index(int fd) {
1145 if (fd < 0) {
1146 return -1;
1147 }
1148
1149 struct stat node {};
1150 if (::fstat(fd, &node) != 0 || !S_ISCHR(node.st_mode)) {
1151 return -1;
1152 }
1153
1154 char drm_dir[64];
1155 std::snprintf(
1156 drm_dir,
1157 sizeof(drm_dir),
1158 "/sys/dev/char/%u:%u/device/drm",
1159 static_cast<unsigned>(major(node.st_rdev)),
1160 static_cast<unsigned>(minor(node.st_rdev))
1161 );
1162
1163 // The directory also holds the render node and the connector entries;
1164 // card_index_from_path() accepts only a bare "card<N>".
1165 std::error_code ec;
1166 for (const auto &entry : fs::directory_iterator {drm_dir, ec}) {
1167 const int index = card_index_from_path(entry.path());
1168 if (index >= 0) {
1169 return index;
1170 }
1171 }
1172 return -1;
1173 }
1174
1175 static void close_device(device_t &device) {
1176 if (device.fd >= 0) {
1177 ::close(device.fd);
1178 device.fd = -1;
1179 }
1180 }
1181
1182 static int open_render_node_for_card_index(int card_index) {
1183 if (card_index < 0) {
1184 return -1;
1185 }
1186
1187 std::error_code ec;
1188 fs::directory_iterator dir("/dev/dri", ec);
1189 if (ec) {
1190 return -1;
1191 }
1192 for (const auto &entry : dir) {
1193 if (!is_render_node(entry.path())) {
1194 continue;
1195 }
1196 const int fd = ::open(entry.path().c_str(), O_RDONLY | O_CLOEXEC);
1197 if (fd < 0) {
1198 continue;
1199 }
1200 if (is_hermes_device(fd) && primary_card_index(fd) == card_index) {
1201 return fd;
1202 }
1203 ::close(fd);
1204 }
1205 return -1;
1206 }
1207
1208 static bool multi_output_requested() {
1209 return config::video.hermes_kms_multi_output;
1210 }
1211
1212 static uint32_t required_uapi_version() {
1213 // Secure capture always uses the generic session-capability handoff.
1214 return session_access_uapi_version;
1215 }
1216
1217 static uint32_t output_count(const caps_t &caps) {
1218 return caps.output_count ? caps.output_count : 1U;
1219 }
1220
1221 static bool has_required_caps(
1222 uint64_t flags,
1223 bool require_multi_output = multi_output_requested(),
1224 bool require_multi_device = false
1225 ) {
1226 constexpr uint64_t required = cap_virtual_output | cap_output_control | cap_frame_acquire |
1227 cap_dmabuf_export | cap_output_identity | cap_session_owner |
1228 cap_frame_wait | cap_session_token | cap_cursor_capture |
1229 cap_zero_copy_target | cap_sync_file;
1230 return (flags & required) == required &&
1231 (!require_multi_output || (flags & cap_multi_output)) &&
1232 (!require_multi_device || (flags & cap_multi_device));
1233 }
1234
1235 static std::vector<device_t> open_devices(bool log_failures) {
1236 std::vector<device_t> devices;
1237 try {
1238 for (const auto &entry : fs::directory_iterator("/dev/dri")) {
1239 // All Hermes control/capture ioctls are DRM_RENDER_ALLOW and work
1240 // through an O_RDONLY fd. The driver intentionally grants only read
1241 // access so O_RDWR GPU probes (notably Chromium/Electron) skip its
1242 // capture-only render nodes. The broker deliberately does not need
1243 // access to private-seat primary cards; those are opened later by
1244 // the compositor through seatd.
1245 if (!is_render_node(entry.path())) {
1246 continue;
1247 }
1248
1249 device_t candidate {};
1250 candidate.fd = ::open(entry.path().c_str(), O_RDONLY | O_CLOEXEC);
1251 if (candidate.fd < 0) {
1252 continue;
1253 }
1254
1255 // Identify the driver through the DRM core before issuing any
1256 // driver-private ioctl. Private command numbers are not globally
1257 // unique across unrelated DRM drivers.
1258 if (!is_hermes_device(candidate.fd)) {
1259 close_device(candidate);
1260 continue;
1261 }
1262
1263 if (::ioctl(candidate.fd, ioctl_get_version, &candidate.version) != 0) {
1264 close_device(candidate);
1265 continue;
1266 }
1267
1268 if (cstr(candidate.version.driver_name) != "hermes-kms") {
1269 close_device(candidate);
1270 continue;
1271 }
1272
1273 candidate.card_index = primary_card_index(candidate.fd);
1274 if (candidate.card_index < 0) {
1275 if (log_failures) {
1276 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] Could not resolve the primary card for "
1277 << entry.path();
1278 }
1279 close_device(candidate);
1280 continue;
1281 }
1282 const auto required_version = required_uapi_version();
1283 if (candidate.version.uapi_version < required_version) {
1284 if (log_failures) {
1285 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] UAPI " << candidate.version.uapi_version
1286 << " is too old; need " << required_version
1287 << (multi_output_requested() ? " for experimental multi-output." : ".");
1288 }
1289 close_device(candidate);
1290 continue;
1291 }
1292
1293 if (::ioctl(candidate.fd, ioctl_get_caps, &candidate.caps) != 0 || !has_required_caps(candidate.caps.flags)) {
1294 if (log_failures) {
1295 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] Driver is present but does not expose the required streaming capabilities.";
1296 }
1297 close_device(candidate);
1298 continue;
1299 }
1300
1301 if (::ioctl(candidate.fd, ioctl_get_identity, &candidate.identity) != 0) {
1302 if (log_failures) {
1303 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] GET_IDENTITY failed for "
1304 << entry.path() << ": " << std::strerror(errno);
1305 }
1306 close_device(candidate);
1307 continue;
1308 }
1309
1310 devices.emplace_back(candidate);
1311 }
1312 } catch (const std::exception &exception) {
1313 if (log_failures) {
1314 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] Could not enumerate DRM devices: " << exception.what();
1315 }
1316 }
1317
1318 // A driver that creates and removes cards at runtime hands out
1319 // device_index values that are neither dense nor stable across a card
1320 // being recreated, so ordering by it would reshuffle the pool between two
1321 // enumerations. Session cards are then ordered by the session index their
1322 // seat and private broker are named after, which is stable by
1323 // construction, and the host card (session_index 0) still comes first.
1324 const bool dynamic_devices = std::any_of(devices.begin(), devices.end(), [](const auto &device) {
1325 return (device.caps.flags & cap_dynamic_devices) != 0;
1326 });
1327 std::sort(devices.begin(), devices.end(), [dynamic_devices](const auto &left, const auto &right) {
1328 if (dynamic_devices) {
1329 if (left.identity.session_index != right.identity.session_index) {
1330 return left.identity.session_index < right.identity.session_index;
1331 }
1332 } else if (left.version.uapi_version >= multi_device_uapi_version &&
1333 right.version.uapi_version >= multi_device_uapi_version &&
1334 left.identity.device_index != right.identity.device_index) {
1335 return left.identity.device_index < right.identity.device_index;
1336 }
1337 return left.card_index < right.card_index;
1338 });
1339
1340 if (devices.empty() && log_failures) {
1341 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] No accessible Hermes-KMS render node found. "
1342 "Load hermes_kms and run `sudo /usr/lib/hermes-kms/hermes-kms-setup configure --user auto` "
1343 "(hermes-kms-seatd package) for this user.";
1344 }
1345 return devices;
1346 }
1347
1348 static bool open_device(device_t &out, bool log_failures) {
1349 auto devices = open_devices(log_failures);
1350 if (devices.empty()) {
1351 return false;
1352 }
1353
1354 out = devices.front();
1355 devices.front().fd = -1;
1356 for (auto &device : devices) {
1357 close_device(device);
1358 }
1359 return true;
1360 }
1361
1362 static bool available() {
1363 device_t device {};
1364 const bool ok = open_device(device, false);
1365 close_device(device);
1366 return ok;
1367 }
1368
1369 // Reason a hermes-kms card node could not be used, distinguished so the UI
1370 // can offer targeted guidance. `open_device` collapses these into a bool;
1371 // this walks the same probe but reports why it stopped.
1372 enum class probe_result {
1373 ok,
1375 uapi_too_old,
1376 missing_caps,
1377 };
1378
1379 struct probe_t {
1381 int card_index {-1};
1382 uint32_t uapi_version {0};
1383 uint32_t output_count {0};
1384 uint32_t device_count {0};
1385 uint32_t session_device_count {0};
1386 bool multi_output_capable {false};
1387 bool multi_device_capable {false};
1390 bool dynamic_devices {false};
1392 bool session_lifecycle {false};
1393 std::string driver_version;
1394 };
1395
1396 static probe_t probe() {
1397 probe_t out;
1398 std::error_code ec;
1399 fs::directory_iterator dir("/dev/dri", ec);
1400 if (ec) {
1401 return out;
1402 }
1403 for (const auto &entry : dir) {
1404 if (!is_render_node(entry.path())) {
1405 continue;
1406 }
1407
1408 device_t candidate {};
1409 candidate.fd = ::open(entry.path().c_str(), O_RDONLY | O_CLOEXEC);
1410 if (candidate.fd < 0) {
1411 continue;
1412 }
1413
1414 if (!is_hermes_device(candidate.fd) ||
1415 ::ioctl(candidate.fd, ioctl_get_version, &candidate.version) != 0 ||
1416 cstr(candidate.version.driver_name) != "hermes-kms") {
1417 close_device(candidate);
1418 continue;
1419 }
1420
1421 // Found the Hermes-KMS device; from here the outcome is definitive.
1422 out.card_index = primary_card_index(candidate.fd);
1423 out.uapi_version = candidate.version.uapi_version;
1424 out.driver_version = std::to_string(candidate.version.driver_major) + "." +
1425 std::to_string(candidate.version.driver_minor) + "." +
1426 std::to_string(candidate.version.driver_patch);
1427
1428 if (candidate.version.uapi_version < required_uapi_version()) {
1429 out.result = probe_result::uapi_too_old;
1430 } else if (::ioctl(candidate.fd, ioctl_get_caps, &candidate.caps) != 0) {
1431 out.result = probe_result::missing_caps;
1432 } else if (::ioctl(candidate.fd, ioctl_get_identity, &candidate.identity) != 0) {
1433 out.result = probe_result::missing_caps;
1434 } else {
1435 out.output_count = output_count(candidate.caps);
1436 out.multi_output_capable =
1437 candidate.version.uapi_version >= multi_output_uapi_version &&
1438 (candidate.caps.flags & cap_multi_output);
1439 out.multi_device_capable =
1440 candidate.version.uapi_version >= multi_device_uapi_version &&
1441 (candidate.caps.flags & cap_multi_device);
1442 out.dynamic_devices =
1443 candidate.version.uapi_version >= dynamic_devices_uapi_version &&
1444 (candidate.caps.flags & cap_dynamic_devices);
1445 out.session_lifecycle =
1446 candidate.version.uapi_version >= session_lifecycle_uapi_version &&
1447 (candidate.caps.flags & cap_session_lifecycle);
1448 out.device_count =
1449 candidate.version.uapi_version >= multi_device_uapi_version &&
1450 candidate.identity.device_count ?
1451 candidate.identity.device_count :
1452 1U;
1453 out.session_device_count =
1454 candidate.version.uapi_version >= session_device_uapi_version &&
1455 candidate.identity.session_device_count ?
1456 candidate.identity.session_device_count :
1457 (out.multi_device_capable ? out.device_count : 0U);
1458 out.result = has_required_caps(candidate.caps.flags) ?
1459 probe_result::ok :
1460 probe_result::missing_caps;
1461 }
1462 close_device(candidate);
1463 return out;
1464 }
1465 return out;
1466 }
1467
1468 static bool select_output(int fd, uint32_t output_index, select_output_t *result = nullptr, bool log_failure = true) {
1469 select_output_t request {};
1470 request.output_index = output_index;
1471 if (::ioctl(fd, ioctl_select_output, &request) != 0) {
1472 if (log_failure) {
1473 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] SELECT_OUTPUT(" << output_index
1474 << ") failed: " << std::strerror(errno);
1475 }
1476 return false;
1477 }
1478 if (result) {
1479 *result = request;
1480 }
1481 return true;
1482 }
1483
1484 static bool refresh_identity(device_t &device) {
1485 std::memset(&device.identity, 0, sizeof(device.identity));
1486 return ::ioctl(device.fd, ioctl_get_identity, &device.identity) == 0;
1487 }
1488
1489 static bool set_output(int fd, bool enabled, uint32_t width, uint32_t height, uint32_t refresh_hz,
1490 uint64_t &session_id, bool log_failure = true) {
1491 set_output_t request {};
1492 request.enabled = enabled ? 1U : 0U;
1493 request.width = width;
1494 request.height = height;
1495 request.refresh_hz = refresh_hz;
1496 request.session_id = session_id;
1497
1498 if (::ioctl(fd, ioctl_set_output, &request) != 0) {
1499 if (log_failure) {
1500 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] SET_OUTPUT failed: " << std::strerror(errno);
1501 }
1502 return false;
1503 }
1504
1505 session_id = request.session_id;
1506 if (enabled && (request.result_flags & (set_output_connected | set_output_owner_assigned)) !=
1507 (set_output_connected | set_output_owner_assigned)) {
1508 BOOST_LOG(warning) << "[VDISPLAY/Hermes-KMS] Output enabled but result flags look incomplete: 0x"
1509 << std::hex << request.result_flags << std::dec;
1510 }
1511 return true;
1512 }
1513
1514 static bool get_status(int fd, status_t &status) {
1515 std::memset(&status, 0, sizeof(status));
1516 return ::ioctl(fd, ioctl_get_status, &status) == 0;
1517 }
1518
1525 static bool owner_token_operation(int fd, uint32_t operation, uint32_t output_index,
1526 uint64_t session_id, std::array<uint64_t, 2> &token,
1527 uint32_t required_result, const char *description) {
1528 session_access_t request {};
1529 request.operation = operation;
1530 if (::ioctl(fd, ioctl_session_access, &request) != 0) {
1531 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] " << description << ": " << std::strerror(errno);
1532 forget_secret(&request, sizeof(request));
1533 token.fill(0);
1534 return false;
1535 }
1536
1537 token = {request.token[0], request.token[1]};
1538 const bool valid = (request.result_flags & session_access_result_token_valid) &&
1539 (request.result_flags & required_result) == required_result &&
1540 request.session_id == session_id && request.output_index == output_index &&
1541 (token[0] || token[1]);
1542 forget_secret(&request, sizeof(request));
1543 if (!valid) {
1544 token.fill(0);
1545 }
1546 return valid;
1547 }
1548
1549 static bool get_session_token(int fd, uint32_t output_index, uint64_t session_id,
1550 std::array<uint64_t, 2> &token) {
1551 return owner_token_operation(fd, session_access_get_token, output_index, session_id, token, 0,
1552 "Could not obtain the generic session capability");
1553 }
1554
1561 static bool revoke_session_bindings(int fd, uint32_t output_index, uint64_t session_id,
1562 std::array<uint64_t, 2> &token) {
1563 return owner_token_operation(fd, session_access_revoke_bindings, output_index, session_id, token,
1564 session_access_result_revoked,
1565 "Could not revoke the session's bindings");
1566 }
1567
1568 static bool bind_session(int fd, uint32_t output_index, uint64_t session_id,
1569 const std::array<uint64_t, 2> &token) {
1570 session_access_t request {};
1571 request.token[0] = token[0];
1572 request.token[1] = token[1];
1573 request.session_id = session_id;
1574 request.operation = session_access_bind;
1575 request.output_index = output_index;
1576 if (::ioctl(fd, ioctl_session_access, &request) != 0) {
1577 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] Could not bind capture to the requested session: "
1578 << std::strerror(errno);
1579 forget_secret(&request, sizeof(request));
1580 return false;
1581 }
1582
1583 const bool bound = (request.result_flags & session_access_result_bound) &&
1584 request.session_id == session_id && request.output_index == output_index;
1585 forget_secret(&request, sizeof(request));
1586 if (!bound) {
1587 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] Driver accepted SESSION_ACCESS without confirming the binding.";
1588 }
1589 return bound;
1590 }
1591
1599 static std::string mode_outside_envelope(const caps_t &caps, uint32_t width, uint32_t height,
1600 uint32_t refresh_hz) {
1601 const bool too_small = (caps.min_width && width < caps.min_width) ||
1602 (caps.min_height && height < caps.min_height);
1603 const bool too_large = (caps.max_width && width > caps.max_width) ||
1604 (caps.max_height && height > caps.max_height);
1605 const bool too_fast = caps.max_refresh_hz && refresh_hz > caps.max_refresh_hz;
1606 if (!too_small && !too_large && !too_fast) {
1607 return {};
1608 }
1609
1610 std::string reason = " The driver accepts " + std::to_string(caps.min_width) + 'x' +
1611 std::to_string(caps.min_height) + " to " + std::to_string(caps.max_width) +
1612 'x' + std::to_string(caps.max_height) + " up to " +
1613 std::to_string(caps.max_refresh_hz) + " Hz";
1614 reason += too_fast && !too_small && !too_large ?
1615 ", so the refresh rate is out of range." :
1616 ", so the requested mode is out of range.";
1617 return reason;
1618 }
1619
1620 static bool claim_available_output(device_t &device, uint32_t width, uint32_t height,
1621 uint32_t refresh_hz, uint64_t &session_id,
1622 bool log_failure = true) {
1623 const bool select_required = multi_output_requested();
1624 const uint32_t count = select_required ? output_count(device.caps) : 1U;
1625 for (uint32_t index = 0; index < count; ++index) {
1626 if (select_required && !select_output(device.fd, index, nullptr, false)) {
1627 continue;
1628 }
1629
1630 status_t status {};
1631 if (get_status(device.fd, status) &&
1632 (status.owner_pid > 0 || status.session_id != 0)) {
1633 continue;
1634 }
1635
1636 uint64_t candidate_session = 0;
1637 bool enabled = false;
1638 for (unsigned int attempt = 0; attempt < 6; ++attempt) {
1639 if (set_output(device.fd, true, width, height, refresh_hz, candidate_session, false)) {
1640 enabled = true;
1641 break;
1642 }
1643 if (errno != EAGAIN || attempt == 5) {
1644 break;
1645 }
1646 std::this_thread::sleep_for(std::chrono::milliseconds {200});
1647 }
1648 if (!enabled) {
1649 // Another session may have won the ownership race after GET_STATUS.
1650 if (errno == EBUSY) {
1651 continue;
1652 }
1653 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] Could not enable output " << (index + 1)
1654 << " at " << width << 'x' << height << '@' << refresh_hz << ": "
1655 << std::strerror(errno)
1656 << mode_outside_envelope(device.caps, width, height, refresh_hz);
1657 continue;
1658 }
1659
1660 device.selected_output_index = index;
1661 refresh_identity(device);
1662 session_id = candidate_session;
1663 return true;
1664 }
1665
1666 if (log_failure) {
1667 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] No free virtual output is available (configured outputs="
1668 << count << ").";
1669 }
1670 return false;
1671 }
1672
1689 static bool claim_broker_card(device_t &out, uint32_t width, uint32_t height, uint32_t refresh_hz,
1690 uint64_t &session_id, std::string &broker_card,
1691 std::optional<uid_t> card_owner_uid) {
1692 const auto card = card_broker::create(card_owner_uid);
1693 if (!card) {
1694 return false;
1695 }
1696
1697 const int card_index = card_index_from_path(card->card_path);
1698 constexpr unsigned int attempts = 30; // ~3s, generous for a udev rule.
1699 for (unsigned int attempt = 0; attempt < attempts; ++attempt) {
1700 auto devices = open_devices(false);
1701 for (auto &device : devices) {
1702 if (device.card_index == card_index &&
1703 claim_available_output(device, width, height, refresh_hz, session_id, false)) {
1704 out = device;
1705 device.fd = -1;
1706 for (auto &remaining : devices) {
1707 close_device(remaining);
1708 }
1709 broker_card = card->name;
1710 return true;
1711 }
1712 }
1713 for (auto &device : devices) {
1714 close_device(device);
1715 }
1716 std::this_thread::sleep_for(std::chrono::milliseconds {100});
1717 }
1718
1719 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] The broker created " << card->name
1720 << " but its render node never became usable; check that the driver's "
1721 "92-hermes-kms-access.rules is installed.";
1722 card_broker::remove(card->name);
1723 return false;
1724 }
1725
1726 static bool claim_available_device_output(
1727 device_t &out,
1728 uint32_t width,
1729 uint32_t height,
1730 uint32_t refresh_hz,
1731 uint64_t &session_id,
1732 std::string &broker_card,
1733 std::optional<uid_t> card_owner_uid
1734 ) {
1735 auto devices = open_devices(true);
1736 for (auto &device : devices) {
1737 // session_devices=N adds a seat0 HOST card. Per-client compositors may
1738 // claim only stable SESSION-role cards and use their session_index for
1739 // the matching private seat/broker.
1740 if (device.version.uapi_version < session_device_uapi_version ||
1741 device.identity.device_role != device_role_session ||
1742 device.identity.session_index == 0) {
1743 close_device(device);
1744 continue;
1745 }
1746
1747 if (!claim_available_output(device, width, height, refresh_hz, session_id, false)) {
1748 close_device(device);
1749 continue;
1750 }
1751
1752 out = device;
1753 device.fd = -1;
1754 for (auto &remaining : devices) {
1755 close_device(remaining);
1756 }
1757 return true;
1758 }
1759
1760 if (card_broker::available()) {
1761 return claim_broker_card(out, width, height, refresh_hz, session_id, broker_card, card_owner_uid);
1762 }
1763
1764 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] No independent DRM device/output is free for a new "
1765 "session, and no card broker is installed to create one.";
1766 return false;
1767 }
1768
1775 static bool disconnect_unowned_outputs(std::vector<std::string> &connector_names) {
1776 auto devices = open_devices(false);
1777 if (devices.empty()) {
1778 return false;
1779 }
1780
1781 bool disconnected = false;
1782 for (auto &device : devices) {
1783 const uint32_t count = output_count(device.caps);
1784 for (uint32_t index = 0; index < count; ++index) {
1785 if (device.version.uapi_version >= multi_output_uapi_version &&
1786 !select_output(device.fd, index, nullptr, false)) {
1787 continue;
1788 }
1789 refresh_identity(device);
1790 const auto connector_name = cstr(device.identity.connector_name);
1791
1792 status_t status {};
1793 if (get_status(device.fd, status) &&
1794 !(status.flags & status_output_enabled)) {
1795 continue;
1796 }
1797
1798 // Active state is private under UAPI v11. Disabling is nevertheless
1799 // safe: the driver accepts this only for an unowned legacy output and
1800 // rejects a live foreign session.
1801 uint64_t session_id = 0;
1802 if (set_output(device.fd, false, 0, 0, 0, session_id, false)) {
1803 BOOST_LOG(warning) << "[VDISPLAY/Hermes-KMS] Disconnected unowned virtual output "
1804 << cstr(device.identity.output_name) << " left enabled at module load.";
1805 if (!connector_name.empty()) {
1806 connector_names.emplace_back(connector_name);
1807 }
1808 disconnected = true;
1809 }
1810 }
1811 close_device(device);
1812 }
1813 return disconnected;
1814 }
1815
1816 static bool get_metrics(int fd, metrics_t &metrics) {
1817 std::memset(&metrics, 0, sizeof(metrics));
1818 return ::ioctl(fd, ioctl_get_metrics, &metrics) == 0;
1819 }
1820 } // namespace hermes_kms
1821
1822 // Virtual display info structure
1824 std::string name;
1825 std::string guid_str;
1826 std::string client_name;
1827 uint32_t width;
1828 uint32_t height;
1829 uint32_t fps;
1830 int device_index; // EVDI index or 0-based Hermes-KMS device index
1831 int session_index; // 1-based Hermes-KMS private-seat index, or -1
1832 int output_index; // 0-based Hermes-KMS output index
1833 int drm_card_index; // DRM card index assigned by the kernel
1834 evdi_handle handle; // EVDI handle
1835 int drm_fd; // DRM fd for card
1836 bool active;
1837 bool removal_pending {false};
1838 bool using_evdi; // true while an EVDI display is connected
1839 bool using_hermes_kms; // true while a Hermes-KMS output owner fd is held
1840 bool hermes_kms_session_lifecycle; // driver can revoke this session's bindings (uapi >= 13)
1841 std::string broker_card; // configfs card the broker made for this display, empty when pooled
1842 bool using_hyprland_headless; // true while Hyprland owns a headless output for this display
1843 std::string connector_name;
1844 uint64_t session_id;
1845 std::array<uint64_t, 2> session_token;
1846 std::shared_ptr<EvdiBuffer> evdi_buffer;
1847 int evdi_buffer_id;
1849 };
1850
1851 static std::map<std::string, VirtualDisplayInfo> virtual_displays;
1852
1853 static bool remove_virtual_display_locked(
1854 const std::string &guid_str,
1855 std::unique_lock<std::mutex> &lock,
1856 bool shutting_down = false
1857 );
1858
1865 static std::optional<VirtualDisplayInfo> parked_display;
1866
1868 static void release_parked_locked(const char *reason) {
1869 if (!parked_display) {
1870 return;
1871 }
1872 BOOST_LOG(info) << "[VDISPLAY] Releasing " << parked_display->name << ", which was kept for the login greeter: "
1873 << reason;
1874 if (parked_display->drm_fd >= 0) {
1875 hermes_kms::set_output(parked_display->drm_fd, false, 0, 0, 0, parked_display->session_id);
1876 ::close(parked_display->drm_fd);
1877 }
1878 parked_display.reset();
1879 }
1880
1881 static std::atomic<bool> evdi_events_running {false};
1882 static std::thread evdi_events_thread;
1883 static std::string evdi_connector_name(int card_index);
1884
1885 namespace {
1886
1888 bool desktop_token_matches(std::string_view token, std::string_view desktop) {
1889 if (token.size() < desktop.size()) {
1890 return false;
1891 }
1892 for (size_t i = 0; i < desktop.size(); ++i) {
1893 if (std::tolower(static_cast<unsigned char>(token[i])) != desktop[i]) {
1894 return false;
1895 }
1896 }
1897 // "GNOME" and "GNOME-Classic" are both Mutter; "GNOMEish" is not GNOME.
1898 return token.size() == desktop.size() || token[desktop.size()] == '-';
1899 }
1900
1901 } // namespace
1902
1903 compositor_e compositorFromDesktopNames(const std::string &desktop_names) {
1904 // "wlroots" is a family name, not a compositor: Hyprland advertises it too,
1905 // and a desktop list is not ordered by specificity ("wlroots:sway" and
1906 // "Hyprland:wlroots" are both shipped). Naming a compositor therefore wins
1907 // over naming its family no matter which token came first, so the generic
1908 // match is held back and only used once every token has been read.
1909 bool wlroots_family = false;
1910
1911 std::string_view remaining {desktop_names};
1912 while (!remaining.empty()) {
1913 const auto separator = remaining.find(':');
1914 const auto token = remaining.substr(0, separator);
1915 if (desktop_token_matches(token, "kde") || desktop_token_matches(token, "plasma")) {
1916 return compositor_e::kwin;
1917 }
1918 if (desktop_token_matches(token, "gnome")) {
1919 return compositor_e::mutter;
1920 }
1921 if (desktop_token_matches(token, "hyprland")) {
1923 }
1924 if (desktop_token_matches(token, "cosmic")) {
1925 return compositor_e::cosmic;
1926 }
1927 // These drive one strategy - plain wlr-output-management, no
1928 // per-compositor workaround - so they are one class, not one enumerator
1929 // each. A new wlroots compositor needs no code beyond this list.
1930 for (const auto *wlr : {"sway", "wayfire", "river", "labwc", "niri"}) {
1931 if (desktop_token_matches(token, wlr)) {
1932 return compositor_e::wlroots;
1933 }
1934 }
1935 if (desktop_token_matches(token, "wlroots")) {
1936 wlroots_family = true;
1937 }
1938 if (separator == std::string_view::npos) {
1939 break;
1940 }
1941 remaining.remove_prefix(separator + 1);
1942 }
1943 return wlroots_family ? compositor_e::wlroots : compositor_e::unknown;
1944 }
1945
1947 for (const char *variable : {"XDG_CURRENT_DESKTOP", "XDG_SESSION_DESKTOP"}) {
1948 const char *value = std::getenv(variable);
1949 if (value && value[0]) {
1950 if (const auto compositor = compositorFromDesktopNames(value); compositor != compositor_e::unknown) {
1951 return compositor;
1952 }
1953 }
1954 }
1955 // A session started from a TTY - `exec Hyprland`, `exec sway` - carries no
1956 // desktop name at all, which is precisely the setup a user reaching for
1957 // virtual displays is likely to have. Each of these compositors exports its
1958 // control socket unconditionally, so the socket names the session when the
1959 // desktop variables do not.
1960 struct socket_hint {
1961 const char *variable;
1962 compositor_e compositor;
1963 };
1964 for (const auto &[variable, compositor] : {
1965 socket_hint {"HYPRLAND_INSTANCE_SIGNATURE", compositor_e::hyprland},
1966 socket_hint {"SWAYSOCK", compositor_e::wlroots},
1967 socket_hint {"WAYFIRE_SOCKET", compositor_e::wlroots},
1968 }) {
1969 if (const char *value = std::getenv(variable); value && value[0]) {
1970 return compositor;
1971 }
1972 }
1973 return compositor_e::unknown;
1974 }
1975
1976 std::string compositorName(compositor_e compositor) {
1977 switch (compositor) {
1978 case compositor_e::kwin:
1979 return "KWin (KDE Plasma)";
1981 return "Mutter (GNOME)";
1983 return "Hyprland";
1985 return "a wlroots compositor";
1987 return "COSMIC";
1989 break;
1990 }
1991 return "an unrecognised compositor";
1992 }
1993
1994 std::string featureName(feature_e feature) {
1995 switch (feature) {
1997 return "virtual display";
1999 return "client-requested mode";
2001 return "exclusive mode";
2003 return "multiple virtual displays";
2005 return "isolated sessions";
2007 return "zero-copy capture";
2008 }
2009 return "unknown feature";
2010 }
2011
2012 std::string readinessName(readiness_e readiness) {
2013 switch (readiness) {
2014 case readiness_e::ready:
2015 return "ready";
2016 case readiness_e::degraded:
2017 return "degraded";
2018 case readiness_e::unavailable:
2019 return "unavailable";
2020 case readiness_e::unknown:
2021 return "unknown";
2022 }
2023 return "unknown";
2024 }
2025
2026 namespace {
2027
2037 std::string drm_card_seat(const std::filesystem::path &card) {
2038 std::ifstream dev_file {card / "dev"};
2039 std::string devnum;
2040 if (!std::getline(dev_file, devnum) || devnum.empty()) {
2041 return {};
2042 }
2043
2044 std::ifstream udev_db {std::filesystem::path {"/run/udev/data"} / ("c" + devnum)};
2045 if (!udev_db) {
2046 return {};
2047 }
2048
2049 static constexpr std::string_view seat_prefix {"E:ID_SEAT="};
2050 for (std::string line; std::getline(udev_db, line);) {
2051 if (line.starts_with(seat_prefix)) {
2052 return line.substr(seat_prefix.size());
2053 }
2054 }
2055 return {};
2056 }
2057
2059 bool is_hermes_kms_card(const std::filesystem::path &card) {
2060 std::ifstream uevent {card / "device" / "uevent"};
2061 for (std::string line; std::getline(uevent, line);) {
2062 if (line == "DRIVER=hermes-kms") {
2063 return true;
2064 }
2065 }
2066 return false;
2067 }
2068
2069 } // namespace
2070
2071 std::vector<FeatureReport> assessSession(const SessionFacts &facts) {
2072 std::vector<FeatureReport> reports;
2073 const auto add = [&reports](feature_e feature, readiness_e readiness, std::string detail, std::string remediation = {}) {
2074 reports.push_back({feature, readiness, std::move(detail), std::move(remediation)});
2075 };
2076
2077 // --- virtual display -----------------------------------------------------
2078 // Hyprland is judged on the compositor, not the backend: aquamarine's
2079 // trouble is with driving any display-only DRM device, so EVDI fails the
2080 // same way Hermes-KMS does and naming the backend would misdirect the user.
2081 readiness_e display_readiness = readiness_e::unavailable;
2082 if (!facts.wayland && !facts.x11) {
2083 // Not a verdict about the session: there isn't one yet. Saying "ready"
2084 // here - which treating this as X11 would - is worse than saying nothing.
2085 for (const auto feature : {
2092 }) {
2093 add(
2094 feature,
2096 "No window system is attached to this process, so nothing about the session can be observed.",
2097 "Run Hermes from inside the graphical session you intend to stream."
2098 );
2099 }
2100 return reports;
2101 }
2102 if (facts.x11) {
2103 display_readiness = readiness_e::ready;
2104 add(feature_e::virtual_display, display_readiness, "X11 session: the xrandr layout path applies.");
2105 } else if (facts.compositor == compositor_e::kwin) {
2106 display_readiness = facts.kscreen ? readiness_e::ready : readiness_e::unavailable;
2107 add(
2109 display_readiness,
2110 facts.kscreen ? "KWin, configured through kscreen-doctor." :
2111 "KWin is running but kscreen-doctor did not answer, so no layout can be applied.",
2112 facts.kscreen ? "" : "Install the kscreen package that provides kscreen-doctor."
2113 );
2114 } else if (facts.compositor == compositor_e::mutter) {
2115 display_readiness = facts.mutter ? readiness_e::ready : readiness_e::unavailable;
2116 add(
2118 display_readiness,
2119 facts.mutter ? "GNOME, driven through org.gnome.Mutter.DisplayConfig." :
2120 "GNOME is running but org.gnome.Mutter.DisplayConfig did not answer.",
2121 facts.mutter ? "" : "Check that gnome-shell is running and that Hermes may reach the session bus."
2122 );
2123 } else if (facts.compositor == compositor_e::hyprland) {
2124 // Hyprland renders a headless output itself, on the primary GPU. That is
2125 // a different mechanism from every other entry here - no virtual DRM
2126 // device, nothing imported - and it is the reason Hyprland is supported
2127 // at all: aquamarine cannot composite onto a display-only device, so the
2128 // device backends stay unavailable here no matter which one is
2129 // configured.
2130 display_readiness = facts.hyprland_control ? readiness_e::ready : readiness_e::unavailable;
2131 add(
2133 display_readiness,
2134 facts.hyprland_control ?
2135 "Hyprland creates a headless output on request and renders it on the primary GPU, "
2136 "so no virtual DRM device is involved." :
2137 "The session is Hyprland, but its control socket is not reachable, so Hermes cannot "
2138 "ask it for a headless output. Hermes-KMS and EVDI are not an alternative here: "
2139 "aquamarine wants every GPU owning an output to host a GL renderer, which a "
2140 "display-only device cannot, and the builds that import directly stall on the "
2141 "page-flip handshake against the driver's software vblank.",
2142 facts.hyprland_control ?
2143 "" :
2144 "Hermes reads HYPRLAND_INSTANCE_SIGNATURE from its own environment; start it inside "
2145 "the Hyprland session, or import that variable into the service."
2146 );
2147 } else if (facts.output_management) {
2148 const bool verified = facts.compositor == compositor_e::wlroots || facts.compositor == compositor_e::cosmic;
2149 display_readiness = verified ? readiness_e::ready : readiness_e::degraded;
2150 add(
2152 display_readiness,
2153 verified ? compositorName(facts.compositor) + ", driven through wlr-output-management." :
2154 "This compositor is not one Hermes has verified, but it advertises "
2155 "wlr-output-management, so the generic path applies."
2156 );
2157 } else {
2158 add(
2161 "The session advertises none of the protocols Hermes can drive an output with.",
2162 "A KDE, GNOME or wlroots session is required for automatic virtual-display activation."
2163 );
2164 }
2165
2166 // --- client-requested mode ----------------------------------------------
2167 if (display_readiness == readiness_e::unavailable) {
2168 add(
2171 "No virtual display can be driven here, so no mode can be applied to one."
2172 );
2173 } else if (facts.compositor == compositor_e::unknown && facts.wayland) {
2174 // wlr-output-management carries set_custom_mode, but whether a compositor
2175 // honours it for an arbitrary geometry is a per-compositor answer.
2176 add(
2179 "The mode is requested through wlr-output-management, which this compositor advertises. "
2180 "Whether it honours an arbitrary custom mode has not been verified here."
2181 );
2182 } else {
2183 add(feature_e::client_requested_mode, readiness_e::ready, "The mode the client asks for is pushed to the compositor and confirmed.");
2184 }
2185
2186 // --- exclusive mode ------------------------------------------------------
2187 const bool exclusive_mechanism = facts.x11 ||
2188 (facts.compositor == compositor_e::kwin && facts.kscreen) ||
2189 facts.output_management;
2190 if (facts.compositor == compositor_e::mutter) {
2191 add(
2194 facts.mutter ?
2195 "GNOME, through ApplyMonitorsConfig: a config naming only the virtual output disables the rest." :
2196 "GNOME is running but org.gnome.Mutter.DisplayConfig did not answer.",
2197 facts.mutter ? "" : "Check that gnome-shell is running and that Hermes may reach the session bus."
2198 );
2199 } else if (!exclusive_mechanism) {
2200 add(feature_e::exclusive_mode, readiness_e::unavailable, "No protocol in this session can disable a physical output.");
2201 } else if (display_readiness == readiness_e::unavailable) {
2202 // Worth saying rather than reporting "ready": the mechanism is present
2203 // and would work, but there is nothing here for it to blank the physical
2204 // monitors on behalf of.
2205 add(
2208 "The compositor can disable a physical output, but this session has no virtual display "
2209 "to blank it for."
2210 );
2211 } else {
2212 add(feature_e::exclusive_mode, readiness_e::ready, "Physical outputs are disabled for the session and restored afterwards.");
2213 }
2214
2215 // --- multiple displays ---------------------------------------------------
2216 // Every branch below counts outputs on a Hermes-KMS device, which is the
2217 // right question only when a DRM device is what backs a virtual display.
2218 // Hyprland creates headless outputs on demand and there is no fixed pool to
2219 // exhaust, so asking about hermes-kms here would report "unavailable" for a
2220 // session that supports this better than the device backends do.
2221 if (facts.compositor == compositor_e::hyprland) {
2222 add(
2225 facts.hyprland_control ?
2226 "Hyprland creates a headless output per request; there is no fixed pool of outputs." :
2227 "Hyprland's control socket is not reachable, so no headless output can be created at all.",
2228 facts.hyprland_control ?
2229 "" :
2230 "Start Hermes inside the Hyprland session, or import HYPRLAND_INSTANCE_SIGNATURE into the service."
2231 );
2232 } else if (!facts.hermes_kms_present) {
2233 add(
2236 "More than one virtual display needs the Hermes-KMS backend; no Hermes-KMS device was opened.",
2237 "Install and load the hermes-kms module."
2238 );
2239 } else if (facts.hermes_kms_multi_output || facts.hermes_kms_multi_device) {
2240 add(feature_e::multiple_displays, readiness_e::ready, "The Hermes-KMS device exposes more than one output.");
2241 } else {
2242 add(
2245 "The Hermes-KMS device exposes a single output.",
2246 "Load hermes_kms with outputs=N (or session_devices=N) and enable the multi-output option."
2247 );
2248 }
2249
2250 // --- isolated sessions ---------------------------------------------------
2251 if (!facts.hermes_kms_multi_device) {
2252 add(
2255 "The loaded hermes-kms driver exposes no session-device pool.",
2256 "Update hermes-kms to a version providing private session devices."
2257 );
2258 } else if (!facts.drm_seat_isolation) {
2259 // The failure this whole probe exists for: every other check passes, the
2260 // session starts, its input is isolated - and its screen is not, because
2261 // a card with no ID_SEAT is on seat0 where the host compositor claims it.
2262 add(
2265 "No Hermes-KMS card carries a private DRM seat, so the host compositor claims the session "
2266 "cards and a session would share the host's screen. Input isolation is installed "
2267 "separately and may already be working, which is what makes this failure quiet.",
2268 "Install the driver's session-seat rule with 'make install-udev' - it lands as "
2269 "72-hermes-kms-session-seats.rules, 70- in driver builds before it moved - then reload "
2270 "udev and re-plug or reload the hermes-kms module."
2271 );
2272 } else {
2273 add(feature_e::isolated_sessions, readiness_e::ready, "Hermes-KMS session cards carry private DRM seats.");
2274 }
2275
2276 // --- zero-copy capture ---------------------------------------------------
2277 if (facts.hermes_kms_present) {
2278 add(feature_e::zero_copy_capture, readiness_e::ready, "Captured as DMA-BUF over the Hermes-KMS render node.");
2279 } else if (facts.x11) {
2280 add(feature_e::zero_copy_capture, readiness_e::degraded, "X11 capture goes through a CPU copy.");
2281 } else if (facts.linux_dmabuf && (facts.screencopy || facts.image_copy_capture)) {
2282 add(feature_e::zero_copy_capture, readiness_e::ready, "The session offers a screen-capture protocol with linux-dmabuf.");
2283 } else if (!facts.screencopy && !facts.image_copy_capture) {
2284 add(
2287 "The session advertises no screen-capture protocol Hermes can use."
2288 );
2289 } else {
2290 add(
2293 "A capture protocol is available but linux-dmabuf is not, so frames are copied through the CPU."
2294 );
2295 }
2296
2297 return reports;
2298 }
2299
2301 // In the session-device pool the host card deliberately stays on seat0, so
2302 // the question is not whether every card carries a private seat but whether
2303 // any does. None of them doing so is the signature of the driver's udev
2304 // rule not being installed, which is the failure this exists to catch.
2305 std::error_code ec;
2306 for (const auto &entry : std::filesystem::directory_iterator {"/sys/class/drm", ec}) {
2307 const auto name = entry.path().filename().string();
2308 if (!name.starts_with("card") || name.find('-') != std::string::npos) {
2309 continue; // "card0-Virtual-1" is a connector, not a card.
2310 }
2311 if (is_hermes_kms_card(entry.path()) && drm_card_seat(entry.path()).starts_with("hermes-kms-")) {
2312 return true;
2313 }
2314 }
2315 return false;
2316 }
2317
2318 std::optional<bool> displayConnectorLit(const std::filesystem::path &drm_class, const std::string &ignored_connector) {
2319 const auto read_attribute = [](const std::filesystem::path &file) {
2320 std::ifstream in {file};
2321 std::string value;
2322 std::getline(in, value);
2323 return value;
2324 };
2325 const auto ignored_suffix = ignored_connector.empty() ? std::string {} : "-" + ignored_connector;
2326
2327 // Every card is recorded, and marked once a connector of its turns up, so
2328 // a card with no connector at all - one sysfs cannot see the monitors of -
2329 // is told apart from one whose monitors are all dark.
2330 std::map<std::string, bool> card_has_connector;
2331 std::error_code ec;
2332 for (const auto &entry : std::filesystem::directory_iterator {drm_class, ec}) {
2333 const auto name = entry.path().filename().string();
2334 if (!name.starts_with("card")) {
2335 continue; // renderD128, version
2336 }
2337 const auto dash = name.find('-');
2338 if (dash == std::string::npos) {
2339 card_has_connector.try_emplace(name, false);
2340 continue;
2341 }
2342 if (name.find("-Writeback-") != std::string::npos) {
2343 continue; // A capture sink the compositor can enable, never a monitor.
2344 }
2345 card_has_connector[name.substr(0, dash)] = true;
2346 if (!ignored_suffix.empty() && name.ends_with(ignored_suffix)) {
2347 continue;
2348 }
2349 if (read_attribute(entry.path() / "status") != "disconnected" &&
2350 read_attribute(entry.path() / "enabled") == "enabled") {
2351 return true;
2352 }
2353 }
2354
2355 if (ec || card_has_connector.empty()) {
2356 return std::nullopt;
2357 }
2358 for (const auto &[card, has_connector] : card_has_connector) {
2359 if (!has_connector) {
2360 return std::nullopt;
2361 }
2362 }
2363 return false;
2364 }
2365
2367 return window_system != window_system_e::NONE;
2368 }
2369
2377 static std::optional<bool> greeter_holds_seat() {
2378#ifdef HERMES_BUILD_SDBUS
2379 char *session_raw = nullptr;
2380 const int status = sd_seat_get_active("seat0", &session_raw, nullptr);
2381 const std::unique_ptr<char, decltype(&std::free)> session {session_raw, &std::free};
2382 if (status == -ENODATA || status == -ENXIO) {
2383 return false; // Nothing is in front: between sessions, or a text console.
2384 }
2385 if (status < 0 || !session) {
2386 return std::nullopt;
2387 }
2388 char *class_raw = nullptr;
2389 if (sd_session_get_class(session.get(), &class_raw) < 0 || !class_raw) {
2390 return std::nullopt;
2391 }
2392 const std::unique_ptr<char, decltype(&std::free)> session_class {class_raw, &std::free};
2393 return std::string_view {session_class.get()} == "greeter";
2394#else
2395 return std::nullopt;
2396#endif
2397 }
2398
2399 bool removalStrandsGreeter(bool greeter_on_seat, bool output_lit, std::optional<bool> another_connector_lit) {
2400 // Only a monitor known to be lit lets the output go. When sysfs cannot
2401 // say, keeping an output the greeter did not need costs a spare screen at
2402 // the login prompt; dropping one it did need costs the login prompt.
2403 return greeter_on_seat && output_lit && another_connector_lit != std::optional<bool> {true};
2404 }
2405
2406 std::string parkedConnector() {
2407 std::lock_guard<std::mutex> lock(vdisplay_mutex);
2408 return parked_display ? parked_display->connector_name : std::string {};
2409 }
2410
2411 bool waitForConnectorEnabled(const std::string &connector, std::chrono::milliseconds timeout, const std::filesystem::path &drm_class) {
2412 if (connector.empty()) {
2413 return false;
2414 }
2415 // Connector type ids are numbered across every DRM device, so the name
2416 // alone identifies one; only the card prefix of its sysfs entry is unknown.
2417 const auto suffix = "-" + connector;
2418 const auto deadline = std::chrono::steady_clock::now() + timeout;
2419 while (true) {
2420 std::error_code ec;
2421 for (const auto &entry : std::filesystem::directory_iterator {drm_class, ec}) {
2422 const auto name = entry.path().filename().string();
2423 if (!name.starts_with("card") || !name.ends_with(suffix)) {
2424 continue;
2425 }
2426 // `enabled` follows the committed state; `status` is only a cache of
2427 // the last probe and can still say "disconnected" here.
2428 std::ifstream in {entry.path() / "enabled"};
2429 std::string value;
2430 std::getline(in, value);
2431 if (value == "enabled") {
2432 return true;
2433 }
2434 }
2435 if (std::chrono::steady_clock::now() >= deadline) {
2436 return false;
2437 }
2438 std::this_thread::sleep_for(std::chrono::milliseconds {100});
2439 }
2440 }
2441
2447 static bool safe_output_name(const std::string &name) {
2448 return !name.empty() && name.size() <= 64 && std::all_of(name.begin(), name.end(), [](unsigned char c) {
2449 return std::isalnum(c) || c == '-' || c == '_';
2450 });
2451 }
2452
2454 const std::string &virtual_output,
2455 const std::map<std::string, int> &enabled_before,
2456 int target_x,
2457 int target_y,
2458 int mode_width,
2459 int mode_height,
2460 int mode_refresh_hz,
2461 const std::map<std::string, kscreen_point_t> &positions_before,
2463 ) {
2464 if (!safe_output_name(virtual_output)) {
2465 // Every caller reads this name back from the compositor, which has no
2466 // reason to invent one a shell would reinterpret. Refuse rather than
2467 // quote: a name that fails this is a bug upstream of here, not a layout
2468 // to apply.
2469 return {};
2470 }
2471
2472 std::string command = "kscreen-doctor";
2473 if (layout != virtual_display_layout_e::detached) {
2474 // Primary puts the virtual output first and moves every physical output
2475 // down one place, keeping their order. Applications and games open on
2476 // the primary output, so this is what puts them in the stream while the
2477 // monitors stay on. restore() puts the recorded priorities back.
2478 const bool virtual_primary = layout == virtual_display_layout_e::primary;
2479 const int shift = virtual_primary ? 1 : 0;
2480 int next_priority = 1 + shift;
2481 for (const auto &[output, priority] : enabled_before) {
2482 if (output == virtual_output || !safe_output_name(output)) {
2483 continue;
2484 }
2485 command += " output." + output + ".enable";
2486 if (priority > 0) {
2487 command += " output." + output + ".priority." + std::to_string(priority + shift);
2488 next_priority = std::max(next_priority, priority + shift + 1);
2489 }
2490 // Enabling an output says nothing about where it lands, so KWin keeps
2491 // whatever the setup it replayed for this output combination said - which
2492 // is the origin for a combination last used exclusively. Put each one
2493 // back where the user had it, so the layout this builds is the whole
2494 // layout rather than a virtual output placed against a moving target.
2495 if (const auto position = positions_before.find(output); position != positions_before.end()) {
2496 command += " output." + output + ".position." +
2497 std::to_string(position->second.x) + ',' + std::to_string(position->second.y);
2498 }
2499 }
2500
2501 command += " output." + virtual_output + ".enable";
2502 command += " output." + virtual_output + ".priority." + std::to_string(virtual_primary ? 1 : next_priority);
2503 } else {
2504 // Detached mode deliberately does not name any physical output and does
2505 // not change the virtual output's priority. KWin may read the physical
2506 // geometry so Hermes can place the virtual desktop beside it, but the
2507 // transaction itself is scoped to the virtual connector.
2508 command += " output." + virtual_output + ".enable";
2509 }
2510 command += " output." + virtual_output + ".position." +
2511 std::to_string(target_x) + ',' + std::to_string(target_y);
2512
2513 // KWin adopts a hotplugged connector at the mode it prefers, not the one
2514 // the client negotiated. Hermes-KMS marks the client's exact CVT mode
2515 // DRM_MODE_TYPE_PREFERRED and still exposes the standard ladder beside it,
2516 // and KWin picked 1920x1080 out of that ladder for an 854x480 session. The
2517 // capture path reports the real scanout, so the client received a
2518 // full-resolution stream of a display it had asked to be small. Presence
2519 // was never enough to check - push the mode, as the Mutter path does
2520 // through ApplyMonitorsConfig.
2521 if (mode_width > 0 && mode_height > 0 && mode_refresh_hz > 0) {
2522 command += " output." + virtual_output + ".mode." +
2523 std::to_string(mode_width) + 'x' + std::to_string(mode_height) +
2524 '@' + std::to_string(mode_refresh_hz);
2525 }
2526
2527 return command;
2528 }
2529
2531 const std::string &virtual_output,
2532 const std::vector<kscreen_output_t> &before,
2533 const std::vector<kscreen_output_t> &current,
2535 ) {
2536 std::set<std::string> present;
2537 for (const auto &output : current) {
2538 if (output.connected) {
2539 present.insert(output.name);
2540 }
2541 }
2542
2543 kscreen_point_t position {};
2544 bool anchored = false;
2545
2546 const auto place_against = [&](const std::vector<kscreen_output_t> &layout_outputs, bool check_presence) {
2547 for (const auto &output : layout_outputs) {
2548 if (output.name == virtual_output ||
2549 !output.connected ||
2550 !output.enabled ||
2551 (check_presence && !present.empty() && !present.contains(output.name))) {
2552 continue;
2553 }
2554
2555 if (layout == virtual_display_layout_e::mirror) {
2556 // Mirror overlaps the primary output so KWin clones the desktop onto
2557 // the virtual connector: windows the compositor places on the physical
2558 // monitor (a nested Gamescope, the panel, anything) then appear in the
2559 // captured stream. This restores the pre-0.5.0 behaviour, per app.
2560 //
2561 // KScreen priority 1 marks the primary output. Before one is found,
2562 // keep the first enabled output as the fallback anchor.
2563 if (output.priority == 1 || !anchored) {
2564 position = {output.x, output.y};
2565 anchored = true;
2566 if (output.priority == 1) {
2567 return;
2568 }
2569 }
2570 continue;
2571 }
2572
2573 // Extend keeps the virtual desktop regions disjoint: overlap mirrors
2574 // physical content into the stream and makes absolute input ambiguous.
2575 // Append the virtual output to the right of everything else.
2576 if (!anchored) {
2577 position = {output.x + output.width, output.y};
2578 anchored = true;
2579 } else {
2580 position.x = std::max(position.x, output.x + output.width);
2581 position.y = std::min(position.y, output.y);
2582 }
2583 }
2584 };
2585
2586 place_against(before, true);
2587 if (!anchored) {
2588 place_against(current, false);
2589 }
2590 return position;
2591 }
2592
2594 const std::vector<kscreen_output_t> &outputs,
2595 const std::string &output_name,
2596 int &offset_x,
2597 int &offset_y,
2598 int &environment_width,
2599 int &environment_height
2600 ) {
2601 const auto selected = std::find_if(outputs.begin(), outputs.end(), [&](const auto &output) {
2602 return output.connected && output.enabled && output.name == output_name &&
2603 output.width > 0 && output.height > 0;
2604 });
2605 if (selected == outputs.end()) {
2606 return false;
2607 }
2608
2609 // Start at a real enabled output, not the coordinate-system origin.
2610 // KWin keeps Virtual-1 at (3440,0) after disabling the 3440-wide monitor
2611 // beside it. In that exclusive layout the desktop begins at x=3440 and is
2612 // 2560 pixels wide; including the now-empty path back to zero made an
2613 // absolute pointer land about three inches to the right on the reporter's
2614 // tablet.
2615 int min_x = selected->x;
2616 int min_y = selected->y;
2617 int max_x = selected->x + selected->width;
2618 int max_y = selected->y + selected->height;
2619 for (const auto &output : outputs) {
2620 if (!output.connected || !output.enabled || output.width <= 0 || output.height <= 0) {
2621 continue;
2622 }
2623 min_x = std::min(min_x, output.x);
2624 min_y = std::min(min_y, output.y);
2625 max_x = std::max(max_x, output.x + output.width);
2626 max_y = std::max(max_y, output.y + output.height);
2627 }
2628
2629 const int width = max_x - min_x;
2630 const int height = max_y - min_y;
2631 if (width <= 0 || height <= 0) {
2632 return false;
2633 }
2634
2635 offset_x = selected->x - min_x;
2636 offset_y = selected->y - min_y;
2637 environment_width = width;
2638 environment_height = height;
2639 return true;
2640 }
2641
2642 std::optional<std::string> kscreenLayoutFailure(std::string_view output) {
2643 // Every way libkscreen's doctor.cpp reports an option it did not apply or a
2644 // configuration KWin refused. Its debug lines ("kscreen.doctor: Set output
2645 // position ...") and the mode it found are not failures.
2646 constexpr std::string_view markers[] {
2647 "applying config failed", // KWin refused the configuration
2648 " not found.", // "Output with name or uuid X", "Output with id N", "Output mode M"
2649 "Wrong input",
2650 "Invalid ",
2651 "Could not set ",
2652 "No output ",
2653 "DBus error from KWin",
2654 "Unable to parse", // a position or an argument
2655 "does not support disabling",
2656 "DPMS not supported",
2657 "DPMS is only supported",
2658 "argument not understood", // --dpms
2659 };
2660 std::size_t start = 0;
2661 while (start < output.size()) {
2662 const auto end = std::min(output.find('\n', start), output.size());
2663 auto line = output.substr(start, end - start);
2664 for (const auto marker : markers) {
2665 if (line.find(marker) != std::string_view::npos) {
2666 while (!line.empty() && (line.back() == '\r' || line.back() == ' ')) {
2667 line.remove_suffix(1);
2668 }
2669 return std::string {line};
2670 }
2671 }
2672 start = end + 1;
2673 }
2674 return std::nullopt;
2675 }
2676
2678 const std::string &json_text,
2679 const std::string &output,
2680 int width,
2681 int height,
2682 int refresh_hz
2683 ) {
2684 if (json_text.empty() || output.empty() || width <= 0 || height <= 0 || refresh_hz <= 0) {
2686 }
2687
2688 try {
2689 const auto data = nlohmann::json::parse(json_text);
2690 for (const auto &entry : data.value("outputs", nlohmann::json::array())) {
2691 if (entry.value("name", std::string {}) != output) {
2692 continue;
2693 }
2694
2695 const auto current_mode_id = entry.value("currentModeId", std::string {});
2697 for (const auto &mode : entry.value("modes", nlohmann::json::array())) {
2698 const auto size = mode.value("size", nlohmann::json::object());
2699 if (size.value("width", 0) != width || size.value("height", 0) != height) {
2700 continue;
2701 }
2702 if (std::lround(mode.value("refreshRate", 0.0)) != refresh_hz) {
2703 continue;
2704 }
2705 if (!current_mode_id.empty() && mode.value("id", std::string {}) == current_mode_id) {
2707 }
2709 }
2710 return state;
2711 }
2712 } catch (const std::exception &error) {
2713 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Could not parse the mode list: " << error.what();
2714 }
2716 }
2717
2718 std::optional<kscreen_hdr_state_t> kscreenHdrState(const std::string &json_text, const std::string &output) {
2719 if (!safe_output_name(output)) {
2720 return std::nullopt;
2721 }
2722 try {
2723 const auto data = nlohmann::json::parse(json_text);
2724 for (const auto &entry : data.at("outputs")) {
2725 if (entry.value("name", std::string {}) != output) {
2726 continue;
2727 }
2728 if (!entry.value("connected", false) || !entry.value("enabled", true)) {
2729 return std::nullopt;
2730 }
2731 // libkscreen omits hdr/wcg when the corresponding capability is absent.
2732 return kscreen_hdr_state_t {entry.contains("hdr"), entry.value("hdr", false),
2733 entry.contains("wcg"), entry.value("wcg", false)};
2734 }
2735 } catch (const std::exception &) {
2736 // Missing/malformed state must not select another output or imply success.
2737 }
2738 return std::nullopt;
2739 }
2740
2741 std::optional<std::string> boundedCommandOutput(const std::string &command, std::chrono::milliseconds timeout, bool *timed_out) {
2742 return platf::bounded_command::output(command, timeout, timed_out);
2743 }
2744
2745 namespace kscreen {
2746 using output_t = kscreen_output_t;
2747
2754 constexpr std::chrono::seconds command_timeout {10};
2755
2756 struct layout_t {
2757 // Every physical output that was enabled before the virtual connector
2758 // appeared, mapped to its KScreen priority. Exclusive mode disables all
2759 // of them, not just the primary one, and restore() brings them all back
2760 // with the priorities they had.
2761 std::map<std::string, int> original_outputs;
2762 std::string virtual_output;
2763 bool physical_output_disabled {false};
2764 bool preserve_physical_outputs {false};
2765 bool restore_pending {false};
2766 bool release_requested {false};
2767 };
2768
2769 static std::mutex layouts_mutex;
2770 static std::map<std::string, layout_t> layouts;
2771 static bool startup_recovery_pending {false};
2772
2773 static bool available() {
2775 return false;
2776 }
2777 return ::access("/usr/bin/kscreen-doctor", X_OK) == 0 || ::access("/bin/kscreen-doctor", X_OK) == 0;
2778 }
2779
2780 static std::string command_output(const char *command) {
2781 bool timed_out = false;
2782 auto output = boundedCommandOutput(command, command_timeout, &timed_out);
2783 if (timed_out) {
2784 BOOST_LOG(warning) << "[VDISPLAY/KScreen] " << command << " did not answer within "
2785 << command_timeout.count() << " seconds and was stopped.";
2786 }
2787 return output.value_or(std::string {});
2788 }
2789
2790 static monitor_restore::snapshot_t output_snapshot() {
2791 std::vector<output_t> result;
2792 if (!available()) {
2793 return std::nullopt;
2794 }
2795
2796 const auto json_text = command_output("kscreen-doctor -j");
2797 if (json_text.empty()) {
2798 return std::nullopt;
2799 }
2800
2801 try {
2802 const auto data = nlohmann::json::parse(json_text);
2803 if (!data.is_object() || !data.contains("outputs") || !data["outputs"].is_array()) {
2804 return std::nullopt;
2805 }
2806 for (const auto &entry : data["outputs"]) {
2807 if (!entry.is_object() || !entry.contains("name") || !entry["name"].is_string() ||
2808 !entry.contains("connected") || !entry["connected"].is_boolean() ||
2809 !entry.contains("enabled") || !entry["enabled"].is_boolean()) {
2810 return std::nullopt;
2811 }
2812 output_t output {
2813 .name = entry.value("name", std::string {}),
2814 .connected = entry.value("connected", false),
2815 .enabled = entry.value("enabled", false),
2816 .priority = entry.value("priority", 0),
2817 .x = entry.value("pos", nlohmann::json::object()).value("x", 0),
2818 .y = entry.value("pos", nlohmann::json::object()).value("y", 0),
2819 .width = entry.value("size", nlohmann::json::object()).value("width", 0),
2820 .height = entry.value("size", nlohmann::json::object()).value("height", 0),
2821 };
2822 if (safe_output_name(output.name)) {
2823 result.emplace_back(std::move(output));
2824 }
2825 }
2826 } catch (const std::exception &error) {
2827 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Could not parse output layout: " << error.what();
2828 return std::nullopt;
2829 }
2830 return result;
2831 }
2832
2833 static std::vector<output_t> outputs() {
2834 return output_snapshot().value_or(std::vector<output_t> {});
2835 }
2836
2837 static std::set<std::string> connected_output_names(const std::vector<output_t> &current) {
2838 std::set<std::string> result;
2839 for (const auto &output : current) {
2840 if (output.connected) {
2841 result.insert(output.name);
2842 }
2843 }
2844 return result;
2845 }
2846
2847 static std::map<std::string, int> enabled_output_priorities(const std::vector<output_t> &current) {
2848 std::map<std::string, int> result;
2849 for (const auto &output : current) {
2850 if (output.connected && output.enabled) {
2851 result.emplace(output.name, output.priority);
2852 }
2853 }
2854 return result;
2855 }
2856
2857 static bool run_layout_command(const std::string &command) {
2858 bool timed_out = false;
2859 const auto output = boundedCommandOutput(command + " 2>&1", command_timeout, &timed_out);
2860 if (!output) {
2861 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Layout command "
2862 << (timed_out ? "did not finish in time and was stopped: " : "failed: ") << command;
2863 return false;
2864 }
2865 // kscreen-doctor exits 0 whatever happened; only its output tells.
2866 if (const auto failure = kscreenLayoutFailure(*output)) {
2867 BOOST_LOG(warning) << "[VDISPLAY/KScreen] The layout was not applied (" << *failure << "): " << command;
2868 return false;
2869 }
2870 return true;
2871 }
2872
2873 static std::string recovery_state_file() {
2874 const char *xdg_state = std::getenv("XDG_STATE_HOME");
2875 const char *home = std::getenv("HOME");
2876 std::string base;
2877 if (xdg_state && xdg_state[0]) {
2878 base = std::string {xdg_state} + "/hermes";
2879 } else if (home && home[0]) {
2880 base = std::string {home} + "/.local/state/hermes";
2881 } else {
2882 return {};
2883 }
2884
2885 std::error_code ec;
2886 fs::create_directories(base, ec);
2887 return base + "/saved-primary";
2888 }
2889
2896 static std::string enable_outputs_command(const std::map<std::string, int> &outputs) {
2897 std::string command = "kscreen-doctor";
2898 int next_priority = 1;
2899 for (const auto &[output, priority] : outputs) {
2900 const int effective = priority > 0 ? priority : next_priority;
2901 command += " output." + output + ".enable";
2902 command += " output." + output + ".priority." + std::to_string(effective);
2903 next_priority = std::max(next_priority, effective + 1);
2904 }
2905 return command;
2906 }
2907
2913 static bool write_recovery_state(const std::map<std::string, int> &outputs) {
2914 std::map<std::string, int> valid;
2915 for (const auto &[output, priority] : outputs) {
2916 if (safe_output_name(output)) {
2917 valid.emplace(output, priority);
2918 }
2919 }
2920 if (valid.empty()) {
2921 return false;
2922 }
2923
2924 const auto path = recovery_state_file();
2925 if (path.empty()) {
2926 return false;
2927 }
2928
2929 const auto temporary_path = path + ".tmp";
2930 {
2931 std::ofstream file {temporary_path, std::ios::binary | std::ios::trunc};
2932 if (!file) {
2933 return false;
2934 }
2935 for (const auto &[output, priority] : valid) {
2936 file << output << ' ' << priority << '\n';
2937 }
2938 file.flush();
2939 if (!file) {
2940 return false;
2941 }
2942 }
2943
2944 std::error_code ec;
2945 fs::rename(temporary_path, path, ec);
2946 if (ec) {
2947 fs::remove(temporary_path, ec);
2948 return false;
2949 }
2950 return true;
2951 }
2952
2953 static std::map<std::string, int> read_recovery_state() {
2954 std::map<std::string, int> outputs;
2955 const auto path = recovery_state_file();
2956 if (path.empty()) {
2957 return outputs;
2958 }
2959
2960 std::ifstream file {path};
2961 std::string line;
2962 while (std::getline(file, line)) {
2963 std::istringstream stream {line};
2964 std::string output;
2965 int priority = 0;
2966 // A file written by an older Hermes holds a bare output name with no
2967 // priority; leave it at 0 so it is assigned the first free priority.
2968 if (!(stream >> output) || !safe_output_name(output)) {
2969 continue;
2970 }
2971 if (!(stream >> priority) || priority < 0) {
2972 priority = 0;
2973 }
2974 outputs.emplace(output, priority);
2975 }
2976 return outputs;
2977 }
2978
2979 static void clear_recovery_state() {
2980 const auto path = recovery_state_file();
2981 if (path.empty()) {
2982 return;
2983 }
2984 std::error_code ec;
2985 fs::remove(path, ec);
2986 }
2987
2988 static bool restore_outputs(const std::map<std::string, int> &saved) {
2989 return monitor_restore::restore(saved, output_snapshot, [](const auto &targets) {
2990 return run_layout_command(enable_outputs_command(targets));
2991 });
2992 }
2993
2994 // Called with layouts_mutex held. One display must not erase another
2995 // session's recovery record when it finishes restoring its own monitors.
2996 static bool persist_pending_recovery() {
2997 std::map<std::string, int> pending;
2998 for (const auto &[name, layout] : layouts) {
2999 if (layout.physical_output_disabled || layout.restore_pending) {
3000 pending.insert(layout.original_outputs.begin(), layout.original_outputs.end());
3001 }
3002 }
3003 if (pending.empty()) {
3004 if (!startup_recovery_pending) {
3005 clear_recovery_state();
3006 }
3007 return true;
3008 }
3009 return write_recovery_state(pending);
3010 }
3011
3012 static void recover_on_startup() {
3013 std::lock_guard<std::mutex> lock(layouts_mutex);
3014 const auto saved_outputs = read_recovery_state();
3015 if (saved_outputs.empty()) {
3016 startup_recovery_pending = false;
3017 return;
3018 }
3019 BOOST_LOG(info) << "[VDISPLAY/KScreen] Recovering the saved physical output layout.";
3020 startup_recovery_pending = !restore_outputs(saved_outputs);
3021 if (!startup_recovery_pending) {
3022 clear_recovery_state();
3023 } else {
3024 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Physical output recovery is pending; retaining the saved layout.";
3025 }
3026 }
3027
3038 static bool apply_pre_session_layout(
3039 const std::string &virtual_output,
3040 const std::vector<output_t> &before,
3041 const std::map<std::string, int> &enabled_before,
3042 int mode_width,
3043 int mode_height,
3044 int mode_refresh_hz,
3045 virtual_display_layout_e layout
3046 ) {
3047 const auto current = outputs();
3048 const auto position = kscreenVirtualOutputPosition(virtual_output, before, current, layout);
3049 const int target_x = position.x;
3050 const int target_y = position.y;
3051
3052 std::map<std::string, kscreen_point_t> positions_before;
3053 for (const auto &output : before) {
3054 if (output.name != virtual_output && enabled_before.contains(output.name)) {
3055 positions_before[output.name] = {output.x, output.y};
3056 }
3057 }
3058
3059 const bool has_mode = mode_width > 0 && mode_height > 0 && mode_refresh_hz > 0;
3061 virtual_output, enabled_before, target_x, target_y, mode_width, mode_height, mode_refresh_hz,
3062 positions_before, layout);
3063 if (command.empty()) {
3064 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Refusing to build a layout around output name "
3065 << virtual_output;
3066 return false;
3067 }
3068
3069 if (!run_layout_command(command)) {
3070 // A mode KWin refuses must not cost us the rest of the layout: the
3071 // output still has to be enabled and placed or there is nothing to
3072 // capture at all. Retry without it, and say what the session lost
3073 // rather than leaving a silent resolution mismatch.
3074 if (!has_mode || !run_layout_command(buildKScreenLayoutCommand(
3075 virtual_output, enabled_before, target_x, target_y, 0, 0, 0,
3076 positions_before, layout))) {
3077 return false;
3078 }
3079 BOOST_LOG(warning) << "[VDISPLAY/KScreen] KWin rejected mode "
3080 << mode_width << 'x' << mode_height << '@' << mode_refresh_hz
3081 << " for " << virtual_output
3082 << "; the output is enabled at the mode KWin chose, so the stream "
3083 "will not match the resolution the client asked for.";
3084 }
3085 BOOST_LOG(info) << "[VDISPLAY/KScreen] Positioned " << virtual_output
3086 << " at " << target_x << ',' << target_y
3087 << (layout == virtual_display_layout_e::mirror ?
3088 " overlapping the primary output (mirror)" :
3089 layout == virtual_display_layout_e::detached ?
3090 " outside the physical output regions (detached; physical outputs preserved)" :
3091 layout == virtual_display_layout_e::primary ?
3092 " outside the pre-session output regions, as the primary output" :
3093 " outside the pre-session output regions");
3094 return true;
3095 }
3096
3103 static void recover_after_unowned_virtual_disconnect(const std::string &virtual_connector) {
3104 if (!available()) {
3105 return;
3106 }
3107
3108 for (int attempt = 0; attempt < 20; ++attempt) {
3109 const auto current = outputs();
3110 std::vector<std::string> physical_outputs;
3111 bool physical_output_enabled = false;
3112 for (const auto &output : current) {
3113 if (!output.connected || output.name == virtual_connector) {
3114 continue;
3115 }
3116 physical_outputs.emplace_back(output.name);
3117 physical_output_enabled = physical_output_enabled || output.enabled;
3118 }
3119
3120 if (physical_output_enabled) {
3121 return;
3122 }
3123 if (!physical_outputs.empty()) {
3124 std::string command = "kscreen-doctor";
3125 int priority = 1;
3126 for (const auto &output : physical_outputs) {
3127 command += " output." + output + ".enable";
3128 command += " output." + output + ".priority." + std::to_string(priority++);
3129 }
3130 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Restoring physical outputs after disconnecting a boot-enabled virtual output.";
3131 run_layout_command(command);
3132 return;
3133 }
3134 std::this_thread::sleep_for(std::chrono::milliseconds {50});
3135 }
3136 }
3137
3138 static bool activate_evdi_output(
3139 const std::string &display_name,
3140 const std::vector<output_t> &before,
3141 const std::string &connector_name,
3142 const char *backend_label,
3143 int mode_width,
3144 int mode_height,
3145 int mode_refresh_hz,
3146 virtual_display_layout_e layout
3147 ) {
3148 if (!available()) {
3149 return false;
3150 }
3151
3152 const auto outputs_before = connected_output_names(before);
3153 const auto enabled_before = enabled_output_priorities(before);
3154
3155 std::string virtual_output;
3156 for (int attempt = 0; attempt < 30 && virtual_output.empty(); ++attempt) {
3157 std::this_thread::sleep_for(std::chrono::milliseconds {100});
3158 const auto current_outputs = outputs();
3159 const auto expected = std::find_if(current_outputs.begin(), current_outputs.end(), [&](const auto &output) {
3160 return output.connected && output.name == connector_name;
3161 });
3162 if (expected != current_outputs.end()) {
3163 virtual_output = expected->name;
3164 break;
3165 }
3166 for (const auto &output : current_outputs) {
3167 if (output.connected && outputs_before.find(output.name) == outputs_before.end()) {
3168 virtual_output = output.name;
3169 break;
3170 }
3171 }
3172 }
3173
3174 if (!safe_output_name(virtual_output)) {
3175 BOOST_LOG(warning) << "[VDISPLAY/KScreen] " << backend_label << " output " << connector_name
3176 << " was not enumerated by KWin.";
3177 return false;
3178 }
3179
3180 // At display-CREATION time we only *enable* the virtual output so the
3181 // compositor starts composing on it and capture can read its framebuffer.
3182 // We deliberately do NOT touch the physical outputs' priorities or
3183 // disable them here: that is a SESSION-level action and must only happen
3184 // once the stream actually starts (see make_exclusive), and only in
3185 // isolated mode. Otherwise creating the display would steal the user's
3186 // monitors before any session is live, blanking the local screens
3187 // prematurely.
3188 std::map<std::string, int> original_outputs;
3189 for (const auto &[output, priority] : enabled_before) {
3190 if (output != virtual_output && safe_output_name(output)) {
3191 original_outputs.emplace(output, priority);
3192 }
3193 }
3194 if (!apply_pre_session_layout(virtual_output, before, enabled_before, mode_width, mode_height, mode_refresh_hz, layout)) {
3195 // KWin enables a hotplugged output by itself, so a layout it did not
3196 // take (refused, or naming a monitor that dropped off the link while
3197 // waking) costs the placement, not the session. Fail only when the
3198 // output really is not enabled.
3199 const auto current = outputs();
3200 const bool enabled = std::ranges::any_of(current, [&](const auto &output) {
3201 return output.name == virtual_output && output.connected && output.enabled;
3202 });
3203 if (!enabled) {
3204 return false;
3205 }
3206 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Hermes' layout for " << virtual_output
3207 << " was not applied; streaming it where KWin placed it.";
3208 }
3209
3210 std::lock_guard<std::mutex> lock(layouts_mutex);
3211 layouts[display_name] = {
3212 .original_outputs = std::move(original_outputs),
3213 .virtual_output = virtual_output,
3214 .physical_output_disabled = false,
3215 .preserve_physical_outputs = layout == virtual_display_layout_e::detached,
3216 };
3217 BOOST_LOG(info) << "[VDISPLAY/KScreen] Enabled " << backend_label << " output " << virtual_output
3218 << (layout == virtual_display_layout_e::detached ?
3219 " without rewriting physical outputs" :
3220 " and restored the pre-session physical layout");
3221 return true;
3222 }
3223
3224 static bool is_active(const std::string &display_name) {
3225 std::lock_guard<std::mutex> lock(layouts_mutex);
3226 return layouts.find(display_name) != layouts.end();
3227 }
3228
3243 static bool apply_mode(const std::string &display_name, int width, int height, int refresh_hz) {
3244 if (!available() || width <= 0 || height <= 0 || refresh_hz <= 0) {
3245 return false;
3246 }
3247
3248 std::string output_name;
3249 {
3250 std::lock_guard<std::mutex> lock(layouts_mutex);
3251 const auto it = layouts.find(display_name);
3252 if (it == layouts.end()) {
3253 return false;
3254 }
3255 output_name = it->second.virtual_output;
3256 }
3257 if (!safe_output_name(output_name)) {
3258 return false;
3259 }
3260
3261 const std::string mode = std::to_string(width) + 'x' + std::to_string(height) + '@' +
3262 std::to_string(refresh_hz);
3263
3264 switch (kscreenModeState(command_output("kscreen-doctor -j"), output_name, width, height, refresh_hz)) {
3265 case kscreen_mode_state_e::current:
3266 BOOST_LOG(debug) << "[VDISPLAY/KScreen] " << output_name << " is already driven at " << mode << '.';
3267 return true;
3268 case kscreen_mode_state_e::not_advertised:
3269 BOOST_LOG(warning) << "[VDISPLAY/KScreen] " << output_name << " does not advertise " << mode
3270 << "; leaving KWin's own choice in place.";
3271 return false;
3272 case kscreen_mode_state_e::unknown_output:
3273 // KWin may not have enumerated the hotplug yet, and a reply we could
3274 // not read is not evidence of anything. Ask for the mode anyway.
3275 break;
3276 case kscreen_mode_state_e::advertised:
3277 break;
3278 }
3279
3280 if (!run_layout_command("kscreen-doctor output." + output_name + ".mode." + mode)) {
3281 return false;
3282 }
3283
3284 switch (kscreenModeState(command_output("kscreen-doctor -j"), output_name, width, height, refresh_hz)) {
3285 case kscreen_mode_state_e::current:
3286 BOOST_LOG(info) << "[VDISPLAY/KScreen] Driving " << output_name << " at " << mode
3287 << " for this session.";
3288 return true;
3289 case kscreen_mode_state_e::unknown_output:
3290 BOOST_LOG(debug) << "[VDISPLAY/KScreen] Applied " << mode << " to " << output_name
3291 << "; KWin's reply was unreadable, so it could not be confirmed.";
3292 return true;
3293 default:
3294 BOOST_LOG(warning) << "[VDISPLAY/KScreen] KWin accepted " << mode << " for " << output_name
3295 << " but is not driving it; the stream will not match the resolution the "
3296 "client asked for.";
3297 return false;
3298 }
3299 }
3300
3301 static bool geometry(const std::string &display_name, int &x, int &y, int &env_width, int &env_height) {
3302 std::string output_name;
3303 {
3304 std::lock_guard<std::mutex> lock(layouts_mutex);
3305 const auto it = layouts.find(display_name);
3306 if (it == layouts.end()) {
3307 return false;
3308 }
3309 output_name = it->second.virtual_output;
3310 }
3311
3312 return kscreenDisplayGeometry(outputs(), output_name, x, y, env_width, env_height);
3313 }
3314
3315 // Called at SESSION START (only when isolated mode is on) to hand the
3316 // desktop over to the virtual output: make it primary and disable the
3317 // physical monitors. This is the moment the local screens are allowed to go
3318 // dark — never before. restore() reverses it when the session ends.
3319 static bool make_exclusive(const std::string &display_name) {
3320 std::lock_guard<std::mutex> lock(layouts_mutex);
3321 const auto it = layouts.find(display_name);
3322 if (it == layouts.end() || it->second.physical_output_disabled) {
3323 return it != layouts.end();
3324 }
3325
3326 // Every lit physical output has to go dark, not just the one that
3327 // happened to be primary: on a multi-monitor desktop the secondary
3328 // screens otherwise stay on and keep showing the local session.
3329 // Read the live layout so monitors that were enabled after the virtual
3330 // display was created are covered as well, and fall back to the
3331 // pre-session snapshot when KScreen cannot be queried. Priorities come
3332 // from the snapshot where known so restore() reinstates the layout the
3333 // user actually had.
3334 std::map<std::string, int> targets;
3335 for (const auto &output : outputs()) {
3336 if (!output.connected || !output.enabled ||
3337 output.name == it->second.virtual_output ||
3338 !safe_output_name(output.name)) {
3339 continue;
3340 }
3341 const auto known = it->second.original_outputs.find(output.name);
3342 targets.emplace(
3343 output.name,
3344 known != it->second.original_outputs.end() ? known->second : output.priority
3345 );
3346 }
3347 if (targets.empty()) {
3348 targets = it->second.original_outputs;
3349 }
3350 if (targets.empty()) {
3351 return true;
3352 }
3353
3354 // Promote the virtual output to primary and disable the physical ones in
3355 // a single atomic kscreen-doctor call so the session never lands on a
3356 // transient no-primary layout.
3357 std::string command = "kscreen-doctor output." + it->second.virtual_output + ".priority.1";
3358 for (const auto &[output, priority] : targets) {
3359 command += " output." + output + ".disable";
3360 }
3361 const auto previous = it->second;
3362 // A rejected/timed-out transaction can still have changed some outputs.
3363 // Publish the complete recovery targets before asking KWin to apply it.
3364 it->second.original_outputs = targets;
3365 it->second.physical_output_disabled = true;
3366 if (!persist_pending_recovery()) {
3367 it->second = previous;
3368 BOOST_LOG(error) << "[VDISPLAY/KScreen] Refusing exclusive mode because monitor recovery state could not be written.";
3369 return false;
3370 }
3371 if (!run_layout_command(command)) {
3372 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Exclusive layout command failed; retaining recovery state in case it was partially applied.";
3373 return false;
3374 }
3375 BOOST_LOG(info) << "[VDISPLAY/KScreen] Exclusive mode disabled " << targets.size()
3376 << " physical output(s) in favour of " << it->second.virtual_output;
3377 return true;
3378 }
3379
3380 static bool restore(const std::string &display_name, bool release_layout = true) {
3381 std::lock_guard<std::mutex> lock(layouts_mutex);
3382 const auto it = layouts.find(display_name);
3383 if (it == layouts.end()) {
3384 return true;
3385 }
3386 auto &layout = it->second;
3387 layout.release_requested |= release_layout;
3388 if (layout.preserve_physical_outputs && !layout.physical_output_disabled) {
3389 if (release_layout) {
3390 layouts.erase(it);
3391 }
3392 return true;
3393 }
3394
3395 layout.restore_pending = true;
3396 if (!restore_outputs(layout.original_outputs)) {
3397 persist_pending_recovery();
3398 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Physical output restoration is not confirmed for "
3399 << display_name << "; retaining its layout for another attempt.";
3400 return false;
3401 }
3402 layout.restore_pending = false;
3403 if (release_layout) {
3404 layouts.erase(it);
3405 }
3406 persist_pending_recovery();
3407 return true;
3408 }
3409
3410 static bool restore_all() {
3411 std::vector<std::string> names;
3412 {
3413 std::lock_guard<std::mutex> lock(layouts_mutex);
3414 for (const auto &[name, layout] : layouts) {
3415 if (layout.physical_output_disabled) {
3416 names.push_back(name);
3417 }
3418 }
3419 }
3420 bool restored = true;
3421 for (const auto &name : names) {
3422 restored = restore(name, false) && restored;
3423 }
3424 return restored;
3425 }
3426
3427 static bool retry_pending_restores() {
3428 std::vector<std::pair<std::string, bool>> pending;
3429 bool retry_startup = false;
3430 {
3431 std::lock_guard<std::mutex> lock(layouts_mutex);
3432 retry_startup = startup_recovery_pending;
3433 for (const auto &[name, layout] : layouts) {
3434 if (layout.restore_pending && layout.release_requested) {
3435 pending.emplace_back(name, layout.release_requested);
3436 }
3437 }
3438 }
3439 if (retry_startup) {
3440 recover_on_startup();
3441 }
3442 bool restored = true;
3443 for (const auto &[name, release_layout] : pending) {
3444 restored = restore(name, release_layout) && restored;
3445 }
3446 std::lock_guard<std::mutex> lock(layouts_mutex);
3447 return restored && !startup_recovery_pending;
3448 }
3449
3450 // ------------------------------------------------------------------
3451 // Input device binding.
3452 //
3453 // KWin binds a touchscreen or a tablet to one output. With nothing
3454 // configured it guesses (Connection::applyScreenToDevice): the built-in
3455 // panel, then an output whose physical size matches the device's, then
3456 // simply the first output. None of those is the streamed output, so a
3457 // client's touches land on the host's own monitor.
3458 //
3459 // The binding System Settings makes is stored per device in kcminputrc,
3460 // under [Libinput][<vendor>][<product>][<name>], as the output's UUID.
3461 // Writing that key ourselves is not an option: KWin keeps output UUIDs to
3462 // itself, and the older OutputName key alone binds nothing, because KWin
3463 // reads OutputUuid after it and an empty one undoes the match (KWin 6.7,
3464 // Device::loadConfiguration). What does work is the property each device
3465 // exposes over D-Bus: setting outputName makes KWin resolve the UUID, bind
3466 // the device and store the binding.
3467 //
3468 // A device can only be bound once it exists, and Hermes creates its touch
3469 // and pen devices per client, after the display is activated. So the
3470 // binding listens for KWin's deviceAdded and binds each Hermes device as
3471 // it appears, for as long as the display lives - a client that resumes
3472 // gets new devices without a new activation. Devices that already exist
3473 // are left alone: they belong to a session already running on its own
3474 // display.
3475 //
3476 // KWin writes the binding to kcminputrc, where it would outlive the
3477 // session, so the value the key held before is kept and put back when the
3478 // display goes away. As on GNOME, a binding left behind by a crash names
3479 // an output that exists only while Hermes streams; with it gone, KWin
3480 // falls back to the guess it would have made anyway.
3481 //
3482 // Concurrent sessions' devices share their names, so new devices follow
3483 // the display activated last. Each device is bound once, on arrival, so a
3484 // running session's devices keep their output when another one starts.
3485 // ------------------------------------------------------------------
3486
3488 static constexpr std::array<const char *, 2> bound_device_names {VIRTUAL_TOUCH_DEVICE_NAME, VIRTUAL_PEN_DEVICE_NAME};
3489
3490 static bool safe_input_device_name(const std::string &name) {
3491 return !name.empty() && name.size() <= 64 && std::all_of(name.begin(), name.end(), [](unsigned char c) {
3492 return std::isalnum(c) || c == ' ' || c == '-' || c == '_';
3493 });
3494 }
3495
3498 static bool uuid_like(const std::string &value) {
3499 return !value.empty() && value.size() <= 38 && std::all_of(value.begin(), value.end(), [](unsigned char c) {
3500 return std::isxdigit(c) || c == '-' || c == '{' || c == '}';
3501 });
3502 }
3503
3504 static std::string input_binding_key_args(const std::string &device_name) {
3505 return "--file kcminputrc --group Libinput --group " + std::to_string(VIRTUAL_INPUT_SETTINGS_VENDOR_ID) +
3506 " --group " + std::to_string(VIRTUAL_INPUT_SETTINGS_PRODUCT_ID) + " --group '" + device_name +
3507 "' --key OutputUuid";
3508 }
3509
3510 static std::string input_binding_read_command(const std::string &device_name) {
3511 if (!safe_input_device_name(device_name)) {
3512 return {};
3513 }
3514 return "kreadconfig6 " + input_binding_key_args(device_name) + " 2>/dev/null";
3515 }
3516
3517 static std::string input_binding_restore_command(const std::string &device_name, const std::string &previous_uuid) {
3518 if (!safe_input_device_name(device_name)) {
3519 return {};
3520 }
3521 const auto prefix = "kwriteconfig6 --notify " + input_binding_key_args(device_name);
3522 if (previous_uuid.empty()) {
3523 return prefix + " --delete 2>/dev/null";
3524 }
3525 if (!uuid_like(previous_uuid)) {
3526 return {};
3527 }
3528 return prefix + " '" + previous_uuid + "' 2>/dev/null";
3529 }
3530
3531 static bool is_hermes_input_device(const std::string &name, uint32_t vendor, uint32_t product) {
3532 return vendor == VIRTUAL_INPUT_SETTINGS_VENDOR_ID && product == VIRTUAL_INPUT_SETTINGS_PRODUCT_ID &&
3533 std::any_of(bound_device_names.begin(), bound_device_names.end(), [&name](const char *bound) {
3534 return name == bound;
3535 });
3536 }
3537
3538 static bool have_config_tools() {
3539 const auto have = [](const char *tool) {
3540 return ::access((std::string {"/usr/bin/"} + tool).c_str(), X_OK) == 0 ||
3541 ::access((std::string {"/bin/"} + tool).c_str(), X_OK) == 0;
3542 };
3543 return have("kreadconfig6") && have("kwriteconfig6");
3544 }
3545
3546#ifdef HERMES_BUILD_SDBUS
3547 static constexpr const char *kwin_service = "org.kde.KWin";
3548 static constexpr const char *input_device_manager_path = "/org/kde/KWin/InputDevice";
3549 static constexpr const char *input_device_interface = "org.kde.KWin.InputDevice";
3550
3551 struct input_binding_t {
3552 sd_bus *bus {nullptr};
3553 sd_bus_slot *slot {nullptr};
3554 std::thread thread;
3555 std::atomic<bool> stop {false};
3557 std::string owner;
3559 std::array<std::string, bound_device_names.size()> previous_uuids;
3561 std::mutex output_mutex;
3562 std::string output;
3563 };
3564
3565 static std::mutex input_binding_mutex;
3566 static std::unique_ptr<input_binding_t> input_binding;
3567
3568 static void bind_input_device(input_binding_t &binding, const std::string &sys_name, bool only_unbound = false) {
3569 // KWin names a device's object after its evdev node.
3570 if (sys_name.empty() || sys_name.size() > 32 || !std::all_of(sys_name.begin(), sys_name.end(), [](unsigned char c) {
3571 return std::isalnum(c);
3572 })) {
3573 return;
3574 }
3575 const std::string path = std::string {input_device_manager_path} + '/' + sys_name;
3576
3577 char *name = nullptr;
3578 uint32_t vendor = 0;
3579 uint32_t product = 0;
3580 sd_bus_error error = SD_BUS_ERROR_NULL;
3581 const bool read =
3582 sd_bus_get_property_string(binding.bus, kwin_service, path.c_str(), input_device_interface, "name", &error, &name) >= 0 &&
3583 sd_bus_get_property_trivial(binding.bus, kwin_service, path.c_str(), input_device_interface, "vendor", &error, 'u', &vendor) >= 0 &&
3584 sd_bus_get_property_trivial(binding.bus, kwin_service, path.c_str(), input_device_interface, "product", &error, 'u', &product) >= 0;
3585 sd_bus_error_free(&error);
3586 const std::string device_name = name ? name : "";
3587 std::free(name);
3588 if (!read || !is_hermes_input_device(device_name, vendor, product)) {
3589 return;
3590 }
3591
3592 if (only_unbound) {
3593 // A device that already names an output belongs to a session that is
3594 // still running; leave it where it is.
3595 char *bound = nullptr;
3596 const bool known = sd_bus_get_property_string(binding.bus, kwin_service, path.c_str(), input_device_interface, "outputName", &error, &bound) >= 0;
3597 const bool has_output = bound && *bound;
3598 std::free(bound);
3599 sd_bus_error_free(&error);
3600 if (!known || has_output) {
3601 return;
3602 }
3603 }
3604
3605 std::string output;
3606 {
3607 std::lock_guard<std::mutex> lock(binding.output_mutex);
3608 output = binding.output;
3609 }
3610 const int set = sd_bus_set_property(
3611 binding.bus,
3612 kwin_service,
3613 path.c_str(),
3614 input_device_interface,
3615 "outputName",
3616 &error,
3617 "s",
3618 output.c_str()
3619 );
3620 if (set < 0) {
3621 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Could not bind " << device_name << " (" << sys_name << ") to "
3622 << output << ": " << (error.message ? error.message : std::strerror(-set))
3623 << ". Its input will land where KWin guesses.";
3624 } else {
3625 BOOST_LOG(info) << "[VDISPLAY/KScreen] Bound " << device_name << " (" << sys_name << ") to " << output << '.';
3626 }
3627 sd_bus_error_free(&error);
3628 }
3629
3637 static void bind_existing_devices(input_binding_t &binding) {
3638 sd_bus_error error = SD_BUS_ERROR_NULL;
3639 sd_bus_message *reply = nullptr;
3640 if (sd_bus_get_property(binding.bus, kwin_service, input_device_manager_path, "org.kde.KWin.InputDeviceManager", "devicesSysNames", &error, &reply, "as") < 0) {
3641 sd_bus_error_free(&error);
3642 return;
3643 }
3644 std::vector<std::string> sys_names;
3645 if (sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s") >= 0) {
3646 const char *sys_name = nullptr;
3647 while (sd_bus_message_read_basic(reply, SD_BUS_TYPE_STRING, &sys_name) > 0 && sys_name) {
3648 sys_names.emplace_back(sys_name);
3649 }
3650 sd_bus_message_exit_container(reply);
3651 }
3652 sd_bus_message_unref(reply);
3653 sd_bus_error_free(&error);
3654
3655 for (const auto &sys_name : sys_names) {
3656 bind_input_device(binding, sys_name, true);
3657 }
3658 }
3659
3660 static int on_input_device_added(sd_bus_message *message, void *userdata, sd_bus_error * /* error */) {
3661 const char *sys_name = nullptr;
3662 if (sd_bus_message_read(message, "s", &sys_name) >= 0 && sys_name) {
3663 bind_input_device(*static_cast<input_binding_t *>(userdata), sys_name);
3664 }
3665 return 0;
3666 }
3667
3669 static void restore_input_bindings(const input_binding_t &binding) {
3670 for (std::size_t i = 0; i < bound_device_names.size(); ++i) {
3671 const auto command = input_binding_restore_command(bound_device_names[i], binding.previous_uuids[i]);
3672 if (command.empty() || !boundedCommandOutput(command, command_timeout, nullptr)) {
3673 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Could not restore the output " << bound_device_names[i]
3674 << " was bound to before the session.";
3675 }
3676 }
3677 }
3678
3686 static void map_input_devices_to(const std::string &owner, const std::string &output);
3687
3688 static void map_input_devices(const std::string &display_name) {
3689 std::string output;
3690 {
3691 std::lock_guard<std::mutex> lock(layouts_mutex);
3692 const auto it = layouts.find(display_name);
3693 if (it == layouts.end()) {
3694 return;
3695 }
3696 output = it->second.virtual_output;
3697 }
3698 map_input_devices_to(display_name, output);
3699 }
3700
3706 static void map_input_devices_to(const std::string &owner, const std::string &output) {
3707 if (!safe_output_name(output)) {
3708 return;
3709 }
3710
3711 std::lock_guard<std::mutex> lock(input_binding_mutex);
3712 if (input_binding) {
3713 // One subscription serves every display; a later one takes over the
3714 // devices created from now on.
3715 {
3716 std::lock_guard<std::mutex> output_lock(input_binding->output_mutex);
3717 input_binding->output = output;
3718 }
3719 input_binding->owner = owner;
3720 BOOST_LOG(info) << "[VDISPLAY/KScreen] Touch and pen input from new clients now goes to " << output << '.';
3721 return;
3722 }
3723
3724 if (!have_config_tools()) {
3725 BOOST_LOG(warning) << "[VDISPLAY/KScreen] kreadconfig6 or kwriteconfig6 is missing, so the touch binding "
3726 "KWin stores could not be undone after the session. Touch input will land where "
3727 "KWin guesses.";
3728 return;
3729 }
3730
3731 auto started = std::make_unique<input_binding_t>();
3732 for (std::size_t i = 0; i < bound_device_names.size(); ++i) {
3733 auto previous = command_output(input_binding_read_command(bound_device_names[i]).c_str());
3734 while (!previous.empty() && std::isspace(static_cast<unsigned char>(previous.back()))) {
3735 previous.pop_back();
3736 }
3737 // A value restore could not write back is left alone rather than
3738 // replaced for good.
3739 if (!previous.empty() && !uuid_like(previous)) {
3740 BOOST_LOG(warning) << "[VDISPLAY/KScreen] " << bound_device_names[i]
3741 << " already has an output binding Hermes could not put back after the session, "
3742 "so touch and pen input are left where KWin places them.";
3743 return;
3744 }
3745 started->previous_uuids[i] = std::move(previous);
3746 }
3747
3748 const int opened = platf::open_user_bus(&started->bus);
3749 if (opened < 0 || !started->bus) {
3750 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Could not connect to the user bus to bind touch input: "
3751 << (opened < 0 ? std::strerror(-opened) : "no connection was returned")
3752 << ". Touch input will land where KWin guesses.";
3753 return;
3754 }
3755 // The input pump is joined during teardown. Bound synchronous KWin
3756 // property calls so a disappearing compositor cannot hold that join
3757 // behind sd-bus's default 25-second timeout for each property.
3758 sd_bus_set_method_call_timeout(started->bus, 2000000);
3759 const int matched = sd_bus_match_signal(
3760 started->bus,
3761 &started->slot,
3762 kwin_service,
3763 input_device_manager_path,
3764 "org.kde.KWin.InputDeviceManager",
3765 "deviceAdded",
3766 on_input_device_added,
3767 started.get()
3768 );
3769 if (matched < 0) {
3770 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Could not subscribe to KWin's input devices: "
3771 << std::strerror(-matched) << ". Touch input will land where KWin guesses.";
3772 sd_bus_unref(started->bus);
3773 return;
3774 }
3775 started->owner = owner;
3776 started->output = output;
3777
3778 // sd-bus permits an object to move between threads, but only one thread
3779 // may operate on it at a time. Enumerate synchronously before the pump
3780 // thread starts; doing this afterwards let sd_bus_process() consume the
3781 // Properties.Get reply and left this call waiting for the default 25 s
3782 // method timeout on every connection. The signal match is already
3783 // installed, so devices added while enumerating remain queued for the
3784 // thread and are not missed.
3785 bind_existing_devices(*started);
3786
3787 input_binding_t *raw = started.get();
3788 started->thread = std::thread([raw]() {
3789 while (!raw->stop.load(std::memory_order_relaxed)) {
3790 const int processed = sd_bus_process(raw->bus, nullptr);
3791 if (processed < 0) {
3792 break;
3793 }
3794 if (processed > 0) {
3795 continue; // more may be queued
3796 }
3797 // A bounded wait rather than an indefinite one, so stopping does not
3798 // need a second wakeup channel.
3799 if (sd_bus_wait(raw->bus, 250000 /* us */) < 0) {
3800 break;
3801 }
3802 }
3803 });
3804 input_binding = std::move(started);
3805 BOOST_LOG(info) << "[VDISPLAY/KScreen] Touch and pen input from this session will be bound to " << output << '.';
3806 }
3807
3813 static void unmap_input_devices(const std::string &display_name) {
3814 std::unique_ptr<input_binding_t> stopping;
3815 {
3816 std::lock_guard<std::mutex> lock(input_binding_mutex);
3817 if (!input_binding || input_binding->owner != display_name) {
3818 return;
3819 }
3820 std::string successor;
3821 std::string successor_output;
3822 {
3823 std::lock_guard<std::mutex> layouts_lock(layouts_mutex);
3824 for (const auto &[name, layout] : layouts) {
3825 if (name != display_name && !layout.release_requested && safe_output_name(layout.virtual_output)) {
3826 successor = name;
3827 successor_output = layout.virtual_output;
3828 break;
3829 }
3830 }
3831 }
3832 if (!successor.empty()) {
3833 {
3834 std::lock_guard<std::mutex> output_lock(input_binding->output_mutex);
3835 input_binding->output = successor_output;
3836 }
3837 input_binding->owner = successor;
3838 BOOST_LOG(info) << "[VDISPLAY/KScreen] Touch and pen input from new clients now goes to "
3839 << successor_output << '.';
3840 return;
3841 }
3842 stopping = std::move(input_binding);
3843 }
3844
3845 stopping->stop.store(true, std::memory_order_relaxed);
3846 if (stopping->thread.joinable()) {
3847 stopping->thread.join();
3848 }
3849 if (stopping->slot) {
3850 sd_bus_slot_unref(stopping->slot);
3851 }
3852 if (stopping->bus) {
3853 sd_bus_unref(stopping->bus);
3854 }
3855 restore_input_bindings(*stopping);
3856 BOOST_LOG(info) << "[VDISPLAY/KScreen] Released the touch and pen input binding.";
3857 }
3858#else
3859 // Without sd-bus there is no way to reach KWin's devices, and so no
3860 // binding to undo either.
3861 static void map_input_devices(const std::string &display_name) {
3862 if (is_active(display_name)) {
3863 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Built without sd-bus, so touch and pen input cannot be bound to "
3864 "the streamed output; KWin will guess where it lands.";
3865 }
3866 }
3867
3868 static void unmap_input_devices(const std::string & /* display_name */) {}
3869
3870 static void map_input_devices_to(const std::string & /* owner */, const std::string & /* output */) {
3871 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Built without sd-bus, so touch and pen input cannot be bound to "
3872 "the streamed output; KWin will guess where it lands.";
3873 }
3874#endif
3875
3876#ifdef HERMES_BUILD_SDBUS
3889 std::mutex placements_mutex;
3890 std::map<std::string, std::string> placements;
3891
3892 static bool call_kwin_scripting(sd_bus *bus, const char *path, const char *interface, const char *method, sd_bus_message **reply, const char *types, ...) {
3893 sd_bus_error error = SD_BUS_ERROR_NULL;
3894 va_list arguments;
3895 va_start(arguments, types);
3896 sd_bus_message *message = nullptr;
3897 int status = sd_bus_message_new_method_call(bus, &message, kwin_service, path, interface, method);
3898 if (status >= 0 && types) {
3899 status = sd_bus_message_appendv(message, types, arguments);
3900 }
3901 va_end(arguments);
3902 if (status >= 0) {
3903 status = sd_bus_call(bus, message, 2000000, &error, reply);
3904 }
3905 sd_bus_message_unref(message);
3906 if (status < 0) {
3907 BOOST_LOG(warning) << "[VDISPLAY/KScreen] KWin scripting " << method << " failed: "
3908 << (error.message ? error.message : std::strerror(-status));
3909 }
3910 sd_bus_error_free(&error);
3911 return status >= 0;
3912 }
3913
3914 static void place_windows(const std::string &display_name, const std::vector<std::string> &classes, const std::vector<std::uint32_t> &gamescope_pids) {
3915 std::string output;
3916 {
3917 std::lock_guard<std::mutex> lock(layouts_mutex);
3918 const auto it = layouts.find(display_name);
3919 if (it == layouts.end()) {
3920 return;
3921 }
3922 output = it->second.virtual_output;
3923 }
3924 if (!safe_output_name(output) || classes.empty()) {
3925 return;
3926 }
3927 const auto contents = platf::window_placement::kwin_script(output, classes, gamescope_pids);
3928 if (contents.empty()) {
3929 return;
3930 }
3931
3932 const auto plugin = "hermes-place-" + output;
3933 const auto directory = std::filesystem::path {"/run/user"} / std::to_string(::getuid()) / "hermes";
3934 const auto script = directory / (plugin + ".js");
3935 std::error_code ec;
3936 std::filesystem::create_directories(directory, ec);
3937 {
3938 std::ofstream file {script, std::ios::trunc};
3939 file << contents;
3940 if (!file) {
3941 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Could not write " << script.string() << "; windows stay where KWin opens them.";
3942 return;
3943 }
3944 }
3945
3946 sd_bus *bus = nullptr;
3947 if (platf::open_user_bus(&bus) < 0 || !bus) {
3948 BOOST_LOG(warning) << "[VDISPLAY/KScreen] Could not reach KWin to place windows on " << output << '.';
3949 return;
3950 }
3951 // A script of the same name from an earlier session would make loading fail.
3952 call_kwin_scripting(bus, "/Scripting", "org.kde.kwin.Scripting", "unloadScript", nullptr, "s", plugin.c_str());
3953 sd_bus_message *reply = nullptr;
3954 int32_t id = -1;
3955 if (call_kwin_scripting(bus, "/Scripting", "org.kde.kwin.Scripting", "loadScript", &reply, "ss", script.c_str(), plugin.c_str())) {
3956 sd_bus_message_read(reply, "i", &id);
3957 sd_bus_message_unref(reply);
3958 }
3959 bool running = false;
3960 if (id >= 0) {
3961 const auto path = "/Scripting/Script" + std::to_string(id);
3962 // KWin 6 names it /Scripting/Script<id>; older ones /<id>.
3963 running = call_kwin_scripting(bus, path.c_str(), "org.kde.kwin.Script", "run", nullptr, nullptr) ||
3964 call_kwin_scripting(bus, ("/" + std::to_string(id)).c_str(), "org.kde.kwin.Script", "run", nullptr, nullptr);
3965 }
3966 sd_bus_unref(bus);
3967 if (!running) {
3968 BOOST_LOG(warning) << "[VDISPLAY/KScreen] KWin did not run the window placement script; windows stay where KWin opens them.";
3969 return;
3970 }
3971 std::lock_guard<std::mutex> lock(placements_mutex);
3972 placements[display_name] = plugin;
3973 BOOST_LOG(info) << "[VDISPLAY/KScreen] Application windows go to " << output << " for this session.";
3974 }
3975
3976 static void unplace_windows(const std::string &display_name) {
3977 std::string plugin;
3978 {
3979 std::lock_guard<std::mutex> lock(placements_mutex);
3980 const auto it = placements.find(display_name);
3981 if (it == placements.end()) {
3982 return;
3983 }
3984 plugin = std::move(it->second);
3985 placements.erase(it);
3986 }
3987 sd_bus *bus = nullptr;
3988 if (platf::open_user_bus(&bus) >= 0 && bus) {
3989 call_kwin_scripting(bus, "/Scripting", "org.kde.kwin.Scripting", "unloadScript", nullptr, "s", plugin.c_str());
3990 sd_bus_unref(bus);
3991 }
3992 std::error_code ec;
3993 std::filesystem::remove(std::filesystem::path {"/run/user"} / std::to_string(::getuid()) / "hermes" / (plugin + ".js"), ec);
3994 }
3995#else
3996 static void place_windows(const std::string &, const std::vector<std::string> &, const std::vector<std::uint32_t> &) {}
3997 static void unplace_windows(const std::string &) {}
3998#endif
3999
4001 static bool any_layout_active() {
4002 std::lock_guard<std::mutex> lock(layouts_mutex);
4003 return !layouts.empty();
4004 }
4005 } // namespace kscreen
4006
4007 // GNOME / Mutter output management. Mutter does not speak kscreen-doctor or
4008 // the wlroots output-management protocol; it exposes
4009 // org.gnome.Mutter.DisplayConfig over D-Bus. We talk to it via `gdbus` (always
4010 // present on GNOME) to avoid a libdbus build dependency.
4011 //
4012 // This backend is intentionally conservative: Mutter typically adopts the
4013 // HERMES-1 connector after Hermes connects it for a stream, so the critical
4014 // step is to *verify* that the virtual output is present and active in
4015 // Mutter's current state rather than to push a full ApplyMonitorsConfig
4016 // (which is all-or-nothing and risky to build blind).
4017 namespace mutter {
4018 static bool available() {
4019 if (sessionCompositor() != compositor_e::mutter) {
4020 return false;
4021 }
4022 return ::access("/usr/bin/gdbus", X_OK) == 0 || ::access("/bin/gdbus", X_OK) == 0;
4023 }
4024
4025 static std::string command_output(const char *command) {
4026 std::array<char, 8192> buffer {};
4027 std::string output;
4028 FILE *pipe = ::popen(command, "r");
4029 if (!pipe) {
4030 return {};
4031 }
4032 while (::fgets(buffer.data(), static_cast<int>(buffer.size()), pipe)) {
4033 output += buffer.data();
4034 }
4035 if (::pclose(pipe) != 0) {
4036 return {};
4037 }
4038 return output;
4039 }
4040
4041 // ------------------------------------------------------------------
4042 // ApplyMonitorsConfig
4043 //
4044 // A boot-enabled virtual connector leaves Mutter extending the desktop
4045 // onto an output nobody is streaming to. KWin recovers through
4046 // kscreen-doctor; Mutter only reconfigures through ApplyMonitorsConfig,
4047 // whose reply-vs-request shapes differ:
4048 //
4049 // GetCurrentState -> a(iiduba(ssss)a{sv}) logical monitors
4050 // ApplyMonitorsConfig -> a(iiduba(ssa{sv})) logical monitors
4051 //
4052 // so a logical monitor loses its trailing property dict, and each monitor
4053 // collapses from (connector, vendor, product, serial) to
4054 // (connector, mode_id, properties). The mode id has to be recovered from
4055 // the monitor's own mode list - the one carrying 'is-current': <true>.
4056 //
4057 // ApplyMonitorsConfig is all-or-nothing, so every config is submitted to
4058 // Mutter's own VERIFY method first and only applied when that succeeds.
4059 // ------------------------------------------------------------------
4060
4061 enum class apply_method : unsigned {
4062 verify = 0,
4063 temporary = 1,
4064 persistent = 2,
4065 };
4066
4068 std::string x;
4069 std::string y;
4070 std::string scale;
4071 std::string transform;
4072 std::string primary;
4073 std::vector<std::string> connectors;
4074 };
4075
4076 struct mode_t {
4077 std::string id;
4078 int width {0};
4079 int height {0};
4080 double refresh {0.0};
4081 bool current {false};
4082 };
4083
4084 struct monitor_t {
4085 std::string connector;
4086 // The rest of the monitor spec. GNOME identifies a monitor by these three
4087 // when binding an input device to it, not by the connector.
4088 std::string vendor;
4089 std::string product;
4090 std::string serial;
4091 std::vector<mode_t> modes;
4092 };
4093
4095 enum class layout_mode_e : unsigned {
4098 };
4099
4100 struct state_t {
4101 std::string serial;
4102 std::map<std::string, std::string> current_mode;
4103 std::vector<monitor_t> monitors;
4104 std::vector<logical_monitor_t> logical_monitors;
4105 // Absence of "layout-mode" means it cannot be changed and that logical is
4106 // in use, so that is the default rather than a guess.
4108 bool global_scale_required {false};
4109
4110 const monitor_t *find_monitor(const std::string &connector) const {
4111 for (const auto &monitor : monitors) {
4112 if (monitor.connector == connector) {
4113 return &monitor;
4114 }
4115 }
4116 return nullptr;
4117 }
4118
4119 const logical_monitor_t *find_logical_monitor(const std::string &connector) const {
4120 for (const auto &lm : logical_monitors) {
4121 if (std::find(lm.connectors.begin(), lm.connectors.end(), connector) != lm.connectors.end()) {
4122 return &lm;
4123 }
4124 }
4125 return nullptr;
4126 }
4127
4128 static double scale_of(const logical_monitor_t &lm) {
4129 const double scale = std::atof(lm.scale.c_str());
4130 return scale > 0.0 ? scale : 1.0;
4131 }
4132
4142 bool logical_size(const logical_monitor_t &lm, int &width, int &height) const {
4143 if (lm.connectors.empty()) {
4144 return false;
4145 }
4146 const auto current = current_mode.find(lm.connectors.front());
4147 const auto *monitor = find_monitor(lm.connectors.front());
4148 if (current == current_mode.end() || !monitor) {
4149 return false;
4150 }
4151 const mode_t *mode = nullptr;
4152 for (const auto &candidate : monitor->modes) {
4153 if (candidate.id == current->second) {
4154 mode = &candidate;
4155 break;
4156 }
4157 }
4158 if (!mode || mode->width <= 0 || mode->height <= 0) {
4159 return false;
4160 }
4161
4162 double w = mode->width;
4163 double h = mode->height;
4164 // Transforms 1, 3, 5 and 7 are the 90 and 270 degree rotations.
4165 const int transform = std::atoi(lm.transform.c_str());
4166 if (transform == 1 || transform == 3 || transform == 5 || transform == 7) {
4167 std::swap(w, h);
4168 }
4169 if (layout_mode == layout_mode_e::logical) {
4170 const double scale = scale_of(lm);
4171 w /= scale;
4172 h /= scale;
4173 }
4174
4175 width = static_cast<int>(std::lround(w));
4176 height = static_cast<int>(std::lround(h));
4177 return width > 0 && height > 0;
4178 }
4179 };
4180
4181 static const char *get_current_state_command =
4182 "gdbus call --session "
4183 "--dest org.gnome.Mutter.DisplayConfig "
4184 "--object-path /org/gnome/Mutter/DisplayConfig "
4185 "--method org.gnome.Mutter.DisplayConfig.GetCurrentState 2>/dev/null";
4186
4187 // Connector names and mode ids are interpolated into a shell command, so
4188 // restrict them to what Mutter actually emits ("DP-2", "4096x2160@100.000+vrr").
4189 static bool safe_variant_token(const std::string &value) {
4190 return !value.empty() && value.size() <= 128 && std::all_of(value.begin(), value.end(), [](unsigned char c) {
4191 return std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '@' || c == '+' || c == ':';
4192 });
4193 }
4194
4195 static std::string trim_variant(const std::string &value) {
4196 const size_t first = value.find_first_not_of(" \t\n\r");
4197 if (first == std::string::npos) {
4198 return {};
4199 }
4200 const size_t last = value.find_last_not_of(" \t\n\r");
4201 return value.substr(first, last - first + 1);
4202 }
4203
4204 // Split the body of a GVariant container on its top-level commas.
4205 static std::vector<std::string> split_variant(const std::string &body) {
4206 std::vector<std::string> parts;
4207 int depth = 0;
4208 bool in_string = false;
4209 size_t start = 0;
4210
4211 for (size_t i = 0; i < body.size(); ++i) {
4212 const char c = body[i];
4213 if (in_string) {
4214 if (c == '\\') {
4215 ++i;
4216 } else if (c == '\'') {
4217 in_string = false;
4218 }
4219 continue;
4220 }
4221 switch (c) {
4222 case '\'':
4223 in_string = true;
4224 break;
4225 case '(':
4226 case '[':
4227 case '{':
4228 case '<':
4229 ++depth;
4230 break;
4231 case ')':
4232 case ']':
4233 case '}':
4234 case '>':
4235 --depth;
4236 break;
4237 case ',':
4238 if (depth == 0) {
4239 parts.emplace_back(trim_variant(body.substr(start, i - start)));
4240 start = i + 1;
4241 }
4242 break;
4243 default:
4244 break;
4245 }
4246 }
4247 parts.emplace_back(trim_variant(body.substr(start)));
4248 return parts;
4249 }
4250
4251 static bool strip_variant(std::string &value, char open, char close) {
4252 if (value.size() < 2 || value.front() != open || value.back() != close) {
4253 return false;
4254 }
4255 value = trim_variant(value.substr(1, value.size() - 2));
4256 return true;
4257 }
4258
4259 static std::string unquote_variant(const std::string &value) {
4260 if (value.size() >= 2 && value.front() == '\'' && value.back() == '\'') {
4261 return value.substr(1, value.size() - 2);
4262 }
4263 return value;
4264 }
4265
4266 // GVariant prints a type annotation ("uint32 0") only where the type cannot
4267 // be inferred from context; keep the literal and drop any prefix.
4268 static std::string numeric_variant(const std::string &value) {
4269 const size_t pos = value.find_last_of(' ');
4270 return pos == std::string::npos ? value : value.substr(pos + 1);
4271 }
4272
4273 // A scale must stay a double: emitting "1" for 1.0 would type the field as
4274 // an integer and the whole config would be rejected.
4275 static std::string double_variant(const std::string &value) {
4276 std::string literal = numeric_variant(value);
4277 if (literal.find('.') == std::string::npos && literal.find('e') == std::string::npos &&
4278 literal.find('E') == std::string::npos) {
4279 literal += ".0";
4280 }
4281 return literal;
4282 }
4283
4284 static bool parse_current_state(const std::string &reply, state_t &out) {
4285 std::string body = trim_variant(reply);
4286 if (!strip_variant(body, '(', ')')) {
4287 return false;
4288 }
4289 const auto top = split_variant(body);
4290 if (top.size() != 4) {
4291 return false;
4292 }
4293
4294 out.serial = numeric_variant(top[0]);
4295 if (out.serial.empty()) {
4296 return false;
4297 }
4298
4299 std::string monitors = top[1];
4300 if (!strip_variant(monitors, '[', ']')) {
4301 return false;
4302 }
4303 for (const auto &entry : split_variant(monitors)) {
4304 std::string monitor = entry;
4305 if (!strip_variant(monitor, '(', ')')) {
4306 continue;
4307 }
4308 const auto fields = split_variant(monitor);
4309 if (fields.size() < 2) {
4310 continue;
4311 }
4312 std::string spec = fields[0];
4313 if (!strip_variant(spec, '(', ')')) {
4314 continue;
4315 }
4316 const auto spec_fields = split_variant(spec);
4317 if (spec_fields.empty()) {
4318 continue;
4319 }
4320 const std::string connector = unquote_variant(spec_fields[0]);
4321 std::string modes = fields[1];
4322 if (connector.empty() || !strip_variant(modes, '[', ']')) {
4323 continue;
4324 }
4325 monitor_t parsed_monitor;
4326 parsed_monitor.connector = connector;
4327 if (spec_fields.size() >= 4) {
4328 parsed_monitor.vendor = unquote_variant(spec_fields[1]);
4329 parsed_monitor.product = unquote_variant(spec_fields[2]);
4330 parsed_monitor.serial = unquote_variant(spec_fields[3]);
4331 }
4332 for (const auto &mode_entry : split_variant(modes)) {
4333 std::string mode = mode_entry;
4334 if (!strip_variant(mode, '(', ')')) {
4335 continue;
4336 }
4337 const auto mode_fields = split_variant(mode);
4338 if (mode_fields.size() < 7) {
4339 continue;
4340 }
4341
4342 mode_t parsed_mode;
4343 parsed_mode.id = unquote_variant(mode_fields[0]);
4344 if (parsed_mode.id.empty()) {
4345 continue;
4346 }
4347 parsed_mode.width = std::atoi(numeric_variant(mode_fields[1]).c_str());
4348 parsed_mode.height = std::atoi(numeric_variant(mode_fields[2]).c_str());
4349 parsed_mode.refresh = std::atof(numeric_variant(mode_fields[3]).c_str());
4350 parsed_mode.current = mode_fields.back().find("'is-current': <true>") != std::string::npos;
4351 if (parsed_mode.current) {
4352 out.current_mode[connector] = parsed_mode.id;
4353 }
4354 parsed_monitor.modes.emplace_back(std::move(parsed_mode));
4355 }
4356 out.monitors.emplace_back(std::move(parsed_monitor));
4357 }
4358
4359 std::string logical = top[2];
4360 if (!strip_variant(logical, '[', ']')) {
4361 return false;
4362 }
4363 for (const auto &entry : split_variant(logical)) {
4364 std::string lm = entry;
4365 if (!strip_variant(lm, '(', ')')) {
4366 continue;
4367 }
4368 const auto fields = split_variant(lm);
4369 if (fields.size() < 6) {
4370 continue;
4371 }
4372
4373 logical_monitor_t parsed;
4374 parsed.x = numeric_variant(fields[0]);
4375 parsed.y = numeric_variant(fields[1]);
4376 parsed.scale = double_variant(fields[2]);
4377 parsed.transform = numeric_variant(fields[3]);
4378 parsed.primary = numeric_variant(fields[4]);
4379
4380 std::string specs = fields[5];
4381 if (!strip_variant(specs, '[', ']')) {
4382 continue;
4383 }
4384 for (const auto &spec_entry : split_variant(specs)) {
4385 std::string spec = spec_entry;
4386 if (!strip_variant(spec, '(', ')')) {
4387 continue;
4388 }
4389 const auto spec_fields = split_variant(spec);
4390 if (spec_fields.empty()) {
4391 continue;
4392 }
4393 const std::string connector = unquote_variant(spec_fields[0]);
4394 if (!connector.empty()) {
4395 parsed.connectors.emplace_back(connector);
4396 }
4397 }
4398
4399 if (!parsed.connectors.empty()) {
4400 out.logical_monitors.emplace_back(std::move(parsed));
4401 }
4402 }
4403
4404 // The properties dict carries the two flags that decide how a layout is
4405 // measured and what scale a new logical monitor may take. Both are
4406 // optional; the defaults in state_t are what their absence means.
4407 std::string properties = top[3];
4408 if (strip_variant(properties, '{', '}')) {
4409 for (const auto &entry : split_variant(properties)) {
4410 const size_t colon = entry.find(':');
4411 if (colon == std::string::npos) {
4412 continue;
4413 }
4414 const std::string key = unquote_variant(trim_variant(entry.substr(0, colon)));
4415 std::string value = trim_variant(entry.substr(colon + 1));
4416 strip_variant(value, '<', '>');
4417 if (key == "layout-mode") {
4418 if (std::atoi(numeric_variant(value).c_str()) == static_cast<int>(layout_mode_e::physical)) {
4419 out.layout_mode = layout_mode_e::physical;
4420 }
4421 } else if (key == "global-scale-required") {
4422 out.global_scale_required = numeric_variant(value) == "true";
4423 }
4424 }
4425 }
4426
4427 return !out.logical_monitors.empty();
4428 }
4429
4430 // Render the a(iiduba(ssa{sv})) argument ApplyMonitorsConfig expects.
4431 static bool build_apply_argument(const state_t &state,
4432 const std::vector<logical_monitor_t> &layout,
4433 std::string &argument,
4434 const std::map<std::string, std::string> &mode_override = {}) {
4435 argument = "[";
4436 for (size_t i = 0; i < layout.size(); ++i) {
4437 const auto &lm = layout[i];
4438 if (lm.primary != "true" && lm.primary != "false") {
4439 return false;
4440 }
4441 argument += (i ? ", (" : "(");
4442 argument += lm.x + ", " + lm.y + ", " + lm.scale + ", uint32 " + lm.transform + ", " + lm.primary + ", [";
4443 for (size_t j = 0; j < lm.connectors.size(); ++j) {
4444 const auto &connector = lm.connectors[j];
4445 std::string mode_id;
4446 if (const auto override_it = mode_override.find(connector); override_it != mode_override.end()) {
4447 mode_id = override_it->second;
4448 } else if (const auto current = state.current_mode.find(connector); current != state.current_mode.end()) {
4449 mode_id = current->second;
4450 } else {
4451 BOOST_LOG(warning) << "[VDISPLAY/Mutter] No mode known for " << connector << "; leaving the layout alone.";
4452 return false;
4453 }
4454 if (!safe_variant_token(connector) || !safe_variant_token(mode_id)) {
4455 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Refusing to build a config from an unexpected connector or mode id.";
4456 return false;
4457 }
4458 argument += (j ? ", ('" : "('");
4459 argument += connector + "', '" + mode_id + "', @a{sv} {})";
4460 }
4461 argument += "])";
4462 }
4463 argument += "]";
4464 return true;
4465 }
4466
4467 static bool run_apply(const state_t &state, const std::string &argument, apply_method method) {
4468 const std::string command =
4469 "gdbus call --session "
4470 "--dest org.gnome.Mutter.DisplayConfig "
4471 "--object-path /org/gnome/Mutter/DisplayConfig "
4472 "--method org.gnome.Mutter.DisplayConfig.ApplyMonitorsConfig " +
4473 state.serial + " " + std::to_string(static_cast<unsigned>(method)) + " \"" + argument + "\" \"@a{sv} {}\" 2>&1";
4474
4475 std::array<char, 4096> buffer {};
4476 std::string output;
4477 FILE *pipe = ::popen(command.c_str(), "r");
4478 if (!pipe) {
4479 return false;
4480 }
4481 while (::fgets(buffer.data(), static_cast<int>(buffer.size()), pipe)) {
4482 output += buffer.data();
4483 }
4484 if (::pclose(pipe) != 0) {
4485 BOOST_LOG(warning) << "[VDISPLAY/Mutter] ApplyMonitorsConfig ("
4486 << (method == apply_method::verify ? "verify" : "apply")
4487 << ") failed: " << trim_variant(output);
4488 return false;
4489 }
4490 return true;
4491 }
4492
4499
4506 static layout_repair build_layout_without(const std::string &reply,
4507 const std::string &virtual_connector,
4508 state_t &state,
4509 std::string &argument) {
4510 state = {};
4511 argument.clear();
4512 if (reply.empty() || virtual_connector.empty() || !parse_current_state(reply, state)) {
4513 return layout_repair::unavailable;
4514 }
4515
4516 std::vector<logical_monitor_t> kept;
4517 bool dropped_primary = false;
4518 bool dropped = false;
4519 for (auto lm : state.logical_monitors) {
4520 const auto before = lm.connectors.size();
4521 lm.connectors.erase(
4522 std::remove(lm.connectors.begin(), lm.connectors.end(), virtual_connector),
4523 lm.connectors.end()
4524 );
4525 if (lm.connectors.size() == before) {
4526 kept.emplace_back(std::move(lm));
4527 continue;
4528 }
4529 dropped = true;
4530 if (lm.connectors.empty()) {
4531 dropped_primary = dropped_primary || lm.primary == "true";
4532 } else {
4533 kept.emplace_back(std::move(lm));
4534 }
4535 }
4536
4537 if (!dropped) {
4538 return layout_repair::not_needed;
4539 }
4540 if (kept.empty()) {
4541 return layout_repair::unsafe;
4542 }
4543 if (dropped_primary) {
4544 kept.front().primary = "true";
4545 }
4546 return build_apply_argument(state, kept, argument) ? layout_repair::ready : layout_repair::unsafe;
4547 }
4548
4556 static void recover_after_unowned_virtual_disconnect(const std::string &virtual_connector) {
4557 if (!available() || virtual_connector.empty()) {
4558 return;
4559 }
4560
4561 for (int attempt = 0; attempt < 20; ++attempt) {
4562 state_t state;
4563 std::string argument;
4564 switch (build_layout_without(command_output(get_current_state_command), virtual_connector, state, argument)) {
4565 case layout_repair::unavailable:
4566 std::this_thread::sleep_for(std::chrono::milliseconds {50});
4567 continue;
4568 case layout_repair::not_needed:
4569 return; // Mutter already dropped the disconnected output.
4570 case layout_repair::unsafe:
4571 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Cannot safely drop virtual output " << virtual_connector
4572 << " from Mutter's layout; leaving it to the compositor.";
4573 return;
4574 case layout_repair::ready:
4575 break;
4576 }
4577
4578 // ApplyMonitorsConfig is all-or-nothing, so let Mutter validate the
4579 // config before it can black out the physical outputs.
4580 if (!run_apply(state, argument, apply_method::verify)) {
4581 return;
4582 }
4583
4584 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Dropping boot-enabled virtual output " << virtual_connector
4585 << " from Mutter's layout.";
4586 // Temporary, like every other layout change Hermes makes: the user's
4587 // saved layout in ~/.config/monitors.xml stays theirs.
4588 run_apply(state, argument, apply_method::temporary);
4589 return;
4590 }
4591 }
4592
4599
4609 static mode_push build_layout_with_mode(const std::string &reply,
4610 const std::string &connector,
4611 uint32_t width,
4612 uint32_t height,
4613 uint32_t refresh_mhz,
4614 state_t &state,
4615 std::string &argument) {
4616 state = {};
4617 argument.clear();
4618 if (reply.empty() || connector.empty() || !width || !height || !parse_current_state(reply, state)) {
4619 return mode_push::unavailable;
4620 }
4621
4622 const monitor_t *monitor = state.find_monitor(connector);
4623 if (!monitor) {
4624 return mode_push::unavailable;
4625 }
4626
4627 // Hermes carries refresh rates in mHz, matching wlr-output-management;
4628 // Mutter reports them in Hz. Compare in Hz.
4629 const auto refresh_delta = [refresh_mhz](double rate) {
4630 const double delta = rate - static_cast<double>(refresh_mhz) / 1000.0;
4631 return delta < 0 ? -delta : delta;
4632 };
4633
4634 const mode_t *chosen = nullptr;
4635 for (const auto &mode : monitor->modes) {
4636 if (mode.width != static_cast<int>(width) || mode.height != static_cast<int>(height)) {
4637 continue;
4638 }
4639 if (!chosen || refresh_delta(mode.refresh) < refresh_delta(chosen->refresh)) {
4640 chosen = &mode;
4641 }
4642 }
4643 if (!chosen) {
4644 return mode_push::unsupported;
4645 }
4646 if (chosen->current) {
4647 return mode_push::already_set;
4648 }
4649
4650 std::vector<logical_monitor_t> layout = state.logical_monitors;
4651 const auto owner = std::find_if(layout.begin(), layout.end(), [&connector](const logical_monitor_t &lm) {
4652 return std::find(lm.connectors.begin(), lm.connectors.end(), connector) != lm.connectors.end();
4653 });
4654 if (owner == layout.end()) {
4655 int right_edge = 0;
4656 // A layout is measured in logical pixels, so the right edge has to come
4657 // from mode / scale. Using the mode size on a scaled desktop places the
4658 // new monitor past the edge, which leaves a gap, and Mutter rejects a
4659 // layout whose monitors are not all adjacent - taking the whole config
4660 // down with it, not just our output.
4661 for (const auto &lm : layout) {
4662 int lm_width = 0;
4663 int lm_height = 0;
4664 if (!state.logical_size(lm, lm_width, lm_height)) {
4665 // Without a size the placement cannot be made adjacent, and Mutter
4666 // would reject the whole config.
4667 return mode_push::unavailable;
4668 }
4669 right_edge = std::max(right_edge, std::atoi(lm.x.c_str()) + lm_width);
4670 }
4671 logical_monitor_t added;
4672 added.x = std::to_string(right_edge);
4673 added.y = "0";
4674 // Where the backend demands one scale for the whole desktop, a scale of
4675 // our own is refused ("Logical monitor scales must be identical"), so
4676 // adopt whatever the existing monitors carry.
4677 added.scale = "1.0";
4678 if (state.global_scale_required && !layout.empty() && !layout.front().scale.empty()) {
4679 added.scale = layout.front().scale;
4680 }
4681 added.transform = "0";
4682 added.primary = layout.empty() ? "true" : "false";
4683 added.connectors.emplace_back(connector);
4684 layout.emplace_back(std::move(added));
4685 }
4686
4687 return build_apply_argument(state, layout, argument, {{connector, chosen->id}}) ? mode_push::ready :
4689 }
4690
4696 static bool mode_confirmed(const std::string &connector,
4697 uint32_t width,
4698 uint32_t height,
4699 uint32_t refresh_mhz,
4700 std::chrono::steady_clock::time_point deadline) {
4701 while (std::chrono::steady_clock::now() < deadline) {
4702 state_t state;
4703 std::string argument;
4704 switch (build_layout_with_mode(command_output(get_current_state_command),
4705 connector, width, height, refresh_mhz, state, argument)) {
4706 case mode_push::already_set:
4707 return true;
4708 case mode_push::unavailable:
4709 // An unreadable reply is not evidence that the mode was refused;
4710 // keep the session going rather than tearing it down over it.
4711 BOOST_LOG(debug) << "[VDISPLAY/Mutter] Could not read back the state of " << connector
4712 << "; assuming the applied mode holds.";
4713 return true;
4714 default:
4715 std::this_thread::sleep_for(std::chrono::milliseconds {100});
4716 break;
4717 }
4718 }
4719
4720 BOOST_LOG(warning) << "[VDISPLAY/Mutter] " << connector << " is not being driven at " << width << 'x'
4721 << height << " after the config was applied; something else is rewriting the "
4722 "display layout, and the stream will not match what the client asked for.";
4723 return false;
4724 }
4725
4744 static bool apply_output_mode(const std::string &connector,
4745 uint32_t width,
4746 uint32_t height,
4747 uint32_t refresh_mhz,
4748 int deadline_ms) {
4749 if (!available() || connector.empty() || !width || !height) {
4750 return false;
4751 }
4752
4753 // Mutter adopts a hotplugged connector asynchronously, so this waits.
4754 // A caller on a hot path - /resume answers a client that is counting the
4755 // seconds - passes a shorter budget than a launch does. Two thirds go to
4756 // waiting for the connector to appear and the rest to confirming the mode
4757 // stuck, so a short budget shortens both rather than spending everything
4758 // on the first half.
4759 const auto start = std::chrono::steady_clock::now();
4760 const auto appear_deadline = start + std::chrono::milliseconds {deadline_ms * 2 / 3};
4761 const auto confirm_budget = std::chrono::milliseconds {deadline_ms / 3};
4762
4763 while (std::chrono::steady_clock::now() < appear_deadline) {
4764 state_t state;
4765 std::string argument;
4766 switch (build_layout_with_mode(command_output(get_current_state_command),
4767 connector, width, height, refresh_mhz, state, argument)) {
4768 case mode_push::unavailable:
4769 // Mutter has not processed the hotplug yet.
4770 std::this_thread::sleep_for(std::chrono::milliseconds {100});
4771 continue;
4772 case mode_push::unsupported:
4773 BOOST_LOG(warning) << "[VDISPLAY/Mutter] " << connector << " does not advertise " << width << "x" << height
4774 << "; leaving Mutter's own choice in place.";
4775 return false;
4776 case mode_push::already_set:
4777 BOOST_LOG(info) << "[VDISPLAY/Mutter] " << connector << " is already driven at the requested mode.";
4778 return true;
4779 case mode_push::ready:
4780 break;
4781 }
4782
4783 if (!run_apply(state, argument, apply_method::verify)) {
4784 return false;
4785 }
4786
4787 BOOST_LOG(info) << "[VDISPLAY/Mutter] Driving " << connector << " at " << width << "x" << height << "@"
4788 << (refresh_mhz / 1000) << "Hz for this session.";
4789 // Temporary rather than persistent: a streaming session must not
4790 // rewrite the user's saved layout in ~/.config/monitors.xml. Mutter
4791 // keeps a temporary config until something else replaces it; it does
4792 // not revert on its own.
4793 if (!run_apply(state, argument, apply_method::temporary)) {
4794 return false;
4795 }
4796
4797 // ApplyMonitorsConfig returning cleanly is not the same as Mutter
4798 // scanning out the mode: it can be superseded by a hotplug or by
4799 // anything else that rewrites the layout while we are still setting up.
4800 // The capture path reports the real scanout, so an unconfirmed mode is
4801 // exactly the resolution mismatch that reaches the client as a broken
4802 // image. Confirm it, and say so when it did not stick.
4803 return mode_confirmed(connector, width, height, refresh_mhz,
4804 std::chrono::steady_clock::now() + confirm_budget);
4805 }
4806
4807 BOOST_LOG(warning) << "[VDISPLAY/Mutter] " << connector << " never appeared in Mutter's monitor state.";
4808 return false;
4809 }
4810
4832 static bool geometry_from_state(const state_t &state,
4833 const std::string &connector,
4834 int &x, int &y,
4835 int &env_width, int &env_height) {
4836 if (connector.empty()) {
4837 return false;
4838 }
4839
4840 const logical_monitor_t *owner = state.find_logical_monitor(connector);
4841 if (!owner) {
4842 BOOST_LOG(debug) << "[VDISPLAY/Mutter] " << connector
4843 << " is not in the monitor layout; absolute input has no offset to apply.";
4844 return false;
4845 }
4846
4847 double envelope_width = 0.0;
4848 double envelope_height = 0.0;
4849 for (const auto &lm : state.logical_monitors) {
4850 int lm_width = 0;
4851 int lm_height = 0;
4852 if (!state.logical_size(lm, lm_width, lm_height)) {
4853 return false;
4854 }
4855 envelope_width = std::max(envelope_width, static_cast<double>(std::atoi(lm.x.c_str()) + lm_width));
4856 envelope_height = std::max(envelope_height, static_cast<double>(std::atoi(lm.y.c_str()) + lm_height));
4857 }
4858 if (envelope_width <= 0.0 || envelope_height <= 0.0) {
4859 return false;
4860 }
4861
4862 // Only the logical layout mode divides the mode by the scale; in the
4863 // physical one the layout already counts mode pixels and there is nothing
4864 // to convert.
4865 const double scale =
4866 state.layout_mode == layout_mode_e::logical ? state_t::scale_of(*owner) : 1.0;
4867 x = static_cast<int>(std::lround(std::atoi(owner->x.c_str()) * scale));
4868 y = static_cast<int>(std::lround(std::atoi(owner->y.c_str()) * scale));
4869 env_width = static_cast<int>(std::lround(envelope_width * scale));
4870 env_height = static_cast<int>(std::lround(envelope_height * scale));
4871 return env_width > 0 && env_height > 0;
4872 }
4873
4874 static bool geometry(const std::string &connector, int &x, int &y, int &env_width, int &env_height) {
4875 if (!available() || connector.empty()) {
4876 return false;
4877 }
4878
4879 state_t state;
4880 if (!parse_current_state(command_output(get_current_state_command), state)) {
4881 return false;
4882 }
4883 return geometry_from_state(state, connector, x, y, env_width, env_height);
4884 }
4885
4886 // ------------------------------------------------------------------
4887 // Session layout: exclusive and mirror.
4888 //
4889 // ApplyMonitorsConfig takes the complete list of logical monitors, and
4890 // Mutter disables every connected monitor absent from that list
4891 // (create_disabled_monitor_specs_for_config). So exclusive mode is a config
4892 // carrying nothing but the virtual output, and there is no separate
4893 // "disable this output" call to look for.
4894 //
4895 // Mirror is not a position. Mutter refuses overlapping logical monitors, so
4896 // cloning means one logical monitor holding both connectors - and it
4897 // refuses that too unless their modes have identical dimensions, which is
4898 // why this can only mirror at a resolution the virtual output advertises.
4899 // ------------------------------------------------------------------
4900
4903 std::string restore_argument;
4905 bool active {false};
4906 };
4907
4908 static std::mutex layouts_mutex;
4909 static std::map<std::string, layout_state_t> layouts;
4910
4916 static bool safe_apply_argument(const std::string &argument) {
4917 if (argument.empty() || argument.size() > 8192) {
4918 return false;
4919 }
4920 return std::all_of(argument.begin(), argument.end(), [](unsigned char c) {
4921 return std::isalnum(c) || c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' ||
4922 c == '\'' || c == ',' || c == ' ' || c == '.' || c == '-' || c == '_' || c == '@' ||
4923 c == '+' || c == ':';
4924 });
4925 }
4926
4927 static std::string recovery_state_file() {
4928 const char *xdg_state = std::getenv("XDG_STATE_HOME");
4929 const char *home = std::getenv("HOME");
4930 std::string base;
4931 if (xdg_state && xdg_state[0]) {
4932 base = std::string {xdg_state} + "/hermes";
4933 } else if (home && home[0]) {
4934 base = std::string {home} + "/.local/state/hermes";
4935 } else {
4936 return {};
4937 }
4938
4939 std::error_code ec;
4940 fs::create_directories(base, ec);
4941 return base + "/saved-mutter-layout";
4942 }
4943
4951 static void write_recovery_state(const std::string &reply, const std::string &virtual_connector) {
4952 state_t ignored;
4953 std::string argument;
4954 if (build_layout_without(reply, virtual_connector, ignored, argument) != layout_repair::ready ||
4955 !safe_apply_argument(argument)) {
4956 BOOST_LOG(warning) << "[VDISPLAY/Mutter] No physical-only layout to fall back on; a crash while the "
4957 "monitors are off would leave them off.";
4958 return;
4959 }
4960
4961 const auto path = recovery_state_file();
4962 if (path.empty()) {
4963 return;
4964 }
4965 const auto temporary_path = path + ".tmp";
4966 {
4967 std::ofstream file {temporary_path, std::ios::binary | std::ios::trunc};
4968 if (!file) {
4969 return;
4970 }
4971 file << argument << '\n';
4972 }
4973 std::error_code ec;
4974 fs::rename(temporary_path, path, ec);
4975 if (ec) {
4976 fs::remove(temporary_path, ec);
4977 }
4978 }
4979
4980 static void clear_recovery_state() {
4981 const auto path = recovery_state_file();
4982 if (path.empty()) {
4983 return;
4984 }
4985 std::error_code ec;
4986 fs::remove(path, ec);
4987 }
4988
4990 static bool apply_argument(const std::string &argument) {
4991 if (!safe_apply_argument(argument)) {
4992 return false;
4993 }
4994 state_t state;
4995 if (!parse_current_state(command_output(get_current_state_command), state)) {
4996 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Could not read the monitor state to apply a layout.";
4997 return false;
4998 }
4999 if (!run_apply(state, argument, apply_method::verify)) {
5000 return false;
5001 }
5002 return run_apply(state, argument, apply_method::temporary);
5003 }
5004
5005 static void recover_on_startup() {
5006 if (!available()) {
5007 return;
5008 }
5009 const auto path = recovery_state_file();
5010 if (path.empty()) {
5011 return;
5012 }
5013 std::string argument;
5014 {
5015 std::ifstream file {path};
5016 if (!file) {
5017 return;
5018 }
5019 std::getline(file, argument);
5020 }
5021 if (argument.empty()) {
5022 clear_recovery_state();
5023 return;
5024 }
5025 if (!safe_apply_argument(argument)) {
5026 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Discarding an unreadable saved layout.";
5027 clear_recovery_state();
5028 return;
5029 }
5030
5031 state_t state;
5032 if (!parse_current_state(command_output(get_current_state_command), state)) {
5033 // Mutter did not answer; this is not evidence the layout is stale.
5034 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Startup recovery deferred: Mutter did not answer.";
5035 return;
5036 }
5037
5038 BOOST_LOG(info) << "[VDISPLAY/Mutter] Recovering the display layout a previous session left behind.";
5039 if (run_apply(state, argument, apply_method::verify) &&
5040 run_apply(state, argument, apply_method::temporary)) {
5041 clear_recovery_state();
5042 return;
5043 }
5044 // Mutter answered and refused: the layout no longer describes this
5045 // desktop, and Mutter has already configured something for it. Keeping
5046 // the file would retry the same rejection every start.
5047 BOOST_LOG(warning) << "[VDISPLAY/Mutter] The saved layout no longer applies to this desktop; discarding it.";
5048 clear_recovery_state();
5049 }
5050
5057
5059 static bool build_restore_layout(const state_t &state, std::string &argument) {
5060 return build_apply_argument(state, state.logical_monitors, argument);
5061 }
5062
5068 static layout_change build_exclusive_layout(const std::string &reply,
5069 const std::string &connector,
5070 state_t &state,
5071 std::string &argument) {
5072 state = {};
5073 argument.clear();
5074 if (reply.empty() || connector.empty() || !parse_current_state(reply, state)) {
5075 return layout_change::unavailable;
5076 }
5077 if (state.current_mode.find(connector) == state.current_mode.end()) {
5078 // Nothing is being scanned out on it, so there is no mode to name and
5079 // handing it the desktop would black the session out.
5080 return layout_change::unsupported;
5081 }
5082
5083 const logical_monitor_t *owner = state.find_logical_monitor(connector);
5084 if (owner && state.logical_monitors.size() == 1 && owner->connectors.size() == 1) {
5085 return layout_change::already_set;
5086 }
5087
5088 logical_monitor_t only;
5089 only.x = "0";
5090 only.y = "0";
5091 // Keep the scale Mutter already drives it at: one of our own can fail the
5092 // "mode divided by scale must be a whole number" check and take the
5093 // whole config with it.
5094 only.scale = owner ? owner->scale : std::string {"1.0"};
5095 only.transform = owner ? owner->transform : std::string {"0"};
5096 only.primary = "true";
5097 only.connectors.emplace_back(connector);
5098
5099 return build_apply_argument(state, {only}, argument) ? layout_change::ready :
5101 }
5102
5108 static layout_change build_mirror_layout(const std::string &reply,
5109 const std::string &connector,
5110 state_t &state,
5111 std::string &argument,
5112 int *mirrored_width = nullptr,
5113 int *mirrored_height = nullptr) {
5114 state = {};
5115 argument.clear();
5116 if (reply.empty() || connector.empty() || !parse_current_state(reply, state)) {
5117 return layout_change::unavailable;
5118 }
5119
5120 // The monitor to clone: the primary one that is not ours, else the first.
5121 const logical_monitor_t *target = nullptr;
5122 for (const auto &lm : state.logical_monitors) {
5123 if (std::find(lm.connectors.begin(), lm.connectors.end(), connector) != lm.connectors.end()) {
5124 if (lm.connectors.size() > 1) {
5125 return layout_change::already_set; // already sharing a logical monitor
5126 }
5127 continue;
5128 }
5129 if (!target || lm.primary == "true") {
5130 target = &lm;
5131 }
5132 }
5133 if (!target || target->connectors.empty()) {
5134 return layout_change::unsupported;
5135 }
5136
5137 const auto target_mode_id = state.current_mode.find(target->connectors.front());
5138 const auto *target_monitor = state.find_monitor(target->connectors.front());
5139 if (target_mode_id == state.current_mode.end() || !target_monitor) {
5140 return layout_change::unavailable;
5141 }
5142 const mode_t *target_mode = nullptr;
5143 for (const auto &mode : target_monitor->modes) {
5144 if (mode.id == target_mode_id->second) {
5145 target_mode = &mode;
5146 break;
5147 }
5148 }
5149 if (!target_mode) {
5150 return layout_change::unavailable;
5151 }
5152
5153 // Mutter refuses a logical monitor whose monitors do not share the mode
5154 // dimensions, so the virtual output has to advertise this exact size.
5155 const monitor_t *virtual_monitor = state.find_monitor(connector);
5156 if (!virtual_monitor) {
5157 return layout_change::unavailable;
5158 }
5159 const mode_t *chosen = nullptr;
5160 for (const auto &mode : virtual_monitor->modes) {
5161 if (mode.width != target_mode->width || mode.height != target_mode->height) {
5162 continue;
5163 }
5164 if (!chosen ||
5165 std::abs(mode.refresh - target_mode->refresh) < std::abs(chosen->refresh - target_mode->refresh)) {
5166 chosen = &mode;
5167 }
5168 }
5169 if (!chosen) {
5170 return layout_change::unsupported;
5171 }
5172
5173 if (mirrored_width) {
5174 *mirrored_width = target_mode->width;
5175 }
5176 if (mirrored_height) {
5177 *mirrored_height = target_mode->height;
5178 }
5179
5180 // Take the connector out of wherever it sits and add it to the target,
5181 // dropping a logical monitor that held nothing else. The target is
5182 // identified by its leading connector, which the virtual one is not.
5183 const std::string target_connector = target->connectors.front();
5184 std::vector<logical_monitor_t> layout;
5185 bool mirrored = false;
5186 for (auto lm : state.logical_monitors) {
5187 lm.connectors.erase(
5188 std::remove(lm.connectors.begin(), lm.connectors.end(), connector),
5189 lm.connectors.end()
5190 );
5191 if (lm.connectors.empty()) {
5192 continue;
5193 }
5194 if (lm.connectors.front() == target_connector) {
5195 lm.connectors.emplace_back(connector);
5196 mirrored = true;
5197 }
5198 layout.emplace_back(std::move(lm));
5199 }
5200 if (layout.empty() || !mirrored) {
5201 return layout_change::unavailable;
5202 }
5203
5204 return build_apply_argument(state, layout, argument, {{connector, chosen->id}}) ?
5205 layout_change::ready :
5207 }
5208
5216 static bool make_exclusive(const std::string &display_name, const std::string &connector) {
5217 if (!available() || connector.empty()) {
5218 return false;
5219 }
5220
5221 const auto reply = command_output(get_current_state_command);
5222 state_t state;
5223 std::string argument;
5224 switch (build_exclusive_layout(reply, connector, state, argument)) {
5225 case layout_change::already_set:
5226 BOOST_LOG(info) << "[VDISPLAY/Mutter] " << connector << " already has the desktop to itself.";
5227 return true;
5228 case layout_change::unsupported:
5229 BOOST_LOG(warning) << "[VDISPLAY/Mutter] " << connector
5230 << " is not being driven; refusing to hand it the desktop.";
5231 return false;
5232 case layout_change::unavailable:
5233 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Could not read the monitor state; leaving the layout alone.";
5234 return false;
5235 case layout_change::ready:
5236 break;
5237 }
5238
5239 std::string restore_argument;
5240 if (!build_restore_layout(state, restore_argument)) {
5241 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Refusing exclusive mode: the current layout could not be "
5242 "captured, so it could not be put back.";
5243 return false;
5244 }
5245
5246 // Written before the monitors go dark, so a crash between the two leaves
5247 // something for the next start to work from.
5248 write_recovery_state(reply, connector);
5249
5250 if (!run_apply(state, argument, apply_method::verify) ||
5251 !run_apply(state, argument, apply_method::temporary)) {
5252 BOOST_LOG(warning) << "[VDISPLAY/Mutter] GNOME refused the exclusive layout; the physical outputs stay on.";
5253 clear_recovery_state();
5254 return false;
5255 }
5256
5257 {
5258 std::lock_guard<std::mutex> lock(layouts_mutex);
5259 layouts[display_name] = {.restore_argument = std::move(restore_argument), .active = true};
5260 }
5261 BOOST_LOG(info) << "[VDISPLAY/Mutter] " << connector << " has the desktop for this session.";
5262 return true;
5263 }
5264
5273 static bool apply_mirror(const std::string &display_name, const std::string &connector) {
5274 if (!available() || connector.empty()) {
5275 return false;
5276 }
5277
5278 state_t state;
5279 std::string argument;
5280 int mirrored_width = 0;
5281 int mirrored_height = 0;
5282 switch (build_mirror_layout(
5283 command_output(get_current_state_command), connector, state, argument, &mirrored_width, &mirrored_height
5284 )) {
5285 case layout_change::already_set:
5286 return true;
5287 case layout_change::unsupported:
5288 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Cannot mirror onto " << connector
5289 << ": GNOME clones by putting both outputs in one logical monitor, which requires "
5290 "them to advertise the same mode size. The session keeps the extended layout.";
5291 return false;
5292 case layout_change::unavailable:
5293 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Could not read the monitor state; not mirroring.";
5294 return false;
5295 case layout_change::ready:
5296 break;
5297 }
5298
5299 std::string restore_argument;
5300 if (!build_restore_layout(state, restore_argument)) {
5301 return false;
5302 }
5303
5304 if (!run_apply(state, argument, apply_method::verify) ||
5305 !run_apply(state, argument, apply_method::temporary)) {
5306 BOOST_LOG(warning) << "[VDISPLAY/Mutter] GNOME refused the mirrored layout; the outputs stay as they were.";
5307 return false;
5308 }
5309
5310 {
5311 std::lock_guard<std::mutex> lock(layouts_mutex);
5312 layouts[display_name] = {.restore_argument = std::move(restore_argument), .active = true};
5313 }
5314 BOOST_LOG(info) << "[VDISPLAY/Mutter] Mirroring onto " << connector << " at " << mirrored_width << 'x'
5315 << mirrored_height << "; the stream runs at that resolution, not the one the client asked for.";
5316 return true;
5317 }
5318
5319 // ------------------------------------------------------------------
5320 // Input device mapping.
5321 //
5322 // Mutter measures an absolute *pointer* against the whole desktop, but a
5323 // touchscreen or a tablet is bound to one monitor by MetaInputMapper. With
5324 // nothing configured it guesses - by EDID, by the device's physical size,
5325 // and failing both a touchscreen falls back to the built-in panel. On a
5326 // laptop that pins the client's touches to the laptop screen; on a desktop
5327 // with no built-in panel nothing matches and the device stretches over the
5328 // whole desktop. Neither is the streamed output.
5329 //
5330 // The deterministic control is the per-device "output" key: a list of at
5331 // least three strings compared against the monitor's EDID vendor, product
5332 // and serial (meta-input-mapper.c, match_config). Hermes owns the vendor
5333 // and product ids of its virtual devices, so it can write the key for
5334 // exactly its own and leave every real device alone.
5335 //
5336 // A mapping left behind by a crash is harmless: it names a monitor that no
5337 // longer exists, no monitor matches it, and the device falls back to what
5338 // it would have done anyway. That is why there is no recovery file here,
5339 // unlike the layout.
5340 //
5341 // The binding is per vendor:product, and every Hermes device carries the
5342 // same pair, so it is one binding for the host rather than one per session.
5343 // With concurrent sessions it therefore points at whichever output was
5344 // activated last. That is a limit of how GNOME addresses devices, not a
5345 // choice made here - and it is still an improvement on the guess, which is
5346 // wrong for every session.
5347 // ------------------------------------------------------------------
5348
5350 const char *schema;
5351 const char *group;
5352 };
5353
5356 static constexpr device_settings_t touch_settings {
5357 "org.gnome.desktop.peripherals.touchscreen", "touchscreens"
5358 };
5359 static constexpr device_settings_t pen_settings {
5360 "org.gnome.desktop.peripherals.tablet", "tablets"
5361 };
5362
5364 static std::string device_settings_target(const device_settings_t &device) {
5365 char ids[16] = {};
5366 // Mutter formats the path with %.4x, so lowercase hex, at least 4 digits.
5367 std::snprintf(ids, sizeof(ids), "%.4x:%.4x", VIRTUAL_INPUT_SETTINGS_VENDOR_ID, VIRTUAL_INPUT_SETTINGS_PRODUCT_ID);
5368 return std::string {device.schema} + ":/org/gnome/desktop/peripherals/" + device.group + "/" + ids + "/";
5369 }
5370
5378 static bool safe_edid_field(const std::string &value) {
5379 return value.size() <= 128 && std::all_of(value.begin(), value.end(), [](unsigned char c) {
5380 return std::isalnum(c) || c == ' ' || c == '-' || c == '_' || c == '.' || c == ':' ||
5381 c == '+' || c == '/' || c == '(' || c == ')' || c == ',';
5382 });
5383 }
5384
5392 static std::string device_output_value(const state_t &state, const std::string &connector) {
5393 const monitor_t *monitor = state.find_monitor(connector);
5394 if (!monitor) {
5395 return {};
5396 }
5397 if (!safe_edid_field(monitor->vendor) || !safe_edid_field(monitor->product) ||
5398 !safe_edid_field(monitor->serial) || !safe_variant_token(monitor->connector)) {
5399 return {};
5400 }
5401 // A binding whose three EDID fields are all empty is read as "not
5402 // configured", so it would bind nothing while still counting as a user
5403 // value - the worst of both.
5404 if (monitor->vendor.empty() && monitor->product.empty() && monitor->serial.empty()) {
5405 return {};
5406 }
5407 return "['" + monitor->vendor + "', '" + monitor->product + "', '" + monitor->serial + "', '" +
5408 monitor->connector + "']";
5409 }
5410
5412 bool active {false};
5415 std::string previous_touch;
5416 std::string previous_pen;
5417 };
5418
5419 static std::mutex input_mapping_mutex;
5420 static input_mapping_t input_mapping;
5421
5422 static std::string read_device_setting(const device_settings_t &device) {
5423 const std::string command = "gsettings get " + device_settings_target(device) + " output 2>/dev/null";
5424 return trim_variant(command_output(command.c_str()));
5425 }
5426
5427 static bool write_device_setting(const device_settings_t &device, const std::string &value) {
5428 const std::string command = "gsettings set " + device_settings_target(device) + " output \"" + value +
5429 "\" 2>/dev/null";
5430 return std::system(command.c_str()) == 0;
5431 }
5432
5433 static void reset_device_setting(const device_settings_t &device) {
5434 const std::string command = "gsettings reset " + device_settings_target(device) + " output 2>/dev/null";
5435 (void) std::system(command.c_str());
5436 }
5437
5439 static bool is_unset_output_value(const std::string &value) {
5440 return value.empty() || value == "['', '', '']" || value == "@as []" || value == "[]";
5441 }
5442
5449 static void map_input_devices(const std::string &connector) {
5450 if (!available() || connector.empty()) {
5451 return;
5452 }
5453
5454 state_t state;
5455 if (!parse_current_state(command_output(get_current_state_command), state)) {
5456 return;
5457 }
5458 const auto value = device_output_value(state, connector);
5459 if (value.empty()) {
5460 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Cannot bind touch input to " << connector
5461 << ": its monitor identity is missing or cannot be spelled safely. Touches will "
5462 "land wherever GNOME guesses.";
5463 return;
5464 }
5465
5466 std::lock_guard<std::mutex> lock(input_mapping_mutex);
5467 if (!input_mapping.active) {
5468 input_mapping.previous_touch = read_device_setting(touch_settings);
5469 input_mapping.previous_pen = read_device_setting(pen_settings);
5470 }
5471 const bool touch_ok = write_device_setting(touch_settings, value);
5472 const bool pen_ok = write_device_setting(pen_settings, value);
5473 if (!touch_ok && !pen_ok) {
5474 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Could not bind the virtual touch devices to " << connector
5475 << "; is gsettings available in this session?";
5476 return;
5477 }
5478 input_mapping.active = true;
5479 BOOST_LOG(info) << "[VDISPLAY/Mutter] Touch and pen input bound to " << connector << '.';
5480 }
5481
5483 static void unmap_input_devices() {
5484 std::lock_guard<std::mutex> lock(input_mapping_mutex);
5485 if (!input_mapping.active) {
5486 return;
5487 }
5488 const auto put_back = [](const device_settings_t &device, const std::string &previous) {
5489 // A value read back from the store has not been through our builder, so
5490 // anything that could not have come out of it is reset rather than
5491 // written to a command line.
5492 if (is_unset_output_value(previous) || !safe_apply_argument(previous)) {
5493 reset_device_setting(device);
5494 } else {
5495 write_device_setting(device, previous);
5496 }
5497 };
5498 put_back(touch_settings, input_mapping.previous_touch);
5499 put_back(pen_settings, input_mapping.previous_pen);
5500 input_mapping = {};
5501 BOOST_LOG(info) << "[VDISPLAY/Mutter] Released the touch and pen input binding.";
5502 }
5503
5505 static void restore(const std::string &display_name) {
5506 std::string argument;
5507 {
5508 std::lock_guard<std::mutex> lock(layouts_mutex);
5509 const auto it = layouts.find(display_name);
5510 if (it == layouts.end() || !it->second.active) {
5511 return;
5512 }
5513 argument = it->second.restore_argument;
5514 layouts.erase(it);
5515 }
5516
5517 if (apply_argument(argument)) {
5518 clear_recovery_state();
5519 BOOST_LOG(info) << "[VDISPLAY/Mutter] Restored the display layout the session found.";
5520 return;
5521 }
5522 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Could not restore the display layout; keeping the recovery state "
5523 "so the next start can.";
5524 }
5525
5526 // ------------------------------------------------------------------
5527 // Watching the layout.
5528 //
5529 // Everything above reads GetCurrentState once and acts on the answer. That
5530 // answer has a shelf life: GNOME rewrites the layout for reasons that have
5531 // nothing to do with streaming - another monitor is plugged in, the
5532 // Displays panel is opened, a stored configuration is reapplied after a
5533 // resume - and any of those can move our output, change its mode, or
5534 // replace the temporary configuration a session applied. The offsets the
5535 // capture path computed at session start are then quietly wrong, and the
5536 // pointer goes back to landing in the wrong place with nothing to show for
5537 // it.
5538 //
5539 // MonitorsChanged is the compositor telling us exactly that. It costs
5540 // nothing until it fires, unlike re-reading the state on a timer, which is
5541 // a subprocess per tick for a whole session.
5542 //
5543 // What this deliberately does NOT do is put the layout back. If the mode or
5544 // the layout changed under us, something - very likely the user - wanted
5545 // it that way, and a session that keeps overwriting the display settings
5546 // while someone is trying to change them is worse than one that follows.
5547 // So it records the change and lets the capture path pick the new geometry
5548 // up; the resolution the client sees follows the compositor.
5549 // ------------------------------------------------------------------
5550
5554 static std::atomic<uint64_t> layout_generation {1};
5555
5556#ifdef HERMES_BUILD_SDBUS
5557 struct watcher_t {
5558 sd_bus *bus {nullptr};
5559 sd_bus_slot *slot {nullptr};
5560 std::thread thread;
5561 std::atomic<bool> stop {false};
5566 std::string signature;
5567 };
5568
5569 static std::mutex watcher_mutex;
5570 static std::unique_ptr<watcher_t> watcher;
5571
5573 static std::string layout_signature() {
5574 state_t state;
5575 std::string signature;
5576 if (!parse_current_state(command_output(get_current_state_command), state) ||
5577 !build_restore_layout(state, signature)) {
5578 return {};
5579 }
5580 return signature;
5581 }
5582
5583 static int on_monitors_changed(sd_bus_message * /* message */, void *userdata, sd_bus_error * /* error */) {
5584 auto *state = static_cast<watcher_t *>(userdata);
5585 const auto signature = layout_signature();
5586 if (signature.empty() || signature == state->signature) {
5587 // Unreadable, or a change that does not touch any geometry we use.
5588 return 0;
5589 }
5590 state->signature = signature;
5591 layout_generation.fetch_add(1, std::memory_order_relaxed);
5592 BOOST_LOG(info) << "[VDISPLAY/Mutter] The desktop layout changed; capture will pick up the new geometry.";
5593 return 0;
5594 }
5595
5597 static void watch_layout() {
5598 if (!available()) {
5599 return;
5600 }
5601
5602 std::lock_guard<std::mutex> lock(watcher_mutex);
5603 if (watcher) {
5604 return; // already watching; one subscription serves every display
5605 }
5606
5607 auto started = std::make_unique<watcher_t>();
5608 const int opened = platf::open_user_bus(&started->bus);
5609 if (opened < 0 || !started->bus) {
5610 BOOST_LOG(debug) << "[VDISPLAY/Mutter] Could not connect to the user bus to watch for layout changes: "
5611 << (opened < 0 ? std::strerror(-opened) : "no connection was returned") << '.';
5612 return;
5613 }
5614 started->signature = layout_signature();
5615
5616 const int matched = sd_bus_match_signal(
5617 started->bus,
5618 &started->slot,
5619 "org.gnome.Mutter.DisplayConfig",
5620 "/org/gnome/Mutter/DisplayConfig",
5621 "org.gnome.Mutter.DisplayConfig",
5622 "MonitorsChanged",
5623 on_monitors_changed,
5624 started.get()
5625 );
5626 if (matched < 0) {
5627 BOOST_LOG(warning) << "[VDISPLAY/Mutter] Could not subscribe to MonitorsChanged: "
5628 << std::strerror(-matched)
5629 << ". A layout change mid-session will go unnoticed.";
5630 sd_bus_unref(started->bus);
5631 return;
5632 }
5633
5634 watcher_t *raw = started.get();
5635 started->thread = std::thread([raw]() {
5636 while (!raw->stop.load(std::memory_order_relaxed)) {
5637 const int processed = sd_bus_process(raw->bus, nullptr);
5638 if (processed < 0) {
5639 break;
5640 }
5641 if (processed > 0) {
5642 continue; // more may be queued
5643 }
5644 // A bounded wait rather than an indefinite one, so stopping does not
5645 // need a second wakeup channel.
5646 if (sd_bus_wait(raw->bus, 250000 /* us */) < 0) {
5647 break;
5648 }
5649 }
5650 });
5651 watcher = std::move(started);
5652 BOOST_LOG(info) << "[VDISPLAY/Mutter] Watching the desktop layout for changes.";
5653 }
5654
5655 static void unwatch_layout() {
5656 std::unique_ptr<watcher_t> stopping;
5657 {
5658 std::lock_guard<std::mutex> lock(watcher_mutex);
5659 stopping = std::move(watcher);
5660 }
5661 if (!stopping) {
5662 return;
5663 }
5664 stopping->stop.store(true, std::memory_order_relaxed);
5665 if (stopping->thread.joinable()) {
5666 stopping->thread.join();
5667 }
5668 if (stopping->slot) {
5669 sd_bus_slot_unref(stopping->slot);
5670 }
5671 if (stopping->bus) {
5672 sd_bus_unref(stopping->bus);
5673 }
5674 }
5675#else
5676 // Without sd-bus there is no subscription to hold, so the generation never
5677 // moves and every capture keeps the geometry it started with.
5678 static void watch_layout() {}
5679
5680 static void unwatch_layout() {}
5681#endif
5682 } // namespace mutter
5683
5684 EvdiBuffer::EvdiBuffer(uint32_t width, uint32_t height):
5685 data_(static_cast<size_t>(width) * height * 4, 0), width_(width), height_(height) {
5686 }
5687
5688 uint64_t EvdiBuffer::copy_to(uint8_t *dst, uint32_t dst_stride) const {
5689 std::lock_guard<std::mutex> lock(mutex_);
5690 const auto row_bytes = stride();
5691 if (dst_stride == row_bytes) {
5692 std::memcpy(dst, data_.data(), static_cast<size_t>(row_bytes) * height_);
5693 } else {
5694 const auto copy_bytes = std::min(dst_stride, row_bytes);
5695 for (uint32_t row = 0; row < height_; ++row) {
5696 std::memcpy(dst + static_cast<size_t>(row) * dst_stride,
5697 data_.data() + static_cast<size_t>(row) * row_bytes, copy_bytes);
5698 }
5699 }
5700 return frame_number();
5701 }
5702
5703 uint64_t EvdiBuffer::wait_for_update(uint64_t last_frame, std::chrono::milliseconds timeout) {
5704 std::unique_lock<std::mutex> lock(mutex_);
5705 condition_.wait_for(lock, timeout, [&] { return frame_number() > last_frame; });
5706 return frame_number();
5707 }
5708
5709 void EvdiBuffer::begin_write() {
5710 mutex_.lock();
5711 }
5712
5713 void EvdiBuffer::end_write() {
5714 mutex_.unlock();
5715 }
5716
5717 void EvdiBuffer::mark_updated() {
5718 frame_number_.fetch_add(1, std::memory_order_release);
5719 condition_.notify_all();
5720 }
5721
5722 // ============================================================================
5723 // EVDI Library Loading
5724 // ============================================================================
5725
5726 static bool load_evdi_library() {
5727 if (evdi.loaded) {
5728 return true;
5729 }
5730
5731 // Try to load libevdi.so
5732 const char *lib_names[] = {
5733 "libevdi.so.1",
5734 "libevdi.so",
5735 "/usr/lib/libevdi.so.1",
5736 "/usr/lib/libevdi.so",
5737 "/usr/local/lib/libevdi.so.1",
5738 "/usr/local/lib/libevdi.so"
5739 };
5740
5741 for (const auto &lib_name : lib_names) {
5742 evdi.lib_handle = dlopen(lib_name, RTLD_NOW);
5743 if (evdi.lib_handle) {
5744 BOOST_LOG(info) << "[VDISPLAY] Loaded EVDI library: " << lib_name;
5745 break;
5746 }
5747 }
5748
5749 if (!evdi.lib_handle) {
5750 BOOST_LOG(warning) << "[VDISPLAY] Could not load libevdi.so: " << dlerror();
5751 BOOST_LOG(warning) << "[VDISPLAY] Virtual-display sessions will be unavailable.";
5752 BOOST_LOG(warning) << "[VDISPLAY] Install the EVDI userspace library and kernel module.";
5753 return false;
5754 }
5755
5756 // Load function pointers
5757 #define LOAD_EVDI_FUNC(name) \
5758 evdi.name = (fn_evdi_##name)dlsym(evdi.lib_handle, "evdi_" #name); \
5759 if (!evdi.name) { \
5760 BOOST_LOG(error) << "[VDISPLAY] Failed to load evdi_" #name; \
5761 dlclose(evdi.lib_handle); \
5762 evdi.lib_handle = nullptr; \
5763 return false; \
5764 }
5765
5766 LOAD_EVDI_FUNC(check_device);
5767 LOAD_EVDI_FUNC(open);
5768 LOAD_EVDI_FUNC(add_device);
5769 LOAD_EVDI_FUNC(close);
5770 LOAD_EVDI_FUNC(connect);
5771 LOAD_EVDI_FUNC(disconnect);
5772 LOAD_EVDI_FUNC(grab_pixels);
5773 LOAD_EVDI_FUNC(register_buffer);
5774 LOAD_EVDI_FUNC(unregister_buffer);
5775 LOAD_EVDI_FUNC(request_update);
5776 LOAD_EVDI_FUNC(handle_events);
5777 LOAD_EVDI_FUNC(get_event_ready);
5778 LOAD_EVDI_FUNC(get_lib_version);
5779
5780 #undef LOAD_EVDI_FUNC
5781
5782 // Check library version
5783 evdi_lib_version version;
5784 evdi.get_lib_version(&version);
5785 BOOST_LOG(info) << "[VDISPLAY] EVDI library version: "
5786 << version.version_major << "."
5787 << version.version_minor << "."
5788 << version.version_patchlevel;
5789 evdi_library_version = std::to_string(version.version_major) + "." +
5790 std::to_string(version.version_minor) + "." +
5791 std::to_string(version.version_patchlevel);
5792
5793 evdi.loaded = true;
5794 return true;
5795 }
5796
5797 static void unload_evdi_library() {
5798 if (evdi.lib_handle) {
5799 dlclose(evdi.lib_handle);
5800 evdi.lib_handle = nullptr;
5801 }
5802 evdi.loaded = false;
5803 evdi_library_version.clear();
5804 }
5805
5806 // ============================================================================
5807 // EVDI Module Check
5808 // ============================================================================
5809
5810 static bool check_evdi_module_loaded(bool log_result = true) {
5811 // Check if evdi kernel module is loaded
5812 std::ifstream modules("/proc/modules");
5813 std::string line;
5814 while (std::getline(modules, line)) {
5815 if (line.find("evdi") != std::string::npos) {
5816 if (log_result) {
5817 BOOST_LOG(info) << "[VDISPLAY] EVDI kernel module is loaded.";
5818 }
5819 return true;
5820 }
5821 }
5822
5823 // Also check sysfs
5824 if (fs::exists("/sys/module/evdi")) {
5825 if (log_result) {
5826 BOOST_LOG(info) << "[VDISPLAY] EVDI kernel module detected via sysfs.";
5827 }
5828 return true;
5829 }
5830
5831 if (log_result) {
5832 BOOST_LOG(warning) << "[VDISPLAY] EVDI kernel module is not loaded.";
5833 BOOST_LOG(warning) << "[VDISPLAY] Try: sudo modprobe evdi";
5834 }
5835 return false;
5836 }
5837
5838 static bool evdi_library_installed() {
5839 constexpr std::array<const char *, 6> library_paths {
5840 "/usr/lib/libevdi.so.1",
5841 "/usr/lib/libevdi.so",
5842 "/usr/local/lib/libevdi.so.1",
5843 "/usr/local/lib/libevdi.so",
5844 "/lib/libevdi.so.1",
5845 "/lib/libevdi.so",
5846 };
5847
5848 return std::any_of(library_paths.begin(), library_paths.end(), [](const auto *path) {
5849 return fs::exists(path);
5850 });
5851 }
5852
5853 static bool evdi_module_installed_for_running_kernel() {
5854 utsname system_info {};
5855 if (uname(&system_info) != 0) {
5856 return false;
5857 }
5858
5859 const fs::path module_root = fs::path("/lib/modules") / system_info.release;
5860 constexpr std::array<const char *, 4> module_extensions {"", ".zst", ".xz", ".gz"};
5861 for (const auto *extension : module_extensions) {
5862 if (fs::exists(module_root / "updates/dkms" / (std::string("evdi.ko") + extension)) ||
5863 fs::exists(module_root / "kernel/drivers/gpu/drm/evdi" / (std::string("evdi.ko") + extension))) {
5864 return true;
5865 }
5866 }
5867
5868 return false;
5869 }
5870
5871 static bool evdi_dkms_build_failed() {
5872 const fs::path dkms_root = "/var/lib/dkms/evdi";
5873 std::error_code ec;
5874 if (!fs::exists(dkms_root, ec)) {
5875 return false;
5876 }
5877
5878 utsname system_info {};
5879 if (uname(&system_info) != 0) {
5880 return false;
5881 }
5882
5883 const std::string kernel_marker = std::string("for kernel ") + system_info.release;
5884 for (fs::recursive_directory_iterator it(dkms_root, fs::directory_options::skip_permission_denied, ec), end;
5885 !ec && it != end;
5886 it.increment(ec)) {
5887 if (it->path().filename() != "make.log") {
5888 continue;
5889 }
5890
5891 std::ifstream log_file(it->path());
5892 std::string log_contents((std::istreambuf_iterator<char>(log_file)), std::istreambuf_iterator<char>());
5893 if (log_contents.find(kernel_marker) != std::string::npos &&
5894 log_contents.find("# exit code: 0") == std::string::npos &&
5895 (log_contents.find(" error:") != std::string::npos || log_contents.find("Error ") != std::string::npos)) {
5896 return true;
5897 }
5898 }
5899
5900 return false;
5901 }
5902
5903 static std::string running_kernel_release() {
5904 utsname system_info {};
5905 return uname(&system_info) == 0 ? system_info.release : "unknown";
5906 }
5907
5908 static std::vector<std::string> dkms_kernels(const std::string &dkms_name) {
5909 std::vector<std::string> kernels;
5910 const fs::path dkms_root = fs::path("/var/lib/dkms") / dkms_name;
5911 std::error_code ec;
5912 for (const auto &version : fs::directory_iterator(dkms_root, fs::directory_options::skip_permission_denied, ec)) {
5913 if (ec || !version.is_directory()) {
5914 continue;
5915 }
5916 for (const auto &kernel : fs::directory_iterator(version.path(), fs::directory_options::skip_permission_denied, ec)) {
5917 if (ec || !kernel.is_directory()) {
5918 continue;
5919 }
5920 bool module_present = false;
5921 for (const auto &architecture : fs::directory_iterator(kernel.path(), fs::directory_options::skip_permission_denied, ec)) {
5922 if (architecture.is_directory() && fs::exists(architecture.path() / "module")) {
5923 module_present = true;
5924 break;
5925 }
5926 }
5927 if (module_present) {
5928 kernels.emplace_back(version.path().filename().string() + " / " + kernel.path().filename().string());
5929 }
5930 }
5931 }
5932 return kernels;
5933 }
5934
5936 constexpr auto count_path = "/sys/devices/evdi/count";
5937 constexpr auto add_path = "/sys/devices/evdi/add";
5938
5939 std::ifstream count_file(count_path);
5940 int device_count = -1;
5941 count_file >> device_count;
5942
5943 return device_count == 0 && access(add_path, W_OK) != 0;
5944 }
5945
5946 // Generic kernel-module helpers, parameterized by module name. The EVDI
5947 // helpers above predate the Hermes-KMS backend and stay specialized; these
5948 // mirror their logic so the Hermes-KMS diagnostics reach the same fidelity.
5949 static bool kernel_module_loaded(const std::string &module_name) {
5950 std::ifstream modules("/proc/modules");
5951 std::string line;
5952 while (std::getline(modules, line)) {
5953 // /proc/modules lines start with the module name followed by a space.
5954 if (line.rfind(module_name + " ", 0) == 0) {
5955 return true;
5956 }
5957 }
5958 return fs::exists(fs::path("/sys/module") / module_name);
5959 }
5960
5961 static bool dkms_module_installed_for_running_kernel(const std::string &module_file) {
5962 utsname system_info {};
5963 if (uname(&system_info) != 0) {
5964 return false;
5965 }
5966
5967 const fs::path module_root = fs::path("/lib/modules") / system_info.release;
5968 constexpr std::array<const char *, 4> module_extensions {"", ".zst", ".xz", ".gz"};
5969 for (const auto *extension : module_extensions) {
5970 if (fs::exists(module_root / "updates/dkms" / (module_file + extension))) {
5971 return true;
5972 }
5973 }
5974 return false;
5975 }
5976
5984 static std::string dkms_version_for_running_kernel(const std::string &dkms_name) {
5985 utsname system_info {};
5986 if (uname(&system_info) != 0) {
5987 return {};
5988 }
5989
5990 std::error_code ec;
5991 const auto target = fs::read_symlink(
5992 fs::path("/var/lib/dkms") / dkms_name /
5993 (std::string("kernel-") + system_info.release + '-' + system_info.machine),
5994 ec
5995 );
5996 if (ec || target.empty()) {
5997 return {};
5998 }
5999 // Relative in every DKMS release seen; an absolute link names the same
6000 // three trailing components.
6001 if (target.is_absolute()) {
6002 return target.parent_path().parent_path().filename().string();
6003 }
6004 return target.begin()->string();
6005 }
6006
6013 static std::string release_of(const std::string &version) {
6014 std::string release;
6015 int parts = 0;
6016 std::size_t start = 0;
6017 while (parts < 3 && start <= version.size()) {
6018 const auto end = std::min(version.find('.', start), version.size());
6019 const auto part = version.substr(start, end - start);
6020 if (part.empty() || !std::all_of(part.begin(), part.end(), [](unsigned char c) { return std::isdigit(c); })) {
6021 break;
6022 }
6023 release += (parts ? "." : "") + part;
6024 ++parts;
6025 start = end + 1;
6026 }
6027 return parts == 3 ? release : std::string {};
6028 }
6029
6040 static std::string inaccessible_hermes_kms_render_node() {
6041 std::error_code ec;
6042 for (const auto &entry : fs::directory_iterator("/sys/class/drm", ec)) {
6043 const auto name = entry.path().filename().string();
6044 if (!name.starts_with("renderD")) {
6045 continue;
6046 }
6047 std::error_code link_ec;
6048 const auto driver = fs::read_symlink(entry.path() / "device" / "driver", link_ec);
6049 if (link_ec || driver.filename() != "hermes-kms") {
6050 continue;
6051 }
6052
6053 std::string role;
6054 std::string access_uid;
6055 std::ifstream {entry.path() / "device" / "hermes_kms_role"} >> role;
6056 std::ifstream {entry.path() / "device" / "hermes_kms_access_uid"} >> access_uid;
6057 if (role == "session" || !access_uid.empty()) {
6058 continue;
6059 }
6060
6061 const auto node = fs::path("/dev/dri") / name;
6062 if (::access(node.c_str(), R_OK) != 0 && errno == EACCES) {
6063 return node.string();
6064 }
6065 }
6066 return {};
6067 }
6068
6069 static bool dkms_build_failed(const std::string &dkms_name) {
6070 const fs::path dkms_root = fs::path("/var/lib/dkms") / dkms_name;
6071 std::error_code ec;
6072 if (!fs::exists(dkms_root, ec)) {
6073 return false;
6074 }
6075
6076 utsname system_info {};
6077 if (uname(&system_info) != 0) {
6078 return false;
6079 }
6080
6081 const std::string kernel_marker = std::string("for kernel ") + system_info.release;
6082 for (fs::recursive_directory_iterator it(dkms_root, fs::directory_options::skip_permission_denied, ec), end;
6083 !ec && it != end;
6084 it.increment(ec)) {
6085 if (it->path().filename() != "make.log") {
6086 continue;
6087 }
6088
6089 std::ifstream log_file(it->path());
6090 std::string log_contents((std::istreambuf_iterator<char>(log_file)), std::istreambuf_iterator<char>());
6091 if (log_contents.find(kernel_marker) != std::string::npos &&
6092 log_contents.find("# exit code: 0") == std::string::npos &&
6093 (log_contents.find(" error:") != std::string::npos || log_contents.find("Error ") != std::string::npos)) {
6094 return true;
6095 }
6096 }
6097
6098 return false;
6099 }
6100
6102 if (!evdi_library_installed()) {
6103 return EVDI_DIAGNOSTIC::LIBRARY_MISSING;
6104 }
6105
6106 if (!check_evdi_module_loaded(false)) {
6107 if (evdi_dkms_build_failed()) {
6108 return EVDI_DIAGNOSTIC::DKMS_BUILD_FAILED;
6109 }
6110
6111 if (!evdi_module_installed_for_running_kernel()) {
6112 return EVDI_DIAGNOSTIC::MODULE_NOT_INSTALLED;
6113 }
6114
6115 return EVDI_DIAGNOSTIC::MODULE_NOT_LOADED;
6116 }
6117
6119 return EVDI_DIAGNOSTIC::INITIAL_DEVICE_CONFIGURATION_REQUIRED;
6120 }
6121
6122 return EVDI_DIAGNOSTIC::READY;
6123 }
6124
6126 SessionFacts facts;
6127 facts.compositor = sessionCompositor();
6128 facts.hyprland_control = facts.compositor == compositor_e::hyprland && hyprland::available();
6129 facts.wayland = window_system == window_system_e::WAYLAND;
6130 facts.x11 = window_system == window_system_e::X11;
6131
6132#ifdef HERMES_BUILD_WAYLAND
6133 if (facts.wayland) {
6134 const auto protocols = wl::probe_protocols();
6135 facts.output_management = protocols.output_management;
6136 facts.screencopy = protocols.screencopy;
6137 facts.image_copy_capture = protocols.image_copy_capture;
6138 facts.linux_dmabuf = protocols.linux_dmabuf;
6139 facts.kscreen = kscreen::available();
6140 facts.mutter = mutter::available();
6141 }
6142#endif
6143
6144 const auto hermes_kms = getHermesKmsStatus();
6145 facts.hermes_kms_present = hermes_kms.device_present;
6146 facts.hermes_kms_multi_output = hermes_kms.multi_output_capable;
6147 facts.hermes_kms_multi_device = hermes_kms.multi_device_capable;
6149 facts.isolated_sessions_requested = config::video.hermes_kms_isolated_sessions;
6150
6151 return facts;
6152 }
6153
6155 const auto facts = probeSessionFacts();
6156 BOOST_LOG(info) << "[VDISPLAY] Session: " << compositorName(facts.compositor)
6157 << (facts.wayland ? " (Wayland)" : facts.x11 ? " (X11)" : " (no window system)");
6158 for (const auto &report : assessSession(facts)) {
6159 // A feature that works is one line; one that does not carries the reason
6160 // and the fix, because a user who reads only the log is the user this
6161 // exists for.
6162 if (report.readiness == readiness_e::ready) {
6163 BOOST_LOG(info) << "[VDISPLAY] " << featureName(report.feature) << ": ready - " << report.detail;
6164 continue;
6165 }
6166 std::string message = "[VDISPLAY] " + featureName(report.feature) + ": " +
6167 readinessName(report.readiness) + " - " + report.detail;
6168 if (!report.remediation.empty()) {
6169 message += " Fix: " + report.remediation;
6170 }
6171 BOOST_LOG(warning) << message;
6172 }
6173 }
6174
6176 const std::string session_type = window_system == window_system_e::X11 ? "x11" :
6177 window_system == window_system_e::WAYLAND ? "wayland" : "unknown";
6178 bool exclusive_layout_supported = window_system == window_system_e::X11;
6179 std::string output_layout_backend = exclusive_layout_supported ? "xrandr" : "unavailable";
6180#ifdef HERMES_BUILD_WAYLAND
6181 if (window_system == window_system_e::WAYLAND && kscreen::available()) {
6182 exclusive_layout_supported = true;
6183 output_layout_backend = "kscreen-doctor";
6184 }
6185#endif
6186#ifdef HERMES_BUILD_WAYLAND
6187 if (window_system == window_system_e::WAYLAND) {
6188 if (!exclusive_layout_supported && wl::output_management_supported()) {
6189 exclusive_layout_supported = true;
6190 // Name the compositor: "wlr-output-management" is the protocol, not a
6191 // strategy, and the compositor behind it is what decides whether a
6192 // Hermes-KMS output is ever composited onto. A bug report that says
6193 // Hyprland is a different report from one that says sway.
6194 output_layout_backend = "wlr-output-management";
6195 if (const auto compositor = sessionCompositor(); compositor != compositor_e::unknown) {
6196 output_layout_backend += " (" + compositorName(compositor) + ")";
6197 }
6198 }
6199 }
6200#endif
6201 // GNOME/Mutter drives the output through ApplyMonitorsConfig, which takes
6202 // the whole layout: a config naming only the virtual output turns the
6203 // physical ones off, so exclusive mode is available here too.
6204 if (window_system == window_system_e::WAYLAND && output_layout_backend == "unavailable" &&
6205 mutter::available()) {
6206 output_layout_backend = "mutter-displayconfig";
6207 exclusive_layout_supported = true;
6208 }
6209 EvdiStatus status {
6210 .diagnostic = getEvdiDiagnostic(),
6211 .library_installed = evdi_library_installed(),
6212 .library_loaded = evdi.loaded,
6213 .module_loaded = check_evdi_module_loaded(false),
6214 .module_installed = evdi_module_installed_for_running_kernel(),
6215 .device_count = -1,
6216 .session_type = session_type,
6217 .exclusive_layout_supported = exclusive_layout_supported,
6218 .output_layout_backend = output_layout_backend,
6219 .library_version = evdi_library_version,
6220 .running_kernel = running_kernel_release(),
6221 .dkms_kernels = dkms_kernels("evdi"),
6222 .active_displays = {},
6223 };
6224
6225 std::ifstream count_file("/sys/devices/evdi/count");
6226 count_file >> status.device_count;
6227
6228 std::lock_guard<std::mutex> lock(vdisplay_mutex);
6229 for (const auto &[guid, display] : virtual_displays) {
6230 if (display.using_evdi && display.active) {
6231 status.active_displays.push_back({
6232 .name = display.name,
6233 .client_name = display.client_name,
6234 .device_index = display.device_index,
6235 .output_index = -1,
6236 .drm_card_index = display.drm_card_index,
6237 .width = display.width,
6238 .height = display.height,
6239 .fps = display.fps / 1000,
6240 .frame_updates = display.evdi_buffer ? display.evdi_buffer->frame_number() : 0,
6241 });
6242 }
6243 }
6244
6245 return status;
6246 }
6247
6249 const auto probe = hermes_kms::probe();
6250 switch (probe.result) {
6251 case hermes_kms::probe_result::ok:
6252 return HERMES_KMS_DIAGNOSTIC::READY;
6253 case hermes_kms::probe_result::uapi_too_old:
6254 return HERMES_KMS_DIAGNOSTIC::UAPI_TOO_OLD;
6255 case hermes_kms::probe_result::missing_caps:
6256 return HERMES_KMS_DIAGNOSTIC::MISSING_CAPABILITIES;
6258 default:
6259 break;
6260 }
6261
6262 // No usable hermes-kms device node. Distinguish why so the UI can point at
6263 // the right fix: module not built for this kernel, a DKMS build that
6264 // failed, the module simply not loaded, a loaded module that never
6265 // created a device node, or one whose node this user may not open.
6266 if (!inaccessible_hermes_kms_render_node().empty()) {
6268 }
6269 if (!kernel_module_loaded("hermes_kms")) {
6270 if (dkms_build_failed("hermes-kms")) {
6271 return HERMES_KMS_DIAGNOSTIC::DKMS_BUILD_FAILED;
6272 }
6273 if (!dkms_module_installed_for_running_kernel("hermes_kms.ko")) {
6274 return HERMES_KMS_DIAGNOSTIC::MODULE_NOT_INSTALLED;
6275 }
6276 return HERMES_KMS_DIAGNOSTIC::MODULE_NOT_LOADED;
6277 }
6278
6279 // Module is loaded but exposed no hermes-kms card node.
6280 return HERMES_KMS_DIAGNOSTIC::DEVICE_NODE_MISSING;
6281 }
6282
6284 const auto probe = hermes_kms::probe();
6285 HermesKmsStatus status {
6286 .diagnostic = getHermesKmsDiagnostic(),
6287 .module_loaded = kernel_module_loaded("hermes_kms"),
6288 .module_installed = dkms_module_installed_for_running_kernel("hermes_kms.ko"),
6289 .device_present = probe.result == hermes_kms::probe_result::ok,
6290 .card_index = probe.card_index,
6291 .uapi_version = probe.uapi_version,
6292 .required_uapi_version = hermes_kms::required_uapi_version(),
6293 .experimental_multi_output_enabled = hermes_kms::multi_output_requested(),
6294 .multi_output_capable = probe.multi_output_capable,
6295 .experimental_isolated_sessions_enabled = config::video.hermes_kms_isolated_sessions,
6296 .multi_device_capable = probe.multi_device_capable,
6297 .device_count = probe.device_count,
6298 .output_count = probe.output_count,
6299 .private_seat_broker_count = 0,
6300 .missing_private_seat_brokers = {},
6301 .driver_version = probe.driver_version,
6302 .running_kernel = running_kernel_release(),
6303 .dkms_kernels = dkms_kernels("hermes-kms"),
6304 .active_displays = {},
6305 .inaccessible_node = {},
6306 .installed_version = dkms_version_for_running_kernel("hermes-kms"),
6307 .reload_needed = false,
6308 .newest_known_uapi_version = hermes_kms::newest_known_uapi_version,
6309 };
6310
6311 if (status.diagnostic == HERMES_KMS_DIAGNOSTIC::NO_ACCESS) {
6312 status.inaccessible_node = inaccessible_hermes_kms_render_node();
6313 }
6314
6315 // A driver package updated while the old module stays loaded keeps
6316 // serving the old driver until the module is reloaded, which for most
6317 // people means a restart. Only a different release is reported: the
6318 // loaded driver names no build, so two builds of one release look alike.
6319 if (!probe.driver_version.empty()) {
6320 const auto installed = release_of(status.installed_version);
6321 status.reload_needed = !installed.empty() && installed != release_of(probe.driver_version);
6322 }
6323
6324 // device_count includes the seat0 HOST card; only session_device_count has
6325 // a matching private seatd instance.
6326 for (uint32_t instance = 1; instance <= probe.session_device_count; ++instance) {
6327 const auto socket =
6328 fs::path {"/run/hermes-kms-seatd"} /
6329 std::to_string(instance) /
6330 "seatd.sock";
6331 std::error_code socket_ec;
6332 if (fs::is_socket(socket, socket_ec) &&
6333 ::access(socket.c_str(), R_OK | W_OK) == 0) {
6334 ++status.private_seat_broker_count;
6335 } else {
6336 status.missing_private_seat_brokers.push_back(instance);
6337 }
6338 }
6339
6340 std::lock_guard<std::mutex> lock(vdisplay_mutex);
6341 for (const auto &[guid, display] : virtual_displays) {
6342 if (display.using_hermes_kms && display.active) {
6343 status.active_displays.push_back({
6344 .name = display.name,
6345 .client_name = display.client_name,
6346 .device_index = display.device_index,
6347 .output_index = display.output_index,
6348 .drm_card_index = display.drm_card_index,
6349 .width = display.width,
6350 .height = display.height,
6351 .fps = display.fps / 1000,
6352 .frame_updates = 0, // Cumulative KMS frame metrics live in getHermesKmsMetrics().
6353 });
6354 }
6355 }
6356
6357 return status;
6358 }
6359
6360 // ============================================================================
6361 // Utility Functions
6362 // ============================================================================
6363
6364 static std::string generate_display_name(const uuid_util::uuid_t &guid) {
6365 return "VIRTUAL-" + guid.string().substr(0, 8);
6366 }
6367
6368 constexpr int EVDI_DEVICE_SEARCH_LIMIT = 64;
6369
6370 static int find_available_evdi_device() {
6371 // First use an already-created EVDI device, if one is available.
6372 for (int i = 0; i < EVDI_DEVICE_SEARCH_LIMIT; i++) {
6373 if (evdi.check_device(i) == EVDI_AVAILABLE) {
6374 return i;
6375 }
6376 }
6377
6378 // evdi_add_device() reports a successful sysfs write, not the EVDI device
6379 // index. Rescan check_device() to find the index assigned by the kernel.
6380 //
6381 // libevdi's write_add_device() returns fwrite()'s result for a 1-byte
6382 // buffer: exactly 1 on a successful sysfs write, 0 on any failure
6383 // (fopen("/sys/devices/evdi/add", "w") failing, or the write itself
6384 // failing). It never returns a negative value, so the previous
6385 // `result < 0` check could never fire and silently swallowed every
6386 // real failure, leaving the caller to poll for a device that was
6387 // never created.
6388 const int result = evdi.add_device();
6389 if (result != 1) {
6390 BOOST_LOG(warning) << "[VDISPLAY] evdi_add_device() failed (returned " << result << ").";
6391 return -1;
6392 }
6393
6394 BOOST_LOG(info) << "[VDISPLAY] Added EVDI device; waiting for its device index.";
6395 for (int attempt = 0; attempt < 125; ++attempt) {
6396 for (int i = 0; i < EVDI_DEVICE_SEARCH_LIMIT; ++i) {
6397 if (evdi.check_device(i) == EVDI_AVAILABLE) {
6398 BOOST_LOG(info) << "[VDISPLAY] EVDI device available at index " << i;
6399 return i;
6400 }
6401 }
6402 std::this_thread::sleep_for(std::chrono::milliseconds {20});
6403 }
6404
6405 BOOST_LOG(warning) << "[VDISPLAY] No EVDI device became available after creation. "
6406 << "Searched indices 0.." << (EVDI_DEVICE_SEARCH_LIMIT - 1) << '.';
6407 return -1;
6408 }
6409
6410 // libevdi numbers devices by their DRM card: evdi_check_device(N) and
6411 // evdi_open(N) use /dev/dri/cardN. That index is not the N of the evdi.N
6412 // platform device - the first EVDI device (evdi.0) is usually card1, and a
6413 // second one added later can become card0. Use the card the handle was opened
6414 // on, and fall back to the platform device for anything else.
6415 static int find_evdi_drm_card(int device_index) {
6416 {
6417 std::error_code ec;
6418 const fs::path card = "/sys/class/drm/card" + std::to_string(device_index);
6419 const auto module = fs::read_symlink(card / "device" / "driver" / "module", ec).filename().string();
6420 if (!ec && module == "evdi") {
6421 return device_index;
6422 }
6423 }
6424
6425 const auto expected_device = "evdi." + std::to_string(device_index);
6426 std::vector<int> evdi_cards;
6427
6428 try {
6429 for (const auto &entry : fs::directory_iterator("/sys/class/drm")) {
6430 const auto name = entry.path().filename().string();
6431 if (name.rfind("card", 0) != 0 || name.find('-') != std::string::npos) {
6432 continue;
6433 }
6434
6435 std::error_code ec;
6436 const auto device_path = fs::weakly_canonical(entry.path() / "device", ec);
6437 if (ec) {
6438 continue;
6439 }
6440
6441 const auto device_path_string = device_path.string();
6442 const auto module_link = entry.path() / "device" / "driver" / "module";
6443 const auto module = fs::read_symlink(module_link, ec).filename().string();
6444 if (ec || module != "evdi") {
6445 continue;
6446 }
6447
6448 const auto card_index = std::stoi(name.substr(4));
6449 if (device_path_string.find(expected_device) != std::string::npos) {
6450 return card_index;
6451 }
6452 evdi_cards.push_back(card_index);
6453 }
6454 } catch (const std::exception &e) {
6455 BOOST_LOG(warning) << "[VDISPLAY] Unable to inspect EVDI DRM devices: " << e.what();
6456 return -1;
6457 }
6458
6459 // Older EVDI kernels do not expose the evdi.N component in the sysfs
6460 // path. A single EVDI card is still unambiguous in that case.
6461 return evdi_cards.size() == 1 ? evdi_cards.front() : -1;
6462 }
6463
6464 static uint32_t normalize_refresh_rate(uint32_t refresh_rate) {
6465 // Apollo's stream path uses mHz, while the early encoder probe passes Hz.
6466 // Accept both forms so a probe cannot produce a 0 Hz EDID (or divide by 0).
6467 return refresh_rate > 0 && refresh_rate < 1000 ? refresh_rate * 1000 : refresh_rate;
6468 }
6469
6470 static void calculate_edid_checksum(unsigned char *edid, size_t block_size = 128) {
6471 uint8_t checksum = 0;
6472 for (size_t i = 0; i < block_size - 1; i++) {
6473 checksum += edid[i];
6474 }
6475 edid[block_size - 1] = 256 - checksum;
6476 }
6477
6478 static void create_detailed_timing_descriptor(unsigned char *dtd, uint32_t width, uint32_t height, uint32_t refresh_rate) {
6479 // Calculate timing parameters based on CVT (Coordinated Video Timings)
6480 // These are approximate values for common resolutions
6481
6482 uint32_t h_blank, v_blank, h_front, h_sync, v_front, v_sync;
6483
6484 // Blanking only. These are the standard industry timings for each
6485 // resolution and do not change with refresh rate — the refresh rate is
6486 // carried by the pixel clock, which is derived below.
6487 if (width == 3840 && height == 2160) {
6488 h_blank = 560;
6489 v_blank = 90;
6490 h_front = 176;
6491 h_sync = 88;
6492 v_front = 8;
6493 v_sync = 10;
6494 } else if (width == 2560 && height == 1440) {
6495 h_blank = 160;
6496 v_blank = 44;
6497 h_front = 48;
6498 h_sync = 32;
6499 v_front = 3;
6500 v_sync = 5;
6501 } else if (width == 1920 && height == 1080) {
6502 h_blank = 280;
6503 v_blank = 45;
6504 h_front = 88;
6505 h_sync = 44;
6506 v_front = 4;
6507 v_sync = 5;
6508 } else if (width == 1280 && height == 720) {
6509 h_blank = 370;
6510 v_blank = 30;
6511 h_front = 110;
6512 h_sync = 40;
6513 v_front = 5;
6514 v_sync = 5;
6515 } else if (width == 1280 && height == 800) {
6516 // Steam Deck native mode, CVT-RB blanking.
6517 h_blank = 160;
6518 v_blank = 23;
6519 h_front = 48;
6520 h_sync = 32;
6521 v_front = 3;
6522 v_sync = 6;
6523 } else {
6524 // Approximate CVT blanking for anything else.
6525 h_blank = static_cast<uint32_t>(width * 0.15);
6526 v_blank = 45;
6527 h_front = h_blank / 4;
6528 h_sync = h_blank / 4;
6529 v_front = 3;
6530 v_sync = 5;
6531 }
6532
6533 const uint32_t h_active = width;
6534 const uint32_t v_active = height;
6535 const uint32_t h_total = h_active + h_blank;
6536 const uint32_t v_total = v_active + v_blank;
6537
6538 // Derive the pixel clock from the requested refresh rate. Every entry above
6539 // used to carry its own hardcoded clock, and every one of them worked out to
6540 // 60 Hz, so the descriptor advertised a 60 Hz display no matter what the
6541 // client asked for — a request for 1080p120 produced a 1080p60 EDID.
6542 uint64_t pixel_clock_khz =
6543 (static_cast<uint64_t>(h_total) * v_total * std::max<uint32_t>(refresh_rate, 1)) / 1000;
6544
6545 // The descriptor stores the clock in 16 bits of 10 kHz units, so it cannot
6546 // express more than 655.35 MHz — 4K above about 66 Hz does not fit. Clamp to
6547 // the highest rate that does, rather than letting the value wrap into a
6548 // nonsense mode, and say so: silently getting a different refresh rate than
6549 // asked for is exactly the confusion this function used to cause.
6550 constexpr uint64_t max_dtd_clock_khz = 655350;
6551 if (pixel_clock_khz > max_dtd_clock_khz) {
6552 const uint32_t achievable_hz =
6553 static_cast<uint32_t>((max_dtd_clock_khz * 1000) / (static_cast<uint64_t>(h_total) * v_total));
6554 BOOST_LOG(warning) << "[VDISPLAY] "sv << width << 'x' << height << '@' << refresh_rate
6555 << "Hz needs a pixel clock a detailed timing descriptor cannot hold; "sv
6556 << "advertising "sv << achievable_hz << "Hz instead"sv;
6557 pixel_clock_khz = max_dtd_clock_khz;
6558 }
6559
6560 const uint16_t pixel_clock = static_cast<uint16_t>(pixel_clock_khz / 10);
6561
6562 // Detailed Timing Descriptor format (18 bytes)
6563 dtd[0] = pixel_clock & 0xFF;
6564 dtd[1] = (pixel_clock >> 8) & 0xFF;
6565
6566 dtd[2] = h_active & 0xFF;
6567 dtd[3] = h_blank & 0xFF;
6568 dtd[4] = ((h_active >> 8) & 0x0F) << 4 | ((h_blank >> 8) & 0x0F);
6569
6570 dtd[5] = v_active & 0xFF;
6571 dtd[6] = v_blank & 0xFF;
6572 dtd[7] = ((v_active >> 8) & 0x0F) << 4 | ((v_blank >> 8) & 0x0F);
6573
6574 dtd[8] = h_front & 0xFF;
6575 dtd[9] = h_sync & 0xFF;
6576 dtd[10] = ((v_front & 0x0F) << 4) | (v_sync & 0x0F);
6577 dtd[11] = (((h_front >> 8) & 0x03) << 6) | (((h_sync >> 8) & 0x03) << 4) |
6578 (((v_front >> 4) & 0x03) << 2) | ((v_sync >> 4) & 0x03);
6579
6580 // Physical size (approximate based on 27" diagonal for 4K, scaled for others)
6581 uint32_t h_size_mm = (width * 600) / 3840; // 600mm for 4K width
6582 uint32_t v_size_mm = (height * 340) / 2160; // 340mm for 4K height
6583 dtd[12] = h_size_mm & 0xFF;
6584 dtd[13] = v_size_mm & 0xFF;
6585 dtd[14] = ((h_size_mm >> 8) & 0x0F) << 4 | ((v_size_mm >> 8) & 0x0F);
6586
6587 dtd[15] = 0; // No border
6588 dtd[16] = 0; // No border
6589 dtd[17] = 0x1E; // Digital separate sync, positive H and V
6590 }
6591
6592 static unsigned char *generate_edid_for_resolution(uint32_t width, uint32_t height, uint32_t refresh_rate) {
6593 static unsigned char edid[256]; // Support for 1 extension block
6594 memset(edid, 0, sizeof(edid));
6595
6596 // Block 0: Base EDID
6597 // Header
6598 edid[0] = 0x00;
6599 edid[1] = 0xFF; edid[2] = 0xFF; edid[3] = 0xFF;
6600 edid[4] = 0xFF; edid[5] = 0xFF; edid[6] = 0xFF;
6601 edid[7] = 0x00;
6602
6603 // Manufacturer ID: "APL" (Apollo)
6604 edid[8] = 0x06; edid[9] = 0x4C;
6605
6606 // Product code
6607 edid[10] = 0x01; edid[11] = 0x00;
6608
6609 // Serial number
6610 edid[12] = 0x01; edid[13] = 0x00; edid[14] = 0x00; edid[15] = 0x00;
6611
6612 // Week and year of manufacture (week 1, 2024)
6613 edid[16] = 0x01; edid[17] = 0x22;
6614
6615 // EDID version 1.4
6616 edid[18] = 0x01; edid[19] = 0x04;
6617
6618 // Video input: Digital, 8-bit color, DisplayPort
6619 edid[20] = 0xB5;
6620
6621 // Screen size (cm) - approximate for 27"
6622 edid[21] = 60; // 60 cm wide
6623 edid[22] = 34; // 34 cm tall
6624
6625 // Gamma (2.2)
6626 edid[23] = 0x78;
6627
6628 // Features: RGB, preferred timing in DTD1
6629 edid[24] = 0x3A;
6630
6631 // Chromaticity coordinates (standard sRGB)
6632 edid[25] = 0xFC; edid[26] = 0x81; edid[27] = 0xA4; edid[28] = 0x55;
6633 edid[29] = 0x4D; edid[30] = 0x9D; edid[31] = 0x25; edid[32] = 0x12;
6634 edid[33] = 0x50; edid[34] = 0x54;
6635
6636 // Advertise only the requested DTD mode. Extra established/standard
6637 // timings become misleading choices in a game's display settings.
6638 edid[35] = 0x00; edid[36] = 0x00; edid[37] = 0x00;
6639 for (int i = 38; i < 54; i += 2) {
6640 edid[i] = 0x01;
6641 edid[i + 1] = 0x01;
6642 }
6643
6644 // Detailed Timing Descriptor 1 (preferred timing)
6645 create_detailed_timing_descriptor(&edid[54], width, height, refresh_rate);
6646
6647 // Descriptor 2: Display name
6648 edid[72] = 0x00; edid[73] = 0x00; edid[74] = 0x00; edid[75] = 0xFC; edid[76] = 0x00;
6649 const char *name = "APOLLO VDISP";
6650 for (int i = 0; i < 13 && name[i]; i++) {
6651 edid[77 + i] = name[i];
6652 }
6653 edid[89] = '\n';
6654
6655 // Descriptor 3: Display range limits
6656 edid[90] = 0x00; edid[91] = 0x00; edid[92] = 0x00; edid[93] = 0xFD; edid[94] = 0x00;
6657 edid[95] = 0x18; // Min V rate: 24 Hz
6658 edid[96] = 0x78; // Max V rate: 120 Hz
6659 edid[97] = 0x0F; // Min H rate: 15 kHz
6660 edid[98] = 0xA0; // Max H rate: 160 kHz
6661 edid[99] = 0x78; // Max pixel clock: 1200 MHz (for 4K@120Hz support)
6662 edid[100] = 0x00; // GTF support
6663 edid[101] = 0x0A; // Newline padding
6664 for (int i = 102; i < 108; i++) edid[i] = 0x20; // Space padding
6665
6666 // Descriptor 4: Dummy/unused
6667 edid[108] = 0x00; edid[109] = 0x00; edid[110] = 0x00; edid[111] = 0x10; edid[112] = 0x00;
6668 for (int i = 113; i < 126; i++) edid[i] = 0x20;
6669
6670 // Extension flag: 1 extension block (for resolutions > 1080p)
6671 bool needs_extension = (width > 1920 || height > 1080);
6672 edid[126] = needs_extension ? 0x01 : 0x00;
6673
6674 // Calculate checksum for block 0
6675 calculate_edid_checksum(edid, 128);
6676
6677 // Block 1: CEA-861 Extension (for 4K support)
6678 if (needs_extension) {
6679 edid[128] = 0x02; // CEA extension tag
6680 edid[129] = 0x03; // Revision 3
6681 edid[130] = 0x18; // DTD offset (24 bytes for data blocks)
6682 edid[131] = 0x72; // Native DTDs, YCbCr support
6683
6684 // Video Data Block
6685 edid[132] = 0x47; // Video tag (0x40) + length (7)
6686 edid[133] = 0x90; // VIC 16: 1080p60 (native)
6687 edid[134] = 0x04; // VIC 4: 720p60
6688 edid[135] = 0x03; // VIC 3: 480p60
6689 edid[136] = 0x5F; // VIC 95: 4K@60Hz (VIC 95)
6690 edid[137] = 0x60; // VIC 96: 4K@60Hz (VIC 96)
6691 edid[138] = 0x61; // VIC 97: 4K@60Hz (VIC 97)
6692 edid[139] = 0x65; // VIC 101: 4K@120Hz
6693
6694 // HDMI Vendor Specific Data Block
6695 edid[140] = 0x67; // Vendor tag (0x60) + length (7)
6696 edid[141] = 0x03; // IEEE OUI for HDMI (0x000C03)
6697 edid[142] = 0x0C;
6698 edid[143] = 0x00;
6699 edid[144] = 0x10; // Source physical address
6700 edid[145] = 0x00;
6701 edid[146] = 0x00; // Supports AI, DC 48/36/30 bit
6702 edid[147] = 0x78; // Max TMDS clock / 5 MHz = 600 MHz
6703
6704 // Detailed Timing Descriptor for 4K if needed
6705 if (width >= 3840) {
6706 create_detailed_timing_descriptor(&edid[152], 3840, 2160, 60);
6707 }
6708
6709 // Calculate checksum for block 1
6710 calculate_edid_checksum(&edid[128], 128);
6711 }
6712
6713 return edid;
6714 }
6715
6716 // Drain libevdi events promptly. Besides delivering pixels into EvdiBuffer,
6717 // evdi_grab_pixels acknowledges the pageflip to the EVDI kernel driver; if
6718 // no consumer does that, compositors can stall on timed-out pageflips.
6719 static void evdi_events_loop() {
6720 evdi_event_context event_context {};
6721 event_context.update_ready_handler = [](int, void *) {};
6722 constexpr int max_rects = 16;
6723 constexpr auto min_grab_interval = std::chrono::microseconds {4167};
6724 constexpr auto max_grab_interval = std::chrono::microseconds {16667};
6725 evdi_rect rects[max_rects];
6726 std::map<evdi_handle, std::chrono::steady_clock::time_point> next_grab_by_handle;
6727 constexpr auto max_pending = std::chrono::seconds {1};
6728 std::map<evdi_handle, std::chrono::steady_clock::time_point> pending_since;
6729
6730 while (evdi_events_running) {
6731 {
6732 std::lock_guard<std::mutex> lock(vdisplay_mutex);
6733 std::set<evdi_handle> active_handles;
6734 const auto now = std::chrono::steady_clock::now();
6735
6736 for (auto &[guid, display] : virtual_displays) {
6737 if (!display.using_evdi || !display.handle || !display.evdi_buffer || display.evdi_buffer_id <= 0) {
6738 continue;
6739 }
6740 active_handles.insert(display.handle);
6741
6742 const auto next_grab = next_grab_by_handle.find(display.handle);
6743 if (next_grab != next_grab_by_handle.end() && next_grab->second > now) {
6744 continue;
6745 }
6746
6747 pollfd poll_fd {};
6748 poll_fd.fd = evdi.get_event_ready(display.handle);
6749 poll_fd.events = POLLIN;
6750 if (poll_fd.fd >= 0 && ::poll(&poll_fd, 1, 0) > 0 && (poll_fd.revents & POLLIN)) {
6751 evdi.handle_events(display.handle, &event_context);
6752 pending_since.erase(display.handle);
6753 } else {
6754 // While a request is pending the driver answers it with an event,
6755 // and logs a warning for every repeated request, so ask again only
6756 // if the answer seems lost.
6757 const auto pending = pending_since.find(display.handle);
6758 if (pending != pending_since.end() && now - pending->second < max_pending) {
6759 continue;
6760 }
6761 if (!evdi.request_update(display.handle, display.evdi_buffer_id)) {
6762 pending_since[display.handle] = now;
6763 continue;
6764 }
6765 pending_since.erase(display.handle);
6766 }
6767 // A true return means a frame is already waiting. The driver sends no
6768 // event for it, so it has to be grabbed now: otherwise its pageflip is
6769 // never acknowledged and the display server stalls on every commit.
6770
6771 int rect_count = max_rects;
6772 display.evdi_buffer->begin_write();
6773 evdi.grab_pixels(display.handle, rects, &rect_count);
6774 display.evdi_buffer->end_write();
6775 display.evdi_buffer->mark_updated();
6776 if (!evdi.request_update(display.handle, display.evdi_buffer_id)) {
6777 pending_since[display.handle] = now;
6778 }
6779 const auto refresh_rate = std::max<uint32_t>(display.fps, 1);
6780 const auto session_interval = std::chrono::microseconds {1000000 / refresh_rate};
6781 next_grab_by_handle[display.handle] = now + std::clamp(session_interval, min_grab_interval, max_grab_interval);
6782 }
6783
6784 for (auto it = next_grab_by_handle.begin(); it != next_grab_by_handle.end();) {
6785 if (!active_handles.contains(it->first)) {
6786 it = next_grab_by_handle.erase(it);
6787 } else {
6788 ++it;
6789 }
6790 }
6791 std::erase_if(pending_since, [&](const auto &entry) {
6792 return !active_handles.contains(entry.first);
6793 });
6794 }
6795
6796 // A 1 ms pump keeps pageflip-to-capture wakeup below one millisecond
6797 // without busy-spinning when no virtual session is active.
6798 std::this_thread::sleep_for(std::chrono::milliseconds {1});
6799 }
6800 }
6801
6802 static void start_evdi_events_thread() {
6803 if (evdi_events_running.exchange(true)) {
6804 return;
6805 }
6806 evdi_events_thread = std::thread(evdi_events_loop);
6807 }
6808
6809 static void stop_evdi_events_thread() {
6810 evdi_events_running = false;
6811 if (evdi_events_thread.joinable()) {
6812 evdi_events_thread.join();
6813 }
6814 }
6815
6816 // ============================================================================
6817 // Public API Implementation
6818 // ============================================================================
6819
6821 std::lock_guard<std::mutex> lifecycle_lock(vdisplay_lifecycle_mutex);
6822 std::lock_guard<std::mutex> lock(vdisplay_mutex);
6823
6824 if (driver_status == DRIVER_STATUS::OK) {
6825 return driver_status;
6826 }
6827
6828 const auto backend = selected_backend();
6829 BOOST_LOG(info) << "[VDISPLAY] Initializing Linux virtual display driver with " << backend_name(backend) << " backend...";
6830
6831 // Nothing to open, nothing to diagnose, and above all nothing to warn
6832 // about: a host configured for no virtual-display device is not a host with
6833 // a broken one. Returning before the EVDI machinery runs is what keeps it
6834 // from reporting a missing library the deployment never wanted.
6835 if (backend == VirtualDisplayBackend::NONE) {
6836 evdi_available = false;
6837 unload_evdi_library();
6838 BOOST_LOG(info) << "[VDISPLAY] No virtual-display backend is configured; Hermes will only "
6839 "stream outputs the session already has.";
6840 driver_status = DRIVER_STATUS::NOT_SUPPORTED;
6841 return driver_status;
6842 }
6843
6844 kscreen::recover_on_startup();
6845 mutter::recover_on_startup();
6846
6847 if (backend == VirtualDisplayBackend::HERMES_KMS) {
6848 evdi_available = false;
6849 unload_evdi_library();
6850 if (!hermes_kms::available()) {
6851 BOOST_LOG(warning) << "[VDISPLAY/Hermes-KMS] Hermes-KMS is unavailable; virtual-display sessions are disabled.";
6852 driver_status = DRIVER_STATUS::NOT_SUPPORTED;
6853 return driver_status;
6854 }
6855
6856 std::vector<std::string> boot_connectors;
6857 if (hermes_kms::disconnect_unowned_outputs(boot_connectors)) {
6858 for (const auto &connector : boot_connectors) {
6859 // Each helper no-ops when its compositor is not the running one.
6860 kscreen::recover_after_unowned_virtual_disconnect(connector);
6861 mutter::recover_after_unowned_virtual_disconnect(connector);
6862 }
6863 }
6864
6865 // Cards outlive the process that asked for one. This Hermes owns none
6866 // yet, so anything still standing in its name is from a run that died.
6867 if (card_broker::available()) {
6869 }
6870
6871 driver_status = DRIVER_STATUS::OK;
6872 device_open = true;
6873 BOOST_LOG(info) << "[VDISPLAY/Hermes-KMS] Hermes-KMS available - experimental zero-copy virtual display supported"
6874 << (hermes_kms::multi_output_requested() ? " with session-scoped multi-output enabled." : ".");
6875 return driver_status;
6876 }
6877
6878 if (backend == VirtualDisplayBackend::HYPRLAND_HEADLESS) {
6879 evdi_available = false;
6880 unload_evdi_library();
6881 if (!hyprland::available()) {
6882 hyprland::log_unreachable(false);
6883 driver_status = DRIVER_STATUS::NOT_SUPPORTED;
6884 return driver_status;
6885 }
6886
6887 driver_status = DRIVER_STATUS::OK;
6888 device_open = true;
6889 BOOST_LOG(info) << "[VDISPLAY] Hyprland headless output backend available - virtual displays supported.";
6890 return driver_status;
6891 }
6892
6893 // Try to load EVDI library
6894 evdi_available = load_evdi_library();
6895
6896 if (evdi_available) {
6897 // Check if kernel module is loaded
6898 if (!check_evdi_module_loaded()) {
6899 BOOST_LOG(warning) << "[VDISPLAY] EVDI library loaded but kernel module not available.";
6900 BOOST_LOG(warning) << "[VDISPLAY] Virtual displays are unavailable until the module is loaded.";
6901 evdi_available = false;
6902 unload_evdi_library();
6903 }
6904 }
6905
6906 if (evdi_available) {
6907 BOOST_LOG(info) << "[VDISPLAY] EVDI available - real virtual displays supported!";
6908 } else {
6909 BOOST_LOG(warning) << "[VDISPLAY] EVDI is unavailable; virtual-display sessions are disabled.";
6910 BOOST_LOG(warning) << "[VDISPLAY] Install libevdi and load the evdi kernel module, then restart Hermes.";
6911 driver_status = DRIVER_STATUS::NOT_SUPPORTED;
6912 return driver_status;
6913 }
6914
6915 driver_status = DRIVER_STATUS::OK;
6916 device_open = true;
6917 BOOST_LOG(info) << "[VDISPLAY] Linux virtual display driver initialized successfully.";
6918
6919 return driver_status;
6920 }
6921
6923 // Idempotent: the watchdog failure path, an explicit shutdown and proc's
6924 // deinit_t can all reach this. Tearing down twice would re-run set_output()
6925 // and ::close() on drm_fds that were already released.
6926 if (!device_open.exchange(false)) {
6927 return;
6928 }
6929
6930 BOOST_LOG(info) << "[VDISPLAY] Closing Linux virtual display driver...";
6931 // Before the displays go: the watch outlives any single one of them,
6932 // and its thread holds a bus connection.
6933 mutter::unwatch_layout();
6934
6935 // Stop watchdog thread
6936 watchdog_running = false;
6937 if (watchdog_thread.joinable()) {
6938 // The watchdog can call the failure callback itself. Joining the current
6939 // thread would throw, while joining while holding vdisplay_mutex can
6940 // deadlock with a watchdog which is just checking a display.
6941 if (watchdog_thread.get_id() == std::this_thread::get_id()) {
6942 watchdog_thread.detach();
6943 } else {
6944 watchdog_thread.join();
6945 }
6946 }
6947 std::lock_guard<std::mutex> lifecycle_lock(vdisplay_lifecycle_mutex);
6948 std::unique_lock<std::mutex> lock(vdisplay_mutex);
6949
6950 release_parked_locked("Hermes is shutting down.");
6951 while (!virtual_displays.empty()) {
6952 const auto guid = virtual_displays.begin()->first;
6953 remove_virtual_display_locked(guid, lock, true);
6954 }
6955 // An orphaned layout can remain after a post-hotplug verification failure.
6956 lock.unlock();
6957 kscreen::retry_pending_restores();
6958 stop_evdi_events_thread();
6959 lock.lock();
6960
6961 // Unload EVDI library
6962 unload_evdi_library();
6963
6964 driver_status = DRIVER_STATUS::UNKNOWN;
6965 BOOST_LOG(info) << "[VDISPLAY] Linux virtual display driver closed.";
6966 }
6967
6968 bool startPingThread(std::function<void()> failCb) {
6969 std::lock_guard<std::mutex> lock(vdisplay_mutex);
6970
6971 if (watchdog_running) {
6972 return true;
6973 }
6974
6975 watchdog_running = true;
6976
6977 watchdog_thread = std::thread([failCb = std::move(failCb)]() {
6978 BOOST_LOG(debug) << "[VDISPLAY] Watchdog thread started.";
6979
6980 while (watchdog_running) {
6981 std::this_thread::sleep_for(5s);
6982
6983 if (!watchdog_running) {
6984 break;
6985 }
6986
6987 bool display_lost = false;
6988 std::vector<std::string> pending_removals;
6989 {
6990 std::lock_guard<std::mutex> lock(vdisplay_mutex);
6991 // The output kept for the greeter has done its job once a user
6992 // session is in front: a desktop survives losing an output, and left
6993 // connected it would stay on that desktop as a monitor nobody asked for.
6994 if (parked_display && greeter_holds_seat() == std::optional<bool> {false}) {
6995 release_parked_locked("the greeter no longer holds the seat.");
6996 }
6997 for (const auto &[guid, vdinfo] : virtual_displays) {
6998 if (vdinfo.removal_pending) {
6999 pending_removals.push_back(guid);
7000 continue;
7001 }
7002 if (vdinfo.active && vdinfo.using_evdi && vdinfo.handle) {
7003 // Check EVDI device health
7004 int ready = evdi.get_event_ready(vdinfo.handle);
7005 if (ready < 0) {
7006 BOOST_LOG(error) << "[VDISPLAY] Virtual display " << vdinfo.name << " lost!";
7007 display_lost = true;
7008 break;
7009 }
7010 } else if (vdinfo.active && vdinfo.using_hermes_kms && vdinfo.drm_fd >= 0) {
7011 hermes_kms::status_t status {};
7012 if (!hermes_kms::get_status(vdinfo.drm_fd, status)) {
7013 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] Virtual display " << vdinfo.name << " lost!";
7014 display_lost = true;
7015 break;
7016 }
7017 }
7018 }
7019 }
7020
7021 {
7022 std::lock_guard<std::mutex> lifecycle_lock(vdisplay_lifecycle_mutex);
7023 // Compositor calls must not hold vdisplay_mutex: EVDI needs its
7024 // event pump to acknowledge pageflips during output transitions.
7025 kscreen::retry_pending_restores();
7026 std::unique_lock<std::mutex> lock(vdisplay_mutex);
7027 for (const auto &guid : pending_removals) {
7028 if (virtual_displays.contains(guid)) {
7029 remove_virtual_display_locked(guid, lock);
7030 }
7031 }
7032 }
7033
7034 if (display_lost) {
7035 if (failCb) {
7036 failCb();
7037 }
7038 return;
7039 }
7040 }
7041
7042 BOOST_LOG(debug) << "[VDISPLAY] Watchdog thread stopped.";
7043 });
7044
7045 return true;
7046 }
7047
7048 bool setRenderAdapterByName(const std::string &adapterName) {
7049 std::lock_guard<std::mutex> lock(vdisplay_mutex);
7050
7051 if (adapterName.empty()) {
7052 BOOST_LOG(debug) << "[VDISPLAY] No specific adapter requested.";
7053 return true;
7054 }
7055
7056 BOOST_LOG(info) << "[VDISPLAY] Adapter hint: " << adapterName;
7057 // On Linux, we don't need to select specific adapters for EVDI
7058 return true;
7059 }
7060
7062 const char *s_client_uid,
7063 const char *s_client_name,
7064 uint32_t width,
7065 uint32_t height,
7066 uint32_t fps,
7067 const uuid_util::uuid_t &guid,
7068 std::optional<uid_t> session_owner_uid,
7070 bool isolated_session
7071 ) {
7072 std::lock_guard<std::mutex> lifecycle_lock(vdisplay_lifecycle_mutex);
7073 if (!kscreen::retry_pending_restores()) {
7074 BOOST_LOG(error) << "[VDISPLAY/KScreen] A physical output restoration is still pending; delaying virtual display creation.";
7075 return {};
7076 }
7077 std::unique_lock<std::mutex> lock(vdisplay_mutex);
7078 std::vector<std::string> pending_removals;
7079 for (const auto &[name, display] : virtual_displays) {
7080 if (display.removal_pending) {
7081 pending_removals.push_back(name);
7082 }
7083 }
7084 for (const auto &name : pending_removals) {
7085 if (!remove_virtual_display_locked(name, lock)) {
7086 BOOST_LOG(error) << "[VDISPLAY] A previous virtual display is still being released.";
7087 return {};
7088 }
7089 }
7090
7091 if (driver_status != DRIVER_STATUS::OK) {
7092 BOOST_LOG(error) << "[VDISPLAY] Driver not initialized.";
7093 return "";
7094 }
7095
7096 std::string guid_str = guid.string();
7097 if (virtual_displays.contains(guid_str)) {
7098 BOOST_LOG(error) << "[VDISPLAY] Client already owns an active virtual display: " << guid_str;
7099 return "";
7100 }
7101 std::string display_name = generate_display_name(guid);
7102
7103 fps = normalize_refresh_rate(fps);
7104 const uint32_t fps_hz = fps / 1000;
7105
7106 if (width == 0 || height == 0 || fps_hz == 0) {
7107 BOOST_LOG(error) << "[VDISPLAY] Refusing invalid virtual display mode "
7108 << width << 'x' << height << '@' << fps_hz << "Hz";
7109 return "";
7110 }
7111
7112 BOOST_LOG(info) << "[VDISPLAY] Creating virtual display: " << display_name
7113 << " (W: " << width << ", H: " << height << ", FPS: " << fps_hz << ")";
7114 BOOST_LOG(info) << "[VDISPLAY] Client: " << s_client_name << " (" << s_client_uid << ")";
7115
7116 VirtualDisplayInfo vdinfo;
7117 vdinfo.name = display_name;
7118 vdinfo.guid_str = guid_str;
7119 vdinfo.client_name = s_client_name ? s_client_name : "";
7120 vdinfo.width = width;
7121 vdinfo.height = height;
7122 vdinfo.fps = fps;
7123 vdinfo.device_index = -1;
7124 vdinfo.session_index = -1;
7125 vdinfo.output_index = -1;
7126 vdinfo.drm_card_index = -1;
7127 vdinfo.handle = nullptr;
7128 vdinfo.drm_fd = -1;
7129 vdinfo.active = true;
7130 vdinfo.using_evdi = false;
7131 vdinfo.using_hermes_kms = false;
7132 vdinfo.hermes_kms_session_lifecycle = false;
7133 vdinfo.broker_card.clear();
7134 vdinfo.using_hyprland_headless = false;
7135 vdinfo.session_id = 0;
7136 vdinfo.session_token = {};
7137 vdinfo.evdi_buffer_id = 0;
7138 vdinfo.layout = layout;
7139
7140 const auto backend = selected_backend();
7141
7142 if (backend == VirtualDisplayBackend::NONE) {
7143 BOOST_LOG(error) << "[VDISPLAY] A virtual display was requested but no virtual-display backend "
7144 "is configured. Set virtual_display_backend to evdi or hermes_kms, or stream "
7145 "an output the session already has.";
7146 return "";
7147 }
7148
7149 // Hyprland owns its headless outputs; there is no DRM device to claim, no
7150 // connector to hotplug and no kscreen layout to diff, so this returns
7151 // before any of that runs. The mode is not set here: Hyprland publishes the
7152 // output at its own default and takes the client's geometry through
7153 // wlr-output-management, which activateVirtualDisplayOutput() already
7154 // drives for every wlr session.
7155 if (backend == VirtualDisplayBackend::HYPRLAND_HEADLESS) {
7156 if (!hyprland::available()) {
7157 hyprland::log_unreachable(true);
7158 return "";
7159 }
7160
7161 const auto output = hyprland::create_headless();
7162 if (!output) {
7163 return "";
7164 }
7165
7166 vdinfo.connector_name = *output;
7167 vdinfo.using_hyprland_headless = true;
7168 virtual_displays[guid_str] = vdinfo;
7169
7170 BOOST_LOG(info) << "[VDISPLAY] Hyprland created headless output " << *output << " for " << display_name
7171 << "; it renders on the primary GPU, so no virtual DRM device is involved.";
7172 return display_name;
7173 }
7174
7175 const auto kscreen_before = kscreen::outputs();
7176
7177 if (backend == VirtualDisplayBackend::HERMES_KMS) {
7178 hermes_kms::device_t device {};
7179 uint64_t session_id = 0;
7180 bool claimed = false;
7181 bool adopted = false;
7182 std::array<uint64_t, 2> session_token {};
7183
7184 // An output kept connected for the login greeter is the one this display
7185 // has to use: releasing it to claim a fresh one would be the very unplug
7186 // it was kept to avoid. It is already owned and lit, so only the mode and
7187 // a capability for the new consumers are needed.
7188 if (parked_display && !isolated_session) {
7189 uint64_t parked_session = parked_display->session_id;
7190 bool mode_set = false;
7191 // The driver rate-limits output changes; like a fresh claim, a refusal
7192 // for that reason is worth a moment's patience.
7193 for (unsigned int attempt = 0; attempt < 6 && !mode_set; ++attempt) {
7194 mode_set = hermes_kms::set_output(parked_display->drm_fd, true, width, height, fps_hz, parked_session, false);
7195 if (!mode_set) {
7196 if (errno != EAGAIN) {
7197 break;
7198 }
7199 std::this_thread::sleep_for(std::chrono::milliseconds {200});
7200 }
7201 }
7202 if (mode_set &&
7203 parked_session == parked_display->session_id &&
7204 hermes_kms::get_session_token(
7205 parked_display->drm_fd,
7206 static_cast<uint32_t>(parked_display->output_index),
7207 parked_session,
7208 session_token
7209 )) {
7210 const auto parked = std::move(*parked_display);
7211 parked_display.reset();
7212 vdinfo.drm_fd = parked.drm_fd;
7213 vdinfo.device_index = parked.device_index;
7214 vdinfo.session_index = parked.session_index;
7215 vdinfo.output_index = parked.output_index;
7216 vdinfo.drm_card_index = parked.drm_card_index;
7217 vdinfo.session_id = parked.session_id;
7218 vdinfo.session_token = session_token;
7219 vdinfo.using_hermes_kms = true;
7220 vdinfo.hermes_kms_session_lifecycle = parked.hermes_kms_session_lifecycle;
7221 vdinfo.connector_name = parked.connector_name;
7222 vdinfo.name = parked.name;
7223 display_name = parked.name;
7224 adopted = true;
7225 BOOST_LOG(info) << "[VDISPLAY/Hermes-KMS] Reusing " << display_name << " (connector "
7226 << vdinfo.connector_name << "), which was kept connected for the login greeter, at "
7227 << width << 'x' << height << '@' << fps_hz;
7228 } else {
7229 release_parked_locked("it could not be handed to the new session, so a fresh output is claimed instead.");
7230 }
7231 }
7232
7233 if (adopted) {
7234 // Nothing to claim.
7235 } else if (isolated_session) {
7236 claimed = hermes_kms::claim_available_device_output(
7237 device,
7238 width,
7239 height,
7240 fps_hz,
7241 session_id,
7242 vdinfo.broker_card,
7243 session_owner_uid
7244 );
7245 } else if (hermes_kms::open_device(device, true)) {
7246 claimed = hermes_kms::claim_available_output(
7247 device,
7248 width,
7249 height,
7250 fps_hz,
7251 session_id
7252 );
7253 }
7254
7255 if (claimed && !hermes_kms::get_session_token(
7256 device.fd,
7257 device.selected_output_index,
7258 session_id,
7259 session_token
7260 )) {
7261 hermes_kms::set_output(device.fd, false, 0, 0, 0, session_id, false);
7262 claimed = false;
7263 }
7264 if (!claimed && !vdinfo.broker_card.empty()) {
7265 // The card was created for this display and this display is not
7266 // happening; leaving it would hold a private seat for nothing.
7267 card_broker::remove(vdinfo.broker_card);
7268 vdinfo.broker_card.clear();
7269 }
7270
7271 if (claimed) {
7272 hermes_kms::status_t status {};
7273 hermes_kms::get_status(device.fd, status);
7274 vdinfo.drm_fd = device.fd;
7275 device.fd = -1;
7276 vdinfo.device_index = device.version.uapi_version >= hermes_kms::multi_device_uapi_version ?
7277 static_cast<int>(device.identity.device_index) :
7278 0;
7279 vdinfo.session_index =
7280 device.version.uapi_version >= hermes_kms::session_device_uapi_version &&
7281 device.identity.device_role == hermes_kms::device_role_session ?
7282 static_cast<int>(device.identity.session_index) :
7283 -1;
7284 vdinfo.output_index = static_cast<int>(device.selected_output_index);
7285 vdinfo.drm_card_index = device.card_index;
7286 vdinfo.session_id = session_id;
7287 vdinfo.session_token = session_token;
7288 vdinfo.using_hermes_kms = true;
7289 vdinfo.hermes_kms_session_lifecycle =
7290 (device.caps.flags & hermes_kms::cap_session_lifecycle) != 0;
7291 vdinfo.connector_name = hermes_kms::cstr(device.identity.connector_name);
7292 display_name = hermes_kms::cstr(device.identity.output_name);
7293 if (display_name.empty()) {
7294 display_name = "HERMES-1";
7295 }
7296 vdinfo.name = display_name;
7297 BOOST_LOG(info) << "[VDISPLAY/Hermes-KMS] Connected " << display_name
7298 << " device=" << (vdinfo.device_index + 1)
7299 << " session_device=" << vdinfo.session_index
7300 << " output=" << (vdinfo.output_index + 1)
7301 << " connector=" << vdinfo.connector_name
7302 << " card=" << vdinfo.drm_card_index
7303 << " session=" << vdinfo.session_id
7304 << " requested=" << status.requested_width << 'x' << status.requested_height
7305 << '@' << status.requested_refresh_hz
7306 << " flags=0x" << std::hex << status.flags << std::dec;
7307 if (!isolated_session &&
7308 !vdinfo.connector_name.empty()) {
7309 kscreen::activate_evdi_output(
7310 vdinfo.name,
7311 kscreen_before,
7312 vdinfo.connector_name,
7313 "Hermes-KMS",
7314 static_cast<int>(vdinfo.width),
7315 static_cast<int>(vdinfo.height),
7316 static_cast<int>(vdinfo.fps / 1000),
7317 vdinfo.layout
7318 );
7319 }
7320 }
7321 hermes_kms::forget_secret(session_token.data(), sizeof(session_token));
7322 hermes_kms::close_device(device);
7323 } else if (evdi_available) {
7324 // Create real virtual display using EVDI
7325 int device = find_available_evdi_device();
7326 if (device >= 0) {
7327 evdi_handle handle = evdi.open(device);
7328 if (handle) {
7329 // Generate EDID for requested resolution
7330 unsigned char *edid = generate_edid_for_resolution(width, height, fps_hz);
7331
7332 // Determine EDID size (128 for base, 256 with extension for 4K)
7333 unsigned int edid_size = (width > 1920 || height > 1080) ? 256 : 128;
7334
7335 // Connect with EDID (no area limit)
7336 BOOST_LOG(info) << "[VDISPLAY] Connecting with " << edid_size << "-byte EDID for " << width << "x" << height;
7337 evdi.connect(handle, edid, edid_size, 0);
7338
7339 // The DRM node is added asynchronously after connect(). Poll at a
7340 // short interval: this is on the stream-start critical path, so the
7341 // former 100 ms sleep made a ready display wait unnecessarily.
7342 for (int attempt = 0; attempt < 25 && vdinfo.drm_card_index < 0; ++attempt) {
7343 vdinfo.drm_card_index = find_evdi_drm_card(device);
7344 if (vdinfo.drm_card_index < 0) {
7345 std::this_thread::sleep_for(std::chrono::milliseconds {20});
7346 }
7347 }
7348
7349 if (vdinfo.drm_card_index >= 0) {
7350 vdinfo.device_index = device;
7351 vdinfo.handle = handle;
7352 vdinfo.using_evdi = true;
7353 const std::string card_path = "/dev/dri/card" + std::to_string(vdinfo.drm_card_index);
7354 display_name = "VIRTUAL-card" + std::to_string(vdinfo.drm_card_index);
7355 vdinfo.name = display_name;
7356
7357 vdinfo.evdi_buffer = std::make_shared<EvdiBuffer>(width, height);
7358 vdinfo.evdi_buffer_id = 1;
7359 evdi_buffer buffer {};
7360 buffer.id = vdinfo.evdi_buffer_id;
7361 buffer.buffer = vdinfo.evdi_buffer->raw_buffer();
7362 buffer.width = static_cast<int>(width);
7363 buffer.height = static_cast<int>(height);
7364 buffer.stride = static_cast<int>(vdinfo.evdi_buffer->stride());
7365 buffer.rects = nullptr;
7366 buffer.rect_count = 0;
7367 evdi.register_buffer(handle, buffer);
7368 evdi.request_update(handle, vdinfo.evdi_buffer_id);
7369 BOOST_LOG(info) << "[VDISPLAY] Created EVDI virtual display on device " << device
7370 << " (" << card_path << ')';
7371
7372 // KWin must own the DRM card and explicitly enable the hotplugged
7373 // EVDI connector. Opening card_path here races for DRM master and
7374 // prevents KWin from ever exposing the output to KScreen.
7375 kscreen::activate_evdi_output(
7376 vdinfo.name,
7377 kscreen_before,
7378 evdi_connector_name(vdinfo.drm_card_index),
7379 "EVDI",
7380 static_cast<int>(vdinfo.width),
7381 static_cast<int>(vdinfo.height),
7382 static_cast<int>(vdinfo.fps / 1000),
7383 vdinfo.layout
7384 );
7385 } else {
7386 BOOST_LOG(error) << "[VDISPLAY] EVDI connected but no matching DRM card appeared.";
7387 evdi.disconnect(handle);
7388 evdi.close(handle);
7389 }
7390 } else {
7391 BOOST_LOG(warning) << "[VDISPLAY] Failed to open EVDI device " << device;
7392 }
7393 } else {
7394 BOOST_LOG(warning) << "[VDISPLAY] No available EVDI device.";
7395 }
7396 }
7397
7398 if (!vdinfo.using_evdi && !vdinfo.using_hermes_kms) {
7399 BOOST_LOG(error) << "[VDISPLAY] Failed to create a usable " << backend_name(backend) << " virtual display.";
7400 return "";
7401 }
7402
7403 const bool using_evdi = vdinfo.using_evdi;
7404 virtual_displays.emplace(guid_str, std::move(vdinfo));
7405 hermes_kms::forget_secret(vdinfo.session_token.data(), sizeof(vdinfo.session_token));
7406 if (using_evdi) {
7407 start_evdi_events_thread();
7408 }
7409
7410 BOOST_LOG(info) << "[VDISPLAY] Virtual display created successfully: " << display_name;
7411 BOOST_LOG(info) << "[VDISPLAY] Mode: " << backend_name(backend) << " (real virtual display)";
7412
7413 return display_name;
7414 }
7415
7416 static bool remove_virtual_display_locked(
7417 const std::string &guid_str,
7418 std::unique_lock<std::mutex> &lock,
7419 bool shutting_down
7420 ) {
7421 auto it = virtual_displays.find(guid_str);
7422 if (it == virtual_displays.end()) {
7423 BOOST_LOG(warning) << "[VDISPLAY] Virtual display not found: " << guid_str;
7424 return false;
7425 }
7426
7427 auto &vdinfo = it->second;
7428 BOOST_LOG(info) << "[VDISPLAY] Removing virtual display: " << vdinfo.name;
7429 vdinfo.removal_pending = true;
7430 // Keep the owner fd and virtual output alive until physical restoration
7431 // is confirmed. Release the registry lock while KWin applies its layout,
7432 // so EVDI pageflips and status queries can continue to make progress.
7433 lock.unlock();
7434 const bool physical_restored = kscreen::restore(vdinfo.name, false);
7435 lock.lock();
7436 if (!physical_restored && !shutting_down) {
7437 BOOST_LOG(warning) << "[VDISPLAY] Deferring removal of " << vdinfo.name
7438 << " until physical output restoration can be confirmed.";
7439 return false;
7440 }
7441 if (!physical_restored) {
7442 BOOST_LOG(warning) << "[VDISPLAY] Physical output restoration remains pending at shutdown; "
7443 "the saved layout will be retried on startup.";
7444 }
7445
7446 if (vdinfo.using_evdi && vdinfo.handle) {
7447 if (vdinfo.evdi_buffer_id > 0) {
7448 evdi.unregister_buffer(vdinfo.handle, vdinfo.evdi_buffer_id);
7449 }
7450 evdi.disconnect(vdinfo.handle);
7451 evdi.close(vdinfo.handle);
7452 }
7453 if (vdinfo.using_hermes_kms && vdinfo.drm_fd >= 0) {
7454 // Cut every consumer loose before the output goes down. Disabling ends
7455 // the session too, but a worker blocked in WAIT_FRAME only learns that
7456 // when its wait returns, and a bind already in flight with the token we
7457 // are about to forget can still land in between. REVOKE_BINDINGS fails
7458 // both immediately with EACCES, and rotates the token as it goes.
7459 if (vdinfo.hermes_kms_session_lifecycle && vdinfo.output_index >= 0) {
7460 std::array<uint64_t, 2> rotated {};
7461 const bool revoked = hermes_kms::revoke_session_bindings(
7462 vdinfo.drm_fd,
7463 static_cast<uint32_t>(vdinfo.output_index),
7464 vdinfo.session_id,
7465 rotated
7466 );
7467 hermes_kms::forget_secret(rotated.data(), sizeof(rotated));
7468 BOOST_LOG(debug) << "[VDISPLAY/Hermes-KMS] Session " << vdinfo.session_id
7469 << (revoked ? " bindings revoked before disable." :
7470 " bindings could not be revoked; the disable ends them.");
7471 }
7472
7473 // SDDM's greeter exits when its last output goes away, and SDDM does not
7474 // start another: on a host with no monitor that is the login prompt gone
7475 // until the display manager is restarted by hand. So while a greeter is
7476 // what this output is showing, the display goes and the output stays.
7477 // Only the host seat's card qualifies - a private seat or a broker card
7478 // never carries the greeter.
7479 if (!shutting_down && !parked_display && vdinfo.broker_card.empty() && vdinfo.session_index < 0 &&
7481 greeter_holds_seat().value_or(false),
7482 waitForConnectorEnabled(vdinfo.connector_name, std::chrono::milliseconds {0}),
7483 displayConnectorLit("/sys/class/drm", vdinfo.connector_name)
7484 )) {
7485 BOOST_LOG(info) << "[VDISPLAY] Keeping " << vdinfo.connector_name << " connected: the login greeter is on "
7486 "the seat and this is its only output. The next session reuses it, and it is released "
7487 "once someone has logged in.";
7488 hermes_kms::forget_secret(vdinfo.session_token.data(), sizeof(vdinfo.session_token));
7489 lock.unlock();
7490 kscreen::restore(vdinfo.name);
7491 kscreen::unmap_input_devices(vdinfo.name);
7492 kscreen::unplace_windows(vdinfo.name);
7493 mutter::restore(vdinfo.name);
7494 mutter::unmap_input_devices();
7495 lock.lock();
7496 vdinfo.removal_pending = false;
7497 parked_display = std::move(vdinfo);
7498 virtual_displays.erase(it);
7499 return true;
7500 }
7501
7502 hermes_kms::set_output(vdinfo.drm_fd, false, 0, 0, 0, vdinfo.session_id);
7503 }
7504 // A headless output outlives the session that asked for it - Hyprland keeps
7505 // it, and its workspaces, until something removes it - so leaving it behind
7506 // strands a monitor on the user's desktop after every stream.
7507 if (vdinfo.using_hyprland_headless) {
7508 hyprland::remove_output(vdinfo.connector_name);
7509 }
7510 hermes_kms::forget_secret(vdinfo.session_token.data(), sizeof(vdinfo.session_token));
7511 lock.unlock();
7512 kscreen::restore(vdinfo.name);
7513 kscreen::unmap_input_devices(vdinfo.name);
7514 kscreen::unplace_windows(vdinfo.name);
7515 mutter::restore(vdinfo.name);
7516 mutter::unmap_input_devices();
7517
7518 lock.lock();
7519 if (vdinfo.drm_fd >= 0) {
7520 ::close(vdinfo.drm_fd);
7521 }
7522 if (!vdinfo.broker_card.empty()) {
7523 // After the fd is closed, so the card is idle when it is unplugged.
7524 card_broker::remove(vdinfo.broker_card);
7525 }
7526
7527 virtual_displays.erase(it);
7528
7529 BOOST_LOG(info) << "[VDISPLAY] Virtual display removed successfully.";
7530 return true;
7531 }
7532
7534 std::lock_guard<std::mutex> lifecycle_lock(vdisplay_lifecycle_mutex);
7535 std::unique_lock<std::mutex> lock(vdisplay_mutex);
7536 return remove_virtual_display_locked(guid.string(), lock);
7537 }
7538
7539 static std::string virtual_display_connector_name(const std::string &display_name);
7540 static bool pushVirtualOutputMode(
7541 const std::string &displayName,
7542 const std::string &connector,
7543 int width,
7544 int height,
7545 int refresh_mhz,
7546 int deadline_ms = 4000
7547 );
7548
7549 int changeDisplaySettings(const char *deviceName, int width, int height, int refresh_rate, int deadline_ms) {
7550 std::unique_lock<std::mutex> lock(vdisplay_mutex);
7551
7552 refresh_rate = normalize_refresh_rate(refresh_rate);
7553 const int refresh_hz = refresh_rate / 1000;
7554
7555 if (width <= 0 || height <= 0 || refresh_hz <= 0) {
7556 BOOST_LOG(error) << "[VDISPLAY] Refusing invalid virtual display mode "
7557 << width << 'x' << height << '@' << refresh_hz << "Hz";
7558 return -1;
7559 }
7560
7561 BOOST_LOG(info) << "[VDISPLAY] Changing display settings for " << deviceName
7562 << " to " << width << "x" << height << "@" << refresh_hz << "Hz";
7563
7564 // Find the virtual display
7565 bool found = false;
7566 std::string push_mode_for;
7567 for (auto &[guid, vdinfo] : virtual_displays) {
7568 if (vdinfo.name == deviceName) {
7569 // createVirtualDisplay() is normally followed by this call with the
7570 // same values. Reconnecting EVDI in that case causes an avoidable
7571 // compositor modeset and a burst of capture reinitializations.
7572 //
7573 // Hermes-KMS is exempt. hermes_kms::set_output() is a cheap idempotent
7574 // ioctl rather than a reconnect, so the cost this guard avoids does not
7575 // exist there, while the skip silently dropped the only reassertion of
7576 // the client's mode: because KWin adopts the connector at its own
7577 // preferred mode, a session whose requested mode already matched what
7578 // createVirtualDisplay() recorded pushed nothing and streamed the
7579 // compositor's resolution instead of the client's.
7580 if (!vdinfo.using_hermes_kms &&
7581 vdinfo.width == static_cast<uint32_t>(width) &&
7582 vdinfo.height == static_cast<uint32_t>(height) &&
7583 vdinfo.fps == static_cast<uint32_t>(refresh_rate)) {
7584 BOOST_LOG(debug) << "[VDISPLAY] Requested mode is already active; skipping virtual-display reconnect.";
7585 return 0;
7586 }
7587
7588 vdinfo.width = width;
7589 vdinfo.height = height;
7590 vdinfo.fps = refresh_rate;
7591
7592 if (vdinfo.using_evdi && vdinfo.handle) {
7593 // Reconnect with new EDID for new resolution
7594 evdi.disconnect(vdinfo.handle);
7595 unsigned char *edid = generate_edid_for_resolution(width, height, refresh_hz);
7596 unsigned int edid_size = (width > 1920 || height > 1080) ? 256 : 128;
7597 BOOST_LOG(info) << "[VDISPLAY] Reconnecting with " << edid_size << "-byte EDID for " << width << "x" << height;
7598 evdi.connect(vdinfo.handle, edid, edid_size, 0);
7599 } else if (vdinfo.using_hermes_kms && vdinfo.drm_fd >= 0) {
7600 if (!hermes_kms::set_output(vdinfo.drm_fd, true, width, height, refresh_hz, vdinfo.session_id)) {
7601 return -1;
7602 }
7603 // The driver now scans out the new geometry, but the compositor still
7604 // drives the connector at the mode it adopted, and the capture path
7605 // follows the compositor. Move it too - after the lock is released,
7606 // because resolving the connector takes vdisplay_mutex again.
7607 push_mode_for = vdinfo.name;
7608 }
7609
7610 BOOST_LOG(info) << "[VDISPLAY] Display settings updated successfully.";
7611 found = true;
7612 break;
7613 }
7614 }
7615
7616 lock.unlock();
7617
7618 if (!found) {
7619 BOOST_LOG(debug) << "[VDISPLAY] Display not found: " << deviceName;
7620 return 0;
7621 }
7622
7623 if (!push_mode_for.empty()) {
7624 const auto connector = virtual_display_connector_name(push_mode_for);
7625 if (connector.empty() ||
7626 !pushVirtualOutputMode(push_mode_for, connector, width, height, refresh_rate, deadline_ms)) {
7627 BOOST_LOG(warning) << "[VDISPLAY] The compositor was not moved to " << width << 'x' << height << '@'
7628 << refresh_hz << "Hz for " << push_mode_for
7629 << "; the previous compositor mode stays active.";
7630 // The driver took the mode and the compositor did not. Callers that
7631 // care can say so; the ones that do not are no worse off than before,
7632 // since the display is still there and still capturable.
7633 return 1;
7634 }
7635 }
7636
7637 return 0;
7638 }
7639
7640 int changeDisplaySettings2(const char *deviceName, int width, int height, int refresh_rate, bool bApplyIsolated) {
7641 if (bApplyIsolated) {
7642 BOOST_LOG(debug) << "[VDISPLAY] Isolated mode is handled by the active virtual-display backend.";
7643 }
7644 return changeDisplaySettings(deviceName, width, height, refresh_rate);
7645 }
7646
7647 static std::string evdi_connector_name(int card_index) {
7648 const auto prefix = "card" + std::to_string(card_index) + "-";
7649 try {
7650 for (const auto &entry : fs::directory_iterator("/sys/class/drm")) {
7651 const auto name = entry.path().filename().string();
7652 if (name.rfind(prefix, 0) != 0) {
7653 continue;
7654 }
7655 // A connector's "device" link points to its card, which is a DRM class
7656 // device with no driver of its own; the driver belongs to the card's
7657 // parent device.
7658 std::error_code ec;
7659 const auto card = entry.path().parent_path() / ("card" + std::to_string(card_index));
7660 const auto module = fs::canonical(card / "device/driver/module", ec).filename().string();
7661 if (!ec && module == "evdi") {
7662 return name.substr(prefix.size());
7663 }
7664 }
7665 } catch (const std::exception &e) {
7666 BOOST_LOG(warning) << "[VDISPLAY] Unable to find EVDI X11 connector: " << e.what();
7667 }
7668 return {};
7669 }
7670
7671 std::string getEvdiConnectorName(const std::string &displayName) {
7672 return evdi_connector_name(getEvdiCardIndex(displayName));
7673 }
7674
7675 std::string getHermesKmsConnectorName(const std::string &displayName) {
7676 std::lock_guard<std::mutex> lock(vdisplay_mutex);
7677 for (const auto &[guid, display] : virtual_displays) {
7678 if (display.name == displayName && display.using_hermes_kms) {
7679 return display.connector_name;
7680 }
7681 }
7682 return {};
7683 }
7684
7686 const std::string &current_state,
7687 const std::string &virtual_connector,
7688 std::string &serial,
7689 std::string &argument
7690 ) {
7691 mutter::state_t state;
7692 const bool ready =
7693 mutter::build_layout_without(current_state, virtual_connector, state, argument) == mutter::layout_repair::ready;
7694 serial = ready ? state.serial : std::string {};
7695 if (!ready) {
7696 argument.clear();
7697 }
7698 return ready;
7699 }
7700
7702 const std::string &current_state,
7703 const std::string &connector,
7704 uint32_t width,
7705 uint32_t height,
7706 uint32_t refresh_mhz,
7707 std::string &serial,
7708 std::string &argument
7709 ) {
7710 mutter::state_t state;
7711 const bool ready =
7712 mutter::build_layout_with_mode(current_state, connector, width, height, refresh_mhz, state, argument) ==
7714 serial = ready ? state.serial : std::string {};
7715 if (!ready) {
7716 argument.clear();
7717 }
7718 return ready;
7719 }
7720
7722 const std::string &current_state,
7723 const std::string &connector,
7724 std::string &serial,
7725 std::string &argument
7726 ) {
7727 mutter::state_t state;
7728 const bool ready =
7729 mutter::build_exclusive_layout(current_state, connector, state, argument) == mutter::layout_change::ready;
7730 serial = ready ? state.serial : std::string {};
7731 if (!ready) {
7732 argument.clear();
7733 }
7734 return ready;
7735 }
7736
7738 const std::string &current_state,
7739 const std::string &connector,
7740 std::string &serial,
7741 std::string &argument
7742 ) {
7743 mutter::state_t state;
7744 const bool ready =
7745 mutter::build_mirror_layout(current_state, connector, state, argument) == mutter::layout_change::ready;
7746 serial = ready ? state.serial : std::string {};
7747 if (!ready) {
7748 argument.clear();
7749 }
7750 return ready;
7751 }
7752
7754 const std::string &current_state,
7755 std::string &serial,
7756 std::string &argument
7757 ) {
7758 mutter::state_t state;
7759 argument.clear();
7760 serial.clear();
7761 if (!mutter::parse_current_state(current_state, state) ||
7762 !mutter::build_restore_layout(state, argument)) {
7763 argument.clear();
7764 return false;
7765 }
7766 serial = state.serial;
7767 return true;
7768 }
7769
7771 const std::string &current_state,
7772 const std::string &connector
7773 ) {
7774 mutter::state_t state;
7775 if (!mutter::parse_current_state(current_state, state)) {
7776 return {};
7777 }
7778 return mutter::device_output_value(state, connector);
7779 }
7780
7781 void mutterInputDeviceSettingsTargets(std::string &touch, std::string &pen) {
7782 touch = mutter::device_settings_target(mutter::touch_settings);
7783 pen = mutter::device_settings_target(mutter::pen_settings);
7784 }
7785
7786 bool isHermesKWinInputDevice(const std::string &name, uint32_t vendor, uint32_t product) {
7787 return kscreen::is_hermes_input_device(name, vendor, product);
7788 }
7789
7790 std::string buildKWinInputBindingReadCommand(const std::string &device_name) {
7791 return kscreen::input_binding_read_command(device_name);
7792 }
7793
7794 std::string buildKWinInputBindingRestoreCommand(const std::string &device_name, const std::string &previous_uuid) {
7795 return kscreen::input_binding_restore_command(device_name, previous_uuid);
7796 }
7797
7799 return mutter::layout_generation.load(std::memory_order_relaxed);
7800 }
7801
7803 const std::string &current_state,
7804 const std::string &connector,
7805 int &offset_x,
7806 int &offset_y,
7807 int &environment_width,
7808 int &environment_height
7809 ) {
7810 mutter::state_t state;
7811 if (!mutter::parse_current_state(current_state, state)) {
7812 return false;
7813 }
7814 return mutter::geometry_from_state(
7815 state,
7816 connector,
7817 offset_x,
7818 offset_y,
7819 environment_width,
7820 environment_height
7821 );
7822 }
7823
7824 static bool virtual_display_mode(const std::string &display_name, int &width, int &height, int &refresh_rate) {
7825 std::lock_guard<std::mutex> lock(vdisplay_mutex);
7826 for (const auto &[guid, display] : virtual_displays) {
7827 // The backend flags are the test for "this entry still owns a display",
7828 // not a list of DRM backends: a Hyprland headless output owns one just as
7829 // much, and leaving it out made activation return false with no log at
7830 // all - the mode was never pushed and nothing said why.
7831 if (display.name == display_name &&
7832 (display.using_evdi || display.using_hermes_kms || display.using_hyprland_headless)) {
7833 width = static_cast<int>(display.width);
7834 height = static_cast<int>(display.height);
7835 refresh_rate = static_cast<int>(display.fps);
7836 return true;
7837 }
7838 }
7839 return false;
7840 }
7841
7843 static virtual_display_layout_e virtual_display_layout(const std::string &display_name) {
7844 std::lock_guard<std::mutex> lock(vdisplay_mutex);
7845 for (const auto &[guid, display] : virtual_displays) {
7846 if (display.name == display_name) {
7847 return display.layout;
7848 }
7849 }
7850 return virtual_display_layout_e::extend;
7851 }
7852
7853 std::string getHyprlandOutputName(const std::string &displayName) {
7854 std::lock_guard<std::mutex> lock(vdisplay_mutex);
7855 for (const auto &[guid, vdinfo] : virtual_displays) {
7856 if (vdinfo.name == displayName && vdinfo.using_hyprland_headless) {
7857 return vdinfo.connector_name;
7858 }
7859 }
7860 return {};
7861 }
7862
7863 static std::string virtual_display_connector_name(const std::string &display_name) {
7864 // A Hyprland headless output has no DRM connector at all - the name is what
7865 // Hyprland called it - but it is the same kind of answer to the same
7866 // question every caller here asks: what does the compositor call this
7867 // display.
7868 if (auto output = getHyprlandOutputName(display_name); !output.empty()) {
7869 return output;
7870 }
7871 if (auto connector = getHermesKmsConnectorName(display_name); !connector.empty()) {
7872 return connector;
7873 }
7874 return getEvdiConnectorName(display_name);
7875 }
7876
7895 static bool pushVirtualOutputMode(
7896 const std::string &displayName,
7897 const std::string &connector,
7898 int width,
7899 int height,
7900 int refresh_mhz,
7901 int deadline_ms
7902 ) {
7903 if (width <= 0 || height <= 0 || refresh_mhz <= 0 || window_system != window_system_e::WAYLAND) {
7904 return false;
7905 }
7906
7907 if (kscreen::is_active(displayName)) {
7908 return kscreen::apply_mode(displayName, width, height, refresh_mhz / 1000);
7909 }
7910 if (mutter::available()) {
7911 return mutter::apply_output_mode(connector, width, height, refresh_mhz, deadline_ms);
7912 }
7913#ifdef HERMES_BUILD_WAYLAND
7914 const bool applied = wl::configure_virtual_output(connector, width, height, refresh_mhz, false);
7915 if (applied && !getHyprlandOutputName(displayName).empty()) {
7916 if (virtual_display_layout(displayName) == virtual_display_layout_e::mirror) {
7917 BOOST_LOG(warning) << "[VDISPLAY] The mirror layout is not implemented on Hyprland; "
7918 "the virtual output extends the desktop instead.";
7919 }
7920 // Pinned here rather than at creation so a mid-session mode change
7921 // re-pins the new mode.
7922 hyprland::pin_output(connector, width, height, refresh_mhz);
7923 }
7924 return applied;
7925#else
7926 (void) connector;
7927 return false;
7928#endif
7929 }
7930
7931 void placeWindowsOnVirtualDisplay(const std::string &displayName, const std::vector<std::string> &windowClasses, const std::vector<std::uint32_t> &gamescopePids) {
7932 if (kscreen::is_active(displayName)) {
7933 kscreen::place_windows(displayName, windowClasses, gamescopePids);
7934 }
7935 }
7936
7937 namespace {
7938 // A session that streams an existing (physical) monitor rather than a
7939 // virtual display. KWin binds an unbound touchscreen to an output of its own
7940 // choosing - with more than one monitor, often not the one being streamed -
7941 // so touch and pen land somewhere the client never sees. Bind them to the
7942 // captured output for the duration of the session, as virtual displays do.
7943 std::mutex physical_input_mutex;
7944 bool physical_session_active = false;
7945 std::string physical_capture_output;
7946 std::string physical_bound_output;
7947 constexpr const char *physical_binding_owner = "hermes-physical-output";
7948
7949 void apply_physical_binding_locked() {
7950 if (!physical_session_active || physical_capture_output.empty() ||
7951 physical_bound_output == physical_capture_output) {
7952 return;
7953 }
7954 if (window_system != window_system_e::WAYLAND || !kscreen::available()) {
7955 return;
7956 }
7957 // A virtual display session owns the binding while it runs.
7958 if (kscreen::any_layout_active()) {
7959 return;
7960 }
7961 kscreen::map_input_devices_to(physical_binding_owner, physical_capture_output);
7962 physical_bound_output = physical_capture_output;
7963 }
7964 } // namespace
7965
7966 void notePhysicalCaptureOutput(const std::string &connector_name) {
7967 std::lock_guard<std::mutex> lock(physical_input_mutex);
7968 physical_capture_output = connector_name;
7969 apply_physical_binding_locked();
7970 }
7971
7973 if (window_system != window_system_e::WAYLAND || !kscreen::available()) {
7974 return {};
7975 }
7976 for (const auto &output : kscreen::outputs()) {
7977 if (output.connected && output.enabled && output.priority == 1) {
7978 // A virtual output made primary is not a monitor to prefer.
7979 return output.name.starts_with("Virtual") ? std::string {} : output.name;
7980 }
7981 }
7982 return {};
7983 }
7984
7986 std::lock_guard<std::mutex> lock(physical_input_mutex);
7987 physical_session_active = true;
7988 physical_bound_output.clear();
7989 apply_physical_binding_locked();
7990 }
7991
7992 void endPhysicalOutputSession() {
7993 std::lock_guard<std::mutex> lock(physical_input_mutex);
7994 if (!physical_session_active) {
7995 return;
7996 }
7997 physical_session_active = false;
7998 if (!physical_bound_output.empty()) {
7999 // No-op if a virtual display took the binding over meanwhile.
8000 kscreen::unmap_input_devices(physical_binding_owner);
8001 physical_bound_output.clear();
8002 }
8003 }
8004
8005 namespace {
8010 bool connector_scanning_out(int fd, const std::string &name) {
8011 drmModeRes *res = drmModeGetResources(fd);
8012 if (!res) {
8013 return false;
8014 }
8015 bool scanning_out = false;
8016 for (int i = 0; i < res->count_connectors && !scanning_out; ++i) {
8017 drmModeConnector *conn = drmModeGetConnectorCurrent(fd, res->connectors[i]);
8018 if (!conn) {
8019 continue;
8020 }
8021 const char *type = drmModeGetConnectorTypeName(conn->connector_type);
8022 const bool match = type && name == std::string {type} + '-' + std::to_string(conn->connector_type_id);
8023 drmModeEncoder *enc = match && conn->encoder_id ? drmModeGetEncoder(fd, conn->encoder_id) : nullptr;
8024 drmModeCrtc *crtc = enc && enc->crtc_id ? drmModeGetCrtc(fd, enc->crtc_id) : nullptr;
8025 scanning_out = crtc && crtc->mode_valid && crtc->buffer_id;
8026 drmModeFreeCrtc(crtc);
8027 drmModeFreeEncoder(enc);
8028 drmModeFreeConnector(conn);
8029 }
8030 drmModeFreeResources(res);
8031 return scanning_out;
8032 }
8033
8035 void simulate_user_activity() {
8036#ifdef HERMES_BUILD_SDBUS
8037 sd_bus *bus = nullptr;
8038 if (platf::open_user_bus(&bus) < 0 || !bus) {
8039 return;
8040 }
8041 // A wedged screensaver must not hold up starting a stream.
8042 sd_bus_set_method_call_timeout(bus, 2'000'000);
8043 sd_bus_call_method(bus, "org.freedesktop.ScreenSaver", "/org/freedesktop/ScreenSaver", "org.freedesktop.ScreenSaver", "SimulateUserActivity", nullptr, nullptr, "");
8044 sd_bus_flush_close_unref(bus);
8045#endif
8046 }
8047
8049 bool output_scanning_out(const std::string &name) {
8050 std::error_code ec;
8051 for (const auto &entry : std::filesystem::directory_iterator {"/dev/dri", ec}) {
8052 if (!entry.path().filename().string().starts_with("card")) {
8053 continue;
8054 }
8055 const int fd = platf::open_drm_node(entry.path().c_str(), O_RDONLY);
8056 if (fd < 0) {
8057 continue;
8058 }
8059 const bool scanning_out = connector_scanning_out(fd, name);
8060 ::close(fd);
8061 if (scanning_out) {
8062 return true;
8063 }
8064 }
8065 return false;
8066 }
8067 } // namespace
8068
8069 namespace {
8071 std::string connector_status(const std::filesystem::path &connector) {
8072 std::ifstream in {connector / "status"};
8073 std::string status;
8074 std::getline(in, status);
8075 return status;
8076 }
8077
8084 std::string aux_i2c_device(const std::filesystem::path &connector) {
8085 std::error_code ec;
8086 for (const auto &entry : std::filesystem::directory_iterator {connector, ec}) {
8087 const auto name = entry.path().filename().string();
8088 if (name.starts_with("i2c-")) {
8089 return "/dev/" + name;
8090 }
8091 }
8092 return {};
8093 }
8094
8100 int read_edid_byte(const std::string &device) {
8101 const int fd = ::open(device.c_str(), O_RDWR | O_CLOEXEC);
8102 if (fd < 0) {
8103 return -1;
8104 }
8105 constexpr long edid_address = 0x50;
8106 unsigned char byte = 0;
8107 const bool answered = ::ioctl(fd, I2C_SLAVE, edid_address) == 0 && ::write(fd, &byte, 1) == 1 && ::read(fd, &byte, 1) == 1;
8108 ::close(fd);
8109 return answered ? 1 : 0;
8110 }
8111
8126 bool wake_displayport_monitors_from_deep_sleep() {
8127 std::vector<std::string> waking;
8128 std::error_code ec;
8129 for (const auto &entry : std::filesystem::directory_iterator {"/sys/class/drm", ec}) {
8130 const auto name = entry.path().filename().string(); // "card1-DP-2"
8131 const auto dash = name.find('-');
8132 if (!name.starts_with("card") || dash == std::string::npos) {
8133 continue;
8134 }
8135 const auto connector = name.substr(dash + 1);
8136 // Read the state first: a waking monitor drops it at once.
8137 if (!connector.starts_with("DP-") || connector_status(entry.path()) != "connected" || output_scanning_out(connector)) {
8138 continue;
8139 }
8140 const auto device = aux_i2c_device(entry.path());
8141 if (device.empty()) {
8142 continue;
8143 }
8144 const int answered = read_edid_byte(device);
8145 if (answered < 0) {
8146 BOOST_LOG(info) << "[VDISPLAY] Can't open " << device << " to wake " << connector << ": " << std::strerror(errno);
8147 } else if (answered == 0) {
8148 waking.push_back(connector);
8149 }
8150 }
8151 if (waking.empty()) {
8152 return false;
8153 }
8154
8155 const auto start = std::chrono::steady_clock::now();
8156 const auto all_lit = [&waking]() {
8157 return std::ranges::all_of(waking, output_scanning_out);
8158 };
8159 bool lit = false;
8160 while (!(lit = all_lit()) && std::chrono::steady_clock::now() - start < 8s) {
8161 std::this_thread::sleep_for(100ms);
8162 }
8163 const auto waited = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
8164 if (lit) {
8165 BOOST_LOG(info) << "[VDISPLAY] Woke " << waking.front() << " from deep sleep over AUX; lit after " << waited << " ms.";
8166 } else {
8167 BOOST_LOG(warning) << "[VDISPLAY] " << waking.front() << " was woken from deep sleep over AUX but is not lit after " << waited << " ms.";
8168 }
8169 return lit;
8170 }
8171
8172 struct physical_output_t {
8173 std::string name;
8174 bool primary = false;
8175 };
8176
8178 physical_output_t enabled_physical_output() {
8179 physical_output_t result;
8180 for (const auto &output : kscreen::outputs()) {
8181 if (!output.connected || !output.enabled || output.name.starts_with("Virtual")) {
8182 continue;
8183 }
8184 if (result.name.empty() || output.priority == 1) {
8185 result = {output.name, output.priority == 1};
8186 }
8187 }
8188 return result;
8189 }
8190 } // namespace
8191
8193 if (window_system != window_system_e::WAYLAND || !kscreen::available()) {
8194 return false;
8195 }
8196
8197 const bool woken = wake_displayport_monitors_from_deep_sleep();
8198
8199 const auto monitor = enabled_physical_output();
8200 if (monitor.name.empty()) {
8201 return false;
8202 }
8203 // Count as user activity, so the idle timer that put the screens to sleep
8204 // doesn't turn them off again before capture starts.
8205 simulate_user_activity();
8206 if (woken && output_scanning_out(monitor.name)) {
8207 return true; // The compositor lit it when it reconnected.
8208 }
8209
8210 BOOST_LOG(info) << "[VDISPLAY/KScreen] " << monitor.name
8211 << " is enabled but dark (power saving); waking it instead of creating a virtual display.";
8212 if (!kscreen::run_layout_command("kscreen-doctor --dpms on")) {
8213 return false;
8214 }
8215
8216 // The screens come back one at a time, and each reads as enabled before
8217 // the compositor has drawn on it. Capture can only open it once it does.
8218 for (int i = 0; i < 30; ++i) {
8219 std::this_thread::sleep_for(100ms);
8220 if (output_scanning_out(monitor.name)) {
8221 return true;
8222 }
8223 }
8224 BOOST_LOG(warning) << "[VDISPLAY/KScreen] " << monitor.name << " did not show a frame within 3 seconds.";
8225 return false;
8226 }
8227
8228 bool activateVirtualDisplayOutput(const std::string &displayName) {
8229 // KWin is configured when the display is created - enabled, placed and
8230 // driven at the requested mode in one kscreen-doctor transaction - so
8231 // activation only has to confirm the mode still holds. A mode KWin declines
8232 // is a warning there, not a failed activation: the output is composited and
8233 // capturable either way, and failing here would tear the session down over
8234 // a resolution mismatch the user can see.
8235 if (window_system == window_system_e::WAYLAND && kscreen::is_active(displayName)) {
8236 int width = 0;
8237 int height = 0;
8238 int refresh_mhz = 0;
8239 if (virtual_display_mode(displayName, width, height, refresh_mhz)) {
8240 kscreen::apply_mode(displayName, width, height, refresh_mhz / 1000);
8241 }
8242 // KWin binds touch and pen to one output, and the one it picks by itself
8243 // is never this one.
8244 kscreen::map_input_devices(displayName);
8245 return true;
8246 }
8247
8248 const auto connector = virtual_display_connector_name(displayName);
8249 if (connector.empty()) {
8250 BOOST_LOG(warning) << "[VDISPLAY] Cannot activate virtual output: DRM connector was not found.";
8251 return false;
8252 }
8253
8254#ifdef HERMES_BUILD_WAYLAND
8255 if (window_system == window_system_e::WAYLAND) {
8256 int width = 0;
8257 int height = 0;
8258 int refresh_mhz = 0;
8259 if (!virtual_display_mode(displayName, width, height, refresh_mhz)) {
8260 return false;
8261 }
8262
8263 const auto compositor = sessionCompositor();
8264
8265 // A Hyprland headless output is already a real output rendered on the
8266 // primary GPU; only its mode is still Hyprland's default. That mode goes
8267 // through wlr-output-management like any other wlr session, so this needs
8268 // no Hyprland-specific branch - just the generic path below, with the
8269 // connector resolved to the HEADLESS name.
8270 //
8271 // A Hermes-KMS or EVDI display on Hyprland is the case that does not
8272 // work. Both assume the model KWin and Mutter use - the compositor
8273 // renders on the real GPU and imports the buffer into a display-only
8274 // device - while aquamarine wants every GPU that owns an output to host
8275 // its own GL renderer, which such a device cannot. Where a build does
8276 // import directly, the page-flip handshake against the software vblank
8277 // stalls instead. Both end as a black or frozen stream with input
8278 // working, so say it before the stream starts. Reaching here means the
8279 // display outlived the backend switch, since selected_backend() sends new
8280 // Hyprland displays to the headless path.
8281 if (compositor == compositor_e::hyprland && getHyprlandOutputName(displayName).empty()) {
8282 BOOST_LOG(warning) << "[VDISPLAY] Hyprland cannot composite onto a virtual DRM device: "
8283 "aquamarine either cannot build a renderer on the display-only device or "
8284 "stalls on page-flip against its software vblank. This display was not "
8285 "created as a Hyprland headless output, so expect a black or frozen "
8286 "stream; recreating it will take the headless path.";
8287 }
8288
8289 // GNOME/Mutter exposes neither kscreen-doctor nor wlr-output-management,
8290 // only org.gnome.Mutter.DisplayConfig. Mutter does adopt the hotplugged
8291 // connector on its own, but asynchronously and at its own preferred mode,
8292 // so waiting for it to appear is not enough: capture would run at the
8293 // requested geometry while the compositor scans out another one, and the
8294 // client would receive a black image. Push the mode instead.
8295 if (mutter::available()) { // implies compositor == compositor_e::mutter
8296 if (pushVirtualOutputMode(displayName, connector, width, height, refresh_mhz)) {
8297 BOOST_LOG(info) << "[VDISPLAY] Mutter is driving virtual output " << connector << " at " << width << "x"
8298 << height << "@" << refresh_mhz << "; capturing it directly.";
8299 // Mirror is a display-creation choice, unlike exclusive mode, which
8300 // waits for a live session before the local screens may go dark.
8301 // A refusal is logged where it happens and costs the session the
8302 // cloning, not the display: the output is driven and capturable.
8303 if (virtual_display_layout(displayName) == virtual_display_layout_e::mirror) {
8304 mutter::apply_mirror(displayName, connector);
8305 }
8306 // Touch and pen are bound to a single monitor by GNOME, and the one
8307 // it picks by itself is never this one.
8308 mutter::map_input_devices(connector);
8309 // Everything decided above is a snapshot of a layout the compositor
8310 // can rewrite at any moment.
8311 mutter::watch_layout();
8312 return true;
8313 }
8314 BOOST_LOG(warning) << "[VDISPLAY] GNOME/Mutter did not end up driving " << connector << " at " << width << "x"
8315 << height << "@" << refresh_mhz
8316 << ". The virtual display may need to be enabled manually in GNOME Settings, "
8317 << "or use a KDE/wlroots session for automatic activation.";
8318 return false;
8319 }
8320
8321 const bool activated = pushVirtualOutputMode(displayName, connector, width, height, refresh_mhz);
8322 if (activated) {
8323 BOOST_LOG(info) << "[VDISPLAY] Activated Wayland virtual output " << connector;
8324 }
8325 return activated;
8326 }
8327#endif
8328
8329 // A Hermes that outlives the session it was attached to - the user logged
8330 // out and the greeter is back - still carries that session's display
8331 // variables, and every layout backend it would reach through them is gone.
8332 // That is the same position as never having had a session.
8333 const auto variable = [](const char *name) {
8334 const char *value = std::getenv(name);
8335 return std::string {value ? value : ""};
8336 };
8337 const bool session_gone = window_system != window_system_e::NONE &&
8338 !displayServerReachable(variable("WAYLAND_DISPLAY"), variable("DISPLAY"), variable("XDG_RUNTIME_DIR"));
8339 if (window_system == window_system_e::NONE || session_gone) {
8340 // Started before anyone logged in, there is no session to drive a layout
8341 // through - but whatever owns the seat, the login greeter included,
8342 // adopts a hotplugged connector on its own. Wait for it to, and stream
8343 // whatever mode it picks: the virtual output offers the client's mode as
8344 // its preferred one.
8345 if (waitForConnectorEnabled(connector, std::chrono::seconds {10})) {
8346 BOOST_LOG(info) << "[VDISPLAY] " << connector << " was lit by the compositor on the seat; "
8347 "no graphical session is attached, so its layout is left as it chose.";
8348 return true;
8349 }
8350 BOOST_LOG(warning) << "[VDISPLAY] Nothing lit " << connector << " within 10 seconds, and no graphical "
8351 "session is attached to configure it. Before login the greeter must be one that "
8352 "adopts new outputs by itself - with SDDM, the Wayland greeter (DisplayServer=wayland); "
8353 "the X11 greeter never lights a virtual output.";
8354 return false;
8355 }
8356
8357 if (window_system != window_system_e::X11) {
8358 BOOST_LOG(warning) << "[VDISPLAY] No display-layout backend is available for this session.";
8359 return false;
8360 }
8361
8362 if (connector.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") != std::string::npos) {
8363 BOOST_LOG(warning) << "[VDISPLAY] Refusing unsafe virtual connector name.";
8364 return false;
8365 }
8366
8367 const std::string command = "xrandr --output '" + connector + "' --auto";
8368 if (std::system(command.c_str()) != 0) {
8369 BOOST_LOG(warning) << "[VDISPLAY] Failed to activate X11 virtual output " << connector;
8370 return false;
8371 }
8372
8373 BOOST_LOG(info) << "[VDISPLAY] Activated X11 virtual output " << connector;
8374 return true;
8375 }
8376
8377 hdr_launch_mode_t virtualDisplayHdrMode(bool requested, const kscreen_hdr_state_t &state, bool driver_reports_frame_color) {
8378 if (!requested) {
8379 return {false, nullptr};
8380 }
8381 if (!state.hdr_supported) {
8382 return {false, "the virtual output does not offer HDR (Hermes-KMS needs hdr_enable=1 color_depth=10)"};
8383 }
8384 if (!driver_reports_frame_color) {
8385 return {false, "this Hermes-KMS driver does not report each frame's colour (UAPI 14), so HDR frames cannot be recognized"};
8386 }
8387 return {true, nullptr};
8388 }
8389
8390 bool configureVirtualDisplayHdr(const std::string &displayName, bool hdr) {
8391 if (config::video.virtual_display_backend != "hermes_kms" ||
8392 window_system != window_system_e::WAYLAND || !kscreen::is_active(displayName)) {
8393 return true; // Other compositors retain their own color configuration.
8394 }
8395 std::string output;
8396 {
8397 std::lock_guard<std::mutex> lock(kscreen::layouts_mutex);
8398 const auto it = kscreen::layouts.find(displayName);
8399 if (it == kscreen::layouts.end()) {
8400 return false;
8401 }
8402 output = it->second.virtual_output;
8403 }
8404 const auto state = kscreenHdrState(kscreen::command_output("kscreen-doctor -j"), output);
8405 if (!state) {
8406 BOOST_LOG(error) << "[VDISPLAY/KScreen] Cannot read the HDR state of " << output << '.';
8407 return false;
8408 }
8409 // The capture descriptor says whether the driver reports frame colour,
8410 // and afterwards confirms the scanout.
8411 const int capture_fd = hermesKmsOpenCapture(displayName);
8412 if (capture_fd < 0) {
8413 return false;
8414 }
8415 auto close_capture = util::fail_guard([capture_fd]() { ::close(capture_fd); });
8416 const auto mode = virtualDisplayHdrMode(hdr, *state, hermesKmsReportsFrameColor(capture_fd));
8417 if (mode.sdr_reason) {
8418 BOOST_LOG(warning) << "[VDISPLAY/KScreen] The client asked for HDR, but " << mode.sdr_reason
8419 << "; streaming SDR.";
8420 }
8421 hdr = mode.hdr;
8422 std::string command = "kscreen-doctor";
8423 bool changed = false;
8424 if (state->hdr_supported && state->hdr != hdr) {
8425 command += " output." + output + (hdr ? ".hdr.enable" : ".hdr.disable");
8426 changed = true;
8427 }
8428 if (state->wcg_supported && state->wcg != hdr) {
8429 command += " output." + output + (hdr ? ".wcg.enable" : ".wcg.disable");
8430 changed = true;
8431 }
8432 if (changed && !kscreen::run_layout_command(command)) {
8433 return false;
8434 }
8435 // KScreen accepting a request is not proof that a new scanout is ready.
8436 // Wait for frame-associated metadata before encoder probing reads it.
8437 const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds {1500};
8438 do {
8439 hermes_kms::color_t color;
8440 uint32_t fourcc = 0;
8441 if (hermesKmsCaptureColor(capture_fd, color, fourcc) &&
8442 (color.known() ? (color.pq() == hdr && (hdr || color.colorspace != hermes_kms::colorspace_bt2020_rgb)) : !hdr)) {
8443 BOOST_LOG(info) << "[VDISPLAY/KScreen] " << output << " scanout confirmed " << (hdr ? "HDR" : "SDR");
8444 return true;
8445 }
8446 std::this_thread::sleep_for(std::chrono::milliseconds {20});
8447 } while (std::chrono::steady_clock::now() < deadline);
8448 BOOST_LOG(error) << "[VDISPLAY/KScreen] " << output << " did not commit the requested "
8449 << (hdr ? "HDR" : "SDR") << " scanout before capture.";
8450 return false;
8451 }
8452
8453 bool enableExclusiveVirtualDisplay(const std::string &displayName) {
8454 std::lock_guard<std::mutex> lifecycle_lock(vdisplay_lifecycle_mutex);
8455 if (window_system == window_system_e::WAYLAND && kscreen::is_active(displayName)) {
8456 const bool enabled = kscreen::make_exclusive(displayName);
8457 if (enabled) {
8458 exclusive_virtual_display_active = true;
8459 }
8460 return enabled;
8461 }
8462
8463 const auto connector = virtual_display_connector_name(displayName);
8464 if (connector.empty()) {
8465 BOOST_LOG(warning) << "[VDISPLAY] Cannot enable exclusive mode: virtual connector was not found.";
8466 return false;
8467 }
8468
8469 // GNOME reaches this before the wlr path below, which it does not speak.
8470 // ApplyMonitorsConfig disables every monitor left out of the config, so the
8471 // desktop is handed over by submitting one that names only this output.
8472 if (window_system == window_system_e::WAYLAND && mutter::available()) {
8473 const bool enabled = mutter::make_exclusive(displayName, connector);
8474 if (enabled) {
8475 exclusive_virtual_display_active = true;
8476 }
8477 return enabled;
8478 }
8479
8480#ifdef HERMES_BUILD_WAYLAND
8481 if (window_system == window_system_e::WAYLAND) {
8482 int width = 0;
8483 int height = 0;
8484 int refresh_rate = 0;
8485 if (!virtual_display_mode(displayName, width, height, refresh_rate)) {
8486 return false;
8487 }
8488 const bool enabled = wl::configure_virtual_output(connector, width, height, refresh_rate, true);
8489 if (enabled) {
8490 exclusive_virtual_display_active = true;
8491 BOOST_LOG(info) << "[VDISPLAY] Enabled exclusive Wayland layout for virtual output " << connector;
8492 } else {
8493 BOOST_LOG(warning) << "[VDISPLAY] Wayland compositor cannot apply the virtual-display exclusive layout.";
8494 }
8495 return enabled;
8496 }
8497#endif
8498
8499 if (window_system != window_system_e::X11) {
8500 BOOST_LOG(warning) << "[VDISPLAY] Exclusive virtual display layout is unavailable for this session.";
8501 return false;
8502 }
8503
8504 // Connector names come from sysfs. Keep the command defensive nevertheless.
8505 if (connector.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") != std::string::npos) {
8506 BOOST_LOG(warning) << "[VDISPLAY] Refusing unsafe virtual connector name.";
8507 return false;
8508 }
8509
8510 const std::string command = "xrandr --output '" + connector + "' --auto --primary"
8511 " && xrandr --query | awk '$2 == \"connected\" && $1 != \"" + connector + "\" { print $1 }'"
8512 " | while IFS= read -r output; do xrandr --output \"$output\" --off; done";
8513 if (std::system(command.c_str()) != 0) {
8514 BOOST_LOG(warning) << "[VDISPLAY] Failed to enable exclusive X11 virtual display layout.";
8515 return false;
8516 }
8517
8518 exclusive_virtual_display_active = true;
8519 BOOST_LOG(info) << "[VDISPLAY] Enabled exclusive X11 layout for virtual output " << connector;
8520 return true;
8521 }
8522
8523 void restoreExclusiveVirtualDisplay() {
8524 std::lock_guard<std::mutex> lifecycle_lock(vdisplay_lifecycle_mutex);
8525 if (!exclusive_virtual_display_active) {
8526 return;
8527 }
8528
8529 if (window_system == window_system_e::WAYLAND && kscreen::available()) {
8530 if (kscreen::restore_all()) {
8531 exclusive_virtual_display_active = false;
8532 }
8533 return;
8534 }
8535
8536 // On GNOME the layout is restored per display when it is torn down, where
8537 // the captured configuration lives. Falling through would reach the wlr
8538 // path, which GNOME does not implement, and warn about it.
8539 if (window_system == window_system_e::WAYLAND && mutter::available()) {
8540 exclusive_virtual_display_active = false;
8541 return;
8542 }
8543
8544#ifdef HERMES_BUILD_WAYLAND
8545 if (window_system == window_system_e::WAYLAND) {
8547 BOOST_LOG(warning) << "[VDISPLAY] Failed to restore the Wayland display layout.";
8548 }
8549 exclusive_virtual_display_active = false;
8550 return;
8551 }
8552#endif
8553
8554 // Restore every connected physical output before EVDI is removed.
8555 const auto command = "xrandr --query | awk '$2 == \"connected\" { print $1 }'"
8556 " | while IFS= read -r output; do xrandr --output \"$output\" --auto; done";
8557 if (std::system(command) != 0) {
8558 BOOST_LOG(warning) << "[VDISPLAY] Failed to restore the X11 display layout.";
8559 } else {
8560 BOOST_LOG(info) << "[VDISPLAY] Restored X11 physical display layout.";
8561 }
8562 exclusive_virtual_display_active = false;
8563 }
8564
8565 std::string getPrimaryDisplay() {
8566 // Return first connected physical display
8567 try {
8568 for (const auto &entry : fs::directory_iterator("/dev/dri")) {
8569 const auto &path = entry.path();
8570 std::string filename = path.filename().string();
8571 if (filename.find("card") == 0 && filename.find("render") == std::string::npos) {
8572 int fd = ::open(path.c_str(), O_RDWR);
8573 if (fd >= 0) {
8574 drmModeRes *res = drmModeGetResources(fd);
8575 if (res) {
8576 for (int i = 0; i < res->count_connectors; i++) {
8577 drmModeConnector *conn = drmModeGetConnector(fd, res->connectors[i]);
8578 if (conn && conn->connection == DRM_MODE_CONNECTED) {
8579 std::string name = "HDMI-A-" + std::to_string(conn->connector_type_id);
8580 drmModeFreeConnector(conn);
8581 drmModeFreeResources(res);
8582 ::close(fd);
8583 return name;
8584 }
8585 if (conn) drmModeFreeConnector(conn);
8586 }
8587 drmModeFreeResources(res);
8588 }
8589 ::close(fd);
8590 }
8591 }
8592 }
8593 } catch (...) {}
8594 return "";
8595 }
8596
8597 bool setPrimaryDisplay(const char *primaryDeviceName) {
8598 BOOST_LOG(debug) << "[VDISPLAY] setPrimaryDisplay is a no-op on Linux.";
8599 return true;
8600 }
8601
8602 bool getDisplayHDRByName(const char *displayName) {
8603 BOOST_LOG(debug) << "[VDISPLAY] HDR check for: " << displayName;
8604 // EVDI doesn't support HDR currently
8605 return false;
8606 }
8607
8608 bool setDisplayHDRByName(const char *displayName, bool enableAdvancedColor) {
8609 BOOST_LOG(debug) << "[VDISPLAY] HDR setting not supported on Linux/EVDI.";
8610 return false;
8611 }
8612
8613 std::vector<std::string> matchDisplay(const std::string &sMatch) {
8614 std::vector<std::string> matches;
8615
8616 std::lock_guard<std::mutex> lock(vdisplay_mutex);
8617
8618 for (const auto &[guid, vdinfo] : virtual_displays) {
8619 if (vdinfo.active && vdinfo.name.find(sMatch) != std::string::npos) {
8620 matches.push_back(vdinfo.name);
8621 }
8622 }
8623
8624 return matches;
8625 }
8626
8627 // ============================================================================
8628 // EVDI-specific functions for KMS integration
8629 // ============================================================================
8630
8634 bool isEvdiDisplay(const std::string &displayName) {
8635 if (!evdi_available) {
8636 return false;
8637 }
8638
8639 std::lock_guard<std::mutex> lock(vdisplay_mutex);
8640 for (const auto &[guid, vdinfo] : virtual_displays) {
8641 if (vdinfo.name == displayName && vdinfo.using_evdi) {
8642 return true;
8643 }
8644 }
8645 return false;
8646 }
8647
8648 bool isHermesKmsDisplay(const std::string &displayName) {
8649 std::lock_guard<std::mutex> lock(vdisplay_mutex);
8650 for (const auto &[guid, vdinfo] : virtual_displays) {
8651 if (vdinfo.name == displayName && vdinfo.using_hermes_kms) {
8652 return true;
8653 }
8654 }
8655 return false;
8656 }
8657
8662 int getEvdiCardIndex(const std::string &displayName) {
8663 std::lock_guard<std::mutex> lock(vdisplay_mutex);
8664 for (const auto &[guid, vdinfo] : virtual_displays) {
8665 if (vdinfo.name == displayName && vdinfo.using_evdi) {
8666 return vdinfo.drm_card_index;
8667 }
8668 }
8669 return -1;
8670 }
8671
8672 int getHermesKmsCardIndex(const std::string &displayName) {
8673 std::lock_guard<std::mutex> lock(vdisplay_mutex);
8674 for (const auto &[guid, vdinfo] : virtual_displays) {
8675 if (vdinfo.name == displayName && vdinfo.using_hermes_kms) {
8676 return vdinfo.drm_card_index;
8677 }
8678 }
8679 return -1;
8680 }
8681
8683 auto devices = hermes_kms::open_devices(false);
8684 const bool present = !devices.empty();
8685 for (auto &candidate : devices) {
8686 hermes_kms::close_device(candidate);
8687 }
8688 return present;
8689 }
8690
8691 std::vector<std::string> listHermesKmsDisplayNames() {
8692 std::lock_guard<std::mutex> lock(vdisplay_mutex);
8693 std::vector<std::string> names;
8694 for (const auto &[guid, vdinfo] : virtual_displays) {
8695 if (vdinfo.using_hermes_kms) {
8696 names.emplace_back(vdinfo.name);
8697 }
8698 }
8699 return names;
8700 }
8701
8702 std::string getHermesKmsDevicePath(const std::string &displayName) {
8703 const int card_index = getHermesKmsCardIndex(displayName);
8704 return card_index >= 0 ?
8705 "/dev/dri/card" + std::to_string(card_index) :
8706 std::string {};
8707 }
8708
8709 std::string getHermesKmsSeatName(const std::string &displayName) {
8710 std::lock_guard<std::mutex> lock(vdisplay_mutex);
8711 for (const auto &[guid, vdinfo] : virtual_displays) {
8712 if (vdinfo.name == displayName &&
8713 vdinfo.using_hermes_kms &&
8714 vdinfo.session_index > 0) {
8715 // Must match Hermes-KMS' 72-hermes-kms-session-seats.rules (70- in
8716 // driver builds before the rule moved after systemd's uaccess tagging).
8717 //
8718 // The name deliberately does not start with "seat". systemd-logind
8719 // only registers seats whose names do, and a seat it registers is one
8720 // a multi-seat display manager offers a login on: naming these
8721 // seathermes<N> made SDDM start a greeter on each, which tore down the
8722 // host's own desktop session. These seats are for compositors Hermes
8723 // starts, not for anyone to log in to.
8724 return "hermes-kms-" + std::to_string(vdinfo.session_index);
8725 }
8726 }
8727 return {};
8728 }
8729
8731 HermesKmsMetrics out {};
8732 int target_card_index = -1;
8733 uint64_t session_id = 0;
8734 std::array<uint64_t, 2> session_token {};
8735 auto token_guard = util::fail_guard([&session_token]() {
8736 hermes_kms::forget_secret(session_token.data(), sizeof(session_token));
8737 });
8738 {
8739 std::lock_guard<std::mutex> lock(vdisplay_mutex);
8740 for (const auto &[guid, display] : virtual_displays) {
8741 if (display.using_hermes_kms && display.active) {
8742 out.output_index = display.output_index;
8743 out.output_name = display.name;
8744 target_card_index = display.drm_card_index;
8745 session_id = display.session_id;
8746 session_token = display.session_token;
8747 break;
8748 }
8749 }
8750 }
8751
8752 hermes_kms::device_t device {};
8753 auto devices = hermes_kms::open_devices(false);
8754 if (devices.empty()) {
8755 return out;
8756 }
8757 auto selected = target_card_index >= 0 ?
8758 std::find_if(devices.begin(), devices.end(), [target_card_index](const auto &candidate) {
8759 return candidate.card_index == target_card_index;
8760 }) :
8761 devices.begin();
8762 if (selected == devices.end()) {
8763 for (auto &candidate : devices) {
8764 hermes_kms::close_device(candidate);
8765 }
8766 return out;
8767 }
8768 device = *selected;
8769 selected->fd = -1;
8770 for (auto &candidate : devices) {
8771 hermes_kms::close_device(candidate);
8772 }
8773 auto guard = util::fail_guard([&device]() { hermes_kms::close_device(device); });
8774
8775 // The driver may be present without the metrics capability (older build).
8776 if (!(device.caps.flags & hermes_kms::cap_metrics)) {
8777 return out;
8778 }
8779 if (out.output_index < 0 ||
8780 !hermes_kms::bind_session(
8781 device.fd,
8782 static_cast<uint32_t>(out.output_index),
8783 session_id,
8784 session_token
8785 )) {
8786 return out;
8787 }
8788
8789 hermes_kms::metrics_t metrics {};
8790 if (!hermes_kms::get_metrics(device.fd, metrics)) {
8791 BOOST_LOG(debug) << "[VDISPLAY/Hermes-KMS] GET_METRICS failed: " << std::strerror(errno);
8792 return out;
8793 }
8794
8795 out.available = true;
8796 out.frame_sequence = metrics.frame_sequence;
8797 out.frame_update_count = metrics.frame_update_count;
8798 out.acquire_count = metrics.acquire_count;
8799 out.acquire_no_frame_count = metrics.acquire_no_frame_count;
8800 out.dmabuf_export_count = metrics.dmabuf_export_count;
8801 out.dmabuf_export_fail_count = metrics.dmabuf_export_fail_count;
8802 out.wait_count = metrics.wait_count;
8803 out.wait_ready_count = metrics.wait_ready_count;
8804 out.wait_timeout_count = metrics.wait_timeout_count;
8805 out.output_enable_count = metrics.output_enable_count;
8806 out.output_disable_count = metrics.output_disable_count;
8807 out.hotplug_event_count = metrics.hotplug_event_count;
8808 out.last_update_ns = metrics.last_update_ns;
8809 out.last_wait_duration_ns = metrics.last_wait_duration_ns;
8810
8811 if (device.caps.flags & hermes_kms::cap_session_lifecycle) {
8812 out.session_lifecycle = true;
8813 out.bind_count = metrics.bind_count;
8814 out.bind_reject_count = metrics.bind_reject_count;
8815 out.unbind_count = metrics.unbind_count;
8816 out.binding_revoke_count = metrics.binding_revoke_count;
8817 out.cross_session_buffer_export_count = metrics.cross_session_buffer_export_count;
8818
8819 // BIND selected this output atomically, so the status describes the
8820 // session just read rather than whatever the fd looked at before.
8821 hermes_kms::status_t status {};
8822 if (hermes_kms::get_status(device.fd, status)) {
8823 out.bound_fd_count = status.bound_fd_count;
8824 }
8825 }
8826 return out;
8827 }
8828
8829 std::shared_ptr<EvdiBuffer> getEvdiBuffer(const std::string &display_name) {
8830 std::lock_guard<std::mutex> lock(vdisplay_mutex);
8831 for (const auto &[guid, display] : virtual_displays) {
8832 if (display.name == display_name && display.using_evdi) {
8833 return display.evdi_buffer;
8834 }
8835 }
8836 return nullptr;
8837 }
8838
8840 for (auto &fd : dma_buf_fd) {
8841 if (fd >= 0) {
8842 ::close(fd);
8843 fd = -1;
8844 }
8845 }
8846 if (sync_file_fd >= 0) {
8847 ::close(sync_file_fd);
8848 sync_file_fd = -1;
8849 }
8850 }
8851
8853 for (auto &fd : dma_buf_fd) {
8854 if (fd >= 0) {
8855 ::close(fd);
8856 fd = -1;
8857 }
8858 }
8859 if (sync_file_fd >= 0) {
8860 ::close(sync_file_fd);
8861 sync_file_fd = -1;
8862 }
8863 }
8864
8865 int hermesKmsOpenCapture(const std::string &display_name) {
8866 int card_index = -1;
8867 int output_index = -1;
8868 uint64_t session_id = 0;
8869 std::array<uint64_t, 2> session_token {};
8870 auto token_guard = util::fail_guard([&session_token]() {
8871 hermes_kms::forget_secret(session_token.data(), sizeof(session_token));
8872 });
8873 {
8874 std::lock_guard<std::mutex> lock(vdisplay_mutex);
8875 for (const auto &[guid, display] : virtual_displays) {
8876 if (display.name == display_name && display.using_hermes_kms) {
8877 card_index = display.drm_card_index;
8878 output_index = display.output_index;
8879 session_id = display.session_id;
8880 session_token = display.session_token;
8881 break;
8882 }
8883 }
8884 }
8885 if (card_index < 0) {
8886 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] No card mapping for capture of " << display_name;
8887 return -1;
8888 }
8889
8890 // The broker intentionally has no access to private-seat primary cards.
8891 // Open the matching render node directly; the compositor opens cardN via
8892 // its private seatd connection.
8893 const int render_fd = hermes_kms::open_render_node_for_card_index(card_index);
8894 if (render_fd < 0) {
8895 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] No accessible render node maps to card"
8896 << card_index << ".";
8897 return -1;
8898 }
8899
8900 if (output_index < 0 ||
8901 !hermes_kms::bind_session(
8902 render_fd,
8903 static_cast<uint32_t>(output_index),
8904 session_id,
8905 session_token
8906 )) {
8907 ::close(render_fd);
8908 return -1;
8909 }
8910 return render_fd;
8911 }
8912
8913 bool getHermesKmsDisplayGeometry(const std::string &display_name,
8914 int &offset_x, int &offset_y,
8915 int &environment_width, int &environment_height) {
8916 // Each compositor answers this through its own output management, and there
8917 // is no generic one: KWin through kscreen-doctor, GNOME through
8918 // org.gnome.Mutter.DisplayConfig. Both guards already check which session
8919 // this is, so the order between them does not matter.
8920 if (kscreen::available()) {
8921 return kscreen::geometry(
8922 display_name,
8923 offset_x,
8924 offset_y,
8925 environment_width,
8926 environment_height
8927 );
8928 }
8929
8930 if (mutter::available()) {
8931 const auto connector = virtual_display_connector_name(display_name);
8932 if (connector.empty()) {
8933 return false;
8934 }
8935 return mutter::geometry(
8936 connector,
8937 offset_x,
8938 offset_y,
8939 environment_width,
8940 environment_height
8941 );
8942 }
8943
8944 return false;
8945 }
8946
8947 bool hermesKmsCaptureSize(int render_fd, int &width, int &height, uint32_t timeout_ms) {
8948 width = height = 0;
8949 if (render_fd < 0) {
8950 errno = EBADF;
8951 return false;
8952 }
8953 const int error = hermes_kms::wait_for_scanout(
8954 width, height, std::chrono::milliseconds {timeout_ms},
8955 [render_fd](hermes_kms::status_t &status) {
8956 return ::ioctl(render_fd, hermes_kms::ioctl_get_status, &status) == 0 ? 0 : errno;
8957 },
8958 [] { return std::chrono::steady_clock::now(); },
8959 [](auto deadline) { std::this_thread::sleep_until(deadline); }
8960 );
8961 if (error) {
8962 errno = error;
8963 return false;
8964 }
8965 return true;
8966 }
8967
8968 bool hermesKmsReportsFrameColor(int render_fd) {
8969 hermes_kms::caps_t caps {};
8970 return ::ioctl(render_fd, hermes_kms::ioctl_get_caps, &caps) == 0 &&
8971 (caps.flags & hermes_kms::cap_frame_color);
8972 }
8973
8974 bool hermesKmsCaptureColor(int render_fd, hermes_kms::color_t &color, uint32_t &fourcc) {
8975 color = {};
8976 fourcc = 0;
8977 hermes_kms::caps_t caps {};
8978 if (::ioctl(render_fd, hermes_kms::ioctl_get_caps, &caps) != 0) {
8979 return false;
8980 }
8982 if (caps.flags & hermes_kms::cap_frame_color) {
8983 if (::ioctl(render_fd, hermes_kms::ioctl_acquire_frame2, &capture) != 0) {
8984 return false;
8985 }
8986 if (!capture.color.supported()) {
8987 errno = EPROTO;
8988 return false;
8989 }
8990 color = capture.color;
8991 } else if (::ioctl(render_fd, hermes_kms::ioctl_acquire_frame, &capture.frame) != 0) {
8992 return false;
8993 }
8994 fourcc = capture.frame.format;
8995 return true;
8996 }
8997
8998 bool hermesKmsAcquireFrame(int render_fd, uint64_t after_sequence,
8999 uint32_t timeout_ms, HermesKmsFrame &out, bool capture_color) {
9000 if (render_fd < 0) {
9001 errno = EBADF;
9002 return false;
9003 }
9004
9005 out.close();
9006 out.color = {};
9007
9008 // Block for a frame newer than what the caller last saw. A zero timeout
9009 // returns immediately; the caller then uses whatever frame is current.
9010 if (timeout_ms) {
9011 hermes_kms::wait_frame_t wait {};
9012 wait.after_sequence = after_sequence;
9013 wait.timeout_ms = timeout_ms;
9014 if (::ioctl(render_fd, hermes_kms::ioctl_wait_frame, &wait) != 0) {
9015 // ETIMEDOUT/EAGAIN: no new frame. Caller may retry or reuse the last one.
9016 return false;
9017 }
9018 }
9019
9020 // Time only the acquire ioctl (DMA-BUF export), excluding the wait above,
9021 // so callers can measure the actual zero-copy cost.
9022 hermes_kms::acquire_frame2_t capture {};
9023 auto &frame = capture.frame;
9024 const auto acquire_t0 = std::chrono::steady_clock::now();
9025 int acquire_ret = -1;
9026 for (unsigned int attempt = 0; attempt < 4; ++attempt) {
9027 capture = {};
9028 frame.flags = hermes_kms::frame_request_dmabuf | hermes_kms::frame_request_sync_file;
9029 for (auto &fd : frame.dma_buf_fd) {
9030 fd = -1;
9031 }
9032 frame.sync_file_fd = -1;
9033 acquire_ret = capture_color ?
9034 ::ioctl(render_fd, hermes_kms::ioctl_acquire_frame2, &capture) :
9035 ::ioctl(render_fd, hermes_kms::ioctl_acquire_frame, &frame);
9036 if (acquire_ret == 0 || errno != ESTALE) {
9037 break;
9038 }
9039 }
9040 const auto acquire_t1 = std::chrono::steady_clock::now();
9041 out.acquire_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(acquire_t1 - acquire_t0).count();
9042 if (acquire_ret != 0) {
9043 // ENODATA: no scanout framebuffer yet (compositor has not committed).
9044 return false;
9045 }
9046
9047 if ((capture_color && !capture.color.supported()) ||
9048 !(frame.flags & hermes_kms::frame_dmabuf_valid) ||
9049 !(frame.flags & hermes_kms::frame_sync_file_valid) ||
9050 !frame.plane_count || frame.plane_count > 4 || frame.sync_file_fd < 0) {
9051 // No usable DMA-BUFs; release anything we got back.
9052 for (auto fd : frame.dma_buf_fd) {
9053 if (fd >= 0) {
9054 ::close(fd);
9055 }
9056 }
9057 if (frame.sync_file_fd >= 0) {
9058 ::close(frame.sync_file_fd);
9059 }
9060 errno = EPROTO;
9061 return false;
9062 }
9063
9064 out.color = capture.color;
9065 out.width = static_cast<int>(frame.width);
9066 out.height = static_cast<int>(frame.height);
9067 out.fourcc = frame.format;
9068 out.modifier = frame.modifier;
9069 out.plane_count = frame.plane_count;
9070 out.sequence = frame.sequence;
9071 out.sync_file_fd = frame.sync_file_fd;
9072 for (uint32_t i = 0; i < 4; ++i) {
9073 out.dma_buf_fd[i] = frame.dma_buf_fd[i];
9074 out.pitch[i] = frame.pitch[i];
9075 out.offset[i] = frame.offset[i];
9076 }
9077 return true;
9078 }
9079
9080 bool hermesKmsWaitUpdate(int render_fd, uint64_t after_frame_sequence,
9081 uint64_t after_cursor_sequence, uint32_t timeout_ms,
9082 HermesKmsUpdate &out) {
9083 out = {};
9084 if (render_fd < 0) {
9085 errno = EBADF;
9086 return false;
9087 }
9088
9090 wait.after_frame_sequence = after_frame_sequence;
9091 wait.after_cursor_sequence = after_cursor_sequence;
9092 wait.timeout_ms = timeout_ms;
9093 if (::ioctl(render_fd, hermes_kms::ioctl_wait_update, &wait) != 0) {
9094 return false;
9095 }
9096
9097 constexpr uint64_t known_flags = hermes_kms::wait_update_frame_ready |
9098 hermes_kms::wait_update_cursor_ready;
9099 out.frame_ready = (wait.flags & hermes_kms::wait_update_frame_ready) != 0;
9100 out.cursor_ready = (wait.flags & hermes_kms::wait_update_cursor_ready) != 0;
9101 out.frame_sequence = wait.frame_sequence;
9102 out.cursor_sequence = wait.cursor_sequence;
9103 if ((wait.flags & ~known_flags) ||
9104 out.frame_ready != (out.frame_sequence > after_frame_sequence) ||
9105 out.cursor_ready != (out.cursor_sequence > after_cursor_sequence) ||
9106 (!out.frame_ready && !out.cursor_ready)) {
9107 errno = EPROTO;
9108 return false;
9109 }
9110 return true;
9111 }
9112
9113 bool hermesKmsAcquireCursor(int render_fd, bool request_buffer,
9114 HermesKmsCursor &out) {
9115 if (render_fd < 0) {
9116 errno = EBADF;
9117 return false;
9118 }
9119
9120 out.close();
9122 int acquire_ret = -1;
9123 for (unsigned int attempt = 0; attempt < 4; ++attempt) {
9124 cursor = {};
9125 if (request_buffer) {
9126 cursor.flags = hermes_kms::cursor_request_dmabuf |
9127 hermes_kms::cursor_request_sync_file;
9128 }
9129 for (auto &fd : cursor.dma_buf_fd) {
9130 fd = -1;
9131 }
9132 cursor.sync_file_fd = -1;
9133 acquire_ret = ::ioctl(render_fd, hermes_kms::ioctl_acquire_cursor, &cursor);
9134 if (acquire_ret == 0 || errno != ESTALE) {
9135 break;
9136 }
9137 }
9138 if (acquire_ret != 0) {
9139 return false;
9140 }
9141
9142 const auto close_reply_fds = [&cursor]() {
9143 for (auto &fd : cursor.dma_buf_fd) {
9144 if (fd >= 0) {
9145 ::close(fd);
9146 fd = -1;
9147 }
9148 }
9149 if (cursor.sync_file_fd >= 0) {
9150 ::close(cursor.sync_file_fd);
9151 cursor.sync_file_fd = -1;
9152 }
9153 };
9154
9155 const bool metadata_valid = (cursor.flags & hermes_kms::cursor_metadata_valid) != 0;
9156 const bool buffer_valid = (cursor.flags & hermes_kms::cursor_buffer_valid) != 0;
9157 const bool dmabuf_valid = (cursor.flags & hermes_kms::cursor_dmabuf_valid) != 0;
9158 const bool sync_file_valid = (cursor.flags & hermes_kms::cursor_sync_file_valid) != 0;
9159 const bool invalid_layout =
9160 cursor.plane_count > 4 ||
9161 (buffer_valid && (!cursor.plane_count || !cursor.width || !cursor.height || !cursor.format)) ||
9162 (request_buffer && buffer_valid &&
9163 (!dmabuf_valid || !sync_file_valid || cursor.sync_file_fd < 0));
9164 if (!metadata_valid || invalid_layout) {
9165 close_reply_fds();
9166 errno = EPROTO;
9167 return false;
9168 }
9169 if (request_buffer && buffer_valid) {
9170 for (uint32_t i = 0; i < cursor.plane_count; ++i) {
9171 if (cursor.dma_buf_fd[i] < 0 || !cursor.pitch[i]) {
9172 close_reply_fds();
9173 errno = EPROTO;
9174 return false;
9175 }
9176 }
9177 }
9178
9179 out.visible = (cursor.flags & hermes_kms::cursor_visible) != 0;
9180 out.position_valid = (cursor.flags & hermes_kms::cursor_position_valid) != 0;
9181 out.geometry_valid = (cursor.flags & hermes_kms::cursor_geometry_valid) != 0;
9182 out.buffer_valid = buffer_valid;
9183 out.position_x = cursor.position_x;
9184 out.position_y = cursor.position_y;
9185 out.crtc_x = cursor.crtc_x;
9186 out.crtc_y = cursor.crtc_y;
9187 out.crtc_w = cursor.crtc_w;
9188 out.crtc_h = cursor.crtc_h;
9189 out.src_x = cursor.src_x;
9190 out.src_y = cursor.src_y;
9191 out.src_w = cursor.src_w;
9192 out.src_h = cursor.src_h;
9193 out.hotspot_x = cursor.hotspot_x;
9194 out.hotspot_y = cursor.hotspot_y;
9195 out.width = cursor.width;
9196 out.height = cursor.height;
9197 out.fourcc = cursor.format;
9198 out.modifier = cursor.modifier;
9199 out.plane_count = cursor.plane_count;
9200 out.sync_file_fd = cursor.sync_file_fd;
9201 out.sequence = cursor.sequence;
9202 out.image_sequence = cursor.image_sequence;
9203 cursor.sync_file_fd = -1;
9204 for (uint32_t i = 0; i < 4; ++i) {
9205 out.dma_buf_fd[i] = cursor.dma_buf_fd[i];
9206 out.pitch[i] = cursor.pitch[i];
9207 out.offset[i] = cursor.offset[i];
9208 cursor.dma_buf_fd[i] = -1;
9209 }
9210 return true;
9211 }
9212
9213} // namespace VDISPLAY
9214
Capture a shell helper's output without an unbounded shutdown wait.
bool available()
Whether a broker socket is there to talk to.
bool remove(const std::string &name)
Remove a card this user created. Removal is a hot-unplug, so a compositor still holding the card sees...
int sweep()
Remove every card this user still holds, and report how many went.
std::optional< card_t > create(std::optional< uid_t > session_account_uid)
Ask for a new card on a private DRM seat.
Ask the privileged broker for a Hermes-KMS card.
std::shared_ptr< display_t > display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config)
Get the display_t instance for the given hwdevice_type. If display_name is empty, use the first monit...
Definition misc.cpp:1658
@ ok
Success.
Definition common.h:436
Declarations for the configuration of Sunshine.
void start()
Start the HTTPS server.
Hermes-KMS scanout readiness shared by capture and its regression tests.
int wait_for_scanout(int &width, int &height, std::chrono::milliseconds timeout, Query query, Now now, SleepUntil sleep_until)
Declarations for logging related functions.
int open_drm_node(const char *path, int flags)
Open a DRM device node without becoming its DRM master.
Definition misc.cpp:138
Miscellaneous declarations for Linux.
@ WAYLAND
Wayland.
Definition misc.h:23
@ NONE
No window system.
Definition misc.h:21
@ X11
X11.
Definition misc.h:22
bool restore(const targets_t &saved, Query query, Apply apply)
Hyprland's control socket.
int version()
Print the version to stdout, then exit.
@ disconnected
A disconnected IGD was found.
Definition upnp.h:52
util::safe_ptr< UPNPDev, freeUPNPDevlist > device_t
Owning pointer to miniupnpc device discovery results.
Definition upnp.h:33
bool restore_virtual_output_layout()
Definition wayland.cpp:1824
bool configure_virtual_output(const std::string &output_name, int width, int height, int refresh_rate, bool exclusive)
Definition wayland.cpp:1760
bool output_management_supported()
Definition wayland.cpp:1846
session_protocols_t probe_protocols()
Probe the session's globals in a single registry roundtrip.
Definition wayland.cpp:1851
int command(const char *name, int argc, char *argv[])
hermes --prelogin status|enable|disable.
Definition prelogin.cpp:632
bool stop(const std::string &client_uuid)
Stop the client's session unit. Stopping one that is already gone succeeds, so this is safe to call o...
uint32_t src_x
DRM 16.16 fixed point.
uint32_t src_h
DRM 16.16 fixed point.
void close()
Close all owned fds (dma_buf_fd[] and sync_file_fd).
uint32_t src_w
DRM 16.16 fixed point.
uint32_t src_y
DRM 16.16 fixed point.
void close()
Close all owned fds (dma_buf_fd[] and sync_file_fd).
Output-lifetime counters read from the Hermes-KMS GET_METRICS ioctl.
uint64_t hotplug_event_count
Hotplug uevents emitted.
uint64_t bind_reject_count
Binds refused: bad token, wrong session, revoked.
uint64_t wait_timeout_count
Waits that timed out.
uint64_t wait_ready_count
Waits that returned a ready frame.
uint64_t frame_sequence
Latest frame sequence number.
uint64_t dmabuf_export_fail_count
Failed DMA-BUF exports.
uint64_t last_update_ns
Timestamp of the last framebuffer update.
uint64_t unbind_count
Bindings given up by their holder.
int output_index
0-based output selected for this snapshot.
uint64_t acquire_count
ACQUIRE_FRAME ioctls served.
uint64_t acquire_no_frame_count
Acquires that found no new frame.
uint64_t output_enable_count
Times the virtual output was enabled.
uint64_t wait_count
WAIT_FRAME ioctls served.
uint64_t output_disable_count
Times the virtual output was disabled.
uint64_t dmabuf_export_count
DMA-BUFs exported to the consumer.
uint64_t bind_count
Bindings granted over the output's lifetime.
uint64_t frame_update_count
Total framebuffer updates seen.
What was observed about the session, before any verdict is drawn.
bool output_management
zwlr_output_manager_v1 is advertised.
bool hermes_kms_present
A Hermes-KMS device was opened.
bool hermes_kms_multi_output
The device advertises more than one output.
bool image_copy_capture
ext_image_copy_capture_manager_v1 is advertised.
bool drm_seat_isolation
Session DRM cards carry a private ID_SEAT.
bool mutter
org.gnome.Mutter.DisplayConfig answers.
bool screencopy
zwlr_screencopy_manager_v1 is advertised.
bool x11
An X11 session, which has its own xrandr layout path.
bool kscreen
kscreen-doctor is usable.
bool wayland
A Wayland session Hermes will capture from.
bool linux_dmabuf
zwp_linux_dmabuf_v1 is advertised.
bool hermes_kms_multi_device
The driver exposes a session-device pool.
bool session_lifecycle
An owner can revoke a session's bindings without ending the stream.
A point in KScreen's logical coordinate space.
bool active
Set once a session layout was applied and a restore is owed.
std::string restore_argument
The config that puts the layout back as it was found, virtual output included.
std::map< std::string, std::string > current_mode
connector -> mode id
bool logical_size(const logical_monitor_t &lm, int &width, int &height) const
Declarations for utility functions.
EvdiStatus getEvdiStatus()
bool needsInitialDeviceConfiguration()
Whether EVDI needs a device pre-created at module load time.
bool getDisplayHDRByName(const char *displayName)
Get the HDR status of a display by name.
bool isHermesKmsDriverPresent()
std::string buildKScreenLayoutCommand(const std::string &virtual_output, const std::map< std::string, int > &enabled_before, int target_x, int target_y, int mode_width, int mode_height, int mode_refresh_hz, const std::map< std::string, kscreen_point_t > &positions_before, virtual_display_layout_e layout)
Build the kscreen-doctor invocation that enables a virtual output, places it, and drives it at a requ...
compositor_e compositorFromDesktopNames(const std::string &desktop_names)
Classify a compositor from an XDG_CURRENT_DESKTOP-style value.
bool hermesKmsAcquireCursor(int render_fd, bool request_buffer, HermesKmsCursor &out)
bool setPrimaryDisplay(const char *primaryDeviceName)
Set the primary display by name.
bool mutterDisplayGeometry(const std::string &current_state, const std::string &connector, int &offset_x, int &offset_y, int &environment_width, int &environment_height)
Where a connector sits on a GNOME desktop, for absolute input.
bool unlockHostSessionIfLocked()
Unlock the active graphical login session for the Hermes user when locked.
bool inLoginSession()
Whether Hermes itself runs inside a login session - started from a terminal or over SSH - rather than...
bool hermesKmsSeatIsolationActive()
Whether Hermes-KMS session cards carry a private DRM seat.
int getEvdiCardIndex(const std::string &displayName)
Get the DRM card index for an EVDI display.
std::vector< std::string > matchDisplay(const std::string &sMatch)
Match displays by a given pattern.
HERMES_KMS_DIAGNOSTIC getHermesKmsDiagnostic()
bool setDisplayHDRByName(const char *displayName, bool enableAdvancedColor)
Set the HDR status of a display by name.
bool windowSystemAttached()
Whether Hermes runs inside a graphical session (Wayland or X11).
bool isEvdiDisplay(const std::string &displayName)
Check if a display name is an EVDI virtual display.
HermesKmsMetrics getHermesKmsMetrics()
Read the Hermes-KMS device metrics, if a metrics-capable device is present. It opens a short-lived re...
std::vector< std::string > listHermesKmsDisplayNames()
@ ready
argument holds the config to submit.
uint64_t displayLayoutGeneration()
A counter bumped whenever the desktop layout changes underneath a running session.
int changeDisplaySettings(const char *deviceName, int width, int height, int refresh_rate, int deadline_ms)
Change the display settings of a virtual display.
constexpr std::chrono::seconds command_timeout
std::string createVirtualDisplay(const char *s_client_uid, const char *s_client_name, uint32_t width, uint32_t height, uint32_t fps, const uuid_util::uuid_t &guid, std::optional< uid_t > session_owner_uid, virtual_display_layout_e layout, bool isolated_session)
Create a virtual display.
bool startPingThread(std::function< void()> failCb)
Start a ping thread to keep the virtual display alive.
bool buildMutterLayoutWithMode(const std::string &current_state, const std::string &connector, uint32_t width, uint32_t height, uint32_t refresh_mhz, std::string &serial, std::string &argument)
Build the Mutter ApplyMonitorsConfig payload that drives a connector at a requested geometry.
bool buildMutterMirrorLayout(const std::string &current_state, const std::string &connector, std::string &serial, std::string &argument)
Build the payload that clones the primary output onto connector.
int hermesKmsOpenCapture(const std::string &display_name)
std::vector< FeatureReport > assessSession(const SessionFacts &facts)
Turn observations into a per-feature verdict with remediation.
std::string compositorName(compositor_e compositor)
SessionFacts probeSessionFacts()
bool hermesKmsWaitUpdate(int render_fd, uint64_t after_frame_sequence, uint64_t after_cursor_sequence, uint32_t timeout_ms, HermesKmsUpdate &out)
compositor_e sessionCompositor()
Classify the compositor of the running session.
kscreen_point_t kscreenVirtualOutputPosition(const std::string &virtual_output, const std::vector< kscreen_output_t > &before, const std::vector< kscreen_output_t > &current, virtual_display_layout_e layout)
Decide where the virtual output goes, in KScreen's logical space.
std::string mutterInputDeviceOutputValue(const std::string &current_state, const std::string &connector)
The GNOME output value that binds an input device to connector.
std::string getHermesKmsDevicePath(const std::string &displayName)
int getHermesKmsCardIndex(const std::string &displayName)
DRIVER_STATUS openVDisplayDevice()
Initialize the virtual display driver.
@ no_device
No card node identifies itself as the hermes-kms driver.
constexpr uint32_t newest_known_uapi_version
bool isHermesKWinInputDevice(const std::string &name, uint32_t vendor, uint32_t product)
Whether a device KWin reports is one of Hermes' touch or pen devices.
void placeWindowsOnVirtualDisplay(const std::string &displayName, const std::vector< std::string > &windowClasses, const std::vector< std::uint32_t > &gamescopePids)
EVDI_DIAGNOSTIC getEvdiDiagnostic()
bool configureVirtualDisplayHdr(const std::string &displayName, bool hdr)
layout_mode_e
Values of Mutter's "layout-mode" property.
@ logical
A logical monitor measures mode / scale.
@ physical
A logical monitor measures the mode, whatever the scale.
std::string getEvdiConnectorName(const std::string &displayName)
std::string getHermesKmsConnectorName(const std::string &displayName)
hdr_launch_mode_t virtualDisplayHdrMode(bool requested, const kscreen_hdr_state_t &state, bool driver_reports_frame_color)
bool getHermesKmsDisplayGeometry(const std::string &display_name, int &offset_x, int &offset_y, int &environment_width, int &environment_height)
std::string featureName(feature_e feature)
bool hermesKmsReportsFrameColor(int render_fd)
bool waitForConnectorEnabled(const std::string &connector, std::chrono::milliseconds timeout, const std::filesystem::path &drm_class)
Wait until some compositor has bound connector to a CRTC.
void mutterInputDeviceSettingsTargets(std::string &touch, std::string &pen)
The relocatable-schema targets whose output key binds Hermes' own touch and pen devices,...
std::string buildKWinInputBindingRestoreCommand(const std::string &device_name, const std::string &previous_uuid)
The kwriteconfig6 command that puts a KWin input device's binding back to previous_uuid,...
std::optional< bool > displayConnectorLit(const std::filesystem::path &drm_class, const std::string &ignored_connector)
Whether any DRM connector is lighting a monitor right now.
void logSessionAssessment()
Probe, assess and log what this session can and cannot do.
kscreen_mode_state_e kscreenModeState(const std::string &json_text, const std::string &output, int width, int height, int refresh_hz)
Find a mode on one output in a kscreen-doctor -j reply.
bool setRenderAdapterByName(const std::string &adapterName)
Set the render adapter by name.
bool hermesKmsCaptureColor(int render_fd, hermes_kms::color_t &color, uint32_t &fourcc)
std::optional< std::string > kscreenLayoutFailure(std::string_view output)
What went wrong with a kscreen-doctor layout command, read from its output.
bool hermesKmsCaptureSize(int render_fd, int &width, int &height, uint32_t timeout_ms)
bool buildMutterLayoutWithoutConnector(const std::string &current_state, const std::string &virtual_connector, std::string &serial, std::string &argument)
Build the Mutter ApplyMonitorsConfig payload that drops a connector.
bool removeVirtualDisplay(const uuid_util::uuid_t &guid)
Remove a virtual display.
HermesKmsStatus getHermesKmsStatus()
bool displayServerReachable(const std::string &wayland_display, const std::string &x_display, const std::string &runtime_dir)
Whether a display server is listening where these variables point.
void beginPhysicalOutputSession()
bool kscreenDisplayGeometry(const std::vector< kscreen_output_t > &outputs, const std::string &output_name, int &offset_x, int &offset_y, int &environment_width, int &environment_height)
Resolve one KScreen output inside the live desktop envelope.
std::shared_ptr< EvdiBuffer > getEvdiBuffer(const std::string &display_name)
int changeDisplaySettings2(const char *deviceName, int width, int height, int refresh_rate, bool bApplyIsolated)
Change the display settings with isolated display option.
@ already_set
Mutter already drives the connector at that mode.
@ unsupported
The connector does not advertise the requested geometry.
@ ready
argument holds the config to submit.
bool isHermesKmsDisplay(const std::string &displayName)
bool removalStrandsGreeter(bool greeter_on_seat, bool output_lit, std::optional< bool > another_connector_lit)
Whether removing a virtual display would leave the login greeter with nothing to draw on.
std::string systemdUserBusAddress(uint32_t uid)
The standard systemd user-bus address for uid.
void closeVDisplayDevice()
Close the virtual display driver.
std::string getHyprlandOutputName(const std::string &displayName)
The Hyprland output name backing a virtual display, or empty.
std::optional< std::string > boundedCommandOutput(const std::string &command, std::chrono::milliseconds timeout, bool *timed_out)
Run a shell command and collect its standard output, waiting no longer than timeout for it.
std::string buildKWinInputBindingReadCommand(const std::string &device_name)
The kreadconfig6 command that prints the output UUID a KWin input device is bound to....
std::optional< std::vector< std::string > > userManagerEnvironment()
The environment the systemd user manager hands to the units it starts, as "NAME=value" strings.
bool activateVirtualDisplayOutput(const std::string &displayName)
std::string getPrimaryDisplay()
Get the primary display name.
std::string parkedConnector()
The connector of the output being kept for the login greeter, or empty. It is lit,...
bool buildMutterRestoreLayout(const std::string &current_state, std::string &serial, std::string &argument)
Build the payload that reproduces the layout in current_state.
bool buildMutterExclusiveLayout(const std::string &current_state, const std::string &connector, std::string &serial, std::string &argument)
Build the ApplyMonitorsConfig payload that hands the desktop to connector alone, which is how a monit...
bool enableExclusiveVirtualDisplay(const std::string &displayName)
bool wakeSleepingMonitor()
Wake a monitor the compositor has put to sleep.
@ unsafe
Dropping it would leave Mutter with nothing to drive.
@ not_needed
The connector is not in Mutter's layout.
@ unavailable
The reply did not parse; worth retrying.
@ ready
argument holds the config to submit.
std::string primaryPhysicalOutputName()
The desktop's primary physical output ("DP-2"), or empty.
std::optional< bool > graphicalSessionPresent()
Whether this user has a session of their own, as logind sees it - graphical or not,...
std::string getHermesKmsSeatName(const std::string &displayName)
Virtual display declarations for Linux.
constexpr const char * VIRTUAL_TOUCH_DEVICE_NAME
The names Hermes gives its per-client touch and pen devices.
feature_e
A thing Hermes does that a session either supports or does not.
@ exclusive_mode
Blank the physical monitors for the duration of a session.
@ virtual_display
Create a virtual display and have it composited onto.
@ multiple_displays
More than one virtual display in the same session.
@ zero_copy_capture
Capture over DMA-BUF rather than through a CPU copy.
@ client_requested_mode
Drive it at the geometry the client asked for.
@ isolated_sessions
One seat and one compositor per client.
virtual_display_layout_e
Where the host compositor places a newly created virtual output.
@ primary
Side-by-side like extend, with the virtual output as the primary one.
@ detached
Side-by-side while preserving physical-output state where possible.
@ extend
Side-by-side, reasserting the pre-session physical layout.
@ mirror
Overlapped with the primary output, so the desktop is cloned.
constexpr uint16_t VIRTUAL_INPUT_SETTINGS_VENDOR_ID
The ids GNOME's per-device settings path is built from.
readiness_e
How well a session supports one feature.
@ unavailable
Cannot work here; remediation says what would change that.
@ degraded
Usable, but not as asked for - the detail says how.
@ unknown
Could not be probed - never assume this means broken.
@ ready
Verified available in this session.
kscreen_mode_state_e
What kscreen-doctor -j says about a mode on one output.
@ advertised
The mode exists and is not the one being driven.
@ current
KWin already drives the output at that mode.
@ not_advertised
The output exists but offers no such mode.
@ unknown_output
KWin does not report that output at all.
compositor_e
The Wayland compositor driving this session.
@ cosmic
COSMIC: wlr-output-management, but no wlr-screencopy for capture.
@ hyprland
Hyprland - aquamarine, not wlroots, and it does not behave like it.
@ wlroots
sway, wayfire, river, labwc: the plain wlr-output-management path.
@ unknown
X11, no session, or a compositor Hermes cannot name.
DRIVER_STATUS
Status of the virtual display driver.
@ NOT_SUPPORTED
Virtual display not supported on this system.
@ UNKNOWN
Driver status unknown.
@ OK
Driver is operational.
EVDI_DIAGNOSTIC
Actionable EVDI state exposed to the Web UI.
HERMES_KMS_DIAGNOSTIC
Actionable Hermes-KMS state exposed to the Web UI.
@ NO_ACCESS
The driver's desktop render node exists but this user may not open it.
void release(input_raw_t *raw, int index)
Free a gamepad whose stream ended; a detached desktop keeps it.
Declarations for Wayland capture.
Identify supported launch commands and build scoped KWin placement scripts.