Compare commits

...

5 Commits

Author SHA1 Message Date
dijunkun
a8769dee06 Merge branch 'file-transfer' of https://github.com/kunkundi/crossdesk into file-transfer 2026-04-21 09:28:22 +08:00
dijunkun
e4dfb61509 [fix] fix wayland cursor mapping 2026-04-20 18:09:13 +08:00
dijunkun
d42b6e3261 [feat] update MiniRTC 2026-04-20 18:02:56 +08:00
dijunkun
855b15025c [fix] fix file transfer window interactions issue 2026-04-14 14:25:16 +08:00
dijunkun
3701b2c0d9 [chore] add acknowledgements 2026-04-14 11:03:06 +08:00
14 changed files with 562 additions and 290 deletions

View File

@@ -262,3 +262,8 @@ sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keyc
# 常见问题 # 常见问题
见 [常见问题](https://github.com/kunkundi/crossdesk/blob/self-hosted-server/docs/FAQ.md) 。 见 [常见问题](https://github.com/kunkundi/crossdesk/blob/self-hosted-server/docs/FAQ.md) 。
# 致谢
- 感谢 [HelloGitHub](https://hellogithub.com/) 的推荐与关注。
- 感谢 [阮一峰的科技爱好者周刊](https://github.com/ruanyf/weekly) 的收录与推荐。
- 感谢 [LinuxDo](https://linux.do) 社区的关注、交流与支持,为 CrossDesk 项目的完善提供了帮助。

View File

@@ -274,3 +274,8 @@ See [CrossDesk Web Client](https://github.com/kunkundi/crossdesk-web-client)。
# FAQ # FAQ
See [FAQ](https://github.com/kunkundi/crosssesk/blob/self-hosted-server/docs/FAQ.md) . See [FAQ](https://github.com/kunkundi/crosssesk/blob/self-hosted-server/docs/FAQ.md) .
# Acknowledgements
- Thanks to [HelloGitHub](https://hellogithub.com/) for the recommendation and exposure.
- Thanks to [Ruanyf Weekly](https://github.com/ruanyf/weekly) for featuring CrossDesk.
- Thanks to the [LinuxDo](https://linux.do) community for the attention, discussions, and support that helped improve CrossDesk.

View File

@@ -11,8 +11,8 @@
#include <X11/Xutil.h> #include <X11/Xutil.h>
#include <unistd.h> #include <unistd.h>
#include <functional>
#include <cstdint> #include <cstdint>
#include <functional>
#include <string> #include <string>
#include <vector> #include <vector>
@@ -47,9 +47,9 @@ class MouseController : public DeviceController {
bool NotifyWaylandPointerMotionAbsolute(uint32_t stream, double x, double y); bool NotifyWaylandPointerMotionAbsolute(uint32_t stream, double x, double y);
bool NotifyWaylandPointerButton(int button, uint32_t state); bool NotifyWaylandPointerButton(int button, uint32_t state);
bool NotifyWaylandPointerAxisDiscrete(uint32_t axis, int32_t steps); bool NotifyWaylandPointerAxisDiscrete(uint32_t axis, int32_t steps);
bool SendWaylandPortalVoidCall(const char* method_name, bool SendWaylandPortalVoidCall(
const std::function<void(DBusMessageIter*)>& const char* method_name,
append_args); const std::function<void(DBusMessageIter*)>& append_args);
enum class WaylandAbsoluteMode { kUnknown, kPixels, kNormalized, kDisabled }; enum class WaylandAbsoluteMode { kUnknown, kPixels, kNormalized, kDisabled };
@@ -72,6 +72,8 @@ class MouseController : public DeviceController {
WaylandAbsoluteMode wayland_absolute_mode_ = WaylandAbsoluteMode::kUnknown; WaylandAbsoluteMode wayland_absolute_mode_ = WaylandAbsoluteMode::kUnknown;
bool wayland_absolute_disabled_logged_ = false; bool wayland_absolute_disabled_logged_ = false;
uint32_t wayland_absolute_stream_id_ = 0; uint32_t wayland_absolute_stream_id_ = 0;
int wayland_portal_space_width_ = 0;
int wayland_portal_space_height_ = 0;
bool using_shared_wayland_session_ = false; bool using_shared_wayland_session_ = false;
}; };
} // namespace crossdesk } // namespace crossdesk

View File

@@ -1,5 +1,3 @@
#include "mouse_controller.h"
#include <algorithm> #include <algorithm>
#include <chrono> #include <chrono>
#include <cmath> #include <cmath>
@@ -7,6 +5,8 @@
#include <cstring> #include <cstring>
#include <thread> #include <thread>
#include "mouse_controller.h"
#if defined(CROSSDESK_HAS_WAYLAND_CAPTURER) && CROSSDESK_HAS_WAYLAND_CAPTURER #if defined(CROSSDESK_HAS_WAYLAND_CAPTURER) && CROSSDESK_HAS_WAYLAND_CAPTURER
#include <dbus/dbus.h> #include <dbus/dbus.h>
#endif #endif
@@ -22,7 +22,8 @@ void MouseController::OnWaylandDisplayInfoListUpdated() {
display_info_list_.empty() display_info_list_.empty()
? 0 ? 0
: reinterpret_cast<uintptr_t>(display_info_list_[0].handle); : reinterpret_cast<uintptr_t>(display_info_list_[0].handle);
const int width0 = display_info_list_.empty() ? 0 : display_info_list_[0].width; const int width0 =
display_info_list_.empty() ? 0 : display_info_list_[0].width;
const int height0 = const int height0 =
display_info_list_.empty() ? 0 : display_info_list_[0].height; display_info_list_.empty() ? 0 : display_info_list_[0].height;
const bool should_log = !logged_wayland_display_info_ || const bool should_log = !logged_wayland_display_info_ ||
@@ -43,8 +44,7 @@ void MouseController::OnWaylandDisplayInfoListUpdated() {
const auto& display = display_info_list_[i]; const auto& display = display_info_list_[i];
LOG_INFO( LOG_INFO(
"Wayland mouse display info [{}]: name={}, rect=({},{})->({},{}) " "Wayland mouse display info [{}]: name={}, rect=({},{})->({},{}) "
"size={}x{}, stream={}" "size={}x{}, stream={}",
,
i, display.name, display.left, display.top, display.right, i, display.name, display.left, display.top, display.right,
display.bottom, display.width, display.height, display.bottom, display.width, display.height,
reinterpret_cast<uintptr_t>(display.handle)); reinterpret_cast<uintptr_t>(display.handle));
@@ -88,6 +88,13 @@ std::string MakeToken(const char* prefix) {
} }
void LogDbusError(const char* action, DBusError* error) { void LogDbusError(const char* action, DBusError* error) {
if (action && error && dbus_error_is_set(error) &&
strcmp(action, "NotifyPointerMotionAbsolute") == 0 && error->name &&
strcmp(error->name, "org.freedesktop.DBus.Error.Failed") == 0 &&
error->message && strcmp(error->message, "Invalid position") == 0) {
return;
}
if (error && dbus_error_is_set(error)) { if (error && dbus_error_is_set(error)) {
LOG_ERROR("{} failed: {} ({})", action, LOG_ERROR("{} failed: {} ({})", action,
error->message ? error->message : "unknown", error->message ? error->message : "unknown",
@@ -190,6 +197,27 @@ bool ReadUint32Like(DBusMessageIter* iter, uint32_t* value) {
return false; return false;
} }
bool ReadIntLike(DBusMessageIter* iter, int* value) {
if (!iter || !value) {
return false;
}
if (dbus_message_iter_get_arg_type(iter) == DBUS_TYPE_INT32) {
int32_t temp = 0;
dbus_message_iter_get_basic(iter, &temp);
*value = static_cast<int>(temp);
return true;
}
uint32_t temp = 0;
if (ReadUint32Like(iter, &temp)) {
*value = static_cast<int>(temp);
return true;
}
return false;
}
bool ReadFirstStreamId(DBusMessageIter* variant, uint32_t* stream_id) { bool ReadFirstStreamId(DBusMessageIter* variant, uint32_t* stream_id) {
if (!variant || !stream_id) { if (!variant || !stream_id) {
return false; return false;
@@ -215,6 +243,85 @@ bool ReadFirstStreamId(DBusMessageIter* variant, uint32_t* stream_id) {
return false; return false;
} }
bool ReadFirstStreamGeometry(DBusMessageIter* variant, int* width,
int* height) {
if (!variant || !width || !height) {
return false;
}
if (dbus_message_iter_get_arg_type(variant) != DBUS_TYPE_ARRAY) {
return false;
}
int parsed_width = 0;
int parsed_height = 0;
DBusMessageIter streams;
dbus_message_iter_recurse(variant, &streams);
while (dbus_message_iter_get_arg_type(&streams) != DBUS_TYPE_INVALID) {
if (dbus_message_iter_get_arg_type(&streams) == DBUS_TYPE_STRUCT) {
DBusMessageIter stream;
dbus_message_iter_recurse(&streams, &stream);
if (dbus_message_iter_get_arg_type(&stream) == DBUS_TYPE_UINT32) {
dbus_message_iter_next(&stream);
}
if (dbus_message_iter_get_arg_type(&stream) == DBUS_TYPE_ARRAY) {
int stream_width = 0;
int stream_height = 0;
int logical_width = 0;
int logical_height = 0;
DBusMessageIter props;
dbus_message_iter_recurse(&stream, &props);
while (dbus_message_iter_get_arg_type(&props) != DBUS_TYPE_INVALID) {
if (dbus_message_iter_get_arg_type(&props) == DBUS_TYPE_DICT_ENTRY) {
DBusMessageIter prop_entry;
dbus_message_iter_recurse(&props, &prop_entry);
const char* prop_key = nullptr;
dbus_message_iter_get_basic(&prop_entry, &prop_key);
if (prop_key && dbus_message_iter_next(&prop_entry) &&
dbus_message_iter_get_arg_type(&prop_entry) ==
DBUS_TYPE_VARIANT) {
DBusMessageIter prop_variant;
dbus_message_iter_recurse(&prop_entry, &prop_variant);
if (dbus_message_iter_get_arg_type(&prop_variant) ==
DBUS_TYPE_STRUCT) {
DBusMessageIter size_iter;
int candidate_width = 0;
int candidate_height = 0;
dbus_message_iter_recurse(&prop_variant, &size_iter);
if (ReadIntLike(&size_iter, &candidate_width) &&
dbus_message_iter_next(&size_iter) &&
ReadIntLike(&size_iter, &candidate_height)) {
if (strcmp(prop_key, "logical_size") == 0) {
logical_width = candidate_width;
logical_height = candidate_height;
} else if (strcmp(prop_key, "size") == 0) {
stream_width = candidate_width;
stream_height = candidate_height;
}
}
}
}
}
dbus_message_iter_next(&props);
}
parsed_width = logical_width > 0 ? logical_width : stream_width;
parsed_height = logical_height > 0 ? logical_height : stream_height;
if (parsed_width > 0 && parsed_height > 0) {
*width = parsed_width;
*height = parsed_height;
return true;
}
}
}
dbus_message_iter_next(&streams);
}
return false;
}
std::string BuildSessionHandleFromRequestPath( std::string BuildSessionHandleFromRequestPath(
const std::string& request_path, const std::string& session_handle_token) { const std::string& request_path, const std::string& session_handle_token) {
if (request_path.rfind(kPortalRequestPathPrefix, 0) != 0 || if (request_path.rfind(kPortalRequestPathPrefix, 0) != 0 ||
@@ -361,8 +468,7 @@ bool ExtractPortalResponse(DBusMessage* message, uint32_t* response_code,
bool SendPortalRequestAndHandleResponse( bool SendPortalRequestAndHandleResponse(
DBusConnection* connection, const char* interface_name, DBusConnection* connection, const char* interface_name,
const char* method_name, const char* method_name, const char* action_name,
const char* action_name,
const std::function<bool(DBusMessage*)>& append_message_args, const std::function<bool(DBusMessage*)>& append_message_args,
const std::function<bool(uint32_t, DBusMessageIter*)>& handle_results, const std::function<bool(uint32_t, DBusMessageIter*)>& handle_results,
std::string* request_path_out = nullptr) { std::string* request_path_out = nullptr) {
@@ -386,8 +492,8 @@ bool SendPortalRequestAndHandleResponse(
DBusError error; DBusError error;
dbus_error_init(&error); dbus_error_init(&error);
DBusMessage* reply = DBusMessage* reply = dbus_connection_send_with_reply_and_block(
dbus_connection_send_with_reply_and_block(connection, message, -1, &error); connection, message, -1, &error);
dbus_message_unref(message); dbus_message_unref(message);
if (!reply) { if (!reply) {
LogDbusError(action_name ? action_name : method_name, &error); LogDbusError(action_name ? action_name : method_name, &error);
@@ -438,6 +544,8 @@ bool MouseController::InitWaylandPortal() {
dbus_connection_ = shared_session.connection; dbus_connection_ = shared_session.connection;
wayland_session_handle_ = shared_session.session_handle; wayland_session_handle_ = shared_session.session_handle;
wayland_absolute_stream_id_ = shared_session.stream_id; wayland_absolute_stream_id_ = shared_session.stream_id;
wayland_portal_space_width_ = shared_session.width;
wayland_portal_space_height_ = shared_session.height;
last_display_index_ = -1; last_display_index_ = -1;
last_norm_x_ = -1.0; last_norm_x_ = -1.0;
last_norm_y_ = -1.0; last_norm_y_ = -1.0;
@@ -448,9 +556,11 @@ bool MouseController::InitWaylandPortal() {
wayland_absolute_mode_ = WaylandAbsoluteMode::kUnknown; wayland_absolute_mode_ = WaylandAbsoluteMode::kUnknown;
wayland_absolute_disabled_logged_ = false; wayland_absolute_disabled_logged_ = false;
using_shared_wayland_session_ = true; using_shared_wayland_session_ = true;
LOG_INFO("Mouse controller attached to shared Wayland portal session, " LOG_INFO(
"stream_id={}", "Mouse controller attached to shared Wayland portal session, "
wayland_absolute_stream_id_); "stream_id={}, portal_space={}x{}",
wayland_absolute_stream_id_, wayland_portal_space_width_,
wayland_portal_space_height_);
return true; return true;
}; };
@@ -469,7 +579,8 @@ bool MouseController::InitWaylandPortal() {
if (!waiting_logged) { if (!waiting_logged) {
waiting_logged = true; waiting_logged = true;
LOG_INFO("Waiting for shared Wayland portal session from screen " LOG_INFO(
"Waiting for shared Wayland portal session from screen "
"capturer before creating a standalone mouse session"); "capturer before creating a standalone mouse session");
} }
@@ -477,7 +588,8 @@ bool MouseController::InitWaylandPortal() {
} }
if (waiting_logged) { if (waiting_logged) {
LOG_WARN("Shared Wayland portal session did not appear in time; falling " LOG_WARN(
"Shared Wayland portal session did not appear in time; falling "
"back to standalone mouse portal session"); "back to standalone mouse portal session");
} }
@@ -677,6 +789,8 @@ bool MouseController::InitWaylandPortal() {
uint32_t granted_devices = 0; uint32_t granted_devices = 0;
uint32_t absolute_stream_id = 0; uint32_t absolute_stream_id = 0;
int absolute_space_width = 0;
int absolute_space_height = 0;
DBusMessageIter dict; DBusMessageIter dict;
dbus_message_iter_recurse(results, &dict); dbus_message_iter_recurse(results, &dict);
while (dbus_message_iter_get_arg_type(&dict) != DBUS_TYPE_INVALID) { while (dbus_message_iter_get_arg_type(&dict) != DBUS_TYPE_INVALID) {
@@ -694,6 +808,8 @@ bool MouseController::InitWaylandPortal() {
ReadUint32Like(&variant, &granted_devices); ReadUint32Like(&variant, &granted_devices);
} else if (strcmp(key, "streams") == 0) { } else if (strcmp(key, "streams") == 0) {
ReadFirstStreamId(&variant, &absolute_stream_id); ReadFirstStreamId(&variant, &absolute_stream_id);
ReadFirstStreamGeometry(&variant, &absolute_space_width,
&absolute_space_height);
} }
} }
} }
@@ -703,19 +819,24 @@ bool MouseController::InitWaylandPortal() {
pointer_granted = (granted_devices & kRemoteDesktopDevicePointer) != 0; pointer_granted = (granted_devices & kRemoteDesktopDevicePointer) != 0;
if (!pointer_granted) { if (!pointer_granted) {
LOG_ERROR( LOG_ERROR(
"RemoteDesktop.Start granted devices mask={}, pointer not allowed", "RemoteDesktop.Start granted devices mask={}, pointer not "
"allowed",
granted_devices); granted_devices);
return false; return false;
} }
if (absolute_stream_id == 0) { if (absolute_stream_id == 0) {
LOG_ERROR("RemoteDesktop.Start did not return a screencast stream id"); LOG_ERROR(
"RemoteDesktop.Start did not return a screencast stream id");
return false; return false;
} }
wayland_absolute_stream_id_ = absolute_stream_id; wayland_absolute_stream_id_ = absolute_stream_id;
wayland_portal_space_width_ = absolute_space_width;
wayland_portal_space_height_ = absolute_space_height;
wayland_absolute_mode_ = WaylandAbsoluteMode::kUnknown; wayland_absolute_mode_ = WaylandAbsoluteMode::kUnknown;
wayland_absolute_disabled_logged_ = false; wayland_absolute_disabled_logged_ = false;
LOG_INFO("Wayland mouse absolute stream id={}", LOG_INFO("Wayland mouse absolute stream id={}, portal_space={}x{}",
wayland_absolute_stream_id_); wayland_absolute_stream_id_, wayland_portal_space_width_,
wayland_portal_space_height_);
return true; return true;
}); });
@@ -782,6 +903,8 @@ void MouseController::CleanupWaylandPortal() {
wayland_absolute_mode_ = WaylandAbsoluteMode::kUnknown; wayland_absolute_mode_ = WaylandAbsoluteMode::kUnknown;
wayland_absolute_disabled_logged_ = false; wayland_absolute_disabled_logged_ = false;
wayland_absolute_stream_id_ = 0; wayland_absolute_stream_id_ = 0;
wayland_portal_space_width_ = 0;
wayland_portal_space_height_ = 0;
using_shared_wayland_session_ = false; using_shared_wayland_session_ = false;
} }
@@ -835,49 +958,80 @@ int MouseController::SendWaylandMouseCommand(RemoteAction remote_action,
} }
const uint32_t stream = wayland_absolute_stream_id_; const uint32_t stream = wayland_absolute_stream_id_;
const double abs_x = norm_x * std::max(width - 1, 1); const int portal_width =
const double abs_y = norm_y * std::max(height - 1, 1); wayland_portal_space_width_ > 0 ? wayland_portal_space_width_ : width;
const int portal_height = wayland_portal_space_height_ > 0
? wayland_portal_space_height_
: height;
const double abs_x = norm_x * static_cast<double>(width);
const double abs_y = norm_y * static_cast<double>(height);
const double max_x = std::nextafter(static_cast<double>(width), 0.0);
const double max_y = std::nextafter(static_cast<double>(height), 0.0);
const double send_x = std::clamp(abs_x, 0.0, std::max(max_x, 0.0));
const double send_y = std::clamp(abs_y, 0.0, std::max(max_y, 0.0));
const bool can_use_relative = last_display_index_ == display_index &&
last_norm_x_ >= 0.0 && last_norm_y_ >= 0.0;
const double rel_dx =
(norm_x - last_norm_x_) * static_cast<double>(portal_width);
const double rel_dy =
(norm_y - last_norm_y_) * static_cast<double>(portal_height);
auto accept_absolute = [&]() { auto accept_motion = [&]() {
last_display_index_ = display_index; last_display_index_ = display_index;
last_norm_x_ = norm_x; last_norm_x_ = norm_x;
last_norm_y_ = norm_y; last_norm_y_ = norm_y;
wayland_absolute_disabled_logged_ = false;
return 0; return 0;
}; };
auto try_relative_fallback = [&]() -> bool {
if (!can_use_relative) {
return false;
}
if (std::abs(rel_dx) < 1e-6 && std::abs(rel_dy) < 1e-6) {
return false;
}
if (NotifyWaylandPointerMotion(rel_dx, rel_dy)) {
return true;
}
return false;
};
if (wayland_absolute_mode_ == WaylandAbsoluteMode::kDisabled) {
if (try_relative_fallback()) {
return accept_motion();
}
if (!wayland_absolute_disabled_logged_) {
wayland_absolute_disabled_logged_ = true;
LOG_ERROR("NotifyPointerMotionAbsolute rejected by portal backend");
}
return -3;
}
if (wayland_absolute_mode_ == WaylandAbsoluteMode::kPixels) { if (wayland_absolute_mode_ == WaylandAbsoluteMode::kPixels) {
if (NotifyWaylandPointerMotionAbsolute(stream, abs_x, abs_y)) { if (NotifyWaylandPointerMotionAbsolute(stream, send_x, send_y)) {
return accept_absolute(); return accept_motion();
} }
wayland_absolute_mode_ = WaylandAbsoluteMode::kDisabled; if (try_relative_fallback()) {
} else if (wayland_absolute_mode_ == WaylandAbsoluteMode::kNormalized) { return accept_motion();
if (NotifyWaylandPointerMotionAbsolute(stream, norm_x, norm_y)) {
return accept_absolute();
} }
wayland_absolute_mode_ = WaylandAbsoluteMode::kDisabled; } else if (wayland_absolute_mode_ == WaylandAbsoluteMode::kUnknown) {
} else { if (NotifyWaylandPointerMotionAbsolute(stream, send_x, send_y)) {
if (NotifyWaylandPointerMotionAbsolute(stream, abs_x, abs_y)) {
wayland_absolute_mode_ = WaylandAbsoluteMode::kPixels; wayland_absolute_mode_ = WaylandAbsoluteMode::kPixels;
LOG_INFO("Wayland absolute pointer mode selected: pixel coordinates");
return accept_absolute();
}
if (NotifyWaylandPointerMotionAbsolute(stream, norm_x, norm_y)) {
wayland_absolute_mode_ = WaylandAbsoluteMode::kNormalized;
LOG_INFO( LOG_INFO(
"Wayland absolute pointer mode selected: normalized " "Wayland absolute pointer mode selected: pixel coordinates "
"coordinates"); "(pointer space {}x{})",
return accept_absolute(); width, height);
return accept_motion();
}
if (try_relative_fallback()) {
return accept_motion();
} }
wayland_absolute_mode_ = WaylandAbsoluteMode::kDisabled;
} }
if (!wayland_absolute_disabled_logged_) { if (!wayland_absolute_disabled_logged_) {
wayland_absolute_disabled_logged_ = true; wayland_absolute_disabled_logged_ = true;
LOG_ERROR( LOG_ERROR("NotifyPointerMotionAbsolute rejected by portal backend");
"NotifyPointerMotionAbsolute rejected by portal backend in both "
"pixel and normalized modes");
} }
return -3; return -3;
} }
@@ -1030,9 +1184,9 @@ bool MouseController::SendWaylandPortalVoidCall(
return false; return false;
} }
DBusMessage* message = dbus_message_new_method_call( DBusMessage* message =
kPortalBusName, kPortalObjectPath, kPortalRemoteDesktopInterface, dbus_message_new_method_call(kPortalBusName, kPortalObjectPath,
method_name); kPortalRemoteDesktopInterface, method_name);
if (!message) { if (!message) {
LOG_ERROR("Failed to allocate {} message", method_name); LOG_ERROR("Failed to allocate {} message", method_name);
return false; return false;

View File

@@ -54,6 +54,7 @@ class Render {
std::chrono::steady_clock::time_point file_send_last_update_time_; std::chrono::steady_clock::time_point file_send_last_update_time_;
uint64_t file_send_last_bytes_ = 0; uint64_t file_send_last_bytes_ = 0;
bool file_transfer_window_visible_ = false; bool file_transfer_window_visible_ = false;
bool file_transfer_window_hovered_ = false;
std::atomic<uint32_t> current_file_id_{0}; std::atomic<uint32_t> current_file_id_{0};
struct QueuedFile { struct QueuedFile {

View File

@@ -234,13 +234,20 @@ int Render::ProcessMouseEvent(const SDL_Event& event) {
continue; continue;
} }
const bool file_transfer_window_hovered =
props->file_transfer_.file_transfer_window_hovered_;
const bool overlay_hovered = props->control_bar_hovered_ ||
props->display_selectable_hovered_ ||
file_transfer_window_hovered;
const SDL_FRect render_rect = props->stream_render_rect_f_; const SDL_FRect render_rect = props->stream_render_rect_f_;
if (render_rect.w <= 1.0f || render_rect.h <= 1.0f) { if (render_rect.w <= 1.0f || render_rect.h <= 1.0f) {
continue; continue;
} }
if (is_pointer_position_event && cursor_x >= render_rect.x && if (is_pointer_position_event && cursor_x >= render_rect.x &&
cursor_x <= render_rect.x + render_rect.w && cursor_y >= render_rect.y && cursor_x <= render_rect.x + render_rect.w &&
cursor_y >= render_rect.y &&
cursor_y <= render_rect.y + render_rect.h) { cursor_y <= render_rect.y + render_rect.h) {
controlled_remote_id_ = it.first; controlled_remote_id_ = it.first;
last_mouse_event.motion.x = cursor_x; last_mouse_event.motion.x = cursor_x;
@@ -276,7 +283,7 @@ int Render::ProcessMouseEvent(const SDL_Event& event) {
remote_action.m.flag = MouseFlag::move; remote_action.m.flag = MouseFlag::move;
} }
if (props->control_bar_hovered_ || props->display_selectable_hovered_) { if (overlay_hovered) {
break; break;
} }
if (props->peer_) { if (props->peer_) {
@@ -322,7 +329,7 @@ int Render::ProcessMouseEvent(const SDL_Event& event) {
remote_action.m.x = std::clamp(remote_action.m.x, 0.0f, 1.0f); remote_action.m.x = std::clamp(remote_action.m.x, 0.0f, 1.0f);
remote_action.m.y = std::clamp(remote_action.m.y, 0.0f, 1.0f); remote_action.m.y = std::clamp(remote_action.m.y, 0.0f, 1.0f);
if (props->control_bar_hovered_) { if (overlay_hovered) {
continue; continue;
} }
if (props->peer_) { if (props->peer_) {
@@ -1028,7 +1035,8 @@ void Render::OnConnectionStatusCb(ConnectionStatus status, const char* user_id,
// Keep Wayland capture session warm to avoid black screen on // Keep Wayland capture session warm to avoid black screen on
// subsequent reconnects. // subsequent reconnects.
render->start_screen_capturer_ = true; render->start_screen_capturer_ = true;
LOG_INFO("Keeping Wayland screen capturer running after " LOG_INFO(
"Keeping Wayland screen capturer running after "
"disconnect to preserve reconnect stability"); "disconnect to preserve reconnect stability");
} else { } else {
render->start_screen_capturer_ = false; render->start_screen_capturer_ = false;

View File

@@ -257,4 +257,3 @@ int Render::ControlWindow(std::shared_ptr<SubStreamWindowProperties>& props) {
return 0; return 0;
} }
} // namespace crossdesk } // namespace crossdesk

View File

@@ -31,6 +31,7 @@ int BitrateDisplay(int bitrate) {
int Render::FileTransferWindow( int Render::FileTransferWindow(
std::shared_ptr<SubStreamWindowProperties>& props) { std::shared_ptr<SubStreamWindowProperties>& props) {
FileTransferState* state = props ? &props->file_transfer_ : &file_transfer_; FileTransferState* state = props ? &props->file_transfer_ : &file_transfer_;
state->file_transfer_window_hovered_ = false;
// Only show window if there are files in transfer list or currently // Only show window if there are files in transfer list or currently
// transferring // transferring
@@ -72,8 +73,6 @@ int Render::FileTransferWindow(
return 0; return 0;
} }
ImGuiIO& io = ImGui::GetIO();
// Position window at bottom-left of stream window // Position window at bottom-left of stream window
// Adjust window size based on number of files // Adjust window size based on number of files
float file_transfer_window_width = main_window_width_ * 0.6f; float file_transfer_window_width = main_window_width_ * 0.6f;
@@ -82,15 +81,25 @@ int Render::FileTransferWindow(
float pos_x = file_transfer_window_width * 0.05f; float pos_x = file_transfer_window_width * 0.05f;
float pos_y = stream_window_height_ - file_transfer_window_height - float pos_y = stream_window_height_ - file_transfer_window_height -
file_transfer_window_width * 0.05; file_transfer_window_width * 0.05;
float same_line_width = file_transfer_window_width * 0.1f;
const ImVec2 mouse_pos = ImGui::GetMousePos();
const bool mouse_in_window_rect =
mouse_pos.x >= pos_x &&
mouse_pos.x <= pos_x + file_transfer_window_width &&
mouse_pos.y >= pos_y &&
mouse_pos.y <= pos_y + file_transfer_window_height;
ImGui::SetNextWindowPos(ImVec2(pos_x, pos_y), ImGuiCond_Always); ImGui::SetNextWindowPos(ImVec2(pos_x, pos_y), ImGuiCond_Always);
ImGui::SetNextWindowSize( ImGui::SetNextWindowSize(
ImVec2(file_transfer_window_width, file_transfer_window_height), ImVec2(file_transfer_window_width, file_transfer_window_height),
ImGuiCond_Always); ImGuiCond_Always);
if (mouse_in_window_rect) {
ImGui::SetNextWindowFocus();
}
// Set Chinese font for proper display // Set Chinese font for proper display
if (stream_windows_system_chinese_font_) { const bool has_chinese_font = stream_windows_system_chinese_font_ != nullptr;
if (has_chinese_font) {
ImGui::PushFont(stream_windows_system_chinese_font_); ImGui::PushFont(stream_windows_system_chinese_font_);
} }
@@ -103,25 +112,28 @@ int Render::FileTransferWindow(
ImGui::SetWindowFontScale(0.5f); ImGui::SetWindowFontScale(0.5f);
bool window_opened = true; bool window_opened = true;
if (ImGui::Begin( const bool show_contents = ImGui::Begin(
localization::file_transfer_progress[localization_language_index_] localization::file_transfer_progress[localization_language_index_]
.c_str(), .c_str(),
&window_opened, &window_opened,
ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_NoScrollbar)) { ImGuiWindowFlags_NoScrollbar);
ImGui::SetWindowFontScale(1.0f);
ImGui::SetWindowFontScale(0.5f);
ImGui::PopStyleColor(4); ImGui::PopStyleColor(4);
ImGui::PopStyleVar(2); ImGui::PopStyleVar(2);
// Close button handling state->file_transfer_window_hovered_ =
mouse_in_window_rect ||
ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
if (!window_opened) { if (!window_opened) {
state->file_transfer_window_visible_ = false; state->file_transfer_window_visible_ = false;
ImGui::End();
return 0;
} }
if (show_contents && window_opened) {
ImGui::SetWindowFontScale(1.0f);
ImGui::SetWindowFontScale(0.5f);
// Display file list // Display file list
if (file_list.empty()) { if (file_list.empty()) {
ImGui::Text("No files in transfer queue"); ImGui::Text("No files in transfer queue");
@@ -225,21 +237,16 @@ int Render::FileTransferWindow(
} }
ImGui::SetWindowFontScale(1.0f); ImGui::SetWindowFontScale(1.0f);
ImGui::SetWindowFontScale(0.5f); ImGui::SetWindowFontScale(0.5f);
}
ImGui::End(); ImGui::End();
ImGui::SetWindowFontScale(1.0f); ImGui::SetWindowFontScale(1.0f);
// Pop Chinese font if it was pushed if (has_chinese_font) {
if (stream_windows_system_chinese_font_) {
ImGui::PopFont(); ImGui::PopFont();
} }
} else {
ImGui::PopStyleColor(4);
ImGui::PopStyleVar(2);
}
ImGui::SetWindowFontScale(1.0f);
return 0; return 0;
} }
} // namespace crossdesk } // namespace crossdesk

View File

@@ -177,8 +177,8 @@ int ScreenCapturerLinux::Start(bool show_cursor) {
backend_name = "Wayland"; backend_name = "Wayland";
} }
LOG_WARN("Linux screen capturer backend {} start failed: {}", LOG_WARN("Linux screen capturer backend {} start failed: {}", backend_name,
backend_name, ret); ret);
if (backend_ == BackendType::kX11 && kDrmBuildEnabled && if (backend_ == BackendType::kX11 && kDrmBuildEnabled &&
TryFallbackToDrm(show_cursor)) { TryFallbackToDrm(show_cursor)) {
@@ -484,7 +484,8 @@ void ScreenCapturerLinux::UpdateAliasesFromBackend(ScreenCapturer* backend) {
} }
} }
std::string ScreenCapturerLinux::MapDisplayName(const char* display_name) const { std::string ScreenCapturerLinux::MapDisplayName(
const char* display_name) const {
std::string input_name = display_name ? display_name : ""; std::string input_name = display_name ? display_name : "";
if (input_name.empty()) { if (input_name.empty()) {
return input_name; return input_name;

View File

@@ -3,13 +3,13 @@
#include "screen_capturer_wayland_build.h" #include "screen_capturer_wayland_build.h"
#if !CROSSDESK_WAYLAND_BUILD_ENABLED #if !CROSSDESK_WAYLAND_BUILD_ENABLED
#error "Wayland capturer requires USE_WAYLAND=true and Wayland development headers" #error \
"Wayland capturer requires USE_WAYLAND=true and Wayland development headers"
#endif #endif
#include <chrono>
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
#include <chrono>
#include <thread> #include <thread>
#include "platform.h" #include "platform.h"
@@ -69,6 +69,9 @@ int ScreenCapturerWayland::Init(const int fps, cb_desktop_data cb) {
frame_width_ = kFallbackWidth; frame_width_ = kFallbackWidth;
frame_height_ = kFallbackHeight; frame_height_ = kFallbackHeight;
frame_stride_ = kFallbackWidth * 4; frame_stride_ = kFallbackWidth * 4;
portal_has_logical_size_ = false;
portal_stream_width_ = 0;
portal_stream_height_ = 0;
logical_width_ = kFallbackWidth; logical_width_ = kFallbackWidth;
logical_height_ = kFallbackHeight; logical_height_ = kFallbackHeight;
y_plane_.resize(kFallbackWidth * kFallbackHeight); y_plane_.resize(kFallbackWidth * kFallbackHeight);
@@ -94,9 +97,9 @@ int ScreenCapturerWayland::Start(bool show_cursor) {
show_cursor_ = show_cursor; show_cursor_ = show_cursor;
paused_ = false; paused_ = false;
pipewire_node_id_ = 0; pipewire_node_id_ = 0;
UpdateDisplayGeometry(logical_width_ > 0 ? logical_width_ : kFallbackWidth, UpdateDisplayGeometry(
logical_height_ > 0 ? logical_height_ logical_width_ > 0 ? logical_width_ : kFallbackWidth,
: kFallbackHeight); logical_height_ > 0 ? logical_height_ : kFallbackHeight);
pipewire_format_ready_.store(false); pipewire_format_ready_.store(false);
pipewire_stream_start_ms_.store(0); pipewire_stream_start_ms_.store(0);
pipewire_last_frame_ms_.store(0); pipewire_last_frame_ms_.store(0);
@@ -111,9 +114,9 @@ int ScreenCapturerWayland::Stop() {
thread_.join(); thread_.join();
} }
pipewire_node_id_ = 0; pipewire_node_id_ = 0;
UpdateDisplayGeometry(logical_width_ > 0 ? logical_width_ : kFallbackWidth, UpdateDisplayGeometry(
logical_height_ > 0 ? logical_height_ logical_width_ > 0 ? logical_width_ : kFallbackWidth,
: kFallbackHeight); logical_height_ > 0 ? logical_height_ : kFallbackHeight);
return 0; return 0;
} }
@@ -182,8 +185,8 @@ void ScreenCapturerWayland::Run() {
const bool format_timeout = const bool format_timeout =
stream_start > 0 && !format_ready && (now - stream_start) > 1200; stream_start > 0 && !format_ready && (now - stream_start) > 1200;
const bool first_frame_timeout = const bool first_frame_timeout = stream_start > 0 && format_ready &&
stream_start > 0 && format_ready && last_frame == 0 && last_frame == 0 &&
(now - stream_start) > 4000; (now - stream_start) > 4000;
const bool frame_stall = last_frame > 0 && (now - last_frame) > 5000; const bool frame_stall = last_frame > 0 && (now - last_frame) > 5000;
@@ -200,10 +203,10 @@ void ScreenCapturerWayland::Run() {
} }
++recovery_index; ++recovery_index;
const char* reason = format_timeout const char* reason =
format_timeout
? "format-timeout" ? "format-timeout"
: (first_frame_timeout ? "first-frame-timeout" : (first_frame_timeout ? "first-frame-timeout" : "frame-stall");
: "frame-stall");
const auto& config = kRecoveryConfigs[recovery_index]; const auto& config = kRecoveryConfigs[recovery_index];
LOG_WARN( LOG_WARN(
"Wayland capture stalled ({}) - retrying PipeWire only, " "Wayland capture stalled ({}) - retrying PipeWire only, "

View File

@@ -94,10 +94,13 @@ class ScreenCapturerWayland : public ScreenCapturer {
bool pipewire_thread_loop_started_ = false; bool pipewire_thread_loop_started_ = false;
bool pointer_granted_ = false; bool pointer_granted_ = false;
bool shared_session_registered_ = false; bool shared_session_registered_ = false;
bool portal_has_logical_size_ = false;
uint32_t spa_video_format_ = 0; uint32_t spa_video_format_ = 0;
int frame_width_ = 0; int frame_width_ = 0;
int frame_height_ = 0; int frame_height_ = 0;
int frame_stride_ = 0; int frame_stride_ = 0;
int portal_stream_width_ = 0;
int portal_stream_height_ = 0;
int logical_width_ = 0; int logical_width_ = 0;
int logical_height_ = 0; int logical_height_ = 0;

View File

@@ -1,14 +1,16 @@
#include "screen_capturer_wayland.h" #include "screen_capturer_wayland.h"
#include "screen_capturer_wayland_build.h" #include "screen_capturer_wayland_build.h"
#if CROSSDESK_WAYLAND_BUILD_ENABLED #if CROSSDESK_WAYLAND_BUILD_ENABLED
#include <chrono>
#include <cstdint>
#include <thread>
#include <unistd.h> #include <unistd.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <limits>
#include <thread>
#include <vector> #include <vector>
#include "libyuv.h" #include "libyuv.h"
@@ -57,6 +59,22 @@ int64_t NowMs() {
.count(); .count();
} }
double SnapLikelyFractionalScale(double observed_scale) {
static constexpr double kCandidates[] = {
1.0, 1.25, 1.3333333333, 1.5, 1.6666666667, 1.75, 2.0, 2.25, 2.5, 3.0};
double best = observed_scale;
double best_error = std::numeric_limits<double>::max();
for (double candidate : kCandidates) {
const double error = std::abs(candidate - observed_scale);
if (error < best_error) {
best = candidate;
best_error = error;
}
}
return best_error <= 0.08 ? best : observed_scale;
}
struct PipeWireTargetLookupState { struct PipeWireTargetLookupState {
pw_thread_loop* loop = nullptr; pw_thread_loop* loop = nullptr;
uint32_t target_node_id = 0; uint32_t target_node_id = 0;
@@ -87,9 +105,9 @@ std::string LookupPipeWireTargetObjectSerial(pw_core* core,
pw_registry_events registry_events{}; pw_registry_events registry_events{};
registry_events.version = PW_VERSION_REGISTRY_EVENTS; registry_events.version = PW_VERSION_REGISTRY_EVENTS;
registry_events.global = registry_events.global = [](void* userdata, uint32_t id, uint32_t permissions,
[](void* userdata, uint32_t id, uint32_t permissions, const char* type, const char* type, uint32_t version,
uint32_t version, const spa_dict* props) { const spa_dict* props) {
(void)permissions; (void)permissions;
(void)version; (void)version;
auto* state = static_cast<PipeWireTargetLookupState*>(userdata); auto* state = static_cast<PipeWireTargetLookupState*>(userdata);
@@ -226,23 +244,23 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
std::string target_object_serial; std::string target_object_serial;
if (mode == PipeWireConnectMode::kTargetObject) { if (mode == PipeWireConnectMode::kTargetObject) {
target_object_serial = target_object_serial = LookupPipeWireTargetObjectSerial(
LookupPipeWireTargetObjectSerial(pw_core_, pw_thread_loop_, pw_core_, pw_thread_loop_, pipewire_node_id_);
pipewire_node_id_);
if (!target_object_serial.empty()) { if (!target_object_serial.empty()) {
pw_properties_set(stream_props, PW_KEY_TARGET_OBJECT, pw_properties_set(stream_props, PW_KEY_TARGET_OBJECT,
target_object_serial.c_str()); target_object_serial.c_str());
LOG_INFO("PipeWire target object serial for node {} is {}", LOG_INFO("PipeWire target object serial for node {} is {}",
pipewire_node_id_, target_object_serial); pipewire_node_id_, target_object_serial);
} else { } else {
LOG_WARN("PipeWire target object serial lookup failed for node {}, " LOG_WARN(
"PipeWire target object serial lookup failed for node {}, "
"falling back to direct target id in target-object mode", "falling back to direct target id in target-object mode",
pipewire_node_id_); pipewire_node_id_);
} }
} }
pw_stream_ = pw_stream_new(pw_core_, "CrossDesk Wayland Capture", pw_stream_ =
stream_props); pw_stream_new(pw_core_, "CrossDesk Wayland Capture", stream_props);
if (!pw_stream_) { if (!pw_stream_) {
LOG_ERROR("Failed to create PipeWire stream"); LOG_ERROR("Failed to create PipeWire stream");
pw_thread_loop_unlock(pw_thread_loop_); pw_thread_loop_unlock(pw_thread_loop_);
@@ -256,9 +274,9 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
static const pw_stream_events stream_events = [] { static const pw_stream_events stream_events = [] {
pw_stream_events events{}; pw_stream_events events{};
events.version = PW_VERSION_STREAM_EVENTS; events.version = PW_VERSION_STREAM_EVENTS;
events.state_changed = events.state_changed = [](void* userdata, enum pw_stream_state old_state,
[](void* userdata, enum pw_stream_state old_state, enum pw_stream_state state,
enum pw_stream_state state, const char* error_message) { const char* error_message) {
auto* self = static_cast<ScreenCapturerWayland*>(userdata); auto* self = static_cast<ScreenCapturerWayland*>(userdata);
if (!self) { if (!self) {
return; return;
@@ -274,10 +292,9 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
LOG_INFO("PipeWire stream state: {} -> {}", LOG_INFO("PipeWire stream state: {} -> {}",
pw_stream_state_as_string(old_state), pw_stream_state_as_string(old_state),
pw_stream_state_as_string(state)); pw_stream_state_as_string(state));
}; };
events.param_changed = events.param_changed = [](void* userdata, uint32_t id,
[](void* userdata, uint32_t id, const struct spa_pod* param) { const struct spa_pod* param) {
auto* self = static_cast<ScreenCapturerWayland*>(userdata); auto* self = static_cast<ScreenCapturerWayland*>(userdata);
if (!self || id != SPA_PARAM_Format || !param) { if (!self || id != SPA_PARAM_Format || !param) {
return; return;
@@ -298,13 +315,11 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
(self->spa_video_format_ == SPA_VIDEO_FORMAT_BGRx) || (self->spa_video_format_ == SPA_VIDEO_FORMAT_BGRx) ||
(self->spa_video_format_ == SPA_VIDEO_FORMAT_BGRA); (self->spa_video_format_ == SPA_VIDEO_FORMAT_BGRA);
#ifdef SPA_VIDEO_FORMAT_RGBx #ifdef SPA_VIDEO_FORMAT_RGBx
supported_format = supported_format = supported_format ||
supported_format ||
(self->spa_video_format_ == SPA_VIDEO_FORMAT_RGBx); (self->spa_video_format_ == SPA_VIDEO_FORMAT_RGBx);
#endif #endif
#ifdef SPA_VIDEO_FORMAT_RGBA #ifdef SPA_VIDEO_FORMAT_RGBA
supported_format = supported_format = supported_format ||
supported_format ||
(self->spa_video_format_ == SPA_VIDEO_FORMAT_RGBA); (self->spa_video_format_ == SPA_VIDEO_FORMAT_RGBA);
#endif #endif
if (!supported_format) { if (!supported_format) {
@@ -331,26 +346,23 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
const spa_pod* params[2]; const spa_pod* params[2];
uint32_t param_count = 0; uint32_t param_count = 0;
params[param_count++] = reinterpret_cast<const spa_pod*>( params[param_count++] =
spa_pod_builder_add_object( reinterpret_cast<const spa_pod*>(spa_pod_builder_add_object(
&builder, SPA_TYPE_OBJECT_ParamBuffers, SPA_PARAM_Buffers, &builder, SPA_TYPE_OBJECT_ParamBuffers, SPA_PARAM_Buffers,
CROSSDESK_SPA_PARAM_BUFFERS_BUFFERS, CROSSDESK_SPA_PARAM_BUFFERS_BUFFERS,
SPA_POD_CHOICE_RANGE_Int(8, 4, 16), SPA_POD_CHOICE_RANGE_Int(8, 4, 16),
CROSSDESK_SPA_PARAM_BUFFERS_BLOCKS, SPA_POD_Int(1), CROSSDESK_SPA_PARAM_BUFFERS_BLOCKS, SPA_POD_Int(1),
CROSSDESK_SPA_PARAM_BUFFERS_SIZE, CROSSDESK_SPA_PARAM_BUFFERS_SIZE,
SPA_POD_CHOICE_RANGE_Int(self->frame_stride_ * SPA_POD_CHOICE_RANGE_Int(
self->frame_height_, self->frame_stride_ * self->frame_height_,
self->frame_stride_ * self->frame_stride_ * self->frame_height_,
self->frame_height_, self->frame_stride_ * self->frame_height_),
self->frame_stride_ *
self->frame_height_),
CROSSDESK_SPA_PARAM_BUFFERS_STRIDE, CROSSDESK_SPA_PARAM_BUFFERS_STRIDE,
SPA_POD_CHOICE_RANGE_Int(self->frame_stride_, SPA_POD_CHOICE_RANGE_Int(self->frame_stride_, self->frame_stride_,
self->frame_stride_,
self->frame_stride_))); self->frame_stride_)));
params[param_count++] = reinterpret_cast<const spa_pod*>( params[param_count++] =
spa_pod_builder_add_object( reinterpret_cast<const spa_pod*>(spa_pod_builder_add_object(
&builder, SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta, &builder, SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta,
CROSSDESK_SPA_PARAM_META_TYPE, SPA_POD_Id(SPA_META_Header), CROSSDESK_SPA_PARAM_META_TYPE, SPA_POD_Id(SPA_META_Header),
CROSSDESK_SPA_PARAM_META_SIZE, CROSSDESK_SPA_PARAM_META_SIZE,
@@ -361,17 +373,80 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
} }
self->pipewire_format_ready_.store(true); self->pipewire_format_ready_.store(true);
const int pointer_width = int pointer_width =
self->logical_width_ > 0 ? self->logical_width_ : self->frame_width_; self->logical_width_ > 0 ? self->logical_width_ : self->frame_width_;
const int pointer_height = self->logical_height_ > 0 int pointer_height = self->logical_height_ > 0 ? self->logical_height_
? self->logical_height_
: self->frame_height_; : self->frame_height_;
double observed_scale_x = pointer_width > 0
? static_cast<double>(self->frame_width_) /
static_cast<double>(pointer_width)
: 1.0;
double observed_scale_y = pointer_height > 0
? static_cast<double>(self->frame_height_) /
static_cast<double>(pointer_height)
: 1.0;
double snapped_scale = 1.0;
bool derived_pointer_space = false;
if (!self->portal_has_logical_size_ && self->portal_stream_width_ > 0 &&
self->portal_stream_height_ > 0 && self->frame_width_ > 0 &&
self->frame_height_ > 0) {
const double raw_scale_x =
static_cast<double>(self->frame_width_) /
static_cast<double>(self->portal_stream_width_);
const double raw_scale_y =
static_cast<double>(self->frame_height_) /
static_cast<double>(self->portal_stream_height_);
const double average_scale = (raw_scale_x + raw_scale_y) * 0.5;
snapped_scale = SnapLikelyFractionalScale(average_scale);
const bool scales_are_consistent =
std::abs(raw_scale_x - raw_scale_y) <= 0.05;
const bool scale_was_snapped =
std::abs(snapped_scale - average_scale) <= 0.08;
if (scales_are_consistent && scale_was_snapped &&
snapped_scale > 1.05) {
pointer_width =
std::max(1, static_cast<int>(std::floor(
static_cast<double>(self->portal_stream_width_) *
snapped_scale +
1e-6)));
pointer_height =
std::max(1, static_cast<int>(std::floor(
static_cast<double>(self->portal_stream_height_) *
snapped_scale +
1e-6)));
observed_scale_x = pointer_width > 0
? static_cast<double>(self->frame_width_) /
static_cast<double>(pointer_width)
: 1.0;
observed_scale_y = pointer_height > 0
? static_cast<double>(self->frame_height_) /
static_cast<double>(pointer_height)
: 1.0;
derived_pointer_space = true;
}
}
self->UpdateDisplayGeometry(pointer_width, pointer_height); self->UpdateDisplayGeometry(pointer_width, pointer_height);
if (derived_pointer_space) {
LOG_INFO( LOG_INFO(
"PipeWire video format: {}, {}x{} stride={} (pointer space {}x{})", "PipeWire video format: {}, {}x{} stride={} (pointer space {}x{}, "
PipeWireFormatName(self->spa_video_format_), "derived from portal stream {}x{} with compositor scale {:.4f}, "
self->frame_width_, self->frame_height_, self->frame_stride_, "effective scale {:.4f}x{:.4f})",
pointer_width, pointer_height); PipeWireFormatName(self->spa_video_format_), self->frame_width_,
self->frame_height_, self->frame_stride_, pointer_width,
pointer_height, self->portal_stream_width_,
self->portal_stream_height_, snapped_scale, observed_scale_x,
observed_scale_y);
} else {
LOG_INFO(
"PipeWire video format: {}, {}x{} stride={} (pointer space {}x{}, "
"scale {:.4f}x{:.4f})",
PipeWireFormatName(self->spa_video_format_), self->frame_width_,
self->frame_height_, self->frame_stride_, pointer_width,
pointer_height, observed_scale_x, observed_scale_y);
}
}; };
events.process = [](void* userdata) { events.process = [](void* userdata) {
auto* self = static_cast<ScreenCapturerWayland*>(userdata); auto* self = static_cast<ScreenCapturerWayland*>(userdata);
@@ -392,7 +467,8 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
const spa_pod* params[8]; const spa_pod* params[8];
int param_count = 0; int param_count = 0;
const spa_rectangle fixed_size{ const spa_rectangle fixed_size{
static_cast<uint32_t>(logical_width_ > 0 ? logical_width_ : kFallbackWidth), static_cast<uint32_t>(logical_width_ > 0 ? logical_width_
: kFallbackWidth),
static_cast<uint32_t>(logical_height_ > 0 ? logical_height_ static_cast<uint32_t>(logical_height_ > 0 ? logical_height_
: kFallbackHeight)}; : kFallbackHeight)};
const spa_rectangle min_size{1u, 1u}; const spa_rectangle min_size{1u, 1u};
@@ -463,9 +539,9 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
} }
void ScreenCapturerWayland::CleanupPipeWire() { void ScreenCapturerWayland::CleanupPipeWire() {
const bool need_lock = pw_thread_loop_ && const bool need_lock =
(pw_stream_ != nullptr || pw_core_ != nullptr || pw_thread_loop_ &&
pw_context_ != nullptr); (pw_stream_ != nullptr || pw_core_ != nullptr || pw_context_ != nullptr);
if (need_lock) { if (need_lock) {
pw_thread_loop_lock(pw_thread_loop_); pw_thread_loop_lock(pw_thread_loop_);
} }
@@ -584,8 +660,8 @@ void ScreenCapturerWayland::HandlePipeWireBuffer() {
uv_plane_.resize(uv_size); uv_plane_.resize(uv_size);
} }
libyuv::ARGBToNV12(src, stride, y_plane_.data(), even_width, libyuv::ARGBToNV12(src, stride, y_plane_.data(), even_width, uv_plane_.data(),
uv_plane_.data(), even_width, even_width, even_height); even_width, even_width, even_height);
std::vector<uint8_t> nv12; std::vector<uint8_t> nv12;
nv12.reserve(y_plane_.size() + uv_plane_.size()); nv12.reserve(y_plane_.size() + uv_plane_.size());

View File

@@ -1,15 +1,15 @@
#include "screen_capturer_wayland.h" #include "screen_capturer_wayland.h"
#include "screen_capturer_wayland_build.h" #include "screen_capturer_wayland_build.h"
#include "wayland_portal_shared.h" #include "wayland_portal_shared.h"
#if CROSSDESK_WAYLAND_BUILD_ENABLED #if CROSSDESK_WAYLAND_BUILD_ENABLED
#include <unistd.h>
#include <chrono> #include <chrono>
#include <cstring> #include <cstring>
#include <functional> #include <functional>
#include <string> #include <string>
#include <unistd.h>
#include "rd_log.h" #include "rd_log.h"
@@ -149,8 +149,8 @@ std::string BuildSessionHandleFromRequestPath(
return ""; return "";
} }
const std::string sender = request_path.substr(sender_start, const std::string sender =
token_sep - sender_start); request_path.substr(sender_start, token_sep - sender_start);
if (sender.empty()) { if (sender.empty()) {
return ""; return "";
} }
@@ -284,8 +284,7 @@ bool ExtractPortalResponse(DBusMessage* message, uint32_t* response_code,
bool SendPortalRequestAndHandleResponse( bool SendPortalRequestAndHandleResponse(
DBusConnection* connection, const char* interface_name, DBusConnection* connection, const char* interface_name,
const char* method_name, const char* method_name, const char* action_name,
const char* action_name,
const std::function<bool(DBusMessage*)>& append_message_args, const std::function<bool(DBusMessage*)>& append_message_args,
const std::atomic<bool>& running, const std::atomic<bool>& running,
const std::function<bool(uint32_t, DBusMessageIter*)>& handle_results, const std::function<bool(uint32_t, DBusMessageIter*)>& handle_results,
@@ -295,9 +294,8 @@ bool SendPortalRequestAndHandleResponse(
return false; return false;
} }
DBusMessage* message = DBusMessage* message = dbus_message_new_method_call(
dbus_message_new_method_call(kPortalBusName, kPortalObjectPath, kPortalBusName, kPortalObjectPath, interface_name, method_name);
interface_name, method_name);
if (!message) { if (!message) {
LOG_ERROR("Failed to allocate {} message", method_name); LOG_ERROR("Failed to allocate {} message", method_name);
return false; return false;
@@ -311,8 +309,8 @@ bool SendPortalRequestAndHandleResponse(
DBusError error; DBusError error;
dbus_error_init(&error); dbus_error_init(&error);
DBusMessage* reply = DBusMessage* reply = dbus_connection_send_with_reply_and_block(
dbus_connection_send_with_reply_and_block(connection, message, -1, &error); connection, message, -1, &error);
dbus_message_unref(message); dbus_message_unref(message);
if (!reply) { if (!reply) {
LogDbusError(action_name ? action_name : method_name, &error); LogDbusError(action_name ? action_name : method_name, &error);
@@ -365,8 +363,8 @@ bool ScreenCapturerWayland::CheckPortalAvailability() const {
return false; return false;
} }
const dbus_bool_t has_owner = dbus_bus_name_has_owner( const dbus_bool_t has_owner =
connection, kPortalBusName, &error); dbus_bus_name_has_owner(connection, kPortalBusName, &error);
if (dbus_error_is_set(&error)) { if (dbus_error_is_set(&error)) {
LogDbusError("dbus_bus_name_has_owner", &error); LogDbusError("dbus_bus_name_has_owner", &error);
dbus_error_free(&error); dbus_error_free(&error);
@@ -415,7 +413,8 @@ bool ScreenCapturerWayland::CreatePortalSession() {
&options); &options);
AppendDictEntryString(&options, "session_handle_token", AppendDictEntryString(&options, "session_handle_token",
session_handle_token); session_handle_token);
AppendDictEntryString(&options, "handle_token", MakeToken("crossdesk_req")); AppendDictEntryString(&options, "handle_token",
MakeToken("crossdesk_req"));
dbus_message_iter_close_container(&iter, &options); dbus_message_iter_close_container(&iter, &options);
return true; return true;
}, },
@@ -459,8 +458,8 @@ bool ScreenCapturerWayland::CreatePortalSession() {
} }
if (session_handle_.empty()) { if (session_handle_.empty()) {
const std::string fallback_handle = BuildSessionHandleFromRequestPath( const std::string fallback_handle =
request_path, session_handle_token); BuildSessionHandleFromRequestPath(request_path, session_handle_token);
if (!fallback_handle.empty()) { if (!fallback_handle.empty()) {
LOG_WARN( LOG_WARN(
"CreateSession response missing session_handle, using derived handle " "CreateSession response missing session_handle, using derived handle "
@@ -505,7 +504,8 @@ bool ScreenCapturerWayland::SelectPortalSource() {
dbus_message_iter_close_container(&iter, &options); dbus_message_iter_close_container(&iter, &options);
return true; return true;
}, },
running_, [](uint32_t response_code, DBusMessageIter*) { running_,
[](uint32_t response_code, DBusMessageIter*) {
if (response_code != 0) { if (response_code != 0) {
LOG_ERROR("SelectSources was denied or malformed, response={}", LOG_ERROR("SelectSources was denied or malformed, response={}",
response_code); response_code);
@@ -538,7 +538,8 @@ bool ScreenCapturerWayland::SelectPortalDevices() {
dbus_message_iter_close_container(&iter, &options); dbus_message_iter_close_container(&iter, &options);
return true; return true;
}, },
running_, [](uint32_t response_code, DBusMessageIter*) { running_,
[](uint32_t response_code, DBusMessageIter*) {
if (response_code != 0) { if (response_code != 0) {
LOG_ERROR("SelectDevices was denied or malformed, response={}", LOG_ERROR("SelectDevices was denied or malformed, response={}",
response_code); response_code);
@@ -567,14 +568,16 @@ bool ScreenCapturerWayland::StartPortalSession() {
dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &parent_window); dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &parent_window);
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}",
&options); &options);
AppendDictEntryString(&options, "handle_token", MakeToken("crossdesk_req")); AppendDictEntryString(&options, "handle_token",
MakeToken("crossdesk_req"));
dbus_message_iter_close_container(&iter, &options); dbus_message_iter_close_container(&iter, &options);
return true; return true;
}, },
running_, running_,
[&](uint32_t response_code, DBusMessageIter* results) { [&](uint32_t response_code, DBusMessageIter* results) {
if (response_code != 0) { if (response_code != 0) {
LOG_ERROR("Start was denied or malformed, response={}", response_code); LOG_ERROR("Start was denied or malformed, response={}",
response_code);
return false; return false;
} }
@@ -602,16 +605,19 @@ bool ScreenCapturerWayland::StartPortalSession() {
DBusMessageIter streams; DBusMessageIter streams;
dbus_message_iter_recurse(&variant, &streams); dbus_message_iter_recurse(&variant, &streams);
if (dbus_message_iter_get_arg_type(&streams) == DBUS_TYPE_STRUCT) { if (dbus_message_iter_get_arg_type(&streams) ==
DBUS_TYPE_STRUCT) {
DBusMessageIter stream; DBusMessageIter stream;
dbus_message_iter_recurse(&streams, &stream); dbus_message_iter_recurse(&streams, &stream);
if (dbus_message_iter_get_arg_type(&stream) == DBUS_TYPE_UINT32) { if (dbus_message_iter_get_arg_type(&stream) ==
DBUS_TYPE_UINT32) {
dbus_message_iter_get_basic(&stream, &pipewire_node_id_); dbus_message_iter_get_basic(&stream, &pipewire_node_id_);
} }
if (dbus_message_iter_next(&stream) && if (dbus_message_iter_next(&stream) &&
dbus_message_iter_get_arg_type(&stream) == DBUS_TYPE_ARRAY) { dbus_message_iter_get_arg_type(&stream) ==
DBUS_TYPE_ARRAY) {
DBusMessageIter props; DBusMessageIter props;
int stream_width = 0; int stream_width = 0;
int stream_height = 0; int stream_height = 0;
@@ -637,7 +643,8 @@ bool ScreenCapturerWayland::StartPortalSession() {
DBusMessageIter size_iter; DBusMessageIter size_iter;
int width = 0; int width = 0;
int height = 0; int height = 0;
dbus_message_iter_recurse(&prop_variant, &size_iter); dbus_message_iter_recurse(&prop_variant,
&size_iter);
if (ReadIntLike(&size_iter, &width) && if (ReadIntLike(&size_iter, &width) &&
dbus_message_iter_next(&size_iter) && dbus_message_iter_next(&size_iter) &&
ReadIntLike(&size_iter, &height)) { ReadIntLike(&size_iter, &height)) {
@@ -665,6 +672,11 @@ bool ScreenCapturerWayland::StartPortalSession() {
stream_width, stream_height, logical_width, stream_width, stream_height, logical_width,
logical_height, picked_width, picked_height); logical_height, picked_width, picked_height);
portal_stream_width_ = stream_width;
portal_stream_height_ = stream_height;
portal_has_logical_size_ =
logical_width > 0 && logical_height > 0;
if (logical_width > 0 && logical_height > 0) { if (logical_width > 0 && logical_height > 0) {
logical_width_ = logical_width; logical_width_ = logical_width;
logical_height_ = logical_height; logical_height_ = logical_height;
@@ -682,8 +694,7 @@ bool ScreenCapturerWayland::StartPortalSession() {
dbus_message_iter_next(&dict); dbus_message_iter_next(&dict);
} }
pointer_granted_ = pointer_granted_ = (granted_devices & kRemoteDesktopDevicePointer) != 0;
(granted_devices & kRemoteDesktopDevicePointer) != 0;
return true; return true;
}); });
if (!ok) { if (!ok) {
@@ -699,8 +710,8 @@ bool ScreenCapturerWayland::StartPortalSession() {
return false; return false;
} }
shared_session_registered_ = PublishSharedWaylandPortalSession( shared_session_registered_ =
SharedWaylandPortalSessionInfo{ PublishSharedWaylandPortalSession(SharedWaylandPortalSessionInfo{
dbus_connection_, session_handle_, pipewire_node_id_, logical_width_, dbus_connection_, session_handle_, pipewire_node_id_, logical_width_,
logical_height_, pointer_granted_}); logical_height_, pointer_granted_});
if (!shared_session_registered_) { if (!shared_session_registered_) {
@@ -728,16 +739,14 @@ bool ScreenCapturerWayland::OpenPipeWireRemote() {
DBusMessageIter options; DBusMessageIter options;
const char* session_handle = session_handle_.c_str(); const char* session_handle = session_handle_.c_str();
dbus_message_iter_init_append(message, &iter); dbus_message_iter_init_append(message, &iter);
dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &session_handle);
&session_handle);
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &options); dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &options);
dbus_message_iter_close_container(&iter, &options); dbus_message_iter_close_container(&iter, &options);
DBusError error; DBusError error;
dbus_error_init(&error); dbus_error_init(&error);
DBusMessage* reply = DBusMessage* reply = dbus_connection_send_with_reply_and_block(
dbus_connection_send_with_reply_and_block(dbus_connection_, message, -1, dbus_connection_, message, -1, &error);
&error);
dbus_message_unref(message); dbus_message_unref(message);
if (!reply) { if (!reply) {
LogDbusError("OpenPipeWireRemote", &error); LogDbusError("OpenPipeWireRemote", &error);
@@ -792,9 +801,8 @@ void ScreenCapturerWayland::ClosePortalSession() {
ReleaseSharedWaylandPortalSession(&close_connection, &close_session_handle); ReleaseSharedWaylandPortalSession(&close_connection, &close_session_handle);
shared_session_registered_ = false; shared_session_registered_ = false;
if (close_connection) { if (close_connection) {
CloseWaylandPortalSessionAndConnection(close_connection, CloseWaylandPortalSessionAndConnection(
close_session_handle, close_connection, close_session_handle, "Session.Close");
"Session.Close");
} }
dbus_connection_ = nullptr; dbus_connection_ = nullptr;
} else if (dbus_connection_ && !session_handle_.empty()) { } else if (dbus_connection_ && !session_handle_.empty()) {
@@ -805,9 +813,9 @@ void ScreenCapturerWayland::ClosePortalSession() {
session_handle_.clear(); session_handle_.clear();
pipewire_node_id_ = 0; pipewire_node_id_ = 0;
UpdateDisplayGeometry(logical_width_ > 0 ? logical_width_ : kFallbackWidth, UpdateDisplayGeometry(
logical_height_ > 0 ? logical_height_ logical_width_ > 0 ? logical_width_ : kFallbackWidth,
: kFallbackHeight); logical_height_ > 0 ? logical_height_ : kFallbackHeight);
pointer_granted_ = false; pointer_granted_ = false;
} }