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