diff --git a/plugins/VelaShell.Plugin.Rdp/Loc.cs b/plugins/VelaShell.Plugin.Rdp/Loc.cs index 7d8cf57..54c7a83 100644 --- a/plugins/VelaShell.Plugin.Rdp/Loc.cs +++ b/plugins/VelaShell.Plugin.Rdp/Loc.cs @@ -34,14 +34,17 @@ var s when s.StartsWith("ko") => 4, ["SmartCard"] = ["Redirect smart-card readers", "重定向智能卡读卡器", "重新導向智慧卡讀卡機", "スマートカード リーダーを転送", "스마트 카드 리더 리디렉션"], ["SmartCardHint"] = ["Allows the remote session to use all local PC/SC readers and cards. Off by default. Requires the local smart-card service and drivers; this does not enable smart-card NLA logon.", "允许远程会话使用全部本地 PC/SC 读卡器和智能卡,默认关闭。需要本机智能卡服务和驱动;此项不启用智能卡 NLA 登录。", "允許遠端工作階段使用全部本機 PC/SC 讀卡機及智慧卡,預設關閉。需要本機智慧卡服務及驅動程式;此項不啟用智慧卡 NLA 登入。", "すべてのローカル PC/SC リーダーとカードの利用を許可します。既定はオフ。サービスとドライバーが必要です。スマートカード NLA ログオンは有効になりません。", "원격 세션에서 모든 로컬 PC/SC 리더와 카드를 사용하도록 허용합니다. 기본값은 꺼짐입니다. 로컬 서비스와 드라이버가 필요하며 스마트 카드 NLA 로그인을 활성화하지는 않습니다."], ["GraphicsMode"] = ["Graphics mode", "图形模式", "圖形模式", "グラフィックス モード", "그래픽 모드"], - ["GraphicsAuto"] = ["Automatic (RDPGFX / H.264)", "自动(RDPGFX / H.264)", "自動(RDPGFX / H.264)", "自動 (RDPGFX / H.264)", "자동 (RDPGFX / H.264)"], + ["GraphicsAuto"] = ["Automatic (RDPGFX)", "自动(RDPGFX)", "自動(RDPGFX)", "自動 (RDPGFX)", "자동 (RDPGFX)"], ["GraphicsClassic"] = ["Classic", "经典", "傳統", "クラシック", "클래식"], + ["Avc"] = ["Offer H.264 / AVC graphics", "提供 H.264 / AVC 图形", "提供 H.264 / AVC 圖形", "H.264 / AVC グラフィックスを提示", "H.264 / AVC 그래픽 제공"], + ["AvcHint"] = ["Off by default. AVC is offered only when the managed RDPGFX pipeline is enabled and this setting is on.", "默认关闭。仅在启用托管 RDPGFX 且打开此项时提供 AVC。", "預設關閉。只有啟用託管 RDPGFX 且開啟此項時才提供 AVC。", "既定はオフ。管理 RDPGFX とこの設定の両方が有効なときだけ AVC を提示します。", "기본값은 꺼짐입니다. 관리 RDPGFX와 이 설정이 모두 켜진 경우에만 AVC를 제공합니다."], ["GraphicsModeHint"] = [ - "Automatic offers RDPGFX with AVC420/AVC444/AVC444v2; the server selects the graphics mode. Classic disables RDPGFX. RemoteApp always uses classic graphics. A graphics failure after negotiation disconnects the session.", - "自动模式协商 RDPGFX(AVC420/AVC444/AVC444v2),由服务器选择图形模式。经典模式关闭 RDPGFX。RemoteApp 始终使用经典图形。协商后图形处理失败会断开会话。", - "自動模式協商 RDPGFX(AVC420/AVC444/AVC444v2),由伺服器選擇圖形模式。傳統模式關閉 RDPGFX。RemoteApp 一律使用傳統圖形。協商後圖形處理失敗會中斷工作階段。", - "自動では RDPGFX (AVC420/AVC444/AVC444v2) を提示し、サーバーが描画方式を選択します。クラシックは RDPGFX を無効にします。RemoteApp は常にクラシックを使用します。ネゴシエーション後の描画障害は接続を終了します。", - "자동은 RDPGFX (AVC420/AVC444/AVC444v2)를 제안하고 서버가 그래픽 모드를 선택합니다. 클래식은 RDPGFX를 비활성화합니다. RemoteApp은 항상 클래식 그래픽을 사용합니다. 협상 후 그래픽 오류가 발생하면 연결이 종료됩니다."], + "Automatic offers RDPGFX; the server selects the graphics mode. Enable H.264/AVC separately to offer AVC420/AVC444/AVC444v2. Classic disables RDPGFX. RemoteApp always uses classic graphics. A graphics failure after negotiation disconnects the session.", + "Automatic offers RDPGFX; AVC420/AVC444/AVC444v2 are offered separately only when enabled. The server selects the graphics mode. Classic disables RDPGFX. RemoteApp always uses classic graphics. A graphics failure after negotiation disconnects the session.", + "自动模式提供 RDPGFX;仅在单独启用时提供 AVC420/AVC444/AVC444v2,由服务器选择图形模式。经典模式关闭 RDPGFX。RemoteApp 始终使用经典图形。协商后图形处理失败会断开会话。", + "自動模式提供 RDPGFX;僅在另行啟用時提供 AVC420/AVC444/AVC444v2,由伺服器選擇圖形模式。傳統模式關閉 RDPGFX。RemoteApp 一律使用傳統圖形。協商後圖形處理失敗會中斷工作階段。", + "自動では RDPGFX を提示します。AVC420/AVC444/AVC444v2 は別設定が有効な場合のみ提示し、サーバーが描画方式を選択します。クラシックは RDPGFX を無効にします。RemoteApp は常にクラシックを使用します。ネゴシエーション後の描画障害は接続を終了します。", + "자동은 RDPGFX를 제공합니다. AVC420/AVC444/AVC444v2는 별도 설정이 켜진 경우에만 제공하며 서버가 그래픽 모드를 선택합니다. 클래식은 RDPGFX를 비활성화합니다. RemoteApp은 항상 클래식 그래픽을 사용합니다. 협상 후 그래픽 오류가 발생하면 연결이 종료됩니다."], ["WpdDevices"] = ["Portable device (WPD)", "便携设备(WPD)", "可攜式裝置(WPD)", "ポータブル デバイス (WPD)", "휴대용 장치 (WPD)"], ["WpdHint"] = [ "Allow the remote session to read and change this selected Windows portable device. Off by default; WPD only, not general USB. Removal closes its handles; reinsertion resumes only when its unique identity is verified.", diff --git a/plugins/VelaShell.Plugin.Rdp/README.md b/plugins/VelaShell.Plugin.Rdp/README.md index e2675cd..4b73028 100644 --- a/plugins/VelaShell.Plugin.Rdp/README.md +++ b/plugins/VelaShell.Plugin.Rdp/README.md @@ -124,8 +124,8 @@ arguments. - Desktop resolution follows the workspace tab: on connect and whenever the window resizes (or moves to a monitor with another DPI), the plugin asks the server over the display-control channel - (MS-RDPEDISP) to match the viewport in device pixels, with the local display scale (150% → remote - UI at 150%, deviceScaleFactor bucketed to 100/140/180) also sent in CS_CORE. A desktop within a + (MS-RDPEDISP) to match the viewport in device pixels, with the local display scale (150% is + quantized to the Windows-supported 140% wire bucket; only 100/140/180 are sent) also sent in CS_CORE. A desktop within a few device pixels of the view is drawn exactly 1:1 on the pixel grid with no filtering; only a real mismatch (a server that cannot follow the window) is scaled to fit with a high-quality filter. Only the width is forced even (MS-RDPEDISP). A new session connects at the last view's size and scale diff --git a/plugins/VelaShell.Plugin.Rdp/RdpClipboardBridge.cs b/plugins/VelaShell.Plugin.Rdp/RdpClipboardBridge.cs index 7fa5790..659e0e4 100644 --- a/plugins/VelaShell.Plugin.Rdp/RdpClipboardBridge.cs +++ b/plugins/VelaShell.Plugin.Rdp/RdpClipboardBridge.cs @@ -68,6 +68,10 @@ private sealed record LocalVersion(RdpClipboardFiles Files, CancellationTokenSou private readonly ConcurrentDictionary _localVersions = new(); private string? _lastRemoteFingerprint; private string? _lastPublishedFingerprint; + private static readonly DataFormat HtmlFormat = DataFormat.CreateBytesPlatformFormat( + OperatingSystem.IsWindows() ? "HTML Format" : OperatingSystem.IsMacOS() ? "public.html" : "text/html"); + private static readonly DataFormat RtfFormat = DataFormat.CreateBytesPlatformFormat( + OperatingSystem.IsWindows() ? "Rich Text Format" : "text/rtf"); internal RdpClipboardBridge(IRdpClipboardTransport transport, IPluginContext context, Control owner, bool enabled, Func? virtualClipboardFactory = null, TimeSpan? fileResponseTimeout = null, TimeSpan? fileRetryDelay = null, @@ -285,6 +289,14 @@ private async Task PublishCoreAsync(CancellationToken ct) { data[RdpClipboardCodec.UnicodeText] = RdpClipboardCodec.EncodeText(text); } + if (await clipboard.TryGetValueAsync(HtmlFormat) is byte[] html) + { + data[RdpClipboardCodec.Html] = RdpClipboardCodec.EncodeRichTextBytes(html); + } + if (await clipboard.TryGetValueAsync(RtfFormat) is byte[] rtf) + { + data[RdpClipboardCodec.Rtf] = RdpClipboardCodec.EncodeRichTextBytes(rtf); + } using Bitmap? bitmap = await clipboard.TryGetBitmapAsync(); if (bitmap is not null) @@ -481,6 +493,10 @@ async Task ReleaseAsync(uint id, TaskCompletionSource completion) ? RdpClipboardCodec.Dib : formats.ContainsKey(RdpClipboardCodec.DibV5) ? RdpClipboardCodec.DibV5 : 0; string? text = null; byte[]? image = null; + byte[]? html = formats.ContainsKey(RdpClipboardCodec.Html) + ? await RequestFormatAsync(RdpClipboardCodec.Html, ct) : null; + byte[]? rtf = formats.ContainsKey(RdpClipboardCodec.Rtf) + ? await RequestFormatAsync(RdpClipboardCodec.Rtf, ct) : null; if (formats.ContainsKey(RdpClipboardCodec.UnicodeText)) { text = RdpClipboardCodec.DecodeText(await RequestFormatAsync(RdpClipboardCodec.UnicodeText, ct).ConfigureAwait(false)); @@ -493,7 +509,7 @@ async Task ReleaseAsync(uint id, TaskCompletionSource completion) } CheckReceive(generation, ct); - if (text is null && image is null) + if (text is null && image is null && html is null && rtf is null) { return; } @@ -529,6 +545,14 @@ async Task ReleaseAsync(uint id, TaskCompletionSource completion) item.SetText(text); data[RdpClipboardCodec.UnicodeText] = RdpClipboardCodec.EncodeText(text); } + if (html is not null) + { + item.Set(HtmlFormat, () => RdpClipboardCodec.EncodeRichTextBytes(html!)); + } + if (rtf is not null) + { + item.Set(RtfFormat, () => RdpClipboardCodec.EncodeRichTextBytes(rtf!)); + } if (image is not null) { if (dib is not null) @@ -1064,6 +1088,8 @@ private void CheckGeneration(int generation) private static string FormatName(uint id) => id switch { RdpClipboardCodec.Png => "PNG", + RdpClipboardCodec.Html => "HTML Format", + RdpClipboardCodec.Rtf => "Rich Text Format", RdpClipboardCodec.FileGroup => "FileGroupDescriptorW", _ => "" }; @@ -1098,6 +1124,14 @@ private static async Task CurrentFingerprintAsync(IClipboard clipboard) { data[RdpClipboardCodec.UnicodeText] = RdpClipboardCodec.EncodeText(text); } + if (await clipboard.TryGetValueAsync(HtmlFormat) is byte[] html) + { + data[RdpClipboardCodec.Html] = RdpClipboardCodec.EncodeRichTextBytes(html); + } + if (await clipboard.TryGetValueAsync(RtfFormat) is byte[] rtf) + { + data[RdpClipboardCodec.Rtf] = RdpClipboardCodec.EncodeRichTextBytes(rtf); + } using Bitmap? bitmap = await clipboard.TryGetBitmapAsync(); if (bitmap is not null) diff --git a/plugins/VelaShell.Plugin.Rdp/RdpClipboardCodec.cs b/plugins/VelaShell.Plugin.Rdp/RdpClipboardCodec.cs index 2cf85d3..016aef8 100644 --- a/plugins/VelaShell.Plugin.Rdp/RdpClipboardCodec.cs +++ b/plugins/VelaShell.Plugin.Rdp/RdpClipboardCodec.cs @@ -17,7 +17,33 @@ internal static class RdpClipboardCodec internal const uint Png = 0xC001; internal const uint FileGroup = 0xC002; internal const uint FileContents = 0xC003; + internal const uint Html = 0xC004; + internal const uint Rtf = 0xC005; private static readonly UnicodeEncoding StrictUnicode = new(false, false, true); + private static readonly UTF8Encoding StrictUtf8 = new(false, true); + + internal static byte[] EncodeRichText(string text) + { + if (text.Contains('\0')) { throw new InvalidDataException("Clipboard rich text contains a NUL character."); } + byte[] data; + try { data = StrictUtf8.GetBytes(text); } + catch (EncoderFallbackException ex) { throw new InvalidDataException("Clipboard rich text is invalid.", ex); } + if (data.Length > MaxPayload) { throw new InvalidDataException("Clipboard rich text is too large."); } + return data; + } + + internal static byte[] EncodeRichTextBytes(byte[] data) + { + if (data.Length > MaxPayload) { throw new InvalidDataException("Clipboard rich text is too large."); } + return data.ToArray(); + } + + internal static string DecodeRichText(byte[] data) + { + if (data.Length > MaxPayload) { throw new InvalidDataException("Clipboard rich text is too large."); } + try { return StrictUtf8.GetString(data); } + catch (DecoderFallbackException ex) { throw new InvalidDataException("Clipboard rich text is invalid.", ex); } + } internal static byte[] EncodeText(string text) { diff --git a/plugins/VelaShell.Plugin.Rdp/RdpConnector.cs b/plugins/VelaShell.Plugin.Rdp/RdpConnector.cs index 1f789d9..75845b2 100644 --- a/plugins/VelaShell.Plugin.Rdp/RdpConnector.cs +++ b/plugins/VelaShell.Plugin.Rdp/RdpConnector.cs @@ -53,6 +53,7 @@ internal static async Task ConnectAsync(WorkspaceConnectRequest req DriveRedirectionLog = driveLog, GraphicsLog = driveLog, EnableGraphicsPipeline = settings.EnableGraphicsPipeline, + EnableAvc = settings.EnableAvc, Security = settings.Security, Performance = settings.Performance, AudioPlayback = settings.Audio diff --git a/plugins/VelaShell.Plugin.Rdp/RdpDesktopControl.cs b/plugins/VelaShell.Plugin.Rdp/RdpDesktopControl.cs index 7b72d19..15b835a 100644 --- a/plugins/VelaShell.Plugin.Rdp/RdpDesktopControl.cs +++ b/plugins/VelaShell.Plugin.Rdp/RdpDesktopControl.cs @@ -44,6 +44,8 @@ private sealed class PendingMove(uint x, uint y) { internal uint _x = x; interna private Window? _window; private TopLevel? _topLevel; private bool _attached; + // The RDP surface owns key delivery while focused; the local IME must be disabled for that control. + private bool _imeAttached = true; internal Func? PublishClipboard { get; set; } internal Action? OperationFailed { get; set; } @@ -80,6 +82,7 @@ public RdpDesktopControl(IRdpSession session, int width, int height) ClipToBounds = true; _ime = new(this); TextInputMethodClientRequested += (_, e) => e.Client = _ime; + SetImeAttached(false); // Coalesce window/tab resizes: ask the server for a matching desktop only after the drag settles. _resizeTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(350) }; _resizeTimer.Tick += (_, _) => { _resizeTimer.Stop(); MatchRemoteToViewport(); }; @@ -428,6 +431,7 @@ private async Task PublishOnFocusAsync(Func publish) protected override void OnGotFocus(FocusChangedEventArgs e) { base.OnGotFocus(e); + SetImeAttached(false); SetRemoteAppFocus(true); UpdateKeyboardHook(); if (PublishClipboard is { } publish) @@ -437,6 +441,7 @@ protected override void OnGotFocus(FocusChangedEventArgs e) } protected override void OnLostFocus(FocusChangedEventArgs e) { + SetImeAttached(true); ReleaseInput(); SetRemoteAppFocus(false); UpdateKeyboardHook(); @@ -509,13 +514,18 @@ internal void PauseUntilShown() } private void OnWindowDeactivated(object? sender, EventArgs e) { + SetImeAttached(true); ReleaseInput(); SetRemoteAppFocus(false); UpdateKeyboardHook(); } private void OnWindowActivated(object? sender, EventArgs e) { - if (IsFocused) { SetRemoteAppFocus(true); } + SetImeAttached(!IsFocused); + if (IsFocused) + { + SetRemoteAppFocus(true); + } UpdateKeyboardHook(); // Returning from another application can retain keyboard focus on this desktop. if (IsFocused && IsEffectivelyVisible && IsEffectivelyEnabled && PublishClipboard is { } publish) @@ -525,6 +535,7 @@ private void OnWindowActivated(object? sender, EventArgs e) } protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e) { + SetImeAttached(false); SetRemoteAppFocus(false); _window?.Activated -= OnWindowActivated; _window?.Deactivated -= OnWindowDeactivated; @@ -765,10 +776,18 @@ private void ReleasePointer() _pointer = null; pointer?.Capture(null); } + private void SetImeAttached(bool attached) + { + if (_imeAttached == attached || _disposed != 0) { return; } + _imeAttached = attached; + InputMethod.SetIsInputMethodEnabled(this, attached); + } + public async ValueTask DisposeAsync() { if (_disposed != 0) { await _inputPump; return; } + SetImeAttached(false); RemoveKeyboardHook(); // releases captured keys while the input queue still accepts them _window?.Activated -= OnWindowActivated; _window?.Deactivated -= OnWindowDeactivated; diff --git a/plugins/VelaShell.Plugin.Rdp/RdpSettings.cs b/plugins/VelaShell.Plugin.Rdp/RdpSettings.cs index 4a23b8d..9845ec3 100644 --- a/plugins/VelaShell.Plugin.Rdp/RdpSettings.cs +++ b/plugins/VelaShell.Plugin.Rdp/RdpSettings.cs @@ -33,7 +33,9 @@ internal sealed record RdpSettings(string Domain, int Width, int Height, int Tim SmartCardKey = "smartCard", RemoteAppProgramKey = "remoteAppProgram", RemoteAppArgumentsKey = "remoteAppArguments", RemoteAppWorkingDirectoryKey = "remoteAppWorkingDirectory"; internal bool EnableGraphicsPipeline { get; init; } = true; + internal bool EnableAvc { get; init; } internal const string GraphicsModeKey = "graphicsMode"; + internal const string AvcKey = "avc"; internal RdpTransportMode Transport { get; init; } = RdpTransportMode.Auto; internal bool AdaptiveNetwork { get; init; } = true; internal const string TransportKey = "transport", AdaptiveNetworkKey = "adaptiveNetwork"; @@ -221,6 +223,7 @@ bool Flag(string key, bool fallback = false) "classic" => false, _ => throw new ProtocolConnectionException(loc.Format("Invalid", GraphicsModeKey)) }; + bool avc = Flag(AvcKey); int colorDepth = request.GetString(ColorDepthKey).Trim() switch { "" => DefaultColorDepth, @@ -285,6 +288,7 @@ bool Flag(string key, bool fallback = false) RemoteApp = remoteApp, SmartCardRedirection = Flag(SmartCardKey), EnableGraphicsPipeline = graphics, + EnableAvc = avc, Transport = request.GetString(TransportKey).Trim().ToLowerInvariant() switch { "" or "auto" => RdpTransportMode.Auto, @@ -461,6 +465,15 @@ internal static IReadOnlyList Declare(Loc loc, IReadOnlyLi Choices = [new("auto", loc["GraphicsAuto"]), new("classic", loc["GraphicsClassic"])] }); fields.Add(new() + { + Key = AvcKey, + Label = loc["Avc"], + Hint = loc["AvcHint"], + Kind = ProtocolSettingKind.Boolean, + DefaultValue = "false", + Page = ExperiencePage + }); + fields.Add(new() { Key = TransportKey, Label = loc["Transport"], diff --git a/src/VelaShell.Rdp/Channels/DrdynvcChannel.cs b/src/VelaShell.Rdp/Channels/DrdynvcChannel.cs index d3a49d4..ce4f254 100644 --- a/src/VelaShell.Rdp/Channels/DrdynvcChannel.cs +++ b/src/VelaShell.Rdp/Channels/DrdynvcChannel.cs @@ -279,14 +279,14 @@ internal async Task ProcessAsync(byte[] pdu, int tunnelType = 0) /// Buffered until the Display Control channel reports its capabilities; a no-op if the server /// never opens the channel (the desktop then stays at the negotiated size, scaled to fit). /// - internal Task RequestResizeAsync(int width, int height, int scale = 100) + internal Task RequestResizeAsync(int width, int height, int scale = 100, CancellationToken cancellationToken = default) { width = Clamp(width) & ~1; // MS-RDPEDISP: the width must be even; the height need not be height = Clamp(height); - return RequestMonitorLayoutAsync(RdpMonitorLayout.Single(width, height), scale); + return RequestMonitorLayoutAsync(RdpMonitorLayout.Single(width, height), scale, cancellationToken); } - internal async Task RequestMonitorLayoutAsync(RdpMonitorLayout layout, int scale = 100) + internal async Task RequestMonitorLayoutAsync(RdpMonitorLayout layout, int scale = 100, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(layout); if (!_displayEnabled) @@ -295,7 +295,7 @@ internal async Task RequestMonitorLayoutAsync(RdpMonitorLayout layout, int scale } scale = RdpScale.Clamp(scale); - await _sendGate.WaitAsync(_ct).ConfigureAwait(false); + await _sendGate.WaitAsync(cancellationToken).ConfigureAwait(false); try { byte[]? frame = null; @@ -321,7 +321,7 @@ internal async Task RequestMonitorLayoutAsync(RdpMonitorLayout layout, int scale _lastSent = frame; } - await _send(frame, _ct).ConfigureAwait(false); + await _send(frame, cancellationToken).ConfigureAwait(false); } finally { _ = _sendGate.Release(); } } diff --git a/src/VelaShell.Rdp/Graphics/Framebuffer.cs b/src/VelaShell.Rdp/Graphics/Framebuffer.cs index 38352a5..be60f3e 100644 --- a/src/VelaShell.Rdp/Graphics/Framebuffer.cs +++ b/src/VelaShell.Rdp/Graphics/Framebuffer.cs @@ -20,6 +20,7 @@ internal sealed partial class Framebuffer private readonly Lock _gate = new(); private int _dirtyLeft, _dirtyTop, _dirtyRight, _dirtyBottom; // exclusive right/bottom; empty when right <= left + private RdpFrameRegion _previousPresented; internal Framebuffer(int width, int height) { @@ -181,6 +182,16 @@ internal RdpFrameRegion CopyTo(Span destination, int stride, bool full) return default; } + // Keep the area presented last in the next changed copy. This protects the retained UI bitmap when a + // producer moves or clears a region: its old pixels are refreshed together with the new dirty bounds. + if (!_previousPresented.IsEmpty + && (_dirtyLeft > _previousPresented.X || _dirtyTop > _previousPresented.Y + || _dirtyRight < _previousPresented.X + _previousPresented.Width + || _dirtyBottom < _previousPresented.Y + _previousPresented.Height)) + { + Union(_previousPresented.X, _previousPresented.Y, + _previousPresented.X + _previousPresented.Width, _previousPresented.Y + _previousPresented.Height); + } var region = new RdpFrameRegion(_dirtyLeft, _dirtyTop, _dirtyRight - _dirtyLeft, _dirtyBottom - _dirtyTop); int rowBytes = region.Width * 4; for (int y = region.Y; y < region.Y + region.Height; y++) @@ -189,6 +200,8 @@ internal RdpFrameRegion CopyTo(Span destination, int stride, bool full) } _dirtyLeft = _dirtyTop = _dirtyRight = _dirtyBottom = 0; + _previousPresented = full || (region.X == 0 && region.Y == 0 && region.Width == Width && region.Height == Height) + ? default : region; return region; } } @@ -199,6 +212,7 @@ internal byte[] Snapshot() lock (_gate) { _dirtyLeft = _dirtyTop = _dirtyRight = _dirtyBottom = 0; + _previousPresented = default; return (byte[])Bgra.Clone(); } } diff --git a/src/VelaShell.Rdp/Graphics/ManagedRdpGfx.cs b/src/VelaShell.Rdp/Graphics/ManagedRdpGfx.cs index 59da52b..f110ab6 100644 --- a/src/VelaShell.Rdp/Graphics/ManagedRdpGfx.cs +++ b/src/VelaShell.Rdp/Graphics/ManagedRdpGfx.cs @@ -22,9 +22,14 @@ internal sealed class ManagedRdpGfx : IRdpGfxBackend private uint _version, _capFlags, _frameId, _decodedFrames; private Rect _dirty; private readonly Action? _log; + private readonly bool _enableAvc; - internal ManagedRdpGfx(int width, int height, Action? log = null) + internal ManagedRdpGfx(int width, int height, Action? log) + : this(width, height, false, log) { } + + internal ManagedRdpGfx(int width, int height, bool enableAvc = false, Action? log = null) { + _enableAvc = enableAvc; _log = log; ValidateDimensions(width, height); OutputWidth = width; OutputHeight = height; @@ -104,7 +109,13 @@ public void Open() { int size = version == 0xa0100 ? 16 : 4; Put32(caps, offset, version); Put32(caps, offset + 4, (uint)size); - if (size == 4) { Put32(caps, offset + 8, version == 0x80105 ? 0x12u : version == 0xa0301 ? 0u : 2u); } + if (size == 4) + { + uint flags = version == 0x80105 + ? 2u | (_enableAvc ? 0x10u : 0u) + : version == 0xa0301 ? 0u : 2u | (_enableAvc ? 0u : 0x20u); + Put32(caps, offset + 8, flags); + } offset += 8 + size; } Enqueue(caps); @@ -299,7 +310,7 @@ private void WireToSurface(ref Reader reader, bool progressive) if (_codecsSeen.Add(codec)) { // Field diagnostics: which codecs this server actually uses (stale-block reports depend on it). - Log($"codec 0x{codec:X4} ({CodecName(codec)}) first used on surface {id}"); + Log($"RDP GFX surface codec 0x{codec:X4} ({CodecName(codec)}) first used on surface {id}"); } _codecs.Decode(new GfxDecodeRequest(id, context, codec, format, rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom, reader.Bytes((int)length).ToArray(), surface._pixels, surface._width, surface._height)); diff --git a/src/VelaShell.Rdp/README.md b/src/VelaShell.Rdp/README.md index 41f8b97..2be7822 100644 --- a/src/VelaShell.Rdp/README.md +++ b/src/VelaShell.Rdp/README.md @@ -80,7 +80,7 @@ await using var session = await RdpManagedSession.ConnectAsync(new RdpClientOpti new(1920, 0, 1920, 1080) ]), ColorDepth = 32, // 15, 16, 24 or 32 - DesktopScaleFactor = 150, // the local display scale, so remote text is not tiny on a high-DPI screen + DesktopScaleFactor = 150, // local scale; wire value is quantized to Windows' supported 140% bucket Clipboard = true, AudioPlayback = true, // default output device; optional, disabled by default EnableGraphicsPipeline = true, // default; false forces classic bitmap/GDI diff --git a/src/VelaShell.Rdp/RdpClientOptions.cs b/src/VelaShell.Rdp/RdpClientOptions.cs index 691b233..db9846b 100644 --- a/src/VelaShell.Rdp/RdpClientOptions.cs +++ b/src/VelaShell.Rdp/RdpClientOptions.cs @@ -109,12 +109,18 @@ public sealed record RdpClientOptions public bool DrawingOrders { get; init; } = true; /// - /// Offer the managed RDP graphics pipeline, including H.264 AVC420/AVC444/AVC444v2. - /// Defaults to true; false selects classic graphics. A server may still choose classic graphics. - /// Graphics failures after negotiation end the session. + /// Offer the managed RDP graphics pipeline. Defaults to true; false selects classic graphics. A server may still + /// choose classic graphics. Graphics failures after negotiation end the session. /// public bool EnableGraphicsPipeline { get; init; } = true; + /// + /// Request H.264 AVC420/AVC444/AVC444v2 capability sets when the managed graphics pipeline is enabled. + /// Defaults to false so AVC is never advertised accidentally; enabling the graphics pipeline alone remains + /// compatible with servers that use the lossless codecs. + /// + public bool EnableAvc { get; init; } + /// Optional graphics initialization/failure diagnostics, called on background threads. public Action? GraphicsLog { get; init; } diff --git a/src/VelaShell.Rdp/RdpManagedSession.Graphics.cs b/src/VelaShell.Rdp/RdpManagedSession.Graphics.cs index 01f64c6..c6f025e 100644 --- a/src/VelaShell.Rdp/RdpManagedSession.Graphics.cs +++ b/src/VelaShell.Rdp/RdpManagedSession.Graphics.cs @@ -18,9 +18,11 @@ public sealed partial class RdpManagedSession } int width = options.MonitorLayout?.DesktopWidth ?? options.Width; int height = options.MonitorLayout?.DesktopHeight ?? options.Height; - IRdpGfxBackend backend = (factory ?? ((w, h) => new ManagedRdpGfx(w, h, + IRdpGfxBackend backend = (factory ?? ((w, h) => new ManagedRdpGfx(w, h, options.EnableAvc, message => GraphicsDiagnostic(options.GraphicsLog, message))))(width, height); - GraphicsDiagnostic(options.GraphicsLog, "managed graphics pipeline ready; offering RDPGFX with AVC420/AVC444/AVC444v2"); + GraphicsDiagnostic(options.GraphicsLog, options.EnableAvc + ? "managed graphics pipeline ready; offering RDPGFX with AVC420/AVC444/AVC444v2" + : "managed graphics pipeline ready; AVC disabled"); return backend; } diff --git a/src/VelaShell.Rdp/RdpManagedSession.cs b/src/VelaShell.Rdp/RdpManagedSession.cs index 149183e..93c9da3 100644 --- a/src/VelaShell.Rdp/RdpManagedSession.cs +++ b/src/VelaShell.Rdp/RdpManagedSession.cs @@ -704,18 +704,18 @@ private async Task DrainDrdynvcAsync() /// Asks the server, via the display-control channel, to resize the desktop to match the view. public Task RequestResizeAsync(int width, int height, CancellationToken cancellationToken) => - _drdynvc?.RequestResizeAsync(width, height) ?? Task.CompletedTask; + _drdynvc?.RequestResizeAsync(width, height, cancellationToken: cancellationToken) ?? Task.CompletedTask; /// /// Like , also passing the display scale in percent /// (150 for a 150% local display) so the remote UI renders at the local text size. /// public Task RequestResizeAsync(int width, int height, int scalePercent, CancellationToken cancellationToken = default) => - _drdynvc?.RequestResizeAsync(width, height, scalePercent) ?? Task.CompletedTask; + _drdynvc?.RequestResizeAsync(width, height, scalePercent, cancellationToken) ?? Task.CompletedTask; /// Requests a multi-monitor virtual desktop layout through MS-RDPEDISP. public Task RequestMonitorLayoutAsync(RdpMonitorLayout layout, int scalePercent = 100, CancellationToken cancellationToken = default) => - _drdynvc?.RequestMonitorLayoutAsync(layout, scalePercent) ?? Task.CompletedTask; + _drdynvc?.RequestMonitorLayoutAsync(layout, scalePercent, cancellationToken) ?? Task.CompletedTask; public Task SetDisplayUpdatesAsync(bool visible, CancellationToken cancellationToken = default) => Guard(async () => { diff --git a/src/VelaShell.Rdp/RdpScale.cs b/src/VelaShell.Rdp/RdpScale.cs index 705baf3..abf4cb9 100644 --- a/src/VelaShell.Rdp/RdpScale.cs +++ b/src/VelaShell.Rdp/RdpScale.cs @@ -1,16 +1,19 @@ namespace VelaShell.Rdp; -/// Display-scale values as MS-RDPBCGR (CS_CORE) and MS-RDPEDISP (monitor layout) define them. +/// Display-scale values accepted by Windows RDP display-scale negotiation. internal static class RdpScale { - /// desktopScaleFactor: a percentage, 100..500. - internal static int Clamp(int percent) => Math.Clamp(percent, 100, 500); - - /// deviceScaleFactor: only 100, 140 or 180 are allowed; pick the nearest bucket. - internal static int Device(int percent) => Clamp(percent) switch + /// + /// Quantizes both desktopScaleFactor and deviceScaleFactor to the only values Windows honors: 100, 140 and 180. + /// Values are clamped first, then rounded to the nearest supported bucket. + /// + internal static int Clamp(int percent) => Math.Clamp(percent, 100, 500) switch { < 120 => 100, < 160 => 140, _ => 180 }; + + /// deviceScaleFactor mirrors the quantized desktop scale. + internal static int Device(int percent) => Clamp(percent); } diff --git a/tests/VelaShell.Plugin.Rdp.Tests/ManagedRdpGfxTests.cs b/tests/VelaShell.Plugin.Rdp.Tests/ManagedRdpGfxTests.cs index 642b84b..77c9741 100644 --- a/tests/VelaShell.Plugin.Rdp.Tests/ManagedRdpGfxTests.cs +++ b/tests/VelaShell.Plugin.Rdp.Tests/ManagedRdpGfxTests.cs @@ -10,7 +10,7 @@ namespace VelaShell.Plugin.Rdp.Tests; public sealed class ManagedRdpGfxTests { [TestMethod] - public void CapabilityNegotiationOffersAvcAndUnknownVersionsDoNotActivateGraphics() + public void CapabilityNegotiationDefaultsAvcOffAndCanOptIn() { using var gfx = new ManagedRdpGfx(2, 1); gfx.Open(); @@ -24,11 +24,24 @@ public void CapabilityNegotiationOffersAvcAndUnknownVersionsDoNotActivateGraphic int size = (int)BinaryPrimitives.ReadUInt32LittleEndian(caps.AsSpan(offset + 4)); Assert.AreEqual(version == 0xa0100 ? 16 : 4, size); uint flags = BinaryPrimitives.ReadUInt32LittleEndian(caps.AsSpan(offset + 8)); - Assert.AreEqual(0u, flags & 0x20); - if (version == 0x80105) { Assert.AreEqual(0x10u, flags & 0x10); } + if (version == 0x80105) { Assert.AreEqual(0u, flags & 0x10); } + else if (version is not (0xa0100 or 0xa0301)) { Assert.AreEqual(0x20u, flags & 0x20); } offset += 8 + size; } Assert.AreEqual(caps.Length, offset); + using var avc = new ManagedRdpGfx(2, 1, true); + avc.Open(); + byte[] avcCaps = avc.ReadResponse()!; + int avcCount = BinaryPrimitives.ReadUInt16LittleEndian(avcCaps.AsSpan(8)); + int avcOffset = 10; + for (int i = 0; i < avcCount; i++) + { + uint version = BinaryPrimitives.ReadUInt32LittleEndian(avcCaps.AsSpan(avcOffset)); + uint flags = BinaryPrimitives.ReadUInt32LittleEndian(avcCaps.AsSpan(avcOffset + 8)); + if (version == 0x80105) { Assert.AreEqual(0x10u, flags & 0x10); } + else if (version != 0xa0100) { Assert.AreEqual(0u, flags & 0x20); } + avcOffset += 8 + (int)BinaryPrimitives.ReadUInt32LittleEndian(avcCaps.AsSpan(avcOffset + 4)); + } gfx.Feed(Packet(Confirm())); Assert.IsFalse(gfx.TryGetFrame(out _)); Assert.IsNull(gfx.ReadResponse(), "Without persistent bitmaps there must be no cache-import request."); diff --git a/tests/VelaShell.Plugin.Rdp.Tests/RdpClipboardTests.cs b/tests/VelaShell.Plugin.Rdp.Tests/RdpClipboardTests.cs index 242b6fe..ea25038 100644 --- a/tests/VelaShell.Plugin.Rdp.Tests/RdpClipboardTests.cs +++ b/tests/VelaShell.Plugin.Rdp.Tests/RdpClipboardTests.cs @@ -27,6 +27,18 @@ public void UnicodeRoundTripAndMalformedPayloads() _ = Assert.Throws(static () => RdpClipboardCodec.EncodeText("a\0b")); } + [TestMethod] + public void RichTextRoundTripsAndRejectsUnsafePayloads() + { + const string html = "

中文🙂

"; + byte[] encoded = RdpClipboardCodec.EncodeRichText(html); + Assert.AreEqual(html, RdpClipboardCodec.DecodeRichText(encoded)); + _ = Assert.Throws(() => RdpClipboardCodec.EncodeRichText("

bad\0text

")); + _ = Assert.Throws(() => RdpClipboardCodec.DecodeRichText([0xC3, 0x28])); + Assert.AreSequenceEqual(new byte[] { 0xFF, 0x00, 0x01 }, RdpClipboardCodec.EncodeRichTextBytes([0xFF, 0x00, 0x01])); + _ = Assert.Throws(() => RdpClipboardCodec.DecodeRichText(new byte[RdpClipboardCodec.MaxPayload + 1])); + } + [TestMethod] public void FileDescriptorsRoundTripDirectoriesAnd64BitLengths() { diff --git a/tests/VelaShell.Plugin.Rdp.Tests/RdpHardeningTests.cs b/tests/VelaShell.Plugin.Rdp.Tests/RdpHardeningTests.cs index 7cdf112..b9b616a 100644 --- a/tests/VelaShell.Plugin.Rdp.Tests/RdpHardeningTests.cs +++ b/tests/VelaShell.Plugin.Rdp.Tests/RdpHardeningTests.cs @@ -337,6 +337,18 @@ public void AShortCompressedStreamPaintsBlackNotStaleMemory() Assert.IsTrue(fb.Bgra.Chunk(4).All(static p => p is [0, 0, 0, 0xFF])); } + [TestMethod] + public void CopyToRefreshesPreviousPresentedRegionWhenUpdateDoesNotCoverIt() + { + var fb = new Framebuffer(16, 16); + byte[] target = new byte[16 * 16 * 4]; + _ = fb.CopyTo(target, 64, full: false); + fb.Blit(2, 3, 4, 4, new byte[4 * 4 * 4]); + Assert.AreEqual(new RdpFrameRegion(2, 3, 4, 4), fb.CopyTo(target, 64, full: false)); + fb.Blit(4, 5, 1, 1, new byte[4]); + Assert.AreEqual(new RdpFrameRegion(2, 3, 4, 4), fb.CopyTo(target, 64, full: false)); + } + [TestMethod] public void CopyToMovesOnlyWhatChanged() { diff --git a/tests/VelaShell.Plugin.Rdp.Tests/RdpRenderingTests.cs b/tests/VelaShell.Plugin.Rdp.Tests/RdpRenderingTests.cs index 58b56f1..5ed7705 100644 --- a/tests/VelaShell.Plugin.Rdp.Tests/RdpRenderingTests.cs +++ b/tests/VelaShell.Plugin.Rdp.Tests/RdpRenderingTests.cs @@ -45,8 +45,8 @@ public void TheClientCoreDataCarriesTheDisplayScaleOnlyWhenItIsNotOneHundredPerc byte[] plain = GccData.BuildClientData(1920, 1080, 32, 1, "VelaShell", 0x409, []); byte[] scaled = GccData.BuildClientData(1920, 1080, 32, 1, "VelaShell", 0x409, [], scaleFactor: 150); Assert.AreEqual(18, scaled.Length - plain.Length, "physical w/h, orientation, desktop and device scale"); - // The tail sits at the end of CS_CORE: desktopScaleFactor 150, deviceScaleFactor 140 (the nearest allowed bucket). - int at = IndexOf(scaled, [0x96, 0, 0, 0, 0x8C, 0, 0, 0]); + // The tail sits at the end of CS_CORE: both scale factors are quantized to the 140% bucket. + int at = IndexOf(scaled, [0x8C, 0, 0, 0, 0x8C, 0, 0, 0]); Assert.IsGreaterThan(0, at); } diff --git a/tests/VelaShell.Plugin.Rdp.Tests/RdpResizeTests.cs b/tests/VelaShell.Plugin.Rdp.Tests/RdpResizeTests.cs index 3332026..60fb884 100644 --- a/tests/VelaShell.Plugin.Rdp.Tests/RdpResizeTests.cs +++ b/tests/VelaShell.Plugin.Rdp.Tests/RdpResizeTests.cs @@ -39,7 +39,7 @@ public async Task DisplayControlNegotiationResizesViaMonitorLayout() await dvc.ProcessAsync([0x50, 0x00, 0x03, 0x00]); // capabilities request, version 3 await dvc.ProcessAsync(CreateRequest(3, DisplayControl)); // create the display-control channel (id 3) await dvc.ProcessAsync(DisplayCapsData(3, maxMonitors: 1)); // its capabilities (no reply owed yet) - await dvc.RequestResizeAsync(1367, 769, 150); // odd width → 1366; the height stays odd; 150% scale + await dvc.RequestResizeAsync(1367, 769, 150); // odd width → 1366; 150% is quantized to the supported 140% bucket Assert.HasCount(3, sent); // caps response, create response, monitor layout @@ -68,10 +68,23 @@ public async Task DisplayControlNegotiationResizesViaMonitorLayout() Assert.AreEqual(0u, layout.U32LE()); // PhysicalWidth (unknown) Assert.AreEqual(0u, layout.U32LE()); // PhysicalHeight Assert.AreEqual(0u, layout.U32LE()); // Orientation - Assert.AreEqual(150u, layout.U32LE()); // DesktopScaleFactor + Assert.AreEqual(140u, layout.U32LE()); // DesktopScaleFactor: Windows-supported bucket Assert.AreEqual(140u, layout.U32LE()); // DeviceScaleFactor: nearest of 100/140/180 } + [TestMethod] + public async Task CancelledResizeDoesNotSendARequest() + { + var sent = new List(); + var dvc = new DrdynvcChannel((pdu, _) => { sent.Add(pdu); return Task.CompletedTask; }, CancellationToken.None); + await dvc.ProcessAsync(CreateRequest(3, DisplayControl)); + await dvc.ProcessAsync(DisplayCapsData(3, maxMonitors: 1)); + using var cancelled = new CancellationTokenSource(); + cancelled.Cancel(); + await Assert.ThrowsAsync(() => dvc.RequestResizeAsync(1280, 720, 140, cancelled.Token)); + Assert.HasCount(1, sent); // only the CREATE response + } + [TestMethod] public async Task PendingResizeFlushesWhenCapabilitiesArrive() { @@ -122,7 +135,7 @@ public async Task MultiMonitorLayoutUsesOneDefinitionPerMonitor() Assert.AreEqual(600u, reader.U32LE()); Assert.AreEqual(340u, reader.U32LE()); Assert.AreEqual(0u, reader.U32LE()); - Assert.AreEqual(125u, reader.U32LE()); + Assert.AreEqual(140u, reader.U32LE()); Assert.AreEqual(140u, reader.U32LE()); Assert.AreEqual(0u, reader.U32LE()); @@ -133,7 +146,7 @@ public async Task MultiMonitorLayoutUsesOneDefinitionPerMonitor() Assert.AreEqual(700u, reader.U32LE()); Assert.AreEqual(390u, reader.U32LE()); Assert.AreEqual(90u, reader.U32LE()); - Assert.AreEqual(125u, reader.U32LE()); + Assert.AreEqual(140u, reader.U32LE()); Assert.AreEqual(140u, reader.U32LE()); } @@ -170,7 +183,7 @@ public async Task InitialMonitorLayoutWaitsForCapabilities() Assert.AreEqual(1600u, reader.U32LE()); Assert.AreEqual(900u, reader.U32LE()); reader.Skip(12); - Assert.AreEqual(150u, reader.U32LE()); + Assert.AreEqual(140u, reader.U32LE()); } [TestMethod]