Skip to main content

tilo_render_protocol/patch/
validate.rs

1//! The check every batch an app sends passes before the UI host touches a widget.
2//!
3//! The UI host builds every window of a workspace from what each app sends. A batch that makes it
4//! build a widget wrongly, or work without bound, takes the workspace's windows down with it. So
5//! every message is checked, once, in the host's own copy:
6//!
7//! - **Valid by type.** A described component's node (`ui.ListRow`) names a component of the
8//!   toolkit's catalogue; each of its props is one the description declares (or a sizing
9//!   argument every node takes, or the companion of a prop it declares, such as `value:as`
10//!   saying which kind of text `value` holds), holding a value of the declared type; each event
11//!   and binding is one it declares. A primitive of the language (`stack`, `list`) is one the
12//!   host builds.
13//! - **Bounded.** Strings, keys, paths, props, depth and the rows of one message are limited,
14//!   and each window's trees together hold at most [`PatchLimits::nodes`] nodes (the host
15//!   counts them as it applies patches: one window's budget is its own).
16//! - **Only its own trees.** A connection is one window of one app; its patches name nodes by
17//!   key paths in the trees it sent, and a path that names no node is refused when applied.
18
19use tilo_actions::ActionAddress;
20use tilo_ui_graph::component::{Catalogue, Description, Type, companion};
21
22use super::{
23    Binding, Event, MAX_CALL_PICTURE_BYTES, MAX_CALL_PICTURES, Node, Patch, ResourceRef, RowChange,
24    ToApp, ToUi, Value, Words,
25};
26
27/// Why a batch was refused: what was wrong, and where.
28#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
29#[error("{what}{at}")]
30pub struct Refused {
31    pub what: &'static str,
32    /// Where, from the outermost part in, such as `` in `stack` s in prop `gap` ``.
33    pub at: String,
34}
35
36impl Refused {
37    #[must_use]
38    pub fn invalid(what: &'static str) -> Self {
39        Self {
40            what,
41            at: String::new(),
42        }
43    }
44
45    /// The same refusal, found in `part`.
46    #[must_use]
47    pub fn within(mut self, part: impl std::fmt::Display) -> Self {
48        self.at = format!(" in {part}{}", self.at);
49        self
50    }
51}
52
53/// What one window may make its UI host hold and do.
54#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
55pub struct PatchLimits {
56    /// Nodes of one window's trees together, rendered rows included.
57    pub nodes: u32,
58    /// How deep a tree nests.
59    pub depth: u32,
60    /// Bytes of one string: a prop's text, a bound value, a splice — as much
61    /// as one text an action carries ([`tilo_actions::MAX_TEXT_BYTES`]), so a
62    /// text an edit keeps is always a text a window can show.
63    pub string_bytes: u32,
64    /// Bytes of one key or name.
65    pub key_bytes: u32,
66    /// Keys in one path.
67    pub path: u32,
68    /// Props of one node.
69    pub props: u32,
70    /// Rows or keys in one message.
71    pub rows: u32,
72    /// Messages in one batch.
73    pub messages: u32,
74}
75
76/// One text's bytes as a window counts one string: the same number
77/// ([`tilo_actions::MAX_TEXT_BYTES`]), so a text an edit keeps is never one the
78/// window refuses to show.
79#[expect(
80    clippy::cast_possible_truncation,
81    reason = "one text's bytes, 8 MiB, fit a window's count of a string"
82)]
83const STRING_BYTES: u32 = tilo_actions::MAX_TEXT_BYTES as u32;
84
85impl Default for PatchLimits {
86    fn default() -> Self {
87        Self {
88            nodes: 200_000,
89            depth: 128,
90            string_bytes: STRING_BYTES,
91            key_bytes: 4096,
92            path: 128,
93            props: 128,
94            rows: 8192,
95            messages: 65_536,
96        }
97    }
98}
99
100/// The sizing and placement arguments every node takes (`fill`, `min: 12.rem`, `at`), as the
101/// language's `prims::NODE_ARGS` names them.
102pub const NODE_ARGS: &[&str] = &[
103    "fill", "min", "max", "height", "aspect", "span", "lines", "truncate", "at", "lead", "x", "y",
104];
105
106/// Every primitive of the language a view may send: the layouts, controls and blocks the host
107/// builds itself, and `part`, a component's named part. A primitive's props are the language's
108/// arguments, which the host reads by name, each as the type it takes, ignoring what it does
109/// not read; so what is checked of them is that the primitive is one the host builds and that
110/// every value is bounded.
111pub const PRIMITIVES: &[&str] = &[
112    "stack",
113    "column",
114    "fragment",
115    "primary",
116    "secondary",
117    "item",
118    "row",
119    "grid",
120    "split",
121    "page",
122    "layers",
123    "scroll",
124    "spacer",
125    "divider",
126    "progress",
127    "form",
128    "field",
129    "toggle",
130    "choice",
131    "list",
132    "checkbox",
133    "date",
134    "image",
135    "embed",
136    "invocation",
137    "error",
138    "text",
139    PART,
140];
141
142/// The kind of a node holding the content of a component's named part.
143pub const PART: &str = "part";
144
145/// The prefix of a described component's kind: `ui.ListRow`.
146pub const COMPONENT_PREFIX: &str = "ui.";
147
148/// Whether `kind` is a primitive the host builds.
149#[must_use]
150pub fn primitive(kind: &str) -> bool {
151    PRIMITIVES.contains(&kind)
152}
153
154/// Checks batches against a toolkit's catalogue and a window's limits.
155pub struct Validator<'a> {
156    catalogue: &'a Catalogue,
157    limits: PatchLimits,
158}
159
160impl<'a> Validator<'a> {
161    #[must_use]
162    pub fn new(catalogue: &'a Catalogue, limits: PatchLimits) -> Self {
163        Self { catalogue, limits }
164    }
165
166    #[must_use]
167    pub fn limits(&self) -> &PatchLimits {
168        &self.limits
169    }
170
171    /// Check one batch an app sent its window.
172    ///
173    /// # Errors
174    /// The first thing in it that is not valid.
175    pub fn to_ui(&self, batch: &[ToUi]) -> Result<(), Refused> {
176        if batch.len() > self.limits.messages as usize {
177            return Err(Refused::invalid(concat!(
178                "over the limit of ",
179                "messages in a batch"
180            )));
181        }
182        for message in batch {
183            self.message(message)?;
184        }
185        Ok(())
186    }
187
188    /// A resource the window names: its id and its type.
189    fn target(&self, target: &ResourceRef) -> Result<(), Refused> {
190        self.key(&target.id)?;
191        self.key(&target.ty)
192    }
193
194    /// `bytes` a message carries whole, within the limit of a string's; `refused` says it is not.
195    fn carried(&self, bytes: usize, refused: &'static str) -> Result<(), Refused> {
196        if bytes > self.limits.string_bytes as usize {
197            return Err(Refused::invalid(refused));
198        }
199        Ok(())
200    }
201
202    #[allow(
203        clippy::too_many_lines,
204        reason = "one arm per message a window takes, read side by side as the protocol lists them"
205    )]
206    fn message(&self, message: &ToUi) -> Result<(), Refused> {
207        match message {
208            ToUi::Loading
209            | ToUi::Close
210            | ToUi::Front { shows: None, .. }
211            | ToUi::Ask(None)
212            | ToUi::Form(None)
213            | ToUi::Activate
214            | ToUi::Kept(_)
215            | ToUi::History(_)
216            | ToUi::Took { .. }
217            | ToUi::CloseWindow => Ok(()),
218            ToUi::Focus { key } => match key {
219                Some(key) => self.key(key),
220                None => Ok(()),
221            },
222            ToUi::Actions(catalogue) => {
223                self.carried(catalogue.len(), "over the limit of bytes in a catalogue")
224            }
225            ToUi::Heard(bytes) | ToUi::Outputs(bytes) => {
226                self.carried(bytes.len(), "over the limit of bytes in a message")
227            }
228            ToUi::CallPictures { shown, pictures } => {
229                if shown.len() > MAX_CALL_PICTURES || pictures.len() > MAX_CALL_PICTURES {
230                    return Err(Refused::invalid("over the limit of pictures in a message"));
231                }
232                for shown in shown {
233                    self.key(&shown.person)?;
234                }
235                for picture in pictures {
236                    self.key(&picture.person)?;
237                    self.key(&picture.stream)?;
238                    if picture.object.is_empty() || picture.object.len() > MAX_CALL_PICTURE_BYTES {
239                        return Err(Refused::invalid("a call picture is not one picture"));
240                    }
241                }
242                Ok(())
243            }
244            ToUi::Page { request, .. } => {
245                if request.len() > super::MAX_PAGE_BYTES {
246                    return Err(Refused::invalid(
247                        "over the limit of bytes in a page request",
248                    ));
249                }
250                Ok(())
251            }
252            ToUi::Front {
253                shows: Some((_, target)),
254                ..
255            } => self.target(target),
256            ToUi::Open { target, tree, .. } => {
257                self.key(&target.id)?;
258                self.key(&target.ty)?;
259                self.node(tree, 0)
260            }
261            ToUi::Patch { patches, .. } => {
262                if patches.len() > self.limits.messages as usize {
263                    return Err(Refused::invalid(concat!(
264                        "over the limit of ",
265                        "patches in a message"
266                    )));
267                }
268                patches.iter().try_for_each(|patch| self.patch(patch))
269            }
270            ToUi::Bound { key, value, .. } => {
271                self.key(key)?;
272                self.value(value, 0)
273            }
274            ToUi::Rows {
275                list, keys, rows, ..
276            } => {
277                self.key(list)?;
278                if keys.len() > self.limits.rows as usize || rows.len() > self.limits.rows as usize
279                {
280                    return Err(Refused::invalid(concat!(
281                        "over the limit of ",
282                        "rows in a message"
283                    )));
284                }
285                keys.iter().try_for_each(|key| self.key(key))?;
286                rows.iter().try_for_each(|row| self.node(row, 1))
287            }
288            ToUi::Spaces { keys, .. } => {
289                if keys.len() > self.limits.rows as usize {
290                    return Err(Refused::invalid(concat!(
291                        "over the limit of ",
292                        "views in a message"
293                    )));
294                }
295                keys.iter().try_for_each(|key| self.key(key))
296            }
297            ToUi::RowsChanged { list, changes, .. } => {
298                self.key(list)?;
299                if changes.len() > self.limits.rows as usize {
300                    return Err(Refused::invalid(concat!(
301                        "over the limit of ",
302                        "rows in a message"
303                    )));
304                }
305                changes.iter().try_for_each(|change| match change {
306                    RowChange::Inserted { key, .. } => self.key(key),
307                    RowChange::Changed { row } => self.node(row, 1),
308                    RowChange::Removed { .. } | RowChange::Moved { .. } | RowChange::Reset => {
309                        Ok(())
310                    }
311                })
312            }
313            ToUi::Notice { words, .. } => self.words(words),
314            ToUi::ShowRun { run } => self.key(run),
315            ToUi::Speak(language) => self.key(language),
316            ToUi::Ask(Some(ask)) => {
317                self.string(&ask.action)?;
318                self.string(&ask.invoker)
319            }
320            ToUi::Form(Some(form)) => {
321                self.string(&form.title)?;
322                self.string(&form.submit)?;
323                if let Some(error) = &form.error {
324                    self.string(error)?;
325                }
326                if let Some((_, key)) = &form.from {
327                    self.key(key)?;
328                }
329                if form.fields.len() > self.limits.messages as usize {
330                    return Err(Refused::invalid(concat!(
331                        "over the limit of ",
332                        "fields in a form"
333                    )));
334                }
335                form.fields.iter().try_for_each(|(key, text)| {
336                    self.key(key)?;
337                    self.string(text)
338                })?;
339                self.node(&form.tree, 1)
340            }
341        }
342    }
343
344    fn patch(&self, patch: &Patch) -> Result<(), Refused> {
345        match patch {
346            Patch::SetRoot(node) => self.node(node, 0),
347            Patch::Insert { parent, node, .. } => {
348                self.path(parent)?;
349                self.node(node, parent.len().saturating_add(1))
350            }
351            Patch::Remove { parent, key } | Patch::Move { parent, key, .. } => {
352                self.path(parent)?;
353                self.key(key)
354            }
355            // A prop, binding or event set on its own is checked against its node's kind when
356            // applied ([`Self::node`] of the node it changed).
357            Patch::SetProp { path, name, value } => {
358                self.path(path)?;
359                self.key(name)?;
360                value
361                    .as_ref()
362                    .map_or(Ok(()), |value| self.value(value, path.len()))
363            }
364            Patch::SetBinding { path, binding } => {
365                self.path(path)?;
366                binding
367                    .as_ref()
368                    .map_or(Ok(()), |binding| self.binding(binding))
369            }
370            Patch::SetEvent {
371                path,
372                event,
373                action,
374            } => {
375                self.path(path)?;
376                self.key(event)?;
377                action.as_ref().map_or(Ok(()), |event| self.event(event))
378            }
379            Patch::SetAnchor { path, anchor } => {
380                self.path(path)?;
381                anchor.as_ref().map_or(Ok(()), |anchor| self.key(anchor))
382            }
383            Patch::SpliceProp {
384                path, name, insert, ..
385            } => {
386                self.path(path)?;
387                self.key(name)?;
388                if insert.len() > self.limits.rows as usize {
389                    return Err(Refused::invalid(concat!(
390                        "over the limit of ",
391                        "items of a list value"
392                    )));
393                }
394                insert
395                    .iter()
396                    .try_for_each(|item| self.value(item, path.len().saturating_add(1)))
397            }
398        }
399    }
400
401    /// Check `node`, at `depth`, and everything under it: its kind, and each prop, binding,
402    /// event and child against it.
403    ///
404    /// # Errors
405    /// The first part of it that is not valid.
406    pub fn node(&self, node: &Node, depth: usize) -> Result<(), Refused> {
407        if depth > self.limits.depth as usize {
408            return Err(Refused::invalid(concat!(
409                "over the limit of ",
410                "tree depth"
411            )));
412        }
413        self.key(&node.key)?;
414        if node.props.len() > self.limits.props as usize {
415            return Err(Refused::invalid(concat!(
416                "over the limit of ",
417                "props of a node"
418            )));
419        }
420        if let Some(anchor) = &node.anchor {
421            self.key(anchor)?;
422        }
423        self.shape(node, depth)
424            .map_err(|refused| refused.within(format_args!("`{}` {}", node.kind, node.key)))?;
425        node.children
426            .iter()
427            .try_for_each(|child| self.node(child, depth.saturating_add(1)))
428    }
429
430    /// Check the node's own parts, not its children, against its kind.
431    pub fn shape(&self, node: &Node, depth: usize) -> Result<(), Refused> {
432        if let Some(name) = node.kind.strip_prefix(COMPONENT_PREFIX) {
433            let description = self
434                .catalogue
435                .get(name)
436                .ok_or_else(|| Refused::invalid("a component the toolkit does not describe"))?;
437            return self.component(node, description, depth);
438        }
439        if !primitive(&node.kind) {
440            return Err(Refused::invalid("a kind of node the host does not build"));
441        }
442        for (name, value) in &node.props {
443            self.key(name)?;
444            self.value(value, depth)
445                .map_err(|refused| refused.within(format_args!("prop `{name}`")))?;
446        }
447        for (name, event) in &node.events {
448            self.key(name)?;
449            self.event(event)?;
450        }
451        node.binding
452            .as_ref()
453            .map_or(Ok(()), |binding| self.binding(binding))
454    }
455
456    fn component(
457        &self,
458        node: &Node,
459        description: &Description,
460        depth: usize,
461    ) -> Result<(), Refused> {
462        for (name, value) in &node.props {
463            self.prop(name, value, description, depth)
464                .map_err(|refused| refused.within(format_args!("prop `{name}`")))?;
465        }
466        self.parts(node, description)
467    }
468
469    fn prop(
470        &self,
471        name: &str,
472        value: &Value,
473        description: &Description,
474        depth: usize,
475    ) -> Result<(), Refused> {
476        self.value(value, depth)?;
477        {
478            let declared = description
479                .prop(name)
480                .map(|prop| &prop.ty)
481                .or_else(|| description.state(name).map(|state| &state.ty))
482                // A value the view gives a control rather than binds to it (a device's
483                // volume): the control shows it, and its `change` event says what the person
484                // did with it.
485                .or_else(|| {
486                    description
487                        .event("change")
488                        .and_then(|_| description.binding(name))
489                        .map(|binding| &binding.ty)
490                });
491            match declared {
492                Some(ty) => {
493                    if !fits(value, ty) {
494                        return Err(Refused::invalid(
495                            "a prop holding a value of another type than its component declares",
496                        ));
497                    }
498                }
499                None if node_arg(name) => {}
500                // Which binding a node binds, of a component with several.
501                None if name == "bind" => {
502                    let Value::Text(bound) = value else {
503                        return Err(Refused::invalid("a binding named by other than text"));
504                    };
505                    if description.binding(bound).is_none() {
506                        return Err(Refused::invalid("a binding its component does not declare"));
507                    }
508                }
509                // A companion of a prop the component declares: `value:as` says which kind of
510                // text `value` holds, and `meta:time` the time of day the day `meta` is due at.
511                None if companion(name).is_some_and(|(prop, _)| {
512                    description.prop(prop).is_some() || description.state(prop).is_some()
513                }) => {}
514                None => {
515                    return Err(Refused::invalid("a prop its component does not declare"));
516                }
517            }
518        }
519        Ok(())
520    }
521
522    fn parts(&self, node: &Node, description: &Description) -> Result<(), Refused> {
523        for (name, event) in &node.events {
524            if description.event(name).is_none()
525                && description.binding(name).is_none()
526                && !offers(description, name)
527            {
528                return Err(Refused::invalid("an event its component does not declare")
529                    .within(format_args!("event `{name}`")));
530            }
531            self.event(event)?;
532        }
533        if let Some(binding) = &node.binding {
534            if description.bindings.is_empty() {
535                return Err(Refused::invalid("a binding on a component that takes none"));
536            }
537            self.binding(binding)?;
538        }
539        Ok(())
540    }
541
542    fn binding(&self, binding: &Binding) -> Result<(), Refused> {
543        self.string(&binding.name)?;
544        if let Some((target, field)) = &binding.field {
545            self.key(target)?;
546            self.key(field)?;
547        }
548        Ok(())
549    }
550
551    fn event(&self, event: &Event) -> Result<(), Refused> {
552        if let Some((target, field)) = &event.toggles {
553            self.key(target)?;
554            self.key(field)?;
555        }
556        if let Some(invoked) = &event.invokes {
557            self.key(&invoked.resource)?;
558            self.key(&invoked.action)?;
559        }
560        Ok(())
561    }
562
563    fn value(&self, value: &Value, depth: usize) -> Result<(), Refused> {
564        if depth > self.limits.depth as usize {
565            return Err(Refused::invalid(concat!(
566                "over the limit of ",
567                "value depth"
568            )));
569        }
570        match value {
571            Value::Unit | Value::Int(_) | Value::Bool(_) => Ok(()),
572            Value::Float(number) if number.is_finite() => Ok(()),
573            Value::Float(_) => Err(Refused::invalid("a number that is not finite")),
574            Value::Text(text) | Value::Error(text) => self.string(text),
575            Value::Enum(case) => self.key(case),
576            Value::Case { case, fields } => {
577                self.key(case)?;
578                for (name, held) in fields {
579                    self.key(name)?;
580                    self.value(held, depth.saturating_add(1))?;
581                }
582                Ok(())
583            }
584            Value::List(items) => {
585                if items.len() > self.limits.rows as usize {
586                    return Err(Refused::invalid(concat!(
587                        "over the limit of ",
588                        "items of a list value"
589                    )));
590                }
591                items
592                    .iter()
593                    .try_for_each(|item| self.value(item, depth.saturating_add(1)))
594            }
595            Value::Opt(held) => held
596                .as_deref()
597                .map_or(Ok(()), |held| self.value(held, depth.saturating_add(1))),
598            Value::Ref(resource) => {
599                self.key(&resource.id)?;
600                self.key(&resource.ty)
601            }
602            Value::Actor(who) => {
603                self.key(who.id.id())?;
604                self.string(&who.name)
605            }
606            Value::Map(entries) => {
607                if entries.len() > self.limits.rows as usize {
608                    return Err(Refused::invalid(concat!(
609                        "over the limit of ",
610                        "entries of a map value"
611                    )));
612                }
613                entries.iter().try_for_each(|(key, value)| {
614                    self.value(key, depth.saturating_add(1))?;
615                    self.value(value, depth.saturating_add(1))
616                })
617            }
618            Value::Action(offered) => {
619                self.string(&offered.label)?;
620                self.key(&offered.event)?;
621                offered.icon.as_ref().map_or(Ok(()), |icon| self.key(icon))
622            }
623            Value::Picture(picture) => self.string(&picture.src),
624            Value::File(file) => {
625                self.string(&file.name)?;
626                self.key(&file.media)?;
627                self.string(&file.url)
628            }
629            Value::Link { reference, title } => {
630                self.string(reference)?;
631                self.string(title)
632            }
633            Value::Rich(rich) => {
634                if rich.blocks.len() > self.limits.rows as usize
635                    || rich.embeds.len() > self.limits.rows as usize
636                {
637                    return Err(Refused::invalid(concat!(
638                        "over the limit of ",
639                        "paragraphs of rich text"
640                    )));
641                }
642                rich.strings().try_for_each(|text| self.string(text))
643            }
644        }
645    }
646
647    fn words(&self, words: &Words) -> Result<(), Refused> {
648        match words {
649            Words::Plain(text) => self.string(text),
650            Words::Phrase { id, args } => {
651                self.key(id)?;
652                if args.len() > self.limits.props as usize {
653                    return Err(Refused::invalid(concat!(
654                        "over the limit of ",
655                        "arguments of a phrase"
656                    )));
657                }
658                args.iter().try_for_each(|(name, value)| {
659                    self.key(name)?;
660                    self.string(value)
661                })
662            }
663        }
664    }
665
666    fn path(&self, path: &[String]) -> Result<(), Refused> {
667        if path.len() > self.limits.path as usize {
668            return Err(Refused::invalid(concat!(
669                "over the limit of ",
670                "path length"
671            )));
672        }
673        path.iter().try_for_each(|key| self.key(key))
674    }
675
676    fn key(&self, key: &str) -> Result<(), Refused> {
677        if key.len() > self.limits.key_bytes as usize {
678            return Err(Refused::invalid(concat!(
679                "over the limit of ",
680                "key length"
681            )));
682        }
683        Ok(())
684    }
685
686    fn resource(&self, resource: &ResourceRef) -> Result<(), Refused> {
687        self.key(&resource.id)?;
688        self.key(&resource.ty)
689    }
690
691    fn string(&self, text: &str) -> Result<(), Refused> {
692        if text.len() > self.limits.string_bytes as usize {
693            return Err(Refused::invalid(concat!(
694                "over the limit of ",
695                "string length"
696            )));
697        }
698        Ok(())
699    }
700
701    /// Check one batch the host sent an app: in an app host, what the window says it did is
702    /// as hostile as what an app sends its window.
703    ///
704    /// # Errors
705    /// The first thing in it that is not valid.
706    pub fn to_app(&self, batch: &[ToApp]) -> Result<(), Refused> {
707        if batch.len() > self.limits.messages as usize {
708            return Err(Refused::invalid(concat!(
709                "over the limit of ",
710                "messages in a batch"
711            )));
712        }
713        for message in batch {
714            self.to_app_message(message)?;
715        }
716        Ok(())
717    }
718
719    /// Check one message the host sent an app: the keys it names, then the value it carries.
720    fn to_app_message(&self, message: &ToApp) -> Result<(), Refused> {
721        self.to_app_targets(message)?;
722        self.to_app_payload(message)
723    }
724
725    /// The keys and resources `message` names.
726    fn to_app_targets(&self, message: &ToApp) -> Result<(), Refused> {
727        match message {
728            ToApp::Fire { key, event, .. } => {
729                self.key(key)?;
730                self.key(event)?;
731            }
732            ToApp::Toggle { target, key, .. }
733            | ToApp::Splice { target, key, .. }
734            | ToApp::Edit { target, key, .. }
735            | ToApp::EditRich { target, key, .. } => {
736                self.resource(target)?;
737                self.key(key)?;
738            }
739            ToApp::Resolve { key, .. } => self.key(key)?,
740            ToApp::Rows {
741                list, open, menu, ..
742            } => {
743                for key in std::iter::once(list).chain(open).chain(menu) {
744                    self.key(key)?;
745                }
746            }
747            ToApp::Focus { at } => {
748                if let Some((_, key)) = at {
749                    self.key(key)?;
750                }
751            }
752            ToApp::FormEdit { field, .. } => self.key(field)?,
753            ToApp::Open { .. }
754            | ToApp::OpenReference { .. }
755            | ToApp::Space { .. }
756            | ToApp::Invoke { .. }
757            | ToApp::Serving { .. }
758            | ToApp::PageAnswer { .. }
759            | ToApp::PagePrompt { .. }
760            | ToApp::Back
761            | ToApp::Answer(_)
762            | ToApp::Undo
763            | ToApp::Redo
764            | ToApp::Composing(_)
765            | ToApp::Held(_)
766            | ToApp::SaveAgain
767            | ToApp::History { .. }
768            | ToApp::FormSubmit { .. }
769            | ToApp::FormCancel { .. } => {}
770        }
771        Ok(())
772    }
773
774    /// The value `message` carries, and how large it comes to.
775    fn to_app_payload(&self, message: &ToApp) -> Result<(), Refused> {
776        match message {
777            ToApp::Fire {
778                value: Some(value), ..
779            } => self.value(value, 0),
780            ToApp::Splice { insert, .. } => self.string(insert),
781            ToApp::Edit { text, .. } | ToApp::FormEdit { text, .. } => self.string(text),
782            ToApp::EditRich { rich, .. } => self.value(&Value::Rich(rich.clone()), 0),
783            ToApp::Open { resource } => self.resource(resource),
784            ToApp::OpenReference { reference } => self.string(reference),
785            ToApp::Rows { start, end, .. } => {
786                if end < start || end.saturating_sub(*start) > self.limits.rows {
787                    return Err(Refused::invalid(concat!(
788                        "over the limit of ",
789                        "rows in a message"
790                    )));
791                }
792                Ok(())
793            }
794            ToApp::Space {
795                width, height, rem, ..
796            } => {
797                if !(width.is_finite()
798                    && height.is_finite()
799                    && *width >= 0.0
800                    && *height >= 0.0
801                    && rem.is_finite()
802                    && *rem > 0.0)
803                {
804                    return Err(Refused::invalid("a space is no size"));
805                }
806                Ok(())
807            }
808            ToApp::Invoke { address, argument } => self.invoke(address, argument.as_deref()),
809            ToApp::Serving { call, invoker } => self.serving(call, invoker.as_deref()),
810            ToApp::PageAnswer { answer, .. } => {
811                if answer.len() > super::MAX_PAGE_BYTES {
812                    return Err(Refused::invalid("over the limit of bytes in a page answer"));
813                }
814                Ok(())
815            }
816            ToApp::PagePrompt { prompt } => {
817                if prompt.len() > self.limits.string_bytes as usize {
818                    return Err(Refused::invalid(
819                        "over the limit of bytes in a page's prompt",
820                    ));
821                }
822                Ok(())
823            }
824            _ => Ok(()),
825        }
826    }
827
828    /// Check an action the host asks an app to run.
829    fn invoke(&self, address: &ActionAddress, argument: Option<&str>) -> Result<(), Refused> {
830        self.key(&address.resource)?;
831        self.key(&address.action)?;
832        argument.map_or(Ok(()), |argument| self.string(argument))
833    }
834
835    /// Check a signed call the host serves for its invoker.
836    fn serving(&self, call: &[u8], invoker: Option<&str>) -> Result<(), Refused> {
837        if call.len() > self.limits.string_bytes as usize {
838            return Err(Refused::invalid(
839                "a signed call is over the limit of a string",
840            ));
841        }
842        invoker.map_or(Ok(()), |invoker| self.string(invoker))
843    }
844}
845
846/// The event an action offered in the prop `prop` fires: `actions.2` for the third of
847/// `actions`. Its node gives it what the action runs, as it gives its declared events.
848#[must_use]
849pub fn offered_event(prop: &str, index: usize) -> String {
850    format!("{prop}.{index}")
851}
852
853/// Whether `event` is one an action offered in a prop of the component fires
854/// ([`offered_event`]): the host binds such an event to the action it runs.
855#[must_use]
856pub fn offers(description: &Description, event: &str) -> bool {
857    fn holds_actions(ty: &Type) -> bool {
858        match ty {
859            Type::Action => true,
860            Type::Option(inner) | Type::List(inner) | Type::Set(inner) => holds_actions(inner),
861            Type::Map { value, .. } => holds_actions(value),
862            _ => false,
863        }
864    }
865    event
866        .rsplit_once('.')
867        .filter(|(_, index)| !index.is_empty() && index.bytes().all(|b| b.is_ascii_digit()))
868        .and_then(|(prop, _)| description.prop(prop))
869        .is_some_and(|prop| holds_actions(&prop.ty))
870}
871
872/// Whether `name` is a sizing or placement argument every node takes, with its unit
873/// (`min.rem`).
874fn node_arg(name: &str) -> bool {
875    let base = name
876        .strip_suffix(".rem")
877        .or_else(|| name.strip_suffix(".dp"))
878        .unwrap_or(name);
879    NODE_ARGS.contains(&base)
880}
881
882/// Whether `value` is one of the type `ty`, as the host reads it into a widget: text shows any
883/// value as text, a whole number is a number, an `Option` holds nothing or a value.
884#[must_use]
885pub fn fits(value: &Value, ty: &Type) -> bool {
886    match (ty, value) {
887        (Type::Option(_), Value::Opt(None) | Value::Unit)
888        | (Type::Int, Value::Int(_))
889        | (Type::Float, Value::Float(_) | Value::Int(_))
890        | (Type::Bool, Value::Bool(_) | Value::Int(_))
891        | (Type::Actor, Value::Actor(_))
892        | (Type::Resource, Value::Ref(_))
893        | (Type::Icon | Type::Time, Value::Text(_))
894        | (Type::Picture, Value::Picture(_))
895        | (Type::File, Value::File(_))
896        | (Type::Link, Value::Link { .. })
897        | (Type::RichText, Value::Rich(_))
898        | (Type::Action, Value::Action(_))
899        // The case's fields are read against the catalogue's set where the node is built.
900        | (Type::Cases { .. }, Value::Case { .. }) => true,
901        (Type::Option(inner), Value::Opt(Some(held))) => fits(held, inner),
902        (Type::Option(inner), other) => fits(other, inner),
903        (_, Value::Opt(Some(held))) => fits(held, ty),
904        (
905            Type::Text,
906            Value::List(_)
907            | Value::Ref(_)
908            | Value::Rich(_)
909            | Value::Map(_)
910            | Value::Action(_)
911            | Value::Picture(_)
912            | Value::File(_)
913            | Value::Link { .. },
914        ) => false,
915        (Type::Text, _) => true,
916        (Type::Choice { cases, .. }, Value::Text(case) | Value::Enum(case)) => cases.contains(case),
917        (Type::List(inner) | Type::Set(inner), Value::List(items)) => {
918            items.iter().all(|item| fits(item, inner))
919        }
920        (Type::Map { key, value }, Value::Map(entries)) => {
921            entries.iter().all(|(k, v)| fits(k, key) && fits(v, value))
922        }
923        _ => false,
924    }
925}
926
927#[cfg(test)]
928mod tests {
929    use super::super::Level;
930    use super::*;
931
932    fn validator() -> Validator<'static> {
933        Validator::new(
934            tilo_ui_graph::component::catalogue(),
935            PatchLimits::default(),
936        )
937    }
938
939    fn component(name: &str, key: &str, props: &[(&str, Value)]) -> Node {
940        let mut node = Node::empty(&format!("{COMPONENT_PREFIX}{name}"), key);
941        for (prop, value) in props {
942            node.props.insert((*prop).to_owned(), value.clone());
943        }
944        node
945    }
946
947    fn open(tree: Node) -> Vec<ToUi> {
948        vec![ToUi::Open {
949            level: Level::Root,
950            target: ResourceRef {
951                id: "doc".to_owned(),
952                ty: "notes.Notebook".to_owned(),
953            },
954            tree,
955            front: None,
956
957            capture_protected: false,
958        }]
959    }
960
961    /// A text an edit keeps is one the window can carry: the bytes of one string here are the
962    /// bytes of one text an action carries, so a paste at the limit is shown and a longer one is
963    /// refused where it is made.
964    #[test]
965    fn a_text_an_edit_keeps_is_one_a_window_carries() {
966        assert_eq!(
967            PatchLimits::default().string_bytes as usize,
968            tilo_actions::MAX_TEXT_BYTES
969        );
970    }
971
972    #[test]
973    fn a_tree_of_described_components_and_primitives_passes() {
974        let mut stack = Node::empty("stack", "s");
975        stack.props.insert("gap".to_owned(), Value::text("section"));
976        stack.props.insert("min.rem".to_owned(), Value::Float(12.0));
977        let mut button = component("Button", "b", &[("label", Value::text("Send"))]);
978        button.events.insert("press".to_owned(), Event::default());
979        stack.children = vec![
980            component(
981                "Text",
982                "t",
983                &[
984                    ("value", Value::text("2026-10-24")),
985                    ("value:as", Value::text("date")),
986                    ("role", Value::text("title")),
987                ],
988            ),
989            button,
990        ];
991        assert_eq!(validator().to_ui(&open(stack)), Ok(()));
992    }
993
994    /// A row's quiet fact is a day the person reads (`Today`, `Overdue`), and the time of day it
995    /// is due at reads with it (`Today 9:00 AM`): the day is the prop the row declares, and the
996    /// time its companion.
997    #[test]
998    fn a_day_reads_with_the_time_of_day_it_is_due_at() {
999        let row = component(
1000            "ListRow",
1001            "t",
1002            &[
1003                ("title", Value::text("Call the landlord")),
1004                ("meta", Value::text("2026-11-03")),
1005                ("meta:as", Value::text("date")),
1006                ("meta:time", Value::text("2026-11-03T17:00:00Z")),
1007            ],
1008        );
1009        assert_eq!(validator().to_ui(&open(row)), Ok(()));
1010        let mistyped = component(
1011            "ListRow",
1012            "t",
1013            &[("title", Value::text("x")), ("meta:tmie", Value::text("x"))],
1014        );
1015        assert!(
1016            validator().to_ui(&open(mistyped)).is_err(),
1017            "a companion is a name the component declares a prop for, spelled as the host reads it"
1018        );
1019    }
1020
1021    #[test]
1022    fn what_a_component_does_not_declare_is_refused() {
1023        let unknown = component("Nothing", "x", &[]);
1024        assert!(validator().to_ui(&open(unknown)).is_err());
1025        let prop = component("Text", "t", &[("color", Value::text("red"))]);
1026        assert!(validator().to_ui(&open(prop)).is_err());
1027        let typed = component("Text", "t", &[("role", Value::text("shouting"))]);
1028        assert!(
1029            validator().to_ui(&open(typed)).is_err(),
1030            "a case not declared"
1031        );
1032        let mut event = component("Text", "t", &[("value", Value::text("x"))]);
1033        event.events.insert("press".to_owned(), Event::default());
1034        assert!(validator().to_ui(&open(event)).is_err());
1035        assert!(
1036            validator()
1037                .to_ui(&open(Node::empty("script", "s")))
1038                .is_err()
1039        );
1040    }
1041
1042    /// A slider over a value the view does not hold (a device's volume) is given that value,
1043    /// and says through `change` what the person did with it.
1044    #[test]
1045    fn a_value_given_to_a_control_with_a_change_event_passes() {
1046        let mut slider = component("Slider", "s", &[("value", Value::Float(0.4))]);
1047        slider.events.insert("change".to_owned(), Event::default());
1048        assert_eq!(validator().to_ui(&open(slider)), Ok(()));
1049        let wrong = component("Slider", "s", &[("value", Value::text("loud"))]);
1050        assert!(validator().to_ui(&open(wrong)).is_err());
1051    }
1052
1053    #[test]
1054    fn work_is_bounded() {
1055        let limits = PatchLimits {
1056            depth: 3,
1057            key_bytes: 16,
1058            ..PatchLimits::default()
1059        };
1060        let checked = Validator::new(tilo_ui_graph::component::catalogue(), limits);
1061        let mut deep = Node::empty("stack", "0");
1062        for level in 1..6 {
1063            deep = Node {
1064                children: vec![deep],
1065                ..Node::empty("stack", &level.to_string())
1066            };
1067        }
1068        assert_eq!(
1069            checked.to_ui(&open(deep)).map_err(|refused| refused.what),
1070            Err("over the limit of tree depth")
1071        );
1072        assert_eq!(
1073            checked
1074                .to_ui(&open(Node::empty(
1075                    "stack",
1076                    "a key far longer than sixteen bytes"
1077                )))
1078                .map_err(|refused| refused.what),
1079            Err("over the limit of key length")
1080        );
1081        assert!(
1082            validator()
1083                .to_ui(&open(component(
1084                    "Text",
1085                    "t",
1086                    &[("value", Value::Float(f64::NAN))]
1087                )))
1088                .is_err()
1089        );
1090    }
1091}