From 62a89748607dfdbc916b5ac8fda49788d7ba8b86 Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 17:09:54 +0800 Subject: [PATCH 1/8] =?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 eab8df4..b355359 100644 --- a/Models/SessionInfo.cs +++ b/Models/SessionInfo.cs @@ -613,6 +613,7 @@ public int SshMonitorRefreshIntervalSeconds /// 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 e93dd5a..ee9d97d 100644 --- a/Services/LocalizationService.cs +++ b/Services/LocalizationService.cs @@ -189,6 +189,8 @@ public sealed class LocalizationService : INotifyPropertyChanged ["SessionEdit.RdpSyncLockKeysHint"] = "Automatically synchronize local lock key states to the remote session on connect.", ["SessionEdit.RdpEnableClipboardLock"] = "Enable clipboard large file locking (LockClipboardData)", ["SessionEdit.RdpEnableClipboardLockHint"] = "Lock clipboard file snapshots during large file transfers so copying other content does not abort transfers.", + ["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", @@ -540,6 +542,8 @@ public sealed class LocalizationService : INotifyPropertyChanged ["SessionEdit.RdpSyncLockKeysHint"] = "连接时把本地的大小写、小键盘、滚动锁定状态同步给远端会话。", ["SessionEdit.RdpEnableClipboardLock"] = "启用剪贴板大文件锁定 (LockClipboardData)", ["SessionEdit.RdpEnableClipboardLockHint"] = "通过剪贴板传输大文件时锁定快照,防止中途复制其他内容导致传输中断。", + ["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 1f332ff..7c95d53 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 { @@ -1723,6 +1733,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 8585d98..1684f2d 100644 --- a/ViewModels/SessionEditViewModel.cs +++ b/ViewModels/SessionEditViewModel.cs @@ -337,6 +337,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; @@ -1552,6 +1553,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; @@ -1865,6 +1867,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 cf439e2..bde4875 100644 --- a/ViewModels/SessionTreeViewModel.cs +++ b/ViewModels/SessionTreeViewModel.cs @@ -265,6 +265,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; @@ -1189,6 +1190,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 7b08ecc..4ed75cd 100644 --- a/Views/SessionEditDialog.axaml +++ b/Views/SessionEditDialog.axaml @@ -1705,7 +1705,7 @@ BorderThickness="1" CornerRadius="4" Padding="18"> - + + diff --git a/native/CxRdpBridge/cxrdp_bridge.cpp b/native/CxRdpBridge/cxrdp_bridge.cpp index de6ced8..359f5cc 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; @@ -3726,6 +3736,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 05aa2e890ec2d3c46ad7dc36f1acd2b4667c1096 Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 17:10:57 +0800 Subject: [PATCH 2/8] =?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 7c95d53..c244313 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 { @@ -1208,33 +1239,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; @@ -1308,6 +1365,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 2bbc1a9..de9b419 100644 --- a/ViewModels/RdpViewModel.cs +++ b/ViewModels/RdpViewModel.cs @@ -818,8 +818,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 946e056ac1f73c1425722be82b5bb38b25e730e3 Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 17:12:39 +0800 Subject: [PATCH 3/8] =?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 359f5cc..6cb140f 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()) @@ -3751,6 +3791,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 30e7fb2cfd4350ec65fb737045d2c01482ca5eab Mon Sep 17 00:00:00 2001 From: heartacker Date: Tue, 24 Nov 2026 17:12:53 +0800 Subject: [PATCH 4/8] =?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 08bb698..20e8760 100644 --- a/Views/RdpView.axaml.cs +++ b/Views/RdpView.axaml.cs @@ -484,6 +484,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) @@ -551,7 +560,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), @@ -581,7 +590,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 @@ -613,7 +622,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 758ba0e6ebfb17b4a25553900ab3d49711f73fb8 Mon Sep 17 00:00:00 2001 From: heartacker Date: Wed, 25 Nov 2026 15:34:36 +0800 Subject: [PATCH 5/8] =?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 6cb140f..d6e271f 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 da7285ad6e98325bdbbd99506805274754008ebc Mon Sep 17 00:00:00 2001 From: heartacker Date: Wed, 25 Nov 2026 16:24:17 +0800 Subject: [PATCH 6/8] 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 de9b419..e7ca5db 100644 --- a/ViewModels/RdpViewModel.cs +++ b/ViewModels/RdpViewModel.cs @@ -23,6 +23,7 @@ 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; @@ -37,6 +38,7 @@ public partial class RdpViewModel : ObservableObject, IDisposable /// has to be wider than the 300 ms that first looked sufficient. /// private const int MonitorLayoutDebounceMilliseconds = 500; + private int? _runtimeDisplayScalePercent; private WriteableBitmap? _bitmapA; private WriteableBitmap? _bitmapB; private bool _useBitmapA; @@ -176,12 +178,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 @@ -414,7 +418,7 @@ private static string GetDisplayStatusText(string message) [RelayCommand] public void Reconnect() { - _resizeReconnectCts?.Cancel(); + CancelPendingResize(); CancelConnectWatchdog(); _reconnectPhase = RdpReconnectPhase.None; _reconnectAttempt = 0; @@ -447,7 +451,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. @@ -480,8 +484,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 || @@ -490,32 +516,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 20e8760..dcb97d5 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 { @@ -286,7 +288,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 d6e271f..455e359 100644 --- a/native/CxRdpBridge/cxrdp_bridge.cpp +++ b/native/CxRdpBridge/cxrdp_bridge.cpp @@ -4649,6 +4649,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."); From 6a62b499c8d69da7a993b640312e507ddcbeaa60 Mon Sep 17 00:00:00 2001 From: heartacker Date: Wed, 25 Nov 2026 16:41:46 +0800 Subject: [PATCH 7/8] fix(rdp): disable local Windows IME while RdpView has focus --- Views/RdpView.axaml.cs | 43 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/Views/RdpView.axaml.cs b/Views/RdpView.axaml.cs index dcb97d5..650bfd5 100644 --- a/Views/RdpView.axaml.cs +++ b/Views/RdpView.axaml.cs @@ -32,6 +32,9 @@ public partial class RdpView : UserControl private WindowsClipboardListener? _clipboardListener; private DispatcherTimer? _clipboardPollTimer; private WindowsRdpShortcutHook? _systemShortcutHook; + private IntPtr _savedImeHwnd; + private IntPtr _savedImeContext; + private bool _imeDisabled; private Cursor? _customRemoteCursor; private Avalonia.Media.Imaging.WriteableBitmap? _customRemoteCursorBitmap; private TopLevel? _subscribedTopLevel; @@ -93,6 +96,7 @@ public RdpView() SyncMultiMonitorActiveFlag(); StopClipboardListener(); UnsubscribeTopLevelScaling(); + RestoreLocalIme(); DisposeSystemShortcutHook(); ReleaseTrackedModifiers(); _pendingWheelY = 0; @@ -101,6 +105,7 @@ public RdpView() GotFocus += (_, _) => { _hasKeyboardFocus = true; + DisableLocalIme(); UpdateSystemShortcutHook(); SyncLocalLockKeysToRemote(); _ = SyncLocalClipboardToRemoteAsync(); @@ -108,6 +113,7 @@ public RdpView() LostFocus += (_, _) => { _hasKeyboardFocus = false; + RestoreLocalIme(); DisposeSystemShortcutHook(); ReleaseTrackedModifiers(); }; @@ -1046,6 +1052,43 @@ private void SyncLocalLockKeysToRemote() [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern short GetKeyState(int nVirtKey); + [System.Runtime.InteropServices.DllImport("imm32.dll")] + private static extern IntPtr ImmAssociateContext(IntPtr hWnd, IntPtr hIMC); + + private void DisableLocalIme() + { + if (!OperatingSystem.IsWindows()) + return; + + var hwnd = TopLevel.GetTopLevel(this)?.TryGetPlatformHandle()?.Handle ?? IntPtr.Zero; + if (hwnd == IntPtr.Zero) + return; + + if (_imeDisabled) + { + if (_savedImeHwnd == hwnd) + return; + RestoreLocalIme(); + } + + _savedImeContext = ImmAssociateContext(hwnd, IntPtr.Zero); + _savedImeHwnd = hwnd; + _imeDisabled = true; + } + + private void RestoreLocalIme() + { + if (!_imeDisabled || !OperatingSystem.IsWindows()) + return; + + if (_savedImeHwnd != IntPtr.Zero) + ImmAssociateContext(_savedImeHwnd, _savedImeContext); + + _savedImeHwnd = IntPtr.Zero; + _savedImeContext = IntPtr.Zero; + _imeDisabled = false; + } + private void OnTopLevelScalingChanged(object? sender, EventArgs e) { if (DataContext is RdpViewModel vm) From 4dcc8fcd2a9103917355ad4ed498df31e93878c0 Mon Sep 17 00:00:00 2001 From: heartacker Date: Thu, 26 Nov 2026 11:46:19 +0800 Subject: [PATCH 8/8] feat(rdp): re-enable clipboard lock option in session editor --- Views/SessionEditDialog.axaml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Views/SessionEditDialog.axaml b/Views/SessionEditDialog.axaml index 4ed75cd..4f909c7 100644 --- a/Views/SessionEditDialog.axaml +++ b/Views/SessionEditDialog.axaml @@ -1720,13 +1720,8 @@ -