diff --git a/crates/thing-core/src/frame.rs b/crates/thing-core/src/frame.rs new file mode 100644 index 0000000..b732cc0 --- /dev/null +++ b/crates/thing-core/src/frame.rs @@ -0,0 +1,171 @@ +//! The frame entry: one `Core::frame` call per frame the host makes drains the port, resolves, +//! binds, lays out and renders. Core owns the pipeline order and is the only caller of +//! `StatePort::drain`; it reads no clock, sleeps nowhere and never awaits. Later cuts extend +//! `frame` in place with their own step; there is no second entry. + +use thing_contract::{DatabaseEntry, ProviderId, RecordKey, SchemaId, SurfaceDocument}; + +use crate::bind::Binder; +use crate::diagnostic::Diagnostic; +use crate::input::InputEvent; +use crate::layout::{LaidTree, LayoutError, LayoutFrame, Measure, Metrics, layout}; +use crate::port::{Address, Change, Interest, Ledger, Lookup, StatePort}; +use crate::render::{RenderCommand, RenderInput, Rendered, ScrollOffsets, render}; +use crate::resolve::{Limits, Resolver}; +use crate::theme::Theme; +use crate::time::Timestamp; + +/// What a core is built with. `metrics` is the mode of the one `Measure` core owns. +#[derive(Clone, Debug, PartialEq)] +pub struct Config { + pub limits: Limits, + pub metrics: Metrics, +} + +impl Config { + pub fn new(metrics: Metrics) -> Self { + Self { limits: Limits::default(), metrics } + } +} + +/// The ports lent to one frame. The host owns its state port and changes it between frames; +/// it lends the same port every frame, because core's `Ledger` counts the subscriptions it made +/// on that port. +pub struct Ports<'a> { + pub state: &'a mut dyn StatePort, +} + +/// What the host tells core each frame. `viewport` is the one writer of size: logical px +/// (`Metrics::Pixels`) or cells (`Metrics::Cells`), the space `LayoutFrame` takes; a resize is +/// the next frame's viewport. +#[derive(Clone, Debug, PartialEq)] +pub struct FrameInput { + pub now: Timestamp, + pub viewport: (f32, f32), + pub scale: f32, + pub events: Vec, +} + +/// What a frame hands back. Later cuts add fields; hosts keep compiling. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct FrameOutput { + pub commands: Vec, + pub diagnostics: Vec, + /// When the host should call `frame` again with nothing else to say; `None` while nothing in + /// core depends on time. + pub next_wake: Option, +} + +pub struct Core { + metrics: Metrics, + measure: Box, + resolver: Resolver, + binder: Binder, + ledger: Ledger, + scroll: ScrollOffsets, + theme: Theme, + /// The surface `show` named, and the one whose interest and trees are held. + wanted: Option
, + shown: Option
, + /// The last good frame: what the user saw, which hit-test reads. + last: Option<(LaidTree, Rendered)>, +} + +impl Core { + pub fn new(config: Config, measure: Box) -> Self { + Self { + metrics: config.metrics, + measure, + resolver: Resolver::new(config.limits.clone()), + binder: Binder::new(config.limits), + ledger: Ledger::new(), + scroll: ScrollOffsets::default(), + theme: Theme::std(), + wanted: None, + shown: None, + last: None, + } + } + + /// Name the one surface displayed. It takes effect at the next frame. + pub fn show(&mut self, provider: ProviderId, key: RecordKey) { + self.wanted = Some(Address { provider, schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME), key }); + } + + 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 port = ports.state; + let mut changes = Vec::new(); + if self.wanted != self.shown { + self.switch(port, &mut changes); + } + changes.extend(port.drain()); + + let mut diagnostics = Vec::new(); + for change in &changes { + let intake = self.resolver.apply(change, port, &mut self.ledger); + diagnostics.extend(intake.diagnostics); + for (key, replaced) in intake.changed { + if replaced { + if let Some(tree) = self.resolver.tree(&key).cloned() { + diagnostics.extend(self.binder.bind(tree, port, &mut self.ledger).diagnostics); + } + } else { + self.binder.forget(&key, port, &mut self.ledger); + } + } + diagnostics.extend(self.binder.apply(change, port, &mut self.ledger).diagnostics); + } + + let commands = self.draw(viewport, scale, &mut diagnostics); + FrameOutput { commands, diagnostics, next_wake: None } + } + + /// Leave the surface shown and take the one wanted: the interest is held before the one read, + /// and what the read finds enters as a change like any republish. + fn switch(&mut self, port: &mut dyn StatePort, changes: &mut Vec) { + if let Some(old) = self.shown.take() { + self.resolver.forget(old.key.as_str(), port, &mut self.ledger); + self.binder.forget(old.key.as_str(), port, &mut self.ledger); + self.ledger.release(port, &Interest::Record(old)); + self.scroll = ScrollOffsets::default(); + self.last = None; + } + if let Some(new) = self.wanted.clone() { + self.ledger.hold(port, &Interest::Record(new.clone())); + match port.read(&new) { + Lookup::Present(entry) => changes.push(Change::Upsert(entry)), + Lookup::Refused(refusal) => changes.push(Change::Refused(refusal)), + Lookup::Absent => {} + } + } + self.shown = self.wanted.clone(); + } + + 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 { + 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 rendered = render(tree, &laid, &input, self.measure.as_mut()); + diagnostics.extend(rendered.diagnostics.iter().cloned()); + let commands = rendered.commands.clone(); + self.last = Some((laid, rendered)); + commands + } + Err(LayoutError::OutOfRange(diagnostic)) => { + diagnostics.push(diagnostic); + self.last.as_ref().map(|(_, rendered)| rendered.commands.clone()).unwrap_or_default() + } + // The host's room, not a document fault: nothing is drawn and the last good frame stays. + Err(LayoutError::Frame(_)) => Vec::new(), + } + } +} diff --git a/crates/thing-core/src/input/event.rs b/crates/thing-core/src/input/event.rs new file mode 100644 index 0000000..7f9493e --- /dev/null +++ b/crates/thing-core/src/input/event.rs @@ -0,0 +1,83 @@ +//! The closed input model every host speaks to core. It is not `#[non_exhaustive]`: a new +//! variant is a contract revision every host compiles against. +//! +//! The viewport and the scale are not events: they are `FrameInput` fields, and a resize is the +//! next frame's viewport. Time is not an event either (`FrameInput::now`). + +/// One thing the user did, in the order the host saw it. +#[derive(Clone, Debug, PartialEq)] +pub enum InputEvent { + /// A key press or auto-repeat (`repeat: true`). A release never enters: a terminal + /// reports Release on Windows and the TUI drops it, and the web host drops keyup. `Char` is the + /// character the keyboard layout produced (Shift+a is `Char('A')` with `shift` set; + /// Shift+Tab is `Tab` with `shift`). A typing key emits `Key` then `Text`, in that order (DOM + /// keydown precedes beforeinput; a window system's key event carries text beside the key; egui emits + /// Event::Key then Event::Text); a Ctrl or Alt chord emits `Key` only. Commands bind to `Key`. + Key { key: Key, modifiers: Modifiers, repeat: bool }, + /// Committed text to insert; a paste is `Text`. Text inserts only from `Text`, so nothing + /// inserts twice. + Text(String), + /// The IME preedit, replacing any earlier one; empty `text` ends it without commit, and the + /// commit arrives as `Text` (DOM compositionupdate/compositionend; a window system's IME preedit and commit). + /// `cursor` is UTF-8 byte offsets into `text`, the window-system convention; the web host converts the + /// DOM's UTF-16 offsets. + Compose { text: String, cursor: Option<(u32, u32)> }, + /// `at` is in the space `Placed` is in: logical px, or cells where a terminal cell + /// `(col, row)` is its centre `(col + 0.5, row + 0.5)`, the point the TUI's paint covers a + /// cell by, so a hit and a drawn cell agree. + PointerDown { at: (f32, f32), button: PointerButton, modifiers: Modifiers }, + /// Sent with or without a button held. + PointerMove { at: (f32, f32), modifiers: Modifiers }, + PointerUp { at: (f32, f32), button: PointerButton, modifiers: Modifiers }, + /// The platform took the pointer (DOM pointercancel; the web host uses setPointerCapture so + /// an up outside the canvas still arrives): a pending press is dropped and no up follows. + PointerCancel, + /// `delta` positive y moves content toward its end (the scroll offset grows), positive x + /// right: the DOM WheelEvent sign. A terminal's ScrollDown is `(0, 1)` `Lines`; a + /// window system whose line delta has the opposite sign is negated by its host. `Units` are logical px or + /// cells; `Lines` are converted by core. + Wheel { at: (f32, f32), delta: (f32, f32), unit: WheelUnit, modifiers: Modifiers }, + /// The host window or terminal gained (`true`) or lost focus. + Focus(bool), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Key { + Char(char), + Enter, + Tab, + Backspace, + Delete, + Escape, + Left, + Right, + Up, + Down, + Home, + End, + PageUp, + PageDown, + Insert, + F(u8), +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct Modifiers { + pub shift: bool, + pub ctrl: bool, + pub alt: bool, + pub meta: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum PointerButton { + Primary, + Secondary, + Middle, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum WheelUnit { + Units, + Lines, +} diff --git a/crates/thing-core/src/input/mod.rs b/crates/thing-core/src/input/mod.rs new file mode 100644 index 0000000..d4f4881 --- /dev/null +++ b/crates/thing-core/src/input/mod.rs @@ -0,0 +1,5 @@ +//! What a host tells core about its user: the closed `InputEvent` vocabulary. + +pub mod event; + +pub use event::{InputEvent, Key, Modifiers, PointerButton, WheelUnit}; diff --git a/crates/thing-core/src/lib.rs b/crates/thing-core/src/lib.rs index 1fb51c7..851512d 100644 --- a/crates/thing-core/src/lib.rs +++ b/crates/thing-core/src/lib.rs @@ -3,8 +3,13 @@ pub mod bind; pub mod diagnostic; +pub mod frame; +pub mod input; pub mod layout; pub mod port; pub mod render; pub mod resolve; pub mod theme; +pub mod time; + +pub use frame::{Config, Core, FrameInput, FrameOutput, Ports}; diff --git a/crates/thing-core/src/resolve/intake.rs b/crates/thing-core/src/resolve/intake.rs index 3764d7b..f2c6fe3 100644 --- a/crates/thing-core/src/resolve/intake.rs +++ b/crates/thing-core/src/resolve/intake.rs @@ -24,6 +24,15 @@ struct Held { reported: HashSet, } +/// What one `apply` did: its diagnostics, and each surface key whose displayed tree it replaced +/// (`true`) or dropped (`false`), sorted by key. A re-resolve that failed keeps its tree and is +/// not listed, so the frame owner never infers a change by comparing trees. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Intake { + pub diagnostics: Vec, + pub changed: Vec<(String, bool)>, +} + pub struct Resolver { limits: Limits, surfaces: HashMap, @@ -43,9 +52,17 @@ impl Resolver { self.surfaces.get(surface_key).and_then(|held| held.tree.as_ref()) } + /// Drop a surface the consumer no longer shows: its interests are released and its entry goes + /// with no tombstone (the consumer leaving is not the provider deleting). + pub fn forget(&mut self, surface_key: &str, port: &mut dyn StatePort, ledger: &mut Ledger) { + if let Some(held) = self.surfaces.remove(surface_key) { + ledger.diff(port, &held.interests, &HashSet::new()); + } + } + /// One drained change. A surface offer is judged by the version rule; a change at a /// composition a held surface read resolves that surface again from its held document. - pub fn apply(&mut self, change: &Change, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec { + pub fn apply(&mut self, change: &Change, port: &mut dyn StatePort, ledger: &mut Ledger) -> Intake { let address = match change { Change::Upsert(entry) => &entry.address, Change::Delete(address) => address, @@ -55,24 +72,30 @@ impl Resolver { return match change { Change::Upsert(entry) => match &entry.record { Record::Surface(document) => self.offer(document, port, ledger), - _ => Vec::new(), + _ => Intake::default(), }, Change::Delete(address) => { // A tombstone: the highest version stays so an older one is not taken again, // but the tree and the interests go. + let mut changed = Vec::new(); if let Some(held) = self.surfaces.get_mut(address.key.as_str()) { - held.tree = None; + if held.tree.take().is_some() { + changed.push((address.key.as_str().to_string(), false)); + } let released = std::mem::take(&mut held.interests); ledger.diff(port, &released, &HashSet::new()); } - Vec::new() + Intake { diagnostics: Vec::new(), changed } } - Change::Refused(refusal) => vec![Diagnostic { - code: Code::DecodeRefused, - surface: address.key.as_str().to_string(), - node: None, - detail: refusal.detail.clone(), - }], + Change::Refused(refusal) => Intake { + diagnostics: vec![Diagnostic { + code: Code::DecodeRefused, + surface: address.key.as_str().to_string(), + node: None, + detail: refusal.detail.clone(), + }], + changed: Vec::new(), + }, }; } let mut readers: Vec = self @@ -82,20 +105,27 @@ impl Resolver { .map(|(key, _)| key.clone()) .collect(); readers.sort(); - let mut diagnostics = Vec::new(); + let mut intake = Intake::default(); for key in readers { let document = self.surfaces[&key].document.clone(); - diagnostics.extend(self.resolve_held(&key, document, port, ledger)); + let (diagnostics, replaced) = self.resolve_held(&key, document, port, ledger); + intake.diagnostics.extend(diagnostics); + if replaced { + intake.changed.push((key, true)); + } } - diagnostics + intake } - fn offer(&mut self, document: &SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec { + fn offer(&mut self, document: &SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> Intake { let key = document.record_key(); if let Some(held) = self.surfaces.get_mut(&key) && document.version <= held.document.version { - return if held.reported.insert(document.version) { + // A subscribe replays the current record: the same document again is not news. + let diagnostics = if document.version == held.document.version && *document == held.document { + Vec::new() + } else if held.reported.insert(document.version) { vec![Diagnostic { code: Code::StaleVersionIgnored, surface: key, @@ -105,13 +135,16 @@ impl Resolver { } else { Vec::new() }; + return Intake { diagnostics, changed: Vec::new() }; } - self.resolve_held(&key, document.clone(), port, ledger) + let (diagnostics, replaced) = self.resolve_held(&key, document.clone(), port, ledger); + Intake { diagnostics, changed: if replaced { vec![(key, true)] } else { Vec::new() } } } /// Resolve `document` as the highest offered for `key`: a tree replaces the held one, no tree - /// keeps it. The interests become the reads either way. - fn resolve_held(&mut self, key: &str, document: SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec { + /// keeps it. The interests become the reads either way. The flag is whether a tree replaced + /// the held one. + fn resolve_held(&mut self, key: &str, document: SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> (Vec, bool) { let resolution = resolve(&document, &*port, &self.limits); let interests: HashSet = resolution.reads.into_iter().map(Interest::Record).collect(); let held = self.surfaces.entry(key.to_string()).or_insert_with(|| Held { @@ -123,9 +156,10 @@ impl Resolver { ledger.diff(port, &held.interests, &interests); held.interests = interests; held.document = document; + let replaced = resolution.tree.is_some(); if let Some(tree) = resolution.tree { held.tree = Some(tree); } - resolution.diagnostics + (resolution.diagnostics, replaced) } } diff --git a/crates/thing-core/src/resolve/mod.rs b/crates/thing-core/src/resolve/mod.rs index 21fa08d..4c0ac3d 100644 --- a/crates/thing-core/src/resolve/mod.rs +++ b/crates/thing-core/src/resolve/mod.rs @@ -10,7 +10,7 @@ mod validate; use thing_contract::SurfaceDocument; -pub use intake::Resolver; +pub use intake::{Intake, Resolver}; use crate::diagnostic::{Code, Diagnostic}; use crate::port::{Address, StatePort}; diff --git a/crates/thing-core/src/time.rs b/crates/thing-core/src/time.rs new file mode 100644 index 0000000..7086013 --- /dev/null +++ b/crates/thing-core/src/time.rs @@ -0,0 +1,5 @@ +//! Wall time as core is told it: the host reads its clock and hands core the reading. + +/// Unix milliseconds, UTC. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Timestamp(pub i64); diff --git a/crates/thing-core/tests/frame.rs b/crates/thing-core/tests/frame.rs new file mode 100644 index 0000000..573c78d --- /dev/null +++ b/crates/thing-core/tests/frame.rs @@ -0,0 +1,490 @@ +//! The frame entry: Core::frame equals the stages composed by hand, and keeps its promises +//! about the port, the last good frame and the room it is given. + +use thing_contract::*; +use thing_core::bind::Binder; +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::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::measure::FixedMeasure; +use thing_testkit::mem_state::{Call, MemState}; +use thing_testkit::state::{self, Swarm}; + +const PROVIDER: &str = "provider.frame"; + +fn measure(metrics: Metrics) -> FixedMeasure { + match metrics { + Metrics::Pixels => FixedMeasure::pixels(), + Metrics::Cells => FixedMeasure::cells(), + } +} + +fn fresh(metrics: Metrics) -> Core { + Core::new(Config::new(metrics), Box::new(measure(metrics))) +} + +fn input(viewport: (f32, f32), scale: f32) -> FrameInput { + FrameInput { now: Timestamp(0), viewport, scale, events: vec![] } +} + +fn run(core: &mut Core, state: &mut MemState, input: FrameInput) -> FrameOutput { + core.frame(input, Ports { state }) +} + +fn show(core: &mut Core, document: &SurfaceDocument) { + core.show(document.provider_id.clone(), RecordKey::new(document.record_key())); +} + +fn world(fixture: Fixture) -> MemState { + let mut state = MemState::from_fixture(fixture); + state::script(fixture, &mut state); + state +} + +/// The commands of the stages composed by hand, as tests/render.rs composes them. +fn staged(document: &SurfaceDocument, state: &mut MemState, viewport: (f32, f32), scale: f32, metrics: Metrics) -> Vec { + let limits = Limits::default(); + let tree = resolve(document, state, &limits).tree.expect("resolves"); + let mut binder = Binder::new(limits); + binder.bind(tree, state, &mut Ledger::new()); + let bound = binder.tree(&document.record_key()).expect("bound"); + let frame = LayoutFrame { viewport, scale, metrics }; + 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 }; + render(bound, &laid, &input, &mut measure(metrics)).commands +} + +fn inline(version: i64, root: Node) -> SurfaceDocument { + SurfaceDocument { + provider_id: ProviderId::new(PROVIDER), + label: seg("main"), + version: ver(version), + title: "frame".into(), + root, + commands: vec![], + } +} + +fn say(version: i64, words: &str) -> SurfaceDocument { + inline(version, boxed("root", vec![text("words", words)])) +} + +fn surface_address(document: &SurfaceDocument) -> Address { + Address { + provider: document.provider_id.clone(), + schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME), + key: RecordKey::new(document.record_key()), + } +} + +fn codes(output: &FrameOutput) -> Vec { + output.diagnostics.iter().map(|diagnostic| diagnostic.code).collect() +} + +fn count(state: &MemState, wanted: impl Fn(&Call) -> bool) -> usize { + state.calls().iter().filter(|call| wanted(call)).count() +} + +#[test] +fn pipeline_equals_the_stages() { + let cells = Fixture::F01SwarmDashboard.load().surfaces.remove(0); + let mut state = world(Fixture::F01SwarmDashboard); + let mut one = fresh(Metrics::Cells); + show(&mut one, &cells); + let output = run(&mut one, &mut state, input((100.0, 37.0), 1.0)); + let expected = staged(&cells, &mut world(Fixture::F01SwarmDashboard), (100.0, 37.0), 1.0, Metrics::Cells); + assert!(!expected.is_empty()); + assert_eq!(output.commands, expected); + assert_eq!(output.next_wake, None); + + let list = Fixture::F06ScrollList.load().surfaces.remove(0); + let mut state = world(Fixture::F06ScrollList); + let mut two = fresh(Metrics::Pixels); + show(&mut two, &list); + let output = run(&mut two, &mut state, input((800.0, 600.0), 1.5)); + let expected = staged(&list, &mut world(Fixture::F06ScrollList), (800.0, 600.0), 1.5, Metrics::Pixels); + assert!(!expected.is_empty()); + assert_eq!(output.commands, expected); +} + +#[test] +fn an_idle_frame_draws_the_same_and_drains_once() { + let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0); + let mut state = world(Fixture::F01SwarmDashboard); + let mut core = fresh(Metrics::Cells); + show(&mut core, &document); + let first = run(&mut core, &mut state, input((100.0, 37.0), 1.0)); + assert_eq!(count(&state, |call| *call == Call::Drain), 1); + let before = state.calls().len(); + let second = run(&mut core, &mut state, input((100.0, 37.0), 1.0)); + assert_eq!(second.commands, first.commands); + assert_eq!(state.calls()[before..], [Call::Drain]); +} + +#[test] +fn show_holds_the_interest_before_it_reads_and_draws_when_published() { + let document = say(1, "hello"); + let mut state = MemState::new(); + let mut core = fresh(Metrics::Cells); + show(&mut core, &document); + let output = run(&mut core, &mut state, input((40.0, 5.0), 1.0)); + assert_eq!(output.commands, vec![]); + assert_eq!(output.diagnostics, vec![]); + let address = surface_address(&document); + let calls = state.calls(); + let subscribe = calls.iter().position(|call| matches!(call, Call::Subscribe(interest) if interest.matches(&address))).expect("subscribed"); + let read = calls.iter().position(|call| *call == Call::Read(address.clone())).expect("read"); + assert!(subscribe < read, "{calls:?}"); + + state.put(&document.provider_id, &document); + let output = run(&mut core, &mut state, input((40.0, 5.0), 1.0)); + assert_eq!(output.commands, staged(&document, &mut MemState::new(), (40.0, 5.0), 1.0, Metrics::Cells)); + assert!(!output.commands.is_empty()); +} + +#[test] +fn a_republish_replaces_the_picture_and_a_delete_empties_it() { + let v1 = say(1, "first"); + let v2 = say(2, "second"); + let mut state = MemState::new(); + state.put(&v1.provider_id, &v1); + let mut core = fresh(Metrics::Cells); + show(&mut core, &v1); + let at = (40.0, 5.0); + let first = run(&mut core, &mut state, input(at, 1.0)); + assert_eq!(first.commands, staged(&v1, &mut MemState::new(), at, 1.0, Metrics::Cells)); + + state.put(&v2.provider_id, &v2); + let second = run(&mut core, &mut state, input(at, 1.0)); + assert_eq!(second.commands, staged(&v2, &mut MemState::new(), at, 1.0, Metrics::Cells)); + assert_ne!(second.commands, first.commands); + assert_eq!(codes(&second), vec![]); + + // The same record delivered again is not news. + state.put(&v2.provider_id, &v2); + let again = run(&mut core, &mut state, input(at, 1.0)); + assert_eq!(codes(&again), vec![]); + assert_eq!(again.commands, second.commands); + + // A different document at the held version is refused and the held one stays. + let other = say(2, "impostor"); + state.put(&other.provider_id, &other); + let stale = run(&mut core, &mut state, input(at, 1.0)); + assert_eq!(codes(&stale), vec![Code::StaleVersionIgnored]); + assert_eq!(stale.commands, second.commands); + + state.delete(&surface_address(&v2)); + let gone = run(&mut core, &mut state, input(at, 1.0)); + assert_eq!(gone.commands, vec![]); +} + +#[test] +fn a_changed_state_record_draws_and_a_late_composition_rebinds() { + let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0); + let mut state = world(Fixture::F01SwarmDashboard); + let mut core = fresh(Metrics::Cells); + show(&mut core, &document); + let at = (100.0, 37.0); + let before = run(&mut core, &mut state, input(at, 1.0)); + + let summary = Swarm { id: "summary".into(), name: "Swarm".into(), load: 0.93 }; + state.put_state(&ProviderId::new("provider.swarm"), "summary", &summary); + let after = run(&mut core, &mut state, input(at, 1.0)); + let mut moved = world(Fixture::F01SwarmDashboard); + moved.put_state(&ProviderId::new("provider.swarm"), "summary", &summary); + assert_eq!(after.commands, staged(&document, &mut moved, at, 1.0, Metrics::Cells)); + assert_ne!(after.commands, before.commands); + + // f09: the surface is published first and its composition after. + let stack = Fixture::F09CompositionStack.load(); + let surface = stack.surfaces[0].clone(); + let mut state = MemState::new(); + state.put(&surface.provider_id, &surface); + for (key, record) in state::swarm_records() { + state.put_state(&ProviderId::new("provider.stack"), key, &record); + } + let mut late = fresh(Metrics::Cells); + show(&mut late, &surface); + let placeholder = run(&mut late, &mut state, input(at, 1.0)); + assert!(codes(&placeholder).contains(&Code::UnresolvedUse), "{:?}", codes(&placeholder)); + for composition in &stack.compositions { + state.put(&ProviderId::new(composition.publisher.clone()), composition); + } + let resolved = run(&mut late, &mut state, input(at, 1.0)); + let mut full = MemState::from_fixture(Fixture::F09CompositionStack); + for (key, record) in state::swarm_records() { + full.put_state(&ProviderId::new("provider.stack"), key, &record); + } + assert_eq!(resolved.commands, staged(&surface, &mut full, at, 1.0, Metrics::Cells)); + assert_ne!(resolved.commands, placeholder.commands); +} + +#[test] +fn no_room_draws_nothing_without_a_diagnostic_and_the_next_frame_draws_again() { + let document = say(1, "room"); + let mut state = MemState::new(); + state.put(&document.provider_id, &document); + let mut core = fresh(Metrics::Cells); + show(&mut core, &document); + let first = run(&mut core, &mut state, input((40.0, 5.0), 1.0)); + assert!(!first.commands.is_empty()); + let cramped = run(&mut core, &mut state, input((0.0, 37.0), 1.0)); + assert_eq!(cramped.commands, vec![]); + assert_eq!(cramped.diagnostics, vec![]); + let again = run(&mut core, &mut state, input((40.0, 5.0), 1.0)); + assert_eq!(again.commands, first.commands); +} + +#[test] +fn a_layout_past_the_precision_bound_keeps_the_last_good_frame() { + let good = say(1, "fits"); + // Two boxes side by side that together reach past the bound: neither alone is refused. + let slab = |id: &str| match boxed(id, vec![]) { + Node::Box(mut slab) => { + slab.style.size = size2(px(1_500_000.0), px(10.0)); + Node::Box(slab) + } + other => other, + }; + let mut wide = inline(2, boxed("root", vec![slab("left"), slab("right")])); + if let Node::Box(root) = &mut wide.root { + root.style.direction = Direction::Row; + } + let mut state = MemState::new(); + state.put(&good.provider_id, &good); + let mut core = fresh(Metrics::Pixels); + show(&mut core, &good); + let first = run(&mut core, &mut state, input((800.0, 600.0), 1.0)); + assert!(!first.commands.is_empty()); + state.put(&wide.provider_id, &wide); + let refused = run(&mut core, &mut state, input((800.0, 600.0), 1.0)); + assert_eq!(refused.commands, first.commands); + assert_eq!(codes(&refused), vec![Code::LayoutOutOfRange]); +} + +fn every_event() -> Vec { + let modifiers = Modifiers { shift: true, ctrl: false, alt: true, meta: false }; + let at = (3.5, 2.5); + vec![ + InputEvent::Key { key: Key::Char('A'), modifiers, repeat: false }, + InputEvent::Key { key: Key::F(5), modifiers: Modifiers::default(), repeat: true }, + InputEvent::Text("hi".into()), + InputEvent::Compose { text: "か".into(), cursor: Some((0, 3)) }, + InputEvent::PointerDown { at, button: PointerButton::Primary, modifiers }, + InputEvent::PointerMove { at, modifiers }, + InputEvent::PointerUp { at, button: PointerButton::Primary, modifiers }, + InputEvent::PointerCancel, + InputEvent::Wheel { at, delta: (0.0, 1.0), unit: WheelUnit::Lines, modifiers }, + InputEvent::Focus(false), + ] +} + +#[test] +fn this_cut_routes_no_input_event() { + 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)); + let (mut quiet, mut busy) = (fresh(Metrics::Pixels), fresh(Metrics::Pixels)); + show(&mut quiet, &document); + 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(); + let output = run(&mut busy, &mut busy_state, with_events); + assert_eq!(output, plain); + assert_eq!(busy_state.calls(), quiet_state.calls()); +} + +#[test] +fn showing_another_surface_releases_the_first() { + let (a, b) = (say(1, "alpha"), { + let mut b = say(1, "beta"); + b.label = seg("other"); + b + }); + let mut state = MemState::new(); + state.put(&a.provider_id, &a); + state.put(&b.provider_id, &b); + let mut core = fresh(Metrics::Cells); + let at = (40.0, 5.0); + show(&mut core, &a); + let first = run(&mut core, &mut state, input(at, 1.0)); + assert_eq!(count(&state, |call| matches!(call, Call::Unsubscribe(_))), 0); + show(&mut core, &b); + let second = run(&mut core, &mut state, input(at, 1.0)); + assert_eq!(count(&state, |call| matches!(call, Call::Unsubscribe(_))), 1); + assert_eq!(second.commands, staged(&b, &mut MemState::new(), at, 1.0, Metrics::Cells)); + assert_ne!(second.commands, first.commands); +} + +/// A random box tree: sizes from a hostile list (zero, negative, NaN, past the bound), scroll and +/// clip boxes, texts. +fn random_node(next: &mut dyn FnMut() -> u64, id: &mut u32, depth: u32) -> Node { + let sizes = [0.0, 1.0, 7.5, 40.0, 100.0, 5000.0, 1e6, 1e7, -4.0, f64::NAN]; + *id += 1; + let name = format!("n{id}"); + if depth == 0 || next() % 4 == 0 { + return text(&name, &format!("text {id}")); + } + let Node::Box(mut node) = boxed(&name, vec![]) else { unreachable!() }; + node.style.size = size2(px(sizes[(next() % 10) as usize]), px(sizes[(next() % 10) as usize])); + node.style.direction = if next() % 2 == 0 { Direction::Row } else { Direction::Column }; + node.style.overflow = [Overflow::Visible, Overflow::Clip, Overflow::Scroll][(next() % 3) as usize].clone(); + let children = next() % 4; + node.children = (0..children).map(|_| random_node(next, id, depth - 1)).collect(); + Node::Box(node) +} + +/// Fixed seeds for reproducibility, plus `THING_FRAME_SEED` when set; a failure names its seed. +#[test] +fn random_documents_and_inputs_never_panic_and_the_frame_is_deterministic() { + let mut seeds = vec![0x9E37_79B9_7F4A_7C15u64, 0xD1B5_4A32_D192_ED03, 0x2545_F491_4F6C_DD1D, 7]; + if let Some(extra) = std::env::var("THING_FRAME_SEED").ok().and_then(|v| v.parse().ok()) { + seeds.push(extra); + } + for seed in seeds { + random_run(seed); + } +} + +fn random_run(mut seed: u64) { + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let rooms = [(100.0, 37.0), (0.0, 0.0), (-5.0, 10.0), (f32::NAN, 4.0), (f32::INFINITY, 4.0), (800.0, 600.0), (1e9, 1e9), (1.0, 1.0)]; + let scales = [1.0, 1.5, 0.0, -1.0, f32::NAN, f32::INFINITY, 1e6, 2.0]; + for metrics in [Metrics::Pixels, Metrics::Cells] { + let (mut left, mut right) = (fresh(metrics), fresh(metrics)); + let (mut left_state, mut right_state) = (MemState::new(), MemState::new()); + let mut shown = false; + for round in 0..200i64 { + if next() % 9 != 0 { + let mut id = 0; + let document = inline(round + 1, random_node(&mut next, &mut id, 4)); + if !shown { + show(&mut left, &document); + show(&mut right, &document); + shown = true; + } + left_state.put(&document.provider_id, &document); + right_state.put(&document.provider_id, &document); + } else if shown { + let address = surface_address(&inline(1, boxed("root", vec![]))); + left_state.delete(&address); + right_state.delete(&address); + } + let room = rooms[(next() % 8) as usize]; + let scale = scales[(next() % 8) as usize]; + let events = every_event().into_iter().take((next() % 11) as usize).collect::>(); + let frame = FrameInput { now: Timestamp(round), viewport: room, scale, events }; + let one = run(&mut left, &mut left_state, frame.clone()); + let two = run(&mut right, &mut right_state, frame); + assert_eq!(one, two, "seed {seed} round {round} in {metrics:?} at {room:?} scale {scale}"); + } + } +} + +fn wide(version: i64) -> SurfaceDocument { + let slab = |id: &str| match boxed(id, vec![]) { + Node::Box(mut slab) => { + slab.style.size = size2(px(1_500_000.0), px(10.0)); + Node::Box(slab) + } + other => other, + }; + let mut document = inline(version, boxed("root", vec![slab("left"), slab("right")])); + if let Node::Box(root) = &mut document.root { + root.style.direction = Direction::Row; + } + document +} + +#[test] +fn the_last_good_frame_is_cleared_by_a_delete_and_a_switch_and_kept_through_a_frame_error() { + let at = (800.0, 600.0); + let good = say(1, "fits"); + // Kept through a room with no size: a refused layout afterwards still shows it. + let mut state = MemState::new(); + state.put(&good.provider_id, &good); + let mut one = fresh(Metrics::Pixels); + show(&mut one, &good); + let first = run(&mut one, &mut state, input(at, 1.0)); + run(&mut one, &mut state, input((f32::NAN, 600.0), 1.0)); + state.put(&good.provider_id, &wide(2)); + let held = run(&mut one, &mut state, input(at, 1.0)); + assert_eq!(held.commands, first.commands); + assert_eq!(codes(&held), vec![Code::LayoutOutOfRange]); + + // Cleared by a delete: what comes after has no frame to fall back on. + let mut state = MemState::new(); + state.put(&good.provider_id, &good); + let mut two = fresh(Metrics::Pixels); + show(&mut two, &good); + run(&mut two, &mut state, input(at, 1.0)); + state.delete(&surface_address(&good)); + assert_eq!(run(&mut two, &mut state, input(at, 1.0)).commands, vec![]); + // The tombstone keeps the version: the same document again, and a different one at it, change nothing shown. + state.put(&good.provider_id, &good); + let replay = run(&mut two, &mut state, input(at, 1.0)); + assert_eq!((codes(&replay), replay.commands), (vec![], vec![])); + state.put(&good.provider_id, &say(1, "other")); + let refused = run(&mut two, &mut state, input(at, 1.0)); + assert_eq!((codes(&refused), refused.commands), (vec![Code::StaleVersionIgnored], vec![])); + state.put(&good.provider_id, &wide(2)); + let out = run(&mut two, &mut state, input(at, 1.0)); + assert_eq!((codes(&out), out.commands), (vec![Code::LayoutOutOfRange], vec![])); + + // Cleared by a switch. + let other = { + let mut other = wide(1); + other.label = seg("other"); + other + }; + let mut state = MemState::new(); + state.put(&good.provider_id, &good); + state.put(&other.provider_id, &other); + let mut three = fresh(Metrics::Pixels); + show(&mut three, &good); + run(&mut three, &mut state, input(at, 1.0)); + show(&mut three, &other); + let switched = run(&mut three, &mut state, input(at, 1.0)); + assert_eq!((codes(&switched), switched.commands), (vec![Code::LayoutOutOfRange], vec![])); +} + +#[test] +fn a_switch_leaves_the_old_surface_holding_no_interest() { + let swarm = Fixture::F01SwarmDashboard.load().surfaces.remove(0); + let other = say(1, "elsewhere"); + let mut state = world(Fixture::F01SwarmDashboard); + state.put(&other.provider_id, &other); + let mut core = fresh(Metrics::Cells); + let at = (100.0, 37.0); + show(&mut core, &swarm); + run(&mut core, &mut state, input(at, 1.0)); + let subscribed = count(&state, |call| matches!(call, Call::Subscribe(_))); + assert!(subscribed > 1, "f01 binds provider state, so more than its own record is held"); + show(&mut core, &other); + run(&mut core, &mut state, input(at, 1.0)); + let subscribes = count(&state, |call| matches!(call, Call::Subscribe(_))); + let unsubscribes = count(&state, |call| matches!(call, Call::Unsubscribe(_))); + assert_eq!(subscribes - unsubscribes, 1, "only the shown surface's own record is held"); + // A record the old surface read now changes nothing and costs no read. + let summary = Swarm { id: "summary".into(), name: "Swarm".into(), load: 0.5 }; + state.put_state(&ProviderId::new("provider.swarm"), "summary", &summary); + let before = state.calls().len(); + run(&mut core, &mut state, input(at, 1.0)); + assert_eq!(state.calls()[before..], [Call::Drain]); +} diff --git a/crates/thing-core/tests/intake.rs b/crates/thing-core/tests/intake.rs index edf0e51..a06eacf 100644 --- a/crates/thing-core/tests/intake.rs +++ b/crates/thing-core/tests/intake.rs @@ -66,7 +66,7 @@ impl Rig { } fn apply(&mut self, change: Change) -> Vec { - self.resolver.apply(&change, &mut self.state, &mut self.ledger) + self.resolver.apply(&change, &mut self.state, &mut self.ledger).diagnostics } fn offer(&mut self, document: &SurfaceDocument) -> Vec { @@ -148,8 +148,11 @@ fn a_surface_that_fails_to_resolve_leaves_the_last_good_tree_displayed() { let bad = surface("main", 2, vec![command_button("go", "undeclared")]); assert_eq!(codes(&rig.offer(&bad)), vec![Code::UndeclaredCommand]); assert_eq!(rig.title(&key).as_deref(), Some("main v1")); - // The refused version was offered: it is stale now, not tried again. - assert_eq!(codes(&rig.offer(&bad)), vec![Code::StaleVersionIgnored]); + // The refused version was offered: it is stale now, not tried again. (The same document again is + // a replay and is silent.) + assert!(rig.offer(&bad).is_empty()); + let other = surface("main", 2, vec![command_button("go", "also-undeclared")]); + assert_eq!(codes(&rig.offer(&other)), vec![Code::StaleVersionIgnored]); assert_eq!(rig.title(&key).as_deref(), Some("main v1")); assert!(rig.offer(&surface("main", 3, vec![])).is_empty()); @@ -177,7 +180,9 @@ fn a_refused_surface_keeps_the_held_tree_and_is_not_a_delete() { assert_eq!(diagnostics[0].surface, key); assert_eq!(rig.title(&key).as_deref(), Some("main v1")); // The version it was refused at was never taken: the same version is still the highest. - assert_eq!(codes(&rig.offer(&v1)), vec![Code::StaleVersionIgnored]); + assert!(rig.offer(&v1).is_empty(), "the same document again is a replay"); + let other = surface("main", 1, vec![command_button("go", "go")]); + assert_eq!(codes(&rig.offer(&other)), vec![Code::StaleVersionIgnored]); } @@ -286,3 +291,40 @@ fn a_deleted_surface_keeps_its_version_as_a_tombstone() { assert!(rig.offer(&surface("main", 4, vec![])).is_empty()); assert_eq!(rig.title(&key).as_deref(), Some("main v4")); } + +#[test] +fn intake_lists_each_tree_a_change_replaced_or_dropped_and_not_a_failed_resolve() { + let mut rig = Rig::new(); + let v1 = surface("main", 1, vec![]); + let key = v1.record_key(); + let offer = |rig: &mut Rig, document: &SurfaceDocument| { + let change = Change::Upsert(Entry { address: surface_address(document), record: Record::Surface(document.clone()) }); + rig.resolver.apply(&change, &mut rig.state, &mut rig.ledger).changed + }; + assert_eq!(offer(&mut rig, &v1), vec![(key.clone(), true)]); + let bad = surface("main", 2, vec![command_button("go", "undeclared")]); + assert_eq!(offer(&mut rig, &bad), vec![]); + assert_eq!(offer(&mut rig, &v1), vec![]); + let gone = rig.resolver.apply(&Change::Delete(surface_address(&v1)), &mut rig.state, &mut rig.ledger); + assert_eq!(gone.changed, vec![(key.clone(), false)]); + let again = rig.resolver.apply(&Change::Delete(surface_address(&v1)), &mut rig.state, &mut rig.ledger); + assert_eq!(again.changed, vec![]); +} + +#[test] +fn forget_releases_the_interests_and_leaves_no_tombstone() { + let mut rig = Rig::new(); + let with_use = surface("main", 1, vec![use_of("u", "card")]); + rig.put(&composition("card", "body")); + rig.offer(&with_use); + let key = with_use.record_key(); + assert!(rig.resolver.tree(&key).is_some()); + let held = rig.ledger.readers(&Interest::Record(comp_address("card"))); + assert_eq!(held, 1); + rig.resolver.forget(&key, &mut rig.state, &mut rig.ledger); + assert!(rig.resolver.tree(&key).is_none()); + assert_eq!(rig.ledger.readers(&Interest::Record(comp_address("card"))), 0); + // Not a tombstone: the same version is taken again. + assert!(rig.offer(&with_use).is_empty()); + assert!(rig.resolver.tree(&key).is_some()); +}