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 9fdd497..84dcb08 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;
@@ -597,7 +597,25 @@ 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";
+ /// 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;
public bool RdpClipboardEnabled { get; set; } = true;
/// Send PERF_DISABLE_WALLPAPER so the server skips the desktop wallpaper.
public bool RdpDisableWallpaper { get; set; } = true;
@@ -609,6 +627,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 67057cb..894404f 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",
@@ -184,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",
@@ -517,7 +520,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"] = "良好",
@@ -530,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 用户",
@@ -2137,6 +2143,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 +2428,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 df924ce..fc9fd00 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;
@@ -22,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;
}
@@ -37,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.
@@ -72,6 +100,20 @@ 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;
+ 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 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");
@@ -91,10 +133,19 @@ 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 bool _supportsMultiMonitor;
private readonly object _frameSync = new();
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();
@@ -103,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.
@@ -133,6 +187,9 @@ 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");
@@ -151,6 +208,9 @@ public RdpBridgeClient()
_statusCallback = OnStatus;
_disconnectCallback = OnDisconnected;
_clipboardTextCallback = OnClipboardText;
+ _clipboardImageCallback = OnClipboardImage;
+ _clipboardFilesCallback = OnClipboardFiles;
+ _pointerCallback = OnPointer;
}
public void Connect(
@@ -236,11 +296,47 @@ public void Connect(
_frameMarkerSupported = nativeApiVersion >= FrameMarkerApiVersion &&
(nativeCapabilities & FrameMarkerCapability) != 0;
+ _supportsSyncLockKeys = nativeApiVersion >= SyncLockKeysApiVersion &&
+ (nativeCapabilities & SyncLockKeysCapability) != 0;
+ if (nativeApiVersion >= PointerShapeApiVersion &&
+ (nativeCapabilities & PointerShapeCapability) != 0)
+ {
+ 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);
+ _supportsMultiMonitor = nativeApiVersion >= MultiMonitorApiVersion &&
+ (nativeCapabilities & MultiMonitorCapability) != 0;
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}");
+ });
+ 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
{
@@ -258,8 +354,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)
{
@@ -270,19 +372,28 @@ 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))
{
- 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, targetProfile);
+ DebugLog($"security profile hint={targetProfile} explicit={!string.IsNullOrEmpty(explicitProfile)} 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 +403,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
{
@@ -494,6 +608,7 @@ private void TryPresentFrame(object? state)
bool interactive;
bool settling;
bool logFrame;
+ RdpFrameDirtyRect? copyRect;
lock (_frameSync)
{
@@ -517,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);
@@ -556,7 +689,8 @@ private void TryPresentFrame(object? state)
stride,
snapshot,
length,
- () => ArrayPool.Shared.Return(snapshot));
+ () => ArrayPool.Shared.Return(snapshot),
+ copyRect);
try
{
@@ -680,6 +814,40 @@ 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);
+ }
+
+ 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
@@ -695,6 +863,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
@@ -1011,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 rect = clampedDirty!.Value;
+ CopyDirtyRectFromNative(data, _frameBuffer, stride, rect);
+ CopyDirtyRectManaged(_frameBuffer, _previousFrameBuffer, stride, rect);
+ if (!_pendingFullFrameCopy)
+ {
+ _pendingCopyDirtyRect = _pendingCopyDirtyRect.HasValue
+ ? UnionDirtyRect(_pendingCopyDirtyRect.Value, rect)
+ : rect;
+ }
+ }
+ else
{
- var diff = ComputeDirtyRectFromDiff(width, height, stride);
- if (diff.HasValue)
+ 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)
{
- dirty = diff;
- dirtySource = "diff";
+ 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;
@@ -1111,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;
@@ -1165,12 +1444,54 @@ 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;
+ }
+ }
+
+ 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");
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;
@@ -1178,6 +1499,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);
@@ -1304,6 +1649,22 @@ 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,
+ int kind,
+ int width,
+ int height,
+ int hotX,
+ int hotY,
+ IntPtr bgraPixels);
+
private static class NativeMethods
{
[DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)]
@@ -1345,6 +1706,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);
@@ -1354,6 +1721,42 @@ 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_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);
+
[DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)]
public static extern void cxrdp_set_clipboard_text(
IntPtr handle,
@@ -1412,6 +1815,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/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/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/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/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 9b9a654..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;
@@ -49,6 +51,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;
@@ -91,6 +94,10 @@ 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;
public string ScaleModeText => IsFitToWindow
? "Fit to window"
@@ -105,6 +112,9 @@ 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(() =>
{
@@ -150,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
@@ -384,7 +396,7 @@ private static string GetDisplayStatusText(string message)
[RelayCommand]
public void Reconnect()
{
- _resizeReconnectCts?.Cancel();
+ CancelPendingResize();
CancelConnectWatchdog();
_reconnectPhase = RdpReconnectPhase.None;
_reconnectAttempt = 0;
@@ -417,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.
@@ -449,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 ||
@@ -459,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)
+ {
+ }
}
///
@@ -641,6 +721,46 @@ 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 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)
+ _client.SetClipboardFiles(filePaths);
+ }
+
+ public void SyncLockKeys(uint flags)
+ {
+ if (IsConnected)
+ _client.SyncLockKeys(flags);
+ }
+
+ public bool TryResizeMonitors(IReadOnlyList monitors)
+ {
+ return IsConnected && _client.TryResizeMonitors(monitors);
+ }
+
[RelayCommand]
private void ToggleScaleMode()
{
@@ -692,14 +812,33 @@ 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
// 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;
@@ -748,6 +887,21 @@ 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));
+ }
+
partial void OnIsConnectedChanged(bool value)
{
if (value)
@@ -824,6 +978,9 @@ 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();
_bitmapA?.Dispose();
diff --git a/ViewModels/SessionEditViewModel.cs b/ViewModels/SessionEditViewModel.cs
index 7412d55..580b89e 100644
--- a/ViewModels/SessionEditViewModel.cs
+++ b/ViewModels/SessionEditViewModel.cs
@@ -330,10 +330,16 @@ 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 string _rdpWindowMode = "Default";
+ [ObservableProperty] private bool _rdpOpenInStandaloneWindow;
[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;
+ [ObservableProperty] private bool _rdpH264Enabled;
[ObservableProperty] private bool _rdpRedirectDrives;
[ObservableProperty] private string _rdpDriveName = "CxShell";
[ObservableProperty] private string _rdpDrivePath = string.Empty;
@@ -1036,6 +1042,20 @@ 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 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" },
@@ -1534,10 +1554,16 @@ 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;
+ RdpWindowMode = session.ResolveEffectiveRdpWindowMode();
+ RdpOpenInStandaloneWindow = session.RdpOpenInStandaloneWindow;
RdpApplyKeyCombinations = session.RdpApplyKeyCombinations;
+ RdpSyncLockKeys = session.RdpSyncLockKeys;
+ RdpEnableClipboardLock = session.RdpEnableClipboardLock;
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;
@@ -1844,10 +1870,16 @@ private void Save()
: "FollowLocal";
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;
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 9427066..e7ce8fb 100644
--- a/ViewModels/SessionTreeViewModel.cs
+++ b/ViewModels/SessionTreeViewModel.cs
@@ -259,10 +259,15 @@ public static void CopySessionValues(SessionInfo target, SessionInfo source)
target.RdpDpiPolicy = source.RdpDpiPolicy;
target.RdpFrameStrategy = source.RdpFrameStrategy;
target.RdpColorQuality = source.RdpColorQuality;
- target.RdpApplyKeyCombinations = source.RdpApplyKeyCombinations;
+ target.RdpSecurityMode = source.RdpSecurityMode;
+ target.RdpWindowMode = source.RdpWindowMode;
+ target.RdpOpenInStandaloneWindow = source.RdpOpenInStandaloneWindow;
+ target.RdpSyncLockKeys = source.RdpSyncLockKeys;
+ target.RdpEnableClipboardLock = source.RdpEnableClipboardLock;
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;
@@ -1180,10 +1185,16 @@ private static SessionInfo CloneSession(SessionInfo source, string name)
RdpDpiPolicy = source.RdpDpiPolicy,
RdpFrameStrategy = source.RdpFrameStrategy,
RdpColorQuality = source.RdpColorQuality,
+ RdpSecurityMode = source.RdpSecurityMode,
+ RdpWindowMode = source.RdpWindowMode,
+ RdpOpenInStandaloneWindow = source.RdpOpenInStandaloneWindow,
RdpApplyKeyCombinations = source.RdpApplyKeyCombinations,
+ RdpSyncLockKeys = source.RdpSyncLockKeys,
+ RdpEnableClipboardLock = source.RdpEnableClipboardLock,
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/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 b667173..3fc560a 100644
--- a/Views/RdpView.axaml
+++ b/Views/RdpView.axaml
@@ -1,6 +1,7 @@
-
+
+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Views/RdpView.axaml.cs b/Views/RdpView.axaml.cs
index 725c0c4..2e0136a 100644
--- a/Views/RdpView.axaml.cs
+++ b/Views/RdpView.axaml.cs
@@ -25,21 +25,56 @@ public partial class RdpView : UserControl
private bool _applyingRemoteClipboardText;
private bool _hasKeyboardFocus;
private string? _lastSyncedClipboardText;
+ private string? _lastSyncedClipboardImageHash;
+ private string? _lastSyncedClipboardFilesKey;
+ private uint _lastSyncedLocalClipboardSeq;
+ private uint _lastAppliedRemoteClipboardSeq;
+ private WindowsClipboardListener? _clipboardListener;
+ private DispatcherTimer? _clipboardPollTimer;
private WindowsRdpShortcutHook? _systemShortcutHook;
+ private Cursor? _customRemoteCursor;
+ private Avalonia.Media.Imaging.WriteableBitmap? _customRemoteCursorBitmap;
+ private TopLevel? _subscribedTopLevel;
+ private static readonly IBrush PopupButtonNormalBrush = new SolidColorBrush(Color.Parse("#22FFFFFF"));
+ private static readonly IBrush PopupButtonActiveBrush = new SolidColorBrush(Color.Parse("#4464D8FF"));
+ private readonly System.Collections.Generic.HashSet _selectedMonitorIndices = new();
+ private readonly System.Collections.Generic.Dictionary _secondaryMonitorWindows = new();
+ private readonly System.Collections.Generic.List _virtualMonitorIds = new();
+ private int _nextVirtualMonitorId = 100;
+ private int? _preferredPrimaryMonitorIndex;
+ private int _ultrawideMode; // 0=standard, 1=local ultrawide -> remote dual, 2=local dual PBP -> remote single ultrawide
+ private Rect? _primarySliceRect;
+ private ushort _lastRemotePointerX;
+ private ushort _lastRemotePointerY;
private double _pendingWheelY;
- private double _lastRenderScaling = 1;
- private DispatcherTimer? _scalingTimer;
+ private Action? _onMultiMonitorPopupOpenChanged;
+ private Control? _lastMultiMonitorAnchor;
+ private DateTime _multiMonitorPopupClosedAtUtc = DateTime.MinValue;
+
+ public bool IsMultiMonitorActive => IsCustomMonitorLayoutActive;
+ private bool IsCustomMonitorLayoutActive =>
+ _selectedMonitorIndices.Count > 1 || _virtualMonitorIds.Count > 0 || _ultrawideMode != 0;
public RdpView()
{
InitializeComponent();
+ MultiMonitorPopup.Closed += (_, _) =>
+ {
+ _multiMonitorPopupClosedAtUtc = DateTime.UtcNow;
+ var callback = _onMultiMonitorPopupOpenChanged;
+ _onMultiMonitorPopupOpenChanged = null;
+ callback?.Invoke(false);
+ };
AddHandler(KeyDownEvent, OnFramebufferKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnFramebufferKeyUp, RoutingStrategies.Tunnel);
+ AddHandler(DragDrop.DragOverEvent, OnRdpDragOver);
+ AddHandler(DragDrop.DropEvent, OnRdpDrop);
AttachedToVisualTree += (_, _) =>
{
_isAttached = true;
- _lastRenderScaling = GetRenderScaling();
Focus();
+ StartClipboardListener();
+ SubscribeTopLevelScaling();
if (DataContext is RdpViewModel vm)
ScheduleStart(vm);
UpdateSystemShortcutHook();
@@ -48,7 +83,16 @@ public RdpView()
{
_isAttached = false;
_hasKeyboardFocus = false;
- StopScalingTimer();
+ CloseMultiMonitorPopup();
+ CloseAllSecondaryMonitorWindows();
+ _ultrawideMode = 0;
+ _virtualMonitorIds.Clear();
+ _selectedMonitorIndices.Clear();
+ _preferredPrimaryMonitorIndex = null;
+ _primarySliceRect = null;
+ SyncMultiMonitorActiveFlag();
+ StopClipboardListener();
+ UnsubscribeTopLevelScaling();
DisposeSystemShortcutHook();
ReleaseTrackedModifiers();
_pendingWheelY = 0;
@@ -58,6 +102,7 @@ public RdpView()
{
_hasKeyboardFocus = true;
UpdateSystemShortcutHook();
+ SyncLocalLockKeysToRemote();
_ = SyncLocalClipboardToRemoteAsync();
};
LostFocus += (_, _) =>
@@ -77,8 +122,10 @@ private void OnDataContextChanged(object? sender, EventArgs e)
_boundVm = vm;
vm.PropertyChanged += OnViewModelPropertyChanged;
- if (vm.IsConnected)
- StartScalingTimer();
+ vm.RemoteClipboardImageReceived += OnRemoteClipboardImageReceived;
+ vm.RemoteClipboardFilesReceived += OnRemoteClipboardFilesReceived;
+ vm.FramebufferInvalidated += OnFramebufferInvalidated;
+ vm.PointerShapeChanged += OnPointerShapeChanged;
ApplyScaleMode(vm);
UpdateSystemShortcutHook();
if (_isAttached)
@@ -99,58 +146,723 @@ private void OnViewModelPropertyChanged(object? sender, System.ComponentModel.Pr
ApplyScaleMode(_boundVm);
}
- if (_boundVm != null && args.PropertyName == nameof(RdpViewModel.IsClipboardChannelReady) && _boundVm.IsClipboardChannelReady)
- _ = SyncLocalClipboardToRemoteAsync();
+ if (_boundVm != null && args.PropertyName == nameof(RdpViewModel.IsConnected))
+ {
+ if (_boundVm.IsConnected)
+ {
+ SyncLocalLockKeysToRemote();
+ SyncMultiMonitorActiveFlag();
+ if (!IsCustomMonitorLayoutActive)
+ _boundVm.RequestViewportResize(RdpViewport.Bounds.Size, GetRenderScaling());
+ }
+ else
+ {
+ CloseMultiMonitorPopup();
+ CloseAllSecondaryMonitorWindows();
+ _ultrawideMode = 0;
+ _virtualMonitorIds.Clear();
+ _selectedMonitorIndices.Clear();
+ _preferredPrimaryMonitorIndex = null;
+ _primarySliceRect = null;
+ PrimarySliceSurface.IsVisible = false;
+ FramebufferImage.IsVisible = true;
+ SyncMultiMonitorActiveFlag();
+ ResetClipboardSyncState();
+ }
+ }
+ if (_boundVm != null && args.PropertyName == nameof(RdpViewModel.IsClipboardChannelReady))
+ {
+ if (_boundVm.IsClipboardChannelReady)
+ _ = SyncLocalClipboardToRemoteAsync();
+ else
+ ResetClipboardSyncState();
+ }
if (_boundVm != null && args.PropertyName == nameof(RdpViewModel.RemoteClipboardText))
_ = ApplyRemoteClipboardTextAsync(_boundVm.RemoteClipboardText);
+ }
+
+ private void UnbindViewModel()
+ {
+ if (_boundVm == null)
+ return;
- if (args.PropertyName == nameof(RdpViewModel.IsConnected))
+ _boundVm.PropertyChanged -= OnViewModelPropertyChanged;
+ _boundVm.RemoteClipboardImageReceived -= OnRemoteClipboardImageReceived;
+ _boundVm.RemoteClipboardFilesReceived -= OnRemoteClipboardFilesReceived;
+ _boundVm.FramebufferInvalidated -= OnFramebufferInvalidated;
+ _boundVm.PointerShapeChanged -= OnPointerShapeChanged;
+ _boundVm = null;
+ ResetClipboardSyncState();
+ DisposeCustomRemoteCursor();
+ DisposeSystemShortcutHook();
+ }
+
+ private void ResetClipboardSyncState()
+ {
+ _lastSyncedClipboardText = null;
+ _lastSyncedClipboardImageHash = null;
+ _lastSyncedClipboardFilesKey = null;
+ _lastSyncedLocalClipboardSeq = 0;
+ _lastAppliedRemoteClipboardSeq = 0;
+ }
+
+ private void OnFramebufferInvalidated()
+ {
+ if (PrimarySliceSurface.IsVisible && DataContext is RdpViewModel vm)
{
- if (_boundVm?.IsConnected == true)
- StartScalingTimer();
- else
- StopScalingTimer();
+ PrimarySliceSurface.Source = vm.Framebuffer;
+ PrimarySliceSurface.InvalidateVisual();
+ }
+ else
+ {
+ FramebufferImage.InvalidateVisual();
}
}
- private void StartScalingTimer()
+ public void ToggleMultiMonitorPopup(
+ Control anchor,
+ PlacementMode placement = PlacementMode.Bottom,
+ Action? onPopupOpenChanged = null)
{
- if (_scalingTimer != null || !_isAttached)
+ if (TopLevel.GetTopLevel(this) is not DetachedTabWindow)
+ return;
+ if (DataContext is not RdpViewModel { IsConnected: true })
return;
- _lastRenderScaling = GetRenderScaling();
- _scalingTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
- _scalingTimer.Tick += (_, _) =>
+ if (MultiMonitorPopup.IsOpen)
{
- var scaling = GetRenderScaling();
- if (Math.Abs(scaling - _lastRenderScaling) < 0.001)
+ var sameAnchor = ReferenceEquals(MultiMonitorPopup.PlacementTarget, anchor);
+ var previousCallback = _onMultiMonitorPopupOpenChanged;
+ _onMultiMonitorPopupOpenChanged = null;
+ MultiMonitorPopup.IsOpen = false;
+ previousCallback?.Invoke(false);
+ if (sameAnchor)
return;
+ }
- _lastRenderScaling = scaling;
- if (DataContext is RdpViewModel vm)
+ if (ReferenceEquals(_lastMultiMonitorAnchor, anchor) &&
+ (DateTime.UtcNow - _multiMonitorPopupClosedAtUtc).TotalMilliseconds < 250)
+ {
+ _lastMultiMonitorAnchor = null;
+ return;
+ }
+
+ _lastMultiMonitorAnchor = anchor;
+ _onMultiMonitorPopupOpenChanged = onPopupOpenChanged;
+ MultiMonitorPopup.PlacementTarget = anchor;
+ MultiMonitorPopup.Placement = placement;
+ PopulateMonitorCheckboxes();
+ UpdateUltrawideModeButtonStates();
+ MultiMonitorPopup.IsOpen = true;
+ _onMultiMonitorPopupOpenChanged?.Invoke(true);
+ }
+
+ public void CloseMultiMonitorPopup()
+ {
+ if (MultiMonitorPopup.IsOpen)
+ MultiMonitorPopup.IsOpen = false;
+ }
+
+ ///
+ /// Closes all secondary / virtual monitor windows and restores single-monitor
+ /// mode before moving this RDP session back into a multi-tab window.
+ ///
+ public void ResetToSingleMonitor()
+ {
+ CloseMultiMonitorPopup();
+ CloseAllSecondaryMonitorWindows();
+ if (DataContext is RdpViewModel vm && vm.IsMultiMonitorActive)
+ {
+ vm.IsMultiMonitorActive = false;
+ var scaling = GetRenderScaling();
+ 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)]);
+ }
+ }
+
+ private void SyncMultiMonitorActiveFlag()
+ {
+ if (DataContext is RdpViewModel vm)
+ vm.IsMultiMonitorActive = vm.IsConnected && IsCustomMonitorLayoutActive;
+ }
+
+ private void OnUltrawideModeStandardClick(object? sender, RoutedEventArgs e)
+ {
+ _ultrawideMode = 0;
+ UpdateUltrawideModeButtonStates();
+ ApplySelectedMonitorLayout();
+ }
+
+ private void OnUltrawideModeSplitDualClick(object? sender, RoutedEventArgs e)
+ {
+ _ultrawideMode = 1;
+ UpdateUltrawideModeButtonStates();
+ ApplySelectedMonitorLayout();
+ }
+
+ private void OnUltrawideModeMergeUltrawideClick(object? sender, RoutedEventArgs e)
+ {
+ _ultrawideMode = 2;
+ if (TopLevel.GetTopLevel(this) is Window window && window.Screens.All.Count >= 2 && _selectedMonitorIndices.Count < 2)
+ {
+ _selectedMonitorIndices.Add(0);
+ _selectedMonitorIndices.Add(1);
+ PopulateMonitorCheckboxes();
+ }
+ UpdateUltrawideModeButtonStates();
+ ApplySelectedMonitorLayout();
+ }
+
+ private void OnAddVirtualMonitorClick(object? sender, RoutedEventArgs e)
+ {
+ if (_virtualMonitorIds.Count >= 3)
+ return;
+
+ _ultrawideMode = 0;
+ _virtualMonitorIds.Add(_nextVirtualMonitorId++);
+ UpdateUltrawideModeButtonStates();
+ ApplySelectedMonitorLayout();
+ PopulateMonitorCheckboxes();
+ }
+
+ private void UpdateUltrawideModeButtonStates()
+ {
+ ModeStandardButton.FontWeight = _ultrawideMode == 0 ? FontWeight.Bold : FontWeight.Normal;
+ ModeStandardButton.Background = _ultrawideMode == 0 ? PopupButtonActiveBrush : PopupButtonNormalBrush;
+ ModeSplitDualButton.FontWeight = _ultrawideMode == 1 ? FontWeight.Bold : FontWeight.Normal;
+ ModeSplitDualButton.Background = _ultrawideMode == 1 ? PopupButtonActiveBrush : PopupButtonNormalBrush;
+ ModeMergeUltrawideButton.FontWeight = _ultrawideMode == 2 ? FontWeight.Bold : FontWeight.Normal;
+ ModeMergeUltrawideButton.Background = _ultrawideMode == 2 ? PopupButtonActiveBrush : PopupButtonNormalBrush;
+
+ var canSplitDual = false;
+ var splitReason = "需在宽屏全屏/最大化状态下开启";
+ var canMergeUltrawide = false;
+ var mergeReason = "需两块高度与 DPI 缩放一致的屏幕在全屏/最大化模式下开启";
+
+ if (TopLevel.GetTopLevel(this) is Window window)
+ {
+ var isFullOrMax = window.WindowState is WindowState.FullScreen or WindowState.Maximized;
+ var currentScreen = window.Screens.ScreenFromWindow(window) ?? window.Screens.Primary;
+ if (isFullOrMax && currentScreen != null)
{
- vm.ConfigureInitialDisplay(RdpViewport.Bounds.Size, GetCurrentMonitorPixelSize(), scaling);
- vm.UpdateDpiScaling(scaling);
+ var aspect = currentScreen.Bounds.Height > 0
+ ? (double)currentScreen.Bounds.Width / currentScreen.Bounds.Height
+ : 0;
+ canSplitDual = currentScreen.Bounds.Width >= 2560 || aspect >= 1.8;
}
- };
- _scalingTimer.Start();
+
+ var screens = window.Screens.All;
+ if (isFullOrMax && screens.Count >= 2 && _virtualMonitorIds.Count == 0)
+ {
+ var s0 = screens[0];
+ var s1 = screens[1];
+ canMergeUltrawide = s0.Bounds.Height == s1.Bounds.Height &&
+ Math.Abs(s0.Scaling - s1.Scaling) < 0.01;
+ }
+ }
+
+ ModeSplitDualButton.IsEnabled = canSplitDual || _ultrawideMode == 1;
+ ToolTip.SetTip(ModeSplitDualButton, canSplitDual ? "将当前带鱼屏拆分为远端左右双屏" : splitReason);
+
+ ModeMergeUltrawideButton.IsEnabled = canMergeUltrawide || _ultrawideMode == 2;
+ ToolTip.SetTip(ModeMergeUltrawideButton, canMergeUltrawide ? "将两块等高等缩放物理屏合并为远端单块带鱼屏" : mergeReason);
+ }
+
+ private void PopulateMonitorCheckboxes()
+ {
+ MonitorCheckboxList.Children.Clear();
+ if (TopLevel.GetTopLevel(this) is not Window window)
+ return;
+
+ var screens = window.Screens.All;
+ if (screens.Count == 0)
+ return;
+
+ var currentScreen = window.Screens.ScreenFromWindow(window) ?? window.Screens.Primary;
+ var currentIndex = 0;
+ for (var i = 0; i < screens.Count; i++)
+ {
+ if (currentScreen != null && screens[i].Bounds == currentScreen.Bounds)
+ {
+ currentIndex = i;
+ break;
+ }
+ }
+
+ if (_selectedMonitorIndices.Count == 0)
+ _selectedMonitorIndices.Add(currentIndex);
+
+ var activePrimaryIndex = _preferredPrimaryMonitorIndex.HasValue && _selectedMonitorIndices.Contains(_preferredPrimaryMonitorIndex.Value)
+ ? _preferredPrimaryMonitorIndex.Value
+ : currentIndex;
+
+ for (var i = 0; i < screens.Count; i++)
+ {
+ var idx = i;
+ var s = screens[i];
+ var scalePct = (int)Math.Round(s.Scaling * 100);
+ var label = $"屏幕 {i + 1} · {s.Bounds.Width}×{s.Bounds.Height} · {scalePct}%";
+ var row = new Grid
+ {
+ ColumnDefinitions = new ColumnDefinitions("*,Auto"),
+ ColumnSpacing = 8
+ };
+ var cb = new CheckBox
+ {
+ Content = label,
+ IsChecked = _selectedMonitorIndices.Contains(idx),
+ Foreground = Brushes.WhiteSmoke,
+ FontSize = 12,
+ VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center
+ };
+ cb.IsCheckedChanged += (_, _) =>
+ {
+ if (cb.IsChecked == true)
+ {
+ _selectedMonitorIndices.Add(idx);
+ }
+ else
+ {
+ if (_selectedMonitorIndices.Count <= 1)
+ {
+ cb.IsChecked = true;
+ return;
+ }
+ _selectedMonitorIndices.Remove(idx);
+ if (_preferredPrimaryMonitorIndex == idx)
+ _preferredPrimaryMonitorIndex = null;
+ }
+
+ ApplySelectedMonitorLayout();
+ PopulateMonitorCheckboxes();
+ };
+
+ var isPrimary = idx == activePrimaryIndex;
+ var primaryBtn = new Button
+ {
+ Content = isPrimary ? "★ 主屏" : "设为主屏",
+ Foreground = Brushes.White,
+ Background = isPrimary ? PopupButtonActiveBrush : PopupButtonNormalBrush,
+ BorderBrush = new SolidColorBrush(Color.Parse("#40FFFFFF")),
+ BorderThickness = new Thickness(1),
+ CornerRadius = new CornerRadius(4),
+ FontSize = 11,
+ Padding = new Thickness(6, 2),
+ IsEnabled = !isPrimary,
+ VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center
+ };
+ primaryBtn.Click += (_, _) =>
+ {
+ _selectedMonitorIndices.Add(idx);
+ _preferredPrimaryMonitorIndex = idx;
+ ApplySelectedMonitorLayout();
+ PopulateMonitorCheckboxes();
+ };
+
+ Grid.SetColumn(cb, 0);
+ Grid.SetColumn(primaryBtn, 1);
+ row.Children.Add(cb);
+ row.Children.Add(primaryBtn);
+ MonitorCheckboxList.Children.Add(row);
+ }
}
- private void StopScalingTimer()
+ private static int ResolveMonitorScalePercent(RdpViewModel vm, double screenScaling)
{
- _scalingTimer?.Stop();
- _scalingTimer = null;
+ 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 UnbindViewModel()
+ private void ApplySelectedMonitorLayout()
{
- if (_boundVm == null)
+ if (DataContext is not RdpViewModel vm || !vm.IsConnected || TopLevel.GetTopLevel(this) is not Window window)
return;
- _boundVm.PropertyChanged -= OnViewModelPropertyChanged;
- _boundVm = null;
- StopScalingTimer();
- DisposeSystemShortcutHook();
+ var screens = window.Screens.All;
+ if (screens.Count == 0 || _selectedMonitorIndices.Count == 0)
+ return;
+
+ var selected = new System.Collections.Generic.List<(int Index, Avalonia.Platform.Screen Screen)>();
+ foreach (var idx in _selectedMonitorIndices)
+ {
+ if (idx >= 0 && idx < screens.Count)
+ selected.Add((idx, screens[idx]));
+ }
+
+ if (selected.Count == 0)
+ return;
+
+ selected.Sort((a, b) => a.Index.CompareTo(b.Index));
+
+ var currentScreen = window.Screens.ScreenFromWindow(window) ?? window.Screens.Primary;
+ var hostEntry = selected[0];
+ var remotePrimaryEntry = selected[0];
+ foreach (var item in selected)
+ {
+ if (currentScreen != null && item.Screen.Bounds == currentScreen.Bounds)
+ hostEntry = item;
+ if (_preferredPrimaryMonitorIndex.HasValue && item.Index == _preferredPrimaryMonitorIndex.Value)
+ remotePrimaryEntry = item;
+ }
+ if (!_preferredPrimaryMonitorIndex.HasValue)
+ remotePrimaryEntry = hostEntry;
+
+ var minX = int.MaxValue;
+ var minY = int.MaxValue;
+ var maxX = int.MinValue;
+ var maxY = int.MinValue;
+ foreach (var item in selected)
+ {
+ if (item.Screen.Bounds.X < minX) minX = item.Screen.Bounds.X;
+ if (item.Screen.Bounds.Y < minY) minY = item.Screen.Bounds.Y;
+ if (item.Screen.Bounds.Right > maxX) maxX = item.Screen.Bounds.Right;
+ if (item.Screen.Bounds.Bottom > maxY) maxY = item.Screen.Bounds.Bottom;
+ }
+
+ var hostScaleFactor = GetRenderScaling();
+ var useViewportForHost = window.WindowState != WindowState.FullScreen &&
+ RdpViewport.Bounds.Width >= 320 &&
+ RdpViewport.Bounds.Height >= 240;
+ var hostPixelW = useViewportForHost
+ ? Math.Clamp(((int)Math.Round(RdpViewport.Bounds.Width * hostScaleFactor)) & ~1, 200, 8192)
+ : Math.Clamp(hostEntry.Screen.Bounds.Width & ~1, 200, 8192);
+ var hostPixelH = useViewportForHost
+ ? Math.Clamp(((int)Math.Round(RdpViewport.Bounds.Height * hostScaleFactor)) & ~1, 200, 8192)
+ : Math.Clamp(hostEntry.Screen.Bounds.Height & ~1, 200, 8192);
+
+ // Mode 1: Single local ultrawide -> Remote virtual dual monitors (left/right 50/50 split)
+ if (_ultrawideMode == 1)
+ {
+ CloseAllSecondaryMonitorWindows();
+ _primarySliceRect = null;
+ PrimarySliceSurface.IsVisible = false;
+ FramebufferImage.IsVisible = true;
+
+ var halfW = Math.Max(200, (hostPixelW / 2) & ~1);
+ var h = Math.Max(200, hostPixelH & ~1);
+ var scale = ResolveMonitorScalePercent(vm, hostEntry.Screen.Scaling);
+ var splitLayouts = new System.Collections.Generic.List
+ {
+ new(0, 0, halfW, h, scale, true),
+ new(halfW, 0, halfW, h, scale, false)
+ };
+ vm.TryResizeMonitors(splitLayouts);
+ SyncMultiMonitorActiveFlag();
+ return;
+ }
+
+ var layouts = new System.Collections.Generic.List(selected.Count);
+ var sliceByIndex = new System.Collections.Generic.Dictionary();
+
+ // 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 = ResolveMonitorScalePercent(vm, remotePrimaryEntry.Screen.Scaling);
+ layouts.Add(new RdpMonitorRect(0, 0, totalW, totalH, scale, true));
+ }
+ 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 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 = ResolveMonitorScalePercent(vm, item.Screen.Scaling);
+ 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 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 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);
+
+ if (selected.Count == 1 && _virtualMonitorIds.Count == 0)
+ {
+ CloseAllSecondaryMonitorWindows();
+ _primarySliceRect = null;
+ PrimarySliceSurface.IsVisible = false;
+ FramebufferImage.IsVisible = true;
+ SyncMultiMonitorActiveFlag();
+ return;
+ }
+
+ _primarySliceRect = sliceByIndex[hostEntry.Index];
+ PrimarySliceSurface.Source = vm.Framebuffer;
+ PrimarySliceSurface.SourceRect = _primarySliceRect.Value;
+ PrimarySliceSurface.IsVisible = true;
+ FramebufferImage.IsVisible = false;
+
+ var activeSecondary = new System.Collections.Generic.HashSet();
+ foreach (var item in selected)
+ {
+ if (item.Index == hostEntry.Index)
+ continue;
+
+ activeSecondary.Add(item.Index);
+ var slice = sliceByIndex[item.Index];
+ if (_secondaryMonitorWindows.TryGetValue(item.Index, out var existing))
+ {
+ existing.UpdateSlice(slice);
+ }
+ else
+ {
+ var monitorWin = new RdpMonitorWindow(this, vm, item.Screen, item.Index, slice, OnSecondaryMonitorCloseRequested);
+ _secondaryMonitorWindows[item.Index] = monitorWin;
+ monitorWin.Show();
+ }
+ }
+
+ for (var vi = 0; vi < _virtualMonitorIds.Count; vi++)
+ {
+ var vId = _virtualMonitorIds[vi];
+ activeSecondary.Add(vId);
+ var slice = sliceByIndex[vId];
+ if (_secondaryMonitorWindows.TryGetValue(vId, out var existing))
+ {
+ existing.UpdateSlice(slice);
+ }
+ else
+ {
+ var vTitle = $"虚拟屏 {vi + 1} · {(int)slice.Width}×{(int)slice.Height}";
+ var monitorWin = new RdpMonitorWindow(
+ this,
+ vm,
+ hostEntry.Screen,
+ vId,
+ slice,
+ OnSecondaryMonitorCloseRequested,
+ startWindowed: true,
+ customTitle: vTitle);
+ _secondaryMonitorWindows[vId] = monitorWin;
+ monitorWin.Show();
+ }
+ }
+
+ var toClose = new System.Collections.Generic.List();
+ foreach (var key in _secondaryMonitorWindows.Keys)
+ {
+ if (!activeSecondary.Contains(key))
+ toClose.Add(key);
+ }
+ foreach (var key in toClose)
+ {
+ if (_secondaryMonitorWindows.Remove(key, out var win))
+ win.CloseProgrammatically();
+ }
+
+ SyncMultiMonitorActiveFlag();
+ }
+
+ private void OnSecondaryMonitorCloseRequested(int monitorIndex)
+ {
+ _selectedMonitorIndices.Remove(monitorIndex);
+ _virtualMonitorIds.Remove(monitorIndex);
+ if (_secondaryMonitorWindows.Remove(monitorIndex, out var win))
+ win.CloseProgrammatically();
+ ApplySelectedMonitorLayout();
+ UpdateUltrawideModeButtonStates();
+ SyncMultiMonitorActiveFlag();
+ }
+
+ private void CloseAllSecondaryMonitorWindows()
+ {
+ foreach (var win in _secondaryMonitorWindows.Values)
+ win.CloseProgrammatically();
+ _secondaryMonitorWindows.Clear();
+ }
+
+ private void OnPointerShapeChanged(int kind, int width, int height, int hotX, int hotY, byte[]? pixels)
+ {
+ if (kind == 1)
+ {
+ DisposeCustomRemoteCursor();
+ ApplyCursorToAllSurfaces(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));
+ ApplyCursorToAllSurfaces(cursor);
+ DisposeCustomRemoteCursor();
+ _customRemoteCursor = cursor;
+ _customRemoteCursorBitmap = bitmap;
+ return;
+ }
+ catch
+ {
+ // Fall back to default arrow cursor if platform cursor creation fails.
+ }
+ }
+
+ DisposeCustomRemoteCursor();
+ ApplyCursorToAllSurfaces(new Cursor(StandardCursorType.Arrow));
+ }
+
+ private void ApplyCursorToAllSurfaces(Cursor cursor)
+ {
+ FramebufferImage.Cursor = cursor;
+ PrimarySliceSurface.Cursor = cursor;
+ foreach (var win in _secondaryMonitorWindows.Values)
+ win.SetRemoteCursor(cursor);
+ }
+
+ private void DisposeCustomRemoteCursor()
+ {
+ _customRemoteCursor?.Dispose();
+ _customRemoteCursor = null;
+ _customRemoteCursorBitmap?.Dispose();
+ _customRemoteCursorBitmap = null;
+ }
+
+ private void StartClipboardListener()
+ {
+ if (OperatingSystem.IsWindows())
+ {
+ if (_clipboardListener != null)
+ return;
+
+ _clipboardListener = new WindowsClipboardListener();
+ _clipboardListener.ClipboardChanged += OnLocalClipboardChanged;
+ return;
+ }
+
+ if (_clipboardPollTimer != null)
+ return;
+
+ _clipboardPollTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(800) };
+ _clipboardPollTimer.Tick += OnClipboardPollTick;
+ _clipboardPollTimer.Start();
+ }
+
+ private void StopClipboardListener()
+ {
+ if (_clipboardListener != null)
+ {
+ _clipboardListener.ClipboardChanged -= OnLocalClipboardChanged;
+ _clipboardListener.Dispose();
+ _clipboardListener = null;
+ }
+
+ if (_clipboardPollTimer != null)
+ {
+ _clipboardPollTimer.Stop();
+ _clipboardPollTimer.Tick -= OnClipboardPollTick;
+ _clipboardPollTimer = null;
+ }
+ }
+
+ private void OnClipboardPollTick(object? sender, EventArgs e)
+ {
+ if (_isAttached && DataContext is RdpViewModel { IsConnected: true, IsClipboardChannelReady: true })
+ _ = SyncLocalClipboardToRemoteAsync();
+ }
+
+ private void OnLocalClipboardChanged()
+ {
+ Dispatcher.UIThread.Post(() => _ = SyncLocalClipboardToRemoteAsync());
+ }
+
+ private void OnRemoteClipboardImageReceived(uint imageFormat, byte[] data)
+ {
+ _ = ApplyRemoteClipboardImageAsync(imageFormat, data);
+ }
+
+ private void OnRemoteClipboardFilesReceived(string[] paths)
+ {
+ _ = ApplyRemoteClipboardFilesAsync(paths);
}
private void UpdateSystemShortcutHook()
@@ -209,8 +921,10 @@ private void OnViewportSizeChanged(object? sender, SizeChangedEventArgs e)
ConfigureInitialDisplay(vm, e.NewSize);
if (_isAttached)
vm.Start();
- vm.RequestViewportResize(e.NewSize, GetRenderScaling());
- _lastRenderScaling = GetRenderScaling();
+ if (IsCustomMonitorLayoutActive)
+ ApplySelectedMonitorLayout();
+ else
+ vm.RequestViewportResize(e.NewSize, GetRenderScaling());
}
}
@@ -231,6 +945,105 @@ private void ConfigureInitialDisplay(RdpViewModel vm, Size viewportSize)
vm.ConfigureInitialDisplay(viewportSize, GetCurrentMonitorPixelSize(), GetRenderScaling());
}
+ private void OnRdpDragOver(object? sender, DragEventArgs e)
+ {
+ if (DataContext is RdpViewModel vm &&
+ vm.IsConnected &&
+ vm.IsClipboardChannelReady &&
+ e.DataTransfer.TryGetFiles() is { Length: > 0 })
+ {
+ e.DragEffects = DragDropEffects.Copy;
+ e.Handled = true;
+ return;
+ }
+
+ e.DragEffects = DragDropEffects.None;
+ }
+
+ private void OnRdpDrop(object? sender, DragEventArgs e)
+ {
+ if (DataContext is not RdpViewModel vm || !vm.IsConnected || !vm.IsClipboardChannelReady)
+ return;
+
+ var files = e.DataTransfer.TryGetFiles();
+ if (files == null || files.Length == 0)
+ return;
+
+ var paths = new System.Collections.Generic.List(files.Length);
+ foreach (var item in files)
+ {
+ var path = item.Path?.LocalPath;
+ if (!string.IsNullOrWhiteSpace(path))
+ paths.Add(path);
+ }
+
+ if (paths.Count == 0)
+ return;
+
+ e.Handled = true;
+ var pathArray = paths.ToArray();
+ _ = DropFilesToRemoteAsync(vm, pathArray);
+ }
+
+ private async Task DropFilesToRemoteAsync(RdpViewModel vm, string[] paths)
+ {
+ vm.SetClipboardFiles(paths);
+ _lastSyncedClipboardFilesKey = string.Join("\n", paths);
+ _lastSyncedClipboardText = null;
+ _lastSyncedClipboardImageHash = null;
+ await Task.Delay(150);
+ SendClipboardPasteShortcut(vm);
+ }
+
+ 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 OnTopLevelScalingChanged(object? sender, EventArgs e)
+ {
+ if (DataContext is RdpViewModel vm)
+ {
+ if (IsCustomMonitorLayoutActive)
+ ApplySelectedMonitorLayout();
+ else
+ vm.RequestViewportResize(RdpViewport.Bounds.Size, GetRenderScaling());
+ }
+ }
+
+ private void SubscribeTopLevelScaling()
+ {
+ UnsubscribeTopLevelScaling();
+ var topLevel = TopLevel.GetTopLevel(this);
+ if (topLevel == null)
+ return;
+
+ _subscribedTopLevel = topLevel;
+ _subscribedTopLevel.ScalingChanged += OnTopLevelScalingChanged;
+ }
+
+ private void UnsubscribeTopLevelScaling()
+ {
+ if (_subscribedTopLevel == null)
+ return;
+
+ _subscribedTopLevel.ScalingChanged -= OnTopLevelScalingChanged;
+ _subscribedTopLevel = null;
+ }
+
private double GetRenderScaling()
{
return TopLevel.GetTopLevel(this)?.RenderScaling ?? 1;
@@ -254,7 +1067,8 @@ private void OnFramebufferPointerPressed(object? sender, PointerPressedEventArgs
{
Focus();
_ = SyncLocalClipboardToRemoteAsync();
- var point = e.GetCurrentPoint(FramebufferImage);
+ var pointerTarget = PrimarySliceSurface.IsVisible ? (Visual)PrimarySliceSurface : FramebufferImage;
+ var point = e.GetCurrentPoint(pointerTarget);
if (point.Properties.IsLeftButtonPressed)
_buttonFlags |= 0x1000;
if (point.Properties.IsMiddleButtonPressed)
@@ -321,17 +1135,108 @@ private void OnFramebufferKeyUp(object? sender, KeyEventArgs e)
SendKey(e, false);
}
+ internal void ForwardKeyDown(KeyEventArgs e) => OnFramebufferKeyDown(this, e);
+ internal void ForwardKeyUp(KeyEventArgs e) => OnFramebufferKeyUp(this, e);
+ internal void ForwardDragOver(DragEventArgs e) => OnRdpDragOver(this, e);
+ internal void ForwardDrop(DragEventArgs e) => OnRdpDrop(this, e);
+ internal void ForwardGotFocus()
+ {
+ SyncLocalLockKeysToRemote();
+ _ = SyncLocalClipboardToRemoteAsync();
+ }
+
+ internal void ForwardLostFocus()
+ {
+ ReleaseTrackedModifiers();
+ }
+
+ internal void RequestClipboardSync() => _ = SyncLocalClipboardToRemoteAsync();
+
+ internal bool TryMapGlobalScreenPoint(PixelPoint screenPoint, out ushort remoteX, out ushort remoteY)
+ {
+ remoteX = 0;
+ remoteY = 0;
+
+ if (PrimarySliceSurface.IsVisible && _primarySliceRect is { Width: > 0, Height: > 0 } slice)
+ {
+ var bounds = PrimarySliceSurface.Bounds;
+ if (bounds.Width > 0 && bounds.Height > 0)
+ {
+ var topLeft = PrimarySliceSurface.PointToScreen(new Point(0, 0));
+ var bottomRight = PrimarySliceSurface.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)
+ {
+ 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(slice.X + relX * slice.Width), 0, ushort.MaxValue);
+ remoteY = (ushort)Math.Clamp((int)Math.Round(slice.Y + relY * slice.Height), 0, ushort.MaxValue);
+ return true;
+ }
+ }
+ }
+
+ foreach (var win in _secondaryMonitorWindows.Values)
+ {
+ if (win.TryMapScreenPoint(screenPoint, out remoteX, out remoteY))
+ return true;
+ }
+
+ return false;
+ }
+
private void SendPointer(PointerEventArgs e, ushort flags)
{
if (DataContext is not RdpViewModel vm || FramebufferImage == null)
return;
+ if (PrimarySliceSurface.IsVisible && _primarySliceRect is { Width: > 0, Height: > 0 } slice)
+ {
+ var bounds = PrimarySliceSurface.Bounds;
+ if (bounds.Width <= 0 || bounds.Height <= 0)
+ return;
+
+ var pos = e.GetPosition(PrimarySliceSurface);
+ if (pos.X < 0 || pos.X > bounds.Width || pos.Y < 0 || pos.Y > bounds.Height)
+ {
+ var screenPt = PrimarySliceSurface.PointToScreen(pos);
+ if (TryMapGlobalScreenPoint(screenPt, out var gx, out var gy))
+ {
+ _lastRemotePointerX = gx;
+ _lastRemotePointerY = gy;
+ vm.SendPointer(flags, gx, gy);
+ }
+ else if (flags != 0x0800)
+ {
+ // In gap between windows: pause move updates, but still deliver button release cleanly.
+ vm.SendPointer(flags, _lastRemotePointerX, _lastRemotePointerY);
+ }
+ return;
+ }
+
+ var relX = Math.Clamp(pos.X / bounds.Width, 0, 1);
+ var relY = Math.Clamp(pos.Y / bounds.Height, 0, 1);
+ var vx = slice.X + relX * slice.Width;
+ var vy = slice.Y + relY * slice.Height;
+ var rx = (ushort)Math.Clamp((int)Math.Round(vx), 0, ushort.MaxValue);
+ var ry = (ushort)Math.Clamp((int)Math.Round(vy), 0, ushort.MaxValue);
+ _lastRemotePointerX = rx;
+ _lastRemotePointerY = ry;
+ vm.SendPointer(flags, rx, ry);
+ return;
+ }
+
var (x, y) = MapPointer(
e.GetPosition(FramebufferImage),
FramebufferImage.Bounds.Size,
vm.RemoteWidth,
vm.RemoteHeight,
vm.IsFitToWindow);
+ _lastRemotePointerX = (ushort)x;
+ _lastRemotePointerY = (ushort)y;
vm.SendPointer(flags, (ushort)x, (ushort)y);
}
@@ -433,21 +1338,86 @@ private async Task PasteClipboardViaRdpAsync()
if (DataContext is not RdpViewModel vm)
return;
+ var currentSeq = RdpClipboardImageHelper.GetWindowsClipboardSequenceNumber();
+ if (vm.IsClipboardChannelReady && currentSeq != 0 && currentSeq == _lastAppliedRemoteClipboardSeq)
+ {
+ SendClipboardPasteShortcut(vm);
+ return;
+ }
+
+ var seqChanged = currentSeq != 0 && currentSeq != _lastSyncedLocalClipboardSeq;
+ var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
+
+ if (vm.IsClipboardChannelReady)
+ {
+ var files = await RdpClipboardImageHelper.TryReadLocalFilesAsync(clipboard);
+ if (files is { Length: > 0 })
+ {
+ var filesKey = string.Join("\n", files);
+ var alreadySynced = !seqChanged && string.Equals(filesKey, _lastSyncedClipboardFilesKey, StringComparison.Ordinal);
+ if (!alreadySynced)
+ {
+ vm.SetClipboardFiles(files);
+ _lastSyncedClipboardFilesKey = filesKey;
+ _lastSyncedClipboardText = null;
+ _lastSyncedClipboardImageHash = null;
+ _lastSyncedLocalClipboardSeq = currentSeq;
+ await Task.Delay(150);
+ }
+
+ SendClipboardPasteShortcut(vm);
+ return;
+ }
+ }
+
var text = await TryReadLocalClipboardTextAsync();
- if (string.IsNullOrEmpty(text))
+ if (!string.IsNullOrEmpty(text))
+ {
+ if (!vm.IsClipboardChannelReady)
+ {
+ vm.SetClipboardText(text);
+ _lastSyncedClipboardText = text;
+ _lastSyncedClipboardImageHash = null;
+ _lastSyncedClipboardFilesKey = null;
+ _lastSyncedLocalClipboardSeq = currentSeq;
+ await PasteLocalClipboardTextAsync(text);
+ return;
+ }
+
+ var alreadySynced = !seqChanged && string.Equals(text, _lastSyncedClipboardText, StringComparison.Ordinal);
+ if (!alreadySynced)
+ {
+ var (html, rtf) = await RdpClipboardImageHelper.TryReadLocalRichTextAsync(clipboard);
+ vm.SetClipboardRichText(text, html, rtf);
+ _lastSyncedClipboardText = text;
+ _lastSyncedClipboardImageHash = null;
+ _lastSyncedClipboardFilesKey = null;
+ _lastSyncedLocalClipboardSeq = currentSeq;
+ await Task.Delay(150);
+ }
+
+ SendClipboardPasteShortcut(vm);
return;
+ }
if (!vm.IsClipboardChannelReady)
- {
- vm.SetClipboardText(text);
- _lastSyncedClipboardText = text;
- await PasteLocalClipboardTextAsync(text);
return;
+
+ var image = await RdpClipboardImageHelper.TryReadLocalImageAsync(clipboard);
+ if (image == null)
+ return;
+
+ var imageAlreadySynced = !seqChanged && string.Equals(image.Hash, _lastSyncedClipboardImageHash, StringComparison.Ordinal);
+ if (!imageAlreadySynced)
+ {
+ vm.SetClipboardImage(image.PngBytes, image.DibBytes);
+ _lastSyncedClipboardImageHash = image.Hash;
+ _lastSyncedClipboardText = null;
+ _lastSyncedClipboardFilesKey = null;
+ _lastSyncedLocalClipboardSeq = currentSeq;
+ await Task.Delay(150);
}
- vm.SetClipboardText(text);
- _lastSyncedClipboardText = text;
- await Task.Delay(300);
SendClipboardPasteShortcut(vm);
}
@@ -510,12 +1480,52 @@ private async Task SyncLocalClipboardToRemoteAsync()
if (_applyingRemoteClipboardText || DataContext is not RdpViewModel vm || !vm.IsClipboardChannelReady)
return;
+ var currentSeq = RdpClipboardImageHelper.GetWindowsClipboardSequenceNumber();
+ if (currentSeq != 0 && currentSeq == _lastAppliedRemoteClipboardSeq)
+ return;
+
+ var seqChanged = currentSeq != 0 && currentSeq != _lastSyncedLocalClipboardSeq;
+ var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
+
+ var files = await RdpClipboardImageHelper.TryReadLocalFilesAsync(clipboard);
+ if (files is { Length: > 0 })
+ {
+ var filesKey = string.Join("\n", files);
+ if (!seqChanged && string.Equals(filesKey, _lastSyncedClipboardFilesKey, StringComparison.Ordinal))
+ return;
+
+ vm.SetClipboardFiles(files);
+ _lastSyncedClipboardFilesKey = filesKey;
+ _lastSyncedClipboardText = null;
+ _lastSyncedClipboardImageHash = null;
+ _lastSyncedLocalClipboardSeq = currentSeq;
+ return;
+ }
+
var text = await TryReadLocalClipboardTextAsync();
- if (text == null || string.Equals(text, _lastSyncedClipboardText, StringComparison.Ordinal))
+ if (!string.IsNullOrEmpty(text))
+ {
+ if (!seqChanged && string.Equals(text, _lastSyncedClipboardText, StringComparison.Ordinal))
+ return;
+
+ var (html, rtf) = await RdpClipboardImageHelper.TryReadLocalRichTextAsync(clipboard);
+ vm.SetClipboardRichText(text, html, rtf);
+ _lastSyncedClipboardText = text;
+ _lastSyncedClipboardImageHash = null;
+ _lastSyncedClipboardFilesKey = null;
+ _lastSyncedLocalClipboardSeq = currentSeq;
return;
+ }
- vm.SetClipboardText(text);
- _lastSyncedClipboardText = text;
+ var image = await RdpClipboardImageHelper.TryReadLocalImageAsync(clipboard);
+ if (image == null || (!seqChanged && string.Equals(image.Hash, _lastSyncedClipboardImageHash, StringComparison.Ordinal)))
+ return;
+
+ vm.SetClipboardImage(image.PngBytes, image.DibBytes);
+ _lastSyncedClipboardImageHash = image.Hash;
+ _lastSyncedClipboardText = null;
+ _lastSyncedClipboardFilesKey = null;
+ _lastSyncedLocalClipboardSeq = currentSeq;
}
private async Task ApplyRemoteClipboardTextAsync(string text)
@@ -528,6 +1538,59 @@ private async Task ApplyRemoteClipboardTextAsync(string text)
{
await clipboard.SetTextAsync(text);
_lastSyncedClipboardText = text;
+ _lastSyncedClipboardImageHash = null;
+ _lastSyncedClipboardFilesKey = null;
+ _lastAppliedRemoteClipboardSeq = RdpClipboardImageHelper.GetWindowsClipboardSequenceNumber();
+ }
+ }
+ catch
+ {
+ // Clipboard access may fail on some desktop backends.
+ }
+ finally
+ {
+ _applyingRemoteClipboardText = false;
+ }
+ }
+
+ 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 = RdpClipboardImageHelper.ComputeHash(
+ imageFormat == RdpBridgeClient.ClipboardImageFormatPng ? data : null,
+ imageFormat == RdpBridgeClient.ClipboardImageFormatDib ? data : null);
+ _lastSyncedClipboardText = null;
+ _lastSyncedClipboardFilesKey = null;
+ _lastAppliedRemoteClipboardSeq = RdpClipboardImageHelper.GetWindowsClipboardSequenceNumber();
+ }
+ }
+ catch
+ {
+ // Clipboard access may fail on some desktop backends.
+ }
+ finally
+ {
+ _applyingRemoteClipboardText = false;
+ }
+ }
+
+ 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);
+ _lastSyncedClipboardText = null;
+ _lastSyncedClipboardImageHash = null;
+ _lastAppliedRemoteClipboardSeq = RdpClipboardImageHelper.GetWindowsClipboardSequenceNumber();
}
}
catch
diff --git a/Views/RdpWorkspaceWindow.axaml b/Views/RdpWorkspaceWindow.axaml
new file mode 100644
index 0000000..c071640
--- /dev/null
+++ b/Views/RdpWorkspaceWindow.axaml
@@ -0,0 +1,143 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
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 23fed19..e1d16b3 100644
--- a/Views/SessionEditDialog.axaml
+++ b/Views/SessionEditDialog.axaml
@@ -1590,7 +1590,7 @@
BorderThickness="1"
CornerRadius="4"
Padding="18">
-
+
+
+
+
+
+
+
+
+
+
+
@@ -1694,7 +1731,7 @@
BorderThickness="1"
CornerRadius="4"
Padding="18">
-
-
+
+
+
+
+
+
+
diff --git a/Views/SessionEditDialog.axaml.cs b/Views/SessionEditDialog.axaml.cs
index 939b8d7..65e3847 100644
--- a/Views/SessionEditDialog.axaml.cs
+++ b/Views/SessionEditDialog.axaml.cs
@@ -451,6 +451,8 @@ 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.RdpWindowMode = GetSelectedOptionText(RdpWindowModeSelect, vm.RdpWindowMode);
vm.RdpAudioMode = GetSelectedOptionText(RdpAudioModeSelect, vm.RdpAudioMode);
vm.VncDisplayMode = GetSelectedOptionText(VncDisplayModeSelect, vm.VncDisplayMode);
vm.VncResizeMode = GetSelectedOptionText(VncResizeModeSelect, vm.VncResizeMode);
@@ -2763,6 +2765,8 @@ private void SetSelectedRdpOptions()
SelectOption(RdpDpiPolicySelect, vm.RdpDpiPolicy);
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.cpp b/native/CxRdpBridge/cxrdp_bridge.cpp
index 15547ed..a34f2ba 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
@@ -13,9 +15,16 @@
#include
#include
#include
+#include
#include
#if defined(_WIN32)
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
#include
#include
#else
@@ -58,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;
@@ -79,9 +114,11 @@ 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;
+ 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
@@ -124,16 +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.
@@ -420,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;
@@ -678,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";
}
@@ -784,7 +1103,13 @@ 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;
CLIPRDR_CAPABILITIES capabilities{};
capabilities.common.msgType = CB_CLIP_CAPS;
@@ -811,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());
}
@@ -1449,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());
}
@@ -1511,8 +1971,29 @@ 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;
+ if (!session->local_clipboard_files.empty())
+ session->locked_clipboard_files[lockClipboardData->clipDataId] = session->local_clipboard_files;
+ 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;
}
@@ -1520,8 +2001,25 @@ 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);
+ 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)
+ {
+ std::ostringstream message;
+ message << "RDP clipboard data unlocked clipDataId=" << unlockClipboardData->clipDataId;
+ notify_status(session, message.str().c_str());
+ }
+ }
return CHANNEL_RC_OK;
}
@@ -1543,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;
{
@@ -1590,45 +2178,317 @@ UINT cx_cliprdr_server_format_data_response(
if ((formatDataResponse->common.msgFlags & CB_RESPONSE_FAIL) != 0)
return CHANNEL_RC_OK;
- uint32_t requestedFormat = 0;
+ 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;
+
+ {
+ std::ostringstream message;
+ message << "RDP clipboard remote data received. format="
+ << clipboard_format_name(requestedFormat)
+ << " bytes=" << length;
+ notify_status(session, message.str().c_str());
+ }
+ notify_clipboard_text(session, decode_clipboard_text_format(data, length, requestedFormat));
+ return CHANNEL_RC_OK;
+}
+
+UINT cx_cliprdr_server_file_contents_request(
+ CliprdrClientContext* cliprdr,
+ const CLIPRDR_FILE_CONTENTS_REQUEST* fileContentsRequest)
+{
+ 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)
+{
+ 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);
- requestedFormat = session->clipboard_requested_format;
- session->clipboard_requested_format = 0;
- }
-
- if (!is_supported_text_format(requestedFormat))
+ session->remote_clipboard_files.clear();
+ session->remote_clipboard_top_level_paths.clear();
return CHANNEL_RC_OK;
+ }
- const auto* data = formatDataResponse->requestedFormatData;
- const auto length = formatDataResponse->common.dataLen;
+ std::string progressMessage;
{
- std::ostringstream message;
- message << "RDP clipboard remote data received. format="
- << clipboard_format_name(requestedFormat)
- << " bytes=" << length;
- notify_status(session, message.str().c_str());
+ 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;
+ }
+ }
+ }
}
- notify_clipboard_text(session, decode_clipboard_text_format(data, length, requestedFormat));
- return CHANNEL_RC_OK;
-}
-UINT cx_cliprdr_server_file_contents_request(
- CliprdrClientContext* cliprdr,
- const CLIPRDR_FILE_CONTENTS_REQUEST* fileContentsRequest)
-{
- (void)cliprdr;
- (void)fileContentsRequest;
- return CHANNEL_RC_OK;
-}
+ if (!progressMessage.empty())
+ notify_status(session, progressMessage.c_str());
-UINT cx_cliprdr_server_file_contents_response(
- CliprdrClientContext* cliprdr,
- const CLIPRDR_FILE_CONTENTS_RESPONSE* fileContentsResponse)
-{
- (void)cliprdr;
- (void)fileContentsResponse;
- return CHANNEL_RC_OK;
+ return request_next_remote_file_chunk(cliprdr, session);
}
void initialize_cliprdr(CxRdpSession* session, CliprdrClientContext* cliprdr)
@@ -1646,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;
@@ -1682,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;
}
}
@@ -2352,6 +3224,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)
@@ -2402,6 +3395,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;
}
@@ -2699,6 +3705,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.
@@ -2707,6 +3718,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:
@@ -2745,6 +3759,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);
@@ -2769,6 +3789,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))
{
@@ -3033,7 +4065,15 @@ CX_RDP_API uint32_t cxrdp_get_capabilities(void)
CX_RDP_CAPABILITY_FRAME_MARKER |
CX_RDP_CAPABILITY_PERFORMANCE_FLAGS |
CX_RDP_CAPABILITY_DIRTY_RECT |
- CX_RDP_CAPABILITY_GFX;
+ 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;
if (has_native_audio_backend())
capabilities |= CX_RDP_CAPABILITY_AUDIO_PLAYBACK | CX_RDP_CAPABILITY_MICROPHONE;
return capabilities;
@@ -3086,6 +4126,42 @@ 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)
+{
+ 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,
@@ -3207,6 +4283,16 @@ CX_RDP_API void cxrdp_send_unicode_key(void* handle, uint16_t code, int down)
freerdp_input_send_unicode_keyboard_event(input, down ? 0 : KBD_FLAGS_RELEASE, code);
}
+CX_RDP_API void cxrdp_sync_lock_keys(void* handle, uint32_t flags)
+{
+ auto* session = static_cast(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);
@@ -3215,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;
}
}
@@ -3329,6 +4569,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);
@@ -3341,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.");
@@ -3474,6 +4771,36 @@ 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 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);
diff --git a/native/CxRdpBridge/cxrdp_bridge.h b/native/CxRdpBridge/cxrdp_bridge.h
index 263e406..43016a2 100644
--- a/native/CxRdpBridge/cxrdp_bridge.h
+++ b/native/CxRdpBridge/cxrdp_bridge.h
@@ -20,8 +20,18 @@ 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_clipboard_image_callback)(void* user_data, uint32_t image_format, const uint8_t* data, uint32_t length);
+typedef void (*cxrdp_clipboard_files_callback)(void* user_data, const char* file_paths_newline_separated);
+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 11u
+#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
@@ -50,6 +60,34 @@ 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
+/* The bridge forwards remote mouse pointer bitmaps and hotspots to the host. */
+#define CX_RDP_CAPABILITY_POINTER_SHAPE 0x00002000u
+#define CX_RDP_CAPABILITY_CLIPBOARD_IMAGE 0x00004000u
+#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
+#define CX_RDP_CAPABILITY_GFX_H264 0x00080000u
+
+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
+
+#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
@@ -79,8 +117,26 @@ 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_image_callback(void* handle, cxrdp_clipboard_image_callback clipboard_image_callback);
+CX_RDP_API void cxrdp_set_clipboard_files_callback(void* handle, cxrdp_clipboard_files_callback clipboard_files_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 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);
+CX_RDP_API void cxrdp_set_clipboard_image(
+ void* handle,
+ uint32_t image_format,
+ const uint8_t* data,
+ uint32_t length);
+CX_RDP_API void cxrdp_set_clipboard_files(void* handle, const char* file_paths_newline_separated);
+CX_RDP_API int cxrdp_set_clipboard_lock_enabled(void* handle, int enabled);
CX_RDP_API int cxrdp_set_drive_redirection(
void* handle,
int enabled,
@@ -102,6 +158,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
@@ -140,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);
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