diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml new file mode 100644 index 0000000..23ae62b --- /dev/null +++ b/.cargo/mutants.toml @@ -0,0 +1 @@ +test_workspace = true diff --git a/crates/thing-core/src/frame.rs b/crates/thing-core/src/frame.rs index 8584278..f8c6d0b 100644 --- a/crates/thing-core/src/frame.rs +++ b/crates/thing-core/src/frame.rs @@ -10,10 +10,10 @@ use std::collections::HashSet; use crate::bind::Binder; use crate::command::{Activation, Commands, Confirming, HostEffect, Resume}; use crate::diagnostic::{Code, Diagnostic}; -use crate::input::{Drafts, InputEvent}; +use crate::input::{Drafts, Input, InputEvent, Owners, Seen}; use crate::layout::{LaidTree, LayoutError, LayoutFrame, Measure, Metrics, layout}; use crate::port::{Address, Change, IdSource, Interest, Ledger, Lookup, StatePort}; -use crate::render::{RenderCommand, RenderInput, Rendered, ScrollOffsets, render}; +use crate::render::{RenderCommand, RenderInput, Rendered, ScrollOffsets, Session, render}; use crate::resolve::{Limits, Resolver}; use crate::theme::Theme; use crate::time::Timestamp; @@ -81,6 +81,8 @@ pub struct Core { theme: Theme, commands: Commands, drafts: Drafts, + /// The pointer's press in progress. + input: Input, /// What activations said since the last frame; the frame's diagnostics carry it out. notes: Vec, /// Resumes whose surface had not bound when the host handed them over; each runs at that surface's @@ -105,6 +107,7 @@ impl Core { theme: Theme::std(), commands: Commands::new(config.client, config.invocation_timeout_ms), drafts: Drafts::new(), + input: Input::new(), notes: Vec::new(), held: Vec::new(), wanted: None, @@ -119,8 +122,7 @@ impl Core { } pub fn frame(&mut self, input: FrameInput, ports: Ports<'_>) -> FrameOutput { - // Input routes only to owners that exist; none does yet, so events change nothing. - let FrameInput { now, viewport, scale, events: _ } = input; + let FrameInput { now, viewport, scale, events } = input; let port = ports.state; let mut changes = Vec::new(); if self.wanted != self.shown { @@ -165,6 +167,9 @@ impl Core { None => self.held.push(resume), } } + // Pointer events act on what the user saw: the last good frame, before this frame's state is + // laid out, each in the order the host saw it. Keys, text and focus change nothing yet. + diagnostics.extend(self.route(&events, scale, now, ports.ids, port)); // Results of this frame are applied above, before the deadline is judged: a late result that was // already queued wins over the timeout. diagnostics.extend(self.commands.tick(now, port, &mut self.ledger)); @@ -218,6 +223,19 @@ impl Core { self.notes.extend(said); } + fn route(&mut self, events: &[InputEvent], scale: f32, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort) -> Vec { + let mut said = Vec::new(); + let (Some(shown), Some((laid, rendered))) = (&self.shown, &self.last) else { return said }; + let Some(tree) = self.binder.tree(shown.key.as_str()) else { return said }; + let line = self.theme.text.get("body").or_else(|| self.theme.text.get("thing.text")).map_or(16.0, |style| style.size); + let seen = Seen { rendered, laid, tree, metrics: self.metrics, scale, line }; + let mut owners = Owners { commands: &mut self.commands, drafts: &mut self.drafts, scroll: &mut self.scroll, ids, port, ledger: &mut self.ledger }; + for event in events { + said.extend(self.input.event(event, &seen, &mut owners, now)); + } + said + } + /// Drop the drafts of nodes the shown surface no longer has. fn retain_drafts(&mut self) { let Some(shown) = &self.shown else { return }; @@ -243,6 +261,7 @@ impl Core { } } if let Some(old) = self.shown.take() { + self.input.cancel(old.key.as_str(), &mut self.drafts); self.resolver.forget(old.key.as_str(), port, &mut self.ledger); self.binder.forget(old.key.as_str(), port, &mut self.ledger); self.commands.forget(old.key.as_str(), port, &mut self.ledger); @@ -262,15 +281,20 @@ impl Core { } fn draw(&mut self, viewport: (f32, f32), scale: f32, diagnostics: &mut Vec) -> Vec { - let tree = self.shown.as_ref().and_then(|address| self.binder.tree(address.key.as_str())); - let Some(tree) = tree else { + let Some(address) = &self.shown else { + self.last = None; + return Vec::new(); + }; + let Some(tree) = self.binder.tree(address.key.as_str()) else { self.last = None; return Vec::new(); }; let frame = LayoutFrame { viewport, scale, metrics: self.metrics }; match layout(tree, &frame, self.measure.as_mut()) { Ok(laid) => { - let input = RenderInput { scale, metrics: self.metrics, viewport, scroll: &self.scroll, theme: &self.theme }; + let states = self.commands.view(address.key.as_str()); + let session = Session::new(&self.drafts, &states); + let input = RenderInput { scale, metrics: self.metrics, viewport, scroll: &self.scroll, theme: &self.theme, session }; let rendered = render(tree, &laid, &input, self.measure.as_mut()); diagnostics.extend(rendered.diagnostics.iter().cloned()); let commands = rendered.commands.clone(); diff --git a/crates/thing-core/src/input/drafts.rs b/crates/thing-core/src/input/drafts.rs index 887943a..e1a618d 100644 --- a/crates/thing-core/src/input/drafts.rs +++ b/crates/thing-core/src/input/drafts.rs @@ -2,10 +2,13 @@ //! A value enters when the user changes an input and leaves when a result clears it or a republish //! removes its node. Nothing else in core, and no host, keeps a second copy. +use std::borrow::Cow; use std::collections::{HashMap, HashSet}; use thing_contract::{InputValue, NodeId}; +use crate::bind::{Bound, BoundTree, Field}; + #[derive(Clone, Debug, Default, PartialEq)] pub struct Drafts { values: HashMap<(String, NodeId), InputValue>, @@ -24,6 +27,15 @@ impl Drafts { self.values.get(&(surface.to_string(), node.clone())) } + /// Put `node`'s draft back to what it was before a press wrote it: `None` leaves it with none. + pub fn restore(&mut self, surface: &str, node: &NodeId, prior: Option) { + let key = (surface.to_string(), node.clone()); + match prior { + Some(value) => self.values.insert(key, value), + None => self.values.remove(&key), + }; + } + /// Drop each draft in `held` that the table still holds with that value. A draft edited since it /// was held is newer than what was sent, and stays; a node with no draft is untouched. pub fn clear_held(&mut self, surface: &str, held: &[(NodeId, InputValue)]) { @@ -49,3 +61,22 @@ impl Drafts { self.values.is_empty() } } + +/// What a node's site currently shows: the draft over the bound value. The one place that rule is +/// written, read by render (through its `Session`) and by pointer input (a Toggle flips what is shown). +/// Only a draft of the site's own kind counts: a Number draft in a TextInput shows as its number. +pub fn current<'a>(tree: &'a BoundTree, drafts: Option<&'a Drafts>, node: &NodeId, field: Field) -> Option> { + let draft = drafts.and_then(|drafts| drafts.get(&tree.resolved().document().record_key(), node)); + let shown = match (field, draft) { + (Field::Checked, Some(InputValue::Bool(held))) => Some(Bound::Bool(held.value)), + (Field::Value, Some(InputValue::Number(held))) => Some(Bound::Number(held.value)), + (Field::Selected, Some(InputValue::Choice(held))) => Some(Bound::Text(held.value.clone())), + (Field::Initial, Some(InputValue::Text(held))) => Some(Bound::Text(held.value.clone())), + (Field::Initial, Some(InputValue::Number(held))) => Some(Bound::Text(held.value.to_string())), + _ => None, + }; + match shown { + Some(bound) => Some(Cow::Owned(bound)), + None => tree.value(node, field).map(Cow::Borrowed), + } +} diff --git a/crates/thing-core/src/input/hit.rs b/crates/thing-core/src/input/hit.rs new file mode 100644 index 0000000..11f60fe --- /dev/null +++ b/crates/thing-core/src/input/hit.rs @@ -0,0 +1,111 @@ +//! Hit-testing: which node a point reaches, read from the geometry render placed and nothing else. +//! The point is in the space `Placed` is in (logical px, or cells), so this file applies no scale, +//! scroll or clip of its own: render already did, and `Placed::visible` is what the user could see. +//! Paint order is the only layer order: the last placed node under the point wins, overlays are last, +//! and a modal overlay shuts out everything painted before it. + +use std::collections::HashMap; + +use thing_contract::{Node, NodeId}; + +use crate::layout::{LaidTree, Rect}; +use crate::render::Rendered; + +/// What the topmost thing under a point is: a node, or a modal overlay's scrim (the viewport +/// beyond everything the modal holds). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HitKind { + Node, + Scrim, +} + +/// The topmost thing under a point. For a `Scrim` the node is the modal overlay. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Hit { + pub node: NodeId, + pub kind: HitKind, +} + +/// What a press can activate: a control, or a modal's scrim (its dismissal). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Control { + Button, + Toggle, + Slider, + Select, + TextInput, + Scrim, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Target { + pub node: NodeId, + pub control: Control, +} + +/// Where a point lands before any node is asked what it takes: the topmost node under it, or the +/// modal overlay (by laid index) when the point reaches nothing inside it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Reach { + Node(usize), + Scrim(usize), +} + +/// Half-open: a node's right and bottom edges belong to its neighbour. +fn covers(rect: Rect, (x, y): (f32, f32)) -> bool { + x >= rect.x && x < rect.x + rect.w && y >= rect.y && y < rect.y + rect.h +} + +pub(super) fn reach(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32)) -> Option { + // The last modal overlay root in paint order: nothing painted before it is reachable, and what + // is painted after it (its own subtree, then any later overlay) is. + let modal = laid + .nodes + .iter() + .rposition(|node| node.parent.is_none() && matches!(index.get(&node.id), Some(Node::Overlay(overlay)) if overlay.modal)); + let floor = modal.map_or(0, |m| m + 1); + let top = rendered.placed.iter().enumerate().skip(floor).rev().find(|(_, placed)| placed.visible.is_some_and(|seen| covers(seen, point))); + match (top, modal) { + (Some((i, _)), _) => Some(Reach::Node(i)), + (None, Some(m)) => Some(Reach::Scrim(m)), + (None, None) => None, + } +} + +/// The topmost node drawn at `point` (a modal's scrim when nothing in the modal is there), read +/// from the last good frame: what the user saw when they pressed. +pub fn hit_test(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32)) -> Option { + Some(match reach(rendered, laid, index, point)? { + Reach::Scrim(m) => Hit { node: laid.nodes[m].id.clone(), kind: HitKind::Scrim }, + Reach::Node(i) => Hit { node: laid.nodes[i].id.clone(), kind: HitKind::Node }, + }) +} + +fn control_of(node: &Node) -> Option { + match node { + Node::Button(_) => Some(Control::Button), + Node::Toggle(_) => Some(Control::Toggle), + Node::Slider(_) => Some(Control::Slider), + Node::Select(_) => Some(Control::Select), + Node::TextInput(_) => Some(Control::TextInput), + _ => None, + } +} + +/// The node `point` activates: the nearest activatable node at or above the topmost one under it +/// (a Button's label hits the Button), or a modal's scrim. A point on a Box, on text outside a +/// control or on a non-modal overlay's root targets nothing. +pub fn target(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32)) -> Option { + let mut at = match reach(rendered, laid, index, point)? { + Reach::Scrim(m) => return Some(Target { node: laid.nodes[m].id.clone(), control: Control::Scrim }), + Reach::Node(i) => Some(i), + }; + while let Some(i) = at { + let laid_node = laid.nodes.get(i)?; + if let Some(control) = index.get(&laid_node.id).copied().and_then(control_of) { + return Some(Target { node: laid_node.id.clone(), control }); + } + at = laid_node.parent.map(|parent| parent as usize); + } + None +} diff --git a/crates/thing-core/src/input/mod.rs b/crates/thing-core/src/input/mod.rs index c363949..3cbdf59 100644 --- a/crates/thing-core/src/input/mod.rs +++ b/crates/thing-core/src/input/mod.rs @@ -1,8 +1,14 @@ -//! What a host tells core about its user: the closed `InputEvent` vocabulary, and the `Drafts` -//! table that owns what the user has typed or chosen and not yet sent. +//! What a host tells core about its user: the closed `InputEvent` vocabulary, the `Drafts` table +//! that owns what the user has typed or chosen and not yet sent, hit-testing against the frame the +//! user saw, and the pointer routes that turn a press, a drag or a wheel into an activation, a draft +//! or a scroll offset. pub mod drafts; pub mod event; +pub mod hit; +pub mod pointer; -pub use drafts::Drafts; +pub use drafts::{Drafts, current}; pub use event::{InputEvent, Key, Modifiers, PointerButton, WheelUnit}; +pub use hit::{Control, Hit, HitKind, Target, hit_test, target}; +pub use pointer::{Input, Owners, Pointer, Seen}; diff --git a/crates/thing-core/src/input/pointer.rs b/crates/thing-core/src/input/pointer.rs new file mode 100644 index 0000000..6783d43 --- /dev/null +++ b/crates/thing-core/src/input/pointer.rs @@ -0,0 +1,191 @@ +//! Pointer input: press state and the routes from a pointer event to the one activation primitive, +//! to `Drafts` (a Slider drag) and to `ScrollOffsets` (the wheel). Input decides which node an +//! event reaches and nothing about what a command does: every commit ends in `Commands::activate`. + +use thing_contract::{BoolValue, InputValue, Node, NodeId, NumberValue, SliderNode}; + +use super::drafts::{Drafts, current}; +use super::event::{InputEvent, PointerButton, WheelUnit}; +use super::hit::{Control, Reach, Target, reach, target}; +use crate::bind::{Bound, BoundTree, Field}; +use crate::command::{Activation, ActivationKind, Commands}; +use crate::diagnostic::Diagnostic; +use crate::layout::{LaidTree, Metrics, Rect}; +use crate::port::{IdSource, Ledger, StatePort}; +use crate::render::{Rendered, ScrollOffsets, clamp}; +use crate::time::Timestamp; + +/// The last good frame and how it was drawn: what every event is judged against. +pub struct Seen<'a> { + pub rendered: &'a Rendered, + pub laid: &'a LaidTree, + pub tree: &'a BoundTree, + pub metrics: Metrics, + /// Device px per logical px (Pixels), which turns a wheel's logical units into the device px + /// scroll offsets are held in. + pub scale: f32, + /// The theme's body text size in logical px: what one wheel line is in Pixels. A guess, unmeasured. + pub line: f32, +} + +/// The owners an event writes through: activation, drafts and scroll positions. +pub struct Owners<'a> { + pub commands: &'a mut Commands, + pub drafts: &'a mut Drafts, + pub scroll: &'a mut ScrollOffsets, + pub ids: &'a mut dyn IdSource, + pub port: &'a mut dyn StatePort, + pub ledger: &'a mut Ledger, +} + +/// The one press in progress. A Slider's press also holds the draft it replaced, so a cancel can put it back. +#[derive(Clone, Debug, PartialEq)] +enum Press { + Target(Target), + Drag { node: NodeId, prior: Option }, +} + +/// The owner of press state. No node holds a pressed or hover flag. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Pointer { + press: Option, +} + +/// The routes every pointer and wheel event takes; it owns the `Pointer`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Input { + pointer: Pointer, +} + +/// The value a press at `x` on a Slider's track `rect` chooses: along `[min, max]`, snapped to `step` +/// from `min`, held in range. None when the slider has no usable range or track. +fn slider_value(slider: &SliderNode, rect: Rect, x: f32) -> Option { + if !(slider.min.is_finite() && slider.max.is_finite() && slider.min < slider.max && rect.w > 0.0 && x.is_finite()) { + return None; + } + let along = f64::from((x - rect.x) / rect.w); + let raw = slider.min + along * (slider.max - slider.min); + let snapped = if slider.step.is_finite() && slider.step > 0.0 { slider.min + ((raw - slider.min) / slider.step).round() * slider.step } else { raw }; + Some(snapped.clamp(slider.min, slider.max)) +} + +fn placed_rect(rendered: &Rendered, node: &NodeId) -> Option { + rendered.placed.iter().find(|placed| &placed.id == node).map(|placed| placed.rect) +} + +impl Input { + pub fn new() -> Self { + Self::default() + } + + /// Drop the press in progress, as the platform taking the pointer does, and as leaving the + /// surface does: a Slider draft the press wrote goes back to what it was. + pub fn cancel(&mut self, surface: &str, drafts: &mut Drafts) { + if let Some(Press::Drag { node, prior }) = self.pointer.press.take() { + drafts.restore(surface, &node, prior); + } + } + + /// Route one event. Keys, text, composition and the window gaining or losing the user are not pointer input and change nothing, + /// and only the primary button presses. The diagnostics are the activations' refusals. + pub fn event(&mut self, event: &InputEvent, seen: &Seen<'_>, owners: &mut Owners<'_>, now: Timestamp) -> Vec { + let surface = seen.tree.resolved().document().record_key(); + match event { + InputEvent::PointerDown { at, button: PointerButton::Primary, .. } => self.down(*at, seen, owners, &surface), + InputEvent::PointerMove { at, .. } => self.drag(*at, seen, owners.drafts, &surface), + InputEvent::PointerUp { at, button: PointerButton::Primary, .. } => return self.up(*at, seen, owners, now, &surface), + InputEvent::PointerCancel => self.cancel(&surface, owners.drafts), + InputEvent::Wheel { at, delta, unit, .. } => wheel(*at, *delta, *unit, seen, owners.scroll), + _ => {} + } + Vec::new() + } + + fn down(&mut self, at: (f32, f32), seen: &Seen<'_>, owners: &mut Owners<'_>, surface: &str) { + // A press never starts over another: the one in progress ends first. + self.cancel(surface, owners.drafts); + let index = seen.tree.index(); + self.pointer.press = target(seen.rendered, seen.laid, &index, at).and_then(|hit| match (hit.control, index.get(&hit.node)) { + (Control::Slider, Some(Node::Slider(slider))) => { + let value = placed_rect(seen.rendered, &hit.node).and_then(|rect| slider_value(slider, rect, at.0))?; + let prior = owners.drafts.get(surface, &hit.node).cloned(); + owners.drafts.set(surface, &hit.node, InputValue::Number(NumberValue { value })); + Some(Press::Drag { node: hit.node, prior }) + } + // A press on a Select or a TextInput does nothing yet: the chooser and text editing are not here. + (Control::Select | Control::TextInput, _) => None, + _ => Some(Press::Target(hit)), + }); + } + + fn drag(&mut self, at: (f32, f32), seen: &Seen<'_>, drafts: &mut Drafts, surface: &str) { + let Some(Press::Drag { node, .. }) = &self.pointer.press else { return }; + let index = seen.tree.index(); + let Some(Node::Slider(slider)) = index.get(node) else { return }; + if let Some(value) = placed_rect(seen.rendered, node).and_then(|rect| slider_value(slider, rect, at.0)) { + drafts.set(surface, node, InputValue::Number(NumberValue { value })); + } + } + + fn up(&mut self, at: (f32, f32), seen: &Seen<'_>, owners: &mut Owners<'_>, now: Timestamp, surface: &str) -> Vec { + let activation = match self.pointer.press.take() { + None => return Vec::new(), + // A drag commits the draft it wrote, wherever the pointer is let go. + Some(Press::Drag { node, .. }) => match owners.drafts.get(surface, &node) { + Some(value) => Activation { node, kind: ActivationKind::Change(value.clone()) }, + None => return Vec::new(), + }, + Some(Press::Target(pressed)) => { + if target(seen.rendered, seen.laid, &seen.tree.index(), at).as_ref() != Some(&pressed) { + return Vec::new(); + } + match pressed.control { + Control::Button | Control::Scrim => Activation { node: pressed.node, kind: ActivationKind::Press }, + Control::Toggle => { + let shown = current(seen.tree, Some(owners.drafts), &pressed.node, Field::Checked); + let checked = matches!(shown.as_deref(), Some(Bound::Bool(true))); + Activation { node: pressed.node, kind: ActivationKind::Change(InputValue::Bool(BoolValue { value: !checked })) } + } + Control::Slider | Control::Select | Control::TextInput => return Vec::new(), + } + } + }; + owners.commands.activate(activation, seen.tree, owners.drafts, now, owners.ids, owners.port, owners.ledger) + } +} + +/// The wheel moves the nearest scroll node at or above what it is over, on the wheel's axis, that +/// has room to move that way; at the end of its travel the next scroll ancestor takes it. Under a +/// modal only the modal's own subtree is reachable. Offsets are held in device px (Pixels) or cells. +fn wheel(at: (f32, f32), delta: (f32, f32), unit: WheelUnit, seen: &Seen<'_>, scroll: &mut ScrollOffsets) { + let index = seen.tree.index(); + let Some(Reach::Node(start) | Reach::Scrim(start)) = reach(seen.rendered, seen.laid, &index, at) else { return }; + let (to_device, line) = match seen.metrics { + Metrics::Cells => (1.0, 1.0), + Metrics::Pixels => (if seen.scale.is_finite() && seen.scale > 0.0 { seen.scale } else { 1.0 }, seen.line), + }; + let per = match unit { + WheelUnit::Units => to_device, + WheelUnit::Lines => line * to_device, + }; + for axis in [0usize, 1] { + let amount = [delta.0, delta.1][axis] * per; + if !amount.is_finite() || amount == 0.0 { + continue; + } + let mut over = Some(start); + while let Some(i) = over { + let node = &seen.laid.nodes[i]; + if let Some(max) = node.max_scroll { + let held = scroll.of(node); + let want = if axis == 0 { (held.0 + amount, held.1) } else { (held.0, held.1 + amount) }; + let next = clamp(want, max); + if next != held { + scroll.set(node.id.clone(), next); + break; + } + } + over = node.parent.map(|parent| parent as usize); + } + } +} diff --git a/crates/thing-core/src/render/leaf.rs b/crates/thing-core/src/render/leaf.rs index 5006af8..59eb34a 100644 --- a/crates/thing-core/src/render/leaf.rs +++ b/crates/thing-core/src/render/leaf.rs @@ -2,12 +2,15 @@ //! 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 std::borrow::Cow; + 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::input::drafts::current; use crate::layout::{ControlForm, LaidControl, Measure, Metrics, Rect, TextRequest}; /// Where an Image lands inside `rect` for an extent of `(w, h)` asset px (1 asset px = 1 logical @@ -25,17 +28,21 @@ fn fitted(fit: &ImageFit, rect: Rect, (w, h): (f32, f32)) -> (Rect, bool) { } impl<'a> Painter<'a> { + /// What the site shows: its draft over its bound value, the one read every control makes. + fn shown(&self, id: &NodeId, field: Field) -> Option> { + current(self.tree, self.input.session.drafts, id, field) + } + fn flag(&self, id: &NodeId, field: Field) -> Option { - match self.tree.value(id, field) { + match self.shown(id, field).as_deref() { 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()), + fn shown_text(&self, id: &NodeId, field: Field) -> Option { + match self.shown(id, field).as_deref() { + Some(Bound::Text(t)) => Some(t.clone()), _ => None, } } @@ -81,7 +88,8 @@ impl<'a> Painter<'a> { pub(super) fn button(&mut self, n: &ButtonNode, rect: Rect, control: LaidControl) { let id = &n.common.id; - let enabled = self.flag(id, Field::Enabled) != Some(false); + let busy = self.input.session.states.is_some_and(|states| states.get(id).busy); + let enabled = self.flag(id, Field::Enabled) != Some(false) && !busy; self.fill(id, rect, if enabled { "thing.control.fill" } else { "thing.control.disabled" }); self.chrome(id, rect, control.form); } @@ -108,7 +116,7 @@ impl<'a> Painter<'a> { 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) { + match self.shown(id, Field::Value).as_deref() { Some(Bound::Number(v)) if v.is_finite() => ((v - n.min) / (n.max - n.min)).clamp(0.0, 1.0), _ => 0.0, } @@ -130,11 +138,11 @@ impl<'a> Painter<'a> { let id = &n.common.id; let inner = control.content; self.chrome(id, rect, control.form); - let Some(value) = self.bound_text(id, Field::Selected) else { return }; + let Some(value) = self.shown_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, + Some(Bound::Options(options)) => options.iter().find(|o| o.value == value).map_or(value.as_str(), |o| o.label.as_str()), + _ => value.as_str(), }; self.draw_text(id, label, "thing.text", false, Some(1), inner, inner.h, text); } @@ -143,26 +151,26 @@ impl<'a> Painter<'a> { let id = &n.common.id; let inner = control.content; self.chrome(id, rect, control.form); - let (content, token) = match self.bound_text(id, Field::Initial).filter(|t| !t.is_empty()) { + let (content, token) = match self.shown_text(id, Field::Initial).filter(|t| !t.is_empty()) { Some(initial) => (initial, "thing.text"), - None => match self.bound_text(id, Field::Placeholder) { + None => match self.shown_text(id, Field::Placeholder) { Some(placeholder) => (placeholder, "thing.text.placeholder"), None => return, }, }; - self.draw_text(id, content, token, n.multiline, if n.multiline { None } else { Some(1) }, inner, inner.h, text); + 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 alt = self.shown_text(id, Field::Alt).unwrap_or_default(); 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); + self.draw_text(id, &alt, "thing.text", true, Some(1), rect, rect.h, text); } return; } @@ -171,7 +179,7 @@ impl<'a> Painter<'a> { 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() }); + self.out.commands.push(RenderCommand::Image { rect: dest, uri: entry.uri.clone(), alt }); 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 d9e411c..4483cd4 100644 --- a/crates/thing-core/src/render/mod.rs +++ b/crates/thing-core/src/render/mod.rs @@ -18,7 +18,9 @@ pub use command::{RenderCommand, balanced}; pub use scroll::{ScrollOffsets, clamp}; use crate::bind::{Bound, BoundTree, Field}; +use crate::command::NodeStates; use crate::diagnostic::{Code, Diagnostic}; +use crate::input::Drafts; use crate::layout::{ControlForm, LaidControl, LaidNode, LaidTree, MAX_DEVICE, Measure, Metrics, Rect}; use crate::theme::{Theme, fallback}; @@ -30,6 +32,26 @@ pub struct RenderInput<'a> { pub viewport: (f32, f32), pub scroll: &'a ScrollOffsets, pub theme: &'a Theme, + pub session: Session<'a>, +} + +/// What the user has done that the documents and state do not say: the drafts that draw over bound +/// values, and the node states (busy, marked) commands derived. `Session::EMPTY` is a surface nobody +/// has touched; a frame drawn with it is the frame the bound tree alone gives. +#[derive(Clone, Copy, Debug)] +pub struct Session<'a> { + pub drafts: Option<&'a Drafts>, + pub states: Option<&'a NodeStates>, +} + +impl Session<'static> { + pub const EMPTY: Session<'static> = Session { drafts: None, states: None }; +} + +impl<'a> Session<'a> { + pub fn new(drafts: &'a Drafts, states: &'a NodeStates) -> Self { + Self { drafts: Some(drafts), states: Some(states) } + } } /// A laid node as it is on screen. `rect` is the scrolled border box in logical px (cells); @@ -195,6 +217,11 @@ impl<'a> Painter<'a> { let Some(node) = node else { return }; let control = laid.control.map(|c| LaidControl { content: self.logical(c.content, shift), ..c }); self.paint(node, rect, control, text); + // A fault commands left on the node shows over its own paint, under what is inside it. + if self.input.session.states.is_some_and(|states| states.get(&laid.id).mark.is_some()) { + let color = self.named(&laid.id, "thing.error"); + self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color }); + } 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); diff --git a/crates/thing-core/tests/frame.rs b/crates/thing-core/tests/frame.rs index c35559b..992cd08 100644 --- a/crates/thing-core/tests/frame.rs +++ b/crates/thing-core/tests/frame.rs @@ -7,7 +7,7 @@ use thing_core::diagnostic::Code; use thing_core::input::{InputEvent, Key, Modifiers, PointerButton, WheelUnit}; use thing_core::layout::{LayoutFrame, Metrics, layout}; use thing_core::port::{Address, Ledger}; -use thing_core::render::{RenderCommand, RenderInput, ScrollOffsets, render}; +use thing_core::render::{RenderCommand, RenderInput, ScrollOffsets, Session, render}; use thing_core::resolve::{Limits, resolve}; use thing_core::theme::Theme; use thing_core::time::Timestamp; @@ -61,7 +61,7 @@ fn staged(document: &SurfaceDocument, state: &mut MemState, viewport: (f32, f32) let laid = layout(bound, &frame, &mut measure(metrics)).unwrap(); let scroll = ScrollOffsets::default(); let theme = Theme::std(); - let input = RenderInput { scale, metrics, viewport, scroll: &scroll, theme: &theme }; + let input = RenderInput { scale, metrics, viewport, scroll: &scroll, theme: &theme, session: Session::EMPTY }; render(bound, &laid, &input, &mut measure(metrics)).commands } @@ -291,7 +291,7 @@ fn every_event() -> Vec { } #[test] -fn this_cut_routes_no_input_event() { +fn keys_text_composition_and_focus_change_nothing_yet() { let document = Fixture::F06ScrollList.load().surfaces.remove(0); let at = (800.0, 600.0); let (mut quiet_state, mut busy_state) = (world(Fixture::F06ScrollList), world(Fixture::F06ScrollList)); @@ -300,7 +300,8 @@ fn this_cut_routes_no_input_event() { show(&mut busy, &document); let plain = run(&mut quiet, &mut quiet_state, input(at, 1.0)); let mut with_events = input(at, 1.0); - with_events.events = every_event(); + // The pointer is routed (tests/input.rs); keys, text, composition and focus are the focus cut's. + with_events.events = every_event().into_iter().filter(|event| !matches!(event, InputEvent::PointerDown { .. } | InputEvent::PointerMove { .. } | InputEvent::PointerUp { .. } | InputEvent::PointerCancel | InputEvent::Wheel { .. })).collect(); let output = run(&mut busy, &mut busy_state, with_events); assert_eq!(output, plain); assert_eq!(busy_state.calls(), quiet_state.calls()); diff --git a/crates/thing-core/tests/goldens/render-f02-login-effect-busy.txt b/crates/thing-core/tests/goldens/render-f02-login-effect-busy.txt new file mode 100644 index 0000000..13f94d2 --- /dev/null +++ b/crates/thing-core/tests/goldens/render-f02-login-effect-busy.txt @@ -0,0 +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 #3a3a48ff +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] diff --git a/crates/thing-core/tests/goldens/render-f04-form-session.txt b/crates/thing-core/tests/goldens/render-f04-form-session.txt new file mode 100644 index 0000000..c3e473a --- /dev/null +++ b/crates/thing-core/tests/goldens/render-f04-form-session.txt @@ -0,0 +1,9 @@ +surface thing:surface:provider.settings.form viewport 800x600 scale 1 pixels +stroke 2 2 796 20 r0 w1 #4a4a60ff +fill 4 4 16 16 r0 #7c9cffff +fill 2 37.5 796 5 r0 #4a4a60ff +fill 196 30 20 20 r0 #7c9cffff +stroke 2 58 796 24 r0 w1 #4a4a60ff +text 4 60 #eeeef4ff font0 size16 [76@0,0 105@8,0 103@16,0 104@24,0 116@32,0] +stroke 2 90 796 24 r0 w1 #4a4a60ff +text 4 92 #eeeef4ff font0 size16 [57@0,0 57@8,0 57@16,0 57@24,0] diff --git a/crates/thing-core/tests/input.rs b/crates/thing-core/tests/input.rs new file mode 100644 index 0000000..076de4f --- /dev/null +++ b/crates/thing-core/tests/input.rs @@ -0,0 +1,748 @@ +//! Pointer input: a press, a drag and a wheel reach the node the user saw drawn, in Pixels (at two +//! scales) and in Cells, and end in the one activation primitive, in drafts or in scroll offsets. +//! Hit-testing reads the geometry render placed, so every test derives its points from `Placed` +//! and never from authored numbers. Ordering is forced: a test that depends on an order puts the +//! events in one frame or in two, and says which. + +use thing_contract::*; +use thing_core::bind::{Binder, BoundTree, Instance}; +use thing_core::command::Commands; +use thing_core::diagnostic::{Code, Diagnostic}; +use thing_core::input::{Drafts, Input, InputEvent, Modifiers, Owners, PointerButton, Seen, WheelUnit, hit_test, target}; +use thing_core::layout::{LaidTree, LayoutFrame, Metrics, Rect, layout}; +use thing_core::port::Ledger; +use thing_core::render::{RenderInput, Rendered, ScrollOffsets, Session, render}; +use thing_core::resolve::{Limits, resolve}; +use thing_core::theme::Theme; +use thing_core::time::Timestamp; +use thing_core::{Config, Core, FrameInput, FrameOutput, Ports}; +use thing_testkit::build::*; +use thing_testkit::fixture::Fixture; +use thing_testkit::ids::SeqIds; +use thing_testkit::measure::FixedMeasure; +use thing_testkit::mem_state::MemState; +use thing_testkit::state::{self, Item}; + +const PROVIDER: &str = "provider.pointer"; +const FEED: &str = "provider.feed"; + +/// Pixels at two scales, and Cells: the modes the pointer must agree with the laid geometry in. +const MODES: [(Metrics, f32); 3] = [(Metrics::Pixels, 1.0), (Metrics::Pixels, 1.5), (Metrics::Cells, 1.0)]; + +fn viewport(metrics: Metrics) -> (f32, f32) { + match metrics { + Metrics::Pixels => (400.0, 320.0), + Metrics::Cells => (50.0, 20.0), + } +} + +fn measure(metrics: Metrics) -> FixedMeasure { + match metrics { + Metrics::Pixels => FixedMeasure::pixels(), + Metrics::Cells => FixedMeasure::cells(), + } +} + +// ----- surfaces ----- + +fn decl(id: &str, captures: &[&str]) -> CommandDecl { + CommandDecl { + id: CommandId::new(id), + payload_schema: SchemaId::new(format!("gamecult.thing.test.{id}.v1")), + captures: captures.iter().map(|node| nid(node)).collect(), + confirm: None, + } +} + +fn column(id: &str, size: Option<(f64, f64)>, overflow: Overflow, children: Vec) -> Node { + let size = size.map_or(size2(Dimension::Percent(Scalar { value: 100.0 }), Dimension::Content), |(w, h)| size2(px(w), px(h))); + let style = BoxStyle { + size, + overflow, + padding: edges(px(0.0)), + gap: size2(px(0.0), px(0.0)), + grow: 0.0, + justify_content: ContentAlign::Start, + ..style() + }; + Node::Box(BoxNode { common: common(id), style, paint: plain_paint(), role: Role::Group, children }) +} + +/// A box of exactly `w` x `h` authored px (a whole number of cells when both are multiples of 8 and 16). +fn fixed(id: &str, w: f64, h: f64) -> Node { + column(id, Some((w, h)), Overflow::Visible, vec![]) +} + +fn button(id: &str, cmd: &str, w: f64, h: f64) -> Node { + Node::Button(ButtonNode { common: common(id), content: vec![fixed(&format!("{id}-body"), w, h)], on_activate: command(cmd), enabled: lit_bool(true) }) +} + +fn overlay(id: &str, modal: bool, children: Vec) -> Node { + Node::Overlay(OverlayNode { common: common(id), anchor: Anchor::Viewport, modal, dismiss: command("dismiss"), children }) +} + +fn surface(root: Node, commands: Vec) -> SurfaceDocument { + SurfaceDocument { provider_id: ProviderId::new(PROVIDER), label: seg("pointer"), version: ver(1), title: "t".into(), root, commands } +} + +/// A main-tree button under a modal overlay whose dialog holds one button. +fn modal_surface() -> SurfaceDocument { + let dialog = column("dialog", Some((160.0, 96.0)), Overflow::Visible, vec![button("confirm", "confirm", 160.0, 48.0)]); + surface( + column("root", None, Overflow::Visible, vec![button("behind", "behind", 320.0, 48.0), overlay("modal", true, vec![dialog])]), + vec![decl("behind", &[]), decl("confirm", &[]), decl("dismiss", &[])], + ) +} + +fn row_id(item: &str, node: &str) -> NodeId { + NodeId::new(format!("{}{node}", Instance::scope_prefix("rows", item, false))) +} + +/// A 160 x 160 scroll pane of twenty buttons, one per feed item, with a button below it. +fn rows_surface() -> SurfaceDocument { + let rows = Node::Repeat(RepeatNode { + common: common("rows"), + collection: CollectionSource::Records(RecordsSource { + provider: Some(ProviderId::new(FEED)), + schema: SchemaId::new("gamecult.thing.test.item.v1"), + key_prefix: "item-".into(), + }), + key_member: path(&["Id"]), + template: std::boxed::Box::new(button("row", "pick", 160.0, 48.0)), + }); + surface( + column("root", None, Overflow::Visible, vec![column("pane", Some((160.0, 160.0)), Overflow::Scroll, vec![rows]), button("below", "below", 160.0, 48.0)]), + vec![decl("pick", &[]), decl("below", &[])], + ) +} + +fn feed() -> MemState { + let mut state = MemState::new(); + for n in 0..20 { + let id = format!("item-{n:04}"); + state.put_state(&ProviderId::new(FEED), &id, &Item { id: id.clone(), title: id.clone() }); + } + state +} + +/// A pane inside a pane, each scrolling: the inner is 80 tall with 400 of content, the outer 160 tall +/// with the inner above 400 more. +fn nested_surface() -> SurfaceDocument { + let inner = column("inner", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("inner-fill", 160.0, 400.0)]); + surface(column("root", None, Overflow::Visible, vec![column("outer", Some((160.0, 160.0)), Overflow::Scroll, vec![inner, fixed("outer-fill", 160.0, 400.0)])]), vec![]) +} + +/// A tall button inside a clip, with room below the clip that the button's own rect also covers. +fn clip_surface() -> SurfaceDocument { + surface( + column("root", None, Overflow::Visible, vec![column("frame", Some((160.0, 64.0)), Overflow::Clip, vec![button("tall", "tall", 160.0, 320.0)])]), + vec![decl("tall", &[])], + ) +} + +fn controls_surface() -> SurfaceDocument { + let slider = Node::Slider(SliderNode { common: common("level"), min: 0.0, max: 100.0, step: 10.0, value: lit_number(0.0), commit: command("set") }); + let toggle = Node::Toggle(ToggleNode { common: common("flag"), checked: lit_bool(false), on_change: command("flip") }); + surface( + column("root", None, Overflow::Visible, vec![button("a", "go", 160.0, 48.0), button("b", "go", 160.0, 48.0), toggle, slider]), + vec![decl("go", &[]), decl("flip", &["flag"]), decl("set", &["level"])], + ) +} + +// ----- the rig: the stages composed by hand, with the owners input writes through ----- + +struct Rig { + tree: BoundTree, + laid: LaidTree, + rendered: Rendered, + metrics: Metrics, + scale: f32, + surface: String, + state: MemState, + ledger: Ledger, + input: Input, + commands: Commands, + drafts: Drafts, + scroll: ScrollOffsets, + ids: SeqIds, + now: Timestamp, +} + +impl Rig { + fn new(mut state: MemState, document: &SurfaceDocument, (metrics, scale): (Metrics, f32)) -> Self { + state.put(&document.provider_id, document); + let limits = Limits::default(); + let resolved = resolve(document, &state, &limits).tree.expect("resolves"); + let mut ledger = Ledger::new(); + let mut binder = Binder::new(limits); + binder.bind(resolved, &mut state, &mut ledger); + let tree = binder.tree(&document.record_key()).expect("bound").clone(); + let mut rig = Self { + laid: LaidTree { nodes: vec![], diagnostics: vec![] }, + rendered: Rendered { commands: vec![], placed: vec![], diagnostics: vec![] }, + tree, + metrics, + scale, + surface: document.record_key(), + state, + ledger, + input: Input::new(), + commands: Commands::new("renderer.test", 15_000), + drafts: Drafts::new(), + scroll: ScrollOffsets::default(), + ids: SeqIds::new(), + now: Timestamp(0), + }; + rig.draw(); + rig + } + + fn frame(&self) -> LayoutFrame { + LayoutFrame { viewport: viewport(self.metrics), scale: self.scale, metrics: self.metrics } + } + + /// The frame the user sees: layout, then render over the scroll offsets, drafts and node states. + fn draw(&mut self) { + self.laid = layout(&self.tree, &self.frame(), &mut measure(self.metrics)).expect("lays out"); + let states = self.commands.view(&self.surface); + let theme = Theme::std(); + let input = RenderInput { + scale: self.scale, + metrics: self.metrics, + viewport: viewport(self.metrics), + scroll: &self.scroll, + theme: &theme, + session: Session::new(&self.drafts, &states), + }; + self.rendered = render(&self.tree, &self.laid, &input, &mut measure(self.metrics)); + } + + fn rect(&self, id: &str) -> Rect { + self.rendered.placed.iter().find(|placed| placed.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}")).rect + } + + fn send(&mut self, event: InputEvent) -> Vec { + let theme = Theme::std(); + let seen = Seen { rendered: &self.rendered, laid: &self.laid, tree: &self.tree, metrics: self.metrics, scale: self.scale, line: theme.text["body"].size }; + let mut owners = Owners { + commands: &mut self.commands, + drafts: &mut self.drafts, + scroll: &mut self.scroll, + ids: &mut self.ids, + port: &mut self.state, + ledger: &mut self.ledger, + }; + self.input.event(&event, &seen, &mut owners, self.now) + } + + fn click(&mut self, at: (f32, f32)) -> Vec { + let mut said = self.send(down(at)); + said.extend(self.send(up(at))); + said + } + + fn minted(&mut self) -> Vec { + self.commands.take_outbound() + } + + fn draft(&self, node: &str) -> Option { + self.drafts.get(&self.surface, &nid(node)).cloned() + } + + fn offset(&self, node: &str) -> Option<(f32, f32)> { + self.scroll.get(&nid(node)) + } + + fn max_scroll(&self, node: &str) -> (f32, f32) { + self.laid.nodes.iter().find(|laid| laid.id.as_str() == node).and_then(|laid| laid.max_scroll).expect("scrolls") + } +} + +fn mods() -> Modifiers { + Modifiers::default() +} + +fn down(at: (f32, f32)) -> InputEvent { + InputEvent::PointerDown { at, button: PointerButton::Primary, modifiers: mods() } +} + +fn up(at: (f32, f32)) -> InputEvent { + InputEvent::PointerUp { at, button: PointerButton::Primary, modifiers: mods() } +} + +fn mv(at: (f32, f32)) -> InputEvent { + InputEvent::PointerMove { at, modifiers: mods() } +} + +fn wheel(at: (f32, f32), delta: (f32, f32), unit: WheelUnit) -> InputEvent { + InputEvent::Wheel { at, delta, unit, modifiers: mods() } +} + +/// The top-left cell (or, in Pixels, the half-pixel) of a rect: a point that is inside it in every mode. +fn inside(rect: Rect) -> (f32, f32) { + (rect.x + 0.5, rect.y + 0.5) +} + +fn commands_of(invocations: &[CommandInvocation]) -> Vec<&str> { + invocations.iter().map(|invocation| invocation.command.as_str()).collect() +} + +fn index_of(rig: &Rig) -> std::collections::HashMap<&NodeId, &Node> { + rig.tree.index() +} + +fn hit_node(rig: &Rig, at: (f32, f32)) -> Option { + hit_test(&rig.rendered, &rig.laid, &index_of(rig), at).map(|hit| hit.node.as_str().to_string()) +} + +// ----- hit-testing agrees with the laid geometry ----- + +#[test] +fn a_point_inside_the_absolute_target_hits_target_and_one_on_the_board_only_hits_board() { + for mode in MODES { + let mut state = MemState::from_fixture(Fixture::F03InputTarget); + state::script(Fixture::F03InputTarget, &mut state); + let document = Fixture::F03InputTarget.load().surfaces.remove(0); + let rig = Rig::new(state, &document, mode); + let (target, board) = (rig.rect("target"), rig.rect("board")); + // The far corner of the target, clear of its label. + let corner = (target.x + target.w - 0.5, target.y + target.h - 0.5); + assert_eq!(hit_node(&rig, corner).as_deref(), Some("target"), "{mode:?}"); + assert_eq!(hit_node(&rig, inside(board)).as_deref(), Some("board"), "{mode:?}"); + assert!(target.x > board.x && target.y > board.y, "{mode:?}: the target stands inside the board, away from its corner"); + } +} + +#[test] +fn a_rect_is_half_open_so_a_shared_edge_belongs_to_the_second_node() { + for mode in MODES { + let rig = Rig::new(MemState::new(), &surface(column("root", None, Overflow::Visible, vec![button("a", "x", 160.0, 48.0), button("b", "x", 160.0, 48.0)]), vec![decl("x", &[])]), mode); + let (a, b) = (rig.rect("a"), rig.rect("b")); + assert_eq!(a.y + a.h, b.y, "{mode:?}: the buttons touch"); + let edge = (a.x + 0.5, b.y); + assert!(target(&rig.rendered, &rig.laid, &index_of(&rig), edge).is_some_and(|hit| hit.node.as_str() == "b"), "{mode:?}"); + let last = (a.x + 0.5, b.y - 0.25); + assert!(target(&rig.rendered, &rig.laid, &index_of(&rig), last).is_some_and(|hit| hit.node.as_str() == "a"), "{mode:?}"); + let beyond = (a.x + a.w, a.y + 0.5); + assert_ne!(target(&rig.rendered, &rig.laid, &index_of(&rig), beyond).map(|hit| hit.node), Some(nid("a")), "{mode:?}: the right edge is outside"); + } +} + +#[test] +fn every_visible_node_is_reached_inside_its_own_visible_rect() { + let fixtures = [Fixture::F01SwarmDashboard, Fixture::F05ModalOverlay, Fixture::F06ScrollList]; + for mode in MODES { + for fixture in fixtures { + let mut state = MemState::from_fixture(fixture); + state::script(fixture, &mut state); + let document = fixture.load().surfaces.remove(0); + let rig = Rig::new(state, &document, mode); + for placed in &rig.rendered.placed { + let Some(seen) = placed.visible.filter(|r| r.w >= 1.0 && r.h >= 1.0) else { continue }; + let hit = hit_node(&rig, inside(seen)).expect("something is there"); + let reached = rig.rendered.placed.iter().find(|p| p.id.as_str() == hit).unwrap(); + let at = inside(seen); + let within = reached.visible.is_some_and(|r| at.0 >= r.x && at.0 < r.x + r.w && at.1 >= r.y && at.1 < r.y + r.h); + assert!(within, "{mode:?} {fixture:?}: {hit} reached at {at:?} is not drawn there"); + } + } + } +} + +#[test] +fn a_node_outside_its_clip_is_not_hit_where_its_rect_reaches_past_the_clip() { + for mode in MODES { + let rig = Rig::new(MemState::new(), &clip_surface(), mode); + let (frame, tall) = (rig.rect("frame"), rig.rect("tall")); + assert!(tall.y + tall.h > frame.y + frame.h, "{mode:?}: the button runs past the clip"); + let below = (tall.x + 0.5, frame.y + frame.h + 0.5); + assert!(below.1 < tall.y + tall.h); + assert_eq!(target(&rig.rendered, &rig.laid, &index_of(&rig), below), None, "{mode:?}"); + assert_ne!(hit_node(&rig, below).as_deref(), Some("tall"), "{mode:?}"); + // Inside the clip it is hit. + let inside_clip = target(&rig.rendered, &rig.laid, &index_of(&rig), inside(frame)); + assert_eq!(inside_clip.map(|hit| hit.node.as_str().to_string()).as_deref(), Some("tall"), "{mode:?}"); + } +} + +// ----- the modal ----- + +#[test] +fn a_modal_confirms_inside_the_dialog_and_dismisses_outside_it_and_never_reaches_beneath() { + for mode in MODES { + let mut rig = Rig::new(MemState::new(), &modal_surface(), mode); + // Inside the dialog: the confirm button. + rig.click(inside(rig.rect("confirm"))); + assert_eq!(commands_of(&rig.minted()), ["confirm"], "{mode:?}"); + // Over a main-tree button under the scrim: the scrim's dismissal, once, and not the button's command. + let behind = rig.rect("behind"); + rig.click((behind.x + behind.w - 0.5, behind.y + 0.5)); + assert_eq!(commands_of(&rig.minted()), ["dismiss"], "{mode:?}"); + // The dialog's own body is not the scrim: nothing. + let dialog = rig.rect("dialog"); + rig.click((dialog.x + dialog.w - 0.5, dialog.y + dialog.h - 0.5)); + assert_eq!(rig.minted(), vec![], "{mode:?}"); + // The scrim is the whole viewport: a corner far from everything dismisses. + let (w, h) = viewport(mode.0); + let far = match mode.0 { + Metrics::Pixels => (w - 1.0, h - 1.0), + Metrics::Cells => (w - 0.5, h - 0.5), + }; + assert_eq!(hit_node(&rig, far).as_deref(), Some("modal"), "{mode:?}"); + // (The overlay that dismissed above still waits on its result, so it is silent: a fresh surface.) + let mut fresh = Rig::new(MemState::new(), &modal_surface(), mode); + fresh.click(far); + assert_eq!(commands_of(&fresh.minted()), ["dismiss"], "{mode:?}"); + // And the same press again, while the first waits, mints nothing more. + fresh.click(far); + assert_eq!(fresh.minted(), vec![], "{mode:?}"); + } +} + +#[test] +fn a_press_on_the_scrim_released_on_a_button_activates_nothing() { + let mut rig = Rig::new(MemState::new(), &modal_surface(), MODES[0]); + let behind = rig.rect("behind"); + let (scrim, confirm) = ((behind.x + behind.w - 0.5, behind.y + 0.5), inside(rig.rect("confirm"))); + rig.send(down(scrim)); + rig.send(up(confirm)); + assert_eq!(rig.minted(), vec![]); +} + +// ----- scroll ----- + +#[test] +fn a_click_hits_the_row_drawn_there_after_a_scroll_and_not_a_row_scrolled_out() { + for mode in MODES { + let mut rig = Rig::new(feed(), &rows_surface(), mode); + let (first, second) = (row_id("item-0000", "row"), row_id("item-0001", "row")); + let (r0, r1) = (rig.rect(first.as_str()), rig.rect(second.as_str())); + let step = r1.y - r0.y; + assert!(step > 0.0); + // At rest the click at row 0's corner is row 0, whose invocation names it in `items`. + rig.click(inside(r0)); + let minted = rig.minted(); + assert_eq!((minted[0].source.as_str(), minted[0].items.clone()), ("row", vec!["item-0000".to_string()]), "{mode:?}"); + // Scrolled by one row (offsets are device px in Pixels): row 1 is drawn where row 0 was. + let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 }; + rig.scroll.set(nid("pane"), (0.0, step * k)); + rig.draw(); + assert_eq!(rig.rect(second.as_str()).y, r0.y, "{mode:?}"); + rig.click(inside(r0)); + assert_eq!(rig.minted()[0].items, vec!["item-0001".to_string()], "{mode:?}"); + // Row 0 is above the pane's clip now: its rect is not hit anywhere, though a point there is drawn. + let gone = rig.rendered.placed.iter().find(|p| p.id == first).unwrap(); + let pane = rig.rect("pane"); + let over = (pane.x + 0.5, gone.rect.y + 0.5); + assert!(over.1 < pane.y, "{mode:?}: the scrolled-out row is above the pane"); + assert_ne!(hit_node(&rig, over).as_deref(), Some(first.as_str()), "{mode:?}"); + assert_eq!(target(&rig.rendered, &rig.laid, &index_of(&rig), over), None, "{mode:?}"); + } +} + +#[test] +fn a_wheel_moves_the_pane_and_clamps_at_the_end_then_goes_to_the_next_pane() { + for mode in MODES { + let mut rig = Rig::new(MemState::new(), &nested_surface(), mode); + let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 }; + let (inner, outer) = (rig.rect("inner"), rig.rect("outer")); + let over = inside(inner); + let (inner_max, _) = (rig.max_scroll("inner"), 0); + assert!(inner_max.1 > 0.0 && rig.max_scroll("outer").1 > 0.0, "{mode:?}"); + // Far past the end: the inner pane clamps at its travel, the outer stays. + rig.send(wheel(over, (0.0, 100_000.0), WheelUnit::Units)); + assert_eq!((rig.offset("inner"), rig.offset("outer")), (Some((0.0, inner_max.1)), None), "{mode:?}"); + // At the end of travel the same wheel goes to the pane around it. + rig.send(wheel(over, (0.0, 16.0), WheelUnit::Units)); + assert_eq!((rig.offset("inner"), rig.offset("outer")), (Some((0.0, inner_max.1)), Some((0.0, 16.0 * k))), "{mode:?}"); + // The other way the inner pane has room, so it takes it and the outer holds. + rig.send(wheel(over, (0.0, -8.0), WheelUnit::Units)); + assert_eq!(rig.offset("inner"), Some((0.0, inner_max.1 - 8.0 * k)), "{mode:?}"); + assert_eq!(rig.offset("outer"), Some((0.0, 16.0 * k)), "{mode:?}"); + // Back to the start, then further: clamps at zero and the outer takes the rest of the way back. + rig.send(wheel(over, (0.0, -100_000.0), WheelUnit::Units)); + assert_eq!(rig.offset("inner"), Some((0.0, 0.0)), "{mode:?}"); + rig.send(wheel(over, (0.0, -4.0), WheelUnit::Units)); + assert_eq!(rig.offset("outer"), Some((0.0, 12.0 * k)), "{mode:?}"); + // A wheel off every pane moves nothing; the horizontal axis has no travel here. + let before = (rig.offset("inner"), rig.offset("outer")); + rig.send(wheel((outer.x - 0.5, outer.y - 0.5), (0.0, 10.0), WheelUnit::Units)); + rig.send(wheel(over, (10.0, 0.0), WheelUnit::Units)); + assert_eq!((rig.offset("inner"), rig.offset("outer")), before, "{mode:?}"); + } +} + +#[test] +fn a_wheel_line_is_one_cell_in_cells_and_the_body_text_size_in_pixels() { + let mut cells = Rig::new(MemState::new(), &nested_surface(), (Metrics::Cells, 1.0)); + cells.send(wheel(inside(cells.rect("inner")), (0.0, 3.0), WheelUnit::Lines)); + assert_eq!(cells.offset("inner"), Some((0.0, 3.0))); + for scale in [1.0, 1.5] { + let mut pixels = Rig::new(MemState::new(), &nested_surface(), (Metrics::Pixels, scale)); + pixels.send(wheel(inside(pixels.rect("inner")), (0.0, 2.0), WheelUnit::Lines)); + assert_eq!(pixels.offset("inner"), Some((0.0, 2.0 * 16.0 * scale))); + } +} + +#[test] +fn a_wheel_over_a_modal_never_scrolls_the_tree_beneath() { + let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("fill", 160.0, 400.0)]); + let document = surface(column("root", None, Overflow::Visible, vec![pane, overlay("modal", true, vec![fixed("dialog", 80.0, 48.0)])]), vec![decl("dismiss", &[])]); + for mode in MODES { + let mut rig = Rig::new(MemState::new(), &document, mode); + rig.send(wheel(inside(rig.rect("pane")), (0.0, 16.0), WheelUnit::Units)); + assert_eq!(rig.offset("pane"), None, "{mode:?}"); + } +} + +// ----- press semantics ----- + +#[test] +fn a_press_released_elsewhere_or_with_another_button_or_after_a_cancel_activates_nothing() { + for mode in MODES { + let mut rig = Rig::new(MemState::new(), &controls_surface(), mode); + let (a, b) = (inside(rig.rect("a")), inside(rig.rect("b"))); + // Down on a, up on b. + rig.send(down(a)); + rig.send(up(b)); + // Secondary and middle buttons never press. + for button in [PointerButton::Secondary, PointerButton::Middle] { + rig.send(InputEvent::PointerDown { at: a, button, modifiers: mods() }); + rig.send(InputEvent::PointerUp { at: a, button, modifiers: mods() }); + } + // Down, the platform takes the pointer, a stray up. + rig.send(down(a)); + rig.send(InputEvent::PointerCancel); + rig.send(up(a)); + // An up with no press. + rig.send(up(a)); + assert_eq!(rig.minted(), vec![], "{mode:?}"); + // And the same button down and up mints once. + rig.click(a); + assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}"); + } +} + +#[test] +fn a_secondary_up_does_not_release_a_primary_press() { + let mut rig = Rig::new(MemState::new(), &controls_surface(), MODES[0]); + let a = inside(rig.rect("a")); + rig.send(down(a)); + rig.send(InputEvent::PointerUp { at: a, button: PointerButton::Secondary, modifiers: mods() }); + assert_eq!(rig.minted(), vec![]); + rig.send(up(a)); + assert_eq!(commands_of(&rig.minted()), ["go"]); +} + +#[test] +fn a_busy_button_mints_once_however_often_it_is_pressed() { + for mode in MODES { + let mut rig = Rig::new(MemState::new(), &controls_surface(), mode); + let a = inside(rig.rect("a")); + assert_eq!(rig.click(a), vec![]); + assert_eq!(rig.click(a), vec![], "{mode:?}: a busy press is silent, not a refusal"); + assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}"); + // The user sees it: the busy button is drawn disabled. + rig.draw(); + let disabled = Theme::std().colors["thing.control.disabled"].clone(); + assert!(rig.rendered.commands.iter().any(|c| matches!(c, thing_core::render::RenderCommand::FillRect { color, .. } if *color == disabled)), "{mode:?}"); + } +} + +#[test] +fn a_toggle_flips_its_draft_and_fires_on_change_once_per_press() { + for mode in MODES { + let mut rig = Rig::new(MemState::new(), &controls_surface(), mode); + let flag = inside(rig.rect("flag")); + rig.click(flag); + let first = rig.minted(); + assert_eq!(commands_of(&first), ["flip"], "{mode:?}"); + assert_eq!(first[0].captured[0].value, InputValue::Bool(BoolValue { value: true }), "{mode:?}"); + assert_eq!(rig.draft("flag"), Some(InputValue::Bool(BoolValue { value: true }))); + // A second press flips what is shown now (the draft), not the bound value it was. The node still + // has an invocation waiting, so it fires nothing more (as a busy button), and the draft stays flipped. + assert_eq!(rig.click(flag), vec![]); + assert_eq!(rig.minted(), vec![], "{mode:?}"); + assert_eq!(rig.draft("flag"), Some(InputValue::Bool(BoolValue { value: false }))); + } +} + +#[test] +fn a_slider_drag_writes_snapped_drafts_and_commits_once_wherever_it_is_released() { + for mode in MODES { + let mut rig = Rig::new(MemState::new(), &controls_surface(), mode); + let track = rig.rect("level"); + let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5); + let value = |v: f64| Some(InputValue::Number(NumberValue { value: v })); + rig.send(down(along(0.34))); + assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: 34 snaps to the step from min"); + rig.send(mv(along(0.76))); + assert_eq!(rig.draft("level"), value(80.0), "{mode:?}"); + // The drag is shown while it is made. + rig.draw(); + let thumb = |rig: &Rig| rig.rendered.commands.iter().filter_map(|c| match c { + thing_core::render::RenderCommand::FillRect { rect, .. } if rect.w <= track.h.max(1.0) + 0.01 && rect.h > 0.0 => Some(rect.x), + _ => None, + }).last(); + assert!(thumb(&rig).is_some()); + // Released far outside the track, even outside the pane: one commit of the last draft. + rig.send(mv((track.x + track.w * 3.0, track.y + 500.0))); + assert_eq!(rig.draft("level"), value(100.0), "{mode:?}: past the end clamps"); + rig.send(up((track.x - 900.0, track.y - 900.0))); + let minted = rig.minted(); + assert_eq!(commands_of(&minted), ["set"], "{mode:?}"); + assert_eq!(minted[0].captured[0].value, InputValue::Number(NumberValue { value: 100.0 }), "{mode:?}"); + // Moving after the up changes nothing. + rig.send(mv(along(0.1))); + assert_eq!(rig.draft("level"), value(100.0), "{mode:?}"); + } +} + +#[test] +fn a_cancelled_slider_press_leaves_the_draft_it_found_and_fires_nothing() { + for mode in MODES { + let mut rig = Rig::new(MemState::new(), &controls_surface(), mode); + let track = rig.rect("level"); + let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5); + // No draft before: a press then a cancel leaves none, and a stray up commits nothing. + rig.send(down(along(0.5))); + assert!(rig.draft("level").is_some()); + rig.send(InputEvent::PointerCancel); + rig.send(up(along(0.5))); + assert_eq!((rig.draft("level"), rig.minted()), (None, vec![]), "{mode:?}"); + // A draft that is already waiting on a result comes back as it was. + rig.send(down(along(0.3))); + rig.send(up(along(0.3))); + assert_eq!(commands_of(&rig.minted()), ["set"]); + let held = rig.draft("level"); + rig.send(down(along(0.9))); + rig.send(mv(along(0.2))); + rig.send(InputEvent::PointerCancel); + assert_eq!((rig.draft("level"), rig.minted()), (held, vec![]), "{mode:?}"); + } +} + +#[test] +fn a_press_on_a_select_or_a_text_input_does_nothing_yet() { + for mode in MODES { + let mut state = MemState::from_fixture(Fixture::F04Form); + state::script(Fixture::F04Form, &mut state); + let document = Fixture::F04Form.load().surfaces.remove(0); + let mut rig = Rig::new(state, &document, mode); + for id in ["theme", "port"] { + assert_eq!(rig.click(inside(rig.rect(id))), vec![], "{mode:?} {id}"); + } + assert_eq!((rig.minted(), rig.drafts.is_empty()), (vec![], true), "{mode:?}"); + } +} + +#[test] +fn a_click_while_a_command_waits_for_confirmation_is_a_refusal_the_event_returns() { + for mode in MODES { + let mut document = surface(column("root", None, Overflow::Visible, vec![button("a", "ask", 160.0, 48.0), button("b", "go", 160.0, 48.0)]), vec![decl("ask", &[]), decl("go", &[])]); + document.commands[0].confirm = Some("Sure?".into()); + let mut rig = Rig::new(MemState::new(), &document, mode); + assert_eq!(rig.click(inside(rig.rect("a"))), vec![]); + assert!(rig.commands.confirming().is_some() && rig.minted().is_empty(), "{mode:?}"); + let said = rig.click(inside(rig.rect("b"))); + assert_eq!(said.iter().map(|d| d.code).collect::>(), vec![Code::ActivationRefused], "{mode:?}"); + assert_eq!(said[0].node.as_ref().map(NodeId::as_str), Some("b")); + } +} + +// ----- through Core::frame ----- + +struct Host { + core: Core, + state: MemState, + ids: SeqIds, + mode: (Metrics, f32), + now: i64, +} + +impl Host { + fn new(mut state: MemState, document: &SurfaceDocument, mode: (Metrics, f32)) -> Self { + state.put(&document.provider_id, document); + let mut core = Core::new(Config::new(mode.0, "renderer.test"), Box::new(measure(mode.0))); + core.show(document.provider_id.clone(), RecordKey::new(document.record_key())); + let mut host = Self { core, state, ids: SeqIds::new(), mode, now: 0 }; + host.frame(vec![]); + host + } + + fn frame(&mut self, events: Vec) -> FrameOutput { + self.now += 1; + let input = FrameInput { now: Timestamp(self.now), viewport: viewport(self.mode.0), scale: self.mode.1, events }; + self.core.frame(input, Ports { state: &mut self.state, ids: &mut self.ids }) + } +} + +#[test] +fn core_frame_routes_a_click_to_the_one_activation_primitive() { + for mode in MODES { + let document = modal_surface(); + let rig = Rig::new(MemState::new(), &document, mode); + let mut host = Host::new(MemState::new(), &document, mode); + let output = host.frame(vec![down(inside(rig.rect("confirm"))), up(inside(rig.rect("confirm")))]); + assert_eq!(commands_of(&output.outbound), ["confirm"], "{mode:?}"); + assert_eq!(output.outbound[0].source.as_str(), "confirm"); + // The next frame mints nothing more, and draws the pressed button busy (disabled). + let next = host.frame(vec![]); + assert!(next.outbound.is_empty()); + let disabled = Theme::std().colors["thing.control.disabled"].clone(); + assert!(next.commands.iter().any(|c| matches!(c, thing_core::render::RenderCommand::FillRect { color, .. } if *color == disabled)), "{mode:?}"); + } +} + +#[test] +fn events_in_one_frame_act_on_the_frame_the_user_saw_and_the_next_frame_draws_their_result() { + for mode in MODES { + let document = rows_surface(); + let rig = Rig::new(feed(), &document, mode); + let (r0, r1) = (rig.rect(row_id("item-0000", "row").as_str()), rig.rect(row_id("item-0001", "row").as_str())); + let step = r1.y - r0.y; + let mut host = Host::new(feed(), &document, mode); + let pane = inside(rig.rect("pane")); + // One frame: the wheel scrolls a row, then the click lands where row 0 was drawn when the frame began. + let first = host.frame(vec![wheel(pane, (0.0, step), WheelUnit::Units), down(inside(r0)), up(inside(r0))]); + assert_eq!(first.outbound[0].items, vec!["item-0000".to_string()], "{mode:?}: the click is judged against the kept frame"); + // The wheel did take effect: the same click one frame later reaches row 1. + let second = host.frame(vec![down(inside(r0)), up(inside(r0))]); + assert_eq!(second.outbound[0].items, vec!["item-0001".to_string()], "{mode:?}"); + // And the scrolled frame was drawn differently from the unscrolled one. + assert_ne!(first.commands, second.commands, "{mode:?}"); + } +} + +#[test] +fn a_surface_left_mid_press_drops_the_press_and_a_stray_up_does_nothing() { + let (one, mut two) = (controls_surface(), controls_surface()); + two.label = seg("other"); + let mode = MODES[0]; + let rig = Rig::new(MemState::new(), &one, mode); + let mut state = MemState::new(); + state.put(&one.provider_id, &one); + state.put(&two.provider_id, &two); + let mut host = Host::new(state, &one, mode); + let track = rig.rect("level"); + host.frame(vec![down((track.x + 0.5 * track.w, track.y + 0.5))]); + host.core.show(two.provider_id.clone(), RecordKey::new(two.record_key())); + host.frame(vec![]); + let output = host.frame(vec![up((track.x + 0.5 * track.w, track.y + 0.5))]); + assert!(output.outbound.is_empty()); +} + +#[test] +fn input_other_than_the_pointer_changes_nothing() { + let mut rig = Rig::new(MemState::new(), &controls_surface(), MODES[0]); + let before = (rig.rendered.clone(), rig.drafts.len()); + for event in [ + InputEvent::Key { key: thing_core::input::Key::Enter, modifiers: mods(), repeat: false }, + InputEvent::Text("x".into()), + InputEvent::Compose { text: "か".into(), cursor: None }, + InputEvent::Focus(true), + ] { + assert_eq!(rig.send(event), vec![]); + } + assert_eq!((rig.minted(), rig.drafts.len()), (vec![], before.1)); +} diff --git a/crates/thing-core/tests/render.rs b/crates/thing-core/tests/render.rs index 1ab0153..1803788 100644 --- a/crates/thing-core/tests/render.rs +++ b/crates/thing-core/tests/render.rs @@ -5,16 +5,20 @@ use std::path::PathBuf; use thing_contract::*; use thing_core::bind::{Binder, BoundTree}; +use thing_core::command::{Activation, ActivationKind, Commands, Mark, NodeStates}; use thing_core::diagnostic::Code; +use thing_core::input::Drafts; use thing_core::layout::{LaidTree, LayoutFrame, Measure, Metrics, Run, layout}; -use thing_core::port::Ledger; +use thing_core::port::{Address, Change, Entry, Ledger, Record}; use thing_core::text::CellMeasure; -use thing_core::render::{Placed, RenderCommand, RenderInput, Rendered, ScrollOffsets, balanced, clamp, render}; +use thing_core::render::{Placed, RenderCommand, RenderInput, Rendered, ScrollOffsets, Session, 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_core::time::Timestamp; +use thing_testkit::ids::SeqIds; use thing_testkit::mem_state::MemState; use thing_testkit::measure::FixedMeasure; use thing_testkit::state; @@ -62,7 +66,7 @@ fn measure(frame: &LayoutFrame) -> Box { } 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 } + RenderInput { scale: frame.scale, metrics: frame.metrics, viewport: frame.viewport, scroll, theme, session: Session::EMPTY } } fn draw(tree: &BoundTree, frame: &LayoutFrame, scroll: &ScrollOffsets) -> (LaidTree, Rendered) { @@ -1412,3 +1416,117 @@ fn a_pixels_control_draws_its_content_in_logical_px_at_any_scale() { let out = with_state(&mut MemState::new(), flat("root", plain(), vec![input]), &pixels(2.0)); assert!(matches!(out.commands.last(), Some(RenderCommand::Text { origin, .. }) if origin.0 == 2.0), "{:?}", out.commands.last()); } + +// ---- the session: drafts and node states draw over the bound tree --------------------------- + +fn session_text(fixture: Fixture, drafts: &Drafts, states: &NodeStates) -> (String, Rendered) { + let set = fixture.load(); + let mut state = MemState::from_fixture(fixture); + state::script(fixture, &mut state); + let tree = bind(&mut state, &set.surfaces[0]).unwrap(); + let frame = pixels(1.0); + let laid = layout(&tree, &frame, &mut *measure(&frame)).unwrap(); + let theme = Theme::std(); + let none = ScrollOffsets::default(); + let input = RenderInput { session: Session::new(drafts, states), ..input(&frame, &none, &theme) }; + let rendered = render(&tree, &laid, &input, &mut *measure(&frame)); + (format!("surface {} viewport 800x600 scale 1 pixels\n{}", set.surfaces[0].record_key(), text_form(&rendered)), rendered) +} + +#[test] +fn drafts_draw_over_the_bound_values_of_a_form() { + let set = Fixture::F04Form.load(); + let surface = set.surfaces[0].record_key(); + let Node::Box(root) = &set.surfaces[0].root else { panic!("a box root") }; + let range = root.children.iter().find_map(|node| match node { + Node::Slider(slider) => Some((slider.min, slider.max)), + _ => None, + }); + let (min, max) = range.expect("a slider"); + let options = root.children.iter().find_map(|node| match node { + Node::Select(SelectNode { options: OptionList::Literal(literal), .. }) => Some(literal.options.clone()), + _ => None, + }); + let chosen = options.expect("literal options").last().expect("an option").value.clone(); + let mut drafts = Drafts::new(); + drafts.set(&surface, &nid("enabled"), InputValue::Bool(BoolValue { value: false })); + drafts.set(&surface, &nid("volume"), InputValue::Number(NumberValue { value: min + (max - min) * 0.25 })); + drafts.set(&surface, &nid("theme"), InputValue::Choice(ChoiceValue { value: chosen })); + drafts.set(&surface, &nid("port"), InputValue::Text(TextValue { value: "9999".into() })); + let (text, drawn) = session_text(Fixture::F04Form, &drafts, &NodeStates::default()); + golden::check(&golden_dir(), "render-f04-form-session.txt", text.as_bytes()); + let (_, plain) = session_text(Fixture::F04Form, &Drafts::new(), &NodeStates::default()); + assert_ne!(drawn.commands, plain.commands); + assert_eq!(plain.commands, fixture_runs(Fixture::F04Form, &pixels(1.0), &ScrollOffsets::default())[0].1.as_ref().unwrap().commands, "no drafts, no states: the bound frame"); +} + +/// f02 with its sign-in button pressed: the commands that came of it, and the world they live in. +struct Pressed { + commands: Commands, + binder: Binder, + state: MemState, + ledger: Ledger, + drafts: Drafts, + invocation: CommandInvocation, + surface: String, +} + +fn pressed() -> Pressed { + let fixture = Fixture::F02LoginEffect; + let set = fixture.load(); + let mut state = MemState::from_fixture(fixture); + state::script(fixture, &mut state); + let document = &set.surfaces[0]; + state.put(&document.provider_id, document); + let limits = Limits::default(); + let resolved = resolve(document, &state, &limits).tree.expect("resolves"); + let mut ledger = Ledger::new(); + let mut binder = Binder::new(limits); + binder.bind(resolved, &mut state, &mut ledger); + let surface = document.record_key(); + let mut commands = Commands::new("renderer.test", 15_000); + let mut drafts = Drafts::new(); + let tree = binder.tree(&surface).unwrap(); + let act = Activation { node: nid("sign-in-button"), kind: ActivationKind::Press }; + let said = commands.activate(act, tree, &mut drafts, Timestamp(0), &mut SeqIds::new(), &mut state, &mut ledger); + assert_eq!(said, vec![]); + let invocation = commands.take_outbound().pop().expect("minted"); + Pressed { commands, binder, state, ledger, drafts, invocation, surface } +} + +#[test] +fn a_busy_button_is_drawn_disabled_and_an_idle_one_is_not() { + let world = pressed(); + let states = world.commands.view(&world.surface); + assert!(states.get(&nid("sign-in-button")).busy); + let (text, busy) = session_text(Fixture::F02LoginEffect, &world.drafts, &states); + golden::check(&golden_dir(), "render-f02-login-effect-busy.txt", text.as_bytes()); + let disabled = Theme::std().colors["thing.control.disabled"].clone(); + let fills = |rendered: &Rendered| rendered.commands.iter().filter(|c| matches!(c, RenderCommand::FillRect { color, .. } if *color == disabled)).count(); + let (_, idle) = session_text(Fixture::F02LoginEffect, &Drafts::new(), &NodeStates::default()); + assert_eq!((fills(&idle), fills(&busy)), (0, 1)); +} + +#[test] +fn a_denied_mark_draws_one_error_stroke_over_the_marked_node() { + let mut world = pressed(); + let result = CommandResult::denied(&world.invocation, seq(1), "no", None); + let provider = world.binder.tree(&world.surface).unwrap().resolved().document().provider_id.clone(); + let address = Address { provider, schema: SchemaId::new(CommandResult::SCHEMA_NAME), key: RecordKey::new(result.record_key()) }; + let change = Change::Upsert(Entry { address, record: Record::Result(result) }); + let binder = &world.binder; + world.commands.apply(&change, Timestamp(1), &|key| binder.tree(key), &mut world.drafts, &mut world.state, &mut world.ledger); + let states = world.commands.view(&world.surface); + assert_eq!(states.get(&nid("sign-in-button")).mark, Some(Mark::Denied { reason: "no".into() })); + let (_, marked) = session_text(Fixture::F02LoginEffect, &world.drafts, &states); + let (_, plain) = session_text(Fixture::F02LoginEffect, &Drafts::new(), &NodeStates::default()); + let error = Theme::std().colors["thing.error"].clone(); + let strokes = |rendered: &Rendered| rendered.commands.iter().filter(|c| matches!(c, RenderCommand::StrokeRect { color, .. } if *color == error)).count(); + assert_eq!((strokes(&plain), strokes(&marked)), (0, 1)); + let button = xywh(placed(&marked, "sign-in-button")); + let stroke = marked.commands.iter().find_map(|c| match c { + RenderCommand::StrokeRect { rect, color, .. } if *color == error => Some((rect.x, rect.y, rect.w, rect.h)), + _ => None, + }); + assert_eq!(stroke, Some(button)); +} diff --git a/crates/thing-tui/examples/fixture.rs b/crates/thing-tui/examples/fixture.rs index c7a2445..ee019e2 100644 --- a/crates/thing-tui/examples/fixture.rs +++ b/crates/thing-tui/examples/fixture.rs @@ -5,8 +5,8 @@ //! Quit with q or Ctrl+C. The loop is the host's, and so is the clock: the host reads the time, //! the terminal size and the terminal's events, lends core its state port and ids, and draws what //! core hands back through `paint`, `diff` and `Terminal`. Core awaits nothing and reads no clock. -//! Core does not route input yet, so a click or a scroll reaches `frame` and changes nothing; a -//! resize is read as the next frame's viewport. +//! Core routes the pointer: a click on a Button mints its command, a wheel scrolls, a drag on a +//! Slider writes its draft. Keys are not routed yet. A resize is read as the next frame's viewport. use std::io; use std::time::{Duration, SystemTime, UNIX_EPOCH}; diff --git a/crates/thing-tui/tests/pipeline.rs b/crates/thing-tui/tests/pipeline.rs index ad9b61d..9991405 100644 --- a/crates/thing-tui/tests/pipeline.rs +++ b/crates/thing-tui/tests/pipeline.rs @@ -95,11 +95,11 @@ fn a_resize_is_the_next_frames_viewport() { assert_eq!(host.text().as_bytes(), golden.as_slice()); } -/// What it can observe today: a frame handed translated events draws the screen it draws without -/// them, because `Core::frame` routes no input yet. The order translate gives is pinned in -/// tests/input.rs, and what core does with it will be observable when it routes. +/// What it can observe today: a frame handed translated key events draws the screen it draws without +/// them, because `Core::frame` routes no keys yet (the focus cut's). The order translate gives is +/// pinned in tests/input.rs; the pointer's effect is core's tests/input.rs. #[test] -fn a_frame_carrying_events_draws_the_same_screen_while_core_routes_none() { +fn a_frame_carrying_key_events_draws_the_same_screen_while_core_routes_no_keys() { let burst = [ Event::Key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)), Event::Resize(100, 37), diff --git a/crates/thing-tui/tests/screen.rs b/crates/thing-tui/tests/screen.rs index b5f685f..8d4d0cf 100644 --- a/crates/thing-tui/tests/screen.rs +++ b/crates/thing-tui/tests/screen.rs @@ -14,7 +14,7 @@ use thing_core::bind::Binder; use thing_core::diagnostic::Code; use thing_core::layout::{LayoutFrame, Metrics, layout}; use thing_core::port::Ledger; -use thing_core::render::{RenderInput, ScrollOffsets, render}; +use thing_core::render::{RenderInput, ScrollOffsets, Session, render}; use thing_core::resolve::{Limits, resolve}; use thing_core::text::CellMeasure; use thing_core::theme::Theme; @@ -44,7 +44,7 @@ fn screen_of(state: &mut MemState, document: &SurfaceDocument) -> Result<(Screen let laid = layout(&tree, &frame, &mut CellMeasure).unwrap(); let scroll = ScrollOffsets::default(); let theme = Theme::std(); - let input = RenderInput { scale: 1.0, metrics: Metrics::Cells, viewport: frame.viewport, scroll: &scroll, theme: &theme }; + let input = RenderInput { scale: 1.0, metrics: Metrics::Cells, viewport: frame.viewport, scroll: &scroll, theme: &theme, session: Session::EMPTY }; let rendered = render(&tree, &laid, &input, &mut CellMeasure); let mut screen = Screen::new(COLS, ROWS); let painted = paint(&rendered.commands, &mut screen);