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    Rows {
831        level: Level,
832        list: String,
833        start: u32,
834        end: u32,
835        open: Option<String>,
836        menu: Option<String>,
837    },
838    Answer(Answer),
839    /// The field `field` (a key of [`Form::fields`]) of the form `form` now holds `text`: what
840    /// was typed, a case or a resource chosen by its name or id, `true` or `false`.
841    FormEdit {
842        form: u64,
843        field: String,
844        text: String,
845    },
846    /// The form `form` was submitted.
847    FormSubmit {
848        form: u64,
849    },
850    /// The form `form` was closed without submitting: what was typed stays for next time.
851    FormCancel {
852        form: u64,
853    },
854    /// The person asked to take back their last step: Undo on a notice, or the window's undo
855    /// (Ctrl+Z, Edit › Undo). The record's undo, the one undo there is: a field the person typed
856    /// into keeps no history of its own beside it.
857    Undo,
858    /// The keyboard focus is in the bound control `key` of `level`, or in none.
859    Focus {
860        at: Option<(Level, String)>,
861    },
862    /// An input method is composing in the focused control, or stopped.
863    Composing(bool),
864    /// The modifier keys held with the pointer now, sent before the event they came with when
865    /// they changed: a press with Shift adds to a selection, one with the command key toggles.
866    Held(Held),
867    /// Layout gave a view of `level` the space `width` by `height` of the window, in `rem` (the
868    /// body text size after the person's setting): what its `space` reads (layout.md, "Responding
869    /// to space"). `key` is the view call's `fragment`, as [`ToUi::Spaces`] named it, or empty for
870    /// the level's own root. `rem` is that body text size in logical pixels, which a view computes
871    /// a place in pixels from (a card it keeps where the person dropped it).
872    Space {
873        level: Level,
874        key: String,
875        width: f32,
876        height: f32,
877        rem: f32,
878    },
879    /// The person asked to bring back what their last undo took back: the window's redo
880    /// (Ctrl+Shift+Z, Edit › Redo). The mirror of [`ToApp::Undo`].
881    Redo,
882    /// The person chose the action `address` from the window's command palette, with the
883    /// argument the palette collected: the app runs it as the person's own step.
884    Invoke {
885        address: ActionAddress,
886        argument: Option<String>,
887    },
888    /// The person asked to save the changes the workspace has not taken yet again
889    /// ([`ToUi::Kept`]).
890    SaveAgain,
891    /// The window bar's History control was pressed: show the system's history of the resource
892    /// the window shows (`open`), or close it and show the resource again.
893    History {
894        open: bool,
895    },
896    /// What the person does from now on serves `call`, the invocation they signed for it, as the
897    /// member `invoker` names (a stamp's invoker): each change it makes keeps the call, for the
898    /// holders that check it. An empty call ends it: what follows is the window's own. A window
899    /// shown on a web page sends it around each of its reader's acts. The call is carried as its
900    /// JSON, as its argument is.
901    Serving {
902        #[serde(with = "serde_bytes")]
903        call: Vec<u8>,
904        invoker: Option<String>,
905    },
906    /// What became of the page request [`ToUi::Page`] asked for: the page's own answer, encoded,
907    /// or a refusal. A page that is gone answers too, so a waiting action is never left waiting.
908    PageAnswer {
909        request_id: u32,
910        #[serde(with = "serde_bytes")]
911        answer: Vec<u8>,
912    },
913    /// The window's page started or stopped waiting on the person's yes (a site asking for the
914    /// camera, a download it offers, a server's sign-in, a request kept from leaving): the
915    /// engine's prompt, encoded (`tilo_page_engine::codec::prompt_json`). The app raises one as
916    /// its call of its own action, which the system keeps as an asked record, and withdraws that
917    /// call once the page no longer waits.
918    PagePrompt {
919        #[serde(with = "serde_bytes")]
920        prompt: Vec<u8>,
921    },
922}
923
924/// Largest batch either side sends or accepts.
925pub const MAX_BATCH_BYTES: usize = 16 << 20;
926
927/// Largest page request or answer one message carries: a page's reading, its outline and a
928/// picture of it fit, and nothing a page could say grows a window without bound.
929pub const MAX_PAGE_BYTES: usize = 8 << 20;
930
931/// One frame's messages as the bytes a transport carries.
932///
933/// # Errors
934/// The messages encode to more than [`MAX_BATCH_BYTES`].
935pub fn encode_batch<T: Serialize>(messages: &[T]) -> Result<Vec<u8>, WireError> {
936    let mut bytes = Vec::with_capacity(64);
937    bytes.extend_from_slice(&VERSION.to_le_bytes());
938    let bytes = postcard::to_extend(messages, bytes).map_err(|_| WireError::Malformed("batch"))?;
939    if bytes.len() > MAX_BATCH_BYTES {
940        return Err(WireError::OverLimit("batch size"));
941    }
942    Ok(bytes)
943}
944
945/// The messages of a batch, read once into the receiver's memory.
946///
947/// # Errors
948/// The bytes are no batch of this version, or are over [`MAX_BATCH_BYTES`].
949pub fn decode_batch<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<Vec<T>, WireError> {
950    if bytes.len() > MAX_BATCH_BYTES {
951        return Err(WireError::OverLimit("batch size"));
952    }
953    let (version, body) = bytes.split_at_checked(2).ok_or(WireError::Truncated)?;
954    if version != VERSION.to_le_bytes() {
955        return Err(WireError::Malformed("batch version"));
956    }
957    let (messages, rest) =
958        postcard::take_from_bytes(body).map_err(|_| WireError::Malformed("batch"))?;
959    if !rest.is_empty() {
960        return Err(WireError::Malformed("bytes after a batch"));
961    }
962    Ok(messages)
963}
964
965/// What carries one side's batches to the other: a queue in one process, a socket and ring
966/// between processes, `postMessage` between a page and a worker. At most one batch a frame.
967pub trait Transport {
968    /// Hand `batch` to the other side.
969    fn send(&mut self, batch: Vec<u8>) -> Result<(), WireError>;
970
971    /// The next batch the other side sent, when one waits.
972    fn recv(&mut self) -> Result<Option<Vec<u8>>, WireError>;
973}
974
975#[cfg(test)]
976mod tests {
977    use super::*;
978
979    fn text(key: &str, value: &str) -> Node {
980        let mut node = Node::empty("ui.Text", key);
981        node.props.insert("value".to_owned(), Value::text(value));
982        node
983    }
984
985    #[test]
986    fn patches_apply_by_key_and_refuse_a_node_the_tree_lacks() {
987        let mut root = Node::empty("stack", "s");
988        root.children = vec![text("a", "1"), text("b", "2")];
989        Patch::Insert {
990            parent: Vec::new(),
991            index: 0,
992            node: text("n", "0"),
993        }
994        .apply(&mut root)
995        .expect("applies");
996        Patch::Move {
997            parent: Vec::new(),
998            key: "b".to_owned(),
999            to: 1,
1000        }
1001        .apply(&mut root)
1002        .expect("applies");
1003        Patch::SetProp {
1004            path: vec!["a".to_owned()],
1005            name: "value".to_owned(),
1006            value: Some(Value::text("3")),
1007        }
1008        .apply(&mut root)
1009        .expect("applies");
1010        let keys: Vec<&str> = root.children.iter().map(|c| c.key.as_str()).collect();
1011        assert_eq!(keys, ["n", "b", "a"]);
1012        assert_eq!(
1013            root.find("a").and_then(|a| a.props.get("value")),
1014            Some(&Value::text("3"))
1015        );
1016        assert_eq!(
1017            Patch::Remove {
1018                parent: vec!["nowhere".to_owned()],
1019                key: "a".to_owned()
1020            }
1021            .apply(&mut root),
1022            Err(Unapplied)
1023        );
1024    }
1025
1026    #[test]
1027    fn a_batch_reads_back_as_it_was_sent_and_scribbles_are_refused() {
1028        let batch = vec![
1029            ToUi::Open {
1030                level: Level::Root,
1031                target: ResourceRef {
1032                    id: "doc".to_owned(),
1033                    ty: "notes.Notebook".to_owned(),
1034                },
1035                tree: text("t", "Notes"),
1036                front: None,
1037
1038                capture_protected: false,
1039            },
1040            ToUi::Patch {
1041                level: Level::Root,
1042                patches: vec![Patch::SetProp {
1043                    path: Vec::new(),
1044                    name: "value".to_owned(),
1045                    value: Some(Value::text("Ideas")),
1046                }],
1047            },
1048        ];
1049        let bytes = encode_batch(&batch).expect("encodes");
1050        let back: Vec<ToUi> = decode_batch(&bytes).expect("decodes");
1051        assert_eq!(back, batch);
1052        for cut in 0..bytes.len() {
1053            let truncated: Result<Vec<ToUi>, _> = decode_batch(&bytes[..cut]);
1054            assert!(truncated.is_err() || cut == bytes.len());
1055        }
1056        let mut other = bytes;
1057        other[0] = 9;
1058        assert!(decode_batch::<ToUi>(&other).is_err(), "another version");
1059    }
1060
1061    #[test]
1062    fn rich_text_reads_back_as_it_was_sent_with_or_without_its_parts() {
1063        let reference = r#"{"app":"a.b","id":"t1","kind":"a.task"}"#;
1064        let rich = |marks: Vec<rich::Mark>, embeds: Vec<rich::Embed>| rich::RichText {
1065            blocks: vec![rich::Block {
1066                kind: "paragraph".to_owned(),
1067                text: "see Fix it".to_owned(),
1068                marks,
1069                attrs: std::collections::BTreeMap::new(),
1070            }],
1071            styles: std::collections::BTreeMap::default(),
1072            embeds,
1073        };
1074        let batch: Vec<ToUi> = [
1075            rich(Vec::new(), Vec::new()),
1076            rich(
1077                vec![rich::Mark {
1078                    start: 4,
1079                    end: 10,
1080                    name: "mention".to_owned(),
1081                    value: rich::Attr::Text(reference.to_owned()),
1082                }],
1083                vec![
1084                    rich::Embed {
1085                        reference: reference.to_owned(),
1086                        view: rich::InlineView::Resource {
1087                            title: "Fix the build".to_owned(),
1088                            icon: None,
1089                            detail: None,
1090                        },
1091                        preview: None,
1092                    },
1093                    rich::Embed {
1094                        reference: "u-ada".to_owned(),
1095                        view: rich::InlineView::Unreadable,
1096                        preview: None,
1097                    },
1098                ],
1099            ),
1100        ]
1101        .into_iter()
1102        .map(|value| ToUi::Patch {
1103            level: Level::Root,
1104            patches: vec![Patch::SetProp {
1105                path: Vec::new(),
1106                name: "value".to_owned(),
1107                value: Some(Value::Rich(value)),
1108            }],
1109        })
1110        .collect();
1111        let bytes = encode_batch(&batch).expect("encodes");
1112        assert_eq!(decode_batch::<ToUi>(&bytes).expect("decodes"), batch);
1113    }
1114
1115    #[test]
1116    fn a_rich_inputs_edit_round_trips_empty_or_not() {
1117        let plain = rich::RichText {
1118            blocks: vec![rich::Block {
1119                kind: "paragraph".into(),
1120                text: "hi".into(),
1121                ..rich::Block::default()
1122            }],
1123            embeds: Vec::new(),
1124            styles: std::collections::BTreeMap::default(),
1125        };
1126        for rich in [rich::RichText::default(), plain] {
1127            let edit = vec![ToApp::EditRich {
1128                level: Level::Root,
1129                target: ResourceRef {
1130                    id: "n1".into(),
1131                    ty: "Note".into(),
1132                },
1133                key: "draft".into(),
1134                rich,
1135                gesture: None,
1136            }];
1137            let bytes = encode_batch(&edit).expect("encodes");
1138            assert_eq!(decode_batch::<ToApp>(&bytes).expect("decodes"), edit);
1139        }
1140    }
1141
1142    #[test]
1143    fn maps_offered_actions_and_list_splices_round_trip_and_apply() {
1144        let who = |id: &str| {
1145            Value::Actor(Actor {
1146                id: tilo_actions::MemberId::person(id).into(),
1147                name: id.to_owned(),
1148                hue: None,
1149                picture: None,
1150            })
1151        };
1152        let reactions = Value::Map(vec![
1153            (Value::text("👍"), Value::List(vec![who("ada"), who("leo")])),
1154            (Value::text("🎉"), Value::List(vec![who("mia")])),
1155        ]);
1156        let offered = Value::List(vec![Value::Action(Offered {
1157            label: "Pin".to_owned(),
1158            icon: Some("pin".to_owned()),
1159            on: Some(false),
1160            event: "actions.0".to_owned(),
1161            ..Offered::default()
1162        })]);
1163        let item = |id: &str| {
1164            Value::Ref(ResourceRef {
1165                id: id.to_owned(),
1166                ty: "chat.Message".to_owned(),
1167            })
1168        };
1169        let mut node = Node::empty("ui.Reactions", "r");
1170        node.props.insert("reactions".to_owned(), reactions);
1171        node.props.insert("actions".to_owned(), offered);
1172        node.props.insert(
1173            "items".to_owned(),
1174            Value::List(vec![item("m1"), item("m3")]),
1175        );
1176        let splice = Patch::SpliceProp {
1177            path: Vec::new(),
1178            name: "items".to_owned(),
1179            at: 1,
1180            remove: 0,
1181            insert: vec![item("m2")],
1182        };
1183        let batch = vec![
1184            ToUi::Open {
1185                level: Level::Root,
1186                target: ResourceRef {
1187                    id: "c".to_owned(),
1188                    ty: "chat.Conversation".to_owned(),
1189                },
1190                tree: node.clone(),
1191                front: None,
1192
1193                capture_protected: false,
1194            },
1195            ToUi::Patch {
1196                level: Level::Root,
1197                patches: vec![splice.clone()],
1198            },
1199        ];
1200        let bytes = encode_batch(&batch).expect("encodes");
1201        assert_eq!(decode_batch::<ToUi>(&bytes).expect("decodes"), batch);
1202        splice.apply(&mut node).expect("applies");
1203        assert_eq!(
1204            node.props.get("items"),
1205            Some(&Value::List(vec![item("m1"), item("m2"), item("m3")]))
1206        );
1207        let past_the_end = Patch::SpliceProp {
1208            path: Vec::new(),
1209            name: "items".to_owned(),
1210            at: 3,
1211            remove: 1,
1212            insert: Vec::new(),
1213        };
1214        assert_eq!(past_the_end.apply(&mut node), Err(Unapplied));
1215        let not_a_list = Patch::SpliceProp {
1216            path: Vec::new(),
1217            name: "reactions".to_owned(),
1218            at: 0,
1219            remove: 0,
1220            insert: Vec::new(),
1221        };
1222        assert_eq!(not_a_list.apply(&mut node), Err(Unapplied));
1223    }
1224}