From a068fc68c3c667c4c1240f7db719fe19514d035e Mon Sep 17 00:00:00 2001 From: Patrik Svensson Date: Tue, 4 Aug 2020 16:05:57 +0200 Subject: [PATCH] Add support for tables --- src/Sample/Program.cs | 16 ++ .../Unit/Composition/BorderTests.cs | 36 +++ .../Unit/Composition/TableTests.cs | 158 +++++++++++ src/Spectre.Console.Tests/Unit/StyleTests.cs | 8 +- src/Spectre.Console/AnsiConsole.cs | 6 +- src/Spectre.Console/Capabilities.cs | 15 +- src/Spectre.Console/Composition/Border.cs | 82 ++++++ src/Spectre.Console/Composition/BorderKind.cs | 18 ++ src/Spectre.Console/Composition/BorderPart.cs | 98 +++++++ .../Composition/Borders/AsciiBorder.cs | 37 +++ .../Composition/Borders/SquareBorder.cs | 37 +++ src/Spectre.Console/Composition/Table.cs | 262 ++++++++++++++++++ src/Spectre.Console/Composition/Text.cs | 17 +- .../Internal/Ansi/AnsiDetector.cs | 19 +- .../Internal/AnsiConsoleRenderer.cs | 4 +- .../Internal/ConsoleBuilder.cs | 43 ++- .../Internal/FallbackConsoleRenderer.cs | 4 +- .../Internal/Text/Markup/MarkupParser.cs | 3 +- .../Internal/Text/StyleParser.cs | 7 +- 19 files changed, 837 insertions(+), 33 deletions(-) create mode 100644 src/Spectre.Console.Tests/Unit/Composition/BorderTests.cs create mode 100644 src/Spectre.Console.Tests/Unit/Composition/TableTests.cs create mode 100644 src/Spectre.Console/Composition/Border.cs create mode 100644 src/Spectre.Console/Composition/BorderKind.cs create mode 100644 src/Spectre.Console/Composition/BorderPart.cs create mode 100644 src/Spectre.Console/Composition/Borders/AsciiBorder.cs create mode 100644 src/Spectre.Console/Composition/Borders/SquareBorder.cs create mode 100644 src/Spectre.Console/Composition/Table.cs diff --git a/src/Sample/Program.cs b/src/Sample/Program.cs index 65ae7a3..b76bb84 100644 --- a/src/Sample/Program.cs +++ b/src/Sample/Program.cs @@ -78,6 +78,22 @@ namespace Sample Text.New("Right adjusted\nRight", foreground: Color.White), fit: true, content: Justify.Right)); + + var table = new Table(); + table.AddColumns("[red underline]Foo[/]", "Bar"); + table.AddRow("[blue][underline]Hell[/]o[/]", "World 🌍"); + table.AddRow("[yellow]Patrik [green]\"Lol[/]\" Svensson[/]", "Was [underline]here[/]!"); + table.AddRow("Lorem ipsum dolor sit amet, consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum", "β—€ Strange language"); + table.AddRow("Hej πŸ‘‹", "[green]VΓ€rlden[/]"); + AnsiConsole.Render(table); + + table = new Table(BorderKind.Ascii); + table.AddColumns("[red underline]Foo[/]", "Bar"); + table.AddRow("[blue][underline]Hell[/]o[/]", "World 🌍"); + table.AddRow("[yellow]Patrik [green]\"Lol[/]\" Svensson[/]", "Was [underline]here[/]!"); + table.AddRow("Lorem ipsum dolor sit amet, consectetur [blue]adipiscing[/] elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum", "β—€ Strange language"); + table.AddRow("Hej πŸ‘‹", "[green]VΓ€rlden[/]"); + AnsiConsole.Render(table); } } } \ No newline at end of file diff --git a/src/Spectre.Console.Tests/Unit/Composition/BorderTests.cs b/src/Spectre.Console.Tests/Unit/Composition/BorderTests.cs new file mode 100644 index 0000000..b25fceb --- /dev/null +++ b/src/Spectre.Console.Tests/Unit/Composition/BorderTests.cs @@ -0,0 +1,36 @@ +using System; +using Shouldly; +using Spectre.Console.Composition; +using Xunit; + +namespace Spectre.Console.Tests.Unit.Composition +{ + public sealed class BorderTests + { + public sealed class TheGetBorderMethod + { + [Theory] + [InlineData(BorderKind.Ascii, typeof(AsciiBorder))] + [InlineData(BorderKind.Square, typeof(SquareBorder))] + public void Should_Return_Correct_Border_For_Specified_Kind(BorderKind kind, Type expected) + { + // Given, When + var result = Border.GetBorder(kind); + + // Then + result.ShouldBeOfType(expected); + } + + [Fact] + public void Should_Throw_If_Unknown_Border_Kind_Is_Specified() + { + // Given, When + var result = Record.Exception(() => Border.GetBorder((BorderKind)int.MaxValue)); + + // Then + result.ShouldBeOfType(); + result.Message.ShouldBe("Unknown border kind"); + } + } + } +} diff --git a/src/Spectre.Console.Tests/Unit/Composition/TableTests.cs b/src/Spectre.Console.Tests/Unit/Composition/TableTests.cs new file mode 100644 index 0000000..3370540 --- /dev/null +++ b/src/Spectre.Console.Tests/Unit/Composition/TableTests.cs @@ -0,0 +1,158 @@ +using System; +using Shouldly; +using Xunit; + +namespace Spectre.Console.Tests.Unit.Composition +{ + public sealed class TableTests + { + public sealed class TheAddColumnMethod + { + [Fact] + public void Should_Throw_If_Column_Is_Null() + { + // Given + var table = new Table(); + + // When + var result = Record.Exception(() => table.AddColumn(null)); + + // Then + result.ShouldBeOfType() + .ParamName.ShouldBe("column"); + } + } + + public sealed class TheAddColumnsMethod + { + [Fact] + public void Should_Throw_If_Columns_Are_Null() + { + // Given + var table = new Table(); + + // When + var result = Record.Exception(() => table.AddColumns(null)); + + // Then + result.ShouldBeOfType() + .ParamName.ShouldBe("columns"); + } + } + + public sealed class TheAddRowMethod + { + [Fact] + public void Should_Throw_If_Rows_Are_Null() + { + // Given + var table = new Table(); + + // When + var result = Record.Exception(() => table.AddRow(null)); + + // Then + result.ShouldBeOfType() + .ParamName.ShouldBe("columns"); + } + + [Fact] + public void Should_Throw_If_Row_Columns_Is_Less_Than_Number_Of_Columns() + { + // Given + var table = new Table(); + table.AddColumn("Hello"); + table.AddColumn("World"); + + // When + var result = Record.Exception(() => table.AddRow("Foo")); + + // Then + result.ShouldBeOfType(); + result.Message.ShouldBe("The number of row columns are less than the number of table columns."); + } + + [Fact] + public void Should_Throw_If_Row_Columns_Are_Greater_Than_Number_Of_Columns() + { + // Given + var table = new Table(); + table.AddColumn("Hello"); + + // When + var result = Record.Exception(() => table.AddRow("Foo", "Bar")); + + // Then + result.ShouldBeOfType(); + result.Message.ShouldBe("The number of row columns are greater than the number of table columns."); + } + } + + [Fact] + public void Should_Render_Table_Correctly() + { + // Given + var console = new PlainConsole(width: 80); + var table = new Table(); + table.AddColumns("Foo", "Bar", "Baz"); + table.AddRow("Qux", "Corgi", "Waldo"); + table.AddRow("Grault", "Garply", "Fred"); + + // When + console.Render(table); + + // Then + console.Lines[0].ShouldBe("β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”"); + console.Lines[1].ShouldBe("β”‚ Foo β”‚ Bar β”‚ Baz β”‚"); + console.Lines[2].ShouldBe("β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€"); + console.Lines[3].ShouldBe("β”‚ Qux β”‚ Corgi β”‚ Waldo β”‚"); + console.Lines[4].ShouldBe("β”‚ Grault β”‚ Garply β”‚ Fred β”‚"); + console.Lines[5].ShouldBe("β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜"); + } + + [Fact] + public void Should_Render_Table_With_Specified_Border() + { + // Given + var console = new PlainConsole(width: 80); + var table = new Table(BorderKind.Ascii); + table.AddColumns("Foo", "Bar", "Baz"); + table.AddRow("Qux", "Corgi", "Waldo"); + table.AddRow("Grault", "Garply", "Fred"); + + // When + console.Render(table); + + // Then + console.Lines[0].ShouldBe("+-------------------------+"); + console.Lines[1].ShouldBe("| Foo | Bar | Baz |"); + console.Lines[2].ShouldBe("|--------+--------+-------|"); + console.Lines[3].ShouldBe("| Qux | Corgi | Waldo |"); + console.Lines[4].ShouldBe("| Grault | Garply | Fred |"); + console.Lines[5].ShouldBe("+-------------------------+"); + } + + [Fact] + public void Should_Render_Table_With_Multiple_Rows_In_Cell_Correctly() + { + // Given + var console = new PlainConsole(width: 80); + var table = new Table(); + table.AddColumns("Foo", "Bar", "Baz"); + table.AddRow("Qux\nQuuux", "Corgi", "Waldo"); + table.AddRow("Grault", "Garply", "Fred"); + + // When + console.Render(table); + + // Then + console.Lines[0].ShouldBe("β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”"); + console.Lines[1].ShouldBe("β”‚ Foo β”‚ Bar β”‚ Baz β”‚"); + console.Lines[2].ShouldBe("β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€"); + console.Lines[3].ShouldBe("β”‚ Qux β”‚ Corgi β”‚ Waldo β”‚"); + console.Lines[4].ShouldBe("β”‚ Quuux β”‚ β”‚ β”‚"); + console.Lines[5].ShouldBe("β”‚ Grault β”‚ Garply β”‚ Fred β”‚"); + console.Lines[6].ShouldBe("β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜"); + } + } +} diff --git a/src/Spectre.Console.Tests/Unit/StyleTests.cs b/src/Spectre.Console.Tests/Unit/StyleTests.cs index 204016f..0efa9dd 100644 --- a/src/Spectre.Console.Tests/Unit/StyleTests.cs +++ b/src/Spectre.Console.Tests/Unit/StyleTests.cs @@ -197,7 +197,7 @@ namespace Spectre.Console.Tests.Unit public void Should_Throw_If_Foreground_Is_Set_Twice() { // Given, When - var result = Style.TryParse("green yellow", out var style); + var result = Style.TryParse("green yellow", out _); // Then result.ShouldBeFalse(); @@ -207,7 +207,7 @@ namespace Spectre.Console.Tests.Unit public void Should_Throw_If_Background_Is_Set_Twice() { // Given, When - var result = Style.TryParse("green on blue yellow", out var style); + var result = Style.TryParse("green on blue yellow", out _); // Then result.ShouldBeFalse(); @@ -217,7 +217,7 @@ namespace Spectre.Console.Tests.Unit public void Should_Throw_If_Color_Name_Could_Not_Be_Found() { // Given, When - var result = Style.TryParse("bold lol", out var style); + var result = Style.TryParse("bold lol", out _); // Then result.ShouldBeFalse(); @@ -227,7 +227,7 @@ namespace Spectre.Console.Tests.Unit public void Should_Throw_If_Background_Color_Name_Could_Not_Be_Found() { // Given, When - var result = Style.TryParse("blue on lol", out var style); + var result = Style.TryParse("blue on lol", out _); // Then result.ShouldBeFalse(); diff --git a/src/Spectre.Console/AnsiConsole.cs b/src/Spectre.Console/AnsiConsole.cs index 31e0254..e88b67e 100644 --- a/src/Spectre.Console/AnsiConsole.cs +++ b/src/Spectre.Console/AnsiConsole.cs @@ -10,12 +10,14 @@ namespace Spectre.Console { private static readonly Lazy _console = new Lazy(() => { - return Create(new AnsiConsoleSettings + var console = Create(new AnsiConsoleSettings { Ansi = AnsiSupport.Detect, ColorSystem = ColorSystemSupport.Detect, Out = System.Console.Out, }); + Created = true; + return console; }); /// @@ -28,6 +30,8 @@ namespace Spectre.Console /// public static Capabilities Capabilities => Console.Capabilities; + internal static bool Created { get; private set; } + /// /// Gets the buffer width of the console. /// diff --git a/src/Spectre.Console/Capabilities.cs b/src/Spectre.Console/Capabilities.cs index abc3e91..8c47677 100644 --- a/src/Spectre.Console/Capabilities.cs +++ b/src/Spectre.Console/Capabilities.cs @@ -16,16 +16,27 @@ namespace Spectre.Console /// public ColorSystem ColorSystem { get; } - internal Capabilities(bool supportsAnsi, ColorSystem colorSystem) + /// + /// Gets a value indicating whether or not + /// this is a legacy console (cmd.exe). + /// + /// + /// Only relevant when running on Microsoft Windows. + /// + public bool LegacyConsole { get; } + + internal Capabilities(bool supportsAnsi, ColorSystem colorSystem, bool legacyConsole) { SupportsAnsi = supportsAnsi; ColorSystem = colorSystem; + LegacyConsole = legacyConsole; } /// public override string ToString() { var supportsAnsi = SupportsAnsi ? "Yes" : "No"; + var legacyConsole = LegacyConsole ? "Legacy" : "Modern"; var bits = ColorSystem switch { ColorSystem.NoColors => "1 bit", @@ -36,7 +47,7 @@ namespace Spectre.Console _ => "?" }; - return $"ANSI={supportsAnsi}, Colors={ColorSystem} ({bits})"; + return $"ANSI={supportsAnsi}, Colors={ColorSystem}, Kind={legacyConsole} ({bits})"; } } } diff --git a/src/Spectre.Console/Composition/Border.cs b/src/Spectre.Console/Composition/Border.cs new file mode 100644 index 0000000..ec42b6a --- /dev/null +++ b/src/Spectre.Console/Composition/Border.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace Spectre.Console.Composition +{ + /// + /// Represents a border used by tables. + /// + public abstract class Border + { + private readonly Dictionary _lookup; + + private static readonly Dictionary _borders = new Dictionary + { + { BorderKind.Ascii, new AsciiBorder() }, + { BorderKind.Square, new SquareBorder() }, + }; + + /// + /// Initializes a new instance of the class. + /// + protected Border() + { + _lookup = Initialize(); + } + + /// + /// Gets a represented by the specified . + /// + /// The kind of border to get. + /// A instance representing the specified . + public static Border GetBorder(BorderKind kind) + { + if (!_borders.TryGetValue(kind, out var border)) + { + throw new InvalidOperationException("Unknown border kind"); + } + + return border; + } + + private Dictionary Initialize() + { + var lookup = new Dictionary(); + foreach (BorderPart part in Enum.GetValues(typeof(BorderPart))) + { + lookup.Add(part, GetBoxPart(part)); + } + + return lookup; + } + + /// + /// Gets the string representation of a specific border part. + /// + /// The part to get a string representation for. + /// The number of repetitions. + /// A string representation of the specified border part. + public string GetPart(BorderPart part, int count) + { + return new string(GetBoxPart(part), count); + } + + /// + /// Gets the string representation of a specific border part. + /// + /// The part to get a string representation for. + /// A string representation of the specified border part. + public string GetPart(BorderPart part) + { + return _lookup[part].ToString(CultureInfo.InvariantCulture); + } + + /// + /// Gets the character representing the specified border part. + /// + /// The part to get the character representation for. + /// A character representation of the specified border part. + protected abstract char GetBoxPart(BorderPart part); + } +} diff --git a/src/Spectre.Console/Composition/BorderKind.cs b/src/Spectre.Console/Composition/BorderKind.cs new file mode 100644 index 0000000..4d3bac9 --- /dev/null +++ b/src/Spectre.Console/Composition/BorderKind.cs @@ -0,0 +1,18 @@ +namespace Spectre.Console +{ + /// + /// Represents different kinds of borders. + /// + public enum BorderKind + { + /// + /// A square border. + /// + Square = 0, + + /// + /// An old school ASCII border. + /// + Ascii = 1, + } +} diff --git a/src/Spectre.Console/Composition/BorderPart.cs b/src/Spectre.Console/Composition/BorderPart.cs new file mode 100644 index 0000000..5b8d7b6 --- /dev/null +++ b/src/Spectre.Console/Composition/BorderPart.cs @@ -0,0 +1,98 @@ +namespace Spectre.Console.Composition +{ + /// + /// Represents the different border parts. + /// + public enum BorderPart + { + /// + /// The top left part of a header. + /// + HeaderTopLeft, + + /// + /// The top part of a header. + /// + HeaderTop, + + /// + /// The top separator part of a header. + /// + HeaderTopSeparator, + + /// + /// The top right part of a header. + /// + HeaderTopRight, + + /// + /// The left part of a header. + /// + HeaderLeft, + + /// + /// A header separator. + /// + HeaderSeparator, + + /// + /// The right part of a header. + /// + HeaderRight, + + /// + /// The bottom left part of a header. + /// + HeaderBottomLeft, + + /// + /// The bottom part of a header. + /// + HeaderBottom, + + /// + /// The bottom separator part of a header. + /// + HeaderBottomSeparator, + + /// + /// The bottom right part of a header. + /// + HeaderBottomRight, + + /// + /// The left part of a cell. + /// + CellLeft, + + /// + /// A cell separator. + /// + CellSeparator, + + /// + /// The right part of a cell. + /// + ColumnRight, + + /// + /// The bottom left part of a footer. + /// + FooterBottomLeft, + + /// + /// The bottom part of a footer. + /// + FooterBottom, + + /// + /// The bottom separator part of a footer. + /// + FooterBottomSeparator, + + /// + /// The bottom right part of a footer. + /// + FooterBottomRight, + } +} diff --git a/src/Spectre.Console/Composition/Borders/AsciiBorder.cs b/src/Spectre.Console/Composition/Borders/AsciiBorder.cs new file mode 100644 index 0000000..75bf931 --- /dev/null +++ b/src/Spectre.Console/Composition/Borders/AsciiBorder.cs @@ -0,0 +1,37 @@ +using System; + +namespace Spectre.Console.Composition +{ + /// + /// Represents an old school ASCII border. + /// + public sealed class AsciiBorder : Border + { + /// + protected override char GetBoxPart(BorderPart part) + { + return part switch + { + BorderPart.HeaderTopLeft => '+', + BorderPart.HeaderTop => '-', + BorderPart.HeaderTopSeparator => '-', + BorderPart.HeaderTopRight => '+', + BorderPart.HeaderLeft => '|', + BorderPart.HeaderSeparator => '|', + BorderPart.HeaderRight => '|', + BorderPart.HeaderBottomLeft => '|', + BorderPart.HeaderBottom => '-', + BorderPart.HeaderBottomSeparator => '+', + BorderPart.HeaderBottomRight => '|', + BorderPart.CellLeft => '|', + BorderPart.CellSeparator => '|', + BorderPart.ColumnRight => '|', + BorderPart.FooterBottomLeft => '+', + BorderPart.FooterBottom => '-', + BorderPart.FooterBottomSeparator => '-', + BorderPart.FooterBottomRight => '+', + _ => throw new InvalidOperationException("Unknown box part."), + }; + } + } +} diff --git a/src/Spectre.Console/Composition/Borders/SquareBorder.cs b/src/Spectre.Console/Composition/Borders/SquareBorder.cs new file mode 100644 index 0000000..e449229 --- /dev/null +++ b/src/Spectre.Console/Composition/Borders/SquareBorder.cs @@ -0,0 +1,37 @@ +using System; + +namespace Spectre.Console.Composition +{ + /// + /// Represents a square border. + /// + public sealed class SquareBorder : Border + { + /// + protected override char GetBoxPart(BorderPart part) + { + return part switch + { + BorderPart.HeaderTopLeft => 'β”Œ', + BorderPart.HeaderTop => '─', + BorderPart.HeaderTopSeparator => '┬', + BorderPart.HeaderTopRight => '┐', + BorderPart.HeaderLeft => 'β”‚', + BorderPart.HeaderSeparator => 'β”‚', + BorderPart.HeaderRight => 'β”‚', + BorderPart.HeaderBottomLeft => 'β”œ', + BorderPart.HeaderBottom => '─', + BorderPart.HeaderBottomSeparator => 'β”Ό', + BorderPart.HeaderBottomRight => '─', + BorderPart.CellLeft => 'β”‚', + BorderPart.CellSeparator => 'β”‚', + BorderPart.ColumnRight => 'β”‚', + BorderPart.FooterBottomLeft => 'β””', + BorderPart.FooterBottom => '─', + BorderPart.FooterBottomSeparator => 'β”΄', + BorderPart.FooterBottomRight => 'β”˜', + _ => throw new InvalidOperationException("Unknown box part."), + }; + } + } +} diff --git a/src/Spectre.Console/Composition/Table.cs b/src/Spectre.Console/Composition/Table.cs new file mode 100644 index 0000000..acd9592 --- /dev/null +++ b/src/Spectre.Console/Composition/Table.cs @@ -0,0 +1,262 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Spectre.Console.Composition; +using Spectre.Console.Internal; + +namespace Spectre.Console +{ + /// + /// Represents a table. + /// + public sealed class Table : IRenderable + { + private readonly List _columns; + private readonly List> _rows; + private readonly Border _border; + + /// + /// Initializes a new instance of the class. + /// + /// The border to use. + public Table(BorderKind border = BorderKind.Square) + { + _columns = new List(); + _rows = new List>(); + _border = Border.GetBorder(border); + } + + /// + /// Adds a column to the table. + /// + /// The column to add. + public void AddColumn(string column) + { + if (column is null) + { + throw new ArgumentNullException(nameof(column)); + } + + _columns.Add(Text.New(column)); + } + + /// + /// Adds multiple columns to the table. + /// + /// The columns to add. + public void AddColumns(params string[] columns) + { + if (columns is null) + { + throw new ArgumentNullException(nameof(columns)); + } + + _columns.AddRange(columns.Select(column => Text.New(column))); + } + + /// + /// Adds a row to the table. + /// + /// The row columns to add. + public void AddRow(params string[] columns) + { + if (columns is null) + { + throw new ArgumentNullException(nameof(columns)); + } + + if (columns.Length < _columns.Count) + { + throw new InvalidOperationException("The number of row columns are less than the number of table columns."); + } + + if (columns.Length > _columns.Count) + { + throw new InvalidOperationException("The number of row columns are greater than the number of table columns."); + } + + _rows.Add(columns.Select(column => Text.New(column)).ToList()); + } + + /// + public int Measure(Encoding encoding, int maxWidth) + { + // Calculate the max width for each column. + var maxColumnWidth = (maxWidth - (2 + (_columns.Count * 2) + (_columns.Count - 1))) / _columns.Count; + var columnWidths = _columns.Select(c => c.Measure(encoding, maxColumnWidth)).ToArray(); + for (var rowIndex = 0; rowIndex < _rows.Count; rowIndex++) + { + for (var columnIndex = 0; columnIndex < _rows[rowIndex].Count; columnIndex++) + { + var columnWidth = _rows[rowIndex][columnIndex].Measure(encoding, maxColumnWidth); + if (columnWidth > columnWidths[columnIndex]) + { + columnWidths[columnIndex] = columnWidth; + } + } + } + + // We now know the max width of each column, so let's recalculate the width. + return columnWidths.Sum() + 2 + (_columns.Count * 2) + (_columns.Count - 1); + } + + /// + public IEnumerable Render(Encoding encoding, int width) + { + // Calculate the max width for each column. + var maxColumnWidth = (width - (2 + (_columns.Count * 2) + (_columns.Count - 1))) / _columns.Count; + var columnWidths = _columns.Select(c => c.Measure(encoding, maxColumnWidth)).ToArray(); + for (var rowIndex = 0; rowIndex < _rows.Count; rowIndex++) + { + for (var columnIndex = 0; columnIndex < _rows[rowIndex].Count; columnIndex++) + { + var columnWidth = _rows[rowIndex][columnIndex].Measure(encoding, maxColumnWidth); + if (columnWidth > columnWidths[columnIndex]) + { + columnWidths[columnIndex] = columnWidth; + } + } + } + + // We now know the max width of each column, so let's recalculate the width. + width = columnWidths.Sum() + 2 + (_columns.Count * 2) + (_columns.Count - 1); + + // Create the rows. + var rows = new List>(); + rows.Add(new List(_columns)); + rows.AddRange(_rows); + + // Iterate all rows. + var result = new List(); + foreach (var (index, firstRow, lastRow, row) in rows.Enumerate()) + { + var cellHeight = 1; + + // Get the list of cells for the row. + var cells = new List>(); + + foreach (var (rowWidth, cell) in columnWidths.Zip(row, (f, s) => (f, s))) + { + var lines = Segment.SplitLines(cell.Render(encoding, rowWidth)); + cellHeight = Math.Max(cellHeight, lines.Count); + cells.Add(lines); + } + + if (firstRow) + { + result.Add(new Segment(_border.GetPart(BorderPart.HeaderTopLeft))); + foreach (var (columnIndex, _, lastColumn, columnWidth) in columnWidths.Enumerate()) + { + result.Add(new Segment(_border.GetPart(BorderPart.HeaderTop))); // Left padding + result.Add(new Segment(_border.GetPart(BorderPart.HeaderTop, columnWidth))); + result.Add(new Segment(_border.GetPart(BorderPart.HeaderTop))); // Right padding + + if (!lastColumn) + { + result.Add(new Segment(_border.GetPart(BorderPart.HeaderTopSeparator))); + } + } + + result.Add(new Segment(_border.GetPart(BorderPart.HeaderTopRight))); + result.Add(Segment.LineBreak()); + } + + // Iterate through each cell row + foreach (var cellRowIndex in Enumerable.Range(0, cellHeight)) + { + // Make cells the same shape + MakeSameHeight(cellHeight, cells); + + var w00t = cells.Enumerate().ToArray(); + foreach (var (cellIndex, firstCell, lastCell, cell) in w00t) + { + if (firstCell) + { + result.Add(new Segment(_border.GetPart(BorderPart.CellLeft))); + } + + result.Add(new Segment(" ")); + result.AddRange(cell[cellRowIndex]); + + // Pad cell right + var length = cell[cellRowIndex].Sum(segment => segment.CellLength(encoding)); + if (length < columnWidths[cellIndex]) + { + result.Add(new Segment(new string(' ', columnWidths[cellIndex] - length))); + } + + result.Add(new Segment(" ")); + + if (lastCell) + { + // Separator + result.Add(new Segment(_border.GetPart(BorderPart.ColumnRight))); + } + else + { + // Separator + result.Add(new Segment(_border.GetPart(BorderPart.CellSeparator))); + } + } + + result.Add(Segment.LineBreak()); + } + + if (firstRow) + { + result.Add(new Segment(_border.GetPart(BorderPart.HeaderBottomLeft))); + foreach (var (columnIndex, first, lastColumn, columnWidth) in columnWidths.Enumerate()) + { + result.Add(new Segment(_border.GetPart(BorderPart.HeaderBottom))); // Left padding + result.Add(new Segment(_border.GetPart(BorderPart.HeaderBottom, columnWidth))); + result.Add(new Segment(_border.GetPart(BorderPart.HeaderBottom))); // Right padding + + if (!lastColumn) + { + result.Add(new Segment(_border.GetPart(BorderPart.HeaderBottomSeparator))); + } + } + + result.Add(new Segment(_border.GetPart(BorderPart.HeaderBottomRight))); + result.Add(Segment.LineBreak()); + } + + if (lastRow) + { + result.Add(new Segment(_border.GetPart(BorderPart.FooterBottomLeft))); + foreach (var (columnIndex, first, lastColumn, columnWidth) in columnWidths.Enumerate()) + { + result.Add(new Segment(_border.GetPart(BorderPart.FooterBottom))); + result.Add(new Segment(_border.GetPart(BorderPart.FooterBottom, columnWidth))); + result.Add(new Segment(_border.GetPart(BorderPart.FooterBottom))); + + if (!lastColumn) + { + result.Add(new Segment(_border.GetPart(BorderPart.FooterBottomSeparator))); + } + } + + result.Add(new Segment(_border.GetPart(BorderPart.FooterBottomRight))); + result.Add(Segment.LineBreak()); + } + } + + return result; + } + + private static void MakeSameHeight(int cellHeight, List> cells) + { + foreach (var cell in cells) + { + if (cell.Count < cellHeight) + { + while (cell.Count != cellHeight) + { + cell.Add(new SegmentLine()); + } + } + } + } + } +} diff --git a/src/Spectre.Console/Composition/Text.cs b/src/Spectre.Console/Composition/Text.cs index c4ac9e2..6fbd348 100644 --- a/src/Spectre.Console/Composition/Text.cs +++ b/src/Spectre.Console/Composition/Text.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; @@ -12,6 +13,7 @@ namespace Spectre.Console /// Represents text with color and decorations. /// [SuppressMessage("Naming", "CA1724:Type names should not match namespaces")] + [DebuggerDisplay("{_text,nq}")] public sealed class Text : IRenderable { private readonly List _spans; @@ -98,15 +100,24 @@ namespace Spectre.Console /// public int Measure(Encoding encoding, int maxWidth) { - var lines = _text.SplitLines(); - return lines.Max(x => x.CellLength(encoding)); + var lines = Segment.SplitLines(Render(encoding, maxWidth)); + if (lines.Count == 0) + { + return 0; + } + + return lines.Max(x => x.Length); } /// public IEnumerable Render(Encoding encoding, int width) { - var result = new List(); + if (string.IsNullOrWhiteSpace(_text)) + { + return Array.Empty(); + } + var result = new List(); var segments = SplitLineBreaks(CreateSegments()); foreach (var (_, _, last, line) in Segment.SplitLines(segments, width).Enumerate()) diff --git a/src/Spectre.Console/Internal/Ansi/AnsiDetector.cs b/src/Spectre.Console/Internal/Ansi/AnsiDetector.cs index 6d48d3e..d678e71 100644 --- a/src/Spectre.Console/Internal/Ansi/AnsiDetector.cs +++ b/src/Spectre.Console/Internal/Ansi/AnsiDetector.cs @@ -32,12 +32,12 @@ namespace Spectre.Console.Internal new Regex("bvterm"), // Bitvise SSH Client }; - public static bool Detect(bool upgrade) + public static (bool SupportsAnsi, bool LegacyConsole) Detect(bool upgrade) { // Github action doesn't setup a correct PTY but supports ANSI. if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("GITHUB_ACTION"))) { - return true; + return (true, false); } // Running on Windows? @@ -47,10 +47,11 @@ namespace Spectre.Console.Internal var conEmu = Environment.GetEnvironmentVariable("ConEmuANSI"); if (!string.IsNullOrEmpty(conEmu) && conEmu.Equals("On", StringComparison.OrdinalIgnoreCase)) { - return true; + return (true, false); } - return Windows.SupportsAnsi(upgrade); + var supportsAnsi = Windows.SupportsAnsi(upgrade, out var legacyConsole); + return (supportsAnsi, legacyConsole); } // Check if the terminal is of type ANSI/VT100/xterm compatible. @@ -59,11 +60,11 @@ namespace Spectre.Console.Internal { if (_regexes.Any(regex => regex.IsMatch(term))) { - return true; + return (true, false); } } - return false; + return (false, true); } [SuppressMessage("Design", "CA1060:Move pinvokes to native methods class")] @@ -91,8 +92,10 @@ namespace Spectre.Console.Internal public static extern uint GetLastError(); [SuppressMessage("Design", "CA1031:Do not catch general exception types")] - public static bool SupportsAnsi(bool upgrade) + public static bool SupportsAnsi(bool upgrade, out bool isLegacy) { + isLegacy = false; + try { var @out = GetStdHandle(STD_OUTPUT_HANDLE); @@ -104,6 +107,8 @@ namespace Spectre.Console.Internal if ((mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) == 0) { + isLegacy = true; + if (!upgrade) { return false; diff --git a/src/Spectre.Console/Internal/AnsiConsoleRenderer.cs b/src/Spectre.Console/Internal/AnsiConsoleRenderer.cs index 47cdfec..290585d 100644 --- a/src/Spectre.Console/Internal/AnsiConsoleRenderer.cs +++ b/src/Spectre.Console/Internal/AnsiConsoleRenderer.cs @@ -41,12 +41,12 @@ namespace Spectre.Console.Internal } } - public AnsiConsoleRenderer(TextWriter @out, ColorSystem system) + public AnsiConsoleRenderer(TextWriter @out, ColorSystem system, bool legacyConsole) { _out = @out ?? throw new ArgumentNullException(nameof(@out)); _system = system; - Capabilities = new Capabilities(true, system); + Capabilities = new Capabilities(true, system, legacyConsole); Encoding = @out.IsStandardOut() ? System.Console.OutputEncoding : Encoding.UTF8; Foreground = Color.Default; Background = Color.Default; diff --git a/src/Spectre.Console/Internal/ConsoleBuilder.cs b/src/Spectre.Console/Internal/ConsoleBuilder.cs index a8abcf8..453f2ac 100644 --- a/src/Spectre.Console/Internal/ConsoleBuilder.cs +++ b/src/Spectre.Console/Internal/ConsoleBuilder.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.InteropServices; namespace Spectre.Console.Internal { @@ -13,9 +14,41 @@ namespace Spectre.Console.Internal var buffer = settings.Out ?? System.Console.Out; - var supportsAnsi = settings.Ansi == AnsiSupport.Detect - ? AnsiDetector.Detect(true) - : settings.Ansi == AnsiSupport.Yes; + var supportsAnsi = settings.Ansi == AnsiSupport.Yes; + var legacyConsole = false; + + if (settings.Ansi == AnsiSupport.Detect) + { + (supportsAnsi, legacyConsole) = AnsiDetector.Detect(true); + + // Check whether or not this is a legacy console from the existing instance (if any). + // We need to do this because once we upgrade the console to support ENABLE_VIRTUAL_TERMINAL_PROCESSING + // on Windows, there is no way of detecting whether or not we're running on a legacy console or not. + if (AnsiConsole.Created && !legacyConsole && buffer.IsStandardOut() && AnsiConsole.Capabilities.LegacyConsole) + { + legacyConsole = AnsiConsole.Capabilities.LegacyConsole; + } + } + else + { + if (buffer.IsStandardOut()) + { + // Are we running on Windows? + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + // Not the first console we're creating? + if (AnsiConsole.Created) + { + legacyConsole = AnsiConsole.Capabilities.LegacyConsole; + } + else + { + // Try detecting whether or not this + (_, legacyConsole) = AnsiDetector.Detect(false); + } + } + } + } var colorSystem = settings.ColorSystem == ColorSystemSupport.Detect ? ColorSystemDetector.Detect(supportsAnsi) @@ -23,13 +56,13 @@ namespace Spectre.Console.Internal if (supportsAnsi) { - return new AnsiConsoleRenderer(buffer, colorSystem) + return new AnsiConsoleRenderer(buffer, colorSystem, legacyConsole) { Decoration = Decoration.None, }; } - return new FallbackConsoleRenderer(buffer, colorSystem); + return new FallbackConsoleRenderer(buffer, colorSystem, legacyConsole); } } } diff --git a/src/Spectre.Console/Internal/FallbackConsoleRenderer.cs b/src/Spectre.Console/Internal/FallbackConsoleRenderer.cs index cb30730..edd1585 100644 --- a/src/Spectre.Console/Internal/FallbackConsoleRenderer.cs +++ b/src/Spectre.Console/Internal/FallbackConsoleRenderer.cs @@ -85,7 +85,7 @@ namespace Spectre.Console.Internal } } - public FallbackConsoleRenderer(TextWriter @out, ColorSystem system) + public FallbackConsoleRenderer(TextWriter @out, ColorSystem system, bool legacyConsole) { _out = @out; _system = system; @@ -105,7 +105,7 @@ namespace Spectre.Console.Internal Encoding = Encoding.UTF8; } - Capabilities = new Capabilities(false, _system); + Capabilities = new Capabilities(false, _system, legacyConsole); } public void Write(string text) diff --git a/src/Spectre.Console/Internal/Text/Markup/MarkupParser.cs b/src/Spectre.Console/Internal/Text/Markup/MarkupParser.cs index 12d358c..fbf1eaf 100644 --- a/src/Spectre.Console/Internal/Text/Markup/MarkupParser.cs +++ b/src/Spectre.Console/Internal/Text/Markup/MarkupParser.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; namespace Spectre.Console.Internal { @@ -35,7 +36,7 @@ namespace Spectre.Console.Internal else if (token.Kind == MarkupTokenKind.Text) { // Get the effecive style. - var effectiveStyle = style.Combine(stack); + var effectiveStyle = style.Combine(stack.Reverse()); result.Append(token.Value, effectiveStyle); } else diff --git a/src/Spectre.Console/Internal/Text/StyleParser.cs b/src/Spectre.Console/Internal/Text/StyleParser.cs index 4c7b1a1..efcdf4a 100644 --- a/src/Spectre.Console/Internal/Text/StyleParser.cs +++ b/src/Spectre.Console/Internal/Text/StyleParser.cs @@ -18,12 +18,7 @@ namespace Spectre.Console.Internal public static bool TryParse(string text, out Style style) { style = Parse(text, out var error); - if (error != null) - { - return false; - } - - return true; + return error == null; } private static Style Parse(string text, out string error)