39#include <nlohmann/json.hpp>
44#include <linux/i2c-dev.h>
48#include <sys/socket.h>
50#include <sys/sysmacros.h>
52#include <sys/utsname.h>
54#ifdef HERMES_BUILD_SDBUS
55 #include <systemd/sd-bus.h>
56 #include <systemd/sd-login.h>
59#include <xf86drmMode.h>
71#ifdef HERMES_BUILD_WAYLAND
75using namespace std::literals;
76namespace fs = std::filesystem;
81 return "unix:path=/run/user/" + std::to_string(uid) +
"/bus";
85 static bool unix_socket_answers(
const std::string &path,
bool abstract_namespace =
false) {
86 sockaddr_un address {};
87 address.sun_family = AF_UNIX;
89 const size_t offset = abstract_namespace ? 1 : 0;
90 if (path.empty() || path.size() + offset >=
sizeof(address.sun_path)) {
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());
96 const int fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
102 const bool answers = ::connect(fd,
reinterpret_cast<const sockaddr *
>(&address), length) == 0 || errno == EAGAIN;
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)) {
114 if (!x_display.empty()) {
117 const auto colon = x_display.rfind(
':');
118 if (colon == std::string::npos) {
121 const auto host = x_display.substr(0, colon);
122 if (!host.empty() && host !=
"unix") {
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) {
129 const auto socket_path =
"/tmp/.X11-unix/X" + number;
130 return unix_socket_answers(socket_path) || unix_socket_answers(socket_path,
true);
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) {
146 if (!session || !*session) {
151 char *type_raw =
nullptr;
152 if (sd_session_get_type(session.get(), &type_raw) < 0) {
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";
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);
175#ifdef HERMES_BUILD_SDBUS
176 sd_bus *bus =
nullptr;
177 if (platf::open_user_bus(&bus) < 0 || !bus) {
180 const std::unique_ptr<sd_bus,
decltype(&sd_bus_unref)> bus_guard {bus, &sd_bus_unref};
182 sd_bus_error error = SD_BUS_ERROR_NULL;
183 sd_bus_message *reply =
nullptr;
184 const int status = sd_bus_get_property(
186 "org.freedesktop.systemd1",
187 "/org/freedesktop/systemd1",
188 "org.freedesktop.systemd1.Manager",
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) {
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);
212#ifdef HERMES_BUILD_SDBUS
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);
225 const std::string session_id {session_id_raw};
226 std::free(session_id_raw);
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");
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";
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()
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);
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);
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);
273 status = sd_bus_get_property_trivial(
274 bus, service, session_path.c_str(), session_interface,
"LockedHint",
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);
286 BOOST_LOG(info) <<
"[Session] Graphical session " << session_id <<
" is already unlocked.";
287 sd_bus_error_free(&error);
296 status = sd_bus_call_method(
297 bus, service, session_path.c_str(), session_interface,
"Unlock",
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);
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);
316 BOOST_LOG(warning) <<
"[Session] Host-session unlock was requested, but this build has no sd-bus support.";
329 int version_patchlevel;
332 struct evdi_device_context;
333 typedef struct evdi_device_context *evdi_handle;
335 enum evdi_device_status {
346 unsigned int pixel_format;
369 uint32_t buffer_length;
371 uint32_t pixel_format;
383 uint32_t buffer_length;
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);
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);
418 fn_evdi_check_device check_device;
420 fn_evdi_add_device add_device;
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;
432 } evdi = {
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
433 nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
false};
440 static const unsigned char default_edid[] = {
441 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
444 0x01, 0x01, 0x01, 0x01,
452 0xFC, 0x81, 0xA4, 0x55, 0x4D, 0x9D, 0x25, 0x12, 0x50, 0x54,
459 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
462 0x80, 0x18, 0x71, 0x38, 0x2D, 0x40,
463 0x58, 0x2C, 0x45, 0x00,
464 0x56, 0x50, 0x21, 0x00, 0x00, 0x1E,
466 0x00, 0x00, 0x00, 0xFC, 0x00,
467 'A',
'P',
'O',
'L',
'L',
'O',
' ',
'V',
'D',
'I',
'S',
'P',
'\n',
469 0x00, 0x00, 0x00, 0xFD, 0x00,
470 0x32, 0x4B, 0x1E, 0x51, 0x11, 0x00, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
479 static std::mutex vdisplay_mutex;
482 static std::mutex vdisplay_lifecycle_mutex;
483 static std::atomic<bool> watchdog_running {
false};
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;
492 enum class VirtualDisplayBackend {
512 static VirtualDisplayBackend selected_backend() {
518 if (config::video.virtual_display_backend ==
"none") {
519 return VirtualDisplayBackend::NONE;
522 return VirtualDisplayBackend::HYPRLAND_HEADLESS;
524 return config::video.virtual_display_backend ==
"hermes_kms" ? VirtualDisplayBackend::HERMES_KMS : VirtualDisplayBackend::EVDI;
527 static const char *backend_name(VirtualDisplayBackend backend) {
529 case VirtualDisplayBackend::HERMES_KMS:
531 case VirtualDisplayBackend::HYPRLAND_HEADLESS:
532 return "Hyprland headless output";
533 case VirtualDisplayBackend::NONE:
535 case VirtualDisplayBackend::EVDI:
543 static bool safe_output_name(
const std::string &name);
556 static std::string socket_path() {
557 const char *signature = std::getenv(
"HYPRLAND_INSTANCE_SIGNATURE");
558 if (!signature || !signature[0]) {
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";
566 static bool available() {
567 const auto path = socket_path();
568 return !path.empty() && std::filesystem::exists(path);
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)) {
578 const int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
582 auto close_fd = util::fail_guard([fd]() {
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) {
594 while (written < command.size()) {
595 const ssize_t n = write(fd, command.data() + written, command.size() - written);
597 if (n < 0 && errno == EINTR) {
602 written +=
static_cast<size_t>(n);
608 const ssize_t n = read(fd, buffer,
sizeof(buffer));
610 if (errno == EINTR) {
618 reply.append(buffer,
static_cast<size_t>(n));
624 static std::vector<std::string> monitor_names() {
625 std::vector<std::string> names;
626 const auto reply = request(
"j/monitors");
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>());
637 }
catch (
const nlohmann::json::exception &e) {
638 BOOST_LOG(warning) <<
"[VDISPLAY] Could not read Hyprland's monitor list: " << e.what();
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));
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).");
666 for (
int attempt = 0; attempt < 40; ++attempt) {
667 for (
const auto &name : monitor_names()) {
668 if (!before.contains(name)) {
672 std::this_thread::sleep_for(std::chrono::milliseconds(25));
675 BOOST_LOG(error) <<
"[VDISPLAY] Hyprland accepted the headless output but never published it.";
710 static void pin_output(
const std::string &name,
int width,
int height,
int refresh_mhz) {
711 if (width <= 0 || height <= 0) {
715 if (!safe_output_name(name)) {
716 BOOST_LOG(warning) <<
"[VDISPLAY] Refusing to pin a Hyprland monitor rule for an unsafe output name.";
719 std::string mode = std::to_string(width) +
"x" + std::to_string(height);
720 if (refresh_mhz > 0) {
722 std::snprintf(refresh,
sizeof(refresh),
"@%.3f", refresh_mhz / 1000.0);
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);
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).");
739 BOOST_LOG(info) <<
"[VDISPLAY] Pinned Hyprland monitor rule '" << rule <<
"'";
742 static bool remove_output(
const std::string &name) {
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).");
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.";
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;
783 constexpr size_t name_len = 32;
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;
800 constexpr uint64_t cap_dynamic_devices = 1ULL << 16;
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;
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;
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];
825 uint32_t preferred_width;
826 uint32_t preferred_height;
827 uint32_t max_refresh_hz;
828 uint32_t output_count;
832 char driver_name[name_len];
833 char output_name[name_len];
834 char connector_name[name_len];
835 uint32_t connector_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;
850 uint32_t output_index;
852 uint32_t selected_output_index;
853 uint32_t output_count;
854 char output_name[name_len];
855 uint32_t reserved[8];
864 uint32_t result_flags;
871 uint64_t timestamp_ns;
873 uint32_t framebuffer_id;
877 uint32_t plane_count;
880 int32_t dma_buf_fd[4];
881 int32_t sync_file_fd;
887 alignas(8) uint64_t reserved[6];
900 uint64_t after_sequence;
902 uint64_t timestamp_ns;
903 uint64_t status_flags;
906 uint64_t reserved[6];
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;
920 uint64_t reserved[5];
926 uint64_t image_sequence;
927 uint64_t timestamp_ns;
942 uint32_t framebuffer_id;
946 uint32_t plane_count;
949 int32_t dma_buf_fd[4];
950 int32_t sync_file_fd;
952 uint32_t reserved_alignment;
953 uint64_t reserved[6];
956 static_assert(
sizeof(
caps_t) == 40);
963 static_assert(offsetof(
identity_t, cursor_plane_id) == 140);
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;
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;
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];
1010 uint64_t session_id;
1012 uint32_t output_index;
1014 uint32_t result_flags;
1015 uint64_t reserved[4];
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;
1036 constexpr uint32_t session_access_get_token = 1U;
1037 constexpr uint32_t session_access_bind = 2U;
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;
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);
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);
1071 int card_index {-1};
1072 uint32_t selected_output_index {0};
1078 static std::string cstr(
const char *value) {
1079 return value && value[0] ? std::string {value, strnlen(value, name_len)} : std::string {};
1082 static void forget_secret(
void *data,
size_t size) {
1083 auto *
byte =
static_cast<volatile unsigned char *
>(data);
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()) {
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) {
1101 index = index * 10 + digit;
1106 static int card_index_from_path(
const fs::path &path) {
1107 return numbered_node_index(path,
"card");
1110 static bool is_render_node(
const fs::path &path) {
1111 return numbered_node_index(path,
"renderD") >= 0;
1114 static bool is_hermes_device(
int fd) {
1119 drmVersionPtr
version = drmGetVersion(fd);
1126 static_cast<size_t>(
version->name_len),
1128 drmFreeVersion(version);
1144 static int primary_card_index(
int fd) {
1149 struct stat node {};
1150 if (::fstat(fd, &node) != 0 || !S_ISCHR(node.st_mode)) {
1158 "/sys/dev/char/%u:%u/device/drm",
1159 static_cast<unsigned>(major(node.st_rdev)),
1160 static_cast<unsigned>(minor(node.st_rdev))
1166 for (
const auto &entry : fs::directory_iterator {drm_dir, ec}) {
1167 const int index = card_index_from_path(entry.path());
1175 static void close_device(
device_t &device) {
1176 if (device.fd >= 0) {
1182 static int open_render_node_for_card_index(
int card_index) {
1183 if (card_index < 0) {
1188 fs::directory_iterator dir(
"/dev/dri", ec);
1192 for (
const auto &entry : dir) {
1193 if (!is_render_node(entry.path())) {
1196 const int fd = ::open(entry.path().c_str(), O_RDONLY | O_CLOEXEC);
1200 if (is_hermes_device(fd) && primary_card_index(fd) == card_index) {
1208 static bool multi_output_requested() {
1209 return config::video.hermes_kms_multi_output;
1212 static uint32_t required_uapi_version() {
1214 return session_access_uapi_version;
1217 static uint32_t output_count(
const caps_t &caps) {
1218 return caps.output_count ? caps.output_count : 1U;
1221 static bool has_required_caps(
1223 bool require_multi_output = multi_output_requested(),
1224 bool require_multi_device =
false
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));
1235 static std::vector<device_t> open_devices(
bool log_failures) {
1236 std::vector<device_t> devices;
1238 for (
const auto &entry : fs::directory_iterator(
"/dev/dri")) {
1245 if (!is_render_node(entry.path())) {
1250 candidate.fd = ::open(entry.path().c_str(), O_RDONLY | O_CLOEXEC);
1251 if (candidate.fd < 0) {
1258 if (!is_hermes_device(candidate.fd)) {
1259 close_device(candidate);
1263 if (::ioctl(candidate.fd, ioctl_get_version, &candidate.version) != 0) {
1264 close_device(candidate);
1268 if (cstr(candidate.version.driver_name) !=
"hermes-kms") {
1269 close_device(candidate);
1273 candidate.card_index = primary_card_index(candidate.fd);
1274 if (candidate.card_index < 0) {
1276 BOOST_LOG(error) <<
"[VDISPLAY/Hermes-KMS] Could not resolve the primary card for "
1279 close_device(candidate);
1282 const auto required_version = required_uapi_version();
1283 if (candidate.version.uapi_version < required_version) {
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." :
".");
1289 close_device(candidate);
1293 if (::ioctl(candidate.fd, ioctl_get_caps, &candidate.caps) != 0 || !has_required_caps(candidate.caps.flags)) {
1295 BOOST_LOG(error) <<
"[VDISPLAY/Hermes-KMS] Driver is present but does not expose the required streaming capabilities.";
1297 close_device(candidate);
1301 if (::ioctl(candidate.fd, ioctl_get_identity, &candidate.identity) != 0) {
1303 BOOST_LOG(error) <<
"[VDISPLAY/Hermes-KMS] GET_IDENTITY failed for "
1304 << entry.path() <<
": " << std::strerror(errno);
1306 close_device(candidate);
1310 devices.emplace_back(candidate);
1312 }
catch (
const std::exception &exception) {
1314 BOOST_LOG(error) <<
"[VDISPLAY/Hermes-KMS] Could not enumerate DRM devices: " << exception.what();
1324 const bool dynamic_devices = std::any_of(devices.begin(), devices.end(), [](
const auto &device) {
1325 return (device.caps.flags & cap_dynamic_devices) != 0;
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;
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;
1337 return left.card_index < right.card_index;
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.";
1348 static bool open_device(device_t &out,
bool log_failures) {
1349 auto devices = open_devices(log_failures);
1350 if (devices.empty()) {
1354 out = devices.front();
1355 devices.front().fd = -1;
1356 for (
auto &device : devices) {
1357 close_device(device);
1364 const bool ok = open_device(device,
false);
1365 close_device(device);
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};
1393 std::string driver_version;
1396 static probe_t probe() {
1399 fs::directory_iterator dir(
"/dev/dri", ec);
1403 for (
const auto &entry : dir) {
1404 if (!is_render_node(entry.path())) {
1409 candidate.fd = ::open(entry.path().c_str(), O_RDONLY | O_CLOEXEC);
1410 if (candidate.fd < 0) {
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);
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);
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;
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);
1449 candidate.version.uapi_version >= multi_device_uapi_version &&
1450 candidate.identity.device_count ?
1451 candidate.identity.device_count :
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) ?
1460 probe_result::missing_caps;
1462 close_device(candidate);
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) {
1473 BOOST_LOG(error) <<
"[VDISPLAY/Hermes-KMS] SELECT_OUTPUT(" << output_index
1474 <<
") failed: " << std::strerror(errno);
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;
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;
1498 if (::ioctl(fd, ioctl_set_output, &request) != 0) {
1500 BOOST_LOG(error) <<
"[VDISPLAY/Hermes-KMS] SET_OUTPUT failed: " << std::strerror(errno);
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;
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;
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));
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));
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");
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");
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));
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));
1587 BOOST_LOG(error) <<
"[VDISPLAY/Hermes-KMS] Driver accepted SESSION_ACCESS without confirming the binding.";
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) {
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.";
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)) {
1631 if (get_status(device.fd, status) &&
1632 (status.owner_pid > 0 || status.session_id != 0)) {
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)) {
1643 if (errno != EAGAIN || attempt == 5) {
1646 std::this_thread::sleep_for(std::chrono::milliseconds {200});
1650 if (errno == EBUSY) {
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);
1660 device.selected_output_index = index;
1661 refresh_identity(device);
1662 session_id = candidate_session;
1667 BOOST_LOG(error) <<
"[VDISPLAY/Hermes-KMS] No free virtual output is available (configured outputs="
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) {
1697 const int card_index = card_index_from_path(card->card_path);
1698 constexpr unsigned int attempts = 30;
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)) {
1706 for (
auto &remaining : devices) {
1707 close_device(remaining);
1709 broker_card = card->name;
1713 for (
auto &device : devices) {
1714 close_device(device);
1716 std::this_thread::sleep_for(std::chrono::milliseconds {100});
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.";
1726 static bool claim_available_device_output(
1730 uint32_t refresh_hz,
1731 uint64_t &session_id,
1732 std::string &broker_card,
1733 std::optional<uid_t> card_owner_uid
1735 auto devices = open_devices(
true);
1736 for (
auto &device : devices) {
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);
1747 if (!claim_available_output(device, width, height, refresh_hz, session_id,
false)) {
1748 close_device(device);
1754 for (
auto &remaining : devices) {
1755 close_device(remaining);
1761 return claim_broker_card(out, width, height, refresh_hz, session_id, broker_card, card_owner_uid);
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.";
1775 static bool disconnect_unowned_outputs(std::vector<std::string> &connector_names) {
1776 auto devices = open_devices(
false);
1777 if (devices.empty()) {
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)) {
1789 refresh_identity(device);
1790 const auto connector_name = cstr(device.identity.connector_name);
1793 if (get_status(device.fd, status) &&
1794 !(status.flags & status_output_enabled)) {
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);
1811 close_device(device);
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;
1825 std::string guid_str;
1826 std::string client_name;
1837 bool removal_pending {
false};
1839 bool using_hermes_kms;
1840 bool hermes_kms_session_lifecycle;
1841 std::string broker_card;
1842 bool using_hyprland_headless;
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;
1851 static std::map<std::string, VirtualDisplayInfo> virtual_displays;
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
1865 static std::optional<VirtualDisplayInfo> parked_display;
1868 static void release_parked_locked(
const char *reason) {
1869 if (!parked_display) {
1872 BOOST_LOG(info) <<
"[VDISPLAY] Releasing " << parked_display->name <<
", which was kept for the login greeter: "
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);
1878 parked_display.reset();
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);
1888 bool desktop_token_matches(std::string_view token, std::string_view desktop) {
1889 if (token.size() < desktop.size()) {
1892 for (
size_t i = 0; i < desktop.size(); ++i) {
1893 if (std::tolower(
static_cast<unsigned char>(token[i])) != desktop[i]) {
1898 return token.size() == desktop.size() || token[desktop.size()] ==
'-';
1909 bool wlroots_family =
false;
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")) {
1918 if (desktop_token_matches(token,
"gnome")) {
1921 if (desktop_token_matches(token,
"hyprland")) {
1924 if (desktop_token_matches(token,
"cosmic")) {
1930 for (
const auto *wlr : {
"sway",
"wayfire",
"river",
"labwc",
"niri"}) {
1931 if (desktop_token_matches(token, wlr)) {
1935 if (desktop_token_matches(token,
"wlroots")) {
1936 wlroots_family =
true;
1938 if (separator == std::string_view::npos) {
1941 remaining.remove_prefix(separator + 1);
1947 for (
const char *variable : {
"XDG_CURRENT_DESKTOP",
"XDG_SESSION_DESKTOP"}) {
1948 const char *value = std::getenv(variable);
1949 if (value && value[0]) {
1960 struct socket_hint {
1961 const char *variable;
1964 for (
const auto &[variable, compositor] : {
1969 if (
const char *value = std::getenv(variable); value && value[0]) {
1977 switch (compositor) {
1979 return "KWin (KDE Plasma)";
1981 return "Mutter (GNOME)";
1985 return "a wlroots compositor";
1991 return "an unrecognised compositor";
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";
2009 return "unknown feature";
2012 std::string readinessName(readiness_e readiness) {
2013 switch (readiness) {
2014 case readiness_e::ready:
2016 case readiness_e::degraded:
2018 case readiness_e::unavailable:
2019 return "unavailable";
2020 case readiness_e::unknown:
2037 std::string drm_card_seat(
const std::filesystem::path &card) {
2038 std::ifstream dev_file {card /
"dev"};
2040 if (!std::getline(dev_file, devnum) || devnum.empty()) {
2044 std::ifstream udev_db {std::filesystem::path {
"/run/udev/data"} / (
"c" + devnum)};
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());
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") {
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)});
2085 for (
const auto 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."
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."
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."
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.",
2144 "Hermes reads HYPRLAND_INSTANCE_SIGNATURE from its own environment; start it inside "
2145 "the Hyprland session, or import that variable into the service."
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."
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."
2171 "No virtual display can be driven here, so no mode can be applied to one."
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."
2187 const bool exclusive_mechanism = facts.
x11 ||
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."
2199 }
else if (!exclusive_mechanism) {
2208 "The compositor can disable a physical output, but this session has no virtual display "
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.",
2230 "Start Hermes inside the Hyprland session, or import HYPRLAND_INSTANCE_SIGNATURE into the service."
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."
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."
2255 "The loaded hermes-kms driver exposes no session-device pool.",
2256 "Update hermes-kms to a version providing private session devices."
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."
2279 }
else if (facts.
x11) {
2287 "The session advertises no screen-capture protocol Hermes can use."
2293 "A capture protocol is available but linux-dmabuf is not, so frames are copied through the CPU."
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) {
2311 if (is_hermes_kms_card(entry.path()) && drm_card_seat(entry.path()).starts_with(
"hermes-kms-")) {
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};
2322 std::getline(in, value);
2325 const auto ignored_suffix = ignored_connector.empty() ? std::string {} :
"-" + ignored_connector;
2330 std::map<std::string, bool> card_has_connector;
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")) {
2337 const auto dash = name.find(
'-');
2338 if (dash == std::string::npos) {
2339 card_has_connector.try_emplace(name,
false);
2342 if (name.find(
"-Writeback-") != std::string::npos) {
2345 card_has_connector[name.substr(0, dash)] =
true;
2346 if (!ignored_suffix.empty() && name.ends_with(ignored_suffix)) {
2349 if (read_attribute(entry.path() /
"status") !=
"disconnected" &&
2350 read_attribute(entry.path() /
"enabled") ==
"enabled") {
2355 if (ec || card_has_connector.empty()) {
2356 return std::nullopt;
2358 for (
const auto &[card, has_connector] : card_has_connector) {
2359 if (!has_connector) {
2360 return std::nullopt;
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) {
2385 if (status < 0 || !session) {
2386 return std::nullopt;
2388 char *class_raw =
nullptr;
2389 if (sd_session_get_class(session.get(), &class_raw) < 0 || !class_raw) {
2390 return std::nullopt;
2392 const std::unique_ptr<char,
decltype(&std::free)> session_class {class_raw, &std::free};
2393 return std::string_view {session_class.get()} ==
"greeter";
2395 return std::nullopt;
2403 return greeter_on_seat && output_lit && another_connector_lit != std::optional<bool> {
true};
2407 std::lock_guard<std::mutex> lock(vdisplay_mutex);
2408 return parked_display ? parked_display->connector_name : std::string {};
2411 bool waitForConnectorEnabled(
const std::string &connector, std::chrono::milliseconds timeout,
const std::filesystem::path &drm_class) {
2412 if (connector.empty()) {
2417 const auto suffix =
"-" + connector;
2418 const auto deadline = std::chrono::steady_clock::now() + timeout;
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)) {
2428 std::ifstream in {entry.path() /
"enabled"};
2430 std::getline(in, value);
2431 if (value ==
"enabled") {
2435 if (std::chrono::steady_clock::now() >= deadline) {
2438 std::this_thread::sleep_for(std::chrono::milliseconds {100});
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 ==
'_';
2454 const std::string &virtual_output,
2455 const std::map<std::string, int> &enabled_before,
2460 int mode_refresh_hz,
2461 const std::map<std::string, kscreen_point_t> &positions_before,
2464 if (!safe_output_name(virtual_output)) {
2472 std::string command =
"kscreen-doctor";
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)) {
2485 command +=
" output." + output +
".enable";
2487 command +=
" output." + output +
".priority." + std::to_string(priority + shift);
2488 next_priority = std::max(next_priority, priority + shift + 1);
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);
2501 command +=
" output." + virtual_output +
".enable";
2502 command +=
" output." + virtual_output +
".priority." + std::to_string(virtual_primary ? 1 : next_priority);
2508 command +=
" output." + virtual_output +
".enable";
2510 command +=
" output." + virtual_output +
".position." +
2511 std::to_string(target_x) +
',' + std::to_string(target_y);
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);
2531 const std::string &virtual_output,
2532 const std::vector<kscreen_output_t> &before,
2533 const std::vector<kscreen_output_t> ¤t,
2536 std::set<std::string> present;
2537 for (
const auto &output :
current) {
2538 if (output.connected) {
2539 present.insert(output.name);
2544 bool anchored =
false;
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 ||
2551 (check_presence && !present.empty() && !present.contains(output.name))) {
2563 if (output.priority == 1 || !anchored) {
2564 position = {output.x, output.y};
2566 if (output.priority == 1) {
2577 position = {output.x + output.width, output.y};
2580 position.
x = std::max(position.
x, output.x + output.width);
2581 position.
y = std::min(position.
y, output.y);
2586 place_against(before,
true);
2588 place_against(
current,
false);
2594 const std::vector<kscreen_output_t> &outputs,
2595 const std::string &output_name,
2598 int &environment_width,
2599 int &environment_height
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;
2605 if (selected == outputs.end()) {
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) {
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);
2629 const int width = max_x - min_x;
2630 const int height = max_y - min_y;
2631 if (width <= 0 || height <= 0) {
2635 offset_x = selected->x - min_x;
2636 offset_y = selected->y - min_y;
2637 environment_width = width;
2638 environment_height = height;
2646 constexpr std::string_view markers[] {
2647 "applying config failed",
2653 "DBus error from KWin",
2655 "does not support disabling",
2656 "DPMS not supported",
2657 "DPMS is only supported",
2658 "argument not understood",
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);
2669 return std::string {line};
2674 return std::nullopt;
2678 const std::string &json_text,
2679 const std::string &output,
2684 if (json_text.empty() || output.empty() || width <= 0 || height <= 0 || refresh_hz <= 0) {
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) {
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) {
2702 if (std::lround(mode.value(
"refreshRate", 0.0)) != refresh_hz) {
2705 if (!current_mode_id.empty() && mode.value(
"id", std::string {}) == current_mode_id) {
2712 }
catch (
const std::exception &error) {
2713 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] Could not parse the mode list: " << error.what();
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;
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) {
2728 if (!entry.value(
"connected",
false) || !entry.value(
"enabled",
true)) {
2729 return std::nullopt;
2732 return kscreen_hdr_state_t {entry.contains(
"hdr"), entry.value(
"hdr",
false),
2733 entry.contains(
"wcg"), entry.value(
"wcg",
false)};
2735 }
catch (
const std::exception &) {
2738 return std::nullopt;
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);
2746 using output_t = kscreen_output_t;
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};
2769 static std::mutex layouts_mutex;
2770 static std::map<std::string, layout_t> layouts;
2771 static bool startup_recovery_pending {
false};
2773 static bool available() {
2777 return ::access(
"/usr/bin/kscreen-doctor", X_OK) == 0 || ::access(
"/bin/kscreen-doctor", X_OK) == 0;
2780 static std::string command_output(
const char *command) {
2781 bool timed_out =
false;
2784 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] " <<
command <<
" did not answer within "
2787 return output.value_or(std::string {});
2790 static monitor_restore::snapshot_t output_snapshot() {
2791 std::vector<output_t> result;
2793 return std::nullopt;
2796 const auto json_text = command_output(
"kscreen-doctor -j");
2797 if (json_text.empty()) {
2798 return std::nullopt;
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;
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;
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),
2822 if (safe_output_name(output.name)) {
2823 result.emplace_back(std::move(output));
2826 }
catch (
const std::exception &error) {
2827 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] Could not parse output layout: " << error.what();
2828 return std::nullopt;
2833 static std::vector<output_t> outputs() {
2834 return output_snapshot().value_or(std::vector<output_t> {});
2837 static std::set<std::string> connected_output_names(
const std::vector<output_t> ¤t) {
2838 std::set<std::string> result;
2839 for (
const auto &output : current) {
2840 if (output.connected) {
2841 result.insert(output.name);
2847 static std::map<std::string, int> enabled_output_priorities(
const std::vector<output_t> ¤t) {
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);
2857 static bool run_layout_command(
const std::string &command) {
2858 bool timed_out =
false;
2861 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] Layout command "
2862 << (timed_out ?
"did not finish in time and was stopped: " :
"failed: ") << command;
2867 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] The layout was not applied (" << *failure <<
"): " <<
command;
2873 static std::string recovery_state_file() {
2874 const char *xdg_state = std::getenv(
"XDG_STATE_HOME");
2875 const char *home = std::getenv(
"HOME");
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";
2886 fs::create_directories(base, ec);
2887 return base +
"/saved-primary";
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);
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);
2920 if (valid.empty()) {
2924 const auto path = recovery_state_file();
2929 const auto temporary_path = path +
".tmp";
2931 std::ofstream file {temporary_path, std::ios::binary | std::ios::trunc};
2935 for (
const auto &[output, priority] : valid) {
2936 file << output <<
' ' << priority <<
'\n';
2945 fs::rename(temporary_path, path, ec);
2947 fs::remove(temporary_path, ec);
2953 static std::map<std::string, int> read_recovery_state() {
2954 std::map<std::string, int> outputs;
2955 const auto path = recovery_state_file();
2960 std::ifstream file {path};
2962 while (std::getline(file, line)) {
2963 std::istringstream stream {line};
2968 if (!(stream >> output) || !safe_output_name(output)) {
2971 if (!(stream >> priority) || priority < 0) {
2974 outputs.emplace(output, priority);
2979 static void clear_recovery_state() {
2980 const auto path = recovery_state_file();
2985 fs::remove(path, ec);
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));
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());
3003 if (pending.empty()) {
3004 if (!startup_recovery_pending) {
3005 clear_recovery_state();
3009 return write_recovery_state(pending);
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;
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();
3024 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] Physical output recovery is pending; retaining the saved layout.";
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,
3044 int mode_refresh_hz,
3045 virtual_display_layout_e layout
3047 const auto current = outputs();
3049 const int target_x = position.x;
3050 const int target_y = position.y;
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};
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);
3064 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] Refusing to build a layout around output name "
3069 if (!run_layout_command(command)) {
3075 virtual_output, enabled_before, target_x, target_y, 0, 0, 0,
3076 positions_before, layout))) {
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.";
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");
3103 static void recover_after_unowned_virtual_disconnect(
const std::string &virtual_connector) {
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) {
3116 physical_outputs.emplace_back(output.name);
3117 physical_output_enabled = physical_output_enabled || output.enabled;
3120 if (physical_output_enabled) {
3123 if (!physical_outputs.empty()) {
3124 std::string
command =
"kscreen-doctor";
3126 for (
const auto &output : physical_outputs) {
3127 command +=
" output." + output +
".enable";
3128 command +=
" output." + output +
".priority." + std::to_string(priority++);
3130 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] Restoring physical outputs after disconnecting a boot-enabled virtual output.";
3131 run_layout_command(command);
3134 std::this_thread::sleep_for(std::chrono::milliseconds {50});
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,
3145 int mode_refresh_hz,
3146 virtual_display_layout_e layout
3152 const auto outputs_before = connected_output_names(before);
3153 const auto enabled_before = enabled_output_priorities(before);
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;
3162 if (expected != current_outputs.end()) {
3163 virtual_output = expected->name;
3166 for (
const auto &output : current_outputs) {
3167 if (output.connected && outputs_before.find(output.name) == outputs_before.end()) {
3168 virtual_output = output.name;
3174 if (!safe_output_name(virtual_output)) {
3175 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] " << backend_label <<
" output " << connector_name
3176 <<
" was not enumerated by KWin.";
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);
3194 if (!apply_pre_session_layout(virtual_output, before, enabled_before, mode_width, mode_height, mode_refresh_hz, layout)) {
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;
3206 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] Hermes' layout for " << virtual_output
3207 <<
" was not applied; streaming it where KWin placed it.";
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,
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");
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();
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) {
3248 std::string output_name;
3250 std::lock_guard<std::mutex> lock(layouts_mutex);
3251 const auto it = layouts.find(display_name);
3252 if (it == layouts.end()) {
3255 output_name = it->second.virtual_output;
3257 if (!safe_output_name(output_name)) {
3261 const std::string mode = std::to_string(width) +
'x' + std::to_string(height) +
'@' +
3262 std::to_string(refresh_hz);
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 <<
'.';
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.";
3272 case kscreen_mode_state_e::unknown_output:
3276 case kscreen_mode_state_e::advertised:
3280 if (!run_layout_command(
"kscreen-doctor output." + output_name +
".mode." + mode)) {
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.";
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.";
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.";
3301 static bool geometry(
const std::string &display_name,
int &x,
int &y,
int &env_width,
int &env_height) {
3302 std::string output_name;
3304 std::lock_guard<std::mutex> lock(layouts_mutex);
3305 const auto it = layouts.find(display_name);
3306 if (it == layouts.end()) {
3309 output_name = it->second.virtual_output;
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();
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)) {
3341 const auto known = it->second.original_outputs.find(output.name);
3344 known != it->second.original_outputs.end() ? known->second : output.priority
3347 if (targets.empty()) {
3348 targets = it->second.original_outputs;
3350 if (targets.empty()) {
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";
3361 const auto previous = it->second;
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.";
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.";
3375 BOOST_LOG(info) <<
"[VDISPLAY/KScreen] Exclusive mode disabled " << targets.size()
3376 <<
" physical output(s) in favour of " << it->second.virtual_output;
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()) {
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) {
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.";
3402 layout.restore_pending =
false;
3403 if (release_layout) {
3406 persist_pending_recovery();
3410 static bool restore_all() {
3411 std::vector<std::string> names;
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);
3420 bool restored =
true;
3421 for (
const auto &name : names) {
3422 restored =
restore(name,
false) && restored;
3427 static bool retry_pending_restores() {
3428 std::vector<std::pair<std::string, bool>> pending;
3429 bool retry_startup =
false;
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);
3439 if (retry_startup) {
3440 recover_on_startup();
3442 bool restored =
true;
3443 for (
const auto &[name, release_layout] : pending) {
3444 restored =
restore(name, release_layout) && restored;
3446 std::lock_guard<std::mutex> lock(layouts_mutex);
3447 return restored && !startup_recovery_pending;
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 ==
'_';
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 ==
'}';
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";
3510 static std::string input_binding_read_command(
const std::string &device_name) {
3511 if (!safe_input_device_name(device_name)) {
3514 return "kreadconfig6 " + input_binding_key_args(device_name) +
" 2>/dev/null";
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)) {
3521 const auto prefix =
"kwriteconfig6 --notify " + input_binding_key_args(device_name);
3522 if (previous_uuid.empty()) {
3523 return prefix +
" --delete 2>/dev/null";
3525 if (!uuid_like(previous_uuid)) {
3528 return prefix +
" '" + previous_uuid +
"' 2>/dev/null";
3531 static bool is_hermes_input_device(
const std::string &name, uint32_t vendor, uint32_t product) {
3533 std::any_of(bound_device_names.begin(), bound_device_names.end(), [&name](
const char *bound) {
3534 return name == bound;
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;
3543 return have(
"kreadconfig6") && have(
"kwriteconfig6");
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";
3551 struct input_binding_t {
3552 sd_bus *bus {
nullptr};
3553 sd_bus_slot *slot {
nullptr};
3555 std::atomic<bool>
stop {
false};
3559 std::array<std::string, bound_device_names.size()> previous_uuids;
3561 std::mutex output_mutex;
3565 static std::mutex input_binding_mutex;
3566 static std::unique_ptr<input_binding_t> input_binding;
3568 static void bind_input_device(input_binding_t &binding,
const std::string &sys_name,
bool only_unbound =
false) {
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);
3575 const std::string path = std::string {input_device_manager_path} +
'/' + sys_name;
3577 char *name =
nullptr;
3578 uint32_t vendor = 0;
3579 uint32_t product = 0;
3580 sd_bus_error error = SD_BUS_ERROR_NULL;
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 :
"";
3588 if (!read || !is_hermes_input_device(device_name, vendor, product)) {
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;
3599 sd_bus_error_free(&error);
3600 if (!known || has_output) {
3607 std::lock_guard<std::mutex> lock(binding.output_mutex);
3608 output = binding.output;
3610 const int set = sd_bus_set_property(
3614 input_device_interface,
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.";
3625 BOOST_LOG(info) <<
"[VDISPLAY/KScreen] Bound " << device_name <<
" (" << sys_name <<
") to " << output <<
'.';
3627 sd_bus_error_free(&error);
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);
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);
3650 sd_bus_message_exit_container(reply);
3652 sd_bus_message_unref(reply);
3653 sd_bus_error_free(&error);
3655 for (
const auto &sys_name : sys_names) {
3656 bind_input_device(binding, sys_name,
true);
3660 static int on_input_device_added(sd_bus_message *message,
void *userdata, sd_bus_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);
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]);
3673 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] Could not restore the output " << bound_device_names[i]
3674 <<
" was bound to before the session.";
3686 static void map_input_devices_to(
const std::string &owner,
const std::string &output);
3688 static void map_input_devices(
const std::string &display_name) {
3691 std::lock_guard<std::mutex> lock(layouts_mutex);
3692 const auto it = layouts.find(display_name);
3693 if (it == layouts.end()) {
3696 output = it->second.virtual_output;
3698 map_input_devices_to(display_name, output);
3706 static void map_input_devices_to(
const std::string &owner,
const std::string &output) {
3707 if (!safe_output_name(output)) {
3711 std::lock_guard<std::mutex> lock(input_binding_mutex);
3712 if (input_binding) {
3716 std::lock_guard<std::mutex> output_lock(input_binding->output_mutex);
3717 input_binding->output = output;
3719 input_binding->owner = owner;
3720 BOOST_LOG(info) <<
"[VDISPLAY/KScreen] Touch and pen input from new clients now goes to " << output <<
'.';
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 "
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();
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.";
3745 started->previous_uuids[i] = std::move(previous);
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.";
3758 sd_bus_set_method_call_timeout(started->bus, 2000000);
3759 const int matched = sd_bus_match_signal(
3763 input_device_manager_path,
3764 "org.kde.KWin.InputDeviceManager",
3766 on_input_device_added,
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);
3775 started->owner = owner;
3776 started->output = output;
3785 bind_existing_devices(*started);
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) {
3794 if (processed > 0) {
3799 if (sd_bus_wait(raw->bus, 250000 ) < 0) {
3804 input_binding = std::move(started);
3805 BOOST_LOG(info) <<
"[VDISPLAY/KScreen] Touch and pen input from this session will be bound to " << output <<
'.';
3813 static void unmap_input_devices(
const std::string &display_name) {
3814 std::unique_ptr<input_binding_t> stopping;
3816 std::lock_guard<std::mutex> lock(input_binding_mutex);
3817 if (!input_binding || input_binding->owner != display_name) {
3820 std::string successor;
3821 std::string successor_output;
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)) {
3827 successor_output = layout.virtual_output;
3832 if (!successor.empty()) {
3834 std::lock_guard<std::mutex> output_lock(input_binding->output_mutex);
3835 input_binding->output = successor_output;
3837 input_binding->owner = successor;
3838 BOOST_LOG(info) <<
"[VDISPLAY/KScreen] Touch and pen input from new clients now goes to "
3839 << successor_output <<
'.';
3842 stopping = std::move(input_binding);
3845 stopping->stop.store(
true, std::memory_order_relaxed);
3846 if (stopping->thread.joinable()) {
3847 stopping->thread.join();
3849 if (stopping->slot) {
3850 sd_bus_slot_unref(stopping->slot);
3852 if (stopping->bus) {
3853 sd_bus_unref(stopping->bus);
3855 restore_input_bindings(*stopping);
3856 BOOST_LOG(info) <<
"[VDISPLAY/KScreen] Released the touch and pen input binding.";
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.";
3868 static void unmap_input_devices(
const std::string & ) {}
3870 static void map_input_devices_to(
const std::string & ,
const std::string & ) {
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.";
3876#ifdef HERMES_BUILD_SDBUS
3889 std::mutex placements_mutex;
3890 std::map<std::string, std::string> placements;
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;
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);
3903 status = sd_bus_call(bus, message, 2000000, &error, reply);
3905 sd_bus_message_unref(message);
3907 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] KWin scripting " << method <<
" failed: "
3908 << (error.message ? error.message : std::strerror(-status));
3910 sd_bus_error_free(&error);
3914 static void place_windows(
const std::string &display_name,
const std::vector<std::string> &classes,
const std::vector<std::uint32_t> &gamescope_pids) {
3917 std::lock_guard<std::mutex> lock(layouts_mutex);
3918 const auto it = layouts.find(display_name);
3919 if (it == layouts.end()) {
3922 output = it->second.virtual_output;
3924 if (!safe_output_name(output) || classes.empty()) {
3927 const auto contents = platf::window_placement::kwin_script(output, classes, gamescope_pids);
3928 if (contents.empty()) {
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");
3936 std::filesystem::create_directories(directory, ec);
3938 std::ofstream file {script, std::ios::trunc};
3941 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] Could not write " << script.string() <<
"; windows stay where KWin opens them.";
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 <<
'.';
3952 call_kwin_scripting(bus,
"/Scripting",
"org.kde.kwin.Scripting",
"unloadScript",
nullptr,
"s", plugin.c_str());
3953 sd_bus_message *reply =
nullptr;
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);
3959 bool running =
false;
3961 const auto path =
"/Scripting/Script" + std::to_string(
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);
3968 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] KWin did not run the window placement script; windows stay where KWin opens them.";
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.";
3976 static void unplace_windows(
const std::string &display_name) {
3979 std::lock_guard<std::mutex> lock(placements_mutex);
3980 const auto it = placements.find(display_name);
3981 if (it == placements.end()) {
3984 plugin = std::move(it->second);
3985 placements.erase(it);
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());
3993 std::filesystem::remove(std::filesystem::path {
"/run/user"} / std::to_string(::getuid()) /
"hermes" / (plugin +
".js"), ec);
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 &) {}
4001 static bool any_layout_active() {
4002 std::lock_guard<std::mutex> lock(layouts_mutex);
4003 return !layouts.empty();
4022 return ::access(
"/usr/bin/gdbus", X_OK) == 0 || ::access(
"/bin/gdbus", X_OK) == 0;
4025 static std::string command_output(
const char *command) {
4026 std::array<char, 8192> buffer {};
4028 FILE *pipe = ::popen(command,
"r");
4032 while (::fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe)) {
4033 output += buffer.data();
4035 if (::pclose(pipe) != 0) {
4061 enum class apply_method :
unsigned {
4071 std::string transform;
4072 std::string primary;
4073 std::vector<std::string> connectors;
4080 double refresh {0.0};
4081 bool current {
false};
4085 std::string connector;
4089 std::string product;
4091 std::vector<mode_t> modes;
4103 std::vector<monitor_t> monitors;
4104 std::vector<logical_monitor_t> logical_monitors;
4108 bool global_scale_required {
false};
4110 const monitor_t *find_monitor(
const std::string &connector)
const {
4111 for (
const auto &monitor : monitors) {
4112 if (monitor.connector == connector) {
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()) {
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;
4143 if (lm.connectors.empty()) {
4147 const auto *monitor = find_monitor(lm.connectors.front());
4151 const mode_t *mode =
nullptr;
4152 for (
const auto &candidate : monitor->modes) {
4153 if (candidate.id ==
current->second) {
4158 if (!mode || mode->width <= 0 || mode->height <= 0) {
4162 double w = mode->width;
4163 double h = mode->height;
4165 const int transform = std::atoi(lm.transform.c_str());
4166 if (transform == 1 || transform == 3 || transform == 5 || transform == 7) {
4170 const double scale = scale_of(lm);
4175 width =
static_cast<int>(std::lround(w));
4176 height =
static_cast<int>(std::lround(h));
4177 return width > 0 && height > 0;
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";
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 ==
':';
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) {
4200 const size_t last = value.find_last_not_of(
" \t\n\r");
4201 return value.substr(first, last - first + 1);
4205 static std::vector<std::string> split_variant(
const std::string &body) {
4206 std::vector<std::string> parts;
4208 bool in_string =
false;
4211 for (
size_t i = 0; i < body.size(); ++i) {
4212 const char c = body[i];
4216 }
else if (c ==
'\'') {
4239 parts.emplace_back(trim_variant(body.substr(start, i - start)));
4247 parts.emplace_back(trim_variant(body.substr(start)));
4251 static bool strip_variant(std::string &value,
char open,
char close) {
4252 if (value.size() < 2 || value.front() != open || value.back() != close) {
4255 value = trim_variant(value.substr(1, value.size() - 2));
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);
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);
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) {
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,
'(',
')')) {
4289 const auto top = split_variant(body);
4290 if (top.size() != 4) {
4294 out.serial = numeric_variant(top[0]);
4295 if (out.serial.empty()) {
4299 std::string monitors = top[1];
4300 if (!strip_variant(monitors,
'[',
']')) {
4303 for (
const auto &entry : split_variant(monitors)) {
4304 std::string monitor = entry;
4305 if (!strip_variant(monitor,
'(',
')')) {
4308 const auto fields = split_variant(monitor);
4309 if (fields.size() < 2) {
4312 std::string spec = fields[0];
4313 if (!strip_variant(spec,
'(',
')')) {
4316 const auto spec_fields = split_variant(spec);
4317 if (spec_fields.empty()) {
4320 const std::string connector = unquote_variant(spec_fields[0]);
4321 std::string modes = fields[1];
4322 if (connector.empty() || !strip_variant(modes,
'[',
']')) {
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]);
4332 for (
const auto &mode_entry : split_variant(modes)) {
4333 std::string mode = mode_entry;
4334 if (!strip_variant(mode,
'(',
')')) {
4337 const auto mode_fields = split_variant(mode);
4338 if (mode_fields.size() < 7) {
4343 parsed_mode.id = unquote_variant(mode_fields[0]);
4344 if (parsed_mode.id.empty()) {
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;
4354 parsed_monitor.modes.emplace_back(std::move(parsed_mode));
4356 out.monitors.emplace_back(std::move(parsed_monitor));
4360 if (!strip_variant(logical,
'[',
']')) {
4363 for (
const auto &entry : split_variant(logical)) {
4364 std::string lm = entry;
4365 if (!strip_variant(lm,
'(',
')')) {
4368 const auto fields = split_variant(lm);
4369 if (fields.size() < 6) {
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]);
4380 std::string specs = fields[5];
4381 if (!strip_variant(specs,
'[',
']')) {
4384 for (
const auto &spec_entry : split_variant(specs)) {
4385 std::string spec = spec_entry;
4386 if (!strip_variant(spec,
'(',
')')) {
4389 const auto spec_fields = split_variant(spec);
4390 if (spec_fields.empty()) {
4393 const std::string connector = unquote_variant(spec_fields[0]);
4394 if (!connector.empty()) {
4395 parsed.connectors.emplace_back(connector);
4399 if (!parsed.connectors.empty()) {
4400 out.logical_monitors.emplace_back(std::move(parsed));
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) {
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;
4421 }
else if (key ==
"global-scale-required") {
4422 out.global_scale_required = numeric_variant(value) ==
"true";
4427 return !out.logical_monitors.empty();
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 = {}) {
4436 for (
size_t i = 0; i < layout.size(); ++i) {
4437 const auto &lm = layout[i];
4438 if (lm.primary !=
"true" && lm.primary !=
"false") {
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()) {
4451 BOOST_LOG(warning) <<
"[VDISPLAY/Mutter] No mode known for " << connector <<
"; leaving the layout alone.";
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.";
4458 argument += (j ?
", ('" :
"('");
4459 argument += connector +
"', '" + mode_id +
"', @a{sv} {})";
4467 static bool run_apply(
const state_t &state,
const std::string &argument, apply_method method) {
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";
4475 std::array<char, 4096> buffer {};
4477 FILE *pipe = ::popen(
command.c_str(),
"r");
4481 while (::fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe)) {
4482 output += buffer.data();
4484 if (::pclose(pipe) != 0) {
4485 BOOST_LOG(warning) <<
"[VDISPLAY/Mutter] ApplyMonitorsConfig ("
4486 << (method == apply_method::verify ?
"verify" :
"apply")
4487 <<
") failed: " << trim_variant(output);
4506 static layout_repair build_layout_without(
const std::string &reply,
4507 const std::string &virtual_connector,
4509 std::string &argument) {
4512 if (reply.empty() || virtual_connector.empty() || !parse_current_state(reply, state)) {
4513 return layout_repair::unavailable;
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),
4525 if (lm.connectors.size() == before) {
4526 kept.emplace_back(std::move(lm));
4530 if (lm.connectors.empty()) {
4531 dropped_primary = dropped_primary || lm.primary ==
"true";
4533 kept.emplace_back(std::move(lm));
4538 return layout_repair::not_needed;
4541 return layout_repair::unsafe;
4543 if (dropped_primary) {
4544 kept.front().primary =
"true";
4546 return build_apply_argument(state, kept, argument) ? layout_repair::ready : layout_repair::unsafe;
4556 static void recover_after_unowned_virtual_disconnect(
const std::string &virtual_connector) {
4557 if (!
available() || virtual_connector.empty()) {
4561 for (
int attempt = 0; attempt < 20; ++attempt) {
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});
4568 case layout_repair::not_needed:
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.";
4574 case layout_repair::ready:
4580 if (!run_apply(state, argument, apply_method::verify)) {
4584 BOOST_LOG(warning) <<
"[VDISPLAY/Mutter] Dropping boot-enabled virtual output " << virtual_connector
4585 <<
" from Mutter's layout.";
4588 run_apply(state, argument, apply_method::temporary);
4609 static mode_push build_layout_with_mode(
const std::string &reply,
4610 const std::string &connector,
4613 uint32_t refresh_mhz,
4615 std::string &argument) {
4618 if (reply.empty() || connector.empty() || !width || !height || !parse_current_state(reply, state)) {
4619 return mode_push::unavailable;
4622 const monitor_t *monitor = state.find_monitor(connector);
4624 return mode_push::unavailable;
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;
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)) {
4639 if (!chosen || refresh_delta(mode.refresh) < refresh_delta(chosen->refresh)) {
4644 return mode_push::unsupported;
4646 if (chosen->current) {
4647 return mode_push::already_set;
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();
4654 if (owner == layout.end()) {
4661 for (
const auto &lm : layout) {
4664 if (!state.logical_size(lm, lm_width, lm_height)) {
4667 return mode_push::unavailable;
4669 right_edge = std::max(right_edge, std::atoi(lm.x.c_str()) + lm_width);
4671 logical_monitor_t added;
4672 added.x = std::to_string(right_edge);
4677 added.scale =
"1.0";
4678 if (state.global_scale_required && !layout.empty() && !layout.front().scale.empty()) {
4679 added.scale = layout.front().scale;
4681 added.transform =
"0";
4682 added.primary = layout.empty() ?
"true" :
"false";
4683 added.connectors.emplace_back(connector);
4684 layout.emplace_back(std::move(added));
4687 return build_apply_argument(state, layout, argument, {{connector, chosen->id}}) ? mode_push::ready :
4696 static bool mode_confirmed(
const std::string &connector,
4699 uint32_t refresh_mhz,
4700 std::chrono::steady_clock::time_point deadline) {
4701 while (std::chrono::steady_clock::now() < deadline) {
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:
4708 case mode_push::unavailable:
4711 BOOST_LOG(debug) <<
"[VDISPLAY/Mutter] Could not read back the state of " << connector
4712 <<
"; assuming the applied mode holds.";
4715 std::this_thread::sleep_for(std::chrono::milliseconds {100});
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.";
4744 static bool apply_output_mode(
const std::string &connector,
4747 uint32_t refresh_mhz,
4749 if (!
available() || connector.empty() || !width || !height) {
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};
4763 while (std::chrono::steady_clock::now() < appear_deadline) {
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:
4770 std::this_thread::sleep_for(std::chrono::milliseconds {100});
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.";
4776 case mode_push::already_set:
4777 BOOST_LOG(info) <<
"[VDISPLAY/Mutter] " << connector <<
" is already driven at the requested mode.";
4779 case mode_push::ready:
4783 if (!run_apply(state, argument, apply_method::verify)) {
4787 BOOST_LOG(info) <<
"[VDISPLAY/Mutter] Driving " << connector <<
" at " << width <<
"x" << height <<
"@"
4788 << (refresh_mhz / 1000) <<
"Hz for this session.";
4793 if (!run_apply(state, argument, apply_method::temporary)) {
4803 return mode_confirmed(connector, width, height, refresh_mhz,
4804 std::chrono::steady_clock::now() + confirm_budget);
4807 BOOST_LOG(warning) <<
"[VDISPLAY/Mutter] " << connector <<
" never appeared in Mutter's monitor state.";
4832 static bool geometry_from_state(
const state_t &state,
4833 const std::string &connector,
4835 int &env_width,
int &env_height) {
4836 if (connector.empty()) {
4840 const logical_monitor_t *owner = state.find_logical_monitor(connector);
4842 BOOST_LOG(debug) <<
"[VDISPLAY/Mutter] " << connector
4843 <<
" is not in the monitor layout; absolute input has no offset to apply.";
4847 double envelope_width = 0.0;
4848 double envelope_height = 0.0;
4849 for (
const auto &lm : state.logical_monitors) {
4852 if (!state.logical_size(lm, lm_width, lm_height)) {
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));
4858 if (envelope_width <= 0.0 || envelope_height <= 0.0) {
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;
4874 static bool geometry(
const std::string &connector,
int &x,
int &y,
int &env_width,
int &env_height) {
4875 if (!
available() || connector.empty()) {
4880 if (!parse_current_state(command_output(get_current_state_command), state)) {
4883 return geometry_from_state(state, connector, x, y, env_width, env_height);
4908 static std::mutex layouts_mutex;
4909 static std::map<std::string, layout_state_t> layouts;
4916 static bool safe_apply_argument(
const std::string &argument) {
4917 if (argument.empty() || argument.size() > 8192) {
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 ==
':';
4927 static std::string recovery_state_file() {
4928 const char *xdg_state = std::getenv(
"XDG_STATE_HOME");
4929 const char *home = std::getenv(
"HOME");
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";
4940 fs::create_directories(base, ec);
4941 return base +
"/saved-mutter-layout";
4951 static void write_recovery_state(
const std::string &reply,
const std::string &virtual_connector) {
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.";
4961 const auto path = recovery_state_file();
4965 const auto temporary_path = path +
".tmp";
4967 std::ofstream file {temporary_path, std::ios::binary | std::ios::trunc};
4971 file << argument <<
'\n';
4974 fs::rename(temporary_path, path, ec);
4976 fs::remove(temporary_path, ec);
4980 static void clear_recovery_state() {
4981 const auto path = recovery_state_file();
4986 fs::remove(path, ec);
4990 static bool apply_argument(
const std::string &argument) {
4991 if (!safe_apply_argument(argument)) {
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.";
4999 if (!run_apply(state, argument, apply_method::verify)) {
5002 return run_apply(state, argument, apply_method::temporary);
5005 static void recover_on_startup() {
5009 const auto path = recovery_state_file();
5013 std::string argument;
5015 std::ifstream file {path};
5019 std::getline(file, argument);
5021 if (argument.empty()) {
5022 clear_recovery_state();
5025 if (!safe_apply_argument(argument)) {
5026 BOOST_LOG(warning) <<
"[VDISPLAY/Mutter] Discarding an unreadable saved layout.";
5027 clear_recovery_state();
5032 if (!parse_current_state(command_output(get_current_state_command), state)) {
5034 BOOST_LOG(warning) <<
"[VDISPLAY/Mutter] Startup recovery deferred: Mutter did not answer.";
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();
5047 BOOST_LOG(warning) <<
"[VDISPLAY/Mutter] The saved layout no longer applies to this desktop; discarding it.";
5048 clear_recovery_state();
5059 static bool build_restore_layout(
const state_t &state, std::string &argument) {
5060 return build_apply_argument(state, state.logical_monitors, argument);
5068 static layout_change build_exclusive_layout(
const std::string &reply,
5069 const std::string &connector,
5071 std::string &argument) {
5074 if (reply.empty() || connector.empty() || !parse_current_state(reply, state)) {
5075 return layout_change::unavailable;
5077 if (state.current_mode.find(connector) == state.current_mode.end()) {
5080 return layout_change::unsupported;
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;
5088 logical_monitor_t only;
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);
5099 return build_apply_argument(state, {only}, argument) ? layout_change::ready :
5108 static layout_change build_mirror_layout(
const std::string &reply,
5109 const std::string &connector,
5111 std::string &argument,
5112 int *mirrored_width =
nullptr,
5113 int *mirrored_height =
nullptr) {
5116 if (reply.empty() || connector.empty() || !parse_current_state(reply, state)) {
5117 return layout_change::unavailable;
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;
5129 if (!target || lm.primary ==
"true") {
5133 if (!target || target->connectors.empty()) {
5134 return layout_change::unsupported;
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;
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;
5150 return layout_change::unavailable;
5155 const monitor_t *virtual_monitor = state.find_monitor(connector);
5156 if (!virtual_monitor) {
5157 return layout_change::unavailable;
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) {
5165 std::abs(mode.refresh - target_mode->refresh) < std::abs(chosen->refresh - target_mode->refresh)) {
5170 return layout_change::unsupported;
5173 if (mirrored_width) {
5174 *mirrored_width = target_mode->width;
5176 if (mirrored_height) {
5177 *mirrored_height = target_mode->height;
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),
5191 if (lm.connectors.empty()) {
5194 if (lm.connectors.front() == target_connector) {
5195 lm.connectors.emplace_back(connector);
5198 layout.emplace_back(std::move(lm));
5200 if (layout.empty() || !mirrored) {
5201 return layout_change::unavailable;
5204 return build_apply_argument(state, layout, argument, {{connector, chosen->id}}) ?
5205 layout_change::ready :
5216 static bool make_exclusive(
const std::string &display_name,
const std::string &connector) {
5217 if (!
available() || connector.empty()) {
5221 const auto reply = command_output(get_current_state_command);
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.";
5228 case layout_change::unsupported:
5229 BOOST_LOG(warning) <<
"[VDISPLAY/Mutter] " << connector
5230 <<
" is not being driven; refusing to hand it the desktop.";
5232 case layout_change::unavailable:
5233 BOOST_LOG(warning) <<
"[VDISPLAY/Mutter] Could not read the monitor state; leaving the layout alone.";
5235 case layout_change::ready:
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.";
5248 write_recovery_state(reply, connector);
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();
5258 std::lock_guard<std::mutex> lock(layouts_mutex);
5259 layouts[display_name] = {.restore_argument = std::move(restore_argument), .active =
true};
5261 BOOST_LOG(info) <<
"[VDISPLAY/Mutter] " << connector <<
" has the desktop for this session.";
5273 static bool apply_mirror(
const std::string &display_name,
const std::string &connector) {
5274 if (!
available() || connector.empty()) {
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
5285 case layout_change::already_set:
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.";
5292 case layout_change::unavailable:
5293 BOOST_LOG(warning) <<
"[VDISPLAY/Mutter] Could not read the monitor state; not mirroring.";
5295 case layout_change::ready:
5299 std::string restore_argument;
5300 if (!build_restore_layout(state, restore_argument)) {
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.";
5311 std::lock_guard<std::mutex> lock(layouts_mutex);
5312 layouts[display_name] = {.restore_argument = std::move(restore_argument), .active =
true};
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.";
5357 "org.gnome.desktop.peripherals.touchscreen",
"touchscreens"
5359 static constexpr device_settings_t pen_settings {
5360 "org.gnome.desktop.peripherals.tablet",
"tablets"
5364 static std::string device_settings_target(
const device_settings_t &device) {
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 +
"/";
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 ==
',';
5392 static std::string device_output_value(
const state_t &state,
const std::string &connector) {
5393 const monitor_t *monitor = state.find_monitor(connector);
5397 if (!safe_edid_field(monitor->vendor) || !safe_edid_field(monitor->product) ||
5398 !safe_edid_field(monitor->serial) || !safe_variant_token(monitor->connector)) {
5404 if (monitor->vendor.empty() && monitor->product.empty() && monitor->serial.empty()) {
5407 return "['" + monitor->vendor +
"', '" + monitor->product +
"', '" + monitor->serial +
"', '" +
5408 monitor->connector +
"']";
5412 bool active {
false};
5416 std::string previous_pen;
5419 static std::mutex input_mapping_mutex;
5423 const std::string command =
"gsettings get " + device_settings_target(device) +
" output 2>/dev/null";
5424 return trim_variant(command_output(command.c_str()));
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 +
5430 return std::system(command.c_str()) == 0;
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());
5439 static bool is_unset_output_value(
const std::string &value) {
5440 return value.empty() || value ==
"['', '', '']" || value ==
"@as []" || value ==
"[]";
5449 static void map_input_devices(
const std::string &connector) {
5450 if (!
available() || connector.empty()) {
5455 if (!parse_current_state(command_output(get_current_state_command), state)) {
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.";
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);
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?";
5478 input_mapping.active =
true;
5479 BOOST_LOG(info) <<
"[VDISPLAY/Mutter] Touch and pen input bound to " << connector <<
'.';
5483 static void unmap_input_devices() {
5484 std::lock_guard<std::mutex> lock(input_mapping_mutex);
5485 if (!input_mapping.active) {
5488 const auto put_back = [](
const device_settings_t &device,
const std::string &previous) {
5492 if (is_unset_output_value(previous) || !safe_apply_argument(previous)) {
5493 reset_device_setting(device);
5495 write_device_setting(device, previous);
5499 put_back(pen_settings, input_mapping.previous_pen);
5501 BOOST_LOG(info) <<
"[VDISPLAY/Mutter] Released the touch and pen input binding.";
5505 static void restore(
const std::string &display_name) {
5506 std::string argument;
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) {
5513 argument = it->second.restore_argument;
5517 if (apply_argument(argument)) {
5518 clear_recovery_state();
5519 BOOST_LOG(info) <<
"[VDISPLAY/Mutter] Restored the display layout the session found.";
5522 BOOST_LOG(warning) <<
"[VDISPLAY/Mutter] Could not restore the display layout; keeping the recovery state "
5523 "so the next start can.";
5554 static std::atomic<uint64_t> layout_generation {1};
5556#ifdef HERMES_BUILD_SDBUS
5558 sd_bus *bus {
nullptr};
5559 sd_bus_slot *slot {
nullptr};
5561 std::atomic<bool>
stop {
false};
5566 std::string signature;
5569 static std::mutex watcher_mutex;
5570 static std::unique_ptr<watcher_t> watcher;
5573 static std::string layout_signature() {
5575 std::string signature;
5576 if (!parse_current_state(command_output(get_current_state_command), state) ||
5577 !build_restore_layout(state, signature)) {
5583 static int on_monitors_changed(sd_bus_message * ,
void *userdata, sd_bus_error * ) {
5584 auto *state =
static_cast<watcher_t *
>(userdata);
5585 const auto signature = layout_signature();
5586 if (signature.empty() || signature == state->signature) {
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.";
5597 static void watch_layout() {
5602 std::lock_guard<std::mutex> lock(watcher_mutex);
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") <<
'.';
5614 started->signature = layout_signature();
5616 const int matched = sd_bus_match_signal(
5619 "org.gnome.Mutter.DisplayConfig",
5620 "/org/gnome/Mutter/DisplayConfig",
5621 "org.gnome.Mutter.DisplayConfig",
5623 on_monitors_changed,
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);
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) {
5641 if (processed > 0) {
5646 if (sd_bus_wait(raw->bus, 250000 ) < 0) {
5651 watcher = std::move(started);
5652 BOOST_LOG(info) <<
"[VDISPLAY/Mutter] Watching the desktop layout for changes.";
5655 static void unwatch_layout() {
5656 std::unique_ptr<watcher_t> stopping;
5658 std::lock_guard<std::mutex> lock(watcher_mutex);
5659 stopping = std::move(watcher);
5664 stopping->stop.store(
true, std::memory_order_relaxed);
5665 if (stopping->thread.joinable()) {
5666 stopping->thread.join();
5668 if (stopping->slot) {
5669 sd_bus_slot_unref(stopping->slot);
5671 if (stopping->bus) {
5672 sd_bus_unref(stopping->bus);
5678 static void watch_layout() {}
5680 static void unwatch_layout() {}
5684 EvdiBuffer::EvdiBuffer(uint32_t width, uint32_t height):
5685 data_(static_cast<size_t>(width) * height * 4, 0), width_(width), height_(height) {
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_);
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);
5700 return frame_number();
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();
5709 void EvdiBuffer::begin_write() {
5713 void EvdiBuffer::end_write() {
5717 void EvdiBuffer::mark_updated() {
5718 frame_number_.fetch_add(1, std::memory_order_release);
5719 condition_.notify_all();
5726 static bool load_evdi_library() {
5732 const char *lib_names[] = {
5735 "/usr/lib/libevdi.so.1",
5736 "/usr/lib/libevdi.so",
5737 "/usr/local/lib/libevdi.so.1",
5738 "/usr/local/lib/libevdi.so"
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;
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.";
5757 #define LOAD_EVDI_FUNC(name) \
5758 evdi.name = (fn_evdi_##name)dlsym(evdi.lib_handle, "evdi_" #name); \
5760 BOOST_LOG(error) << "[VDISPLAY] Failed to load evdi_" #name; \
5761 dlclose(evdi.lib_handle); \
5762 evdi.lib_handle = nullptr; \
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);
5780 #undef LOAD_EVDI_FUNC
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);
5797 static void unload_evdi_library() {
5798 if (evdi.lib_handle) {
5799 dlclose(evdi.lib_handle);
5800 evdi.lib_handle =
nullptr;
5802 evdi.loaded =
false;
5803 evdi_library_version.clear();
5810 static bool check_evdi_module_loaded(
bool log_result =
true) {
5812 std::ifstream modules(
"/proc/modules");
5814 while (std::getline(modules, line)) {
5815 if (line.find(
"evdi") != std::string::npos) {
5817 BOOST_LOG(info) <<
"[VDISPLAY] EVDI kernel module is loaded.";
5824 if (fs::exists(
"/sys/module/evdi")) {
5826 BOOST_LOG(info) <<
"[VDISPLAY] EVDI kernel module detected via sysfs.";
5832 BOOST_LOG(warning) <<
"[VDISPLAY] EVDI kernel module is not loaded.";
5833 BOOST_LOG(warning) <<
"[VDISPLAY] Try: sudo modprobe evdi";
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",
5848 return std::any_of(library_paths.begin(), library_paths.end(), [](
const auto *path) {
5849 return fs::exists(path);
5853 static bool evdi_module_installed_for_running_kernel() {
5854 utsname system_info {};
5855 if (uname(&system_info) != 0) {
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))) {
5871 static bool evdi_dkms_build_failed() {
5872 const fs::path dkms_root =
"/var/lib/dkms/evdi";
5874 if (!fs::exists(dkms_root, ec)) {
5878 utsname system_info {};
5879 if (uname(&system_info) != 0) {
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;
5887 if (it->path().filename() !=
"make.log") {
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)) {
5903 static std::string running_kernel_release() {
5904 utsname system_info {};
5905 return uname(&system_info) == 0 ? system_info.release :
"unknown";
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;
5912 for (
const auto &version : fs::directory_iterator(dkms_root, fs::directory_options::skip_permission_denied, ec)) {
5913 if (ec || !
version.is_directory()) {
5916 for (
const auto &kernel : fs::directory_iterator(
version.path(), fs::directory_options::skip_permission_denied, ec)) {
5917 if (ec || !kernel.is_directory()) {
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;
5927 if (module_present) {
5928 kernels.emplace_back(
version.path().filename().string() +
" / " + kernel.path().filename().string());
5936 constexpr auto count_path =
"/sys/devices/evdi/count";
5937 constexpr auto add_path =
"/sys/devices/evdi/add";
5939 std::ifstream count_file(count_path);
5940 int device_count = -1;
5941 count_file >> device_count;
5943 return device_count == 0 && access(add_path, W_OK) != 0;
5949 static bool kernel_module_loaded(
const std::string &module_name) {
5950 std::ifstream modules(
"/proc/modules");
5952 while (std::getline(modules, line)) {
5954 if (line.rfind(module_name +
" ", 0) == 0) {
5958 return fs::exists(fs::path(
"/sys/module") / module_name);
5961 static bool dkms_module_installed_for_running_kernel(
const std::string &module_file) {
5962 utsname system_info {};
5963 if (uname(&system_info) != 0) {
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))) {
5984 static std::string dkms_version_for_running_kernel(
const std::string &dkms_name) {
5985 utsname system_info {};
5986 if (uname(&system_info) != 0) {
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),
5996 if (ec || target.empty()) {
6001 if (target.is_absolute()) {
6002 return target.parent_path().parent_path().filename().string();
6004 return target.begin()->string();
6013 static std::string release_of(
const std::string &version) {
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); })) {
6023 release += (parts ?
"." :
"") + part;
6027 return parts == 3 ?
release : std::string {};
6040 static std::string inaccessible_hermes_kms_render_node() {
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")) {
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") {
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()) {
6061 const auto node = fs::path(
"/dev/dri") / name;
6062 if (::access(node.c_str(), R_OK) != 0 && errno == EACCES) {
6063 return node.string();
6069 static bool dkms_build_failed(
const std::string &dkms_name) {
6070 const fs::path dkms_root = fs::path(
"/var/lib/dkms") / dkms_name;
6072 if (!fs::exists(dkms_root, ec)) {
6076 utsname system_info {};
6077 if (uname(&system_info) != 0) {
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;
6085 if (it->path().filename() !=
"make.log") {
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)) {
6102 if (!evdi_library_installed()) {
6103 return EVDI_DIAGNOSTIC::LIBRARY_MISSING;
6106 if (!check_evdi_module_loaded(
false)) {
6107 if (evdi_dkms_build_failed()) {
6108 return EVDI_DIAGNOSTIC::DKMS_BUILD_FAILED;
6111 if (!evdi_module_installed_for_running_kernel()) {
6112 return EVDI_DIAGNOSTIC::MODULE_NOT_INSTALLED;
6115 return EVDI_DIAGNOSTIC::MODULE_NOT_LOADED;
6119 return EVDI_DIAGNOSTIC::INITIAL_DEVICE_CONFIGURATION_REQUIRED;
6122 return EVDI_DIAGNOSTIC::READY;
6132#ifdef HERMES_BUILD_WAYLAND
6139 facts.
kscreen = kscreen::available();
6140 facts.
mutter = mutter::available();
6156 BOOST_LOG(info) <<
"[VDISPLAY] Session: " <<
compositorName(facts.compositor)
6157 << (facts.wayland ?
" (Wayland)" : facts.x11 ?
" (X11)" :
" (no window system)");
6163 BOOST_LOG(info) <<
"[VDISPLAY] " <<
featureName(report.feature) <<
": ready - " << report.detail;
6166 std::string message =
"[VDISPLAY] " +
featureName(report.feature) +
": " +
6167 readinessName(report.readiness) +
" - " + report.detail;
6168 if (!report.remediation.empty()) {
6169 message +=
" Fix: " + report.remediation;
6171 BOOST_LOG(warning) << message;
6179 std::string output_layout_backend = exclusive_layout_supported ?
"xrandr" :
"unavailable";
6180#ifdef HERMES_BUILD_WAYLAND
6182 exclusive_layout_supported =
true;
6183 output_layout_backend =
"kscreen-doctor";
6186#ifdef HERMES_BUILD_WAYLAND
6189 exclusive_layout_supported =
true;
6194 output_layout_backend =
"wlr-output-management";
6196 output_layout_backend +=
" (" +
compositorName(compositor) +
")";
6205 mutter::available()) {
6206 output_layout_backend =
"mutter-displayconfig";
6207 exclusive_layout_supported =
true;
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(),
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 = {},
6225 std::ifstream count_file(
"/sys/devices/evdi/count");
6226 count_file >> status.device_count;
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,
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,
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;
6266 if (!inaccessible_hermes_kms_render_node().empty()) {
6269 if (!kernel_module_loaded(
"hermes_kms")) {
6270 if (dkms_build_failed(
"hermes-kms")) {
6271 return HERMES_KMS_DIAGNOSTIC::DKMS_BUILD_FAILED;
6273 if (!dkms_module_installed_for_running_kernel(
"hermes_kms.ko")) {
6274 return HERMES_KMS_DIAGNOSTIC::MODULE_NOT_INSTALLED;
6276 return HERMES_KMS_DIAGNOSTIC::MODULE_NOT_LOADED;
6280 return HERMES_KMS_DIAGNOSTIC::DEVICE_NODE_MISSING;
6284 const auto probe = hermes_kms::probe();
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,
6319 if (!probe.driver_version.empty()) {
6321 status.
reload_needed = !installed.empty() && installed != release_of(probe.driver_version);
6326 for (uint32_t instance = 1; instance <= probe.session_device_count; ++instance) {
6328 fs::path {
"/run/hermes-kms-seatd"} /
6329 std::to_string(instance) /
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;
6336 status.missing_private_seat_brokers.push_back(instance);
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,
6365 return "VIRTUAL-" + guid.string().substr(0, 8);
6368 constexpr int EVDI_DEVICE_SEARCH_LIMIT = 64;
6370 static int find_available_evdi_device() {
6372 for (
int i = 0; i < EVDI_DEVICE_SEARCH_LIMIT; i++) {
6373 if (evdi.check_device(i) == EVDI_AVAILABLE) {
6388 const int result = evdi.add_device();
6390 BOOST_LOG(warning) <<
"[VDISPLAY] evdi_add_device() failed (returned " << result <<
").";
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;
6402 std::this_thread::sleep_for(std::chrono::milliseconds {20});
6405 BOOST_LOG(warning) <<
"[VDISPLAY] No EVDI device became available after creation. "
6406 <<
"Searched indices 0.." << (EVDI_DEVICE_SEARCH_LIMIT - 1) <<
'.';
6415 static int find_evdi_drm_card(
int device_index) {
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;
6425 const auto expected_device =
"evdi." + std::to_string(device_index);
6426 std::vector<int> evdi_cards;
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) {
6436 const auto device_path = fs::weakly_canonical(entry.path() /
"device", ec);
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") {
6448 const auto card_index = std::stoi(name.substr(4));
6449 if (device_path_string.find(expected_device) != std::string::npos) {
6452 evdi_cards.push_back(card_index);
6454 }
catch (
const std::exception &e) {
6455 BOOST_LOG(warning) <<
"[VDISPLAY] Unable to inspect EVDI DRM devices: " << e.what();
6461 return evdi_cards.size() == 1 ? evdi_cards.front() : -1;
6464 static uint32_t normalize_refresh_rate(uint32_t refresh_rate) {
6467 return refresh_rate > 0 && refresh_rate < 1000 ? refresh_rate * 1000 : refresh_rate;
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];
6475 edid[block_size - 1] = 256 - checksum;
6478 static void create_detailed_timing_descriptor(
unsigned char *dtd, uint32_t width, uint32_t height, uint32_t refresh_rate) {
6482 uint32_t h_blank, v_blank, h_front, h_sync, v_front, v_sync;
6487 if (width == 3840 && height == 2160) {
6494 }
else if (width == 2560 && height == 1440) {
6501 }
else if (width == 1920 && height == 1080) {
6508 }
else if (width == 1280 && height == 720) {
6515 }
else if (width == 1280 && height == 800) {
6525 h_blank =
static_cast<uint32_t
>(width * 0.15);
6527 h_front = h_blank / 4;
6528 h_sync = h_blank / 4;
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;
6542 uint64_t pixel_clock_khz =
6543 (
static_cast<uint64_t
>(h_total) * v_total * std::max<uint32_t>(refresh_rate, 1)) / 1000;
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;
6560 const uint16_t pixel_clock =
static_cast<uint16_t
>(pixel_clock_khz / 10);
6563 dtd[0] = pixel_clock & 0xFF;
6564 dtd[1] = (pixel_clock >> 8) & 0xFF;
6566 dtd[2] = h_active & 0xFF;
6567 dtd[3] = h_blank & 0xFF;
6568 dtd[4] = ((h_active >> 8) & 0x0F) << 4 | ((h_blank >> 8) & 0x0F);
6570 dtd[5] = v_active & 0xFF;
6571 dtd[6] = v_blank & 0xFF;
6572 dtd[7] = ((v_active >> 8) & 0x0F) << 4 | ((v_blank >> 8) & 0x0F);
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);
6581 uint32_t h_size_mm = (width * 600) / 3840;
6582 uint32_t v_size_mm = (height * 340) / 2160;
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);
6592 static unsigned char *generate_edid_for_resolution(uint32_t width, uint32_t height, uint32_t refresh_rate) {
6593 static unsigned char edid[256];
6594 memset(edid, 0,
sizeof(edid));
6599 edid[1] = 0xFF; edid[2] = 0xFF; edid[3] = 0xFF;
6600 edid[4] = 0xFF; edid[5] = 0xFF; edid[6] = 0xFF;
6604 edid[8] = 0x06; edid[9] = 0x4C;
6607 edid[10] = 0x01; edid[11] = 0x00;
6610 edid[12] = 0x01; edid[13] = 0x00; edid[14] = 0x00; edid[15] = 0x00;
6613 edid[16] = 0x01; edid[17] = 0x22;
6616 edid[18] = 0x01; edid[19] = 0x04;
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;
6638 edid[35] = 0x00; edid[36] = 0x00; edid[37] = 0x00;
6639 for (
int i = 38; i < 54; i += 2) {
6645 create_detailed_timing_descriptor(&edid[54], width, height, refresh_rate);
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];
6656 edid[90] = 0x00; edid[91] = 0x00; edid[92] = 0x00; edid[93] = 0xFD; edid[94] = 0x00;
6664 for (
int i = 102; i < 108; i++) edid[i] = 0x20;
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;
6671 bool needs_extension = (width > 1920 || height > 1080);
6672 edid[126] = needs_extension ? 0x01 : 0x00;
6675 calculate_edid_checksum(edid, 128);
6678 if (needs_extension) {
6705 if (width >= 3840) {
6706 create_detailed_timing_descriptor(&edid[152], 3840, 2160, 60);
6710 calculate_edid_checksum(&edid[128], 128);
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;
6730 while (evdi_events_running) {
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();
6736 for (
auto &[guid, display] : virtual_displays) {
6740 active_handles.insert(
display.handle);
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) {
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);
6757 const auto pending = pending_since.find(
display.handle);
6758 if (pending != pending_since.end() && now - pending->second < max_pending) {
6761 if (!evdi.request_update(
display.handle,
display.evdi_buffer_id)) {
6762 pending_since[
display.handle] = now;
6765 pending_since.erase(
display.handle);
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;
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);
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);
6791 std::erase_if(pending_since, [&](
const auto &entry) {
6792 return !active_handles.contains(entry.first);
6798 std::this_thread::sleep_for(std::chrono::milliseconds {1});
6802 static void start_evdi_events_thread() {
6803 if (evdi_events_running.exchange(
true)) {
6806 evdi_events_thread = std::thread(evdi_events_loop);
6809 static void stop_evdi_events_thread() {
6810 evdi_events_running =
false;
6811 if (evdi_events_thread.joinable()) {
6812 evdi_events_thread.join();
6821 std::lock_guard<std::mutex> lifecycle_lock(vdisplay_lifecycle_mutex);
6822 std::lock_guard<std::mutex> lock(vdisplay_mutex);
6825 return driver_status;
6828 const auto backend = selected_backend();
6829 BOOST_LOG(info) <<
"[VDISPLAY] Initializing Linux virtual display driver with " << backend_name(backend) <<
" backend...";
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.";
6841 return driver_status;
6844 kscreen::recover_on_startup();
6845 mutter::recover_on_startup();
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.";
6853 return driver_status;
6856 std::vector<std::string> boot_connectors;
6857 if (hermes_kms::disconnect_unowned_outputs(boot_connectors)) {
6858 for (
const auto &connector : boot_connectors) {
6860 kscreen::recover_after_unowned_virtual_disconnect(connector);
6861 mutter::recover_after_unowned_virtual_disconnect(connector);
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;
6878 if (backend == VirtualDisplayBackend::HYPRLAND_HEADLESS) {
6879 evdi_available =
false;
6880 unload_evdi_library();
6881 if (!hyprland::available()) {
6882 hyprland::log_unreachable(
false);
6884 return driver_status;
6889 BOOST_LOG(info) <<
"[VDISPLAY] Hyprland headless output backend available - virtual displays supported.";
6890 return driver_status;
6894 evdi_available = load_evdi_library();
6896 if (evdi_available) {
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();
6906 if (evdi_available) {
6907 BOOST_LOG(info) <<
"[VDISPLAY] EVDI available - real virtual displays supported!";
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.";
6912 return driver_status;
6917 BOOST_LOG(info) <<
"[VDISPLAY] Linux virtual display driver initialized successfully.";
6919 return driver_status;
6926 if (!device_open.exchange(
false)) {
6930 BOOST_LOG(info) <<
"[VDISPLAY] Closing Linux virtual display driver...";
6933 mutter::unwatch_layout();
6936 watchdog_running =
false;
6937 if (watchdog_thread.joinable()) {
6941 if (watchdog_thread.get_id() == std::this_thread::get_id()) {
6942 watchdog_thread.detach();
6944 watchdog_thread.join();
6947 std::lock_guard<std::mutex> lifecycle_lock(vdisplay_lifecycle_mutex);
6948 std::unique_lock<std::mutex> lock(vdisplay_mutex);
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);
6957 kscreen::retry_pending_restores();
6958 stop_evdi_events_thread();
6962 unload_evdi_library();
6965 BOOST_LOG(info) <<
"[VDISPLAY] Linux virtual display driver closed.";
6969 std::lock_guard<std::mutex> lock(vdisplay_mutex);
6971 if (watchdog_running) {
6975 watchdog_running =
true;
6977 watchdog_thread = std::thread([failCb = std::move(failCb)]() {
6978 BOOST_LOG(debug) <<
"[VDISPLAY] Watchdog thread started.";
6980 while (watchdog_running) {
6981 std::this_thread::sleep_for(5s);
6983 if (!watchdog_running) {
6987 bool display_lost =
false;
6988 std::vector<std::string> pending_removals;
6990 std::lock_guard<std::mutex> lock(vdisplay_mutex);
6994 if (parked_display && greeter_holds_seat() == std::optional<bool> {
false}) {
6995 release_parked_locked(
"the greeter no longer holds the seat.");
6997 for (
const auto &[guid, vdinfo] : virtual_displays) {
6998 if (vdinfo.removal_pending) {
6999 pending_removals.push_back(guid);
7002 if (vdinfo.active && vdinfo.using_evdi && vdinfo.handle) {
7004 int ready = evdi.get_event_ready(vdinfo.handle);
7006 BOOST_LOG(error) <<
"[VDISPLAY] Virtual display " << vdinfo.name <<
" lost!";
7007 display_lost =
true;
7010 }
else if (vdinfo.active && vdinfo.using_hermes_kms && vdinfo.drm_fd >= 0) {
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;
7022 std::lock_guard<std::mutex> lifecycle_lock(vdisplay_lifecycle_mutex);
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);
7042 BOOST_LOG(debug) <<
"[VDISPLAY] Watchdog thread stopped.";
7049 std::lock_guard<std::mutex> lock(vdisplay_mutex);
7051 if (adapterName.empty()) {
7052 BOOST_LOG(debug) <<
"[VDISPLAY] No specific adapter requested.";
7056 BOOST_LOG(info) <<
"[VDISPLAY] Adapter hint: " << adapterName;
7062 const char *s_client_uid,
7063 const char *s_client_name,
7068 std::optional<uid_t> session_owner_uid,
7070 bool isolated_session
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.";
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);
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.";
7092 BOOST_LOG(error) <<
"[VDISPLAY] Driver not initialized.";
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;
7101 std::string display_name = generate_display_name(guid);
7103 fps = normalize_refresh_rate(fps);
7104 const uint32_t fps_hz = fps / 1000;
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";
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 <<
")";
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;
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;
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;
7140 const auto backend = selected_backend();
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.";
7155 if (backend == VirtualDisplayBackend::HYPRLAND_HEADLESS) {
7156 if (!hyprland::available()) {
7157 hyprland::log_unreachable(
true);
7161 const auto output = hyprland::create_headless();
7166 vdinfo.connector_name = *output;
7167 vdinfo.using_hyprland_headless =
true;
7168 virtual_displays[guid_str] = vdinfo;
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;
7175 const auto kscreen_before = kscreen::outputs();
7177 if (backend == VirtualDisplayBackend::HERMES_KMS) {
7179 uint64_t session_id = 0;
7180 bool claimed =
false;
7181 bool adopted =
false;
7182 std::array<uint64_t, 2> session_token {};
7188 if (parked_display && !isolated_session) {
7189 uint64_t parked_session = parked_display->session_id;
7190 bool mode_set =
false;
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);
7196 if (errno != EAGAIN) {
7199 std::this_thread::sleep_for(std::chrono::milliseconds {200});
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),
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;
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;
7229 release_parked_locked(
"it could not be handed to the new session, so a fresh output is claimed instead.");
7235 }
else if (isolated_session) {
7236 claimed = hermes_kms::claim_available_device_output(
7245 }
else if (hermes_kms::open_device(device,
true)) {
7246 claimed = hermes_kms::claim_available_output(
7255 if (claimed && !hermes_kms::get_session_token(
7257 device.selected_output_index,
7261 hermes_kms::set_output(device.fd,
false, 0, 0, 0, session_id,
false);
7264 if (!claimed && !vdinfo.broker_card.empty()) {
7268 vdinfo.broker_card.clear();
7273 hermes_kms::get_status(device.fd, status);
7274 vdinfo.drm_fd = device.fd;
7276 vdinfo.device_index = device.version.uapi_version >= hermes_kms::multi_device_uapi_version ?
7277 static_cast<int>(device.identity.device_index) :
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) :
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";
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(
7312 vdinfo.connector_name,
7314 static_cast<int>(vdinfo.width),
7315 static_cast<int>(vdinfo.height),
7316 static_cast<int>(vdinfo.fps / 1000),
7321 hermes_kms::forget_secret(session_token.data(),
sizeof(session_token));
7322 hermes_kms::close_device(device);
7323 }
else if (evdi_available) {
7325 int device = find_available_evdi_device();
7327 evdi_handle handle = evdi.open(device);
7330 unsigned char *edid = generate_edid_for_resolution(width, height, fps_hz);
7333 unsigned int edid_size = (width > 1920 || height > 1080) ? 256 : 128;
7336 BOOST_LOG(info) <<
"[VDISPLAY] Connecting with " << edid_size <<
"-byte EDID for " << width <<
"x" << height;
7337 evdi.connect(handle, edid, edid_size, 0);
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});
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;
7357 vdinfo.evdi_buffer = std::make_shared<EvdiBuffer>(width, height);
7358 vdinfo.evdi_buffer_id = 1;
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 <<
')';
7375 kscreen::activate_evdi_output(
7378 evdi_connector_name(vdinfo.drm_card_index),
7380 static_cast<int>(vdinfo.width),
7381 static_cast<int>(vdinfo.height),
7382 static_cast<int>(vdinfo.fps / 1000),
7386 BOOST_LOG(error) <<
"[VDISPLAY] EVDI connected but no matching DRM card appeared.";
7387 evdi.disconnect(handle);
7391 BOOST_LOG(warning) <<
"[VDISPLAY] Failed to open EVDI device " << device;
7394 BOOST_LOG(warning) <<
"[VDISPLAY] No available EVDI device.";
7398 if (!vdinfo.using_evdi && !vdinfo.using_hermes_kms) {
7399 BOOST_LOG(error) <<
"[VDISPLAY] Failed to create a usable " << backend_name(backend) <<
" virtual display.";
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));
7407 start_evdi_events_thread();
7410 BOOST_LOG(info) <<
"[VDISPLAY] Virtual display created successfully: " << display_name;
7411 BOOST_LOG(info) <<
"[VDISPLAY] Mode: " << backend_name(backend) <<
" (real virtual display)";
7413 return display_name;
7416 static bool remove_virtual_display_locked(
7417 const std::string &guid_str,
7418 std::unique_lock<std::mutex> &lock,
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;
7427 auto &vdinfo = it->second;
7428 BOOST_LOG(info) <<
"[VDISPLAY] Removing virtual display: " << vdinfo.name;
7429 vdinfo.removal_pending =
true;
7434 const bool physical_restored = kscreen::restore(vdinfo.name,
false);
7436 if (!physical_restored && !shutting_down) {
7437 BOOST_LOG(warning) <<
"[VDISPLAY] Deferring removal of " << vdinfo.name
7438 <<
" until physical output restoration can be confirmed.";
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.";
7446 if (vdinfo.using_evdi && vdinfo.handle) {
7447 if (vdinfo.evdi_buffer_id > 0) {
7448 evdi.unregister_buffer(vdinfo.handle, vdinfo.evdi_buffer_id);
7450 evdi.disconnect(vdinfo.handle);
7451 evdi.close(vdinfo.handle);
7453 if (vdinfo.using_hermes_kms && vdinfo.drm_fd >= 0) {
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(
7463 static_cast<uint32_t
>(vdinfo.output_index),
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.");
7479 if (!shutting_down && !parked_display && vdinfo.broker_card.empty() && vdinfo.session_index < 0 &&
7481 greeter_holds_seat().value_or(
false),
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));
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();
7496 vdinfo.removal_pending =
false;
7497 parked_display = std::move(vdinfo);
7498 virtual_displays.erase(it);
7502 hermes_kms::set_output(vdinfo.drm_fd,
false, 0, 0, 0, vdinfo.session_id);
7507 if (vdinfo.using_hyprland_headless) {
7508 hyprland::remove_output(vdinfo.connector_name);
7510 hermes_kms::forget_secret(vdinfo.session_token.data(),
sizeof(vdinfo.session_token));
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();
7519 if (vdinfo.drm_fd >= 0) {
7520 ::close(vdinfo.drm_fd);
7522 if (!vdinfo.broker_card.empty()) {
7524 card_broker::remove(vdinfo.broker_card);
7527 virtual_displays.erase(it);
7529 BOOST_LOG(info) <<
"[VDISPLAY] Virtual display removed successfully.";
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);
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,
7546 int deadline_ms = 4000
7550 std::unique_lock<std::mutex> lock(vdisplay_mutex);
7552 refresh_rate = normalize_refresh_rate(refresh_rate);
7553 const int refresh_hz = refresh_rate / 1000;
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";
7561 BOOST_LOG(info) <<
"[VDISPLAY] Changing display settings for " << deviceName
7562 <<
" to " << width <<
"x" << height <<
"@" << refresh_hz <<
"Hz";
7566 std::string push_mode_for;
7567 for (
auto &[guid, vdinfo] : virtual_displays) {
7568 if (vdinfo.name == deviceName) {
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.";
7588 vdinfo.width = width;
7589 vdinfo.height = height;
7590 vdinfo.fps = refresh_rate;
7592 if (vdinfo.using_evdi && vdinfo.handle) {
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)) {
7607 push_mode_for = vdinfo.name;
7610 BOOST_LOG(info) <<
"[VDISPLAY] Display settings updated successfully.";
7619 BOOST_LOG(debug) <<
"[VDISPLAY] Display not found: " << deviceName;
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.";
7641 if (bApplyIsolated) {
7642 BOOST_LOG(debug) <<
"[VDISPLAY] Isolated mode is handled by the active virtual-display backend.";
7647 static std::string evdi_connector_name(
int card_index) {
7648 const auto prefix =
"card" + std::to_string(card_index) +
"-";
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) {
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());
7665 }
catch (
const std::exception &e) {
7666 BOOST_LOG(warning) <<
"[VDISPLAY] Unable to find EVDI X11 connector: " << e.what();
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;
7686 const std::string ¤t_state,
7687 const std::string &virtual_connector,
7688 std::string &serial,
7689 std::string &argument
7694 serial = ready ? state.serial : std::string {};
7702 const std::string ¤t_state,
7703 const std::string &connector,
7706 uint32_t refresh_mhz,
7707 std::string &serial,
7708 std::string &argument
7712 mutter::build_layout_with_mode(current_state, connector, width, height, refresh_mhz, state, argument) ==
7714 serial = ready ? state.serial : std::string {};
7722 const std::string ¤t_state,
7723 const std::string &connector,
7724 std::string &serial,
7725 std::string &argument
7730 serial = ready ? state.serial : std::string {};
7738 const std::string ¤t_state,
7739 const std::string &connector,
7740 std::string &serial,
7741 std::string &argument
7746 serial = ready ? state.serial : std::string {};
7754 const std::string ¤t_state,
7755 std::string &serial,
7756 std::string &argument
7761 if (!mutter::parse_current_state(current_state, state) ||
7762 !mutter::build_restore_layout(state, argument)) {
7766 serial = state.serial;
7771 const std::string ¤t_state,
7772 const std::string &connector
7775 if (!mutter::parse_current_state(current_state, state)) {
7778 return mutter::device_output_value(state, connector);
7782 touch = mutter::device_settings_target(mutter::touch_settings);
7783 pen = mutter::device_settings_target(mutter::pen_settings);
7787 return kscreen::is_hermes_input_device(name, vendor, product);
7791 return kscreen::input_binding_read_command(device_name);
7795 return kscreen::input_binding_restore_command(device_name, previous_uuid);
7799 return mutter::layout_generation.load(std::memory_order_relaxed);
7803 const std::string ¤t_state,
7804 const std::string &connector,
7807 int &environment_width,
7808 int &environment_height
7811 if (!mutter::parse_current_state(current_state, state)) {
7814 return mutter::geometry_from_state(
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) {
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);
7844 std::lock_guard<std::mutex> lock(vdisplay_mutex);
7845 for (
const auto &[guid, display] : virtual_displays) {
7846 if (
display.name == display_name) {
7850 return virtual_display_layout_e::extend;
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;
7863 static std::string virtual_display_connector_name(
const std::string &display_name) {
7868 if (
auto output = getHyprlandOutputName(display_name); !output.empty()) {
7895 static bool pushVirtualOutputMode(
7896 const std::string &displayName,
7897 const std::string &connector,
7907 if (kscreen::is_active(displayName)) {
7908 return kscreen::apply_mode(displayName, width, height, refresh_mhz / 1000);
7910 if (mutter::available()) {
7911 return mutter::apply_output_mode(connector, width, height, refresh_mhz, deadline_ms);
7913#ifdef HERMES_BUILD_WAYLAND
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.";
7922 hyprland::pin_output(connector, width, height, refresh_mhz);
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);
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";
7949 void apply_physical_binding_locked() {
7950 if (!physical_session_active || physical_capture_output.empty() ||
7951 physical_bound_output == physical_capture_output) {
7958 if (kscreen::any_layout_active()) {
7961 kscreen::map_input_devices_to(physical_binding_owner, physical_capture_output);
7962 physical_bound_output = physical_capture_output;
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();
7976 for (
const auto &output : kscreen::outputs()) {
7977 if (output.connected && output.enabled && output.priority == 1) {
7979 return output.name.starts_with(
"Virtual") ? std::string {} : output.name;
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();
7992 void endPhysicalOutputSession() {
7993 std::lock_guard<std::mutex> lock(physical_input_mutex);
7994 if (!physical_session_active) {
7997 physical_session_active =
false;
7998 if (!physical_bound_output.empty()) {
8000 kscreen::unmap_input_devices(physical_binding_owner);
8001 physical_bound_output.clear();
8010 bool connector_scanning_out(
int fd,
const std::string &name) {
8011 drmModeRes *res = drmModeGetResources(fd);
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]);
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);
8030 drmModeFreeResources(res);
8031 return scanning_out;
8035 void simulate_user_activity() {
8036#ifdef HERMES_BUILD_SDBUS
8037 sd_bus *bus =
nullptr;
8038 if (platf::open_user_bus(&bus) < 0 || !bus) {
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);
8049 bool output_scanning_out(
const std::string &name) {
8051 for (
const auto &entry : std::filesystem::directory_iterator {
"/dev/dri", ec}) {
8052 if (!entry.path().filename().string().starts_with(
"card")) {
8059 const bool scanning_out = connector_scanning_out(fd, name);
8071 std::string connector_status(
const std::filesystem::path &connector) {
8072 std::ifstream in {connector /
"status"};
8074 std::getline(in, status);
8084 std::string aux_i2c_device(
const std::filesystem::path &connector) {
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;
8100 int read_edid_byte(
const std::string &device) {
8101 const int fd = ::open(device.c_str(), O_RDWR | O_CLOEXEC);
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;
8109 return answered ? 1 : 0;
8126 bool wake_displayport_monitors_from_deep_sleep() {
8127 std::vector<std::string> waking;
8129 for (
const auto &entry : std::filesystem::directory_iterator {
"/sys/class/drm", ec}) {
8130 const auto name = entry.path().filename().string();
8131 const auto dash = name.find(
'-');
8132 if (!name.starts_with(
"card") || dash == std::string::npos) {
8135 const auto connector = name.substr(dash + 1);
8137 if (!connector.starts_with(
"DP-") || connector_status(entry.path()) !=
"connected" || output_scanning_out(connector)) {
8140 const auto device = aux_i2c_device(entry.path());
8141 if (device.empty()) {
8144 const int answered = read_edid_byte(device);
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);
8151 if (waking.empty()) {
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);
8160 while (!(lit = all_lit()) && std::chrono::steady_clock::now() - start < 8s) {
8161 std::this_thread::sleep_for(100ms);
8163 const auto waited = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
8165 BOOST_LOG(info) <<
"[VDISPLAY] Woke " << waking.front() <<
" from deep sleep over AUX; lit after " << waited <<
" ms.";
8167 BOOST_LOG(warning) <<
"[VDISPLAY] " << waking.front() <<
" was woken from deep sleep over AUX but is not lit after " << waited <<
" ms.";
8172 struct physical_output_t {
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")) {
8184 if (result.name.empty() || output.priority == 1) {
8185 result = {output.name, output.priority == 1};
8197 const bool woken = wake_displayport_monitors_from_deep_sleep();
8199 const auto monitor = enabled_physical_output();
8200 if (monitor.name.empty()) {
8205 simulate_user_activity();
8206 if (woken && output_scanning_out(monitor.name)) {
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")) {
8218 for (
int i = 0; i < 30; ++i) {
8219 std::this_thread::sleep_for(100ms);
8220 if (output_scanning_out(monitor.name)) {
8224 BOOST_LOG(warning) <<
"[VDISPLAY/KScreen] " << monitor.name <<
" did not show a frame within 3 seconds.";
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);
8244 kscreen::map_input_devices(displayName);
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.";
8254#ifdef HERMES_BUILD_WAYLAND
8258 int refresh_mhz = 0;
8259 if (!virtual_display_mode(displayName, width, height, refresh_mhz)) {
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.";
8295 if (mutter::available()) {
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.";
8304 mutter::apply_mirror(displayName, connector);
8308 mutter::map_input_devices(connector);
8311 mutter::watch_layout();
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.";
8321 const bool activated = pushVirtualOutputMode(displayName, connector, width, height, refresh_mhz);
8323 BOOST_LOG(info) <<
"[VDISPLAY] Activated Wayland virtual output " << connector;
8333 const auto variable = [](
const char *name) {
8334 const char *value = std::getenv(name);
8335 return std::string {value ? value :
""};
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.";
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.";
8358 BOOST_LOG(warning) <<
"[VDISPLAY] No display-layout backend is available for this session.";
8362 if (connector.find_first_not_of(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") != std::string::npos) {
8363 BOOST_LOG(warning) <<
"[VDISPLAY] Refusing unsafe virtual connector name.";
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;
8373 BOOST_LOG(info) <<
"[VDISPLAY] Activated X11 virtual output " << connector;
8379 return {
false,
nullptr};
8381 if (!state.hdr_supported) {
8382 return {
false,
"the virtual output does not offer HDR (Hermes-KMS needs hdr_enable=1 color_depth=10)"};
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"};
8387 return {
true,
nullptr};
8391 if (config::video.virtual_display_backend !=
"hermes_kms" ||
8397 std::lock_guard<std::mutex> lock(kscreen::layouts_mutex);
8398 const auto it = kscreen::layouts.find(displayName);
8399 if (it == kscreen::layouts.end()) {
8402 output = it->second.virtual_output;
8404 const auto state = kscreenHdrState(kscreen::command_output(
"kscreen-doctor -j"), output);
8406 BOOST_LOG(error) <<
"[VDISPLAY/KScreen] Cannot read the HDR state of " << output <<
'.';
8412 if (capture_fd < 0) {
8415 auto close_capture = util::fail_guard([capture_fd]() { ::close(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.";
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");
8428 if (state->wcg_supported && state->wcg != hdr) {
8429 command +=
" output." + output + (hdr ?
".wcg.enable" :
".wcg.disable");
8432 if (changed && !kscreen::run_layout_command(command)) {
8437 const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds {1500};
8440 uint32_t fourcc = 0;
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");
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.";
8454 std::lock_guard<std::mutex> lifecycle_lock(vdisplay_lifecycle_mutex);
8456 const bool enabled = kscreen::make_exclusive(displayName);
8458 exclusive_virtual_display_active =
true;
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.";
8473 const bool enabled = mutter::make_exclusive(displayName, connector);
8475 exclusive_virtual_display_active =
true;
8480#ifdef HERMES_BUILD_WAYLAND
8484 int refresh_rate = 0;
8485 if (!virtual_display_mode(displayName, width, height, refresh_rate)) {
8490 exclusive_virtual_display_active =
true;
8491 BOOST_LOG(info) <<
"[VDISPLAY] Enabled exclusive Wayland layout for virtual output " << connector;
8493 BOOST_LOG(warning) <<
"[VDISPLAY] Wayland compositor cannot apply the virtual-display exclusive layout.";
8500 BOOST_LOG(warning) <<
"[VDISPLAY] Exclusive virtual display layout is unavailable for this session.";
8505 if (connector.find_first_not_of(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") != std::string::npos) {
8506 BOOST_LOG(warning) <<
"[VDISPLAY] Refusing unsafe virtual connector name.";
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.";
8518 exclusive_virtual_display_active =
true;
8519 BOOST_LOG(info) <<
"[VDISPLAY] Enabled exclusive X11 layout for virtual output " << connector;
8523 void restoreExclusiveVirtualDisplay() {
8524 std::lock_guard<std::mutex> lifecycle_lock(vdisplay_lifecycle_mutex);
8525 if (!exclusive_virtual_display_active) {
8530 if (kscreen::restore_all()) {
8531 exclusive_virtual_display_active =
false;
8540 exclusive_virtual_display_active =
false;
8544#ifdef HERMES_BUILD_WAYLAND
8547 BOOST_LOG(warning) <<
"[VDISPLAY] Failed to restore the Wayland display layout.";
8549 exclusive_virtual_display_active =
false;
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.";
8560 BOOST_LOG(info) <<
"[VDISPLAY] Restored X11 physical display layout.";
8562 exclusive_virtual_display_active =
false;
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);
8574 drmModeRes *res = drmModeGetResources(fd);
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);
8585 if (conn) drmModeFreeConnector(conn);
8587 drmModeFreeResources(res);
8598 BOOST_LOG(debug) <<
"[VDISPLAY] setPrimaryDisplay is a no-op on Linux.";
8603 BOOST_LOG(debug) <<
"[VDISPLAY] HDR check for: " << displayName;
8609 BOOST_LOG(debug) <<
"[VDISPLAY] HDR setting not supported on Linux/EVDI.";
8614 std::vector<std::string> matches;
8616 std::lock_guard<std::mutex> lock(vdisplay_mutex);
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);
8635 if (!evdi_available) {
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) {
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) {
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;
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;
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);
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);
8704 return card_index >= 0 ?
8705 "/dev/dri/card" + std::to_string(card_index) :
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) {
8724 return "hermes-kms-" + std::to_string(vdinfo.session_index);
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));
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) {
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;
8753 auto devices = hermes_kms::open_devices(
false);
8754 if (devices.empty()) {
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;
8762 if (selected == devices.end()) {
8763 for (
auto &candidate : devices) {
8764 hermes_kms::close_device(candidate);
8770 for (
auto &candidate : devices) {
8771 hermes_kms::close_device(candidate);
8773 auto guard = util::fail_guard([&device]() { hermes_kms::close_device(device); });
8776 if (!(device.caps.flags & hermes_kms::cap_metrics)) {
8780 !hermes_kms::bind_session(
8790 if (!hermes_kms::get_metrics(device.fd, metrics)) {
8791 BOOST_LOG(debug) <<
"[VDISPLAY/Hermes-KMS] GET_METRICS failed: " << std::strerror(errno);
8795 out.available =
true;
8811 if (device.caps.flags & hermes_kms::cap_session_lifecycle) {
8822 if (hermes_kms::get_status(device.fd, status)) {
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;
8840 for (
auto &fd : dma_buf_fd) {
8846 if (sync_file_fd >= 0) {
8853 for (
auto &fd : dma_buf_fd) {
8859 if (sync_file_fd >= 0) {
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));
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;
8885 if (card_index < 0) {
8886 BOOST_LOG(error) <<
"[VDISPLAY/Hermes-KMS] No card mapping for capture of " << display_name;
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 <<
".";
8900 if (output_index < 0 ||
8901 !hermes_kms::bind_session(
8903 static_cast<uint32_t
>(output_index),
8914 int &offset_x,
int &offset_y,
8915 int &environment_width,
int &environment_height) {
8920 if (kscreen::available()) {
8921 return kscreen::geometry(
8930 if (mutter::available()) {
8931 const auto connector = virtual_display_connector_name(display_name);
8932 if (connector.empty()) {
8935 return mutter::geometry(
8949 if (render_fd < 0) {
8954 width, height, std::chrono::milliseconds {timeout_ms},
8956 return ::ioctl(render_fd, hermes_kms::ioctl_get_status, &status) == 0 ? 0 : errno;
8958 [] {
return std::chrono::steady_clock::now(); },
8959 [](
auto deadline) { std::this_thread::sleep_until(deadline); }
8970 return ::ioctl(render_fd, hermes_kms::ioctl_get_caps, &caps) == 0 &&
8971 (caps.flags & hermes_kms::cap_frame_color);
8978 if (::ioctl(render_fd, hermes_kms::ioctl_get_caps, &caps) != 0) {
8982 if (caps.flags & hermes_kms::cap_frame_color) {
8983 if (::ioctl(render_fd, hermes_kms::ioctl_acquire_frame2, &capture) != 0) {
8986 if (!capture.color.supported()) {
8990 color = capture.color;
8991 }
else if (::ioctl(render_fd, hermes_kms::ioctl_acquire_frame, &capture.frame) != 0) {
8994 fourcc = capture.frame.format;
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) {
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) {
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) {
9028 frame.flags = hermes_kms::frame_request_dmabuf | hermes_kms::frame_request_sync_file;
9029 for (
auto &fd : frame.dma_buf_fd) {
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) {
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) {
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) {
9052 for (
auto fd : frame.dma_buf_fd) {
9057 if (frame.sync_file_fd >= 0) {
9058 ::close(frame.sync_file_fd);
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];
9081 uint64_t after_cursor_sequence, uint32_t timeout_ms,
9084 if (render_fd < 0) {
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) {
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)) {
9115 if (render_fd < 0) {
9122 int acquire_ret = -1;
9123 for (
unsigned int attempt = 0; attempt < 4; ++attempt) {
9125 if (request_buffer) {
9126 cursor.flags = hermes_kms::cursor_request_dmabuf |
9127 hermes_kms::cursor_request_sync_file;
9129 for (
auto &fd : cursor.dma_buf_fd) {
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) {
9138 if (acquire_ret != 0) {
9142 const auto close_reply_fds = [&cursor]() {
9143 for (
auto &fd : cursor.dma_buf_fd) {
9149 if (cursor.sync_file_fd >= 0) {
9150 ::close(cursor.sync_file_fd);
9151 cursor.sync_file_fd = -1;
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) {
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]) {
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;
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...
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.
Miscellaneous declarations for Linux.
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.
util::safe_ptr< UPNPDev, freeUPNPDevlist > device_t
Owning pointer to miniupnpc device discovery results.
bool restore_virtual_output_layout()
bool configure_virtual_output(const std::string &output_name, int width, int height, int refresh_rate, bool exclusive)
bool output_management_supported()
session_protocols_t probe_protocols()
Probe the session's globals in a single registry roundtrip.
int command(const char *name, int argc, char *argv[])
hermes --prelogin status|enable|disable.
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 cross_session_buffer_export_count
uint64_t bind_count
Bindings granted over the output's lifetime.
uint64_t binding_revoke_count
uint64_t last_wait_duration_ns
uint64_t frame_update_count
Total framebuffer updates seen.
std::string inaccessible_node
std::string installed_version
What was observed about the session, before any verdict is drawn.
bool output_management
zwlr_output_manager_v1 is advertised.
bool isolated_sessions_requested
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 ¤t_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 ¤t_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 ¤t_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 > ¤t, virtual_display_layout_e layout)
Decide where the virtual output goes, in KScreen's logical space.
std::string mutterInputDeviceOutputValue(const std::string ¤t_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 ¤t_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 ¤t_state, std::string &serial, std::string &argument)
Build the payload that reproduces the layout in current_state.
bool buildMutterExclusiveLayout(const std::string ¤t_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.