Skip to content
Open
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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ RDP sessions stay alive across idle periods and network drops: the bridge enable

RDP certificate verification: the bridge no longer ignores the server certificate. `cxrdp_set_certificate_callback` (API 16, `CX_RDP_CAPABILITY_CERTIFICATE_VERIFICATION`) registers `RdpBridgeClient.OnCertificateVerification`, which runs on the native connect thread and blocks while `Services/RdpCertificateTrustService` asks the user, because the answer must exist before the handshake continues; the bridge calls it outside `callback_mutex` on purpose, so never take that lock around a prompt. The native side switches `FreeRDP_IgnoreCertificate`/`AutoAcceptCertificate` to FALSE only when a callback is registered (an older host keeps the accept-all behaviour), normalises the digest to lower-case hex, and caches one decision per fingerprint so a TLS + NLA/CredSSP exchange prompts once. The trust store (`rdp_certificates` collection in `SqliteAppDataStore`) is keyed on the real target `_profileCacheHost/_profileCachePort`, never the loopback endpoint a tunnel or proxy relay substitutes. First-use prompting and changed-certificate blocking mirror SSH (`ConfirmRdpCertificateOnFirstConnection`, `BlockChangedRdpCertificates`, both default true); a changed certificate is rejected without a prompt and the operator removes the entry in Settings → Trusted hosts, and `RdpCertificatePromptService.CancelPending()` closes a pending prompt when the tab is disconnected.

RDP DPI policy (`SessionInfo.RdpDpiPolicy`, edited in `Views/SessionEditDialog.axaml`): `FollowLocal` (default) maps the local render scaling to a quantized RDP scale (100/125/150/175/200) via `Services/RdpDpiScale.cs`; `Fixed100` forces 100%; `KeepRemote` advertises no scale. At connect time `RdpBridgeClient` calls `cxrdp_set_display_scale`, and the bridge adds the `disp` dynamic channel (registered as `DISP_CHANNEL_NAME` "disp" — the long `DISP_DVC_CHANNEL_NAME` fails to resolve the static addin in freerdp-client3.dll) and sets `FreeRDP_DesktopScaleFactor`/`DeviceScaleFactor`. On resize or a monitored DPI change, `RdpViewModel` calls `cxrdp_update_display`; the bridge queues it on the worker thread, which sends `DispClientContext.SendMonitorLayout` with physical dimensions and then resizes GDI directly (the host's deactivate/reactivate does not emit a Desktop Resize Update). Fall back to the full-reconnect resize path when the bridge lacks API 6 / `CX_RDP_CAPABILITY_RUNTIME_RESIZE`. The C API version is 15 and the smoke tool asserts the runtime-resize capability bit.
RDP DPI policy (`SessionInfo.RdpDpiPolicy`, edited in `Views/SessionEditDialog.axaml`): `FollowLocal` (default) maps the local render scaling to a quantized RDP scale (100/125/150/175/200) via `Services/RdpDpiScale.cs`; `Fixed100` forces 100%; `KeepRemote` advertises no scale. At connect time `RdpBridgeClient` calls `cxrdp_set_display_scale`, and the bridge adds the `disp` dynamic channel (registered as `DISP_CHANNEL_NAME` "disp" — the long `DISP_DVC_CHANNEL_NAME` fails to resolve the static addin in freerdp-client3.dll) and sets `FreeRDP_DesktopScaleFactor`/`DeviceScaleFactor`. On resize or a monitored DPI change, `RdpViewModel` calls `cxrdp_update_display`; the bridge queues it on the worker thread, which sends `DispClientContext.SendMonitorLayout` with physical dimensions and then resizes GDI directly (the host's deactivate/reactivate does not emit a Desktop Resize Update). **GDI buffer ownership (2026-11-29 crash fix, seen 11-27 and 11-29):** `push_frame` must publish `gdi->primary->bitmap->data` (validated through `gdi->primary`), NEVER the cached `gdi->primary_buffer` — FreeRDP 3.32.2's `gdi_init_primary` assigns `primary_buffer` before its final allocations and its `fail_hwnd` path frees the bitmap without clearing the cached pointer, so a failed `gdi_resize` leaves it dangling at the freed data while `gdi->width/height` already hold the new size, and the next frame callback hands freed memory to `CopyDirtyRectFromNative` (the reproducible Access Violation during resolution switches). When `gdi_resize` fails destructively (`gdi->primary == nullptr`), `cx_desktop_resize` rebuilds the GDI in place — `unbind_gfx_pipeline` → `gdi_init` at the settings size → `bind_gfx_pipeline`, because `gfx->custom` still points at the broken struct — and only aborts the session via `freerdp_abort_connect` when the rebuild itself fails; `cx_begin_paint` keeps a null-guarded chain for the same broken state. Fall back to the full-reconnect resize path when the bridge lacks API 6 / `CX_RDP_CAPABILITY_RUNTIME_RESIZE`. The C API version is 15 and the smoke tool asserts the runtime-resize capability bit.

RDP scale wire format (`Services/RdpDpiScale.cs`, `native/CxRdpBridge/cxrdp_bridge.cpp`): `ResolveScalePercent` may return any of 100/125/150/175/200 for `DesktopScaleFactor`, but `DeviceScaleFactor` is only allowed to be 100, 140 or 180 — any other value makes Windows drop BOTH scale factors silently, which looked like "the DPI setting does nothing" on multi-monitor layouts. Both sides therefore funnel it through `RdpDpiScale.DeviceScaleFactorFromDesktopScale` / `resolve_device_scale_factor`; keep the two in sync. Desktop sizes must be even numbers (`& ~1`) because MS-RDPEDISP rejects an odd width, and `PhysicalWidth`/`PhysicalHeight` are derived from the scale by `compute_physical_mm` so the remote sees a plausible monitor. `cx_post_connect` remembers whether the `disp` capabilities already arrived (`disp_caps_received`) and, when they did, queues the initial monitor layout instead of waiting for the first resize; after `freerdp_connect` the worker resets all of it so ARC reconnects re-send a layout. `RdpViewModel` keeps `_runtimeDisplayScalePercent` next to the runtime width/height: a resize is only sent when the size moved by 2 px or the scale actually changed, and `RequestViewportResize` debounces 250 ms (`_resizeDebounceCts`) because MS-RDPEDISP throttles back-to-back `SendMonitorLayout` PDUs during a window drag. `Views/RdpView.axaml.cs` disables the local Windows IME with `ImmAssociateContext(hwnd, IntPtr.Zero)` while the RDP view holds focus and restores the saved context on `LostFocus`, so a local input method cannot swallow remote keystrokes.

Expand Down
78 changes: 66 additions & 12 deletions Controls/DataGridSourceAdapter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Reflection;
using System.Runtime.CompilerServices;
Expand All @@ -14,6 +15,10 @@ namespace CxShell.Controls;
/// </summary>
public sealed class DataGridSourceAdapter<T> : IDisposable
{
private static readonly string[] NestedKeyPropertyNames = ["Session", "Entry", "Recording"];
private static readonly string[] DirectKeyPropertyNames = ["Id", "Key", "FullPath", "Path", "Name"];
private static readonly ConcurrentDictionary<Type, KeyPlan> KeyPlans = new();
private static readonly ConcurrentDictionary<Type, PropertyInfo?> IdProperties = new();
private static readonly IComparer<object?> ObjectComparer = Comparer<object?>.Create(CompareValues);
private readonly IReadOnlyList<T> _items;
private readonly Dictionary<DataGridRowKey, T> _itemsByKey = new();
Expand Down Expand Up @@ -257,28 +262,77 @@ private static bool SupportsScalar(Type type)
_ => null
};

private static string GetStableKeyText(T item)
/// <summary>
/// Property lookups that produce a row key, resolved once per item type. Row keys are
/// rebuilt on every selection query, so scanning the type with reflection per item made
/// selection cost grow with the number of properties instead of the number of rows.
/// </summary>
private sealed class KeyPlan
{
public required string TypeName { get; init; }
public required (string Name, PropertyInfo Property)[] Nested { get; init; }
public required (string Name, PropertyInfo Property)[] Direct { get; init; }
}

private static KeyPlan BuildKeyPlan(Type type)
{
var properties = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (property.GetMethod == null || property.GetIndexParameters().Length != 0)
continue;

properties.TryAdd(property.Name, property);
}

return new KeyPlan
{
TypeName = type.FullName ?? string.Empty,
Nested = Collect(NestedKeyPropertyNames),
Direct = Collect(DirectKeyPropertyNames)
};

(string, PropertyInfo)[] Collect(string[] names)
{
var found = new List<(string, PropertyInfo)>(names.Length);
foreach (var name in names)
{
if (properties.TryGetValue(name, out var property))
found.Add((name, property));
}

return found.ToArray();
}
}

private string GetStableKeyText(T item)
{
if (item == null)
return "null";

var type = item.GetType();
foreach (var nestedPropertyName in new[] { "Session", "Entry", "Recording" })
var plan = KeyPlans.GetOrAdd(item.GetType(), static type => BuildKeyPlan(type));
var hash = RuntimeHelpers.GetHashCode(item);

foreach (var (name, property) in plan.Nested)
{
var nested = type.GetProperty(nestedPropertyName, BindingFlags.Public | BindingFlags.Instance)?.GetValue(item);
var nestedId = nested?.GetType().GetProperty("Id", BindingFlags.Public | BindingFlags.Instance)?.GetValue(nested);
if (nestedId != null)
return $"{type.FullName}:{nestedPropertyName}:{nestedId}:{RuntimeHelpers.GetHashCode(item)}";
var nested = property.GetValue(item);
if (nested == null)
continue;

var idProperty = IdProperties.GetOrAdd(
nested.GetType(),
static nestedType => nestedType.GetProperty("Id", BindingFlags.Public | BindingFlags.Instance));
if (idProperty?.GetValue(nested) is { } nestedId)
return $"{plan.TypeName}:{name}:{nestedId}:{hash}";
}

foreach (var propertyName in new[] { "Id", "Key", "FullPath", "Path", "Name" })
foreach (var (name, property) in plan.Direct)
{
var property = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
var value = property?.GetValue(item);
var value = property.GetValue(item);
if (value != null && !string.IsNullOrWhiteSpace(value.ToString()))
return $"{type.FullName}:{propertyName}:{value}:{RuntimeHelpers.GetHashCode(item)}";
return $"{plan.TypeName}:{name}:{value}:{hash}";
}

return $"{type.FullName}:{RuntimeHelpers.GetHashCode(item)}";
return $"{plan.TypeName}:{hash}";
}
}
73 changes: 73 additions & 0 deletions CxShell.Tests/DataGridSourceAdapterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,79 @@ [new DataGridSelectionInterval(1, 3, scope)],
Assert.Equal(items.Skip(1).Take(2), selected);
}

[Fact]
public void GetSelectedItems_ResolvesKeyFromNestedProperty()
{
var sharedId = Guid.NewGuid();
var items = new[]
{
new NestedKeyItem(new NestedKeyId { Id = sharedId }),
new NestedKeyItem(new NestedKeyId { Id = sharedId })
};
using var adapter = new DataGridSourceAdapter<NestedKeyItem>(items, snapshot: true);

var selected = SelectExplicitly(adapter, items[0]);

Assert.Equal(new[] { items[0] }, selected);
}

[Fact]
public void GetSelectedItems_ResolvesKeyFromDirectProperty()
{
var items = new[]
{
new DirectKeyItem { Name = "first" },
new DirectKeyItem { Name = "first" }
};
using var adapter = new DataGridSourceAdapter<DirectKeyItem>(items, snapshot: true);

var selected = SelectExplicitly(adapter, items[1]);

Assert.Equal(new[] { items[1] }, selected);
}

[Fact]
public void GetSelectedItems_FallsBackToInstanceIdentityWithoutKeyProperties()
{
var items = new[] { new BareItem(), new BareItem() };
using var adapter = new DataGridSourceAdapter<BareItem>(items, snapshot: true);

var selected = SelectExplicitly(adapter, items[0]);

Assert.Equal(new[] { items[0] }, selected);
}

private static IReadOnlyList<T> SelectExplicitly<T>(DataGridSourceAdapter<T> adapter, T item)
{
var grid = new DataGrid { SelectionMode = DataGridSelectionMode.Extended };
grid.Selection = new DataGridSelectionState(
ImmutableArray.Create(adapter.GetKey(item)),
null,
ImmutableArray<DataGridSelectionInterval>.Empty,
ImmutableArray<DataGridRowKey>.Empty);
return adapter.GetSelectedItems(grid);
}

private sealed class NestedKeyItem(NestedKeyId session)
{
public NestedKeyId Session { get; } = session;
public string Name { get; } = "shared-name";
}

private sealed class NestedKeyId
{
public Guid Id { get; init; }
}

private sealed class DirectKeyItem
{
public string Name { get; init; } = string.Empty;
}

private sealed class BareItem
{
}

private static SessionRecordingItemViewModel[] CreateItems(int count)
{
return Enumerable.Range(0, count)
Expand Down
38 changes: 6 additions & 32 deletions Services/SshConnectionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -1242,40 +1241,15 @@ public void ResizeTerminal(TerminalPtySize size)
if (_shellStream == null)
return;

// SSH.NET keeps the session channel private; send the PTY window-change
// request through that channel so remote readline/bash wrap at our width.
var channelField = typeof(ShellStream).GetField(
"_channel",
BindingFlags.Instance | BindingFlags.NonPublic);
var channel = channelField?.GetValue(_shellStream);
if (channel == null || channelField == null)
return;

var method = channelField.FieldType.GetMethod(
"SendWindowChangeRequest",
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
binder: null,
types: new[] { typeof(uint), typeof(uint), typeof(uint), typeof(uint) },
modifiers: null)
?? channel.GetType().GetMethod(
"SendWindowChangeRequest",
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
binder: null,
types: new[] { typeof(uint), typeof(uint), typeof(uint), typeof(uint) },
modifiers: null);
if (method == null)
{
ErrorOccurred?.Invoke("SSH terminal resize failed: SendWindowChangeRequest was not found.");
return;
}

method.Invoke(channel, new object[]
{
// ShellStream.ChangeWindowSize sends the PTY window-change request on the
// session channel, so remote readline/bash wrap at our width. Reaching into
// the private channel field by reflection used to break whenever SSH.NET
// reshaped its internals, and reflection is not available under NativeAOT.
_shellStream.ChangeWindowSize(
(uint)Math.Max(1, size.Columns),
(uint)Math.Max(1, size.Rows),
(uint)Math.Max(0, size.PixelWidth),
(uint)Math.Max(0, size.PixelHeight)
});
(uint)Math.Max(0, size.PixelHeight));
}
catch (Exception ex)
{
Expand Down
Loading
Loading