Thing 2.0 cut 6a: render, LaidTree to the closed command list

render() turns a BoundTree, its LaidTree, ScrollOffsets and a Theme into commands, placed
geometry and diagnostics: clips balanced, scroll applied once through one clamp, overlays
translated by their anchor's scroll ancestors and never clipped by the main tree, text through
Measure::text. Goldens render-*.txt through the one bless path; f01 and f05 gain paint.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 07:44:52 +01:00
commit 55796965df
25 changed files with 4214 additions and 2 deletions

View file

@ -5,4 +5,6 @@ pub mod bind;
pub mod diagnostic;
pub mod layout;
pub mod port;
pub mod render;
pub mod resolve;
pub mod theme;

View file

@ -0,0 +1,37 @@
//! The closed render-command list. Z order is emission order: there is no z-index, no layer and
//! no custom command. Coordinates are f32 logical px (Pixels) or cells (Cells), already divided
//! by the scale; colours are literals, so a theme token cannot reach a backend by type.
use thing_contract::Rgba;
use crate::layout::{Rect, Run};
#[derive(Clone, Debug, PartialEq)]
pub enum RenderCommand {
FillRect { rect: Rect, radius: f32, color: Rgba },
StrokeRect { rect: Rect, radius: f32, width: f32, color: Rgba },
/// One line of text at `origin` (its top-left).
Text { origin: (f32, f32), run: Run, color: Rgba },
Image { rect: Rect, uri: String, alt: String },
ClipPush { rect: Rect, radius: f32 },
ClipPop,
Polyline { points: Vec<(f32, f32)>, width: f32, color: Rgba },
Polygon { points: Vec<(f32, f32)>, color: Rgba },
Embed { rect: Rect, slot_kind: String, slot_id: String },
}
/// Whether every ClipPush has its ClipPop, nested, and no ClipPop comes first.
pub fn balanced(commands: &[RenderCommand]) -> bool {
let mut open = 0usize;
for command in commands {
match command {
RenderCommand::ClipPush { .. } => open += 1,
RenderCommand::ClipPop => match open.checked_sub(1) {
Some(rest) => open = rest,
None => return false,
},
_ => {}
}
}
open == 0
}

View file

@ -0,0 +1,317 @@
//! Render: a `BoundTree`, its `LaidTree`, the scroll offsets and a theme become the closed command
//! list and the placed geometry hit-test, IME and accessibility read. A pure function: it reads
//! no port, no clock and no state, and equal inputs give an equal `Rendered`.
//!
//! This is the one place device px become logical px (divided by the scale) and scroll offsets
//! apply. Paint order is `LaidTree` order, which layout owns; render only looks nodes up.
mod command;
mod scroll;
use std::collections::HashMap;
use thing_contract::{Anchor, BoxNode, ColorRef, Node, NodeId, Rgba};
pub use command::{RenderCommand, balanced};
pub use scroll::{ScrollOffsets, clamp};
use crate::bind::{Bound, BoundTree, Field};
use crate::diagnostic::{Code, Diagnostic};
use crate::layout::{LaidTree, MAX_DEVICE, Measure, Metrics, Rect, TextRequest};
use crate::resolve::grow;
use crate::theme::{Theme, fallback};
/// What a frame is drawn with. `viewport` is what layout was given (logical px or cells).
#[derive(Clone, Copy, Debug)]
pub struct RenderInput<'a> {
pub scale: f32,
pub metrics: Metrics,
pub viewport: (f32, f32),
pub scroll: &'a ScrollOffsets,
pub theme: &'a Theme,
}
/// A laid node as it is on screen. `rect` is the scrolled border box in logical px (cells);
/// `visible` is `rect` cut by the clips open around it, `None` when nothing of it shows.
#[derive(Clone, Debug, PartialEq)]
pub struct Placed {
pub id: NodeId,
pub rect: Rect,
pub visible: Option<Rect>,
}
/// The frame: commands in paint order, `placed` in the same order, and the diagnostics of the
/// frame (layout's, then render's).
#[derive(Clone, Debug, PartialEq)]
pub struct Rendered {
pub commands: Vec<RenderCommand>,
pub placed: Vec<Placed>,
pub diagnostics: Vec<Diagnostic>,
}
pub fn render(tree: &BoundTree, laid: &LaidTree, input: &RenderInput, text: &mut dyn Measure) -> Rendered {
let mut nodes = HashMap::new();
index(tree, &tree.resolved().document().root, &mut nodes);
let k = match input.metrics {
Metrics::Pixels if input.scale.is_finite() && input.scale > 0.0 => input.scale,
_ => 1.0,
};
let mut ids = HashMap::new();
for (i, node) in laid.nodes.iter().enumerate() {
ids.entry(&node.id).or_insert(i);
}
let mut painter = Painter {
tree,
laid,
input,
nodes,
ids,
k,
shift: Vec::with_capacity(laid.nodes.len()),
inner: Vec::with_capacity(laid.nodes.len()),
stack: Vec::new(),
clips: Vec::new(),
out: Rendered { commands: Vec::new(), placed: Vec::new(), diagnostics: laid.diagnostics.clone() },
};
for i in 0..laid.nodes.len() {
painter.enter(i, text);
}
while let Some(top) = painter.stack.pop() {
painter.close(top);
}
painter.out
}
/// Every node of the document by id, Repeat instances included (ids are unique after resolve).
fn index<'a>(tree: &'a BoundTree, node: &'a Node, out: &mut HashMap<&'a NodeId, &'a Node>) {
grow(|| {
let (id, children): (&NodeId, &[Node]) = match node {
Node::Box(n) => (&n.common.id, &n.children),
Node::Button(n) => (&n.common.id, &n.content),
Node::Overlay(n) => (&n.common.id, &n.children),
Node::Repeat(n) => {
for instance in tree.instances(&n.common.id) {
index(tree, &instance.root, out);
}
(&n.common.id, &[])
}
Node::Text(n) => (&n.common.id, &[]),
Node::Image(n) => (&n.common.id, &[]),
Node::Toggle(n) => (&n.common.id, &[]),
Node::Slider(n) => (&n.common.id, &[]),
Node::TextInput(n) => (&n.common.id, &[]),
Node::Select(n) => (&n.common.id, &[]),
Node::Plot(n) => (&n.common.id, &[]),
Node::Embed(n) => (&n.common.id, &[]),
Node::Use(n) => (&n.common.id, &[]),
Node::Slot(_) => return,
};
out.insert(id, node);
for child in children {
index(tree, child, out);
}
})
}
struct Painter<'a> {
tree: &'a BoundTree,
laid: &'a LaidTree,
input: &'a RenderInput<'a>,
nodes: HashMap<&'a NodeId, &'a Node>,
ids: HashMap<&'a NodeId, usize>,
k: f32,
/// Per laid node so far: the device translation it is drawn under, and the one its children
/// are drawn under (that minus its own clamped offset).
shift: Vec<(f32, f32)>,
inner: Vec<(f32, f32)>,
/// The open nodes, a chain of ancestors; and the scrolled padding boxes of the open clips.
stack: Vec<usize>,
clips: Vec<Rect>,
out: Rendered,
}
fn meet(a: Rect, b: Rect) -> Option<Rect> {
let (x0, y0) = (a.x.max(b.x), a.y.max(b.y));
let (x1, y1) = ((a.x + a.w).min(b.x + b.w), (a.y + a.h).min(b.y + b.h));
(x1 >= x0 && y1 >= y0).then_some(Rect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 })
}
fn radius(value: f64) -> f32 {
let value = value as f32;
if value.is_finite() && value > 0.0 { value } else { 0.0 }
}
/// A thumb along one axis: the track starts at `start` and is `track` long, the content reaches
/// `max` past it, and the view is `offset` in. Returns the thumb's start and length.
fn thumb_span(start: f32, track: f32, max: f32, offset: f32) -> (f32, f32) {
let length = track * track / (track + max);
(start + (track - length) * offset / max, length)
}
impl<'a> Painter<'a> {
fn logical(&self, rect: Rect, shift: (f32, f32)) -> Rect {
let k = self.k;
Rect { x: (rect.x + shift.0) / k, y: (rect.y + shift.1) / k, w: rect.w / k, h: rect.h / k }
}
fn fault(&mut self, node: &NodeId, token: &str) -> Rgba {
self.out.diagnostics.push(Diagnostic {
code: Code::ThemeTokenUnknown,
surface: self.tree.resolved().document().record_key(),
node: Some(node.clone()),
detail: token.to_string(),
});
fallback()
}
fn color(&mut self, node: &NodeId, color: &ColorRef) -> Rgba {
match (self.input.theme.resolve(color), color) {
(Some(rgba), _) => rgba,
(None, ColorRef::Token(token)) => self.fault(node, &token.name),
(None, ColorRef::Rgba(literal)) => literal.clone(),
}
}
fn named(&mut self, node: &NodeId, name: &str) -> Rgba {
match self.input.theme.color(name) {
Some(rgba) => rgba,
None => self.fault(node, name),
}
}
/// The border a Box draws: its colour and width, when it has a legal width.
fn border(&self, b: &'a BoxNode) -> Option<(&'a ColorRef, f32)> {
let border = b.paint.border.as_ref()?;
let width = border.width as f32;
(width.is_finite() && width > 0.0 && width * self.k <= MAX_DEVICE).then_some((&border.color, width))
}
fn enter(&mut self, i: usize, text: &mut dyn Measure) {
let tree = self.laid;
let laid = &tree.nodes[i];
let parent = laid.parent.map(|p| p as usize);
while let Some(&top) = self.stack.last() {
if Some(top) == parent {
break;
}
self.stack.pop();
self.close(top);
}
let node = self.nodes.get(&laid.id).copied();
let shift = match (parent, node) {
(Some(p), _) => self.inner[p],
// An overlay root is carried by what its anchor is carried by, never by the anchor's own scroll.
(None, Some(Node::Overlay(o))) => match &o.anchor {
Anchor::Node(anchor) => match self.ids.get(&anchor.node) {
Some(&a) if a < i => self.shift[a],
_ => (0.0, 0.0),
},
Anchor::Viewport => (0.0, 0.0),
},
(None, _) => (0.0, 0.0),
};
let own = self.input.scroll.of(laid);
self.shift.push(shift);
self.inner.push((shift.0 - own.0, shift.1 - own.1));
let rect = self.logical(laid.rect, shift);
let visible = self.clips.iter().try_fold(rect, |seen, clip| meet(seen, *clip));
self.out.placed.push(Placed { id: laid.id.clone(), rect, visible });
self.stack.push(i);
let Some(node) = node else { return };
self.paint(node, rect, text);
if let (Some(padding), Node::Box(b)) = (laid.clip, node) {
let clip = self.logical(padding, shift);
let border = self.border(b).map_or(0.0, |(_, width)| width);
self.out.commands.push(RenderCommand::ClipPush { rect: clip, radius: (radius(b.paint.radius) - border).max(0.0) });
self.clips.push(clip);
}
}
fn paint(&mut self, node: &'a Node, rect: Rect, text: &mut dyn Measure) {
match node {
Node::Box(b) => {
let id = &b.common.id;
if let Some(background) = &b.paint.background {
let color = self.color(id, background);
self.out.commands.push(RenderCommand::FillRect { rect, radius: radius(b.paint.radius), color });
}
if let Some((color, width)) = self.border(b) {
let color = self.color(id, color);
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: radius(b.paint.radius), width, color });
}
}
Node::Overlay(o) if o.modal => {
let color = self.named(&o.common.id, "thing.scrim");
let (w, h) = self.input.viewport;
self.out.commands.push(RenderCommand::FillRect { rect: Rect { x: 0.0, y: 0.0, w, h }, radius: 0.0, color });
}
Node::Embed(e) => {
let (slot_kind, slot_id) = (e.slot_kind.clone(), e.slot_id.clone());
self.out.commands.push(RenderCommand::Embed { rect, slot_kind, slot_id });
}
Node::Use(u) => {
let color = self.named(&u.common.id, "thing.placeholder");
self.out.commands.push(RenderCommand::FillRect { rect, radius: 0.0, color });
let color = self.named(&u.common.id, "thing.error");
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
}
Node::Text(n) => {
let tree = self.tree;
match tree.value(&n.common.id, Field::Content) {
Some(Bound::Text(content)) => {
let color = match self.input.theme.text.get(&n.style_token) {
Some(style) => style.color.clone(),
None => self.fault(&n.common.id, &n.style_token),
};
let request = TextRequest {
node: &n.common.id,
text: content,
style_token: &n.style_token,
wrap: n.wrap,
max_lines: n.max_lines.map(|lines| lines.get().max(0) as u32),
};
for line in text.text(&request, rect.w).lines {
let origin = (rect.x, rect.y + line.y);
self.out.commands.push(RenderCommand::Text { origin, run: line.run, color: color.clone() });
}
}
Some(Bound::Error(_)) => {
let color = self.named(&n.common.id, "thing.error");
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
}
_ => {}
}
}
// Button, Toggle, Slider, Select, TextInput, Image and Plot draw nothing until the leaves cut.
_ => {}
}
}
/// Close an open node: its clip, then its scrollbars (which the clip does not cut).
fn close(&mut self, i: usize) {
let laid = self.laid;
let node = &laid.nodes[i];
let Some(padding) = node.clip else { return };
self.clips.pop();
self.out.commands.push(RenderCommand::ClipPop);
let Some(max) = node.max_scroll else { return };
let offset = self.input.scroll.of(node);
let thickness = match self.input.metrics {
Metrics::Cells => 1.0,
Metrics::Pixels => self.input.theme.scrollbar.max(0.0),
} * self.k;
let shift = self.shift[i];
let thumb = self.named(&node.id, "thing.scrollbar.thumb");
if max.1 > 0.0 {
let (y, h) = thumb_span(padding.y, padding.h, max.1, offset.1);
let rect = self.logical(Rect { x: padding.x + padding.w - thickness, y, w: thickness, h }, shift);
self.out.commands.push(RenderCommand::FillRect { rect, radius: 0.0, color: thumb.clone() });
}
if max.0 > 0.0 {
let (x, w) = thumb_span(padding.x, padding.w, max.0, offset.0);
let rect = self.logical(Rect { x, y: padding.y + padding.h - thickness, w, h: thickness }, shift);
self.out.commands.push(RenderCommand::FillRect { rect, radius: 0.0, color: thumb });
}
}
}

View file

@ -0,0 +1,38 @@
//! Scroll positions: runtime state, never a layout input. Input writes them here and render reads
//! them here, both through the one `clamp`.
use std::collections::HashMap;
use thing_contract::NodeId;
use crate::layout::LaidNode;
/// `offset` held within `[0, max_scroll]` on each axis; a NaN offset is 0, and an axis that
/// cannot scroll holds 0.
pub fn clamp(offset: (f32, f32), max_scroll: (f32, f32)) -> (f32, f32) {
let axis = |v: f32, max: f32| if v.is_nan() || !(max > 0.0 && max.is_finite()) { 0.0 } else { v.clamp(0.0, max) };
(axis(offset.0, max_scroll.0), axis(offset.1, max_scroll.1))
}
/// Where each scroll node is scrolled to, in device px (Pixels) or cells (Cells), as written.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ScrollOffsets(HashMap<NodeId, (f32, f32)>);
impl ScrollOffsets {
pub fn set(&mut self, node: NodeId, offset: (f32, f32)) {
self.0.insert(node, offset);
}
pub fn get(&self, node: &NodeId) -> Option<(f32, f32)> {
self.0.get(node).copied()
}
/// The offset a laid node is drawn at: what was written, clamped to what layout says it can
/// scroll. A node that does not scroll, or has no offset, has none.
pub fn of(&self, node: &LaidNode) -> (f32, f32) {
match (self.0.get(&node.id), node.max_scroll) {
(Some(offset), Some(max)) => clamp(*offset, max),
_ => (0.0, 0.0),
}
}
}

View file

@ -0,0 +1,84 @@
//! The theme a frame is drawn with: named colours and named text styles, resolved to literals
//! in render so a token never reaches a backend. Where a host's theme comes from is
//! `thing2:follow_up:theme-record-contract`; render takes a `&Theme`.
use std::collections::BTreeMap;
use thing_contract::{ColorRef, Rgba};
use crate::layout::CellStyle;
/// What a text style token draws as: the colour render emits, and the size and cell attributes
/// the text engine reads when it shapes the line.
#[derive(Clone, Debug, PartialEq)]
pub struct TextStyle {
pub color: Rgba,
pub size: f32,
pub cells: CellStyle,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Theme {
pub colors: BTreeMap<String, Rgba>,
pub text: BTreeMap<String, TextStyle>,
/// Scrollbar thickness, logical px (one cell in Cells).
pub scrollbar: f32,
}
/// The colour a token the theme does not hold draws as, so the fault is visible.
pub fn fallback() -> Rgba {
Rgba { r: 0xff, g: 0x00, b: 0xff, a: 0xff }
}
fn rgba(hex: u32) -> Rgba {
Rgba { r: (hex >> 24) as u8, g: (hex >> 16) as u8, b: (hex >> 8) as u8, a: hex as u8 }
}
impl Theme {
/// `thing.std`'s default: every token render and the fixtures use.
pub fn std() -> Self {
let colors = [
("thing.surface", 0x1e1e2eff),
("thing.error", 0xe5484dff),
("thing.placeholder", 0x6e6e80ff),
("thing.scrim", 0x00000099),
("thing.scrollbar.thumb", 0xffffff66),
("thing.control.fill", 0x2c2c3eff),
("thing.control.border", 0x4a4a60ff),
("thing.control.accent", 0x7c9cffff),
("thing.control.text", 0xeeeef4ff),
("thing.plot.mark", 0x7c9cffff),
]
.into_iter()
.map(|(name, hex)| (name.to_string(), rgba(hex)))
.collect();
let style = |hex: u32, size: f32, bold: bool| TextStyle {
color: rgba(hex),
size,
cells: CellStyle { bold, ..CellStyle::default() },
};
let text = [
("title", style(0xffffffff, 24.0, true)),
("body", style(0xeeeef4ff, 16.0, false)),
("thing.text", style(0xeeeef4ff, 16.0, false)),
]
.into_iter()
.map(|(name, style)| (name.to_string(), style))
.collect();
Self { colors, text, scrollbar: 6.0 }
}
/// The literal a colour is: a token the theme holds, or the literal itself. `None` is an
/// unknown token.
pub fn resolve(&self, color: &ColorRef) -> Option<Rgba> {
match color {
ColorRef::Rgba(literal) => Some(literal.clone()),
ColorRef::Token(token) => self.colors.get(&token.name).cloned(),
}
}
/// A named colour of the theme's own (render's scrim, error and thumb).
pub fn color(&self, name: &str) -> Option<Rgba> {
self.colors.get(name).cloned()
}
}

View file

@ -0,0 +1,7 @@
surface thing:surface:provider.swarm.dashboard viewport 100x37 scale 1 cells
fill 0 0 100 23 r8 #1e1e2eff
text 2 2 #ffffffff cells "42.0%" bold=false italic=false underline=false
text 54 2 #eeeef4ff cells "Eureka" bold=false italic=false underline=false
text 2 11 #eeeef4ff cells "Libby" bold=false italic=false underline=false
text 54 11 #eeeef4ff cells "Kiko" bold=false italic=false underline=false
text 2 20 #eeeef4ff cells "Restart" bold=false italic=false underline=false

View file

@ -0,0 +1,7 @@
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 1 pixels
fill 0 0 800 68 r8 #1e1e2eff
text 2 2 #ffffffff font0 size16 [52@0,0 50@8,0 46@16,0 48@24,0 37@32,0]
text 404 2 #eeeef4ff font0 size16 [69@0,0 117@8,0 114@16,0 101@24,0 107@32,0 97@40,0]
text 2 26 #eeeef4ff font0 size16 [76@0,0 105@8,0 98@16,0 98@24,0 121@32,0]
text 404 26 #eeeef4ff font0 size16 [75@0,0 105@8,0 107@16,0 111@24,0]
text 2 50 #eeeef4ff font0 size16 [82@0,0 101@8,0 115@16,0 116@24,0 97@32,0 114@40,0 116@48,0]

View file

@ -0,0 +1,2 @@
surface thing:surface:provider.login.login viewport 800x600 scale 1 pixels
text 2 34 #eeeef4ff font0 size16 [83@0,0 105@8,0 103@16,0 110@24,0 32@32,0 105@40,0 110@48,0]

View file

@ -0,0 +1,2 @@
surface thing:surface:provider.muninn.input-target viewport 800x600 scale 1 pixels
text 282 122 #eeeef4ff font0 size16 [82@0,0 101@8,0 97@16,0 100@24,0 121@32,0]

View file

@ -0,0 +1 @@
surface thing:surface:provider.settings.form viewport 800x600 scale 1 pixels

View file

@ -0,0 +1,7 @@
surface thing:surface:provider.dialog.modal viewport 800x600 scale 1.5 pixels
text 2 2 #eeeef4ff font0 size16 [84@0,0 104@8,0 101@16,0 32@24,0 97@32,0 114@40,0 99@48,0 104@56,0 105@64,0 118@72,0 101@80,0 32@88,0 104@96,0 111@104,0 108@112,0 100@120,0 115@128,0 32@136,0 49@144,0 50@152,0 32@160,0 105@168,0 116@176,0 101@184,0 109@192,0 115@200,0 46@208,0]
fill 0 0 800 600 r0 #00000099
fill 0 266 800 68 r6 #2c2c3eff
text 2 268 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0 32@48,0 116@56,0 104@64,0 101@72,0 32@80,0 97@88,0 114@96,0 99@104,0 104@112,0 105@120,0 118@128,0 101@136,0 63@144,0]
text 2 292 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0]
text 2 316 #eeeef4ff font0 size16 [67@0,0 97@8,0 110@16,0 99@24,0 101@32,0 108@40,0]

View file

@ -0,0 +1,7 @@
surface thing:surface:provider.dialog.modal viewport 800x600 scale 1 pixels
text 2 2 #eeeef4ff font0 size16 [84@0,0 104@8,0 101@16,0 32@24,0 97@32,0 114@40,0 99@48,0 104@56,0 105@64,0 118@72,0 101@80,0 32@88,0 104@96,0 111@104,0 108@112,0 100@120,0 115@128,0 32@136,0 49@144,0 50@152,0 32@160,0 105@168,0 116@176,0 101@184,0 109@192,0 115@200,0 46@208,0]
fill 0 0 800 600 r0 #00000099
fill 0 266 800 68 r6 #2c2c3eff
text 2 268 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0 32@48,0 116@56,0 104@64,0 101@72,0 32@80,0 97@88,0 114@96,0 99@104,0 104@112,0 105@120,0 118@128,0 101@136,0 63@144,0]
text 2 292 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0]
text 2 316 #eeeef4ff font0 size16 [67@0,0 97@8,0 110@16,0 99@24,0 101@32,0 108@40,0]

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1 @@
surface thing:surface:provider.market.plot viewport 800x600 scale 1 pixels

View file

@ -0,0 +1,4 @@
surface thing:surface:provider.viewport.embed-viewport viewport 800x600 scale 1 pixels
text 2 2 #eeeef4ff font0 size16 [98@0,0 101@8,0 102@16,0 111@24,0 114@32,0 101@40,0]
embed 244 2 320 180 "viewport.world" "main"
text 758 2 #eeeef4ff font0 size16 [97@0,0 102@8,0 116@16,0 101@24,0 114@32,0]

View file

@ -0,0 +1,8 @@
surface thing:surface:provider.stack.stack viewport 800x600 scale 1 pixels
text 2 2 #ff00ffff font0 size16 [76@0,0 111@8,0 97@16,0 100@24,0]
text 4 48 #ffffffff font0 size16 [67@0,0 97@8,0 114@16,0 100@24,0]
text 4 72 #eeeef4ff font0 size16 [79@0,0 112@8,0 101@16,0 110@24,0]
text 6 98 #ffffffff font0 size16 [67@0,0 97@8,0 114@16,0 100@24,0]
text 6 122 #eeeef4ff font0 size16 [79@0,0 112@8,0 101@16,0 110@24,0]
text 6 146 #eeeef4ff font0 size16 [110@0,0 101@8,0 115@16,0 116@24,0 101@32,0 100@40,0]
diagnostic ThemeTokenUnknown std-stat/stat-label caption

View file

@ -0,0 +1,7 @@
surface thing:surface:provider.hostile.duplicate-id refused DuplicateNodeId
surface thing:surface:provider.hostile.schema-mismatch viewport 800x600 scale 1 pixels
stroke 2 2 796 16 r0 w1 #e5484dff
surface thing:surface:provider.hostile.undeclared-command refused UndeclaredCommand
surface thing:surface:provider.hostile.unresolved-use viewport 800x600 scale 1 pixels
fill 2 2 796 16 r0 #6e6e80ff
stroke 2 2 796 16 r0 w1 #e5484dff

View file

@ -0,0 +1 @@
surface thing:surface:provider.deep.deep viewport 800x600 scale 1 pixels

View file

@ -0,0 +1,13 @@
surface thing:surface:provider.text.text-edge viewport 800x600 scale 1 pixels
text 2 2 #eeeef4ff font0 size16 [72@0,0 101@8,0 108@16,0 108@24,0 111@32,0 32@40,0 1513@48,0 1500@56,0 1493@64,0 1501@72,0 32@80,0 1506@88,0 1493@96,0 1500@104,0 1501@112,0 32@120,0 97@128,0 110@136,0 100@144,0 32@152,0 1605@160,0 1585@168,0 1581@176,0 1576@184,0 1575@192,0 32@200,0 1576@208,0 1575@216,0 1604@224,0 1593@232,0 1575@240,0 1604@248,0 1605@256,0 32@264,0 116@272,0 104@280,0 101@288,0 110@296,0 32@304,0 49@312,0 50@320,0 51@328,0 32@336,0 101@344,0 110@352,0 100@360,0 46@368,0]
text 2 26 #eeeef4ff font0 size16 [26085@0,0 26412@8,0 35486@16,0 12486@24,0 12473@32,0 12488@40,0 32@48,0 20320@56,0 22909@64,0 19990@72,0 30028@80,0 32@88,0 54620@96,0 44397@104,0 50612@112,0 32@120,0 65313@128,0 65314@136,0 65315@144,0 65297@152,0 65298@160,0 65299@168,0]
text 2 50 #eeeef4ff font0 size16 [101@0,0 769@8,0 32@16,0 97@24,0 776@32,0 32@40,0 110@48,0 771@56,0 32@64,0 111@72,0 770@80,0 803@88,0 32@96,0 122@104,0 859@112,0 847@120,0 768@128,0]
text 2 74 #eeeef4ff font0 size16 [128105@0,0 8205@8,0 128105@16,0 8205@24,0 128103@32,0 8205@40,0 128102@48,0 32@56,0 128104@64,0 127997@72,0 8205@80,0 128187@88,0 32@96,0 127987@104,0 65039@112,0 8205@120,0 127752@128,0]
text 2 98 #eeeef4ff font0 size16 [84@0,0 104@8,0 101@16,0 32@24,0 113@32,0 117@40,0 105@48,0 99@56,0 107@64,0 32@72,0 98@80,0 114@88,0 111@96,0 119@104,0 110@112,0 32@120,0 102@128,0 111@136,0 120@144,0 32@152,0 106@160,0 117@168,0 109@176,0 112@184,0 115@192,0 32@200,0 111@208,0 118@216,0 101@224,0 114@232,0 32@240,0 116@248,0 104@256,0 101@264,0 32@272,0 108@280,0 97@288,0 122@296,0 121@304,0 32@312,0 100@320,0 111@328,0 103@336,0 32@344,0 119@352,0 104@360,0 105@368,0 108@376,0 101@384,0 32@392,0 116@400,0 104@408,0 101@416,0 32@424,0 101@432,0 118@440,0 101@448,0 110@456,0 105@464,0 110@472,0 103@480,0 32@488,0 108@496,0 105@504,0 103@512,0 104@520,0 116@528,0 32@536,0 115@544,0 108@552,0 105@560,0 100@568,0 101@576,0 115@584,0 32@592,0 97@600,0 99@608,0 114@616,0 111@624,0 115@632,0 115@640,0 32@648,0 116@656,0 104@664,0 101@672,0 32@680,0 118@688,0 97@696,0 108@704,0 108@712,0 101@720,0 121@728,0 44@736,0 32@744,0 97@752,0 110@760,0 100@768,0 32@776,0 116@784,0]
text 2 114 #eeeef4ff font0 size16 [104@0,0 101@8,0 32@16,0 108@24,0 111@32,0 110@40,0 103@48,0 32@56,0 112@64,0 97@72,0 114@80,0 97@88,0 103@96,0 114@104,0 97@112,0 112@120,0 104@128,0 32@136,0 107@144,0 101@152,0 101@160,0 112@168,0 115@176,0 32@184,0 103@192,0 111@200,0 105@208,0 110@216,0 103@224,0 32@232,0 115@240,0 111@248,0 32@256,0 116@264,0 104@272,0 97@280,0 116@288,0 32@296,0 97@304,0 110@312,0 121@320,0 32@328,0 114@336,0 101@344,0 97@352,0 115@360,0 111@368,0 110@376,0 97@384,0 98@392,0 108@400,0 101@408,0 32@416,0 99@424,0 111@432,0 108@440,0 117@448,0 109@456,0 110@464,0 32@472,0 109@480,0 117@488,0 115@496,0 116@504,0 32@512,0 98@520,0 114@528,0 101@536,0 97@544,0 107@552,0 32@560,0 105@568,0 116@576,0 32@584,0 97@592,0 99@600,0 114@608,0 111@616,0 115@624,0 115@632,0 32@640,0 115@648,0 101@656,0 118@664,0 101@672,0 114@680,0 97@688,0 108@696,0 32@704,0 108@712,0 105@720,0 110@728,0 101@736,0 115@744,0 46@752,0 32@760,0 84@768,0 104@776,0 101@784,0]
text 2 130 #eeeef4ff font0 size16 [32@0,0 113@8,0 117@16,0 105@24,0 99@32,0 107@40,0 32@48,0 98@56,0 114@64,0 111@72,0 119@80,0 110@88,0 32@96,0 102@104,0 111@112,0 120@120,0 32@128,0 106@136,0 117@144,0 109@152,0 112@160,0 115@168,0 32@176,0 111@184,0 118@192,0 101@200,0 114@208,0 32@216,0 116@224,0 104@232,0 101@240,0 32@248,0 108@256,0 97@264,0 122@272,0 121@280,0 32@288,0 100@296,0 111@304,0 103@312,0 32@320,0 119@328,0 104@336,0 105@344,0 108@352,0 101@360,0 32@368,0 116@376,0 104@384,0 101@392,0 32@400,0 101@408,0 118@416,0 101@424,0 110@432,0 105@440,0 110@448,0 103@456,0 32@464,0 108@472,0 105@480,0 103@488,0 104@496,0 116@504,0 32@512,0 115@520,0 108@528,0 105@536,0 100@544,0 101@552,0 115@560,0 32@568,0 97@576,0 99@584,0 114@592,0 111@600,0 115@608,0 115@616,0 32@624,0 116@632,0 104@640,0 101@648,0 32@656,0 118@664,0 97@672,0 108@680,0 108@688,0 101@696,0 121@704,0 44@712,0 32@720,0 97@728,0 110@736,0 100@744,0 32@752,0 116@760,0 104@768,0 101@776,0 32@784,0]
text 2 146 #eeeef4ff font0 size16 [108@0,0 111@8,0 110@16,0 103@24,0 32@32,0 112@40,0 97@48,0 114@56,0 97@64,0 103@72,0 114@80,0 97@88,0 112@96,0 104@104,0 32@112,0 107@120,0 101@128,0 101@136,0 112@144,0 115@152,0 32@160,0 103@168,0 111@176,0 105@184,0 110@192,0 103@200,0 32@208,0 115@216,0 111@224,0 32@232,0 116@240,0 104@248,0 97@256,0 116@264,0 32@272,0 97@280,0 110@288,0 121@296,0 32@304,0 114@312,0 101@320,0 97@328,0 115@336,0 111@344,0 110@352,0 97@360,0 98@368,0 108@376,0 101@384,0 32@392,0 99@400,0 111@408,0 108@416,0 117@424,0 109@432,0 110@440,0 32@448,0 109@456,0 117@464,0 115@472,0 116@480,0 32@488,0 98@496,0 114@504,0 101@512,0 97@520,0 107@528,0 32@536,0 105@544,0 116@552,0 32@560,0 97@568,0 99@576,0 114@584,0 111@592,0 115@600,0 115@608,0 32@616,0 115@624,0 101@632,0 118@640,0 101@648,0 114@656,0 97@664,0 108@672,0 32@680,0 108@688,0 105@696,0 110@704,0 101@712,0 115@720,0 46@728,0 32@736,0 84@744,0 104@752,0 101@760,0 32@768,0 113@776,0 117@784,0]
text 2 162 #eeeef4ff font0 size16 [105@0,0 99@8,0 107@16,0 32@24,0 98@32,0 114@40,0 111@48,0 119@56,0 110@64,0 32@72,0 102@80,0 111@88,0 120@96,0 32@104,0 106@112,0 117@120,0 109@128,0 112@136,0 115@144,0 32@152,0 111@160,0 118@168,0 101@176,0 114@184,0 32@192,0 116@200,0 104@208,0 101@216,0 32@224,0 108@232,0 97@240,0 122@248,0 121@256,0 32@264,0 100@272,0 111@280,0 103@288,0 32@296,0 119@304,0 104@312,0 105@320,0 108@328,0 101@336,0 32@344,0 116@352,0 104@360,0 101@368,0 32@376,0 101@384,0 118@392,0 101@400,0 110@408,0 105@416,0 110@424,0 103@432,0 32@440,0 108@448,0 105@456,0 103@464,0 104@472,0 116@480,0 32@488,0 115@496,0 108@504,0 105@512,0 100@520,0 101@528,0 115@536,0 32@544,0 97@552,0 99@560,0 114@568,0 111@576,0 115@584,0 115@592,0 32@600,0 116@608,0 104@616,0 101@624,0 32@632,0 118@640,0 97@648,0 108@656,0 108@664,0 101@672,0 121@680,0 44@688,0 32@696,0 97@704,0 110@712,0 100@720,0 32@728,0 116@736,0 104@744,0 101@752,0 32@760,0 108@768,0 111@776,0 110@784,0]
text 2 178 #eeeef4ff font0 size16 [103@0,0 32@8,0 112@16,0 97@24,0 114@32,0 97@40,0 103@48,0 114@56,0 97@64,0 112@72,0 104@80,0 32@88,0 107@96,0 101@104,0 101@112,0 112@120,0 115@128,0 32@136,0 103@144,0 111@152,0 105@160,0 110@168,0 103@176,0 32@184,0 115@192,0 111@200,0 32@208,0 116@216,0 104@224,0 97@232,0 116@240,0 32@248,0 97@256,0 110@264,0 121@272,0 32@280,0 114@288,0 101@296,0 97@304,0 115@312,0 111@320,0 110@328,0 97@336,0 98@344,0 108@352,0 101@360,0 32@368,0 99@376,0 111@384,0 108@392,0 117@400,0 109@408,0 110@416,0 32@424,0 109@432,0 117@440,0 115@448,0 116@456,0 32@464,0 98@472,0 114@480,0 101@488,0 97@496,0 107@504,0 32@512,0 105@520,0 116@528,0 32@536,0 97@544,0 99@552,0 114@560,0 111@568,0 115@576,0 115@584,0 32@592,0 115@600,0 101@608,0 118@616,0 101@624,0 114@632,0 97@640,0 108@648,0 32@656,0 108@664,0 105@672,0 110@680,0 101@688,0 115@696,0 46@704,0 32@712,0 84@720,0 104@728,0 101@736,0 32@744,0 113@752,0 117@760,0 105@768,0 99@776,0 107@784,0]
text 2 194 #eeeef4ff font0 size16 [32@0,0 98@8,0 114@16,0 111@24,0 119@32,0 110@40,0 32@48,0 102@56,0 111@64,0 120@72,0 32@80,0 106@88,0 117@96,0 109@104,0 112@112,0 115@120,0 32@128,0 111@136,0 118@144,0 101@152,0 114@160,0 32@168,0 116@176,0 104@184,0 101@192,0 32@200,0 108@208,0 97@216,0 122@224,0 121@232,0 32@240,0 100@248,0 111@256,0 103@264,0 32@272,0 119@280,0 104@288,0 105@296,0 108@304,0 101@312,0 32@320,0 116@328,0 104@336,0 101@344,0 32@352,0 101@360,0 118@368,0 101@376,0 110@384,0 105@392,0 110@400,0 103@408,0 32@416,0 108@424,0 105@432,0 103@440,0 104@448,0 116@456,0 32@464,0 115@472,0 108@480,0 105@488,0 100@496,0 101@504,0 115@512,0 32@520,0 97@528,0 99@536,0 114@544,0 111@552,0 115@560,0 115@568,0 32@576,0 116@584,0 104@592,0 101@600,0 32@608,0 118@616,0 97@624,0 108@632,0 108@640,0 101@648,0 121@656,0 44@664,0 32@672,0 97@680,0 110@688,0 100@696,0 32@704,0 116@712,0 104@720,0 101@728,0 32@736,0 108@744,0 111@752,0 110@760,0 103@768,0 32@776,0 112@784,0]
text 2 210 #eeeef4ff font0 size16 [97@0,0 114@8,0 97@16,0 103@24,0 114@32,0 97@40,0 112@48,0 104@56,0 32@64,0 107@72,0 101@80,0 101@88,0 112@96,0 115@104,0 32@112,0 103@120,0 111@128,0 105@136,0 110@144,0 103@152,0 32@160,0 115@168,0 111@176,0 32@184,0 116@192,0 104@200,0 97@208,0 116@216,0 32@224,0 97@232,0 110@240,0 121@248,0 32@256,0 114@264,0 101@272,0 97@280,0 115@288,0 111@296,0 110@304,0 97@312,0 98@320,0 108@328,0 101@336,0 32@344,0 99@352,0 111@360,0 108@368,0 117@376,0 109@384,0 110@392,0 32@400,0 109@408,0 117@416,0 115@424,0 116@432,0 32@440,0 98@448,0 114@456,0 101@464,0 97@472,0 107@480,0 32@488,0 105@496,0 116@504,0 32@512,0 97@520,0 99@528,0 114@536,0 111@544,0 115@552,0 115@560,0 32@568,0 115@576,0 101@584,0 118@592,0 101@600,0 114@608,0 97@616,0 108@624,0 32@632,0 108@640,0 105@648,0 110@656,0 101@664,0 115@672,0 46@680,0 32@688,0]

View file

@ -0,0 +1,647 @@
//! Render: the command list, clips, scroll, overlays, theme and the text seam. `THING_BLESS=1`
//! rewrites the `render-*` goldens through `golden::check`; any other run compares.
use std::path::PathBuf;
use thing_contract::*;
use thing_core::bind::{Binder, BoundTree};
use thing_core::diagnostic::Code;
use thing_core::layout::{LaidTree, LayoutFrame, Metrics, Run, layout};
use thing_core::port::Ledger;
use thing_core::render::{Placed, RenderCommand, RenderInput, Rendered, ScrollOffsets, balanced, clamp, render};
use thing_core::resolve::{Limits, resolve};
use thing_core::theme::Theme;
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;
fn golden_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
}
fn frame(w: f32, h: f32, scale: f32, metrics: Metrics) -> LayoutFrame {
LayoutFrame { viewport: (w, h), scale, metrics }
}
fn pixels(scale: f32) -> LayoutFrame {
frame(800.0, 600.0, scale, Metrics::Pixels)
}
fn bind(state: &mut MemState, document: &SurfaceDocument) -> Result<BoundTree, Code> {
let limits = Limits::default();
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 measure(frame: &LayoutFrame) -> FixedMeasure {
match frame.metrics {
Metrics::Pixels => FixedMeasure::pixels(),
Metrics::Cells => FixedMeasure::cells(),
}
}
fn input<'a>(frame: &LayoutFrame, scroll: &'a ScrollOffsets, theme: &'a Theme) -> RenderInput<'a> {
RenderInput { scale: frame.scale, metrics: frame.metrics, viewport: frame.viewport, scroll, theme }
}
fn draw(tree: &BoundTree, frame: &LayoutFrame, scroll: &ScrollOffsets) -> (LaidTree, Rendered) {
let laid = layout(tree, frame, &mut measure(frame)).unwrap();
let rendered = render(tree, &laid, &input(frame, scroll, &Theme::std()), &mut measure(frame));
(laid, rendered)
}
fn surface_of(root: Node) -> SurfaceDocument {
SurfaceDocument {
provider_id: ProviderId::new("provider.render"),
label: seg("inline"),
version: ver(1),
title: "inline".into(),
root,
commands: vec![CommandDecl { id: CommandId::new("dismiss"), payload_schema: SchemaId::new("gamecult.thing.test.dismiss.v1"), captures: vec![], confirm: None }],
}
}
fn inline(root: Node, frame: &LayoutFrame, scroll: &ScrollOffsets) -> (LaidTree, Rendered) {
let tree = bind(&mut MemState::new(), &surface_of(root)).expect("resolves");
draw(&tree, frame, scroll)
}
// ---- the text form -----------------------------------------------------------------------
fn hex(c: &Rgba) -> String {
format!("#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a)
}
fn rect_text(r: &thing_core::layout::Rect) -> String {
format!("{} {} {} {}", r.x, r.y, r.w, r.h)
}
fn points(points: &[(f32, f32)]) -> String {
points.iter().map(|(x, y)| format!("{x},{y}")).collect::<Vec<_>>().join(" ")
}
fn line(command: &RenderCommand) -> String {
match command {
RenderCommand::FillRect { rect, radius, color } => format!("fill {} r{radius} {}", rect_text(rect), hex(color)),
RenderCommand::StrokeRect { rect, radius, width, color } => format!("stroke {} r{radius} w{width} {}", rect_text(rect), hex(color)),
RenderCommand::Text { origin, run, color } => match run {
Run::Glyphs { font, size, glyphs } => {
let glyphs: Vec<String> = glyphs.iter().map(|g| format!("{}@{},{}", g.id, g.x, g.y)).collect();
format!("text {} {} {} font{} size{size} [{}]", origin.0, origin.1, hex(color), font.0, glyphs.join(" "))
}
Run::Cells { text, style } => format!(
"text {} {} {} cells {text:?} bold={} italic={} underline={}",
origin.0,
origin.1,
hex(color),
style.bold,
style.italic,
style.underline
),
},
RenderCommand::Image { rect, uri, alt } => format!("image {} {uri:?} {alt:?}", rect_text(rect)),
RenderCommand::ClipPush { rect, radius } => format!("clip-push {} r{radius}", rect_text(rect)),
RenderCommand::ClipPop => "clip-pop".to_string(),
RenderCommand::Polyline { points: p, width, color } => format!("polyline w{width} {} {}", hex(color), points(p)),
RenderCommand::Polygon { points: p, color } => format!("polygon {} {}", hex(color), points(p)),
RenderCommand::Embed { rect, slot_kind, slot_id } => format!("embed {} {slot_kind:?} {slot_id:?}", rect_text(rect)),
}
}
fn text_form(rendered: &Rendered) -> String {
let mut out = String::new();
for command in &rendered.commands {
out += &line(command);
out += "\n";
}
for d in &rendered.diagnostics {
out += &format!("diagnostic {:?} {} {}\n", d.code, d.node.as_ref().map_or("-", |n| n.as_str()), d.detail);
}
out
}
// ---- fixtures ----------------------------------------------------------------------------
/// Every surface of a fixture, bound under the fixture's state script and rendered.
fn fixture_runs(fixture: Fixture, frame: &LayoutFrame, scroll: &ScrollOffsets) -> Vec<(String, Result<Rendered, Code>)> {
let set = fixture.load();
let mut state = MemState::from_fixture(fixture);
state::script(fixture, &mut state);
set.surfaces
.iter()
.map(|document| (document.record_key(), bind(&mut state, document).map(|tree| draw(&tree, frame, scroll).1)))
.collect()
}
fn fixture_text(fixture: Fixture, frame: &LayoutFrame, scroll: &ScrollOffsets) -> String {
let mut out = String::new();
for (key, run) in fixture_runs(fixture, frame, scroll) {
match run {
Ok(rendered) => {
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);
assert!(balanced(&rendered.commands), "{key}: clips are balanced");
out += &text_form(&rendered);
}
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, scroll: &ScrollOffsets) {
let text = fixture_text(fixture, frame, scroll);
golden::check(&golden_dir(), &format!("render-{}{suffix}.txt", stem(fixture)), text.as_bytes());
}
fn scrolled(node: &str, offset: (f32, f32)) -> ScrollOffsets {
let mut scroll = ScrollOffsets::default();
scroll.set(nid(node), offset);
scroll
}
#[test]
fn goldens() {
let none = ScrollOffsets::default();
for fixture in Fixture::ALL {
check(fixture, "", &pixels(1.0), &none);
}
check(Fixture::F01SwarmDashboard, "-cells", &frame(100.0, 37.0, 1.0, Metrics::Cells), &none);
check(Fixture::F05ModalOverlay, "-scale1.5", &pixels(1.5), &none);
check(Fixture::F06ScrollList, "-scale1.5", &pixels(1.5), &none);
check(Fixture::F06ScrollList, "-scroll1000", &pixels(1.0), &scrolled("root", (0.0, 1000.0)));
}
#[test]
fn determinism() {
let none = ScrollOffsets::default();
for fixture in Fixture::ALL {
for frame in [pixels(1.0), pixels(1.5), frame(100.0, 37.0, 1.0, Metrics::Cells)] {
let first = fixture_runs(fixture, &frame, &none);
let second = fixture_runs(fixture, &frame, &none);
let fresh = std::thread::spawn({
let none = none.clone();
move || fixture_runs(fixture, &frame, &none)
})
.join()
.unwrap();
assert_eq!(first, second, "{fixture:?} twice (a second bind of unchanged state included)");
assert_eq!(format!("{first:?}"), format!("{fresh:?}"), "{fixture:?} on a fresh thread");
}
}
}
// ---- inline trees ------------------------------------------------------------------------
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 sized(w: f64, h: f64) -> BoxStyle {
BoxStyle { size: size2(px(w), px(h)), ..plain() }
}
fn bx(id: &str, style: BoxStyle, paint: Paint, children: Vec<Node>) -> Node {
Node::Box(BoxNode { common: common(id), style, paint, role: Role::Group, children })
}
fn flat(id: &str, style: BoxStyle, children: Vec<Node>) -> Node {
bx(id, style, plain_paint(), children)
}
fn filled(color: &str) -> Paint {
Paint { background: Some(ColorRef::Token(ThemeToken { name: color.into() })), border: None, radius: 0.0 }
}
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 overlay(id: &str, anchor: Anchor, modal: bool, children: Vec<Node>) -> Node {
Node::Overlay(OverlayNode { common: common(id), anchor, modal, dismiss: command("dismiss"), children })
}
fn at(node: &str) -> Anchor {
Anchor::Node(AnchorNode { node: nid(node) })
}
fn placed<'a>(rendered: &'a Rendered, id: &str) -> &'a Placed {
rendered.placed.iter().find(|p| p.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}"))
}
fn xywh(p: &Placed) -> (f32, f32, f32, f32) {
(p.rect.x, p.rect.y, p.rect.w, p.rect.h)
}
/// Clip depth after each command.
fn depths(commands: &[RenderCommand]) -> Vec<usize> {
let mut depth = 0usize;
commands
.iter()
.map(|c| {
match c {
RenderCommand::ClipPush { .. } => depth += 1,
RenderCommand::ClipPop => depth -= 1,
_ => {}
}
depth
})
.collect()
}
fn fills(rendered: &Rendered) -> Vec<(f32, f32, f32, f32)> {
rendered
.commands
.iter()
.filter_map(|c| match c {
RenderCommand::FillRect { rect, .. } => Some((rect.x, rect.y, rect.w, rect.h)),
_ => None,
})
.collect()
}
#[test]
fn balance_is_judged_on_the_sequence() {
let push = || RenderCommand::ClipPush { rect: thing_core::layout::Rect { x: 0.0, y: 0.0, w: 1.0, h: 1.0 }, radius: 0.0 };
assert!(balanced(&[]));
assert!(balanced(&[push(), push(), RenderCommand::ClipPop, RenderCommand::ClipPop]));
assert!(!balanced(&[push()]));
assert!(!balanced(&[RenderCommand::ClipPop]));
assert!(!balanced(&[RenderCommand::ClipPop, push()]));
assert!(!balanced(&[push(), RenderCommand::ClipPop, RenderCommand::ClipPop]));
}
#[test]
fn a_clip_closes_before_its_sibling_and_scrollbars_follow_it() {
let pane = |id: &str| flat(id, BoxStyle { overflow: Overflow::Clip, ..sized(50.0, 20.0) }, vec![embed(&format!("{id}-e"), 10.0, 10.0)]);
let root = flat("root", plain(), vec![pane("a"), pane("b")]);
let (_, rendered) = inline(root, &pixels(1.0), &ScrollOffsets::default());
let kinds: Vec<&str> = rendered
.commands
.iter()
.map(|c| match c {
RenderCommand::ClipPush { .. } => "push",
RenderCommand::ClipPop => "pop",
RenderCommand::Embed { .. } => "embed",
_ => "other",
})
.collect();
assert_eq!(kinds, ["push", "embed", "pop", "push", "embed", "pop"]);
}
#[test]
fn scroll_translates_descendants_and_never_the_scroll_node() {
let pane = bx("pane", BoxStyle { overflow: Overflow::Scroll, direction: Direction::Column, ..sized(100.0, 50.0) }, filled("thing.surface"), vec![
embed("top", 10.0, 30.0),
embed("mid", 10.0, 30.0),
embed("low", 10.0, 300.0),
]);
let root = flat("root", plain(), vec![pane]);
for scale in [1.0f32, 1.5] {
let frame = pixels(scale);
let (laid, at0) = inline(root.clone(), &frame, &ScrollOffsets::default());
let max = laid.nodes.iter().find(|n| n.id.as_str() == "pane").unwrap().max_scroll.unwrap();
assert!(max.1 > 100.0);
let device = 40.0;
let (_, moved) = inline(root.clone(), &frame, &scrolled("pane", (0.0, device)));
assert_eq!(xywh(placed(&moved, "pane")), xywh(placed(&at0, "pane")), "the scroll node stays");
for id in ["top", "mid", "low"] {
let (before, after) = (placed(&at0, id).rect, placed(&moved, id).rect);
assert!((after.y - (before.y - device / scale)).abs() < 1e-3, "{id} at scale {scale}");
assert_eq!((after.x, after.w, after.h), (before.x, before.w, before.h));
}
// Its background is the same fill, drawn first; the thumb is the one that moved.
assert_eq!(fills(&at0)[0], fills(&moved)[0]);
assert_ne!(fills(&at0)[1], fills(&moved)[1], "the thumb follows the offset");
// An offset past max_scroll clamps, and an absent or non-scroll id is ignored.
let (_, past) = inline(root.clone(), &frame, &scrolled("pane", (0.0, 1e9)));
let (_, exact) = inline(root.clone(), &frame, &scrolled("pane", (0.0, max.1)));
assert_eq!(past, exact);
let (_, other) = inline(root.clone(), &frame, &scrolled("nowhere", (0.0, 40.0)));
assert_eq!(other, at0);
let (_, neg) = inline(root.clone(), &frame, &scrolled("pane", (-50.0, -50.0)));
assert_eq!(neg, at0);
}
}
#[test]
fn a_row_scrolled_out_is_not_visible() {
let pane = flat("pane", BoxStyle { overflow: Overflow::Scroll, direction: Direction::Column, ..sized(100.0, 50.0) }, vec![
embed("top", 10.0, 30.0),
embed("mid", 10.0, 30.0),
embed("low", 10.0, 300.0),
]);
let root = flat("root", plain(), vec![pane]);
let (_, rendered) = inline(root, &pixels(1.0), &scrolled("pane", (0.0, 100.0)));
assert_eq!(placed(&rendered, "top").visible, None);
assert_eq!(placed(&rendered, "mid").visible, None);
assert!(placed(&rendered, "low").visible.is_some());
assert!(placed(&rendered, "pane").visible.is_some());
// Half in view: cut by the pane's padding box.
let (_, half) = inline(
flat("root", plain(), vec![flat("pane", BoxStyle { overflow: Overflow::Scroll, direction: Direction::Column, ..sized(100.0, 50.0) }, vec![embed("top", 10.0, 30.0), embed("low", 10.0, 300.0)])]),
&pixels(1.0),
&scrolled("pane", (0.0, 20.0)),
);
let visible = placed(&half, "top").visible.unwrap();
assert_eq!((visible.y, visible.h), (0.0, 10.0));
}
#[test]
fn clamp_holds_both_ends_and_refuses_nan() {
assert_eq!(clamp((5.0, 5.0), (10.0, 10.0)), (5.0, 5.0));
assert_eq!(clamp((-5.0, 50.0), (10.0, 10.0)), (0.0, 10.0));
assert_eq!(clamp((f32::NAN, f32::INFINITY), (10.0, 10.0)), (0.0, 10.0));
assert_eq!(clamp((5.0, 5.0), (0.0, f32::NAN)), (0.0, 0.0));
}
/// A scroll pane holding a target a popup is anchored to, with a popup inside the popup and a
/// popup on the viewport.
fn popup_tree() -> Node {
let pane = flat("pane", BoxStyle { overflow: Overflow::Scroll, direction: Direction::Column, ..sized(200.0, 100.0) }, vec![
embed("spacer", 10.0, 30.0),
bx("target", sized(50.0, 20.0), filled("thing.surface"), vec![]),
embed("tall", 10.0, 400.0),
]);
flat("root", plain(), vec![
pane,
overlay("pop", at("target"), false, vec![bx("pop-box", sized(20.0, 10.0), filled("thing.control.fill"), vec![])]),
overlay("deeper", at("pop-box"), false, vec![bx("deep-box", sized(5.0, 5.0), filled("thing.control.accent"), vec![])]),
overlay("fixed", Anchor::Viewport, false, vec![bx("fixed-box", sized(8.0, 8.0), filled("thing.control.accent"), vec![])]),
])
}
#[test]
fn an_overlay_anchored_in_a_scroll_box_follows_the_scroll_and_is_not_clipped() {
for scale in [1.0f32, 2.0] {
let frame = pixels(scale);
let (_, at0) = inline(popup_tree(), &frame, &ScrollOffsets::default());
let device = 20.0;
let (_, moved) = inline(popup_tree(), &frame, &scrolled("pane", (0.0, device)));
let up = device / scale;
for id in ["target", "pop", "pop-box", "deeper", "deep-box"] {
assert!((placed(&moved, id).rect.y - (placed(&at0, id).rect.y - up)).abs() < 1e-3, "{id} moves with the anchor's scroll ancestor at scale {scale}");
assert_eq!(placed(&moved, id).rect.x, placed(&at0, id).rect.x);
}
// The anchor's own scroll does not move the anchor: pop sits on target.
assert_eq!(xywh(placed(&moved, "pop")), xywh(placed(&moved, "target")));
// A viewport overlay does not move.
assert_eq!(xywh(placed(&moved, "fixed-box")), xywh(placed(&at0, "fixed-box")));
// Not clipped by the box: every clip is closed before the first overlay command.
let first = moved.commands.iter().position(|c| matches!(c, RenderCommand::FillRect { color, .. } if *color == Theme::std().color("thing.control.fill").unwrap())).unwrap();
assert_eq!(depths(&moved.commands)[first], 0);
assert!(balanced(&moved.commands));
assert!(placed(&moved, "pop-box").visible.is_some());
}
}
#[test]
fn overlays_paint_after_the_main_tree_and_the_scrim_precedes_its_content() {
let root = flat("root", plain(), vec![
overlay("modal", Anchor::Viewport, true, vec![bx("dialog", sized(40.0, 20.0), filled("thing.control.fill"), vec![])]),
bx("main", sized(30.0, 30.0), filled("thing.surface"), vec![]),
]);
let (_, rendered) = inline(root, &pixels(1.0), &ScrollOffsets::default());
let theme = Theme::std();
let colors: Vec<Rgba> = rendered
.commands
.iter()
.filter_map(|c| match c {
RenderCommand::FillRect { color, .. } => Some(color.clone()),
_ => None,
})
.collect();
let expect: Vec<Rgba> = ["thing.surface", "thing.scrim", "thing.control.fill"].iter().map(|n| theme.color(n).unwrap()).collect();
assert_eq!(colors, expect);
let scrim = fills(&rendered)[1];
assert_eq!(scrim, (0.0, 0.0, 800.0, 600.0));
}
#[test]
fn diagnostics_inside_an_overlay_reach_the_frame() {
let bad = Paint { background: Some(ColorRef::Token(ThemeToken { name: "nope".into() })), border: None, radius: 0.0 };
let invalid = BoxStyle { padding: edges(px(-3.0)), ..plain() };
let root = flat("root", plain(), vec![overlay("pop", Anchor::Viewport, false, vec![bx("inside", invalid, bad, vec![])])]);
let (laid, rendered) = inline(root, &pixels(1.0), &ScrollOffsets::default());
assert!(laid.diagnostics.iter().any(|d| d.code == Code::StyleValueInvalid && d.node.as_ref().map(|n| n.as_str()) == Some("inside")));
let codes: Vec<(Code, &str)> = rendered.diagnostics.iter().map(|d| (d.code, d.node.as_ref().unwrap().as_str())).collect();
assert_eq!(codes, [(Code::StyleValueInvalid, "inside"), (Code::ThemeTokenUnknown, "inside")]);
assert_eq!(rendered.diagnostics[1].detail, "nope");
}
#[test]
fn scale_divides_device_coordinates() {
let none = ScrollOffsets::default();
let tree = |scale: f32| {
let set = Fixture::F05ModalOverlay.load();
let mut state = MemState::from_fixture(Fixture::F05ModalOverlay);
state::script(Fixture::F05ModalOverlay, &mut state);
let bound = bind(&mut state, &set.surfaces[0]).unwrap();
draw(&bound, &pixels(scale), &none)
};
let (laid, rendered) = tree(1.5);
assert_eq!(rendered.placed.len(), laid.nodes.len());
for (node, placed) in laid.nodes.iter().zip(&rendered.placed) {
assert_eq!(node.id, placed.id);
assert_eq!(xywh(placed), (node.rect.x / 1.5, node.rect.y / 1.5, node.rect.w / 1.5, node.rect.h / 1.5), "{}", node.id.as_str());
}
// The dialog's fill is its border box in logical px.
let dialog = placed(&rendered, "dialog");
assert!(fills(&rendered).contains(&xywh(dialog)));
}
#[test]
fn an_unknown_token_is_the_visible_fallback_and_named_once() {
let root = flat("root", plain(), vec![
bx("b", sized(10.0, 10.0), filled("thing.nope"), vec![]),
Node::Text(TextNode { common: common("t"), content: lit_text("hi"), style_token: "nope-style".into(), wrap: false, max_lines: None, selectable: false }),
]);
let (_, rendered) = inline(root, &pixels(1.0), &ScrollOffsets::default());
let magenta = Rgba { r: 255, g: 0, b: 255, a: 255 };
assert!(rendered.commands.iter().any(|c| matches!(c, RenderCommand::FillRect { color, .. } if *color == magenta)));
assert!(rendered.commands.iter().any(|c| matches!(c, RenderCommand::Text { color, .. } if *color == magenta)));
let named: Vec<(&str, &str)> = rendered.diagnostics.iter().map(|d| (d.node.as_ref().unwrap().as_str(), d.detail.as_str())).collect();
assert_eq!(named, [("b", "thing.nope"), ("t", "nope-style")]);
assert!(rendered.diagnostics.iter().all(|d| d.code == Code::ThemeTokenUnknown));
}
#[test]
fn wrapping_text_is_one_command_per_engine_line_at_the_node_origin() {
let root = flat("root", BoxStyle { padding: edges(px(5.0)), direction: Direction::Column, ..plain() }, vec![Node::Text(TextNode {
common: common("t"),
content: lit_text("abcdefghij"),
style_token: "body".into(),
wrap: true,
max_lines: None,
selectable: false,
})]);
let width = BoxStyle { size: size2(px(34.0), Dimension::Auto), ..plain() };
let root = if let Node::Box(mut b) = root { b.style.size = width.size; Node::Box(b) } else { unreachable!() };
let (_, rendered) = inline(root.clone(), &pixels(1.0), &ScrollOffsets::default());
let t = xywh(placed(&rendered, "t"));
let lines: Vec<(f32, f32, String)> = rendered
.commands
.iter()
.filter_map(|c| match c {
RenderCommand::Text { origin, run: Run::Glyphs { glyphs, .. }, .. } => Some((origin.0, origin.1, glyphs.iter().map(|g| char::from_u32(g.id).unwrap()).collect())),
_ => None,
})
.collect();
assert_eq!(lines, [(t.0, t.1, "abc".into()), (t.0, t.1 + 16.0, "def".into()), (t.0, t.1 + 32.0, "ghi".into()), (t.0, t.1 + 48.0, "j".into())]);
assert_eq!(t.3, 64.0, "layout sized the leaf for the lines the engine returns");
// Cells: the line's characters, one row each.
let cells = frame(20.0, 10.0, 1.0, Metrics::Cells);
let root = if let Node::Box(mut b) = root { b.style.size = size2(px(5.0), Dimension::Auto); b.style.padding = edges(px(0.0)); Node::Box(b) } else { unreachable!() };
let (_, rendered) = inline(root, &cells, &ScrollOffsets::default());
let texts: Vec<(f32, f32, String)> = rendered
.commands
.iter()
.filter_map(|c| match c {
RenderCommand::Text { origin, run: Run::Cells { text, .. }, .. } => Some((origin.0, origin.1, text.clone())),
_ => None,
})
.collect();
assert_eq!(texts, [(0.0, 0.0, "abcde".into()), (0.0, 1.0, "fghij".into())]);
}
#[test]
fn leaves_draw_what_this_cut_owns() {
let error_text = Node::Text(TextNode { common: common("e"), content: TextSource::Bound(item_bind(path(&["Nope"]))), style_token: "body".into(), wrap: false, max_lines: None, selectable: false });
let use_node = Node::Use(UseNode {
common: common("u"),
composition: CompositionRef { publisher: "nobody".into(), name: seg("missing"), version: ver(1) },
args: vec![],
});
let root = flat("root", BoxStyle { direction: Direction::Column, ..plain() }, vec![error_text, use_node, embed("x", 20.0, 10.0)]);
let (laid, rendered) = inline(root, &pixels(1.0), &ScrollOffsets::default());
let theme = Theme::std();
let u = placed(&rendered, "u");
assert!(u.rect.w >= 16.0 && u.rect.h >= 16.0, "a Use placeholder is visible: {:?}", u.rect);
assert!(rendered.commands.iter().any(|c| matches!(c, RenderCommand::FillRect { color, .. } if *color == theme.color("thing.placeholder").unwrap())));
let strokes = rendered.commands.iter().filter(|c| matches!(c, RenderCommand::StrokeRect { color, .. } if *color == theme.color("thing.error").unwrap())).count();
assert!(strokes >= 1);
assert!(rendered.commands.iter().any(|c| matches!(c, RenderCommand::Embed { slot_id, .. } if slot_id == "x")));
assert_eq!(rendered.placed.len(), laid.nodes.len());
}
#[test]
fn an_oversize_asset_extent_through_bind_is_an_invalid_measure_and_renders() {
let provider = ProviderId::new("provider.render");
let catalog = AssetCatalog {
provider_id: provider.clone(),
catalog_id: seg("icons"),
version: ver(1),
assets: vec![AssetEntry { id: "huge".into(), media_type: "image/png".into(), uri: "asset://huge".into(), width: count(4_000_000), height: count(10) }],
};
let mut state = MemState::new();
state.put(&provider, &catalog);
let picture = Node::Image(ImageNode { common: common("pic"), catalog: "icons".into(), asset: "huge".into(), fit: ImageFit::Contain, alt: lit_text("alt") });
let tree = bind(&mut state, &surface_of(flat("root", BoxStyle { direction: Direction::Column, ..plain() }, vec![picture, embed("after", 10.0, 10.0)]))).unwrap();
let (laid, rendered) = draw(&tree, &pixels(1.0), &ScrollOffsets::default());
let invalid: Vec<&str> = laid.diagnostics.iter().filter(|d| d.code == Code::StyleValueInvalid).map(|d| d.detail.as_str()).collect();
assert_eq!(invalid, ["measure"]);
assert_eq!(rendered.diagnostics, laid.diagnostics);
assert!(balanced(&rendered.commands));
assert!(placed(&rendered, "after").rect.w == 10.0);
}
#[test]
fn random_documents_render_without_panic_balanced_and_equal() {
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
let sizes = [0.0, 1.0, 7.5, 40.0, 100.0, 5000.0, 1e6, 1e7, -4.0, f64::NAN];
let overflows = [Overflow::Visible, Overflow::Clip, Overflow::Scroll];
let tokens = ["thing.surface", "thing.error", "unknown", "thing.scrim"];
for round in 0..300u64 {
let mut counter = 0u32;
let mut generated: Vec<String> = Vec::new();
fn grow(depth: u32, next: &mut dyn FnMut() -> u64, counter: &mut u32, generated: &mut Vec<String>, sizes: &[f64], overflows: &[Overflow], tokens: &[&str]) -> Node {
*counter += 1;
let id = format!("n{counter}");
generated.push(id.clone());
let pick = next();
match (pick % 7, depth) {
(0, _) => embed(&id, sizes[(next() % 10) as usize], sizes[(next() % 10) as usize]),
(1, _) => Node::Text(TextNode { common: common(&id), content: lit_text("some wrapping words"), style_token: tokens[(next() % 4) as usize].into(), wrap: next() % 2 == 0, max_lines: None, selectable: false }),
(2, d) if d < 3 => {
let anchor = if next() % 2 == 0 { Anchor::Viewport } else { at(&generated[(next() % generated.len() as u64) as usize]) };
let children = (0..(next() % 3)).map(|_| grow(depth + 1, next, counter, generated, sizes, overflows, tokens)).collect();
overlay(&id, anchor, next() % 2 == 0, children)
}
(_, d) if d < 4 => {
let mut style = BoxStyle { overflow: overflows[(next() % 3) as usize].clone(), ..plain() };
style.size = size2(px(sizes[(next() % 10) as usize]), px(sizes[(next() % 10) as usize]));
style.padding = edges(px(sizes[(next() % 10) as usize].min(40.0)));
style.direction = if next() % 2 == 0 { Direction::Row } else { Direction::Column };
let paint = Paint {
background: (next() % 2 == 0).then(|| ColorRef::Token(ThemeToken { name: tokens[(next() % 4) as usize].into() })),
border: (next() % 3 == 0).then(|| Border { color: ColorRef::Rgba(Rgba { r: 1, g: 2, b: 3, a: 4 }), width: sizes[(next() % 10) as usize] }),
radius: sizes[(next() % 10) as usize],
};
let children = (0..(next() % 4)).map(|_| grow(depth + 1, next, counter, generated, sizes, overflows, tokens)).collect();
bx(&id, style, paint, children)
}
_ => embed(&id, 3.0, 3.0),
}
}
let root = grow(0, &mut next, &mut counter, &mut generated, &sizes, &overflows, &tokens);
let ids = generated.clone();
let mut scroll = ScrollOffsets::default();
for id in &ids {
if next() % 3 != 0 {
continue;
}
scroll.set(nid(id), ((next() % 400) as f32 - 100.0, [f32::NAN, 1e30, 30.0, 400.0][(next() % 4) as usize]));
}
let frame = [pixels(1.0), pixels(1.5), pixels(2.0), frame(80.0, 30.0, 1.0, Metrics::Cells)][(round % 4) as usize];
let Ok(tree) = bind(&mut MemState::new(), &surface_of(root)) else { continue };
let Ok(laid) = layout(&tree, &frame, &mut measure(&frame)) else { continue };
let theme = Theme::std();
let first = render(&tree, &laid, &input(&frame, &scroll, &theme), &mut measure(&frame));
let second = render(&tree, &laid, &input(&frame, &scroll, &theme), &mut measure(&frame));
assert_eq!(first, second, "round {round}");
assert!(balanced(&first.commands), "round {round}");
assert_eq!(first.placed.len(), laid.nodes.len());
}
}

View file

@ -183,6 +183,10 @@ impl Fixture {
const SWARM: &str = "provider.swarm";
const SWARM_SCHEMA: &str = "gamecult.thing.test.swarm.v1";
fn token(name: &str) -> ColorRef {
ColorRef::Token(ThemeToken { name: name.into() })
}
fn swarm_ref(key: &str) -> StateSource {
StateSource::Record(StateRef {
provider: Some(ProviderId::new(SWARM)),
@ -235,7 +239,7 @@ fn swarm_dashboard() -> SurfaceDocument {
let root = Node::Box(BoxNode {
common: common("root"),
style: grid,
paint: plain_paint(),
paint: Paint { background: Some(token("thing.surface")), border: None, radius: 8.0 },
role: Role::Group,
children: vec![load_text, minds, restart],
});
@ -654,7 +658,11 @@ fn modal_overlay() -> SurfaceDocument {
let dialog = Node::Box(BoxNode {
common: common("dialog"),
style: style(),
paint: plain_paint(),
paint: Paint {
background: Some(ColorRef::Rgba(Rgba { r: 0x2c, g: 0x2c, b: 0x3e, a: 0xff })),
border: None,
radius: 6.0,
},
role: Role::Dialog,
children: vec![
text("dialog-title", "Delete the archive?"),