use crate::geometry::{Color, Point, Rect, Size, Transform, Vec2};
use crate::path::{BoolOp, DEFAULT_TOLERANCE, PathOps};
use crate::scene::{
BlendMode, Clip, Element, Fill, FillStrokeStyle, Filter, Layer, Mask, SceneImage, SceneNode,
Stroke,
};
use crate::text::{RichSpan, TextMeasure, TextStyle, measure_text};
use kurbo::{BezPath, Shape};
#[derive(Debug, Clone)]
pub struct Ctx {
pub fill: Option<Fill>,
pub stroke: Option<Stroke>,
pub font: TextStyle,
pub transform: Option<Transform>,
pub alpha: f64,
pub clip: Option<Clip>,
pub blend_mode: BlendMode,
pub mask: Option<Mask>,
pub filter: Option<Filter>,
pub name: Option<String>,
pub z_index: i32,
}
impl Default for Ctx {
fn default() -> Self {
Self {
fill: Some(Fill::Solid(Color::BLACK)),
stroke: None,
font: TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
transform: None,
alpha: 1.0,
clip: None,
blend_mode: BlendMode::Normal,
mask: None,
filter: None,
name: None,
z_index: 0,
}
}
}
impl Ctx {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_fill(mut self, color: Color) -> Self {
self.fill = Some(Fill::Solid(color));
self
}
#[must_use]
pub fn with_fill_gradient(mut self, gradient: impl Into<Fill>) -> Self {
self.fill = Some(gradient.into());
self
}
#[must_use]
pub fn without_fill(mut self) -> Self {
self.fill = None;
self
}
#[must_use]
pub fn with_stroke(mut self, stroke: Stroke) -> Self {
self.stroke = Some(stroke);
self
}
#[must_use]
pub fn with_line(mut self, color: Color, width: f64) -> Self {
self.stroke = Some(match self.stroke {
Some(mut s) => {
s.color = color;
s.width = width;
s
}
None => Stroke::new(color, width),
});
self
}
#[must_use]
pub fn without_stroke(mut self) -> Self {
self.stroke = None;
self
}
#[must_use]
pub fn with_line_width(mut self, width: f64) -> Self {
self.stroke_mut().width = width;
self
}
#[must_use]
pub fn with_line_cap(mut self, cap: crate::scene::LineCap) -> Self {
self.stroke_mut().line_cap = cap;
self
}
#[must_use]
pub fn with_line_join(mut self, join: crate::scene::LineJoin) -> Self {
self.stroke_mut().line_join = join;
self
}
#[must_use]
pub fn with_miter_limit(mut self, limit: f64) -> Self {
self.stroke_mut().miter_limit = limit;
self
}
#[must_use]
pub fn with_dash(mut self, pattern: Vec<f64>, offset: f64) -> Self {
let s = self.stroke_mut();
s.dash_array = pattern;
s.dash_offset = offset;
self
}
fn stroke_mut(&mut self) -> &mut Stroke {
let fallback = match &self.stroke {
Some(_) => self.font.color,
None => self.shape_fill(),
};
self.stroke
.get_or_insert_with(|| Stroke::new(fallback, 1.0))
}
#[must_use]
pub fn with_font(mut self, font: TextStyle) -> Self {
self.font = font;
self
}
#[must_use]
pub fn with_text_color(mut self, color: Color) -> Self {
self.font.color = color;
self
}
#[must_use]
pub fn with_text_align(mut self, align: crate::text::TextAlign) -> Self {
self.font.align = align;
self
}
#[must_use]
pub fn with_text_baseline(mut self, baseline: crate::text::TextBaseline) -> Self {
self.font.baseline = baseline;
self
}
#[must_use]
pub fn with_max_width(mut self, max_width: f64) -> Self {
self.font.max_width = Some(max_width);
self
}
#[must_use]
pub fn without_max_width(mut self) -> Self {
self.font.max_width = None;
self
}
#[must_use]
pub fn with_transform(mut self, t: Transform) -> Self {
self.transform = Some(t);
self
}
#[must_use]
pub fn translate(mut self, x: f64, y: f64) -> Self {
let t = Transform::translate(x, y);
self.transform = Some(match self.transform {
Some(cur) => cur.then(&t),
None => t,
});
self
}
#[must_use]
pub fn rotate(mut self, angle: f64) -> Self {
let t = Transform::rotate(angle);
self.transform = Some(match self.transform {
Some(cur) => cur.then(&t),
None => t,
});
self
}
#[must_use]
pub fn scale(mut self, s: f64) -> Self {
let t = Transform::scale(s);
self.transform = Some(match self.transform {
Some(cur) => cur.then(&t),
None => t,
});
self
}
#[must_use]
pub fn with_alpha(mut self, alpha: f64) -> Self {
self.alpha = alpha.clamp(0.0, 1.0);
self
}
#[must_use]
pub fn with_clip(mut self, clip: Clip) -> Self {
self.clip = Some(clip);
self
}
#[must_use]
pub fn with_blend(mut self, mode: BlendMode) -> Self {
self.blend_mode = mode;
self
}
#[must_use]
pub fn with_mask(mut self, mask: Mask) -> Self {
self.mask = Some(mask);
self
}
#[must_use]
pub fn with_filter(mut self, filter: Filter) -> Self {
self.filter = Some(filter);
self
}
#[must_use]
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub fn with_z(mut self, z: i32) -> Self {
self.z_index = z;
self
}
fn text_color(&self) -> Color {
self.font.color
}
fn shape_fill(&self) -> Color {
let from_gradient = match &self.fill {
Some(Fill::Solid(c)) => return *c,
Some(Fill::Sketch(sf)) => return sf.color,
Some(Fill::LinearGradient(g)) => first_stop_color(&g.stops),
Some(Fill::RadialGradient(g)) => first_stop_color(&g.stops),
Some(Fill::SweepGradient(g)) => first_stop_color(&g.stops),
Some(Fill::Image(_)) => None,
None => None,
};
from_gradient.unwrap_or(self.font.color)
}
fn fill_stroke(&self) -> FillStrokeStyle {
FillStrokeStyle {
fill: self.fill.clone(),
stroke: self.stroke.clone(),
}
}
fn stroke_or_default(&self) -> Stroke {
self.stroke
.clone()
.unwrap_or_else(|| Stroke::new(self.shape_fill(), 1.0))
}
fn attrs(&self, mut n: SceneNode) -> SceneNode {
if let Some(t) = self.transform {
n = n.with_transform(t);
}
if (self.alpha - 1.0).abs() > f64::EPSILON {
n = n.with_opacity(self.alpha);
}
if let Some(c) = &self.clip {
n = n.with_clip(c.clone());
}
if !self.blend_mode.is_normal() {
n = n.with_blend_mode(self.blend_mode);
}
if let Some(m) = &self.mask {
n = n.with_mask(m.clone());
}
if let Some(f) = &self.filter {
n = n.with_filter(f.clone());
}
if let Some(name) = &self.name {
n = n.with_name(name.clone());
}
if self.z_index != 0 {
n = n.with_z(self.z_index);
}
n
}
fn node(&self, element: Element) -> SceneNode {
self.attrs(SceneNode::new(element))
}
#[must_use]
pub fn fill_text(&self, x: f64, y: f64, text: impl Into<String>) -> SceneNode {
let mut style = self.font.clone();
style.color = self.text_color();
self.node(Element::text(text, Point::new(x, y), style))
}
#[must_use]
pub fn fill_text_max_width(
&self,
x: f64,
y: f64,
text: impl Into<String>,
max_width: f64,
) -> SceneNode {
self.clone().with_max_width(max_width).fill_text(x, y, text)
}
#[must_use]
pub fn fill_rich_text(&self, x: f64, y: f64, spans: Vec<RichSpan>) -> SceneNode {
let mut style = self.font.clone();
style.color = self.text_color();
self.node(Element::rich_text(spans, Point::new(x, y), style))
}
#[must_use]
pub fn measure_text(&self, text: impl AsRef<str>) -> TextMeasure {
self.measure_rich_text(std::slice::from_ref(&RichSpan::new(
text.as_ref(),
self.font.clone(),
)))
}
#[must_use]
pub fn measure_rich_text(&self, spans: &[RichSpan]) -> TextMeasure {
measure_text(spans, self.font.max_width)
}
#[must_use]
pub fn measure_size(&self, text: impl AsRef<str>) -> Size {
self.measure_text(text).size
}
#[must_use]
pub fn draw_image(&self, image: SceneImage, x: f64, y: f64, w: f64, h: f64) -> SceneNode {
self.node(Element::Image {
image,
frame: Rect::new(x, y, x + w, y + h),
opacity: self.alpha,
})
}
#[must_use]
pub fn draw_image_at_size(&self, image: SceneImage, x: f64, y: f64) -> SceneNode {
let (w, h) = (image.width() as f64, image.height() as f64);
self.draw_image(image, x, y, w, h)
}
#[must_use]
pub fn fill_rect(&self, x: f64, y: f64, w: f64, h: f64) -> SceneNode {
self.node(Element::rect(
Rect::new(x, y, x + w, y + h),
FillStrokeStyle {
fill: self.fill.clone(),
stroke: None,
},
))
}
#[must_use]
pub fn stroke_rect(&self, x: f64, y: f64, w: f64, h: f64) -> SceneNode {
self.node(Element::rect(
Rect::new(x, y, x + w, y + h),
FillStrokeStyle {
fill: None,
stroke: Some(self.stroke_or_default()),
},
))
}
#[must_use]
pub fn fill_stroke_rect(&self, x: f64, y: f64, w: f64, h: f64) -> SceneNode {
self.node(Element::rect(
Rect::new(x, y, x + w, y + h),
self.fill_stroke(),
))
}
#[must_use]
pub fn round_rect(&self, x: f64, y: f64, w: f64, h: f64, radius: f64) -> SceneNode {
self.node(Element::RoundedRect {
rect: Rect::new(x, y, x + w, y + h),
radii: radius.into(),
style: self.fill_stroke(),
})
}
#[must_use]
pub fn round_rect_radii(
&self,
x: f64,
y: f64,
w: f64,
h: f64,
radii: crate::scene::CornerRadii,
) -> SceneNode {
self.node(Element::RoundedRect {
rect: Rect::new(x, y, x + w, y + h),
radii,
style: self.fill_stroke(),
})
}
#[must_use]
pub fn fill_circle(&self, x: f64, y: f64, r: f64) -> SceneNode {
self.node(Element::circle(
Point::new(x, y),
r,
FillStrokeStyle {
fill: self.fill.clone(),
stroke: None,
},
))
}
#[must_use]
pub fn stroke_circle(&self, x: f64, y: f64, r: f64) -> SceneNode {
self.node(Element::circle(
Point::new(x, y),
r,
FillStrokeStyle {
fill: None,
stroke: Some(self.stroke_or_default()),
},
))
}
#[must_use]
pub fn fill_ellipse(&self, x: f64, y: f64, rx: f64, ry: f64, rotation: f64) -> SceneNode {
self.node(Element::ellipse(
Point::new(x, y),
Vec2::new(rx, ry),
rotation,
self.fill_stroke(),
))
}
#[must_use]
pub fn pie(&self, cx: f64, cy: f64, r: f64, start_angle: f64, sweep_angle: f64) -> SceneNode {
self.node(Element::Pie {
center: Point::new(cx, cy),
radius: r,
start_angle,
sweep_angle,
style: self.fill_stroke(),
})
}
#[must_use]
pub fn arc(
&self,
cx: f64,
cy: f64,
rx: f64,
ry: f64,
start_angle: f64,
sweep_angle: f64,
) -> SceneNode {
self.node(Element::Arc {
center: Point::new(cx, cy),
radii: Vec2::new(rx, ry),
start_angle,
sweep_angle,
style: self.stroke_or_default(),
})
}
#[must_use]
pub fn line(&self, x0: f64, y0: f64, x1: f64, y1: f64) -> SceneNode {
self.node(Element::line(
Point::new(x0, y0),
Point::new(x1, y1),
self.stroke_or_default(),
))
}
#[must_use]
pub fn polyline(&self, pts: &[(f64, f64)]) -> SceneNode {
self.node(Element::poly(to_points(pts), self.stroke_or_default()))
}
#[must_use]
pub fn polygon(&self, pts: &[(f64, f64)]) -> SceneNode {
self.node(Element::polygon(to_points(pts), self.fill_stroke()))
}
#[must_use]
pub fn fill(&self, path: &Path2D) -> SceneNode {
self.node(Element::Path {
path: path.path.clone(),
style: FillStrokeStyle {
fill: self.fill.clone(),
stroke: None,
},
closed: true,
})
}
#[must_use]
pub fn stroke(&self, path: &Path2D) -> SceneNode {
self.node(Element::Path {
path: path.path.clone(),
style: FillStrokeStyle {
fill: None,
stroke: Some(self.stroke_or_default()),
},
closed: path.closed,
})
}
#[must_use]
pub fn fill_stroke_path(&self, path: &Path2D) -> SceneNode {
self.node(Element::Path {
path: path.path.clone(),
style: self.fill_stroke(),
closed: path.closed,
})
}
#[must_use]
pub fn path(&self, path: BezPath, closed: bool) -> SceneNode {
self.node(Element::Path {
path,
style: self.fill_stroke(),
closed,
})
}
#[must_use]
pub fn boolean_path(&self, a: &BezPath, b: &BezPath, op: BoolOp) -> SceneNode {
self.path(a.boolean(b, op, DEFAULT_TOLERANCE), true)
}
#[must_use]
pub fn outline_path(&self, path: &BezPath, stroke: &Stroke) -> SceneNode {
self.node(Element::Path {
path: path.outline(stroke, DEFAULT_TOLERANCE),
style: FillStrokeStyle {
fill: Some(Fill::Solid(stroke.color)),
stroke: None,
},
closed: false,
})
}
#[must_use]
pub fn gradient_path(
&self,
path: BezPath,
gradient: crate::scene::LinearGradient,
) -> SceneNode {
self.node(Element::GradientPath {
path,
gradient,
stroke: self.stroke.clone(),
})
}
#[must_use]
pub fn group(&self, children: Vec<SceneNode>) -> SceneNode {
self.attrs(SceneNode::group(children))
}
#[must_use]
pub fn layer(&self, name: impl Into<String>) -> Layer {
let mut l = Layer::new(name);
if let Some(t) = self.transform {
l = l.with_transform(t);
}
if (self.alpha - 1.0).abs() > f64::EPSILON {
l = l.with_opacity(self.alpha);
}
if !self.blend_mode.is_normal() {
l = l.with_blend_mode(self.blend_mode);
}
l
}
}
fn first_stop_color(stops: &[crate::scene::GradientStop]) -> Option<Color> {
stops.iter().map(|s| s.color).next()
}
fn to_points(pts: &[(f64, f64)]) -> Vec<Point> {
pts.iter().map(|&(x, y)| Point::new(x, y)).collect()
}
#[derive(Debug, Clone, Default)]
pub struct Path2D {
path: BezPath,
started: bool,
closed: bool,
}
impl Path2D {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn from_bezpath(path: BezPath) -> Self {
let closed = path
.elements()
.last()
.is_some_and(|el| matches!(el, kurbo::PathEl::ClosePath));
Self {
started: !path.elements().is_empty(),
path,
closed,
}
}
#[must_use]
pub fn as_bezpath(&self) -> &BezPath {
&self.path
}
#[must_use]
pub fn into_bezpath(self) -> BezPath {
self.path
}
#[must_use]
pub fn is_closed(&self) -> bool {
self.closed
}
pub fn move_to(&mut self, x: f64, y: f64) -> &mut Self {
self.path.move_to((x, y));
self.started = true;
self.closed = false;
self
}
pub fn line_to(&mut self, x: f64, y: f64) -> &mut Self {
if self.started {
self.path.line_to((x, y));
} else {
self.path.move_to((x, y));
self.started = true;
}
self
}
pub fn hline_to(&mut self, x: f64) -> &mut Self {
let y = self.current_point().map(|p| p.y).unwrap_or(0.0);
self.line_to(x, y)
}
pub fn vline_to(&mut self, y: f64) -> &mut Self {
let x = self.current_point().map(|p| p.x).unwrap_or(0.0);
self.line_to(x, y)
}
pub fn quad_to(&mut self, cx: f64, cy: f64, x: f64, y: f64) -> &mut Self {
if !self.started {
self.path.move_to((cx, cy));
self.started = true;
}
self.path.quad_to((cx, cy), (x, y));
self
}
pub fn curve_to(
&mut self,
c1x: f64,
c1y: f64,
c2x: f64,
c2y: f64,
x: f64,
y: f64,
) -> &mut Self {
if !self.started {
self.path.move_to((c1x, c1y));
self.started = true;
}
self.path.curve_to((c1x, c1y), (c2x, c2y), (x, y));
self
}
pub fn bezier_curve_to(
&mut self,
c1x: f64,
c1y: f64,
c2x: f64,
c2y: f64,
x: f64,
y: f64,
) -> &mut Self {
self.curve_to(c1x, c1y, c2x, c2y, x, y)
}
pub fn arc(
&mut self,
cx: f64,
cy: f64,
radius: f64,
start_angle: f64,
end_angle: f64,
) -> &mut Self {
self.ellipse(cx, cy, radius, radius, 0.0, start_angle, end_angle)
}
pub fn arc_ccw(
&mut self,
cx: f64,
cy: f64,
radius: f64,
start_angle: f64,
end_angle: f64,
) -> &mut Self {
self.ellipse(
cx,
cy,
radius,
radius,
0.0,
start_angle,
end_angle - std::f64::consts::TAU,
)
}
#[allow(clippy::too_many_arguments)]
pub fn ellipse(
&mut self,
cx: f64,
cy: f64,
rx: f64,
ry: f64,
rotation: f64,
start_angle: f64,
end_angle: f64,
) -> &mut Self {
let sweep = end_angle - start_angle;
if !sweep.is_finite() || sweep == 0.0 || !rx.is_finite() || !ry.is_finite() {
return self;
}
let (rx, ry) = (rx.abs(), ry.abs());
let n = ((sweep.abs() / std::f64::consts::FRAC_PI_2).ceil() as usize).max(1);
let step = sweep / n as f64;
let alpha = (4.0 / 3.0) * (step / 4.0).tan();
let (sin_r, cos_r) = rotation.sin_cos();
let center = Point::new(cx, cy);
let at = |theta: f64| -> Point {
let (s, c) = theta.sin_cos();
Point::new(
center.x + rx * c * cos_r - ry * s * sin_r,
center.y + rx * c * sin_r + ry * s * cos_r,
)
};
let tangent = |theta: f64| -> Point {
let (s, c) = theta.sin_cos();
Point::new(
-rx * s * cos_r - ry * c * sin_r,
-rx * s * sin_r + ry * c * cos_r,
)
};
let first = at(start_angle);
if self.started {
self.path.line_to(first);
} else {
self.path.move_to(first);
self.started = true;
}
let mut t = start_angle;
for _ in 0..n {
let p0 = at(t);
let p3 = at(t + step);
let d0 = tangent(t);
let d3 = tangent(t + step);
let c1 = Point::new(p0.x + alpha * d0.x, p0.y + alpha * d0.y);
let c2 = Point::new(p3.x - alpha * d3.x, p3.y - alpha * d3.y);
self.path.curve_to(c1, c2, p3);
t += step;
}
self
}
pub fn rect(&mut self, x: f64, y: f64, w: f64, h: f64) -> &mut Self {
self.path.move_to((x, y));
self.path.line_to((x + w, y));
self.path.line_to((x + w, y + h));
self.path.line_to((x, y + h));
self.path.close_path();
self.started = true;
self
}
pub fn round_rect(&mut self, x: f64, y: f64, w: f64, h: f64, radius: f64) -> &mut Self {
let r = kurbo::RoundedRect::new(x, y, x + w, y + h, radius);
self.path.extend(r.to_path(0.1));
self.started = true;
self
}
pub fn circle(&mut self, cx: f64, cy: f64, r: f64) -> &mut Self {
self.path
.extend(kurbo::Circle::new((cx, cy), r).to_path(0.1));
self.started = true;
self
}
pub fn add_path(&mut self, other: &Path2D, transform: Option<Transform>) -> &mut Self {
let els: Vec<_> = other.path.elements().to_vec();
let mut buf = BezPath::from_vec(els);
if let Some(t) = transform {
buf.apply_affine(t.to_kurbo());
}
self.path.extend(buf);
self.started = self.started || other.started;
self
}
pub fn close_path(&mut self) -> &mut Self {
self.path.close_path();
self.closed = true;
self
}
fn current_point(&self) -> Option<Point> {
self.path.elements().iter().rev().find_map(|el| match el {
kurbo::PathEl::MoveTo(p)
| kurbo::PathEl::LineTo(p)
| kurbo::PathEl::QuadTo(_, p)
| kurbo::PathEl::CurveTo(_, _, p) => Some(*p),
kurbo::PathEl::ClosePath => None,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::scene::{LinearGradient, NodeKind, ObjectFit, Scene, Stroke};
fn default_ctx() -> Ctx {
Ctx::new().with_fill(Color::rgb(0x33, 0x66, 0x99))
}
#[test]
fn fill_text_anchors_and_color() {
let ctx =
default_ctx().with_font(TextStyle::new(Color::rgb(0xff, 0, 0), 24.0, "sans-serif"));
match ctx
.fill_text(50.0, 50.0, "Hi")
.into_element()
.expect("leaf")
{
Element::Text {
spans,
position,
style,
layout,
} => {
assert_eq!(spans.len(), 1);
assert_eq!(spans[0].text, "Hi");
assert_eq!(spans[0].style.color, Color::rgb(0xff, 0, 0));
assert_eq!(position, Point::new(50.0, 50.0));
assert_eq!(style.font_size, 24.0);
if let Some(l) = layout {
assert!(!l.lines.is_empty());
assert!(l.width > 0.0 && l.height > 0.0);
}
}
_ => panic!("expected Text"),
}
}
#[test]
fn text_color_independent_of_shape_fill() {
let ctx = default_ctx().with_text_color(Color::rgb(0xff, 0, 0));
match ctx.fill_text(0.0, 0.0, "x").into_element().expect("leaf") {
Element::Text { spans, .. } => assert_eq!(spans[0].style.color, Color::rgb(0xff, 0, 0)),
_ => panic!("expected Text"),
}
match ctx
.fill_rect(0.0, 0.0, 1.0, 1.0)
.into_element()
.expect("leaf")
{
Element::Rect { style, .. } => {
assert_eq!(style.fill, Some(Fill::Solid(Color::rgb(0x33, 0x66, 0x99))));
}
_ => panic!("expected Rect"),
}
}
#[test]
fn rect_builders() {
let ctx = default_ctx();
match ctx
.fill_rect(10.0, 20.0, 30.0, 40.0)
.into_element()
.expect("leaf")
{
Element::Rect { rect, style } => {
assert_eq!(rect, Rect::new(10.0, 20.0, 40.0, 60.0));
assert!(style.fill.is_some() && style.stroke.is_none());
}
_ => panic!("expected Rect"),
}
let ctx = Ctx::new().with_stroke(Stroke::new(Color::BLACK, 2.0));
match ctx
.stroke_rect(0.0, 0.0, 5.0, 5.0)
.into_element()
.expect("leaf")
{
Element::Rect { rect, style } => {
assert_eq!(rect, Rect::new(0.0, 0.0, 5.0, 5.0));
assert_eq!(style.stroke.as_ref().unwrap().width, 2.0);
assert!(style.fill.is_none(), "stroke_rect 不应填充");
}
_ => panic!("expected Rect"),
}
}
#[test]
fn shape_builders() {
let ctx = Ctx::new()
.with_fill(Color::BLACK)
.with_stroke(Stroke::new(Color::BLACK, 1.0));
assert!(matches!(
ctx.line(0.0, 0.0, 1.0, 1.0).into_element().expect("leaf"),
Element::Line { .. }
));
assert!(matches!(
ctx.polyline(&[(0.0, 0.0), (1.0, 1.0), (2.0, 0.0)])
.into_element()
.expect("leaf"),
Element::Polyline { .. }
));
assert!(matches!(
ctx.polygon(&[(0.0, 0.0), (1.0, 1.0), (0.0, 1.0)])
.into_element()
.expect("leaf"),
Element::Polygon { .. }
));
assert!(matches!(
ctx.fill_circle(0.0, 0.0, 5.0).into_element().expect("leaf"),
Element::Circle { .. }
));
assert!(matches!(
ctx.fill_ellipse(0.0, 0.0, 4.0, 2.0, 0.0)
.into_element()
.expect("leaf"),
Element::Ellipse { .. }
));
}
#[test]
fn path_builder() {
let ctx = Ctx::new()
.with_fill(Color::BLACK)
.with_stroke(Stroke::new(Color::BLACK, 1.0));
let mut p = Path2D::new();
p.move_to(0.0, 0.0);
p.line_to(1.0, 0.0);
p.line_to(1.0, 1.0);
p.close_path();
match ctx
.path(p.into_bezpath(), true)
.into_element()
.expect("leaf")
{
Element::Path {
style,
closed,
path,
} => {
assert!(closed);
assert!(style.fill.is_some() && style.stroke.is_some());
assert!(!path.is_empty());
}
_ => panic!("expected Path"),
}
}
#[test]
fn measure_returns_size() {
let ctx = default_ctx().with_font(TextStyle::new(Color::BLACK, 20.0, "sans-serif"));
let m = ctx.measure_text("Hello");
assert!(m.size.width > 0.0 && m.size.height > 0.0);
assert!(m.metrics.width > 0.0);
}
#[test]
fn elements_are_pushable() {
let ctx = default_ctx();
let mut scene = Scene::new(100.0, 100.0);
scene.push(ctx.fill_rect(0.0, 0.0, 10.0, 10.0));
scene.push(ctx.fill_text(5.0, 5.0, "ok"));
assert_eq!(scene.nodes.len(), 2);
}
#[test]
fn path2d_fill_and_stroke_are_independent() {
let ctx = Ctx::new()
.with_fill(Color::RED)
.with_stroke(Stroke::new(Color::BLACK, 2.0));
let mut p = Path2D::new();
p.move_to(0.0, 0.0);
p.line_to(10.0, 0.0);
p.line_to(10.0, 10.0);
let filled = ctx.fill(&p).into_element().expect("leaf");
match &filled {
Element::Path { style, .. } => {
assert!(style.fill.is_some(), "fill 应带填充");
assert!(style.stroke.is_none(), "fill 不应描边");
}
_ => panic!("expected Path"),
}
let stroked = ctx.stroke(&p).into_element().expect("leaf");
match &stroked {
Element::Path { style, .. } => {
assert!(style.fill.is_none(), "stroke 不应填充");
assert_eq!(style.stroke.as_ref().unwrap().width, 2.0);
}
_ => panic!("expected Path"),
}
let both = ctx.fill_stroke_path(&p).into_element().expect("leaf");
match &both {
Element::Path { style, .. } => {
assert!(style.fill.is_some() && style.stroke.is_some());
}
_ => panic!("expected Path"),
}
}
#[test]
fn path2d_accumulates_segments() {
let mut p = Path2D::new();
p.move_to(0.0, 0.0);
p.line_to(10.0, 0.0);
p.quad_to(15.0, 5.0, 10.0, 10.0);
p.curve_to(5.0, 15.0, 0.0, 15.0, 0.0, 10.0);
p.close_path();
assert!(p.is_closed());
let els = p.as_bezpath().elements();
assert!(
els.iter()
.any(|e| matches!(e, kurbo::PathEl::CurveTo(_, _, _))),
"应包含三次贝塞尔段"
);
assert!(
els.iter().any(|e| matches!(e, kurbo::PathEl::QuadTo(_, _))),
"应包含二次贝塞尔段"
);
assert!(els.iter().any(|e| matches!(e, kurbo::PathEl::ClosePath)));
}
#[test]
fn path2d_line_to_on_empty_path_starts_subpath() {
let mut p = Path2D::new();
p.line_to(5.0, 5.0);
assert!(!p.as_bezpath().elements().is_empty());
p.hline_to(10.0);
p.vline_to(0.0);
let els = p.as_bezpath().elements();
assert_eq!(els.len(), 3, "got {els:?}");
}
#[test]
fn path2d_arc_generates_bezier_segments() {
let mut p = Path2D::new();
p.arc(0.0, 0.0, 10.0, 0.0, std::f64::consts::FRAC_PI_2);
let els = p.as_bezpath().elements().to_vec();
assert!(
els.iter()
.any(|e| matches!(e, kurbo::PathEl::CurveTo(_, _, _))),
"应生成贝塞尔段: {els:?}"
);
let last = els.iter().rev().find_map(|e| match e {
kurbo::PathEl::CurveTo(_, _, p) | kurbo::PathEl::LineTo(p) => Some(*p),
_ => None,
});
assert!(last.is_some());
let last = last.unwrap();
assert!(
(last.x - 0.0).abs() < 1e-9 && (last.y - 10.0).abs() < 1e-9,
"got {last:?}"
);
}
#[test]
fn node_attributes_are_applied() {
let ctx = Ctx::new()
.with_fill(Color::BLACK)
.with_alpha(0.5)
.with_name("box")
.with_z(3)
.with_clip(Clip::rect(Rect::new(0.0, 0.0, 10.0, 10.0)));
let n = ctx.fill_rect(0.0, 0.0, 5.0, 5.0);
assert_eq!(n.opacity, 0.5);
assert_eq!(n.name.as_deref(), Some("box"));
assert_eq!(n.z_index, 3);
assert!(n.clip.is_some());
assert!(n.transform.is_none());
let n = ctx
.clone()
.translate(10.0, 20.0)
.fill_rect(0.0, 0.0, 5.0, 5.0);
let t = n.transform.unwrap();
let p = t.apply_point(Point::new(1.0, 1.0));
assert_eq!(p, Point::new(11.0, 21.0));
}
#[test]
fn transforms_compose() {
let ctx = Ctx::new().translate(10.0, 0.0).scale(2.0);
let t = ctx.fill_rect(0.0, 0.0, 1.0, 1.0).transform.unwrap();
let p = t.apply_point(Point::new(1.0, 1.0));
assert_eq!(p, Point::new(12.0, 2.0), "先平移再缩放 → (1+10)*2");
}
#[test]
fn fine_grained_stroke_settings() {
let ctx = Ctx::new()
.with_stroke(Stroke::new(Color::RED, 3.0))
.with_line_cap(crate::scene::LineCap::Round)
.with_line_join(crate::scene::LineJoin::Bevel)
.with_miter_limit(4.0)
.with_dash(vec![2.0, 1.0], 0.5);
let s = ctx.stroke.clone().unwrap();
assert_eq!(s.color, Color::RED);
assert_eq!(s.width, 3.0);
assert_eq!(s.line_cap, crate::scene::LineCap::Round);
assert_eq!(s.line_join, crate::scene::LineJoin::Bevel);
assert_eq!(s.miter_limit, 4.0);
assert_eq!(s.dash_array, vec![2.0, 1.0]);
assert_eq!(s.dash_offset, 0.5);
let s2 = ctx.with_line_width(7.0).stroke.unwrap();
assert_eq!(s2.width, 7.0);
assert_eq!(s2.color, Color::RED);
assert_eq!(s2.line_cap, crate::scene::LineCap::Round);
let s3 = Ctx::new()
.with_fill(Color::BLUE)
.with_line_width(2.0)
.stroke
.unwrap();
assert_eq!(s3.color, Color::BLUE);
assert_eq!(s3.width, 2.0);
}
#[test]
fn gradient_fill() {
let g = LinearGradient::new(
Point::new(0.0, 0.0),
Point::new(100.0, 0.0),
vec![crate::scene::GradientStop {
offset: 0.0,
color: Color::RED,
}],
);
let ctx = Ctx::new().with_fill_gradient(g.clone());
match ctx
.fill_rect(0.0, 0.0, 10.0, 10.0)
.into_element()
.expect("leaf")
{
Element::Rect { style, .. } => {
assert!(matches!(style.fill, Some(Fill::LinearGradient(_))));
}
_ => panic!("expected Rect"),
}
let s = Ctx::new()
.with_fill_gradient(g)
.with_line_width(1.0)
.stroke
.unwrap();
assert_eq!(s.color, Color::RED);
}
#[test]
fn rich_text_spans_keep_their_styles() {
let ctx = Ctx::new().with_font(TextStyle::new(Color::BLACK, 12.0, "sans-serif"));
let spans = vec![
RichSpan::new("bold ", TextStyle::new(Color::RED, 20.0, "sans-serif")),
RichSpan::new("plain", TextStyle::new(Color::BLUE, 12.0, "sans-serif")),
];
match ctx
.fill_rich_text(0.0, 0.0, spans)
.into_element()
.expect("leaf")
{
Element::Text { spans, .. } => {
assert_eq!(spans.len(), 2);
assert_eq!(spans[0].style.color, Color::RED);
assert_eq!(spans[0].style.font_size, 20.0);
assert_eq!(spans[1].style.color, Color::BLUE);
}
_ => panic!("expected Text"),
}
let spans = vec![RichSpan::new(
"hello",
TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
)];
assert!(ctx.measure_rich_text(&spans).size.width >= 0.0);
}
#[test]
fn draw_image_builders() {
let img = SceneImage::from_rgba8(4, 2, vec![0u8; 4 * 2 * 4]).unwrap();
let ctx = Ctx::new();
match ctx
.draw_image(img.clone(), 1.0, 2.0, 100.0, 50.0)
.into_element()
.expect("leaf")
{
Element::Image { frame, .. } => {
assert_eq!(frame, Rect::new(1.0, 2.0, 101.0, 52.0));
}
_ => panic!("expected Image"),
}
match ctx
.draw_image_at_size(img, 1.0, 2.0)
.into_element()
.expect("leaf")
{
Element::Image { frame, .. } => {
assert_eq!(frame, Rect::new(1.0, 2.0, 5.0, 4.0), "应为原始像素尺寸");
}
_ => panic!("expected Image"),
}
}
#[test]
fn image_opacity_follows_alpha() {
let img = SceneImage::from_rgba8(1, 1, vec![0u8; 4]).unwrap();
let node = Ctx::new().with_alpha(0.4).draw_image_at_size(img, 0.0, 0.0);
assert_eq!(node.opacity, 0.4);
match node.element().expect("leaf") {
Element::Image { opacity, .. } => assert!((opacity - 0.4).abs() < 1e-9),
_ => panic!("expected Image"),
}
}
#[test]
fn group_carries_context_attributes() {
let ctx = Ctx::new().with_alpha(0.5).translate(1.0, 1.0);
let child = ctx.fill_rect(0.0, 0.0, 1.0, 1.0);
let g = ctx.group(vec![child]);
assert_eq!(g.opacity, 0.5);
assert!(g.transform.is_some());
match &g.kind {
NodeKind::Group(children) => assert_eq!(children.len(), 1),
_ => panic!("expected Group"),
}
}
#[test]
fn layer_accepts_ctx_output() {
let ctx = Ctx::new().with_fill(Color::BLACK);
let mut layer = ctx.clone().with_alpha(0.5).layer("grid");
layer.push(ctx.fill_rect(0.0, 0.0, 1.0, 1.0));
assert_eq!(layer.nodes.len(), 1);
assert_eq!(layer.name, "grid");
assert_eq!(layer.opacity, 0.5);
}
#[test]
fn pie_and_arc_helpers() {
let ctx = Ctx::new()
.with_fill(Color::RED)
.with_stroke(Stroke::new(Color::BLACK, 1.0));
match ctx
.pie(5.0, 5.0, 10.0, 0.0, std::f64::consts::FRAC_PI_2)
.into_element()
.expect("leaf")
{
Element::Pie { center, radius, .. } => {
assert_eq!(center, Point::new(5.0, 5.0));
assert_eq!(radius, 10.0);
}
_ => panic!("expected Pie"),
}
match ctx
.arc(5.0, 5.0, 10.0, 20.0, 0.0, std::f64::consts::FRAC_PI_2)
.into_element()
.expect("leaf")
{
Element::Arc { center, radii, .. } => {
assert_eq!(center, Point::new(5.0, 5.0));
assert_eq!(radii, Vec2::new(10.0, 20.0));
}
_ => panic!("expected Arc"),
}
}
#[test]
fn round_rect_helper() {
let ctx = Ctx::new().with_fill(Color::BLACK);
match ctx
.round_rect(1.0, 2.0, 3.0, 4.0, 0.5)
.into_element()
.expect("leaf")
{
Element::RoundedRect { rect, radii, .. } => {
assert_eq!(rect, Rect::new(1.0, 2.0, 4.0, 6.0));
assert_eq!(radii.uniform_value(), 0.5);
assert!(radii.is_uniform());
}
_ => panic!("expected RoundedRect"),
}
}
#[test]
fn without_fill_or_stroke() {
let ctx = Ctx::new()
.with_fill(Color::RED)
.with_stroke(Stroke::new(Color::BLUE, 2.0));
match ctx
.clone()
.without_fill()
.fill_stroke_rect(0.0, 0.0, 1.0, 1.0)
.into_element()
.expect("leaf")
{
Element::Rect { style, .. } => {
assert!(style.fill.is_none() && style.stroke.is_some())
}
_ => panic!("expected Rect"),
}
match ctx
.without_stroke()
.fill_stroke_rect(0.0, 0.0, 1.0, 1.0)
.into_element()
.expect("leaf")
{
Element::Rect { style, .. } => {
assert!(style.fill.is_some() && style.stroke.is_none())
}
_ => panic!("expected Rect"),
}
}
#[test]
fn object_fit_is_orthogonal() {
let img = SceneImage::from_rgba8(1, 1, vec![0u8; 4])
.unwrap()
.with_object_fit(ObjectFit::Cover);
match Ctx::new()
.draw_image_at_size(img, 0.0, 0.0)
.into_element()
.expect("leaf")
{
Element::Image { image, .. } => assert_eq!(image.object_fit, ObjectFit::Cover),
_ => panic!("expected Image"),
}
}
}