From 17a0008d3e9f1c3ba549292318ee6af4191705b1 Mon Sep 17 00:00:00 2001 From: Eureka Date: Sun, 29 Nov 2026 05:16:57 +0000 Subject: [PATCH] Thing 2.0 cut 7b: pointer input (hit-test from placed geometry, press, drag, wheel, render reads the session) (#27) --- .cargo/mutants.toml | 1 + crates/thing-core/src/command/mod.rs | 35 +- crates/thing-core/src/frame.rs | 40 +- crates/thing-core/src/input/drafts.rs | 31 + crates/thing-core/src/input/hit.rs | 102 ++ crates/thing-core/src/input/mod.rs | 14 +- crates/thing-core/src/input/pointer.rs | 210 ++++ crates/thing-core/src/input/tests.rs | 959 ++++++++++++++++++ crates/thing-core/src/render/leaf.rs | 40 +- crates/thing-core/src/render/mod.rs | 41 +- crates/thing-core/tests/command.rs | 26 +- crates/thing-core/tests/frame.rs | 9 +- .../goldens/render-f02-login-effect-busy.txt | 6 + .../tests/goldens/render-f04-form-session.txt | 9 + crates/thing-core/tests/input.rs | 204 ++++ crates/thing-core/tests/render.rs | 127 ++- crates/thing-core/tests/support/mod.rs | 189 ++++ crates/thing-tui/examples/fixture.rs | 4 +- crates/thing-tui/tests/pipeline.rs | 8 +- crates/thing-tui/tests/screen.rs | 4 +- 20 files changed, 1994 insertions(+), 65 deletions(-) create mode 100644 .cargo/mutants.toml create mode 100644 crates/thing-core/src/input/hit.rs create mode 100644 crates/thing-core/src/input/pointer.rs create mode 100644 crates/thing-core/src/input/tests.rs create mode 100644 crates/thing-core/tests/goldens/render-f02-login-effect-busy.txt create mode 100644 crates/thing-core/tests/goldens/render-f04-form-session.txt create mode 100644 crates/thing-core/tests/input.rs create mode 100644 crates/thing-core/tests/support/mod.rs 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/command/mod.rs b/crates/thing-core/src/command/mod.rs index 0777e8d..0b320ca 100644 --- a/crates/thing-core/src/command/mod.rs +++ b/crates/thing-core/src/command/mod.rs @@ -251,8 +251,8 @@ impl Commands { ledger: &mut Ledger, ) -> Vec { let surface = tree.resolved().document().record_key(); - if self.confirming.is_some() { - return vec![refused(&surface, &act.node, "a command is waiting for confirmation")]; + if let Some(waiting) = self.confirming_refusal(&surface, &act.node) { + return vec![waiting]; } let Some(located) = tree.locate(&act.node) else { return vec![refused(&surface, &act.node, "the node is not in the surface")]; @@ -262,15 +262,16 @@ impl Commands { return vec![refused(&surface, &act.node, "the node fires no command for this activation")]; }; if let ActivationKind::Change(value) = &act.kind { + // A control that takes no change holds no value the user did not send: the gate is before the draft. + if let Some(held) = self.refuses_change(tree, &act.node) { + return vec![held]; + } match capture::change(tree, &act.node, located.node, value) { Ok(taken) => drafts.set(&surface, &act.node, taken), Err(detail) => return vec![refused(&surface, &act.node, detail)], } } - if matches!(located.node, Node::Button(_)) && tree.value(&act.node, Field::Enabled) == Some(&Bound::Bool(false)) { - return Vec::new(); - } - if self.busy(&surface, &act.node) { + if self.holds(tree, &act.node) { return Vec::new(); } let Some(decl) = tree.resolved().document().commands.iter().find(|decl| decl.id == command.id) else { @@ -289,6 +290,28 @@ impl Commands { self.begin(prepared, act.node, decl.confirm.as_ref(), now, ids, port, ledger) } + /// Why `node` takes no change now, said as a refusal: a command waits for confirmation, or the + /// control is disabled, or its own invocation waits for a result. A change that is refused writes + /// no draft, so a control that looks disabled never holds a value that was not sent. A press on + /// such a control stays silent (`activate`); a change is an edit the user made and is told. + pub(crate) fn refuses_change(&self, tree: &BoundTree, node: &NodeId) -> Option { + let surface = tree.resolved().document().record_key(); + if let Some(waiting) = self.confirming_refusal(&surface, node) { + return Some(waiting); + } + self.holds(tree, node).then(|| refused(&surface, node, "the control is disabled or waiting for a result")) + } + + fn confirming_refusal(&self, surface: &str, node: &NodeId) -> Option { + self.confirming.is_some().then(|| refused(surface, node, "a command is waiting for confirmation")) + } + + /// Whether `node` is a disabled Button or has an invocation waiting for its result. + fn holds(&self, tree: &BoundTree, node: &NodeId) -> bool { + let disabled = tree.value(node, Field::Enabled) == Some(&Bound::Bool(false)); + disabled || self.busy(&tree.resolved().document().record_key(), node) + } + /// Answer the command waiting on confirmation. Accepting mints with the captures taken at the /// user's action; rejecting drops it and draws no id. pub fn confirm(&mut self, accept: bool, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort, ledger: &mut Ledger) { diff --git a/crates/thing-core/src/frame.rs b/crates/thing-core/src/frame.rs index 8584278..57cd035 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,9 +122,12 @@ 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; + // Input is judged entirely against the frame the user saw: its geometry and the values bound + // into it. Nothing of this frame (the surface it switches to, the provider updates it drains, + // the tree it binds) is in place yet, so no event reads a world the user did not look at. + let routed = self.route(&events, scale, now, ports.ids, port); let mut changes = Vec::new(); if self.wanted != self.shown { self.switch(port, &mut changes); @@ -129,6 +135,7 @@ impl Core { changes.extend(port.drain()); let mut diagnostics = std::mem::take(&mut self.notes); + diagnostics.extend(routed); let mut effects = Vec::new(); let mut rebound = false; for change in &changes { @@ -218,6 +225,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 +263,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 +283,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..e114275 --- /dev/null +++ b/crates/thing-core/src/input/hit.rs @@ -0,0 +1,102 @@ +//! 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 scroll or +//! clip of its own: render already did, and `Placed::visible` is what the user could see. `k` (device px +//! per logical px, from `render::device_scale`) only puts point and edges on the device grid layout laid. +//! 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 a press can activate: a control, or a modal's scrim (its dismissal). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Control { + Button, + Toggle, + Slider, + Select, + TextInput, + Scrim, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct Target { + pub(super) node: NodeId, + pub(super) 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), +} + +/// A coordinate on the device grid, held to 1/1024 px. Layout lays whole device pixels, render divides +/// them by the scale, and a pointer is that logical coordinate again: `k` times it is the device pixel +/// only up to the rounding error of dividing and multiplying back, which at a fractional scale is enough to +/// put the first pixel past an edge inside it. The grid is coarser than that error and finer than any +/// pixel, so an edge and a pointer that mean the same device position compare equal. +fn on_device(logical: f32, k: f32) -> f32 { + const GRID: f32 = 1024.0; + (logical * k * GRID).round() / GRID +} + +/// Half-open on the device grid: a node's right and bottom edges belong to its neighbour. +fn covers(rect: Rect, (x, y): (f32, f32), k: f32) -> bool { + let (x, y) = (on_device(x, k), on_device(y, k)); + x >= on_device(rect.x, k) && x < on_device(rect.x + rect.w, k) && y >= on_device(rect.y, k) && y < on_device(rect.y + rect.h, k) +} + +pub(super) fn reach(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: 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); + // A non-modal overlay's root is only where its content is anchored: it is the viewport or the + // anchor's rect, not something drawn, so a press that misses the content goes on through it. + let transparent = |i: usize| laid.nodes[i].parent.is_none() && matches!(index.get(&laid.nodes[i].id), Some(Node::Overlay(_))); + let top = rendered.placed.iter().enumerate().skip(floor).rev().find(|(i, placed)| !transparent(*i) && placed.visible.is_some_and(|seen| covers(seen, point, k))); + match (top, modal) { + (Some((i, _)), _) => Some(Reach::Node(i)), + (None, Some(m)) => Some(Reach::Scrim(m)), + (None, None) => None, + } +} + +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(super) fn target(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: f32) -> Option { + let mut at = match reach(rendered, laid, index, point, k)? { + 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..ea8b60b 100644 --- a/crates/thing-core/src/input/mod.rs +++ b/crates/thing-core/src/input/mod.rs @@ -1,8 +1,16 @@ -//! 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; +mod hit; +mod pointer; -pub use drafts::Drafts; +#[cfg(test)] +mod tests; + +pub use drafts::{Drafts, current}; pub use event::{InputEvent, Key, Modifiers, PointerButton, WheelUnit}; +pub(crate) use pointer::{Input, Owners, 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..7bebfa2 --- /dev/null +++ b/crates/thing-core/src/input/pointer.rs @@ -0,0 +1,210 @@ +//! 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, device_scale}; +use crate::time::Timestamp; + +/// The last good frame and how it was drawn: what every event is judged against. +pub(crate) struct Seen<'a> { + pub(crate) rendered: &'a Rendered, + pub(crate) laid: &'a LaidTree, + pub(crate) tree: &'a BoundTree, + pub(crate) 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(crate) scale: f32, + /// The theme's body text size in logical px: what one wheel line is in Pixels. A guess, unmeasured. + pub(crate) line: f32, +} + +impl Seen<'_> { + /// Device px per logical px, which is what a pointer is multiplied by to land on laid pixels. + fn k(&self) -> f32 { + device_scale(self.metrics, self.scale) + } +} + +/// The owners an event writes through: activation, drafts and scroll positions. +pub(crate) struct Owners<'a> { + pub(crate) commands: &'a mut Commands, + pub(crate) drafts: &'a mut Drafts, + pub(crate) scroll: &'a mut ScrollOffsets, + pub(crate) ids: &'a mut dyn IdSource, + pub(crate) port: &'a mut dyn StatePort, + pub(crate) 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)] +struct Pointer { + press: Option, +} + +/// The routes every pointer and wheel event takes; it owns the `Pointer`. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) 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(crate) 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(crate) 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(crate) 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, .. } => return self.down(*at, seen, owners, &surface), + InputEvent::PointerMove { at, .. } => return self.drag(*at, seen, owners, &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) -> Vec { + // A press never starts over another: the one in progress ends first. + self.cancel(surface, owners.drafts); + let index = seen.tree.index(); + let mut said = Vec::new(); + self.pointer.press = target(seen.rendered, seen.laid, &index, at, seen.k()).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))?; + // A slider that takes no change takes no press: nothing is drafted, so nothing is left unsent. + if let Some(held) = owners.commands.refuses_change(seen.tree, &hit.node) { + said.push(held); + return None; + } + 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 }) + } + _ => Some(Press::Target(hit)), + }); + said + } + + fn drag(&mut self, at: (f32, f32), seen: &Seen<'_>, owners: &mut Owners<'_>, surface: &str) -> Vec { + let Some(Press::Drag { node, .. }) = &self.pointer.press else { return Vec::new() }; + let index = seen.tree.index(); + let Some(Node::Slider(slider)) = index.get(node) else { return Vec::new() }; + if let Some(held) = owners.commands.refuses_change(seen.tree, node) { + return vec![held]; + } + if let Some(value) = placed_rect(seen.rendered, node).and_then(|rect| slider_value(slider, rect, at.0)) { + owners.drafts.set(surface, node, InputValue::Number(NumberValue { value })); + } + Vec::new() + } + + 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, seen.k()).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 })) } + } + // A Select's chooser and a TextInput's editing are not here: a press on them does nothing, and + // does not fall through to a control around them. A Slider's press is a `Drag`, never a target. + 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, seen.k()) else { return }; + let to_device = seen.k(); + let line = match seen.metrics { + Metrics::Cells => 1.0, + Metrics::Pixels => 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/input/tests.rs b/crates/thing-core/src/input/tests.rs new file mode 100644 index 0000000..a70a023 --- /dev/null +++ b/crates/thing-core/src/input/tests.rs @@ -0,0 +1,959 @@ +//! Pointer input: a press, a drag and a wheel reach the node the user saw drawn, in Pixels (at several +//! 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. These tests live in the crate because `Input`, `Seen` and `Owners` +//! are not public; for the same reason they cannot use `thing-testkit`'s state port (its types name the +//! library build of this crate, not this test build), so `Port`, `Counter` and `Boxes` below are the three +//! small doubles they need. The contract documents they press are `tests/support`, shared with the host tests. + +use std::collections::HashMap; + +use thing_contract::*; +use thing_testkit::build::*; + +use super::hit::{Reach, Target, reach, target}; +use super::pointer::{Owners, Seen}; +use super::{Drafts, Input, InputEvent, Modifiers, PointerButton, WheelUnit}; +use crate::bind::{Binder, BoundTree, Instance}; +use crate::command::Commands; +use crate::diagnostic::{Code, Diagnostic}; +use crate::layout::{Constraint, LaidTree, LayoutFrame, Leaf, Measure, Metrics, Rect, TextLayout, TextRequest, layout}; +use crate::port::{Address, Change, Entry, IdSource, Interest, Ledger, Lookup, Prefix, Record, StatePort, StateValue, SubscriptionId}; +use crate::render::{RenderInput, Rendered, ScrollOffsets, Session, render}; +use crate::resolve::{Limits, resolve}; +use crate::theme::Theme; +use crate::time::Timestamp; + +#[path = "../../tests/support/mod.rs"] +mod support; +use support::*; + +/// Records by address, the interests asked of the port and the changes queued for a drain. +#[derive(Clone, Default)] +struct Port { + records: HashMap, + interests: Vec<(SubscriptionId, Interest)>, + queue: Vec, +} + +impl Port { + fn new() -> Self { + Self::default() + } + + fn put(&mut self, provider: &ProviderId, document: &SurfaceDocument) { + let address = Address { provider: provider.clone(), schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME), key: RecordKey::new(document.record_key()) }; + self.records.insert(address.clone(), Entry { address, record: Record::Surface(document.clone()) }); + } + + fn put_item(&mut self, provider: &ProviderId, id: &str, title: &str) { + let address = Address { provider: provider.clone(), schema: SchemaId::new("gamecult.thing.test.item.v1"), key: RecordKey::new(id) }; + let value = StateValue::Record(vec![("Id".into(), StateValue::Text(id.into())), ("Title".into(), StateValue::Text(title.into()))]); + let record = Record::State { schema: address.schema.clone(), value }; + self.records.insert(address.clone(), Entry { address, record }); + } +} + +impl StatePort for Port { + fn read(&self, address: &Address) -> Lookup { + self.records.get(address).map_or(Lookup::Absent, |entry| Lookup::Present(entry.clone())) + } + + fn list(&self, prefix: &Prefix) -> Vec { + let mut held: Vec<_> = self.records.values().filter(|entry| prefix.matches(&entry.address)).collect(); + held.sort_by(|a, b| a.address.key.as_str().cmp(b.address.key.as_str())); + held.into_iter().map(|entry| Lookup::Present(entry.clone())).collect() + } + + fn subscribe(&mut self, interest: Interest) -> SubscriptionId { + let id = SubscriptionId(self.interests.len() as u64); + self.interests.push((id, interest)); + id + } + + fn unsubscribe(&mut self, id: SubscriptionId) { + self.interests.retain(|(held, _)| *held != id); + } + + fn drain(&mut self) -> Vec { + std::mem::take(&mut self.queue) + } +} + +/// Ids that differ by a counter. +#[derive(Default)] +struct Counter(u128); + +impl IdSource for Counter { + fn fill(&mut self, bytes: &mut [u8; 16]) { + self.0 += 1; + *bytes = self.0.to_be_bytes(); + } +} + +/// Fixed control sizes and no text: these documents hold boxes and controls only. +struct Boxes { + cells: bool, +} + +impl Measure for Boxes { + fn measure(&mut self, leaf: &Leaf, _: Constraint) -> (f32, f32) { + let control = |w: f32, h: f32| if self.cells { (w / 8.0, 1.0) } else { (w, h) }; + match leaf { + Leaf::TextInput { multiline, .. } => control(200.0, if *multiline { 72.0 } else { 24.0 }), + Leaf::Toggle { .. } => control(40.0, 20.0), + Leaf::Slider { .. } => control(160.0, 20.0), + Leaf::Select { .. } => control(160.0, 24.0), + Leaf::Text { .. } | Leaf::Image { .. } => (0.0, 0.0), + } + } + + fn text(&mut self, _: &TextRequest, _: f32) -> TextLayout { + TextLayout { lines: vec![] } + } +} + +/// 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) -> Boxes { + Boxes { cells: metrics == Metrics::Cells } +} + +fn row_id(item: &str, node: &str) -> NodeId { + NodeId::new(format!("{}{node}", Instance::scope_prefix("rows", item, false))) +} + +fn feed() -> Port { + let mut state = Port::new(); + for n in 0..20 { + let id = format!("item-{n:04}"); + state.put_item(&ProviderId::new(FEED), &id, &id); + } + state +} + +// ----- 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: Port, + ledger: Ledger, + input: Input, + commands: Commands, + drafts: Drafts, + scroll: ScrollOffsets, + ids: Counter, + now: Timestamp, +} + +impl Rig { + fn new(mut state: Port, 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: Counter::default(), + 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() +} + +/// Device px per logical px, as input holds it. +fn device_k(rig: &Rig) -> f32 { + match rig.metrics { + Metrics::Pixels => rig.scale, + Metrics::Cells => 1.0, + } +} + +/// The node, or the modal whose scrim it is, that a point reaches. +fn hit_node(rig: &Rig, at: (f32, f32)) -> Option { + match reach(&rig.rendered, &rig.laid, &index_of(rig), at, device_k(rig))? { + Reach::Node(i) | Reach::Scrim(i) => Some(rig.laid.nodes[i].id.as_str().to_string()), + } +} + +fn rig_target(rig: &Rig, at: (f32, f32)) -> Option { + target(&rig.rendered, &rig.laid, &index_of(rig), at, device_k(rig)) +} + +// ----- 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 rig = Rig::new(Port::new(), &target_surface(), mode); + let (target, board) = (rig.rect("target"), rig.rect("board")); + // The far corner of the target. + 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(Port::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!(rig_target(&rig, edge).is_some_and(|hit| hit.node.as_str() == "b"), "{mode:?}"); + let last = (a.x + 0.5, b.y - 0.25); + assert!(rig_target(&rig, last).is_some_and(|hit| hit.node.as_str() == "a"), "{mode:?}"); + let under = (b.x + 0.5, b.y + b.h); + assert_eq!(rig_target(&rig, under), None, "{mode:?}: the bottom edge is outside"); + let beyond = (a.x + a.w, a.y + 0.5); + assert_ne!(rig_target(&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 documents = [ + (modal_surface(), Port::new()), + (rows_surface(), feed()), + (controls_surface(), Port::new()), + (nested_surface(), Port::new()), + (clip_surface(), Port::new()), + (nonmodal_surface(Anchor::Viewport), Port::new()), + (target_surface(), Port::new()), + ]; + for mode in MODES { + for (document, state) in &documents { + let rig = Rig::new(state.clone(), 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 at = inside(seen); + let hit = hit_node(&rig, at).expect("something is there"); + let reached = rig.rendered.placed.iter().find(|p| p.id.as_str() == hit).unwrap(); + 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:?} {}: {hit} reached at {at:?} is not drawn there", document.label.as_str()); + } + } + } +} + +#[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(Port::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!(rig_target(&rig, below), None, "{mode:?}"); + assert_ne!(hit_node(&rig, below).as_deref(), Some("tall"), "{mode:?}"); + // Inside the clip it is hit. + let inside_clip = rig_target(&rig, inside(frame)); + assert_eq!(inside_clip.map(|hit| hit.node.as_str().to_string()).as_deref(), Some("tall"), "{mode:?}"); + } +} + +// ----- the edge of a node, at a scale that does not divide ----- + +/// Rows of odd widths and heights, so edges fall between whole logical px at a fractional scale. +fn seam_surface() -> SurfaceDocument { + let row = |id: &str, h: f64, widths: &[f64]| { + let mut row = column(id, None, Overflow::Visible, widths.iter().enumerate().map(|(i, w)| fixed(&format!("{id}-{i}"), *w, h)).collect()); + if let Node::Box(b) = &mut row { + b.style.direction = Direction::Row; + b.style.size = size2(Dimension::Percent(Scalar { value: 100.0 }), px(h)); + b.style.justify_content = ContentAlign::Start; + } + row + }; + surface( + column("root", None, Overflow::Visible, vec![ + row("r0", 7.0, &[9.0, 14.0, 5.0, 31.0]), + row("r1", 13.0, &[11.0, 3.0, 17.0]), + row("r2", 5.0, &[6.0, 6.0, 6.0, 6.0, 7.0]), + row("r3", 19.0, &[23.0, 29.0, 13.0]), + ]), + vec![], + ) +} + +#[test] +fn the_first_device_pixel_past_a_nodes_right_or_bottom_edge_is_not_the_node_at_every_scale() { + let scales = [1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0]; + for mode in scales.map(|scale| (Metrics::Pixels, scale)) { + let rig = Rig::new(Port::new(), &seam_surface(), mode); + let k = device_k(&rig); + let mut leaves = 0; + for node in rig.laid.nodes.iter().filter(|node| node.id.as_str().contains('-')) { + leaves += 1; + let (id, r) = (node.id.as_str(), node.rect); + assert!(r.w >= 1.0 && r.h >= 1.0 && r.x.fract() == 0.0 && r.y.fract() == 0.0, "{mode:?} {id}: laid in whole device px, {r:?}"); + // Device pixels, as a host at this scale reports a pointer: the pixel's corner and its centre. + let at = |dx: f32, dy: f32, off: f32| ((dx + off) / k, (dy + off) / k); + for off in [0.0, 0.5] { + let last = at(r.x + r.w - 1.0, r.y + r.h - 1.0, off); + assert_eq!(hit_node(&rig, last).as_deref(), Some(id), "{mode:?} {id} the last pixel of the node, +{off}"); + let right = at(r.x + r.w, r.y, off); + assert_ne!(hit_node(&rig, right).as_deref(), Some(id), "{mode:?} {id} the pixel right of the node, +{off}"); + let below = at(r.x, r.y + r.h, off); + assert_ne!(hit_node(&rig, below).as_deref(), Some(id), "{mode:?} {id} the pixel below the node, +{off}"); + let first = at(r.x, r.y, off); + assert_eq!(hit_node(&rig, first).as_deref(), Some(id), "{mode:?} {id} the first pixel of the node, +{off}"); + } + } + assert_eq!(leaves, 15, "{mode:?}"); + } +} + +// ----- a non-modal overlay ----- + +fn nonmodal_surface(anchor: Anchor) -> SurfaceDocument { + let pop = Node::Overlay(OverlayNode { common: common("pop"), anchor, modal: false, dismiss: command("dismiss"), children: vec![button("pop-button", "inside", 80.0, 48.0)] }); + surface( + column("root", None, Overflow::Visible, vec![button("behind", "behind", 320.0, 48.0), button("other", "other", 320.0, 48.0), pop]), + vec![decl("behind", &[]), decl("other", &[]), decl("inside", &[]), decl("dismiss", &[])], + ) +} + +#[test] +fn a_press_passes_through_a_non_modal_overlays_root_to_what_lies_beneath_and_its_own_content_still_takes_it() { + let node = Anchor::Node(AnchorNode { node: nid("behind") }); + for mode in MODES { + for anchor in [Anchor::Viewport, node.clone()] { + let mut rig = Rig::new(Port::new(), &nonmodal_surface(anchor.clone()), mode); + let (behind, other, inner) = (rig.rect("behind"), rig.rect("other"), rig.rect("pop-button")); + let (a, b) = ((behind.x + behind.w - 0.5, behind.y + 0.5), (other.x + other.w - 0.5, other.y + 0.5)); + for at in [a, b] { + assert!(!(at.0 >= inner.x && at.0 < inner.x + inner.w && at.1 >= inner.y && at.1 < inner.y + inner.h), "{mode:?} {anchor:?}: {at:?} is clear of the overlay's content"); + assert_eq!(hit_node(&rig, at).as_deref().map(|id| id != "pop"), Some(true), "{mode:?} {anchor:?}: the overlay's root is not what is hit at {at:?}"); + } + rig.click(a); + assert_eq!(commands_of(&rig.minted()), ["behind"], "{mode:?} {anchor:?}: the press reaches the anchor or the node under the viewport overlay"); + rig.click(b); + assert_eq!(commands_of(&rig.minted()), ["other"], "{mode:?} {anchor:?}"); + // The overlay's own content is drawn over them and takes its press. + rig.click(inside(inner)); + assert_eq!(commands_of(&rig.minted()), ["inside"], "{mode:?} {anchor:?}"); + } + } +} + +#[test] +fn a_wheel_over_a_non_modal_overlays_root_reaches_the_pane_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("pop", false, vec![fixed("pop-body", 8.0, 16.0)])]), vec![decl("dismiss", &[])]); + for mode in MODES { + let mut rig = Rig::new(Port::new(), &document, mode); + let pane = rig.rect("pane"); + rig.send(wheel((pane.x + pane.w - 0.5, pane.y + pane.h - 0.5), (0.0, 16.0), WheelUnit::Units)); + assert!(rig.offset("pane").is_some_and(|o| o.1 > 0.0), "{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(Port::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(Port::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(Port::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!(rig_target(&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(Port::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(Port::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(Port::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(Port::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(Port::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(Port::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(Port::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, crate::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(Port::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 is a change to a control with an invocation waiting: it is refused and says so, it + // fires nothing more, and it leaves the draft that was sent (a busy control holds no unsent value). + let said = rig.click(flag); + assert_eq!(said.iter().map(|d| (d.code, d.node.as_ref().map(NodeId::as_str))).collect::>(), vec![(Code::ActivationRefused, Some("flag"))], "{mode:?}"); + assert_eq!(rig.minted(), vec![], "{mode:?}"); + assert_eq!(rig.draft("flag"), Some(InputValue::Bool(BoolValue { value: true })), "{mode:?}"); + } +} + +#[test] +fn a_slider_drag_writes_snapped_drafts_and_commits_once_wherever_it_is_released() { + for mode in MODES { + let mut rig = Rig::new(Port::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 { + crate::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(Port::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 rig = Rig::new(Port::new(), &fields_surface(), mode); + for id in ["field", "choice"] { + 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(Port::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")); + } +} + +// ----- a control that takes no change holds no unsent value ----- + +fn result_change(sent: &CommandInvocation, clear: bool) -> Change { + let result = CommandResult::completed(sent, seq(1), None, clear, None); + let address = Address { provider: ProviderId::new(PROVIDER), schema: SchemaId::new(CommandResult::SCHEMA_NAME), key: RecordKey::new(result.record_key()) }; + Change::Upsert(Entry { address, record: Record::Result(result) }) +} + +fn refusals(said: &[Diagnostic]) -> Vec<(Code, Option<&str>)> { + said.iter().map(|d| (d.code, d.node.as_ref().map(NodeId::as_str))).collect() +} + +#[test] +fn a_slider_that_waits_for_its_result_takes_no_press_or_drag_and_a_completion_leaves_no_stray_draft() { + for mode in MODES { + let mut rig = Rig::new(Port::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.3))); + rig.send(up(along(0.3))); + let sent = rig.minted().remove(0); + assert_eq!(rig.draft("level"), value(30.0), "{mode:?}"); + // The slider waits: a second press and its drag are refused, say so, and write nothing. + assert_eq!(refusals(&rig.send(down(along(0.8)))), vec![(Code::ActivationRefused, Some("level"))], "{mode:?}"); + assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: the press wrote nothing"); + rig.send(mv(along(0.9))); + assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: a refused press starts no drag"); + assert_eq!(rig.send(up(along(0.9))), vec![], "{mode:?}"); + assert_eq!(rig.minted(), vec![], "{mode:?}"); + // The result clears the draft that was sent, and nothing else is left drawn on the slider. + let tree = &rig.tree; + rig.commands.apply(&result_change(&sent, true), Timestamp(5), &|_| Some(tree), &mut rig.drafts, &mut rig.state, &mut rig.ledger); + assert_eq!(rig.draft("level"), None, "{mode:?}"); + } +} + +#[test] +fn a_toggle_pressed_while_it_waits_is_refused_and_a_completion_leaves_the_provider_true() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &controls_surface(), mode); + let flag = inside(rig.rect("flag")); + rig.click(flag); + let sent = rig.minted().remove(0); + assert_eq!(refusals(&rig.click(flag)), vec![(Code::ActivationRefused, Some("flag"))], "{mode:?}"); + let tree = &rig.tree; + rig.commands.apply(&result_change(&sent, true), Timestamp(5), &|_| Some(tree), &mut rig.drafts, &mut rig.state, &mut rig.ledger); + assert_eq!(rig.draft("flag"), None, "{mode:?}: nothing survives to show a checked box the provider does not hold"); + } +} + +#[test] +fn a_slider_press_while_a_command_waits_for_confirmation_writes_no_draft() { + for mode in MODES { + let mut document = controls_surface(); + document.commands.iter_mut().find(|c| c.id.as_str() == "go").unwrap().confirm = Some("Sure?".into()); + let mut rig = Rig::new(Port::new(), &document, mode); + rig.click(inside(rig.rect("a"))); + assert!(rig.commands.confirming().is_some(), "{mode:?}"); + let track = rig.rect("level"); + let said = rig.send(down((track.x + 0.5 * track.w, track.y + 0.5))); + assert_eq!(refusals(&said), vec![(Code::ActivationRefused, Some("level"))], "{mode:?}"); + assert_eq!((rig.draft("level"), rig.drafts.is_empty()), (None, true), "{mode:?}"); + } +} + +#[test] +fn input_other_than_the_pointer_changes_nothing() { + let mut rig = Rig::new(Port::new(), &controls_surface(), MODES[0]); + let before = (rig.rendered.clone(), rig.drafts.len()); + for event in [ + InputEvent::Key { key: crate::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)); +} + +#[test] +fn a_slider_snaps_from_its_own_minimum_and_follows_its_own_track() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &lone_slider(20.0, 120.0, 10.0), mode); + let track = rig.rect("level"); + assert!(track.x > 0.0, "{mode:?}: the track does not start at the root's edge"); + 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.0))); + assert_eq!(rig.draft("level"), value(20.0), "{mode:?}: the track's left edge is the minimum"); + rig.send(mv(along(0.47))); + assert_eq!(rig.draft("level"), value(70.0), "{mode:?}: 20 + 47 = 67 snaps to 70 from 20"); + rig.send(mv(along(1.0))); + assert_eq!(rig.draft("level"), value(120.0), "{mode:?}"); + // A move that is not a position is not a value. + rig.send(mv((f32::NAN, track.y))); + assert_eq!(rig.draft("level"), value(120.0), "{mode:?}"); + } +} + +#[test] +fn a_track_that_shrinks_to_nothing_mid_drag_leaves_the_draft_as_it_was() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &controls_surface(), mode); + let track = rig.rect("level"); + let value = |v: f64| Some(InputValue::Number(NumberValue { value: v })); + rig.send(down((track.x + 0.5 * track.w, track.y + 0.5))); + assert_eq!(rig.draft("level"), value(50.0), "{mode:?}"); + // The surface shrinks under the pointer: the slider's rect is now zero wide. + for placed in rig.rendered.placed.iter_mut().filter(|placed| placed.id.as_str() == "level") { + placed.rect.w = 0.0; + } + // At the track's left edge (0 over 0) and past it (n over 0): neither is a value. + for x in [track.x, track.x + 10.0] { + rig.send(mv((x, track.y + 0.5))); + assert_eq!(rig.draft("level"), value(50.0), "{mode:?}: a move over a zero-width track at {x}"); + } + rig.send(up((track.x, track.y))); + let minted = rig.minted(); + assert_eq!(minted.len(), 1, "{mode:?}"); + assert_eq!(minted[0].captured[0].value, InputValue::Number(NumberValue { value: 50.0 }), "{mode:?}"); + } +} + +#[test] +fn a_slider_with_no_range_or_a_step_of_zero_is_handled_by_what_it_declares() { + for mode in MODES { + for (min, max) in [(5.0, 5.0), (0.0, f64::INFINITY), (9.0, 3.0)] { + let mut rig = Rig::new(Port::new(), &lone_slider(min, max, 1.0), mode); + let at = inside(rig.rect("level")); + rig.click(at); + assert_eq!((rig.draft("level"), rig.minted()), (None, vec![]), "{mode:?} {min}..{max}"); + } + // No step: the raw position, unsnapped. + let mut rig = Rig::new(Port::new(), &lone_slider(0.0, 100.0, 0.0), mode); + let track = rig.rect("level"); + rig.send(down((track.x + 0.25 * track.w, track.y + 0.5))); + assert_eq!(rig.draft("level"), Some(InputValue::Number(NumberValue { value: 25.0 })), "{mode:?}"); + } +} + +#[test] +fn a_press_on_a_text_input_or_a_select_does_not_fall_through_to_the_button_around_it() { + let (input, select) = fields(); + let card = Node::Button(ButtonNode { + common: common("card"), + content: vec![fixed("pad", 160.0, 16.0), input, select], + on_activate: command("go"), + enabled: lit_bool(true), + }); + for mode in MODES { + let document = surface(column("root", None, Overflow::Visible, vec![card.clone()]), vec![decl("go", &[])]); + let mut rig = Rig::new(Port::new(), &document, mode); + for id in ["field", "choice"] { + let r = rig.rect(id); + assert!(r.w >= 1.0 && r.h >= 1.0, "{mode:?} {id}"); + assert_eq!(rig.click(inside(r)), vec![], "{mode:?} {id}"); + } + assert_eq!(rig.minted(), vec![], "{mode:?}: the card around them was not pressed"); + // The card itself still is. + rig.click(inside(rig.rect("pad"))); + assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}"); + } +} + +#[test] +fn a_wheel_that_is_not_a_number_or_runs_on_a_bad_scale_is_ignored_or_taken_at_one() { + let mut rig = Rig::new(Port::new(), &nested_surface(), (Metrics::Pixels, 1.5)); + let over = inside(rig.rect("inner")); + // The scale the host gave is not usable: the offset is the wheel's units as they are. + for bad in [0.0, f32::INFINITY, f32::NAN, -2.0] { + rig.scroll = ScrollOffsets::default(); + rig.scale = bad; + rig.send(wheel(over, (0.0, 10.0), WheelUnit::Units)); + assert_eq!(rig.offset("inner"), Some((0.0, 10.0)), "scale {bad}"); + } + // A delta that is not a number moves nothing, and does not reset what is scrolled. + rig.scale = 1.5; + rig.scroll.set(nid("inner"), (0.0, 30.0)); + for bad in [f32::NAN, f32::INFINITY] { + rig.send(wheel(over, (0.0, bad), WheelUnit::Units)); + rig.send(wheel(over, (bad, 0.0), WheelUnit::Units)); + assert_eq!(rig.offset("inner"), Some((0.0, 30.0)), "delta {bad}"); + } +} + +#[test] +fn a_wheel_scrolls_the_horizontal_axis_by_its_own_delta() { + let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("wide", 400.0, 400.0)]); + let document = surface(column("root", None, Overflow::Visible, vec![pane]), vec![]); + for mode in MODES { + let mut rig = Rig::new(Port::new(), &document, mode); + let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 }; + let over = inside(rig.rect("pane")); + assert!(rig.max_scroll("pane").0 > 0.0 && rig.max_scroll("pane").1 > 0.0, "{mode:?}"); + rig.send(wheel(over, (8.0, 4.0), WheelUnit::Units)); + assert_eq!(rig.offset("pane"), Some((8.0 * k, 4.0 * k)), "{mode:?}"); + rig.send(wheel(over, (-2.0, 0.0), WheelUnit::Units)); + assert_eq!(rig.offset("pane"), Some((6.0 * k, 4.0 * k)), "{mode:?}"); + } +} 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..3f5d1bc 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); @@ -50,12 +72,18 @@ pub struct Rendered { pub diagnostics: Vec, } +/// Device px per logical px: the scale in Pixels when it is finite and positive, else 1; always 1 in +/// Cells. The one owner of the rule: render divides by it, and input multiplies by it. +pub(crate) fn device_scale(metrics: Metrics, scale: f32) -> f32 { + match metrics { + Metrics::Pixels if scale.is_finite() && scale > 0.0 => scale, + _ => 1.0, + } +} + pub fn render(tree: &BoundTree, laid: &LaidTree, input: &RenderInput, text: &mut dyn Measure) -> Rendered { let nodes = tree.index(); - let k = match input.metrics { - Metrics::Pixels if input.scale.is_finite() && input.scale > 0.0 => input.scale, - _ => 1.0, - }; + let k = device_scale(input.metrics, input.scale); let mut ids = HashMap::new(); for (i, node) in laid.nodes.iter().enumerate() { ids.entry(&node.id).or_insert(i); @@ -195,6 +223,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/command.rs b/crates/thing-core/tests/command.rs index fac8a63..aa23642 100644 --- a/crates/thing-core/tests/command.rs +++ b/crates/thing-core/tests/command.rs @@ -1198,20 +1198,18 @@ fn tg_surface() -> SurfaceDocument { } #[test] -fn a_completion_clears_the_drafts_it_captured_and_a_newer_edit_survives() { - for newer in [Some(false), None] { - let mut rig = Rig::new(MemState::new(), &tg_surface()); - let mut ids = SeqIds::new(); - rig.act(&nid("t"), ActivationKind::Change(bool_value(true)), PINNED_NOW, &mut ids); - let first = rig.commands.take_outbound().pop().expect("minted"); - if let Some(value) = newer { - // The node is busy: this edit mints nothing, and it is the draft now. - rig.act(&nid("t"), ActivationKind::Change(bool_value(value)), at(10), &mut ids); - assert!(rig.commands.take_outbound().is_empty()); - } - rig.feed(&completed(&first, 1, true, None), at(20)); - assert_eq!(rig.draft(&nid("t")), newer.map(bool_value), "newer edit {newer:?}"); - } +fn a_change_to_a_node_that_waits_is_refused_writes_no_draft_and_the_completion_clears_what_was_sent() { + let mut rig = Rig::new(MemState::new(), &tg_surface()); + let mut ids = SeqIds::new(); + rig.act(&nid("t"), ActivationKind::Change(bool_value(true)), PINNED_NOW, &mut ids); + let first = rig.commands.take_outbound().pop().expect("minted"); + // The node waits for its result: this edit is refused and mints nothing, and it is not a draft. + let said = rig.act(&nid("t"), ActivationKind::Change(bool_value(false)), at(10), &mut ids); + assert_eq!(said.iter().map(|d| d.code).collect::>(), vec![Code::ActivationRefused]); + assert!(rig.commands.take_outbound().is_empty()); + assert_eq!(rig.draft(&nid("t")), Some(bool_value(true))); + rig.feed(&completed(&first, 1, true, None), at(20)); + assert_eq!(rig.draft(&nid("t")), None); } #[test] 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..8d61993 --- /dev/null +++ b/crates/thing-core/tests/input.rs @@ -0,0 +1,204 @@ +//! Pointer input through `Core::frame`, the one way a host reaches it: a click lands on the node the +//! user saw drawn, in the frame the user saw it, and mints through the one activation primitive. The +//! routes themselves (hit-testing, press state, the wheel) are tested in the crate, where they are visible. +//! Every test derives its points from the geometry render placed. Ordering is forced: a test that +//! depends on an order puts the events in one frame or in two, and says which. + +mod support; + +use support::*; +use thing_contract::*; +use thing_core::bind::{Binder, Instance}; +use thing_core::input::{InputEvent, Modifiers, PointerButton, WheelUnit}; +use thing_core::layout::{LayoutFrame, Metrics, Rect, layout}; +use thing_core::port::Ledger; +use thing_core::render::{Placed, RenderInput, 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, Settings}; + +/// 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(), + } +} + +fn row_id(item: &str, node: &str) -> NodeId { + NodeId::new(format!("{}{node}", Instance::scope_prefix("rows", item, false))) +} + +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 +} + +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 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() +} + +/// What render placed for `document` at rest: where the host will click, from the public stages. +struct Placement(Vec); + +fn placement(mut state: MemState, document: &SurfaceDocument, (metrics, scale): (Metrics, f32)) -> Placement { + 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"); + let laid = layout(tree, &LayoutFrame { viewport: viewport(metrics), scale, metrics }, &mut measure(metrics)).expect("lays out"); + let theme = Theme::std(); + let input = RenderInput { scale, metrics, viewport: viewport(metrics), scroll: &ScrollOffsets::default(), theme: &theme, session: Session::EMPTY }; + Placement(render(tree, &laid, &input, &mut measure(metrics)).placed) +} + +impl Placement { + fn rect(&self, id: &str) -> Rect { + self.0.iter().find(|placed| placed.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}")).rect + } +} + +// ----- 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 = placement(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 = placement(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_click_is_judged_against_the_values_the_user_saw_not_the_ones_the_provider_wrote_in_the_same_frame() { + for mode in MODES { + let fixture = Fixture::F04Form; + let mut state = MemState::from_fixture(fixture); + state::script(fixture, &mut state); + let document = fixture.load().surfaces.remove(0); + let mut seen = MemState::from_fixture(fixture); + state::script(fixture, &mut seen); + let toggle = inside(placement(seen, &document, mode).rect("enabled")); + let mut host = Host::new(state, &document, mode); + // The user saw `enabled` checked. In the frame they click it the provider writes it unchecked. + host.state.put_state(&ProviderId::new("provider.settings"), "current", &Settings { enabled: false, volume: 40.0, theme: "dark".into() }); + let output = host.frame(vec![down(toggle), up(toggle)]); + assert_eq!(output.outbound.len(), 1, "{mode:?}"); + assert_eq!(output.outbound[0].captured[0].value, InputValue::Bool(BoolValue { value: false }), "{mode:?}: they unchecked what they saw checked"); + } +} + +#[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 = placement(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()); +} diff --git a/crates/thing-core/tests/render.rs b/crates/thing-core/tests/render.rs index 1ab0153..bbaf2d1 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,120 @@ 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::Number(NumberValue { value: 9999.0 })); + let (text, drawn) = session_text(Fixture::F04Form, &drafts, &NodeStates::default()); + golden::check(&golden_dir(), "render-f04-form-session.txt", text.as_bytes()); + // A number input's draft is its number or the text typed: both are drawn as the text they are. + drafts.set(&surface, &nid("port"), InputValue::Text(TextValue { value: "9999".into() })); + assert_eq!(session_text(Fixture::F04Form, &drafts, &NodeStates::default()).1.commands, drawn.commands); + 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-core/tests/support/mod.rs b/crates/thing-core/tests/support/mod.rs new file mode 100644 index 0000000..1e0effa --- /dev/null +++ b/crates/thing-core/tests/support/mod.rs @@ -0,0 +1,189 @@ +//! The surfaces the pointer tests share: contract documents only, so the same text is built into the +//! integration tests (through `thing_core`) and into the crate's own (through `crate`), whose types +//! differ though these do not. +#![allow(dead_code)] + +use thing_contract::*; +use thing_testkit::build::*; + +pub const PROVIDER: &str = "provider.pointer"; + +pub const FEED: &str = "provider.feed"; + +// ----- surfaces ----- + +pub 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, + } +} + +pub 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). +pub fn fixed(id: &str, w: f64, h: f64) -> Node { + column(id, Some((w, h)), Overflow::Visible, vec![]) +} + +pub 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) }) +} + +pub fn overlay(id: &str, modal: bool, children: Vec) -> Node { + Node::Overlay(OverlayNode { common: common(id), anchor: Anchor::Viewport, modal, dismiss: command("dismiss"), children }) +} + +pub 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. +pub 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", &[])], + ) +} + +/// A 160 x 160 scroll pane of twenty buttons, one per feed item, with a button below it. +pub 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", &[])], + ) +} + +/// 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. +pub 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. +pub 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", &[])], + ) +} + +/// A root with a 16px left margin, so no control's rect starts where the root's does. +pub fn indented(id: &str, children: Vec) -> Node { + let mut root = column(id, None, Overflow::Visible, children); + if let Node::Box(b) = &mut root { + b.style.padding.left = px(16.0); + } + root +} + +pub 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( + indented("root", 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 edge of a node, at a scale that does not divide ----- + +/// Rows of odd widths and heights, so edges fall between whole logical px at a fractional scale. +pub fn seam_surface() -> SurfaceDocument { + let row = |id: &str, h: f64, widths: &[f64]| { + let mut row = column(id, None, Overflow::Visible, widths.iter().enumerate().map(|(i, w)| fixed(&format!("{id}-{i}"), *w, h)).collect()); + if let Node::Box(b) = &mut row { + b.style.direction = Direction::Row; + b.style.size = size2(Dimension::Percent(Scalar { value: 100.0 }), px(h)); + b.style.justify_content = ContentAlign::Start; + } + row + }; + surface( + column("root", None, Overflow::Visible, vec![ + row("r0", 7.0, &[9.0, 14.0, 5.0, 31.0]), + row("r1", 13.0, &[11.0, 3.0, 17.0]), + row("r2", 5.0, &[6.0, 6.0, 6.0, 6.0, 7.0]), + row("r3", 19.0, &[23.0, 29.0, 13.0]), + ]), + vec![], + ) +} + +// ----- a non-modal overlay ----- + +pub fn nonmodal_surface(anchor: Anchor) -> SurfaceDocument { + let pop = Node::Overlay(OverlayNode { common: common("pop"), anchor, modal: false, dismiss: command("dismiss"), children: vec![button("pop-button", "inside", 80.0, 48.0)] }); + surface( + column("root", None, Overflow::Visible, vec![button("behind", "behind", 320.0, 48.0), button("other", "other", 320.0, 48.0), pop]), + vec![decl("behind", &[]), decl("other", &[]), decl("inside", &[]), decl("dismiss", &[])], + ) +} + +// ----- the cases the mutants found open ----- + +pub fn lone_slider(min: f64, max: f64, step: f64) -> SurfaceDocument { + let slider = Node::Slider(SliderNode { common: common("level"), min, max, step, value: lit_number(min), commit: command("set") }); + surface(indented("root", vec![slider]), vec![decl("set", &["level"])]) +} + +/// A board with an absolute target standing inside it, away from its corner. +pub fn target_surface() -> SurfaceDocument { + let mut over = style(); + over.position = Position::Absolute; + over.inset = Edges { top: px(64.0), right: Dimension::Auto, bottom: Dimension::Auto, left: px(96.0) }; + over.size = size2(px(48.0), px(48.0)); + let target = Node::Box(BoxNode { common: common("target"), style: over, paint: plain_paint(), role: Role::Group, children: vec![] }); + surface(column("root", Some((320.0, 160.0)), Overflow::Visible, vec![fixed("board", 320.0, 160.0), target]), vec![]) +} + +/// A Select and a TextInput side by side, outside any button. +pub fn fields_surface() -> SurfaceDocument { + let (field, choice) = fields(); + surface(indented("root", vec![field, choice]), vec![decl("go", &[])]) +} + +/// A TextInput and a Select, each firing `go`. +pub fn fields() -> (Node, Node) { + let input = Node::TextInput(TextInputNode { + common: common("field"), + multiline: false, + input_kind: InputKind::Text, + placeholder: lit_text(""), + initial: lit_text("x"), + submit: command("go"), + }); + let select = Node::Select(SelectNode { + common: common("choice"), + options: OptionList::Literal(LiteralOptions { options: vec![SelectOption { value: "a".into(), label: "A".into() }] }), + value: record_bind(path(&["Theme"]), None), + on_change: command("go"), + }); + (input, select) +} 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);