Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions plugins/VelaShell.Plugin.Rdp/Loc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
4 changes: 2 additions & 2 deletions plugins/VelaShell.Plugin.Rdp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
36 changes: 35 additions & 1 deletion plugins/VelaShell.Plugin.Rdp/RdpClipboardBridge.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ private sealed record LocalVersion(RdpClipboardFiles Files, CancellationTokenSou
private readonly ConcurrentDictionary<uint, LocalVersion> _localVersions = new();
private string? _lastRemoteFingerprint;
private string? _lastPublishedFingerprint;
private static readonly DataFormat<byte[]> HtmlFormat = DataFormat.CreateBytesPlatformFormat(
OperatingSystem.IsWindows() ? "HTML Format" : OperatingSystem.IsMacOS() ? "public.html" : "text/html");
private static readonly DataFormat<byte[]> RtfFormat = DataFormat.CreateBytesPlatformFormat(
OperatingSystem.IsWindows() ? "Rich Text Format" : "text/rtf");

internal RdpClipboardBridge(IRdpClipboardTransport transport, IPluginContext context, Control owner, bool enabled,
Func<IRdpVirtualFileClipboard?>? virtualClipboardFactory = null, TimeSpan? fileResponseTimeout = null, TimeSpan? fileRetryDelay = null,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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));
Expand All @@ -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;
}
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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",
_ => ""
};
Expand Down Expand Up @@ -1098,6 +1124,14 @@ private static async Task<string> 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)
Expand Down
26 changes: 26 additions & 0 deletions plugins/VelaShell.Plugin.Rdp/RdpClipboardCodec.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
1 change: 1 addition & 0 deletions plugins/VelaShell.Plugin.Rdp/RdpConnector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ internal static async Task<IRdpSession> ConnectAsync(WorkspaceConnectRequest req
DriveRedirectionLog = driveLog,
GraphicsLog = driveLog,
EnableGraphicsPipeline = settings.EnableGraphicsPipeline,
EnableAvc = settings.EnableAvc,
Security = settings.Security,
Performance = settings.Performance,
AudioPlayback = settings.Audio
Expand Down
21 changes: 20 additions & 1 deletion plugins/VelaShell.Plugin.Rdp/RdpDesktopControl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Task>? PublishClipboard { get; set; }
internal Action? OperationFailed { get; set; }
Expand Down Expand Up @@ -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(); };
Expand Down Expand Up @@ -428,6 +431,7 @@ private async Task PublishOnFocusAsync(Func<Task> publish)
protected override void OnGotFocus(FocusChangedEventArgs e)
{
base.OnGotFocus(e);
SetImeAttached(false);
SetRemoteAppFocus(true);
UpdateKeyboardHook();
if (PublishClipboard is { } publish)
Expand All @@ -437,6 +441,7 @@ protected override void OnGotFocus(FocusChangedEventArgs e)
}
protected override void OnLostFocus(FocusChangedEventArgs e)
{
SetImeAttached(true);
ReleaseInput();
SetRemoteAppFocus(false);
UpdateKeyboardHook();
Expand Down Expand Up @@ -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)
Expand All @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
13 changes: 13 additions & 0 deletions plugins/VelaShell.Plugin.Rdp/RdpSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -461,6 +465,15 @@ internal static IReadOnlyList<ProtocolSettingField> 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"],
Expand Down
Loading
Loading