From 5b5957d84f98d1c5c4c455423e6b62f2db3f0437 Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 12:47:46 +0800 Subject: [PATCH 01/15] fix(rdp): guard optional native exports and define WIN32_LEAN_AND_MEAN for CxRdpBridge --- Services/RdpBridgeClient.cs | 60 ++++++++++++++++++++++------- native/CxRdpBridge/cxrdp_bridge.cpp | 6 +++ 2 files changed, 52 insertions(+), 14 deletions(-) diff --git a/Services/RdpBridgeClient.cs b/Services/RdpBridgeClient.cs index df924ce..2350184 100644 --- a/Services/RdpBridgeClient.cs +++ b/Services/RdpBridgeClient.cs @@ -239,8 +239,11 @@ public void Connect( if (nativeApiVersion >= GfxApiVersion && (nativeCapabilities & GfxCapability) != 0) { var gfxRequested = GraphicsPipelineForcedOn || session.RdpGraphicsPipelineEnabled; - var gfxResult = NativeMethods.cxrdp_set_graphics_pipeline(_handle, gfxRequested ? 1 : 0); - DebugLog($"graphics pipeline requested={gfxRequested} session={session.RdpGraphicsPipelineEnabled} env={GraphicsPipelineForcedOn} result={gfxResult}"); + TryInvokeOptionalNative("cxrdp_set_graphics_pipeline", () => + { + var gfxResult = NativeMethods.cxrdp_set_graphics_pipeline(_handle, gfxRequested ? 1 : 0); + DebugLog($"graphics pipeline requested={gfxRequested} session={session.RdpGraphicsPipelineEnabled} env={GraphicsPipelineForcedOn} result={gfxResult}"); + }); } else { @@ -258,8 +261,14 @@ public void Connect( var useFrameMarkers = _frameMode != RdpFramePresentationMode.Legacy; if (_frameMarkerSupported) { - var markerResult = NativeMethods.cxrdp_set_frame_marker_enabled(_handle, useFrameMarkers ? 1 : 0); - DebugLog($"frame markers enabled={useFrameMarkers} result={markerResult}"); + if (!TryInvokeOptionalNative("cxrdp_set_frame_marker_enabled", () => + { + var markerResult = NativeMethods.cxrdp_set_frame_marker_enabled(_handle, useFrameMarkers ? 1 : 0); + DebugLog($"frame markers enabled={useFrameMarkers} result={markerResult}"); + })) + { + _frameMarkerSupported = false; + } } else if (useFrameMarkers) { @@ -273,16 +282,22 @@ public void Connect( var cachedProfile = RdpSecurityProfileCache.Get(_profileCacheHost, _profileCachePort); if (!string.IsNullOrEmpty(cachedProfile)) { - var profileResult = NativeMethods.cxrdp_set_security_profile(_handle, cachedProfile); - DebugLog($"security profile hint={cachedProfile} result={profileResult}"); + TryInvokeOptionalNative("cxrdp_set_security_profile", () => + { + var profileResult = NativeMethods.cxrdp_set_security_profile(_handle, cachedProfile); + DebugLog($"security profile hint={cachedProfile} result={profileResult}"); + }); } // Environment override CXSHELL_RDP_CLIPBOARD_CHANNEL=0 still wins // inside the bridge, so it remains a global troubleshooting switch. - var clipboardResult = NativeMethods.cxrdp_set_clipboard_channel( - _handle, - session.RdpClipboardEnabled ? 1 : 0); - DebugLog($"clipboard channel requested={session.RdpClipboardEnabled} result={clipboardResult}"); + TryInvokeOptionalNative("cxrdp_set_clipboard_channel", () => + { + var clipboardResult = NativeMethods.cxrdp_set_clipboard_channel( + _handle, + session.RdpClipboardEnabled ? 1 : 0); + DebugLog($"clipboard channel requested={session.RdpClipboardEnabled} result={clipboardResult}"); + }); } else { @@ -292,10 +307,13 @@ public void Connect( if (nativeApiVersion >= PerformanceFlagsApiVersion && (nativeCapabilities & PerformanceFlagsCapability) != 0) { - var wallpaperResult = NativeMethods.cxrdp_set_disable_wallpaper( - _handle, - session.RdpDisableWallpaper ? 1 : 0); - DebugLog($"disable wallpaper requested={session.RdpDisableWallpaper} result={wallpaperResult}"); + TryInvokeOptionalNative("cxrdp_set_disable_wallpaper", () => + { + var wallpaperResult = NativeMethods.cxrdp_set_disable_wallpaper( + _handle, + session.RdpDisableWallpaper ? 1 : 0); + DebugLog($"disable wallpaper requested={session.RdpDisableWallpaper} result={wallpaperResult}"); + }); } else { @@ -1165,6 +1183,20 @@ private void OnStatus(IntPtr userData, IntPtr message) StatusChanged?.Invoke(text); } + private static bool TryInvokeOptionalNative(string exportName, Action action) + { + try + { + action(); + return true; + } + catch (EntryPointNotFoundException) + { + DebugLog($"native bridge export missing: {exportName}; falling back."); + return false; + } + } + private void OnDisconnected(IntPtr userData) { DebugLog("disconnected callback"); diff --git a/native/CxRdpBridge/cxrdp_bridge.cpp b/native/CxRdpBridge/cxrdp_bridge.cpp index 15547ed..b13770c 100644 --- a/native/CxRdpBridge/cxrdp_bridge.cpp +++ b/native/CxRdpBridge/cxrdp_bridge.cpp @@ -16,6 +16,12 @@ #include #if defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif #include #include #else From 2475445d7d74d1e88b712401e6660316ac3524e7 Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 15:32:06 +0800 Subject: [PATCH 02/15] perf(rdp): enable FreeRDP UDP multitransport for low-latency sessions Added: - Enabled FreeRDP Multitransport (UDP-FECR and UDP-FECL) in CxRdpBridge. Changed: - Configured FreeRDP_SupportMultitransport=TRUE and FreeRDP_MultitransportFlags in connection_thread before handshake. Fixed: - Reduced head-of-line blocking and frame/input latency over high-latency or lossy WAN links. Technical Approach: - Advertise TRANSPORT_TYPE_UDP_FECR | TRANSPORT_TYPE_UDP_FECL during RDP negotiation in native/CxRdpBridge/cxrdp_bridge.cpp. Servers or firewalls that disallow UDP automatically fall back to pure TCP during handshake without breaking compatibility. --- native/CxRdpBridge/cxrdp_bridge.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/native/CxRdpBridge/cxrdp_bridge.cpp b/native/CxRdpBridge/cxrdp_bridge.cpp index b13770c..d933136 100644 --- a/native/CxRdpBridge/cxrdp_bridge.cpp +++ b/native/CxRdpBridge/cxrdp_bridge.cpp @@ -2751,6 +2751,12 @@ void connection_thread(CxRdpSession* session) freerdp_settings_set_uint32(settings, FreeRDP_TcpConnectTimeout, 10000); freerdp_settings_set_uint32(settings, FreeRDP_TcpAckTimeout, 5000); + freerdp_settings_set_bool(settings, FreeRDP_SupportMultitransport, TRUE); + freerdp_settings_set_uint32( + settings, + FreeRDP_MultitransportFlags, + TRANSPORT_TYPE_UDP_FECR | TRANSPORT_TYPE_UDP_FECL); + freerdp_settings_set_bool(settings, FreeRDP_NegotiateSecurityLayer, profile->negotiate ? TRUE : FALSE); freerdp_settings_set_bool(settings, FreeRDP_NlaSecurity, profile->nla ? TRUE : FALSE); freerdp_settings_set_bool(settings, FreeRDP_TlsSecurity, profile->tls ? TRUE : FALSE); From d70bf6fed0e1df162f5ca7764deff41aa775a1ea Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 15:32:36 +0800 Subject: [PATCH 03/15] feat(rdp): add manual security mode selector in session editor Added: - Per-session RdpSecurityMode setting (Auto, Negotiate, NLA, TLS, RDP) in SessionInfo and SessionEditDialog with full zh-CN/en-US localization. Changed: - RdpBridgeClient.Connect now prioritizes an explicit RdpSecurityMode over the host-level RdpSecurityProfileCache hint when configured. Fixed: - Allows locking specific legacy or hardened RDP hosts to a known-good security protocol without waiting for fallback probing. Technical Approach: - Reuse the existing cxrdp_set_security_profile (API 7) native export without bumping the bridge ABI; Auto mode continues to delegate to RdpSecurityProfileCache. --- Models/SessionInfo.cs | 2 ++ Services/RdpBridgeClient.cs | 26 ++++++++++++++++++++++---- ViewModels/SessionEditViewModel.cs | 11 +++++++++++ ViewModels/SessionTreeViewModel.cs | 2 ++ Views/SessionEditDialog.axaml | 13 ++++++++++++- Views/SessionEditDialog.axaml.cs | 2 ++ 6 files changed, 51 insertions(+), 5 deletions(-) diff --git a/Models/SessionInfo.cs b/Models/SessionInfo.cs index 9fdd497..0feb7e4 100644 --- a/Models/SessionInfo.cs +++ b/Models/SessionInfo.cs @@ -597,6 +597,8 @@ public int SshMonitorRefreshIntervalSeconds /// Frame presentation strategy: Auto, Coalesce, FrameMarker or Legacy. public string RdpFrameStrategy { get; set; } = "Auto"; public string RdpColorQuality { get; set; } = "32"; + /// Preferred RDP security mode: Auto, Negotiate, NLA, TLS or RDP. + public string RdpSecurityMode { get; set; } = "Auto"; public bool RdpApplyKeyCombinations { get; set; } = true; public bool RdpClipboardEnabled { get; set; } = true; /// Send PERF_DISABLE_WALLPAPER so the server skips the desktop wallpaper. diff --git a/Services/RdpBridgeClient.cs b/Services/RdpBridgeClient.cs index 2350184..edaf611 100644 --- a/Services/RdpBridgeClient.cs +++ b/Services/RdpBridgeClient.cs @@ -279,13 +279,16 @@ public void Connect( if (nativeApiVersion >= FastConnectApiVersion && (nativeCapabilities & FastConnectCapability) != 0) { - var cachedProfile = RdpSecurityProfileCache.Get(_profileCacheHost, _profileCachePort); - if (!string.IsNullOrEmpty(cachedProfile)) + var explicitProfile = NormalizeExplicitSecurityProfile(session.RdpSecurityMode); + var targetProfile = !string.IsNullOrEmpty(explicitProfile) + ? explicitProfile + : RdpSecurityProfileCache.Get(_profileCacheHost, _profileCachePort); + if (!string.IsNullOrEmpty(targetProfile)) { TryInvokeOptionalNative("cxrdp_set_security_profile", () => { - var profileResult = NativeMethods.cxrdp_set_security_profile(_handle, cachedProfile); - DebugLog($"security profile hint={cachedProfile} result={profileResult}"); + var profileResult = NativeMethods.cxrdp_set_security_profile(_handle, targetProfile); + DebugLog($"security profile hint={targetProfile} explicit={!string.IsNullOrEmpty(explicitProfile)} result={profileResult}"); }); } @@ -1197,6 +1200,21 @@ private static bool TryInvokeOptionalNative(string exportName, Action action) } } + internal static string NormalizeExplicitSecurityProfile(string? configuredMode) + { + if (string.IsNullOrWhiteSpace(configuredMode)) + return string.Empty; + + return configuredMode.Trim().ToLowerInvariant() switch + { + "negotiate" => "negotiate", + "nla" => "nla", + "tls" => "tls", + "rdp" => "rdp", + _ => string.Empty + }; + } + private void OnDisconnected(IntPtr userData) { DebugLog("disconnected callback"); diff --git a/ViewModels/SessionEditViewModel.cs b/ViewModels/SessionEditViewModel.cs index 7412d55..2f04f4c 100644 --- a/ViewModels/SessionEditViewModel.cs +++ b/ViewModels/SessionEditViewModel.cs @@ -330,6 +330,7 @@ public readonly record struct AppearanceColorPalette( [ObservableProperty] private string _rdpDpiPolicy = "FollowLocal"; [ObservableProperty] private string _rdpFrameStrategy = "Auto"; [ObservableProperty] private string _rdpColorQuality = "32"; + [ObservableProperty] private string _rdpSecurityMode = "Auto"; [ObservableProperty] private bool _rdpApplyKeyCombinations = true; [ObservableProperty] private bool _rdpClipboardEnabled = true; [ObservableProperty] private bool _rdpDisableWallpaper = true; @@ -1036,6 +1037,14 @@ public bool IsNumericKeypadModeForceNormal new SelectOption { Header = "True Color (24 bit)", Content = "24" }, new SelectOption { Header = "Highest Quality (32 bit)", Content = "32" } ]; + public ObservableCollection RdpSecurityModeOptions { get; } = + [ + new SelectOption { Header = "Auto (Prefer cached / Negotiate)", Content = "Auto" }, + new SelectOption { Header = "Negotiate (Recommended)", Content = "Negotiate" }, + new SelectOption { Header = "NLA (CredSSP)", Content = "NLA" }, + new SelectOption { Header = "TLS", Content = "TLS" }, + new SelectOption { Header = "Standard RDP", Content = "RDP" } + ]; public ObservableCollection RdpAudioModeOptions { get; } = [ new SelectOption { Header = "Play on this computer", Content = "PlayLocal" }, @@ -1534,6 +1543,7 @@ public SessionEditViewModel(SessionInfo session) : "FollowLocal"; RdpFrameStrategy = RdpFramePresentationModes.Normalize(session.RdpFrameStrategy); RdpColorQuality = string.IsNullOrWhiteSpace(session.RdpColorQuality) ? "32" : session.RdpColorQuality; + RdpSecurityMode = string.IsNullOrWhiteSpace(session.RdpSecurityMode) ? "Auto" : session.RdpSecurityMode; RdpApplyKeyCombinations = session.RdpApplyKeyCombinations; RdpClipboardEnabled = session.RdpClipboardEnabled; RdpDisableWallpaper = session.RdpDisableWallpaper; @@ -1844,6 +1854,7 @@ private void Save() : "FollowLocal"; session.RdpFrameStrategy = RdpFramePresentationModes.Normalize(RdpFrameStrategy); session.RdpColorQuality = RdpColorQuality; + session.RdpSecurityMode = string.IsNullOrWhiteSpace(RdpSecurityMode) ? "Auto" : RdpSecurityMode; session.RdpApplyKeyCombinations = RdpApplyKeyCombinations; session.RdpClipboardEnabled = RdpClipboardEnabled; session.RdpDisableWallpaper = RdpDisableWallpaper; diff --git a/ViewModels/SessionTreeViewModel.cs b/ViewModels/SessionTreeViewModel.cs index 9427066..0cacb02 100644 --- a/ViewModels/SessionTreeViewModel.cs +++ b/ViewModels/SessionTreeViewModel.cs @@ -259,6 +259,7 @@ public static void CopySessionValues(SessionInfo target, SessionInfo source) target.RdpDpiPolicy = source.RdpDpiPolicy; target.RdpFrameStrategy = source.RdpFrameStrategy; target.RdpColorQuality = source.RdpColorQuality; + target.RdpSecurityMode = source.RdpSecurityMode; target.RdpApplyKeyCombinations = source.RdpApplyKeyCombinations; target.RdpClipboardEnabled = source.RdpClipboardEnabled; target.RdpDisableWallpaper = source.RdpDisableWallpaper; @@ -1180,6 +1181,7 @@ private static SessionInfo CloneSession(SessionInfo source, string name) RdpDpiPolicy = source.RdpDpiPolicy, RdpFrameStrategy = source.RdpFrameStrategy, RdpColorQuality = source.RdpColorQuality, + RdpSecurityMode = source.RdpSecurityMode, RdpApplyKeyCombinations = source.RdpApplyKeyCombinations, RdpClipboardEnabled = source.RdpClipboardEnabled, RdpDisableWallpaper = source.RdpDisableWallpaper, diff --git a/Views/SessionEditDialog.axaml b/Views/SessionEditDialog.axaml index 23fed19..337e97e 100644 --- a/Views/SessionEditDialog.axaml +++ b/Views/SessionEditDialog.axaml @@ -1590,7 +1590,7 @@ BorderThickness="1" CornerRadius="4" Padding="18"> - + + + diff --git a/Views/SessionEditDialog.axaml.cs b/Views/SessionEditDialog.axaml.cs index 939b8d7..afec1d1 100644 --- a/Views/SessionEditDialog.axaml.cs +++ b/Views/SessionEditDialog.axaml.cs @@ -451,6 +451,7 @@ private bool SaveCurrentSession() vm.RdpDpiPolicy = GetSelectedOptionText(RdpDpiPolicySelect, vm.RdpDpiPolicy); vm.RdpFrameStrategy = GetSelectedOptionText(RdpFrameStrategySelect, vm.RdpFrameStrategy); vm.RdpColorQuality = GetSelectedOptionText(RdpColorQualitySelect, vm.RdpColorQuality); + vm.RdpSecurityMode = GetSelectedOptionText(RdpSecurityModeSelect, vm.RdpSecurityMode); vm.RdpAudioMode = GetSelectedOptionText(RdpAudioModeSelect, vm.RdpAudioMode); vm.VncDisplayMode = GetSelectedOptionText(VncDisplayModeSelect, vm.VncDisplayMode); vm.VncResizeMode = GetSelectedOptionText(VncResizeModeSelect, vm.VncResizeMode); @@ -2763,6 +2764,7 @@ private void SetSelectedRdpOptions() SelectOption(RdpDpiPolicySelect, vm.RdpDpiPolicy); SelectOption(RdpFrameStrategySelect, vm.RdpFrameStrategy); SelectOption(RdpColorQualitySelect, vm.RdpColorQuality); + SelectOption(RdpSecurityModeSelect, vm.RdpSecurityMode); SelectOption(RdpAudioModeSelect, vm.RdpAudioMode); } From 7d2222c9bba77b3ebced89babe13ed9e2e75783f Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 15:33:01 +0800 Subject: [PATCH 04/15] feat(rdp): sync CapsLock/NumLock/ScrollLock state with remote session Added: - Native ABI v12 export cxrdp_sync_lock_keys and CX_RDP_CAPABILITY_SYNC_LOCK_KEYS capability bit. - Per-session RdpSyncLockKeys toggle (default true) in SessionInfo and SessionEditDialog. Changed: - RdpView reads Windows lock-key states via GetKeyState and synchronizes them to the remote host upon connection. Fixed: - Eliminates CapsLock/NumLock state mismatch between local and remote desktops when typing passwords or text. Technical Approach: - Invoke freerdp_input_send_synchronize_event in native/CxRdpBridge/cxrdp_bridge.cpp with standard RDP sync flags (ScrollLock=0x01, NumLock=0x02, CapsLock=0x04), guarded by native API/capability checks in RdpBridgeClient. --- Models/SessionInfo.cs | 1 + Services/RdpBridgeClient.cs | 14 ++++++++++++++ ViewModels/RdpViewModel.cs | 6 ++++++ ViewModels/SessionEditViewModel.cs | 3 +++ ViewModels/SessionTreeViewModel.cs | 2 ++ Views/RdpView.axaml.cs | 21 +++++++++++++++++++++ Views/SessionEditDialog.axaml | 13 ++++++++----- native/CxRdpBridge/cxrdp_bridge.cpp | 13 ++++++++++++- native/CxRdpBridge/cxrdp_bridge.h | 5 ++++- 9 files changed, 71 insertions(+), 7 deletions(-) diff --git a/Models/SessionInfo.cs b/Models/SessionInfo.cs index 0feb7e4..4e0f3a2 100644 --- a/Models/SessionInfo.cs +++ b/Models/SessionInfo.cs @@ -600,6 +600,7 @@ public int SshMonitorRefreshIntervalSeconds /// Preferred RDP security mode: Auto, Negotiate, NLA, TLS or RDP. public string RdpSecurityMode { get; set; } = "Auto"; public bool RdpApplyKeyCombinations { get; set; } = true; + public bool RdpSyncLockKeys { get; set; } = true; public bool RdpClipboardEnabled { get; set; } = true; /// Send PERF_DISABLE_WALLPAPER so the server skips the desktop wallpaper. public bool RdpDisableWallpaper { get; set; } = true; diff --git a/Services/RdpBridgeClient.cs b/Services/RdpBridgeClient.cs index edaf611..170b8c8 100644 --- a/Services/RdpBridgeClient.cs +++ b/Services/RdpBridgeClient.cs @@ -72,6 +72,8 @@ public sealed class RdpBridgeClient : IDisposable private const uint DirtyRectCapability = 0x00000400; private const uint GfxApiVersion = 11; private const uint GfxCapability = 0x00000800; + private const uint SyncLockKeysApiVersion = 12; + private const uint SyncLockKeysCapability = 0x00001000; private static readonly object DebugLogLock = new(); private static readonly object NativeLoadFailureLock = new(); private static readonly bool DetailedDebugLogEnabled = IsEnvironmentFlagEnabled("CXSHELL_RDP_DEBUG_LOG"); @@ -95,6 +97,7 @@ public sealed class RdpBridgeClient : IDisposable private readonly RdpFrameComposer _frameComposer = new(enabled: FrameCoalescingEnabled, useCoverage: FrameCoverageEnabled); private RdpFramePresentationMode _frameMode = RdpFramePresentationMode.Auto; private bool _frameMarkerSupported; + private bool _supportsSyncLockKeys; private bool _dirtyRectSupported; private bool _gfxFrameMode; private byte[] _frameBuffer = Array.Empty(); @@ -236,6 +239,8 @@ public void Connect( _frameMarkerSupported = nativeApiVersion >= FrameMarkerApiVersion && (nativeCapabilities & FrameMarkerCapability) != 0; + _supportsSyncLockKeys = nativeApiVersion >= SyncLockKeysApiVersion && + (nativeCapabilities & SyncLockKeysCapability) != 0; if (nativeApiVersion >= GfxApiVersion && (nativeCapabilities & GfxCapability) != 0) { var gfxRequested = GraphicsPipelineForcedOn || session.RdpGraphicsPipelineEnabled; @@ -701,6 +706,12 @@ public void SendUnicodeKey(char key, bool down) NativeMethods.cxrdp_send_unicode_key(_handle, key, down ? 1 : 0); } + public void SyncLockKeys(uint flags) + { + if (_handle != IntPtr.Zero && _supportsSyncLockKeys) + NativeMethods.cxrdp_sync_lock_keys(_handle, flags); + } + /// /// Marks the session as interactive so the next presentation tick publishes /// the pending framebuffer immediately instead of waiting out a repaint @@ -1404,6 +1415,9 @@ public static extern int cxrdp_connect( [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern void cxrdp_send_unicode_key(IntPtr handle, ushort code, int down); + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] + public static extern void cxrdp_sync_lock_keys(IntPtr handle, uint flags); + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern void cxrdp_set_clipboard_text( IntPtr handle, diff --git a/ViewModels/RdpViewModel.cs b/ViewModels/RdpViewModel.cs index 9b9a654..a75d638 100644 --- a/ViewModels/RdpViewModel.cs +++ b/ViewModels/RdpViewModel.cs @@ -641,6 +641,12 @@ public void SetClipboardText(string text) _client.SetClipboardText(text); } + public void SyncLockKeys(uint flags) + { + if (IsConnected) + _client.SyncLockKeys(flags); + } + [RelayCommand] private void ToggleScaleMode() { diff --git a/ViewModels/SessionEditViewModel.cs b/ViewModels/SessionEditViewModel.cs index 2f04f4c..158ee25 100644 --- a/ViewModels/SessionEditViewModel.cs +++ b/ViewModels/SessionEditViewModel.cs @@ -332,6 +332,7 @@ public readonly record struct AppearanceColorPalette( [ObservableProperty] private string _rdpColorQuality = "32"; [ObservableProperty] private string _rdpSecurityMode = "Auto"; [ObservableProperty] private bool _rdpApplyKeyCombinations = true; + [ObservableProperty] private bool _rdpSyncLockKeys = true; [ObservableProperty] private bool _rdpClipboardEnabled = true; [ObservableProperty] private bool _rdpDisableWallpaper = true; [ObservableProperty] private bool _rdpGraphicsPipelineEnabled; @@ -1545,6 +1546,7 @@ public SessionEditViewModel(SessionInfo session) RdpColorQuality = string.IsNullOrWhiteSpace(session.RdpColorQuality) ? "32" : session.RdpColorQuality; RdpSecurityMode = string.IsNullOrWhiteSpace(session.RdpSecurityMode) ? "Auto" : session.RdpSecurityMode; RdpApplyKeyCombinations = session.RdpApplyKeyCombinations; + RdpSyncLockKeys = session.RdpSyncLockKeys; RdpClipboardEnabled = session.RdpClipboardEnabled; RdpDisableWallpaper = session.RdpDisableWallpaper; RdpGraphicsPipelineEnabled = session.RdpGraphicsPipelineEnabled; @@ -1856,6 +1858,7 @@ private void Save() session.RdpColorQuality = RdpColorQuality; session.RdpSecurityMode = string.IsNullOrWhiteSpace(RdpSecurityMode) ? "Auto" : RdpSecurityMode; session.RdpApplyKeyCombinations = RdpApplyKeyCombinations; + session.RdpSyncLockKeys = RdpSyncLockKeys; session.RdpClipboardEnabled = RdpClipboardEnabled; session.RdpDisableWallpaper = RdpDisableWallpaper; session.RdpGraphicsPipelineEnabled = RdpGraphicsPipelineEnabled; diff --git a/ViewModels/SessionTreeViewModel.cs b/ViewModels/SessionTreeViewModel.cs index 0cacb02..22ce94a 100644 --- a/ViewModels/SessionTreeViewModel.cs +++ b/ViewModels/SessionTreeViewModel.cs @@ -261,6 +261,7 @@ public static void CopySessionValues(SessionInfo target, SessionInfo source) target.RdpColorQuality = source.RdpColorQuality; target.RdpSecurityMode = source.RdpSecurityMode; target.RdpApplyKeyCombinations = source.RdpApplyKeyCombinations; + target.RdpSyncLockKeys = source.RdpSyncLockKeys; target.RdpClipboardEnabled = source.RdpClipboardEnabled; target.RdpDisableWallpaper = source.RdpDisableWallpaper; target.RdpGraphicsPipelineEnabled = source.RdpGraphicsPipelineEnabled; @@ -1183,6 +1184,7 @@ private static SessionInfo CloneSession(SessionInfo source, string name) RdpColorQuality = source.RdpColorQuality, RdpSecurityMode = source.RdpSecurityMode, RdpApplyKeyCombinations = source.RdpApplyKeyCombinations, + RdpSyncLockKeys = source.RdpSyncLockKeys, RdpClipboardEnabled = source.RdpClipboardEnabled, RdpDisableWallpaper = source.RdpDisableWallpaper, RdpGraphicsPipelineEnabled = source.RdpGraphicsPipelineEnabled, diff --git a/Views/RdpView.axaml.cs b/Views/RdpView.axaml.cs index 725c0c4..3be4a9a 100644 --- a/Views/RdpView.axaml.cs +++ b/Views/RdpView.axaml.cs @@ -107,12 +107,33 @@ private void OnViewModelPropertyChanged(object? sender, System.ComponentModel.Pr if (args.PropertyName == nameof(RdpViewModel.IsConnected)) { if (_boundVm?.IsConnected == true) + { StartScalingTimer(); + SyncLocalLockKeysToRemote(); + } else StopScalingTimer(); } } + private void SyncLocalLockKeysToRemote() + { + if (!OperatingSystem.IsWindows() || DataContext is not RdpViewModel vm || !vm.IsConnected || !vm.Session.RdpSyncLockKeys) + return; + + uint flags = 0; + if ((GetKeyState(0x91) & 1) != 0) // VK_SCROLL + flags |= 0x01; + if ((GetKeyState(0x90) & 1) != 0) // VK_NUMLOCK + flags |= 0x02; + if ((GetKeyState(0x14) & 1) != 0) // VK_CAPITAL + flags |= 0x04; + vm.SyncLockKeys(flags); + } + + [System.Runtime.InteropServices.DllImport("user32.dll")] + private static extern short GetKeyState(int nVirtKey); + private void StartScalingTimer() { if (_scalingTimer != null || !_isAttached) diff --git a/Views/SessionEditDialog.axaml b/Views/SessionEditDialog.axaml index 337e97e..d7b27e1 100644 --- a/Views/SessionEditDialog.axaml +++ b/Views/SessionEditDialog.axaml @@ -1713,11 +1713,14 @@ FontWeight="SemiBold" Foreground="{atom:SharedTokenResource ColorText}"/> - + + + + (handle); + auto* input = session && session->instance && session->instance->context ? session->instance->context->input : nullptr; + if (!session || !input || !session->connected) + return; + + freerdp_input_send_synchronize_event(input, flags); +} + CX_RDP_API void cxrdp_set_clipboard_text(void* handle, const char* text) { auto* session = static_cast(handle); diff --git a/native/CxRdpBridge/cxrdp_bridge.h b/native/CxRdpBridge/cxrdp_bridge.h index 263e406..c7ae427 100644 --- a/native/CxRdpBridge/cxrdp_bridge.h +++ b/native/CxRdpBridge/cxrdp_bridge.h @@ -21,7 +21,7 @@ typedef void (*cxrdp_status_callback)(void* user_data, const char* message); typedef void (*cxrdp_disconnect_callback)(void* user_data); typedef void (*cxrdp_clipboard_text_callback)(void* user_data, const char* text); -#define CX_RDP_BRIDGE_API_VERSION 11u +#define CX_RDP_BRIDGE_API_VERSION 12u #define CX_RDP_CAPABILITY_CLIPBOARD 0x00000001u #define CX_RDP_CAPABILITY_DRIVE_REDIRECTION 0x00000002u #define CX_RDP_CAPABILITY_AUDIO_PLAYBACK 0x00000004u @@ -50,6 +50,8 @@ typedef void (*cxrdp_clipboard_text_callback)(void* user_data, const char* text) groups surface commands between START_FRAME/END_FRAME and FreeRDP's GDI backend calls EndPaint exactly once per complete frame, just like MSTSC. */ #define CX_RDP_CAPABILITY_GFX 0x00000800u +/* The bridge can synchronize CapsLock/NumLock/ScrollLock state to the remote session. */ +#define CX_RDP_CAPABILITY_SYNC_LOCK_KEYS 0x00001000u #define CX_RDP_AUDIO_PLAY_LOCAL 0 #define CX_RDP_AUDIO_PLAY_REMOTE 1 @@ -79,6 +81,7 @@ CX_RDP_API void cxrdp_disconnect(void* handle); CX_RDP_API void cxrdp_send_pointer(void* handle, uint16_t flags, uint16_t x, uint16_t y); CX_RDP_API void cxrdp_send_key(void* handle, uint32_t key, int down); CX_RDP_API void cxrdp_send_unicode_key(void* handle, uint16_t code, int down); +CX_RDP_API void cxrdp_sync_lock_keys(void* handle, uint32_t flags); CX_RDP_API void cxrdp_set_clipboard_callback(void* handle, cxrdp_clipboard_text_callback clipboard_text_callback); CX_RDP_API void cxrdp_set_clipboard_text(void* handle, const char* text); CX_RDP_API int cxrdp_set_drive_redirection( From c3cf0aae08c85dd27938e569b4beb8e59b52f09c Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 15:33:06 +0800 Subject: [PATCH 05/15] feat(rdp): sync remote mouse pointer shape across platforms Added: - Native ABI v13 export cxrdp_set_pointer_callback and CX_RDP_CAPABILITY_POINTER_SHAPE capability bit. - Cross-platform Avalonia Cursor construction and disposal in RdpView for custom remote cursors, null cursor, and default arrow fallback. Changed: - Registered FreeRDP graphics pointer callbacks (Pointer_New, Free, Set, SetNull, SetDefault) in cx_post_connect. Fixed: - Replaces the static arrow cursor over RDP viewports with live remote pointer shapes (I-beam, resize handles, hand pointers, etc.). Technical Approach: - Decode arbitrary-bpp remote pointer masks to BGRA32 via freerdp_image_copy_from_pointer_data in CxRdpBridge, marshal pixel buffers to UI thread in RdpViewModel, and safely dispose previous WriteableBitmap/Cursor instances in RdpView. --- Services/RdpBridgeClient.cs | 36 +++++++ ViewModels/RdpViewModel.cs | 8 ++ Views/RdpView.axaml.cs | 56 +++++++++++ native/CxRdpBridge/cxrdp_bridge.cpp | 150 +++++++++++++++++++++++++++- native/CxRdpBridge/cxrdp_bridge.h | 17 +++- 5 files changed, 265 insertions(+), 2 deletions(-) diff --git a/Services/RdpBridgeClient.cs b/Services/RdpBridgeClient.cs index 170b8c8..5fd7de2 100644 --- a/Services/RdpBridgeClient.cs +++ b/Services/RdpBridgeClient.cs @@ -74,6 +74,8 @@ public sealed class RdpBridgeClient : IDisposable private const uint GfxCapability = 0x00000800; private const uint SyncLockKeysApiVersion = 12; private const uint SyncLockKeysCapability = 0x00001000; + private const uint PointerShapeApiVersion = 13; + private const uint PointerShapeCapability = 0x00002000; private static readonly object DebugLogLock = new(); private static readonly object NativeLoadFailureLock = new(); private static readonly bool DetailedDebugLogEnabled = IsEnvironmentFlagEnabled("CXSHELL_RDP_DEBUG_LOG"); @@ -93,6 +95,7 @@ public sealed class RdpBridgeClient : IDisposable private readonly StatusCallback _statusCallback; private readonly DisconnectCallback _disconnectCallback; private readonly ClipboardTextCallback _clipboardTextCallback; + private readonly PointerCallback _pointerCallback; private readonly object _frameSync = new(); private readonly RdpFrameComposer _frameComposer = new(enabled: FrameCoalescingEnabled, useCoverage: FrameCoverageEnabled); private RdpFramePresentationMode _frameMode = RdpFramePresentationMode.Auto; @@ -136,6 +139,7 @@ static RdpBridgeClient() public event Action? StatusChanged; public event Action? Disconnected; public event Action? ClipboardTextReceived; + public event Action? PointerShapeChanged; public static string DebugLogPath => Path.Combine(GetDebugLogDirectory(), "rdp-debug.log"); @@ -154,6 +158,7 @@ public RdpBridgeClient() _statusCallback = OnStatus; _disconnectCallback = OnDisconnected; _clipboardTextCallback = OnClipboardText; + _pointerCallback = OnPointer; } public void Connect( @@ -241,6 +246,11 @@ public void Connect( (nativeCapabilities & FrameMarkerCapability) != 0; _supportsSyncLockKeys = nativeApiVersion >= SyncLockKeysApiVersion && (nativeCapabilities & SyncLockKeysCapability) != 0; + if (nativeApiVersion >= PointerShapeApiVersion && + (nativeCapabilities & PointerShapeCapability) != 0) + { + NativeMethods.cxrdp_set_pointer_callback(_handle, _pointerCallback); + } if (nativeApiVersion >= GfxApiVersion && (nativeCapabilities & GfxCapability) != 0) { var gfxRequested = GraphicsPipelineForcedOn || session.RdpGraphicsPipelineEnabled; @@ -1232,6 +1242,19 @@ private void OnDisconnected(IntPtr userData) Disconnected?.Invoke(); } + private void OnPointer(IntPtr userData, int kind, int width, int height, int hotX, int hotY, IntPtr bgraPixels) + { + byte[]? copy = null; + if (kind == 2 && bgraPixels != IntPtr.Zero && width > 0 && height > 0) + { + var byteCount = checked(width * height * 4); + copy = new byte[byteCount]; + Marshal.Copy(bgraPixels, copy, 0, byteCount); + } + + PointerShapeChanged?.Invoke(kind, width, height, hotX, hotY, copy); + } + private void OnClipboardText(IntPtr userData, IntPtr text) { var value = text == IntPtr.Zero ? string.Empty : Marshal.PtrToStringUTF8(text) ?? string.Empty; @@ -1365,6 +1388,16 @@ private static uint GetNativeCapabilities() [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void ClipboardTextCallback(IntPtr userData, IntPtr text); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate void PointerCallback( + IntPtr userData, + int kind, + int width, + int height, + int hotX, + int hotY, + IntPtr bgraPixels); + private static class NativeMethods { [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] @@ -1415,6 +1448,9 @@ public static extern int cxrdp_connect( [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern void cxrdp_send_unicode_key(IntPtr handle, ushort code, int down); + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] + public static extern void cxrdp_set_pointer_callback(IntPtr handle, PointerCallback? pointerCallback); + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern void cxrdp_sync_lock_keys(IntPtr handle, uint flags); diff --git a/ViewModels/RdpViewModel.cs b/ViewModels/RdpViewModel.cs index a75d638..31c8cab 100644 --- a/ViewModels/RdpViewModel.cs +++ b/ViewModels/RdpViewModel.cs @@ -91,6 +91,7 @@ private static int ResolveConnectTimeoutSeconds() public SessionInfo Session { get; } public string? Password { get; } + public event Action? PointerShapeChanged; public double FixedScaleFactor => Math.Clamp(ScreenScalePercent, 10, 500) / 100.0; public string ScaleModeText => IsFitToWindow ? "Fit to window" @@ -105,6 +106,7 @@ public RdpViewModel(SessionInfo session, string? password) _client.FramebufferUpdated += OnFramebufferUpdated; _client.StatusChanged += message => Dispatcher.UIThread.Post(() => HandleStatus(message)); _client.ClipboardTextReceived += OnClipboardTextReceived; + _client.PointerShapeChanged += OnPointerShapeChanged; LocalizationService.Shared.LanguageChanged += OnLanguageChanged; _client.Disconnected += () => Dispatcher.UIThread.Post(() => { @@ -754,6 +756,11 @@ private void OnClipboardTextReceived(string text) Dispatcher.UIThread.Post(() => RemoteClipboardText = text); } + private void OnPointerShapeChanged(int kind, int width, int height, int hotX, int hotY, byte[]? pixels) + { + Dispatcher.UIThread.Post(() => PointerShapeChanged?.Invoke(kind, width, height, hotX, hotY, pixels)); + } + partial void OnIsConnectedChanged(bool value) { if (value) @@ -830,6 +837,7 @@ public void Dispose() CancelConnectWatchdog(); _client.FramebufferUpdated -= OnFramebufferUpdated; _client.ClipboardTextReceived -= OnClipboardTextReceived; + _client.PointerShapeChanged -= OnPointerShapeChanged; LocalizationService.Shared.LanguageChanged -= OnLanguageChanged; _client.Dispose(); _bitmapA?.Dispose(); diff --git a/Views/RdpView.axaml.cs b/Views/RdpView.axaml.cs index 3be4a9a..c425ef8 100644 --- a/Views/RdpView.axaml.cs +++ b/Views/RdpView.axaml.cs @@ -29,6 +29,8 @@ public partial class RdpView : UserControl private double _pendingWheelY; private double _lastRenderScaling = 1; private DispatcherTimer? _scalingTimer; + private Cursor? _customRemoteCursor; + private Avalonia.Media.Imaging.WriteableBitmap? _customRemoteCursorBitmap; public RdpView() { @@ -77,6 +79,7 @@ private void OnDataContextChanged(object? sender, EventArgs e) _boundVm = vm; vm.PropertyChanged += OnViewModelPropertyChanged; + vm.PointerShapeChanged += OnPointerShapeChanged; if (vm.IsConnected) StartScalingTimer(); ApplyScaleMode(vm); @@ -169,11 +172,64 @@ private void UnbindViewModel() return; _boundVm.PropertyChanged -= OnViewModelPropertyChanged; + _boundVm.PointerShapeChanged -= OnPointerShapeChanged; _boundVm = null; + DisposeCustomRemoteCursor(); StopScalingTimer(); DisposeSystemShortcutHook(); } + private void OnPointerShapeChanged(int kind, int width, int height, int hotX, int hotY, byte[]? pixels) + { + if (kind == 1) + { + DisposeCustomRemoteCursor(); + FramebufferImage.Cursor = new Cursor(StandardCursorType.None); + return; + } + + if (kind == 2 && pixels != null && width > 0 && height > 0) + { + try + { + var bitmap = new Avalonia.Media.Imaging.WriteableBitmap( + new PixelSize(width, height), + new Vector(96, 96), + Avalonia.Platform.PixelFormat.Bgra8888, + Avalonia.Platform.AlphaFormat.Unpremul); + using (var fb = bitmap.Lock()) + { + var copyBytes = Math.Min(pixels.Length, fb.RowBytes * fb.Size.Height); + System.Runtime.InteropServices.Marshal.Copy(pixels, 0, fb.Address, copyBytes); + } + + var clampedHotX = Math.Clamp(hotX, 0, width - 1); + var clampedHotY = Math.Clamp(hotY, 0, height - 1); + var cursor = new Cursor(bitmap, new PixelPoint(clampedHotX, clampedHotY)); + FramebufferImage.Cursor = cursor; + DisposeCustomRemoteCursor(); + _customRemoteCursor = cursor; + _customRemoteCursorBitmap = bitmap; + return; + } + catch + { + // Fall back to default arrow cursor if platform cursor creation fails. + } + } + + DisposeCustomRemoteCursor(); + FramebufferImage.Cursor = new Cursor(StandardCursorType.Arrow); + } + + private void DisposeCustomRemoteCursor() + { + _customRemoteCursor?.Dispose(); + _customRemoteCursor = null; + _customRemoteCursorBitmap?.Dispose(); + _customRemoteCursorBitmap = null; + } + private void UpdateSystemShortcutHook() { var shouldEnable = OperatingSystem.IsWindows() && diff --git a/native/CxRdpBridge/cxrdp_bridge.cpp b/native/CxRdpBridge/cxrdp_bridge.cpp index 9907349..56a1f84 100644 --- a/native/CxRdpBridge/cxrdp_bridge.cpp +++ b/native/CxRdpBridge/cxrdp_bridge.cpp @@ -136,6 +136,7 @@ struct CxRdpSession cxrdp_status_callback status_callback = nullptr; cxrdp_disconnect_callback disconnect_callback = nullptr; cxrdp_clipboard_text_callback clipboard_text_callback = nullptr; + cxrdp_pointer_callback pointer_callback = nullptr; void* user_data = nullptr; std::string last_error; std::mutex clipboard_mutex; @@ -2358,6 +2359,127 @@ BOOL cx_load_channels(freerdp* instance) return TRUE; } +struct CxRdpPointer +{ + rdpPointer pointer; + uint8_t* bgra; + int width; + int height; + int hot_x; + int hot_y; +}; + +BOOL cx_pointer_new(rdpContext* context, rdpPointer* pointer) +{ + if (!context || !pointer || pointer->width == 0 || pointer->height == 0) + return FALSE; + + auto* cxPtr = reinterpret_cast(pointer); + const size_t byteCount = static_cast(pointer->width) * static_cast(pointer->height) * 4u; + cxPtr->bgra = static_cast(std::calloc(1, byteCount)); + if (!cxPtr->bgra) + return FALSE; + + cxPtr->width = static_cast(pointer->width); + cxPtr->height = static_cast(pointer->height); + cxPtr->hot_x = static_cast(pointer->xPos); + cxPtr->hot_y = static_cast(pointer->yPos); + + const BOOL ok = freerdp_image_copy_from_pointer_data( + cxPtr->bgra, + PIXEL_FORMAT_BGRA32, + 0, + 0, + 0, + pointer->width, + pointer->height, + pointer->xorMaskData, + pointer->lengthXorMask, + pointer->andMaskData, + pointer->lengthAndMask, + pointer->xorBpp, + &context->gdi->palette); + if (!ok) + { + std::free(cxPtr->bgra); + cxPtr->bgra = nullptr; + return FALSE; + } + + return TRUE; +} + +void cx_pointer_free(rdpContext* context, rdpPointer* pointer) +{ + (void)context; + if (!pointer) + return; + + auto* cxPtr = reinterpret_cast(pointer); + if (cxPtr->bgra) + { + std::free(cxPtr->bgra); + cxPtr->bgra = nullptr; + } +} + +BOOL cx_pointer_set(rdpContext* context, rdpPointer* pointer) +{ + auto* session = get_session(context); + if (!session || !pointer) + return TRUE; + + auto* cxPtr = reinterpret_cast(pointer); + if (!cxPtr->bgra || cxPtr->width <= 0 || cxPtr->height <= 0) + return TRUE; + + std::lock_guard lock(session->callback_mutex); + if (session->pointer_callback) + { + session->pointer_callback( + session->user_data, + CX_RDP_POINTER_CUSTOM, + cxPtr->width, + cxPtr->height, + cxPtr->hot_x, + cxPtr->hot_y, + cxPtr->bgra); + } + return TRUE; +} + +BOOL cx_pointer_set_null(rdpContext* context) +{ + auto* session = get_session(context); + if (!session) + return TRUE; + + std::lock_guard lock(session->callback_mutex); + if (session->pointer_callback) + session->pointer_callback(session->user_data, CX_RDP_POINTER_NULL, 0, 0, 0, 0, nullptr); + return TRUE; +} + +BOOL cx_pointer_set_default(rdpContext* context) +{ + auto* session = get_session(context); + if (!session) + return TRUE; + + std::lock_guard lock(session->callback_mutex); + if (session->pointer_callback) + session->pointer_callback(session->user_data, CX_RDP_POINTER_DEFAULT, 0, 0, 0, 0, nullptr); + return TRUE; +} + +BOOL cx_pointer_set_position(rdpContext* context, UINT32 x, UINT32 y) +{ + (void)context; + (void)x; + (void)y; + return TRUE; +} + BOOL cx_post_connect(freerdp* instance) { if (!instance || !instance->context) @@ -2408,6 +2530,19 @@ BOOL cx_post_connect(freerdp* instance) { notify_status(session, "RDP GFX channel not bound yet; awaiting the graphics channel."); } + if (instance->context->graphics) + { + rdpPointer pointer{}; + pointer.size = sizeof(CxRdpPointer); + pointer.New = cx_pointer_new; + pointer.Free = cx_pointer_free; + pointer.Set = cx_pointer_set; + pointer.SetNull = cx_pointer_set_null; + pointer.SetDefault = cx_pointer_set_default; + pointer.SetPosition = cx_pointer_set_position; + graphics_register_pointer(instance->context->graphics, &pointer); + } + notify_status(session, "RDP connected."); return TRUE; } @@ -3046,7 +3181,8 @@ CX_RDP_API uint32_t cxrdp_get_capabilities(void) CX_RDP_CAPABILITY_PERFORMANCE_FLAGS | CX_RDP_CAPABILITY_DIRTY_RECT | CX_RDP_CAPABILITY_GFX | - CX_RDP_CAPABILITY_SYNC_LOCK_KEYS; + CX_RDP_CAPABILITY_SYNC_LOCK_KEYS | + CX_RDP_CAPABILITY_POINTER_SHAPE; if (has_native_audio_backend()) capabilities |= CX_RDP_CAPABILITY_AUDIO_PLAYBACK | CX_RDP_CAPABILITY_MICROPHONE; return capabilities; @@ -3099,6 +3235,18 @@ CX_RDP_API void cxrdp_set_clipboard_callback( session->clipboard_text_callback = clipboard_text_callback; } +CX_RDP_API void cxrdp_set_pointer_callback( + void* handle, + cxrdp_pointer_callback pointer_callback) +{ + auto* session = static_cast(handle); + if (!session) + return; + + std::lock_guard lock(session->callback_mutex); + session->pointer_callback = pointer_callback; +} + CX_RDP_API int cxrdp_connect( void* handle, const char* host, diff --git a/native/CxRdpBridge/cxrdp_bridge.h b/native/CxRdpBridge/cxrdp_bridge.h index c7ae427..5745386 100644 --- a/native/CxRdpBridge/cxrdp_bridge.h +++ b/native/CxRdpBridge/cxrdp_bridge.h @@ -20,8 +20,16 @@ typedef void (*cxrdp_frame_callback)(void* user_data, int width, int height, int typedef void (*cxrdp_status_callback)(void* user_data, const char* message); typedef void (*cxrdp_disconnect_callback)(void* user_data); typedef void (*cxrdp_clipboard_text_callback)(void* user_data, const char* text); +typedef void (*cxrdp_pointer_callback)( + void* user_data, + int kind, + int width, + int height, + int hot_x, + int hot_y, + const uint8_t* bgra_pixels); -#define CX_RDP_BRIDGE_API_VERSION 12u +#define CX_RDP_BRIDGE_API_VERSION 13u #define CX_RDP_CAPABILITY_CLIPBOARD 0x00000001u #define CX_RDP_CAPABILITY_DRIVE_REDIRECTION 0x00000002u #define CX_RDP_CAPABILITY_AUDIO_PLAYBACK 0x00000004u @@ -52,6 +60,12 @@ typedef void (*cxrdp_clipboard_text_callback)(void* user_data, const char* text) #define CX_RDP_CAPABILITY_GFX 0x00000800u /* The bridge can synchronize CapsLock/NumLock/ScrollLock state to the remote session. */ #define CX_RDP_CAPABILITY_SYNC_LOCK_KEYS 0x00001000u +/* The bridge forwards remote mouse pointer bitmaps and hotspots to the host. */ +#define CX_RDP_CAPABILITY_POINTER_SHAPE 0x00002000u + +#define CX_RDP_POINTER_DEFAULT 0 +#define CX_RDP_POINTER_NULL 1 +#define CX_RDP_POINTER_CUSTOM 2 #define CX_RDP_AUDIO_PLAY_LOCAL 0 #define CX_RDP_AUDIO_PLAY_REMOTE 1 @@ -83,6 +97,7 @@ CX_RDP_API void cxrdp_send_key(void* handle, uint32_t key, int down); CX_RDP_API void cxrdp_send_unicode_key(void* handle, uint16_t code, int down); CX_RDP_API void cxrdp_sync_lock_keys(void* handle, uint32_t flags); CX_RDP_API void cxrdp_set_clipboard_callback(void* handle, cxrdp_clipboard_text_callback clipboard_text_callback); +CX_RDP_API void cxrdp_set_pointer_callback(void* handle, cxrdp_pointer_callback pointer_callback); CX_RDP_API void cxrdp_set_clipboard_text(void* handle, const char* text); CX_RDP_API int cxrdp_set_drive_redirection( void* handle, From d2d9e70fd84c2a1e951ea891502ff7f799a3c34c Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 15:33:27 +0800 Subject: [PATCH 06/15] feat(rdp): add cross-platform image/file/rich-text clipboard, drag-and-drop paste, and large file locking Added: - Services/RdpClipboardImageHelper.cs for cross-platform CF_DIB/PNG, HTML/RTF rich text, and file list (CF_HDROP / text/uri-list) clipboard conversion with SHA-256 anti-loop hashing. - Services/WindowsClipboardListener.cs using a dedicated HWND_MESSAGE window (AddClipboardFormatListener) for zero-delay Windows clipboard change notifications, plus 800ms polling on macOS/Linux. - Drag-and-drop local file/folder paste directly onto the RDP viewport. - Per-session RdpEnableClipboardLock toggle (LockClipboardData) and native ABI v14 clipboard extension declarations. Changed: - Extended RdpBridgeClient, RdpViewModel, and RdpView to synchronize files, images, rich text, and plain text with Windows clipboard sequence-number deduplication. Fixed: - Enables mstsc-grade bidirectional image, rich text, and file clipboard workflows and prevents clipboard feedback loops. Technical Approach: - Extend cxrdp_bridge.h to API v14 (CX_RDP_CAPABILITY_CLIPBOARD_IMAGE/FILES/RICH_TEXT/LOCK) with managed capability gating and EntryPointNotFoundException fallbacks. --- Models/SessionInfo.cs | 1 + Services/RdpBridgeClient.cs | 133 ++++++ Services/RdpClipboardImageHelper.cs | 639 +++++++++++++++++++++++++++ Services/WindowsClipboardListener.cs | 194 ++++++++ ViewModels/RdpViewModel.cs | 34 ++ ViewModels/SessionEditViewModel.cs | 3 + ViewModels/SessionTreeViewModel.cs | 2 + Views/RdpView.axaml | 1 + Views/RdpView.axaml.cs | 212 ++++++++- Views/SessionEditDialog.axaml | 3 + native/CxRdpBridge/cxrdp_bridge.h | 27 +- 11 files changed, 1247 insertions(+), 2 deletions(-) create mode 100644 Services/RdpClipboardImageHelper.cs create mode 100644 Services/WindowsClipboardListener.cs diff --git a/Models/SessionInfo.cs b/Models/SessionInfo.cs index 4e0f3a2..9c73a9d 100644 --- a/Models/SessionInfo.cs +++ b/Models/SessionInfo.cs @@ -601,6 +601,7 @@ public int SshMonitorRefreshIntervalSeconds public string RdpSecurityMode { get; set; } = "Auto"; public bool RdpApplyKeyCombinations { get; set; } = true; public bool RdpSyncLockKeys { get; set; } = true; + public bool RdpEnableClipboardLock { get; set; } = true; public bool RdpClipboardEnabled { get; set; } = true; /// Send PERF_DISABLE_WALLPAPER so the server skips the desktop wallpaper. public bool RdpDisableWallpaper { get; set; } = true; diff --git a/Services/RdpBridgeClient.cs b/Services/RdpBridgeClient.cs index 5fd7de2..62d1759 100644 --- a/Services/RdpBridgeClient.cs +++ b/Services/RdpBridgeClient.cs @@ -76,6 +76,13 @@ public sealed class RdpBridgeClient : IDisposable private const uint SyncLockKeysCapability = 0x00001000; private const uint PointerShapeApiVersion = 13; private const uint PointerShapeCapability = 0x00002000; + public const uint ClipboardImageFormatPng = 1; + public const uint ClipboardImageFormatDib = 2; + private const uint ClipboardExtendedApiVersion = 14; + private const uint ClipboardImageCapability = 0x00004000; + private const uint ClipboardFilesCapability = 0x00008000; + private const uint ClipboardRichTextCapability = 0x00010000; + private const uint ClipboardLockCapability = 0x00020000; private static readonly object DebugLogLock = new(); private static readonly object NativeLoadFailureLock = new(); private static readonly bool DetailedDebugLogEnabled = IsEnvironmentFlagEnabled("CXSHELL_RDP_DEBUG_LOG"); @@ -95,7 +102,13 @@ public sealed class RdpBridgeClient : IDisposable private readonly StatusCallback _statusCallback; private readonly DisconnectCallback _disconnectCallback; private readonly ClipboardTextCallback _clipboardTextCallback; + private readonly ClipboardImageCallback _clipboardImageCallback; + private readonly ClipboardFilesCallback _clipboardFilesCallback; private readonly PointerCallback _pointerCallback; + private bool _supportsClipboardImage; + private bool _supportsClipboardFiles; + private bool _supportsClipboardRichText; + private bool _supportsClipboardLock; private readonly object _frameSync = new(); private readonly RdpFrameComposer _frameComposer = new(enabled: FrameCoalescingEnabled, useCoverage: FrameCoverageEnabled); private RdpFramePresentationMode _frameMode = RdpFramePresentationMode.Auto; @@ -139,6 +152,8 @@ static RdpBridgeClient() public event Action? StatusChanged; public event Action? Disconnected; public event Action? ClipboardTextReceived; + public event Action? ClipboardImageReceived; + public event Action? ClipboardFilesReceived; public event Action? PointerShapeChanged; public static string DebugLogPath => Path.Combine(GetDebugLogDirectory(), "rdp-debug.log"); @@ -158,6 +173,8 @@ public RdpBridgeClient() _statusCallback = OnStatus; _disconnectCallback = OnDisconnected; _clipboardTextCallback = OnClipboardText; + _clipboardImageCallback = OnClipboardImage; + _clipboardFilesCallback = OnClipboardFiles; _pointerCallback = OnPointer; } @@ -251,6 +268,21 @@ public void Connect( { NativeMethods.cxrdp_set_pointer_callback(_handle, _pointerCallback); } + + _supportsClipboardImage = nativeApiVersion >= ClipboardExtendedApiVersion && + (nativeCapabilities & ClipboardImageCapability) != 0; + _supportsClipboardFiles = nativeApiVersion >= ClipboardExtendedApiVersion && + (nativeCapabilities & ClipboardFilesCapability) != 0; + _supportsClipboardRichText = nativeApiVersion >= ClipboardExtendedApiVersion && + (nativeCapabilities & ClipboardRichTextCapability) != 0; + _supportsClipboardLock = nativeApiVersion >= ClipboardExtendedApiVersion && + (nativeCapabilities & ClipboardLockCapability) != 0; + if (_supportsClipboardImage) + NativeMethods.cxrdp_set_clipboard_image_callback(_handle, _clipboardImageCallback); + if (_supportsClipboardFiles) + NativeMethods.cxrdp_set_clipboard_files_callback(_handle, _clipboardFilesCallback); + if (_supportsClipboardLock) + NativeMethods.cxrdp_set_clipboard_lock_enabled(_handle, session.RdpEnableClipboardLock ? 1 : 0); if (nativeApiVersion >= GfxApiVersion && (nativeCapabilities & GfxCapability) != 0) { var gfxRequested = GraphicsPipelineForcedOn || session.RdpGraphicsPipelineEnabled; @@ -737,6 +769,47 @@ public void SetClipboardText(string text) NativeMethods.cxrdp_set_clipboard_text(_handle, text ?? string.Empty); } + public void SetClipboardRichText(string plainText, byte[]? htmlBytes, byte[]? rtfBytes) + { + if (_handle == IntPtr.Zero) + return; + + if (_supportsClipboardRichText) + { + NativeMethods.cxrdp_set_clipboard_rich_text( + _handle, + plainText ?? string.Empty, + htmlBytes, + (uint)(htmlBytes?.Length ?? 0), + rtfBytes, + (uint)(rtfBytes?.Length ?? 0)); + } + else + { + NativeMethods.cxrdp_set_clipboard_text(_handle, plainText ?? string.Empty); + } + } + + public void SetClipboardImage(uint imageFormat, byte[] data) + { + if (_handle == IntPtr.Zero || !_supportsClipboardImage || data.Length == 0) + return; + + NativeMethods.cxrdp_set_clipboard_image(_handle, imageFormat, data, (uint)data.Length); + } + + public void SetClipboardFiles(IReadOnlyList filePaths) + { + if (_handle == IntPtr.Zero || !_supportsClipboardFiles || filePaths.Count == 0) + return; + + var joined = string.Join('\n', filePaths.Where(p => !string.IsNullOrWhiteSpace(p))); + if (string.IsNullOrWhiteSpace(joined)) + return; + + NativeMethods.cxrdp_set_clipboard_files(_handle, joined); + } + /// /// Requests a resolution/DPI change on a live session without reconnecting. /// Returns false when the native bridge cannot do it (then callers should @@ -1262,6 +1335,30 @@ private void OnClipboardText(IntPtr userData, IntPtr text) ClipboardTextReceived?.Invoke(value); } + private void OnClipboardImage(IntPtr userData, uint imageFormat, IntPtr data, uint length) + { + if (data == IntPtr.Zero || length == 0) + return; + + var copy = new byte[length]; + Marshal.Copy(data, copy, 0, (int)length); + ClipboardImageReceived?.Invoke(imageFormat, copy); + } + + private void OnClipboardFiles(IntPtr userData, IntPtr filePaths) + { + if (filePaths == IntPtr.Zero) + return; + + var raw = Marshal.PtrToStringUTF8(filePaths); + if (string.IsNullOrWhiteSpace(raw)) + return; + + var paths = raw.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + if (paths.Length > 0) + ClipboardFilesReceived?.Invoke(paths); + } + private static string GetDebugLogDirectory() { var root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); @@ -1388,6 +1485,12 @@ private static uint GetNativeCapabilities() [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void ClipboardTextCallback(IntPtr userData, IntPtr text); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate void ClipboardImageCallback(IntPtr userData, uint imageFormat, IntPtr data, uint length); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate void ClipboardFilesCallback(IntPtr userData, IntPtr filePaths); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void PointerCallback( IntPtr userData, @@ -1451,6 +1554,36 @@ public static extern int cxrdp_connect( [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern void cxrdp_set_pointer_callback(IntPtr handle, PointerCallback? pointerCallback); + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] + public static extern void cxrdp_set_clipboard_image_callback(IntPtr handle, ClipboardImageCallback? callback); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] + public static extern void cxrdp_set_clipboard_files_callback(IntPtr handle, ClipboardFilesCallback? callback); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] + public static extern void cxrdp_set_clipboard_rich_text( + IntPtr handle, + [MarshalAs(UnmanagedType.LPUTF8Str)] string plainText, + byte[]? htmlBytes, + uint htmlLength, + byte[]? rtfBytes, + uint rtfLength); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] + public static extern void cxrdp_set_clipboard_image( + IntPtr handle, + uint imageFormat, + byte[] data, + uint length); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] + public static extern void cxrdp_set_clipboard_files( + IntPtr handle, + [MarshalAs(UnmanagedType.LPUTF8Str)] string filePathsNewlineSeparated); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] + public static extern int cxrdp_set_clipboard_lock_enabled(IntPtr handle, int enabled); + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern void cxrdp_sync_lock_keys(IntPtr handle, uint flags); diff --git a/Services/RdpClipboardImageHelper.cs b/Services/RdpClipboardImageHelper.cs new file mode 100644 index 0000000..1709c9a --- /dev/null +++ b/Services/RdpClipboardImageHelper.cs @@ -0,0 +1,639 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Input; +using Avalonia.Input.Platform; +using Avalonia.Media.Imaging; +using Avalonia.Platform; + +namespace CxShell.Services; + +public sealed record RdpClipboardImagePayload(byte[]? PngBytes, byte[]? DibBytes, string Hash); + +public static class RdpClipboardImageHelper +{ + private const uint CfDib = 8; + private const uint CfHDrop = 15; + private const uint GmemMoveable = 0x0002; + private static uint _cfPng; + private static uint _cfHtml; + private static uint _cfRtf; + + public static uint GetWindowsClipboardSequenceNumber() + { + return OperatingSystem.IsWindows() ? GetClipboardSequenceNumber() : 0u; + } + + private static bool TryOpenClipboardWithRetry(int maxAttempts = 10, int delayMs = 10) + { + for (var attempt = 0; attempt < maxAttempts; attempt++) + { + if (OpenClipboard(IntPtr.Zero)) + return true; + + if (attempt + 1 < maxAttempts) + System.Threading.Thread.Sleep(delayMs); + } + + return false; + } + + public static async Task<(byte[]? HtmlBytes, byte[]? RtfBytes)> TryReadLocalRichTextAsync(IClipboard? clipboard) + { + if (OperatingSystem.IsWindows()) + { + if (TryOpenClipboardWithRetry()) + { + try + { + if (_cfHtml == 0) + _cfHtml = RegisterClipboardFormatW("HTML Format"); + if (_cfRtf == 0) + _cfRtf = RegisterClipboardFormatW("Rich Text Format"); + + var html = _cfHtml != 0 ? ReadWindowsClipboardBytes(_cfHtml) : null; + var rtf = _cfRtf != 0 ? ReadWindowsClipboardBytes(_cfRtf) : null; + if (html != null || rtf != null) + return (html, rtf); + } + catch + { + // Ignore platform read errors. + } + finally + { + CloseClipboard(); + } + } + } + + if (clipboard == null) + return (null, null); + + try + { + var transfer = await clipboard.TryGetDataAsync(); + if (transfer == null) + return (null, null); + + var html = await TryExtractBytesFromDataTransferAsync(transfer, "text/html"); + var rtf = await TryExtractBytesFromDataTransferAsync(transfer, "text/rtf"); + return (html, rtf); + } + catch + { + return (null, null); + } + } + + public static async Task TryReadLocalFilesAsync(IClipboard? clipboard) + { + if (OperatingSystem.IsWindows()) + { + var winFiles = TryReadWindowsClipboardFiles(); + if (winFiles is { Length: > 0 }) + return winFiles; + } + + if (clipboard == null) + return null; + + try + { + var files = await clipboard.TryGetFilesAsync(); + if (files == null) + return null; + + var paths = new System.Collections.Generic.List(); + foreach (var item in files) + { + var path = item.Path?.LocalPath; + if (!string.IsNullOrWhiteSpace(path)) + paths.Add(path); + } + + return paths.Count > 0 ? paths.ToArray() : null; + } + catch + { + return null; + } + } + + public static async Task TryWriteLocalFilesAsync(IClipboard? clipboard, string[] paths) + { + if (paths == null || paths.Length == 0) + return false; + + if (OperatingSystem.IsWindows()) + return TryWriteWindowsClipboardFiles(paths); + + if (clipboard == null) + return false; + + try + { + var uris = new System.Collections.Generic.List(paths.Length); + foreach (var p in paths) + { + if (!string.IsNullOrWhiteSpace(p)) + uris.Add(new Uri(Path.GetFullPath(p)).AbsoluteUri); + } + + if (uris.Count == 0) + return false; + + var transfer = new DataTransfer(); + var item = new DataTransferItem(); + var uriListText = string.Join("\r\n", uris) + "\r\n"; + item.Set( + DataFormat.CreateBytesPlatformFormat("text/uri-list"), + System.Text.Encoding.UTF8.GetBytes(uriListText)); + if (OperatingSystem.IsMacOS()) + item.Set(DataFormat.CreateStringPlatformFormat("public.file-url"), uris[0]); + + transfer.Add(item); + await clipboard.SetDataAsync(transfer); + return true; + } + catch + { + return false; + } + } + + private static string[]? TryReadWindowsClipboardFiles() + { + if (!TryOpenClipboardWithRetry()) + return null; + + try + { + if (!IsClipboardFormatAvailable(CfHDrop)) + return null; + + var hDrop = GetClipboardData(CfHDrop); + if (hDrop == IntPtr.Zero) + return null; + + var count = DragQueryFileW(hDrop, 0xFFFFFFFFu, null, 0); + if (count == 0) + return null; + + var result = new System.Collections.Generic.List((int)count); + for (uint i = 0; i < count; i++) + { + var length = DragQueryFileW(hDrop, i, null, 0); + if (length == 0) + continue; + var buffer = new char[length + 1]; + DragQueryFileW(hDrop, i, buffer, length + 1); + var path = new string(buffer, 0, (int)length); + if (!string.IsNullOrWhiteSpace(path)) + result.Add(path); + } + + return result.Count > 0 ? result.ToArray() : null; + } + catch + { + return null; + } + finally + { + CloseClipboard(); + } + } + + private static bool TryWriteWindowsClipboardFiles(string[] paths) + { + if (!TryOpenClipboardWithRetry()) + return false; + + try + { + if (!EmptyClipboard()) + return false; + + // DROPFILES header (20 bytes) + UTF-16LE null-separated paths + final null + var sb = new System.Text.StringBuilder(); + foreach (var p in paths) + { + if (!string.IsNullOrWhiteSpace(p)) + { + sb.Append(p); + sb.Append('\0'); + } + } + sb.Append('\0'); + + var textBytes = System.Text.Encoding.Unicode.GetBytes(sb.ToString()); + var payload = new byte[20 + textBytes.Length]; + BitConverter.TryWriteBytes(payload.AsSpan(0, 4), 20); // pFiles offset + BitConverter.TryWriteBytes(payload.AsSpan(16, 4), 1); // fWide = TRUE + Buffer.BlockCopy(textBytes, 0, payload, 20, textBytes.Length); + + return WriteWindowsClipboardBytes(CfHDrop, payload); + } + catch + { + return false; + } + finally + { + CloseClipboard(); + } + } + + [DllImport("shell32.dll", CharSet = CharSet.Unicode)] + private static extern uint DragQueryFileW(IntPtr hDrop, uint iFile, [Out] char[]? lpszFile, uint cch); + + public static string ComputeHash(byte[]? pngBytes, byte[]? dibBytes) + { + var source = (pngBytes is { Length: > 0 } ? pngBytes : dibBytes) ?? Array.Empty(); + return Convert.ToHexString(SHA256.HashData(source)); + } + + public static async Task TryReadLocalImageAsync(IClipboard? clipboard) + { + if (OperatingSystem.IsWindows()) + { + var winPayload = TryReadWindowsClipboardImage(); + if (winPayload != null) + return winPayload; + } + + if (clipboard == null) + return null; + + try + { + var dataTransfer = await clipboard.TryGetDataAsync(); + if (dataTransfer == null) + return null; + + foreach (var format in new[] { "image/png", "PNG", "public.png" }) + { + var raw = await TryExtractBytesFromDataTransferAsync(dataTransfer, format); + if (raw is { Length: > 8 }) + { + var dib = TryConvertPngToDib(raw); + return new RdpClipboardImagePayload(raw, dib, ComputeHash(raw, dib)); + } + } + } + catch + { + // Ignore platform clipboard read failures. + } + + return null; + } + + public static async Task TryWriteLocalImageAsync(IClipboard? clipboard, uint imageFormat, byte[] data) + { + if (data == null || data.Length == 0) + return false; + + byte[]? pngBytes = null; + byte[]? dibBytes = null; + + if (imageFormat == RdpBridgeClient.ClipboardImageFormatPng) + { + pngBytes = data; + dibBytes = TryConvertPngToDib(data); + } + else if (imageFormat == RdpBridgeClient.ClipboardImageFormatDib) + { + dibBytes = data; + pngBytes = TryConvertDibToPng(data); + } + + if (OperatingSystem.IsWindows()) + { + if (TryWriteWindowsClipboardImage(pngBytes, dibBytes)) + return true; + } + + if (clipboard != null && pngBytes is { Length: > 0 }) + { + try + { + var transfer = new DataTransfer(); + var item = new DataTransferItem(); + item.Set(DataFormat.CreateBytesPlatformFormat("image/png"), pngBytes); + transfer.Add(item); + await clipboard.SetDataAsync(transfer); + return true; + } + catch + { + // Ignore platform clipboard write failures. + } + } + + return false; + } + + public static byte[]? TryConvertDibToPng(byte[] dibBytes) + { + if (dibBytes.Length < 40) + return null; + + try + { + var headerSize = BitConverter.ToInt32(dibBytes, 0); + if (headerSize < 40 || headerSize > dibBytes.Length) + return null; + + var bitCount = BitConverter.ToUInt16(dibBytes, 14); + var compression = BitConverter.ToUInt32(dibBytes, 16); + var colorsUsed = BitConverter.ToUInt32(dibBytes, 32); + + uint colorTableSize = 0; + if (bitCount <= 8) + { + colorTableSize = (colorsUsed == 0 ? (1u << bitCount) : colorsUsed) * 4u; + } + else if (compression == 3 && headerSize == 40) // BI_BITFIELDS + { + colorTableSize = 12; + } + + var pixelOffset = 14 + headerSize + (int)colorTableSize; + var fileSize = 14 + dibBytes.Length; + var bmp = new byte[fileSize]; + bmp[0] = (byte)'B'; + bmp[1] = (byte)'M'; + BitConverter.TryWriteBytes(bmp.AsSpan(2, 4), fileSize); + BitConverter.TryWriteBytes(bmp.AsSpan(10, 4), pixelOffset); + Buffer.BlockCopy(dibBytes, 0, bmp, 14, dibBytes.Length); + + using var bmpStream = new MemoryStream(bmp); + using var bitmap = new Bitmap(bmpStream); + using var pngStream = new MemoryStream(); +#pragma warning disable CS0618 + bitmap.Save(pngStream); +#pragma warning restore CS0618 + return pngStream.ToArray(); + } + catch + { + return null; + } + } + + public static unsafe byte[]? TryConvertPngToDib(byte[] pngBytes) + { + if (pngBytes.Length < 8) + return null; + + try + { + using var pngStream = new MemoryStream(pngBytes); + using var writeable = WriteableBitmap.Decode(pngStream); + var width = writeable.PixelSize.Width; + var height = writeable.PixelSize.Height; + if (width <= 0 || height <= 0) + return null; + + using var fb = writeable.Lock(); + var stride = width * 4; + var imageSize = stride * height; + var dib = new byte[40 + imageSize]; + + // BITMAPINFOHEADER (40 bytes) + BitConverter.TryWriteBytes(dib.AsSpan(0, 4), 40); // biSize + BitConverter.TryWriteBytes(dib.AsSpan(4, 4), width); // biWidth + BitConverter.TryWriteBytes(dib.AsSpan(8, 4), height); // biHeight (positive = bottom-up) + BitConverter.TryWriteBytes(dib.AsSpan(12, 2), (ushort)1); // biPlanes + BitConverter.TryWriteBytes(dib.AsSpan(14, 2), (ushort)32); // biBitCount + BitConverter.TryWriteBytes(dib.AsSpan(16, 4), 0); // biCompression = BI_RGB + BitConverter.TryWriteBytes(dib.AsSpan(20, 4), imageSize); // biSizeImage + + var isRgba = fb.Format == PixelFormat.Rgba8888; + var srcBase = (byte*)fb.Address; + for (var y = 0; y < height; y++) + { + var srcRow = srcBase + (long)y * fb.RowBytes; + var dstOffset = 40 + (height - 1 - y) * stride; + if (!isRgba) + { + Marshal.Copy((IntPtr)srcRow, dib, dstOffset, stride); + } + else + { + for (var x = 0; x < width; x++) + { + var si = x * 4; + var di = dstOffset + si; + dib[di] = srcRow[si + 2]; // B + dib[di + 1] = srcRow[si + 1]; // G + dib[di + 2] = srcRow[si]; // R + dib[di + 3] = srcRow[si + 3]; // A + } + } + } + + return dib; + } + catch + { + return null; + } + } + + private static async Task TryExtractBytesFromDataTransferAsync(IAsyncDataTransfer dataTransfer, string formatName) + { + try + { + var format = DataFormat.CreateBytesPlatformFormat(formatName); + foreach (var item in dataTransfer.Items) + { + var value = await item.TryGetRawAsync(format); + if (value is byte[] bytes && bytes.Length > 0) + return bytes; + } + } + catch + { + // Ignore unsupported format errors. + } + + return null; + } + + private static uint GetWindowsPngFormat() + { + if (_cfPng == 0) + _cfPng = RegisterClipboardFormatW("PNG"); + return _cfPng; + } + + private static RdpClipboardImagePayload? TryReadWindowsClipboardImage() + { + if (!TryOpenClipboardWithRetry()) + return null; + + try + { + var pngFormat = GetWindowsPngFormat(); + var pngBytes = pngFormat != 0 ? ReadWindowsClipboardBytes(pngFormat) : null; + var dibBytes = ReadWindowsClipboardBytes(CfDib); + + if (pngBytes == null && dibBytes == null) + return null; + + pngBytes ??= TryConvertDibToPng(dibBytes!); + dibBytes ??= TryConvertPngToDib(pngBytes!); + + if (pngBytes == null && dibBytes == null) + return null; + + return new RdpClipboardImagePayload(pngBytes, dibBytes, ComputeHash(pngBytes, dibBytes)); + } + catch + { + return null; + } + finally + { + CloseClipboard(); + } + } + + private static bool TryWriteWindowsClipboardImage(byte[]? pngBytes, byte[]? dibBytes) + { + if (pngBytes == null && dibBytes == null) + return false; + + if (!TryOpenClipboardWithRetry()) + return false; + + try + { + if (!EmptyClipboard()) + return false; + + var wroteAny = false; + if (dibBytes is { Length: > 0 }) + wroteAny |= WriteWindowsClipboardBytes(CfDib, dibBytes); + + var pngFormat = GetWindowsPngFormat(); + if (pngFormat != 0 && pngBytes is { Length: > 0 }) + wroteAny |= WriteWindowsClipboardBytes(pngFormat, pngBytes); + + return wroteAny; + } + catch + { + return false; + } + finally + { + CloseClipboard(); + } + } + + private static byte[]? ReadWindowsClipboardBytes(uint format) + { + if (!IsClipboardFormatAvailable(format)) + return null; + + var handle = GetClipboardData(format); + if (handle == IntPtr.Zero) + return null; + + var size = (int)GlobalSize(handle); + if (size <= 0) + return null; + + var ptr = GlobalLock(handle); + if (ptr == IntPtr.Zero) + return null; + + try + { + var buffer = new byte[size]; + Marshal.Copy(ptr, buffer, 0, size); + return buffer; + } + finally + { + GlobalUnlock(handle); + } + } + + private static bool WriteWindowsClipboardBytes(uint format, byte[] data) + { + var hGlobal = GlobalAlloc(GmemMoveable, (UIntPtr)data.Length); + if (hGlobal == IntPtr.Zero) + return false; + + var ptr = GlobalLock(hGlobal); + if (ptr == IntPtr.Zero) + { + GlobalFree(hGlobal); + return false; + } + + try + { + Marshal.Copy(data, 0, ptr, data.Length); + } + finally + { + GlobalUnlock(hGlobal); + } + + if (SetClipboardData(format, hGlobal) == IntPtr.Zero) + { + GlobalFree(hGlobal); + return false; + } + + return true; + } + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool OpenClipboard(IntPtr hWndNewOwner); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool CloseClipboard(); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool EmptyClipboard(); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool IsClipboardFormatAvailable(uint format); + + [DllImport("user32.dll", SetLastError = true)] + private static extern IntPtr GetClipboardData(uint uFormat); + + [DllImport("user32.dll", SetLastError = true)] + private static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem); + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern uint RegisterClipboardFormatW(string lpszFormat); + + [DllImport("user32.dll")] + private static extern uint GetClipboardSequenceNumber(); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr GlobalAlloc(uint uFlags, UIntPtr dwBytes); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr GlobalFree(IntPtr hMem); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr GlobalLock(IntPtr hMem); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool GlobalUnlock(IntPtr hMem); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern UIntPtr GlobalSize(IntPtr hMem); +} diff --git a/Services/WindowsClipboardListener.cs b/Services/WindowsClipboardListener.cs new file mode 100644 index 0000000..9dbe496 --- /dev/null +++ b/Services/WindowsClipboardListener.cs @@ -0,0 +1,194 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; + +namespace CxShell.Services; + +/// +/// Listens for real-time Windows clipboard changes via AddClipboardFormatListener +/// on a dedicated hidden message-only window thread. +/// +public sealed class WindowsClipboardListener : IDisposable +{ + private const uint WmClipboardUpdate = 0x031D; + private const uint WmQuit = 0x0012; + private static readonly IntPtr HwndMessage = new(-3); + + private readonly WndProcDelegate _wndProc; + private readonly Thread? _thread; + private uint _threadId; + private IntPtr _hwnd; + private bool _disposed; + + public event Action? ClipboardChanged; + + public WindowsClipboardListener() + { + _wndProc = WndProc; + if (!OperatingSystem.IsWindows()) + return; + + _thread = new Thread(RunMessageLoop) + { + IsBackground = true, + Name = "CxShell.Win32ClipboardListener" + }; + _thread.Start(); + } + + private void RunMessageLoop() + { + try + { + _threadId = GetCurrentThreadId(); + var className = $"CxShellClipboardListener_{Guid.NewGuid():N}"; + var hInstance = GetModuleHandleW(null); + + var wc = new WNDCLASSEXW + { + cbSize = (uint)Marshal.SizeOf(), + lpfnWndProc = Marshal.GetFunctionPointerForDelegate(_wndProc), + hInstance = hInstance, + lpszClassName = className + }; + + var atom = RegisterClassExW(ref wc); + if (atom == 0) + return; + + _hwnd = CreateWindowExW( + 0, + className, + string.Empty, + 0, + 0, 0, 0, 0, + HwndMessage, + IntPtr.Zero, + hInstance, + IntPtr.Zero); + + if (_hwnd == IntPtr.Zero) + { + UnregisterClassW(className, hInstance); + return; + } + + AddClipboardFormatListener(_hwnd); + + try + { + while (GetMessageW(out var msg, IntPtr.Zero, 0, 0) > 0) + { + TranslateMessage(ref msg); + DispatchMessageW(ref msg); + } + } + finally + { + RemoveClipboardFormatListener(_hwnd); + DestroyWindow(_hwnd); + _hwnd = IntPtr.Zero; + UnregisterClassW(className, hInstance); + } + } + catch + { + // Prevent background clipboard listener failures from crashing the process. + } + } + + private IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) + { + if (msg == WmClipboardUpdate) + { + ClipboardChanged?.Invoke(); + return IntPtr.Zero; + } + + return DefWindowProcW(hWnd, msg, wParam, lParam); + } + + public void Dispose() + { + if (_disposed) + return; + _disposed = true; + + if (_threadId != 0) + PostThreadMessageW(_threadId, WmQuit, IntPtr.Zero, IntPtr.Zero); + } + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct WNDCLASSEXW + { + public uint cbSize; + public uint style; + public IntPtr lpfnWndProc; + public int cbClsExtra; + public int cbWndExtra; + public IntPtr hInstance; + public IntPtr hIcon; + public IntPtr hCursor; + public IntPtr hbrBackground; + public string? lpszMenuName; + public string lpszClassName; + public IntPtr hIconSm; + } + + [StructLayout(LayoutKind.Sequential)] + private struct MSG + { + public IntPtr hwnd; + public uint message; + public IntPtr wParam; + public IntPtr lParam; + public uint time; + public int ptX; + public int ptY; + } + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern ushort RegisterClassExW(ref WNDCLASSEXW lpwcx); + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool UnregisterClassW(string lpClassName, IntPtr hInstance); + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr CreateWindowExW( + uint dwExStyle, string lpClassName, string lpWindowName, uint dwStyle, + int x, int y, int nWidth, int nHeight, + IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool DestroyWindow(IntPtr hWnd); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool AddClipboardFormatListener(IntPtr hwnd); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool RemoveClipboardFormatListener(IntPtr hwnd); + + [DllImport("user32.dll")] + private static extern int GetMessageW(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax); + + [DllImport("user32.dll")] + private static extern bool TranslateMessage(ref MSG lpMsg); + + [DllImport("user32.dll")] + private static extern IntPtr DispatchMessageW(ref MSG lpMsg); + + [DllImport("user32.dll")] + private static extern IntPtr DefWindowProcW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool PostThreadMessageW(uint idThread, uint msg, IntPtr wParam, IntPtr lParam); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr GetModuleHandleW(string? lpModuleName); + + [DllImport("kernel32.dll")] + private static extern uint GetCurrentThreadId(); +} diff --git a/ViewModels/RdpViewModel.cs b/ViewModels/RdpViewModel.cs index 31c8cab..9aaf688 100644 --- a/ViewModels/RdpViewModel.cs +++ b/ViewModels/RdpViewModel.cs @@ -92,6 +92,8 @@ private static int ResolveConnectTimeoutSeconds() public SessionInfo Session { get; } public string? Password { get; } public event Action? PointerShapeChanged; + public event Action? RemoteClipboardImageReceived; + public event Action? RemoteClipboardFilesReceived; public double FixedScaleFactor => Math.Clamp(ScreenScalePercent, 10, 500) / 100.0; public string ScaleModeText => IsFitToWindow ? "Fit to window" @@ -106,6 +108,8 @@ public RdpViewModel(SessionInfo session, string? password) _client.FramebufferUpdated += OnFramebufferUpdated; _client.StatusChanged += message => Dispatcher.UIThread.Post(() => HandleStatus(message)); _client.ClipboardTextReceived += OnClipboardTextReceived; + _client.ClipboardImageReceived += OnClipboardImageReceived; + _client.ClipboardFilesReceived += OnClipboardFilesReceived; _client.PointerShapeChanged += OnPointerShapeChanged; LocalizationService.Shared.LanguageChanged += OnLanguageChanged; _client.Disconnected += () => Dispatcher.UIThread.Post(() => @@ -643,6 +647,24 @@ public void SetClipboardText(string text) _client.SetClipboardText(text); } + public void SetClipboardRichText(string plainText, byte[]? htmlBytes, byte[]? rtfBytes) + { + if (IsConnected) + _client.SetClipboardRichText(plainText, htmlBytes, rtfBytes); + } + + public void SetClipboardImage(uint imageFormat, byte[] data) + { + if (IsConnected) + _client.SetClipboardImage(imageFormat, data); + } + + public void SetClipboardFiles(IReadOnlyList filePaths) + { + if (IsConnected) + _client.SetClipboardFiles(filePaths); + } + public void SyncLockKeys(uint flags) { if (IsConnected) @@ -756,6 +778,16 @@ private void OnClipboardTextReceived(string text) Dispatcher.UIThread.Post(() => RemoteClipboardText = text); } + private void OnClipboardImageReceived(uint imageFormat, byte[] data) + { + Dispatcher.UIThread.Post(() => RemoteClipboardImageReceived?.Invoke(imageFormat, data)); + } + + private void OnClipboardFilesReceived(string[] paths) + { + Dispatcher.UIThread.Post(() => RemoteClipboardFilesReceived?.Invoke(paths)); + } + private void OnPointerShapeChanged(int kind, int width, int height, int hotX, int hotY, byte[]? pixels) { Dispatcher.UIThread.Post(() => PointerShapeChanged?.Invoke(kind, width, height, hotX, hotY, pixels)); @@ -837,6 +869,8 @@ public void Dispose() CancelConnectWatchdog(); _client.FramebufferUpdated -= OnFramebufferUpdated; _client.ClipboardTextReceived -= OnClipboardTextReceived; + _client.ClipboardImageReceived -= OnClipboardImageReceived; + _client.ClipboardFilesReceived -= OnClipboardFilesReceived; _client.PointerShapeChanged -= OnPointerShapeChanged; LocalizationService.Shared.LanguageChanged -= OnLanguageChanged; _client.Dispose(); diff --git a/ViewModels/SessionEditViewModel.cs b/ViewModels/SessionEditViewModel.cs index 158ee25..8585d98 100644 --- a/ViewModels/SessionEditViewModel.cs +++ b/ViewModels/SessionEditViewModel.cs @@ -333,6 +333,7 @@ public readonly record struct AppearanceColorPalette( [ObservableProperty] private string _rdpSecurityMode = "Auto"; [ObservableProperty] private bool _rdpApplyKeyCombinations = true; [ObservableProperty] private bool _rdpSyncLockKeys = true; + [ObservableProperty] private bool _rdpEnableClipboardLock = true; [ObservableProperty] private bool _rdpClipboardEnabled = true; [ObservableProperty] private bool _rdpDisableWallpaper = true; [ObservableProperty] private bool _rdpGraphicsPipelineEnabled; @@ -1547,6 +1548,7 @@ public SessionEditViewModel(SessionInfo session) RdpSecurityMode = string.IsNullOrWhiteSpace(session.RdpSecurityMode) ? "Auto" : session.RdpSecurityMode; RdpApplyKeyCombinations = session.RdpApplyKeyCombinations; RdpSyncLockKeys = session.RdpSyncLockKeys; + RdpEnableClipboardLock = session.RdpEnableClipboardLock; RdpClipboardEnabled = session.RdpClipboardEnabled; RdpDisableWallpaper = session.RdpDisableWallpaper; RdpGraphicsPipelineEnabled = session.RdpGraphicsPipelineEnabled; @@ -1859,6 +1861,7 @@ private void Save() session.RdpSecurityMode = string.IsNullOrWhiteSpace(RdpSecurityMode) ? "Auto" : RdpSecurityMode; session.RdpApplyKeyCombinations = RdpApplyKeyCombinations; session.RdpSyncLockKeys = RdpSyncLockKeys; + session.RdpEnableClipboardLock = RdpEnableClipboardLock; session.RdpClipboardEnabled = RdpClipboardEnabled; session.RdpDisableWallpaper = RdpDisableWallpaper; session.RdpGraphicsPipelineEnabled = RdpGraphicsPipelineEnabled; diff --git a/ViewModels/SessionTreeViewModel.cs b/ViewModels/SessionTreeViewModel.cs index 22ce94a..87f79c0 100644 --- a/ViewModels/SessionTreeViewModel.cs +++ b/ViewModels/SessionTreeViewModel.cs @@ -262,6 +262,7 @@ public static void CopySessionValues(SessionInfo target, SessionInfo source) target.RdpSecurityMode = source.RdpSecurityMode; target.RdpApplyKeyCombinations = source.RdpApplyKeyCombinations; target.RdpSyncLockKeys = source.RdpSyncLockKeys; + target.RdpEnableClipboardLock = source.RdpEnableClipboardLock; target.RdpClipboardEnabled = source.RdpClipboardEnabled; target.RdpDisableWallpaper = source.RdpDisableWallpaper; target.RdpGraphicsPipelineEnabled = source.RdpGraphicsPipelineEnabled; @@ -1185,6 +1186,7 @@ private static SessionInfo CloneSession(SessionInfo source, string name) RdpSecurityMode = source.RdpSecurityMode, RdpApplyKeyCombinations = source.RdpApplyKeyCombinations, RdpSyncLockKeys = source.RdpSyncLockKeys, + RdpEnableClipboardLock = source.RdpEnableClipboardLock, RdpClipboardEnabled = source.RdpClipboardEnabled, RdpDisableWallpaper = source.RdpDisableWallpaper, RdpGraphicsPipelineEnabled = source.RdpGraphicsPipelineEnabled, diff --git a/Views/RdpView.axaml b/Views/RdpView.axaml index b667173..6598e35 100644 --- a/Views/RdpView.axaml +++ b/Views/RdpView.axaml @@ -9,6 +9,7 @@ Background="{atom:SharedTokenResource ColorBgLayout}"> { _isAttached = true; @@ -45,12 +53,14 @@ public RdpView() if (DataContext is RdpViewModel vm) ScheduleStart(vm); UpdateSystemShortcutHook(); + StartClipboardListener(); }; DetachedFromVisualTree += (_, _) => { _isAttached = false; _hasKeyboardFocus = false; StopScalingTimer(); + StopClipboardListener(); DisposeSystemShortcutHook(); ReleaseTrackedModifiers(); _pendingWheelY = 0; @@ -80,6 +90,8 @@ private void OnDataContextChanged(object? sender, EventArgs e) _boundVm = vm; vm.PropertyChanged += OnViewModelPropertyChanged; vm.PointerShapeChanged += OnPointerShapeChanged; + vm.RemoteClipboardImageReceived += OnRemoteClipboardImageReceived; + vm.RemoteClipboardFilesReceived += OnRemoteClipboardFilesReceived; if (vm.IsConnected) StartScalingTimer(); ApplyScaleMode(vm); @@ -173,7 +185,10 @@ private void UnbindViewModel() _boundVm.PropertyChanged -= OnViewModelPropertyChanged; _boundVm.PointerShapeChanged -= OnPointerShapeChanged; + _boundVm.RemoteClipboardImageReceived -= OnRemoteClipboardImageReceived; + _boundVm.RemoteClipboardFilesReceived -= OnRemoteClipboardFilesReceived; _boundVm = null; + ResetClipboardSyncState(); DisposeCustomRemoteCursor(); StopScalingTimer(); DisposeSystemShortcutHook(); @@ -587,12 +602,207 @@ private async Task SyncLocalClipboardToRemoteAsync() if (_applyingRemoteClipboardText || DataContext is not RdpViewModel vm || !vm.IsClipboardChannelReady) return; + if (OperatingSystem.IsWindows()) + { + var seq = RdpClipboardImageHelper.GetWindowsClipboardSequenceNumber(); + if (seq != 0 && + (_lastSyncedClipboardSequenceNumber == seq || _lastAppliedRemoteClipboardSequenceNumber == seq)) + { + return; + } + } + + var clipboard = TopLevel.GetTopLevel(this)?.Clipboard; + + var files = await RdpClipboardImageHelper.TryReadLocalFilesAsync(clipboard); + if (files is { Length: > 0 }) + { + var filesKey = string.Join('\n', files); + if (!string.Equals(filesKey, _lastSyncedClipboardFilesKey, StringComparison.Ordinal)) + { + vm.SetClipboardFiles(files); + _lastSyncedClipboardFilesKey = filesKey; + _lastSyncedClipboardImageHash = null; + _lastSyncedClipboardText = null; + } + if (OperatingSystem.IsWindows()) + _lastSyncedClipboardSequenceNumber = RdpClipboardImageHelper.GetWindowsClipboardSequenceNumber(); + return; + } + + var image = await RdpClipboardImageHelper.TryReadLocalImageAsync(clipboard); + if (image != null && (image.PngBytes is { Length: > 0 } || image.DibBytes is { Length: > 0 })) + { + if (!string.Equals(image.Hash, _lastSyncedClipboardImageHash, StringComparison.Ordinal)) + { + if (image.DibBytes is { Length: > 0 }) + vm.SetClipboardImage(RdpBridgeClient.ClipboardImageFormatDib, image.DibBytes); + else if (image.PngBytes is { Length: > 0 }) + vm.SetClipboardImage(RdpBridgeClient.ClipboardImageFormatPng, image.PngBytes); + _lastSyncedClipboardImageHash = image.Hash; + _lastSyncedClipboardFilesKey = null; + _lastSyncedClipboardText = null; + } + if (OperatingSystem.IsWindows()) + _lastSyncedClipboardSequenceNumber = RdpClipboardImageHelper.GetWindowsClipboardSequenceNumber(); + return; + } + var text = await TryReadLocalClipboardTextAsync(); if (text == null || string.Equals(text, _lastSyncedClipboardText, StringComparison.Ordinal)) + { + if (OperatingSystem.IsWindows()) + _lastSyncedClipboardSequenceNumber = RdpClipboardImageHelper.GetWindowsClipboardSequenceNumber(); return; + } + + var (htmlBytes, rtfBytes) = await RdpClipboardImageHelper.TryReadLocalRichTextAsync(clipboard); + if ((htmlBytes is { Length: > 0 }) || (rtfBytes is { Length: > 0 })) + vm.SetClipboardRichText(text, htmlBytes, rtfBytes); + else + vm.SetClipboardText(text); - vm.SetClipboardText(text); _lastSyncedClipboardText = text; + _lastSyncedClipboardImageHash = null; + _lastSyncedClipboardFilesKey = null; + if (OperatingSystem.IsWindows()) + _lastSyncedClipboardSequenceNumber = RdpClipboardImageHelper.GetWindowsClipboardSequenceNumber(); + } + + private void OnRemoteClipboardImageReceived(uint imageFormat, byte[] data) + { + _ = ApplyRemoteClipboardImageAsync(imageFormat, data); + } + + private async Task ApplyRemoteClipboardImageAsync(uint imageFormat, byte[] data) + { + _applyingRemoteClipboardText = true; + try + { + var clipboard = TopLevel.GetTopLevel(this)?.Clipboard; + if (await RdpClipboardImageHelper.TryWriteLocalImageAsync(clipboard, imageFormat, data)) + { + _lastSyncedClipboardImageHash = imageFormat == RdpBridgeClient.ClipboardImageFormatPng + ? RdpClipboardImageHelper.ComputeHash(data, null) + : RdpClipboardImageHelper.ComputeHash(null, data); + _lastSyncedClipboardFilesKey = null; + _lastSyncedClipboardText = null; + if (OperatingSystem.IsWindows()) + _lastAppliedRemoteClipboardSequenceNumber = RdpClipboardImageHelper.GetWindowsClipboardSequenceNumber(); + } + } + catch + { + } + finally + { + _applyingRemoteClipboardText = false; + } + } + + private void OnRemoteClipboardFilesReceived(string[] paths) + { + _ = ApplyRemoteClipboardFilesAsync(paths); + } + + private async Task ApplyRemoteClipboardFilesAsync(string[] paths) + { + _applyingRemoteClipboardText = true; + try + { + var clipboard = TopLevel.GetTopLevel(this)?.Clipboard; + if (await RdpClipboardImageHelper.TryWriteLocalFilesAsync(clipboard, paths)) + { + _lastSyncedClipboardFilesKey = string.Join('\n', paths); + _lastSyncedClipboardImageHash = null; + _lastSyncedClipboardText = null; + if (OperatingSystem.IsWindows()) + _lastAppliedRemoteClipboardSequenceNumber = RdpClipboardImageHelper.GetWindowsClipboardSequenceNumber(); + } + } + catch + { + } + finally + { + _applyingRemoteClipboardText = false; + } + } + + private void StartClipboardListener() + { + if (OperatingSystem.IsWindows()) + { + if (_clipboardListener != null) + return; + + _clipboardListener = new WindowsClipboardListener(); + _clipboardListener.ClipboardChanged += () => + Dispatcher.UIThread.Post(() => _ = SyncLocalClipboardToRemoteAsync()); + return; + } + + if (_clipboardPollTimer != null) + return; + + _clipboardPollTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(800) }; + _clipboardPollTimer.Tick += (_, _) => _ = SyncLocalClipboardToRemoteAsync(); + _clipboardPollTimer.Start(); + } + + private void StopClipboardListener() + { + _clipboardListener?.Dispose(); + _clipboardListener = null; + _clipboardPollTimer?.Stop(); + _clipboardPollTimer = null; + } + + private void ResetClipboardSyncState() + { + _lastSyncedClipboardText = null; + _lastSyncedClipboardImageHash = null; + _lastSyncedClipboardFilesKey = null; + _lastSyncedClipboardSequenceNumber = null; + _lastAppliedRemoteClipboardSequenceNumber = null; + } + + private void OnViewportDragOver(object? sender, DragEventArgs e) + { + var hasFiles = e.DataTransfer.TryGetFiles()?.Any() == true; + e.DragEffects = hasFiles ? DragDropEffects.Copy : DragDropEffects.None; + e.Handled = true; + } + + private async void OnViewportDrop(object? sender, DragEventArgs e) + { + if (DataContext is not RdpViewModel vm || !vm.IsConnected || !vm.IsClipboardChannelReady) + return; + + var storageItems = e.DataTransfer.TryGetFiles(); + if (storageItems == null) + return; + + var paths = new System.Collections.Generic.List(); + foreach (var item in storageItems) + { + var localPath = item.Path.LocalPath; + if (!string.IsNullOrWhiteSpace(localPath) && + (System.IO.File.Exists(localPath) || System.IO.Directory.Exists(localPath))) + { + paths.Add(localPath); + } + } + + if (paths.Count == 0) + return; + + e.Handled = true; + vm.SetClipboardFiles(paths); + _lastSyncedClipboardFilesKey = string.Join('\n', paths); + await Task.Delay(150); + if (vm.IsConnected) + SendClipboardPasteShortcut(vm); } private async Task ApplyRemoteClipboardTextAsync(string text) diff --git a/Views/SessionEditDialog.axaml b/Views/SessionEditDialog.axaml index d7b27e1..a208e54 100644 --- a/Views/SessionEditDialog.axaml +++ b/Views/SessionEditDialog.axaml @@ -1720,6 +1720,9 @@ + Date: Tue, 24 Nov 2026 15:33:56 +0800 Subject: [PATCH 07/15] feat(rdp): add 3-mode RDP window workflow, 4-state immersive maximize, unified FullScreenConnectionBar, and multi-monitor/virtual screen suite Added: - 3-mode RdpWindowMode selector (Default / MultiTab / Standalone) in SessionEditDialog with backward compatibility for RdpOpenInStandaloneWindow. - Standalone multi-tab RDP window (RdpWorkspaceWindow) and session tree context menu actions to open RDP sessions in multi-tab or standalone windows. - Multi-monitor & virtual screen suite exclusive to DetachedTabWindow: FreeRDP dynamic multi-monitor layout (ABI v15, mixed DPI), secondary monitor windows (RdpMonitorWindow), slice surface renderer (RdpSliceSurface), cross-screen drag, ultrawide virtual dual-screen & PBP merge, and automatic single-monitor reset when moving back to multi-tab windows. - Session edit buttons in SessionTreeView and SessionManagerWindow, plus right-click context menus and AtomUI tooltips across window title bars and tabs. - Complete zh-CN and en-US localization in LocalizationService. Changed: - Unified all windows (MainWindow, DetachedTabWindow, RdpWorkspaceWindow, RdpMonitorWindow) on origin FullScreenConnectionBar with optional multi-tab and multi-monitor extensions and borderless Text buttons. - Maximizing DetachedTabWindow now enters immersive mode (hiding title bar while keeping taskbar) directly, unifying the 4-state window model (Minimize / Normal / Immersive Maximize / FullScreen). Fixed: - Eliminated duplicate tooltips, misaligned tab close buttons, and redundant taskbar-mode buttons while preserving upstream v0.1.79 desktop loading and reconnect overlays. Technical Approach: - Extend FullScreenConnectionBar with opt-in ShowTabSwitcher, ShowMultiMonitorButton, ShowFullScreenButton, and SetExternalPopupOpen without altering default MainWindow behavior; enforce single-monitor boundary in multi-tab containers via RdpView.ResetToSingleMonitor(). --- Controls/RdpSliceSurface.cs | 83 ++ Models/SessionInfo.cs | 28 +- Services/LocalizationService.cs | 44 +- Services/RdpBridgeClient.cs | 59 ++ ViewModels/MainWindowViewModel.cs | 28 +- ViewModels/RdpViewModel.cs | 19 + ViewModels/SessionEditViewModel.cs | 12 + ViewModels/SessionTreeViewModel.cs | 5 +- Views/DetachedTabWindow.axaml | 95 +- Views/DetachedTabWindow.axaml.cs | 40 + Views/FullScreenConnectionBar.axaml | 161 ++- Views/FullScreenConnectionBar.axaml.cs | 161 +++ Views/MainWindow.axaml.cs | 1 + Views/RdpMonitorWindow.axaml | 75 ++ Views/RdpMonitorWindow.axaml.cs | 453 +++++++++ Views/RdpView.axaml | 106 +- Views/RdpView.axaml.cs | 1248 +++++++++++++++++++----- Views/RdpWorkspaceWindow.axaml | 143 +++ Views/RdpWorkspaceWindow.axaml.cs | 358 +++++++ Views/SessionEditDialog.axaml | 34 +- Views/SessionEditDialog.axaml.cs | 2 + Views/SessionManagerWindow.axaml | 5 + Views/SessionManagerWindow.axaml.cs | 8 + Views/SessionTreeView.axaml | 6 + Views/SessionTreeView.axaml.cs | 6 + native/CxRdpBridge/cxrdp_bridge.h | 15 +- rdpbuild.ps1 | 18 + 27 files changed, 2850 insertions(+), 363 deletions(-) create mode 100644 Controls/RdpSliceSurface.cs create mode 100644 Views/RdpMonitorWindow.axaml create mode 100644 Views/RdpMonitorWindow.axaml.cs create mode 100644 Views/RdpWorkspaceWindow.axaml create mode 100644 Views/RdpWorkspaceWindow.axaml.cs create mode 100644 rdpbuild.ps1 diff --git a/Controls/RdpSliceSurface.cs b/Controls/RdpSliceSurface.cs new file mode 100644 index 0000000..7c83fcc --- /dev/null +++ b/Controls/RdpSliceSurface.cs @@ -0,0 +1,83 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media; +using Avalonia.Media.Imaging; + +namespace CxShell.Controls; + +/// +/// Renders a rectangular slice of a shared RDP with zero extra pixel copies. +/// +public sealed class RdpSliceSurface : Control +{ + private Bitmap? _source; + private Rect _sourceRect; + + public Bitmap? Source + { + get => _source; + set + { + if (ReferenceEquals(_source, value)) + return; + _source = value; + InvalidateVisual(); + } + } + + public Rect SourceRect + { + get => _sourceRect; + set + { + if (_sourceRect == value) + return; + _sourceRect = value; + InvalidateVisual(); + } + } + + public override void Render(DrawingContext context) + { + base.Render(context); + + if (_source == null || Bounds.Width <= 0 || Bounds.Height <= 0) + return; + + var bitmapSize = _source.PixelSize; + if (bitmapSize.Width <= 0 || bitmapSize.Height <= 0) + return; + + var src = _sourceRect.Width > 0 && _sourceRect.Height > 0 + ? _sourceRect + : new Rect(0, 0, bitmapSize.Width, bitmapSize.Height); + + if (src.X >= bitmapSize.Width || src.Y >= bitmapSize.Height) + { + context.FillRectangle(Brushes.Black, new Rect(0, 0, Bounds.Width, Bounds.Height)); + return; + } + + var clampedX = System.Math.Clamp(src.X, 0, bitmapSize.Width - 1); + var clampedY = System.Math.Clamp(src.Y, 0, bitmapSize.Height - 1); + var clampedW = System.Math.Clamp(src.Width, 1, bitmapSize.Width - clampedX); + var clampedH = System.Math.Clamp(src.Height, 1, bitmapSize.Height - clampedY); + + // Guard against bilinear edge bleeding from the adjacent monitor's right/bottom border + if (clampedX > 0 && clampedW > 2) + { + clampedX += 1; + clampedW -= 1; + } + if (clampedY > 0 && clampedH > 2) + { + clampedY += 1; + clampedH -= 1; + } + + context.DrawImage( + _source, + new Rect(clampedX, clampedY, clampedW, clampedH), + new Rect(0, 0, Bounds.Width, Bounds.Height)); + } +} diff --git a/Models/SessionInfo.cs b/Models/SessionInfo.cs index 9c73a9d..2242f30 100644 --- a/Models/SessionInfo.cs +++ b/Models/SessionInfo.cs @@ -155,7 +155,7 @@ public class ProxySettings : INotifyPropertyChanged public Guid Id { get; set; } = Guid.NewGuid(); public string Name { get; set; } = string.Empty; - [JsonConverter(typeof(JsonStringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public ProxyProtocol Protocol { get; set; } = ProxyProtocol.None; public string Host { get; set; } = string.Empty; @@ -163,7 +163,7 @@ public class ProxySettings : INotifyPropertyChanged public string Username { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; - [JsonConverter(typeof(JsonStringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public AuthMethod AuthMethod { get; set; } = AuthMethod.Password; public string PrivateKeyPath { get; set; } = string.Empty; @@ -228,7 +228,7 @@ public class SshTunnelRule { public Guid Id { get; set; } = Guid.NewGuid(); - [JsonConverter(typeof(JsonStringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public SshTunnelRuleType Type { get; set; } = SshTunnelRuleType.Local; public string SourceHost { get; set; } = "localhost"; @@ -379,7 +379,7 @@ public class SessionInfo public List ProxyServers { get; set; } = new(); public Guid? SelectedProxyId { get; set; } - [JsonConverter(typeof(JsonStringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public SessionProtocol Protocol { get; set; } = SessionProtocol.SSH; /// @@ -389,7 +389,7 @@ public class SessionInfo [JsonIgnore] public LocalTerminalProfile? LocalTerminalProfile { get; set; } - [JsonConverter(typeof(JsonStringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public AuthMethod AuthMethod { get; set; } = AuthMethod.Password; public string Password { get; set; } = string.Empty; @@ -522,9 +522,9 @@ public class SessionInfo public bool RunLoginScriptFile { get; set; } public string LoginScriptFilePath { get; set; } = string.Empty; public string LoginScriptParameters { get; set; } = string.Empty; - [JsonConverter(typeof(JsonStringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public LoginScriptExecutionMode LoginScriptExecutionMode { get; set; } = LoginScriptExecutionMode.SendText; - [JsonConverter(typeof(JsonStringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public LoginScriptExecutionTarget LoginScriptExecutionTarget { get; set; } = LoginScriptExecutionTarget.Remote; public string LoginScriptInterpreter { get; set; } = string.Empty; public string SshRemoteCommand { get; set; } = string.Empty; @@ -599,6 +599,20 @@ public int SshMonitorRefreshIntervalSeconds public string RdpColorQuality { get; set; } = "32"; /// Preferred RDP security mode: Auto, Negotiate, NLA, TLS or RDP. public string RdpSecurityMode { get; set; } = "Auto"; + /// RDP window mode: Default (main window tab), MultiTab (standalone multi-tab RDP window), or Standalone (detached single-session window with multi-monitor support). + public string RdpWindowMode { get; set; } = "Default"; + public bool RdpOpenInStandaloneWindow { get; set; } + + public string ResolveEffectiveRdpWindowMode() + { + if (string.Equals(RdpWindowMode, "MultiTab", StringComparison.OrdinalIgnoreCase)) + return "MultiTab"; + if (string.Equals(RdpWindowMode, "Standalone", StringComparison.OrdinalIgnoreCase)) + return "Standalone"; + if (string.Equals(RdpWindowMode, "Default", StringComparison.OrdinalIgnoreCase) && RdpOpenInStandaloneWindow) + return "MultiTab"; + return RdpOpenInStandaloneWindow ? "MultiTab" : "Default"; + } public bool RdpApplyKeyCombinations { get; set; } = true; public bool RdpSyncLockKeys { get; set; } = true; public bool RdpEnableClipboardLock { get; set; } = true; diff --git a/Services/LocalizationService.cs b/Services/LocalizationService.cs index 67057cb..31c2a34 100644 --- a/Services/LocalizationService.cs +++ b/Services/LocalizationService.cs @@ -171,7 +171,8 @@ public sealed class LocalizationService : INotifyPropertyChanged ["FullScreenBar.Pin"] = "Pin the connection bar", ["FullScreenBar.Unpin"] = "Unpin the connection bar (auto hide)", ["FullScreenBar.Minimize"] = "Minimize", - ["FullScreenBar.Restore"] = "Exit full screen", + ["FullScreenBar.Restore"] = "Restore window", + ["FullScreenBar.ToggleFullScreen"] = "Toggle full screen (F11)", ["FullScreenBar.Close"] = "Close this session", ["FullScreenBar.Quality"] = "Link quality", ["FullScreenBar.QualityGood"] = "Good", @@ -517,7 +518,8 @@ public sealed class LocalizationService : INotifyPropertyChanged ["FullScreenBar.Pin"] = "固定连接栏", ["FullScreenBar.Unpin"] = "取消固定(自动隐藏)", ["FullScreenBar.Minimize"] = "最小化", - ["FullScreenBar.Restore"] = "退出全屏", + ["FullScreenBar.Restore"] = "还原窗口", + ["FullScreenBar.ToggleFullScreen"] = "切换全屏 (F11)", ["FullScreenBar.Close"] = "关闭当前会话", ["FullScreenBar.Quality"] = "网络质量", ["FullScreenBar.QualityGood"] = "良好", @@ -2137,6 +2139,25 @@ private static void AddGeneratedTexts(Dictionary english, Dictio english["UiText.087"] = "Window size (W):"; english["UiText.088"] = "Resize screen (C):"; english["UiText.089"] = "Color quality (Q):"; + english["SessionEdit.RdpSecurityMode"] = "Security mode:"; + english["SessionEdit.RdpWindowModeSection"] = "Window Mode"; + english["SessionEdit.RdpWindowModeLabel"] = "Open Mode:"; + english["SessionEdit.RdpWindowMode.Default"] = "Default (Main window tab)"; + english["SessionEdit.RdpWindowMode.MultiTab"] = "Multi-tab window"; + english["SessionEdit.RdpWindowMode.Standalone"] = "Standalone window (Multi-monitor)"; + english["SessionEdit.RdpOpenInStandaloneWindow"] = "Open in standalone RDP multi-tab window"; + english["SessionEdit.RdpSyncLockKeys"] = "Sync CapsLock / NumLock / ScrollLock state"; + english["SessionEdit.RdpSyncLockKeysHint"] = "Automatically synchronize local lock key states to the remote session on connect or focus."; + english["SessionEdit.RdpEnableClipboardLock"] = "Enable clipboard large file locking (LockClipboardData)"; + english["SessionEdit.RdpEnableClipboardLockHint"] = "Lock clipboard file snapshots during large file transfers so copying other content does not abort transfers."; + english["Rdp.MultiMonitor"] = "Multi-Monitor"; + english["Rdp.MultiMonitorTip"] = "Multi-monitor / Virtual screen settings"; + english["Rdp.MoveToWorkspace"] = "Move to multi-tab RDP window (single monitor)"; + english["Rdp.OpenInWorkspace"] = "Open in multi-tab RDP window"; + english["Rdp.OpenInDetachedWindow"] = "Open in standalone window (multi-monitor)"; + english["Rdp.CloseTab"] = "Close tab"; + english["Rdp.CloseOtherTabs"] = "Close other tabs"; + english["Rdp.KeepTaskbar"] = "Keep taskbar"; english["UiText.090"] = "Devices"; english["UiText.091"] = "Apply key combinations on the remote computer"; english["UiText.092"] = "Share this computer's drives with the remote computer"; @@ -2403,6 +2424,25 @@ private static void AddGeneratedTexts(Dictionary english, Dictio chinese["UiText.087"] = "窗口大小(W):"; chinese["UiText.088"] = "改变屏幕大小(C):"; chinese["UiText.089"] = "颜色质量(Q):"; + chinese["SessionEdit.RdpSecurityMode"] = "安全模式:"; + chinese["SessionEdit.RdpWindowModeSection"] = "窗口模式"; + chinese["SessionEdit.RdpWindowModeLabel"] = "打开方式:"; + chinese["SessionEdit.RdpWindowMode.Default"] = "默认(主窗口标签页)"; + chinese["SessionEdit.RdpWindowMode.MultiTab"] = "多标签"; + chinese["SessionEdit.RdpWindowMode.Standalone"] = "独立窗体(支持多屏)"; + chinese["SessionEdit.RdpOpenInStandaloneWindow"] = "在独立的 RDP 多标签窗口中打开"; + chinese["SessionEdit.RdpSyncLockKeys"] = "同步 CapsLock / NumLock / ScrollLock 锁定键状态"; + chinese["SessionEdit.RdpSyncLockKeysHint"] = "连接或切入 RDP 窗口时自动将本地大小写与小键盘锁定状态同步到远端。"; + chinese["SessionEdit.RdpEnableClipboardLock"] = "启用剪贴板大文件锁定 (LockClipboardData)"; + chinese["SessionEdit.RdpEnableClipboardLockHint"] = "通过剪贴板传输大文件时锁定快照,防止中途复制其他内容导致传输中断。"; + chinese["Rdp.MultiMonitor"] = "多显示器"; + chinese["Rdp.MultiMonitorTip"] = "多显示器 / 虚拟屏幕设置"; + chinese["Rdp.MoveToWorkspace"] = "移入多标签 RDP 窗口(自动收敛为单屏)"; + chinese["Rdp.OpenInWorkspace"] = "在独立多标签窗口打开"; + chinese["Rdp.OpenInDetachedWindow"] = "在独立窗体打开(支持多屏)"; + chinese["Rdp.CloseTab"] = "关闭标签页"; + chinese["Rdp.CloseOtherTabs"] = "关闭其他标签页"; + chinese["Rdp.KeepTaskbar"] = "保留任务栏"; chinese["UiText.090"] = "设备"; chinese["UiText.091"] = "在远程计算机上应用密钥组合"; chinese["UiText.092"] = "与远程计算机分享该计算机的驱动器"; diff --git a/Services/RdpBridgeClient.cs b/Services/RdpBridgeClient.cs index 62d1759..94b9f17 100644 --- a/Services/RdpBridgeClient.cs +++ b/Services/RdpBridgeClient.cs @@ -12,6 +12,26 @@ namespace CxShell.Services; +public readonly record struct RdpMonitorRect( + int Left, + int Top, + int Width, + int Height, + int DesktopScaleFactor, + bool IsPrimary); + +[StructLayout(LayoutKind.Sequential)] +internal struct NativeMonitorRect +{ + public int Left; + public int Top; + public uint Width; + public uint Height; + public uint DesktopScaleFactor; + public uint DeviceScaleFactor; + public int IsPrimary; +} + public sealed class RdpFramebufferEventArgs : EventArgs { private Action? _release; @@ -83,6 +103,8 @@ public sealed class RdpBridgeClient : IDisposable private const uint ClipboardFilesCapability = 0x00008000; private const uint ClipboardRichTextCapability = 0x00010000; private const uint ClipboardLockCapability = 0x00020000; + private const uint MultiMonitorApiVersion = 15; + private const uint MultiMonitorCapability = 0x00040000; private static readonly object DebugLogLock = new(); private static readonly object NativeLoadFailureLock = new(); private static readonly bool DetailedDebugLogEnabled = IsEnvironmentFlagEnabled("CXSHELL_RDP_DEBUG_LOG"); @@ -109,6 +131,7 @@ public sealed class RdpBridgeClient : IDisposable private bool _supportsClipboardFiles; private bool _supportsClipboardRichText; private bool _supportsClipboardLock; + private bool _supportsMultiMonitor; private readonly object _frameSync = new(); private readonly RdpFrameComposer _frameComposer = new(enabled: FrameCoalescingEnabled, useCoverage: FrameCoverageEnabled); private RdpFramePresentationMode _frameMode = RdpFramePresentationMode.Auto; @@ -283,6 +306,8 @@ public void Connect( NativeMethods.cxrdp_set_clipboard_files_callback(_handle, _clipboardFilesCallback); if (_supportsClipboardLock) NativeMethods.cxrdp_set_clipboard_lock_enabled(_handle, session.RdpEnableClipboardLock ? 1 : 0); + _supportsMultiMonitor = nativeApiVersion >= MultiMonitorApiVersion && + (nativeCapabilities & MultiMonitorCapability) != 0; if (nativeApiVersion >= GfxApiVersion && (nativeCapabilities & GfxCapability) != 0) { var gfxRequested = GraphicsPipelineForcedOn || session.RdpGraphicsPipelineEnabled; @@ -754,6 +779,34 @@ public void SyncLockKeys(uint flags) NativeMethods.cxrdp_sync_lock_keys(_handle, flags); } + public bool TryResizeMonitors(IReadOnlyList monitors) + { + if (_handle == IntPtr.Zero || !_supportsMultiMonitor || monitors == null || monitors.Count == 0) + return false; + + var array = new NativeMonitorRect[Math.Min(monitors.Count, 16)]; + for (var i = 0; i < array.Length; i++) + { + var m = monitors[i]; + var clampedScale = Math.Clamp(m.DesktopScaleFactor, 100, 500); + var deviceScale = clampedScale >= 180 ? 180u : clampedScale >= 140 ? 140u : 100u; + array[i] = new NativeMonitorRect + { + Left = m.Left, + Top = m.Top, + Width = (uint)Math.Max(200, m.Width), + Height = (uint)Math.Max(200, m.Height), + DesktopScaleFactor = (uint)clampedScale, + DeviceScaleFactor = deviceScale, + IsPrimary = m.IsPrimary ? 1 : 0 + }; + } + + var rc = NativeMethods.cxrdp_resize_monitors(_handle, array, array.Length); + DebugLogDetailed($"multi-monitor resize count={array.Length} rc={rc}"); + return rc == 0; + } + /// /// Marks the session as interactive so the next presentation tick publishes /// the pending framebuffer immediately instead of waiting out a repaint @@ -1542,6 +1595,12 @@ public static extern int cxrdp_connect( [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern void cxrdp_disconnect(IntPtr handle); + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] + public static extern int cxrdp_resize_monitors( + IntPtr handle, + [In] NativeMonitorRect[] monitors, + int count); + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern void cxrdp_send_pointer(IntPtr handle, ushort flags, ushort x, ushort y); diff --git a/ViewModels/MainWindowViewModel.cs b/ViewModels/MainWindowViewModel.cs index 95c2b03..2f0489b 100644 --- a/ViewModels/MainWindowViewModel.cs +++ b/ViewModels/MainWindowViewModel.cs @@ -2560,7 +2560,17 @@ public async Task ConnectSession(SessionInfo session, string? passwordOverride, } } - private async Task ConnectRdpSession(SessionInfo session, string? passwordOverride) + public Task OpenRdpInWorkspaceWindowAsync(SessionInfo session) => + ConnectRdpSession(session, null, openInWorkspace: true, openInDetached: false); + + public Task OpenRdpInDetachedWindowAsync(SessionInfo session) => + ConnectRdpSession(session, null, openInWorkspace: false, openInDetached: true); + + private async Task ConnectRdpSession( + SessionInfo session, + string? passwordOverride, + bool? openInWorkspace = null, + bool openInDetached = false) { var password = string.IsNullOrEmpty(passwordOverride) ? GetSavedPassword(session) @@ -2573,11 +2583,25 @@ private async Task ConnectRdpSession(SessionInfo session, string? passwordOverri var rdp = new RdpViewModel(session, password); var tab = new TerminalTabViewModel(session, rdp); + RecordAudit(session, ConnectionAuditEventType.ConnectStarted); + + var effectiveWindowMode = session.ResolveEffectiveRdpWindowMode(); + if (openInDetached || (openInWorkspace == null && string.Equals(effectiveWindowMode, "Standalone", StringComparison.OrdinalIgnoreCase))) + { + Views.DetachedTabWindow.ShowFor(tab); + return; + } + + if (openInWorkspace ?? string.Equals(effectiveWindowMode, "MultiTab", StringComparison.OrdinalIgnoreCase)) + { + Views.RdpWorkspaceWindow.OpenTab(tab); + return; + } + tab.CloseRequested += CloseTab; tab.PropertyChanged += OnTerminalTabPropertyChanged; AddTabToActiveGroup(tab); SelectedTab = tab; - RecordAudit(session, ConnectionAuditEventType.ConnectStarted); IsTerminalFullScreen = false; ConnectionStatusText = "RDP ready"; diff --git a/ViewModels/RdpViewModel.cs b/ViewModels/RdpViewModel.cs index 9aaf688..1c155ab 100644 --- a/ViewModels/RdpViewModel.cs +++ b/ViewModels/RdpViewModel.cs @@ -49,6 +49,7 @@ private static int ResolveConnectTimeoutSeconds() [ObservableProperty] private int _remoteWidth; [ObservableProperty] private int _remoteHeight; [ObservableProperty] private bool _isFitToWindow = true; + [ObservableProperty] private bool _isMultiMonitorActive; [ObservableProperty] private int _screenScalePercent = 100; [ObservableProperty] private bool _isClipboardChannelReady; [ObservableProperty] private string _remoteClipboardText = string.Empty; @@ -92,6 +93,7 @@ private static int ResolveConnectTimeoutSeconds() public SessionInfo Session { get; } public string? Password { get; } public event Action? PointerShapeChanged; + public event Action? FramebufferInvalidated; public event Action? RemoteClipboardImageReceived; public event Action? RemoteClipboardFilesReceived; public double FixedScaleFactor => Math.Clamp(ScreenScalePercent, 10, 500) / 100.0; @@ -659,6 +661,17 @@ public void SetClipboardImage(uint imageFormat, byte[] data) _client.SetClipboardImage(imageFormat, data); } + public void SetClipboardImage(byte[]? pngBytes, byte[]? dibBytes) + { + if (!IsConnected) + return; + + if (dibBytes is { Length: > 0 }) + _client.SetClipboardImage(RdpBridgeClient.ClipboardImageFormatDib, dibBytes); + else if (pngBytes is { Length: > 0 }) + _client.SetClipboardImage(RdpBridgeClient.ClipboardImageFormatPng, pngBytes); + } + public void SetClipboardFiles(IReadOnlyList filePaths) { if (IsConnected) @@ -671,6 +684,11 @@ public void SyncLockKeys(uint flags) _client.SyncLockKeys(flags); } + public bool TryResizeMonitors(IReadOnlyList monitors) + { + return IsConnected && _client.TryResizeMonitors(monitors); + } + [RelayCommand] private void ToggleScaleMode() { @@ -730,6 +748,7 @@ private void OnFramebufferUpdated(object? sender, RdpFramebufferEventArgs e) // per frame while still giving the Image a new source instance, // which is what forces Avalonia to upload the changed pixels. Framebuffer = target; + FramebufferInvalidated?.Invoke(); RemoteWidth = e.Width; RemoteHeight = e.Height; IsDesktopLoading = false; diff --git a/ViewModels/SessionEditViewModel.cs b/ViewModels/SessionEditViewModel.cs index 8585d98..d0ad2cf 100644 --- a/ViewModels/SessionEditViewModel.cs +++ b/ViewModels/SessionEditViewModel.cs @@ -331,6 +331,8 @@ public readonly record struct AppearanceColorPalette( [ObservableProperty] private string _rdpFrameStrategy = "Auto"; [ObservableProperty] private string _rdpColorQuality = "32"; [ObservableProperty] private string _rdpSecurityMode = "Auto"; + [ObservableProperty] private string _rdpWindowMode = "Default"; + [ObservableProperty] private bool _rdpOpenInStandaloneWindow; [ObservableProperty] private bool _rdpApplyKeyCombinations = true; [ObservableProperty] private bool _rdpSyncLockKeys = true; [ObservableProperty] private bool _rdpEnableClipboardLock = true; @@ -1047,6 +1049,12 @@ public bool IsNumericKeypadModeForceNormal new SelectOption { Header = "TLS", Content = "TLS" }, new SelectOption { Header = "Standard RDP", Content = "RDP" } ]; + public ObservableCollection RdpWindowModeOptions { get; } = + [ + new SelectOption { Header = LocalizationService.Shared.Text("SessionEdit.RdpWindowMode.Default"), Content = "Default" }, + new SelectOption { Header = LocalizationService.Shared.Text("SessionEdit.RdpWindowMode.MultiTab"), Content = "MultiTab" }, + new SelectOption { Header = LocalizationService.Shared.Text("SessionEdit.RdpWindowMode.Standalone"), Content = "Standalone" } + ]; public ObservableCollection RdpAudioModeOptions { get; } = [ new SelectOption { Header = "Play on this computer", Content = "PlayLocal" }, @@ -1546,6 +1554,8 @@ public SessionEditViewModel(SessionInfo session) RdpFrameStrategy = RdpFramePresentationModes.Normalize(session.RdpFrameStrategy); RdpColorQuality = string.IsNullOrWhiteSpace(session.RdpColorQuality) ? "32" : session.RdpColorQuality; RdpSecurityMode = string.IsNullOrWhiteSpace(session.RdpSecurityMode) ? "Auto" : session.RdpSecurityMode; + RdpWindowMode = session.ResolveEffectiveRdpWindowMode(); + RdpOpenInStandaloneWindow = session.RdpOpenInStandaloneWindow; RdpApplyKeyCombinations = session.RdpApplyKeyCombinations; RdpSyncLockKeys = session.RdpSyncLockKeys; RdpEnableClipboardLock = session.RdpEnableClipboardLock; @@ -1859,6 +1869,8 @@ private void Save() session.RdpFrameStrategy = RdpFramePresentationModes.Normalize(RdpFrameStrategy); session.RdpColorQuality = RdpColorQuality; session.RdpSecurityMode = string.IsNullOrWhiteSpace(RdpSecurityMode) ? "Auto" : RdpSecurityMode; + session.RdpWindowMode = string.IsNullOrWhiteSpace(RdpWindowMode) ? "Default" : RdpWindowMode; + session.RdpOpenInStandaloneWindow = string.Equals(session.RdpWindowMode, "MultiTab", StringComparison.OrdinalIgnoreCase); session.RdpApplyKeyCombinations = RdpApplyKeyCombinations; session.RdpSyncLockKeys = RdpSyncLockKeys; session.RdpEnableClipboardLock = RdpEnableClipboardLock; diff --git a/ViewModels/SessionTreeViewModel.cs b/ViewModels/SessionTreeViewModel.cs index 87f79c0..2069249 100644 --- a/ViewModels/SessionTreeViewModel.cs +++ b/ViewModels/SessionTreeViewModel.cs @@ -260,7 +260,8 @@ public static void CopySessionValues(SessionInfo target, SessionInfo source) target.RdpFrameStrategy = source.RdpFrameStrategy; target.RdpColorQuality = source.RdpColorQuality; target.RdpSecurityMode = source.RdpSecurityMode; - target.RdpApplyKeyCombinations = source.RdpApplyKeyCombinations; + target.RdpWindowMode = source.RdpWindowMode; + target.RdpOpenInStandaloneWindow = source.RdpOpenInStandaloneWindow; target.RdpSyncLockKeys = source.RdpSyncLockKeys; target.RdpEnableClipboardLock = source.RdpEnableClipboardLock; target.RdpClipboardEnabled = source.RdpClipboardEnabled; @@ -1184,6 +1185,8 @@ private static SessionInfo CloneSession(SessionInfo source, string name) RdpFrameStrategy = source.RdpFrameStrategy, RdpColorQuality = source.RdpColorQuality, RdpSecurityMode = source.RdpSecurityMode, + RdpWindowMode = source.RdpWindowMode, + RdpOpenInStandaloneWindow = source.RdpOpenInStandaloneWindow, RdpApplyKeyCombinations = source.RdpApplyKeyCombinations, RdpSyncLockKeys = source.RdpSyncLockKeys, RdpEnableClipboardLock = source.RdpEnableClipboardLock, diff --git a/Views/DetachedTabWindow.axaml b/Views/DetachedTabWindow.axaml index 6a9f676..f389b26 100644 --- a/Views/DetachedTabWindow.axaml +++ b/Views/DetachedTabWindow.axaml @@ -1,7 +1,9 @@ - - - - - - + + + + + + + + + + + + + + + + @@ -51,13 +90,15 @@ IsVisible="{Binding $parent[Window].DataContext.IsTerminalSession, x:CompileBindings=False}"/> - diff --git a/Views/DetachedTabWindow.axaml.cs b/Views/DetachedTabWindow.axaml.cs index 4d2f070..c9a8077 100644 --- a/Views/DetachedTabWindow.axaml.cs +++ b/Views/DetachedTabWindow.axaml.cs @@ -45,7 +45,16 @@ public DetachedTabWindow() KeepTaskbarFullScreenButton.SetValue( AtomUI.Desktop.Controls.ToolTip.TipProperty, Services.LocalizationService.Shared.Text("Toolbar.FullScreenKeepTaskbarTip")); + DetachedMultiMonitorButton.SetValue( + AtomUI.Desktop.Controls.ToolTip.TipProperty, + Services.LocalizationService.Shared.Text("Rdp.MultiMonitorTip")); + MoveToWorkspaceButton.SetValue( + AtomUI.Desktop.Controls.ToolTip.TipProperty, + Services.LocalizationService.Shared.Text("Rdp.MoveToWorkspace")); Closed += OnClosed; + FullScreenConnectionBar.ToggleFullScreenRequested += ToggleFullScreen; + FullScreenConnectionBar.MultiMonitorRequested += anchor => + DetachedRdpView.ToggleMultiMonitorPopup(anchor, PlacementMode.Bottom, FullScreenConnectionBar.SetExternalPopupOpen); PropertyChanged += OnWindowPropertyChanged; AddHandler(KeyDownEvent, OnWindowKeyDown, RoutingStrategies.Tunnel, handledEventsToo: true); _dragWatchTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(120) }; @@ -66,6 +75,7 @@ public TerminalTabViewModel? Tab set { _tab = value; + FullScreenConnectionBar.ShowMultiMonitorButton = value?.IsRdpSession == true; DataContext = value; } } @@ -198,6 +208,13 @@ private void OnWindowPropertyChanged(object? sender, AvaloniaPropertyChangedEven return; } + if (state == WindowState.Maximized && !_keepTaskbarFullScreen.IsActive) + { + _keepTaskbarFullScreen.Enter(); + UpdateConnectionBarState(); + return; + } + // Another full screen path (the caption button, F11, or a window manager // shortcut) took over, so hand the title bar back instead of leaving the // window stuck in a borderless maximized state. @@ -305,6 +322,27 @@ private void OnConnectionBarPinnedChanged(object? sender, EventArgs e) SessionTreeViewModel.PersistSharedSettings(); } + private void OnDetachedMultiMonitorClick(object? sender, RoutedEventArgs e) + { + if (sender is Control anchor) + DetachedRdpView.ToggleMultiMonitorPopup(anchor, PlacementMode.Bottom); + } + + private void OnMoveToWorkspaceClick(object? sender, RoutedEventArgs e) + { + if (_disposed || _tab is not { IsRdpSession: true } tab) + return; + + DetachedRdpView.ResetToSingleMonitor(); + _reattach = null; + _closeTab = null; + _tab = null; + DataContext = null; + _disposed = true; + RdpWorkspaceWindow.OpenTab(tab); + Close(); + } + private void OnKeepTaskbarFullScreenClick(object? sender, RoutedEventArgs e) { if (_keepTaskbarFullScreen.IsActive) @@ -435,6 +473,8 @@ private void TryReattachAtCursor() // The main window owns the tab now. Close this window without letting // the close path dispose the session. + if (_tab?.IsRdpSession == true) + DetachedRdpView.ResetToSingleMonitor(); _reattach = null; _closeTab = null; _tab = null; diff --git a/Views/FullScreenConnectionBar.axaml b/Views/FullScreenConnectionBar.axaml index effbaef..aae9960 100644 --- a/Views/FullScreenConnectionBar.axaml +++ b/Views/FullScreenConnectionBar.axaml @@ -2,6 +2,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:atom="https://atomui.net" xmlns:antdicons="https://atomui.net/icons/antdesign" + xmlns:views="using:CxShell.Views" x:Class="CxShell.Views.FullScreenConnectionBar" HorizontalAlignment="Center" VerticalAlignment="Top" @@ -26,7 +27,7 @@ BorderBrush="{atom:SharedTokenResource ColorBorderSecondary}" BorderThickness="1" BoxShadow="0 6 18 0 #40000000"> - + + + diff --git a/Views/RdpMonitorWindow.axaml.cs b/Views/RdpMonitorWindow.axaml.cs new file mode 100644 index 0000000..8c6535c --- /dev/null +++ b/Views/RdpMonitorWindow.axaml.cs @@ -0,0 +1,453 @@ +using System; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Platform; +using CxShell.ViewModels; + +namespace CxShell.Views; + +public partial class RdpMonitorWindow : AtomUI.Desktop.Controls.Window +{ + private readonly RdpView _ownerView; + private readonly RdpViewModel _vm; + private readonly Screen _screen; + private readonly int _monitorIndex; + private readonly Action _onCloseRequested; + private Rect _virtualSliceRect; + private bool _keepTaskbar; + private bool _isWindowed; + private bool _updatingGeometry; + private bool _isClosingProgrammatically; + private ushort _buttonFlags; + private double _pendingWheelY; + private ushort _lastRemoteX; + private ushort _lastRemoteY; + + public RdpMonitorWindow() + { + InitializeComponent(); + _ownerView = null!; + _vm = null!; + _screen = null!; + _onCloseRequested = _ => { }; + } + + public RdpMonitorWindow( + RdpView ownerView, + RdpViewModel vm, + Screen screen, + int monitorIndex, + Rect virtualSliceRect, + Action onCloseRequested, + bool startWindowed = false, + string? customTitle = null) + { + InitializeComponent(); + _ownerView = ownerView; + _vm = vm; + _screen = screen; + _monitorIndex = monitorIndex; + _virtualSliceRect = virtualSliceRect; + _onCloseRequested = onCloseRequested; + _isWindowed = startWindowed; + + AddHandler(KeyDownEvent, OnMonitorKeyDown, RoutingStrategies.Tunnel); + AddHandler(KeyUpEvent, OnMonitorKeyUp, RoutingStrategies.Tunnel); + AddHandler(DragDrop.DragOverEvent, (_, e) => _ownerView.ForwardDragOver(e)); + AddHandler(DragDrop.DropEvent, (_, e) => _ownerView.ForwardDrop(e)); + GotFocus += (_, _) => _ownerView.ForwardGotFocus(); + LostFocus += (_, _) => _ownerView.ForwardLostFocus(); + PropertyChanged += OnWindowPropertyChanged; + + var scalePct = (int)Math.Round(screen.Scaling * 100); + var titleText = customTitle ?? $"屏幕 {monitorIndex + 1} · {screen.Bounds.Width}×{screen.Bounds.Height} · {scalePct}%"; + Title = titleText; + + FloatingBar.Endpoint = titleText; + FloatingBar.CloseToolTip = "关闭此屏"; + FloatingBar.MinimizeRequested += (_, _) => WindowState = WindowState.Minimized; + FloatingBar.RestoreRequested += (_, _) => OnFloatingBarRestoreRequested(); + FloatingBar.ToggleFullScreenRequested += OnFloatingBarToggleFullScreenRequested; + FloatingBar.TaskbarModeToggleRequested += OnToggleImmersiveModeClick; + FloatingBar.CloseRequested += (_, _) => _onCloseRequested(_monitorIndex); + FloatingBar.InteractionCompleted += () => SliceSurface.Focus(); + FloatingBar.DragRestoreRequested += e => + { + if (!_isWindowed) + { + _isWindowed = true; + ApplyWindowGeometry(); + BeginMoveDrag(e); + e.Handled = true; + return; + } + + if (WindowState is WindowState.Maximized or WindowState.FullScreen) + { + WindowState = WindowState.Normal; + BeginMoveDrag(e); + e.Handled = true; + } + }; + + ApplyWindowGeometry(); + UpdateSlice(_virtualSliceRect); + + _vm.FramebufferInvalidated += OnFramebufferInvalidated; + _vm.PropertyChanged += OnViewModelPropertyChanged; + Closed += (_, _) => + { + FloatingBar?.StopTimer(); + _vm.FramebufferInvalidated -= OnFramebufferInvalidated; + _vm.PropertyChanged -= OnViewModelPropertyChanged; + if (!_isClosingProgrammatically) + { + _isClosingProgrammatically = true; + _onCloseRequested(_monitorIndex); + } + }; + } + + public void CloseProgrammatically() + { + _isClosingProgrammatically = true; + Close(); + } + + private void OnMonitorKeyDown(object? sender, KeyEventArgs e) + { + if (e.Key == Key.F11) + { + ToggleImmersiveFullScreen(); + e.Handled = true; + return; + } + + _ownerView.ForwardKeyDown(e); + } + + private void OnMonitorKeyUp(object? sender, KeyEventArgs e) + { + _ownerView.ForwardKeyUp(e); + } + + public int MonitorIndex => _monitorIndex; + + public void UpdateSlice(Rect virtualSliceRect) + { + _virtualSliceRect = virtualSliceRect; + SliceSurface.Source = _vm.Framebuffer; + SliceSurface.SourceRect = virtualSliceRect; + SliceSurface.InvalidateVisual(); + } + + public void SetRemoteCursor(Cursor cursor) + { + SliceSurface.Cursor = cursor; + } + + private void OnWindowPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e) + { + if (_updatingGeometry || !_isWindowed || e.Property != WindowStateProperty) + return; + + var state = WindowState; + var isImmersive = state is WindowState.Maximized or WindowState.FullScreen; + IsTitleBarVisible = !isImmersive; + WindowDecorations = state == WindowState.FullScreen + ? WindowDecorations.None + : WindowDecorations.Full; + FloatingBar.ShowMinimizeButton = true; + FloatingBar.RestoreToolTip = "还原窗口"; + FloatingBar.FullScreenToolTip = "切换全屏 (F11)"; + FloatingBar.TaskbarModeLabel = "保留任务栏"; + FloatingBar.SetImmersiveActive(isImmersive); + } + + private void ApplyWindowGeometry() + { + _updatingGeometry = true; + try + { + var targetScreen = _monitorIndex >= 100 && IsVisible + ? (Screens.ScreenFromWindow(this) ?? _screen) + : _screen; + var scaling = targetScreen.Scaling > 0 ? targetScreen.Scaling : 1.0; + + if (_isWindowed) + { + WindowState = WindowState.Normal; + IsTitleBarVisible = true; + WindowDecorations = WindowDecorations.Full; + CanResize = true; + ShowInTaskbar = true; + var area = targetScreen.WorkingArea; + var w = Math.Max(640, area.Width * 0.78); + var h = Math.Max(420, area.Height * 0.78); + Position = new PixelPoint( + area.X + (int)((area.Width - w) / 2), + area.Y + (int)((area.Height - h) / 2)); + Width = w / scaling; + Height = h / scaling; + FloatingBar.ShowMinimizeButton = true; + FloatingBar.RestoreToolTip = "还原窗口"; + FloatingBar.FullScreenToolTip = "切换全屏 (F11)"; + FloatingBar.TaskbarModeLabel = "保留任务栏"; + FloatingBar.SetImmersiveActive(false); + return; + } + + WindowState = WindowState.Normal; + IsTitleBarVisible = false; + WindowDecorations = WindowDecorations.None; + CanResize = false; + ShowInTaskbar = false; + var rect = _keepTaskbar ? targetScreen.WorkingArea : targetScreen.Bounds; + Position = new PixelPoint(rect.X, rect.Y); + Width = rect.Width / scaling; + Height = rect.Height / scaling; + FloatingBar.ShowMinimizeButton = false; + FloatingBar.RestoreToolTip = "窗口化"; + FloatingBar.FullScreenToolTip = "切换窗口化 / 沉浸全屏 (F11)"; + FloatingBar.TaskbarModeLabel = _keepTaskbar ? "真全屏" : "保留任务栏"; + FloatingBar.SetImmersiveActive(true); + } + finally + { + _updatingGeometry = false; + } + } + + private void OnFramebufferInvalidated() + { + SliceSurface.Source = _vm.Framebuffer; + SliceSurface.InvalidateVisual(); + } + + private void OnViewModelPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(RdpViewModel.Framebuffer)) + { + SliceSurface.Source = _vm.Framebuffer; + SliceSurface.InvalidateVisual(); + } + } + + private void OnFloatingBarRestoreRequested() + { + if (!_isWindowed) + { + _isWindowed = true; + ApplyWindowGeometry(); + } + else if (WindowState is WindowState.Maximized or WindowState.FullScreen) + { + WindowState = WindowState.Normal; + } + + SliceSurface.Focus(); + } + + private void OnFloatingBarToggleFullScreenRequested() + { + if (_isWindowed) + { + if (WindowState == WindowState.FullScreen) + { + WindowState = WindowState.Normal; + } + else + { + _isWindowed = false; + _keepTaskbar = false; + ApplyWindowGeometry(); + } + } + else + { + _isWindowed = true; + ApplyWindowGeometry(); + } + + SliceSurface.Focus(); + } + + private void ToggleImmersiveFullScreen() + { + if (_isWindowed) + { + if (WindowState == WindowState.FullScreen) + { + WindowState = WindowState.Normal; + } + else + { + _isWindowed = false; + _keepTaskbar = false; + ApplyWindowGeometry(); + } + } + else + { + _isWindowed = true; + ApplyWindowGeometry(); + } + + SliceSurface.Focus(); + } + + private void OnToggleImmersiveModeClick() + { + if (_isWindowed) + { + _isWindowed = false; + _keepTaskbar = true; + } + else + { + _keepTaskbar = !_keepTaskbar; + } + + ApplyWindowGeometry(); + } + + private void OnEnterKeepTaskbarClick(object? sender, RoutedEventArgs e) + { + _isWindowed = false; + _keepTaskbar = true; + ApplyWindowGeometry(); + SliceSurface.Focus(); + } + + private void OnEnterImmersiveClick(object? sender, RoutedEventArgs e) + { + _isWindowed = false; + _keepTaskbar = false; + ApplyWindowGeometry(); + SliceSurface.Focus(); + } + + public bool TryMapScreenPoint(PixelPoint screenPoint, out ushort remoteX, out ushort remoteY) + { + remoteX = 0; + remoteY = 0; + var bounds = SliceSurface.Bounds; + if (bounds.Width <= 0 || bounds.Height <= 0 || _virtualSliceRect.Width <= 0 || _virtualSliceRect.Height <= 0) + return false; + + var topLeft = SliceSurface.PointToScreen(new Point(0, 0)); + var bottomRight = SliceSurface.PointToScreen(new Point(bounds.Width, bounds.Height)); + var sw = bottomRight.X - topLeft.X; + var sh = bottomRight.Y - topLeft.Y; + if (sw <= 0 || sh <= 0 || + screenPoint.X < topLeft.X || screenPoint.X > bottomRight.X || + screenPoint.Y < topLeft.Y || screenPoint.Y > bottomRight.Y) + { + return false; + } + + var relX = Math.Clamp((double)(screenPoint.X - topLeft.X) / sw, 0, 1); + var relY = Math.Clamp((double)(screenPoint.Y - topLeft.Y) / sh, 0, 1); + remoteX = (ushort)Math.Clamp((int)Math.Round(_virtualSliceRect.X + relX * _virtualSliceRect.Width), 0, ushort.MaxValue); + remoteY = (ushort)Math.Clamp((int)Math.Round(_virtualSliceRect.Y + relY * _virtualSliceRect.Height), 0, ushort.MaxValue); + return true; + } + + private bool TryMapPointer(PointerEventArgs e, out ushort remoteX, out ushort remoteY, bool allowFallbackOnGap = false) + { + remoteX = 0; + remoteY = 0; + var bounds = SliceSurface.Bounds; + if (bounds.Width <= 0 || bounds.Height <= 0 || _virtualSliceRect.Width <= 0 || _virtualSliceRect.Height <= 0) + return false; + + var pos = e.GetPosition(SliceSurface); + if (pos.X < 0 || pos.X > bounds.Width || pos.Y < 0 || pos.Y > bounds.Height) + { + var screenPt = SliceSurface.PointToScreen(pos); + if (_ownerView.TryMapGlobalScreenPoint(screenPt, out remoteX, out remoteY)) + { + _lastRemoteX = remoteX; + _lastRemoteY = remoteY; + return true; + } + + if (allowFallbackOnGap) + { + remoteX = _lastRemoteX; + remoteY = _lastRemoteY; + return true; + } + + return false; + } + + var relX = Math.Clamp(pos.X / bounds.Width, 0, 1); + var relY = Math.Clamp(pos.Y / bounds.Height, 0, 1); + var vx = _virtualSliceRect.X + relX * _virtualSliceRect.Width; + var vy = _virtualSliceRect.Y + relY * _virtualSliceRect.Height; + remoteX = (ushort)Math.Clamp((int)Math.Round(vx), 0, ushort.MaxValue); + remoteY = (ushort)Math.Clamp((int)Math.Round(vy), 0, ushort.MaxValue); + _lastRemoteX = remoteX; + _lastRemoteY = remoteY; + return true; + } + + private void OnSurfacePointerMoved(object? sender, PointerEventArgs e) + { + if (TryMapPointer(e, out var x, out var y)) + _vm.SendPointer((ushort)(0x0800 | _buttonFlags), x, y); + } + + private void OnSurfacePointerPressed(object? sender, PointerPressedEventArgs e) + { + SliceSurface.Focus(); + _ownerView.RequestClipboardSync(); + if (!TryMapPointer(e, out var x, out var y)) + return; + + var point = e.GetCurrentPoint(SliceSurface); + ushort flag = 0x1000; // left button (also covers touch/pen primary tap) + if (point.Properties.IsRightButtonPressed) + flag = 0x2000; + else if (point.Properties.IsMiddleButtonPressed) + flag = 0x4000; + + _buttonFlags |= flag; + _vm.SendPointer((ushort)(0x8000 | flag), x, y); + } + + private void OnSurfacePointerReleased(object? sender, PointerReleasedEventArgs e) + { + if (!TryMapPointer(e, out var x, out var y, allowFallbackOnGap: true)) + return; + + ushort flag = e.InitialPressMouseButton switch + { + MouseButton.Right => 0x2000, + MouseButton.Middle => 0x4000, + _ => 0x1000 + }; + + _buttonFlags = (ushort)(_buttonFlags & ~flag); + _vm.SendPointer(flag, x, y); + } + + private void OnSurfacePointerWheelChanged(object? sender, PointerWheelEventArgs e) + { + if (!TryMapPointer(e, out var x, out var y)) + return; + + var notches = CxShell.Services.RdpWheelInput.TakeNotches(ref _pendingWheelY, e.Delta.Y); + if (notches != 0) + { + var wheelFlag = CxShell.Services.RdpWheelInput.GetNotchFlags(notches); + for (var i = 0; i < Math.Abs(notches); i++) + _vm.SendPointer(wheelFlag, x, y); + } + + e.Handled = true; + } +} diff --git a/Views/RdpView.axaml b/Views/RdpView.axaml index 6598e35..3fc560a 100644 --- a/Views/RdpView.axaml +++ b/Views/RdpView.axaml @@ -1,6 +1,7 @@ - + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Views/RdpWorkspaceWindow.axaml.cs b/Views/RdpWorkspaceWindow.axaml.cs new file mode 100644 index 0000000..d1057a5 --- /dev/null +++ b/Views/RdpWorkspaceWindow.axaml.cs @@ -0,0 +1,358 @@ +using System; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Media; +using Avalonia.VisualTree; +using CommunityToolkit.Mvvm.ComponentModel; +using CxShell.ViewModels; + +namespace CxShell.Views; + +public partial class RdpWorkspaceTabItem : ObservableObject +{ + private static readonly IBrush SelectedBrush = new SolidColorBrush(Color.Parse("#2B3440")); + private static readonly IBrush FloatingSelectedBrush = new SolidColorBrush(Color.Parse("#4464D8FF")); + private static readonly IBrush FloatingUnselectedBrush = new SolidColorBrush(Color.Parse("#1FFFFFFF")); + private static readonly IBrush UnselectedBrush = Brushes.Transparent; + + public RdpWorkspaceTabItem(TerminalTabViewModel tab) + { + Tab = tab; + } + + public TerminalTabViewModel Tab { get; } + public string Title => Tab.Title; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(TabBackground))] + [NotifyPropertyChangedFor(nameof(FloatingTabBackground))] + [NotifyPropertyChangedFor(nameof(TitleFontWeight))] + private bool _isSelected; + + public IBrush TabBackground => IsSelected ? SelectedBrush : UnselectedBrush; + public IBrush FloatingTabBackground => IsSelected ? FloatingSelectedBrush : FloatingUnselectedBrush; + public FontWeight TitleFontWeight => IsSelected ? FontWeight.SemiBold : FontWeight.Normal; +} + +/// +/// Standalone multi-tab window dedicated to hosting RDP sessions outside the main window. +/// +public partial class RdpWorkspaceWindow : AtomUI.Desktop.Controls.Window +{ + private static RdpWorkspaceWindow? _instance; + private readonly ObservableCollection _tabs = []; + private WindowState _windowStateBeforeFullScreen = WindowState.Normal; + private RdpViewModel? _selectedRdpVm; + + public RdpWorkspaceWindow() + { + InitializeComponent(); + TabStripItems.ItemsSource = _tabs; + RdpViewsItems.ItemsSource = _tabs; + + FloatingBar.TabItemsSource = _tabs; + FloatingBar.TabSelected += item => + { + if (item is RdpWorkspaceTabItem tabItem) + SelectTab(tabItem); + }; + FloatingBar.TabCloseRequested += item => + { + if (item is RdpWorkspaceTabItem tabItem) + CloseTabItem(tabItem); + }; + FloatingBar.MultiMonitorRequested += anchor => + GetSelectedRdpView()?.ToggleMultiMonitorPopup(anchor, PlacementMode.Bottom, FloatingBar.SetExternalPopupOpen); + FloatingBar.MinimizeRequested += (_, _) => WindowState = WindowState.Minimized; + FloatingBar.RestoreRequested += (_, _) => WindowState = WindowState.Normal; + FloatingBar.ToggleFullScreenRequested += ToggleFullScreen; + FloatingBar.CloseRequested += (_, _) => Close(); + FloatingBar.DragRestoreRequested += e => + { + if (WindowState is WindowState.Maximized or WindowState.FullScreen) + { + WindowState = WindowState.Normal; + BeginMoveDrag(e); + e.Handled = true; + } + }; + + Closed += OnClosed; + PropertyChanged += OnWindowPropertyChanged; + AddHandler(KeyDownEvent, OnWindowKeyDown, RoutingStrategies.Tunnel, handledEventsToo: true); + } + + public static void OpenTab(TerminalTabViewModel tab) + { + var window = _instance; + if (window == null) + { + window = new RdpWorkspaceWindow(); + _instance = window; + window.Show(); + } + + window.AddAndSelectTab(tab); + + if (window.WindowState == WindowState.Minimized) + window.WindowState = WindowState.Normal; + + window.Activate(); + } + + public static void CloseAll() + { + var window = _instance; + _instance = null; + window?.Close(); + } + + private void AddAndSelectTab(TerminalTabViewModel tab) + { + var item = new RdpWorkspaceTabItem(tab); + _tabs.Add(item); + SelectTab(item); + } + + private void SelectTab(RdpWorkspaceTabItem item) + { + GetSelectedRdpView()?.CloseMultiMonitorPopup(); + + foreach (var existing in _tabs) + existing.IsSelected = ReferenceEquals(existing, item); + + if (_selectedRdpVm != null) + { + _selectedRdpVm.PropertyChanged -= OnSelectedRdpPropertyChanged; + _selectedRdpVm = null; + } + + if (item.Tab.Rdp is { } rdp) + { + _selectedRdpVm = rdp; + rdp.PropertyChanged += OnSelectedRdpPropertyChanged; + } + + UpdateMultiMonitorButtonState(); + } + + private RdpView? GetSelectedRdpView() + { + var selected = _tabs.FirstOrDefault(t => t.IsSelected); + if (selected?.Tab.Rdp is not { } rdp) + return null; + + return RdpViewsItems.GetVisualDescendants() + .OfType() + .FirstOrDefault(v => ReferenceEquals(v.DataContext, rdp)); + } + + private void OnSelectedRdpPropertyChanged(object? sender, PropertyChangedEventArgs e) + { + if (e.PropertyName is nameof(RdpViewModel.IsConnected) or nameof(RdpViewModel.IsMultiMonitorActive)) + UpdateMultiMonitorButtonState(); + } + + private void UpdateMultiMonitorButtonState() + { + var connected = _selectedRdpVm?.IsConnected == true; + var active = _selectedRdpVm?.IsMultiMonitorActive == true; + FloatingBar.IsMultiMonitorEnabled = connected; + FloatingBar.IsMultiMonitorActive = active; + if (TitleBarMultiMonitorButton != null) + TitleBarMultiMonitorButton.IsEnabled = connected; + } + + private void OnTitleBarMultiMonitorClick(object? sender, RoutedEventArgs e) + { + if (sender is Control anchor) + GetSelectedRdpView()?.ToggleMultiMonitorPopup(anchor, PlacementMode.Bottom); + } + + private void DetachTabItem(RdpWorkspaceTabItem item) + { + var wasSelected = item.IsSelected; + var index = _tabs.IndexOf(item); + if (index < 0) + return; + + _tabs.RemoveAt(index); + DetachedTabWindow.ShowFor(item.Tab); + + if (_tabs.Count == 0) + { + Close(); + return; + } + + if (wasSelected) + { + var nextIndex = Math.Min(index, _tabs.Count - 1); + SelectTab(_tabs[nextIndex]); + } + } + + private void CloseTabItem(RdpWorkspaceTabItem item) + { + var wasSelected = item.IsSelected; + var index = _tabs.IndexOf(item); + if (index < 0) + return; + + _tabs.RemoveAt(index); + try + { + item.Tab.Dispose(); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"RDP workspace tab cleanup failed: {ex.Message}"); + } + + if (_tabs.Count == 0) + { + Close(); + return; + } + + if (wasSelected) + { + var nextIndex = Math.Min(index, _tabs.Count - 1); + SelectTab(_tabs[nextIndex]); + } + } + + private void TabItem_OnPointerPressed(object? sender, PointerPressedEventArgs e) + { + if (e.Source is Control source && IsInsideButton(source)) + return; + + if (sender is Control { DataContext: RdpWorkspaceTabItem item }) + { + SelectTab(item); + e.Handled = true; + } + } + + private static bool IsInsideButton(Control? control) + { + while (control != null) + { + if (control is Button) + return true; + control = control.Parent as Control; + } + + return false; + } + + private void DetachTabButton_OnClick(object? sender, RoutedEventArgs e) + { + if (sender is Control { DataContext: RdpWorkspaceTabItem item }) + { + e.Handled = true; + DetachTabItem(item); + } + } + + private void CloseOtherTabsButton_OnClick(object? sender, RoutedEventArgs e) + { + if (sender is Control { DataContext: RdpWorkspaceTabItem keep }) + { + e.Handled = true; + foreach (var other in _tabs.Where(t => !ReferenceEquals(t, keep)).ToList()) + CloseTabItem(other); + } + } + + private void CloseTabButton_OnClick(object? sender, RoutedEventArgs e) + { + if (sender is Control { DataContext: RdpWorkspaceTabItem item }) + { + e.Handled = true; + CloseTabItem(item); + } + } + + private void OnClosed(object? sender, EventArgs e) + { + FloatingBar?.StopTimer(); + if (_selectedRdpVm != null) + { + _selectedRdpVm.PropertyChanged -= OnSelectedRdpPropertyChanged; + _selectedRdpVm = null; + } + if (ReferenceEquals(_instance, this)) + _instance = null; + + foreach (var item in _tabs.ToArray()) + { + try + { + item.Tab.Dispose(); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"RDP workspace tab cleanup failed: {ex.Message}"); + } + } + + _tabs.Clear(); + } + + private void OnWindowPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e) + { + if (e.Property != WindowStateProperty) + return; + + var state = WindowState; + if (state != WindowState.FullScreen) + _windowStateBeforeFullScreen = state; + + var isImmersive = state is WindowState.Maximized or WindowState.FullScreen; + IsTitleBarVisible = !isImmersive; + WindowDecorations = state == WindowState.FullScreen + ? WindowDecorations.None + : WindowDecorations.Full; + FloatingBar?.SetImmersiveActive(isImmersive); + } + + private void OnWindowKeyDown(object? sender, KeyEventArgs e) + { + if (e.Key == Key.Escape && WindowState == WindowState.FullScreen) + { + ExitFullScreen(); + e.Handled = true; + return; + } + + if (e.Key != Key.F11) + return; + + ToggleFullScreen(); + e.Handled = true; + } + + private void ToggleFullScreen() + { + if (WindowState == WindowState.FullScreen) + ExitFullScreen(); + else + WindowState = WindowState.FullScreen; + } + + private void ExitFullScreen() + { + if (WindowState != WindowState.FullScreen) + return; + + WindowState = _windowStateBeforeFullScreen == WindowState.FullScreen + ? WindowState.Normal + : _windowStateBeforeFullScreen; + } +} diff --git a/Views/SessionEditDialog.axaml b/Views/SessionEditDialog.axaml index a208e54..3560513 100644 --- a/Views/SessionEditDialog.axaml +++ b/Views/SessionEditDialog.axaml @@ -1700,6 +1700,32 @@ + + + + + + + + - - diff --git a/Views/SessionEditDialog.axaml.cs b/Views/SessionEditDialog.axaml.cs index afec1d1..65e3847 100644 --- a/Views/SessionEditDialog.axaml.cs +++ b/Views/SessionEditDialog.axaml.cs @@ -452,6 +452,7 @@ private bool SaveCurrentSession() vm.RdpFrameStrategy = GetSelectedOptionText(RdpFrameStrategySelect, vm.RdpFrameStrategy); vm.RdpColorQuality = GetSelectedOptionText(RdpColorQualitySelect, vm.RdpColorQuality); vm.RdpSecurityMode = GetSelectedOptionText(RdpSecurityModeSelect, vm.RdpSecurityMode); + vm.RdpWindowMode = GetSelectedOptionText(RdpWindowModeSelect, vm.RdpWindowMode); vm.RdpAudioMode = GetSelectedOptionText(RdpAudioModeSelect, vm.RdpAudioMode); vm.VncDisplayMode = GetSelectedOptionText(VncDisplayModeSelect, vm.VncDisplayMode); vm.VncResizeMode = GetSelectedOptionText(VncResizeModeSelect, vm.VncResizeMode); @@ -2765,6 +2766,7 @@ private void SetSelectedRdpOptions() SelectOption(RdpFrameStrategySelect, vm.RdpFrameStrategy); SelectOption(RdpColorQualitySelect, vm.RdpColorQuality); SelectOption(RdpSecurityModeSelect, vm.RdpSecurityMode); + SelectOption(RdpWindowModeSelect, vm.RdpWindowMode); SelectOption(RdpAudioModeSelect, vm.RdpAudioMode); } diff --git a/Views/SessionManagerWindow.axaml b/Views/SessionManagerWindow.axaml index af10c21..9f76ca8 100644 --- a/Views/SessionManagerWindow.axaml +++ b/Views/SessionManagerWindow.axaml @@ -25,6 +25,11 @@ + + vm.MainWindow.OpenRdpInWorkspaceWindowAsync(rdpSession), vm.CanUseSelectedSession); + AddItem(LocalizationService.Shared.Text("Rdp.OpenInDetachedWindow"), () => vm.MainWindow.OpenRdpInDetachedWindowAsync(rdpSession), vm.CanUseSelectedSession); + } AddItem(vm.PropertiesText, () => { OnEditClick(anchor, new RoutedEventArgs()); diff --git a/native/CxRdpBridge/cxrdp_bridge.h b/native/CxRdpBridge/cxrdp_bridge.h index 5641593..c1ee1b8 100644 --- a/native/CxRdpBridge/cxrdp_bridge.h +++ b/native/CxRdpBridge/cxrdp_bridge.h @@ -31,7 +31,7 @@ typedef void (*cxrdp_pointer_callback)( int hot_y, const uint8_t* bgra_pixels); -#define CX_RDP_BRIDGE_API_VERSION 14u +#define CX_RDP_BRIDGE_API_VERSION 15u #define CX_RDP_CAPABILITY_CLIPBOARD 0x00000001u #define CX_RDP_CAPABILITY_DRIVE_REDIRECTION 0x00000002u #define CX_RDP_CAPABILITY_AUDIO_PLAYBACK 0x00000004u @@ -68,6 +68,18 @@ typedef void (*cxrdp_pointer_callback)( #define CX_RDP_CAPABILITY_CLIPBOARD_FILES 0x00008000u #define CX_RDP_CAPABILITY_CLIPBOARD_RICH_TEXT 0x00010000u #define CX_RDP_CAPABILITY_CLIPBOARD_LOCK 0x00020000u +#define CX_RDP_CAPABILITY_MULTI_MONITOR 0x00040000u + +typedef struct CxRdpMonitorRect +{ + int32_t left; + int32_t top; + uint32_t width; + uint32_t height; + uint32_t desktop_scale_factor; + uint32_t device_scale_factor; + int32_t is_primary; +} CxRdpMonitorRect; #define CX_RDP_CLIPBOARD_IMAGE_PNG 1u #define CX_RDP_CLIPBOARD_IMAGE_DIB 2u @@ -145,6 +157,7 @@ CX_RDP_API int cxrdp_set_display_scale(void* handle, int scalePercent); The worker applies it through the display-control channel; the host must keep framebuffer dimensions from the frame callback. */ CX_RDP_API int cxrdp_update_display(void* handle, int width, int height, int scalePercent); +CX_RDP_API int cxrdp_resize_monitors(void* handle, const CxRdpMonitorRect* monitors, int count); /* Prefer the security profile that succeeded on a previous connection to this host: "negotiate", "nla", "tls" or "rdp". An empty/NULL name restores diff --git a/rdpbuild.ps1 b/rdpbuild.ps1 new file mode 100644 index 0000000..4068f5a --- /dev/null +++ b/rdpbuild.ps1 @@ -0,0 +1,18 @@ +$ErrorActionPreference = "Stop" +$env:VCPKG_ROOT = "D:\vcpkg" + +& (Join-Path $PSScriptRoot "tools\build-rdp-bridge.ps1") ` + -VcpkgRoot $env:VCPKG_ROOT ` + -Triplet x64-windows ` + -OutputDir (Join-Path $PSScriptRoot "runtimes\win-x64\native") + +dotnet publish (Join-Path $PSScriptRoot "CxShell.csproj") ` + -c Release ` + -r win-x64 ` + --self-contained true ` + -o (Join-Path $PSScriptRoot "artifacts\publish\win-x64") ` + /p:DebugType=none ` + /p:DebugSymbols=false +if ($LASTEXITCODE -ne 0) { + throw "dotnet publish failed with exit code $LASTEXITCODE." +} \ No newline at end of file From aa52f1a5c27d097bdea1b602a82cd14b8f3a22cb Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 15:53:49 +0800 Subject: [PATCH 08/15] fix(rdp): snap multi-monitor layouts and derive framebuffer slices from normalized layout bounds Fixed: - Multi-monitor display corruption in right-left, top-bottom, and bottom-top arrangements. Technical Approach: - Snap adjacent monitors tightly against the host viewport's effective pixel dimensions (hostPixelW/hostPixelH) before computing relative MS-RDPEDISP coordinates so there are zero gaps or overlaps. - Compute every monitor's framebuffer slice rectangle directly from (layout.Left - minLayoutX, layout.Top - minLayoutY, layout.Width, layout.Height) instead of raw physical Screen.Bounds. --- Views/RdpView.axaml.cs | 83 +++++++++++++++++++++++++++++++++--------- 1 file changed, 65 insertions(+), 18 deletions(-) diff --git a/Views/RdpView.axaml.cs b/Views/RdpView.axaml.cs index 4af9d63..08827a6 100644 --- a/Views/RdpView.axaml.cs +++ b/Views/RdpView.axaml.cs @@ -546,17 +546,17 @@ private void ApplySelectedMonitorLayout() var layouts = new System.Collections.Generic.List(selected.Count); var sliceByIndex = new System.Collections.Generic.Dictionary(); - foreach (var item in selected) - { - var b = item.Screen.Bounds; - var w = item.Index == hostEntry.Index ? hostPixelW : Math.Clamp(b.Width & ~1, 200, 8192); - var h = item.Index == hostEntry.Index ? hostPixelH : Math.Clamp(b.Height & ~1, 200, 8192); - sliceByIndex[item.Index] = new Rect(b.X - minX, b.Y - minY, w, h); - } // Mode 2: Local dual PBP screens -> Remote single merged ultrawide monitor if (_ultrawideMode == 2 && selected.Count >= 2 && _virtualMonitorIds.Count == 0) { + foreach (var item in selected) + { + var b = item.Screen.Bounds; + var w = item.Index == hostEntry.Index ? hostPixelW : Math.Clamp(b.Width & ~1, 200, 8192); + var h = item.Index == hostEntry.Index ? hostPixelH : Math.Clamp(b.Height & ~1, 200, 8192); + sliceByIndex[item.Index] = new Rect(b.X - minX, b.Y - minY, w, h); + } var totalW = Math.Clamp((maxX - minX) & ~1, 200, 8192); var totalH = Math.Clamp((maxY - minY) & ~1, 200, 8192); var scale = Math.Clamp((int)Math.Round(remotePrimaryEntry.Screen.Scaling * 100), 100, 500); @@ -564,33 +564,80 @@ private void ApplySelectedMonitorLayout() } else { + // Snap adjacent monitors tightly to hostEntry's effective pixel rect so + // right-left, top-bottom, and bottom-top arrangements have zero gaps or + // overlaps (required by MS-RDPEDISP) even when hostPixelW/H differs from + // the physical screen bounds (e.g. taskbar or windowed mode). + var hostBounds = hostEntry.Screen.Bounds; + var snappedCoords = new System.Collections.Generic.Dictionary(); foreach (var item in selected) { var b = item.Screen.Bounds; var w = item.Index == hostEntry.Index ? hostPixelW : Math.Clamp(b.Width & ~1, 200, 8192); var h = item.Index == hostEntry.Index ? hostPixelH : Math.Clamp(b.Height & ~1, 200, 8192); - var left = b.X - remotePrimaryEntry.Screen.Bounds.X; - var top = b.Y - remotePrimaryEntry.Screen.Bounds.Y; + var x = b.X; + var y = b.Y; + + if (item.Index != hostEntry.Index) + { + if (b.X >= hostBounds.Right - 2) + x = hostBounds.X + hostPixelW; + else if (b.Right <= hostBounds.X + 2) + x = hostBounds.X - w; + + if (b.Y >= hostBounds.Bottom - 2) + y = hostBounds.Y + hostPixelH; + else if (b.Bottom <= hostBounds.Y + 2) + y = hostBounds.Y - h; + } + var scale = Math.Clamp((int)Math.Round(item.Screen.Scaling * 100), 100, 500); - layouts.Add(new RdpMonitorRect(left, top, w, h, scale, item.Index == remotePrimaryEntry.Index)); + snappedCoords[item.Index] = (x, y, w, h, scale, item.Index == remotePrimaryEntry.Index); + } + + var primaryCoord = snappedCoords[remotePrimaryEntry.Index]; + var layoutByIndex = new System.Collections.Generic.Dictionary(); + var minLayoutX = int.MaxValue; + var minLayoutY = int.MaxValue; + var maxLayoutRight = int.MinValue; + + foreach (var item in selected) + { + var c = snappedCoords[item.Index]; + var left = c.X - primaryCoord.X; + var top = c.Y - primaryCoord.Y; + var rect = new RdpMonitorRect(left, top, c.W, c.H, c.Scale, c.IsPrimary); + layouts.Add(rect); + layoutByIndex[item.Index] = rect; + if (left < minLayoutX) minLayoutX = left; + if (top < minLayoutY) minLayoutY = top; + if (left + c.W > maxLayoutRight) maxLayoutRight = left + c.W; } // Append any user-created virtual monitors (windowed on host screen) to the right - var nextRight = hostEntry.Screen.Bounds.X + hostPixelW; - if (selected.Count > 1 && maxX > nextRight) - nextRight = maxX; - var hostBounds = hostEntry.Screen.Bounds; + var hostLayout = layoutByIndex[hostEntry.Index]; + var nextRight = Math.Max(hostLayout.Left + hostLayout.Width, maxLayoutRight); var hostScale = Math.Clamp((int)Math.Round(hostEntry.Screen.Scaling * 100), 100, 500); foreach (var vId in _virtualMonitorIds) { var vw = Math.Clamp(hostBounds.Width & ~1, 200, 8192); var vh = Math.Clamp(hostBounds.Height & ~1, 200, 8192); - var vLeft = nextRight - remotePrimaryEntry.Screen.Bounds.X; - var vTop = hostBounds.Y - remotePrimaryEntry.Screen.Bounds.Y; - layouts.Add(new RdpMonitorRect(vLeft, vTop, vw, vh, hostScale, false)); - sliceByIndex[vId] = new Rect(nextRight - minX, hostBounds.Y - minY, vw, vh); + var vRect = new RdpMonitorRect(nextRight, hostLayout.Top, vw, vh, hostScale, false); + layouts.Add(vRect); + layoutByIndex[vId] = vRect; + if (vRect.Left < minLayoutX) minLayoutX = vRect.Left; + if (vRect.Top < minLayoutY) minLayoutY = vRect.Top; nextRight += vw; } + + // Compute every monitor's framebuffer slice directly from the normalized + // layout coordinates so negative left/top offsets (right-left, bottom-top) + // map accurately to [0..totalWidth, 0..totalHeight] in the GDI framebuffer. + foreach (var kv in layoutByIndex) + { + var l = kv.Value; + sliceByIndex[kv.Key] = new Rect(l.Left - minLayoutX, l.Top - minLayoutY, l.Width, l.Height); + } } vm.TryResizeMonitors(layouts); From 49eb7f2ac3ec6f5426e44878b230a6d33d2038ea Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 15:58:34 +0800 Subject: [PATCH 09/15] fix(rdp): implement cxrdp_resize_monitors and CS_MONITOR handshake in CxRdpBridge Fixed: - Multi-monitor layout requests were silently ignored because cxrdp_resize_monitors and FreeRDP_UseMultimon/FreeRDP_ForceMultimon were missing from cxrdp_bridge.cpp after rebasing onto origin/master. Technical Approach: - Enable FreeRDP_UseMultimon and FreeRDP_ForceMultimon with an initial primary rdpMonitor definition during pre-connect so Windows servers negotiate CS_MONITOR. - Expose CX_RDP_CAPABILITY_MULTI_MONITOR and implement cxrdp_resize_monitors forwarding DISPLAY_CONTROL_MONITOR_LAYOUT arrays through DispClientContext.SendMonitorLayout. --- native/CxRdpBridge/cxrdp_bridge.cpp | 69 ++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/native/CxRdpBridge/cxrdp_bridge.cpp b/native/CxRdpBridge/cxrdp_bridge.cpp index 56a1f84..899b324 100644 --- a/native/CxRdpBridge/cxrdp_bridge.cpp +++ b/native/CxRdpBridge/cxrdp_bridge.cpp @@ -2916,6 +2916,18 @@ void connection_thread(CxRdpSession* session) // The static addin in freerdp-client3.dll is registered as // "disp"; the long DVC name is only the wire protocol name. freerdp_settings_set_bool(settings, FreeRDP_SupportDisplayControl, TRUE); + freerdp_settings_set_bool(settings, FreeRDP_UseMultimon, TRUE); + freerdp_settings_set_bool(settings, FreeRDP_ForceMultimon, TRUE); + { + rdpMonitor initialMonitor{}; + initialMonitor.x = 0; + initialMonitor.y = 0; + initialMonitor.width = static_cast(freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)); + initialMonitor.height = static_cast(freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + initialMonitor.is_primary = TRUE; + if (initialMonitor.width > 0 && initialMonitor.height > 0) + freerdp_settings_set_monitor_def_array_sorted(settings, &initialMonitor, 1); + } const char* displayChannel[] = { DISP_CHANNEL_NAME }; if (!freerdp_client_add_dynamic_channel(settings, 1, displayChannel)) { @@ -3182,7 +3194,8 @@ CX_RDP_API uint32_t cxrdp_get_capabilities(void) CX_RDP_CAPABILITY_DIRTY_RECT | CX_RDP_CAPABILITY_GFX | CX_RDP_CAPABILITY_SYNC_LOCK_KEYS | - CX_RDP_CAPABILITY_POINTER_SHAPE; + CX_RDP_CAPABILITY_POINTER_SHAPE | + CX_RDP_CAPABILITY_MULTI_MONITOR; if (has_native_audio_backend()) capabilities |= CX_RDP_CAPABILITY_AUDIO_PLAYBACK | CX_RDP_CAPABILITY_MICROPHONE; return capabilities; @@ -3500,6 +3513,60 @@ CX_RDP_API int cxrdp_set_display_scale(void* handle, int scalePercent) return 0; } +CX_RDP_API int cxrdp_resize_monitors( + void* handle, + const CxRdpMonitorRect* monitors, + int count) +{ + auto* session = static_cast(handle); + if (!session || !session->connected.load() || !session->running.load() || !monitors || count <= 0 || count > 16) + return -1; + + DispClientContext* disp = nullptr; + { + std::lock_guard lock(session->display_mutex); + disp = session->disp; + } + + if (!disp || !disp->SendMonitorLayout) + return -2; + + std::vector layouts(static_cast(count)); + bool hasPrimary = false; + for (int i = 0; i < count; ++i) + { + const auto& src = monitors[i]; + uint32_t w = src.width < 200u ? 200u : (src.width > 8192u ? 8192u : src.width); + uint32_t h = src.height < 200u ? 200u : (src.height > 8192u ? 8192u : src.height); + w &= ~1u; + h &= ~1u; + + auto& dst = layouts[static_cast(i)]; + dst.Flags = src.is_primary != 0 ? DISPLAY_CONTROL_MONITOR_PRIMARY : 0u; + if (src.is_primary != 0) + hasPrimary = true; + dst.Left = src.left; + dst.Top = src.top; + dst.Width = w; + dst.Height = h; + dst.PhysicalWidth = w; + dst.PhysicalHeight = h; + dst.Orientation = ORIENTATION_LANDSCAPE; + dst.DesktopScaleFactor = (src.desktop_scale_factor >= 100u && src.desktop_scale_factor <= 500u) + ? src.desktop_scale_factor + : 100u; + dst.DeviceScaleFactor = src.device_scale_factor == 180u + ? 180u + : (src.device_scale_factor == 140u ? 140u : 100u); + } + + if (!hasPrimary) + layouts[0].Flags = DISPLAY_CONTROL_MONITOR_PRIMARY; + + const UINT rc = disp->SendMonitorLayout(disp, static_cast(count), layouts.data()); + return rc == CHANNEL_RC_OK ? 0 : -3; +} + CX_RDP_API int cxrdp_update_display(void* handle, int width, int height, int scalePercent) { auto* session = static_cast(handle); From 9fe65e87f2954eea4c46ea797832c8434e81fe34 Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 17:09:54 +0800 Subject: [PATCH 10/15] =?UTF-8?q?feat(rdp):=20=E6=96=B0=E5=A2=9E=E4=BC=9A?= =?UTF-8?q?=E8=AF=9D=E7=BA=A7=20H.264/AVC444=20=E5=9B=BE=E5=BD=A2=E5=8A=A0?= =?UTF-8?q?=E9=80=9F=E9=80=89=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Models/SessionInfo.cs | 1 + Services/LocalizationService.cs | 4 ++++ Services/RdpBridgeClient.cs | 13 +++++++++++++ ViewModels/SessionEditViewModel.cs | 3 +++ ViewModels/SessionTreeViewModel.cs | 2 ++ Views/SessionEditDialog.axaml | 10 +++++++++- native/CxRdpBridge/cxrdp_bridge.cpp | 27 ++++++++++++++++++++++++++- native/CxRdpBridge/cxrdp_bridge.h | 2 ++ 8 files changed, 60 insertions(+), 2 deletions(-) diff --git a/Models/SessionInfo.cs b/Models/SessionInfo.cs index 2242f30..84dcb08 100644 --- a/Models/SessionInfo.cs +++ b/Models/SessionInfo.cs @@ -627,6 +627,7 @@ public string ResolveEffectiveRdpWindowMode() /// the pipeline still connect - the bridge retries once without EGFX. /// public bool RdpGraphicsPipelineEnabled { get; set; } = true; + public bool RdpH264Enabled { get; set; } public bool RdpRedirectDrives { get; set; } public string RdpDriveName { get; set; } = "CxShell"; public string RdpDrivePath { get; set; } = string.Empty; diff --git a/Services/LocalizationService.cs b/Services/LocalizationService.cs index 31c2a34..894404f 100644 --- a/Services/LocalizationService.cs +++ b/Services/LocalizationService.cs @@ -185,6 +185,8 @@ public sealed class LocalizationService : INotifyPropertyChanged ["SessionEdit.RdpDisableWallpaperHint"] = "Sends the RDP performance flag PERF_DISABLE_WALLPAPER. Skipping the wallpaper reduces first-screen paint work and bandwidth on slow links. Turn this off to keep the remote wallpaper.", ["SessionEdit.RdpGraphicsPipeline"] = "EGFX graphics pipeline", ["SessionEdit.RdpGraphicsPipelineHint"] = "Negotiates MS-RDPEGFX so the server sends complete START_FRAME/END_FRAME logical frames, like MSTSC: the desktop appears at once instead of being painted strip by strip. On by default. If the server rejects the pipeline the session still connects on the legacy path automatically.", + ["SessionEdit.RdpH264"] = "H.264 / AVC444 acceleration", + ["SessionEdit.RdpH264Hint"] = "Requests H.264 and AVC444 video codecs over EGFX for smoother video and scrolling on high-latency links. Requires EGFX graphics pipeline and server/decoder support.", ["SessionEdit.SshHost"] = "SSH Host", ["SessionEdit.SshPort"] = "SSH Port", ["SessionEdit.SshUsername"] = "SSH Username", @@ -532,6 +534,8 @@ public sealed class LocalizationService : INotifyPropertyChanged ["SessionEdit.RdpDisableWallpaperHint"] = "向服务端发送 RDP 性能标志 PERF_DISABLE_WALLPAPER,跳过壁纸绘制,可减少首屏数据量与带宽占用;关闭后保留远程壁纸。", ["SessionEdit.RdpGraphicsPipeline"] = "EGFX 图形管道", ["SessionEdit.RdpGraphicsPipelineHint"] = "协商 MS-RDPEGFX,让服务端以 START_FRAME/END_FRAME 发送完整逻辑帧(与 MSTSC 一致):桌面一次成型,不再从上往下逐块刷出。默认开启;若服务端拒绝该管道,连接会自动退回 legacy 路径,不影响连上。", + ["SessionEdit.RdpH264"] = "启用 H.264 / AVC444 视频加速", + ["SessionEdit.RdpH264Hint"] = "在 EGFX 图形管道上请求 H.264 与 AVC444 编码,以提升高延迟或视频/滚动场景流畅度。需同时开启 EGFX 图形管道且服务端与本地解码器支持。", ["SessionEdit.SshHost"] = "SSH 主机", ["SessionEdit.SshPort"] = "SSH 端口", ["SessionEdit.SshUsername"] = "SSH 用户", diff --git a/Services/RdpBridgeClient.cs b/Services/RdpBridgeClient.cs index 94b9f17..ee7fb01 100644 --- a/Services/RdpBridgeClient.cs +++ b/Services/RdpBridgeClient.cs @@ -92,6 +92,7 @@ public sealed class RdpBridgeClient : IDisposable private const uint DirtyRectCapability = 0x00000400; private const uint GfxApiVersion = 11; private const uint GfxCapability = 0x00000800; + private const uint GfxH264Capability = 0x00080000; private const uint SyncLockKeysApiVersion = 12; private const uint SyncLockKeysCapability = 0x00001000; private const uint PointerShapeApiVersion = 13; @@ -316,6 +317,15 @@ public void Connect( var gfxResult = NativeMethods.cxrdp_set_graphics_pipeline(_handle, gfxRequested ? 1 : 0); DebugLog($"graphics pipeline requested={gfxRequested} session={session.RdpGraphicsPipelineEnabled} env={GraphicsPipelineForcedOn} result={gfxResult}"); }); + if ((nativeCapabilities & GfxH264Capability) != 0) + { + var h264Requested = gfxRequested && session.RdpH264Enabled; + TryInvokeOptionalNative("cxrdp_set_h264_enabled", () => + { + var h264Result = NativeMethods.cxrdp_set_h264_enabled(_handle, h264Requested ? 1 : 0); + DebugLog($"graphics pipeline h264 requested={h264Requested} result={h264Result}"); + }); + } } else { @@ -1704,6 +1714,9 @@ public static extern int cxrdp_get_frame_dirty_rect( [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern int cxrdp_set_graphics_pipeline(IntPtr handle, int enabled); + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] + public static extern int cxrdp_set_h264_enabled(IntPtr handle, int enabled); + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr cxrdp_get_last_error(IntPtr handle); } diff --git a/ViewModels/SessionEditViewModel.cs b/ViewModels/SessionEditViewModel.cs index d0ad2cf..580b89e 100644 --- a/ViewModels/SessionEditViewModel.cs +++ b/ViewModels/SessionEditViewModel.cs @@ -339,6 +339,7 @@ public readonly record struct AppearanceColorPalette( [ObservableProperty] private bool _rdpClipboardEnabled = true; [ObservableProperty] private bool _rdpDisableWallpaper = true; [ObservableProperty] private bool _rdpGraphicsPipelineEnabled; + [ObservableProperty] private bool _rdpH264Enabled; [ObservableProperty] private bool _rdpRedirectDrives; [ObservableProperty] private string _rdpDriveName = "CxShell"; [ObservableProperty] private string _rdpDrivePath = string.Empty; @@ -1562,6 +1563,7 @@ public SessionEditViewModel(SessionInfo session) RdpClipboardEnabled = session.RdpClipboardEnabled; RdpDisableWallpaper = session.RdpDisableWallpaper; RdpGraphicsPipelineEnabled = session.RdpGraphicsPipelineEnabled; + RdpH264Enabled = session.RdpH264Enabled; RdpRedirectDrives = session.RdpRedirectDrives; RdpDriveName = string.IsNullOrWhiteSpace(session.RdpDriveName) ? "CxShell" : session.RdpDriveName; RdpDrivePath = session.RdpDrivePath ?? string.Empty; @@ -1877,6 +1879,7 @@ private void Save() session.RdpClipboardEnabled = RdpClipboardEnabled; session.RdpDisableWallpaper = RdpDisableWallpaper; session.RdpGraphicsPipelineEnabled = RdpGraphicsPipelineEnabled; + session.RdpH264Enabled = RdpH264Enabled; session.RdpRedirectDrives = RdpRedirectDrives; session.RdpDriveName = string.IsNullOrWhiteSpace(RdpDriveName) ? "CxShell" : RdpDriveName.Trim(); session.RdpDrivePath = RdpRedirectDrives ? RdpDrivePath.Trim() : string.Empty; diff --git a/ViewModels/SessionTreeViewModel.cs b/ViewModels/SessionTreeViewModel.cs index 2069249..e7ce8fb 100644 --- a/ViewModels/SessionTreeViewModel.cs +++ b/ViewModels/SessionTreeViewModel.cs @@ -267,6 +267,7 @@ public static void CopySessionValues(SessionInfo target, SessionInfo source) target.RdpClipboardEnabled = source.RdpClipboardEnabled; target.RdpDisableWallpaper = source.RdpDisableWallpaper; target.RdpGraphicsPipelineEnabled = source.RdpGraphicsPipelineEnabled; + target.RdpH264Enabled = source.RdpH264Enabled; target.RdpRedirectDrives = source.RdpRedirectDrives; target.RdpDriveName = source.RdpDriveName; target.RdpDrivePath = source.RdpDrivePath; @@ -1193,6 +1194,7 @@ private static SessionInfo CloneSession(SessionInfo source, string name) RdpClipboardEnabled = source.RdpClipboardEnabled, RdpDisableWallpaper = source.RdpDisableWallpaper, RdpGraphicsPipelineEnabled = source.RdpGraphicsPipelineEnabled, + RdpH264Enabled = source.RdpH264Enabled, RdpRedirectDrives = source.RdpRedirectDrives, RdpDriveName = source.RdpDriveName, RdpDrivePath = source.RdpDrivePath, diff --git a/Views/SessionEditDialog.axaml b/Views/SessionEditDialog.axaml index 3560513..e1d16b3 100644 --- a/Views/SessionEditDialog.axaml +++ b/Views/SessionEditDialog.axaml @@ -1731,7 +1731,7 @@ BorderThickness="1" CornerRadius="4" Padding="18"> - + + diff --git a/native/CxRdpBridge/cxrdp_bridge.cpp b/native/CxRdpBridge/cxrdp_bridge.cpp index 899b324..5348860 100644 --- a/native/CxRdpBridge/cxrdp_bridge.cpp +++ b/native/CxRdpBridge/cxrdp_bridge.cpp @@ -88,6 +88,7 @@ struct CxRdpSession bool frame_marker_enabled = true; bool disable_wallpaper = true; bool graphics_pipeline_requested = true; + bool h264_requested = false; bool gfx_frame_mode = false; // EGFX is decoded by FreeRDP's GDI backend, but the client must hand the // RdpgfxClientContext to gdi_graphics_pipeline_init(). Without that @@ -2840,6 +2841,11 @@ void connection_thread(CxRdpSession* session) freerdp_settings_set_bool(settings, FreeRDP_SupportGraphicsPipeline, TRUE); freerdp_settings_set_bool(settings, FreeRDP_GfxPlanar, TRUE); freerdp_settings_set_bool(settings, FreeRDP_GfxProgressive, TRUE); + freerdp_settings_set_bool(settings, FreeRDP_GfxProgressiveV2, TRUE); + const BOOL enableH264 = session->h264_requested ? TRUE : FALSE; + freerdp_settings_set_bool(settings, FreeRDP_GfxH264, enableH264); + freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444, enableH264); + freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444v2, enableH264); // A positive FrameAcknowledge makes the client send // RDPGFX_FRAME_ACKNOWLEDGE; without it the server throttles the // graphics channel and may stop streaming frames entirely. @@ -2848,6 +2854,9 @@ void connection_thread(CxRdpSession* session) else { freerdp_settings_set_bool(settings, FreeRDP_SupportGraphicsPipeline, FALSE); + freerdp_settings_set_bool(settings, FreeRDP_GfxH264, FALSE); + freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444, FALSE); + freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444v2, FALSE); } // Cheap bandwidth/CPU wins that do not change what the user sees: @@ -3195,7 +3204,8 @@ CX_RDP_API uint32_t cxrdp_get_capabilities(void) CX_RDP_CAPABILITY_GFX | CX_RDP_CAPABILITY_SYNC_LOCK_KEYS | CX_RDP_CAPABILITY_POINTER_SHAPE | - CX_RDP_CAPABILITY_MULTI_MONITOR; + CX_RDP_CAPABILITY_MULTI_MONITOR | + CX_RDP_CAPABILITY_GFX_H264; if (has_native_audio_backend()) capabilities |= CX_RDP_CAPABILITY_AUDIO_PLAYBACK | CX_RDP_CAPABILITY_MICROPHONE; return capabilities; @@ -3712,6 +3722,21 @@ CX_RDP_API int cxrdp_set_graphics_pipeline(void* handle, int enabled) return 0; } +CX_RDP_API int cxrdp_set_h264_enabled(void* handle, int enabled) +{ + auto* session = static_cast(handle); + if (!session) + return -1; + if (session->running) + { + set_error(session, "RDP H.264 setting must be configured before connecting."); + return -2; + } + + session->h264_requested = enabled != 0; + return 0; +} + CX_RDP_API const char* cxrdp_get_last_error(void* handle) { auto* session = static_cast(handle); diff --git a/native/CxRdpBridge/cxrdp_bridge.h b/native/CxRdpBridge/cxrdp_bridge.h index c1ee1b8..43016a2 100644 --- a/native/CxRdpBridge/cxrdp_bridge.h +++ b/native/CxRdpBridge/cxrdp_bridge.h @@ -69,6 +69,7 @@ typedef void (*cxrdp_pointer_callback)( #define CX_RDP_CAPABILITY_CLIPBOARD_RICH_TEXT 0x00010000u #define CX_RDP_CAPABILITY_CLIPBOARD_LOCK 0x00020000u #define CX_RDP_CAPABILITY_MULTI_MONITOR 0x00040000u +#define CX_RDP_CAPABILITY_GFX_H264 0x00080000u typedef struct CxRdpMonitorRect { @@ -196,6 +197,7 @@ CX_RDP_API int cxrdp_get_frame_dirty_rect( instead of host-side heuristics. Default: enabled. Requires CX_RDP_CAPABILITY_GFX (API 11). */ CX_RDP_API int cxrdp_set_graphics_pipeline(void* handle, int enabled); +CX_RDP_API int cxrdp_set_h264_enabled(void* handle, int enabled); CX_RDP_API const char* cxrdp_get_last_error(void* handle); From 73bd3f5428d5612cf9e761f53c5b1d4f55008e72 Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 17:10:57 +0800 Subject: [PATCH 11/15] =?UTF-8?q?perf(rdp):=20=E6=94=AF=E6=8C=81=E5=B1=80?= =?UTF-8?q?=E9=83=A8=E8=84=8F=E7=9F=A9=E5=BD=A2=E5=B8=A7=E6=8B=B7=E8=B4=9D?= =?UTF-8?q?=E4=BB=A5=E9=99=8D=E4=BD=8E=E9=AB=98=E5=88=86=E8=BE=A8=E7=8E=87?= =?UTF-8?q?=20CPU=20=E5=8D=A0=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Services/RdpBridgeClient.cs | 149 ++++++++++++++++++++++++++++++------ ViewModels/RdpViewModel.cs | 22 +++++- 2 files changed, 145 insertions(+), 26 deletions(-) diff --git a/Services/RdpBridgeClient.cs b/Services/RdpBridgeClient.cs index ee7fb01..fc9fd00 100644 --- a/Services/RdpBridgeClient.cs +++ b/Services/RdpBridgeClient.cs @@ -42,13 +42,15 @@ public RdpFramebufferEventArgs( int stride, byte[] pixels, int? pixelLength = null, - Action? release = null) + Action? release = null, + RdpFrameDirtyRect? dirtyRect = null) { Width = width; Height = height; Stride = stride; Pixels = pixels; PixelLength = pixelLength ?? pixels.Length; + DirtyRect = dirtyRect; _release = release; } @@ -57,6 +59,12 @@ public RdpFramebufferEventArgs( public int Stride { get; } public byte[] Pixels { get; } + /// + /// Optional dirty region (already unioned with the previous frame for + /// double-buffered targets). Null means the entire framebuffer must be copied. + /// + public RdpFrameDirtyRect? DirtyRect { get; } + /// /// Valid byte count in . A pooled array may be larger /// than the frame, so callers must use this instead of Pixels.Length. @@ -146,6 +154,9 @@ public sealed class RdpBridgeClient : IDisposable private int _previousFrameHeight; private int _previousFrameStride; private string _dirtyRectSource = "none"; + private bool _pendingFullFrameCopy = true; + private RdpFrameDirtyRect? _pendingCopyDirtyRect; + private RdpFrameDirtyRect? _lastPresentedDirtyRect; // Input arrives on the UI thread. Only a single atomic write is done there; // the presentation timer folds it into the composer under _frameSync, so // sending a mouse event never has to wait for a frame-copy lock. @@ -597,6 +608,7 @@ private void TryPresentFrame(object? state) bool interactive; bool settling; bool logFrame; + RdpFrameDirtyRect? copyRect; lock (_frameSync) { @@ -620,11 +632,29 @@ private void TryPresentFrame(object? state) wave = _frameComposer.InRepaintWave; collectMs = (long)_frameComposer.FirstFrameAge(now).TotalMilliseconds; dirtySource = _dirtyRectSource; - snapshot = ArrayPool.Shared.Rent(length); - Buffer.BlockCopy(_frameBuffer, 0, snapshot, 0, length); width = _frameWidth; height = _frameHeight; stride = _frameStride; + snapshot = ArrayPool.Shared.Rent(length); + + var currentDirty = _pendingFullFrameCopy ? null : _pendingCopyDirtyRect; + if (currentDirty.HasValue && _lastPresentedDirtyRect.HasValue) + { + copyRect = ClampDirtyRect(UnionDirtyRect(currentDirty.Value, _lastPresentedDirtyRect.Value), width, height); + } + else + { + copyRect = null; + } + + if (copyRect.HasValue) + CopyDirtyRectManaged(_frameBuffer, snapshot, stride, copyRect.Value); + else + Buffer.BlockCopy(_frameBuffer, 0, snapshot, 0, length); + + _lastPresentedDirtyRect = currentDirty; + _pendingFullFrameCopy = false; + _pendingCopyDirtyRect = null; _frameDirty = false; interactive = _frameComposer.IsInteractive(now); settling = _frameComposer.InSettlingWindow(now); @@ -659,7 +689,8 @@ private void TryPresentFrame(object? state) stride, snapshot, length, - () => ArrayPool.Shared.Return(snapshot)); + () => ArrayPool.Shared.Return(snapshot), + copyRect); try { @@ -1189,33 +1220,59 @@ private void OnFrame(IntPtr userData, int width, int height, int stride, IntPtr _previousFrameWidth = width; _previousFrameHeight = height; _previousFrameStride = stride; + _pendingFullFrameCopy = true; + _pendingCopyDirtyRect = null; + _lastPresentedDirtyRect = null; } - Marshal.Copy(data, _frameBuffer, 0, length); - - // Most Windows servers leave FreeRDP's GDI invalid region empty on - // the legacy bitmap-update path. Diffing against the previous batch - // gives a server-independent dirty region: the first batch only - // covers the strip that was actually painted, so the composer can - // hold the frame until the whole desktop has arrived. - // Wave classification is only needed for the first frame and the - // settling window. In interactive/settled mode every snapshot is - // published as-is, so skip the sampled full-surface diff (thousands - // of cache-missing reads per mouse-move batch). - if (dirty is null && classifyWave && FrameCoverageEnabled && FrameCoalescingEnabled) + var clampedDirty = dirty.HasValue ? ClampDirtyRect(dirty.Value, width, height) : null; + var canPartialCopy = !sizeChanged && + !classifyWave && + clampedDirty.HasValue && + stride >= width * 4; + if (canPartialCopy) { - var diff = ComputeDirtyRectFromDiff(width, height, stride); - if (diff.HasValue) + var rect = clampedDirty!.Value; + CopyDirtyRectFromNative(data, _frameBuffer, stride, rect); + CopyDirtyRectManaged(_frameBuffer, _previousFrameBuffer, stride, rect); + if (!_pendingFullFrameCopy) { - dirty = diff; - dirtySource = "diff"; + _pendingCopyDirtyRect = _pendingCopyDirtyRect.HasValue + ? UnionDirtyRect(_pendingCopyDirtyRect.Value, rect) + : rect; + } + } + else + { + Marshal.Copy(data, _frameBuffer, 0, length); + + // Most Windows servers leave FreeRDP's GDI invalid region empty on + // the legacy bitmap-update path. Diffing against the previous batch + // gives a server-independent dirty region: the first batch only + // covers the strip that was actually painted, so the composer can + // hold the frame until the whole desktop has arrived. + // Wave classification is only needed for the first frame and the + // settling window. In interactive/settled mode every snapshot is + // published as-is, so skip the sampled full-surface diff (thousands + // of cache-missing reads per mouse-move batch). + if (dirty is null && classifyWave && FrameCoverageEnabled && FrameCoalescingEnabled) + { + var diff = ComputeDirtyRectFromDiff(width, height, stride); + if (diff.HasValue) + { + dirty = diff; + dirtySource = "diff"; + } } + + // Keep the diff baseline fresh even when classification is idle, + // so switching back to wave mode never sees a stale full-screen + // difference. This is a plain sequential copy and stays cheap. + Buffer.BlockCopy(_frameBuffer, 0, _previousFrameBuffer, 0, length); + _pendingFullFrameCopy = true; + _pendingCopyDirtyRect = null; } - // Keep the diff baseline fresh even when classification is idle, - // so switching back to wave mode never sees a stale full-screen - // difference. This is a plain sequential copy and stays cheap. - Buffer.BlockCopy(_frameBuffer, 0, _previousFrameBuffer, 0, length); _dirtyRectSource = dirtySource; _frameWidth = width; _frameHeight = height; @@ -1289,6 +1346,50 @@ private void OnFrame(IntPtr userData, int width, int height, int stride, IntPtr return new RdpFrameDirtyRect(left, top, Math.Max(1, right - left), Math.Max(1, bottom - top)); } + private static RdpFrameDirtyRect? ClampDirtyRect(RdpFrameDirtyRect rect, int width, int height) + { + var x = Math.Clamp(rect.X, 0, width); + var y = Math.Clamp(rect.Y, 0, height); + var right = Math.Clamp(rect.X + rect.Width, 0, width); + var bottom = Math.Clamp(rect.Y + rect.Height, 0, height); + var w = right - x; + var h = bottom - y; + if (w <= 0 || h <= 0) + return null; + return new RdpFrameDirtyRect(x, y, w, h); + } + + private static RdpFrameDirtyRect UnionDirtyRect(RdpFrameDirtyRect a, RdpFrameDirtyRect b) + { + var x = Math.Min(a.X, b.X); + var y = Math.Min(a.Y, b.Y); + var right = Math.Max(a.X + a.Width, b.X + b.Width); + var bottom = Math.Max(a.Y + a.Height, b.Y + b.Height); + return new RdpFrameDirtyRect(x, y, right - x, bottom - y); + } + + private static void CopyDirtyRectFromNative(IntPtr source, byte[] destination, int stride, RdpFrameDirtyRect rect) + { + var rowBytes = rect.Width * 4; + var xBytes = rect.X * 4; + for (var row = 0; row < rect.Height; row++) + { + var offset = (rect.Y + row) * stride + xBytes; + Marshal.Copy(IntPtr.Add(source, offset), destination, offset, rowBytes); + } + } + + private static void CopyDirtyRectManaged(byte[] source, byte[] destination, int stride, RdpFrameDirtyRect rect) + { + var rowBytes = rect.Width * 4; + var xBytes = rect.X * 4; + for (var row = 0; row < rect.Height; row++) + { + var offset = (rect.Y + row) * stride + xBytes; + Buffer.BlockCopy(source, offset, destination, offset, rowBytes); + } + } + private void OnStatus(IntPtr userData, IntPtr message) { var text = message == IntPtr.Zero ? string.Empty : Marshal.PtrToStringUTF8(message) ?? string.Empty; diff --git a/ViewModels/RdpViewModel.cs b/ViewModels/RdpViewModel.cs index 1c155ab..552ca49 100644 --- a/ViewModels/RdpViewModel.cs +++ b/ViewModels/RdpViewModel.cs @@ -740,8 +740,26 @@ private void OnFramebufferUpdated(object? sender, RdpFramebufferEventArgs e) var target = GetTargetBitmap(e.Width, e.Height); using (var locked = target.Lock()) { - var copyBytes = Math.Min(e.PixelLength, locked.RowBytes * locked.Size.Height); - Marshal.Copy(e.Pixels, 0, locked.Address, copyBytes); + if (e.DirtyRect is { } dirty && + e.Stride == locked.RowBytes && + dirty.X >= 0 && dirty.Y >= 0 && + dirty.X + dirty.Width <= locked.Size.Width && + dirty.Y + dirty.Height <= locked.Size.Height) + { + var rowBytes = dirty.Width * 4; + var xBytes = dirty.X * 4; + for (var row = 0; row < dirty.Height; row++) + { + var offset = (dirty.Y + row) * e.Stride + xBytes; + if (offset + rowBytes <= e.PixelLength) + Marshal.Copy(e.Pixels, offset, IntPtr.Add(locked.Address, offset), rowBytes); + } + } + else + { + var copyBytes = Math.Min(e.PixelLength, locked.RowBytes * locked.Size.Height); + Marshal.Copy(e.Pixels, 0, locked.Address, copyBytes); + } } // Alternating two persistent bitmaps keeps allocations at zero From 108581ff3b09e58c8733f3c316b9cc0b2e3d66e7 Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 17:12:39 +0800 Subject: [PATCH 12/15] =?UTF-8?q?feat(rdp):=20=E8=A1=A5=E9=BD=90=E5=8E=9F?= =?UTF-8?q?=E7=94=9F=E5=89=AA=E8=B4=B4=E6=9D=BF=E6=95=B0=E6=8D=AE=E9=94=81?= =?UTF-8?q?=E5=AE=9A=EF=BC=88LockClipboardData=EF=BC=89=E4=B8=8E=E8=83=BD?= =?UTF-8?q?=E5=8A=9B=E5=BC=80=E5=85=B3=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- native/CxRdpBridge/cxrdp_bridge.cpp | 63 +++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 4 deletions(-) diff --git a/native/CxRdpBridge/cxrdp_bridge.cpp b/native/CxRdpBridge/cxrdp_bridge.cpp index 5348860..314d728 100644 --- a/native/CxRdpBridge/cxrdp_bridge.cpp +++ b/native/CxRdpBridge/cxrdp_bridge.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #if defined(_WIN32) @@ -85,6 +86,7 @@ struct CxRdpSession bool openssl_providers_loaded = false; bool clipboard_channel_enabled = false; bool clipboard_channel_requested = true; + bool clipboard_lock_enabled = true; bool frame_marker_enabled = true; bool disable_wallpaper = true; bool graphics_pipeline_requested = true; @@ -142,6 +144,7 @@ struct CxRdpSession std::string last_error; std::mutex clipboard_mutex; std::string local_clipboard_text; + std::unordered_map locked_clipboard_text; // Display control (DPI remoting + in-place resize). The worker owns the // FreeRDP objects; a UI call only queues a request here. @@ -793,6 +796,8 @@ UINT send_client_capabilities(CliprdrClientContext* cliprdr) generalCapabilitySet.capabilitySetLength = CB_CAPSTYPE_GENERAL_LEN; generalCapabilitySet.version = CB_CAPS_VERSION_2; generalCapabilitySet.generalFlags = CB_USE_LONG_FORMAT_NAMES; + if (!session || session->clipboard_lock_enabled) + generalCapabilitySet.generalFlags |= CB_CAN_LOCK_CLIPDATA; CLIPRDR_CAPABILITIES capabilities{}; capabilities.common.msgType = CB_CLIP_CAPS; @@ -1519,8 +1524,27 @@ UINT cx_cliprdr_server_lock_clipboard_data( CliprdrClientContext* cliprdr, const CLIPRDR_LOCK_CLIPBOARD_DATA* lockClipboardData) { - (void)cliprdr; - (void)lockClipboardData; + if (!cliprdr || !lockClipboardData) + return CHANNEL_RC_OK; + + if (auto* session = static_cast(cliprdr->custom)) + { + bool locked = false; + { + std::lock_guard lock(session->clipboard_mutex); + if (session->clipboard_lock_enabled) + { + session->locked_clipboard_text[lockClipboardData->clipDataId] = session->local_clipboard_text; + locked = true; + } + } + if (locked) + { + std::ostringstream message; + message << "RDP clipboard data locked clipDataId=" << lockClipboardData->clipDataId; + notify_status(session, message.str().c_str()); + } + } return CHANNEL_RC_OK; } @@ -1528,8 +1552,23 @@ UINT cx_cliprdr_server_unlock_clipboard_data( CliprdrClientContext* cliprdr, const CLIPRDR_UNLOCK_CLIPBOARD_DATA* unlockClipboardData) { - (void)cliprdr; - (void)unlockClipboardData; + if (!cliprdr || !unlockClipboardData) + return CHANNEL_RC_OK; + + if (auto* session = static_cast(cliprdr->custom)) + { + bool unlocked = false; + { + std::lock_guard lock(session->clipboard_mutex); + unlocked = session->locked_clipboard_text.erase(unlockClipboardData->clipDataId) > 0; + } + if (unlocked) + { + std::ostringstream message; + message << "RDP clipboard data unlocked clipDataId=" << unlockClipboardData->clipDataId; + notify_status(session, message.str().c_str()); + } + } return CHANNEL_RC_OK; } @@ -3204,6 +3243,7 @@ CX_RDP_API uint32_t cxrdp_get_capabilities(void) CX_RDP_CAPABILITY_GFX | CX_RDP_CAPABILITY_SYNC_LOCK_KEYS | CX_RDP_CAPABILITY_POINTER_SHAPE | + CX_RDP_CAPABILITY_CLIPBOARD_LOCK | CX_RDP_CAPABILITY_MULTI_MONITOR | CX_RDP_CAPABILITY_GFX_H264; if (has_native_audio_backend()) @@ -3737,6 +3777,21 @@ CX_RDP_API int cxrdp_set_h264_enabled(void* handle, int enabled) return 0; } +CX_RDP_API int cxrdp_set_clipboard_lock_enabled(void* handle, int enabled) +{ + auto* session = static_cast(handle); + if (!session) + return -1; + if (session->running) + { + set_error(session, "RDP clipboard lock option must be configured before connecting."); + return -2; + } + + session->clipboard_lock_enabled = enabled != 0; + return 0; +} + CX_RDP_API const char* cxrdp_get_last_error(void* handle) { auto* session = static_cast(handle); From 25258bfaf51b1eb98ddccab43309656568f2576e Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 17:12:53 +0800 Subject: [PATCH 13/15] =?UTF-8?q?feat(rdp):=20=E7=BB=9F=E4=B8=80=E5=A4=9A?= =?UTF-8?q?=E5=B1=8F=E7=BC=A9=E6=94=BE=E6=AF=94=E4=BE=8B=E4=B8=8E=E4=BC=9A?= =?UTF-8?q?=E8=AF=9D=20RdpDpiPolicy=20=E7=AD=96=E7=95=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Views/RdpView.axaml.cs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/Views/RdpView.axaml.cs b/Views/RdpView.axaml.cs index 08827a6..0c2242f 100644 --- a/Views/RdpView.axaml.cs +++ b/Views/RdpView.axaml.cs @@ -466,6 +466,15 @@ private void PopulateMonitorCheckboxes() } } + private static int ResolveMonitorScalePercent(RdpViewModel vm, double screenScaling) + { + var policy = Enum.TryParse(vm.Session.RdpDpiPolicy, true, out var parsed) + ? parsed + : RdpDpiPolicy.FollowLocal; + var resolved = RdpDpiScale.ResolveScalePercent(policy, screenScaling); + return resolved > 0 ? Math.Clamp(resolved, 100, 500) : 100; + } + private void ApplySelectedMonitorLayout() { if (DataContext is not RdpViewModel vm || !vm.IsConnected || TopLevel.GetTopLevel(this) is not Window window) @@ -533,7 +542,7 @@ private void ApplySelectedMonitorLayout() var halfW = Math.Max(200, (hostPixelW / 2) & ~1); var h = Math.Max(200, hostPixelH & ~1); - var scale = Math.Clamp((int)Math.Round(hostEntry.Screen.Scaling * 100), 100, 500); + var scale = ResolveMonitorScalePercent(vm, hostEntry.Screen.Scaling); var splitLayouts = new System.Collections.Generic.List { new(0, 0, halfW, h, scale, true), @@ -559,7 +568,7 @@ private void ApplySelectedMonitorLayout() } var totalW = Math.Clamp((maxX - minX) & ~1, 200, 8192); var totalH = Math.Clamp((maxY - minY) & ~1, 200, 8192); - var scale = Math.Clamp((int)Math.Round(remotePrimaryEntry.Screen.Scaling * 100), 100, 500); + var scale = ResolveMonitorScalePercent(vm, remotePrimaryEntry.Screen.Scaling); layouts.Add(new RdpMonitorRect(0, 0, totalW, totalH, scale, true)); } else @@ -591,7 +600,7 @@ private void ApplySelectedMonitorLayout() y = hostBounds.Y - h; } - var scale = Math.Clamp((int)Math.Round(item.Screen.Scaling * 100), 100, 500); + var scale = ResolveMonitorScalePercent(vm, item.Screen.Scaling); snappedCoords[item.Index] = (x, y, w, h, scale, item.Index == remotePrimaryEntry.Index); } From 905dfae16dc85b3235acd2c8091065814c85c807 Mon Sep 17 00:00:00 2001 From: heartacker Date: Wed, 25 Nov 2026 15:34:36 +0800 Subject: [PATCH 14/15] =?UTF-8?q?feat(rdp):=20=E8=A1=A5=E9=BD=90=E5=8E=9F?= =?UTF-8?q?=E7=94=9F=E5=89=AA=E8=B4=B4=E6=9D=BF=E5=9B=BE=E7=89=87/?= =?UTF-8?q?=E6=96=87=E4=BB=B6/=E5=AF=8C=E6=96=87=E6=9C=AC=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=E4=B8=8E=20CLIPRDR=20=E5=8D=8F=E8=AE=AE=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在 native/CxRdpBridge/cxrdp_bridge.cpp 补齐 cxrdp_set_clipboard_image_callback / cxrdp_set_clipboard_files_callback / cxrdp_set_clipboard_rich_text / cxrdp_set_clipboard_image / cxrdp_set_clipboard_files 导出,严格对齐 cxrdp_bridge.h 4 参数图片签名 - 补齐 FileGroupDescriptorW、FileContents 分块读写、PNG/CF_DIB、HTML/RTF 与 LockClipboardData 文件锁定协议处理 - 在 cxrdp_get_capabilities() 中开启 CLIPBOARD_IMAGE / CLIPBOARD_FILES / CLIPBOARD_RICH_TEXT 能力位(api=15, caps=0xFFFFF) --- native/CxRdpBridge/cxrdp_bridge.cpp | 1064 ++++++++++++++++++++++++++- 1 file changed, 1035 insertions(+), 29 deletions(-) diff --git a/native/CxRdpBridge/cxrdp_bridge.cpp b/native/CxRdpBridge/cxrdp_bridge.cpp index 314d728..92ec1e1 100644 --- a/native/CxRdpBridge/cxrdp_bridge.cpp +++ b/native/CxRdpBridge/cxrdp_bridge.cpp @@ -6,6 +6,8 @@ #include #include #include +#include +#include #include #include #include @@ -65,6 +67,32 @@ extern "C" { namespace { +struct LocalClipboardFileEntry +{ + std::string relative_name; + std::filesystem::path full_path; + bool is_directory = false; + uint64_t file_size = 0; + uint64_t last_write_time = 0; +}; + +struct RemoteClipboardFileEntry +{ + std::string relative_name; + std::filesystem::path local_path; + bool is_directory = false; + uint64_t expected_size = 0; + uint64_t received_bytes = 0; + bool size_known = false; +}; + +constexpr uint32_t CX_CLIPRDR_FORMAT_PNG = 0xC001u; +constexpr uint32_t CX_CLIPRDR_FORMAT_FILE_GROUP_DESCRIPTOR_W = 0xC002u; +constexpr uint32_t CX_CLIPRDR_FORMAT_HTML = 0xC003u; +constexpr uint32_t CX_CLIPRDR_FORMAT_RTF = 0xC004u; +constexpr uint32_t CX_CLIPRDR_FORMAT_FILE_CONTENTS = 0xC005u; +constexpr uint32_t CX_CLIPRDR_FILE_CHUNK_SIZE = 65536u; + struct CxRdpSession { freerdp* instance = nullptr; @@ -133,18 +161,36 @@ struct CxRdpSession bool client_capabilities_sent = false; std::chrono::steady_clock::time_point cliprdr_connected_at{}; uint32_t clipboard_requested_format = 0; + uint32_t clipboard_requested_image_format = 0; + bool clipboard_requested_files = false; uint64_t local_clipboard_revision = 0; uint64_t offered_clipboard_revision = 0; cxrdp_frame_callback frame_callback = nullptr; cxrdp_status_callback status_callback = nullptr; cxrdp_disconnect_callback disconnect_callback = nullptr; cxrdp_clipboard_text_callback clipboard_text_callback = nullptr; + cxrdp_clipboard_image_callback clipboard_image_callback = nullptr; + cxrdp_clipboard_files_callback clipboard_files_callback = nullptr; cxrdp_pointer_callback pointer_callback = nullptr; void* user_data = nullptr; std::string last_error; std::mutex clipboard_mutex; + int local_clipboard_kind = 0; // 0=text, 1=image, 2=files std::string local_clipboard_text; + std::vector local_clipboard_html; + std::vector local_clipboard_rtf; + std::vector local_clipboard_png; + std::vector local_clipboard_dib; + std::vector local_clipboard_files; std::unordered_map locked_clipboard_text; + std::unordered_map> locked_clipboard_files; + std::vector remote_clipboard_files; + std::vector remote_clipboard_top_level_paths; + size_t remote_file_download_index = 0; + uint32_t remote_file_stream_id = 1; + bool remote_file_requesting_size = false; + int last_upload_progress_pct = -1; + int last_download_progress_pct = -1; // Display control (DPI remoting + in-place resize). The worker owns the // FreeRDP objects; a UI call only queues a request here. @@ -431,6 +477,254 @@ void notify_clipboard_text(CxRdpSession* session, const std::string& text) session->clipboard_text_callback(session->user_data, text.c_str()); } +void notify_clipboard_image(CxRdpSession* session, uint32_t imageFormat, const uint8_t* data, uint32_t length) +{ + if (!session || !data || length == 0) + return; + + std::lock_guard lock(session->callback_mutex); + if (session->clipboard_image_callback) + session->clipboard_image_callback(session->user_data, imageFormat, data, length); +} + +void notify_clipboard_files(CxRdpSession* session, const std::vector& paths) +{ + if (!session || paths.empty()) + return; + + std::ostringstream joined; + for (size_t i = 0; i < paths.size(); ++i) + { + if (i > 0) + joined << '\n'; + joined << paths[i]; + } + + const auto payload = joined.str(); + std::lock_guard lock(session->callback_mutex); + if (session->clipboard_files_callback) + session->clipboard_files_callback(session->user_data, payload.c_str()); +} + +uint64_t get_file_last_write_time(const std::filesystem::path& path) +{ +#if defined(_WIN32) + WIN32_FILE_ATTRIBUTE_DATA attrData{}; + if (!GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &attrData)) + return 0; + + return (static_cast(attrData.ftLastWriteTime.dwHighDateTime) << 32) | + static_cast(attrData.ftLastWriteTime.dwLowDateTime); +#else + (void)path; + return 0; +#endif +} + +std::vector serialize_file_group_descriptor_w(const std::vector& files) +{ + constexpr size_t descriptorSize = 592; + const uint32_t count = static_cast(files.size()); + std::vector buffer(4 + static_cast(count) * descriptorSize, 0); + + buffer[0] = static_cast(count & 0xFFu); + buffer[1] = static_cast((count >> 8) & 0xFFu); + buffer[2] = static_cast((count >> 16) & 0xFFu); + buffer[3] = static_cast((count >> 24) & 0xFFu); + + std::wstring_convert, char16_t> converter; + for (size_t i = 0; i < files.size(); ++i) + { + const auto& entry = files[i]; + BYTE* dst = buffer.data() + 4 + i * descriptorSize; + + // dwFlags: FD_ATTRIBUTES (0x04) | FD_FILESIZE (0x40) | FD_PROGRESSUI (0x4000) [| FD_WRITESTIME (0x20)] + uint32_t flags = 0x00004044u; + if (entry.last_write_time != 0) + { + flags |= 0x00000020u; + const uint32_t writeTimeLow = static_cast(entry.last_write_time & 0xFFFFFFFFu); + const uint32_t writeTimeHigh = static_cast((entry.last_write_time >> 32) & 0xFFFFFFFFu); + std::memcpy(dst + 56, &writeTimeLow, 4); + std::memcpy(dst + 60, &writeTimeHigh, 4); + } + std::memcpy(dst + 0, &flags, 4); + + const uint32_t attrs = entry.is_directory ? 0x00000010u : 0x00000020u; + std::memcpy(dst + 36, &attrs, 4); + + const uint32_t sizeHigh = static_cast((entry.file_size >> 32) & 0xFFFFFFFFu); + const uint32_t sizeLow = static_cast(entry.file_size & 0xFFFFFFFFu); + std::memcpy(dst + 64, &sizeHigh, 4); + std::memcpy(dst + 68, &sizeLow, 4); + + std::u16string utf16Name; + try + { + utf16Name = converter.from_bytes(entry.relative_name); + } + catch (const std::range_error&) + { + for (const unsigned char ch : entry.relative_name) + utf16Name.push_back(ch < 0x80 ? static_cast(ch) : u'_'); + } + + const size_t maxChars = 259; + const size_t charCount = utf16Name.size() < maxChars ? utf16Name.size() : maxChars; + for (size_t c = 0; c < charCount; ++c) + { + const uint16_t ch = static_cast(utf16Name[c]); + dst[72 + c * 2] = static_cast(ch & 0xFFu); + dst[72 + c * 2 + 1] = static_cast((ch >> 8) & 0xFFu); + } + } + + return buffer; +} + +bool parse_file_group_descriptor_w( + const BYTE* data, + uint32_t length, + const std::filesystem::path& baseDir, + std::vector& outFiles, + std::vector& outTopLevelPaths) +{ + outFiles.clear(); + outTopLevelPaths.clear(); + if (!data || length < 4) + return false; + + uint32_t count = 0; + std::memcpy(&count, data, 4); + constexpr size_t descriptorSize = 592; + if (count == 0 || 4 + static_cast(count) * descriptorSize > length) + return false; + + std::wstring_convert, char16_t> converter; + for (uint32_t i = 0; i < count; ++i) + { + const BYTE* src = data + 4 + static_cast(i) * descriptorSize; + uint32_t attrs = 0; + uint32_t sizeHigh = 0; + uint32_t sizeLow = 0; + std::memcpy(&attrs, src + 36, 4); + std::memcpy(&sizeHigh, src + 64, 4); + std::memcpy(&sizeLow, src + 68, 4); + + std::u16string utf16Name; + for (size_t c = 0; c < 260; ++c) + { + const uint16_t ch = static_cast(src[72 + c * 2] | (static_cast(src[72 + c * 2 + 1]) << 8)); + if (ch == 0) + break; + utf16Name.push_back(static_cast(ch)); + } + + std::string relName; + try + { + relName = converter.to_bytes(utf16Name); + } + catch (const std::range_error&) + { + continue; + } + + if (relName.empty() || relName.find("..") != std::string::npos) + continue; + + std::filesystem::path relPath = std::filesystem::u8path(relName); + RemoteClipboardFileEntry entry{}; + entry.relative_name = relName; + entry.local_path = baseDir / relPath; + entry.is_directory = (attrs & 0x00000010u) != 0; + entry.expected_size = (static_cast(sizeHigh) << 32) | sizeLow; + entry.size_known = entry.expected_size > 0; + outFiles.push_back(entry); + + if (relName.find('\\') == std::string::npos && relName.find('/') == std::string::npos) + outTopLevelPaths.push_back(entry.local_path.u8string()); + } + + return !outFiles.empty(); +} + +UINT request_next_remote_file_chunk(CliprdrClientContext* cliprdr, CxRdpSession* session) +{ + if (!cliprdr || !session || !cliprdr->ClientFileContentsRequest) + return CHANNEL_RC_OK; + + CLIPRDR_FILE_CONTENTS_REQUEST req{}; + bool hasWork = false; + std::vector completedPaths; + + { + std::lock_guard lock(session->clipboard_mutex); + while (session->remote_file_download_index < session->remote_clipboard_files.size()) + { + auto& entry = session->remote_clipboard_files[session->remote_file_download_index]; + if (entry.is_directory) + { + std::error_code ec; + std::filesystem::create_directories(entry.local_path, ec); + ++session->remote_file_download_index; + continue; + } + + if (entry.size_known && entry.received_bytes >= entry.expected_size) + { + if (entry.expected_size == 0) + { + std::error_code ec; + std::filesystem::create_directories(entry.local_path.parent_path(), ec); + std::ofstream emptyFile(entry.local_path, std::ios::binary | std::ios::trunc); + } + ++session->remote_file_download_index; + continue; + } + + req.common.msgType = CB_FILECONTENTS_REQUEST; + req.streamId = ++session->remote_file_stream_id; + req.listIndex = static_cast(session->remote_file_download_index); + if (!entry.size_known) + { + req.dwFlags = FILECONTENTS_SIZE; + req.cbRequested = 8; + session->remote_file_requesting_size = true; + } + else + { + req.dwFlags = FILECONTENTS_RANGE; + req.nPositionLow = static_cast(entry.received_bytes & 0xFFFFFFFFu); + req.nPositionHigh = static_cast((entry.received_bytes >> 32) & 0xFFFFFFFFu); + const uint64_t remaining = entry.expected_size - entry.received_bytes; + req.cbRequested = static_cast(remaining < CX_CLIPRDR_FILE_CHUNK_SIZE ? remaining : CX_CLIPRDR_FILE_CHUNK_SIZE); + session->remote_file_requesting_size = false; + } + hasWork = true; + break; + } + + if (!hasWork && !session->remote_clipboard_top_level_paths.empty()) + { + completedPaths = session->remote_clipboard_top_level_paths; + session->remote_clipboard_top_level_paths.clear(); + session->remote_clipboard_files.clear(); + } + } + + if (hasWork) + return cliprdr->ClientFileContentsRequest(cliprdr, &req); + + if (!completedPaths.empty()) + { + notify_status(session, "RDP clipboard remote files downloaded."); + notify_clipboard_files(session, completedPaths); + } + + return CHANNEL_RC_OK; +} + std::string normalize_clipboard_newlines(const std::string& value) { std::string normalized; @@ -689,6 +983,20 @@ const char* clipboard_format_name(uint32_t formatId) return "CF_OEMTEXT"; case CF_UNICODETEXT: return "CF_UNICODETEXT"; + case CF_DIB: + return "CF_DIB"; + case CF_DIBV5: + return "CF_DIBV5"; + case CX_CLIPRDR_FORMAT_PNG: + return "PNG"; + case CX_CLIPRDR_FORMAT_HTML: + return "HTML Format"; + case CX_CLIPRDR_FORMAT_RTF: + return "Rich Text Format"; + case CX_CLIPRDR_FORMAT_FILE_GROUP_DESCRIPTOR_W: + return "FileGroupDescriptorW"; + case CX_CLIPRDR_FORMAT_FILE_CONTENTS: + return "FileContents"; default: return "UNKNOWN"; } @@ -795,7 +1103,11 @@ UINT send_client_capabilities(CliprdrClientContext* cliprdr) generalCapabilitySet.capabilitySetType = CB_CAPSTYPE_GENERAL; generalCapabilitySet.capabilitySetLength = CB_CAPSTYPE_GENERAL_LEN; generalCapabilitySet.version = CB_CAPS_VERSION_2; - generalCapabilitySet.generalFlags = CB_USE_LONG_FORMAT_NAMES; + generalCapabilitySet.generalFlags = + CB_USE_LONG_FORMAT_NAMES | + CB_STREAM_FILECLIP_ENABLED | + CB_FILECLIP_NO_FILE_PATHS | + CB_HUGE_FILE_SUPPORT_ENABLED; if (!session || session->clipboard_lock_enabled) generalCapabilitySet.generalFlags |= CB_CAN_LOCK_CLIPDATA; @@ -824,24 +1136,105 @@ UINT send_client_format_list(CliprdrClientContext* cliprdr) if (!cliprdr || !cliprdr->ClientFormatList) return CHANNEL_RC_OK; - CLIPRDR_FORMAT formats[3]{}; - formats[0].formatId = CF_UNICODETEXT; - formats[1].formatId = CF_TEXT; - formats[2].formatId = CF_OEMTEXT; + auto* session = static_cast(cliprdr->custom); + int kind = 0; + bool hasPng = false; + bool hasDib = false; + bool hasFiles = false; + bool hasHtml = false; + bool hasRtf = false; + if (session) + { + std::lock_guard lock(session->clipboard_mutex); + kind = session->local_clipboard_kind; + hasPng = !session->local_clipboard_png.empty(); + hasDib = !session->local_clipboard_dib.empty(); + hasFiles = !session->local_clipboard_files.empty(); + hasHtml = !session->local_clipboard_html.empty(); + hasRtf = !session->local_clipboard_rtf.empty(); + } + + std::vector formats; + static char pngFormatName[] = "PNG"; + static char fileGroupDescriptorName[] = "FileGroupDescriptorW"; + static char fileContentsName[] = "FileContents"; + static char htmlFormatName[] = "HTML Format"; + static char rtfFormatName[] = "Rich Text Format"; + const char* kindLabel = "text"; + + if (kind == 2 && hasFiles) + { + kindLabel = "files"; + CLIPRDR_FORMAT fileFormat{}; + fileFormat.formatId = CX_CLIPRDR_FORMAT_FILE_GROUP_DESCRIPTOR_W; + fileFormat.formatName = fileGroupDescriptorName; + formats.push_back(fileFormat); + + CLIPRDR_FORMAT fileContentsFormat{}; + fileContentsFormat.formatId = CX_CLIPRDR_FORMAT_FILE_CONTENTS; + fileContentsFormat.formatName = fileContentsName; + formats.push_back(fileContentsFormat); + } + else if (kind == 1 && (hasPng || hasDib)) + { + kindLabel = "image"; + if (hasDib) + { + CLIPRDR_FORMAT dibFormat{}; + dibFormat.formatId = CF_DIB; + formats.push_back(dibFormat); + } + if (hasPng) + { + CLIPRDR_FORMAT pngFormat{}; + pngFormat.formatId = CX_CLIPRDR_FORMAT_PNG; + pngFormat.formatName = pngFormatName; + formats.push_back(pngFormat); + } + } + else + { + CLIPRDR_FORMAT unicodeFormat{}; + unicodeFormat.formatId = CF_UNICODETEXT; + formats.push_back(unicodeFormat); + + CLIPRDR_FORMAT textFormat{}; + textFormat.formatId = CF_TEXT; + formats.push_back(textFormat); + + CLIPRDR_FORMAT oemFormat{}; + oemFormat.formatId = CF_OEMTEXT; + formats.push_back(oemFormat); + + if (hasHtml) + { + CLIPRDR_FORMAT htmlFormat{}; + htmlFormat.formatId = CX_CLIPRDR_FORMAT_HTML; + htmlFormat.formatName = htmlFormatName; + formats.push_back(htmlFormat); + } + + if (hasRtf) + { + CLIPRDR_FORMAT rtfFormat{}; + rtfFormat.formatId = CX_CLIPRDR_FORMAT_RTF; + rtfFormat.formatName = rtfFormatName; + formats.push_back(rtfFormat); + } + } CLIPRDR_FORMAT_LIST formatList{}; formatList.common.msgType = CB_FORMAT_LIST; formatList.common.msgFlags = 0; - formatList.common.dataLen = sizeof(formats); - formatList.numFormats = static_cast(sizeof(formats) / sizeof(formats[0])); - formatList.formats = formats; + formatList.common.dataLen = static_cast(formats.size() * sizeof(CLIPRDR_FORMAT)); + formatList.numFormats = static_cast(formats.size()); + formatList.formats = formats.data(); - auto* session = static_cast(cliprdr->custom); const UINT rc = cliprdr->ClientFormatList(cliprdr, &formatList); if (session) { std::ostringstream message; - message << "RDP clipboard offered local text formats. rc=" << rc; + message << "RDP clipboard offered local " << kindLabel << " formats. rc=" << rc; notify_status(session, message.str().c_str()); } @@ -1462,29 +1855,83 @@ UINT cx_cliprdr_server_format_list(CliprdrClientContext* cliprdr, const CLIPRDR_ return CHANNEL_RC_OK; auto* session = static_cast(cliprdr->custom); - uint32_t selectedFormat = 0; + uint32_t selectedTextFormat = 0; + uint32_t selectedImageFormat = 0; + uint32_t selectedImageKind = 0; + uint32_t selectedFilesFormat = 0; for (UINT32 index = 0; index < formatList->numFormats; ++index) { - const uint32_t formatId = formatList->formats[index].formatId; + const auto& fmt = formatList->formats[index]; + const uint32_t formatId = fmt.formatId; if (formatId == CF_UNICODETEXT) { - selectedFormat = CF_UNICODETEXT; - break; + selectedTextFormat = CF_UNICODETEXT; + } + else if (formatId == CF_TEXT && selectedTextFormat == 0) + { + selectedTextFormat = CF_TEXT; + } + else if (formatId == CF_OEMTEXT && selectedTextFormat == 0) + { + selectedTextFormat = CF_OEMTEXT; } - if (formatId == CF_TEXT && selectedFormat == 0) - selectedFormat = CF_TEXT; - else if (formatId == CF_OEMTEXT && selectedFormat == 0) - selectedFormat = CF_OEMTEXT; + if (fmt.formatName && equals_ignore_case(fmt.formatName, "FileGroupDescriptorW")) + { + selectedFilesFormat = formatId; + } + else if (fmt.formatName && + (equals_ignore_case(fmt.formatName, "PNG") || equals_ignore_case(fmt.formatName, "image/png"))) + { + selectedImageFormat = formatId; + selectedImageKind = CX_RDP_CLIPBOARD_IMAGE_PNG; + } + else if (formatId == CF_DIB && selectedImageKind != CX_RDP_CLIPBOARD_IMAGE_PNG) + { + selectedImageFormat = CF_DIB; + selectedImageKind = CX_RDP_CLIPBOARD_IMAGE_DIB; + } + else if (formatId == CF_DIBV5 && selectedImageFormat == 0) + { + selectedImageFormat = CF_DIBV5; + selectedImageKind = CX_RDP_CLIPBOARD_IMAGE_DIB; + } + } + + uint32_t selectedFormat = 0; + uint32_t requestedImageKind = 0; + bool requestedFiles = false; + if (selectedFilesFormat != 0) + { + selectedFormat = selectedFilesFormat; + requestedFiles = true; + } + else if (selectedTextFormat == CF_UNICODETEXT) + { + selectedFormat = selectedTextFormat; + } + else if (selectedImageFormat != 0) + { + selectedFormat = selectedImageFormat; + requestedImageKind = selectedImageKind; + } + else + { + selectedFormat = selectedTextFormat; } if (session) { + { + std::lock_guard lock(session->clipboard_mutex); + session->clipboard_requested_image_format = requestedImageKind; + session->clipboard_requested_files = requestedFiles; + } mark_cliprdr_confirmed(session, "remote formats"); std::ostringstream message; message << "RDP clipboard remote formats received. count=" << formatList->numFormats - << " selected=" << clipboard_format_name(selectedFormat); + << " selected=" << (requestedFiles ? "FileGroupDescriptorW" : (requestedImageKind == CX_RDP_CLIPBOARD_IMAGE_PNG ? "PNG" : clipboard_format_name(selectedFormat))); notify_status(session, message.str().c_str()); } @@ -1535,6 +1982,8 @@ UINT cx_cliprdr_server_lock_clipboard_data( if (session->clipboard_lock_enabled) { session->locked_clipboard_text[lockClipboardData->clipDataId] = session->local_clipboard_text; + if (!session->local_clipboard_files.empty()) + session->locked_clipboard_files[lockClipboardData->clipDataId] = session->local_clipboard_files; locked = true; } } @@ -1560,7 +2009,9 @@ UINT cx_cliprdr_server_unlock_clipboard_data( bool unlocked = false; { std::lock_guard lock(session->clipboard_mutex); - unlocked = session->locked_clipboard_text.erase(unlockClipboardData->clipDataId) > 0; + const bool unlockedText = session->locked_clipboard_text.erase(unlockClipboardData->clipDataId) > 0; + const bool unlockedFiles = session->locked_clipboard_files.erase(unlockClipboardData->clipDataId) > 0; + unlocked = unlockedText || unlockedFiles; } if (unlocked) { @@ -1590,7 +2041,97 @@ UINT cx_cliprdr_server_format_data_request( response.common.dataLen = 0; response.requestedFormatData = nullptr; - if (session && is_supported_text_format(formatDataRequest->requestedFormatId)) + if (session && formatDataRequest->requestedFormatId == CX_CLIPRDR_FORMAT_FILE_GROUP_DESCRIPTOR_W) + { + std::vector files; + { + std::lock_guard lock(session->clipboard_mutex); + if (session->local_clipboard_kind == 2 && !session->local_clipboard_files.empty()) + files = session->local_clipboard_files; + } + + if (!files.empty()) + { + data = serialize_file_group_descriptor_w(files); + response.common.msgFlags = CB_RESPONSE_OK; + response.common.dataLen = static_cast(data.size()); + response.requestedFormatData = data.data(); + + std::ostringstream message; + message << "RDP clipboard remote requested local file list. count=" << files.size() + << " bytes=" << data.size(); + notify_status(session, message.str().c_str()); + } + } + else if (session && formatDataRequest->requestedFormatId == CF_DIB) + { + { + std::lock_guard lock(session->clipboard_mutex); + if (session->local_clipboard_kind == 1 && !session->local_clipboard_dib.empty()) + data.assign(session->local_clipboard_dib.begin(), session->local_clipboard_dib.end()); + } + + if (!data.empty()) + { + response.common.msgFlags = CB_RESPONSE_OK; + response.common.dataLen = static_cast(data.size()); + response.requestedFormatData = data.data(); + + std::ostringstream message; + message << "RDP clipboard remote requested local image. format=CF_DIB bytes=" << data.size(); + notify_status(session, message.str().c_str()); + } + } + else if (session && formatDataRequest->requestedFormatId == CX_CLIPRDR_FORMAT_PNG) + { + { + std::lock_guard lock(session->clipboard_mutex); + if (session->local_clipboard_kind == 1 && !session->local_clipboard_png.empty()) + data.assign(session->local_clipboard_png.begin(), session->local_clipboard_png.end()); + } + + if (!data.empty()) + { + response.common.msgFlags = CB_RESPONSE_OK; + response.common.dataLen = static_cast(data.size()); + response.requestedFormatData = data.data(); + + std::ostringstream message; + message << "RDP clipboard remote requested local image. format=PNG bytes=" << data.size(); + notify_status(session, message.str().c_str()); + } + } + else if (session && formatDataRequest->requestedFormatId == CX_CLIPRDR_FORMAT_HTML) + { + { + std::lock_guard lock(session->clipboard_mutex); + if (session->local_clipboard_kind == 0 && !session->local_clipboard_html.empty()) + data.assign(session->local_clipboard_html.begin(), session->local_clipboard_html.end()); + } + + if (!data.empty()) + { + response.common.msgFlags = CB_RESPONSE_OK; + response.common.dataLen = static_cast(data.size()); + response.requestedFormatData = data.data(); + } + } + else if (session && formatDataRequest->requestedFormatId == CX_CLIPRDR_FORMAT_RTF) + { + { + std::lock_guard lock(session->clipboard_mutex); + if (session->local_clipboard_kind == 0 && !session->local_clipboard_rtf.empty()) + data.assign(session->local_clipboard_rtf.begin(), session->local_clipboard_rtf.end()); + } + + if (!data.empty()) + { + response.common.msgFlags = CB_RESPONSE_OK; + response.common.dataLen = static_cast(data.size()); + response.requestedFormatData = data.data(); + } + } + else if (session && is_supported_text_format(formatDataRequest->requestedFormatId)) { std::string text; { @@ -1638,17 +2179,65 @@ UINT cx_cliprdr_server_format_data_response( return CHANNEL_RC_OK; uint32_t requestedFormat = 0; + uint32_t requestedImageKind = 0; + bool requestedFiles = false; { std::lock_guard lock(session->clipboard_mutex); requestedFormat = session->clipboard_requested_format; + requestedImageKind = session->clipboard_requested_image_format; + requestedFiles = session->clipboard_requested_files; session->clipboard_requested_format = 0; + session->clipboard_requested_image_format = 0; + session->clipboard_requested_files = false; + } + + const auto* data = formatDataResponse->requestedFormatData; + const auto length = formatDataResponse->common.dataLen; + + if (requestedFiles) + { + if (data && length > 0) + { + const auto stamp = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + std::error_code ec; + const auto baseDir = std::filesystem::temp_directory_path(ec) / "CxShell-RdpClip" / std::to_string(stamp); + std::filesystem::create_directories(baseDir, ec); + + std::vector parsedFiles; + std::vector topLevelPaths; + if (parse_file_group_descriptor_w(data, length, baseDir, parsedFiles, topLevelPaths)) + { + { + std::lock_guard lock(session->clipboard_mutex); + session->remote_clipboard_files = std::move(parsedFiles); + session->remote_clipboard_top_level_paths = std::move(topLevelPaths); + session->remote_file_download_index = 0; + session->remote_file_requesting_size = false; + } + return request_next_remote_file_chunk(cliprdr, session); + } + } + return CHANNEL_RC_OK; + } + + if (requestedImageKind != 0) + { + if (data && length > 0) + { + std::ostringstream message; + message << "RDP clipboard remote image received. kind=" << requestedImageKind + << " bytes=" << length; + notify_status(session, message.str().c_str()); + notify_clipboard_image(session, requestedImageKind, data, length); + } + return CHANNEL_RC_OK; } if (!is_supported_text_format(requestedFormat)) return CHANNEL_RC_OK; - const auto* data = formatDataResponse->requestedFormatData; - const auto length = formatDataResponse->common.dataLen; { std::ostringstream message; message << "RDP clipboard remote data received. format=" @@ -1664,18 +2253,242 @@ UINT cx_cliprdr_server_file_contents_request( CliprdrClientContext* cliprdr, const CLIPRDR_FILE_CONTENTS_REQUEST* fileContentsRequest) { - (void)cliprdr; - (void)fileContentsRequest; - return CHANNEL_RC_OK; + if (!cliprdr || !fileContentsRequest || !cliprdr->ClientFileContentsResponse) + return CHANNEL_RC_OK; + + auto* session = static_cast(cliprdr->custom); + CLIPRDR_FILE_CONTENTS_RESPONSE response{}; + response.common.msgType = CB_FILECONTENTS_RESPONSE; + response.common.msgFlags = CB_RESPONSE_FAIL; + response.streamId = fileContentsRequest->streamId; + + LocalClipboardFileEntry entry{}; + bool found = false; + if (session) + { + std::lock_guard lock(session->clipboard_mutex); + if (fileContentsRequest->haveClipDataId) + { + const auto it = session->locked_clipboard_files.find(fileContentsRequest->clipDataId); + if (it != session->locked_clipboard_files.end() && + fileContentsRequest->listIndex < it->second.size()) + { + entry = it->second[fileContentsRequest->listIndex]; + found = true; + } + } + if (!found && + session->local_clipboard_kind == 2 && + fileContentsRequest->listIndex < session->local_clipboard_files.size()) + { + entry = session->local_clipboard_files[fileContentsRequest->listIndex]; + found = true; + } + } + + static constexpr BYTE kEmptyPayload = 0; + std::vector payload; + if (found && (fileContentsRequest->dwFlags & FILECONTENTS_SIZE) != 0) + { + payload.resize(8); + const uint64_t size = entry.file_size; + std::memcpy(payload.data(), &size, 8); + response.common.msgFlags = CB_RESPONSE_OK; + response.cbRequested = 8; + response.requestedData = payload.data(); + } + else if (found && !entry.is_directory && (fileContentsRequest->dwFlags & FILECONTENTS_RANGE) != 0) + { + const uint64_t offset = + (static_cast(fileContentsRequest->nPositionHigh) << 32) | + fileContentsRequest->nPositionLow; + const uint32_t toRead = fileContentsRequest->cbRequested; +#if defined(_WIN32) + HANDLE hFile = CreateFileW( + entry.full_path.c_str(), + GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + nullptr); + if (hFile == INVALID_HANDLE_VALUE) + { + if (session) + { + std::ostringstream msg; + msg << "RDP clipboard file contents read failed: could not open " + << entry.relative_name << " (error=" << GetLastError() << ")"; + notify_status(session, msg.str().c_str()); + } + } + else + { + bool readOk = true; + uint32_t bytesRead = 0; + DWORD winErr = 0; + if (toRead > 0) + { + LARGE_INTEGER liOffset{}; + liOffset.QuadPart = static_cast(offset); + if (!SetFilePointerEx(hFile, liOffset, nullptr, FILE_BEGIN)) + { + readOk = false; + winErr = GetLastError(); + } + else + { + payload.resize(toRead); + DWORD chunkRead = 0; + if (!ReadFile(hFile, payload.data(), toRead, &chunkRead, nullptr)) + { + readOk = false; + winErr = GetLastError(); + } + else + { + bytesRead = static_cast(chunkRead); + } + } + } + CloseHandle(hFile); + + if (readOk) + { + payload.resize(bytesRead); + response.common.msgFlags = CB_RESPONSE_OK; + response.cbRequested = bytesRead; + response.requestedData = payload.empty() ? &kEmptyPayload : payload.data(); + } + else if (session) + { + std::ostringstream msg; + msg << "RDP clipboard file contents read failed: " << entry.relative_name + << " (error=" << winErr << ")"; + notify_status(session, msg.str().c_str()); + } + } +#else + std::ifstream file(entry.full_path, std::ios::binary); + if (file) + { + uint32_t bytesRead = 0; + if (toRead > 0) + { + file.seekg(static_cast(offset), std::ios::beg); + payload.resize(toRead); + file.read(reinterpret_cast(payload.data()), static_cast(toRead)); + bytesRead = static_cast(file.gcount()); + } + payload.resize(bytesRead); + response.common.msgFlags = CB_RESPONSE_OK; + response.cbRequested = bytesRead; + response.requestedData = payload.empty() ? &kEmptyPayload : payload.data(); + } +#endif + + if (response.common.msgFlags == CB_RESPONSE_OK && session && entry.file_size > 0) + { + const uint64_t sent = offset + response.cbRequested; + const int pct = static_cast(sent >= entry.file_size ? 100 : (sent * 100) / entry.file_size); + bool shouldNotify = false; + { + std::lock_guard lock(session->clipboard_mutex); + if (pct == 100 || session->last_upload_progress_pct < 0 || pct - session->last_upload_progress_pct >= 10) + { + session->last_upload_progress_pct = pct == 100 ? -1 : pct; + shouldNotify = true; + } + } + if (shouldNotify) + { + std::ostringstream msg; + msg << "RDP clipboard uploading " << entry.relative_name << " (" << pct << "%)"; + notify_status(session, msg.str().c_str()); + } + } + } + + return cliprdr->ClientFileContentsResponse(cliprdr, &response); } UINT cx_cliprdr_server_file_contents_response( CliprdrClientContext* cliprdr, const CLIPRDR_FILE_CONTENTS_RESPONSE* fileContentsResponse) { - (void)cliprdr; - (void)fileContentsResponse; - return CHANNEL_RC_OK; + if (!cliprdr || !fileContentsResponse) + return CHANNEL_RC_OK; + + auto* session = static_cast(cliprdr->custom); + if (!session) + return CHANNEL_RC_OK; + + if ((fileContentsResponse->common.msgFlags & CB_RESPONSE_FAIL) != 0) + { + std::lock_guard lock(session->clipboard_mutex); + session->remote_clipboard_files.clear(); + session->remote_clipboard_top_level_paths.clear(); + return CHANNEL_RC_OK; + } + + std::string progressMessage; + { + std::lock_guard lock(session->clipboard_mutex); + if (session->remote_file_download_index < session->remote_clipboard_files.size()) + { + auto& entry = session->remote_clipboard_files[session->remote_file_download_index]; + if (session->remote_file_requesting_size) + { + if (fileContentsResponse->cbRequested >= 8 && fileContentsResponse->requestedData) + { + uint64_t size = 0; + std::memcpy(&size, fileContentsResponse->requestedData, 8); + entry.expected_size = size; + } + entry.size_known = true; + session->remote_file_requesting_size = false; + } + else + { + std::error_code ec; + std::filesystem::create_directories(entry.local_path.parent_path(), ec); + const auto mode = entry.received_bytes == 0 + ? (std::ios::binary | std::ios::trunc) + : (std::ios::binary | std::ios::app); + std::ofstream out(entry.local_path, mode); + if (out && fileContentsResponse->requestedData && fileContentsResponse->cbRequested > 0) + { + out.write( + reinterpret_cast(fileContentsResponse->requestedData), + static_cast(fileContentsResponse->cbRequested)); + entry.received_bytes += fileContentsResponse->cbRequested; + if (entry.expected_size > 0) + { + const int pct = static_cast( + entry.received_bytes >= entry.expected_size + ? 100 + : (entry.received_bytes * 100) / entry.expected_size); + if (pct == 100 || session->last_download_progress_pct < 0 || pct - session->last_download_progress_pct >= 10) + { + session->last_download_progress_pct = pct == 100 ? -1 : pct; + std::ostringstream msg; + msg << "RDP clipboard downloading " << entry.relative_name << " (" << pct << "%)"; + progressMessage = msg.str(); + } + } + } + else + { + entry.received_bytes = entry.expected_size; + } + } + } + } + + if (!progressMessage.empty()) + notify_status(session, progressMessage.c_str()); + + return request_next_remote_file_chunk(cliprdr, session); } void initialize_cliprdr(CxRdpSession* session, CliprdrClientContext* cliprdr) @@ -1693,6 +2506,12 @@ void initialize_cliprdr(CxRdpSession* session, CliprdrClientContext* cliprdr) session->client_capabilities_sent = false; session->cliprdr_connected_at = std::chrono::steady_clock::now(); session->clipboard_requested_format = 0; + session->clipboard_requested_image_format = 0; + session->clipboard_requested_files = false; + session->remote_clipboard_files.clear(); + session->remote_clipboard_top_level_paths.clear(); + session->remote_file_download_index = 0; + session->remote_file_requesting_size = false; } cliprdr->custom = session; @@ -1729,6 +2548,12 @@ void uninitialize_cliprdr(CxRdpSession* session, CliprdrClientContext* cliprdr) session->cliprdr_wait_logged = false; session->client_capabilities_sent = false; session->clipboard_requested_format = 0; + session->clipboard_requested_image_format = 0; + session->clipboard_requested_files = false; + session->remote_clipboard_files.clear(); + session->remote_clipboard_top_level_paths.clear(); + session->remote_file_download_index = 0; + session->remote_file_requesting_size = false; } } @@ -3243,6 +4068,9 @@ CX_RDP_API uint32_t cxrdp_get_capabilities(void) CX_RDP_CAPABILITY_GFX | CX_RDP_CAPABILITY_SYNC_LOCK_KEYS | CX_RDP_CAPABILITY_POINTER_SHAPE | + CX_RDP_CAPABILITY_CLIPBOARD_IMAGE | + CX_RDP_CAPABILITY_CLIPBOARD_FILES | + CX_RDP_CAPABILITY_CLIPBOARD_RICH_TEXT | CX_RDP_CAPABILITY_CLIPBOARD_LOCK | CX_RDP_CAPABILITY_MULTI_MONITOR | CX_RDP_CAPABILITY_GFX_H264; @@ -3298,6 +4126,30 @@ CX_RDP_API void cxrdp_set_clipboard_callback( session->clipboard_text_callback = clipboard_text_callback; } +CX_RDP_API void cxrdp_set_clipboard_image_callback( + void* handle, + cxrdp_clipboard_image_callback clipboard_image_callback) +{ + auto* session = static_cast(handle); + if (!session) + return; + + std::lock_guard lock(session->callback_mutex); + session->clipboard_image_callback = clipboard_image_callback; +} + +CX_RDP_API void cxrdp_set_clipboard_files_callback( + void* handle, + cxrdp_clipboard_files_callback clipboard_files_callback) +{ + auto* session = static_cast(handle); + if (!session) + return; + + std::lock_guard lock(session->callback_mutex); + session->clipboard_files_callback = clipboard_files_callback; +} + CX_RDP_API void cxrdp_set_pointer_callback( void* handle, cxrdp_pointer_callback pointer_callback) @@ -3449,7 +4301,161 @@ CX_RDP_API void cxrdp_set_clipboard_text(void* handle, const char* text) { std::lock_guard lock(session->clipboard_mutex); + session->local_clipboard_kind = 0; session->local_clipboard_text = text ? text : ""; + session->local_clipboard_html.clear(); + session->local_clipboard_rtf.clear(); + session->local_clipboard_png.clear(); + session->local_clipboard_dib.clear(); + session->local_clipboard_files.clear(); + ++session->local_clipboard_revision; + } +} + +CX_RDP_API void cxrdp_set_clipboard_rich_text( + void* handle, + const char* plain_text, + const uint8_t* html_bytes, + uint32_t html_length, + const uint8_t* rtf_bytes, + uint32_t rtf_length) +{ + auto* session = static_cast(handle); + if (!session) + return; + + { + std::lock_guard lock(session->clipboard_mutex); + session->local_clipboard_kind = 0; + session->local_clipboard_text = plain_text ? plain_text : ""; + if (html_bytes && html_length > 0) + session->local_clipboard_html.assign(html_bytes, html_bytes + html_length); + else + session->local_clipboard_html.clear(); + if (rtf_bytes && rtf_length > 0) + session->local_clipboard_rtf.assign(rtf_bytes, rtf_bytes + rtf_length); + else + session->local_clipboard_rtf.clear(); + session->local_clipboard_png.clear(); + session->local_clipboard_dib.clear(); + session->local_clipboard_files.clear(); + ++session->local_clipboard_revision; + } +} + +CX_RDP_API void cxrdp_set_clipboard_image( + void* handle, + uint32_t image_format, + const uint8_t* data, + uint32_t length) +{ + auto* session = static_cast(handle); + if (!session || !data || length == 0) + return; + + if (image_format != CX_RDP_CLIPBOARD_IMAGE_PNG && + image_format != CX_RDP_CLIPBOARD_IMAGE_DIB) + return; + + { + std::lock_guard lock(session->clipboard_mutex); + session->local_clipboard_kind = 1; + session->local_clipboard_text.clear(); + session->local_clipboard_html.clear(); + session->local_clipboard_rtf.clear(); + session->local_clipboard_files.clear(); + if (image_format == CX_RDP_CLIPBOARD_IMAGE_PNG) + { + session->local_clipboard_png.assign(data, data + length); + session->local_clipboard_dib.clear(); + } + else + { + session->local_clipboard_dib.assign(data, data + length); + session->local_clipboard_png.clear(); + } + ++session->local_clipboard_revision; + } +} + +CX_RDP_API void cxrdp_set_clipboard_files(void* handle, const char* file_paths_newline_separated) +{ + auto* session = static_cast(handle); + if (!session || !file_paths_newline_separated) + return; + + std::vector entries; + std::istringstream stream(file_paths_newline_separated); + std::string line; + while (std::getline(stream, line)) + { + if (!line.empty() && line.back() == '\r') + line.pop_back(); + while (line.size() > 1 && (line.back() == '\\' || line.back() == '/')) + { + if (line.size() == 3 && std::isalpha(static_cast(line[0])) && line[1] == ':') + break; + line.pop_back(); + } + if (line.empty()) + continue; + + std::error_code ec; + const auto rootPath = std::filesystem::u8path(line); + if (!std::filesystem::exists(rootPath, ec)) + continue; + + const auto rootName = rootPath.filename().u8string(); + if (rootName.empty()) + continue; + + if (std::filesystem::is_directory(rootPath, ec)) + { + entries.push_back({rootName, rootPath, true, 0, get_file_last_write_time(rootPath)}); + for (auto it = std::filesystem::recursive_directory_iterator( + rootPath, + std::filesystem::directory_options::skip_permission_denied, + ec); + !ec && it != std::filesystem::recursive_directory_iterator(); + it.increment(ec)) + { + const auto& item = *it; + const auto rel = std::filesystem::relative(item.path(), rootPath, ec); + if (ec) + { + ec.clear(); + continue; + } + std::string relName = rootName + "\\" + rel.u8string(); + for (char& ch : relName) + { + if (ch == '/') + ch = '\\'; + } + const bool isDir = item.is_directory(ec); + const uint64_t size = isDir ? 0 : item.file_size(ec); + entries.push_back({relName, item.path(), isDir, size, get_file_last_write_time(item.path())}); + } + } + else if (std::filesystem::is_regular_file(rootPath, ec)) + { + const uint64_t size = std::filesystem::file_size(rootPath, ec); + entries.push_back({rootName, rootPath, false, size, get_file_last_write_time(rootPath)}); + } + } + + if (entries.empty()) + return; + + { + std::lock_guard lock(session->clipboard_mutex); + session->local_clipboard_kind = 2; + session->local_clipboard_text.clear(); + session->local_clipboard_html.clear(); + session->local_clipboard_rtf.clear(); + session->local_clipboard_png.clear(); + session->local_clipboard_dib.clear(); + session->local_clipboard_files = std::move(entries); ++session->local_clipboard_revision; } } From 4237cb068722c207d49bdfa937e479af301732f6 Mon Sep 17 00:00:00 2001 From: heartacker Date: Wed, 25 Nov 2026 16:24:17 +0800 Subject: [PATCH 15/15] fix(rdp): stabilize dynamic resolution and DPI following --- Services/RdpDisplaySizeResolver.cs | 8 +- ViewModels/RdpViewModel.cs | 110 +++++++++++++++++++++++----- Views/RdpView.axaml.cs | 4 +- native/CxRdpBridge/cxrdp_bridge.cpp | 3 + 4 files changed, 102 insertions(+), 23 deletions(-) diff --git a/Services/RdpDisplaySizeResolver.cs b/Services/RdpDisplaySizeResolver.cs index e8258eb..4277217 100644 --- a/Services/RdpDisplaySizeResolver.cs +++ b/Services/RdpDisplaySizeResolver.cs @@ -42,9 +42,11 @@ public static class RdpDisplaySizeResolver private static RdpDesktopSize Clamp(int width, int height) { - return new RdpDesktopSize( - Math.Clamp(width, MinimumWidth, MaximumWidth), - Math.Clamp(height, MinimumHeight, MaximumHeight)); + // MS-RDPEDISP (DISPLAYCONTROL_MONITOR_LAYOUT) requires an even width; + // Windows servers silently reject odd widths. + var clampedWidth = Math.Clamp(width, MinimumWidth, MaximumWidth) & ~1; + var clampedHeight = Math.Clamp(height, MinimumHeight, MaximumHeight); + return new RdpDesktopSize(clampedWidth, clampedHeight); } private static double NormalizeRenderScaling(double renderScaling) diff --git a/ViewModels/RdpViewModel.cs b/ViewModels/RdpViewModel.cs index 552ca49..bad1367 100644 --- a/ViewModels/RdpViewModel.cs +++ b/ViewModels/RdpViewModel.cs @@ -23,10 +23,12 @@ public partial class RdpViewModel : ObservableObject, IDisposable private RdpReconnectPhase _reconnectPhase = RdpReconnectPhase.None; private int _reconnectAttempt; private double _renderScaling = 1; + private CancellationTokenSource? _resizeDebounceCts; private CancellationTokenSource? _resizeReconnectCts; private CancellationTokenSource? _connectWatchdogCts; private int? _runtimeDesktopWidth; private int? _runtimeDesktopHeight; + private int? _runtimeDisplayScalePercent; private WriteableBitmap? _bitmapA; private WriteableBitmap? _bitmapB; private bool _useBitmapA; @@ -158,12 +160,14 @@ public void Start() { try { + var initialScale = RdpDpiScale.ResolveScalePercent(ResolveDpiPolicy(), _renderScaling); + _runtimeDisplayScalePercent = initialScale; _client.Connect( Session, Password, _runtimeDesktopWidth, _runtimeDesktopHeight, - RdpDpiScale.ResolveScalePercent(ResolveDpiPolicy(), _renderScaling)); + initialScale); // Do not reset IsConnected here: Connect() only starts the // native worker. A posted "false" used to race the "RDP // connected." status and clear the state right after the @@ -392,7 +396,7 @@ private static string GetDisplayStatusText(string message) [RelayCommand] public void Reconnect() { - _resizeReconnectCts?.Cancel(); + CancelPendingResize(); CancelConnectWatchdog(); _reconnectPhase = RdpReconnectPhase.None; _reconnectAttempt = 0; @@ -425,7 +429,7 @@ public void CancelReconnect() public void Disconnect() { - _resizeReconnectCts?.Cancel(); + CancelPendingResize(); CancelConnectWatchdog(); // The native bridge only reports a disconnect while it believes the // transport is live, so remember whether this teardown can produce one. @@ -457,8 +461,30 @@ public void ConfigureInitialDisplay(Size viewportSize, PixelSize? monitorPixelSi _runtimeDesktopHeight = size.Value.Height; } + private void CancelPendingResize() + { + var debounceCts = _resizeDebounceCts; + _resizeDebounceCts = null; + if (debounceCts != null) + { + try { debounceCts.Cancel(); } catch (ObjectDisposedException) { } + debounceCts.Dispose(); + } + + var reconnectCts = _resizeReconnectCts; + _resizeReconnectCts = null; + if (reconnectCts != null) + { + try { reconnectCts.Cancel(); } catch (ObjectDisposedException) { } + reconnectCts.Dispose(); + } + } + public void RequestViewportResize(Size viewportSize, double renderScaling = 1) { + if (renderScaling > 0) + _renderScaling = renderScaling; + if (!IsConnected || !UsesReconnectResizeMode(Session) || viewportSize.Width < 320 || @@ -467,32 +493,78 @@ public void RequestViewportResize(Size viewportSize, double renderScaling = 1) return; } - var size = RdpDisplaySizeResolver.ResolveViewport(viewportSize, renderScaling); + var size = RdpDisplaySizeResolver.ResolveViewport(viewportSize, _renderScaling); if (size == null) return; var width = size.Value.Width; var height = size.Value.Height; - var currentWidth = _runtimeDesktopWidth ?? Math.Max(1, Session.RdpDesktopWidth); - var currentHeight = _runtimeDesktopHeight ?? Math.Max(1, Session.RdpDesktopHeight); - if (Math.Abs(width - currentWidth) < 32 && Math.Abs(height - currentHeight) < 32) + var scale = RdpDpiScale.ResolveScalePercent(ResolveDpiPolicy(), _renderScaling); + var currentWidth = _runtimeDesktopWidth ?? (RemoteWidth > 0 ? RemoteWidth : Math.Max(1, Session.RdpDesktopWidth)); + var currentHeight = _runtimeDesktopHeight ?? (RemoteHeight > 0 ? RemoteHeight : Math.Max(1, Session.RdpDesktopHeight)); + var currentScale = _runtimeDisplayScalePercent ?? scale; + if (Math.Abs(width - currentWidth) < 2 && + Math.Abs(height - currentHeight) < 2 && + scale == currentScale) + { return; + } - var scale = RdpDpiScale.ResolveScalePercent(ResolveDpiPolicy(), renderScaling); - if (_client.UpdateDisplay(width, height, scale)) + // Debounce rapid window drags / maximize / fullscreen transitions so we + // only send the settled layout once; Windows MS-RDPEDISP drops or + // throttles back-to-back SendMonitorLayout PDUs. + var previousDebounce = _resizeDebounceCts; + var debounceCts = new CancellationTokenSource(); + _resizeDebounceCts = debounceCts; + if (previousDebounce != null) { - _runtimeDesktopWidth = width; - _runtimeDesktopHeight = height; - StatusText = $"RDP display updated to {width}x{height} @ {scale}%."; - return; + try { previousDebounce.Cancel(); } catch (ObjectDisposedException) { } + previousDebounce.Dispose(); } - // The bridge cannot resize in place (older native build or the display - // control channel was not negotiated) - fall back to a full reconnect. - _resizeReconnectCts?.Cancel(); - var cts = new CancellationTokenSource(); - _resizeReconnectCts = cts; - _ = ReconnectAfterResizeDelayAsync(width, height, cts.Token); + _ = ApplyViewportResizeDebouncedAsync(width, height, scale, debounceCts.Token); + } + + private async Task ApplyViewportResizeDebouncedAsync(int width, int height, int scale, CancellationToken cancellationToken) + { + try + { + await Task.Delay(TimeSpan.FromMilliseconds(250), cancellationToken).ConfigureAwait(false); + await Dispatcher.UIThread.InvokeAsync(() => + { + if (cancellationToken.IsCancellationRequested || !IsConnected) + return; + + var currentWidth = _runtimeDesktopWidth ?? (RemoteWidth > 0 ? RemoteWidth : Math.Max(1, Session.RdpDesktopWidth)); + var currentHeight = _runtimeDesktopHeight ?? (RemoteHeight > 0 ? RemoteHeight : Math.Max(1, Session.RdpDesktopHeight)); + var currentScale = _runtimeDisplayScalePercent ?? scale; + if (Math.Abs(width - currentWidth) < 2 && + Math.Abs(height - currentHeight) < 2 && + scale == currentScale) + { + return; + } + + if (_client.UpdateDisplay(width, height, scale)) + { + _runtimeDesktopWidth = width; + _runtimeDesktopHeight = height; + _runtimeDisplayScalePercent = scale; + StatusText = $"RDP display updated to {width}x{height} @ {scale}%."; + return; + } + + // The bridge cannot resize in place (older native build or the display + // control channel was not negotiated) - fall back to a full reconnect. + _resizeReconnectCts?.Cancel(); + var cts = new CancellationTokenSource(); + _resizeReconnectCts = cts; + _ = ReconnectAfterResizeDelayAsync(width, height, cts.Token); + }); + } + catch (OperationCanceledException) + { + } } /// diff --git a/Views/RdpView.axaml.cs b/Views/RdpView.axaml.cs index 0c2242f..2e0136a 100644 --- a/Views/RdpView.axaml.cs +++ b/Views/RdpView.axaml.cs @@ -152,6 +152,8 @@ private void OnViewModelPropertyChanged(object? sender, System.ComponentModel.Pr { SyncLocalLockKeysToRemote(); SyncMultiMonitorActiveFlag(); + if (!IsCustomMonitorLayoutActive) + _boundVm.RequestViewportResize(RdpViewport.Bounds.Size, GetRenderScaling()); } else { @@ -273,7 +275,7 @@ public void ResetToSingleMonitor() { vm.IsMultiMonitorActive = false; var scaling = GetRenderScaling(); - var w = Math.Max(640, (int)Math.Round(RdpViewport.Bounds.Width * scaling)); + var w = Math.Max(640, (int)Math.Round(RdpViewport.Bounds.Width * scaling)) & ~1; var h = Math.Max(480, (int)Math.Round(RdpViewport.Bounds.Height * scaling)); vm.TryResizeMonitors([new Services.RdpMonitorRect(0, 0, w, h, (int)Math.Round(scaling * 100), true)]); } diff --git a/native/CxRdpBridge/cxrdp_bridge.cpp b/native/CxRdpBridge/cxrdp_bridge.cpp index 92ec1e1..a34f2ba 100644 --- a/native/CxRdpBridge/cxrdp_bridge.cpp +++ b/native/CxRdpBridge/cxrdp_bridge.cpp @@ -4635,6 +4635,9 @@ CX_RDP_API int cxrdp_update_display(void* handle, int width, int height, int sca return -2; } + // MS-RDPEDISP requires an even width; odd widths are rejected by Windows. + width &= ~1; + if (scalePercent != 0 && (scalePercent < 50 || scalePercent > 400)) { set_error(session, "RDP display scale is out of range.");