Thing 2.0 cut 5a: layout (Taffy, device pixels, a Measure seam for text) #15

Merged
eureka merged 29 commits from hands/thing2-layout into main 2026-11-28 05:33:05 +00:00
27 changed files with 2104 additions and 0 deletions

34
Cargo.lock generated
View file

@ -355,6 +355,12 @@ dependencies = [
"serde",
]
[[package]]
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]]
name = "rustversion"
version = "1.0.23"
@ -448,6 +454,21 @@ version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "slotmap"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"
dependencies = [
"version_check",
]
[[package]]
name = "smallvec"
version = "1.16.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
[[package]]
name = "stacker"
version = "0.1.25"
@ -483,6 +504,18 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "taffy"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cae92eb1b204bfd239b5c463e1bd2c3ce4913d2d3abfb5c64f5cfee9d65e5c68"
dependencies = [
"rustc-hash",
"serde",
"slotmap",
"smallvec",
]
[[package]]
name = "thing-contract"
version = "0.1.0"
@ -500,6 +533,7 @@ name = "thing-core"
version = "0.1.0"
dependencies = [
"stacker",
"taffy",
"thing-contract",
"thing-testkit",
]

View file

@ -7,3 +7,4 @@ anyhow = "1"
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "4c9af401ae33812d862dde4ff3131433fc73c7dc", package = "cultcache-rs" }
serde = { version = "1", features = ["derive"] }
rmp-serde = "1.3"
taffy = { version = "0.16", default-features = false, features = ["std", "taffy_tree", "flexbox", "grid", "block_layout", "content_size"] }

View file

@ -5,9 +5,12 @@ edition = "2024"
license = "MIT"
publish = false
# Normal dependencies are thing-contract, stacker and taffy: layout is thing-core's job, and no
# Taffy type is in its public API.
[dependencies]
thing-contract = { path = "../thing-contract" }
stacker = "0.1.25"
taffy.workspace = true
[dev-dependencies]
thing-testkit = { path = "../thing-testkit" }

View file

@ -35,6 +35,10 @@ pub enum Code {
RepeatKeyDuplicate,
/// A surface offered at a version at or below one already offered; the held tree stays.
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

@ -0,0 +1,123 @@
//! The Measure seam: what a leaf's intrinsic size is. Text, controls and images are sized by a
//! `Measure` the frame owner composes (cut 9a ships Pixels and Cells); layout never estimates
//! them. Taffy's own types stop at this file: `Leaf` and `Constraint` are plain data.
use taffy::{AvailableSpace, Size};
use thing_contract::NodeId;
use crate::bind::Bound;
/// The room a leaf is offered on one axis.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Avail {
Definite(f32),
MinContent,
MaxContent,
}
/// What a leaf is asked, in logical px (Pixels) or cells (Cells). `known` is a size the parent
/// already fixed on an axis; `available` is the room on each axis, `[width, height]`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Constraint {
pub known: [Option<f32>; 2],
pub available: [Avail; 2],
}
/// A leaf node with the values it shows, borrowed from the bound tree.
#[derive(Clone, Copy, Debug)]
pub enum Leaf<'a> {
Text { node: &'a NodeId, content: &'a Bound, style_token: &'a str, wrap: bool, max_lines: Option<u32> },
TextInput { node: &'a NodeId, multiline: bool, placeholder: &'a Bound, value: &'a Bound },
Toggle { node: &'a NodeId },
Slider { node: &'a NodeId },
Select { node: &'a NodeId, selected: &'a Bound },
Image { node: &'a NodeId, catalog: &'a str, asset: &'a str },
Plot { node: &'a NodeId },
}
/// The intrinsic size `(width, height)` of a leaf under a constraint. A non-finite or negative
/// answer is taken as zero.
pub trait Measure {
fn measure(&mut self, leaf: &Leaf, constraint: Constraint) -> (f32, f32);
}
/// The largest length, in device px or cells, a style or a measure may state: 2^21 = 2,097,152.
/// f32 has 24 mantissa bits, so a coordinate below 2^24 is exact to a whole pixel and one below
/// 2^21 keeps 3 fractional bits, 1/8 px. A coordinate is a sum of lengths along an axis: eight
/// maximal siblings still sum below 2^24 (whole-pixel exact), and any run of siblings whose
/// extents sum below 2^21 keeps 1/8 px. A length beyond the bound is an invalid style value and a
/// larger measured size is clamped to it.
pub(super) const MAX_DEVICE: f32 = 2_097_152.0;
/// The smallest nonzero extent a measure may state: 1/8 px, the precision the length bound
/// leaves. A smaller side is below the resolution layout keeps.
pub(super) const MIN_SIDE: f32 = 0.125;
/// The one place logical units become device units and back: `k` device px per logical px
/// (1 in Cells). Everything past this adapter, the style map and the solver included, is device.
#[derive(Clone, Copy, Debug)]
pub(super) struct Device(f32);
impl Device {
pub(super) fn new(k: f32) -> Self {
Self(k)
}
pub(super) fn px(self, logical: f32) -> f32 {
logical * self.0
}
fn logical(self, device: f32) -> f32 {
device / self.0
}
fn avail(self, space: AvailableSpace) -> Avail {
match space {
AvailableSpace::Definite(v) => Avail::Definite(self.logical(v)),
AvailableSpace::MinContent => Avail::MinContent,
AvailableSpace::MaxContent => Avail::MaxContent,
}
}
/// A measure's answer as a device size: non-finite or negative is zero, huge is the bound.
fn size(self, (w, h): (f32, f32)) -> Size<f32> {
let side = |v: f32| if v.is_finite() && v > 0.0 { self.px(v).min(MAX_DEVICE) } else { 0.0 };
Size { width: side(w), height: side(h) }
}
}
/// Taffy's leaf callback to `Measure`: device px in, logical out, and back.
pub(super) fn measure_leaf(
measure: &mut dyn Measure,
leaf: &Leaf,
dev: Device,
known: Size<Option<f32>>,
space: Size<AvailableSpace>,
) -> Size<f32> {
let constraint = Constraint {
known: [known.width.map(|v| dev.logical(v)), known.height.map(|v| dev.logical(v))],
available: [dev.avail(space.width), dev.avail(space.height)],
};
dev.size(measure.measure(leaf, constraint))
}
/// The aspect ratio an Image keeps when stretched, from what its measure says unconstrained
/// (logical px, judged in device px). `Ok(None)` is no extent at all (0x0: nothing known yet).
/// Each side must be 0 or within [MIN_SIDE, MAX_DEVICE] and not just one of them zero; the ratio
/// is then within [MIN_SIDE / MAX_DEVICE, MAX_DEVICE / MIN_SIDE] = [2^-24, 2^24] by derivation, so
/// no second range is checked. Anything else is an invalid measure: `Err`. A side the image takes
/// from its ratio is held under MAX_DEVICE by the image's own max size (see the walk).
pub(super) fn intrinsic_ratio(measure: &mut dyn Measure, leaf: &Leaf, dev: Device) -> Result<Option<f32>, ()> {
let constraint = Constraint { known: [None, None], available: [Avail::MaxContent, Avail::MaxContent] };
let (w, h) = measure.measure(leaf, constraint);
let (w, h) = (dev.px(w), dev.px(h));
let legal = |v: f32| v == 0.0 || (v.is_finite() && (MIN_SIDE..=MAX_DEVICE).contains(&v));
if !legal(w) || !legal(h) {
return Err(());
}
match (w == 0.0, h == 0.0) {
(true, true) => Ok(None),
(false, false) => Ok(Some(w / h)),
_ => Err(()),
}
}

View file

@ -0,0 +1,168 @@
//! Layout: a `BoundTree` and a `LayoutFrame` become the geometry of every node, solved by Taffy
//! (the one solver) and handed back as plain rectangles. A pure function: it reads no port, no
//! clock and no state, builds a fresh Taffy tree per call and keeps none.
//!
//! Pixels mode runs the solver in device pixels (every Px length and every measured size is
//! multiplied by the scale factor at the one adapter) with Taffy's cumulative rounding, so every
//! edge lands on a device pixel and adjacent boxes share it. Cells mode ignores the scale. The
//! viewport is a block container the document root flows in, and is not itself in the output.
mod measure;
mod style;
mod tree;
use taffy::{AvailableSpace, Size, compute_leaf_layout};
use measure::{Device, MAX_DEVICE};
use thing_contract::NodeId;
pub use measure::{Avail, Constraint, Leaf, Measure};
use crate::bind::BoundTree;
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.
/// Taffy recurses natively and nothing in it can be wrapped per level, so the walk's depth is
/// known first and the one segment is sized for it.
const STACK_PER_LEVEL: usize = 96 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Metrics {
Pixels,
Cells,
}
/// The room one layout fills. `viewport` is logical px (Pixels) or cells (Cells); `scale` is the
/// device pixels per logical px and is ignored in Cells.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LayoutFrame {
pub viewport: (f32, f32),
pub scale: f32,
pub metrics: Metrics,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rect {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
}
/// One node's geometry. `rect` is the absolute border box in device px (Pixels) or cells, and is
/// unscrolled. `content` is the scrollable content size of an `Overflow::Scroll` node; `clip` is
/// set for Clip and Scroll.
#[derive(Clone, Debug, PartialEq)]
pub struct LaidNode {
pub id: NodeId,
pub rect: Rect,
pub content: Option<(f32, f32)>,
pub clip: bool,
}
/// Every laid node in paint order (document order, Repeat instances spliced), and the style
/// values that were not legal.
#[derive(Clone, Debug, PartialEq)]
pub struct LaidTree {
pub nodes: Vec<LaidNode>,
pub diagnostics: Vec<Diagnostic>,
}
/// Whole numbers stay whole, and negative zero is written as zero.
fn clean(v: f32) -> f32 {
if v == 0.0 || !v.is_finite() { 0.0 } else { v }
}
/// Why a frame was refused: nothing is laid out in a room that is not a finite positive size.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FrameError {
/// The scale is not finite, not positive or past 1024 (Pixels only).
Scale,
/// A viewport side is not finite, not positive or past the length bound.
Viewport,
}
/// 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.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.into());
};
let mut built = tree::build(tree, dev, (vw, vh), measure);
let tree::Built { taffy, root, entries, leaves, diagnostics } = &mut built;
let space = Size { width: AvailableSpace::Definite(vw), height: AvailableSpace::Definite(vh) };
// Entries come parent first, so one pass finds the deepest; the viewport and a spare few add.
let mut depth = vec![1usize; entries.len()];
for (i, entry) in entries.iter().enumerate() {
depth[i] = entry.parent.map_or(1, |parent| depth[parent] + 1);
}
let levels = depth.iter().copied().max().unwrap_or(0) + 8;
stacker::grow(STACK_PER_LEVEL * levels, || {
taffy
.compute_layout_with_measure(*root, space, |inputs, _, context, style| {
let leaf = context.and_then(|index| leaves.get(*index));
compute_leaf_layout(
inputs,
style,
|_, _| 0.0,
|known, space| match leaf {
Some(leaf) => measure::measure_leaf(measure, leaf, dev, known, space),
None => Size::ZERO,
},
)
})
.expect("taffy: the root is in the tree")
});
let mut absolute: Vec<(f32, f32)> = Vec::with_capacity(entries.len());
let mut nodes = Vec::with_capacity(entries.len());
for entry in entries.iter() {
let laid = taffy.layout(entry.node).expect("taffy: node is in the tree");
let (px, py) = entry.parent.map_or((0.0, 0.0), |parent| absolute[parent]);
let (x, y) = (px + laid.location.x, py + laid.location.y);
absolute.push((x, y));
let (w, h) = (laid.size.width, laid.size.height);
let content = entry.scroll.then(|| {
let overflow = laid.scrollable_overflow_rect.rect();
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) },
content,
clip: entry.clip,
});
}
Ok(LaidTree { nodes, diagnostics: std::mem::take(diagnostics) })
}

View file

@ -0,0 +1,289 @@
//! The one style map: `BoxStyle` and `Paint` onto Taffy's `Style`. The destructure names every
//! contract field, so a new field fails to compile until it is mapped.
//!
//! A slot holding a value its CSS counterpart forbids (a non-finite or oversized number, a
//! negative where none is allowed, a Dimension arm the slot cannot take) takes its initial value
//! and is reported once by field name. `Percent` is authored in percent points (50 is half).
use taffy::style_helpers::TaffyZero;
use taffy::{
AlignContent, AlignItems, Dimension, Display as TDisplay, FlexDirection, FlexWrap, GridTemplateComponent,
LengthPercentage, LengthPercentageAuto, MaxTrackSizingFunction, MinTrackSizingFunction, Overflow as TOverflow,
Point, Position as TPosition, Rect, Size, Style, TrackSizingFunction,
};
use thing_contract as c;
use super::measure::{Device, MAX_DEVICE};
/// Field names of the slots that took their initial value.
pub(super) type Invalid = Vec<&'static str>;
fn number(value: f64, negative: bool) -> Option<f32> {
let fits = value.is_finite() && value.abs() <= f64::from(MAX_DEVICE) && (negative || value >= 0.0);
fits.then_some(value as f32)
}
fn length(scalar: &c::Scalar, dev: Device, negative: bool) -> Option<f32> {
number(scalar.value, negative).map(|v| dev.px(v)).filter(|v| v.abs() <= MAX_DEVICE)
}
fn percent(scalar: &c::Scalar, negative: bool) -> Option<f32> {
number(scalar.value, negative).map(|v| v / 100.0)
}
fn lp(d: &c::Dimension, dev: Device) -> Option<LengthPercentage> {
match d {
c::Dimension::Px(s) => length(s, dev, false).map(LengthPercentage::length),
c::Dimension::Percent(s) => percent(s, false).map(LengthPercentage::percent),
_ => None,
}
}
fn lpa(d: &c::Dimension, dev: Device, negative: bool) -> Option<LengthPercentageAuto> {
match d {
c::Dimension::Px(s) => length(s, dev, negative).map(LengthPercentageAuto::length),
c::Dimension::Percent(s) => percent(s, negative).map(LengthPercentageAuto::percent),
c::Dimension::Auto => Some(LengthPercentageAuto::auto()),
_ => None,
}
}
fn size_dim(d: &c::Dimension, dev: Device) -> Option<Dimension> {
match d {
c::Dimension::Px(s) => length(s, dev, false).map(Dimension::length),
c::Dimension::Percent(s) => percent(s, false).map(Dimension::percent),
c::Dimension::Auto => Some(Dimension::auto()),
c::Dimension::Content => Some(Dimension::fit_content()),
c::Dimension::Fr(_) => None,
}
}
fn basis_dim(d: &c::Dimension, dev: Device) -> Option<Dimension> {
match d {
c::Dimension::Content => Some(Dimension::content()),
c::Dimension::Fr(_) => None,
other => size_dim(other, dev),
}
}
fn track(d: &c::Dimension, dev: Device) -> Option<GridTemplateComponent<String>> {
use MaxTrackSizingFunction as Max;
use MinTrackSizingFunction as Min;
let (min, max) = match d {
c::Dimension::Px(s) => {
let v = length(s, dev, false)?;
(Min::length(v), Max::length(v))
}
c::Dimension::Percent(s) => {
let v = percent(s, false)?;
(Min::percent(v), Max::percent(v))
}
c::Dimension::Fr(s) => (Min::auto(), Max::fr(number(s.value, false)?)),
c::Dimension::Auto => (Min::auto(), Max::auto()),
c::Dimension::Content => (Min::max_content(), Max::max_content()),
};
Some(GridTemplateComponent::Single(TrackSizingFunction { min, max }))
}
struct Slots {
dev: Device,
invalid: Invalid,
}
impl Slots {
fn take<T>(&mut self, field: &'static str, value: Option<T>, initial: T) -> T {
value.unwrap_or_else(|| {
if !self.invalid.contains(&field) {
self.invalid.push(field);
}
initial
})
}
fn size2(&mut self, field: &'static str, s: &c::Size2) -> Size<Dimension> {
let dev = self.dev;
Size {
width: self.take(field, size_dim(&s.width, dev), Dimension::auto()),
height: self.take(field, size_dim(&s.height, dev), Dimension::auto()),
}
}
fn size2_lpa(&mut self, field: &'static str, s: &c::Size2) -> Size<LengthPercentageAuto> {
let dev = self.dev;
Size {
width: self.take(field, lpa(&s.width, dev, false), LengthPercentageAuto::auto()),
height: self.take(field, lpa(&s.height, dev, false), LengthPercentageAuto::auto()),
}
}
fn edges_lpa(
&mut self,
field: &'static str,
e: &c::Edges,
negative: bool,
initial: LengthPercentageAuto,
) -> Rect<LengthPercentageAuto> {
let dev = self.dev;
Rect {
left: self.take(field, lpa(&e.left, dev, negative), initial),
right: self.take(field, lpa(&e.right, dev, negative), initial),
top: self.take(field, lpa(&e.top, dev, negative), initial),
bottom: self.take(field, lpa(&e.bottom, dev, negative), initial),
}
}
fn edges_lp(&mut self, field: &'static str, e: &c::Edges) -> Rect<LengthPercentage> {
let dev = self.dev;
let zero = LengthPercentage::ZERO;
Rect {
left: self.take(field, lp(&e.left, dev), zero),
right: self.take(field, lp(&e.right, dev), zero),
top: self.take(field, lp(&e.top, dev), zero),
bottom: self.take(field, lp(&e.bottom, dev), zero),
}
}
fn tracks(&mut self, field: &'static str, dims: &[c::Dimension]) -> Vec<GridTemplateComponent<String>> {
let dev = self.dev;
let tracks: Option<Vec<_>> = dims.iter().map(|d| track(d, dev)).collect();
self.take(field, tracks, Vec::new())
}
fn weight(&mut self, field: &'static str, value: f64, initial: f32) -> f32 {
self.take(field, number(value, false), initial)
}
}
fn item(align: &c::ItemAlign) -> Option<AlignItems> {
Some(match align {
c::ItemAlign::Auto => return None,
c::ItemAlign::Start => AlignItems::FLEX_START,
c::ItemAlign::End => AlignItems::FLEX_END,
c::ItemAlign::Center => AlignItems::CENTER,
c::ItemAlign::Stretch => AlignItems::STRETCH,
c::ItemAlign::Baseline => AlignItems::BASELINE,
})
}
fn content(align: &c::ContentAlign, auto: AlignContent) -> AlignContent {
match align {
c::ContentAlign::Auto => auto,
c::ContentAlign::Start => AlignContent::FLEX_START,
c::ContentAlign::End => AlignContent::FLEX_END,
c::ContentAlign::Center => AlignContent::CENTER,
c::ContentAlign::Stretch => AlignContent::STRETCH,
c::ContentAlign::SpaceBetween => AlignContent::SPACE_BETWEEN,
c::ContentAlign::SpaceAround => AlignContent::SPACE_AROUND,
c::ContentAlign::SpaceEvenly => AlignContent::SPACE_EVENLY,
}
}
/// The Taffy style of a Box. `dev` converts Px lengths to the solver's device units; the slots that were not legal are named in the second value.
pub(super) fn box_style(s: &c::BoxStyle, paint: &c::Paint, dev: Device) -> (Style, Invalid) {
let c::BoxStyle {
display,
direction,
wrap,
gap,
padding,
margin,
size,
min_size,
max_size,
position,
inset,
overflow,
align_items,
align_self,
align_content,
justify_content,
grow,
shrink,
basis,
grid_columns,
grid_rows,
} = s;
let mut slots = Slots { dev, invalid: Vec::new() };
let border = match &paint.border {
None => LengthPercentage::ZERO,
Some(b) => {
let width = slots.take("border", length(&c::Scalar { value: b.width }, dev, false), 0.0);
LengthPercentage::length(width)
}
};
let overflow = match overflow {
c::Overflow::Visible => TOverflow::Visible,
c::Overflow::Clip => TOverflow::Clip,
c::Overflow::Scroll => TOverflow::Scroll,
};
let gap = {
let width = slots.take("gap", lp(&gap.width, dev), LengthPercentage::ZERO);
let height = slots.take("gap", lp(&gap.height, dev), LengthPercentage::ZERO);
Size { width, height }
};
let style = Style {
display: match display {
c::Display::Flex => TDisplay::Flex,
c::Display::Grid => TDisplay::Grid,
c::Display::Block => TDisplay::Block,
},
flex_direction: match direction {
c::Direction::Row => FlexDirection::Row,
c::Direction::Column => FlexDirection::Column,
c::Direction::RowReverse => FlexDirection::RowReverse,
c::Direction::ColumnReverse => FlexDirection::ColumnReverse,
},
flex_wrap: match wrap {
c::Wrap::NoWrap => FlexWrap::NoWrap,
c::Wrap::Wrap => FlexWrap::Wrap,
c::Wrap::WrapReverse => FlexWrap::WrapReverse,
},
gap,
padding: slots.edges_lp("padding", padding),
border: Rect { left: border, right: border, top: border, bottom: border },
margin: slots.edges_lpa("margin", margin, true, LengthPercentageAuto::ZERO),
size: slots.size2("size", size),
min_size: slots.size2_lpa("min_size", min_size),
max_size: slots.size2_lpa("max_size", max_size),
position: match position {
c::Position::Relative => TPosition::Relative,
c::Position::Absolute => TPosition::Absolute,
},
inset: slots.edges_lpa("inset", inset, true, LengthPercentageAuto::auto()),
overflow: Point { x: overflow, y: overflow },
scrollbar_width: 0.0,
align_items: item(align_items).unwrap_or(AlignItems::STRETCH),
align_self: item(align_self),
align_content: content(align_content, AlignContent::STRETCH),
justify_content: content(justify_content, AlignContent::FLEX_START),
flex_grow: slots.weight("grow", *grow, 0.0),
flex_shrink: slots.weight("shrink", *shrink, 1.0),
flex_basis: {
let basis = basis_dim(basis, dev);
slots.take("basis", basis, Dimension::auto())
},
grid_template_columns: slots.tracks("grid_columns", grid_columns).into_iter().collect(),
grid_template_rows: slots.tracks("grid_rows", grid_rows).into_iter().collect(),
..Style::default()
};
(style, slots.invalid)
}
/// An Embed's style: exactly its declared size, never shrunk.
pub(super) fn embed_style(width: f64, height: f64, dev: Device) -> (Style, Invalid) {
let mut slots = Slots { dev, invalid: Vec::new() };
let side = |slots: &mut Slots, value: f64| {
let v = slots.take("size", length(&c::Scalar { value }, dev, false), 0.0);
(Dimension::length(v), LengthPercentageAuto::length(v))
};
let (w, wa) = side(&mut slots, width);
let (h, ha) = side(&mut slots, height);
let style = Style {
size: Size { width: w, height: h },
min_size: Size { width: wa, height: ha },
max_size: Size { width: wa, height: ha },
flex_shrink: 0.0,
..Style::default()
};
(style, slots.invalid)
}

View file

@ -0,0 +1,245 @@
//! The walk: a `BoundTree` becomes a Taffy tree, one Taffy node per laid node, Repeats spliced.
use taffy::{Style, TaffyTree};
use thing_contract::{Node, NodeId, Overflow};
use super::measure::{Device, Leaf, MAX_DEVICE, intrinsic_ratio};
use super::style::{Invalid, box_style, embed_style};
use crate::bind::{Bound, BoundTree, Field};
use crate::diagnostic::{Code, Diagnostic};
use crate::resolve::grow;
static ABSENT: Bound = Bound::Absent;
/// One laid node, in document order. `parent` is the entry of the nearest laid ancestor.
pub(super) struct Entry<'a> {
pub(super) id: &'a NodeId,
pub(super) node: taffy::NodeId,
pub(super) parent: Option<usize>,
pub(super) clip: bool,
pub(super) scroll: bool,
}
pub(super) struct Built<'a> {
pub(super) taffy: TaffyTree<usize>,
pub(super) root: taffy::NodeId,
pub(super) entries: Vec<Entry<'a>>,
/// The Taffy context of a measured leaf is its index here.
pub(super) leaves: Vec<Leaf<'a>>,
pub(super) diagnostics: Vec<Diagnostic>,
}
struct Builder<'a, 'm> {
tree: &'a BoundTree,
surface: String,
dev: Device,
measure: &'m mut dyn super::Measure,
taffy: TaffyTree<usize>,
entries: Vec<Entry<'a>>,
leaves: Vec<Leaf<'a>>,
diagnostics: Vec<Diagnostic>,
}
pub(super) fn build<'a>(
tree: &'a BoundTree,
dev: Device,
viewport: (f32, f32),
measure: &mut dyn super::Measure,
) -> Built<'a> {
let document = tree.resolved().document();
let mut builder = Builder {
tree,
surface: document.record_key(),
dev,
measure,
taffy: TaffyTree::new(),
entries: Vec::new(),
leaves: Vec::new(),
diagnostics: Vec::new(),
};
let mut kids = Vec::new();
builder.visit(&document.root, None, &mut kids);
// The viewport is a block container; the document root is its flow child, so a root with an
// auto width fills the viewport and a Repeat at the root has a parent to splice into.
let root = Style {
display: taffy::Display::Block,
position: taffy::Position::Relative,
size: taffy::Size { width: taffy::Dimension::length(viewport.0), height: taffy::Dimension::length(viewport.1) },
..Style::default()
};
let root = builder.taffy.new_with_children(root, &kids).expect("taffy: insert");
Built { taffy: builder.taffy, root, entries: builder.entries, leaves: builder.leaves, diagnostics: builder.diagnostics }
}
impl<'a> Builder<'a, '_> {
fn hidden(&self, id: &NodeId) -> bool {
matches!(self.tree.value(id, Field::Visible), Some(Bound::Bool(false)))
}
fn value(&self, id: &NodeId, field: Field) -> &'a Bound {
self.tree.value(id, field).unwrap_or(&ABSENT)
}
fn report(&mut self, id: &NodeId, invalid: Invalid) {
for field in invalid {
self.diagnostics.push(Diagnostic {
code: Code::StyleValueInvalid,
surface: self.surface.clone(),
node: Some(id.clone()),
detail: field.to_string(),
});
}
}
fn entry(&mut self, id: &'a NodeId, parent: Option<usize>, overflow: &Overflow) -> usize {
let clip = !matches!(overflow, Overflow::Visible);
let scroll = matches!(overflow, Overflow::Scroll);
self.entries.push(Entry { id, node: taffy::NodeId::from(0u64), parent, clip, scroll });
self.entries.len() - 1
}
fn leaf(&mut self, id: &'a NodeId, parent: Option<usize>, leaf: Leaf<'a>, out: &mut Vec<taffy::NodeId>) {
let mut style = Style::default();
if matches!(leaf, Leaf::Image { .. }) {
// A stretched image keeps its shape: the ratio is what the measure says it is unconstrained.
// Whatever its ratio derives, a side of the image stays within the length bound.
let bound = taffy::LengthPercentageAuto::length(MAX_DEVICE);
style.max_size = taffy::Size { width: bound, height: bound };
// An invalid measure leaves the image unconstrained (no ratio, not replaced) and is named.
match intrinsic_ratio(self.measure, &leaf, self.dev) {
Ok(ratio) => {
style.item_is_replaced = true;
style.aspect_ratio = ratio;
}
Err(()) => self.report(id, vec!["measure"]),
}
}
let index = self.entry(id, parent, &Overflow::Visible);
let context = self.leaves.len();
self.leaves.push(leaf);
let node = self.taffy.new_leaf_with_context(style, context).expect("taffy: insert");
self.entries[index].node = node;
out.push(node);
}
fn container(
&mut self,
id: &'a NodeId,
parent: Option<usize>,
(style, invalid): (Style, Invalid),
overflow: &Overflow,
children: &'a [Node],
out: &mut Vec<taffy::NodeId>,
) {
self.report(id, invalid);
let index = self.entry(id, parent, overflow);
let mut kids = Vec::new();
for child in children {
self.visit(child, Some(index), &mut kids);
}
let node = self.taffy.new_with_children(style, &kids).expect("taffy: insert");
self.entries[index].node = node;
out.push(node);
}
/// Append the Taffy nodes `node` contributes to its parent's children: one, none (hidden,
/// Overlay, a Repeat with no instances) or one per Repeat instance.
fn visit(&mut self, node: &'a Node, parent: Option<usize>, out: &mut Vec<taffy::NodeId>) {
grow(|| match node {
Node::Box(b) => {
if !self.hidden(&b.common.id) {
let style = box_style(&b.style, &b.paint, self.dev);
self.container(&b.common.id, parent, style, &b.style.overflow, &b.children, out);
}
}
Node::Button(b) => {
if !self.hidden(&b.common.id) {
self.container(&b.common.id, parent, (Style::default(), Vec::new()), &Overflow::Visible, &b.content, out);
}
}
// A Repeat has no box: its instances are its parent's children, in instance order.
Node::Repeat(r) => {
if !self.hidden(&r.common.id) {
for instance in self.tree.instances(&r.common.id) {
self.visit(&instance.root, parent, out);
}
}
}
// Overlays are placed by their own cut; in flow they are nothing.
Node::Overlay(_) => {}
// A Use that stayed is resolve's placeholder (beside its diagnostic): a childless leaf
// that keeps its place so render can draw the error. A Slot never survives resolve.
Node::Use(u) => {
if !self.hidden(&u.common.id) {
let index = self.entry(&u.common.id, parent, &Overflow::Visible);
let id = self.taffy.new_leaf(Style::default()).expect("taffy: insert");
self.entries[index].node = id;
out.push(id);
}
}
Node::Slot(_) => debug_assert!(false, "resolve expands Slot"),
Node::Embed(e) => {
if !self.hidden(&e.common.id) {
let (style, invalid) = embed_style(e.width, e.height, self.dev);
self.report(&e.common.id, invalid);
let index = self.entry(&e.common.id, parent, &Overflow::Visible);
let id = self.taffy.new_leaf(style).expect("taffy: insert");
self.entries[index].node = id;
out.push(id);
}
}
Node::Text(n) => {
let id = &n.common.id;
if !self.hidden(id) {
let leaf = Leaf::Text {
node: id,
content: self.value(id, Field::Content),
style_token: &n.style_token,
wrap: n.wrap,
max_lines: n.max_lines.map(|lines| lines.get().max(0) as u32),
};
self.leaf(id, parent, leaf, out);
}
}
Node::TextInput(n) => {
let id = &n.common.id;
if !self.hidden(id) {
let leaf = Leaf::TextInput {
node: id,
multiline: n.multiline,
placeholder: self.value(id, Field::Placeholder),
value: self.value(id, Field::Initial),
};
self.leaf(id, parent, leaf, out);
}
}
Node::Toggle(n) => {
if !self.hidden(&n.common.id) {
self.leaf(&n.common.id, parent, Leaf::Toggle { node: &n.common.id }, out);
}
}
Node::Slider(n) => {
if !self.hidden(&n.common.id) {
self.leaf(&n.common.id, parent, Leaf::Slider { node: &n.common.id }, out);
}
}
Node::Select(n) => {
let id = &n.common.id;
if !self.hidden(id) {
self.leaf(id, parent, Leaf::Select { node: id, selected: self.value(id, Field::Selected) }, out);
}
}
Node::Image(n) => {
if !self.hidden(&n.common.id) {
let leaf = Leaf::Image { node: &n.common.id, catalog: &n.catalog, asset: &n.asset };
self.leaf(&n.common.id, parent, leaf, out);
}
}
Node::Plot(n) => {
if !self.hidden(&n.common.id) {
self.leaf(&n.common.id, parent, Leaf::Plot { node: &n.common.id }, out);
}
}
})
}
}

View file

@ -3,5 +3,6 @@
pub mod bind;
pub mod diagnostic;
pub mod layout;
pub mod port;
pub mod resolve;

View file

@ -0,0 +1,8 @@
surface thing:surface:provider.swarm.dashboard viewport 100x37 scale 1 cells
root 0 0 100 23
load 2 2 48 1
minds#6:mind-1/mind-name 54 2 48 1
minds#6:mind-2/mind-name 2 11 48 1
minds#6:mind-3/mind-name 54 11 48 1
restart 2 20 48 1
restart-label 2 20 7 1

View file

@ -0,0 +1,8 @@
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 1.5 pixels
root 0 0 1200 102
load 3 3 597 24
minds#6:mind-1/mind-name 606 3 597 24
minds#6:mind-2/mind-name 3 39 597 24
minds#6:mind-3/mind-name 606 39 597 24
restart 3 75 597 24
restart-label 3 75 84 24

View file

@ -0,0 +1,8 @@
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 2 pixels
root 0 0 1600 136
load 4 4 796 32
minds#6:mind-1/mind-name 808 4 796 32
minds#6:mind-2/mind-name 4 52 796 32
minds#6:mind-3/mind-name 808 52 796 32
restart 4 100 796 32
restart-label 4 100 112 32

View file

@ -0,0 +1,8 @@
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 1 pixels
root 0 0 800 68
load 2 2 398 16
minds#6:mind-1/mind-name 404 2 398 16
minds#6:mind-2/mind-name 2 26 398 16
minds#6:mind-3/mind-name 404 26 398 16
restart 2 50 398 16
restart-label 2 50 56 16

View file

@ -0,0 +1,5 @@
surface thing:surface:provider.login.login viewport 800x600 scale 1 pixels
root 0 0 800 52
username 2 2 796 24
sign-in-button 2 34 796 16
sign-in-button-label 2 34 56 16

View file

@ -0,0 +1,5 @@
surface thing:surface:provider.muninn.input-target viewport 800x600 scale 1 pixels
root 80 0 640 360
board 82 2 636 360
target 280 120 48 48
target-label 282 122 44 16

View file

@ -0,0 +1,6 @@
surface thing:surface:provider.settings.form viewport 800x600 scale 1 pixels
root 0 0 800 116
enabled 2 2 796 20
volume 2 30 796 20
theme 2 58 796 24
port 2 90 796 24

View file

@ -0,0 +1,5 @@
surface thing:surface:provider.market.plot viewport 800x600 scale 1 pixels
root 0 0 800 20
line 2 2 796 0
bar 2 10 796 0
area 2 18 796 0

View file

@ -0,0 +1,5 @@
surface thing:surface:provider.viewport.embed-viewport viewport 800x600 scale 1.5 pixels
root 0 0 1200 276
before 3 3 72 270
viewport 366 3 480 270
after 1137 3 60 270

View file

@ -0,0 +1,5 @@
surface thing:surface:provider.viewport.embed-viewport viewport 800x600 scale 1 pixels
root 0 0 800 184
before 2 2 48 180
viewport 244 2 320 180
after 758 2 40 180

View file

@ -0,0 +1,14 @@
surface thing:surface:provider.stack.stack viewport 800x600 scale 1 pixels
root 0 0 800 168
std-stat 2 2 796 36
std-stat/stat-label 2 2 796 16
std-stat/stat-value 2 22 796 16
outer-card 2 46 796 120
outer-card/card-title 4 48 792 16
outer-card/card-act 4 72 792 16
outer-card/card-act-label 4 72 32 16
inner-card 4 96 792 68
inner-card/card-title 6 98 788 16
inner-card/card-act 6 122 788 16
inner-card/card-act-label 6 122 32 16
inner-note 6 146 788 16

View file

@ -0,0 +1,8 @@
surface thing:surface:provider.hostile.duplicate-id refused DuplicateNodeId
surface thing:surface:provider.hostile.schema-mismatch viewport 800x600 scale 1 pixels
root 0 0 800 20
mismatch 2 2 796 16
surface thing:surface:provider.hostile.undeclared-command refused UndeclaredCommand
surface thing:surface:provider.hostile.unresolved-use viewport 800x600 scale 1 pixels
root 0 0 800 4
ghost-use 2 2 796 0

View file

@ -0,0 +1,85 @@
surface thing:surface:provider.deep.deep viewport 800x600 scale 1 pixels
deep-0 0 0 800 336
deep-1 2 2 796 332
deep-2 4 4 792 328
deep-3 6 6 788 324
deep-4 8 8 784 320
deep-5 10 10 780 316
deep-6 12 12 776 312
deep-7 14 14 772 308
deep-8 16 16 768 304
deep-9 18 18 764 300
deep-10 20 20 760 296
deep-11 22 22 756 292
deep-12 24 24 752 288
deep-13 26 26 748 284
deep-14 28 28 744 280
deep-15 30 30 740 276
deep-16 32 32 736 272
deep-17 34 34 732 268
deep-18 36 36 728 264
deep-19 38 38 724 260
deep-20 40 40 720 256
deep-21 42 42 716 252
deep-22 44 44 712 248
deep-23 46 46 708 244
deep-24 48 48 704 240
deep-25 50 50 700 236
deep-26 52 52 696 232
deep-27 54 54 692 228
deep-28 56 56 688 224
deep-29 58 58 684 220
deep-30 60 60 680 216
deep-31 62 62 676 212
deep-32 64 64 672 208
deep-33 66 66 668 204
deep-34 68 68 664 200
deep-35 70 70 660 196
deep-36 72 72 656 192
deep-37 74 74 652 188
deep-38 76 76 648 184
deep-39 78 78 644 180
deep-40 80 80 640 176
deep-41 82 82 636 172
deep-42 84 84 632 168
deep-43 86 86 628 164
deep-44 88 88 624 160
deep-45 90 90 620 156
deep-46 92 92 616 152
deep-47 94 94 612 148
deep-48 96 96 608 144
deep-49 98 98 604 140
deep-50 100 100 600 136
deep-51 102 102 596 132
deep-52 104 104 592 128
deep-53 106 106 588 124
deep-54 108 108 584 120
deep-55 110 110 580 116
deep-56 112 112 576 112
deep-57 114 114 572 108
deep-58 116 116 568 104
deep-59 118 118 564 100
deep-60 120 120 560 96
deep-61 122 122 556 92
deep-62 124 124 552 88
deep-63 126 126 548 84
deep-64 128 128 544 80
deep-65 130 130 540 76
deep-66 132 132 536 72
deep-67 134 134 532 68
deep-68 136 136 528 64
deep-69 138 138 524 60
deep-70 140 140 520 56
deep-71 142 142 516 52
deep-72 144 144 512 48
deep-73 146 146 508 44
deep-74 148 148 504 40
deep-75 150 150 500 36
deep-76 152 152 496 32
deep-77 154 154 492 28
deep-78 156 156 488 24
deep-79 158 158 484 20
deep-80 160 160 480 16
deep-81 162 162 476 12
deep-82 164 164 472 8
deep-83 166 166 468 4

View file

@ -0,0 +1,7 @@
surface thing:surface:provider.text.text-edge viewport 800x600 scale 1.5 pixels
root 0 0 1200 342
bidi 3 3 1194 24
cjk 3 39 1194 24
combining 3 75 1194 24
emoji-zwj 3 111 1194 24
long-wrap 3 147 1194 192

View file

@ -0,0 +1,7 @@
surface thing:surface:provider.text.text-edge viewport 800x600 scale 1 pixels
root 0 0 800 228
bidi 2 2 796 16
cjk 2 26 796 16
combining 2 50 796 16
emoji-zwj 2 74 796 16
long-wrap 2 98 796 128

View file

@ -0,0 +1,973 @@
//! Layout: Taffy over a bound tree, device-pixel geometry, the style map and the Repeat splice.
//! `THING_BLESS=1` rewrites the `layout-*` goldens through `golden::check`.
use std::path::PathBuf;
use taffy::style_helpers::{auto, length};
use taffy::{AlignContent, AlignItems, AvailableSpace, FlexDirection, Style, TaffyTree};
use thing_contract::*;
use thing_core::bind::{Binder, BoundTree};
use thing_core::diagnostic::Code;
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::*;
use thing_testkit::fixture::Fixture;
use thing_testkit::golden;
use thing_testkit::mem_state::MemState;
use thing_testkit::measure::FixedMeasure;
use thing_testkit::state::{self, Swarm};
fn golden_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
}
fn pixels(w: f32, h: f32, scale: f32) -> LayoutFrame {
LayoutFrame { viewport: (w, h), scale, metrics: Metrics::Pixels }
}
fn cells(w: f32, h: f32) -> LayoutFrame {
LayoutFrame { viewport: (w, h), scale: 1.0, metrics: Metrics::Cells }
}
fn bind(state: &mut MemState, document: &SurfaceDocument) -> Result<BoundTree, Code> {
bind_with(state, document, Limits::default())
}
fn bind_with(state: &mut MemState, document: &SurfaceDocument, limits: Limits) -> Result<BoundTree, Code> {
let resolution = resolve(document, state, &limits);
let Some(tree) = resolution.tree else {
return Err(resolution.diagnostics.iter().find(|d| d.code.refuses_document()).map(|d| d.code).expect("a refusal"));
};
let mut binder = Binder::new(limits);
binder.bind(tree, state, &mut Ledger::new());
Ok(binder.tree(&document.record_key()).expect("bound").clone())
}
fn render(laid: &LaidTree) -> String {
let mut out = String::new();
for LaidNode { id, rect, content, clip } in &laid.nodes {
out += &format!("{}\t{}\t{}\t{}\t{}", id.as_str(), rect.x, rect.y, rect.w, rect.h);
if *clip {
out += "\tclip";
}
if let Some((w, h)) = content {
out += &format!("\tcontent {w}x{h}");
}
out += "\n";
}
out
}
/// Every surface of a fixture, resolved, bound under the fixture's state script and laid out.
fn laid_fixture(fixture: Fixture, frame: &LayoutFrame) -> Vec<(String, Result<LaidTree, Code>)> {
let set = fixture.load();
let mut state = MemState::from_fixture(fixture);
state::script(fixture, &mut state);
set.surfaces
.iter()
.map(|document| {
let laid = bind(&mut state, document).map(|tree| {
let mut measure = match frame.metrics {
Metrics::Pixels => FixedMeasure::pixels(&set.catalogs),
Metrics::Cells => FixedMeasure::cells(&set.catalogs),
};
layout(&tree, frame, &mut measure).unwrap()
});
(document.record_key(), laid)
})
.collect()
}
fn fixture_text(fixture: Fixture, frame: &LayoutFrame) -> String {
let mut out = String::new();
for (key, laid) in laid_fixture(fixture, frame) {
match laid {
Ok(laid) => {
let mode = if frame.metrics == Metrics::Cells { "cells" } else { "pixels" };
out += &format!("surface {key} viewport {}x{} scale {} {mode}\n", frame.viewport.0, frame.viewport.1, frame.scale);
out += &render(&laid);
}
Err(code) => out += &format!("surface {key} refused {code:?}\n"),
}
}
out
}
fn stem(fixture: Fixture) -> String {
fixture.file_name().trim_end_matches(".surface.cc").to_string()
}
fn check(fixture: Fixture, suffix: &str, frame: &LayoutFrame) -> String {
let text = fixture_text(fixture, frame);
golden::check(&golden_dir(), &format!("layout-{}{suffix}.txt", stem(fixture)), text.as_bytes());
text
}
const NOT_HERE: [Fixture; 2] = [Fixture::F05ModalOverlay, Fixture::F06ScrollList];
#[test]
fn goldens() {
for fixture in Fixture::ALL.into_iter().filter(|f| !NOT_HERE.contains(f)) {
check(fixture, "", &pixels(800.0, 600.0, 1.0));
}
check(Fixture::F01SwarmDashboard, "-scale2", &pixels(800.0, 600.0, 2.0));
check(Fixture::F01SwarmDashboard, "-scale1.5", &pixels(800.0, 600.0, 1.5));
check(Fixture::F08EmbedViewport, "-scale1.5", &pixels(800.0, 600.0, 1.5));
check(Fixture::F12TextEdge, "-scale1.5", &pixels(800.0, 600.0, 1.5));
check(Fixture::F01SwarmDashboard, "-cells", &cells(100.0, 37.0));
}
#[test]
fn determinism() {
for fixture in Fixture::ALL.into_iter().filter(|f| !NOT_HERE.contains(f)) {
for frame in [pixels(800.0, 600.0, 1.0), pixels(800.0, 600.0, 1.5)] {
let first = laid_fixture(fixture, &frame);
let second = laid_fixture(fixture, &frame);
let fresh = std::thread::spawn(move || laid_fixture(fixture, &frame)).join().unwrap();
assert_eq!(first, second, "{fixture:?} twice");
assert_eq!(first, fresh, "{fixture:?} on a fresh thread");
let bytes = |runs: &[(String, Result<LaidTree, Code>)]| format!("{runs:?}");
assert_eq!(bytes(&first), bytes(&fresh));
}
}
}
#[test]
fn scale_linearity() {
let one = laid_fixture(Fixture::F01SwarmDashboard, &pixels(800.0, 600.0, 1.0));
let two = laid_fixture(Fixture::F01SwarmDashboard, &pixels(800.0, 600.0, 2.0));
let (one, two) = (one[0].1.as_ref().unwrap(), two[0].1.as_ref().unwrap());
assert_eq!(one.nodes.len(), two.nodes.len());
assert!(one.nodes.len() > 5);
for (a, b) in one.nodes.iter().zip(&two.nodes) {
assert_eq!(a.id, b.id);
let doubled = |v: f32| v * 2.0;
assert_eq!((doubled(a.rect.x), doubled(a.rect.y), doubled(a.rect.w), doubled(a.rect.h)), (b.rect.x, b.rect.y, b.rect.w, b.rect.h), "{}", a.id.as_str());
}
}
// ---- inline trees ----------------------------------------------------------------------
/// The initial value of every slot: a Row flex box with no gap, padding or size.
fn plain() -> BoxStyle {
let zero = || px(0.0);
let auto = || size2(Dimension::Auto, Dimension::Auto);
BoxStyle {
display: Display::Flex,
direction: Direction::Row,
wrap: Wrap::NoWrap,
gap: size2(zero(), zero()),
padding: edges(zero()),
margin: edges(zero()),
size: auto(),
min_size: auto(),
max_size: auto(),
position: Position::Relative,
inset: edges(Dimension::Auto),
overflow: Overflow::Visible,
align_items: ItemAlign::Stretch,
align_self: ItemAlign::Auto,
align_content: ContentAlign::Auto,
justify_content: ContentAlign::Auto,
grow: 0.0,
shrink: 1.0,
basis: Dimension::Auto,
grid_columns: vec![],
grid_rows: vec![],
}
}
fn all<T: Copy>(v: f32) -> taffy::Rect<T>
where
T: taffy::style_helpers::FromLength,
{
taffy::Rect { left: length(v), right: length(v), top: length(v), bottom: length(v) }
}
fn bx(id: &str, style: BoxStyle, children: Vec<Node>) -> Node {
Node::Box(BoxNode { common: common(id), style, paint: plain_paint(), role: Role::Group, children })
}
fn bx_paint(id: &str, style: BoxStyle, paint: Paint, children: Vec<Node>) -> Node {
Node::Box(BoxNode { common: common(id), style, paint, role: Role::Group, children })
}
fn embed(id: &str, w: f64, h: f64) -> Node {
Node::Embed(EmbedNode { common: common(id), slot_kind: "k".into(), slot_id: id.into(), width: w, height: h })
}
fn sized(w: f64, h: f64) -> BoxStyle {
BoxStyle { size: size2(px(w), px(h)), ..plain() }
}
fn surface_of(root: Node) -> SurfaceDocument {
SurfaceDocument {
provider_id: ProviderId::new("provider.layout"),
label: seg("inline"),
version: ver(1),
title: "inline".into(),
root,
commands: vec![],
}
}
fn lay_with(state: &mut MemState, root: Node, frame: &LayoutFrame) -> LaidTree {
let tree = bind(state, &surface_of(root)).expect("resolves");
layout(&tree, frame, &mut FixedMeasure::pixels(&[])).unwrap()
}
fn lay(root: Node, w: f32, h: f32) -> LaidTree {
lay_with(&mut MemState::new(), root, &pixels(w, h, 1.0))
}
fn rect(laid: &LaidTree, id: &str) -> (f32, f32, f32, f32) {
let node = laid.nodes.iter().find(|n| n.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}"));
(node.rect.x, node.rect.y, node.rect.w, node.rect.h)
}
fn ids(laid: &LaidTree) -> Vec<&str> {
laid.nodes.iter().map(|n| n.id.as_str()).collect()
}
#[test]
fn raw_taffy_rederivation() {
// row, gap 10, padding 5, border 2, 400x200; a is 100x50, b grows and holds b1, c is absolute.
let mut root = sized(400.0, 200.0);
root.gap = size2(px(10.0), px(10.0));
root.padding = edges(px(5.0));
let mut b = BoxStyle { grow: 1.0, direction: Direction::Column, ..plain() };
b.padding = edges(px(3.0));
let mut c = sized(30.0, 30.0);
c.position = Position::Absolute;
c.inset = Edges { top: px(20.0), right: Dimension::Auto, bottom: Dimension::Auto, left: px(10.0) };
let paint = Paint { background: None, border: Some(Border { color: ColorRef::Rgba(Rgba { r: 0, g: 0, b: 0, a: 255 }), width: 2.0 }), radius: 0.0 };
let laid = lay(
bx_paint("root", root, paint, vec![
bx("a", sized(100.0, 50.0), vec![]),
bx("b", b, vec![bx("b1", sized(20.0, 20.0), vec![])]),
bx("c", c, vec![]),
]),
800.0,
600.0,
);
let mut t: TaffyTree<()> = TaffyTree::new();
let leaf = |t: &mut TaffyTree<()>, w: f32, h: f32| {
t.new_leaf(Style { size: taffy::Size { width: length(w), height: length(h) }, ..Default::default() }).unwrap()
};
let a = leaf(&mut t, 100.0, 50.0);
let b1 = leaf(&mut t, 20.0, 20.0);
let b = t
.new_with_children(
Style { flex_grow: 1.0, flex_direction: FlexDirection::Column, padding: all(3.0), ..Default::default() },
&[b1],
)
.unwrap();
let c = t
.new_leaf(Style {
position: taffy::Position::Absolute,
size: taffy::Size { width: length(30.0), height: length(30.0) },
inset: taffy::Rect { left: length(10.0), top: length(20.0), right: auto(), bottom: auto() },
..Default::default()
})
.unwrap();
let root = t
.new_with_children(
Style {
position: taffy::Position::Relative,
size: taffy::Size { width: length(400.0), height: length(200.0) },
gap: taffy::Size { width: length(10.0), height: length(10.0) },
padding: all(5.0),
border: all(2.0),
align_items: AlignItems::STRETCH,
align_content: AlignContent::STRETCH,
justify_content: AlignContent::FLEX_START,
..Default::default()
},
&[a, b, c],
)
.unwrap();
let viewport = t
.new_with_children(
Style {
display: taffy::Display::Block,
position: taffy::Position::Relative,
size: taffy::Size { width: length(800.0), height: length(600.0) },
..Default::default()
},
&[root],
)
.unwrap();
t.compute_layout(viewport, taffy::Size { width: AvailableSpace::Definite(800.0), height: AvailableSpace::Definite(600.0) }).unwrap();
let at = |node, parent: (f32, f32)| {
let l = t.layout(node).unwrap();
((parent.0 + l.location.x, parent.1 + l.location.y), (l.size.width, l.size.height))
};
let (root_at, root_size) = at(root, (0.0, 0.0));
let expect = |id: &str, origin: (f32, f32), size: (f32, f32)| {
assert_eq!(rect(&laid, id), (origin.0, origin.1, size.0, size.1), "{id}");
};
expect("root", root_at, root_size);
let (a_at, a_size) = at(a, root_at);
expect("a", a_at, a_size);
let (b_at, b_size) = at(b, root_at);
expect("b", b_at, b_size);
let (b1_at, b1_size) = at(b1, b_at);
expect("b1", b1_at, b1_size);
let (c_at, c_size) = at(c, root_at);
expect("c", c_at, c_size);
// The hand tree is not a restatement of the mapping: pin the shape it must have.
assert_eq!((a_at, b_at.0, c_size), ((7.0, 7.0), 117.0, (30.0, 30.0)));
assert_eq!(c_at, (root_at.0 + 12.0, root_at.1 + 22.0));
}
#[test]
fn arm_table() {
let probe = |mutate: &dyn Fn(&mut BoxStyle)| {
let mut style = sized(100.0, 50.0);
mutate(&mut style);
lay(bx("root", plain(), vec![bx("child", style, vec![embed("e", 10.0, 10.0)])]), 400.0, 300.0)
};
let one = |laid: &LaidTree, field: &str| {
assert_eq!(laid.diagnostics.len(), 1, "{:?}", laid.diagnostics);
let d = &laid.diagnostics[0];
assert_eq!((d.code, d.node.as_ref().map(|n| n.as_str()), d.detail.as_str()), (Code::StyleValueInvalid, Some("child"), field));
assert!(!d.code.refuses_document());
};
let initial = |mutate: &dyn Fn(&mut BoxStyle)| {
let mut style = sized(100.0, 50.0);
mutate(&mut style);
lay(bx("root", plain(), vec![bx("child", style, vec![embed("e", 10.0, 10.0)])]), 400.0, 300.0).nodes
};
let fr = probe(&|s| s.size.width = Dimension::Fr(Scalar { value: 1.0 }));
one(&fr, "size");
assert_eq!(fr.nodes, initial(&|s| s.size.width = Dimension::Auto));
let content = probe(&|s| s.min_size.width = Dimension::Content);
one(&content, "min_size");
let padding = probe(&|s| s.padding.top = Dimension::Auto);
one(&padding, "padding");
assert_eq!(padding.nodes, initial(&|s| s.padding.top = px(0.0)));
one(&probe(&|s| s.gap.width = px(-1.0)), "gap");
let grow = probe(&|s| s.grow = f64::NAN);
one(&grow, "grow");
assert_eq!(grow.nodes, initial(&|s| s.grow = 0.0));
let shrink = probe(&|s| s.shrink = -1.0);
one(&shrink, "shrink");
assert_eq!(shrink.nodes, initial(&|s| s.shrink = 1.0));
// A slot is named once however many of its parts are wrong.
one(&probe(&|s| s.gap = size2(px(-1.0), px(-2.0))), "gap");
one(&probe(&|s| s.grow = 5e6), "grow");
let wide = probe(&|s| s.size.width = px(1e40));
one(&wide, "size");
assert_eq!(wide.nodes, initial(&|s| s.size.width = Dimension::Auto));
one(&probe(&|s| s.basis = Dimension::Fr(Scalar { value: 1.0 })), "basis");
one(&probe(&|s| s.grid_columns = vec![Dimension::Content, px(-1.0)]), "grid_columns");
let border = {
let paint = Paint { background: None, border: Some(Border { color: ColorRef::Rgba(Rgba { r: 0, g: 0, b: 0, a: 0 }), width: -1.0 }), radius: 0.0 };
lay(bx("root", plain(), vec![bx_paint("child", sized(100.0, 50.0), paint, vec![])]), 400.0, 300.0)
};
one(&border, "border");
// Negative margin and inset are legal.
let negative = probe(&|s| s.margin.left = px(-5.0));
assert!(negative.diagnostics.is_empty());
assert_eq!(rect(&negative, "child").0, -5.0);
}
#[test]
fn taffy_edges() {
// A percent height under an auto-height parent behaves as auto.
let mut child = plain();
child.size.height = Dimension::Percent(Scalar { value: 50.0 });
let laid = lay(bx("root", plain(), vec![bx("child", child, vec![embed("e", 10.0, 20.0)])]), 400.0, 300.0);
assert_eq!(rect(&laid, "child").3, 20.0);
// min wins over max.
let mut clamped = sized(100.0, 10.0);
clamped.min_size.width = px(80.0);
clamped.max_size.width = px(50.0);
assert_eq!(rect(&lay(bx("root", plain(), vec![bx("c", clamped, vec![])]), 400.0, 300.0), "c").2, 80.0);
// Content shrink-wraps a text leaf inside a column that stretches the rest.
let column = BoxStyle { direction: Direction::Column, ..plain() };
let wrapped = BoxStyle { size: size2(Dimension::Content, Dimension::Auto), ..plain() };
let laid = lay(
bx("root", column, vec![bx("wrap", wrapped, vec![text("t", "hello")]), bx("stretch", plain(), vec![])]),
200.0,
300.0,
);
assert_eq!(rect(&laid, "wrap").2, 40.0);
assert_eq!(rect(&laid, "stretch").2, 200.0);
// Fr, Px and Content tracks with auto placement.
let mut grid = BoxStyle { display: Display::Grid, size: size2(px(400.0), Dimension::Auto), ..plain() };
grid.grid_columns = vec![px(100.0), Dimension::Fr(Scalar { value: 1.0 }), Dimension::Content];
let laid = lay(
bx("root", grid, vec![embed("g1", 10.0, 10.0), embed("g2", 10.0, 10.0), embed("g3", 50.0, 10.0), embed("g4", 10.0, 10.0)]),
800.0,
600.0,
);
assert_eq!((rect(&laid, "g1").0, rect(&laid, "g2").0, rect(&laid, "g3").0), (0.0, 100.0, 350.0));
assert_eq!((rect(&laid, "g4").0, rect(&laid, "g4").1), (0.0, 10.0));
// Overflow Scroll reports the content size; Clip only clips.
let mut scroll = sized(100.0, 50.0);
scroll.overflow = Overflow::Scroll;
let mut clip = sized(100.0, 50.0);
clip.overflow = Overflow::Clip;
let laid = lay(
bx("root", plain(), vec![bx("scroll", scroll, vec![embed("big", 200.0, 300.0)]), bx("clip", clip, vec![embed("big2", 200.0, 300.0)])]),
800.0,
600.0,
);
let node = |id: &str| laid.nodes.iter().find(|n| n.id.as_str() == id).unwrap();
assert_eq!((node("scroll").clip, node("scroll").content), (true, Some((200.0, 300.0))));
assert_eq!((node("clip").clip, node("clip").content), (true, None));
assert_eq!((node("root").clip, node("root").content), (false, None));
}
#[test]
fn item_alignment_and_content_arms() {
// align_items Auto is CSS normal: items stretch across the cross axis.
let column = BoxStyle { direction: Direction::Column, align_items: ItemAlign::Auto, size: size2(px(200.0), Dimension::Auto), ..plain() };
let laid = lay(bx("root", column, vec![bx("stretched", plain(), vec![embed("e", 10.0, 10.0)])]), 800.0, 600.0);
assert_eq!(rect(&laid, "stretched").2, 200.0);
// basis Content ignores the declared width: the item takes its content.
let basis = BoxStyle { basis: Dimension::Content, ..sized(100.0, 10.0) };
let laid = lay(bx("root", plain(), vec![bx("b", basis, vec![embed("e", 30.0, 10.0)])]), 800.0, 600.0);
assert_eq!(rect(&laid, "b").2, 30.0);
// A Content track is as wide as its widest item and does not stretch; an Auto track does.
let mut grid = BoxStyle { display: Display::Grid, size: size2(px(400.0), Dimension::Auto), justify_content: ContentAlign::Stretch, ..plain() };
grid.grid_columns = vec![Dimension::Content, Dimension::Auto];
let laid = lay(bx("root", grid, vec![embed("c1", 50.0, 10.0), embed("c2", 10.0, 10.0)]), 800.0, 600.0);
assert_eq!(rect(&laid, "c2").0, 50.0);
// A Fr track holds at least its content.
let mut grid = BoxStyle { display: Display::Grid, size: size2(px(100.0), Dimension::Auto), ..plain() };
let fr = || Dimension::Fr(Scalar { value: 1.0 });
grid.grid_columns = vec![fr(), fr()];
let laid = lay(bx("root", grid, vec![embed("f1", 80.0, 10.0), embed("f2", 10.0, 10.0)]), 800.0, 600.0);
assert_eq!(rect(&laid, "f2").0, 80.0);
// Scroll lets a flex item shrink below its content; Clip does not.
let item = |overflow| BoxStyle { overflow, ..plain() };
let laid = lay(
bx("root", sized(100.0, 20.0), vec![
bx("scroll", item(Overflow::Scroll), vec![embed("a", 300.0, 10.0)]),
]),
800.0,
600.0,
);
assert_eq!(rect(&laid, "scroll").2, 100.0);
let laid = lay(
bx("root", sized(100.0, 20.0), vec![bx("clip", item(Overflow::Clip), vec![embed("a", 300.0, 10.0)])]),
800.0,
600.0,
);
assert_eq!(rect(&laid, "clip").2, 300.0);
// A scrollable content size is whole device pixels.
let mut scroll = sized(100.0, 50.0);
scroll.overflow = Overflow::Scroll;
let laid = lay(bx("root", plain(), vec![bx("s", scroll, vec![embed("big", 200.4, 300.6)])]), 800.0, 600.0);
assert_eq!(laid.nodes[1].content, Some((200.0, 301.0)));
}
#[test]
fn available_space_is_logical() {
// A text leaf that is not stretched wraps at the room it is offered: 100 logical px at any
// scale, which holds twelve 8 px characters.
let column = BoxStyle { direction: Direction::Column, align_items: ItemAlign::Start, ..sized(100.0, 600.0) };
let root = bx("root", column, vec![text("t", &"xxxx ".repeat(10))]);
for scale in [1.0, 2.0] {
let laid = lay_with(&mut MemState::new(), root.clone(), &pixels(800.0, 600.0, scale));
assert_eq!(rect(&laid, "t").2, 96.0 * scale);
}
}
#[test]
fn repeat_splice() {
let laid = &laid_fixture(Fixture::F01SwarmDashboard, &pixels(800.0, 600.0, 1.0))[0].1;
let laid = laid.as_ref().unwrap();
let names: Vec<_> = laid.nodes.iter().filter(|n| n.id.as_str().ends_with("mind-name")).collect();
assert_eq!(names.len(), 3);
// The instances are direct items of the two-column grid: the Repeat has no box, and the
// three instances tile the tracks after the load text, ahead of the button.
let cells: Vec<_> = names.iter().map(|n| (n.rect.x, n.rect.y)).collect();
assert!(cells[0].0 > cells[1].0 && cells[2].0 == cells[0].0);
assert!(cells[1].1 > cells[0].1 && cells[2].1 == cells[1].1);
assert!(!ids(laid).contains(&"minds"));
let depth = |id: &str| id.matches('/').count();
let root_children: Vec<_> = laid.nodes.iter().filter(|n| depth(n.id.as_str()) <= 1 && n.id.as_str() != "root").collect();
assert!(root_children.len() >= 5);
// A Repeat in error contributes nothing: its sibling sits where it would without it.
let provider = ProviderId::new("provider.swarm");
let mut state = MemState::new();
for key in ["mind-1", "mind-2"] {
state.put_state(&provider, key, &Swarm { id: "same".into(), name: key.into(), load: 0.0 });
}
let repeat = |id: &str| {
Node::Repeat(RepeatNode {
common: common(id),
collection: CollectionSource::Records(RecordsSource {
provider: Some(provider.clone()),
schema: SchemaId::new("gamecult.thing.test.swarm.v1"),
key_prefix: "mind-".into(),
}),
key_member: path(&["Id"]),
template: std::boxed::Box::new(embed("row", 10.0, 10.0)),
})
};
let column = BoxStyle { direction: Direction::Column, ..plain() };
let with = lay_with(&mut state, bx("root", column.clone(), vec![repeat("rows"), embed("after", 5.0, 5.0)]), &pixels(400.0, 300.0, 1.0));
let without = lay_with(&mut state, bx("root", column, vec![embed("after", 5.0, 5.0)]), &pixels(400.0, 300.0, 1.0));
let tree = bind(&mut state, &surface_of(bx("root", plain(), vec![repeat("rows")]))).unwrap();
assert!(tree.repeat_error(&nid("rows")).is_some(), "the fixture's Repeat is in error");
assert_eq!(rect(&with, "after"), rect(&without, "after"));
assert_eq!(ids(&with), ["root", "after"]);
}
#[test]
fn visibility() {
let provider = ProviderId::new("provider.swarm");
let mut state = MemState::new();
state.put_state(&provider, "summary", &Swarm { id: "summary".into(), name: "Swarm".into(), load: 0.4 });
let visible_by = |schema: &str, key: &str, member: &str| BoolSource::Bound(Bind {
source: StateSource::Record(StateRef { provider: Some(provider.clone()), schema: SchemaId::new(schema), key: RecordKey::new(key) }),
member: path(&[member]),
format: None,
});
let hidden = |id: &str, visible: BoolSource, children: Vec<Node>| {
let mut node = bx(id, sized(10.0, 10.0), children);
if let Node::Box(b) = &mut node {
b.common.visible = visible;
}
node
};
let root = bx("root", plain(), vec![
hidden("gone", lit_bool(false), vec![embed("gone-child", 5.0, 5.0)]),
// The record does not exist: Absent.
hidden("absent", visible_by("gamecult.thing.test.swarm.v1", "missing", "Name"), vec![]),
// A text member read as a bool: Error.
hidden("error", visible_by("gamecult.thing.test.swarm.v1", "summary", "Name"), vec![]),
hidden("shown", lit_bool(true), vec![]),
]);
let laid = lay_with(&mut state, root, &pixels(400.0, 300.0, 1.0));
assert_eq!(ids(&laid), ["root", "absent", "error", "shown"]);
}
#[test]
fn embed_exact() {
let row = sized(200.0, 100.0);
let laid = lay(bx("root", row, vec![embed("viewport", 320.0, 180.0), bx("other", sized(150.0, 20.0), vec![])]), 800.0, 600.0);
assert_eq!(rect(&laid, "viewport").2, 320.0);
assert_eq!(rect(&laid, "viewport").3, 180.0);
let f08 = laid_fixture(Fixture::F08EmbedViewport, &pixels(800.0, 600.0, 1.0));
let f08 = f08[0].1.as_ref().unwrap();
assert_eq!(rect(f08, "viewport").2, 320.0);
assert_eq!(rect(f08, "viewport").3, 180.0);
}
#[test]
fn image_measures_through_the_measure() {
struct Fixed;
impl Measure for Fixed {
fn measure(&mut self, leaf: &Leaf, _: Constraint) -> (f32, f32) {
match leaf {
Leaf::Image { .. } => (40.0, 20.0),
_ => (0.0, 0.0),
}
}
}
let image = Node::Image(ImageNode {
common: common("pic"),
catalog: "c".into(),
asset: "a".into(),
fit: ImageFit::Contain,
alt: lit_text("alt"),
});
let root = bx("root", BoxStyle { direction: Direction::Column, size: size2(px(200.0), Dimension::Auto), ..plain() }, vec![image]);
let tree = bind(&mut MemState::new(), &surface_of(root)).unwrap();
let laid = layout(&tree, &pixels(800.0, 600.0, 1.0), &mut Fixed).unwrap();
// Stretched across the column, the image keeps its two-to-one shape.
assert_eq!(rect(&laid, "pic"), (0.0, 0.0, 200.0, 100.0));
// With no extent known, an Image is 0x0.
let none = layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels(&[])).unwrap();
assert_eq!(rect(&none, "pic").2 + rect(&none, "pic").3, 200.0);
}
#[derive(Clone, Copy, Debug)]
enum Kind {
Flex,
Grid,
Block,
Scroll,
}
const KINDS: [Kind; 4] = [Kind::Flex, Kind::Grid, Kind::Block, Kind::Scroll];
fn kind_style(kind: Kind) -> BoxStyle {
let auto_track = || vec![Dimension::Auto];
match kind {
Kind::Flex => plain(),
Kind::Grid => BoxStyle { display: Display::Grid, grid_columns: auto_track(), grid_rows: auto_track(), ..plain() },
Kind::Block => BoxStyle { display: Display::Block, ..plain() },
Kind::Scroll => BoxStyle { overflow: Overflow::Scroll, ..plain() },
}
}
/// `levels` nested boxes of one kind with a text leaf at the bottom.
#[test]
fn invalid_image_measures_are_named_and_harmless() {
struct Image((f32, f32));
impl Measure for Image {
fn measure(&mut self, leaf: &Leaf, _: Constraint) -> (f32, f32) {
match leaf {
Leaf::Image { .. } => self.0,
_ => (8.0, 16.0),
}
}
}
let picture = || Node::Image(ImageNode { common: common("pic"), catalog: "c".into(), asset: "a".into(), fit: ImageFit::Contain, alt: lit_text("alt") });
let root = || bx("root", BoxStyle { direction: Direction::Column, size: size2(px(200.0), Dimension::Auto), ..plain() }, vec![picture(), text("sibling", "hi")]);
let tree = bind(&mut MemState::new(), &surface_of(root())).unwrap();
let try_run = |size| layout(&tree, &pixels(800.0, 600.0, 1.0), &mut Image(size));
let run = |size| try_run(size).unwrap();
let mut refused = 0;
for size in [(1e7, 1e-30), (1e-30, 1e7), (0.0, 5.0), (f32::NAN, 1.0), (f32::INFINITY, 1.0), (-1.0, 2.0), (1e8, 1e8), (1.0, 1e7), (1e-3, 5.0), (3e6, 3e6)] {
// The measure still answers at its own size, so a bogus extent may also reach past the
// precision bound: then the layout is refused, which is as far from a silent shift.
let laid = match try_run(size) {
Ok(laid) => laid,
Err(LayoutError::OutOfRange(_)) => {
refused += 1;
continue;
}
Err(other) => panic!("{other:?}"),
};
assert_eq!(laid.diagnostics.len(), 1, "{size:?}");
let d = &laid.diagnostics[0];
assert_eq!((d.code, d.node.as_ref().map(|n| n.as_str()), d.detail.as_str()), (Code::StyleValueInvalid, Some("pic"), "measure"), "{size:?}");
// The sibling keeps its size (stretched across the column) and is not zeroed.
let sibling = rect(&laid, "sibling");
assert_eq!((sibling.2, sibling.3), (200.0, 16.0), "{size:?}");
assert!(laid.nodes.iter().all(|n| [n.rect.x, n.rect.y, n.rect.w, n.rect.h].iter().all(|v| v.is_finite())), "{size:?}");
}
assert!(refused < 10, "some invalid measures lay out with a diagnostic");
// The bound is judged in device px: 1.5e6 logical px at scale 2 is past it.
match layout(&tree, &pixels(800.0, 600.0, 2.0), &mut Image((1.5e6, 1.5e6))) {
Ok(doubled) => assert_eq!(doubled.diagnostics.len(), 1),
Err(LayoutError::OutOfRange(_)) => {}
Err(other) => panic!("{other:?}"),
}
// No extent yet (0x0) is not a fault, and a sound ratio is kept.
assert!(run((0.0, 0.0)).diagnostics.is_empty());
let sound = run((40.0, 20.0));
assert!(sound.diagnostics.is_empty());
assert_eq!(rect(&sound, "pic").3, 100.0);
}
fn chain(kind: Kind, levels: usize) -> Node {
let mut node = text("bottom", "x");
for level in (0..levels).rev() {
node = bx(&format!("deep-{level}"), kind_style(kind), vec![node]);
}
node
}
fn deep_limits() -> Limits {
Limits { max_tree_depth: 4096, ..Limits::default() }
}
fn run_default_thread(tree: &BoundTree) -> LaidTree {
std::thread::scope(|scope| {
scope
.spawn(|| layout(tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels(&[])).unwrap())
.join()
.expect("layout stays inside a default thread stack")
})
}
#[test]
fn depth() {
// f11 is 84 Box levels, as deep as CultCache decodes.
let mut state = MemState::from_fixture(Fixture::F11Deep);
let document = Fixture::F11Deep.load().surfaces.remove(0);
let tree = bind(&mut state, &document).unwrap();
assert!(run_default_thread(&tree).nodes.len() > 20);
// Every display kind at 1,024 levels (the resolver STACK_BOUND, the leaf included) lays out on a default thread. The tree is built and
// dropped on a roomy one: only layout is held to the default stack.
for kind in KINDS {
let nodes = std::thread::Builder::new()
.stack_size(128 * 1024 * 1024)
.spawn(move || {
let document = surface_of(chain(kind, 1023));
let tree = bind_with(&mut MemState::new(), &document, deep_limits()).unwrap();
run_default_thread(&tree).nodes.len()
})
.unwrap()
.join()
.unwrap();
assert_eq!(nodes, 1024, "{kind:?}");
}
}
/// How much stack one level of nesting takes inside Taffy, per kind. STACK_PER_LEVEL is twice
/// the worst of these in a debug build; run with --nocapture to read them.
#[test]
fn stack_per_level() {
struct Probe(Option<usize>);
impl Measure for Probe {
fn measure(&mut self, _: &Leaf, _: Constraint) -> (f32, f32) {
let left = stacker::remaining_stack().unwrap_or(0);
self.0 = Some(self.0.map_or(left, |low| low.min(left)));
(8.0, 16.0)
}
}
for kind in KINDS {
let used = |levels: usize| {
let tree = bind(&mut MemState::new(), &surface_of(chain(kind, levels))).unwrap();
let mut probe = Probe(None);
layout(&tree, &pixels(800.0, 600.0, 1.0), &mut probe).unwrap();
probe.0.expect("the bottom text was measured")
};
// The segment is sized by depth, so each run leaves a different amount of its own.
let (shallow, deep) = (used(16), used(48));
println!("LAYOUT_STACK_PROBE {kind:?}: shallow {shallow} deep {deep}");
}
}
#[test]
fn extreme_values_never_panic() {
let huge = |v: f64| px(v);
let count = std::cell::Cell::new(0);
let boxed_with = |mutate: &dyn Fn(&mut BoxStyle)| {
let mut style = sized(10.0, 10.0);
mutate(&mut style);
count.set(count.get() + 1);
bx(&format!("child{}", count.get()), style, vec![embed(&format!("e{}", count.get()), 5.0, 5.0)])
};
let root = bx("root", plain(), vec![
boxed_with(&|s| s.size = size2(huge(3e38), huge(3e38))),
boxed_with(&|s| s.margin = edges(huge(3e38))),
boxed_with(&|s| s.padding = edges(huge(3e38))),
boxed_with(&|s| s.size.width = Dimension::Percent(Scalar { value: 3e38 })),
boxed_with(&|s| s.grow = 3e38),
boxed_with(&|s| s.gap = size2(huge(1e7 + 1.0), huge(0.0))),
boxed_with(&|s| s.grid_columns = vec![Dimension::Fr(Scalar { value: 3e38 })]),
embed("big-embed", 3e38, 3e38),
]);
let laid = lay(root, 800.0, 600.0);
assert!(!laid.diagnostics.is_empty());
assert!(laid.diagnostics.iter().all(|d| d.code == Code::StyleValueInvalid && d.node.is_some()));
assert!(laid.diagnostics.iter().any(|d| d.node.as_ref().map(|n| n.as_str()) == Some("big-embed")));
// A length at the bound is legal; one past it is not.
let at = lay(bx("root", plain(), vec![bx("c", sized(2_097_152.0, 10.0), vec![])]), 800.0, 600.0);
assert!(at.diagnostics.is_empty());
let past = lay(bx("root", plain(), vec![bx("c", sized(2_097_153.0, 10.0), vec![])]), 800.0, 600.0);
assert_eq!(past.diagnostics.len(), 1);
// The bound is on device pixels: 6e6 logical px at scale 2 is past it.
let scaled = lay_with(&mut MemState::new(), bx("root", plain(), vec![bx("c", sized(6e6, 10.0), vec![])]), &pixels(800.0, 600.0, 2.0));
assert_eq!(scaled.diagnostics.len(), 1);
// A measure that answers beyond the bound is clamped to it.
struct Huge;
impl Measure for Huge {
fn measure(&mut self, _: &Leaf, _: Constraint) -> (f32, f32) {
(f32::MAX, f32::INFINITY)
}
}
let tree = bind(&mut MemState::new(), &surface_of(bx("root", plain(), vec![text("t", "x"), text("u", "y")]))).unwrap();
// 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]
fn image_measures_never_resize_fixed_siblings() {
struct Image((f32, f32));
impl Measure for Image {
fn measure(&mut self, leaf: &Leaf, _: Constraint) -> (f32, f32) {
match leaf {
Leaf::Image { .. } => self.0,
_ => (8.0, 16.0),
}
}
}
let picture = || Node::Image(ImageNode { common: common("pic"), catalog: "c".into(), asset: "a".into(), fit: ImageFit::Fill, alt: lit_text("alt") });
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
// Lengths are log-uniform over the allowed range, [1/8, 2^21], edges included.
let mut length = |next: &mut dyn FnMut() -> u64| {
let unit = (next() % 10_001) as f32 / 10_000.0;
(0.125f32 * (2_097_152.0f32 / 0.125).powf(unit)).clamp(0.125, 2_097_152.0)
};
for round in 0..400 {
let size = if round % 7 == 0 { (length(&mut next), length(&mut next)) } else { (length(&mut next).min(4096.0), length(&mut next).min(4096.0)) };
let direction = if round % 2 == 0 { Direction::Column } else { Direction::Row };
let fixed = BoxStyle { shrink: 0.0, ..sized(30.0, 20.0) };
let siblings = vec![embed("e1", 16.0, 12.0), picture(), bx("b1", fixed, vec![]), embed("e2", 7.0, 9.0)];
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 = 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);
assert_eq!((r.2, r.3), (w, h), "{id} with an image measuring {size:?}, {direction:?}");
}
let pic = rect(&laid, "pic");
assert!(pic.2 <= 2_097_152.0 && pic.3 <= 2_097_152.0, "{size:?} {pic:?}");
}
}
}
#[test]
fn random_styles_never_panic() {
let mut seed = 0x2545_F491_4F6C_DD1Du64;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
let values = [0.0, 1.0, 7.5, 100.0, 4096.0, 1e6, 1e7, 1e7 + 1.0, 1e30, 3e38, -1.0, -3e38, f64::NAN, f64::INFINITY];
for round in 0..300 {
let mut pick = || values[(next() % values.len() as u64) as usize];
let mut dims = Vec::new();
for n in 0..40u64 {
dims.push(match n % 5 {
0 => Dimension::Px(Scalar { value: pick() }),
1 => Dimension::Percent(Scalar { value: pick() }),
2 => Dimension::Fr(Scalar { value: pick() }),
3 => Dimension::Auto,
_ => Dimension::Content,
});
}
let mut cursor = 0;
let mut dim = || {
cursor += 7;
dims[cursor % dims.len()].clone()
};
let mut styles = Vec::new();
for n in 0..5u64 {
let mut s = plain();
s.display = [Display::Flex, Display::Grid, Display::Block][(n % 3) as usize].clone();
s.direction = [Direction::Row, Direction::Column][(n % 2) as usize].clone();
s.size = size2(dim(), dim());
s.min_size = size2(dim(), dim());
s.max_size = size2(dim(), dim());
s.margin = edges(dim());
s.padding = edges(dim());
s.gap = size2(dim(), dim());
s.basis = dim();
s.grow = pick();
s.shrink = pick();
s.grid_columns = vec![dim(), dim()];
s.overflow = [Overflow::Visible, Overflow::Clip, Overflow::Scroll][(n % 3) as usize].clone();
styles.push(s);
}
let leaf = |id: &str, s: &BoxStyle| bx(id, s.clone(), vec![embed(&format!("{id}-e"), 3.0, 3.0), text(&format!("{id}-t"), "ab cd")]);
let root = bx("root", styles[0].clone(), vec![
leaf("a", &styles[1]),
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 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())));
}
}
#[test]
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(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(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(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}");
}
#[test]
fn each_edge_of_the_precision_bound_refuses() {
let refused = |root: Node| {
let tree = bind(&mut MemState::new(), &surface_of(root)).unwrap();
matches!(layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels(&[])), Err(LayoutError::OutOfRange(_)))
};
let column = BoxStyle { direction: Direction::Column, ..plain() };
// The bottom edge alone is past the bound: the top is not.
assert!(refused(bx("root", column.clone(), vec![embed("a", 10.0, 16.0), embed("b", 10.0, 2_097_152.0)])));
// The right edge alone.
assert!(refused(bx("root", plain(), vec![embed("a", 16.0, 10.0), embed("b", 2_097_152.0, 10.0)])));
// A position past the bound on the negative side.
let pull = BoxStyle { margin: Edges { left: px(-2_097_152.0), ..edges(px(0.0)) }, ..plain() };
assert!(refused(bx("root", plain(), vec![bx("outer", pull.clone(), vec![bx("inner", pull, vec![embed("e", 1.0, 1.0)])])])));
// Whole layouts at the bound are fine.
assert!(!refused(bx("root", column, vec![embed("a", 10.0, 2_097_152.0)])));
}

View file

@ -4,6 +4,7 @@
pub mod build;
pub mod fixture;
pub mod golden;
pub mod measure;
pub mod mem_state;
pub mod state;
pub mod store;

View file

@ -0,0 +1,78 @@
//! A layout oracle, not a text engine: every size is a fixed function of the leaf, so layout
//! goldens never move when a real text measure changes.
use std::collections::HashMap;
use thing_contract::AssetCatalog;
use thing_core::bind::Bound;
use thing_core::layout::{Avail, Constraint, Leaf, Measure};
/// Text is 8 px wide per character and 16 px tall per line (one cell each in Cells); controls
/// have fixed sizes; an Image is its catalog entry's extent (0x0 when missing); a Plot is 0x0.
pub struct FixedMeasure {
cells: bool,
extents: HashMap<(String, String), (f32, f32)>,
}
impl FixedMeasure {
pub fn pixels(catalogs: &[AssetCatalog]) -> Self {
Self::new(false, catalogs)
}
pub fn cells(catalogs: &[AssetCatalog]) -> Self {
Self::new(true, catalogs)
}
fn new(cells: bool, catalogs: &[AssetCatalog]) -> Self {
let mut extents = HashMap::new();
for catalog in catalogs {
for asset in &catalog.assets {
let key = (catalog.catalog_id.as_str().to_string(), asset.id.clone());
extents.insert(key, (asset.width.get() as f32, asset.height.get() as f32));
}
}
Self { cells, extents }
}
fn text(&self, content: &Bound, wrap: bool, max_lines: Option<u32>, c: &Constraint) -> (f32, f32) {
let (cw, ch) = if self.cells { (1.0, 1.0) } else { (8.0, 16.0) };
let text = match content {
Bound::Text(text) => text.as_str(),
_ => "",
};
let chars = text.chars().count() as f32;
let room = c.known[0].map(Avail::Definite).unwrap_or(c.available[0]);
let (width, lines) = match (wrap, room) {
(true, Avail::Definite(w)) => {
let capacity = (w / cw).floor().max(1.0);
(chars.min(capacity), (chars / capacity).ceil().max(1.0))
}
(true, Avail::MinContent) => {
let word = text.split_whitespace().map(|w| w.chars().count()).max().unwrap_or(0) as f32;
(word, (chars / word.max(1.0)).ceil().max(1.0))
}
_ => (chars, 1.0),
};
let lines = max_lines.map_or(lines, |cap| lines.min(cap as f32));
(width * cw, lines * ch)
}
}
impl Measure for FixedMeasure {
fn measure(&mut self, leaf: &Leaf, c: Constraint) -> (f32, f32) {
// Pixels sizes, then the same control in cells: width / 8 and one row.
let control = |w: f32, h: f32| if self.cells { (w / 8.0, 1.0) } else { (w, h) };
match leaf {
Leaf::Text { content, wrap, max_lines, .. } => self.text(content, *wrap, *max_lines, &c),
Leaf::TextInput { multiline, .. } => control(200.0, if *multiline { 72.0 } else { 24.0 }),
Leaf::Toggle { .. } => control(40.0, 20.0),
Leaf::Slider { .. } => control(160.0, 20.0),
Leaf::Select { .. } => control(160.0, 24.0),
Leaf::Image { catalog, asset, .. } => {
let (w, h) = self.extents.get(&(catalog.to_string(), asset.to_string())).copied().unwrap_or((0.0, 0.0));
if self.cells { (w / 8.0, (h / 16.0).ceil()) } else { (w, h) }
}
Leaf::Plot { .. } => (0.0, 0.0),
}
}
}