Thing 2.0 cut 7a: commands (activate, Drafts, minted invocations, lifecycle, effects as data) (#25)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 2m49s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 3m53s

This commit is contained in:
Eureka 2026-11-29 00:35:39 +00:00
commit 668ec478cd
23 changed files with 2716 additions and 57 deletions

View file

@ -8,8 +8,11 @@
mod format;
mod repeat;
mod scope;
mod walk;
pub use scope::Located;
use std::collections::{BTreeMap, HashMap, HashSet};
use thing_contract::{AssetEntry, NodeId, SelectOption};
@ -81,9 +84,14 @@ pub enum Bound {
/// One instance of a Repeat's template: its key, and the template with derived ids, whose sites
/// are in the same table. A refused item's key is `!` and its record key.
///
/// The one id scheme is `scope_prefix`: an id inside an instance is its prefix followed by the
/// template's id, so a node in nested instances is the inner prefix, then the outer, then its declared id.
#[derive(Clone, Debug, PartialEq)]
pub struct Instance {
pub key: String,
/// What `Instance::scope_prefix` derived for this instance: each of the template's ids is this followed by the template id.
pub prefix: String,
pub root: thing_contract::Node,
}
@ -344,3 +352,17 @@ impl Binder {
self.surfaces.get(surface).map(|surface| &surface.bound)
}
}
impl Instance {
/// The prefix of every id of the instance of `repeat` (a laid id) whose key is `key`:
/// `<repeat>#<key byte length>:<key>/`; an item the port refused has no key to read, so its
/// identity is its record key in the distinct form `<repeat>!<length>:<record key>/`. Resolve's
/// instance ids and command captures both derive scope here, so there is one scheme.
pub fn scope_prefix(repeat: &str, key: &str, refused: bool) -> String {
if refused {
format!("{repeat}!{}:{key}/", key.len())
} else {
format!("{repeat}#{}:{key}/", key.len())
}
}
}

View file

@ -159,20 +159,21 @@ impl Walker<'_> {
let (key, prefix) = match &entry.item {
Item::Fault(_) => {
let record = entry.record_key.clone().unwrap_or_default();
(format!("!{record}"), format!("{id}!{}:{record}/", record.len()))
let prefix = Instance::scope_prefix(id, &record, true);
(format!("!{record}"), prefix)
}
Item::Value(value) => {
let key = key_of(value, &repeat.key_member)?;
if !keys.insert(key.clone()) {
return Err(fault(Code::RepeatKeyDuplicate, format!("two items of {id} share one key")));
}
let prefix = format!("{id}#{}:{key}/", key.len());
let prefix = Instance::scope_prefix(id, &key, false);
(key, prefix)
}
};
let mut root = (*repeat.template).clone();
rewrite(&mut root, &prefix, &inside);
built.push((Instance { key, root }, entry.item));
built.push((Instance { key, prefix, root }, entry.item));
}
let mut ids = Vec::new();

View file

@ -0,0 +1,111 @@
//! Where a node sits in a bound tree: the one id -> node index, and the Repeat instances that
//! enclose a node, which commands read to name a row and to find the inputs beside a button.
use std::collections::HashMap;
use thing_contract::{Node, NodeId};
use super::walk::{children, common};
use super::BoundTree;
use crate::resolve::grow;
/// A node and the Repeat instances around it, read off the tree.
#[derive(Clone, Debug, PartialEq)]
pub struct Located<'a> {
pub node: &'a Node,
/// The id the author declared: the laid id with its instance prefixes removed.
pub declared: NodeId,
/// The prefix of each enclosing instance, innermost first. An id declared at the top of the
/// document, reached from here, is these joined in order followed by it.
pub prefixes: Vec<String>,
/// The key of each enclosing instance, outermost first.
pub items: Vec<String>,
}
struct Walk<'a, 'b> {
tree: &'a BoundTree,
prefixes: Vec<&'a str>,
items: Vec<&'a str>,
visit: &'b mut dyn FnMut(Located<'a>) -> bool,
}
impl<'a> Walk<'a, '_> {
/// Visit the node, then what it holds; stops (`true`) as soon as a visit says so.
fn node(&mut self, node: &'a Node) -> bool {
grow(|| {
let Some(common) = common(node) else { return false };
let skip: usize = self.prefixes.iter().map(|prefix| prefix.len()).sum();
let declared = NodeId::new(common.id.as_str().get(skip..).unwrap_or(common.id.as_str()));
let located = Located {
node,
declared,
prefixes: self.prefixes.iter().rev().map(|prefix| prefix.to_string()).collect(),
items: self.items.iter().map(|item| item.to_string()).collect(),
};
if (self.visit)(located) {
return true;
}
if let Node::Repeat(repeat) = node {
for instance in self.tree.instances(&repeat.common.id) {
self.prefixes.push(&instance.prefix);
self.items.push(&instance.key);
let stop = self.node(&instance.root);
self.prefixes.pop();
self.items.pop();
if stop {
return true;
}
}
return false;
}
children(node).iter().any(|child| self.node(child))
})
}
}
impl BoundTree {
/// Every node of the document by laid id, Repeat instances included (ids are unique after
/// resolve). The one index render, hit-test and commands share.
pub fn index(&self) -> HashMap<&NodeId, &Node> {
let mut found = HashMap::new();
self.walk(&mut |located| {
if let Some(common) = common(located.node) {
found.insert(&common.id, located.node);
}
false
});
found
}
/// The node with laid id `id`, and where it sits.
pub fn locate(&self, id: &NodeId) -> Option<Located<'_>> {
let mut found = None;
self.walk(&mut |located| {
let hit = common(located.node).is_some_and(|common| &common.id == id);
if hit {
found = Some(located);
}
hit
});
found
}
/// The first node declared as `declared` inside the instances keyed `items` (outermost first).
pub fn locate_source(&self, declared: &NodeId, items: &[String]) -> Option<Located<'_>> {
let mut found = None;
self.walk(&mut |located| {
let hit = &located.declared == declared && located.items == items;
if hit {
found = Some(located);
}
hit
});
found
}
fn walk<'a>(&'a self, visit: &mut dyn FnMut(Located<'a>) -> bool) {
let mut walk = Walk { tree: self, prefixes: Vec::new(), items: Vec::new(), visit };
walk.node(&self.resolved().document().root);
}
}

View file

@ -0,0 +1,110 @@
//! Captures: the values an invocation carries, read at the user's action from the drafts over the
//! bound values. An input beside a button in a Repeat row is found by scope: the activating node's
//! innermost instance first, then outward, then the declared id itself.
use std::collections::HashMap;
use thing_contract::{BoolValue, CapturedInput, ChoiceValue, CommandDecl, InputKind, InputValue, Node, NodeId, NumberValue, TextValue};
use crate::bind::{Bound, BoundTree, Field};
use crate::input::Drafts;
/// What the captures of one command came to: the values to send, and the drafts they were read from
/// (laid id and the value the table held), which a completed result clears if still held.
pub(super) struct Captured {
pub inputs: Vec<CapturedInput>,
pub held: Vec<(NodeId, InputValue)>,
}
/// The laid id of `declared` as seen from a node whose enclosing instance prefixes are `scope`
/// (innermost first): the most specific one the tree holds.
pub(super) fn laid_id(index: &HashMap<&NodeId, &Node>, scope: &[String], declared: &NodeId) -> Option<NodeId> {
(0..=scope.len())
.map(|start| NodeId::new(format!("{}{}", scope[start..].concat(), declared.as_str())))
.find(|candidate| index.contains_key(candidate))
}
fn number(text: &str) -> Option<f64> {
text.trim().parse::<f64>().ok().filter(|value| value.is_finite())
}
/// The value one input sends: its draft when it has one of the right kind, else what it is bound to.
fn value(tree: &BoundTree, drafts: &Drafts, surface: &str, laid: &NodeId, node: &Node) -> Option<InputValue> {
let draft = drafts.get(surface, laid);
let bound = |field| tree.value(laid, field);
match node {
Node::Toggle(_) => match (draft, bound(Field::Checked)) {
(Some(InputValue::Bool(held)), _) => Some(InputValue::Bool(held.clone())),
(_, Some(Bound::Bool(checked))) => Some(InputValue::Bool(BoolValue { value: *checked })),
_ => None,
},
Node::Slider(_) => match (draft, bound(Field::Value)) {
(Some(InputValue::Number(held)), _) => Some(InputValue::Number(held.clone())),
(_, Some(Bound::Number(at))) => Some(InputValue::Number(NumberValue { value: *at })),
_ => None,
},
Node::Select(_) => match (draft, bound(Field::Selected)) {
(Some(InputValue::Choice(held)), _) => Some(InputValue::Choice(held.clone())),
(_, Some(Bound::Text(selected))) => Some(InputValue::Choice(ChoiceValue { value: selected.clone() })),
_ => None,
},
Node::TextInput(input) => {
let initial = match bound(Field::Initial) {
Some(Bound::Text(text)) => Some(text.as_str()),
_ => None,
};
match input.input_kind {
InputKind::Text => match (draft, initial) {
(Some(InputValue::Text(held)), _) => Some(InputValue::Text(held.clone())),
(_, Some(text)) => Some(InputValue::Text(TextValue { value: text.to_string() })),
_ => None,
},
InputKind::Number => {
let typed = match draft {
Some(InputValue::Text(held)) => number(&held.value),
Some(InputValue::Number(held)) => Some(held.value).filter(|value| value.is_finite()),
_ => initial.and_then(number),
};
typed.map(|value| InputValue::Number(NumberValue { value }))
}
}
}
_ => None,
}
}
/// The captures of `decl`, in declared order, resolved from the scope of the activating node. The
/// error is the declared id of the first capture with no value to send.
pub(super) fn capture(tree: &BoundTree, drafts: &Drafts, surface: &str, scope: &[String], decl: &CommandDecl) -> Result<Captured, NodeId> {
let index = tree.index();
let mut captured = Captured { inputs: Vec::new(), held: Vec::new() };
for declared in &decl.captures {
let laid = laid_id(&index, scope, declared).ok_or_else(|| declared.clone())?;
let node = index.get(&laid).ok_or_else(|| declared.clone())?;
let value = value(tree, drafts, surface, &laid, node).ok_or_else(|| declared.clone())?;
captured.inputs.push(CapturedInput { node: declared.clone(), value });
if let Some(draft) = drafts.get(surface, &laid) {
captured.held.push((laid, draft.clone()));
}
}
Ok(captured)
}
/// The value a change input takes, or why it takes none. A slider is a range input: a value that is
/// not finite is refused, and a finite one outside its range is clamped to it. A select takes only an
/// option it declares (bound options included, as bound for this node).
pub(super) fn change(tree: &BoundTree, laid: &NodeId, node: &Node, value: &InputValue) -> Result<InputValue, &'static str> {
match (node, value) {
(Node::Slider(slider), InputValue::Number(at)) => {
if !at.value.is_finite() {
return Err("the slider value is not a finite number");
}
Ok(InputValue::Number(NumberValue { value: at.value.max(slider.min).min(slider.max) }))
}
(Node::Select(_), InputValue::Choice(chosen)) => match tree.value(laid, Field::Options) {
Some(Bound::Options(options)) if options.iter().any(|option| option.value == chosen.value) => Ok(value.clone()),
_ => Err("the choice names no declared option"),
},
_ => Ok(value.clone()),
}
}

View file

@ -0,0 +1,183 @@
//! The invocation lifecycle: `Issued -> Pending* -> Completed | Denied | Failed`, with the core-only
//! terminal states `Malformed` and `TimedOut`. Terminal is final: a later result is a diagnostic,
//! never a state change. Core decides every transition; a provider only offers results.
use thing_contract::{CommandResult, DatabaseEntry, Outcome};
use super::{Commands, HostEffect, Live, Mark, State, capture, fault, validate};
use crate::bind::BoundTree;
use crate::diagnostic::{Code, Diagnostic};
use crate::input::Drafts;
use crate::port::{Change, Ledger, Record, StatePort};
use crate::time::Timestamp;
/// What one drained change did: the effects for the host to run, and what core says about it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Answered {
pub effects: Vec<HostEffect>,
pub diagnostics: Vec<Diagnostic>,
}
impl Commands {
/// One drained change. Only a command result is this module's; any other address is not and
/// answers empty. A result under no held invocation is `UnknownInvocation`, logged only.
/// `trees` finds a surface's bound tree by record key.
pub fn apply<'t>(
&mut self,
change: &Change,
now: Timestamp,
trees: &dyn Fn(&str) -> Option<&'t BoundTree>,
drafts: &mut Drafts,
port: &mut dyn StatePort,
ledger: &mut Ledger,
) -> Answered {
let mut answered = Answered::default();
let address = match change {
Change::Upsert(entry) => &entry.address,
Change::Delete(address) => address,
Change::Refused(refusal) => &refusal.address,
};
if address.schema.as_str() != CommandResult::SCHEMA_NAME {
return answered;
}
self.expire(now);
let Some(at) = self.live.iter().position(|live| live.interest.matches(address)) else {
if !matches!(change, Change::Delete(_)) {
answered.diagnostics.push(fault(
address.key.as_str(),
None,
Code::UnknownInvocation,
"no invocation of this id is held",
));
}
return answered;
};
if matches!(change, Change::Delete(_)) {
return answered;
}
let surface = self.live[at].surface.clone();
let issuing = self.live[at].issuing.clone();
if self.live[at].state.is_terminal() {
answered.diagnostics.push(fault(&surface, issuing.as_ref(), Code::ResultAfterTerminal, "the invocation is already terminal"));
return answered;
}
let result = match change {
Change::Upsert(entry) => match &entry.record {
// One equality catches a body naming another invocation, and a seq that is not the key's.
Record::Result(result) if result.record_key() == address.key.as_str() => result,
Record::Result(_) => {
self.malformed(at, "the result is not the one its key names", now, &mut answered, port, ledger);
return answered;
}
_ => {
self.malformed(at, "the record at a result address is not a result", now, &mut answered, port, ledger);
return answered;
}
},
_ => {
self.malformed(at, "the result was refused at decode", now, &mut answered, port, ledger);
return answered;
}
};
let seq = result.seq().get();
if seq <= self.live[at].highest {
return answered;
}
self.live[at].highest = seq;
match result.outcome() {
Outcome::Pending(pending) => {
self.live[at].state = State::Pending(pending.message.clone());
self.live[at].deadline = now.plus_ms(self.timeout_ms);
}
Outcome::Completed(completed) => {
let effect = match &completed.effect {
None => None,
Some(effect) => match validate::effect(effect, trees(&surface), &self.live[at]) {
Ok(effect) => Some(effect),
Err(detail) => {
self.malformed(at, &detail, now, &mut answered, port, ledger);
return answered;
}
},
};
if completed.clear_drafts {
drafts.clear_held(&surface, &self.live[at].held);
}
answered.effects.extend(effect);
self.settle(at, State::Completed, None, now, port, ledger);
}
Outcome::Denied(denied) => {
let mut target = issuing.clone();
if let Some(declared) = &denied.node {
let found = trees(&surface).and_then(|tree| capture::laid_id(&tree.index(), &self.live[at].scope, declared));
match found {
Some(laid) => target = Some(laid),
None => answered.diagnostics.push(fault(
&surface,
issuing.as_ref(),
Code::MalformedResult,
"denied node not in the surface",
)),
}
}
self.settle(at, State::Denied, None, now, port, ledger);
if let Some(node) = target {
self.marks.insert((surface, node), Mark::Denied { reason: denied.reason.clone() });
}
}
Outcome::Failed(failed) => {
self.settle(at, State::Failed, Some(Mark::Failed { reason: failed.reason.clone() }), now, port, ledger);
}
}
answered
}
/// Within a frame results apply before `tick` (`Core::frame` drains and applies, then ticks), so a
/// result queued for the frame its deadline passes wins over the timeout.
/// Move every non-terminal invocation whose deadline has come to `TimedOut`. A deadline is
/// compared with the time given: a wall clock that went backward delays a timeout, never fires one early.
pub fn tick(&mut self, now: Timestamp, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec<Diagnostic> {
self.expire(now);
let mut diagnostics = Vec::new();
for at in 0..self.live.len() {
let live = &self.live[at];
if !live.state.is_terminal() && live.deadline <= now {
diagnostics.push(fault(&live.surface, live.issuing.as_ref(), Code::InvocationTimedOut, "no result by the deadline"));
self.settle(at, State::TimedOut, Some(Mark::TimedOut), now, port, ledger);
}
}
diagnostics
}
/// The earliest deadline of an invocation still waiting; the frame's `next_wake`.
pub fn next_deadline(&self) -> Option<Timestamp> {
self.live.iter().filter(|live| !live.state.is_terminal()).map(|live: &Live| live.deadline).min()
}
/// A result core will not take: the invocation is `Malformed`, and nothing it carried runs.
fn malformed(&mut self, at: usize, detail: &str, now: Timestamp, answered: &mut Answered, port: &mut dyn StatePort, ledger: &mut Ledger) {
let live = &self.live[at];
answered.diagnostics.push(fault(&live.surface, live.issuing.as_ref(), Code::MalformedResult, detail));
self.settle(at, State::Malformed, Some(Mark::Malformed), now, port, ledger);
}
/// Forget the invocations that went terminal a whole timeout ago: a result after that is for an
/// invocation core no longer holds, so the table stays bounded by the work of one timeout. A
/// result inside the window is still judged against the invocation (`ResultAfterTerminal`).
fn expire(&mut self, now: Timestamp) {
let timeout = self.timeout_ms;
self.live.retain(|live| live.done.is_none_or(|done| now < done.plus_ms(timeout)));
}
/// Enter a terminal state: the interest in results is released in the same call, and the
/// issuing node shows the mark.
fn settle(&mut self, at: usize, state: State, mark: Option<Mark>, now: Timestamp, port: &mut dyn StatePort, ledger: &mut Ledger) {
let live = &mut self.live[at];
live.state = state;
live.done = Some(now);
ledger.release(port, &live.interest);
if let (Some(mark), Some(node)) = (mark, &live.issuing) {
self.marks.insert((live.surface.clone(), node.clone()), mark);
}
}
}

View file

@ -0,0 +1,459 @@
//! Commands: the one owner of invocation minting, the invocation lifecycle and result validation.
//! It follows the Resolver and Binder: it is handed what the frame drained and never drains, reads
//! no clock (time is a parameter) and awaits nothing. Core writes no record but an invocation, and
//! that leaves through `take_outbound`, never through a port.
//!
//! Every way of minting (a press, a key, a confirmed dialog, a resume after an external step)
//! ends in `mint`. A user action mints one id; nothing re-mints.
mod capture;
mod lifecycle;
mod validate;
use std::collections::HashMap;
use thing_contract::{
CapturedInput, CommandDecl, CommandId, CommandInvocation, CommandRef, CommandResult, DatabaseEntry, InputValue, Node, NodeId,
ProviderId, RecordPayload, SchemaId, Seq, Version,
};
use crate::bind::{Bound, BoundTree, Field};
use crate::diagnostic::{Code, Diagnostic};
use crate::input::Drafts;
use crate::port::{IdSource, Interest, Ledger, Prefix, StatePort};
use crate::time::Timestamp;
pub use lifecycle::Answered;
/// The empty MessagePack array: a payload record with no slots. Thing Script has no payload source yet.
const EMPTY_PAYLOAD: [u8; 1] = [0x90];
/// What the user did to one node.
#[derive(Clone, Debug, PartialEq)]
pub struct Activation {
/// The laid id, instance ids included.
pub node: NodeId,
pub kind: ActivationKind,
}
#[derive(Clone, Debug, PartialEq)]
pub enum ActivationKind {
/// A Button or an Overlay's dismissal.
Press,
/// A Toggle, a Slider or a Select took a value; it is written to Drafts first, then the command fires.
Change(InputValue),
/// A TextInput's submit.
Submit,
}
/// What the host runs for a provider's result. Closed.
#[derive(Clone, Debug, PartialEq)]
pub enum HostEffect {
OpenSurface { key: String },
OpenExternal { url: String, resume: Resume },
}
/// The command to run when an external step returns. The host holds it across a navigation (the
/// session dies on `location.assign`) and hands it to `Core::resume`. `source` and `items` are the
/// invocation's, so a resumed command names the same row.
#[derive(Clone, Debug, PartialEq)]
pub struct Resume {
pub surface_key: String,
pub command: CommandId,
pub source: NodeId,
pub items: Vec<String>,
}
/// Why a node shows a fault: the last terminal answer of an invocation issued from it, until it mints again.
#[derive(Clone, Debug, PartialEq)]
pub enum Mark {
Denied { reason: String },
Failed { reason: String },
Malformed,
TimedOut,
}
/// What render and accessibility read of one node. Derived from the live invocations; nothing is
/// stored on a node.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NodeState {
/// A non-terminal invocation was issued from this node.
pub busy: bool,
pub mark: Option<Mark>,
/// The message of the latest Pending result of a busy node's invocation.
pub pending: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NodeStates {
nodes: HashMap<NodeId, NodeState>,
}
impl NodeStates {
/// The state of a laid node; a node nothing happened to is the default.
pub fn get(&self, node: &NodeId) -> NodeState {
self.nodes.get(node).cloned().unwrap_or_default()
}
}
/// A command waiting for the user's yes. Its captures are the values at the user's action.
#[derive(Clone, Debug, PartialEq)]
pub struct Confirming {
pub surface: String,
pub node: NodeId,
pub command: CommandId,
pub text: String,
prepared: Prepared,
}
impl Confirming {
pub fn captured(&self) -> &[CapturedInput] {
&self.prepared.captured
}
}
/// Everything an invocation is except its id and its time: what a confirm holds until the user answers.
#[derive(Clone, Debug, PartialEq)]
struct Prepared {
surface: String,
provider: ProviderId,
version: Version,
command: CommandId,
payload_schema: SchemaId,
captured: Vec<CapturedInput>,
held: Vec<(NodeId, InputValue)>,
source: NodeId,
items: Vec<String>,
/// The laid node the user acted on; a resume has none.
issuing: Option<NodeId>,
/// The instance prefixes around the issuing node, innermost first.
scope: Vec<String>,
}
/// An invocation core issued. Terminal ones stay so a late result is judged, not lost.
#[derive(Clone, Debug)]
struct Live {
surface: String,
issuing: Option<NodeId>,
state: State,
/// The highest result `seq` taken.
highest: i32,
deadline: Timestamp,
/// When it went terminal; `None` while it waits.
done: Option<Timestamp>,
held: Vec<(NodeId, InputValue)>,
scope: Vec<String>,
interest: Interest,
source: NodeId,
items: Vec<String>,
}
#[derive(Clone, Debug, PartialEq)]
enum State {
Issued,
Pending(String),
Completed,
Denied,
Failed,
Malformed,
TimedOut,
}
impl State {
fn is_terminal(&self) -> bool {
!matches!(self, State::Issued | State::Pending(_))
}
}
pub struct Commands {
client: String,
timeout_ms: u32,
live: Vec<Live>,
marks: HashMap<(String, NodeId), Mark>,
confirming: Option<Confirming>,
outbound: Vec<CommandInvocation>,
}
fn fault(surface: &str, node: Option<&NodeId>, code: Code, detail: impl Into<String>) -> Diagnostic {
Diagnostic { code, surface: surface.to_string(), node: node.cloned(), detail: detail.into() }
}
/// An activation core did not act on; nothing was minted and no draft was written.
fn refused(surface: &str, node: &NodeId, detail: &str) -> Diagnostic {
fault(surface, Some(node), Code::ActivationRefused, detail)
}
/// A v4 UUID from 16 bytes: the version and variant bits are core's, so a minted id is always
/// UUID-shaped and dot-free (a result key splits at its last dot).
fn uuid(ids: &mut dyn IdSource) -> String {
let mut bytes = [0u8; 16];
ids.fill(&mut bytes);
bytes[6] = bytes[6] & 0x0f | 0x40;
bytes[8] = bytes[8] & 0x3f | 0x80;
let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32])
}
/// The key prefix every result of `invocation` shares, derived from the contract's one key
/// scheme: a result's key is this followed by its `seq`.
fn result_prefix(invocation: &CommandInvocation) -> String {
let key = CommandResult::pending(invocation, Seq::FIRST, "").record_key();
key[..key.rfind('.').map_or(key.len(), |dot| dot + 1)].to_string()
}
/// The command a node fires for an activation, when the node takes that kind of activation.
fn command_of<'a>(node: &'a Node, kind: &ActivationKind) -> Option<&'a CommandRef> {
match (node, kind) {
(Node::Button(n), ActivationKind::Press) => Some(&n.on_activate),
(Node::Overlay(n), ActivationKind::Press) => Some(&n.dismiss),
(Node::TextInput(n), ActivationKind::Submit) => Some(&n.submit),
(Node::Toggle(n), ActivationKind::Change(InputValue::Bool(_))) => Some(&n.on_change),
(Node::Slider(n), ActivationKind::Change(InputValue::Number(_))) => Some(&n.commit),
(Node::Select(n), ActivationKind::Change(InputValue::Choice(_))) => Some(&n.on_change),
_ => None,
}
}
/// Where a command is fired from: the declared id of its source, and the instances around it.
struct Origin {
issuing: Option<NodeId>,
source: NodeId,
scope: Vec<String>,
items: Vec<String>,
}
impl Commands {
pub fn new(client: impl Into<String>, timeout_ms: u32) -> Self {
Self {
client: client.into(),
timeout_ms,
live: Vec::new(),
marks: HashMap::new(),
confirming: None,
outbound: Vec::new(),
}
}
/// The one commit primitive: the user acted on `act.node` of `tree`. Every path calls it. It
/// mints one invocation, or nothing. A refusal (a node that is not a command source for this kind, a
/// node nobody laid, a change the input does not take, a command waiting on confirmation) answers with
/// a `Code::ActivationRefused` diagnostic. A disabled or busy button is not a refusal: the user sees
/// it, so it stays silent.
#[allow(clippy::too_many_arguments)]
pub fn activate(
&mut self,
act: Activation,
tree: &BoundTree,
drafts: &mut Drafts,
now: Timestamp,
ids: &mut dyn IdSource,
port: &mut dyn StatePort,
ledger: &mut Ledger,
) -> Vec<Diagnostic> {
let surface = tree.resolved().document().record_key();
if self.confirming.is_some() {
return vec![refused(&surface, &act.node, "a command is waiting for confirmation")];
}
let Some(located) = tree.locate(&act.node) else {
return vec![refused(&surface, &act.node, "the node is not in the surface")];
};
// A Param command is the same refusal: resolve leaves none in a tree, so none reaches here.
let Some(CommandRef::Id(command)) = command_of(located.node, &act.kind) else {
return vec![refused(&surface, &act.node, "the node fires no command for this activation")];
};
if let ActivationKind::Change(value) = &act.kind {
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) {
return Vec::new();
}
let Some(decl) = tree.resolved().document().commands.iter().find(|decl| decl.id == command.id) else {
return vec![fault(&surface, Some(&act.node), Code::UndeclaredCommand, "the command is not declared")];
};
let origin = Origin {
issuing: Some(act.node.clone()),
source: located.declared,
scope: located.prefixes,
items: located.items,
};
let prepared = match self.prepare(tree, drafts, decl, origin) {
Ok(prepared) => prepared,
Err(diagnostic) => return vec![diagnostic],
};
self.begin(prepared, act.node, decl.confirm.as_ref(), now, ids, port, ledger)
}
/// 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) {
if let Some(confirming) = self.confirming.take()
&& accept
{
self.mint(confirming.prepared, now, ids, port, ledger);
}
}
pub fn confirming(&self) -> Option<&Confirming> {
self.confirming.as_ref()
}
/// Run the command an external step named, as the invocation that asked for it: its declared
/// captures, its source and items, no issuing node (nothing is marked busy).
#[allow(clippy::too_many_arguments)]
pub fn resume(
&mut self,
resume: &Resume,
tree: &BoundTree,
drafts: &Drafts,
now: Timestamp,
ids: &mut dyn IdSource,
port: &mut dyn StatePort,
ledger: &mut Ledger,
) -> Vec<Diagnostic> {
let surface = tree.resolved().document().record_key();
let decl = tree.resolved().document().commands.iter().find(|decl| decl.id == resume.command);
let (Some(decl), true) = (decl, surface == resume.surface_key) else {
return vec![fault(&surface, None, Code::UndeclaredCommand, "the command to resume is not declared at the held version")];
};
let scope = tree.locate_source(&resume.source, &resume.items).map(|located| located.prefixes).unwrap_or_default();
let origin = Origin { issuing: None, source: resume.source.clone(), scope, items: resume.items.clone() };
match self.prepare(tree, drafts, decl, origin) {
Ok(prepared) => self.begin(prepared, resume.source.clone(), decl.confirm.as_ref(), now, ids, port, ledger),
Err(diagnostic) => vec![diagnostic],
}
}
/// The invocations minted since the last call, in order.
pub fn take_outbound(&mut self) -> Vec<CommandInvocation> {
std::mem::take(&mut self.outbound)
}
/// What render and accessibility read for `surface`.
pub fn view(&self, surface: &str) -> NodeStates {
let mut nodes: HashMap<NodeId, NodeState> = HashMap::new();
for ((held, node), mark) in &self.marks {
if held == surface {
nodes.entry(node.clone()).or_default().mark = Some(mark.clone());
}
}
for live in self.live.iter().filter(|live| live.surface == surface && !live.state.is_terminal()) {
if let Some(node) = &live.issuing {
let state = nodes.entry(node.clone()).or_default();
state.busy = true;
if let State::Pending(message) = &live.state {
state.pending = Some(message.clone());
}
}
}
NodeStates { nodes }
}
/// The surface is no longer shown: its invocations leave the table with their interests, its
/// marks go and a confirmation waiting on it is dropped.
pub fn forget(&mut self, surface: &str, port: &mut dyn StatePort, ledger: &mut Ledger) {
for live in self.live.iter().filter(|live| live.surface == surface && !live.state.is_terminal()) {
ledger.release(port, &live.interest);
}
self.live.retain(|live| live.surface != surface);
self.marks.retain(|(held, _), _| held != surface);
if self.confirming.as_ref().is_some_and(|confirming| confirming.surface == surface) {
self.confirming = None;
}
}
fn busy(&self, surface: &str, node: &NodeId) -> bool {
self.live.iter().any(|live| !live.state.is_terminal() && live.surface == surface && live.issuing.as_ref() == Some(node))
}
fn prepare(&self, tree: &BoundTree, drafts: &Drafts, decl: &CommandDecl, origin: Origin) -> Result<Prepared, Diagnostic> {
let document = tree.resolved().document();
let surface = document.record_key();
let captured = capture::capture(tree, drafts, &surface, &origin.scope, decl).map_err(|node| {
fault(&surface, Some(&node), Code::CaptureUnavailable, "the captured input has no value to send")
})?;
Ok(Prepared {
surface,
provider: document.provider_id.clone(),
version: document.version,
command: decl.id.clone(),
payload_schema: decl.payload_schema.clone(),
captured: captured.inputs,
held: captured.held,
source: origin.source,
items: origin.items,
issuing: origin.issuing,
scope: origin.scope,
})
}
/// Where every way of acting on a command meets its confirmation: a command that asks waits for the
/// user's yes, holding the captures it was prepared with; any other mints. One command waits at a time.
#[allow(clippy::too_many_arguments)]
fn begin(
&mut self,
prepared: Prepared,
node: NodeId,
confirm: Option<&String>,
now: Timestamp,
ids: &mut dyn IdSource,
port: &mut dyn StatePort,
ledger: &mut Ledger,
) -> Vec<Diagnostic> {
let Some(text) = confirm else {
self.mint(prepared, now, ids, port, ledger);
return Vec::new();
};
if self.confirming.is_some() {
return vec![refused(&prepared.surface, &node, "another command is waiting for confirmation")];
}
self.confirming = Some(Confirming { surface: prepared.surface.clone(), node, command: prepared.command.clone(), text: text.clone(), prepared });
Vec::new()
}
/// The one mint: draw one id, hold the interest in its results before the host can send, and
/// queue the invocation.
fn mint(&mut self, prepared: Prepared, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort, ledger: &mut Ledger) {
let invocation = CommandInvocation {
invocation_id: uuid(ids),
surface_key: prepared.surface.clone(),
surface_version: prepared.version,
command: prepared.command,
payload: RecordPayload { schema: prepared.payload_schema, bytes: EMPTY_PAYLOAD.to_vec() },
captured: prepared.captured,
client: self.client.clone(),
issued_at: now.rfc3339(),
delegation: None,
source: prepared.source.clone(),
items: prepared.items.clone(),
};
let interest = Interest::Prefix(Prefix {
provider: prepared.provider,
schema: SchemaId::new(CommandResult::SCHEMA_NAME),
key_prefix: result_prefix(&invocation),
});
ledger.hold(port, &interest);
if let Some(node) = &prepared.issuing {
self.marks.remove(&(prepared.surface.clone(), node.clone()));
}
self.live.push(Live {
surface: prepared.surface,
issuing: prepared.issuing,
state: State::Issued,
highest: 0,
deadline: now.plus_ms(self.timeout_ms),
done: None,
held: prepared.held,
scope: prepared.scope,
interest,
source: prepared.source,
items: prepared.items,
});
self.outbound.push(invocation);
}
}

View file

@ -0,0 +1,58 @@
//! What core will run for a provider's result: the closed effects, judged before any is emitted.
//! A provider decides what to ask; core decides whether it is allowed.
use thing_contract::{CommandId, CommandRef, Effect};
use super::{HostEffect, Live, Resume};
use crate::bind::BoundTree;
/// Whether `url` is absolute with the scheme http or https (ASCII case-insensitive) and a host.
fn web_url(url: &str) -> bool {
if url.chars().any(|c| c.is_control() || c.is_whitespace()) {
return false;
}
let Some((scheme, rest)) = url.split_once("://") else { return false };
(scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https"))
&& !rest.starts_with(['/', '?', '#'])
&& !rest.is_empty()
}
/// The effect as data for the host, or why core refuses it. `tree` is the invocation's surface as
/// held now: a resume names a command that surface declares.
pub(super) fn effect(effect: &Effect, tree: Option<&BoundTree>, live: &Live) -> Result<HostEffect, String> {
match effect {
Effect::OpenSurface(open) => {
if open.key.starts_with("thing:surface:") {
Ok(HostEffect::OpenSurface { key: open.key.clone() })
} else {
Err("OpenSurface names a key that is not a surface".into())
}
}
Effect::OpenExternal(open) => {
if !web_url(&open.url) {
return Err("OpenExternal names a url that is not absolute http or https".into());
}
let CommandRef::Id(resume) = &open.resume else {
return Err("OpenExternal resumes through a parameter".into());
};
let declared = tree.is_some_and(|tree| declares(tree, &resume.id));
if !declared {
return Err("OpenExternal resumes a command the surface does not declare".into());
}
Ok(HostEffect::OpenExternal {
url: open.url.clone(),
resume: Resume {
surface_key: live.surface.clone(),
command: resume.id.clone(),
source: live.source.clone(),
items: live.items.clone(),
},
})
}
}
}
pub(super) fn declares(tree: &BoundTree, command: &CommandId) -> bool {
tree.resolved().document().commands.iter().any(|decl| &decl.id == command)
}

View file

@ -45,12 +45,30 @@ pub enum Code {
OverlayAnchorMissing,
/// A colour or text token the theme does not hold; it drew as the fallback colour.
ThemeTokenUnknown,
/// A result that could not be taken: refused by decode, not a result, filed under another key than its
/// own, or carrying an effect core will not run. The invocation is Malformed.
MalformedResult,
/// A result under the result key space for an invocation core does not hold.
UnknownInvocation,
/// A result for an invocation already terminal; the state does not change.
ResultAfterTerminal,
/// An invocation with no result by its deadline; it is TimedOut.
InvocationTimedOut,
/// A capture whose input has no value to send (a bound error, absent, or a number that does not parse);
/// nothing was minted.
CaptureUnavailable,
/// A command capture naming no node, or a node that holds no input value.
CaptureUndeclared,
/// An activation core refused to act on: a kind the node does not take, a node nobody laid, a change
/// value outside what the input allows, a command blocked by a confirmation, or a resume that can no
/// longer run. Nothing was minted; the detail says which.
ActivationRefused,
}
impl Code {
/// Whether the fault leaves no tree (the whole document is refused) or only a placeholder.
pub fn refuses_document(self) -> bool {
matches!(self, Code::UndeclaredCommand | Code::DuplicateNodeId | Code::UnboundParam | Code::ExpansionLimit | Code::TooDeepToResolve)
matches!(self, Code::UndeclaredCommand | Code::DuplicateNodeId | Code::UnboundParam | Code::ExpansionLimit | Code::TooDeepToResolve | Code::CaptureUndeclared)
}
}

View file

@ -3,13 +3,16 @@
//! `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 thing_contract::{CommandInvocation, DatabaseEntry, ProviderId, RecordKey, SchemaId, SurfaceDocument};
use std::collections::HashSet;
use crate::bind::Binder;
use crate::diagnostic::Diagnostic;
use crate::input::InputEvent;
use crate::command::{Activation, Commands, Confirming, HostEffect, Resume};
use crate::diagnostic::{Code, Diagnostic};
use crate::input::{Drafts, InputEvent};
use crate::layout::{LaidTree, LayoutError, LayoutFrame, Measure, Metrics, layout};
use crate::port::{Address, Change, Interest, Ledger, Lookup, StatePort};
use crate::port::{Address, Change, IdSource, Interest, Ledger, Lookup, StatePort};
use crate::render::{RenderCommand, RenderInput, Rendered, ScrollOffsets, render};
use crate::resolve::{Limits, Resolver};
use crate::theme::Theme;
@ -20,11 +23,17 @@ use crate::time::Timestamp;
pub struct Config {
pub limits: Limits,
pub metrics: Metrics,
/// How long an invocation waits for a result, and for the next one after a Pending (a heartbeat).
/// A guess, to be measured (build-spec O5).
pub invocation_timeout_ms: u32,
/// The kind of host core runs in (`renderer.web`, `renderer.tui`), written to every invocation. It
/// is never a caller identity: core has no identity to write, the transport sets it.
pub client: String,
}
impl Config {
pub fn new(metrics: Metrics) -> Self {
Self { limits: Limits::default(), metrics }
pub fn new(metrics: Metrics, client: impl Into<String>) -> Self {
Self { limits: Limits::default(), metrics, invocation_timeout_ms: 15_000, client: client.into() }
}
}
@ -33,6 +42,7 @@ impl Config {
/// on that port.
pub struct Ports<'a> {
pub state: &'a mut dyn StatePort,
pub ids: &'a mut dyn IdSource,
}
/// What the host tells core each frame. `viewport` is the one writer of size: logical px
@ -55,6 +65,10 @@ pub struct FrameOutput {
/// 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>,
/// The invocations minted since the last frame, in order: core's only outbound write.
pub outbound: Vec<CommandInvocation>,
/// What the host runs for the results taken this frame.
pub effects: Vec<HostEffect>,
}
pub struct Core {
@ -65,6 +79,13 @@ pub struct Core {
ledger: Ledger,
scroll: ScrollOffsets,
theme: Theme,
commands: Commands,
drafts: Drafts,
/// What activations said since the last frame; the frame's diagnostics carry it out.
notes: Vec<Diagnostic>,
/// Resumes whose surface had not bound when the host handed them over; each runs at that surface's
/// first bind, or is dropped when the surface is left first.
held: Vec<Resume>,
/// The surface `show` named, and the one whose interest and trees are held.
wanted: Option<Address>,
shown: Option<Address>,
@ -82,6 +103,10 @@ impl Core {
ledger: Ledger::new(),
scroll: ScrollOffsets::default(),
theme: Theme::std(),
commands: Commands::new(config.client, config.invocation_timeout_ms),
drafts: Drafts::new(),
notes: Vec::new(),
held: Vec::new(),
wanted: None,
shown: None,
last: None,
@ -95,7 +120,7 @@ impl Core {
pub fn frame(&mut self, input: FrameInput, ports: Ports<'_>) -> FrameOutput {
// Input routes only to owners that exist; none does yet, so events change nothing.
let FrameInput { now: _, viewport, scale, events: _ } = input;
let FrameInput { now, viewport, scale, events: _ } = input;
let port = ports.state;
let mut changes = Vec::new();
if self.wanted != self.shown {
@ -103,32 +128,124 @@ impl Core {
}
changes.extend(port.drain());
let mut diagnostics = Vec::new();
let mut diagnostics = std::mem::take(&mut self.notes);
let mut effects = Vec::new();
let mut rebound = false;
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);
let bound = self.binder.bind(tree, port, &mut self.ledger);
rebound |= !bound.dirty.is_empty();
diagnostics.extend(bound.diagnostics);
}
} else {
self.binder.forget(&key, port, &mut self.ledger);
}
}
diagnostics.extend(self.binder.apply(change, port, &mut self.ledger).diagnostics);
let applied = self.binder.apply(change, port, &mut self.ledger);
rebound |= !applied.dirty.is_empty();
diagnostics.extend(applied.diagnostics);
let binder = &self.binder;
let answered = self.commands.apply(change, now, &|key| binder.tree(key), &mut self.drafts, port, &mut self.ledger);
diagnostics.extend(answered.diagnostics);
effects.extend(answered.effects);
}
if rebound {
self.retain_drafts();
}
for resume in std::mem::take(&mut self.held) {
match self.binder.tree(&resume.surface_key) {
Some(tree) => {
let said = self.commands.resume(&resume, tree, &self.drafts, now, ports.ids, port, &mut self.ledger);
diagnostics.extend(said);
}
None => self.held.push(resume),
}
}
// Results of this frame are applied above, before the deadline is judged: a late result that was
// already queued wins over the timeout.
diagnostics.extend(self.commands.tick(now, port, &mut self.ledger));
let commands = self.draw(viewport, scale, &mut diagnostics);
FrameOutput { commands, diagnostics, next_wake: None }
FrameOutput {
commands,
diagnostics,
next_wake: self.commands.next_deadline(),
outbound: self.commands.take_outbound(),
effects,
}
}
/// The host's semantic activation: the user, or an accessibility action or an automation acting for
/// them, activated a node of the shown surface. It is the one primitive every input path ends in (pointer and
/// keyboard routes arrive here too). The invocation it mints is in the next
/// frame's `outbound`; a refusal (see `Commands::activate`) is said in that frame's `diagnostics`.
pub fn activate(&mut self, act: Activation, now: Timestamp, ports: Ports<'_>) {
let Some(tree) = self.shown.as_ref().and_then(|shown| self.binder.tree(shown.key.as_str())) else {
let node = Some(act.node);
self.notes.push(Diagnostic { code: Code::ActivationRefused, surface: String::new(), node, detail: "no surface is shown".into() });
return;
};
let said = self.commands.activate(act, tree, &mut self.drafts, now, ports.ids, ports.state, &mut self.ledger);
self.notes.extend(said);
}
/// Answer the command waiting on confirmation (`confirming`). The host shows the question and calls
/// this with the user's answer; accepting mints with the captures taken at the activation.
pub fn confirm(&mut self, accept: bool, now: Timestamp, ports: Ports<'_>) {
self.commands.confirm(accept, now, ports.ids, ports.state, &mut self.ledger);
}
/// The command waiting for the user's yes or no, for the host to ask.
pub fn confirming(&self) -> Option<&Confirming> {
self.commands.confirming()
}
/// Run the command an `OpenExternal` effect named, once the external step has returned. The host
/// holds the `Resume` across the navigation and hands it back here; the command is minted, or asks
/// for confirmation, like an activation. A resume handed over before its surface has bound is held and
/// runs at the first bind; one whose surface is left first is dropped and said. Any other refusal is
/// said in the next frame's `diagnostics`.
pub fn resume(&mut self, resume: &Resume, now: Timestamp, ports: Ports<'_>) {
let Some(tree) = self.binder.tree(&resume.surface_key) else {
self.held.push(resume.clone());
return;
};
let said = self.commands.resume(resume, tree, &self.drafts, now, ports.ids, ports.state, &mut self.ledger);
self.notes.extend(said);
}
/// Drop the drafts of nodes the shown surface no longer has.
fn retain_drafts(&mut self) {
let Some(shown) = &self.shown else { return };
let key = shown.key.as_str();
let live: HashSet<_> = match self.binder.tree(key) {
Some(tree) => tree.index().keys().map(|id| (*id).clone()).collect(),
None => HashSet::new(),
};
self.drafts.retain(key, &live);
}
/// 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>) {
// A resume is for the surface it names: leaving for another one forgets it.
let wanted = self.wanted.as_ref().map(|address| address.key.as_str().to_string());
for resume in std::mem::take(&mut self.held) {
if wanted.as_deref() == Some(resume.surface_key.as_str()) {
self.held.push(resume);
} else {
let detail = "the surface was left before it bound; the resume is dropped";
self.notes.push(Diagnostic { code: Code::ActivationRefused, surface: resume.surface_key, node: Some(resume.source), detail: detail.into() });
}
}
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.commands.forget(old.key.as_str(), port, &mut self.ledger);
self.ledger.release(port, &Interest::Record(old));
self.scroll = ScrollOffsets::default();
self.last = None;

View file

@ -0,0 +1,51 @@
//! Drafts: the one owner of every input node's uncommitted value, keyed (surface key, laid node id).
//! 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::collections::{HashMap, HashSet};
use thing_contract::{InputValue, NodeId};
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Drafts {
values: HashMap<(String, NodeId), InputValue>,
}
impl Drafts {
pub fn new() -> Self {
Self::default()
}
pub fn set(&mut self, surface: &str, node: &NodeId, value: InputValue) {
self.values.insert((surface.to_string(), node.clone()), value);
}
pub fn get(&self, surface: &str, node: &NodeId) -> Option<&InputValue> {
self.values.get(&(surface.to_string(), node.clone()))
}
/// 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)]) {
for (node, value) in held {
let key = (surface.to_string(), node.clone());
if self.values.get(&key) == Some(value) {
self.values.remove(&key);
}
}
}
/// Keep only the drafts of `surface` whose node is in `live` (the ids of the republished tree);
/// other surfaces' drafts stay.
pub fn retain(&mut self, surface: &str, live: &HashSet<NodeId>) {
self.values.retain(|(held, node), _| held != surface || live.contains(node));
}
pub fn len(&self) -> usize {
self.values.len()
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
}

View file

@ -1,5 +1,8 @@
//! What a host tells core about its user: the closed `InputEvent` vocabulary.
//! 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.
pub mod drafts;
pub mod event;
pub use drafts::Drafts;
pub use event::{InputEvent, Key, Modifiers, PointerButton, WheelUnit};

View file

@ -2,6 +2,7 @@
//! through ports; it reads no clock, spawns nothing and awaits nothing.
pub mod bind;
pub mod command;
pub mod diagnostic;
pub mod frame;
pub mod input;

View file

@ -111,6 +111,12 @@ pub trait StatePort {
fn drain(&mut self) -> Vec<Change>;
}
/// Where core gets the 16 random bytes of an invocation id. Core sets the UUID version and
/// variant bits itself, so a source need only be unpredictable; a test source is a script or a counter.
pub trait IdSource {
fn fill(&mut self, bytes: &mut [u8; 16]);
}
#[cfg(test)]
mod tests {
use super::*;

View file

@ -20,7 +20,6 @@ pub use scroll::{ScrollOffsets, clamp};
use crate::bind::{Bound, BoundTree, Field};
use crate::diagnostic::{Code, Diagnostic};
use crate::layout::{ControlForm, LaidControl, LaidNode, LaidTree, MAX_DEVICE, Measure, Metrics, Rect};
use crate::resolve::grow;
use crate::theme::{Theme, fallback};
/// What a frame is drawn with. `viewport` is what layout was given (logical px or cells).
@ -52,8 +51,7 @@ pub struct Rendered {
}
pub fn render(tree: &BoundTree, laid: &LaidTree, input: &RenderInput, text: &mut dyn Measure) -> Rendered {
let mut nodes = HashMap::new();
index(tree, &tree.resolved().document().root, &mut nodes);
let nodes = tree.index();
let k = match input.metrics {
Metrics::Pixels if input.scale.is_finite() && input.scale > 0.0 => input.scale,
_ => 1.0,
@ -84,37 +82,6 @@ pub fn render(tree: &BoundTree, laid: &LaidTree, input: &RenderInput, text: &mut
painter.out
}
/// Every node of the document by id, Repeat instances included (ids are unique after resolve).
fn index<'a>(tree: &'a BoundTree, node: &'a Node, out: &mut HashMap<&'a NodeId, &'a Node>) {
grow(|| {
let (id, children): (&NodeId, &[Node]) = match node {
Node::Box(n) => (&n.common.id, &n.children),
Node::Button(n) => (&n.common.id, &n.content),
Node::Overlay(n) => (&n.common.id, &n.children),
Node::Repeat(n) => {
for instance in tree.instances(&n.common.id) {
index(tree, &instance.root, out);
}
(&n.common.id, &[])
}
Node::Text(n) => (&n.common.id, &[]),
Node::Image(n) => (&n.common.id, &[]),
Node::Toggle(n) => (&n.common.id, &[]),
Node::Slider(n) => (&n.common.id, &[]),
Node::TextInput(n) => (&n.common.id, &[]),
Node::Select(n) => (&n.common.id, &[]),
Node::Plot(n) => (&n.common.id, &[]),
Node::Embed(n) => (&n.common.id, &[]),
Node::Use(n) => (&n.common.id, &[]),
Node::Slot(_) => return,
};
out.insert(id, node);
for child in children {
index(tree, child, out);
}
})
}
struct Painter<'a> {
tree: &'a BoundTree,
laid: &'a LaidTree,

View file

@ -93,7 +93,7 @@ pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits
key(a).cmp(&key(b))
});
let tree = root.and_then(|root| {
diagnostics.extend(validate::check(&root, limits, &document.record_key()));
diagnostics.extend(validate::check(&root, &document.commands, limits, &document.record_key()));
let refused = diagnostics.iter().any(|diagnostic| diagnostic.code.refuses_document());
// Field by field: `..document.clone()` would clone the whole input tree to discard it.
(!refused).then(|| ResolvedTree {

View file

@ -4,7 +4,7 @@
use std::collections::HashSet;
use thing_contract::{Node, NodeId};
use thing_contract::{CommandDecl, Node, NodeId};
use super::Limits;
use crate::diagnostic::{Code, Diagnostic};
@ -44,8 +44,8 @@ pub(super) fn size(node: &Node) -> usize {
super::grow(|| 1 + children(node).iter().map(size).sum::<usize>())
}
/// Faults of the finished tree, in pre-order: duplicate ids, then depth. A tree deeper than the limit is not walked further.
pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec<Diagnostic> {
/// Faults of the finished tree, in pre-order: duplicate ids, then depth, then each command capture that is not an input node. A tree deeper than the limit is not walked further.
pub(super) fn check(root: &Node, commands: &[CommandDecl], limits: &Limits, surface: &str) -> Vec<Diagnostic> {
let mut found = Vec::new();
let fault = |code, node: Option<&NodeId>, detail: String| Diagnostic {
code,
@ -54,6 +54,7 @@ pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec<Diagnost
detail,
};
let mut seen: HashSet<&NodeId> = HashSet::new();
let mut inputs: HashSet<&NodeId> = HashSet::new();
let mut too_deep = false;
let mut stack = vec![(root, 1usize)];
while let Some((node, depth)) = stack.pop() {
@ -62,6 +63,9 @@ pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec<Diagnost
continue;
}
if let Some(id) = id(node) {
if matches!(node, Node::Toggle(_) | Node::Slider(_) | Node::Select(_) | Node::TextInput(_)) {
inputs.insert(id);
}
if !seen.insert(id) {
found.push(fault(Code::DuplicateNodeId, Some(id), format!("node id '{}' occurs twice", id.as_str())));
}
@ -71,6 +75,11 @@ pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec<Diagnost
if too_deep {
found.push(fault(Code::ExpansionLimit, None, format!("the tree is deeper than {} levels", limits.max_tree_depth)));
}
for capture in commands.iter().flat_map(|decl| &decl.captures) {
if !inputs.contains(capture) {
found.push(fault(Code::CaptureUndeclared, Some(capture), format!("capture '{}' is not an input node of the surface", capture.as_str())));
}
}
found
}

View file

@ -3,3 +3,34 @@
/// Unix milliseconds, UTC.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Timestamp(pub i64);
impl Timestamp {
/// This instant plus `ms` milliseconds, saturating.
pub fn plus_ms(self, ms: u32) -> Timestamp {
Timestamp(self.0.saturating_add(i64::from(ms)))
}
/// RFC 3339 in UTC to whole seconds (an instant inside a second is floored), as
/// `2026-01-01T00:00:00Z`. The civil date comes from days since 1970-01-01 by Hinnant's
/// `civil_from_days`, valid for every date this type holds in the proleptic Gregorian calendar.
pub fn rfc3339(self) -> String {
let seconds = self.0.div_euclid(1000);
let days = seconds.div_euclid(86_400);
let in_day = seconds.rem_euclid(86_400);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let day_of_era = z.rem_euclid(146_097);
let year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let shifted_month = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
let month = if shifted_month < 10 { shifted_month + 3 } else { shifted_month - 9 };
let year = year_of_era + era * 400 + i64::from(month <= 2);
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
in_day / 3600,
in_day % 3600 / 60,
in_day % 60
)
}
}

File diff suppressed because it is too large Load diff

View file

@ -14,6 +14,7 @@ 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::{Call, MemState};
use thing_testkit::state::{self, Swarm};
@ -28,7 +29,7 @@ fn measure(metrics: Metrics) -> FixedMeasure {
}
fn fresh(metrics: Metrics) -> Core {
Core::new(Config::new(metrics), Box::new(measure(metrics)))
Core::new(Config::new(metrics, "renderer.test"), Box::new(measure(metrics)))
}
fn input(viewport: (f32, f32), scale: f32) -> FrameInput {
@ -36,7 +37,7 @@ fn input(viewport: (f32, f32), scale: f32) -> FrameInput {
}
fn run(core: &mut Core, state: &mut MemState, input: FrameInput) -> FrameOutput {
core.frame(input, Ports { state })
core.frame(input, Ports { state, ids: &mut SeqIds::new() })
}
fn show(core: &mut Core, document: &SurfaceDocument) {

View file

@ -0,0 +1,58 @@
//! Id sources for tests: a script of the UUIDs a fixture holds, and a counter.
use thing_core::port::IdSource;
/// Gives the UUIDs it was built with, in order, as the 16 bytes they spell. A fixture id is
/// already v4, so core's version and variant bits leave it as it was. Panics when exhausted.
#[derive(Debug)]
pub struct ScriptedIds {
left: std::vec::IntoIter<[u8; 16]>,
}
impl ScriptedIds {
pub fn new<S: AsRef<str>>(uuids: impl IntoIterator<Item = S>) -> Self {
let decoded: Vec<[u8; 16]> = uuids
.into_iter()
.map(|uuid| {
let digits: Vec<u8> = uuid.as_ref().bytes().filter(|byte| *byte != b'-').collect();
assert_eq!(digits.len(), 32, "{} is not a UUID", uuid.as_ref());
let mut bytes = [0u8; 16];
for (byte, pair) in bytes.iter_mut().zip(digits.chunks(2)) {
*byte = u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).expect("hex digits");
}
bytes
})
.collect();
Self { left: decoded.into_iter() }
}
/// How many ids have not been drawn.
pub fn remaining(&self) -> usize {
self.left.len()
}
}
impl IdSource for ScriptedIds {
fn fill(&mut self, bytes: &mut [u8; 16]) {
*bytes = self.left.next().expect("ScriptedIds ran out of ids");
}
}
/// Counts: the first id spells 1, the next 2.
#[derive(Debug, Default)]
pub struct SeqIds {
next: u128,
}
impl SeqIds {
pub fn new() -> Self {
Self::default()
}
}
impl IdSource for SeqIds {
fn fill(&mut self, bytes: &mut [u8; 16]) {
self.next += 1;
*bytes = self.next.to_be_bytes();
}
}

View file

@ -4,6 +4,7 @@
pub mod build;
pub mod fixture;
pub mod golden;
pub mod ids;
pub mod measure;
pub mod mem_state;
pub mod state;

View file

@ -146,7 +146,10 @@ impl MemState {
}
}
/// A state holding every document of a fixture, each under the provider that publishes it.
/// A state holding every document of a fixture, each under the provider that publishes it. Invocations
/// and results are skipped: they are timeline data, not initial state. A test takes them from
/// `Fixture::load` and puts each result with `put` at its scripted step, after core minted its
/// invocation, and compares that invocation with the fixture's (the fixture is the expected output).
pub fn from_fixture(fixture: crate::fixture::Fixture) -> Self {
let set = fixture.load();
let mut state = Self::new();

View file

@ -8,6 +8,9 @@ use thing_contract::ThingContract;
pub const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z";
/// `PINNED_CLOCK` as core is told time: Unix milliseconds.
pub const PINNED_NOW: thing_core::time::Timestamp = thing_core::time::Timestamp(1_767_225_600_000);
/// A cache with the contract registered and no backing store.
pub fn memory() -> CultCache {
let mut cache = CultCache::new();