Thing 2.0 cut F: Core::frame, the closed InputEvent model, Resolver Intake and forget
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8fe8b1aaad
commit
fd726bf16c
9 changed files with 644 additions and 21 deletions
171
crates/thing-core/src/frame.rs
Normal file
171
crates/thing-core/src/frame.rs
Normal file
|
|
@ -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::{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<InputEvent>,
|
||||
}
|
||||
|
||||
/// What a frame hands back. Later cuts add fields; hosts keep compiling.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct FrameOutput {
|
||||
pub commands: Vec<RenderCommand>,
|
||||
pub diagnostics: Vec<Diagnostic>,
|
||||
/// When the host should call `frame` again with nothing else to say; `None` while nothing in
|
||||
/// core depends on time.
|
||||
pub next_wake: Option<Timestamp>,
|
||||
}
|
||||
|
||||
pub struct Core {
|
||||
metrics: Metrics,
|
||||
measure: Box<dyn Measure>,
|
||||
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<Address>,
|
||||
shown: Option<Address>,
|
||||
/// 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<dyn Measure>) -> 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<Change>) {
|
||||
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<Diagnostic>) -> Vec<RenderCommand> {
|
||||
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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
83
crates/thing-core/src/input/event.rs
Normal file
83
crates/thing-core/src/input/event.rs
Normal file
|
|
@ -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: crossterm 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; winit's KeyEvent 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` (winit Ime::Preedit/Commit; DOM compositionupdate/compositionend).
|
||||
/// `cursor` is UTF-8 byte offsets into `text`, winit's 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. crossterm ScrollDown is `(0, 1)` `Lines`; winit's
|
||||
/// LineDelta has the opposite sign and a winit host negates it. `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,
|
||||
}
|
||||
5
crates/thing-core/src/input/mod.rs
Normal file
5
crates/thing-core/src/input/mod.rs
Normal file
|
|
@ -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};
|
||||
|
|
@ -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};
|
||||
|
|
|
|||
|
|
@ -24,6 +24,15 @@ struct Held {
|
|||
reported: HashSet<Version>,
|
||||
}
|
||||
|
||||
/// 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<Diagnostic>,
|
||||
pub changed: Vec<(String, bool)>,
|
||||
}
|
||||
|
||||
pub struct Resolver {
|
||||
limits: Limits,
|
||||
surfaces: HashMap<String, Held>,
|
||||
|
|
@ -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<Diagnostic> {
|
||||
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<String> = 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<Diagnostic> {
|
||||
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<Diagnostic> {
|
||||
/// 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<Diagnostic>, bool) {
|
||||
let resolution = resolve(&document, &*port, &self.limits);
|
||||
let interests: HashSet<Interest> = 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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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};
|
||||
|
|
|
|||
5
crates/thing-core/src/time.rs
Normal file
5
crates/thing-core/src/time.rs
Normal file
|
|
@ -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);
|
||||
320
crates/thing-core/tests/frame.rs
Normal file
320
crates/thing-core/tests/frame.rs
Normal file
|
|
@ -0,0 +1,320 @@
|
|||
//! 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, StatePort};
|
||||
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<RenderCommand> {
|
||||
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<Code> {
|
||||
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");
|
||||
let mut wide = say(2, "does not fit");
|
||||
if let Node::Box(root) = &mut wide.root {
|
||||
root.style.size = size2(px(3_000_000.0), px(10.0));
|
||||
}
|
||||
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<InputEvent> {
|
||||
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);
|
||||
}
|
||||
|
|
@ -66,7 +66,7 @@ impl Rig {
|
|||
}
|
||||
|
||||
fn apply(&mut self, change: Change) -> Vec<Diagnostic> {
|
||||
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<Diagnostic> {
|
||||
|
|
|
|||
Loading…
Reference in a new issue