Compare commits

...

14 Commits
0.4.0 ... 0.7.0

Author SHA1 Message Date
Patrik Svensson
d475e3b30a Reset colors before line break
Closes #28
2020-08-07 13:12:03 +02:00
Patrik Svensson
9637066927 Add better algorithm for calculating column widths
Closes #14
2020-08-07 12:55:33 +02:00
AdmiringWorm
0b4321115a Add background color examples in Sample console 2020-08-07 08:20:20 +02:00
AdmiringWorm
5cd9ece31a Add check for IsDefault when comparing Colors 2020-08-07 08:20:20 +02:00
AdmiringWorm
b0341862cf Add failing unit test for comparing black and default color 2020-08-07 08:20:20 +02:00
AdmiringWorm
2e7b3d520a Update regex to correctly identify Windows 10
When running .NET Core 2.1 or .NET Framework 4.6.1, the used regex for
detecting Windows 10 TrueColor support does not match the OSDescription.
The reason for this is because on those frameworks the description has
trailing whitespaces, but they do not on .NET Core 3.1.
This commit updates the regex to ignore any trailing whitespaces.
2020-08-07 08:11:34 +02:00
Patrik Svensson
646f51a628 Fix NuGet badge (skip-ci) 2020-08-05 16:03:09 +02:00
Patrik Svensson
a0bd481255 Add package icon
Closes #20
2020-08-05 15:49:43 +02:00
Patrik Svensson
6d197c5140 Add border support for panels
Closes #11
2020-08-05 15:28:15 +02:00
Patrik Svensson
108e56c229 Add rounded border 2020-08-05 14:19:45 +02:00
Patrik Svensson
66994cd904 Add grid support 2020-08-05 00:44:05 +02:00
Patrik Svensson
f9bd936254 Add support for showing no border 2020-08-05 00:44:05 +02:00
Patrik Svensson
a068fc68c3 Add support for tables 2020-08-04 22:24:13 +02:00
Patrik Svensson
aa34c145b9 skip-ci: Do not explicitly fetch tags 2020-08-04 09:35:29 +02:00
44 changed files with 1869 additions and 90 deletions

View File

@@ -2,9 +2,7 @@ name: Continuous Integration
on: pull_request on: pull_request
env: env:
# Set the DOTNET_SKIP_FIRST_TIME_EXPERIENCE environment variable to stop wasting time caching packages
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
# Disable sending usage data to Microsoft
DOTNET_CLI_TELEMETRY_OPTOUT: true DOTNET_CLI_TELEMETRY_OPTOUT: true
jobs: jobs:
@@ -28,10 +26,6 @@ jobs:
with: with:
fetch-depth: 0 fetch-depth: 0
- name: 'Get Git tags'
run: git fetch --tags
shell: bash
- name: Setup dotnet - name: Setup dotnet
uses: actions/setup-dotnet@v1 uses: actions/setup-dotnet@v1
with: with:

View File

@@ -8,9 +8,7 @@ on:
- main - main
env: env:
# Set the DOTNET_SKIP_FIRST_TIME_EXPERIENCE environment variable to stop wasting time caching packages
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
# Disable sending usage data to Microsoft
DOTNET_CLI_TELEMETRY_OPTOUT: true DOTNET_CLI_TELEMETRY_OPTOUT: true
jobs: jobs:
@@ -39,10 +37,6 @@ jobs:
with: with:
fetch-depth: 0 fetch-depth: 0
- name: 'Get Git tags'
run: git fetch --tags
shell: bash
- name: Setup dotnet - name: Setup dotnet
uses: actions/setup-dotnet@v1 uses: actions/setup-dotnet@v1
with: with:
@@ -69,10 +63,6 @@ jobs:
with: with:
fetch-depth: 0 fetch-depth: 0
- name: 'Get Git tags'
run: git fetch --tags
shell: bash
- name: Setup dotnet - name: Setup dotnet
uses: actions/setup-dotnet@v1 uses: actions/setup-dotnet@v1
with: with:

View File

@@ -1,6 +1,6 @@
# `Spectre.Console` # `Spectre.Console`
_[![Spectre.IO NuGet Version](https://img.shields.io/nuget/v/spectre.io.svg?style=flat&label=NuGet%3A%20Spectre.Console)](https://www.nuget.org/packages/spectre.console)_ _[![Spectre.Console NuGet Version](https://img.shields.io/nuget/v/spectre.console.svg?style=flat&label=NuGet%3A%20Spectre.Console)](https://www.nuget.org/packages/spectre.console)_
A .NET Standard 2.0 library that makes it easier to create beautiful console applications. A .NET Standard 2.0 library that makes it easier to create beautiful console applications.
It is heavily inspired by the excellent [Rich library](https://github.com/willmcgugan/rich) It is heavily inspired by the excellent [Rich library](https://github.com/willmcgugan/rich)

BIN
gfx/large-logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 600 KiB

BIN
gfx/medium-logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

BIN
gfx/small-logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

View File

@@ -18,6 +18,7 @@
<Authors>Patrik Svensson</Authors> <Authors>Patrik Svensson</Authors>
<RepositoryType>git</RepositoryType> <RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/spectresystems/spectre.console</RepositoryUrl> <RepositoryUrl>https://github.com/spectresystems/spectre.console</RepositoryUrl>
<PackageIcon>small-logo.png</PackageIcon>
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance> <PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
<PackageProjectUrl>https://github.com/spectresystems/spectre.console</PackageProjectUrl> <PackageProjectUrl>https://github.com/spectresystems/spectre.console</PackageProjectUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageLicenseExpression>MIT</PackageLicenseExpression>

View File

@@ -17,11 +17,17 @@ namespace Sample
AnsiConsole.MarkupLine("[white on red]Good[/] [red]bye[/]!"); AnsiConsole.MarkupLine("[white on red]Good[/] [red]bye[/]!");
AnsiConsole.WriteLine(); AnsiConsole.WriteLine();
// We can also use System.ConsoleColor with AnsiConsole. // We can also use System.ConsoleColor with AnsiConsole
// to set the foreground and background color.
foreach (ConsoleColor value in Enum.GetValues(typeof(ConsoleColor))) foreach (ConsoleColor value in Enum.GetValues(typeof(ConsoleColor)))
{ {
AnsiConsole.Foreground = value; var foreground = value;
AnsiConsole.WriteLine("ConsoleColor.{0}", value); var background = (ConsoleColor)(15 - (int)value);
AnsiConsole.Foreground = foreground;
AnsiConsole.Background = background;
AnsiConsole.WriteLine("{0} on {1}", foreground, background);
AnsiConsole.ResetColors();
} }
// We can get the default console via the static API. // We can get the default console via the static API.
@@ -51,12 +57,18 @@ namespace Sample
// Nest some panels and text // Nest some panels and text
AnsiConsole.Foreground = Color.Maroon; AnsiConsole.Foreground = Color.Maroon;
AnsiConsole.Render(new Panel(new Panel(new Panel(new Panel( AnsiConsole.Render(
new Panel(
new Panel(
new Panel(
new Panel(
Text.New( Text.New(
"[underline]I[/] heard [underline on blue]you[/] like 📦\n\n\n\n" + "[underline]I[/] heard [underline on blue]you[/] like 📦\n\n\n\n" +
"So I put a 📦 in a 📦\nin a 📦 in a 📦\n\n" + "So I put a 📦 in a 📦\nin a 📦 in a 📦\n\n" +
"😅", "😅", foreground: Color.White),
foreground: Color.White), content: Justify.Center))))); content: Justify.Center,
border: BorderKind.Rounded))),
border: BorderKind.Ascii));
// Reset colors // Reset colors
AnsiConsole.ResetColors(); AnsiConsole.ResetColors();
@@ -78,6 +90,71 @@ namespace Sample
Text.New("Right adjusted\nRight", Text.New("Right adjusted\nRight",
foreground: Color.White), foreground: Color.White),
fit: true, content: Justify.Right)); fit: true, content: Justify.Right));
// A normal, square table
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);
// A rounded table
table = new Table { Border = BorderKind.Rounded };
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);
// A rounded table without headers
table = new Table { Border = BorderKind.Rounded, ShowHeaders = false };
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);
// Emulate the usage information for "dotnet run"
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine("Usage: [grey]dotnet [blue]run[/] [[options] [[[[--] <additional arguments>...]][/]");
AnsiConsole.WriteLine();
var grid = new Grid();
grid.AddColumn(new GridColumn { NoWrap = true });
grid.AddColumn(new GridColumn { NoWrap = true, Width = 2 });
grid.AddColumn();
grid.AddRow("Options:", "", "");
grid.AddRow(" [blue]-h[/], [blue]--help[/]", "", "Show command line help.");
grid.AddRow(" [blue]-c[/], [blue]--configuration[/] <CONFIGURATION>", "", "The configuration to run for.\nThe default for most projects is [green]Debug[/].");
grid.AddRow(" [blue]-v[/], [blue]--verbosity[/] <LEVEL>", "", "Set the MSBuild verbosity level. Allowed values are \nq[grey][[uiet][/], m[grey][[inimal][/], n[grey][[ormal][/], d[grey][[etailed][/], and diag[grey][[nostic][/].");
AnsiConsole.Render(grid);
// A simple table
AnsiConsole.WriteLine();
table = new Table { Border = BorderKind.Rounded };
table.AddColumn("Foo");
table.AddColumn("Bar");
table.AddColumn("Baz");
table.AddRow("Qux\nQuuuuuux", "[blue]Corgi[/]", "Waldo");
table.AddRow("Grault", "Garply", "Fred");
AnsiConsole.Render(table);
// Render a table in some panels.
AnsiConsole.Render(new Panel(new Panel(table, border: BorderKind.Ascii)));
// Draw another table
table = new Table { Expand = false };
table.AddColumn(new TableColumn("Date"));
table.AddColumn(new TableColumn("Title"));
table.AddColumn(new TableColumn("Production\nBudget"));
table.AddColumn(new TableColumn("Box Office"));
table.AddRow("Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "[red]$375,126,118[/]");
table.AddRow("May 25, 2018", "[yellow]Solo[/]: A Star Wars Story", "$275,000,000", "$393,151,347");
table.AddRow("Dec 15, 2017", "Star Wars Ep. VIII: The Last Jedi", "$262,000,000", "[bold green]$1,332,539,889[/]");
AnsiConsole.Render(table);
} }
} }
} }

View File

@@ -246,6 +246,38 @@ namespace Spectre.Console.Tests.Unit
public sealed class WriteLine public sealed class WriteLine
{ {
[Fact]
public void Should_Reset_Colors_Correctly_After_Line_Break()
{
// Given
var fixture = new AnsiConsoleFixture(ColorSystem.Standard, AnsiSupport.Yes);
// When
fixture.Console.Background = ConsoleColor.Red;
fixture.Console.WriteLine("Hello");
fixture.Console.Background = ConsoleColor.Green;
fixture.Console.WriteLine("World");
// Then
fixture.Output.NormalizeLineEndings()
.ShouldBe("Hello\nWorld\n");
}
[Fact]
public void Should_Reset_Colors_Correctly_After_Line_Break_In_Text()
{
// Given
var fixture = new AnsiConsoleFixture(ColorSystem.Standard, AnsiSupport.Yes);
// When
fixture.Console.Background = ConsoleColor.Red;
fixture.Console.WriteLine("Hello\nWorld");
// Then
fixture.Output.NormalizeLineEndings()
.ShouldBe("Hello\nWorld\n");
}
[Theory] [Theory]
[InlineData(AnsiSupport.Yes)] [InlineData(AnsiSupport.Yes)]
[InlineData(AnsiSupport.No)] [InlineData(AnsiSupport.No)]

View File

@@ -78,6 +78,20 @@ namespace Spectre.Console.Tests.Unit
// Then // Then
result.ShouldBeFalse(); result.ShouldBeFalse();
} }
[Fact]
public void Shourd_Not_Consider_Black_And_Default_Colors_Equal()
{
// Given
var color1 = Color.Default;
var color2 = Color.Black;
// When
var result = color1.Equals(color2);
// Then
result.ShouldBeFalse();
}
} }
public sealed class TheGetHashCodeMethod public sealed class TheGetHashCodeMethod

View File

@@ -0,0 +1,37 @@
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))]
[InlineData(BorderKind.Rounded, typeof(RoundedBorder))]
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<InvalidOperationException>();
result.Message.ShouldBe("Unknown border kind");
}
}
}
}

View File

@@ -0,0 +1,100 @@
using System;
using Shouldly;
using Xunit;
namespace Spectre.Console.Tests.Unit.Composition
{
public sealed class GridTests
{
public sealed class TheAddRowMethod
{
[Fact]
public void Should_Throw_If_Rows_Are_Null()
{
// Given
var grid = new Grid();
// When
var result = Record.Exception(() => grid.AddRow(null));
// Then
result.ShouldBeOfType<ArgumentNullException>()
.ParamName.ShouldBe("columns");
}
[Fact]
public void Should_Throw_If_Row_Columns_Is_Less_Than_Number_Of_Columns()
{
// Given
var grid = new Grid();
grid.AddColumn();
grid.AddColumn();
// When
var result = Record.Exception(() => grid.AddRow("Foo"));
// Then
result.ShouldBeOfType<InvalidOperationException>();
result.Message.ShouldBe("The number of row columns are less than the number of grid columns.");
}
[Fact]
public void Should_Throw_If_Row_Columns_Are_Greater_Than_Number_Of_Columns()
{
// Given
var grid = new Grid();
grid.AddColumn();
// When
var result = Record.Exception(() => grid.AddRow("Foo", "Bar"));
// Then
result.ShouldBeOfType<InvalidOperationException>();
result.Message.ShouldBe("The number of row columns are greater than the number of grid columns.");
}
}
[Fact]
public void Should_Render_Grid_With_No_Border_Correctly()
{
// Given
var console = new PlainConsole(width: 80);
var grid = new Grid();
grid.AddColumn();
grid.AddColumn();
grid.AddColumn();
grid.AddRow("Qux", "Corgi", "Waldo");
grid.AddRow("Grault", "Garply", "Fred");
// When
console.Render(grid);
// Then
console.Lines.Count.ShouldBe(2);
console.Lines[0].ShouldBe("Qux Corgi Waldo");
console.Lines[1].ShouldBe("Grault Garply Fred ");
}
[Fact]
public void Should_Render_Grid()
{
var console = new PlainConsole(width: 80);
var grid = new Grid();
grid.AddColumn(new GridColumn { NoWrap = true });
grid.AddColumn();
grid.AddRow("[bold]Options[/]", string.Empty);
grid.AddRow(" [blue]-h[/], [blue]--help[/]", "Show command line help.");
grid.AddRow(" [blue]-c[/], [blue]--configuration[/]", "The configuration to run for.\nThe default for most projects is [green]Debug[/].");
// When
console.Render(grid);
// Then
console.Lines.Count.ShouldBe(4);
console.Lines[0].ShouldBe("Options ");
console.Lines[1].ShouldBe(" -h, --help Show command line help. ");
console.Lines[2].ShouldBe(" -c, --configuration The configuration to run for. ");
console.Lines[3].ShouldBe(" The default for most projects is Debug. ");
}
}
}

View File

@@ -0,0 +1,253 @@
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((string)null));
// Then
result.ShouldBeOfType<ArgumentNullException>()
.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<ArgumentNullException>()
.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<ArgumentNullException>()
.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<InvalidOperationException>();
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<InvalidOperationException>();
result.Message.ShouldBe("The number of row columns are greater than the number of table columns.");
}
}
[Fact]
public void Should_Measure_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(new Panel(table));
// Then
console.Lines.Count.ShouldBe(8);
console.Lines[0].ShouldBe("┌─────────────────────────────┐");
console.Lines[1].ShouldBe("│ ┌────────┬────────┬───────┐ │");
console.Lines[2].ShouldBe("│ │ Foo │ Bar │ Baz │ │");
console.Lines[3].ShouldBe("│ ├────────┼────────┼───────┤ │");
console.Lines[4].ShouldBe("│ │ Qux │ Corgi │ Waldo │ │");
console.Lines[5].ShouldBe("│ │ Grault │ Garply │ Fred │ │");
console.Lines[6].ShouldBe("│ └────────┴────────┴───────┘ │");
console.Lines[7].ShouldBe("└─────────────────────────────┘");
}
[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.Count.ShouldBe(6);
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_Expand_Table_To_Available_Space_If_Specified()
{
// Given
var console = new PlainConsole(width: 80);
var table = new Table() { Expand = true };
table.AddColumns("Foo", "Bar", "Baz");
table.AddRow("Qux", "Corgi", "Waldo");
table.AddRow("Grault", "Garply", "Fred");
// When
console.Render(table);
// Then
console.Lines.Count.ShouldBe(6);
console.Lines[0].Length.ShouldBe(80);
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_Ascii_Border_Correctly()
{
// Given
var console = new PlainConsole(width: 80);
var table = new Table { Border = BorderKind.Ascii };
table.AddColumns("Foo", "Bar", "Baz");
table.AddRow("Qux", "Corgi", "Waldo");
table.AddRow("Grault", "Garply", "Fred");
// When
console.Render(table);
// Then
console.Lines.Count.ShouldBe(6);
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_Rounded_Border_Correctly()
{
// Given
var console = new PlainConsole(width: 80);
var table = new Table { Border = BorderKind.Rounded };
table.AddColumns("Foo", "Bar", "Baz");
table.AddRow("Qux", "Corgi", "Waldo");
table.AddRow("Grault", "Garply", "Fred");
// When
console.Render(table);
// Then
console.Lines.Count.ShouldBe(6);
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_No_Border_Correctly()
{
// Given
var console = new PlainConsole(width: 80);
var table = new Table { Border = BorderKind.None };
table.AddColumns("Foo", "Bar", "Baz");
table.AddRow("Qux", "Corgi", "Waldo");
table.AddRow("Grault", "Garply", "Fred");
// When
console.Render(table);
// Then
console.Lines.Count.ShouldBe(3);
console.Lines[0].ShouldBe("Foo Bar Baz ");
console.Lines[1].ShouldBe("Qux Corgi Waldo");
console.Lines[2].ShouldBe("Grault Garply Fred ");
}
[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.Count.ShouldBe(7);
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("└────────┴────────┴───────┘");
}
}
}

View File

@@ -197,7 +197,7 @@ namespace Spectre.Console.Tests.Unit
public void Should_Throw_If_Foreground_Is_Set_Twice() public void Should_Throw_If_Foreground_Is_Set_Twice()
{ {
// Given, When // Given, When
var result = Style.TryParse("green yellow", out var style); var result = Style.TryParse("green yellow", out _);
// Then // Then
result.ShouldBeFalse(); result.ShouldBeFalse();
@@ -207,7 +207,7 @@ namespace Spectre.Console.Tests.Unit
public void Should_Throw_If_Background_Is_Set_Twice() public void Should_Throw_If_Background_Is_Set_Twice()
{ {
// Given, When // Given, When
var result = Style.TryParse("green on blue yellow", out var style); var result = Style.TryParse("green on blue yellow", out _);
// Then // Then
result.ShouldBeFalse(); result.ShouldBeFalse();
@@ -217,7 +217,7 @@ namespace Spectre.Console.Tests.Unit
public void Should_Throw_If_Color_Name_Could_Not_Be_Found() public void Should_Throw_If_Color_Name_Could_Not_Be_Found()
{ {
// Given, When // Given, When
var result = Style.TryParse("bold lol", out var style); var result = Style.TryParse("bold lol", out _);
// Then // Then
result.ShouldBeFalse(); result.ShouldBeFalse();
@@ -227,7 +227,7 @@ namespace Spectre.Console.Tests.Unit
public void Should_Throw_If_Background_Color_Name_Could_Not_Be_Found() public void Should_Throw_If_Background_Color_Name_Could_Not_Be_Found()
{ {
// Given, When // Given, When
var result = Style.TryParse("blue on lol", out var style); var result = Style.TryParse("blue on lol", out _);
// Then // Then
result.ShouldBeFalse(); result.ShouldBeFalse();

View File

@@ -10,12 +10,14 @@ namespace Spectre.Console
{ {
private static readonly Lazy<IAnsiConsole> _console = new Lazy<IAnsiConsole>(() => private static readonly Lazy<IAnsiConsole> _console = new Lazy<IAnsiConsole>(() =>
{ {
return Create(new AnsiConsoleSettings var console = Create(new AnsiConsoleSettings
{ {
Ansi = AnsiSupport.Detect, Ansi = AnsiSupport.Detect,
ColorSystem = ColorSystemSupport.Detect, ColorSystem = ColorSystemSupport.Detect,
Out = System.Console.Out, Out = System.Console.Out,
}); });
Created = true;
return console;
}); });
/// <summary> /// <summary>
@@ -28,6 +30,8 @@ namespace Spectre.Console
/// </summary> /// </summary>
public static Capabilities Capabilities => Console.Capabilities; public static Capabilities Capabilities => Console.Capabilities;
internal static bool Created { get; private set; }
/// <summary> /// <summary>
/// Gets the buffer width of the console. /// Gets the buffer width of the console.
/// </summary> /// </summary>

View File

@@ -16,16 +16,27 @@ namespace Spectre.Console
/// </summary> /// </summary>
public ColorSystem ColorSystem { get; } public ColorSystem ColorSystem { get; }
internal Capabilities(bool supportsAnsi, ColorSystem colorSystem) /// <summary>
/// Gets a value indicating whether or not
/// this is a legacy console (cmd.exe).
/// </summary>
/// <remarks>
/// Only relevant when running on Microsoft Windows.
/// </remarks>
public bool LegacyConsole { get; }
internal Capabilities(bool supportsAnsi, ColorSystem colorSystem, bool legacyConsole)
{ {
SupportsAnsi = supportsAnsi; SupportsAnsi = supportsAnsi;
ColorSystem = colorSystem; ColorSystem = colorSystem;
LegacyConsole = legacyConsole;
} }
/// <inheritdoc/> /// <inheritdoc/>
public override string ToString() public override string ToString()
{ {
var supportsAnsi = SupportsAnsi ? "Yes" : "No"; var supportsAnsi = SupportsAnsi ? "Yes" : "No";
var legacyConsole = LegacyConsole ? "Legacy" : "Modern";
var bits = ColorSystem switch var bits = ColorSystem switch
{ {
ColorSystem.NoColors => "1 bit", 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})";
} }
} }
} }

View File

@@ -82,7 +82,8 @@ namespace Spectre.Console
/// <inheritdoc/> /// <inheritdoc/>
public bool Equals(Color other) public bool Equals(Color other)
{ {
return R == other.R && G == other.G && B == other.B; return (IsDefault && other.IsDefault) ||
(IsDefault == other.IsDefault && R == other.R && G == other.G && B == other.B);
} }
/// <summary> /// <summary>

View File

@@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Spectre.Console.Composition
{
/// <summary>
/// Represents a border used by tables.
/// </summary>
public abstract class Border
{
private readonly Dictionary<BorderPart, string> _lookup;
private static readonly Dictionary<BorderKind, Border> _borders = new Dictionary<BorderKind, Border>
{
{ BorderKind.None, new NoBorder() },
{ BorderKind.Ascii, new AsciiBorder() },
{ BorderKind.Square, new SquareBorder() },
{ BorderKind.Rounded, new RoundedBorder() },
};
/// <summary>
/// Initializes a new instance of the <see cref="Border"/> class.
/// </summary>
protected Border()
{
_lookup = Initialize();
}
/// <summary>
/// Gets a <see cref="Border"/> represented by the specified <see cref="BorderKind"/>.
/// </summary>
/// <param name="kind">The kind of border to get.</param>
/// <returns>A <see cref="Border"/> instance representing the specified <see cref="BorderKind"/>.</returns>
public static Border GetBorder(BorderKind kind)
{
if (!_borders.TryGetValue(kind, out var border))
{
throw new InvalidOperationException("Unknown border kind");
}
return border;
}
private Dictionary<BorderPart, string> Initialize()
{
var lookup = new Dictionary<BorderPart, string>();
foreach (BorderPart part in Enum.GetValues(typeof(BorderPart)))
{
var text = GetBoxPart(part);
if (text.Length > 1)
{
throw new InvalidOperationException("A box part cannot contain more than one character.");
}
lookup.Add(part, GetBoxPart(part));
}
return lookup;
}
/// <summary>
/// Gets the string representation of a specific border part.
/// </summary>
/// <param name="part">The part to get a string representation for.</param>
/// <param name="count">The number of repetitions.</param>
/// <returns>A string representation of the specified border part.</returns>
public string GetPart(BorderPart part, int count)
{
// TODO: This need some optimization...
return string.Join(string.Empty, Enumerable.Repeat(GetBoxPart(part)[0], count));
}
/// <summary>
/// Gets the string representation of a specific border part.
/// </summary>
/// <param name="part">The part to get a string representation for.</param>
/// <returns>A string representation of the specified border part.</returns>
public string GetPart(BorderPart part)
{
return _lookup[part].ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// Gets the character representing the specified border part.
/// </summary>
/// <param name="part">The part to get the character representation for.</param>
/// <returns>A character representation of the specified border part.</returns>
protected abstract string GetBoxPart(BorderPart part);
}
}

View File

@@ -0,0 +1,28 @@
namespace Spectre.Console
{
/// <summary>
/// Represents different kinds of borders.
/// </summary>
public enum BorderKind
{
/// <summary>
/// No border.
/// </summary>
None = 0,
/// <summary>
/// A square border.
/// </summary>
Square = 1,
/// <summary>
/// An old school ASCII border.
/// </summary>
Ascii = 2,
/// <summary>
/// A rounded border.
/// </summary>
Rounded = 3,
}
}

View File

@@ -0,0 +1,98 @@
namespace Spectre.Console.Composition
{
/// <summary>
/// Represents the different border parts.
/// </summary>
public enum BorderPart
{
/// <summary>
/// The top left part of a header.
/// </summary>
HeaderTopLeft,
/// <summary>
/// The top part of a header.
/// </summary>
HeaderTop,
/// <summary>
/// The top separator part of a header.
/// </summary>
HeaderTopSeparator,
/// <summary>
/// The top right part of a header.
/// </summary>
HeaderTopRight,
/// <summary>
/// The left part of a header.
/// </summary>
HeaderLeft,
/// <summary>
/// A header separator.
/// </summary>
HeaderSeparator,
/// <summary>
/// The right part of a header.
/// </summary>
HeaderRight,
/// <summary>
/// The bottom left part of a header.
/// </summary>
HeaderBottomLeft,
/// <summary>
/// The bottom part of a header.
/// </summary>
HeaderBottom,
/// <summary>
/// The bottom separator part of a header.
/// </summary>
HeaderBottomSeparator,
/// <summary>
/// The bottom right part of a header.
/// </summary>
HeaderBottomRight,
/// <summary>
/// The left part of a cell.
/// </summary>
CellLeft,
/// <summary>
/// A cell separator.
/// </summary>
CellSeparator,
/// <summary>
/// The right part of a cell.
/// </summary>
CellRight,
/// <summary>
/// The bottom left part of a footer.
/// </summary>
FooterBottomLeft,
/// <summary>
/// The bottom part of a footer.
/// </summary>
FooterBottom,
/// <summary>
/// The bottom separator part of a footer.
/// </summary>
FooterBottomSeparator,
/// <summary>
/// The bottom right part of a footer.
/// </summary>
FooterBottomRight,
}
}

View File

@@ -0,0 +1,37 @@
using System;
namespace Spectre.Console.Composition
{
/// <summary>
/// Represents an old school ASCII border.
/// </summary>
public sealed class AsciiBorder : Border
{
/// <inheritdoc/>
protected override string 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.CellRight => "|",
BorderPart.FooterBottomLeft => "+",
BorderPart.FooterBottom => "-",
BorderPart.FooterBottomSeparator => "-",
BorderPart.FooterBottomRight => "+",
_ => throw new InvalidOperationException("Unknown box part."),
};
}
}
}

View File

@@ -0,0 +1,10 @@
namespace Spectre.Console.Composition
{
internal sealed class NoBorder : Border
{
protected override string GetBoxPart(BorderPart part)
{
return " ";
}
}
}

View File

@@ -0,0 +1,37 @@
using System;
namespace Spectre.Console.Composition
{
/// <summary>
/// Represents a rounded border.
/// </summary>
public sealed class RoundedBorder : Border
{
/// <inheritdoc/>
protected override string 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.CellRight => "│",
BorderPart.FooterBottomLeft => "╰",
BorderPart.FooterBottom => "─",
BorderPart.FooterBottomSeparator => "┴",
BorderPart.FooterBottomRight => "╯",
_ => throw new InvalidOperationException("Unknown box part."),
};
}
}
}

View File

@@ -0,0 +1,37 @@
using System;
namespace Spectre.Console.Composition
{
/// <summary>
/// Represents a square border.
/// </summary>
public sealed class SquareBorder : Border
{
/// <inheritdoc/>
protected override string 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.CellRight => "│",
BorderPart.FooterBottomLeft => "└",
BorderPart.FooterBottom => "─",
BorderPart.FooterBottomSeparator => "┴",
BorderPart.FooterBottomRight => "┘",
_ => throw new InvalidOperationException("Unknown box part."),
};
}
}
}

View File

@@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
using System.Text;
using Spectre.Console.Composition;
namespace Spectre.Console
{
/// <summary>
/// Represents a grid.
/// </summary>
public sealed class Grid : IRenderable
{
private readonly Table _table;
/// <summary>
/// Initializes a new instance of the <see cref="Grid"/> class.
/// </summary>
public Grid()
{
_table = new Table
{
Border = BorderKind.None,
ShowHeaders = false,
};
}
/// <inheritdoc/>
public Measurement Measure(Encoding encoding, int maxWidth)
{
return ((IRenderable)_table).Measure(encoding, maxWidth);
}
/// <inheritdoc/>
public IEnumerable<Segment> Render(Encoding encoding, int width)
{
return ((IRenderable)_table).Render(encoding, width);
}
/// <summary>
/// Adds a column to the grid.
/// </summary>
public void AddColumn()
{
_table.AddColumn(string.Empty);
}
/// <summary>
/// Adds a column to the grid.
/// </summary>
/// <param name="column">The column to add.</param>
public void AddColumn(GridColumn column)
{
if (column is null)
{
throw new ArgumentNullException(nameof(column));
}
_table.AddColumn(new TableColumn(string.Empty)
{
Width = column.Width,
NoWrap = column.NoWrap,
LeftPadding = 0,
RightPadding = 1,
});
}
/// <summary>
/// Adds a new row to the grid.
/// </summary>
/// <param name="columns">The columns to add.</param>
public void AddRow(params string[] columns)
{
if (columns is null)
{
throw new ArgumentNullException(nameof(columns));
}
if (columns.Length < _table.ColumnCount)
{
throw new InvalidOperationException("The number of row columns are less than the number of grid columns.");
}
if (columns.Length > _table.ColumnCount)
{
throw new InvalidOperationException("The number of row columns are greater than the number of grid columns.");
}
_table.AddRow(columns);
}
}
}

View File

@@ -0,0 +1,20 @@
namespace Spectre.Console
{
/// <summary>
/// Represents a grid column.
/// </summary>
public sealed class GridColumn
{
/// <summary>
/// Gets or sets the width of the column.
/// If <c>null</c>, the column will adapt to it's contents.
/// </summary>
public int? Width { get; set; }
/// <summary>
/// Gets or sets a value indicating whether wrapping of
/// text within the column should be prevented.
/// </summary>
public bool NoWrap { get; set; }
}
}

View File

@@ -13,8 +13,8 @@ namespace Spectre.Console.Composition
/// </summary> /// </summary>
/// <param name="encoding">The encoding to use.</param> /// <param name="encoding">The encoding to use.</param>
/// <param name="maxWidth">The maximum allowed width.</param> /// <param name="maxWidth">The maximum allowed width.</param>
/// <returns>The width of the object.</returns> /// <returns>The minimum and maximum width of the object.</returns>
int Measure(Encoding encoding, int maxWidth); Measurement Measure(Encoding encoding, int maxWidth);
/// <summary> /// <summary>
/// Renders the object. /// Renders the object.

View File

@@ -0,0 +1,77 @@
using System;
namespace Spectre.Console.Composition
{
/// <summary>
/// Represents a measurement.
/// </summary>
public struct Measurement : IEquatable<Measurement>
{
/// <summary>
/// Gets the minimum width.
/// </summary>
public int Min { get; }
/// <summary>
/// Gets the maximum width.
/// </summary>
public int Max { get; }
/// <summary>
/// Initializes a new instance of the <see cref="Measurement"/> struct.
/// </summary>
/// <param name="min">The minimum width.</param>
/// <param name="max">The maximum width.</param>
public Measurement(int min, int max)
{
Min = min;
Max = max;
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
return obj is Measurement measurement && Equals(measurement);
}
/// <inheritdoc/>
public override int GetHashCode()
{
unchecked
{
var hash = (int)2166136261;
hash = (hash * 16777619) ^ Min.GetHashCode();
hash = (hash * 16777619) ^ Max.GetHashCode();
return hash;
}
}
/// <inheritdoc/>
public bool Equals(Measurement other)
{
return Min == other.Min && Max == other.Max;
}
/// <summary>
/// Checks if two <see cref="Measurement"/> instances are equal.
/// </summary>
/// <param name="left">The first measurement instance to compare.</param>
/// <param name="right">The second measurement instance to compare.</param>
/// <returns><c>true</c> if the two measurements are equal, otherwise <c>false</c>.</returns>
public static bool operator ==(Measurement left, Measurement right)
{
return left.Equals(right);
}
/// <summary>
/// Checks if two <see cref="Measurement"/> instances are not equal.
/// </summary>
/// <param name="left">The first measurement instance to compare.</param>
/// <param name="right">The second measurement instance to compare.</param>
/// <returns><c>true</c> if the two measurements are not equal, otherwise <c>false</c>.</returns>
public static bool operator !=(Measurement left, Measurement right)
{
return !(left == right);
}
}
}

View File

@@ -13,6 +13,7 @@ namespace Spectre.Console
private readonly IRenderable _child; private readonly IRenderable _child;
private readonly bool _fit; private readonly bool _fit;
private readonly Justify _content; private readonly Justify _content;
private readonly Border _border;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="Panel"/> class. /// Initializes a new instance of the <see cref="Panel"/> class.
@@ -20,35 +21,42 @@ namespace Spectre.Console
/// <param name="child">The child.</param> /// <param name="child">The child.</param>
/// <param name="fit">Whether or not to fit the panel to it's parent.</param> /// <param name="fit">Whether or not to fit the panel to it's parent.</param>
/// <param name="content">The justification of the panel content.</param> /// <param name="content">The justification of the panel content.</param>
public Panel(IRenderable child, bool fit = false, Justify content = Justify.Left) /// <param name="border">The border to use.</param>
public Panel(
IRenderable child,
bool fit = false,
Justify content = Justify.Left,
BorderKind border = BorderKind.Square)
{ {
_child = child; _child = child ?? throw new System.ArgumentNullException(nameof(child));
_fit = fit; _fit = fit;
_content = content; _content = content;
_border = Border.GetBorder(border);
} }
/// <inheritdoc/> /// <inheritdoc/>
public int Measure(Encoding encoding, int maxWidth) Measurement IRenderable.Measure(Encoding encoding, int maxWidth)
{ {
var childWidth = _child.Measure(encoding, maxWidth); var childWidth = _child.Measure(encoding, maxWidth);
return childWidth + 4; return new Measurement(childWidth.Min + 4, childWidth.Max + 4);
} }
/// <inheritdoc/> /// <inheritdoc/>
public IEnumerable<Segment> Render(Encoding encoding, int width) IEnumerable<Segment> IRenderable.Render(Encoding encoding, int width)
{ {
var childWidth = width - 4; var childWidth = width - 4;
if (!_fit) if (!_fit)
{ {
childWidth = _child.Measure(encoding, width - 2); var measurement = _child.Measure(encoding, width - 2);
childWidth = measurement.Max;
} }
var result = new List<Segment>(); var result = new List<Segment>();
var panelWidth = childWidth + 2; var panelWidth = childWidth + 2;
result.Add(new Segment("┌")); result.Add(new Segment(_border.GetPart(BorderPart.HeaderTopLeft)));
result.Add(new Segment(new string('─', panelWidth))); result.Add(new Segment(_border.GetPart(BorderPart.HeaderTop, panelWidth)));
result.Add(new Segment("┐")); result.Add(new Segment(_border.GetPart(BorderPart.HeaderTopRight)));
result.Add(new Segment("\n")); result.Add(new Segment("\n"));
// Render the child. // Render the child.
@@ -58,13 +66,15 @@ namespace Spectre.Console
var lines = Segment.SplitLines(childSegments, childWidth); var lines = Segment.SplitLines(childSegments, childWidth);
foreach (var line in lines) foreach (var line in lines)
{ {
result.Add(new Segment("│ ")); result.Add(new Segment(_border.GetPart(BorderPart.CellLeft)));
result.Add(new Segment(" ")); // Left padding
var content = new List<Segment>(); var content = new List<Segment>();
var length = line.Sum(segment => segment.CellLength(encoding)); var length = line.Sum(segment => segment.CellLength(encoding));
if (length < childWidth) if (length < childWidth)
{ {
// Justify right side
if (_content == Justify.Right) if (_content == Justify.Right)
{ {
var diff = childWidth - length; var diff = childWidth - length;
@@ -82,6 +92,7 @@ namespace Spectre.Console
content.Add(segment.StripLineEndings()); content.Add(segment.StripLineEndings());
} }
// Justify left side
if (length < childWidth) if (length < childWidth)
{ {
if (_content == Justify.Left) if (_content == Justify.Left)
@@ -104,13 +115,14 @@ namespace Spectre.Console
result.AddRange(content); result.AddRange(content);
result.Add(new Segment(" ")); result.Add(new Segment(" "));
result.Add(new Segment(_border.GetPart(BorderPart.CellRight)));
result.Add(new Segment("\n")); result.Add(new Segment("\n"));
} }
result.Add(new Segment("└")); result.Add(new Segment(_border.GetPart(BorderPart.FooterBottomLeft)));
result.Add(new Segment(new string('─', panelWidth))); result.Add(new Segment(_border.GetPart(BorderPart.FooterBottom, panelWidth)));
result.Add(new Segment("┘")); result.Add(new Segment(_border.GetPart(BorderPart.FooterBottomRight)));
result.Add(new Segment("\n")); result.Add(new Segment("\n"));
return result; return result;

View File

@@ -211,5 +211,21 @@ namespace Spectre.Console.Composition
return lines; return lines;
} }
internal static List<List<SegmentLine>> MakeSameHeight(int cellHeight, List<List<SegmentLine>> cells)
{
foreach (var cell in cells)
{
if (cell.Count < cellHeight)
{
while (cell.Count != cellHeight)
{
cell.Add(new SegmentLine());
}
}
}
return cells;
}
} }
} }

View File

@@ -0,0 +1,168 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spectre.Console.Composition;
using Spectre.Console.Internal;
namespace Spectre.Console
{
/// <summary>
/// Represents a table.
/// </summary>
public sealed partial class Table
{
// Calculate the widths of each column, including padding, not including borders.
// Ported from Rich by Will McGugan, licensed under MIT.
// https://github.com/willmcgugan/rich/blob/527475837ebbfc427530b3ee0d4d0741d2d0fc6d/rich/table.py#L394
private List<int> CalculateColumnWidths(Encoding encoding, int maxWidth)
{
var width_ranges = _columns.Select(column => MeasureColumn(column, encoding, maxWidth));
var widths = width_ranges.Select(range => range.Max).ToList();
var tableWidth = widths.Sum();
if (ShouldExpand())
{
var ratios = _columns.Select(c => c.Ratio ?? 0).ToList();
if (ratios.Any(r => r != 0))
{
var fixedWidths = new List<int>();
foreach (var (range, column) in width_ranges.Zip(_columns, (a, b) => (a, b)))
{
fixedWidths.Add(column.IsFlexible() ? 0 : range.Max);
}
var flexMinimum = new List<int>();
foreach (var column in _columns)
{
if (column.IsFlexible())
{
flexMinimum.Add(column.Width ?? 1 + column.GetPadding());
}
else
{
flexMinimum.Add(0);
}
}
var flexibleWidth = maxWidth - fixedWidths.Sum();
var flexWidths = Ratio.Distribute(flexibleWidth, ratios, flexMinimum);
var flexWidthsIterator = flexWidths.GetEnumerator();
foreach (var (index, _, _, column) in _columns.Enumerate())
{
if (column.IsFlexible())
{
flexWidthsIterator.MoveNext();
widths[index] = fixedWidths[index] + flexWidthsIterator.Current;
}
}
}
}
tableWidth = widths.Sum();
if (tableWidth > maxWidth)
{
var wrappable = _columns.Select(c => !c.NoWrap).ToList();
widths = CollapseWidths(widths, wrappable, maxWidth);
tableWidth = widths.Sum();
// last resort, reduce columns evenly
if (tableWidth > maxWidth)
{
var excessWidth = tableWidth - maxWidth;
widths = Ratio.Reduce(excessWidth, widths.Select(w => 1).ToList(), widths, widths);
tableWidth = widths.Sum();
}
}
if (tableWidth < maxWidth && ShouldExpand())
{
var padWidths = Ratio.Distribute(maxWidth - tableWidth, widths);
widths = widths.Zip(padWidths, (a, b) => (a, b)).Select(f => f.a + f.b).ToList();
}
return widths;
}
// Reduce widths so that the total is less or equal to the max width.
// Ported from Rich by Will McGugan, licensed under MIT.
// https://github.com/willmcgugan/rich/blob/527475837ebbfc427530b3ee0d4d0741d2d0fc6d/rich/table.py#L442
private static List<int> CollapseWidths(List<int> widths, List<bool> wrappable, int maxWidth)
{
var totalWidth = widths.Sum();
var excessWidth = totalWidth - maxWidth;
if (wrappable.AnyTrue())
{
while (totalWidth > 0 && excessWidth > 0)
{
var maxColumn = widths.Zip(wrappable, (first, second) => (width: first, isWrappable: second))
.Where(x => x.isWrappable)
.Max(x => x.width);
var secondMaxColumn = widths.Zip(wrappable, (width, isWrappable) => isWrappable && width != maxColumn ? maxColumn : 0).Max();
var columnDifference = maxColumn - secondMaxColumn;
var ratios = widths.Zip(wrappable, (width, allowWrap) =>
{
if (width == maxColumn && allowWrap)
{
return 1;
}
return 0;
}).ToList();
if (!ratios.Any(x => x > 0) || columnDifference == 0)
{
break;
}
var maxReduce = widths.Select(_ => Math.Min(excessWidth, columnDifference)).ToList();
widths = Ratio.Reduce(excessWidth, ratios, maxReduce, widths);
totalWidth = widths.Sum();
excessWidth = totalWidth - maxWidth;
}
}
return widths;
}
private (int Min, int Max) MeasureColumn(TableColumn column, Encoding encoding, int maxWidth)
{
// Predetermined width?
if (column.Width != null)
{
var padding = column.GetPadding();
return (column.Width.Value + padding, column.Width.Value + padding);
}
var columnIndex = _columns.IndexOf(column);
var rows = _rows.Select(row => row[columnIndex]);
var minWidths = new List<int>();
var maxWidths = new List<int>();
foreach (var row in rows)
{
var measure = ((IRenderable)row).Measure(encoding, maxWidth);
minWidths.Add(measure.Min);
maxWidths.Add(measure.Max);
}
return (minWidths.Count > 0 ? minWidths.Max() : 1,
maxWidths.Count > 0 ? maxWidths.Max() : maxWidth);
}
private int GetExtraWidth(bool includePadding)
{
var edges = 2;
var separators = _columns.Count - 1;
var padding = includePadding ? _columns.Select(x => x.GetPadding()).Sum() : 0;
return separators + edges + padding;
}
}
}

View File

@@ -0,0 +1,317 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spectre.Console.Composition;
using Spectre.Console.Internal;
namespace Spectre.Console
{
/// <summary>
/// Represents a table.
/// </summary>
public sealed partial class Table : IRenderable
{
private readonly List<TableColumn> _columns;
private readonly List<List<Text>> _rows;
/// <summary>
/// Gets the number of columns in the table.
/// </summary>
public int ColumnCount => _columns.Count;
/// <summary>
/// Gets the number of rows in the table.
/// </summary>
public int RowCount => _rows.Count;
/// <summary>
/// Gets or sets the kind of border to use.
/// </summary>
public BorderKind Border { get; set; } = BorderKind.Square;
/// <summary>
/// Gets or sets a value indicating whether or not table headers should be shown.
/// </summary>
public bool ShowHeaders { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether or not the table should
/// fit the available space. If <c>false</c>, the table width will be
/// auto calculated. Defaults to <c>false</c>.
/// </summary>
public bool Expand { get; set; } = false;
/// <summary>
/// Gets or sets the width of the table.
/// </summary>
public int? Width { get; set; } = null;
/// <summary>
/// Initializes a new instance of the <see cref="Table"/> class.
/// </summary>
public Table()
{
_columns = new List<TableColumn>();
_rows = new List<List<Text>>();
}
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="column">The column to add.</param>
public void AddColumn(string column)
{
if (column is null)
{
throw new ArgumentNullException(nameof(column));
}
_columns.Add(new TableColumn(column));
}
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="column">The column to add.</param>
public void AddColumn(TableColumn column)
{
if (column is null)
{
throw new ArgumentNullException(nameof(column));
}
_columns.Add(column);
}
/// <summary>
/// Adds multiple columns to the table.
/// </summary>
/// <param name="columns">The columns to add.</param>
public void AddColumns(params string[] columns)
{
if (columns is null)
{
throw new ArgumentNullException(nameof(columns));
}
_columns.AddRange(columns.Select(column => new TableColumn(column)));
}
/// <summary>
/// Adds a row to the table.
/// </summary>
/// <param name="columns">The row columns to add.</param>
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());
}
/// <inheritdoc/>
Measurement IRenderable.Measure(Encoding encoding, int maxWidth)
{
if (Width != null)
{
maxWidth = Math.Min(Width.Value, maxWidth);
}
maxWidth -= GetExtraWidth(includePadding: true);
var measurements = _columns.Select(column => MeasureColumn(column, encoding, maxWidth)).ToList();
var min = measurements.Sum(x => x.Min) + GetExtraWidth(includePadding: true);
var max = Width ?? measurements.Sum(x => x.Max) + GetExtraWidth(includePadding: true);
return new Measurement(min, max);
}
/// <inheritdoc/>
IEnumerable<Segment> IRenderable.Render(Encoding encoding, int width)
{
var border = Composition.Border.GetBorder(Border);
var showBorder = Border != BorderKind.None;
var hideBorder = Border == BorderKind.None;
var maxWidth = width;
if (Width != null)
{
maxWidth = Math.Min(Width.Value, maxWidth);
}
maxWidth -= GetExtraWidth(includePadding: true);
// Calculate the column and table widths
var columnWidths = CalculateColumnWidths(encoding, maxWidth);
// Update the table width.
width = columnWidths.Sum() + GetExtraWidth(includePadding: false);
var rows = new List<List<Text>>();
if (ShowHeaders)
{
// Add columns to top of rows
rows.Add(new List<Text>(_columns.Select(c => c.Text)));
}
// Add rows.
rows.AddRange(_rows);
// Iterate all rows
var result = new List<Segment>();
foreach (var (index, firstRow, lastRow, row) in rows.Enumerate())
{
var cellHeight = 1;
// Get the list of cells for the row and calculate the cell height
var cells = new List<List<SegmentLine>>();
foreach (var (rowWidth, cell) in columnWidths.Zip(row, (f, s) => (f, s)))
{
var lines = Segment.SplitLines(((IRenderable)cell).Render(encoding, rowWidth));
cellHeight = Math.Max(cellHeight, lines.Count);
cells.Add(lines);
}
// Show top of header?
if (firstRow && showBorder)
{
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
cells = Segment.MakeSameHeight(cellHeight, cells);
foreach (var (cellIndex, firstCell, lastCell, cell) in cells.Enumerate())
{
if (firstCell && showBorder)
{
// Show left column edge
result.Add(new Segment(border.GetPart(BorderPart.CellLeft)));
}
// Pad column on left side.
if (showBorder)
{
var leftPadding = _columns[cellIndex].LeftPadding;
if (leftPadding > 0)
{
result.Add(new Segment(new string(' ', leftPadding)));
}
}
// Add content
result.AddRange(cell[cellRowIndex]);
// Pad cell content right
var length = cell[cellRowIndex].Sum(segment => segment.CellLength(encoding));
if (length < columnWidths[cellIndex])
{
result.Add(new Segment(new string(' ', columnWidths[cellIndex] - length)));
}
// Pad column on the right side
if (showBorder || (hideBorder && !lastCell))
{
var rightPadding = _columns[cellIndex].RightPadding;
if (rightPadding > 0)
{
result.Add(new Segment(new string(' ', rightPadding)));
}
}
if (lastCell && showBorder)
{
// Add right column edge
result.Add(new Segment(border.GetPart(BorderPart.CellRight)));
}
else if (showBorder || (hideBorder && !lastCell))
{
// Add column separator
result.Add(new Segment(border.GetPart(BorderPart.CellSeparator)));
}
}
result.Add(Segment.LineBreak());
}
// Show bottom of header?
if (firstRow && showBorder && ShowHeaders)
{
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());
}
// Show bottom of footer?
if (lastRow && showBorder)
{
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 bool ShouldExpand()
{
return Expand || Width != null;
}
}
}

View File

@@ -0,0 +1,67 @@
using System;
namespace Spectre.Console
{
/// <summary>
/// Represents a table column.
/// </summary>
public sealed class TableColumn
{
/// <summary>
/// Gets the text associated with the column.
/// </summary>
public Text Text { get; }
/// <summary>
/// Gets or sets the width of the column.
/// If <c>null</c>, the column will adapt to it's contents.
/// </summary>
public int? Width { get; set; }
/// <summary>
/// Gets or sets the left padding.
/// </summary>
public int LeftPadding { get; set; }
/// <summary>
/// Gets or sets the right padding.
/// </summary>
public int RightPadding { get; set; }
/// <summary>
/// Gets or sets the ratio to use when calculating column width.
/// If <c>null</c>, the column will adapt to it's contents.
/// </summary>
public int? Ratio { get; set; }
/// <summary>
/// Gets or sets a value indicating whether wrapping of
/// text within the column should be prevented.
/// </summary>
public bool NoWrap { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="TableColumn"/> class.
/// </summary>
/// <param name="text">The table column text.</param>
public TableColumn(string text)
{
Text = Text.New(text ?? throw new ArgumentNullException(nameof(text)));
Width = null;
LeftPadding = 1;
RightPadding = 1;
Ratio = null;
NoWrap = false;
}
internal int GetPadding()
{
return LeftPadding + RightPadding;
}
internal bool IsFlexible()
{
return Width == null;
}
}
}

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -12,6 +13,7 @@ namespace Spectre.Console
/// Represents text with color and decorations. /// Represents text with color and decorations.
/// </summary> /// </summary>
[SuppressMessage("Naming", "CA1724:Type names should not match namespaces")] [SuppressMessage("Naming", "CA1724:Type names should not match namespaces")]
[DebuggerDisplay("{_text,nq}")]
public sealed class Text : IRenderable public sealed class Text : IRenderable
{ {
private readonly List<Span> _spans; private readonly List<Span> _spans;
@@ -96,17 +98,29 @@ namespace Spectre.Console
} }
/// <inheritdoc/> /// <inheritdoc/>
public int Measure(Encoding encoding, int maxWidth) Measurement IRenderable.Measure(Encoding encoding, int maxWidth)
{ {
var lines = _text.SplitLines(); var lines = Segment.SplitLines(((IRenderable)this).Render(encoding, maxWidth));
return lines.Max(x => x.CellLength(encoding)); if (lines.Count == 0)
{
return new Measurement(0, maxWidth);
}
var max = lines.Max(line => line.Length);
var min = lines.SelectMany(line => line.Select(segment => segment.Text.Length)).Max();
return new Measurement(min, max);
} }
/// <inheritdoc/> /// <inheritdoc/>
public IEnumerable<Segment> Render(Encoding encoding, int width) IEnumerable<Segment> IRenderable.Render(Encoding encoding, int width)
{ {
var result = new List<Segment>(); if (string.IsNullOrWhiteSpace(_text))
{
return Array.Empty<Segment>();
}
var result = new List<Segment>();
var segments = SplitLineBreaks(CreateSegments()); var segments = SplitLineBreaks(CreateSegments());
foreach (var (_, _, last, line) in Segment.SplitLines(segments, width).Enumerate()) foreach (var (_, _, last, line) in Segment.SplitLines(segments, width).Enumerate())
@@ -129,11 +143,11 @@ namespace Spectre.Console
{ {
// Creates individual segments of line breaks. // Creates individual segments of line breaks.
var result = new List<Segment>(); var result = new List<Segment>();
var queue = new Queue<Segment>(segments); var queue = new Stack<Segment>(segments.Reverse());
while (queue.Count > 0) while (queue.Count > 0)
{ {
var segment = queue.Dequeue(); var segment = queue.Pop();
var index = segment.Text.IndexOf("\n", StringComparison.OrdinalIgnoreCase); var index = segment.Text.IndexOf("\n", StringComparison.OrdinalIgnoreCase);
if (index == -1) if (index == -1)
@@ -149,7 +163,7 @@ namespace Spectre.Console
} }
result.Add(Segment.LineBreak()); result.Add(Segment.LineBreak());
queue.Enqueue(new Segment(second.Text.Substring(1), second.Style)); queue.Push(new Segment(second.Text.Substring(1), second.Style));
} }
} }
@@ -167,10 +181,8 @@ namespace Spectre.Console
// Create a span list. // Create a span list.
var spans = new List<(int Offset, bool Leaving, int Style)>(); var spans = new List<(int Offset, bool Leaving, int Style)>();
spans.Add((0, false, 0));
spans.AddRange(_spans.SelectIndex((span, index) => (span.Start, false, index + 1))); spans.AddRange(_spans.SelectIndex((span, index) => (span.Start, false, index + 1)));
spans.AddRange(_spans.SelectIndex((span, index) => (span.End, true, index + 1))); spans.AddRange(_spans.SelectIndex((span, index) => (span.End, true, index + 1)));
spans.Add((_text.Length, true, 0));
spans = spans.OrderBy(x => x.Offset).ThenBy(x => !x.Leaving).ToList(); spans = spans.OrderBy(x => x.Offset).ThenBy(x => !x.Leaving).ToList();
// Keep track of applied styles using a stack // Keep track of applied styles using a stack

View File

@@ -32,12 +32,12 @@ namespace Spectre.Console.Internal
new Regex("bvterm"), // Bitvise SSH Client 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. // Github action doesn't setup a correct PTY but supports ANSI.
if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("GITHUB_ACTION"))) if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("GITHUB_ACTION")))
{ {
return true; return (true, false);
} }
// Running on Windows? // Running on Windows?
@@ -47,10 +47,11 @@ namespace Spectre.Console.Internal
var conEmu = Environment.GetEnvironmentVariable("ConEmuANSI"); var conEmu = Environment.GetEnvironmentVariable("ConEmuANSI");
if (!string.IsNullOrEmpty(conEmu) && conEmu.Equals("On", StringComparison.OrdinalIgnoreCase)) 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. // 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))) 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")] [SuppressMessage("Design", "CA1060:Move pinvokes to native methods class")]
@@ -91,8 +92,10 @@ namespace Spectre.Console.Internal
public static extern uint GetLastError(); public static extern uint GetLastError();
[SuppressMessage("Design", "CA1031:Do not catch general exception types")] [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 try
{ {
var @out = GetStdHandle(STD_OUTPUT_HANDLE); var @out = GetStdHandle(STD_OUTPUT_HANDLE);
@@ -104,6 +107,8 @@ namespace Spectre.Console.Internal
if ((mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) == 0) if ((mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) == 0)
{ {
isLegacy = true;
if (!upgrade) if (!upgrade)
{ {
return false; return false;

View File

@@ -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)); _out = @out ?? throw new ArgumentNullException(nameof(@out));
_system = system; _system = system;
Capabilities = new Capabilities(true, system); Capabilities = new Capabilities(true, system, legacyConsole);
Encoding = @out.IsStandardOut() ? System.Console.OutputEncoding : Encoding.UTF8; Encoding = @out.IsStandardOut() ? System.Console.OutputEncoding : Encoding.UTF8;
Foreground = Color.Default; Foreground = Color.Default;
Background = Color.Default; Background = Color.Default;
@@ -60,12 +60,19 @@ namespace Spectre.Console.Internal
return; return;
} }
_out.Write(AnsiBuilder.GetAnsi( var parts = text.NormalizeLineEndings().Split(new[] { '\n' });
_system, foreach (var (_, _, last, part) in parts.Enumerate())
text.NormalizeLineEndings(native: true), {
Decoration, if (!string.IsNullOrEmpty(part))
Foreground, {
Background)); _out.Write(AnsiBuilder.GetAnsi(_system, part, Decoration, Foreground, Background));
}
if (!last)
{
_out.Write(Environment.NewLine);
}
}
} }
} }
} }

View File

@@ -19,7 +19,7 @@ namespace Spectre.Console.Internal
{ {
if (supportsAnsi) if (supportsAnsi)
{ {
var regex = new Regex("^Microsoft Windows (?'major'[0-9]*).(?'minor'[0-9]*).(?'build'[0-9]*)$"); var regex = new Regex("^Microsoft Windows (?'major'[0-9]*).(?'minor'[0-9]*).(?'build'[0-9]*)\\s*$");
var match = regex.Match(RuntimeInformation.OSDescription); var match = regex.Match(RuntimeInformation.OSDescription);
if (match.Success && int.TryParse(match.Groups["major"].Value, out var major)) if (match.Success && int.TryParse(match.Groups["major"].Value, out var major))
{ {

View File

@@ -1,4 +1,5 @@
using System; using System;
using System.Runtime.InteropServices;
namespace Spectre.Console.Internal namespace Spectre.Console.Internal
{ {
@@ -13,9 +14,41 @@ namespace Spectre.Console.Internal
var buffer = settings.Out ?? System.Console.Out; var buffer = settings.Out ?? System.Console.Out;
var supportsAnsi = settings.Ansi == AnsiSupport.Detect var supportsAnsi = settings.Ansi == AnsiSupport.Yes;
? AnsiDetector.Detect(true) var legacyConsole = false;
: settings.Ansi == AnsiSupport.Yes;
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 var colorSystem = settings.ColorSystem == ColorSystemSupport.Detect
? ColorSystemDetector.Detect(supportsAnsi) ? ColorSystemDetector.Detect(supportsAnsi)
@@ -23,13 +56,13 @@ namespace Spectre.Console.Internal
if (supportsAnsi) if (supportsAnsi)
{ {
return new AnsiConsoleRenderer(buffer, colorSystem) return new AnsiConsoleRenderer(buffer, colorSystem, legacyConsole)
{ {
Decoration = Decoration.None, Decoration = Decoration.None,
}; };
} }
return new FallbackConsoleRenderer(buffer, colorSystem); return new FallbackConsoleRenderer(buffer, colorSystem, legacyConsole);
} }
} }
} }

View File

@@ -6,6 +6,19 @@ namespace Spectre.Console.Internal
{ {
internal static class EnumerableExtensions internal static class EnumerableExtensions
{ {
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
{
action(item);
}
}
public static bool AnyTrue(this IEnumerable<bool> source)
{
return source.Any(b => b);
}
public static IEnumerable<(int Index, bool First, bool Last, T Item)> Enumerate<T>(this IEnumerable<T> source) public static IEnumerable<(int Index, bool First, bool Last, T Item)> Enumerate<T>(this IEnumerable<T> source)
{ {
if (source is null) if (source is null)
@@ -40,5 +53,18 @@ namespace Spectre.Console.Internal
{ {
return source.Select((value, index) => func(value, index)); return source.Select((value, index) => func(value, index));
} }
public static IEnumerable<(TFirst First, TSecond Second)> Zip<TFirst, TSecond>(
this IEnumerable<TFirst> source, IEnumerable<TSecond> first)
{
return source.Zip(first, (first, second) => (first, second));
}
public static IEnumerable<(TFirst First, TSecond Second, TThird Third)> Zip<TFirst, TSecond, TThird>(
this IEnumerable<TFirst> first, IEnumerable<TSecond> second, IEnumerable<TThird> third)
{
return first.Zip(second, (a, b) => (a, b))
.Zip(third, (a, b) => (a.a, a.b, b));
}
} }
} }

View File

@@ -85,7 +85,7 @@ namespace Spectre.Console.Internal
} }
} }
public FallbackConsoleRenderer(TextWriter @out, ColorSystem system) public FallbackConsoleRenderer(TextWriter @out, ColorSystem system, bool legacyConsole)
{ {
_out = @out; _out = @out;
_system = system; _system = system;
@@ -105,7 +105,7 @@ namespace Spectre.Console.Internal
Encoding = Encoding.UTF8; Encoding = Encoding.UTF8;
} }
Capabilities = new Capabilities(false, _system); Capabilities = new Capabilities(false, _system, legacyConsole);
} }
public void Write(string text) public void Write(string text)

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
namespace Spectre.Console.Internal namespace Spectre.Console.Internal
{ {
@@ -35,7 +36,7 @@ namespace Spectre.Console.Internal
else if (token.Kind == MarkupTokenKind.Text) else if (token.Kind == MarkupTokenKind.Text)
{ {
// Get the effecive style. // Get the effecive style.
var effectiveStyle = style.Combine(stack); var effectiveStyle = style.Combine(stack.Reverse());
result.Append(token.Value, effectiveStyle); result.Append(token.Value, effectiveStyle);
} }
else else

View File

@@ -18,12 +18,7 @@ namespace Spectre.Console.Internal
public static bool TryParse(string text, out Style style) public static bool TryParse(string text, out Style style)
{ {
style = Parse(text, out var error); style = Parse(text, out var error);
if (error != null) return error == null;
{
return false;
}
return true;
} }
private static Style Parse(string text, out string error) private static Style Parse(string text, out string error)

View File

@@ -0,0 +1,75 @@
// Ported from Rich by Will McGugan, licensed under MIT.
// https://github.com/willmcgugan/rich/blob/527475837ebbfc427530b3ee0d4d0741d2d0fc6d/rich/_ratio.py
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Spectre.Console.Internal
{
internal static class Ratio
{
public static List<int> Reduce(int total, List<int> ratios, List<int> maximums, List<int> values)
{
ratios = ratios.Zip(maximums, (a, b) => (ratio: a, max: b)).Select(a => a.max > 0 ? a.ratio : 0).ToList();
var totalRatio = ratios.Sum();
if (totalRatio == 0)
{
return values;
}
var totalRemaining = total;
var result = new List<int>();
foreach (var (ratio, maximum, value) in ratios.Zip(maximums, values))
{
if (ratio > 0 && totalRatio > 0)
{
var distributed = (int)Math.Min(maximum, Math.Round(ratio * totalRemaining / (double)totalRatio));
result.Add(value - distributed);
totalRemaining -= distributed;
totalRatio -= ratio;
}
else
{
result.Add(value);
}
}
return result;
}
public static List<int> Distribute(int total, List<int> ratios, List<int> minimums = null)
{
if (minimums != null)
{
ratios = ratios.Zip(minimums, (a, b) => (ratio: a, min: b)).Select(a => a.min > 0 ? a.ratio : 0).ToList();
}
var totalRatio = ratios.Sum();
Debug.Assert(totalRatio > 0, "Sum or ratios must be > 0");
var totalRemaining = total;
var distributedTotal = new List<int>();
if (minimums == null)
{
minimums = ratios.Select(_ => 0).ToList();
}
foreach (var (ratio, minimum) in ratios.Zip(minimums, (a, b) => (a, b)))
{
var distributed = (totalRatio > 0)
? Math.Max(minimum, (int)Math.Ceiling(ratio * totalRemaining / (double)totalRatio))
: totalRemaining;
distributedTotal.Add(distributed);
totalRatio -= ratio;
totalRemaining -= distributed;
}
return distributedTotal;
}
}
}

View File

@@ -6,6 +6,7 @@
<ItemGroup> <ItemGroup>
<AdditionalFiles Include="..\stylecop.json" Link="stylecop.json" /> <AdditionalFiles Include="..\stylecop.json" Link="stylecop.json" />
<None Include="../../gfx/small-logo.png" Pack="true" PackagePath="\" Link="Properties/small-logo.png" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -21,6 +22,9 @@
<Compile Update="ConsoleExtensions.*.cs"> <Compile Update="ConsoleExtensions.*.cs">
<DependentUpon>ConsoleExtensions.cs</DependentUpon> <DependentUpon>ConsoleExtensions.cs</DependentUpon>
</Compile> </Compile>
<Compile Update="**/Table.*.cs">
<DependentUpon>**/Table.cs</DependentUpon>
</Compile>
</ItemGroup> </ItemGroup>