diff --git a/crates/thing-core/src/layout/measure.rs b/crates/thing-core/src/layout/measure.rs index b6655e5..f35752e 100644 --- a/crates/thing-core/src/layout/measure.rs +++ b/crates/thing-core/src/layout/measure.rs @@ -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 } diff --git a/crates/thing-core/src/layout/tree.rs b/crates/thing-core/src/layout/tree.rs index c735065..a5f049f 100644 --- a/crates/thing-core/src/layout/tree.rs +++ b/crates/thing-core/src/layout/tree.rs @@ -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); } } }) diff --git a/crates/thing-core/src/render/leaf.rs b/crates/thing-core/src/render/leaf.rs new file mode 100644 index 0000000..a088976 --- /dev/null +++ b/crates/thing-core/src/render/leaf.rs @@ -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 { + 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, 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() { + 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); + } + } +} diff --git a/crates/thing-core/src/render/mod.rs b/crates/thing-core/src/render/mod.rs index 10bfdef..d331c40 100644 --- a/crates/thing-core/src/render/mod.rs +++ b/crates/thing-core/src/render/mod.rs @@ -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; @@ -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(_) => {} } } diff --git a/crates/thing-core/src/render/plot.rs b/crates/thing-core/src/render/plot.rs new file mode 100644 index 0000000..dcad73c --- /dev/null +++ b/crates/thing-core/src/render/plot.rs @@ -0,0 +1,147 @@ +//! 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 point is skipped, 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, Option), 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 { + fn at(&self, i: usize, v: f64) -> Option<(f32, f32)> { + let tx = (i as f64 - self.x.0) / (self.x.1 - self.x.0); + let ty = self.value(v); + let point = (self.rect.x as f64 + tx * self.rect.w as f64, ty); + (point.0.is_finite() && point.1.is_finite()).then_some((point.0 as f32, point.1 as f32)) + } + + fn value(&self, v: f64) -> f64 { + let t = (v - self.y.0) / (self.y.1 - self.y.0); + self.rect.y as f64 + self.rect.h as f64 - t * self.rect.h as f64 + } +} + +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), + _ => {} + } + } + + 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.is_finite() { + return; + } + let mut shapes = Vec::new(); + match n.mark { + PlotMark::Bar => { + let slot = rect.w / values.len() as f32; + for (i, v) in values.iter().enumerate().filter(|(_, v)| v.is_finite()) { + let top = frame.value(*v); + let (y0, y1) = (top.min(base) as f32, top.max(base) as f32); + if y0.is_finite() && y1.is_finite() { + let rect = Rect { x: rect.x + slot * i as f32, y: y0, w: slot, h: y1 - y0 }; + shapes.push(RenderCommand::FillRect { rect, radius: 0.0, color: color.clone() }); + } + } + } + PlotMark::Line | PlotMark::Area => { + let mut run: Vec<(f32, f32)> = Vec::new(); + let mut flush = |run: &mut Vec<(f32, f32)>, shapes: &mut Vec| { + 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 => flush(&mut run, &mut shapes), + } + } + flush(&mut run, &mut shapes); + } + } + 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); + } +} diff --git a/crates/thing-core/src/theme.rs b/crates/thing-core/src/theme.rs index 77cd498..513e5ef 100644 --- a/crates/thing-core/src/theme.rs +++ b/crates/thing-core/src/theme.rs @@ -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)) diff --git a/crates/thing-testkit/src/measure.rs b/crates/thing-testkit/src/measure.rs index 3d77b40..2570a1e 100644 --- a/crates/thing-testkit/src/measure.rs +++ b/crates/thing-testkit/src/measure.rs @@ -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), } } }