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
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