layout: a layout reaching past the precision bound is refused (LayoutOutOfRange), never rounded

This commit is contained in:
Meta Vens 2026-11-28 06:19:04 +01:00
commit f34bc185ae
3 changed files with 89 additions and 13 deletions

View file

@ -37,6 +37,8 @@ pub enum Code {
StaleVersionIgnored,
/// A style slot holding a value its CSS counterpart forbids; the slot took its initial value.
StyleValueInvalid,
/// A laid node reaches past the precision bound: the layout is refused, never rounded.
LayoutOutOfRange,
}
impl Code {

View file

@ -18,7 +18,7 @@ use thing_contract::NodeId;
pub use measure::{Avail, Constraint, Leaf, Measure};
use crate::bind::BoundTree;
use crate::diagnostic::Diagnostic;
use crate::diagnostic::{Code, Diagnostic};
/// The stack one level of nesting takes inside Taffy's recursion, worst of Flex, Grid, Block and
/// scroll boxes, measured in a debug build by `stack_per_level` in tests/layout.rs, doubled.
@ -82,16 +82,31 @@ pub enum FrameError {
Viewport,
}
pub fn layout(tree: &BoundTree, frame: &LayoutFrame, measure: &mut dyn Measure) -> Result<LaidTree, FrameError> {
/// Why no layout came back. The frame owner keeps the last good `LaidTree` on either and shows
/// the diagnostic of `OutOfRange` (code `LayoutOutOfRange`, naming the first offending node in
/// document order).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LayoutError {
Frame(FrameError),
OutOfRange(Diagnostic),
}
impl From<FrameError> for LayoutError {
fn from(error: FrameError) -> Self {
LayoutError::Frame(error)
}
}
pub fn layout(tree: &BoundTree, frame: &LayoutFrame, measure: &mut dyn Measure) -> Result<LaidTree, LayoutError> {
let k = match frame.metrics {
Metrics::Cells => 1.0,
Metrics::Pixels if frame.scale.is_finite() && frame.scale > 0.0 && frame.scale <= 1024.0 => frame.scale,
Metrics::Pixels => return Err(FrameError::Scale),
Metrics::Pixels => return Err(FrameError::Scale.into()),
};
let dev = Device::new(k);
let side = |v: f32| (v.is_finite() && v > 0.0 && dev.px(v) <= MAX_DEVICE).then(|| dev.px(v));
let (Some(vw), Some(vh)) = (side(frame.viewport.0), side(frame.viewport.1)) else {
return Err(FrameError::Viewport);
return Err(FrameError::Viewport.into());
};
let mut built = tree::build(tree, dev, (vw, vh), measure);
let tree::Built { taffy, root, entries, leaves, diagnostics } = &mut built;
@ -131,6 +146,17 @@ pub fn layout(tree: &BoundTree, frame: &LayoutFrame, measure: &mut dyn Measure)
let round = |v: f32| (v + 0.5).floor();
(clean(round(overflow.right).max(w)), clean(round(overflow.bottom).max(h)))
});
// Precision is a property of the whole layout: a position or an extent past the bound
// (a sum along an axis included) refuses it, so no value is silently rounded.
let reach = [x, y, x + w, y + h, content.map_or(0.0, |c| c.0), content.map_or(0.0, |c| c.1)];
if reach.iter().any(|v| !v.is_finite() || v.abs() > MAX_DEVICE) {
return Err(LayoutError::OutOfRange(Diagnostic {
code: Code::LayoutOutOfRange,
surface: tree.resolved().document().record_key(),
node: Some(entry.id.clone()),
detail: "position or extent past the precision bound".to_string(),
}));
}
nodes.push(LaidNode {
id: entry.id.clone(),
rect: Rect { x: clean(x), y: clean(y), w: clean(w), h: clean(h) },

View file

@ -8,7 +8,7 @@ use taffy::{AlignContent, AlignItems, AvailableSpace, FlexDirection, Style, Taff
use thing_contract::*;
use thing_core::bind::{Binder, BoundTree};
use thing_core::diagnostic::Code;
use thing_core::layout::{Constraint, FrameError, LaidNode, LaidTree, LayoutFrame, Leaf, Measure, Metrics, layout};
use thing_core::layout::{Constraint, FrameError, LaidNode, LayoutError, LaidTree, LayoutFrame, Leaf, Measure, Metrics, layout};
use thing_core::port::Ledger;
use thing_core::resolve::{Limits, resolve};
use thing_testkit::build::*;
@ -769,9 +769,13 @@ fn extreme_values_never_panic() {
}
}
let tree = bind(&mut MemState::new(), &surface_of(bx("root", plain(), vec![text("t", "x"), text("u", "y")]))).unwrap();
let laid = layout(&tree, &pixels(800.0, 600.0, 1.0), &mut Huge).unwrap();
assert_eq!(laid.nodes.len(), 3);
assert!(laid.nodes.iter().all(|n| n.rect.w <= 2_097_152.0 && n.rect.h <= 2_097_152.0), "{laid:?}");
// Two clamped texts side by side reach past the bound together: refused, naming the second.
match layout(&tree, &pixels(800.0, 600.0, 1.0), &mut Huge) {
Err(LayoutError::OutOfRange(d)) => {
assert_eq!((d.code, d.node.as_ref().map(|n| n.as_str())), (Code::LayoutOutOfRange, Some("u")));
}
other => panic!("{other:?}"),
}
}
#[test]
@ -806,7 +810,15 @@ fn image_measures_never_resize_fixed_siblings() {
for root_style in [plain(), sized(800.0, 600.0)] {
let root = bx("root", BoxStyle { direction: direction.clone(), ..root_style }, siblings.clone());
let tree = bind(&mut MemState::new(), &surface_of(root)).unwrap();
let laid = layout(&tree, &pixels(800.0, 600.0, 1.0), &mut Image(size)).unwrap();
let laid = match layout(&tree, &pixels(800.0, 600.0, 1.0), &mut Image(size)) {
Ok(laid) => laid,
// Never a silent shift: the layout is refused outright.
Err(LayoutError::OutOfRange(d)) => {
assert_eq!(d.code, Code::LayoutOutOfRange);
continue;
}
Err(other) => panic!("{other:?}"),
};
assert!(laid.diagnostics.is_empty(), "{size:?}");
for (id, w, h) in [("e1", 16.0, 12.0), ("b1", 30.0, 20.0), ("e2", 7.0, 9.0)] {
let r = rect(&laid, id);
@ -869,7 +881,8 @@ fn random_styles_never_panic() {
bx("m", styles[2].clone(), vec![leaf("b", &styles[3]), leaf("c", &styles[4])]),
]);
let scale = [1.0, 1.5, 2.0][round % 3];
let laid = lay_with(&mut MemState::new(), root, &pixels(800.0, 600.0, scale));
let tree = bind(&mut MemState::new(), &surface_of(root)).unwrap();
let Ok(laid) = layout(&tree, &pixels(800.0, 600.0, scale), &mut FixedMeasure::pixels(&[])) else { continue };
assert!(laid.nodes.iter().all(|n| [n.rect.x, n.rect.y, n.rect.w, n.rect.h].iter().all(|v| v.is_finite())));
}
}
@ -879,14 +892,49 @@ fn bad_frames_are_refused() {
let tree = bind(&mut MemState::new(), &surface_of(bx("root", plain(), vec![]))).unwrap();
let run = |frame: LayoutFrame| layout(&tree, &frame, &mut FixedMeasure::pixels(&[])).map(|laid| laid.nodes.len());
for scale in [f32::NAN, f32::INFINITY, 0.0, -1.0, 2048.0] {
assert_eq!(run(pixels(800.0, 600.0, scale)), Err(FrameError::Scale), "scale {scale}");
assert_eq!(run(pixels(800.0, 600.0, scale)), Err(LayoutError::Frame(FrameError::Scale)), "scale {scale}");
}
for viewport in [(f32::NAN, 600.0), (800.0, 0.0), (-5.0, 600.0), (800.0, f32::INFINITY), (1e7, 600.0)] {
let frame = pixels(viewport.0, viewport.1, 2.0);
assert_eq!(run(frame), Err(FrameError::Viewport), "viewport {viewport:?}");
assert_eq!(run(frame), Err(LayoutError::Frame(FrameError::Viewport)), "viewport {viewport:?}");
}
assert_eq!(run(pixels(800.0, 600.0, 1.0)), Ok(1));
// Cells ignore the scale; their viewport is still checked.
assert_eq!(run(LayoutFrame { viewport: (10.0, 5.0), scale: f32::NAN, metrics: Metrics::Cells }), Ok(1));
assert_eq!(run(LayoutFrame { viewport: (0.0, 5.0), scale: 1.0, metrics: Metrics::Cells }), Err(FrameError::Viewport));
assert_eq!(run(LayoutFrame { viewport: (0.0, 5.0), scale: 1.0, metrics: Metrics::Cells }), Err(LayoutError::Frame(FrameError::Viewport)));
}
#[test]
fn large_siblings_on_one_axis_are_exact_or_refused() {
let mut refused = 0;
let mut exact = 0;
for direction in [Direction::Row, Direction::Column] {
for (count, side) in [(2usize, 1_000_000.0f64), (4, 2_097_152.0), (8, 2_097_152.0), (3, 600_000.0), (16, 2_097_152.0)] {
let mut kids: Vec<Node> = (0..count).map(|n| {
let (w, h) = if matches!(direction, Direction::Row) { (side, 10.0) } else { (10.0, side) };
embed(&format!("big{n}"), w, h)
}).collect();
kids.push(bx("fixed", BoxStyle { shrink: 0.0, ..sized(30.0, 20.0) }, vec![]));
for root_style in [plain(), sized(800.0, 600.0)] {
let root = bx("root", BoxStyle { direction: direction.clone(), ..root_style }, kids.clone());
let tree = bind(&mut MemState::new(), &surface_of(root)).unwrap();
match layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels(&[])) {
Ok(laid) => {
exact += 1;
for (id, w, h) in [("fixed", 30.0, 20.0)] {
let r = rect(&laid, id);
assert_eq!((r.2, r.3), (w, h), "{id}, {count} siblings of {side}, {direction:?}");
}
}
Err(LayoutError::OutOfRange(d)) => {
refused += 1;
assert_eq!(d.code, Code::LayoutOutOfRange);
assert!(d.node.is_some());
}
Err(other) => panic!("{other:?}"),
}
}
}
}
assert!(exact > 0 && refused > 0, "exact {exact}, refused {refused}");
}