Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/build-github.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ jobs:
10.0.x
11.0.x

- name: Restore locked Graphviz build artifacts
shell: pwsh
run: ./ud.ps1

# 3. Restore dependencies
- name: 3) Restore dependencies
run: dotnet restore ${{env.PATH_SLNX}}
Expand Down
34 changes: 14 additions & 20 deletions .github/workflows/dotgraph.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: DOT rendering on Windows, Linux, and macOS
name: Bundled DOT rendering on Windows, Linux, and macOS

on:
push:
Expand All @@ -11,7 +11,7 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [windows-latest, ubuntu-latest, macos-latest]
os: [windows-latest, windows-11-arm, ubuntu-24.04, ubuntu-24.04-arm, macos-15-intel, macos-15]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
Expand All @@ -20,23 +20,17 @@ jobs:
dotnet-version: |
10.0.x
11.0.x
- name: Install Graphviz on Windows
if: runner.os == 'Windows'
run: choco install graphviz --no-progress -y
- name: Install Graphviz on Linux
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y graphviz
- name: Install Graphviz on macOS
if: runner.os == 'macOS'
run: brew install graphviz
- name: Test rendering
- name: Restore locked Graphviz build artifacts
shell: pwsh
run: ./ud.ps1
- name: Test bundled renderer without installing Graphviz
run: dotnet test source/Lite.StateMachine.DotGraph.Tests -c Release --filter TestCategory!=ExternalGraphviz
- name: Test restored NuGet package with an empty PATH
shell: pwsh
run: ./scripts/Test-DotGraphPackage.ps1
- name: Test sample console and PowerShell entry points
shell: pwsh
run: |
if ($IsWindows) {
$env:GRAPHVIZ_DOT = 'C:\Program Files\Graphviz\bin\dot.exe'
} else {
$env:GRAPHVIZ_DOT = 'dot'
}
dotnet test source/Lite.StateMachine.DotGraph.Tests -c Release --verbosity normal
- name: Pack standalone renderer
run: dotnet pack source/Lite.StateMachine.DotGraph -c Release --no-build
dotnet run --project samples/Sample11.GenerateDotGraph -c Release -f net10.0 -- ./output/ci-sample11
if ($LASTEXITCODE -ne 0) { throw 'Console sample failed.' }
./samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 -SkipBuild -OutputDirectory ./output/ci-sample11-powershell
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,7 @@ sdkconfig.*
/[Dd]ocs/backup
/[Ss]andbox
/[Tt]ools

# Graphviz/font binaries are restored from the pinned manifest by ud.ps1.
/source/Lite.StateMachine.DotGraph/Assets/*.wasm
/source/Lite.StateMachine.DotGraph/Assets/*.ttf
4 changes: 4 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
<!--<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>-->
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Wasmtime" Version="50.0.1" />
<PackageVersion Include="Svg.Skia" Version="5.2.3" />
<PackageVersion Include="SkiaSharp" Version="4.148.0" />
<PackageVersion Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="4.148.0" />
<PackageVersion Include="Lite.EventIpc" Version="1.3.2" />
<PackageVersion Include="DryIoc" Version="5.4.3" />
<PackageVersion Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="5.0.0-1.25277.114" />
Expand Down
10 changes: 8 additions & 2 deletions Lite.StateMachine.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,15 @@
<Project Path="samples/Sample10.UsingEventIPC/Sample10.UsingEventIPC.csproj" Id="f89325bb-17ff-4db9-9647-92bad4e2f974" />
<Project Path="samples/Sample11.GenerateDotGraph/Sample11.GenerateDotGraph.csproj" />
</Folder>
<Folder Name="/Scripts/">
<File Path="scripts/Test-DotGraphPackage.ps1" />
<File Path="scripts/Update-Graphviz.ps1" />
</Folder>
<Folder Name="/Solution Items/">
<File Path=".github/workflows/build-github.yml" />
<File Path="build.ps1" />
<File Path="ud.ps1" />
<File Path="scripts/Update-Graphviz.ps1" />
<File Path="readme-nuget.md" />
<File Path="readme.md" />
<File Path=".editorconfig" />
Expand All @@ -21,10 +27,10 @@
<File Path="Directory.Packages.props" />
</Folder>
<Folder Name="/Tests/">
<Project Path="source/Lite.StateMachine.DotGraph.Tests/Lite.StateMachine.DotGraph.Tests.csproj" />
<Project Path="source/Lite.Statemachine.BenchmarkTests/Lite.StateMachine.BenchmarkTests.csproj" Id="de19a850-9787-485a-b4d2-4620ca204969" />
<Project Path="source/Lite.StateMachine.DotGraph.Tests/Lite.StateMachine.DotGraph.Tests.csproj" />
<Project Path="source/Lite.StateMachine.Tests/Lite.StateMachine.Tests.csproj" Id="9644caac-1ac7-49b2-a502-896ca82f7b74" />
</Folder>
<Project Path="source/Lite.StateMachine/Lite.StateMachine.csproj" />
<Project Path="source/Lite.StateMachine.DotGraph/Lite.StateMachine.DotGraph.csproj" />
<Project Path="source/Lite.StateMachine/Lite.StateMachine.csproj" />
</Solution>
11 changes: 8 additions & 3 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,14 @@ await renderer.RenderAsync(machine.ExportUml(), "machine.svg");
await renderer.RenderFileAsync("machine.dot", "machine.png", DotGraphFormat.Png);
```

The renderer requires an installed or application-supplied [Graphviz](https://graphviz.org/download/)
executable. It is independent of the core library and uses portable .NET process APIs
for Windows, Linux, and macOS. See the package README for deployment requirements.
The renderer bundles Graphviz and its execution/rasterization dependencies through
NuGet; no Graphviz installation or PATH setup is required. It is independent of the
core library. See the package README for supported platforms and backend limitations.

When building the renderer from source, PowerShell 7's `./ud.ps1` restores its
locked binary artifacts into the ignored `output` directory. Builds also perform
this restore automatically. Maintainers can explicitly upgrade with `./ud.ps1 -Latest`;
see the renderer README for checksum verification and review steps.

![Sample Composite State Image](https://raw.githubusercontent.com/SuessLabs/Lite.StateMachine/develop/docs/SampleGraphviz-1080.png)

Expand Down
80 changes: 69 additions & 11 deletions samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
.SYNOPSIS
Builds the sample, loads its DLL, and renders the same diagrams as the console app.
.EXAMPLE
./Generate-Diagrams.ps1 -DotPath 'C:/Program Files/Graphviz/bin/dot.exe'
./Generate-Diagrams.ps1
#>
#Requires -Version 7.0

[CmdletBinding()]
param(
[string] $OutputDirectory = (Join-Path $PSScriptRoot 'diagrams'),
[string] $DotPath = 'dot',
[string] $DotPath,
[ValidateSet('Debug', 'Release')]
[string] $Configuration = 'Release',
[switch] $SkipBuild
Expand All @@ -23,8 +23,9 @@ if ([Environment]::Version.Major -lt 10) {
}

$project = Join-Path $PSScriptRoot 'Sample11.GenerateDotGraph.csproj'
if (-not $SkipBuild) {
dotnet build $project -c $Configuration -f net10.0
if (-not $SkipBuild)
{
dotnet build $project -c $Configuration -f net10.0 -p:TargetFrameworks=net10.0
if ($LASTEXITCODE -ne 0) {
throw 'Sample build failed.'
}
Expand All @@ -34,6 +35,47 @@ if (-not $SkipBuild) {
$assemblyDirectory = [IO.Path]::GetFullPath(
(Join-Path $PSScriptRoot "../../output/Sample11.GenerateDotGraph/$Configuration/net10.0"))

# PowerShell does not use the sample's .deps.json automatically. These C# callbacks
# resolve its NuGet assemblies/native libraries, including on background render threads.
Add-Type -TypeDefinition @'
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
public static class Sample11DependencyLoader
{
public static void Initialize(string applicationPath)
{
var resolver = new AssemblyDependencyResolver(applicationPath);
AssemblyLoadContext.Default.Resolving += (context, name) =>
{
var path = resolver.ResolveAssemblyToPath(name);
return path == null ? null : context.LoadFromAssemblyPath(path);
};

AssemblyLoadContext.Default.ResolvingUnmanagedDll += (assembly, name) =>
{
var path = resolver.ResolveUnmanagedDllToPath(name);
return path == null ? IntPtr.Zero : NativeLibrary.Load(path);
};

// ResolvingUnmanagedDll is a fallback, after PATH lookup. Register a resolver
// on these assemblies first so another installed application's older native
// Skia/HarfBuzz cannot win over the versions in this sample's .deps.json.
foreach (var name in new[] { "SkiaSharp", "HarfBuzzSharp" })
{
var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(name));
NativeLibrary.SetDllImportResolver(assembly, (library, importingAssembly, searchPath) =>
{
var path = resolver.ResolveUnmanagedDllToPath(library);
return path == null ? IntPtr.Zero : NativeLibrary.Load(path);
});
}
}
}
'@
[Sample11DependencyLoader]::Initialize((Join-Path $assemblyDirectory 'Sample11.GenerateDotGraph.dll'))

foreach ($assemblyName in @('Lite.StateMachine.dll', 'Lite.StateMachine.DotGraph.dll', 'Sample11.GenerateDotGraph.dll'))
{
$assemblyPath = Join-Path $assemblyDirectory $assemblyName
Expand All @@ -44,23 +86,39 @@ foreach ($assemblyName in @('Lite.StateMachine.dll', 'Lite.StateMachine.DotGraph
}

$OutputDirectory = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputDirectory)

[void][IO.Directory]::CreateDirectory($OutputDirectory)
$renderer = [Lite.StateMachine.DotGraph.GraphvizRenderer]::new($DotPath, [TimeSpan]::FromSeconds(30))

$renderer = if ($DotPath) {
[Lite.StateMachine.DotGraph.GraphvizRenderer]::new($DotPath, [TimeSpan]::FromSeconds(30))
} else {
[Lite.StateMachine.DotGraph.GraphvizRenderer]::new()
}

$token = [Threading.CancellationToken]::None

foreach ($includeLegend in @($false, $true)) {
foreach ($includeLegend in @($false, $true))
{
$name = if ($includeLegend) { 'machine-legend' } else { 'machine' }

# This calls a public DLL method, not the console application's entry point.
$dot = [Sample11.GenerateDotGraph.WorkflowDiagram]::ExportDot($includeLegend)
$dot = [Sample11.GenerateDotGraph.SampleStateMachine]::ExportDot($includeLegend)

[IO.File]::WriteAllText((Join-Path $OutputDirectory "$name.dot"), $dot)

[void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.svg"),
[Lite.StateMachine.DotGraph.DotGraphFormat]::Svg, $token).GetAwaiter().GetResult()
try
{
[void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.svg"),
[Lite.StateMachine.DotGraph.DotGraphFormat]::Svg, $token).GetAwaiter().GetResult()

[void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.png"),
[Lite.StateMachine.DotGraph.DotGraphFormat]::Png, $token).GetAwaiter().GetResult()
[void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.png"),
[Lite.StateMachine.DotGraph.DotGraphFormat]::Png, $token).GetAwaiter().GetResult()
}
catch
{
Write-Host $_.Exception.ToString()
throw
}

Write-Output "Generated $name.dot, $name.svg, and $name.png in $OutputDirectory"
}
2 changes: 1 addition & 1 deletion samples/Sample11.GenerateDotGraph/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ private static async Task<int> Main(string[] args)

var renderer = new GraphvizRenderer(args.Length > 1
? args[1]
: "dot");
: null);

Directory.CreateDirectory(outputDirectory);

Expand Down
22 changes: 13 additions & 9 deletions samples/Sample11.GenerateDotGraph/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ the topology. Neither generation path runs the workflow.
## Requirements

* Install .NET 10 or 11
* Install [Graphviz](https://graphviz.org/download/).
* Add Graphviz's `bin` directory to PATH, or pass its `dot`/`dot.exe` path explicitly.
* No Graphviz installation, PATH changes, or runtime downloads are needed.
The renderer embeds Graphviz and a PNG fallback font; NuGet supplies its runtimes.

The project references the local core and renderer projects; it does not reference
or reuse the unit-test assembly.
Expand All @@ -30,7 +30,7 @@ From the repository root:
```powershell
dotnet run --project samples/Sample11.GenerateDotGraph -c Release -f net10.0 -- samples/Sample11.GenerateDotGraph/diagrams

# Optional second argument: the Graphviz executable (quote paths with spaces).
# Optional opt-in to your own Graphviz executable instead of the bundled engine:
dotnet run --project samples/Sample11.GenerateDotGraph -c Release -f net10.0 -- samples/Sample11.GenerateDotGraph/diagrams 'C:/Program Files/Graphviz/bin/dot.exe'
```

Expand All @@ -45,15 +45,19 @@ Run a fresh process to avoid conflicts with previously loaded DLL versions:
```powershell
pwsh -NoProfile -File samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1

# Optional output folder and Graphviz path:
pwsh -NoProfile -File samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 -OutputDirectory ./output/sample11-powershell -DotPath 'C:/Program Files/Graphviz/bin/dot.exe'
# Optional output folder (still uses bundled Graphviz):
pwsh -NoProfile -File samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1 -OutputDirectory ./output/sample11-powershell
```

The script builds `net10.0`, loads the sample DLL and its libraries, and calls
`WorkflowDiagram.ExportDot(bool)` directly. It then renders the returned DOT through
`SampleStateMachine.ExportDot(bool)` directly. It then renders the returned DOT through
`GraphvizRenderer`; it does not launch the sample executable. `-SkipBuild` reuses a
previous build, and `-Configuration Debug` selects Debug output instead of Release.
By default, the script writes to this sample's `diagrams` directory.
It uses the sample's `.deps.json` to resolve the renderer's NuGet/native dependencies.
SkiaSharp/HarfBuzz native imports are resolved before PATH lookup, so an older DLL
installed by another application cannot override the sample's packaged version.
`-DotPath` is only needed when explicitly opting into an external Graphviz executable.

Both generation paths produce six files, replacing existing images on success:

Expand All @@ -62,6 +66,6 @@ Both generation paths produce six files, replacing existing images on success:
| Without legend | `machine.dot` | `machine.svg` | `machine.png` |
| With legend | `machine-legend.dot` | `machine-legend.svg` | `machine-legend.png` |

The checked-in `diagrams` directory contains generated examples. DOT text is the
same from both paths; image layout may vary with the installed Graphviz version
and fonts.
The generated `diagrams` directory contains both examples. DOT text is the
same from both paths. Both paths use the same pinned Graphviz engine by default.
See the renderer README for supported platforms and bundled-backend limitations.
78 changes: 78 additions & 0 deletions scripts/Test-DotGraphPackage.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#Requires -Version 7.0
<#
.SYNOPSIS
Packs the renderer, restores a fresh NuGet consumer, and renders with an empty PATH.
#>
[CmdletBinding()]
param()

$ErrorActionPreference = 'Stop'
$repository = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
# Unix runners commonly expose dotnet through several PATH entries/symlinks.
$dotnet = (Get-Command dotnet -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source
$version = '0.0.0-bundled.' + [DateTime]::UtcNow.Ticks
$scratch = Join-Path ([IO.Path]::GetTempPath()) ('dotgraph-package-' + [Guid]::NewGuid().ToString('N'))
$feed = Join-Path $scratch 'feed'
$consumer = Join-Path $scratch 'consumer'
$publish = Join-Path $scratch 'publish'
[void][IO.Directory]::CreateDirectory($consumer)

& $dotnet pack (Join-Path $repository 'source/Lite.StateMachine.DotGraph') -c Release "-p:PackageVersion=$version" --output $feed -m:1 -p:UseSharedCompilation=false
if ($LASTEXITCODE -ne 0) { throw 'Renderer packing failed.' }

$project = @"
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Lite.StateMachine.DotGraph" Version="$version" />
</ItemGroup>
</Project>
"@
[IO.File]::WriteAllText((Join-Path $consumer 'Consumer.csproj'), $project)
[IO.File]::WriteAllText((Join-Path $consumer 'Program.cs'), @'
using Lite.StateMachine.DotGraph;
var renderer = new GraphvizRenderer();
var directory = Path.Combine(AppContext.BaseDirectory, "images");
Directory.CreateDirectory(directory);
var dot = "digraph { subgraph cluster_child { label=\"Child\"; a [label=\"Prépare\"]; a -> b [label=\"Success\"]; } b -> c; }";
await renderer.RenderAsync(dot, Path.Combine(directory, "machine.svg"));
await renderer.RenderAsync(dot, Path.Combine(directory, "machine.png"), DotGraphFormat.Png);
var svg = File.ReadAllText(Path.Combine(directory, "machine.svg"));
var png = File.ReadAllBytes(Path.Combine(directory, "machine.png"));
if (!svg.Contains("<svg") || !svg.Contains("Prépare") || !svg.Contains("Child"))
throw new Exception("SVG is missing graph content.");
if (Convert.ToHexString(png.AsSpan(0, 8)) != "89504E470D0A1A0A")
throw new Exception("Invalid PNG signature.");
Console.WriteLine("PASS: Published NuGet consumer rendered SVG and PNG with an empty PATH.");
'@)
$escapedFeed = [Security.SecurityElement]::Escape($feed)
$configPath = Join-Path $scratch 'NuGet.Config'
[IO.File]::WriteAllText($configPath, @"
<configuration>
<packageSources>
<clear />
<add key="local" value="$escapedFeed" />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
</packageSources>
</configuration>
"@)
& $dotnet restore $consumer --configfile $configPath
if ($LASTEXITCODE -ne 0) { throw 'NuGet consumer restore failed.' }
& $dotnet publish $consumer -c Release --no-restore --self-contained false --output $publish -m:1 -p:UseSharedCompilation=false
if ($LASTEXITCODE -ne 0) { throw 'NuGet consumer publish failed.' }

$savedPath = $env:PATH
try {
# Nothing, including an existing Graphviz installation, can be resolved on PATH.
$env:PATH = ''
& $dotnet (Join-Path $publish 'Consumer.dll')
if ($LASTEXITCODE -ne 0) { throw 'Published bundled rendering failed.' }
} finally {
$env:PATH = $savedPath
}
Write-Output "Smoke-test files: $scratch"
Loading
Loading