pub mod extract;
pub mod ir;
pub mod layout;
pub mod materialize;
pub mod measure;
pub mod paint;
pub mod theme;
pub mod types;
use crate::{ast::Diagram, builder::types::OutputConfig, error::DiagramResult};
use lievisual::geometry::PathSeg;
use lievisual::geometry::Transform;
use lievisual::scene::{Element, SceneNode};
use lievisual::text::{TextAlign, TextBaseline};
pub fn build_diagram(diagram: &Diagram) -> DiagramResult<lievisual::Scene> {
build_diagram_with_config(diagram, &OutputConfig::default())
}
pub fn build_diagram_with_config(
diagram: &Diagram,
config: &OutputConfig,
) -> DiagramResult<lievisual::Scene> {
let ug = extract::run(diagram)?;
let ug = measure::measure_all(ug);
let (gg, style) = layout::engine::run(&ug)
.map_err(|e| crate::error::DiagramError::RenderError(format!("layout failed: {e}")))?;
let sg = materialize::run(&gg, &style);
let scene = paint::run(&sg);
let (nodes, w, h) = fit_to_canvas(scene.nodes, config);
let mut out = lievisual::Scene::new(w, h);
out.background = config.background;
out.nodes.extend(nodes);
Ok(out)
}
fn compute_bbox(elements: &[SceneNode]) -> Option<(f64, f64, f64, f64)> {
let mut min_x: Option<f64> = None;
let mut min_y: Option<f64> = None;
let mut max_x: Option<f64> = None;
let mut max_y: Option<f64> = None;
for element in elements {
macro_rules! expand {
($x:expr, $y:expr) => {
let x = $x;
let y = $y;
if min_x.is_none() || x < min_x.unwrap() {
min_x = Some(x);
}
if min_y.is_none() || y < min_y.unwrap() {
min_y = Some(y);
}
if max_x.is_none() || x > max_x.unwrap() {
max_x = Some(x);
}
if max_y.is_none() || y > max_y.unwrap() {
max_y = Some(y);
}
};
}
match &element.element {
Element::Rect { rect, .. } | Element::RoundedRect { rect, .. } => {
expand!(rect.min_x(), rect.min_y());
expand!(rect.max_x(), rect.max_y());
}
Element::Circle { center, radius, .. } => {
expand!(center.x - radius, center.y - radius);
expand!(center.x + radius, center.y + radius);
}
Element::Ellipse { center, radii, .. } | Element::Arc { center, radii, .. } => {
expand!(center.x - radii.x, center.y - radii.y);
expand!(center.x + radii.x, center.y + radii.y);
}
Element::Pie { center, radius, .. } => {
expand!(center.x - radius, center.y - radius);
expand!(center.x + radius, center.y + radius);
}
Element::Line { start, end, .. } => {
expand!(start.x, start.y);
expand!(end.x, end.y);
}
Element::Polyline { points, .. } | Element::Polygon { points, .. } => {
for p in points {
expand!(p.x, p.y);
}
}
Element::Path { path, .. } | Element::GradientPath { path, .. } => {
for seg in path.segments() {
match seg {
PathSeg::Line(line) => {
expand!(line.p0.x, line.p0.y);
expand!(line.p1.x, line.p1.y);
}
PathSeg::Quad(quad) => {
expand!(quad.p0.x, quad.p0.y);
expand!(quad.p1.x, quad.p1.y);
expand!(quad.p2.x, quad.p2.y);
}
PathSeg::Cubic(cubic) => {
expand!(cubic.p0.x, cubic.p0.y);
expand!(cubic.p1.x, cubic.p1.y);
expand!(cubic.p2.x, cubic.p2.y);
expand!(cubic.p3.x, cubic.p3.y);
}
}
}
}
Element::Text {
position,
layout,
style,
..
} => {
let tw = layout
.as_ref()
.map(|l| l.width)
.unwrap_or(style.font_size * 4.0);
let th = layout.as_ref().map(|l| l.height).unwrap_or(style.font_size);
let (tx0, tx1) = match style.align {
TextAlign::Left | TextAlign::Justify => (position.x, position.x + tw),
TextAlign::Center => (position.x - tw / 2.0, position.x + tw / 2.0),
TextAlign::Right => (position.x - tw, position.x),
};
let (ty0, ty1) = match style.baseline {
TextBaseline::Top => (position.y, position.y + th),
TextBaseline::Middle => (position.y - th / 2.0, position.y + th / 2.0),
TextBaseline::Bottom => (position.y - th, position.y),
_ => (position.y - th * 0.8, position.y + th * 0.2),
};
expand!(tx0, ty0);
expand!(tx1, ty1);
}
Element::Image { frame, .. } => {
expand!(frame.min_x(), frame.min_y());
expand!(frame.max_x(), frame.max_y());
}
Element::Group { children } => {
if let Some((cx0, cy0, cx1, cy1)) = compute_bbox(children) {
expand!(cx0, cy0);
expand!(cx1, cy1);
}
}
}
}
match (min_x, min_y, max_x, max_y) {
(Some(x0), Some(y0), Some(x1), Some(y1)) => Some((x0, y0, x1, y1)),
_ => None,
}
}
const CANVAS_MARGIN: f64 = 8.0;
fn resolve_cfg(limit: Option<f64>, default: f64) -> f64 {
match limit {
Some(v) if v.is_finite() && v > 0.0 => v,
_ => default,
}
}
fn resolve_avail(limit: Option<f64>, default: f64) -> f64 {
match limit {
Some(v) if v.is_finite() && v > 0.0 => (v - 2.0 * CANVAS_MARGIN).max(1.0),
Some(_) => (default - 2.0 * CANVAS_MARGIN).max(1.0),
None => f64::INFINITY,
}
}
fn fit_to_canvas(elements: Vec<SceneNode>, config: &OutputConfig) -> (Vec<SceneNode>, f64, f64) {
let cfg_w = resolve_cfg(config.width, types::DEFAULT_WIDTH);
let cfg_h = resolve_cfg(config.height, types::DEFAULT_HEIGHT);
let Some((x0, y0, x1, y1)) = compute_bbox(&elements) else {
return (elements, cfg_w, cfg_h);
};
if ![x0, y0, x1, y1].iter().all(|v| v.is_finite()) {
return (elements, cfg_w, cfg_h);
}
let content_w = (x1 - x0).max(1.0);
let content_h = (y1 - y0).max(1.0);
let avail_w = resolve_avail(config.width, types::DEFAULT_WIDTH);
let avail_h = resolve_avail(config.height, types::DEFAULT_HEIGHT);
let natural = (avail_w / content_w).min(avail_h / content_h);
let natural = if natural.is_finite() { natural } else { 1.0 };
let max_scale = if config.upscale { f64::MAX } else { 1.0 };
let scale = natural.clamp(f64::MIN_POSITIVE, max_scale);
let canvas_w = content_w * scale + 2.0 * CANVAS_MARGIN;
let canvas_h = content_h * scale + 2.0 * CANVAS_MARGIN;
let offset_x = CANVAS_MARGIN - x0 * scale;
let offset_y = CANVAS_MARGIN - y0 * scale;
if offset_x.abs() < 0.5 && offset_y.abs() < 0.5 && (scale - 1.0).abs() < 0.001 {
return (elements, canvas_w, canvas_h);
}
let transform = Transform::translate(offset_x, offset_y).then(&Transform::scale(scale));
(
vec![
SceneNode::new(Element::Group { children: elements })
.with_z(0)
.with_transform(transform),
],
canvas_w,
canvas_h,
)
}
#[cfg(test)]
mod tests {
use super::*;
use lievisual::geometry::Rect;
use lievisual::scene::FillStrokeStyle;
fn rect_node(x0: f64, y0: f64, x1: f64, y1: f64) -> SceneNode {
SceneNode::new(Element::rect(
Rect::new(x0, y0, x1, y1),
FillStrokeStyle::default(),
))
}
#[test]
fn fit_to_canvas_upscale_scales_up() {
let elements = vec![rect_node(0.0, 0.0, 100.0, 100.0)];
let config = OutputConfig {
upscale: true,
..OutputConfig::default()
};
let (_, w, h) = fit_to_canvas(elements, &config);
assert!(
w > 500.0 && h > 500.0,
"upscale 应放大内容到目标尺寸,got {w}x{h}"
);
}
#[test]
fn fit_to_canvas_no_upscale_keeps_natural_size() {
let elements = vec![rect_node(0.0, 0.0, 100.0, 100.0)];
let config = OutputConfig::default();
let (_, w, h) = fit_to_canvas(elements, &config);
assert!(
w < 200.0 && h < 200.0,
"不 upscale 应保持自然尺寸,got {w}x{h}"
);
}
#[test]
fn fit_to_canvas_width_only_constraint() {
let elements = vec![rect_node(0.0, 0.0, 100.0, 100.0)];
let config = OutputConfig {
width: Some(500.0),
height: None,
upscale: true,
..OutputConfig::default()
};
let (_, w, h) = fit_to_canvas(elements, &config);
assert!((w - 500.0).abs() < 1.0, "只限宽时应放大到目标宽度,got {w}");
assert!((h - 500.0).abs() < 1.0, "高度应按比例同步放大,got {h}");
}
#[test]
fn fit_to_canvas_height_only_constraint() {
let elements = vec![rect_node(0.0, 0.0, 100.0, 100.0)];
let config = OutputConfig {
width: None,
height: Some(500.0),
upscale: true,
..OutputConfig::default()
};
let (_, w, h) = fit_to_canvas(elements, &config);
assert!((h - 500.0).abs() < 1.0, "只限高时应放大到目标高度,got {h}");
assert!((w - 500.0).abs() < 1.0, "宽度应按比例同步放大,got {w}");
}
}