From 89e69b042fb407909f6ccd76f560aa132a476e38 Mon Sep 17 00:00:00 2001 From: Siegfried Pammer Date: Mon, 11 May 2026 21:46:18 +0200 Subject: [PATCH] Drag-reorder top-level assemblies via ProDataGrid row-drag Wires ProDataGrid's native row-drag API on the assembly tree: CanUserReorderRows=True, RowDragHandle=Row, RowDragStarting cancels drags whose source isn't a top-level AssemblyTreeNode (or is a package-nested entry). AssemblyRowDropHandler validates that the target is a sibling (not Inside, not deeper than top-level) and routes the reorder through AssemblyList.Move so the same persistence path the rest of the app uses (Unload / OpenAssembly) captures the new ordering. Assisted-by: Claude:claude-opus-4-7:Claude Code --- .../AssemblyTreeDragReorderTests.cs | 200 ++++++++++++++++++ ILSpy/AssemblyTree/AssemblyListPane.axaml | 2 +- ILSpy/AssemblyTree/AssemblyListPane.axaml.cs | 30 +++ ILSpy/AssemblyTree/AssemblyRowDropHandler.cs | 127 +++++++++++ 4 files changed, 358 insertions(+), 1 deletion(-) create mode 100644 ILSpy.Tests/AssemblyList/AssemblyTreeDragReorderTests.cs create mode 100644 ILSpy/AssemblyTree/AssemblyRowDropHandler.cs diff --git a/ILSpy.Tests/AssemblyList/AssemblyTreeDragReorderTests.cs b/ILSpy.Tests/AssemblyList/AssemblyTreeDragReorderTests.cs new file mode 100644 index 000000000..ab4dc5e01 --- /dev/null +++ b/ILSpy.Tests/AssemblyList/AssemblyTreeDragReorderTests.cs @@ -0,0 +1,200 @@ +// Copyright (c) 2026 AlphaSierraPapa for the SharpDevelop Team +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of this +// software and associated documentation files (the "Software"), to deal in the Software +// without restriction, including without limitation the rights to use, copy, modify, merge, +// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons +// to whom the Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all copies or +// substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. + +using System.Linq; +using System.Threading.Tasks; + +using Avalonia.Controls; +using Avalonia.Controls.DataGridDragDrop; +using Avalonia.Headless.NUnit; +using Avalonia.Input; +using Avalonia.VisualTree; + +using AwesomeAssertions; + +using ICSharpCode.ILSpyX; + +using ILSpy.AppEnv; +using ILSpy.AssemblyTree; +using ILSpy.TreeNodes; +using ILSpy.ViewModels; +using ILSpy.Views; + +using NUnit.Framework; + +namespace ICSharpCode.ILSpy.Tests; + +[TestFixture] +public class AssemblyTreeDragReorderTests +{ + [AvaloniaTest] + public async Task AssemblyListPane_Enables_Row_Reorder_On_The_DataGrid() + { + // Mirrors WPF's SharpTreeView AllowDropOrder=True — the assembly tree must opt in to + // ProDataGrid's row-drag-drop machinery (otherwise the handler we wire below is never + // asked to validate anything). + var window = AppComposition.Current.GetExport(); + window.Show(); + var vm = (MainWindowViewModel)window.DataContext!; + await vm.AssemblyTreeModel.WaitForAssembliesAsync(minimumCount: 1); + var pane = await window.WaitForComponent(); + var grid = await pane.WaitForComponent(); + + grid.CanUserReorderRows.Should().BeTrue(); + grid.RowDragHandle.Should().Be(DataGridRowDragHandle.Row, + "the assembly tree has no row-headers so the drag gesture must originate from the row body"); + // Regression — ProDataGrid's row-drag controller short-circuits when IsReadOnly is true + // (DataGridRowDragDropController.ShouldHandlePointer + DataGridHierarchicalRowReorderHandler + // both bail on grid.IsReadOnly). Read-only intent moved onto the column instead so cells + // stay uneditable without disabling drag. + grid.IsReadOnly.Should().BeFalse(); + grid.Columns[0].IsReadOnly.Should().BeTrue(); + } + + [AvaloniaTest] + public async Task AssemblyListPane_Wires_AssemblyRowDropHandler_With_The_Live_AssemblyList() + { + // The pane owns the handler instance — it builds one from the model's AssemblyList so + // dropping into the grid mutates the same list that file-open and Unload mutate. + var window = AppComposition.Current.GetExport(); + window.Show(); + var vm = (MainWindowViewModel)window.DataContext!; + await vm.AssemblyTreeModel.WaitForAssembliesAsync(minimumCount: 1); + var pane = await window.WaitForComponent(); + var grid = await pane.WaitForComponent(); + + grid.RowDropHandler.Should().BeOfType(); + } + + [AvaloniaTest] + public async Task Dropping_An_Assembly_After_Another_Reorders_The_AssemblyList() + { + // End-to-end on the live drop handler: simulate "drag row[1] After row[0]" and verify + // the underlying AssemblyList reordered. The handler is responsible for turning + // HierarchicalNode wrappers (or bare AssemblyTreeNodes) into LoadedAssembly refs and + // calling AssemblyList.Move with the correct insert index. + var window = AppComposition.Current.GetExport(); + window.Show(); + var vm = (MainWindowViewModel)window.DataContext!; + await vm.AssemblyTreeModel.WaitForAssembliesAsync(minimumCount: 2); + var pane = await window.WaitForComponent(); + var grid = await pane.WaitForComponent(); + var list = vm.AssemblyTreeModel.AssemblyList!; + + var before = list.GetAssemblies(); + var first = vm.AssemblyTreeModel.Root!.Children.OfType() + .First(n => n.LoadedAssembly == before[0]); + var second = vm.AssemblyTreeModel.Root!.Children.OfType() + .First(n => n.LoadedAssembly == before[1]); + + var handler = (AssemblyRowDropHandler)grid.RowDropHandler; + // "Drop first AFTER second" → ordering should become [second, first, ...rest]. + var args = MakeArgs(items: new object[] { first }, target: second, + position: DataGridRowDropPosition.After); + handler.Validate(args).Should().BeTrue(); + handler.Execute(args).Should().BeTrue(); + + var after = list.GetAssemblies(); + after[0].Should().BeSameAs(before[1]); + after[1].Should().BeSameAs(before[0]); + + // Restore so subsequent tests run against the original order. + list.Move(new[] { after[1] }, 0); + } + + [AvaloniaTest] + public async Task Validate_Rejects_Inside_Position() + { + // "Inside" would mean dropping one assembly as a child of another — there's no such + // relationship in the model, so the handler must refuse it (the grid then renders the + // "not allowed" cursor). + var window = AppComposition.Current.GetExport(); + window.Show(); + var vm = (MainWindowViewModel)window.DataContext!; + await vm.AssemblyTreeModel.WaitForAssembliesAsync(minimumCount: 2); + var pane = await window.WaitForComponent(); + var grid = await pane.WaitForComponent(); + + var topLevel = vm.AssemblyTreeModel.Root!.Children.OfType().ToArray(); + var handler = (AssemblyRowDropHandler)grid.RowDropHandler; + + var args = MakeArgs(items: new object[] { topLevel[1] }, target: topLevel[0], + position: DataGridRowDropPosition.Inside); + handler.Validate(args).Should().BeFalse(); + } + + [AvaloniaTest] + public async Task Validate_Rejects_Non_TopLevel_Target() + { + // Dropping onto a child of an assembly (a namespace or type) must not reorder anything + // — that target doesn't live in AssemblyList at all. + var window = AppComposition.Current.GetExport(); + window.Show(); + var vm = (MainWindowViewModel)window.DataContext!; + await vm.AssemblyTreeModel.WaitForAssembliesAsync(minimumCount: 1); + var pane = await window.WaitForComponent(); + var grid = await pane.WaitForComponent(); + + var topLevel = vm.AssemblyTreeModel.Root!.Children.OfType().First(); + topLevel.IsExpanded = true; + var childNode = topLevel.Children.First(); + + var handler = (AssemblyRowDropHandler)grid.RowDropHandler; + var args = MakeArgs(items: new object[] { topLevel }, target: childNode, + position: DataGridRowDropPosition.Before); + handler.Validate(args).Should().BeFalse(); + } + + [AvaloniaTest] + public async Task Validate_Rejects_Dragging_Non_Assembly_Nodes() + { + // Sub-nodes (namespaces, types, etc.) must not be picked up by the reorder gesture — + // only top-level AssemblyTreeNodes are eligible source items. + var window = AppComposition.Current.GetExport(); + window.Show(); + var vm = (MainWindowViewModel)window.DataContext!; + await vm.AssemblyTreeModel.WaitForAssembliesAsync(minimumCount: 2); + var pane = await window.WaitForComponent(); + var grid = await pane.WaitForComponent(); + + var topLevel = vm.AssemblyTreeModel.Root!.Children.OfType().ToArray(); + topLevel[0].IsExpanded = true; + var childOfFirst = topLevel[0].Children.First(); + + var handler = (AssemblyRowDropHandler)grid.RowDropHandler; + var args = MakeArgs(items: new object[] { childOfFirst }, target: topLevel[1], + position: DataGridRowDropPosition.Before); + handler.Validate(args).Should().BeFalse(); + } + + static DataGridRowDropEventArgs MakeArgs( + object[] items, object target, DataGridRowDropPosition position) + => new( + grid: null!, + targetList: null, + items: items, + sourceIndices: System.Array.Empty(), + targetItem: target, + targetIndex: 0, + insertIndex: 0, + targetRow: null, + position: position, + isSameGrid: true, + requestedEffect: DragDropEffects.Move, + dragEventArgs: null!); +} diff --git a/ILSpy/AssemblyTree/AssemblyListPane.axaml b/ILSpy/AssemblyTree/AssemblyListPane.axaml index 2b914a4e3..c43e467da 100644 --- a/ILSpy/AssemblyTree/AssemblyListPane.axaml +++ b/ILSpy/AssemblyTree/AssemblyListPane.axaml @@ -24,12 +24,12 @@ HeadersVisibility="None" HierarchicalRowsEnabled="True" GridLinesVisibility="None" - IsReadOnly="True" CanUserResizeColumns="False" SelectionMode="Extended" SelectionChanged="OnTreeGridSelectionChanged"> diff --git a/ILSpy/AssemblyTree/AssemblyListPane.axaml.cs b/ILSpy/AssemblyTree/AssemblyListPane.axaml.cs index e0e9fb0ed..f769d303e 100644 --- a/ILSpy/AssemblyTree/AssemblyListPane.axaml.cs +++ b/ILSpy/AssemblyTree/AssemblyListPane.axaml.cs @@ -24,6 +24,7 @@ using System.Linq; using Avalonia; using Avalonia.Controls; +using Avalonia.Controls.DataGridDragDrop; using Avalonia.Controls.DataGridHierarchical; using Avalonia.Input; using Avalonia.Threading; @@ -73,6 +74,14 @@ namespace ILSpy.AssemblyTree global::Avalonia.Interactivity.RoutingStrategies.Bubble, handledEventsToo: true); + // Drag-reorder of top-level assembly rows. The actual reorder lives in + // AssemblyRowDropHandler (wired to the live AssemblyList in BindTree); the + // RowDragStarting hook here just cancels drags that originate from non-eligible + // rows so the user never even sees a pickup cursor on a type or namespace. + TreeGrid.CanUserReorderRows = true; + TreeGrid.RowDragHandle = DataGridRowDragHandle.Row; + TreeGrid.RowDragStarting += OnTreeGridRowDragStarting; + // Context-menu host. Tests bypass this and re-attach via AttachContextMenu so they // can inject stub entries — at app-runtime we resolve the registry through the // composition host. Both paths route through the same Opening handler. @@ -457,6 +466,27 @@ namespace ILSpy.AssemblyTree hierarchicalModel.SetRoots(root.Children); TreeGrid.HierarchicalModel = hierarchicalModel; + + // Re-target the drop handler whenever the active AssemblyList changes (the user + // can switch lists from the dropdown), so the next reorder mutates the right list. + if (root is AssemblyListTreeNode listRoot) + TreeGrid.RowDropHandler = new AssemblyRowDropHandler(listRoot.AssemblyList); + } + + void OnTreeGridRowDragStarting(object? sender, DataGridRowDragStartingEventArgs e) + { + // Refuse the gesture for anything other than a top-level AssemblyTreeNode owned by + // the user (not a nuget-nested entry). Cancelling here stops the drag visuals from + // ever showing — the user gets immediate feedback that the row is not movable. + foreach (var item in e.Items) + { + if (!AssemblyRowDropHandler.TryUnwrapTopLevelAssemblyNode(item, out var node) + || node.PackageEntry != null) + { + e.Cancel = true; + return; + } + } } } } diff --git a/ILSpy/AssemblyTree/AssemblyRowDropHandler.cs b/ILSpy/AssemblyTree/AssemblyRowDropHandler.cs new file mode 100644 index 000000000..ad1b192e8 --- /dev/null +++ b/ILSpy/AssemblyTree/AssemblyRowDropHandler.cs @@ -0,0 +1,127 @@ +// Copyright (c) 2026 AlphaSierraPapa for the SharpDevelop Team +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of this +// software and associated documentation files (the "Software"), to deal in the Software +// without restriction, including without limitation the rights to use, copy, modify, merge, +// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons +// to whom the Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all copies or +// substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. + +using System; +using System.Collections.Generic; +using System.Linq; + +using Avalonia.Controls.DataGridDragDrop; +using Avalonia.Controls.DataGridHierarchical; +using Avalonia.Input; + +using ICSharpCode.ILSpyX; + +using ILSpy.TreeNodes; + +namespace ILSpy.AssemblyTree +{ + /// + /// Handles drag-reorder drops on the assembly tree. Only top-level + /// s are eligible — drops onto descendants (namespaces, + /// types, …) or "Inside" another assembly are rejected. The reorder mutation goes + /// through so the same persistence path the rest of + /// the app uses (file-open, Unload) also captures user reordering. + /// + internal sealed class AssemblyRowDropHandler : IDataGridRowDropHandler + { + readonly AssemblyList assemblyList; + + public AssemblyRowDropHandler(AssemblyList assemblyList) + { + ArgumentNullException.ThrowIfNull(assemblyList); + this.assemblyList = assemblyList; + } + + public bool Validate(DataGridRowDropEventArgs args) + { + if (!TryResolve(args, out _, out _)) + { + args.EffectiveEffect = DragDropEffects.None; + return false; + } + args.EffectiveEffect = DragDropEffects.Move; + return true; + } + + public bool Execute(DataGridRowDropEventArgs args) + { + if (!TryResolve(args, out var dragged, out var target)) + return false; + var ordering = assemblyList.GetAssemblies(); + int targetIndex = Array.IndexOf(ordering, target.LoadedAssembly); + if (targetIndex < 0) + return false; + int insertIndex = args.Position == DataGridRowDropPosition.After + ? targetIndex + 1 + : targetIndex; + var loaded = dragged.Select(n => n.LoadedAssembly).ToArray(); + assemblyList.Move(loaded, insertIndex); + return true; + } + + bool TryResolve(DataGridRowDropEventArgs args, + out AssemblyTreeNode[] dragged, + out AssemblyTreeNode target) + { + dragged = Array.Empty(); + target = null!; + + // "Inside" would mean making one assembly a child of another — not a relationship + // that exists in the model. + if (args.Position == DataGridRowDropPosition.Inside) + return false; + + if (!TryUnwrapTopLevelAssemblyNode(args.TargetItem, out target)) + return false; + + var sources = new List(args.Items.Count); + foreach (var item in args.Items) + { + if (!TryUnwrapTopLevelAssemblyNode(item, out var node) + || node.PackageEntry != null) + return false; + if (ReferenceEquals(node, target)) + return false; + sources.Add(node); + } + if (sources.Count == 0) + return false; + + dragged = sources.ToArray(); + return true; + } + + internal static bool TryUnwrapTopLevelAssemblyNode(object? item, out AssemblyTreeNode node) + { + node = null!; + AssemblyTreeNode? candidate = item switch { + HierarchicalNode hn => hn.Item as AssemblyTreeNode, + AssemblyTreeNode atn => atn, + _ => null, + }; + if (candidate == null) + return false; + // Top-level = direct child of the AssemblyListTreeNode root. Reordering deeper + // nodes (namespaces, types) makes no sense. + if (candidate.Parent is not AssemblyListTreeNode) + return false; + node = candidate; + return true; + } + } +}