Skip to main content

tilo_render_protocol/
patch.rs

1//! Component patches: how a tilolang app's window reaches the room's UI host, and what the
2//! person did comes back.
3//!
4//! The scene protocol carries pixels an app's toolkit recorded. This one carries what a
5//! tilolang app's views *are*: trees of the toolkit's described components
6//! (`tilo_ui_graph::component`) and the language's layout primitives, keyed by stable keys,
7//! and the changes the runtime planned to them. The UI host (the room's render service) holds
8//! the widgets, lays them out, shapes text, draws and takes input; the app (its view
9//! instances, in an app host) holds the data. So:
10//!
11//! - **The app sends its views** ([`ToUi`]): a level's tree when it opens, the runtime's
12//!   patches to it after, the rows of virtual lists the host asked for, what bound controls
13//!   show, and what the window says (a notice, the Ask bar).
14//! - **The host sends what the person did** ([`ToApp`]): events of components (an action
15//!   reference fired by key), edits through bindings (text as splices, so concurrent edits
16//!   merge), the rows a list shows now, focus and composition. Typing shows in the host's text
17//!   field on the next frame; the app hears of it as a splice and never draws it.
18//!
19//! **Transport-agnostic.** A side sends at most one batch per frame: its messages, in order,
20//! encoded as one byte string ([`encode_batch`], [`decode_batch`]). What carries the bytes is
21//! the transport's: a socket between processes with a sealed memfd for a large batch
22//! ([`unix`]), a `postMessage` between a page and a worker in the browser (the bytes are an
23//! `ArrayBuffer` transferred, not copied), or a queue in one process ([`local`]). Nothing here
24//! needs a socket, a thread or a clock, so both ends build for `wasm32`.
25//!
26//! **Hostile until validated.** A batch the UI host receives is decoded once into its own
27//! memory and checked ([`validate`]) against the component descriptions and the window's
28//! budget before any widget is touched; a batch that fails is refused whole and the window
29//! shows the platform's error state, while the host and every other window keep running.
30//! A connection is one window of one app: a patch can only name nodes of the trees that
31//! window's app sent.
32
33use tilo_actions::ActionAddress;
34/// Rich text as a window shows it ([`Value::Rich`]).
35pub use tilo_ui_graph::rich;
36
37use serde::{Deserialize, Serialize};
38
39use crate::WireError;
40
41pub mod diff;
42pub mod local;
43#[cfg(windows)]
44pub mod pipe;
45#[cfg(unix)]
46pub mod unix;
47pub mod validate;
48
49/// The version both ends name. A newer end must still read this one's messages.
50pub const VERSION: u16 = 3;
51
52/// Whether a node of `kind` is a virtual list on the wire: a `ui.VirtualList` or a
53/// `ui.TreeView`, whose rows the app sends apart from the tree ([`ToUi::Rows`]) as the list
54/// shows them. A `list` in a view's content is drawn whole (a card's is its preview), so its
55/// rows travel in the tree.
56#[must_use]
57pub fn is_virtual_list(kind: &str) -> bool {
58    matches!(kind, "ui.VirtualList" | "ui.TreeView" | "ui.MediaGrid")
59}
60
61/// The prop of a view's shell that says the window opened it as a page of its own
62/// (`open(r, view: v)`, a search hit's view): the window places it over what it showed, a list
63/// beside it or not, and gives it the shell's Back.
64pub const PAGE: &str = "page";
65
66/// One window's two views: the app's root, and the view of the resource `open(r)` (or a
67/// row) went to, shown after it.
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
69pub enum Level {
70    Root,
71    Detail,
72}
73
74/// A node of a view's tree: a described component (`ui.ListRow`), a primitive of the language
75/// (`stack`, `row`, `list`), a `slot` holding a component's named slot, or a `fragment`.
76#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
77pub struct Node {
78    pub kind: String,
79    /// Stable for as long as the node shows the same thing: widgets are kept by key.
80    pub key: String,
81    pub props: std::collections::BTreeMap<String, Value>,
82    pub binding: Option<Binding>,
83    /// What each event does, by the event's name.
84    pub events: std::collections::BTreeMap<String, Event>,
85    /// The resource or part a link to this node names.
86    pub anchor: Option<String>,
87    pub children: Vec<Node>,
88}
89
90impl Node {
91    /// A node of `kind` with `key` and nothing else.
92    #[must_use]
93    pub fn empty(kind: &str, key: &str) -> Self {
94        Self {
95            kind: kind.to_owned(),
96            key: key.to_owned(),
97            ..Self::default()
98        }
99    }
100
101    /// The node at `path` (keys from this node's children down), if there is one.
102    #[must_use]
103    pub fn at(&self, path: &[String]) -> Option<&Self> {
104        let mut node = self;
105        for key in path {
106            node = node.children.iter().find(|child| child.key == *key)?;
107        }
108        Some(node)
109    }
110
111    /// The node at `path`, to change it.
112    pub fn at_mut(&mut self, path: &[String]) -> Option<&mut Self> {
113        let mut node = self;
114        for key in path {
115            node = node.children.iter_mut().find(|child| child.key == *key)?;
116        }
117        Some(node)
118    }
119
120    /// The node whose key is `key`, anywhere under this one (this one included); the first
121    /// found, depth first.
122    #[must_use]
123    pub fn find(&self, key: &str) -> Option<&Self> {
124        if self.key == key {
125            return Some(self);
126        }
127        self.children.iter().find_map(|child| child.find(key))
128    }
129
130    /// Every node of `kind` under this one (this one included), in drawing order.
131    #[must_use]
132    pub fn of_kind(&self, kind: &str) -> Vec<&Self> {
133        let mut out = Vec::new();
134        let mut at = vec![self];
135        while let Some(node) = at.pop() {
136            if node.kind == kind {
137                out.push(node);
138            }
139            at.extend(node.children.iter().rev());
140        }
141        out
142    }
143
144    /// The first node of `kind` under this one (this one included), in drawing order.
145    #[must_use]
146    pub fn first_of_kind(&self, kind: &str) -> Option<&Self> {
147        self.of_kind(kind).into_iter().next()
148    }
149
150    /// How many nodes the tree holds, this one included.
151    #[must_use]
152    pub fn count(&self) -> usize {
153        1usize.saturating_add(self.children.iter().map(Self::count).sum::<usize>())
154    }
155}
156
157/// A resource a node shows or an event carries: its id in the room, and its type.
158#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
159pub struct ResourceRef {
160    pub id: String,
161    pub ty: String,
162}
163
164impl ResourceRef {
165    /// The id the resource is named by.
166    #[must_use]
167    pub fn id_string(&self) -> String {
168        self.id.clone()
169    }
170}
171
172/// Who acted, what the workspace calls them, and the colour it paints them in.
173#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
174pub struct Actor {
175    pub id: tilo_actions::Actor,
176    pub name: String,
177    /// The presence palette slot the workspace paints them in: their chosen colour, else the one
178    /// who they are gives them. `None` where the sender does not know the workspace's members,
179    /// and the window derives it from `id` by the same rule.
180    #[serde(default)]
181    pub hue: Option<u8>,
182    /// The picture the workspace shows for them, as the address a face reads its bytes from (a
183    /// `data:` or `tilo-blob://` URL). `None` shows their initials.
184    #[serde(default)]
185    pub picture: Option<String>,
186}
187
188/// A value a node holds: the language's values as a view shows them. Formatting (a date the
189/// person's way, a number with their separators) is the host's, so values travel as they are.
190#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
191pub enum Value {
192    Unit,
193    Int(i64),
194    Float(f64),
195    Bool(bool),
196    Text(String),
197    List(Vec<Value>),
198    Opt(Option<Box<Value>>),
199    /// A case of an enum, by name.
200    Enum(String),
201    /// A case of an enum whose cases carry fields, by name, with its fields by name: a
202    /// drawing's `arc`.
203    Case {
204        case: String,
205        fields: Vec<(String, Value)>,
206    },
207    Ref(ResourceRef),
208    Actor(Actor),
209    /// Rich text, with how each reference in it reads for the person reading it.
210    Rich(rich::RichText),
211    /// What a failed or refused part of a view shows.
212    Error(String),
213    /// A map's entries, each key once, in key order.
214    Map(Vec<(Value, Value)>),
215    /// An action offered to the person: how a control shows it, and the event of its node
216    /// that choosing it fires.
217    Action(Offered),
218    /// A picture: where its bytes are read from, and what it says to assistive technology.
219    Picture(Picture),
220    /// A file a person handed the window (dropped on it, or chosen): what it is called, its
221    /// media type, its size and the content address its bytes are at.
222    File(File),
223    /// A record a view names: what refers to it, and how it reads for the person now.
224    Link {
225        reference: String,
226        title: String,
227    },
228}
229
230/// A file a node hands over ([`Value::File`]): its name, media type, size and content address.
231pub use tilo_ui_graph::component::File;
232/// An action a node offers ([`Value::Action`]), as the toolkit holds one.
233pub use tilo_ui_graph::component::Offered;
234/// A picture a node shows ([`Value::Picture`]): its address, and its accessible name.
235pub use tilo_ui_graph::component::Picture;
236
237/// The description of the component a node of `kind` is of (`ui.BlockEditor`): what its props
238/// are, which is the one list of them a host reads a node's values by.
239#[must_use]
240pub fn description(kind: &str) -> Option<&'static tilo_ui_graph::component::Description> {
241    tilo_ui_graph::component::catalogue().get(kind.strip_prefix("ui.")?)
242}
243
244/// The type a described component's prop takes, as the catalogue declares it.
245pub use tilo_ui_graph::component::Type as PropType;
246
247impl Value {
248    #[must_use]
249    pub fn text(text: impl Into<String>) -> Self {
250        Self::Text(text.into())
251    }
252
253    #[must_use]
254    pub fn some(value: Self) -> Self {
255        Self::Opt(Some(Box::new(value)))
256    }
257}
258
259/// What a bound control edits, as the host needs to show and announce it.
260#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
261pub struct Binding {
262    /// The record it edits, by the id its app publishes it under, and the field; `None` for the
263    /// view's own state.
264    pub field: Option<(String, String)>,
265    /// The kind its app publishes that record as (`tl.so.tilo.notes.Note`), when it edits
266    /// one: with the record, what names the place a control edits however the window composes
267    /// around it, as an action on the record is named. Every field is written, `None` included:
268    /// the batch is postcard, which cannot skip one.
269    pub kind: Option<String>,
270    /// What it is called, for assistive technology.
271    pub name: String,
272}
273
274impl Binding {
275    /// The resource (by id) and field it edits, when it edits one.
276    #[must_use]
277    pub fn field(&self) -> Option<(&str, &str)> {
278        self.field
279            .as_ref()
280            .map(|(target, field)| (target.as_str(), field.as_str()))
281    }
282}
283
284/// An event a node's view gave it. What it does is the app's: the host reports the event by
285/// the node's key and name, and the app applies the action reference its view attached. The
286/// host knows only, when that action toggles a field of a resource (`pin` toggles `pinned`),
287/// which, so a header does not repeat a control that stands for it; and which action on which
288/// resource it runs, so a menu the system completes does not offer it twice.
289#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
290pub struct Event {
291    pub toggles: Option<(String, String)>,
292    /// What the event runs, when it runs an action on a resource.
293    pub invokes: Option<Invocation>,
294}
295
296/// An action one event runs, by the address the API runs it by: the resource and the action as
297/// the app publishes it there. That address is what the control says it does: nothing the window
298/// composes around it and no language changes it.
299#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
300pub struct Invocation {
301    /// The resource the action runs on, by the id the app publishes it under.
302    pub resource: String,
303    /// The action as the app publishes it there (`new_note`).
304    pub action: String,
305}
306
307/// One change of a level's tree, against the tree the ones before it left. Paths are keys from
308/// the root's children down; the root is the empty path.
309#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
310pub enum Patch {
311    /// The root itself changed kind or key: the tree anew.
312    SetRoot(Node),
313    Insert {
314        parent: Vec<String>,
315        index: u32,
316        node: Node,
317    },
318    Remove {
319        parent: Vec<String>,
320        key: String,
321    },
322    Move {
323        parent: Vec<String>,
324        key: String,
325        to: u32,
326    },
327    SetProp {
328        path: Vec<String>,
329        name: String,
330        value: Option<Value>,
331    },
332    SetBinding {
333        path: Vec<String>,
334        binding: Option<Binding>,
335    },
336    SetEvent {
337        path: Vec<String>,
338        event: String,
339        action: Option<Event>,
340    },
341    SetAnchor {
342        path: Vec<String>,
343        anchor: Option<String>,
344    },
345    /// Part of a list prop replaced in place: `remove` items from `at` on taken out and
346    /// `insert` put there. A long list (a collection's items) changes by what changed, never
347    /// sent whole again.
348    SpliceProp {
349        path: Vec<String>,
350        name: String,
351        at: u32,
352        remove: u32,
353        insert: Vec<Value>,
354    },
355}
356
357/// Why `apply` could not take a patch: it names a node the tree does not have.
358#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
359#[error("a patch names a node the tree does not have")]
360pub struct Unapplied;
361
362impl Patch {
363    /// Apply this patch to `root`.
364    pub fn apply(self, root: &mut Node) -> Result<(), Unapplied> {
365        match self {
366            Self::SetRoot(node) => *root = node,
367            Self::Insert {
368                parent,
369                index,
370                node,
371            } => {
372                let parent = root.at_mut(&parent).ok_or(Unapplied)?;
373                let index = usize::try_from(index)
374                    .unwrap_or(usize::MAX)
375                    .min(parent.children.len());
376                parent.children.insert(index, node);
377            }
378            Self::Remove { parent, key } => {
379                let parent = root.at_mut(&parent).ok_or(Unapplied)?;
380                let at = parent
381                    .children
382                    .iter()
383                    .position(|child| child.key == key)
384                    .ok_or(Unapplied)?;
385                parent.children.remove(at);
386            }
387            Self::Move { parent, key, to } => {
388                let parent = root.at_mut(&parent).ok_or(Unapplied)?;
389                let at = parent
390                    .children
391                    .iter()
392                    .position(|child| child.key == key)
393                    .ok_or(Unapplied)?;
394                let moved = parent.children.remove(at);
395                let to = usize::try_from(to)
396                    .unwrap_or(usize::MAX)
397                    .min(parent.children.len());
398                parent.children.insert(to, moved);
399            }
400            Self::SetProp { path, name, value } => {
401                let node = root.at_mut(&path).ok_or(Unapplied)?;
402                match value {
403                    Some(value) => {
404                        node.props.insert(name, value);
405                    }
406                    None => {
407                        node.props.remove(&name);
408                    }
409                }
410            }
411            Self::SetBinding { path, binding } => {
412                root.at_mut(&path).ok_or(Unapplied)?.binding = binding;
413            }
414            Self::SetEvent {
415                path,
416                event,
417                action,
418            } => {
419                let node = root.at_mut(&path).ok_or(Unapplied)?;
420                match action {
421                    Some(action) => {
422                        node.events.insert(event, action);
423                    }
424                    None => {
425                        node.events.remove(&event);
426                    }
427                }
428            }
429            Self::SetAnchor { path, anchor } => {
430                root.at_mut(&path).ok_or(Unapplied)?.anchor = anchor;
431            }
432            Self::SpliceProp {
433                path,
434                name,
435                at,
436                remove,
437                insert,
438            } => {
439                let node = root.at_mut(&path).ok_or(Unapplied)?;
440                let Some(Value::List(items)) = node.props.get_mut(&name) else {
441                    return Err(Unapplied);
442                };
443                let at = usize::try_from(at).map_err(|_| Unapplied)?;
444                let end = at
445                    .checked_add(usize::try_from(remove).map_err(|_| Unapplied)?)
446                    .filter(|end| *end <= items.len())
447                    .ok_or(Unapplied)?;
448                items.splice(at..end, insert);
449            }
450        }
451        Ok(())
452    }
453}
454
455/// A change of a virtual list's rows, against the rows the ones before it left.
456#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
457pub enum RowChange {
458    Inserted {
459        index: u32,
460        key: String,
461    },
462    Removed {
463        index: u32,
464    },
465    Moved {
466        from: u32,
467        to: u32,
468    },
469    /// A rendered row shows something else now: boxed, as one row is far larger than the index
470    /// changes beside it.
471    Changed {
472        row: Box<Node>,
473    },
474    /// The list was replaced as a whole: its rows are read anew.
475    Reset,
476}
477
478/// Words the window says: a phrase of the platform's catalogue (the host says it in the
479/// person's language), or text the app made (an error, an action's label).
480#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
481pub enum Words {
482    Phrase {
483        id: String,
484        args: Vec<(String, String)>,
485    },
486    Plain(String),
487}
488
489impl Words {
490    #[must_use]
491    pub fn phrase(id: &str) -> Self {
492        Self::Phrase {
493            id: id.to_owned(),
494            args: Vec::new(),
495        }
496    }
497}
498
499/// What kind of notice the window shows: the tone its icon and colour take.
500#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
501pub enum NoticeKind {
502    Info,
503    Error,
504    Success,
505    Warning,
506}
507
508/// What brings the window's content column to the front of a narrow window.
509#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
510pub enum Front {
511    /// What the person did last: a click slides it in, a key lands it.
512    Input,
513    /// An agent, a script or a search hit: it lands at once.
514    Action,
515}
516
517/// The Ask bar: trusted chrome naming who asks for what.
518#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
519pub struct Ask {
520    /// The action, as its package names it.
521    pub action: String,
522    /// Who asks.
523    pub invoker: String,
524}
525
526/// A person's answer to the Ask bar.
527#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
528pub enum Answer {
529    Allow,
530    Decline,
531    Always,
532}
533
534/// An action waiting for its arguments: the form the window shows for what the invocation still
535/// needs. The app derives its fields from the action's parameters (each control from the
536/// parameter's type), keeps what the person typed as their lens state, and checks each value as
537/// the action takes it; the window presents the fields (a sheet over the window, a popover at the
538/// control it came from, a sheet from the foot of a narrow window) with the title, submit and
539/// cancel, and reports edits by field.
540#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
541#[allow(
542    clippy::struct_excessive_bools,
543    reason = "each bool is an independent facet the app decides about its form"
544)]
545pub struct Form {
546    /// Which form: edits and answers name it, so ones for a form that closed are dropped.
547    pub id: u64,
548    /// The action, as its label names it ("Share…").
549    pub title: String,
550    /// The submit button's label: the action's label without its ellipsis ("Share").
551    pub submit: String,
552    /// The action takes something away: the submit button is destructive.
553    pub destructive: bool,
554    /// Every argument parses as its type: submit can be taken.
555    pub ready: bool,
556    /// Why the action refused the last submit, when that names no field.
557    pub error: Option<String>,
558    /// The control that ran the action, by level and key: a popover form is anchored to it.
559    pub from: Option<(Level, String)>,
560    /// Each field's control in `tree` by key, in order, with the text it holds now (what the
561    /// person typed, else the default): the window shows it when the form opens.
562    pub fields: Vec<(String, String)>,
563    /// Every field is short (one line, a switch or a choice): a popover can hold them.
564    pub short: bool,
565    /// The controls whose choice answers the form by itself, by key: a form's quick choices,
566    /// where a pick says everything the form asks, so one tap is one answer.
567    pub answers: Vec<String>,
568    /// Offer the submit button: a form whose quick choices answer it needs none until the
569    /// person is on the way in by hand, so its footer stands as Cancel alone.
570    pub confirm: bool,
571    /// The fields, laid out: a tree of the same components and content nodes views send.
572    pub tree: Node,
573}
574
575/// What an app sends its window.
576#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
577pub enum ToUi {
578    /// The window shows the platform's loading state until a level opens.
579    Loading,
580    /// A level opened (or opened anew): its view's tree, without the rows of its virtual lists,
581    /// and the resource it shows. A detail opening with `front` comes to the front of a narrow
582    /// window. `capture_protected` says the view declares `protect capture`: wherever it is
583    /// shown, a capture or a stream leaves it out.
584    Open {
585        level: Level,
586        target: ResourceRef,
587        tree: Node,
588        front: Option<Front>,
589        capture_protected: bool,
590    },
591    /// The detail level closed.
592    Close,
593    /// A level's page comes to the front of a narrow window. When the window draws the item its
594    /// own view shows in place (a tree beside what it shows), `shows` is that item and the press
595    /// that showed it: what the person types after that press belongs to it.
596    Front {
597        front: Front,
598        shows: Option<(u64, ResourceRef)>,
599    },
600    /// The runtime's patches to a level's tree.
601    Patch { level: Level, patches: Vec<Patch> },
602    /// What the bound control `key` shows now. `acked` is the last of its splices the app took:
603    /// the host keeps what the person typed after it.
604    Bound {
605        level: Level,
606        key: String,
607        value: Value,
608        acked: u64,
609    },
610    /// Rows of the virtual list `list` (its key in the level): how many it has, the keys of
611    /// those from `start` on, and those of them rendered.
612    Rows {
613        level: Level,
614        list: String,
615        len: u32,
616        start: u32,
617        keys: Vec<String>,
618        rows: Vec<Node>,
619    },
620    /// What changed of a virtual list's rows, and how many it has now.
621    RowsChanged {
622        level: Level,
623        list: String,
624        len: u32,
625        changes: Vec<RowChange>,
626    },
627    /// The view calls of a level that read the space layout gives them, by the keys of their
628    /// `fragment`s: what the window measures, so each runs again with the size it was given,
629    /// live, and no view that reads none costs a measure. The root view's own is the level's,
630    /// which the window tells anyway. Sent when the set changes.
631    Spaces { level: Level, keys: Vec<String> },
632    Notice {
633        words: Words,
634        kind: NoticeKind,
635        /// The notice offers Undo.
636        undo: bool,
637    },
638    /// The Ask bar, or none.
639    Ask(Option<Ask>),
640    /// The form of an action waiting for its arguments, or none: it closed (submitted,
641    /// cancelled, or the action ran).
642    Form(Option<Box<Form>>),
643    /// Someone asked to see the window ("Show this window"): it comes forward.
644    Activate,
645    /// A change mark was activated: show what the task run `run` (its group,
646    /// `runtime_collab::task_run_group`) did, where the system keeps its log.
647    ShowRun { run: String },
648    /// The app ran the first `fired` presses the window sent (`ToApp::Fire`), and sent what
649    /// they opened before this. What the person typed after a press goes to the app once it
650    /// ran it, into the field focused then.
651    Took { fired: u64 },
652    /// What changed of the actions the app offers the person at this window, as their command
653    /// palette lists them: the change of its published surface the broker takes (a
654    /// `SurfaceDelta`, JSON), so each action's description crosses once per resource type
655    /// and a resource as its address and what differs for it. Bytes, not a byte at a time: the
656    /// first one holds every shape.
657    Actions(#[serde(with = "serde_bytes")] Vec<u8>),
658    /// The language the window reads in now (`de-DE`): the person chose another in Settings while
659    /// it is open. Its own chrome relabels in it, as the app's words the app sends do.
660    Speak(String),
661    /// Whether the app holds changes of the person's that the workspace has not taken yet: the
662    /// window marks them unsaved and offers to try again ([`ToApp::SaveAgain`]) until it has.
663    Kept(bool),
664    /// What the app's connection heard of the people at the app, which the window shows as a
665    /// window with a connection of its own does: the member list, a step of an agent's action.
666    /// Carried as the JSON the window's toolkit reads it as.
667    Heard(#[serde(with = "serde_bytes")] Vec<u8>),
668    /// Whether the window shows the history of what it shows now ([`ToApp::History`]): its bar's
669    /// History control stands open while it does. Back, or opening something else, closes it.
670    History(bool),
671    /// Ask the window's page engine to do something, as the app's page actions do: `request` is
672    /// the page's own request, encoded (`tilo_webview`'s page protocol), which the window runs
673    /// on the engine it holds for this window and answers with [`ToApp::PageAnswer`].
674    Page {
675        request_id: u32,
676        #[serde(with = "serde_bytes")]
677        request: Vec<u8>,
678    },
679    /// The places a playback plays, as the app's `outputs` Collection stands now: JSON, one item
680    /// per place with the Collection item's id and the `Output` type's fields. The window process
681    /// plays them on the computer's sound devices and casts to a receiver (`tilo-media`'s
682    /// playback bridge); it is sent only when the Collection changed.
683    Outputs(#[serde(with = "serde_bytes")] Vec<u8>),
684    /// The pictures of the system's call the window shows: every picture the app's view shows now
685    /// as a tile (`shown`, so a tile whose person stopped showing forgets its last frame), and the
686    /// pictures the call delivered since the last message. The window decodes them where it draws
687    /// (`ui::live_pictures`), which is what a call's tile reads.
688    CallPictures {
689        shown: Vec<CallShown>,
690        pictures: Vec<CallPicture>,
691    },
692    /// Where the keyboard goes, as the app asks: `Some(key)` moves it to the control with that
693    /// test id, `None` ends its place in an editor (the `blur()` a view applies), as closing the
694    /// editor does. The window answers through the same focus request a widget builds with.
695    Focus { key: Option<String> },
696    /// The app closes its window (the `close()` a view applies, as a terminal whose shell exited
697    /// does): it goes as the person closing it does.
698    CloseWindow,
699}
700
701/// Which of a person's pictures a call tile shows.
702#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
703#[serde(rename_all = "snake_case")]
704pub enum CallPictureSource {
705    Camera,
706    Screen,
707}
708
709/// One picture a view's call tiles show: a person's camera or the screen they share.
710#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
711#[serde(deny_unknown_fields)]
712pub struct CallShown {
713    /// The person, as the workspace names them (their root key, lowercase hex).
714    pub person: String,
715    pub source: CallPictureSource,
716}
717
718/// One picture the call delivered for a tile: the tilo-video/1 object of a person's camera or
719/// screen, as the call received it.
720#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
721#[serde(deny_unknown_fields)]
722pub struct CallPicture {
723    /// The person it shows.
724    pub person: String,
725    /// The stream it belongs to: one participation's source, for as long as that participation
726    /// lasts. A person on two devices, or back after leaving, is another stream; a decoder starts
727    /// over with each.
728    pub stream: String,
729    pub source: CallPictureSource,
730    /// The tilo-video/1 object: header and access unit.
731    #[serde(with = "serde_bytes")]
732    pub object: Vec<u8>,
733}
734
735/// The most pictures one [`ToUi::CallPictures`] carries, and the most a tile set shows: what a
736/// call view draws at once (`tilo_actions::remote::native_media::MAX_SHOWN`).
737pub const MAX_CALL_PICTURES: usize = 64;
738
739/// The largest a [`CallPicture`]'s object is: one coded picture of a call
740/// (`tilo_actions::remote::native_media::MAX_PICTURE_BYTES`).
741pub const MAX_CALL_PICTURE_BYTES: usize = 512 * 1024;
742
743/// The modifier keys held while the person pressed: what a tilolang press reads as
744/// `host.Press`. `command` is Ctrl, or ⌘ on a Mac.
745#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
746pub struct Held {
747    pub shift: bool,
748    pub command: bool,
749    pub alt: bool,
750}
751
752/// What the person did, as the window tells its app.
753#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
754pub enum ToApp {
755    /// The event `event` of the node `key` happened, carrying `value` when it carries one.
756    Fire {
757        level: Level,
758        key: String,
759        event: String,
760        value: Option<Value>,
761        /// The gesture the event is one part of, when the person's act made more than one change
762        /// (a picture pasted into a document, and the app naming it): its action's change names
763        /// it, as the edit that came with it does, so one undo takes both back. A uuid's text.
764        gesture: Option<String>,
765    },
766    /// The checkbox or switch `key` of the view of `target` is now `checked`.
767    ///
768    /// An edit names the resource the level showed when the person made it: it applies to that
769    /// resource, whatever the level shows by the time the app takes it.
770    Toggle {
771        level: Level,
772        target: ResourceRef,
773        key: String,
774        checked: bool,
775    },
776    /// Text typed into the bound control `key` of the view of `target`: `delete` bytes at byte
777    /// `at` replaced by `insert`, against what the control showed. `seq` counts the control's
778    /// splices.
779    Splice {
780        level: Level,
781        target: ResourceRef,
782        key: String,
783        seq: u64,
784        at: u32,
785        delete: u32,
786        insert: String,
787    },
788    /// The bound control `key` of the view of `target`, which edits a value other than text (a
789    /// number, a date), now holds `text`.
790    Edit {
791        level: Level,
792        target: ResourceRef,
793        key: String,
794        text: String,
795    },
796    /// The bound rich-text control `key` of the view of `target` now holds `rich`: its
797    /// paragraphs, marks and references (the runtime brings the field to it by splices and
798    /// marks).
799    EditRich {
800        level: Level,
801        target: ResourceRef,
802        key: String,
803        rich: rich::RichText,
804        /// The gesture the edit is one part of, when the person's act made more than one change
805        /// ([`ToApp::Fire`]'s `gesture`): both changes are one step of theirs.
806        gesture: Option<String>,
807    },
808    /// The suggestion in the invocation card `key` was allowed or declined, as a window that drew
809    /// answers on the card sends it. Only the system's confirm answers a call that asks a person,
810    /// so an app refuses it; it keeps its place so an older window's messages still read.
811    Resolve {
812        level: Level,
813        key: String,
814        approve: bool,
815    },
816    /// A component presenting `resource` was activated: show it.
817    Open {
818        resource: ResourceRef,
819    },
820    /// A reference in rich text was activated: open what it refers to, `reference` being the
821    /// `mention` mark's value (`tilo_reference::embed`).
822    OpenReference {
823        reference: String,
824    },
825    /// Back from the detail level.
826    Back,
827    /// The virtual list `list` shows the rows `start..end` now, the row `open` — its key —
828    /// stands open into its item where it stands ([`ToUi::Rows`] answers with its document), and
829    /// the person opened the menu of the row `menu`, which the app sends again with it.
830    ///
831    /// `store` is the identity of the window's store for that list, minted when the store is
832    /// made: a list the window has just built asks with one no answer of the app's was rendered
833    /// for, so every row of the range comes again rather than being left to a store that no
834    /// longer exists.
835    Rows {
836        level: Level,
837        list: String,
838        start: u32,
839        end: u32,
840        open: Option<String>,
841        menu: Option<String>,
842        store: u64,
843    },
844    Answer(Answer),
845    /// The field `field` (a key of [`Form::fields`]) of the form `form` now holds `text`: what
846    /// was typed, a case or a resource chosen by its name or id, `true` or `false`.
847    FormEdit {
848        form: u64,
849        field: String,
850        text: String,
851    },
852    /// The form `form` was submitted.
853    FormSubmit {
854        form: u64,
855    },
856    /// The form `form` was closed without submitting: what was typed stays for next time.
857    FormCancel {
858        form: u64,
859    },
860    /// The person asked to take back their last step: Undo on a notice, or the window's undo
861    /// (Ctrl+Z, Edit › Undo). The record's undo, the one undo there is: a field the person typed
862    /// into keeps no history of its own beside it.
863    Undo,
864    /// The keyboard focus is in the bound control `key` of `level`, or in none.
865    Focus {
866        at: Option<(Level, String)>,
867    },
868    /// An input method is composing in the focused control, or stopped.
869    Composing(bool),
870    /// The modifier keys held with the pointer now, sent before the event they came with when
871    /// they changed: a press with Shift adds to a selection, one with the command key toggles.
872    Held(Held),
873    /// Layout gave a view of `level` the space `width` by `height` of the window, in `rem` (the
874    /// body text size after the person's setting): what its `space` reads (layout.md, "Responding
875    /// to space"). `key` is the view call's `fragment`, as [`ToUi::Spaces`] named it, or empty for
876    /// the level's own root. `rem` is that body text size in logical pixels, which a view computes
877    /// a place in pixels from (a card it keeps where the person dropped it).
878    Space {
879        level: Level,
880        key: String,
881        width: f32,
882        height: f32,
883        rem: f32,
884    },
885    /// The person asked to bring back what their last undo took back: the window's redo
886    /// (Ctrl+Shift+Z, Edit › Redo). The mirror of [`ToApp::Undo`].
887    Redo,
888    /// The person chose the action `address` from the window's command palette, with the
889    /// argument the palette collected: the app runs it as the person's own step.
890    Invoke {
891        address: ActionAddress,
892        argument: Option<String>,
893    },
894    /// The person asked to save the changes the workspace has not taken yet again
895    /// ([`ToUi::Kept`]).
896    SaveAgain,
897    /// The window bar's History control was pressed: show the system's history of the resource
898    /// the window shows (`open`), or close it and show the resource again.
899    History {
900        open: bool,
901    },
902    /// What the person does from now on serves `call`, the invocation they signed for it, as the
903    /// member `invoker` names (a stamp's invoker): each change it makes keeps the call, for the
904    /// holders that check it. An empty call ends it: what follows is the window's own. A window
905    /// shown on a web page sends it around each of its reader's acts. The call is carried as its
906    /// JSON, as its argument is.
907    Serving {
908        #[serde(with = "serde_bytes")]
909        call: Vec<u8>,
910        invoker: Option<String>,
911    },
912    /// What became of the page request [`ToUi::Page`] asked for: the page's own answer, encoded,
913    /// or a refusal. A page that is gone answers too, so a waiting action is never left waiting.
914    PageAnswer {
915        request_id: u32,
916        #[serde(with = "serde_bytes")]
917        answer: Vec<u8>,
918    },
919    /// The window's page started or stopped waiting on the person's yes (a site asking for the
920    /// camera, a download it offers, a server's sign-in, a request kept from leaving): the
921    /// engine's prompt, encoded (`tilo_page_engine::codec::prompt_json`). The app raises one as
922    /// its call of its own action, which the system keeps as an asked record, and withdraws that
923    /// call once the page no longer waits.
924    PagePrompt {
925        #[serde(with = "serde_bytes")]
926        prompt: Vec<u8>,
927    },
928}
929
930/// Largest batch either side sends or accepts.
931pub const MAX_BATCH_BYTES: usize = 16 << 20;
932
933/// Largest page request or answer one message carries: a page's reading, its outline and a
934/// picture of it fit, and nothing a page could say grows a window without bound.
935pub const MAX_PAGE_BYTES: usize = 8 << 20;
936
937/// One frame's messages as the bytes a transport carries.
938///
939/// # Errors
940/// The messages encode to more than [`MAX_BATCH_BYTES`].
941pub fn encode_batch<T: Serialize>(messages: &[T]) -> Result<Vec<u8>, WireError> {
942    let mut bytes = Vec::with_capacity(64);
943    bytes.extend_from_slice(&VERSION.to_le_bytes());
944    let bytes = postcard::to_extend(messages, bytes).map_err(|_| WireError::Malformed("batch"))?;
945    if bytes.len() > MAX_BATCH_BYTES {
946        return Err(WireError::OverLimit("batch size"));
947    }
948    Ok(bytes)
949}
950
951/// The messages of a batch, read once into the receiver's memory.
952///
953/// # Errors
954/// The bytes are no batch of this version, or are over [`MAX_BATCH_BYTES`].
955pub fn decode_batch<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<Vec<T>, WireError> {
956    if bytes.len() > MAX_BATCH_BYTES {
957        return Err(WireError::OverLimit("batch size"));
958    }
959    let (version, body) = bytes.split_at_checked(2).ok_or(WireError::Truncated)?;
960    if version != VERSION.to_le_bytes() {
961        return Err(WireError::Malformed("batch version"));
962    }
963    let (messages, rest) =
964        postcard::take_from_bytes(body).map_err(|_| WireError::Malformed("batch"))?;
965    if !rest.is_empty() {
966        return Err(WireError::Malformed("bytes after a batch"));
967    }
968    Ok(messages)
969}
970
971/// What carries one side's batches to the other: a queue in one process, a socket and ring
972/// between processes, `postMessage` between a page and a worker. At most one batch a frame.
973pub trait Transport {
974    /// Hand `batch` to the other side.
975    fn send(&mut self, batch: Vec<u8>) -> Result<(), WireError>;
976
977    /// The next batch the other side sent, when one waits.
978    fn recv(&mut self) -> Result<Option<Vec<u8>>, WireError>;
979}
980
981#[cfg(test)]
982mod tests {
983    use super::*;
984
985    fn text(key: &str, value: &str) -> Node {
986        let mut node = Node::empty("ui.Text", key);
987        node.props.insert("value".to_owned(), Value::text(value));
988        node
989    }
990
991    #[test]
992    fn patches_apply_by_key_and_refuse_a_node_the_tree_lacks() {
993        let mut root = Node::empty("stack", "s");
994        root.children = vec![text("a", "1"), text("b", "2")];
995        Patch::Insert {
996            parent: Vec::new(),
997            index: 0,
998            node: text("n", "0"),
999        }
1000        .apply(&mut root)
1001        .expect("applies");
1002        Patch::Move {
1003            parent: Vec::new(),
1004            key: "b".to_owned(),
1005            to: 1,
1006        }
1007        .apply(&mut root)
1008        .expect("applies");
1009        Patch::SetProp {
1010            path: vec!["a".to_owned()],
1011            name: "value".to_owned(),
1012            value: Some(Value::text("3")),
1013        }
1014        .apply(&mut root)
1015        .expect("applies");
1016        let keys: Vec<&str> = root.children.iter().map(|c| c.key.as_str()).collect();
1017        assert_eq!(keys, ["n", "b", "a"]);
1018        assert_eq!(
1019            root.find("a").and_then(|a| a.props.get("value")),
1020            Some(&Value::text("3"))
1021        );
1022        assert_eq!(
1023            Patch::Remove {
1024                parent: vec!["nowhere".to_owned()],
1025                key: "a".to_owned()
1026            }
1027            .apply(&mut root),
1028            Err(Unapplied)
1029        );
1030    }
1031
1032    #[test]
1033    fn a_batch_reads_back_as_it_was_sent_and_scribbles_are_refused() {
1034        let batch = vec![
1035            ToUi::Open {
1036                level: Level::Root,
1037                target: ResourceRef {
1038                    id: "doc".to_owned(),
1039                    ty: "notes.Notebook".to_owned(),
1040                },
1041                tree: text("t", "Notes"),
1042                front: None,
1043
1044                capture_protected: false,
1045            },
1046            ToUi::Patch {
1047                level: Level::Root,
1048                patches: vec![Patch::SetProp {
1049                    path: Vec::new(),
1050                    name: "value".to_owned(),
1051                    value: Some(Value::text("Ideas")),
1052                }],
1053            },
1054        ];
1055        let bytes = encode_batch(&batch).expect("encodes");
1056        let back: Vec<ToUi> = decode_batch(&bytes).expect("decodes");
1057        assert_eq!(back, batch);
1058        for cut in 0..bytes.len() {
1059            let truncated: Result<Vec<ToUi>, _> = decode_batch(&bytes[..cut]);
1060            assert!(truncated.is_err() || cut == bytes.len());
1061        }
1062        let mut other = bytes;
1063        other[0] = 9;
1064        assert!(decode_batch::<ToUi>(&other).is_err(), "another version");
1065    }
1066
1067    #[test]
1068    fn rich_text_reads_back_as_it_was_sent_with_or_without_its_parts() {
1069        let reference = r#"{"app":"a.b","id":"t1","kind":"a.task"}"#;
1070        let rich = |marks: Vec<rich::Mark>, embeds: Vec<rich::Embed>| rich::RichText {
1071            blocks: vec![rich::Block {
1072                kind: "paragraph".to_owned(),
1073                text: "see Fix it".to_owned(),
1074                marks,
1075                attrs: std::collections::BTreeMap::new(),
1076            }],
1077            styles: std::collections::BTreeMap::default(),
1078            embeds,
1079        };
1080        let batch: Vec<ToUi> = [
1081            rich(Vec::new(), Vec::new()),
1082            rich(
1083                vec![rich::Mark {
1084                    start: 4,
1085                    end: 10,
1086                    name: "mention".to_owned(),
1087                    value: rich::Attr::Text(reference.to_owned()),
1088                }],
1089                vec![
1090                    rich::Embed {
1091                        reference: reference.to_owned(),
1092                        view: rich::InlineView::Resource {
1093                            title: "Fix the build".to_owned(),
1094                            icon: None,
1095                            detail: None,
1096                        },
1097                        preview: None,
1098                    },
1099                    rich::Embed {
1100                        reference: "u-ada".to_owned(),
1101                        view: rich::InlineView::Unreadable,
1102                        preview: None,
1103                    },
1104                ],
1105            ),
1106        ]
1107        .into_iter()
1108        .map(|value| ToUi::Patch {
1109            level: Level::Root,
1110            patches: vec![Patch::SetProp {
1111                path: Vec::new(),
1112                name: "value".to_owned(),
1113                value: Some(Value::Rich(value)),
1114            }],
1115        })
1116        .collect();
1117        let bytes = encode_batch(&batch).expect("encodes");
1118        assert_eq!(decode_batch::<ToUi>(&bytes).expect("decodes"), batch);
1119    }
1120
1121    #[test]
1122    fn a_rich_inputs_edit_round_trips_empty_or_not() {
1123        let plain = rich::RichText {
1124            blocks: vec![rich::Block {
1125                kind: "paragraph".into(),
1126                text: "hi".into(),
1127                ..rich::Block::default()
1128            }],
1129            embeds: Vec::new(),
1130            styles: std::collections::BTreeMap::default(),
1131        };
1132        for rich in [rich::RichText::default(), plain] {
1133            let edit = vec![ToApp::EditRich {
1134                level: Level::Root,
1135                target: ResourceRef {
1136                    id: "n1".into(),
1137                    ty: "Note".into(),
1138                },
1139                key: "draft".into(),
1140                rich,
1141                gesture: None,
1142            }];
1143            let bytes = encode_batch(&edit).expect("encodes");
1144            assert_eq!(decode_batch::<ToApp>(&bytes).expect("decodes"), edit);
1145        }
1146    }
1147
1148    #[test]
1149    fn maps_offered_actions_and_list_splices_round_trip_and_apply() {
1150        let who = |id: &str| {
1151            Value::Actor(Actor {
1152                id: tilo_actions::MemberId::person(id).into(),
1153                name: id.to_owned(),
1154                hue: None,
1155                picture: None,
1156            })
1157        };
1158        let reactions = Value::Map(vec![
1159            (Value::text("👍"), Value::List(vec![who("ada"), who("leo")])),
1160            (Value::text("🎉"), Value::List(vec![who("mia")])),
1161        ]);
1162        let offered = Value::List(vec![Value::Action(Offered {
1163            label: "Pin".to_owned(),
1164            icon: Some("pin".to_owned()),
1165            on: Some(false),
1166            event: "actions.0".to_owned(),
1167            ..Offered::default()
1168        })]);
1169        let item = |id: &str| {
1170            Value::Ref(ResourceRef {
1171                id: id.to_owned(),
1172                ty: "chat.Message".to_owned(),
1173            })
1174        };
1175        let mut node = Node::empty("ui.Reactions", "r");
1176        node.props.insert("reactions".to_owned(), reactions);
1177        node.props.insert("actions".to_owned(), offered);
1178        node.props.insert(
1179            "items".to_owned(),
1180            Value::List(vec![item("m1"), item("m3")]),
1181        );
1182        let splice = Patch::SpliceProp {
1183            path: Vec::new(),
1184            name: "items".to_owned(),
1185            at: 1,
1186            remove: 0,
1187            insert: vec![item("m2")],
1188        };
1189        let batch = vec![
1190            ToUi::Open {
1191                level: Level::Root,
1192                target: ResourceRef {
1193                    id: "c".to_owned(),
1194                    ty: "chat.Conversation".to_owned(),
1195                },
1196                tree: node.clone(),
1197                front: None,
1198
1199                capture_protected: false,
1200            },
1201            ToUi::Patch {
1202                level: Level::Root,
1203                patches: vec![splice.clone()],
1204            },
1205        ];
1206        let bytes = encode_batch(&batch).expect("encodes");
1207        assert_eq!(decode_batch::<ToUi>(&bytes).expect("decodes"), batch);
1208        splice.apply(&mut node).expect("applies");
1209        assert_eq!(
1210            node.props.get("items"),
1211            Some(&Value::List(vec![item("m1"), item("m2"), item("m3")]))
1212        );
1213        let past_the_end = Patch::SpliceProp {
1214            path: Vec::new(),
1215            name: "items".to_owned(),
1216            at: 3,
1217            remove: 1,
1218            insert: Vec::new(),
1219        };
1220        assert_eq!(past_the_end.apply(&mut node), Err(Unapplied));
1221        let not_a_list = Patch::SpliceProp {
1222            path: Vec::new(),
1223            name: "reactions".to_owned(),
1224            at: 0,
1225            remove: 0,
1226            insert: Vec::new(),
1227        };
1228        assert_eq!(not_a_list.apply(&mut node), Err(Unapplied));
1229    }
1230}