// 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.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Avalonia.Controls; using Avalonia.Headless.NUnit; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Layout; using Avalonia.VisualTree; using AwesomeAssertions; using ICSharpCode.ILSpy.AppEnv; using ICSharpCode.ILSpy.Metadata; using ICSharpCode.ILSpy.TextView; using ICSharpCode.ILSpy.ViewModels; using ICSharpCode.ILSpy.Views; using NUnit.Framework; namespace ICSharpCode.ILSpy.Tests.Metadata; [TestFixture] public class MetadataRowDetailsTests { [AvaloniaTest] public void Shell_Rebuilds_Its_Content_Whenever_The_DataContext_Changes() { // The DataGrid builds a row-details template once per details element and then reuses // the built control across row recycling, swapping only the DataContext. Per-item // content (text blob vs. sub-grid) therefore has to be produced by a control that // re-runs its factory on every DataContext change — that is the shell's contract. var factoryInputs = new List(); var shell = new MetadataRowDetailsControl(item => { factoryInputs.Add(item); return item switch { string s => new TextBox { Text = s }, IList bits => new DataGrid { ItemsSource = bits }, _ => null, }; }); shell.DataContext = "blob text"; shell.Content.Should().BeOfType() .Which.Text.Should().Be("blob text"); var bits = new List { new(true, "<0001> bit") }; shell.DataContext = bits; shell.Content.Should().BeOfType() .Which.ItemsSource.Should().BeSameAs(bits); shell.DataContext = null; shell.Content.Should().BeNull("a recycled details element gets its DataContext nulled and must drop stale content"); factoryInputs.Should().Equal("blob text", bits, null); } [AvaloniaTest] public void CreateTemplate_Builds_A_DataContext_Tracking_Shell() { var template = MetadataRowDetails.CreateTemplate( item => item is string s ? new TextBox { Text = s } : null); var control = template.Build("ignored-build-parameter"); var shell = control.Should().BeOfType().Subject; shell.DataContext = "hello"; shell.Content.Should().BeOfType().Which.Text.Should().Be("hello"); } [AvaloniaTest] public async Task Coff_Characteristics_Row_Renders_Its_Flag_Bits_In_Expanded_Row_Details() { // The COFF header view keeps the Characteristics flags word permanently expanded: // the row's details area lists all 16 bits with their meanings, while every other // row of the header stays detail-less. var (window, vm) = await TestHarness.BootAsync(); var coffNode = vm.AssemblyTreeModel.FindCoreLib() .GetChild() .GetChild(); vm.AssemblyTreeModel.SelectNode(coffNode); var tab = await vm.DockWorkspace.WaitForMetadataTabAsync(); TestCapture.Step("coff-header-grid"); tab.RowDetailsTemplate.Should().NotBeNull("the COFF header page carries a flags details template"); tab.IsRowDetailsVisible.Should().NotBeNull(); var metadataPage = await window.WaitForComponent(); var grid = metadataPage.FindControl("Grid")!; await grid.WaitForComponent(); await Waiters.WaitForAsync(() => grid.GetVisualDescendants().OfType() .Any(r => r.DataContext is Entry { Member: "Characteristics" } && r.AreDetailsVisible)); TestCapture.Step("characteristics-row-expanded"); var rows = grid.GetVisualDescendants().OfType().ToList(); var characteristicsRow = rows.Single(r => r.DataContext is Entry { Member: "Characteristics" }); characteristicsRow.AreDetailsVisible.Should().BeTrue(); rows.Where(r => r != characteristicsRow).Should() .OnlyContain(r => !r.AreDetailsVisible, "only the flags row carries details"); var shell = await characteristicsRow.WaitForComponent(); var flagsGrid = shell.Content.Should().BeOfType().Subject; ((IEnumerable)flagsGrid.ItemsSource!).Cast().Should().HaveCount(16); flagsGrid.HeadersVisibility.Should().Be(DataGridHeadersVisibility.None); } [AvaloniaTest] public async Task Optional_Header_Expands_Details_For_The_Dll_Characteristics_Row_Only() { var (_, vm) = await TestHarness.BootAsync(); var optionalNode = vm.AssemblyTreeModel.FindCoreLib() .GetChild() .GetChild(); vm.AssemblyTreeModel.SelectNode(optionalNode); var tab = await vm.DockWorkspace.WaitForMetadataTabAsync(); TestCapture.Step("optional-header-grid"); tab.RowDetailsTemplate.Should().NotBeNull(); tab.RowDetailsVisibilityMode.Should().Be(DataGridRowDetailsVisibilityMode.Collapsed, "non-flag rows must never grow a details area, not even on selection"); tab.IsRowDetailsVisible.Should().NotBeNull(); var entries = tab.Items.Cast().ToList(); var dllCharacteristics = entries.Single(e => e.Member == "DLL Characteristics"); tab.IsRowDetailsVisible!(dllCharacteristics).Should().BeTrue(); entries.Where(e => e != dllCharacteristics).Should() .OnlyContain(e => !tab.IsRowDetailsVisible!(e)); } [AvaloniaTest] public void Details_Content_Stretches_Across_The_Full_Row_Width() { // The details area spans the host row, and its content fills it: a capped or // left-pinned control would leave dead space to the right of the blob text or // sub-grid columns. var text = MetadataRowDetails.BuildTextBlob("blob text"); text.HorizontalAlignment.Should().Be(HorizontalAlignment.Stretch); text.MaxWidth.Should().Be(double.PositiveInfinity, "the text blob must not cap its width"); var flagsGrid = (DataGrid)MetadataRowDetails.BuildFlagsGrid(new List { new(true, "<0001> bit") }); flagsGrid.HorizontalAlignment.Should().Be(HorizontalAlignment.Stretch); flagsGrid.Columns[^1].Width.UnitType.Should().Be(DataGridLengthUnitType.Star, "the meaning column takes the leftover width"); var detailsGrid = (DataGrid)MetadataRowDetails.BuildDetailsGrid( new List { new(true, "<0001> bit") }, ("Value", nameof(BitEntry.Value)), ("Meaning", nameof(BitEntry.Meaning))); detailsGrid.HorizontalAlignment.Should().Be(HorizontalAlignment.Stretch); detailsGrid.Columns[^1].Width.UnitType.Should().Be(DataGridLengthUnitType.Star, "the last column takes the leftover width"); } [AvaloniaTest] public void Text_Blob_Is_A_Read_Only_Editor_With_Extension_Driven_Highlighting() { // Text payloads are code (embedded source, source-link JSON): they render in the // theme-aware AvaloniaEdit editor, which adds syntax colours and virtualizes long // documents, while staying read-only but selectable. The optional extension picks // the highlighting; without one (hex dumps) the text stays plain. var editor = MetadataRowDetails.BuildTextBlob("class C { }", ".cs") .Should().BeOfType().Subject; editor.Text.Should().Be("class C { }"); editor.IsReadOnly.Should().BeTrue(); editor.WordWrap.Should().BeTrue(); editor.MaxHeight.Should().Be(400, "the host row must stay bounded; the editor scrolls internally"); editor.MinHeight.Should().Be(100, "a short payload must still get a recognisable details area, not a squeezed strip"); editor.SyntaxHighlighting.Should().NotBeNull(); editor.SyntaxHighlighting!.Name.Should().Be("C#"); var json = (DecompilerTextEditor)MetadataRowDetails.BuildTextBlob("{ }", ".json"); json.SyntaxHighlighting.Should().NotBeNull("AvaloniaEdit ships a built-in JSON definition"); var plain = (DecompilerTextEditor)MetadataRowDetails.BuildTextBlob("01-02-03"); plain.SyntaxHighlighting.Should().BeNull(); var unknown = (DecompilerTextEditor)MetadataRowDetails.BuildTextBlob("text", ".xyz"); unknown.SyntaxHighlighting.Should().BeNull("an unrecognized extension degrades to plain text"); } [AvaloniaTest] public void Text_Blob_Editor_Uses_The_Decompiler_View_Styling() { // The details editor is a second surface showing code, so it must look like the main // decompiler view: the user-selected editor font (applied live, the same way the text // view reacts to the Options page), the flat square-cornered selection highlight, and // the themed editor background. var settings = AppComposition.Current.GetExport().DisplaySettings; var originalFont = settings.SelectedFont; var originalSize = settings.SelectedFontSize; var editor = (DecompilerTextEditor)MetadataRowDetails.BuildTextBlob("class C { }", ".cs"); var window = new Window { Content = editor }; try { settings.SelectedFont = "Liberation Mono"; settings.SelectedFontSize = 17; window.Show(); editor.FontFamily.Name.Should().Be("Liberation Mono", "the details editor renders in the user-selected editor font"); editor.FontSize.Should().Be(17); settings.SelectedFontSize = 21; editor.FontSize.Should().Be(21, "font settings apply live while the details row is open"); editor.TextArea.SelectionCornerRadius.Should().Be(0, "selection styling matches the decompiler view (flat, square corners)"); window.TryFindResource("ILSpy.EditorSelectionBrush", window.ActualThemeVariant, out var selectionBrush) .Should().BeTrue(); editor.TextArea.SelectionBrush.Should().Be(selectionBrush); window.TryFindResource("ILSpy.EditorBackground", window.ActualThemeVariant, out var background) .Should().BeTrue(); editor.Background.Should().Be(background); window.Close(); settings.SelectedFontSize = 13; editor.FontSize.Should().Be(21, "an editor detached by row recycling must stop tracking the settings instance"); } finally { window.Close(); settings.SelectedFont = originalFont; settings.SelectedFontSize = originalSize; } } [AvaloniaTest] public void Text_Blob_Editor_Carries_Its_Own_Copy_And_Select_All_Context_Menu() { // Without a menu of its own, a right-click inside the details editor inherits the // metadata grid's cell-oriented context menu, whose Copy entries are bound to the // hovered DataGridCell and therefore permanently disabled inside the details area. // The editor must instead offer the decompiler-view editor menu shape: Copy // following the selection, plus Select All. var editor = (DecompilerTextEditor)MetadataRowDetails.BuildTextBlob("class C { }", ".cs"); var window = new Window { Content = editor }; window.Show(); try { var menu = editor.ContextMenu; menu.Should().NotBeNull("the editor must not inherit the metadata grid's cell menu"); // Raise the context-request gesture (what a right-click produces) rather than // calling menu.Open(): only the gesture path raises ContextMenu.Opening, where // the enablement of Copy is decided. editor.RaiseEvent(new ContextRequestedEventArgs()); menu!.IsOpen.Should().BeTrue(); var items = menu.Items.OfType().ToList(); items.Should().HaveCount(2); var copy = items[0]; var selectAll = items[1]; copy.Header.Should().Be("Copy"); selectAll.Header.Should().Be("Select All"); copy.IsEnabled.Should().BeFalse("nothing is selected yet"); menu.Close(); editor.Select(0, 5); editor.RaiseEvent(new ContextRequestedEventArgs()); copy.IsEnabled.Should().BeTrue("a non-empty selection makes Copy actionable"); menu.Close(); selectAll.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent)); editor.SelectionLength.Should().Be(editor.Text.Length); } finally { window.Close(); } } [AvaloniaTest] public async Task Double_Tap_Inside_The_Details_Area_Does_Not_Resolve_To_An_Activatable_Row() { // Row activation navigates away from the metadata view. A double-click inside the // details area (e.g. word-selection in an embedded-source editor, or a click in the // flags sub-grid) is interacting with the details content, not requesting navigation, // so the row-resolution walk must reject sources under the details presenter. var (window, vm) = await TestHarness.BootAsync(); var coffNode = vm.AssemblyTreeModel.FindCoreLib() .GetChild() .GetChild(); vm.AssemblyTreeModel.SelectNode(coffNode); await vm.DockWorkspace.WaitForMetadataTabAsync(); var metadataPage = await window.WaitForComponent(); var grid = metadataPage.FindControl("Grid")!; await grid.WaitForComponent(); await Waiters.WaitForAsync(() => grid.GetVisualDescendants().OfType() .Any(r => r.DataContext is Entry { Member: "Characteristics" } && r.AreDetailsVisible)); var characteristicsRow = grid.GetVisualDescendants().OfType() .Single(r => r.DataContext is Entry { Member: "Characteristics" }); var shell = await characteristicsRow.WaitForComponent(); MetadataTablePage.FindActivatableRow(shell).Should().BeNull( "visuals under the details presenter must not trigger row activation"); var cell = characteristicsRow.GetVisualDescendants().OfType().First(); MetadataTablePage.FindActivatableRow(cell).Should().BeSameAs(characteristicsRow, "regular cells keep resolving to their owning row"); } }