use crate::geometry::{Color, Point, Rect, Transform, Vec2};
use crate::render::Renderer;
use crate::scene::{
BlendMode, ColorMatrix, Fill, FillStrokeStyle, GradientSpread, GradientStop, LineCap, LineJoin,
LinearGradient, Scene, SketchFill, SketchFillStyle, Stroke, SweepGradient,
};
use crate::text::TextStyle;
use kurbo::Shape as _;
use std::fmt::Write;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SvgSizing {
#[default]
Fixed,
Intrinsic,
}
pub struct SvgRenderer {
buf: String,
width: f64,
height: f64,
background: Option<Color>,
gradient_id: usize,
clip_id: usize,
mask_id: usize,
filter_id: usize,
image_id: usize,
color_matrices: Vec<ColorMatrix>,
antialias_stack: Vec<bool>,
patterns: Vec<(SketchFill, ColorMatrix)>,
title: Option<String>,
description: Option<String>,
scale: Option<f64>,
sizing: SvgSizing,
style: Option<String>,
}
impl SvgRenderer {
pub fn new(width: f64, height: f64) -> Self {
Self {
buf: String::new(),
width,
height,
background: None,
gradient_id: 0,
clip_id: 0,
mask_id: 0,
filter_id: 0,
image_id: 0,
color_matrices: Vec::new(),
antialias_stack: Vec::new(),
patterns: Vec::new(),
title: None,
description: None,
scale: None,
sizing: SvgSizing::Fixed,
style: None,
}
}
#[must_use]
pub fn with_background(mut self, bg: Color) -> Self {
self.background = Some(bg);
self
}
#[must_use]
pub fn with_scale(mut self, scale: f64) -> Self {
self.scale = Some(scale);
self
}
#[must_use]
pub fn with_sizing(mut self, sizing: SvgSizing) -> Self {
self.sizing = sizing;
self
}
#[must_use]
pub fn with_style(mut self, style: impl Into<String>) -> Self {
self.style = Some(style.into());
self
}
#[must_use]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn into_string(self) -> String {
let mut out = String::new();
let scale = self.scale.unwrap_or(1.0);
let vw = self.width / scale;
let vh = self.height / scale;
let _ = write!(out, r#"<svg xmlns="http://www.w3.org/2000/svg""#);
if self.sizing == SvgSizing::Fixed {
let _ = write!(
out,
r#" width="{:.2}" height="{:.2}""#,
self.width, self.height
);
}
let _ = write!(out, r#" viewBox="0 0 {:.2} {:.2}""#, vw, vh);
if let Some(style) = &self.style {
let _ = write!(out, r#" style="{}""#, escape_attr(style));
}
let _ = writeln!(out, ">");
if let Some(t) = &self.title {
let _ = writeln!(out, "<title>{}</title>", escape_text(t));
}
if let Some(d) = &self.description {
let _ = writeln!(out, "<desc>{}</desc>", escape_text(d));
}
let _ = write!(
out,
r#"<rect x="0" y="0" width="{:.2}" height="{:.2}""#,
vw, vh
);
out.push_str(&color_attr_str(
"fill",
self.background.unwrap_or(Color::WHITE),
));
let _ = writeln!(out, "/>");
out.push_str(&self.buf);
out.push_str("</svg>\n");
out
}
fn next_gradient_id(&mut self) -> usize {
let id = self.gradient_id;
self.gradient_id += 1;
id
}
}
impl Renderer for SvgRenderer {
fn render_scene(&mut self, scene: &Scene) {
self.title = scene.title.clone();
self.description = scene.description.clone();
let scale = self
.scale
.unwrap_or(if scene.scale.is_finite() && scene.scale > 0.0 {
scene.scale
} else {
1.0
});
self.scale = Some(scale);
if self.background.is_none() {
self.background = Some(scene.background);
}
if self.width <= 0.0 {
self.width = scene.width * scale;
}
if self.height <= 0.0 {
self.height = scene.height * scale;
}
self.render_scene_ordered(scene);
}
fn draw_rect(&mut self, rect: Rect, style: &FillStrokeStyle) {
let mut el = String::new();
let _ = write!(
el,
r#"<rect x="{:.2}" y="{:.2}" width="{:.2}" height="{:.2}" "#,
rect.min_x(),
rect.min_y(),
rect.width(),
rect.height()
);
self.apply_fill_stroke(&mut el, style, rect);
let _ = writeln!(el, "/>");
self.buf.push_str(&el);
}
fn draw_circle(&mut self, center: Point, radius: f64, style: &FillStrokeStyle) {
let mut el = String::new();
let _ = write!(
el,
r#"<circle cx="{:.2}" cy="{:.2}" r="{:.2}" "#,
center.x, center.y, radius
);
self.apply_fill_stroke(&mut el, style, square_bbox(center, radius));
let _ = writeln!(el, "/>");
self.buf.push_str(&el);
}
fn draw_ellipse(&mut self, center: Point, radii: Vec2, rotation: f64, style: &FillStrokeStyle) {
let mut el = String::new();
let _ = write!(
el,
r#"<ellipse cx="{:.2}" cy="{:.2}" rx="{:.2}" ry="{:.2}" "#,
center.x, center.y, radii.x, radii.y
);
if rotation != 0.0 {
let _ = write!(
el,
r#"transform="rotate({:.2} {:.2} {:.2})" "#,
rotation.to_degrees(),
center.x,
center.y
);
}
self.apply_fill_stroke(
&mut el,
style,
square_bbox(center, radii.x.abs().max(radii.y.abs())),
);
let _ = writeln!(el, "/>");
self.buf.push_str(&el);
}
fn draw_rounded_rect(&mut self, rect: Rect, radius: f64, style: &FillStrokeStyle) {
let (x, y) = (
rect.min_x().min(rect.max_x()),
rect.min_y().min(rect.max_y()),
);
let w = (rect.max_x() - rect.min_x()).abs();
let h = (rect.max_y() - rect.min_y()).abs();
let mut el = String::new();
let _ = write!(
el,
r#"<rect x="{:.2}" y="{:.2}" width="{:.2}" height="{:.2}" rx="{:.2}" "#,
x, y, w, h, radius
);
self.apply_fill_stroke(&mut el, style, Rect::new(x, y, x + w, y + h));
let _ = writeln!(el, "/>");
self.buf.push_str(&el);
}
fn draw_line(&mut self, start: Point, end: Point, style: &Stroke) {
let mut el = String::new();
let _ = write!(
el,
r#"<line x1="{:.2}" y1="{:.2}" x2="{:.2}" y2="{:.2}" "#,
start.x, start.y, end.x, end.y
);
self.apply_stroke_only(&mut el, style);
let _ = writeln!(el, "/>");
self.buf.push_str(&el);
}
fn draw_polyline(&mut self, points: &[Point], style: &Stroke) {
let pts: Vec<String> = points
.iter()
.map(|p| format!("{:.2},{:.2}", p.x, p.y))
.collect();
let mut el = String::new();
let _ = write!(el, r#"<polyline points="{}" "#, pts.join(" "));
self.apply_stroke_only(&mut el, style);
let _ = writeln!(el, "/>");
self.buf.push_str(&el);
}
fn draw_polygon(&mut self, points: &[Point], style: &FillStrokeStyle) {
let pts: Vec<String> = points
.iter()
.map(|p| format!("{:.2},{:.2}", p.x, p.y))
.collect();
let mut el = String::new();
let _ = write!(el, r#"<polygon points="{}" "#, pts.join(" "));
self.apply_fill_stroke(&mut el, style, points_bbox(points));
let _ = writeln!(el, "/>");
self.buf.push_str(&el);
}
fn draw_arc(
&mut self,
center: Point,
radii: Vec2,
start_angle: f64,
sweep_angle: f64,
style: &Stroke,
) {
let d = arc_path_d(center, radii, start_angle, sweep_angle, false);
let mut el = String::new();
let _ = write!(el, r#"<path d="{}" "#, d);
self.apply_stroke_only(&mut el, style);
let _ = writeln!(el, "/>");
self.buf.push_str(&el);
}
fn draw_pie(
&mut self,
center: Point,
radius: f64,
start_angle: f64,
sweep_angle: f64,
style: &FillStrokeStyle,
) {
let d = arc_path_d(
center,
Vec2::new(radius, radius),
start_angle,
sweep_angle,
true,
);
let mut el = String::new();
let _ = write!(el, r#"<path d="{}" "#, d);
self.apply_fill_stroke(&mut el, style, square_bbox(center, radius));
let _ = writeln!(el, "/>");
self.buf.push_str(&el);
}
fn draw_path(&mut self, path: &kurbo::BezPath, style: &FillStrokeStyle, closed: bool) {
let d = if closed {
let mut p = path.clone();
p.close_path();
p.to_svg()
} else {
path.to_svg()
};
let mut el = String::new();
let _ = write!(el, r#"<path d="{}" "#, d);
self.apply_fill_stroke(&mut el, style, path.bounding_box());
let _ = writeln!(el, "/>");
self.buf.push_str(&el);
}
fn draw_gradient_path(
&mut self,
path: &kurbo::BezPath,
gradient: &LinearGradient,
stroke: Option<&Stroke>,
) {
let mut p = path.clone();
p.close_path();
let d = p.to_svg();
let matrix = self.current_color_matrix();
let fill = self.linear_gradient_fill(gradient, matrix);
let mut el = String::new();
let _ = write!(el, r#"<path d="{d}""#);
el.push_str(&fill);
if let Some(s) = stroke {
self.append_stroke(&mut el, s);
}
let _ = writeln!(el, "/>");
self.buf.push_str(&el);
}
fn draw_text(
&mut self,
spans: &[crate::text::RichSpan],
position: Point,
style: &TextStyle,
layout: Option<&crate::text::TextLayout>,
) {
let content = spans.iter().map(|s| s.text.as_str()).collect::<String>();
let metrics = layout.map(crate::text::layout_metrics);
let anchor = match style.align {
crate::text::TextAlign::Left | crate::text::TextAlign::Justify => "start",
crate::text::TextAlign::Center => "middle",
crate::text::TextAlign::Right => "end",
};
let (anchor_offset, alphabetic_baseline) = match &metrics {
Some(m) => (style.baseline.anchor_offset(m), m.alphabetic_baseline),
None => {
let ab = style.font_size * 0.85;
let off = match style.baseline {
crate::text::TextBaseline::Top => 0.0,
crate::text::TextBaseline::Hanging => style.font_size * 0.75,
crate::text::TextBaseline::Middle => style.font_size * 0.5,
crate::text::TextBaseline::Alphabetic => ab,
crate::text::TextBaseline::Ideographic => style.font_size * 0.9,
crate::text::TextBaseline::Bottom => style.font_size * 1.3,
};
(off, ab)
}
};
let block_top_y = position.y - anchor_offset;
let alphabetic_y = block_top_y + alphabetic_baseline;
let baseline = "alphabetic";
let fstyle = match style.font_style {
crate::text::FontStyle::Normal => "normal",
crate::text::FontStyle::Italic => "italic",
crate::text::FontStyle::Oblique => "oblique",
};
let rot = if style.rotation != 0.0 {
format!(
r#" transform="rotate({:.2} {:.2} {:.2})""#,
style.rotation.to_degrees(),
position.x,
position.y
)
} else {
String::new()
};
let lh = match style.line_height {
Some(h) => format!(r#" style="line-height:{:.2}""#, h),
None => String::new(),
};
let fwidth = if style.font_width != crate::text::FontWidth::Normal {
format!(
r#" font-stretch="{:.0}%""#,
style.font_width.ratio() * 100.0
)
} else {
String::new()
};
let letter = if style.letter_spacing != 0.0 {
format!(r#" letter-spacing="{:.2}""#, style.letter_spacing)
} else {
String::new()
};
let decoration: Vec<&str> = match (style.underline, style.strikethrough) {
(true, true) => vec!["underline", "line-through"],
(true, false) => vec!["underline"],
(false, true) => vec!["line-through"],
(false, false) => vec![],
};
let deco = if decoration.is_empty() {
String::new()
} else {
format!(r#" text-decoration="{}""#, decoration.join(" "))
};
let bshift = if style.baseline_shift != 0.0 {
format!(r#" baseline-shift="{:.2}px""#, -style.baseline_shift)
} else {
String::new()
};
if let Some(bg) = style.background_color {
let (w, h) = match &metrics {
Some(m) => (m.width, m.height),
None => {
let avg_w = style.font_size * 0.6;
(
(content.chars().count() as f64 * avg_w).max(avg_w),
style.font_size * 1.3,
)
}
};
let rx = position.x;
let ry = block_top_y;
let bx = match style.align {
crate::text::TextAlign::Right => rx - w,
crate::text::TextAlign::Center => rx - w / 2.0,
crate::text::TextAlign::Left | crate::text::TextAlign::Justify => rx,
};
let mut bg_el = String::new();
let _ = write!(
bg_el,
r#"<rect x="{:.2}" y="{:.2}" width="{:.2}" height="{:.2}""#,
bx,
ry - style.baseline_shift,
w,
h
);
bg_el.push_str(&self.color_attr("fill", bg));
bg_el.push_str("/>\n");
self.buf.push_str(&bg_el);
}
let mut el = String::new();
let _ = write!(
el,
r#"<text x="{:.2}" y="{:.2}" text-anchor="{}" dominant-baseline="{}" font-family="{}" font-size="{:.2}" font-style="{}" font-weight="{:.0}""#,
position.x,
alphabetic_y,
anchor,
baseline,
escape_attr(&style.font_family_css()),
style.font_size,
fstyle,
style.font_weight.value(),
);
el.push_str(&self.color_attr("fill", style.color));
el.push_str(&fwidth);
el.push_str(&letter);
el.push_str(&deco);
el.push_str(&lh);
el.push_str(&rot);
el.push_str(&bshift);
el.push('>');
if spans.len() > 1 || content.contains('\n') {
el.push_str(&self.rich_text_tspans(spans, position.x, style, metrics.as_ref()));
} else {
el.push_str(&escape_text(&content));
}
el.push_str("</text>\n");
self.buf.push_str(&el);
}
fn draw_image(&mut self, image: &crate::SceneImage, frame: Rect, opacity: f64) {
let data_uri = image_data_uri(&image.pixmap);
let op = if (opacity - 1.0).abs() > 1e-6 {
format!(r#" opacity="{:.3}""#, opacity)
} else {
String::new()
};
let (w, h) = match image.object_fit {
crate::ObjectFit::None => (image.pixmap.width() as f64, image.pixmap.height() as f64),
_ => (frame.width(), frame.height()),
};
let rendering = match image.quality {
crate::scene::ImageQuality::Nearest => r#" image-rendering="pixelated""#,
crate::scene::ImageQuality::Bilinear => "",
crate::scene::ImageQuality::Bicubic => r#" image-rendering="high-quality""#,
};
let (x, y) = (frame.min_x(), frame.min_y());
if image.object_fit == crate::ObjectFit::Tile {
let id = self.image_id;
self.image_id += 1;
let (iw, ih) = (image.pixmap.width() as f64, image.pixmap.height() as f64);
let (tw, th) = (frame.width(), frame.height());
let _ = write!(
self.buf,
r#"<defs><pattern id="img{id}" patternUnits="userSpaceOnUse" x="{x:.2}" y="{y:.2}" width="{iw:.2}" height="{ih:.2}"><image x="0" y="0" width="{iw:.2}" height="{ih:.2}" href="{data_uri}" preserveAspectRatio="none"{rendering}/></pattern></defs>"#
);
let _ = writeln!(
self.buf,
r#"<rect x="{x:.2}" y="{y:.2}" width="{tw:.2}" height="{th:.2}" fill="url(#img{id})"{op}/>"#
);
return;
}
let el = format!(
r#"<image x="{:.2}" y="{:.2}" width="{:.2}" height="{:.2}" href="{}" preserveAspectRatio="{}"{op}{rendering}/>"#,
frame.min_x(),
frame.min_y(),
w,
h,
data_uri,
image.preserve_aspect_ratio(),
);
self.buf.push_str(&el);
self.buf.push('\n');
}
fn push_transform(&mut self, t: Transform) {
let m = format!(
r#"<g transform="matrix({:.6} {:.6} {:.6} {:.6} {:.6} {:.6})">"#,
t.a, t.b, t.c, t.d, t.e, t.f
);
self.buf.push_str(&m);
}
fn pop_transform(&mut self) {
self.buf.push_str("</g>");
}
fn push_opacity(&mut self, opacity: f64) {
let m = format!(r#"<g opacity="{:.3}">"#, opacity);
self.buf.push_str(&m);
}
fn pop_opacity(&mut self) {
self.buf.push_str("</g>");
}
fn push_blend(&mut self, mode: BlendMode) {
match mode.css_keyword() {
Some(kw) => {
let m = format!(r#"<g style="mix-blend-mode:{kw}">"#);
self.buf.push_str(&m);
}
None => self.buf.push_str("<g>"),
}
}
fn pop_blend(&mut self) {
self.buf.push_str("</g>");
}
fn push_mask(&mut self, mask: &crate::scene::Mask) {
let id = self.mask_id;
self.mask_id += 1;
let d = mask.shape.to_bezpath().to_svg();
let fill_attr = self.mask_fill_attr(&mask.fill);
let defs = format!(
r#"<defs><mask id="mask{id}" mask-type="alpha" maskContentUnits="userSpaceOnUse"><path d="{d}"{fill_attr}/></mask></defs>"#
);
self.buf.push_str(&defs);
let m = format!(r#"<g mask="url(#mask{id})">"#);
self.buf.push_str(&m);
}
fn pop_mask(&mut self) {
self.buf.push_str("</g>");
}
fn push_filter(&mut self, filter: &crate::scene::Filter) {
let id = self.filter_id;
self.filter_id += 1;
let prim = match filter {
crate::scene::Filter::Blur { std_dev } => {
format!(r#"<feGaussianBlur stdDeviation="{std_dev:.2}"/>"#)
}
crate::scene::Filter::DropShadow {
dx,
dy,
std_dev,
color,
} => {
let opacity = if color.a == 255 {
String::new()
} else {
format!(r#" flood-opacity="{:.3}""#, color.a as f64 / 255.0)
};
format!(
r##"<feDropShadow dx="{dx:.2}" dy="{dy:.2}" stdDeviation="{std_dev:.2}" flood-color="#{:02x}{:02x}{:02x}"{opacity}/>"##,
color.r, color.g, color.b
)
}
};
let defs = format!(
r#"<defs><filter id="filter{id}" x="-50%" y="-50%" width="200%" height="200%" filterUnits="objectBoundingBox">{prim}</filter></defs>"#
);
self.buf.push_str(&defs);
let m = format!(r#"<g filter="url(#filter{id})">"#);
self.buf.push_str(&m);
}
fn pop_filter(&mut self) {
self.buf.push_str("</g>");
}
fn push_name(&mut self, name: Option<&str>) {
match name {
Some(id) => self
.buf
.push_str(&format!(r#"<g id="{}">"#, escape_attr(id))),
None => self.buf.push_str("<g>"),
}
}
fn pop_name(&mut self) {
self.buf.push_str("</g>");
}
fn push_clip(&mut self, clip: &crate::scene::Clip) {
let id = self.clip_id;
self.clip_id += 1;
let inner = match clip {
crate::scene::Clip::Rect(rect) => format!(
r#"<rect x="{:.2}" y="{:.2}" width="{:.2}" height="{:.2}"/>"#,
rect.min_x(),
rect.min_y(),
rect.width(),
rect.height()
),
crate::scene::Clip::RoundedRect { rect, radius } => format!(
r#"<rect x="{:.2}" y="{:.2}" width="{:.2}" height="{:.2}" rx="{:.2}"/>"#,
rect.min_x(),
rect.min_y(),
rect.width(),
rect.height(),
radius
),
crate::scene::Clip::Circle { center, radius } => format!(
r#"<circle cx="{:.2}" cy="{:.2}" r="{:.2}"/>"#,
center.x, center.y, radius
),
crate::scene::Clip::Ellipse {
center,
radii,
rotation,
} => {
let rot = if *rotation != 0.0 {
format!(
r#" transform="rotate({:.2} {:.2} {:.2})""#,
rotation.to_degrees(),
center.x,
center.y
)
} else {
String::new()
};
format!(
r#"<ellipse cx="{:.2}" cy="{:.2}" rx="{:.2}" ry="{:.2}"{} />"#,
center.x, center.y, radii.x, radii.y, rot
)
}
crate::scene::Clip::Path(path) => {
format!(r#"<path d="{}"/>"#, path.to_svg())
}
};
let defs = format!(
r#"<defs><clipPath id="clip{}">{}</clipPath></defs>"#,
id, inner
);
self.buf.push_str(&defs);
let m = format!(r#"<g clip-path="url(#clip{})">"#, id);
self.buf.push_str(&m);
}
fn pop_clip(&mut self) {
self.buf.push_str("</g>");
}
fn push_color_matrix(&mut self, matrix: ColorMatrix) {
let composed = match self.color_matrices.last() {
Some(outer) => matrix.then(*outer),
None => matrix,
};
self.color_matrices.push(composed);
}
fn pop_color_matrix(&mut self) {
self.color_matrices.pop();
}
fn push_antialias(&mut self, enabled: bool) {
self.antialias_stack.push(enabled);
}
fn pop_antialias(&mut self) {
self.antialias_stack.pop();
}
}
impl SvgRenderer {
fn current_color_matrix(&self) -> ColorMatrix {
self.color_matrices
.last()
.copied()
.unwrap_or(ColorMatrix::IDENTITY)
}
fn color_attr(&self, prefix: &str, c: Color) -> String {
color_attr_str(prefix, self.current_color_matrix().apply(c))
}
fn current_antialias(&self) -> bool {
self.antialias_stack.last().copied().unwrap_or(true)
}
fn append_antialias_hint(&self, el: &mut String) {
if !self.current_antialias() {
let _ = write!(el, r#" shape-rendering="crispEdges""#);
}
}
fn mask_fill_attr(&mut self, fill: &Fill) -> String {
match fill {
Fill::Sketch(sf) => color_attr_str("fill", sf.color),
Fill::SweepGradient(g) => {
color_attr_str("fill", g.sample(0.5 * (g.start_angle + g.end_angle)))
}
other => self.fill_attr(other, ColorMatrix::IDENTITY),
}
}
fn apply_fill_stroke(&mut self, el: &mut String, style: &FillStrokeStyle, bbox: Rect) {
match &style.fill {
Some(Fill::SweepGradient(g)) => {
self.emit_sweep_overlay(el, g, bbox);
let _ = write!(el, r#" fill="none""#);
}
Some(fill) => {
let matrix = self.current_color_matrix();
el.push_str(&self.fill_attr(fill, matrix));
}
None => {
let _ = write!(el, r#" fill="none""#);
}
}
if let Some(s) = &style.stroke {
self.append_stroke(el, s);
}
self.append_antialias_hint(el);
}
fn linear_gradient_fill(&mut self, g: &LinearGradient, matrix: ColorMatrix) -> String {
let gid = self.next_gradient_id();
let stops: String = g.stops.iter().map(|s| stop_svg(s, matrix)).collect();
let defs = format!(
r#"<defs><linearGradient id="grad{gid}" gradientUnits="userSpaceOnUse" x1="{:.2}" y1="{:.2}" x2="{:.2}" y2="{:.2}"{}>{stops}</linearGradient></defs>"#,
g.start.x,
g.start.y,
g.end.x,
g.end.y,
spread_attr(g.spread),
);
self.buf.push_str(&defs);
format!(r#" fill="url(#grad{gid})""#)
}
fn fill_attr(&mut self, fill: &Fill, matrix: ColorMatrix) -> String {
match fill {
Fill::Solid(c) => color_attr_str("fill", matrix.apply(*c)),
Fill::Sketch(sf) => {
let pid = self.sketch_pattern(sf, matrix);
format!(r#" fill="url(#sk{pid})""#)
}
Fill::LinearGradient(g) => self.linear_gradient_fill(g, matrix),
Fill::RadialGradient(g) => {
let gid = self.next_gradient_id();
let stops: String = g.stops.iter().map(|s| stop_svg(s, matrix)).collect();
let defs = format!(
r#"<defs><radialGradient id="grad{gid}" gradientUnits="userSpaceOnUse" cx="{:.2}" cy="{:.2}" r="{:.2}"{}>{stops}</radialGradient></defs>"#,
g.center.x,
g.center.y,
g.radius,
spread_attr(g.spread),
);
self.buf.push_str(&defs);
format!(r#" fill="url(#grad{gid})""#)
}
Fill::SweepGradient(_) => r#" fill="none""#.to_string(),
Fill::Image(f) => {
let id = self.image_id;
self.image_id += 1;
let data_uri = image_data_uri(&f.image);
let (x, y) = (f.tile.min_x(), f.tile.min_y());
let (w, h) = (f.tile.width(), f.tile.height());
let defs = format!(
r#"<defs><pattern id="img{id}" patternUnits="userSpaceOnUse" x="{x:.2}" y="{y:.2}" width="{w:.2}" height="{h:.2}"><image x="0" y="0" width="{w:.2}" height="{h:.2}" href="{data_uri}" preserveAspectRatio="none"/></pattern></defs>"#
);
self.buf.push_str(&defs);
format!(r#" fill="url(#img{id})""#)
}
}
}
fn emit_sweep_overlay(&mut self, shape: &str, g: &SweepGradient, bbox: Rect) {
let cid = self.next_gradient_id();
let _ = write!(
self.buf,
r#"<defs><clipPath id="swc{cid}">{shape}/></clipPath></defs><g clip-path="url(#swc{cid})">"#
);
let (cx, cy) = (g.center.x, g.center.y);
let x0 = bbox.min_x().min(bbox.max_x());
let x1 = bbox.min_x().max(bbox.max_x());
let y0 = bbox.min_y().min(bbox.max_y());
let y1 = bbox.min_y().max(bbox.max_y());
let r = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
.iter()
.map(|&(x, y)| (x - cx).hypot(y - cy))
.fold(1.0_f64, f64::max);
let step = std::f64::consts::TAU / SWEEP_WEDGES as f64;
let large = u8::from(step > std::f64::consts::PI);
let matrix = self.current_color_matrix();
for i in 0..SWEEP_WEDGES {
let a0 = g.start_angle + step * i as f64;
let a1 = a0 + step;
let mid = (0.5 * (a0 + a1)).rem_euclid(std::f64::consts::TAU);
let color = matrix.apply(g.sample(mid));
let (p0x, p0y) = (cx + r * a0.cos(), cy + r * a0.sin());
let (p1x, p1y) = (cx + r * a1.cos(), cy + r * a1.sin());
let fill = color_attr_str("fill", color);
let _ = write!(
self.buf,
r#"<path d="M {cx:.2} {cy:.2} L {p0x:.2} {p0y:.2} A {r:.2} {r:.2} 0 {large} 1 {p1x:.2} {p1y:.2} Z"{fill}/>"#
);
}
self.buf.push_str("</g>");
}
fn sketch_pattern(&mut self, sf: &SketchFill, matrix: ColorMatrix) -> usize {
if let Some(id) = self
.patterns
.iter()
.position(|(f, m)| f == sf && *m == matrix)
{
return id;
}
let id = self.patterns.len();
self.patterns.push((sf.clone(), matrix));
let gap = sf.gap();
let w = sf.weight();
let inset = (w * 0.5).min(gap * 0.25);
let a = inset;
let b = gap - inset;
let mid = gap * 0.5;
let angle = match sf.style {
SketchFillStyle::CrossHatch => sf.angle + 45.0,
_ => sf.angle,
};
let content = match sf.style {
SketchFillStyle::Hachure => format!(
r#"<line x1="{mid:.2}" y1="0" x2="{mid:.2}" y2="{gap:.2}"{stroke} stroke-width="{w:.2}"/>"#,
stroke = color_attr_str("stroke", matrix.apply(sf.color))
),
SketchFillStyle::CrossHatch => format!(
r#"<line x1="{mid:.2}" y1="0" x2="{mid:.2}" y2="{gap:.2}"{stroke} stroke-width="{w:.2}"/><line x1="0" y1="{mid:.2}" x2="{gap:.2}" y2="{mid:.2}"{stroke} stroke-width="{w:.2}"/>"#,
stroke = color_attr_str("stroke", matrix.apply(sf.color))
),
SketchFillStyle::Zigzag => format!(
r#"<polyline fill="none" points="{a:.2},0 {b:.2},{q:.2} {a:.2},{m:.2} {b:.2},{t:.2} {a:.2},{gap:.2}"{stroke} stroke-width="{w:.2}"/>"#,
q = gap * 0.25,
m = gap * 0.5,
t = gap * 0.75,
stroke = color_attr_str("stroke", matrix.apply(sf.color))
),
SketchFillStyle::Dots => format!(
r#"<circle cx="{mid:.2}" cy="{mid:.2}" r="{r:.2}"{fill}/>"#,
r = crate::sketch::fill::dot_radius(sf),
fill = color_attr_str("fill", matrix.apply(sf.color))
),
};
let defs = format!(
r#"<defs><pattern id="sk{id}" width="{gap:.2}" height="{gap:.2}" patternUnits="userSpaceOnUse" patternTransform="rotate({angle:.2})">{content}</pattern></defs>"#
);
self.buf.push_str(&defs);
id
}
fn apply_stroke_only(&self, el: &mut String, style: &Stroke) {
let _ = write!(el, r#" fill="none""#);
self.append_stroke(el, style);
self.append_antialias_hint(el);
}
fn append_stroke(&self, el: &mut String, s: &Stroke) {
el.push_str(&self.color_attr("stroke", s.color));
let _ = write!(
el,
r#" stroke-width="{:.2}" stroke-miterlimit="{:.2}""#,
s.width, s.miter_limit
);
let cap = match s.line_cap {
LineCap::Butt => "butt",
LineCap::Round => "round",
LineCap::Square => "square",
};
let join = match s.line_join {
LineJoin::Miter => "miter",
LineJoin::Round => "round",
LineJoin::Bevel => "bevel",
};
let _ = write!(
el,
r#" stroke-linecap="{}" stroke-linejoin="{}""#,
cap, join
);
if !s.dash_array.is_empty() {
let da = s
.dash_array
.iter()
.map(|d| format!("{:.2}", d))
.collect::<Vec<_>>()
.join(",");
let _ = write!(el, r#" stroke-dasharray="{}""#, da);
if s.dash_offset != 0.0 {
let _ = write!(el, r#" stroke-dashoffset="{:.2}""#, s.dash_offset);
}
}
}
fn rich_text_tspans(
&self,
spans: &[crate::text::RichSpan],
x: f64,
base: &TextStyle,
metrics: Option<&crate::text::TextMetrics>,
) -> String {
let line_h = base.line_height.unwrap_or_else(|| {
metrics
.filter(|m| m.line_height > 0.0)
.map_or(base.font_size * 1.2, |m| m.line_height)
});
let mut lines: Vec<Vec<(&str, &TextStyle)>> = vec![Vec::new()];
for span in spans {
for (i, seg) in span.text.split('\n').enumerate() {
if i > 0 {
lines.push(Vec::new());
}
lines
.last_mut()
.expect("lines starts with one empty line")
.push((seg, &span.style));
}
}
while lines.len() > 1 && lines.last().is_some_and(|l| l.is_empty()) {
lines.pop();
}
let mut out = String::new();
for (i, segs) in lines.iter().enumerate() {
let dy = if i == 0 { 0.0 } else { line_h };
let _ = write!(out, r#"<tspan x="{:.2}" dy="{:.2}">"#, x, dy);
if segs.is_empty() {
out.push_str("​");
} else {
for (text, span_style) in segs {
let _ = write!(out, "<tspan{}>", self.rich_span_attrs(span_style, base));
out.push_str(&escape_text(text));
out.push_str("</tspan>");
}
}
out.push_str("</tspan>");
}
out
}
fn rich_span_attrs(&self, span: &TextStyle, base: &TextStyle) -> String {
let mut attrs = String::new();
if span.font_family != base.font_family {
let _ = write!(
attrs,
r#" font-family="{}""#,
escape_attr(&span.font_family_css())
);
}
if (span.font_size - base.font_size).abs() > f64::EPSILON {
let _ = write!(attrs, r#" font-size="{:.2}""#, span.font_size);
}
if span.color != base.color {
attrs.push_str(&self.color_attr("fill", span.color));
}
if span.font_weight != base.font_weight {
let _ = write!(attrs, r#" font-weight="{:.0}""#, span.font_weight.value());
}
if span.font_style != base.font_style {
let f = match span.font_style {
crate::text::FontStyle::Normal => "normal",
crate::text::FontStyle::Italic => "italic",
crate::text::FontStyle::Oblique => "oblique",
};
let _ = write!(attrs, r#" font-style="{f}""#);
}
if span.font_width != base.font_width {
let _ = write!(
attrs,
r#" font-stretch="{:.0}%""#,
span.font_width.ratio() * 100.0
);
}
if span.letter_spacing != base.letter_spacing {
let _ = write!(attrs, r#" letter-spacing="{:.2}""#, span.letter_spacing);
}
if span.underline != base.underline || span.strikethrough != base.strikethrough {
let _ = write!(
attrs,
r#" text-decoration="{}""#,
deco_keyword(span.underline, span.strikethrough)
);
}
attrs
}
}
fn color_attr_str(prefix: &str, c: Color) -> String {
let mut s = format!(r##" {prefix}="#{:02x}{:02x}{:02x}""##, c.r, c.g, c.b);
if c.a != 255 {
s.push_str(&format!(r#" {prefix}-opacity="{:.3}""#, c.a as f64 / 255.0));
}
s
}
fn deco_keyword(underline: bool, strikethrough: bool) -> &'static str {
match (underline, strikethrough) {
(false, false) => "none",
(true, false) => "underline",
(false, true) => "line-through",
(true, true) => "underline line-through",
}
}
const SWEEP_WEDGES: usize = 120;
fn image_data_uri(pixmap: &crate::Pixmap) -> String {
format!("data:image/png;base64,{}", base64_encode(&pixmap.to_png()))
}
fn square_bbox(center: Point, r: f64) -> Rect {
Rect::new(center.x - r, center.y - r, center.x + r, center.y + r)
}
fn points_bbox(points: &[Point]) -> Rect {
let Some(first) = points.first() else {
return Rect::ZERO;
};
points
.iter()
.fold(Rect::new(first.x, first.y, first.x, first.y), |r, p| {
Rect::new(
r.min_x().min(p.x),
r.min_y().min(p.y),
r.max_x().max(p.x),
r.max_y().max(p.y),
)
})
}
fn spread_attr(spread: GradientSpread) -> &'static str {
match spread {
GradientSpread::Pad => "",
GradientSpread::Repeat => r#" spreadMethod="repeat""#,
GradientSpread::Reflect => r#" spreadMethod="reflect""#,
}
}
fn stop_svg(s: &GradientStop, matrix: ColorMatrix) -> String {
let color = matrix.apply(s.color);
let opacity = if color.a == 255 {
String::new()
} else {
format!(r#" stop-opacity="{:.3}""#, f64::from(color.a) / 255.0)
};
format!(
r##"<stop offset="{:.3}" stop-color="#{:02x}{:02x}{:02x}"{} />"##,
s.offset, color.r, color.g, color.b, opacity
)
}
fn arc_path_d(
center: Point,
radii: Vec2,
start_angle: f64,
sweep_angle: f64,
sector: bool,
) -> String {
let point_at = |angle: f64| -> (f64, f64) {
(
center.x + radii.x * angle.cos(),
center.y + radii.y * angle.sin(),
)
};
let segments: Vec<(f64, f64)> = if sweep_angle.abs() >= std::f64::consts::TAU - 1e-9 {
let half = sweep_angle / 2.0;
vec![(start_angle, half), (start_angle + half, half)]
} else {
vec![(start_angle, sweep_angle)]
};
let mut d = String::new();
let start = point_at(start_angle);
if sector {
let _ = write!(
d,
"M {:.2} {:.2} L {:.2} {:.2}",
center.x, center.y, start.0, start.1
);
} else {
let _ = write!(d, "M {:.2} {:.2}", start.0, start.1);
}
for (a, s) in segments {
let large_arc = if s.abs() > std::f64::consts::PI { 1 } else { 0 };
let sweep_flag = if s >= 0.0 { 1 } else { 0 };
let end = point_at(a + s);
let _ = write!(
d,
" A {:.2} {:.2} 0 {} {} {:.2} {:.2}",
radii.x, radii.y, large_arc, sweep_flag, end.0, end.1
);
}
if sector {
d.push_str(" Z");
}
d
}
fn escape_text(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
_ => out.push(c),
}
}
out
}
fn escape_attr(s: &str) -> String {
escape_text(s).replace('"', """)
}
fn base64_encode(data: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b0 = chunk[0] as u32;
let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
let n = (b0 << 16) | (b1 << 8) | b2;
out.push(ALPHABET[((n >> 18) & 0x3f) as usize] as char);
out.push(ALPHABET[((n >> 12) & 0x3f) as usize] as char);
if chunk.len() > 1 {
out.push(ALPHABET[((n >> 6) & 0x3f) as usize] as char);
} else {
out.push('=');
}
if chunk.len() > 2 {
out.push(ALPHABET[(n & 0x3f) as usize] as char);
} else {
out.push('=');
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geometry::Vec2;
use crate::scene::{Element, Scene, SceneNode};
use crate::text::{FontStyle, FontWeight, FontWidth, TextAlign, TextBaseline, TextStyle};
fn render(scene: &Scene) -> String {
let mut svg = SvgRenderer::new(scene.width, scene.height).with_background(scene.background);
scene.render(&mut svg);
svg.into_string()
}
#[test]
fn blend_mode_emits_mix_blend_mode() {
let mut scene = Scene::new(20.0, 20.0);
scene.push_node(
SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 20.0, 20.0),
FillStrokeStyle::fill(Color::rgb(0x80, 0x80, 0x80)),
))
.with_blend_mode(BlendMode::Multiply),
);
let out = render(&scene);
assert!(out.contains("mix-blend-mode:multiply"), "{out}");
let mut plain = Scene::new(20.0, 20.0);
plain.push(Element::rect(
Rect::new(0.0, 0.0, 20.0, 20.0),
FillStrokeStyle::fill(Color::BLACK),
));
assert!(!render(&plain).contains("mix-blend-mode"));
}
#[test]
fn porter_duff_degrades_without_mix_blend_mode() {
let mut scene = Scene::new(20.0, 20.0);
scene.push_node(
SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
FillStrokeStyle::fill(Color::BLACK),
))
.with_blend_mode(BlendMode::Clear),
);
let out = render(&scene);
assert!(!out.contains("mix-blend-mode"), "{out}");
assert!(BlendMode::Clear.is_porter_duff());
assert!(!BlendMode::Multiply.is_porter_duff());
}
#[test]
fn mask_emits_svg_mask() {
let mut scene = Scene::new(20.0, 20.0);
scene.push_node(
SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 20.0, 20.0),
FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
))
.with_mask(crate::scene::Mask::new(crate::scene::Clip::Rect(
Rect::new(0.0, 0.0, 10.0, 20.0),
))),
);
let out = render(&scene);
assert!(out.contains(r#"<mask id="mask0""#), "{out}");
assert!(out.contains(r#"mask="url(#mask0)""#), "{out}");
}
#[test]
fn filter_emits_svg_filter() {
let make = |f: crate::scene::Filter| {
let mut scene = Scene::new(20.0, 20.0);
scene.push_node(
SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
FillStrokeStyle::fill(Color::BLACK),
))
.with_filter(f),
);
render(&scene)
};
let blur = make(crate::scene::Filter::blur(2.0));
assert!(blur.contains(r#"<filter id="filter0""#), "{blur}");
assert!(blur.contains("feGaussianBlur"), "{blur}");
assert!(blur.contains(r#"filter="url(#filter0)""#), "{blur}");
let shadow = make(crate::scene::Filter::drop_shadow(
3.0,
3.0,
2.0,
Color::rgba(0x00, 0x00, 0x00, 128),
));
assert!(shadow.contains("feDropShadow"), "{shadow}");
assert!(shadow.contains(r#"flood-opacity="0.502""#), "{shadow}");
}
#[test]
fn scene_metadata_title_desc_scale() {
let scene = Scene::new(100.0, 50.0)
.with_title("T")
.with_description("D")
.with_scale(2.0);
let out = render(&scene);
assert!(out.contains("<title>T</title>"));
assert!(out.contains("<desc>D</desc>"));
assert!(out.contains(r#"width="100.00" height="50.00" viewBox="0 0 50.00 25.00""#));
}
#[test]
fn size_fallback_multiplies_scene_by_scale() {
let scene = Scene::new(100.0, 50.0).with_scale(2.0);
let mut svg = SvgRenderer::new(0.0, 0.0);
scene.render(&mut svg);
let out = svg.into_string();
assert!(
out.contains(r#"width="200.00" height="100.00" viewBox="0 0 100.00 50.00""#),
"回落应把 scene 尺寸 × scale 作为输出尺寸,实际: {out}"
);
assert!(out.contains(r##"width="100.00" height="50.00" fill="#ffffff""##));
}
#[test]
fn ellipse_rounded_rect_polygon_native_tags() {
let mut scene = Scene::new(200.0, 200.0);
scene.push(Element::ellipse(
Point::new(10.0, 10.0),
Vec2::new(30.0, 15.0),
0.0,
FillStrokeStyle::fill(Color::BLACK),
));
scene.push(Element::rounded_rect(
Rect::new(50.0, 50.0, 90.0, 70.0),
5.0,
FillStrokeStyle::fill(Color::BLACK),
));
scene.push(Element::polygon(
vec![
Point::new(0.0, 0.0),
Point::new(10.0, 0.0),
Point::new(5.0, 10.0),
],
FillStrokeStyle::fill(Color::BLACK),
));
let out = render(&scene);
assert!(out.contains("<ellipse cx=\"10.00\" cy=\"10.00\" rx=\"30.00\" ry=\"15.00\""));
assert!(
out.contains(r#"<rect x="50.00" y="50.00" width="40.00" height="20.00" rx="5.00""#)
);
assert!(out.contains("<polygon points=\"0.00,0.00 10.00,0.00 5.00,10.00\""));
}
#[test]
fn arc_and_pie_native_path() {
let mut scene = Scene::new(100.0, 100.0);
scene.push(Element::arc(
Point::new(50.0, 50.0),
Vec2::new(40.0, 30.0),
0.0,
std::f64::consts::FRAC_PI_2,
Stroke::new(Color::BLACK, 2.0),
));
scene.push(Element::pie(
Point::new(50.0, 50.0),
30.0,
0.0,
std::f64::consts::FRAC_PI_2,
FillStrokeStyle::fill(Color::BLACK),
));
let out = render(&scene);
assert!(out.contains("A 40.00 30.00"));
assert!(out.contains("M 50.00 50.00 L "));
assert!(out.contains(" Z"));
}
#[test]
fn radial_gradient_and_dash() {
let mut scene = Scene::new(100.0, 100.0);
let radial = crate::scene::RadialGradient::new(
Point::new(50.0, 50.0),
20.0,
vec![
GradientStop {
offset: 0.0,
color: Color::WHITE,
},
GradientStop {
offset: 1.0,
color: Color::BLACK,
},
],
);
scene.push(Element::circle(
Point::new(50.0, 50.0),
20.0,
FillStrokeStyle {
fill: Some(radial.into()),
stroke: Some(Stroke::dashed(Color::BLACK, 1.0, vec![3.0, 2.0])),
},
));
let out = render(&scene);
assert!(out.contains("<radialGradient"));
assert!(out.contains("gradientUnits=\"userSpaceOnUse\""));
assert!(out.contains("stroke-dasharray=\"3.00,2.00\""));
assert!(out.contains("stroke-miterlimit=\"10.00\""));
}
#[test]
fn gradient_spread_maps_to_spread_method() {
let grad = LinearGradient::new(
Point::new(0.0, 0.0),
Point::new(10.0, 0.0),
vec![
GradientStop {
offset: 0.0,
color: Color::WHITE,
},
GradientStop {
offset: 1.0,
color: Color::BLACK,
},
],
);
let scene_with = |g: LinearGradient| {
let mut s = Scene::new(100.0, 100.0);
s.push(Element::rect(
Rect::new(0.0, 0.0, 100.0, 100.0),
FillStrokeStyle::fill_gradient(g),
));
s
};
let pad = render(&scene_with(grad.clone()));
assert!(!pad.contains("spreadMethod"), "Pad 应省略属性: {pad}");
let reflect = render(&scene_with(
grad.clone().with_spread(GradientSpread::Reflect),
));
assert!(reflect.contains(r#"spreadMethod="reflect""#));
let repeat = render(&scene_with(grad.with_spread(GradientSpread::Repeat)));
assert!(repeat.contains(r#"spreadMethod="repeat""#));
}
#[test]
fn sweep_gradient_becomes_clipped_wedges() {
let mut scene = Scene::new(100.0, 100.0);
let g = crate::scene::SweepGradient::full(
Point::new(50.0, 50.0),
0.0,
vec![
GradientStop {
offset: 0.0,
color: Color::rgb(0xff, 0x00, 0x00),
},
GradientStop {
offset: 1.0,
color: Color::rgb(0x00, 0x00, 0xff),
},
],
);
scene.push(Element::circle(
Point::new(50.0, 50.0),
40.0,
FillStrokeStyle::fill_gradient(g),
));
let out = render(&scene);
assert!(out.contains("<clipPath"), "应有裁切路径: {out}");
assert!(out.contains(r#"clip-path="url(#swc"#));
assert_eq!(
out.matches(r#"<path d="M 50.00 50.00 L"#).count(),
SWEEP_WEDGES,
"每个扇区一个 wedge"
);
assert!(
out.contains(r#"fill="none""#),
"形状自身不再填充(由 wedge 着色)"
);
}
#[test]
fn sweep_partial_wrapped_wedges_take_start_color() {
let mut scene = Scene::new(100.0, 100.0);
let g = crate::scene::SweepGradient::new(
Point::new(50.0, 50.0),
std::f64::consts::FRAC_PI_2,
std::f64::consts::PI,
vec![
GradientStop {
offset: 0.0,
color: Color::rgb(0xff, 0x00, 0x00),
},
GradientStop {
offset: 1.0,
color: Color::rgb(0x00, 0x00, 0xff),
},
],
);
scene.push(Element::circle(
Point::new(50.0, 50.0),
40.0,
FillStrokeStyle::fill_gradient(g),
));
let out = render(&scene);
let anchor = out
.find(r#"L 106.57 50.00"#)
.expect("应存在弧起点在角度 0 位置的 wedge");
let close = out[anchor..]
.find("/>")
.map(|i| anchor + i + 2)
.expect("wedge path 元素应闭合");
let elem = &out[anchor..close];
assert!(
elem.contains(r##"fill="#ff0000""##),
"角度 0(回卷到 ramp 之前)应为起始色红: {elem}"
);
}
#[test]
fn rounded_rect_uniform_uses_rect_per_corner_uses_path() {
let scene_with = |radii: crate::scene::CornerRadii| {
let mut s = Scene::new(20.0, 20.0);
s.push(Element::rounded_rect(
Rect::new(0.0, 0.0, 20.0, 20.0),
radii,
FillStrokeStyle::fill(Color::BLACK),
));
s
};
let uniform = render(&scene_with(3.0.into()));
assert!(
uniform.contains(r#"<rect x="0.00" y="0.00" width="20.00" height="20.00" rx="3.00""#)
);
let per_corner = render(&scene_with(crate::scene::CornerRadii::new(
6.0, 0.0, 0.0, 0.0,
)));
assert!(
!per_corner.contains("rx="),
"每角半径不能用 <rect rx>: {per_corner}"
);
assert!(
per_corner.contains(r#"<path d=""#),
"应退化为路径: {per_corner}"
);
}
fn quad_pixmap() -> crate::Pixmap {
let mut px = Vec::with_capacity(4 * 4 * 4);
for y in 0..4u32 {
for x in 0..4u32 {
let (r, g, b) = match (x < 2, y < 2) {
(true, true) => (255u8, 0u8, 0u8),
(false, true) => (0, 255, 0),
(true, false) => (0, 0, 255),
(false, false) => (255, 255, 255),
};
px.extend_from_slice(&[r, g, b, 255]);
}
}
crate::Pixmap::from_rgba8(4, 4, px).unwrap()
}
#[test]
fn image_quality_maps_to_image_rendering() {
use crate::scene::ImageQuality;
let scene_with = |q: ImageQuality| {
let mut s = Scene::new(8.0, 8.0);
s.push(Element::image(
crate::SceneImage::from_pixmap(quad_pixmap()).with_quality(q),
Rect::new(0.0, 0.0, 8.0, 8.0),
));
s
};
assert!(
render(&scene_with(ImageQuality::Nearest)).contains(r#"image-rendering="pixelated""#)
);
assert!(!render(&scene_with(ImageQuality::Bilinear)).contains("image-rendering"));
assert!(
render(&scene_with(ImageQuality::Bicubic))
.contains(r#"image-rendering="high-quality""#)
);
}
#[test]
fn tile_object_fit_emits_a_pattern() {
let mut scene = Scene::new(8.0, 8.0);
scene.push(Element::image(
crate::SceneImage::from_pixmap(quad_pixmap()).with_object_fit(crate::ObjectFit::Tile),
Rect::new(0.0, 0.0, 8.0, 8.0),
));
let out = render(&scene);
assert!(
out.contains(r#"<pattern id="img0" patternUnits="userSpaceOnUse""#),
"{out}"
);
assert!(
out.contains(r#"width="4.00" height="4.00""#),
"瓦片按原始像素尺寸: {out}"
);
assert!(out.contains(r#"fill="url(#img0)""#), "{out}");
}
#[test]
fn image_fill_emits_a_pattern() {
let mut scene = Scene::new(8.0, 8.0);
scene.push(Element::rect(
Rect::new(0.0, 0.0, 8.0, 8.0),
FillStrokeStyle::fill_gradient(crate::scene::ImageFill::natural(
quad_pixmap(),
Point::new(0.0, 0.0),
)),
));
let out = render(&scene);
assert!(out.contains(r#"<pattern id="img0""#), "{out}");
assert!(out.contains(r#"fill="url(#img0)""#), "{out}");
}
#[test]
fn antialias_off_emits_crisp_edges() {
let rect = |w: f64| {
Element::rect(
Rect::new(0.0, 0.0, w, w),
FillStrokeStyle::fill(Color::BLACK),
)
};
let mut scene = Scene::new(20.0, 20.0);
scene.push(SceneNode::new(rect(10.0)).with_antialias(false));
scene.push(rect(5.0));
let out = render(&scene);
assert_eq!(
out.matches(r#"shape-rendering="crispEdges""#).count(),
1,
"只有关闭的那个形状带提示: {out}"
);
let mut nested = Scene::new(20.0, 20.0);
nested.push_node(
SceneNode::group(vec![SceneNode::new(rect(2.0)), SceneNode::new(rect(3.0))])
.with_antialias(false),
);
let out = render(&nested);
assert_eq!(
out.matches(r#"shape-rendering="crispEdges""#).count(),
2,
"子树继承容器的设置: {out}"
);
}
#[test]
fn color_matrix_is_baked_into_paints() {
let mut scene = Scene::new(20.0, 20.0);
scene.push_node(
SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 20.0, 20.0),
FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
))
.with_color_matrix(crate::scene::ColorMatrix::grayscale()),
);
let out = render(&scene);
assert!(out.contains(r##"fill="#363636""##), "灰化后的填充: {out}");
assert!(!out.contains(r##"fill="#ff0000""##), "不应保留原色: {out}");
}
#[test]
fn nested_color_matrices_compose() {
let child = SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 20.0, 20.0),
FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
))
.with_color_matrix(crate::scene::ColorMatrix::grayscale());
let group = SceneNode::group(vec![child])
.with_color_matrix(crate::scene::ColorMatrix::brightness(0.5));
let mut scene = Scene::new(20.0, 20.0);
scene.push_node(group);
let out = render(&scene);
assert!(out.contains(r##"fill="#1b1b1b""##), "组合后的填充: {out}");
}
#[test]
fn opacity_name_visibility() {
let mut scene = Scene::new(100.0, 100.0);
scene.push_node(
SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
FillStrokeStyle::fill(Color::BLACK),
))
.with_opacity(0.4)
.with_name("a"),
);
scene.push_node(
SceneNode::new(Element::rect(
Rect::new(20.0, 0.0, 30.0, 10.0),
FillStrokeStyle::fill(Color::BLACK),
))
.with_visible(false),
);
let out = render(&scene);
assert!(out.contains(r#"<g id="a">"#));
assert!(out.contains(r#"<g opacity="0.400">"#));
assert!(!out.contains(r#"x="20.00""#));
}
#[test]
fn text_escaping() {
let mut scene = Scene::new(100.0, 100.0);
scene.push(Element::text(
"a <b> & \"c\"",
Point::new(1.0, 2.0),
TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
));
let out = render(&scene);
assert!(out.contains("a <b> & \"c\""));
}
#[test]
fn text_align_anchor() {
let mut scene = Scene::new(200.0, 100.0);
let style = |align| TextStyle::new(Color::BLACK, 12.0, "sans-serif").with_align(align);
scene.push(Element::text(
"L",
Point::new(10.0, 10.0),
style(TextAlign::Left),
));
scene.push(Element::text(
"C",
Point::new(100.0, 10.0),
style(TextAlign::Center),
));
scene.push(Element::text(
"R",
Point::new(190.0, 10.0),
style(TextAlign::Right),
));
let out = render(&scene);
assert!(out.contains(r#"text-anchor="start""#));
assert!(out.contains(r#"text-anchor="middle""#));
assert!(out.contains(r#"text-anchor="end""#));
}
#[test]
fn text_baseline_and_font_attrs() {
let mut scene = Scene::new(200.0, 100.0);
scene.push(Element::text(
"b",
Point::new(10.0, 10.0),
TextStyle::new(Color::BLACK, 12.0, "sans-serif")
.with_baseline(TextBaseline::Middle)
.with_weight(FontWeight::Bold)
.with_style(FontStyle::Italic)
.with_line_height(18.0),
));
let out = render(&scene);
assert!(out.contains(r#"dominant-baseline="alphabetic""#));
assert!(out.contains(r#"font-weight="700""#));
assert!(out.contains(r#"font-style="italic""#));
assert!(out.contains(r#"style="line-height:18.00""#));
}
#[test]
fn node_and_layer_transform_matrix() {
use crate::geometry::Transform;
use crate::scene::Layer;
let mut scene = Scene::new(100.0, 100.0);
scene.push_node(
SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
FillStrokeStyle::fill(Color::BLACK),
))
.with_transform(Transform::translate(5.0, 7.0)),
);
scene.push_layer(Layer::new("l").with_transform(Transform::translate(1.0, 2.0)));
let out = render(&scene);
assert!(out.contains(r#"matrix(1.000000 0.000000 0.000000 1.000000 5.000000 7.000000)"#));
assert!(out.contains(r#"matrix(1.000000 0.000000 0.000000 1.000000 1.000000 2.000000)"#));
}
#[test]
fn layer_render_order_bottom_to_top() {
use crate::scene::Layer;
let mut scene = Scene::new(100.0, 100.0);
scene.push(Element::rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
FillStrokeStyle::fill(Color::BLACK),
));
scene.push_layer(
Layer::new("bottom").with_nodes(vec![SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 5.0, 5.0),
FillStrokeStyle::fill(Color::BLACK),
))]),
);
scene.push_layer(
Layer::new("top").with_nodes(vec![SceneNode::new(Element::circle(
Point::new(0.0, 0.0),
1.0,
FillStrokeStyle::fill(Color::BLACK),
))]),
);
let out = render(&scene);
let bg_idx = out.find("width=\"10.00\"").expect("默认层矩形");
let bottom_idx = out.find(r#"<g id="bottom">"#).expect("bottom 图层");
let top_idx = out.find(r#"<g id="top">"#).expect("top 图层");
assert!(
bg_idx < bottom_idx && bottom_idx < top_idx,
"渲染顺序应为 默认层 < bottom < top"
);
}
#[test]
fn path_closed_vs_open() {
use kurbo::BezPath;
let mut scene = Scene::new(100.0, 100.0);
let mut open = BezPath::new();
open.move_to((0.0, 0.0));
open.line_to((10.0, 0.0));
scene.push(Element::Path {
path: open,
style: FillStrokeStyle::stroke(Color::BLACK, 1.0),
closed: false,
});
let mut closed = BezPath::new();
closed.move_to((20.0, 0.0));
closed.line_to((30.0, 0.0));
closed.line_to((25.0, 10.0));
scene.push(Element::Path {
path: closed,
style: FillStrokeStyle::stroke(Color::BLACK, 1.0),
closed: true,
});
let out = render(&scene);
assert!(
out.contains(r#"d="M0,0 L10,0""#),
"开放路径 d 应为 M0,0 L10,0: {}",
out
);
assert!(
out.contains(r#"d="M20,0 L30,0 L25,10 Z""#),
"闭合路径 d 应以 Z 结尾: {}",
out
);
}
#[test]
fn prelaid_text_ignores_layout_in_svg() {
use crate::text::RichSpan;
use crate::text::measure_text;
let mut scene = Scene::new(100.0, 100.0);
let style = TextStyle::new(Color::BLACK, 12.0, "sans-serif");
let m = measure_text(
std::slice::from_ref(&RichSpan::new("hello", style.clone())),
None,
);
scene.push(Element::Text {
spans: vec![RichSpan::new("hello", style.clone())],
position: Point::new(1.0, 2.0),
style,
layout: Some(m.layout),
});
let out = render(&scene);
assert!(out.contains(">hello</text>"));
assert!(!out.contains("path"));
}
#[test]
fn font_family_attr_is_css_normalized_and_xml_escaped() {
use crate::text::TextStyle;
let mut scene = Scene::new(100.0, 100.0);
let style = TextStyle::new(
Color::BLACK,
12.0,
"Helvetica Neue, Rock & Roll, sans-serif",
);
scene.push(Element::text("x", Point::new(1.0, 2.0), style));
let out = render(&scene);
assert!(out.contains(r#"font-family="'Helvetica Neue', 'Rock & Roll', sans-serif""#));
assert!(!out.contains("'"));
}
#[test]
fn text_decoration_spacing_stretch_emitted() {
use crate::text::TextStyle;
let mut scene = Scene::new(100.0, 100.0);
let style = TextStyle::new(Color::BLACK, 12.0, "sans-serif")
.with_underline(true)
.with_strikethrough(true)
.with_letter_spacing(2.0)
.with_font_width(FontWidth::Condensed);
scene.push(Element::text("x", Point::new(1.0, 2.0), style));
let out = render(&scene);
assert!(out.contains(r#"text-decoration="underline line-through""#));
assert!(out.contains(r#"letter-spacing="2.00""#));
assert!(out.contains(r#"font-stretch="75%""#));
}
#[test]
fn clip_emits_clip_path_and_wraps_subtree() {
use crate::scene::Clip;
let mut scene = Scene::new(100.0, 100.0);
scene.push_node(
SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 50.0, 50.0),
FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
))
.with_clip(Clip::circle(Point::new(25.0, 25.0), 10.0)),
);
let out = render(&scene);
assert!(out.contains(
r#"<clipPath id="clip0"><circle cx="25.00" cy="25.00" r="10.00"/></clipPath>"#
));
assert!(out.contains(r#"<g clip-path="url(#clip0)">"#));
}
#[test]
fn base64_encode_standard_vectors() {
assert_eq!(base64_encode(b""), "");
assert_eq!(base64_encode(b"f"), "Zg==");
assert_eq!(base64_encode(b"fo"), "Zm8=");
assert_eq!(base64_encode(b"foo"), "Zm9v");
assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
assert_eq!(base64_encode(b"fooba"), "Zm9vYmE=");
assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
}
fn test_image(w: u32, h: u32, fill: u8) -> crate::SceneImage {
let pixels = vec![fill; (w * h * 4) as usize];
crate::SceneImage::from_rgba8(w, h, pixels).unwrap()
}
#[test]
fn image_emits_data_uri_and_contain_meet() {
let mut scene = Scene::new(100.0, 100.0);
scene.push(Element::image(
test_image(4, 4, 255),
Rect::new(0.0, 0.0, 10.0, 20.0),
));
let out = render(&scene);
assert!(out.contains(r#"href="data:image/png;base64,"#));
assert!(out.contains(r#"width="10.00" height="20.00""#));
assert!(out.contains(r#"preserveAspectRatio="xMidYMid meet""#));
}
#[test]
fn image_object_fit_none_uses_raw_pixel_size() {
let mut scene = Scene::new(100.0, 100.0);
scene.push(Element::image(
test_image(30, 40, 255).with_object_fit(crate::ObjectFit::None),
Rect::new(5.0, 6.0, 105.0, 106.0),
));
let out = render(&scene);
assert!(out.contains(r#"x="5.00" y="6.00" width="30.00" height="40.00""#));
assert!(out.contains(r#"preserveAspectRatio="none""#));
}
#[test]
fn image_object_fit_fill_maps_to_none() {
let mut scene = Scene::new(100.0, 100.0);
scene.push(Element::image(
test_image(10, 10, 255).with_object_fit(crate::ObjectFit::Fill),
Rect::new(0.0, 0.0, 10.0, 10.0),
));
let out = render(&scene);
assert!(out.contains(r#"width="10.00" height="10.00""#));
assert!(out.contains(r#"preserveAspectRatio="none""#));
}
#[test]
fn image_respects_opacity() {
let mut scene = Scene::new(100.0, 100.0);
scene.push_node(
SceneNode::from(Element::image(
test_image(10, 10, 255),
Rect::new(0.0, 0.0, 10.0, 10.0),
))
.with_opacity(0.5),
);
let out = render(&scene);
assert!(out.contains(r#"opacity="0.500""#));
}
#[test]
fn text_baseline_shift_and_background_emitted() {
use crate::text::TextStyle;
let mut scene = Scene::new(200.0, 100.0);
let sup = TextStyle::new(Color::BLACK, 12.0, "sans-serif").with_baseline_shift(6.0);
scene.push(Element::text("x²", Point::new(10.0, 50.0), sup));
let code = TextStyle::new(Color::BLACK, 12.0, "sans-serif")
.with_background_color(Some(Color::rgb(0xf0, 0xf0, 0xf0)));
scene.push(Element::text("code", Point::new(30.0, 50.0), code));
let out = render(&scene);
assert!(out.contains("baseline-shift=\"-6.00px\""));
assert!(out.contains("<rect "));
assert!(out.contains("fill=\"#f0f0f0\""));
}
#[test]
fn text_background_uses_layout_exact_size() {
use crate::text::{RichSpan, TextStyle, measure_text};
let style = TextStyle::new(Color::BLACK, 12.0, "sans-serif")
.with_background_color(Some(Color::rgb(0xf0, 0xf0, 0xf0)));
let m = measure_text(
std::slice::from_ref(&RichSpan::new("code", style.clone())),
None,
);
let mut scene = Scene::new(200.0, 100.0);
scene.push(Element::Text {
spans: vec![RichSpan::new("code", style.clone())],
position: Point::new(30.0, 50.0),
style,
layout: Some(m.layout),
});
let out = render(&scene);
let expect_w = format!("{:.2}", m.metrics.width);
let expect_h = format!("{:.2}", m.metrics.height);
assert!(
out.contains(&format!("width=\"{}\" height=\"{}\"", expect_w, expect_h)),
"背景矩形应使用 layout 精确尺寸,但输出含: {}",
out
);
}
#[test]
fn text_no_background_when_none() {
use crate::text::TextStyle;
let mut scene = Scene::new(100.0, 100.0);
scene.push(Element::text(
"plain",
Point::new(10.0, 50.0),
TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
));
let out = render(&scene);
assert_eq!(out.matches("<rect ").count(), 1);
}
#[test]
fn text_background_uses_real_measurement() {
use crate::text::TextStyle;
let style = TextStyle::new(Color::BLACK, 20.0, "sans-serif")
.with_background_color(Some(Color::rgb(0xff, 0xff, 0x00)));
let el = Element::text("Hello World", Point::new(10.0, 40.0), style);
let measured_w = match &el {
Element::Text {
layout: Some(l), ..
} => l.width,
_ => return,
};
let mut scene = Scene::new(300.0, 80.0);
scene.push(el);
let out = render(&scene);
let bg = out
.lines()
.find(|l| l.contains("#ffff00"))
.expect("应输出文本背景矩形");
let w: f64 = bg
.split("width=\"")
.nth(1)
.and_then(|s| s.split('"').next())
.and_then(|s| s.parse().ok())
.expect("背景矩形应有 width");
assert!(
(w - measured_w).abs() < 0.5,
"背景矩形宽度应等于排版宽度 {measured_w:.2},实际 {w:.2}"
);
}
#[test]
fn element_text_prelayouts() {
use crate::text::TextStyle;
let el = Element::text(
"Hello",
Point::new(0.0, 0.0),
TextStyle::new(Color::BLACK, 16.0, "sans-serif"),
);
match &el {
Element::Text { layout, .. } => {
if let Some(l) = layout {
assert!(!l.lines.is_empty());
assert!(l.width > 0.0);
}
}
_ => panic!("expected Text"),
}
let empty = Element::text(
"",
Point::new(0.0, 0.0),
TextStyle::new(Color::BLACK, 16.0, "sans-serif"),
);
match &empty {
Element::Text { layout, .. } => assert!(layout.is_none(), "空文本不应排版"),
_ => panic!("expected Text"),
}
let rich = Element::rich_text(
vec![crate::text::RichSpan::new(
"ab",
TextStyle::new(Color::BLACK, 16.0, "sans-serif"),
)],
Point::new(0.0, 0.0),
TextStyle::new(Color::BLACK, 16.0, "sans-serif"),
);
match &rich {
Element::Text { layout, .. } => {
if let Some(l) = layout {
assert!(!l.lines.is_empty());
}
}
_ => panic!("expected Text"),
}
let empty_rich = Element::rich_text(
vec![],
Point::new(0.0, 0.0),
TextStyle::new(Color::BLACK, 16.0, "sans-serif"),
);
match &empty_rich {
Element::Text { layout, .. } => assert!(layout.is_none()),
_ => panic!("expected Text"),
}
}
#[test]
fn falls_back_to_scene_size_and_background() {
let mut scene = Scene::new(300.0, 200.0).with_background(Color::rgb(0x00, 0x00, 0xff));
scene.push(Element::rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
FillStrokeStyle::fill(Color::RED),
));
let mut svg = SvgRenderer::new(0.0, 0.0);
scene.render(&mut svg);
let out = svg.into_string();
assert!(
out.contains(r#"width="300.00" height="200.00" viewBox="0 0 300.00 200.00""#),
"应回落到场景尺寸,实际输出: {out}"
);
assert!(
out.contains(r##"fill="#0000ff""##),
"应回落到场景背景色,实际输出: {out}"
);
}
#[test]
fn explicit_renderer_settings_win() {
let scene = Scene::new(300.0, 200.0).with_scale(3.0);
let mut svg = SvgRenderer::new(50.0, 40.0)
.with_scale(2.0)
.with_background(Color::GREEN);
scene.render(&mut svg);
let out = svg.into_string();
assert!(out.contains(r#"width="50.00" height="40.00" viewBox="0 0 25.00 20.00""#));
assert!(out.contains(r##"fill="#00ff00""##));
assert!(
!out.contains(r#"viewBox="0 0 16.67"#),
"渲染器 scale 应优先: {out}"
);
}
#[test]
fn full_circle_arc_is_split_in_two() {
let d = arc_path_d(
Point::new(50.0, 50.0),
Vec2::new(30.0, 30.0),
0.0,
std::f64::consts::TAU,
true,
);
assert_eq!(
d.matches(" A ").count(),
2,
"整圆应拆成两段弧,实际 d = {d}"
);
assert!(d.starts_with("M 50.00 50.00 L "), "扇形应含中心点: {d}");
assert!(d.ends_with(" Z"), "扇形应闭合: {d}");
let open_pie = arc_path_d(
Point::new(50.0, 50.0),
Vec2::new(30.0, 30.0),
0.0,
std::f64::consts::TAU,
false,
);
assert_eq!(open_pie.matches(" A ").count(), 2, "整圆弧: {open_pie}");
let normal = arc_path_d(
Point::new(50.0, 50.0),
Vec2::new(30.0, 30.0),
0.0,
std::f64::consts::FRAC_PI_2,
true,
);
assert_eq!(normal.matches(" A ").count(), 1, "普通扇形: {normal}");
}
#[test]
fn gradient_stop_alpha_uses_stop_opacity() {
let mut scene = Scene::new(100.0, 100.0);
let grad = LinearGradient::new(
Point::new(0.0, 0.0),
Point::new(100.0, 0.0),
vec![
GradientStop {
offset: 0.0,
color: Color::rgba(0xff, 0x00, 0x00, 128),
},
GradientStop {
offset: 1.0,
color: Color::rgb(0x00, 0x00, 0xff),
},
],
);
scene.push(Element::rect(
Rect::new(0.0, 0.0, 100.0, 100.0),
FillStrokeStyle {
fill: Some(grad.into()),
stroke: None,
},
));
let out = render(&scene);
assert!(
out.contains(r##"stop-color="#ff0000" stop-opacity="0.502""##),
"半透明 stop 应输出 stop-opacity: {out}"
);
assert!(
out.contains(r##"stop-color="#0000ff" />"##),
"不透明 stop 不应带 stop-opacity: {out}"
);
}
#[test]
fn rich_text_spans_emit_tspan_with_own_style() {
use crate::text::RichSpan;
let mut scene = Scene::new(300.0, 60.0);
scene.push(Element::rich_text(
vec![
RichSpan::new(
"red ",
TextStyle::new(Color::rgb(0xff, 0x00, 0x00), 20.0, "sans-serif")
.with_weight(FontWeight::Bold),
),
RichSpan::new(
"blue",
TextStyle::new(Color::rgb(0x00, 0x00, 0xff), 12.0, "sans-serif"),
),
],
Point::new(10.0, 30.0),
TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
));
let out = render(&scene);
assert!(out.contains("<tspan"), "富文本应输出 tspan: {out}");
assert!(
out.contains(r##"fill="#ff0000""##)
&& out.contains(r##"font-size="20.00""##)
&& out.contains(r##"font-weight="700""##),
"红色加粗 span 的样式应保留: {out}"
);
assert!(
out.contains(r##"fill="#0000ff""##),
"蓝色 span 的样式应保留: {out}"
);
assert!(out.contains(">red </tspan>"), "span 文本应完整: {out}");
assert!(out.contains(">blue</tspan>"), "span 文本应完整: {out}");
let mut plain = Scene::new(100.0, 30.0);
plain.push(Element::text(
"plain",
Point::new(1.0, 2.0),
TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
));
let out_plain = render(&plain);
assert!(
!out_plain.contains("<tspan"),
"纯文本不应输出 tspan: {out_plain}"
);
}
#[test]
fn multiline_text_emits_line_tspans() {
let mut scene = Scene::new(100.0, 100.0);
scene.push(Element::text(
"line1\nline2",
Point::new(5.0, 10.0),
TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
));
let out = render(&scene);
assert!(out.contains(">line1</tspan>"), "第一行内容缺失: {out}");
assert!(out.contains(">line2</tspan>"), "第二行内容缺失: {out}");
let line_tspans: Vec<&str> = out.matches(r#"<tspan x="5.00" dy="#).collect();
assert!(line_tspans.len() >= 2, "应有两个行级 tspan: {out}");
}
#[test]
fn translucent_color_uses_fill_and_stroke_opacity() {
let mut scene = Scene::new(40.0, 40.0);
scene.push(Element::rect(
Rect::new(0.0, 0.0, 40.0, 40.0),
FillStrokeStyle {
fill: Some(Color::rgba(0xff, 0x00, 0x00, 128).into()),
stroke: Some(Stroke::new(Color::rgba(0x00, 0x00, 0xff, 128), 2.0)),
},
));
let out = render(&scene);
assert!(
out.contains(r##"fill="#ff0000" fill-opacity="0.502""##),
"半透明 fill 应带 fill-opacity: {out}"
);
assert!(
out.contains(r##"stroke="#0000ff" stroke-opacity="0.502""##),
"半透明 stroke 应带 stroke-opacity: {out}"
);
assert!(
!out.contains("#ff000080") && !out.contains("#0000ff80"),
"不应输出 8 位 hex: {out}"
);
}
fn sketch_rect(color: crate::geometry::Color, style: SketchFillStyle) -> Scene {
let mut scene = Scene::new(200.0, 200.0);
scene.push(Element::rect(
Rect::new(10.0, 10.0, 100.0, 80.0),
FillStrokeStyle {
fill: Some(Fill::Sketch(SketchFill::new(color).with_style(style))),
stroke: None,
},
));
scene
}
#[test]
fn sketch_fill_emits_one_pattern_definition() {
let out = render(&sketch_rect(
Color::rgb(0x33, 0x66, 0x99),
SketchFillStyle::Hachure,
));
assert!(out.contains(r#"<pattern id="sk0""#), "{out}");
assert!(out.contains(r#"patternUnits="userSpaceOnUse""#), "{out}");
assert!(
out.contains(r#"patternTransform="rotate(-41.00)""#),
"{out}"
);
assert!(out.contains(r#"fill="url(#sk0)""#), "{out}");
assert_eq!(out.matches("<pattern").count(), 1, "只应定义一次: {out}");
}
#[test]
fn identical_sketch_fills_share_one_pattern() {
let mut scene = Scene::new(400.0, 400.0);
for i in 0..100 {
let x = (i % 10) as f64 * 20.0;
let y = (i / 10) as f64 * 20.0;
scene.push(Element::rect(
Rect::new(x, y, x + 16.0, y + 16.0),
FillStrokeStyle {
fill: Some(Fill::Sketch(SketchFill::new(Color::rgb(0xcc, 0x33, 0x33)))),
stroke: None,
},
));
}
let out = render(&scene);
assert_eq!(out.matches("<pattern").count(), 1, "pattern 数应 ≤1: {out}");
assert_eq!(out.matches(r#"fill="url(#sk0)""#).count(), 100);
}
#[test]
fn pattern_pool_is_keyed_by_all_parameters() {
let mut scene = Scene::new(300.0, 100.0);
for (i, style) in [
SketchFillStyle::Hachure,
SketchFillStyle::CrossHatch,
SketchFillStyle::Zigzag,
SketchFillStyle::Dots,
]
.into_iter()
.enumerate()
{
scene.push(Element::rect(
Rect::new(i as f64 * 70.0, 10.0, i as f64 * 70.0 + 60.0, 80.0),
FillStrokeStyle {
fill: Some(Fill::Sketch(
SketchFill::new(Color::rgb(0x11, 0x22, 0x33)).with_style(style),
)),
stroke: None,
},
));
}
let out = render(&scene);
assert_eq!(out.matches("<pattern").count(), 4, "四种样式各一个: {out}");
assert!(out.contains("<circle"), "Dots 用圆点: {out}");
assert!(out.contains("<polyline"), "Zigzag 用折线: {out}");
}
#[test]
fn different_colors_get_different_patterns() {
let mut scene = Scene::new(300.0, 100.0);
for (i, c) in [
Color::rgb(0xff, 0x00, 0x00),
Color::rgb(0x00, 0xff, 0x00),
Color::rgb(0x00, 0x00, 0xff),
]
.into_iter()
.enumerate()
{
scene.push(Element::rect(
Rect::new(i as f64 * 90.0, 10.0, i as f64 * 90.0 + 80.0, 80.0),
FillStrokeStyle {
fill: Some(Fill::Sketch(SketchFill::new(c))),
stroke: None,
},
));
}
let out = render(&scene);
assert_eq!(out.matches("<pattern").count(), 3, "{out}");
}
#[test]
fn translucent_sketch_color_uses_stroke_opacity() {
let out = render(&sketch_rect(
Color::rgba(0x33, 0x66, 0x99, 128),
SketchFillStyle::Hachure,
));
assert!(out.contains(r#"stroke-opacity="0.502""#), "{out}");
assert!(!out.contains("#33669980"), "不应输出 8 位 hex: {out}");
}
#[test]
fn pattern_tile_content_is_inset_from_the_edges() {
let out = render(&sketch_rect(Color::BLACK, SketchFillStyle::Hachure));
let gap = 4.0;
assert!(
out.contains(&format!(r#"x1="{:.2}""#, gap * 0.5)),
"竖线应在 tile 中间: {out}"
);
assert!(!out.contains(r#"x1="0.00""#), "线不应贴在 tile 边缘: {out}");
}
#[test]
fn no_pattern_without_a_sketch_fill() {
let mut scene = Scene::new(100.0, 100.0);
scene.push(Element::rect(
Rect::new(10.0, 10.0, 90.0, 90.0),
FillStrokeStyle::fill(Color::rgb(0x33, 0x66, 0x99)),
));
let out = render(&scene);
assert!(!out.contains("<pattern"), "{out}");
assert!(!out.contains("<defs>"), "{out}");
}
fn render_with(scene: &Scene, f: impl FnOnce(SvgRenderer) -> SvgRenderer) -> String {
let mut svg = f(SvgRenderer::new(scene.width, scene.height).with_background(Color::WHITE));
scene.render(&mut svg);
svg.into_string()
}
fn sized_scene() -> Scene {
let mut scene = Scene::new(120.0, 60.0);
scene.push(Element::rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
FillStrokeStyle::fill(Color::RED),
));
scene
}
#[test]
fn fixed_sizing_writes_width_and_height() {
let out = render_with(&sized_scene(), |r| r);
assert!(
out.starts_with(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="120.00" height="60.00" viewBox="0 0 120.00 60.00">"#
),
"{out}"
);
}
#[test]
fn intrinsic_sizing_omits_width_and_height() {
let out = render_with(&sized_scene(), |r| r.with_sizing(SvgSizing::Intrinsic));
assert!(
out.starts_with(
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120.00 60.00">"#
),
"{out}"
);
assert!(!out.contains(r#"<svg width="#), "根节点不应带 width: {out}");
}
#[test]
fn root_style_is_emitted_and_escaped() {
let out = render_with(&sized_scene(), |r| {
r.with_sizing(SvgSizing::Intrinsic)
.with_style(r#"max-width: 120.000px; background-color: #ffffff;"#)
});
assert!(
out.starts_with(
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120.00 60.00" style="max-width: 120.000px; background-color: #ffffff;">"#
),
"{out}"
);
let out = render_with(&sized_scene(), |r| r.with_style(r#"content: "x""#));
assert!(out.contains(r#"style="content: "x"""#), "{out}");
}
#[test]
fn intrinsic_sizing_keeps_scale_in_viewbox() {
let out = render_with(&sized_scene(), |r| {
r.with_scale(2.0).with_sizing(SvgSizing::Intrinsic)
});
assert!(
out.starts_with(
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60.00 30.00">"#
),
"{out}"
);
}
}