use kurbo::Shape;
use crate::geometry::{Point, Rect, Size, Transform, Vec2};
use crate::scene::{Element, NodeKind, Scene, SceneNode, Stroke};
pub fn element_bounds(element: &Element) -> Option<Rect> {
let box_ = match element {
Element::Rect { rect, style } => {
let mut r = normalized(*rect);
if let Some(pad) = stroke_inset(style.stroke.as_ref()) {
r = r.inflate(pad, pad);
}
Some(r)
}
Element::RoundedRect {
rect,
radii: _,
style,
} => {
let mut r = normalized(*rect);
if let Some(pad) = stroke_inset(style.stroke.as_ref()) {
r = r.inflate(pad, pad);
}
Some(r)
}
Element::Circle {
center,
radius,
style,
} => circle_box(*center, *radius, style.stroke.as_ref()),
Element::Ellipse {
center,
radii,
rotation,
style,
} => {
let e = kurbo::Ellipse::new(
(center.x, center.y),
(radii.x.abs(), radii.y.abs()),
*rotation,
);
inflate_opt(e.bounding_box(), style.stroke.as_ref())
}
Element::Line { start, end, style } => {
let r = Rect::from_points(*start, *end);
inflate_opt(r, Some(style))
}
Element::Polyline { points, style } => points_box(points).map(|r| inflate(r, Some(style))),
Element::Polygon { points, style } => {
points_box(points).map(|r| inflate(r, style.stroke.as_ref()))
}
Element::Arc {
center,
radii,
start_angle,
sweep_angle,
style,
} => inflate_opt(
arc_box(*center, *radii, *start_angle, *sweep_angle),
Some(style),
),
Element::Pie {
center,
radius,
start_angle: _,
sweep_angle: _,
style,
} => circle_box(*center, *radius, style.stroke.as_ref()),
Element::Path { path, style, .. } => {
inflate_opt(path.bounding_box(), style.stroke.as_ref())
}
Element::GradientPath {
path,
gradient: _,
stroke,
} => inflate_opt(path.bounding_box(), stroke.as_ref()),
Element::Image {
image,
frame,
opacity: _,
} => {
let mut r = normalized(*frame);
if image.object_fit == crate::scene::ObjectFit::None {
r = r.union(Rect::from_origin_size(
Point::new(r.min_x(), r.min_y()),
Size::new(image.width() as f64, image.height() as f64),
));
}
Some(r)
}
Element::Text {
spans,
position,
style,
layout,
} => text_box(spans, *position, style, layout.as_deref()),
};
box_.filter(|r| r.is_finite() && r.width() >= 0.0 && r.height() >= 0.0)
}
fn inflate_opt(r: Rect, stroke: Option<&Stroke>) -> Option<Rect> {
Some(inflate(r, stroke))
}
fn inflate(r: Rect, stroke: Option<&Stroke>) -> Rect {
match stroke_inset(stroke) {
Some(pad) => r.inflate(pad, pad),
None => r,
}
}
fn stroke_inset(stroke: Option<&Stroke>) -> Option<f64> {
let w = stroke.map(|s| s.width).unwrap_or(0.0);
if w.is_finite() && w > 0.0 {
Some(w / 2.0)
} else {
None
}
}
fn normalized(r: Rect) -> Rect {
Rect::new(
r.min_x().min(r.max_x()),
r.min_y().min(r.max_y()),
r.max_x().max(r.min_x()),
r.max_y().max(r.min_y()),
)
}
fn circle_box(center: Point, radius: f64, stroke: Option<&Stroke>) -> Option<Rect> {
let r = radius.abs();
if !r.is_finite() {
return None;
}
inflate_opt(
Rect::new(center.x - r, center.y - r, center.x + r, center.y + r),
stroke,
)
}
fn union_all(boxes: impl IntoIterator<Item = Rect>) -> Option<Rect> {
boxes.into_iter().reduce(|a, b| a.union(b))
}
fn points_box(points: &[Point]) -> Option<Rect> {
union_all(
points
.iter()
.filter(|p| p.is_finite())
.map(|p| Rect::from_points(*p, *p)),
)
}
fn pt_box(p: Point) -> Rect {
Rect::from_points(p, p)
}
fn arc_box(center: Point, radii: Vec2, start_angle: f64, sweep_angle: f64) -> Rect {
let rx = radii.x.abs();
let ry = radii.y.abs();
let at = |theta: f64| Point::new(center.x + rx * theta.cos(), center.y + ry * theta.sin());
let (lo, hi) = if sweep_angle >= 0.0 {
(start_angle, start_angle + sweep_angle)
} else {
(start_angle + sweep_angle, start_angle)
};
let mut pts = vec![at(start_angle), at(start_angle + sweep_angle)];
if lo.is_finite() && hi.is_finite() {
for k in [
0.0,
std::f64::consts::PI,
std::f64::consts::FRAC_PI_2,
-std::f64::consts::FRAC_PI_2,
] {
let n = ((lo - k) / std::f64::consts::TAU).ceil();
let theta = k + n * std::f64::consts::TAU;
if theta <= hi {
pts.push(at(theta));
}
}
}
union_all(pts.into_iter().filter(|p| p.is_finite()).map(pt_box))
.unwrap_or_else(|| pt_box(center))
}
fn text_box(
spans: &[crate::text::RichSpan],
position: Point,
style: &crate::text::TextStyle,
layout: Option<&crate::text::TextLayout>,
) -> Option<Rect> {
let m = match layout {
Some(l) => crate::text::layout_metrics(l),
None => crate::text::measure_text(spans, style.max_width).metrics,
};
let (w, h) = (m.width, m.height);
if !w.is_finite() || !h.is_finite() || w <= 0.0 || h <= 0.0 {
return None;
}
let (x0, x1) = match style.align {
crate::text::TextAlign::Left | crate::text::TextAlign::Justify => {
(position.x, position.x + w)
}
crate::text::TextAlign::Center => (position.x - w / 2.0, position.x + w / 2.0),
crate::text::TextAlign::Right => (position.x - w, position.x),
};
let shift = style.baseline_shift;
let block_top = position.y - style.baseline.anchor_offset(&m);
let (y0, y1) = (block_top + shift, block_top + h + shift);
let mut r = Rect::new(x0, y0, x1, y1);
if style.rotation != 0.0 && style.rotation.is_finite() {
let rot = Transform::rotate(style.rotation);
r = transform_box_about(&rot, r, position)?;
}
Some(r)
}
pub fn node_bounds(node: &SceneNode) -> Option<Rect> {
if !node.visible {
return None;
}
let local = match &node.kind {
NodeKind::Draw(element) => element_bounds(element)?,
NodeKind::Group(children) => nodes_bounds(children)?,
};
Some(match node.transform.as_ref() {
Some(t) => transform_box(t, local),
None => local,
})
}
pub fn nodes_bounds(nodes: &[SceneNode]) -> Option<Rect> {
union_all(nodes.iter().filter_map(node_bounds))
}
pub fn scene_bounds(scene: &Scene) -> Option<Rect> {
union_all(scene.root_lists().filter_map(|(nodes, t)| {
let b = nodes_bounds(nodes)?;
Some(match t {
Some(t) => transform_box(&t, b),
None => b,
})
}))
}
fn transform_box(t: &Transform, r: Rect) -> Rect {
transform_box_about(t, r, Point::ZERO).unwrap_or(r)
}
fn transform_box_about(t: &Transform, r: Rect, pivot: Point) -> Option<Rect> {
let corners = [
Point::new(r.min_x(), r.min_y()),
Point::new(r.max_x(), r.min_y()),
Point::new(r.max_x(), r.max_y()),
Point::new(r.min_x(), r.max_y()),
]
.into_iter()
.map(|c| {
let p = t.apply_point(Point::new(c.x - pivot.x, c.y - pivot.y));
Point::new(p.x + pivot.x, p.y + pivot.y)
});
union_all(corners.filter(|p| p.is_finite()).map(pt_box))
}
#[derive(Debug, Clone)]
pub struct FitOptions {
pub max_width: Option<f64>,
pub max_height: Option<f64>,
pub margin: f64,
pub upscale: bool,
pub empty_size: Option<Size>,
}
impl Default for FitOptions {
fn default() -> Self {
Self {
max_width: None,
max_height: None,
margin: 0.0,
upscale: false,
empty_size: None,
}
}
}
impl FitOptions {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_max_width(mut self, w: f64) -> Self {
self.max_width = Some(w);
self
}
#[must_use]
pub fn with_max_height(mut self, h: f64) -> Self {
self.max_height = Some(h);
self
}
#[must_use]
pub fn with_margin(mut self, margin: f64) -> Self {
self.margin = margin;
self
}
#[must_use]
pub fn with_upscale(mut self, upscale: bool) -> Self {
self.upscale = upscale;
self
}
#[must_use]
pub fn with_empty_size(mut self, size: Size) -> Self {
self.empty_size = Some(size);
self
}
}
pub fn fit_scene(scene: &mut Scene, opts: FitOptions) -> bool {
let margin = if opts.margin.is_finite() && opts.margin > 0.0 {
opts.margin
} else {
0.0
};
let Some(bbox) = scene_bounds(scene).filter(|r| r.is_finite()) else {
if let Some(size) = opts.empty_size {
scene.width = size.width;
scene.height = size.height;
return true;
}
return false;
};
let content_w = (bbox.width()).max(1.0);
let content_h = (bbox.height()).max(1.0);
let avail_w =
sanitize_max(opts.max_width).map_or(f64::INFINITY, |w| (w - 2.0 * margin).max(1.0));
let avail_h =
sanitize_max(opts.max_height).map_or(f64::INFINITY, |h| (h - 2.0 * margin).max(1.0));
let natural = (avail_w / content_w).min(avail_h / content_h);
let natural = if natural.is_finite() { natural } else { 1.0 };
let max_scale = if opts.upscale { f64::MAX } else { 1.0 };
let scale = natural.clamp(f64::MIN_POSITIVE, max_scale);
scene.width = content_w * scale + 2.0 * margin;
scene.height = content_h * scale + 2.0 * margin;
let offset_x = margin - bbox.min_x() * scale;
let offset_y = margin - bbox.min_y() * scale;
if offset_x.abs() < 0.5 && offset_y.abs() < 0.5 && (scale - 1.0).abs() < 1e-3 {
return true;
}
let fit = Transform::translate(offset_x, offset_y).then(&Transform::scale(scale));
if !scene.nodes.is_empty() {
let children = std::mem::take(&mut scene.nodes);
scene
.nodes
.push(SceneNode::group(children).with_transform(fit));
}
for layer in &mut scene.layers {
layer.transform = Some(match layer.transform.take() {
Some(t) => t.then(&fit),
None => fit,
});
}
true
}
fn sanitize_max(v: Option<f64>) -> Option<f64> {
v.filter(|v| v.is_finite() && *v > 0.0)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geometry::Color;
use crate::scene::{Element, FillStrokeStyle, Layer, ObjectFit, SceneImage};
use crate::text::TextStyle;
fn rect_node(x0: f64, y0: f64, x1: f64, y1: f64) -> SceneNode {
SceneNode::new(Element::rect(
Rect::new(x0, y0, x1, y1),
FillStrokeStyle::default(),
))
}
fn scene_with(nodes: Vec<SceneNode>) -> Scene {
let mut s = Scene::new(0.0, 0.0);
s.nodes = nodes;
s
}
#[test]
fn element_bounds_includes_stroke_half_width() {
let el = Element::rect(
Rect::new(0.0, 0.0, 100.0, 100.0),
FillStrokeStyle {
fill: None,
stroke: Some(Stroke::new(Color::BLACK, 10.0)),
},
);
let b = element_bounds(&el).unwrap();
assert_eq!((b.min_x(), b.min_y()), (-5.0, -5.0));
assert_eq!((b.max_x(), b.max_y()), (105.0, 105.0));
}
#[test]
fn line_bounds_includes_stroke_half_width() {
let el = Element::Line {
start: Point::new(0.0, 0.0),
end: Point::new(100.0, 0.0),
style: Stroke::new(Color::BLACK, 20.0),
};
let b = element_bounds(&el).unwrap();
assert_eq!(b.min_y(), -10.0, "水平线应上下各扩展半个线宽");
assert_eq!(b.max_y(), 10.0);
}
#[test]
fn node_bounds_applies_transform() {
let node =
rect_node(0.0, 0.0, 10.0, 10.0).with_transform(Transform::translate(100.0, 50.0));
let b = node_bounds(&node).unwrap();
assert_eq!((b.min_x(), b.min_y()), (100.0, 50.0));
assert_eq!((b.max_x(), b.max_y()), (110.0, 60.0));
}
#[test]
fn node_bounds_applies_rotation() {
let node = rect_node(0.0, 0.0, 10.0, 10.0)
.with_transform(Transform::rotate(std::f64::consts::FRAC_PI_2));
let b = node_bounds(&node).unwrap();
assert!((b.min_x() + 10.0).abs() < 1e-9, "got {b:?}");
assert!((b.max_x()).abs() < 1e-9, "got {b:?}");
assert!((b.min_y()).abs() < 1e-9, "got {b:?}");
assert!((b.max_y() - 10.0).abs() < 1e-9, "got {b:?}");
}
#[test]
fn invisible_nodes_are_skipped() {
let node = rect_node(0.0, 0.0, 1000.0, 1000.0).with_visible(false);
assert_eq!(node_bounds(&node), None);
assert_eq!(nodes_bounds(&[node]), None);
}
#[test]
fn group_bounds_unions_children() {
let g = SceneNode::group(vec![
rect_node(0.0, 0.0, 10.0, 10.0),
rect_node(90.0, 40.0, 100.0, 50.0),
]);
let b = node_bounds(&g).unwrap();
assert_eq!(
(b.min_x(), b.min_y(), b.max_x(), b.max_y()),
(0.0, 0.0, 100.0, 50.0)
);
}
#[test]
fn arc_bounds_covers_only_the_swept_range() {
let b = arc_box(
Point::new(0.0, 0.0),
Vec2::new(10.0, 10.0),
0.0,
std::f64::consts::FRAC_PI_2,
);
assert!((b.min_x() - 0.0).abs() < 1e-9, "got {b:?}");
assert!((b.min_y() - 0.0).abs() < 1e-9, "got {b:?}");
assert!((b.max_x() - 10.0).abs() < 1e-9, "got {b:?}");
assert!((b.max_y() - 10.0).abs() < 1e-9, "got {b:?}");
let half = arc_box(
Point::new(0.0, 0.0),
Vec2::new(10.0, 10.0),
0.0,
std::f64::consts::PI,
);
assert!((half.min_y() - 0.0).abs() < 1e-9, "got {half:?}");
assert!((half.max_y() - 10.0).abs() < 1e-9, "got {half:?}");
}
#[test]
fn image_none_fit_may_overflow_frame() {
let img = SceneImage::from_rgba8(50, 20, vec![0u8; 50 * 20 * 4])
.unwrap()
.with_object_fit(ObjectFit::None);
let el = Element::Image {
image: img,
frame: Rect::new(0.0, 0.0, 10.0, 10.0),
opacity: 1.0,
};
let b = element_bounds(&el).unwrap();
assert_eq!(
(b.max_x(), b.max_y()),
(50.0, 20.0),
"应按原始像素尺寸溢出 frame"
);
}
#[test]
fn text_bounds_uses_real_measurement() {
let style = TextStyle::new(Color::BLACK, 16.0, "sans-serif");
let el = Element::Text {
spans: vec![crate::text::RichSpan::new("Hello", style.clone())],
position: Point::new(0.0, 0.0),
style,
layout: None,
};
let b = element_bounds(&el);
if let Some(b) = b {
assert!(b.width() > 0.0 && b.height() > 0.0, "got {b:?}");
}
}
#[test]
fn scene_bounds_covers_layers() {
let mut s = scene_with(vec![rect_node(0.0, 0.0, 10.0, 10.0)]);
let mut layer = Layer::new("overlay");
layer.push(rect_node(100.0, 100.0, 120.0, 120.0));
s.push_layer(layer);
let b = scene_bounds(&s).unwrap();
assert_eq!(
(b.min_x(), b.min_y(), b.max_x(), b.max_y()),
(0.0, 0.0, 120.0, 120.0)
);
}
#[test]
fn empty_scene_has_no_bounds() {
assert_eq!(scene_bounds(&scene_with(vec![])), None);
}
#[test]
fn fit_hugs_content_with_margin() {
let mut s = scene_with(vec![rect_node(20.0, 30.0, 120.0, 80.0)]);
assert!(fit_scene(&mut s, FitOptions::new().with_margin(8.0)));
assert_eq!(s.width, 116.0);
assert_eq!(s.height, 66.0);
let b = scene_bounds(&s).unwrap();
assert!((b.min_x() - 8.0).abs() < 1e-9, "got {b:?}");
assert!((b.min_y() - 8.0).abs() < 1e-9, "got {b:?}");
}
#[test]
fn fit_never_upscales_by_default() {
let mut s = scene_with(vec![rect_node(0.0, 0.0, 100.0, 100.0)]);
fit_scene(
&mut s,
FitOptions::new()
.with_max_width(800.0)
.with_max_height(600.0)
.with_margin(8.0),
);
assert!(
s.width < 200.0 && s.height < 200.0,
"got {}x{}",
s.width,
s.height
);
}
#[test]
fn fit_upscales_when_requested() {
let mut s = scene_with(vec![rect_node(0.0, 0.0, 100.0, 100.0)]);
fit_scene(
&mut s,
FitOptions::new()
.with_max_width(800.0)
.with_max_height(600.0)
.with_margin(8.0)
.with_upscale(true),
);
assert!(
s.width > 500.0 && s.height > 500.0,
"got {}x{}",
s.width,
s.height
);
}
#[test]
fn fit_single_axis_constraint_keeps_aspect() {
let mut s = scene_with(vec![rect_node(0.0, 0.0, 100.0, 100.0)]);
fit_scene(
&mut s,
FitOptions::new()
.with_max_width(500.0)
.with_margin(8.0)
.with_upscale(true),
);
assert!((s.width - 500.0).abs() < 1.0, "got {}", s.width);
assert!((s.height - 500.0).abs() < 1.0, "got {}", s.height);
let mut s = scene_with(vec![rect_node(0.0, 0.0, 100.0, 100.0)]);
fit_scene(
&mut s,
FitOptions::new()
.with_max_height(500.0)
.with_margin(8.0)
.with_upscale(true),
);
assert!((s.height - 500.0).abs() < 1.0, "got {}", s.height);
assert!((s.width - 500.0).abs() < 1.0, "got {}", s.width);
}
#[test]
fn fit_uses_uniform_scale() {
let mut s = scene_with(vec![rect_node(0.0, 0.0, 200.0, 100.0)]);
fit_scene(
&mut s,
FitOptions::new()
.with_max_width(1000.0)
.with_max_height(300.0)
.with_margin(0.0)
.with_upscale(true),
);
assert!((s.width - 600.0).abs() < 1e-6, "got {}", s.width);
assert!((s.height - 300.0).abs() < 1e-6, "got {}", s.height);
}
#[test]
fn fit_tiny_constraint_keeps_positive_canvas() {
let mut s = scene_with(vec![rect_node(0.0, 0.0, 100.0, 100.0)]);
fit_scene(
&mut s,
FitOptions::new()
.with_max_width(4.0)
.with_max_height(4.0)
.with_margin(8.0),
);
assert!(
s.width > 0.0 && s.height > 0.0,
"got {}x{}",
s.width,
s.height
);
assert!(s.width.is_finite() && s.height.is_finite());
}
#[test]
fn fit_empty_scene_uses_empty_size() {
let mut s = scene_with(vec![]);
assert!(fit_scene(
&mut s,
FitOptions::new().with_empty_size(Size::new(800.0, 600.0))
));
assert_eq!((s.width, s.height), (800.0, 600.0));
let mut s = Scene::new(123.0, 456.0);
assert!(!fit_scene(&mut s, FitOptions::new()));
assert_eq!((s.width, s.height), (123.0, 456.0));
}
#[test]
fn fit_skips_wrapping_when_already_placed() {
let mut s = scene_with(vec![rect_node(0.0, 0.0, 100.0, 50.0)]);
fit_scene(&mut s, FitOptions::new());
assert_eq!(s.nodes.len(), 1, "恒等变换不应包裹 Group");
assert!(matches!(s.nodes[0].element(), Some(Element::Rect { .. })));
assert_eq!((s.width, s.height), (100.0, 50.0));
}
#[test]
fn fit_moves_layers_together_with_nodes() {
let mut s = scene_with(vec![rect_node(1000.0, 1000.0, 1100.0, 1050.0)]);
let mut layer = Layer::new("overlay");
layer.push(rect_node(1000.0, 1000.0, 1100.0, 1050.0));
s.push_layer(layer);
fit_scene(&mut s, FitOptions::new().with_margin(5.0));
let b = scene_bounds(&s).unwrap();
assert!((b.min_x() - 5.0).abs() < 1e-6, "got {b:?}");
assert!((b.min_y() - 5.0).abs() < 1e-6, "got {b:?}");
assert!((b.width() - 100.0).abs() < 1e-6, "got {b:?}");
assert!((b.height() - 50.0).abs() < 1e-6, "got {b:?}");
}
#[test]
fn fit_composes_onto_existing_layer_transform() {
let mut s = Scene::new(0.0, 0.0);
let mut layer = Layer::new("shifted").with_transform(Transform::translate(1000.0, 0.0));
layer.push(rect_node(0.0, 0.0, 100.0, 50.0));
s.push_layer(layer);
fit_scene(&mut s, FitOptions::new().with_margin(5.0));
let b = scene_bounds(&s).unwrap();
assert!((b.min_x() - 5.0).abs() < 1e-6, "got {b:?}");
assert!((b.min_y() - 5.0).abs() < 1e-6, "got {b:?}");
}
#[test]
fn text_box_y_uses_real_alphabetic_baseline() {
let style = TextStyle::new(Color::BLACK, 16.0, "sans-serif");
let m = crate::text::measure_text(
std::slice::from_ref(&crate::text::RichSpan::new("Ag", style.clone())),
None,
);
if m.size.height <= 0.0 {
return; }
let pos = Point::new(10.0, 50.0);
let el = Element::Text {
spans: vec![crate::text::RichSpan::new("Ag", style.clone())],
position: pos,
style: style.clone(),
layout: Some(m.layout.clone()),
};
let b = element_bounds(&el).expect("有字体时应测得包围盒");
let expect_top = pos.y - m.metrics.alphabetic_baseline;
assert!(
(b.min_y() - expect_top).abs() < 1e-9,
"块顶应为 {expect_top}, got {}",
b.min_y()
);
assert!(
(b.max_y() - (expect_top + m.size.height)).abs() < 1e-9,
"块底应为 {}",
expect_top + m.size.height
);
}
}