Thing 2.0 cut 6b: render leaves (Image fit in core, Plot lowered to polylines and polygons) (#20)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 2m46s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 6m0s

This commit is contained in:
Eureka 2026-11-28 07:41:33 +00:00
commit 8fe8b1aaad
18 changed files with 897 additions and 38 deletions

View file

@ -32,7 +32,6 @@ pub enum Leaf<'a> {
Slider { node: &'a NodeId },
Select { node: &'a NodeId, selected: &'a Bound },
Image { node: &'a NodeId, asset: &'a Bound },
Plot { node: &'a NodeId },
}
/// A face the text engine drew with. Opaque to core: the backend maps it to its own font.
@ -123,6 +122,12 @@ impl Device {
if self.cells { 1.0 } else { self.px(16.0) }
}
/// A Plot's size: the CSS default object size, 300x150 logical px, or 38x10 cells. A plot is
/// sized by layout, never measured.
pub(super) fn plot(self) -> (f32, f32) {
if self.cells { (38.0, 10.0) } else { (self.px(300.0), self.px(150.0)) }
}
pub(super) fn px(self, logical: f32) -> f32 {
logical * self.k
}

View file

@ -278,7 +278,16 @@ impl<'a> Builder<'a, '_> {
}
Node::Plot(n) => {
if !self.hidden(&n.common.id) {
self.leaf(&n.common.id, parent, Leaf::Plot { node: &n.common.id }, out);
// A plot declares no size: layout gives it the default object size.
let (width, height) = self.dev.plot();
let style = Style {
size: taffy::Size { width: taffy::Dimension::length(width), height: taffy::Dimension::length(height) },
..Style::default()
};
let index = self.entry(&n.common.id, parent, &Overflow::Visible);
let id = self.taffy.new_leaf(style).expect("taffy: insert");
self.entries[index].node = id;
out.push(id);
}
}
})

View file

@ -0,0 +1,174 @@
//! The leaves: control chrome, an Image's fit and the missing-asset placeholder. Core alone turns
//! fit and control state into geometry; no caret, selection or focus ring (those need edit and
//! focus state). Pixels and Cells share the lowering; only the inset and the stroke differ.
use thing_contract::{ButtonNode, ImageFit, ImageNode, NodeId, SelectNode, SliderNode, TextInputNode, ToggleNode};
use super::Painter;
use super::command::RenderCommand;
use crate::bind::{Bound, Field};
use crate::diagnostic::{Code, Diagnostic};
use crate::layout::{Measure, Metrics, Rect, TextRequest};
/// Where an Image lands inside `rect` for an extent of `(w, h)` asset px (1 asset px = 1 logical
/// px), and whether it must be clipped to `rect`.
fn fitted(fit: &ImageFit, rect: Rect, (w, h): (f32, f32)) -> (Rect, bool) {
let scale = match fit {
ImageFit::Fill => return (rect, false),
ImageFit::Contain => (rect.w / w).min(rect.h / h),
ImageFit::Cover => (rect.w / w).max(rect.h / h),
ImageFit::Unscaled => 1.0,
};
let (dw, dh) = (w * scale, h * scale);
let dest = Rect { x: rect.x + (rect.w - dw) / 2.0, y: rect.y + (rect.h - dh) / 2.0, w: dw, h: dh };
(dest, matches!(fit, ImageFit::Cover | ImageFit::Unscaled))
}
impl<'a> Painter<'a> {
fn flag(&self, id: &NodeId, field: Field) -> Option<bool> {
match self.tree.value(id, field) {
Some(Bound::Bool(b)) => Some(*b),
_ => None,
}
}
fn bound_text(&self, id: &NodeId, field: Field) -> Option<&'a str> {
let tree = self.tree;
match tree.value(id, field) {
Some(Bound::Text(t)) => Some(t.as_str()),
_ => None,
}
}
/// The inset of a control's content from its border: 2 logical px, none in a cell grid.
fn inset(&self) -> f32 {
if self.input.metrics == Metrics::Cells { 0.0 } else { 2.0 }
}
fn stroke(&mut self, id: &NodeId, rect: Rect) {
let color = self.named(id, "thing.control.border");
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
}
fn fill(&mut self, id: &NodeId, rect: Rect, token: &str) {
let color = self.named(id, token);
self.out.commands.push(RenderCommand::FillRect { rect, radius: 0.0, color });
}
/// The lines of `content` the engine breaks at `at.w`, those that end within `room` of the top.
#[allow(clippy::too_many_arguments)]
pub(super) fn draw_text(&mut self, id: &NodeId, content: &str, token: &str, wrap: bool, max_lines: Option<u32>, at: Rect, room: f32, text: &mut dyn Measure) {
let color = match self.input.theme.text.get(token) {
Some(style) => style.color.clone(),
None => self.fault(id, token),
};
let request = TextRequest { node: id, text: content, style_token: token, wrap, max_lines };
for line in text.text(&request, at.w).lines.into_iter().filter(|line| line.y + line.height <= room) {
self.out.commands.push(RenderCommand::Text { origin: (at.x, at.y + line.y), run: line.run, color: color.clone() });
}
}
/// What stands where a leaf's content could not be drawn: a fill and an error stroke.
pub(super) fn placeholder(&mut self, id: &NodeId, rect: Rect) {
self.fill(id, rect, "thing.placeholder");
let color = self.named(id, "thing.error");
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
}
/// The content box of a control: `rect` less the inset all round.
fn content_box(&self, rect: Rect) -> Rect {
let pad = self.inset().min(rect.w / 2.0).min(rect.h / 2.0).max(0.0);
Rect { x: rect.x + pad, y: rect.y + pad, w: rect.w - 2.0 * pad, h: rect.h - 2.0 * pad }
}
pub(super) fn button(&mut self, n: &ButtonNode, rect: Rect) {
let id = &n.common.id;
let enabled = self.flag(id, Field::Enabled) != Some(false);
self.fill(id, rect, if enabled { "thing.control.fill" } else { "thing.control.disabled" });
self.stroke(id, rect);
}
pub(super) fn toggle(&mut self, n: &ToggleNode, rect: Rect) {
let id = &n.common.id;
self.stroke(id, rect);
let inner = self.content_box(rect);
let side = inner.h.min(inner.w / 2.0).max(0.0);
let checked = self.flag(id, Field::Checked) == Some(true);
let x = if checked { inner.x + inner.w - side } else { inner.x };
self.fill(id, Rect { x, y: inner.y + (inner.h - side) / 2.0, w: side, h: side }, "thing.control.accent");
}
pub(super) fn slider(&mut self, n: &SliderNode, rect: Rect) {
let id = &n.common.id;
let thickness = if self.input.metrics == Metrics::Cells { rect.h } else { rect.h / 4.0 };
self.fill(id, Rect { x: rect.x, y: rect.y + (rect.h - thickness) / 2.0, w: rect.w, h: thickness }, "thing.control.border");
let fraction = if n.min.is_finite() && n.max.is_finite() && n.min < n.max {
match self.tree.value(id, Field::Value) {
Some(Bound::Number(v)) if v.is_finite() => ((v - n.min) / (n.max - n.min)).clamp(0.0, 1.0),
_ => 0.0,
}
} else {
self.out.diagnostics.push(Diagnostic {
code: Code::StyleValueInvalid,
surface: self.tree.resolved().document().record_key(),
node: Some(id.clone()),
detail: "max".to_string(),
});
0.0
};
let side = rect.h.min(rect.w).max(0.0);
let x = rect.x + (rect.w - side) * fraction as f32;
self.fill(id, Rect { x, y: rect.y, w: side, h: side }, "thing.control.accent");
}
pub(super) fn select(&mut self, n: &SelectNode, rect: Rect, text: &mut dyn Measure) {
let id = &n.common.id;
self.stroke(id, rect);
let Some(value) = self.bound_text(id, Field::Selected) else { return };
let tree = self.tree;
let label = match tree.value(id, Field::Options) {
Some(Bound::Options(options)) => options.iter().find(|o| o.value == value).map_or(value, |o| o.label.as_str()),
_ => value,
};
let inner = self.content_box(rect);
self.draw_text(id, label, "thing.text", false, Some(1), inner, inner.h, text);
}
pub(super) fn text_input(&mut self, n: &TextInputNode, rect: Rect, text: &mut dyn Measure) {
let id = &n.common.id;
self.stroke(id, rect);
let (content, token) = match self.bound_text(id, Field::Initial).filter(|t| !t.is_empty()) {
Some(initial) => (initial, "thing.text"),
None => match self.bound_text(id, Field::Placeholder) {
Some(placeholder) => (placeholder, "thing.text.placeholder"),
None => return,
},
};
let inner = self.content_box(rect);
self.draw_text(id, content, token, n.multiline, if n.multiline { None } else { Some(1) }, inner, inner.h, text);
}
pub(super) fn image(&mut self, n: &ImageNode, rect: Rect, text: &mut dyn Measure) {
let id = &n.common.id;
let alt = self.bound_text(id, Field::Alt).unwrap_or("");
let tree = self.tree;
let entry = match tree.value(id, Field::Asset) {
Some(Bound::Asset(entry)) if entry.width.get() > 0 && entry.height.get() > 0 => entry,
_ => {
self.placeholder(id, rect);
if !alt.is_empty() && rect.w > 0.0 {
self.draw_text(id, alt, "thing.text", true, Some(1), rect, rect.h, text);
}
return;
}
};
let (dest, clipped) = fitted(&n.fit, rect, (entry.width.get() as f32, entry.height.get() as f32));
if clipped {
self.out.commands.push(RenderCommand::ClipPush { rect, radius: 0.0 });
}
self.out.commands.push(RenderCommand::Image { rect: dest, uri: entry.uri.clone(), alt: alt.to_string() });
if clipped {
self.out.commands.push(RenderCommand::ClipPop);
}
}
}

View file

@ -6,6 +6,8 @@
//! apply. Paint order is `LaidTree` order, which layout owns; render only looks nodes up.
mod command;
mod leaf;
mod plot;
mod scroll;
use std::collections::HashMap;
@ -17,7 +19,7 @@ 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::layout::{LaidTree, MAX_DEVICE, Measure, Metrics, Rect};
use crate::resolve::grow;
use crate::theme::{Theme, fallback};
@ -154,7 +156,7 @@ impl<'a> Painter<'a> {
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 {
pub(super) fn fault(&mut self, node: &NodeId, token: &str) -> Rgba {
self.out.diagnostics.push(Diagnostic {
code: Code::ThemeTokenUnknown,
surface: self.tree.resolved().document().record_key(),
@ -172,7 +174,7 @@ impl<'a> Painter<'a> {
}
}
fn named(&mut self, node: &NodeId, name: &str) -> Rgba {
pub(super) fn named(&mut self, node: &NodeId, name: &str) -> Rgba {
match self.input.theme.color(name) {
Some(rgba) => rgba,
None => self.fault(node, name),
@ -250,31 +252,13 @@ impl<'a> Painter<'a> {
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::Use(u) => self.placeholder(&u.common.id, rect),
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() });
}
let max_lines = n.max_lines.map(|lines| lines.get().max(0) as u32);
self.draw_text(&n.common.id, content, &n.style_token, n.wrap, max_lines, rect, f32::INFINITY, text);
}
Some(Bound::Error(_)) => {
let color = self.named(&n.common.id, "thing.error");
@ -283,8 +267,14 @@ impl<'a> Painter<'a> {
_ => {}
}
}
// Button, Toggle, Slider, Select, TextInput, Image and Plot draw nothing until the leaves cut.
_ => {}
Node::Button(n) => self.button(n, rect),
Node::Toggle(n) => self.toggle(n, rect),
Node::Slider(n) => self.slider(n, rect),
Node::Select(n) => self.select(n, rect, text),
Node::TextInput(n) => self.text_input(n, rect, text),
Node::Image(n) => self.image(n, rect, text),
Node::Plot(n) => self.plot(n, rect),
Node::Overlay(_) | Node::Repeat(_) | Node::Slot(_) => {}
}
}

View file

@ -0,0 +1,173 @@
//! A Plot lowered to geometry: the domain, then Polylines, Polygons or FillRects. Pure and
//! bounded: a series of N points gives at most N vertices (Line), 2N (Area: each run of m >= 2
//! points adds two baseline vertices) or N rects (Bar); a non-finite or unrepresentable (f32) point is skipped with one diagnostic, never drawn.
use thing_contract::{PlotMark, PlotNode};
use super::Painter;
use super::command::RenderCommand;
use crate::bind::{Bound, Field};
use crate::diagnostic::{Code, Diagnostic};
use crate::layout::Rect;
/// One axis' domain: an explicit bound that is finite and not crossed by the other end is kept,
/// anything else takes the data value and is named; equal ends widen by 1 each way.
fn domain(explicit: (Option<f64>, Option<f64>), data: (f64, f64), names: (&'static str, &'static str), invalid: &mut Vec<&'static str>) -> (f64, f64) {
let (mut lo, mut hi) = (explicit.0.filter(|v| v.is_finite()), explicit.1.filter(|v| v.is_finite()));
if explicit.0.is_some() && lo.is_none() {
invalid.push(names.0);
}
if explicit.1.is_some() && hi.is_none() {
invalid.push(names.1);
}
if let (Some(a), Some(b)) = (lo, hi) {
if a > b {
invalid.extend([names.0, names.1]);
(lo, hi) = (None, None);
}
} else if let Some(a) = lo {
if a > data.1 {
invalid.push(names.0);
lo = None;
}
} else if let Some(b) = hi {
if b < data.0 {
invalid.push(names.1);
hi = None;
}
}
let (lo, hi) = (lo.unwrap_or(data.0), hi.unwrap_or(data.1));
if lo == hi { (lo - 1.0, hi + 1.0) } else { (lo, hi) }
}
/// Where the series lands in `rect`: screen y grows down.
struct Frame {
rect: Rect,
x: (f64, f64),
y: (f64, f64),
}
impl Frame {
/// A point of the series as f32 screen coordinates, `None` when either does not fit an f32.
fn at(&self, i: usize, v: f64) -> Option<(f32, f32)> {
let tx = halved(i as f64, self.x);
let x = (self.rect.x as f64 + tx * self.rect.w as f64) as f32;
let y = self.value(v) as f32;
(x.is_finite() && y.is_finite()).then_some((x, y))
}
/// Screen y of a value: y grows down. Halves keep a span near f64's range from overflowing.
fn value(&self, v: f64) -> f64 {
self.rect.y as f64 + self.rect.h as f64 - halved(v, self.y) * self.rect.h as f64
}
}
/// Where `v` falls in `(lo, hi)`, 0 to 1, computed on halves so `hi - lo` cannot overflow.
fn halved(v: f64, (lo, hi): (f64, f64)) -> f64 {
(v / 2.0 - lo / 2.0) / (hi / 2.0 - lo / 2.0)
}
impl Painter<'_> {
pub(super) fn plot(&mut self, n: &thing_contract::PlotNode, rect: Rect) {
let tree = self.tree;
match tree.value(&n.common.id, Field::Series) {
Some(Bound::Series(values)) => self.plot_series(n, values, rect),
Some(Bound::Error(_)) => self.placeholder(&n.common.id, rect),
_ => {}
}
}
/// A point that was not drawn is said once for the plot, whatever the reason.
fn dropped(&mut self, n: &PlotNode) {
self.out.diagnostics.push(Diagnostic {
code: Code::StyleValueInvalid,
surface: self.tree.resolved().document().record_key(),
node: Some(n.common.id.clone()),
detail: "series".to_string(),
});
}
fn plot_series(&mut self, n: &PlotNode, values: &[f64], rect: Rect) {
if values.is_empty() || !(rect.w > 0.0 && rect.h > 0.0) {
return;
}
let finite = || values.iter().copied().filter(|v| v.is_finite());
let low = finite().fold(f64::INFINITY, f64::min);
let high = finite().fold(f64::NEG_INFINITY, f64::max);
let data_y = if low <= high { (low, high) } else { (0.0, 0.0) };
let mut invalid = Vec::new();
let x = domain((n.x_min, n.x_max), (0.0, (values.len() - 1) as f64), ("x_min", "x_max"), &mut invalid);
let y = domain((n.y_min, n.y_max), data_y, ("y_min", "y_max"), &mut invalid);
for name in invalid {
self.out.diagnostics.push(Diagnostic {
code: Code::StyleValueInvalid,
surface: self.tree.resolved().document().record_key(),
node: Some(n.common.id.clone()),
detail: name.to_string(),
});
}
let frame = Frame { rect, x, y };
let color = self.named(&n.common.id, "thing.plot.mark");
let width = match self.input.metrics {
crate::layout::Metrics::Cells => 1.0,
crate::layout::Metrics::Pixels => 2.0,
};
let base = frame.value(0.0f64.clamp(y.0, y.1));
if !(base as f32).is_finite() {
self.dropped(n);
return;
}
let mut shapes = Vec::new();
let mut dropped = false;
match n.mark {
PlotMark::Bar => {
let slot = rect.w / values.len() as f32;
for (i, v) in values.iter().enumerate() {
let top = frame.value(*v);
let (y0, y1) = (top.min(base) as f32, top.max(base) as f32);
let bar = Rect { x: rect.x + slot * i as f32, y: y0, w: slot, h: y1 - y0 };
if v.is_finite() && [bar.x, bar.y, bar.w, bar.h].iter().all(|c| c.is_finite()) {
shapes.push(RenderCommand::FillRect { rect: bar, radius: 0.0, color: color.clone() });
} else {
dropped = true;
}
}
}
PlotMark::Line | PlotMark::Area => {
let mut run: Vec<(f32, f32)> = Vec::new();
let flush = |run: &mut Vec<(f32, f32)>, shapes: &mut Vec<RenderCommand>| {
if run.len() >= 2 {
let mut points = std::mem::take(run);
if n.mark == PlotMark::Area {
let (first, last) = (points[0].0, points[points.len() - 1].0);
points.extend([(last, base as f32), (first, base as f32)]);
shapes.push(RenderCommand::Polygon { points, color: color.clone() });
} else {
shapes.push(RenderCommand::Polyline { points, width, color: color.clone() });
}
}
run.clear();
};
for (i, v) in values.iter().enumerate() {
match v.is_finite().then(|| frame.at(i, *v)).flatten() {
Some(point) => run.push(point),
None => {
dropped = true;
flush(&mut run, &mut shapes);
}
}
}
flush(&mut run, &mut shapes);
}
}
if dropped {
self.dropped(n);
}
if shapes.is_empty() {
return;
}
self.out.commands.push(RenderCommand::ClipPush { rect, radius: 0.0 });
self.out.commands.extend(shapes);
self.out.commands.push(RenderCommand::ClipPop);
}
}

View file

@ -47,6 +47,7 @@ impl Theme {
("thing.control.border", 0x4a4a60ff),
("thing.control.accent", 0x7c9cffff),
("thing.control.text", 0xeeeef4ff),
("thing.control.disabled", 0x3a3a48ff),
("thing.plot.mark", 0x7c9cffff),
]
.into_iter()
@ -61,6 +62,7 @@ impl Theme {
("title", style(0xffffffff, 24.0, true)),
("body", style(0xeeeef4ff, 16.0, false)),
("thing.text", style(0xeeeef4ff, 16.0, false)),
("thing.text.placeholder", style(0x6e6e80ff, 16.0, false)),
]
.into_iter()
.map(|(name, style)| (name.to_string(), style))

View file

@ -1,5 +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
root 0 0 800 470
line 2 2 300 150
bar 2 160 300 150
area 2 318 300 150

View file

@ -4,4 +4,6 @@ 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
fill 2 20 48 1 r0 #2c2c3eff
stroke 2 20 48 1 r0 w1 #4a4a60ff
text 2 20 #eeeef4ff cells "Restart" bold=false italic=false underline=false

View file

@ -4,4 +4,6 @@ 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]
fill 2 50 398 16 r0 #2c2c3eff
stroke 2 50 398 16 r0 w1 #4a4a60ff
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

@ -1,2 +1,6 @@
surface thing:surface:provider.login.login viewport 800x600 scale 1 pixels
stroke 2 2 796 24 r0 w1 #4a4a60ff
text 4 4 #6e6e80ff font0 size16 [117@0,0 115@8,0 101@16,0 114@24,0 110@32,0 97@40,0 109@48,0 101@56,0]
fill 2 34 796 16 r0 #2c2c3eff
stroke 2 34 796 16 r0 w1 #4a4a60ff
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

@ -1,2 +1,3 @@
surface thing:surface:provider.muninn.input-target viewport 800x600 scale 1 pixels
image 82 3.125 636 357.75 "asset://provider.muninn/board.png" "The board the target sits on"
text 282 122 #eeeef4ff font0 size16 [82@0,0 101@8,0 97@16,0 100@24,0 121@32,0]

View file

@ -1 +1,9 @@
surface thing:surface:provider.settings.form viewport 800x600 scale 1 pixels
stroke 2 2 796 20 r0 w1 #4a4a60ff
fill 780 4 16 16 r0 #7c9cffff
fill 2 37.5 796 5 r0 #4a4a60ff
fill 778 30 20 20 r0 #7c9cffff
stroke 2 58 796 24 r0 w1 #4a4a60ff
text 4 60 #eeeef4ff font0 size16 [68@0,0 97@8,0 114@16,0 107@24,0]
stroke 2 90 796 24 r0 w1 #4a4a60ff
text 4 92 #eeeef4ff font0 size16 [56@0,0 48@8,0 56@16,0 48@24,0]

View file

@ -3,5 +3,9 @@ text 2 2 #eeeef4ff font0 size16 [84@0,0 104@8,0 101@16,0 32@24,0 97@32,0 114@40,
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]
fill 2 292 796 16 r0 #2c2c3eff
stroke 2 292 796 16 r0 w1 #4a4a60ff
text 2 292 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0]
fill 2 316 796 16 r0 #2c2c3eff
stroke 2 316 796 16 r0 w1 #4a4a60ff
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

@ -3,5 +3,9 @@ text 2 2 #eeeef4ff font0 size16 [84@0,0 104@8,0 101@16,0 32@24,0 97@32,0 114@40,
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]
fill 2 292 796 16 r0 #2c2c3eff
stroke 2 292 796 16 r0 w1 #4a4a60ff
text 2 292 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0]
fill 2 316 796 16 r0 #2c2c3eff
stroke 2 316 796 16 r0 w1 #4a4a60ff
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

@ -1 +1,14 @@
surface thing:surface:provider.market.plot viewport 800x600 scale 1 pixels
clip-push 2 2 300 150 r0
polyline w2 #7c9cffff 2,152 77,77 152,114.5 227,2 302,47
clip-pop
clip-push 2 160 300 150 r0
fill 2 253.75 60 56.25 r0 #7c9cffff
fill 62 206.875 60 103.125 r0 #7c9cffff
fill 122 230.3125 60 79.6875 r0 #7c9cffff
fill 182 160 60 150 r0 #7c9cffff
fill 242 188.125 60 121.875 r0 #7c9cffff
clip-pop
clip-push 2 318 300 150 r0
polygon #7c9cffff 2,168 5.030303,-19.5 8.060606,74.25 11.090909,-207 14.121212,-94.5 14.121212,393 2,393
clip-pop

View file

@ -1,8 +1,12 @@
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]
fill 4 72 792 16 r0 #2c2c3eff
stroke 4 72 792 16 r0 w1 #4a4a60ff
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]
fill 6 122 788 16 r0 #2c2c3eff
stroke 6 122 788 16 r0 w1 #4a4a60ff
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

@ -593,7 +593,10 @@ fn random_documents_render_without_panic_balanced_and_equal() {
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 refused = 0u32;
let (mut with_image, mut with_plot) = (0u32, 0u32);
const ROUNDS: u64 = 300;
for round in 0..ROUNDS {
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 {
@ -601,9 +604,29 @@ fn random_documents_render_without_panic_balanced_and_equal() {
let id = format!("n{counter}");
generated.push(id.clone());
let pick = next();
match (pick % 7, depth) {
match (pick % 13, 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 }),
(3, _) => Node::Toggle(ToggleNode { common: common(&id), checked: lit_bool(next() % 2 == 0), on_change: command("dismiss") }),
(4, _) => Node::Slider(SliderNode {
common: common(&id),
min: sizes[(next() % 10) as usize],
max: sizes[(next() % 10) as usize],
step: 1.0,
value: lit_number(sizes[(next() % 10) as usize]),
commit: command("dismiss"),
}),
(5, _) => image(&id, "x", [ImageFit::Fill, ImageFit::Contain, ImageFit::Cover, ImageFit::Unscaled][(next() % 4) as usize].clone()),
(6, _) => Node::Button(ButtonNode { common: common(&id), content: vec![], on_activate: command("dismiss"), enabled: lit_bool(next() % 2 == 0) }),
(7, _) => Node::TextInput(TextInputNode {
common: common(&id),
multiline: next() % 2 == 0,
input_kind: InputKind::Text,
placeholder: lit_text("type here"),
initial: lit_text(["", "typed words"][(next() % 2) as usize]),
submit: command("dismiss"),
}),
(8 | 9, _) => Node::Plot(PlotNode { common: common(&id), series: series_bind("s"), mark: [PlotMark::Line, PlotMark::Area, PlotMark::Bar][(next() % 3) as usize].clone(), x_min: None, x_max: None, y_min: None, y_max: None }),
(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();
@ -635,15 +658,39 @@ fn random_documents_render_without_panic_balanced_and_equal() {
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 };
// Every round binds an asset entry and a series (NaN and infinities among its values), so
// Image fit and Plot lowering run wherever the document holds them.
let mut state = MemState::new();
state.put(&ProviderId::new(PROVIDER), &catalog(&[("x", 50, 20)]));
let values: Vec<f64> = (0..2 + next() % 8)
.map(|_| match next() % 7 {
0 => f64::NAN,
1 => f64::INFINITY,
_ => (next() % 100) as f64 - 50.0,
})
.collect();
state.put_state(&ProviderId::new(PROVIDER), "s", &Series { values });
let Ok(tree) = bind(&mut state, &surface_of(root)) else {
refused += 1;
continue;
};
let Ok(laid) = layout(&tree, &frame, &mut measure(&frame)) else {
refused += 1;
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}");
with_image += first.commands.iter().any(|c| matches!(c, RenderCommand::Image { .. })) as u32;
with_plot += first.commands.iter().any(|c| matches!(c, RenderCommand::Polyline { .. } | RenderCommand::Polygon { .. })) as u32;
assert!(balanced(&first.commands), "round {round}");
assert_eq!(first.placed.len(), laid.nodes.len());
}
// A round that layout refuses renders nothing: keep them few enough that render is exercised.
eprintln!("random documents: {refused} of {ROUNDS} refused; {with_image} rendered an Image, {with_plot} a Polyline or Polygon");
assert!(with_image >= 20 && with_plot >= 20, "image {with_image}, plot {with_plot}");
assert!(refused * 20 <= ROUNDS as u32, "{refused} of {ROUNDS} rounds were refused");
}
#[test]
@ -683,3 +730,421 @@ fn a_scrollbar_is_one_cell_thick_in_cells_and_the_theme_thickness_in_pixels() {
let (_, device) = inline(pane(), &pixels(2.0), &ScrollOffsets::default());
assert_eq!(fills(&device).iter().map(|f| f.2).collect::<Vec<_>>(), [Theme::std().scrollbar]);
}
// ---- leaves ------------------------------------------------------------------------------
use thing_core::layout::Rect;
use thing_testkit::state::{Series, Swarm};
const PROVIDER: &str = "provider.render";
fn rect(x: f32, y: f32, w: f32, h: f32) -> Rect {
Rect { x, y, w, h }
}
fn color(token: &str) -> Rgba {
Theme::std().color(token).unwrap()
}
fn catalog(assets: &[(&str, i32, i32)]) -> AssetCatalog {
AssetCatalog {
provider_id: ProviderId::new(PROVIDER),
catalog_id: seg("icons"),
version: ver(1),
assets: assets
.iter()
.map(|(id, w, h)| AssetEntry { id: (*id).into(), media_type: "image/png".into(), uri: format!("asset://{id}"), width: count(*w), height: count(*h) })
.collect(),
}
}
fn image(id: &str, asset: &str, fit: ImageFit) -> Node {
Node::Image(ImageNode { common: common(id), catalog: "icons".into(), asset: asset.into(), fit, alt: lit_text("alt") })
}
fn with_state(state: &mut MemState, root: Node, frame: &LayoutFrame) -> Rendered {
let tree = bind(state, &surface_of(root)).expect("resolves");
draw(&tree, frame, &ScrollOffsets::default()).1
}
fn rendered(root: Node) -> Rendered {
with_state(&mut MemState::new(), root, &pixels(1.0))
}
fn series_bind(key: &str) -> Bind {
Bind {
source: StateSource::Record(StateRef { provider: Some(ProviderId::new(PROVIDER)), schema: SchemaId::new("gamecult.thing.test.series.v1"), key: RecordKey::new(key) }),
member: path(&["Values"]),
format: None,
}
}
fn plot_node(mark: PlotMark, bounds: [Option<f64>; 4]) -> Node {
Node::Plot(PlotNode { common: common("p"), series: series_bind("s"), mark, x_min: bounds[0], x_max: bounds[1], y_min: bounds[2], y_max: bounds[3] })
}
/// A plot over `values` in a root that is exactly the plot: its rect is (0, 0, 300, 150).
fn plotted(values: &[f64], mark: PlotMark, bounds: [Option<f64>; 4]) -> Rendered {
let mut state = MemState::new();
state.put_state(&ProviderId::new(PROVIDER), "s", &Series { values: values.to_vec() });
with_state(&mut state, flat("root", plain(), vec![plot_node(mark, bounds)]), &pixels(1.0))
}
fn polylines(rendered: &Rendered) -> Vec<Vec<(f32, f32)>> {
rendered.commands.iter().filter_map(|c| if let RenderCommand::Polyline { points, .. } = c { Some(points.clone()) } else { None }).collect()
}
fn invalid(rendered: &Rendered) -> Vec<&str> {
rendered.diagnostics.iter().filter(|d| d.code == Code::StyleValueInvalid).map(|d| d.detail.as_str()).collect()
}
fn lines_of(rendered: &Rendered) -> Vec<String> {
rendered
.commands
.iter()
.filter_map(|c| match c {
RenderCommand::Text { run: Run::Glyphs { glyphs, .. }, .. } => Some(glyphs.iter().filter_map(|g| char::from_u32(g.id)).collect()),
_ => None,
})
.collect()
}
fn fills_of(rendered: &Rendered, token: &str) -> Vec<Rect> {
let want = color(token);
rendered.commands.iter().filter_map(|c| if let RenderCommand::FillRect { rect, color, .. } = c { (*color == want).then_some(*rect) } else { None }).collect()
}
#[test]
fn fit_table() {
let provider = ProviderId::new(PROVIDER);
// A row 100 high stretches an image to 100 high and leaves it its extent's width, so the rect
// is the ratio of none of the assets: wide 400x100, tall 100x100, small 100x100.
let run = |asset: &str, fit: ImageFit, at: Rect| {
let mut state = MemState::new();
state.put(&provider, &catalog(&[("wide", 400, 200), ("tall", 100, 400), ("small", 40, 20)]));
let rendered = with_state(&mut state, flat("root", sized(100.0, 100.0), vec![image("pic", asset, fit)]), &pixels(1.0));
assert_eq!(placed(&rendered, "pic").rect, at, "{asset}: the image's rect");
rendered.commands
};
let wide = rect(0.0, 0.0, 400.0, 100.0);
let tall = rect(0.0, 0.0, 100.0, 100.0);
let small = rect(0.0, 0.0, 100.0, 100.0);
let img = |r: Rect, uri: &str| RenderCommand::Image { rect: r, uri: format!("asset://{uri}"), alt: "alt".into() };
let clip = |at: Rect, inner: RenderCommand| [RenderCommand::ClipPush { rect: at, radius: 0.0 }, inner, RenderCommand::ClipPop].to_vec();
for (asset, at) in [("wide", wide), ("tall", tall), ("small", small)] {
assert_eq!(run(asset, ImageFit::Fill, at), [img(at, asset)], "{asset}");
}
assert_eq!(run("wide", ImageFit::Contain, wide), [img(rect(100.0, 0.0, 200.0, 100.0), "wide")]);
assert_eq!(run("tall", ImageFit::Contain, tall), [img(rect(37.5, 0.0, 25.0, 100.0), "tall")]);
assert_eq!(run("small", ImageFit::Contain, small), [img(rect(0.0, 25.0, 100.0, 50.0), "small")]);
assert_eq!(run("wide", ImageFit::Cover, wide), clip(wide, img(rect(0.0, -50.0, 400.0, 200.0), "wide")));
assert_eq!(run("tall", ImageFit::Cover, tall), clip(tall, img(rect(0.0, -150.0, 100.0, 400.0), "tall")));
assert_eq!(run("small", ImageFit::Cover, small), clip(small, img(rect(-50.0, 0.0, 200.0, 100.0), "small")));
assert_eq!(run("wide", ImageFit::Unscaled, wide), clip(wide, img(rect(0.0, -50.0, 400.0, 200.0), "wide")));
assert_eq!(run("tall", ImageFit::Unscaled, tall), clip(tall, img(rect(0.0, -150.0, 100.0, 400.0), "tall")));
assert_eq!(run("small", ImageFit::Unscaled, small), clip(small, img(rect(30.0, 40.0, 40.0, 20.0), "small")));
}
#[test]
fn a_missing_asset_is_one_placeholder_and_no_image_command() {
let provider = ProviderId::new(PROVIDER);
let mut state = MemState::new();
// No catalog (Absent), an entry the catalog lacks (Error), and a 0x0 entry.
state.put(&provider, &catalog(&[("empty", 0, 0), ("sliver", 0, 10)]));
let mut root = vec![Node::Image(ImageNode { common: common("absent"), catalog: "nowhere".into(), asset: "x".into(), fit: ImageFit::Fill, alt: lit_text("alt") })];
for (id, asset) in [("lacks", "nothing"), ("empty", "empty")] {
root.push(image(id, asset, ImageFit::Contain));
}
let out = with_state(&mut state, flat("root", plain(), root), &pixels(1.0));
let none = rect(0.0, 0.0, 0.0, 0.0);
let placeholder = || {
[
RenderCommand::FillRect { rect: none, radius: 0.0, color: color("thing.placeholder") },
RenderCommand::StrokeRect { rect: none, radius: 0.0, width: 1.0, color: color("thing.error") },
]
};
let three: Vec<_> = (0..3).flat_map(|_| placeholder()).collect();
assert_eq!(out.commands, three, "no catalog (Absent), a missing entry (Error) and a 0x0 entry");
// One zero side is no extent either.
let out = with_state(&mut state, flat("root", plain(), vec![image("sliver", "sliver", ImageFit::Contain)]), &pixels(1.0));
assert!(!out.commands.iter().any(|c| matches!(c, RenderCommand::Image { .. })), "{:?}", out.commands);
// Where the placeholder has height but no width, the alt text has nowhere to go.
let mut state = MemState::new();
state.put(&provider, &catalog(&[("empty", 0, 0)]));
let out = with_state(&mut state, flat("root", sized(100.0, 40.0), vec![image("pic", "empty", ImageFit::Contain)]), &pixels(1.0));
assert_eq!(placed(&out, "pic").rect, rect(0.0, 0.0, 0.0, 40.0));
assert!(!out.commands.iter().any(|c| matches!(c, RenderCommand::Text { .. })), "{:?}", out.commands);
}
#[test]
fn a_nan_splits_a_line_and_a_one_point_run_draws_nothing() {
let split = plotted(&[1.0, 2.0, f64::NAN, 3.0, 4.0], PlotMark::Line, [None; 4]);
assert_eq!(
polylines(&split),
[vec![(0.0, 150.0), (75.0, 100.0)], vec![(225.0, 50.0), (300.0, 0.0)]],
"y grows down, so the least value is the bottom"
);
assert!(balanced(&split.commands));
let lone = plotted(&[1.0, f64::NAN, 2.0, f64::INFINITY, 3.0], PlotMark::Line, [None; 4]);
assert_eq!(lone.commands, []);
assert_eq!(invalid(&lone), ["series"], "dropped points are said once");
assert_eq!(plotted(&[], PlotMark::Line, [None; 4]).commands, []);
// Every point of one value: the equal ends widen by 1 and the line runs through the middle.
assert_eq!(polylines(&plotted(&[5.0, 5.0], PlotMark::Line, [None; 4])), [vec![(0.0, 75.0), (300.0, 75.0)]]);
}
#[test]
fn explicit_bounds_clip_and_a_bad_bound_takes_the_data_and_is_named() {
let clipped = plotted(&[1.0, 2.0, 3.0], PlotMark::Line, [None, None, Some(0.0), Some(2.0)]);
assert_eq!(polylines(&clipped), [vec![(0.0, 75.0), (150.0, 0.0), (300.0, -75.0)]]);
assert!(matches!(clipped.commands.first(), Some(RenderCommand::ClipPush { rect: r, .. }) if *r == rect(0.0, 0.0, 300.0, 150.0)));
assert!(matches!(clipped.commands.last(), Some(RenderCommand::ClipPop)));
assert_eq!(invalid(&clipped), Vec::<&str>::new());
let nan = plotted(&[1.0, 3.0], PlotMark::Line, [None, None, None, Some(f64::NAN)]);
assert_eq!(invalid(&nan), ["y_max"]);
assert_eq!(polylines(&nan), [vec![(0.0, 150.0), (300.0, 0.0)]], "the data's own max");
let nan_min = plotted(&[1.0, 3.0], PlotMark::Line, [Some(f64::NAN), None, Some(f64::NEG_INFINITY), None]);
assert_eq!(invalid(&nan_min), ["x_min", "y_min"]);
let crossed = plotted(&[1.0, 3.0], PlotMark::Line, [None, None, Some(9.0), Some(2.0)]);
assert_eq!(invalid(&crossed), ["y_min", "y_max"]);
assert_eq!(polylines(&crossed), [vec![(0.0, 150.0), (300.0, 0.0)]]);
let past = plotted(&[1.0, 3.0], PlotMark::Line, [Some(7.0), None, None, None]);
assert_eq!(invalid(&past), ["x_min"]);
}
#[test]
fn bars_rise_from_the_baseline_and_an_area_closes_to_it() {
let bars = plotted(&[2.0, -1.0, 4.0], PlotMark::Bar, [None; 4]);
let slots: Vec<_> = fills_of(&bars, "thing.plot.mark");
// y domain [-1, 4]: the baseline (0) is at y 120; slot width is 300 / 3.
assert_eq!(slots, [rect(0.0, 60.0, 100.0, 60.0), rect(100.0, 120.0, 100.0, 30.0), rect(200.0, 0.0, 100.0, 120.0)]);
assert!(balanced(&bars.commands));
let area = plotted(&[1.0, 2.0], PlotMark::Area, [None; 4]);
let polygons: Vec<_> = area.commands.iter().filter_map(|c| if let RenderCommand::Polygon { points, .. } = c { Some(points.clone()) } else { None }).collect();
// The baseline 0 clamps into the domain [1, 2]: the bottom.
assert_eq!(polygons, [vec![(0.0, 150.0), (300.0, 0.0), (300.0, 150.0), (0.0, 150.0)]]);
}
#[test]
fn a_plot_lowers_to_a_bounded_number_of_vertices() {
let mut seed = 0x2545_F491_4F6C_DD1Du64;
for round in 0..40 {
let n = 1 + round * 7;
let values: Vec<f64> = (0..n)
.map(|_| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
match seed % 5 {
0 => f64::NAN,
1 => f64::NEG_INFINITY,
_ => (seed % 1000) as f64 - 500.0,
}
})
.collect();
for (mark, bound) in [(PlotMark::Line, 1), (PlotMark::Area, 2), (PlotMark::Bar, 1)] {
let out = plotted(&values, mark, [None; 4]);
let vertices: usize = out
.commands
.iter()
.map(|c| match c {
RenderCommand::Polyline { points, .. } | RenderCommand::Polygon { points, .. } => points.len(),
RenderCommand::FillRect { .. } => 1,
_ => 0,
})
.sum();
assert!(vertices <= bound * n, "{n} points gave {vertices}");
assert!(balanced(&out.commands));
}
}
}
#[test]
fn a_plot_without_a_series_draws_nothing_and_a_refused_series_is_the_placeholder() {
let absent = rendered(flat("root", plain(), vec![plot_node(PlotMark::Line, [None; 4])]));
assert_eq!(absent.commands, []);
// The record is there but holds no Values: an Error site.
let mut state = MemState::new();
state.put_state(&ProviderId::new(PROVIDER), "s", &Swarm { id: "s".into(), name: "n".into(), load: 0.0 });
let mut node = plot_node(PlotMark::Line, [None; 4]);
if let Node::Plot(p) = &mut node {
if let StateSource::Record(r) = &mut p.series.source {
r.schema = SchemaId::new("gamecult.thing.test.swarm.v1");
}
}
let out = with_state(&mut state, flat("root", plain(), vec![node]), &pixels(1.0));
let whole = rect(0.0, 0.0, 300.0, 150.0);
assert_eq!(
out.commands,
[
RenderCommand::FillRect { rect: whole, radius: 0.0, color: color("thing.placeholder") },
RenderCommand::StrokeRect { rect: whole, radius: 0.0, width: 1.0, color: color("thing.error") },
]
);
}
#[test]
fn a_plot_is_sized_by_layout_to_the_default_object_size() {
let plot = || flat("root", plain(), vec![plot_node(PlotMark::Line, [None; 4])]);
let out = rendered(plot());
assert_eq!(placed(&out, "p").rect, rect(0.0, 0.0, 300.0, 150.0));
let scaled = with_state(&mut MemState::new(), plot(), &pixels(2.0));
assert_eq!(placed(&scaled, "p").rect, rect(0.0, 0.0, 300.0, 150.0), "logical, whatever the scale");
let cells = with_state(&mut MemState::new(), plot(), &frame(80.0, 30.0, 1.0, Metrics::Cells));
assert_eq!(placed(&cells, "p").rect, rect(0.0, 0.0, 38.0, 10.0));
}
fn knob(rendered: &Rendered) -> Rect {
*fills_of(rendered, "thing.control.accent").last().expect("a knob")
}
#[test]
fn a_toggle_knob_follows_checked_and_a_slider_thumb_is_clamped() {
let toggle = |checked: bool| {
let node = Node::Toggle(ToggleNode { common: common("t"), checked: lit_bool(checked), on_change: command("dismiss") });
rendered(flat("root", plain(), vec![node]))
};
// A 40x20 toggle inset by 2: a 16 knob at the left or at the right.
assert_eq!(knob(&toggle(false)), rect(2.0, 2.0, 16.0, 16.0));
assert_eq!(knob(&toggle(true)), rect(22.0, 2.0, 16.0, 16.0));
let slider = |min: f64, max: f64, value: f64| {
let node = Node::Slider(SliderNode { common: common("s"), min, max, step: 1.0, value: lit_number(value), commit: command("dismiss") });
rendered(flat("root", plain(), vec![node]))
};
// A 160x20 slider: the thumb is 20 wide and travels 140.
for (value, x) in [(5.0, 70.0), (-5.0, 0.0), (99.0, 140.0), (f64::NAN, 0.0)] {
let out = slider(0.0, 10.0, value);
assert_eq!(knob(&out), rect(x, 0.0, 20.0, 20.0), "value {value}");
assert_eq!(invalid(&out), Vec::<&str>::new());
}
for (min, max) in [(3.0, 3.0), (5.0, 1.0), (f64::NAN, 1.0), (0.0, f64::INFINITY)] {
let out = slider(min, max, 2.0);
assert_eq!(knob(&out).x, 0.0, "{min}..{max}: the thumb is at the start");
assert_eq!(invalid(&out), ["max"]);
assert_eq!(out.diagnostics.last().unwrap().node, Some(nid("s")));
}
}
#[test]
fn a_disabled_button_is_the_disabled_token_and_its_content_follows_the_chrome() {
let button = |enabled: bool| {
let node = Node::Button(ButtonNode { common: common("b"), content: vec![text("label", "Go")], on_activate: command("dismiss"), enabled: lit_bool(enabled) });
rendered(flat("root", plain(), vec![node]))
};
let on = button(true);
let off = button(false);
assert_eq!(fills_of(&on, "thing.control.fill").len(), 1);
assert_eq!(fills_of(&on, "thing.control.disabled").len(), 0);
assert_eq!(fills_of(&off, "thing.control.fill").len(), 0);
assert_eq!(fills_of(&off, "thing.control.disabled").len(), 1);
assert!(matches!(on.commands.as_slice(), [RenderCommand::FillRect { .. }, RenderCommand::StrokeRect { .. }, RenderCommand::Text { .. }]));
}
#[test]
fn a_placeholder_shows_only_while_the_input_is_empty_and_a_select_shows_its_label() {
let input = |initial: &str| {
let node = Node::TextInput(TextInputNode {
common: common("i"),
multiline: false,
input_kind: InputKind::Text,
placeholder: lit_text("type"),
initial: lit_text(initial),
submit: command("dismiss"),
});
rendered(flat("root", plain(), vec![node]))
};
let text_color = |r: &Rendered| match r.commands.iter().find(|c| matches!(c, RenderCommand::Text { .. })) {
Some(RenderCommand::Text { color, .. }) => color.clone(),
_ => panic!("no text"),
};
let empty = input("");
assert_eq!(lines_of(&empty), ["type"]);
assert_eq!(text_color(&empty), color("thing.placeholder"));
let filled = input("hi");
assert_eq!(lines_of(&filled), ["hi"]);
assert_eq!(text_color(&filled), color("thing.control.text"));
let select = |value: &str| {
let mut state = MemState::new();
state.put_state(&ProviderId::new(PROVIDER), "row", &Swarm { id: "row".into(), name: value.into(), load: 0.0 });
let options = OptionList::Literal(LiteralOptions {
options: vec![SelectOption { value: "a".into(), label: "Alpha".into() }, SelectOption { value: "b".into(), label: "Beta".into() }],
});
let value = Bind {
source: StateSource::Record(StateRef { provider: Some(ProviderId::new(PROVIDER)), schema: SchemaId::new("gamecult.thing.test.swarm.v1"), key: RecordKey::new("row") }),
member: path(&["Name"]),
format: None,
};
let node = Node::Select(SelectNode { common: common("sel"), options, value, on_change: command("dismiss") });
with_state(&mut state, flat("root", plain(), vec![node]), &pixels(1.0))
};
assert_eq!(lines_of(&select("b")), ["Beta"]);
assert_eq!(lines_of(&select("zzz")), ["zzz"], "the value itself when no option matches");
}
fn finite(rendered: &Rendered) -> bool {
rendered.commands.iter().all(|c| match c {
RenderCommand::Polyline { points, .. } | RenderCommand::Polygon { points, .. } => points.iter().all(|p| p.0.is_finite() && p.1.is_finite()),
RenderCommand::FillRect { rect, .. } | RenderCommand::ClipPush { rect, .. } => [rect.x, rect.y, rect.w, rect.h].iter().all(|v| v.is_finite()),
_ => true,
})
}
#[test]
fn every_emitted_plot_coordinate_is_a_finite_f32() {
let hostile = [f64::NAN, f64::INFINITY, 1e308, -1e308, 0.0, 1.0, 2.5, f64::NEG_INFINITY];
for mark in [PlotMark::Line, PlotMark::Area, PlotMark::Bar] {
let bounds = [
[None, None, None, Some(1e-300)],
[None, None, Some(-1e300), Some(1e300)],
[None, None, Some(-1.7e308), Some(1.7e308)],
[None, Some(1e-300), None, None],
[Some(-1e300), Some(1e300), None, None],
[None; 4],
];
for bound in bounds {
for values in [&hostile[..], &[0.0, 1.0], &[1e38, -1e38, 3e38], &[1.0, 2.0]] {
let out = plotted(values, mark.clone(), bound);
assert!(finite(&out), "{mark:?} {bound:?} {values:?}: {:?}", out.commands);
assert!(balanced(&out.commands));
assert!(invalid(&out).iter().filter(|d| **d == "series").count() <= 1, "said at most once");
}
}
}
// A span of 1e-300: one point sits on the axis, the other cannot be placed, and that is said once.
let tiny = plotted(&[0.0, 1.0], PlotMark::Line, [None, None, None, Some(1e-300)]);
assert_eq!(tiny.commands, []);
assert_eq!(invalid(&tiny), ["series"]);
assert_eq!(tiny.diagnostics.last().unwrap().node, Some(nid("p")));
// A range of 1e300 either side: every point is placeable (mid-height) and nothing is dropped.
let wide = plotted(&[1.0, 2.0], PlotMark::Line, [None, None, Some(-1e300), Some(1e300)]);
assert_eq!(polylines(&wide), [vec![(0.0, 75.0), (300.0, 75.0)]]);
assert_eq!(invalid(&wide), Vec::<&str>::new());
}
#[test]
fn a_polyline_is_one_cell_wide_in_cells_and_two_px_in_pixels() {
let width = |frame: &LayoutFrame| {
let mut state = MemState::new();
state.put_state(&ProviderId::new(PROVIDER), "s", &Series { values: vec![1.0, 2.0] });
let out = with_state(&mut state, flat("root", plain(), vec![plot_node(PlotMark::Line, [None; 4])]), frame);
out.commands.iter().find_map(|c| if let RenderCommand::Polyline { width, .. } = c { Some(*width) } else { None }).expect("a polyline")
};
assert_eq!(width(&pixels(1.0)), 2.0);
assert_eq!(width(&frame(80.0, 30.0, 1.0, Metrics::Cells)), 1.0);
}
#[test]
fn the_alt_line_of_a_placeholder_draws_only_when_it_fits() {
let provider = ProviderId::new(PROVIDER);
let in_grid = |height: f64| {
let mut state = MemState::new();
// A 100x0 entry is no extent and an invalid measure, so a row stretches it to the row's height.
state.put(&provider, &catalog(&[("flat", 100, 0)]));
let out = with_state(&mut state, flat("root", sized(100.0, height), vec![image("pic", "flat", ImageFit::Contain)]), &pixels(1.0));
assert_eq!(placed(&out, "pic").rect, rect(0.0, 0.0, 100.0, height as f32));
out
};
assert_eq!(lines_of(&in_grid(40.0)), ["alt"]);
assert_eq!(lines_of(&in_grid(10.0)), Vec::<String>::new(), "a 16 high line does not fit 10");
}

View file

@ -5,7 +5,7 @@ use thing_core::bind::Bound;
use thing_core::layout::{Avail, CellStyle, Constraint, FontId, Glyph, Leaf, Measure, Run, TextLayout, TextLine, TextRequest};
/// 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 bound catalog entry's extent (0x0 when missing); a Plot is 0x0.
/// have fixed sizes; an Image is its bound catalog entry's extent (0x0 when missing).
pub struct FixedMeasure {
cells: bool,
}
@ -107,7 +107,6 @@ impl Measure for FixedMeasure {
};
if self.cells { (w / 8.0, (h / 16.0).ceil()) } else { (w, h) }
}
Leaf::Plot { .. } => (0.0, 0.0),
}
}
}