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 /// Carry out the layout's action `action` with `argument` (its JSON) on the desktop the
700 /// device shows this window on ([`ToApp::Desktop`]), as the person it shows the window to: a
701 /// shell's Close of a window, its launcher's Open, a drag that moves or sizes one. The device
702 /// runs it as that person, as their own session would, never as the app.
703 Desktop { action: String, argument: String },
704}
705
706/// Which of a person's pictures a call tile shows.
707#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
708#[serde(rename_all = "snake_case")]
709pub enum CallPictureSource {
710 Camera,
711 Screen,
712}
713
714/// One picture a view's call tiles show: a person's camera or the screen they share.
715#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
716#[serde(deny_unknown_fields)]
717pub struct CallShown {
718 /// The person, as the workspace names them (their root key, lowercase hex).
719 pub person: String,
720 pub source: CallPictureSource,
721}
722
723/// One picture the call delivered for a tile: the tilo-video/1 object of a person's camera or
724/// screen, as the call received it.
725#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
726#[serde(deny_unknown_fields)]
727pub struct CallPicture {
728 /// The person it shows.
729 pub person: String,
730 /// The stream it belongs to: one participation's source, for as long as that participation
731 /// lasts. A person on two devices, or back after leaving, is another stream; a decoder starts
732 /// over with each.
733 pub stream: String,
734 pub source: CallPictureSource,
735 /// The tilo-video/1 object: header and access unit.
736 #[serde(with = "serde_bytes")]
737 pub object: Vec<u8>,
738}
739
740/// The most pictures one [`ToUi::CallPictures`] carries, and the most a tile set shows: what a
741/// call view draws at once (`tilo_actions::remote::native_media::MAX_SHOWN`).
742pub const MAX_CALL_PICTURES: usize = 64;
743
744/// The largest a [`CallPicture`]'s object is: one coded picture of a call
745/// (`tilo_actions::remote::native_media::MAX_PICTURE_BYTES`).
746pub const MAX_CALL_PICTURE_BYTES: usize = 512 * 1024;
747
748/// The modifier keys held while the person pressed: what a tilolang press reads as
749/// `host.Press`. `command` is Ctrl, or ⌘ on a Mac.
750#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
751pub struct Held {
752 pub shift: bool,
753 pub command: bool,
754 pub alt: bool,
755}
756
757/// What the person did, as the window tells its app.
758#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
759pub enum ToApp {
760 /// The event `event` of the node `key` happened, carrying `value` when it carries one.
761 Fire {
762 level: Level,
763 key: String,
764 event: String,
765 value: Option<Value>,
766 /// The gesture the event is one part of, when the person's act made more than one change
767 /// (a picture pasted into a document, and the app naming it): its action's change names
768 /// it, as the edit that came with it does, so one undo takes both back. A uuid's text.
769 gesture: Option<String>,
770 },
771 /// The checkbox or switch `key` of the view of `target` is now `checked`.
772 ///
773 /// An edit names the resource the level showed when the person made it: it applies to that
774 /// resource, whatever the level shows by the time the app takes it.
775 Toggle {
776 level: Level,
777 target: ResourceRef,
778 key: String,
779 checked: bool,
780 },
781 /// Text typed into the bound control `key` of the view of `target`: `delete` bytes at byte
782 /// `at` replaced by `insert`, against what the control showed. `seq` counts the control's
783 /// splices.
784 Splice {
785 level: Level,
786 target: ResourceRef,
787 key: String,
788 seq: u64,
789 at: u32,
790 delete: u32,
791 insert: String,
792 },
793 /// The bound control `key` of the view of `target`, which edits a value other than text (a
794 /// number, a date), now holds `text`.
795 Edit {
796 level: Level,
797 target: ResourceRef,
798 key: String,
799 text: String,
800 },
801 /// The bound rich-text control `key` of the view of `target` now holds `rich`: its
802 /// paragraphs, marks and references (the runtime brings the field to it by splices and
803 /// marks).
804 EditRich {
805 level: Level,
806 target: ResourceRef,
807 key: String,
808 rich: rich::RichText,
809 /// The gesture the edit is one part of, when the person's act made more than one change
810 /// ([`ToApp::Fire`]'s `gesture`): both changes are one step of theirs.
811 gesture: Option<String>,
812 },
813 /// The suggestion in the invocation card `key` was allowed or declined, as a window that drew
814 /// answers on the card sends it. Only the system's confirm answers a call that asks a person,
815 /// so an app refuses it; it keeps its place so an older window's messages still read.
816 Resolve {
817 level: Level,
818 key: String,
819 approve: bool,
820 },
821 /// A component presenting `resource` was activated: show it.
822 Open {
823 resource: ResourceRef,
824 },
825 /// A reference in rich text was activated: open what it refers to, `reference` being the
826 /// `mention` mark's value (`tilo_reference::embed`).
827 OpenReference {
828 reference: String,
829 },
830 /// Back from the detail level.
831 Back,
832 /// The virtual list `list` shows the rows `start..end` now, the row `open` — its key —
833 /// stands open into its item where it stands ([`ToUi::Rows`] answers with its document), and
834 /// the person opened the menu of the row `menu`, which the app sends again with it.
835 ///
836 /// `store` is the identity of the window's store for that list, minted when the store is
837 /// made: a list the window has just built asks with one no answer of the app's was rendered
838 /// for, so every row of the range comes again rather than being left to a store that no
839 /// longer exists.
840 Rows {
841 level: Level,
842 list: String,
843 start: u32,
844 end: u32,
845 open: Option<String>,
846 menu: Option<String>,
847 store: u64,
848 },
849 Answer(Answer),
850 /// The field `field` (a key of [`Form::fields`]) of the form `form` now holds `text`: what
851 /// was typed, a case or a resource chosen by its name or id, `true` or `false`.
852 FormEdit {
853 form: u64,
854 field: String,
855 text: String,
856 },
857 /// The form `form` was submitted.
858 FormSubmit {
859 form: u64,
860 },
861 /// The form `form` was closed without submitting: what was typed stays for next time.
862 FormCancel {
863 form: u64,
864 },
865 /// The person asked to take back their last step: Undo on a notice, or the window's undo
866 /// (Ctrl+Z, Edit › Undo). The record's undo, the one undo there is: a field the person typed
867 /// into keeps no history of its own beside it.
868 Undo,
869 /// The keyboard focus is in the bound control `key` of `level`, or in none.
870 Focus {
871 at: Option<(Level, String)>,
872 },
873 /// An input method is composing in the focused control, or stopped.
874 Composing(bool),
875 /// The modifier keys held with the pointer now, sent before the event they came with when
876 /// they changed: a press with Shift adds to a selection, one with the command key toggles.
877 Held(Held),
878 /// Layout gave a view of `level` the space `width` by `height` of the window, in `rem` (the
879 /// body text size after the person's setting): what its `space` reads (layout.md, "Responding
880 /// to space"). `key` is the view call's `fragment`, as [`ToUi::Spaces`] named it, or empty for
881 /// the level's own root. `rem` is that body text size in logical pixels, which a view computes
882 /// a place in pixels from (a card it keeps where the person dropped it).
883 Space {
884 level: Level,
885 key: String,
886 width: f32,
887 height: f32,
888 rem: f32,
889 },
890 /// The person asked to bring back what their last undo took back: the window's redo
891 /// (Ctrl+Shift+Z, Edit › Redo). The mirror of [`ToApp::Undo`].
892 Redo,
893 /// The person chose the action `address` from the window's command palette, with the
894 /// argument the palette collected: the app runs it as the person's own step.
895 Invoke {
896 address: ActionAddress,
897 argument: Option<String>,
898 },
899 /// The person asked to save the changes the workspace has not taken yet again
900 /// ([`ToUi::Kept`]).
901 SaveAgain,
902 /// The window bar's History control was pressed: show the system's history of the resource
903 /// the window shows (`open`), or close it and show the resource again.
904 History {
905 open: bool,
906 },
907 /// What the person does from now on serves `call`, the invocation they signed for it, as the
908 /// member `invoker` names (a stamp's invoker): each change it makes keeps the call, for the
909 /// holders that check it. An empty call ends it: what follows is the window's own. A window
910 /// shown on a web page sends it around each of its reader's acts. The call is carried as its
911 /// JSON, as its argument is.
912 Serving {
913 #[serde(with = "serde_bytes")]
914 call: Vec<u8>,
915 invoker: Option<String>,
916 },
917 /// What became of the page request [`ToUi::Page`] asked for: the page's own answer, encoded,
918 /// or a refusal. A page that is gone answers too, so a waiting action is never left waiting.
919 PageAnswer {
920 request_id: u32,
921 #[serde(with = "serde_bytes")]
922 answer: Vec<u8>,
923 },
924 /// The window's page started or stopped waiting on the person's yes (a site asking for the
925 /// camera, a download it offers, a server's sign-in, a request kept from leaving): the
926 /// engine's prompt, encoded (`tilo_page_engine::codec::prompt_json`). The app raises one as
927 /// its call of its own action, which the system keeps as an asked record, and withdraws that
928 /// call once the page no longer waits.
929 PagePrompt {
930 #[serde(with = "serde_bytes")]
931 prompt: Vec<u8>,
932 },
933 /// The layout of the desktop the device shows this window on, as the person it shows the
934 /// window to reads it there: the layout's `read` answer, as its JSON. A shell shown where no
935 /// session runs it (a web page of the workspace's desktop) is handed its layout this way, as
936 /// a session hands its own shell the layout it keeps.
937 Desktop {
938 layout: String,
939 },
940}
941
942/// Largest batch either side sends or accepts.
943pub const MAX_BATCH_BYTES: usize = 16 << 20;
944
945/// Largest page request or answer one message carries: a page's reading, its outline and a
946/// picture of it fit, and nothing a page could say grows a window without bound.
947pub const MAX_PAGE_BYTES: usize = 8 << 20;
948
949/// One frame's messages as the bytes a transport carries.
950///
951/// # Errors
952/// The messages encode to more than [`MAX_BATCH_BYTES`].
953pub fn encode_batch<T: Serialize>(messages: &[T]) -> Result<Vec<u8>, WireError> {
954 let mut bytes = Vec::with_capacity(64);
955 bytes.extend_from_slice(&VERSION.to_le_bytes());
956 let bytes = postcard::to_extend(messages, bytes).map_err(|_| WireError::Malformed("batch"))?;
957 if bytes.len() > MAX_BATCH_BYTES {
958 return Err(WireError::OverLimit("batch size"));
959 }
960 Ok(bytes)
961}
962
963/// The messages of a batch, read once into the receiver's memory.
964///
965/// # Errors
966/// The bytes are no batch of this version, or are over [`MAX_BATCH_BYTES`].
967pub fn decode_batch<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<Vec<T>, WireError> {
968 if bytes.len() > MAX_BATCH_BYTES {
969 return Err(WireError::OverLimit("batch size"));
970 }
971 let (version, body) = bytes.split_at_checked(2).ok_or(WireError::Truncated)?;
972 if version != VERSION.to_le_bytes() {
973 return Err(WireError::Malformed("batch version"));
974 }
975 let (messages, rest) =
976 postcard::take_from_bytes(body).map_err(|_| WireError::Malformed("batch"))?;
977 if !rest.is_empty() {
978 return Err(WireError::Malformed("bytes after a batch"));
979 }
980 Ok(messages)
981}
982
983/// What carries one side's batches to the other: a queue in one process, a socket and ring
984/// between processes, `postMessage` between a page and a worker. At most one batch a frame.
985pub trait Transport {
986 /// Hand `batch` to the other side.
987 fn send(&mut self, batch: Vec<u8>) -> Result<(), WireError>;
988
989 /// The next batch the other side sent, when one waits.
990 fn recv(&mut self) -> Result<Option<Vec<u8>>, WireError>;
991}
992
993#[cfg(test)]
994mod tests {
995 use super::*;
996
997 fn text(key: &str, value: &str) -> Node {
998 let mut node = Node::empty("ui.Text", key);
999 node.props.insert("value".to_owned(), Value::text(value));
1000 node
1001 }
1002
1003 #[test]
1004 fn patches_apply_by_key_and_refuse_a_node_the_tree_lacks() {
1005 let mut root = Node::empty("stack", "s");
1006 root.children = vec![text("a", "1"), text("b", "2")];
1007 Patch::Insert {
1008 parent: Vec::new(),
1009 index: 0,
1010 node: text("n", "0"),
1011 }
1012 .apply(&mut root)
1013 .expect("applies");
1014 Patch::Move {
1015 parent: Vec::new(),
1016 key: "b".to_owned(),
1017 to: 1,
1018 }
1019 .apply(&mut root)
1020 .expect("applies");
1021 Patch::SetProp {
1022 path: vec!["a".to_owned()],
1023 name: "value".to_owned(),
1024 value: Some(Value::text("3")),
1025 }
1026 .apply(&mut root)
1027 .expect("applies");
1028 let keys: Vec<&str> = root.children.iter().map(|c| c.key.as_str()).collect();
1029 assert_eq!(keys, ["n", "b", "a"]);
1030 assert_eq!(
1031 root.find("a").and_then(|a| a.props.get("value")),
1032 Some(&Value::text("3"))
1033 );
1034 assert_eq!(
1035 Patch::Remove {
1036 parent: vec!["nowhere".to_owned()],
1037 key: "a".to_owned()
1038 }
1039 .apply(&mut root),
1040 Err(Unapplied)
1041 );
1042 }
1043
1044 #[test]
1045 fn a_batch_reads_back_as_it_was_sent_and_scribbles_are_refused() {
1046 let batch = vec![
1047 ToUi::Open {
1048 level: Level::Root,
1049 target: ResourceRef {
1050 id: "doc".to_owned(),
1051 ty: "notes.Notebook".to_owned(),
1052 },
1053 tree: text("t", "Notes"),
1054 front: None,
1055
1056 capture_protected: false,
1057 },
1058 ToUi::Patch {
1059 level: Level::Root,
1060 patches: vec![Patch::SetProp {
1061 path: Vec::new(),
1062 name: "value".to_owned(),
1063 value: Some(Value::text("Ideas")),
1064 }],
1065 },
1066 ];
1067 let bytes = encode_batch(&batch).expect("encodes");
1068 let back: Vec<ToUi> = decode_batch(&bytes).expect("decodes");
1069 assert_eq!(back, batch);
1070 for cut in 0..bytes.len() {
1071 let truncated: Result<Vec<ToUi>, _> = decode_batch(&bytes[..cut]);
1072 assert!(truncated.is_err() || cut == bytes.len());
1073 }
1074 let mut other = bytes;
1075 other[0] = 9;
1076 assert!(decode_batch::<ToUi>(&other).is_err(), "another version");
1077 }
1078
1079 #[test]
1080 fn rich_text_reads_back_as_it_was_sent_with_or_without_its_parts() {
1081 let reference = r#"{"app":"a.b","id":"t1","kind":"a.task"}"#;
1082 let rich = |marks: Vec<rich::Mark>, embeds: Vec<rich::Embed>| rich::RichText {
1083 blocks: vec![rich::Block {
1084 kind: "paragraph".to_owned(),
1085 text: "see Fix it".to_owned(),
1086 marks,
1087 attrs: std::collections::BTreeMap::new(),
1088 }],
1089 styles: std::collections::BTreeMap::default(),
1090 embeds,
1091 };
1092 let batch: Vec<ToUi> = [
1093 rich(Vec::new(), Vec::new()),
1094 rich(
1095 vec![rich::Mark {
1096 start: 4,
1097 end: 10,
1098 name: "mention".to_owned(),
1099 value: rich::Attr::Text(reference.to_owned()),
1100 }],
1101 vec![
1102 rich::Embed {
1103 reference: reference.to_owned(),
1104 view: rich::InlineView::Resource {
1105 title: "Fix the build".to_owned(),
1106 icon: None,
1107 detail: None,
1108 },
1109 preview: None,
1110 },
1111 rich::Embed {
1112 reference: "u-ada".to_owned(),
1113 view: rich::InlineView::Unreadable,
1114 preview: None,
1115 },
1116 ],
1117 ),
1118 ]
1119 .into_iter()
1120 .map(|value| ToUi::Patch {
1121 level: Level::Root,
1122 patches: vec![Patch::SetProp {
1123 path: Vec::new(),
1124 name: "value".to_owned(),
1125 value: Some(Value::Rich(value)),
1126 }],
1127 })
1128 .collect();
1129 let bytes = encode_batch(&batch).expect("encodes");
1130 assert_eq!(decode_batch::<ToUi>(&bytes).expect("decodes"), batch);
1131 }
1132
1133 #[test]
1134 fn a_rich_inputs_edit_round_trips_empty_or_not() {
1135 let plain = rich::RichText {
1136 blocks: vec![rich::Block {
1137 kind: "paragraph".into(),
1138 text: "hi".into(),
1139 ..rich::Block::default()
1140 }],
1141 embeds: Vec::new(),
1142 styles: std::collections::BTreeMap::default(),
1143 };
1144 for rich in [rich::RichText::default(), plain] {
1145 let edit = vec![ToApp::EditRich {
1146 level: Level::Root,
1147 target: ResourceRef {
1148 id: "n1".into(),
1149 ty: "Note".into(),
1150 },
1151 key: "draft".into(),
1152 rich,
1153 gesture: None,
1154 }];
1155 let bytes = encode_batch(&edit).expect("encodes");
1156 assert_eq!(decode_batch::<ToApp>(&bytes).expect("decodes"), edit);
1157 }
1158 }
1159
1160 #[test]
1161 fn maps_offered_actions_and_list_splices_round_trip_and_apply() {
1162 let who = |id: &str| {
1163 Value::Actor(Actor {
1164 id: tilo_actions::MemberId::person(id).into(),
1165 name: id.to_owned(),
1166 hue: None,
1167 picture: None,
1168 })
1169 };
1170 let reactions = Value::Map(vec![
1171 (Value::text("👍"), Value::List(vec![who("ada"), who("leo")])),
1172 (Value::text("🎉"), Value::List(vec![who("mia")])),
1173 ]);
1174 let offered = Value::List(vec![Value::Action(Offered {
1175 label: "Pin".to_owned(),
1176 icon: Some("pin".to_owned()),
1177 on: Some(false),
1178 event: "actions.0".to_owned(),
1179 ..Offered::default()
1180 })]);
1181 let item = |id: &str| {
1182 Value::Ref(ResourceRef {
1183 id: id.to_owned(),
1184 ty: "chat.Message".to_owned(),
1185 })
1186 };
1187 let mut node = Node::empty("ui.Reactions", "r");
1188 node.props.insert("reactions".to_owned(), reactions);
1189 node.props.insert("actions".to_owned(), offered);
1190 node.props.insert(
1191 "items".to_owned(),
1192 Value::List(vec![item("m1"), item("m3")]),
1193 );
1194 let splice = Patch::SpliceProp {
1195 path: Vec::new(),
1196 name: "items".to_owned(),
1197 at: 1,
1198 remove: 0,
1199 insert: vec![item("m2")],
1200 };
1201 let batch = vec![
1202 ToUi::Open {
1203 level: Level::Root,
1204 target: ResourceRef {
1205 id: "c".to_owned(),
1206 ty: "chat.Conversation".to_owned(),
1207 },
1208 tree: node.clone(),
1209 front: None,
1210
1211 capture_protected: false,
1212 },
1213 ToUi::Patch {
1214 level: Level::Root,
1215 patches: vec![splice.clone()],
1216 },
1217 ];
1218 let bytes = encode_batch(&batch).expect("encodes");
1219 assert_eq!(decode_batch::<ToUi>(&bytes).expect("decodes"), batch);
1220 splice.apply(&mut node).expect("applies");
1221 assert_eq!(
1222 node.props.get("items"),
1223 Some(&Value::List(vec![item("m1"), item("m2"), item("m3")]))
1224 );
1225 let past_the_end = Patch::SpliceProp {
1226 path: Vec::new(),
1227 name: "items".to_owned(),
1228 at: 3,
1229 remove: 1,
1230 insert: Vec::new(),
1231 };
1232 assert_eq!(past_the_end.apply(&mut node), Err(Unapplied));
1233 let not_a_list = Patch::SpliceProp {
1234 path: Vec::new(),
1235 name: "reactions".to_owned(),
1236 at: 0,
1237 remove: 0,
1238 insert: Vec::new(),
1239 };
1240 assert_eq!(not_a_list.apply(&mut node), Err(Unapplied));
1241 }
1242}