tilo-render-protocol 0.5.0

Scene transport between Tilo apps and the workspace's render service: frame records, vello encodings by resource id, the validator every scene passes before a GPU sees it, and the shared memory and control channel they travel on.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
//! The check every batch an app sends passes before the UI host touches a widget.
//!
//! The UI host builds every window of a workspace from what each app sends. A batch that makes it
//! build a widget wrongly, or work without bound, takes the workspace's windows down with it. So
//! every message is checked, once, in the host's own copy:
//!
//! - **Valid by type.** A described component's node (`ui.ListRow`) names a component of the
//!   toolkit's catalogue; each of its props is one the description declares (or a sizing
//!   argument every node takes, or the companion of a prop it declares, such as `value:as`
//!   saying which kind of text `value` holds), holding a value of the declared type; each event
//!   and binding is one it declares. A primitive of the language (`stack`, `list`) is one the
//!   host builds.
//! - **Bounded.** Strings, keys, paths, props, depth and the rows of one message are limited,
//!   and each window's trees together hold at most [`PatchLimits::nodes`] nodes (the host
//!   counts them as it applies patches: one window's budget is its own).
//! - **Only its own trees.** A connection is one window of one app; its patches name nodes by
//!   key paths in the trees it sent, and a path that names no node is refused when applied.

use tilo_actions::ActionAddress;
use tilo_ui_graph::component::{Catalogue, Description, Type, companion};

use super::{
    Binding, Event, MAX_CALL_PICTURE_BYTES, MAX_CALL_PICTURES, Node, Patch, ResourceRef, RowChange,
    ToApp, ToUi, Value, Words,
};

/// Why a batch was refused: what was wrong, and where.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("{what}{at}")]
pub struct Refused {
    pub what: &'static str,
    /// Where, from the outermost part in, such as `` in `stack` s in prop `gap` ``.
    pub at: String,
}

impl Refused {
    #[must_use]
    pub fn invalid(what: &'static str) -> Self {
        Self {
            what,
            at: String::new(),
        }
    }

    /// The same refusal, found in `part`.
    #[must_use]
    pub fn within(mut self, part: impl std::fmt::Display) -> Self {
        self.at = format!(" in {part}{}", self.at);
        self
    }
}

/// What one window may make its UI host hold and do.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PatchLimits {
    /// Nodes of one window's trees together, rendered rows included.
    pub nodes: u32,
    /// How deep a tree nests.
    pub depth: u32,
    /// Bytes of one string: a prop's text, a bound value, a splice — as much
    /// as one text an action carries ([`tilo_actions::MAX_TEXT_BYTES`]), so a
    /// text an edit keeps is always a text a window can show.
    pub string_bytes: u32,
    /// Bytes of one key or name.
    pub key_bytes: u32,
    /// Keys in one path.
    pub path: u32,
    /// Props of one node.
    pub props: u32,
    /// Rows or keys in one message.
    pub rows: u32,
    /// Messages in one batch.
    pub messages: u32,
}

/// One text's bytes as a window counts one string: the same number
/// ([`tilo_actions::MAX_TEXT_BYTES`]), so a text an edit keeps is never one the
/// window refuses to show.
#[expect(
    clippy::cast_possible_truncation,
    reason = "one text's bytes, 8 MiB, fit a window's count of a string"
)]
const STRING_BYTES: u32 = tilo_actions::MAX_TEXT_BYTES as u32;

impl Default for PatchLimits {
    fn default() -> Self {
        Self {
            nodes: 200_000,
            depth: 128,
            string_bytes: STRING_BYTES,
            key_bytes: 4096,
            path: 128,
            props: 128,
            rows: 8192,
            messages: 65_536,
        }
    }
}

/// The sizing and placement arguments every node takes (`fill`, `min: 12.rem`, `at`), as the
/// language's `prims::NODE_ARGS` names them.
pub const NODE_ARGS: &[&str] = &[
    "fill", "min", "max", "height", "aspect", "span", "lines", "truncate", "at", "lead", "x", "y",
];

/// Every primitive of the language a view may send: the layouts, controls and blocks the host
/// builds itself, and `part`, a component's named part. A primitive's props are the language's
/// arguments, which the host reads by name, each as the type it takes, ignoring what it does
/// not read; so what is checked of them is that the primitive is one the host builds and that
/// every value is bounded.
pub const PRIMITIVES: &[&str] = &[
    "stack",
    "column",
    "fragment",
    "primary",
    "secondary",
    "item",
    "row",
    "grid",
    "split",
    "page",
    "layers",
    "scroll",
    "spacer",
    "divider",
    "progress",
    "form",
    "field",
    "toggle",
    "choice",
    "list",
    "checkbox",
    "date",
    "image",
    "embed",
    "invocation",
    "error",
    "text",
    PART,
];

/// The kind of a node holding the content of a component's named part.
pub const PART: &str = "part";

/// The prefix of a described component's kind: `ui.ListRow`.
pub const COMPONENT_PREFIX: &str = "ui.";

/// Whether `kind` is a primitive the host builds.
#[must_use]
pub fn primitive(kind: &str) -> bool {
    PRIMITIVES.contains(&kind)
}

/// Checks batches against a toolkit's catalogue and a window's limits.
pub struct Validator<'a> {
    catalogue: &'a Catalogue,
    limits: PatchLimits,
}

impl<'a> Validator<'a> {
    #[must_use]
    pub fn new(catalogue: &'a Catalogue, limits: PatchLimits) -> Self {
        Self { catalogue, limits }
    }

    #[must_use]
    pub fn limits(&self) -> &PatchLimits {
        &self.limits
    }

    /// Check one batch an app sent its window.
    ///
    /// # Errors
    /// The first thing in it that is not valid.
    pub fn to_ui(&self, batch: &[ToUi]) -> Result<(), Refused> {
        if batch.len() > self.limits.messages as usize {
            return Err(Refused::invalid(concat!(
                "over the limit of ",
                "messages in a batch"
            )));
        }
        for message in batch {
            self.message(message)?;
        }
        Ok(())
    }

    /// A resource the window names: its id and its type.
    fn target(&self, target: &ResourceRef) -> Result<(), Refused> {
        self.key(&target.id)?;
        self.key(&target.ty)
    }

    /// `bytes` a message carries whole, within the limit of a string's; `refused` says it is not.
    fn carried(&self, bytes: usize, refused: &'static str) -> Result<(), Refused> {
        if bytes > self.limits.string_bytes as usize {
            return Err(Refused::invalid(refused));
        }
        Ok(())
    }

    #[allow(
        clippy::too_many_lines,
        reason = "one arm per message a window takes, read side by side as the protocol lists them"
    )]
    fn message(&self, message: &ToUi) -> Result<(), Refused> {
        match message {
            ToUi::Loading
            | ToUi::Close
            | ToUi::Front { shows: None, .. }
            | ToUi::Ask(None)
            | ToUi::Form(None)
            | ToUi::Activate
            | ToUi::Kept(_)
            | ToUi::History(_)
            | ToUi::Took { .. } => Ok(()),
            ToUi::Focus { key } => match key {
                Some(key) => self.key(key),
                None => Ok(()),
            },
            ToUi::Actions(catalogue) => {
                self.carried(catalogue.len(), "over the limit of bytes in a catalogue")
            }
            ToUi::Heard(bytes) | ToUi::Outputs(bytes) => {
                self.carried(bytes.len(), "over the limit of bytes in a message")
            }
            ToUi::CallPictures { shown, pictures } => {
                if shown.len() > MAX_CALL_PICTURES || pictures.len() > MAX_CALL_PICTURES {
                    return Err(Refused::invalid("over the limit of pictures in a message"));
                }
                for shown in shown {
                    self.key(&shown.person)?;
                }
                for picture in pictures {
                    self.key(&picture.person)?;
                    self.key(&picture.stream)?;
                    if picture.object.is_empty() || picture.object.len() > MAX_CALL_PICTURE_BYTES {
                        return Err(Refused::invalid("a call picture is not one picture"));
                    }
                }
                Ok(())
            }
            ToUi::Page { request, .. } => {
                if request.len() > super::MAX_PAGE_BYTES {
                    return Err(Refused::invalid(
                        "over the limit of bytes in a page request",
                    ));
                }
                Ok(())
            }
            ToUi::Front {
                shows: Some((_, target)),
                ..
            } => self.target(target),
            ToUi::Open { target, tree, .. } => {
                self.key(&target.id)?;
                self.key(&target.ty)?;
                self.node(tree, 0)
            }
            ToUi::Patch { patches, .. } => {
                if patches.len() > self.limits.messages as usize {
                    return Err(Refused::invalid(concat!(
                        "over the limit of ",
                        "patches in a message"
                    )));
                }
                patches.iter().try_for_each(|patch| self.patch(patch))
            }
            ToUi::Bound { key, value, .. } => {
                self.key(key)?;
                self.value(value, 0)
            }
            ToUi::Rows {
                list, keys, rows, ..
            } => {
                self.key(list)?;
                if keys.len() > self.limits.rows as usize || rows.len() > self.limits.rows as usize
                {
                    return Err(Refused::invalid(concat!(
                        "over the limit of ",
                        "rows in a message"
                    )));
                }
                keys.iter().try_for_each(|key| self.key(key))?;
                rows.iter().try_for_each(|row| self.node(row, 1))
            }
            ToUi::Spaces { keys, .. } => {
                if keys.len() > self.limits.rows as usize {
                    return Err(Refused::invalid(concat!(
                        "over the limit of ",
                        "views in a message"
                    )));
                }
                keys.iter().try_for_each(|key| self.key(key))
            }
            ToUi::RowsChanged { list, changes, .. } => {
                self.key(list)?;
                if changes.len() > self.limits.rows as usize {
                    return Err(Refused::invalid(concat!(
                        "over the limit of ",
                        "rows in a message"
                    )));
                }
                changes.iter().try_for_each(|change| match change {
                    RowChange::Inserted { key, .. } => self.key(key),
                    RowChange::Changed { row } => self.node(row, 1),
                    RowChange::Removed { .. } | RowChange::Moved { .. } | RowChange::Reset => {
                        Ok(())
                    }
                })
            }
            ToUi::Notice { words, .. } => self.words(words),
            ToUi::ShowRun { run } => self.key(run),
            ToUi::Speak(language) => self.key(language),
            ToUi::Ask(Some(ask)) => {
                self.string(&ask.action)?;
                self.string(&ask.invoker)
            }
            ToUi::Form(Some(form)) => {
                self.string(&form.title)?;
                self.string(&form.submit)?;
                if let Some(error) = &form.error {
                    self.string(error)?;
                }
                if let Some((_, key)) = &form.from {
                    self.key(key)?;
                }
                if form.fields.len() > self.limits.messages as usize {
                    return Err(Refused::invalid(concat!(
                        "over the limit of ",
                        "fields in a form"
                    )));
                }
                form.fields.iter().try_for_each(|(key, text)| {
                    self.key(key)?;
                    self.string(text)
                })?;
                self.node(&form.tree, 1)
            }
        }
    }

    fn patch(&self, patch: &Patch) -> Result<(), Refused> {
        match patch {
            Patch::SetRoot(node) => self.node(node, 0),
            Patch::Insert { parent, node, .. } => {
                self.path(parent)?;
                self.node(node, parent.len().saturating_add(1))
            }
            Patch::Remove { parent, key } | Patch::Move { parent, key, .. } => {
                self.path(parent)?;
                self.key(key)
            }
            // A prop, binding or event set on its own is checked against its node's kind when
            // applied ([`Self::node`] of the node it changed).
            Patch::SetProp { path, name, value } => {
                self.path(path)?;
                self.key(name)?;
                value
                    .as_ref()
                    .map_or(Ok(()), |value| self.value(value, path.len()))
            }
            Patch::SetBinding { path, binding } => {
                self.path(path)?;
                binding
                    .as_ref()
                    .map_or(Ok(()), |binding| self.binding(binding))
            }
            Patch::SetEvent {
                path,
                event,
                action,
            } => {
                self.path(path)?;
                self.key(event)?;
                action.as_ref().map_or(Ok(()), |event| self.event(event))
            }
            Patch::SetAnchor { path, anchor } => {
                self.path(path)?;
                anchor.as_ref().map_or(Ok(()), |anchor| self.key(anchor))
            }
            Patch::SpliceProp {
                path, name, insert, ..
            } => {
                self.path(path)?;
                self.key(name)?;
                if insert.len() > self.limits.rows as usize {
                    return Err(Refused::invalid(concat!(
                        "over the limit of ",
                        "items of a list value"
                    )));
                }
                insert
                    .iter()
                    .try_for_each(|item| self.value(item, path.len().saturating_add(1)))
            }
        }
    }

    /// Check `node`, at `depth`, and everything under it: its kind, and each prop, binding,
    /// event and child against it.
    ///
    /// # Errors
    /// The first part of it that is not valid.
    pub fn node(&self, node: &Node, depth: usize) -> Result<(), Refused> {
        if depth > self.limits.depth as usize {
            return Err(Refused::invalid(concat!(
                "over the limit of ",
                "tree depth"
            )));
        }
        self.key(&node.key)?;
        if node.props.len() > self.limits.props as usize {
            return Err(Refused::invalid(concat!(
                "over the limit of ",
                "props of a node"
            )));
        }
        if let Some(anchor) = &node.anchor {
            self.key(anchor)?;
        }
        self.shape(node, depth)
            .map_err(|refused| refused.within(format_args!("`{}` {}", node.kind, node.key)))?;
        node.children
            .iter()
            .try_for_each(|child| self.node(child, depth.saturating_add(1)))
    }

    /// Check the node's own parts, not its children, against its kind.
    pub fn shape(&self, node: &Node, depth: usize) -> Result<(), Refused> {
        if let Some(name) = node.kind.strip_prefix(COMPONENT_PREFIX) {
            let description = self
                .catalogue
                .get(name)
                .ok_or_else(|| Refused::invalid("a component the toolkit does not describe"))?;
            return self.component(node, description, depth);
        }
        if !primitive(&node.kind) {
            return Err(Refused::invalid("a kind of node the host does not build"));
        }
        for (name, value) in &node.props {
            self.key(name)?;
            self.value(value, depth)
                .map_err(|refused| refused.within(format_args!("prop `{name}`")))?;
        }
        for (name, event) in &node.events {
            self.key(name)?;
            self.event(event)?;
        }
        node.binding
            .as_ref()
            .map_or(Ok(()), |binding| self.binding(binding))
    }

    fn component(
        &self,
        node: &Node,
        description: &Description,
        depth: usize,
    ) -> Result<(), Refused> {
        for (name, value) in &node.props {
            self.prop(name, value, description, depth)
                .map_err(|refused| refused.within(format_args!("prop `{name}`")))?;
        }
        self.parts(node, description)
    }

    fn prop(
        &self,
        name: &str,
        value: &Value,
        description: &Description,
        depth: usize,
    ) -> Result<(), Refused> {
        self.value(value, depth)?;
        {
            let declared = description
                .prop(name)
                .map(|prop| &prop.ty)
                .or_else(|| description.state(name).map(|state| &state.ty))
                // A value the view gives a control rather than binds to it (a device's
                // volume): the control shows it, and its `change` event says what the person
                // did with it.
                .or_else(|| {
                    description
                        .event("change")
                        .and_then(|_| description.binding(name))
                        .map(|binding| &binding.ty)
                });
            match declared {
                Some(ty) => {
                    if !fits(value, ty) {
                        return Err(Refused::invalid(
                            "a prop holding a value of another type than its component declares",
                        ));
                    }
                }
                None if node_arg(name) => {}
                // Which binding a node binds, of a component with several.
                None if name == "bind" => {
                    let Value::Text(bound) = value else {
                        return Err(Refused::invalid("a binding named by other than text"));
                    };
                    if description.binding(bound).is_none() {
                        return Err(Refused::invalid("a binding its component does not declare"));
                    }
                }
                // A companion of a prop the component declares: `value:as` says which kind of
                // text `value` holds, and `meta:time` the time of day the day `meta` is due at.
                None if companion(name).is_some_and(|(prop, _)| {
                    description.prop(prop).is_some() || description.state(prop).is_some()
                }) => {}
                None => {
                    return Err(Refused::invalid("a prop its component does not declare"));
                }
            }
        }
        Ok(())
    }

    fn parts(&self, node: &Node, description: &Description) -> Result<(), Refused> {
        for (name, event) in &node.events {
            if description.event(name).is_none()
                && description.binding(name).is_none()
                && !offers(description, name)
            {
                return Err(Refused::invalid("an event its component does not declare")
                    .within(format_args!("event `{name}`")));
            }
            self.event(event)?;
        }
        if let Some(binding) = &node.binding {
            if description.bindings.is_empty() {
                return Err(Refused::invalid("a binding on a component that takes none"));
            }
            self.binding(binding)?;
        }
        Ok(())
    }

    fn binding(&self, binding: &Binding) -> Result<(), Refused> {
        self.string(&binding.name)?;
        if let Some((target, field)) = &binding.field {
            self.key(target)?;
            self.key(field)?;
        }
        Ok(())
    }

    fn event(&self, event: &Event) -> Result<(), Refused> {
        if let Some((target, field)) = &event.toggles {
            self.key(target)?;
            self.key(field)?;
        }
        if let Some(invoked) = &event.invokes {
            self.key(&invoked.resource)?;
            self.key(&invoked.action)?;
        }
        Ok(())
    }

    fn value(&self, value: &Value, depth: usize) -> Result<(), Refused> {
        if depth > self.limits.depth as usize {
            return Err(Refused::invalid(concat!(
                "over the limit of ",
                "value depth"
            )));
        }
        match value {
            Value::Unit | Value::Int(_) | Value::Bool(_) => Ok(()),
            Value::Float(number) if number.is_finite() => Ok(()),
            Value::Float(_) => Err(Refused::invalid("a number that is not finite")),
            Value::Text(text) | Value::Error(text) => self.string(text),
            Value::Enum(case) => self.key(case),
            Value::Case { case, fields } => {
                self.key(case)?;
                for (name, held) in fields {
                    self.key(name)?;
                    self.value(held, depth.saturating_add(1))?;
                }
                Ok(())
            }
            Value::List(items) => {
                if items.len() > self.limits.rows as usize {
                    return Err(Refused::invalid(concat!(
                        "over the limit of ",
                        "items of a list value"
                    )));
                }
                items
                    .iter()
                    .try_for_each(|item| self.value(item, depth.saturating_add(1)))
            }
            Value::Opt(held) => held
                .as_deref()
                .map_or(Ok(()), |held| self.value(held, depth.saturating_add(1))),
            Value::Ref(resource) => {
                self.key(&resource.id)?;
                self.key(&resource.ty)
            }
            Value::Actor(who) => {
                self.key(who.id.id())?;
                self.string(&who.name)
            }
            Value::Map(entries) => {
                if entries.len() > self.limits.rows as usize {
                    return Err(Refused::invalid(concat!(
                        "over the limit of ",
                        "entries of a map value"
                    )));
                }
                entries.iter().try_for_each(|(key, value)| {
                    self.value(key, depth.saturating_add(1))?;
                    self.value(value, depth.saturating_add(1))
                })
            }
            Value::Action(offered) => {
                self.string(&offered.label)?;
                self.key(&offered.event)?;
                offered.icon.as_ref().map_or(Ok(()), |icon| self.key(icon))
            }
            Value::Picture(picture) => self.string(&picture.src),
            Value::File(file) => {
                self.string(&file.name)?;
                self.key(&file.media)?;
                self.string(&file.url)
            }
            Value::Link { reference, title } => {
                self.string(reference)?;
                self.string(title)
            }
            Value::Rich(rich) => {
                if rich.blocks.len() > self.limits.rows as usize
                    || rich.embeds.len() > self.limits.rows as usize
                {
                    return Err(Refused::invalid(concat!(
                        "over the limit of ",
                        "paragraphs of rich text"
                    )));
                }
                rich.strings().try_for_each(|text| self.string(text))
            }
        }
    }

    fn words(&self, words: &Words) -> Result<(), Refused> {
        match words {
            Words::Plain(text) => self.string(text),
            Words::Phrase { id, args } => {
                self.key(id)?;
                if args.len() > self.limits.props as usize {
                    return Err(Refused::invalid(concat!(
                        "over the limit of ",
                        "arguments of a phrase"
                    )));
                }
                args.iter().try_for_each(|(name, value)| {
                    self.key(name)?;
                    self.string(value)
                })
            }
        }
    }

    fn path(&self, path: &[String]) -> Result<(), Refused> {
        if path.len() > self.limits.path as usize {
            return Err(Refused::invalid(concat!(
                "over the limit of ",
                "path length"
            )));
        }
        path.iter().try_for_each(|key| self.key(key))
    }

    fn key(&self, key: &str) -> Result<(), Refused> {
        if key.len() > self.limits.key_bytes as usize {
            return Err(Refused::invalid(concat!(
                "over the limit of ",
                "key length"
            )));
        }
        Ok(())
    }

    fn resource(&self, resource: &ResourceRef) -> Result<(), Refused> {
        self.key(&resource.id)?;
        self.key(&resource.ty)
    }

    fn string(&self, text: &str) -> Result<(), Refused> {
        if text.len() > self.limits.string_bytes as usize {
            return Err(Refused::invalid(concat!(
                "over the limit of ",
                "string length"
            )));
        }
        Ok(())
    }

    /// Check one batch the host sent an app: in an app host, what the window says it did is
    /// as hostile as what an app sends its window.
    ///
    /// # Errors
    /// The first thing in it that is not valid.
    pub fn to_app(&self, batch: &[ToApp]) -> Result<(), Refused> {
        if batch.len() > self.limits.messages as usize {
            return Err(Refused::invalid(concat!(
                "over the limit of ",
                "messages in a batch"
            )));
        }
        for message in batch {
            self.to_app_message(message)?;
        }
        Ok(())
    }

    /// Check one message the host sent an app: the keys it names, then the value it carries.
    fn to_app_message(&self, message: &ToApp) -> Result<(), Refused> {
        self.to_app_targets(message)?;
        self.to_app_payload(message)
    }

    /// The keys and resources `message` names.
    fn to_app_targets(&self, message: &ToApp) -> Result<(), Refused> {
        match message {
            ToApp::Fire { key, event, .. } => {
                self.key(key)?;
                self.key(event)?;
            }
            ToApp::Toggle { target, key, .. }
            | ToApp::Splice { target, key, .. }
            | ToApp::Edit { target, key, .. }
            | ToApp::EditRich { target, key, .. } => {
                self.resource(target)?;
                self.key(key)?;
            }
            ToApp::Resolve { key, .. } => self.key(key)?,
            ToApp::Rows {
                list, open, menu, ..
            } => {
                for key in std::iter::once(list).chain(open).chain(menu) {
                    self.key(key)?;
                }
            }
            ToApp::Focus { at } => {
                if let Some((_, key)) = at {
                    self.key(key)?;
                }
            }
            ToApp::FormEdit { field, .. } => self.key(field)?,
            ToApp::Open { .. }
            | ToApp::OpenReference { .. }
            | ToApp::Space { .. }
            | ToApp::Invoke { .. }
            | ToApp::Serving { .. }
            | ToApp::PageAnswer { .. }
            | ToApp::PagePrompt { .. }
            | ToApp::Back
            | ToApp::Answer(_)
            | ToApp::Undo
            | ToApp::Redo
            | ToApp::Composing(_)
            | ToApp::Held(_)
            | ToApp::SaveAgain
            | ToApp::History { .. }
            | ToApp::FormSubmit { .. }
            | ToApp::FormCancel { .. } => {}
        }
        Ok(())
    }

    /// The value `message` carries, and how large it comes to.
    fn to_app_payload(&self, message: &ToApp) -> Result<(), Refused> {
        match message {
            ToApp::Fire {
                value: Some(value), ..
            } => self.value(value, 0),
            ToApp::Splice { insert, .. } => self.string(insert),
            ToApp::Edit { text, .. } | ToApp::FormEdit { text, .. } => self.string(text),
            ToApp::EditRich { rich, .. } => self.value(&Value::Rich(rich.clone()), 0),
            ToApp::Open { resource } => self.resource(resource),
            ToApp::OpenReference { reference } => self.string(reference),
            ToApp::Rows { start, end, .. } => {
                if end < start || end.saturating_sub(*start) > self.limits.rows {
                    return Err(Refused::invalid(concat!(
                        "over the limit of ",
                        "rows in a message"
                    )));
                }
                Ok(())
            }
            ToApp::Space {
                width, height, rem, ..
            } => {
                if !(width.is_finite()
                    && height.is_finite()
                    && *width >= 0.0
                    && *height >= 0.0
                    && rem.is_finite()
                    && *rem > 0.0)
                {
                    return Err(Refused::invalid("a space is no size"));
                }
                Ok(())
            }
            ToApp::Invoke { address, argument } => self.invoke(address, argument.as_deref()),
            ToApp::Serving { call, invoker } => self.serving(call, invoker.as_deref()),
            ToApp::PageAnswer { answer, .. } => {
                if answer.len() > super::MAX_PAGE_BYTES {
                    return Err(Refused::invalid("over the limit of bytes in a page answer"));
                }
                Ok(())
            }
            ToApp::PagePrompt { prompt } => {
                if prompt.len() > self.limits.string_bytes as usize {
                    return Err(Refused::invalid(
                        "over the limit of bytes in a page's prompt",
                    ));
                }
                Ok(())
            }
            _ => Ok(()),
        }
    }

    /// Check an action the host asks an app to run.
    fn invoke(&self, address: &ActionAddress, argument: Option<&str>) -> Result<(), Refused> {
        self.key(&address.resource)?;
        self.key(&address.action)?;
        argument.map_or(Ok(()), |argument| self.string(argument))
    }

    /// Check a signed call the host serves for its invoker.
    fn serving(&self, call: &[u8], invoker: Option<&str>) -> Result<(), Refused> {
        if call.len() > self.limits.string_bytes as usize {
            return Err(Refused::invalid(
                "a signed call is over the limit of a string",
            ));
        }
        invoker.map_or(Ok(()), |invoker| self.string(invoker))
    }
}

/// The event an action offered in the prop `prop` fires: `actions.2` for the third of
/// `actions`. Its node gives it what the action runs, as it gives its declared events.
#[must_use]
pub fn offered_event(prop: &str, index: usize) -> String {
    format!("{prop}.{index}")
}

/// Whether `event` is one an action offered in a prop of the component fires
/// ([`offered_event`]): the host binds such an event to the action it runs.
#[must_use]
pub fn offers(description: &Description, event: &str) -> bool {
    fn holds_actions(ty: &Type) -> bool {
        match ty {
            Type::Action => true,
            Type::Option(inner) | Type::List(inner) | Type::Set(inner) => holds_actions(inner),
            Type::Map { value, .. } => holds_actions(value),
            _ => false,
        }
    }
    event
        .rsplit_once('.')
        .filter(|(_, index)| !index.is_empty() && index.bytes().all(|b| b.is_ascii_digit()))
        .and_then(|(prop, _)| description.prop(prop))
        .is_some_and(|prop| holds_actions(&prop.ty))
}

/// Whether `name` is a sizing or placement argument every node takes, with its unit
/// (`min.rem`).
fn node_arg(name: &str) -> bool {
    let base = name
        .strip_suffix(".rem")
        .or_else(|| name.strip_suffix(".dp"))
        .unwrap_or(name);
    NODE_ARGS.contains(&base)
}

/// Whether `value` is one of the type `ty`, as the host reads it into a widget: text shows any
/// value as text, a whole number is a number, an `Option` holds nothing or a value.
#[must_use]
pub fn fits(value: &Value, ty: &Type) -> bool {
    match (ty, value) {
        (Type::Option(_), Value::Opt(None) | Value::Unit)
        | (Type::Int, Value::Int(_))
        | (Type::Float, Value::Float(_) | Value::Int(_))
        | (Type::Bool, Value::Bool(_) | Value::Int(_))
        | (Type::Actor, Value::Actor(_))
        | (Type::Resource, Value::Ref(_))
        | (Type::Icon | Type::Time, Value::Text(_))
        | (Type::Picture, Value::Picture(_))
        | (Type::File, Value::File(_))
        | (Type::Link, Value::Link { .. })
        | (Type::RichText, Value::Rich(_))
        | (Type::Action, Value::Action(_))
        // The case's fields are read against the catalogue's set where the node is built.
        | (Type::Cases { .. }, Value::Case { .. }) => true,
        (Type::Option(inner), Value::Opt(Some(held))) => fits(held, inner),
        (Type::Option(inner), other) => fits(other, inner),
        (_, Value::Opt(Some(held))) => fits(held, ty),
        (
            Type::Text,
            Value::List(_)
            | Value::Ref(_)
            | Value::Rich(_)
            | Value::Map(_)
            | Value::Action(_)
            | Value::Picture(_)
            | Value::File(_)
            | Value::Link { .. },
        ) => false,
        (Type::Text, _) => true,
        (Type::Choice { cases, .. }, Value::Text(case) | Value::Enum(case)) => cases.contains(case),
        (Type::List(inner) | Type::Set(inner), Value::List(items)) => {
            items.iter().all(|item| fits(item, inner))
        }
        (Type::Map { key, value }, Value::Map(entries)) => {
            entries.iter().all(|(k, v)| fits(k, key) && fits(v, value))
        }
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::super::Level;
    use super::*;

    fn validator() -> Validator<'static> {
        Validator::new(
            tilo_ui_graph::component::catalogue(),
            PatchLimits::default(),
        )
    }

    fn component(name: &str, key: &str, props: &[(&str, Value)]) -> Node {
        let mut node = Node::empty(&format!("{COMPONENT_PREFIX}{name}"), key);
        for (prop, value) in props {
            node.props.insert((*prop).to_owned(), value.clone());
        }
        node
    }

    fn open(tree: Node) -> Vec<ToUi> {
        vec![ToUi::Open {
            level: Level::Root,
            target: ResourceRef {
                id: "doc".to_owned(),
                ty: "notes.Notebook".to_owned(),
            },
            tree,
            front: None,

            capture_protected: false,
        }]
    }

    /// A text an edit keeps is one the window can carry: the bytes of one string here are the
    /// bytes of one text an action carries, so a paste at the limit is shown and a longer one is
    /// refused where it is made.
    #[test]
    fn a_text_an_edit_keeps_is_one_a_window_carries() {
        assert_eq!(
            PatchLimits::default().string_bytes as usize,
            tilo_actions::MAX_TEXT_BYTES
        );
    }

    #[test]
    fn a_tree_of_described_components_and_primitives_passes() {
        let mut stack = Node::empty("stack", "s");
        stack.props.insert("gap".to_owned(), Value::text("section"));
        stack.props.insert("min.rem".to_owned(), Value::Float(12.0));
        let mut button = component("Button", "b", &[("label", Value::text("Send"))]);
        button.events.insert("press".to_owned(), Event::default());
        stack.children = vec![
            component(
                "Text",
                "t",
                &[
                    ("value", Value::text("2026-10-24")),
                    ("value:as", Value::text("date")),
                    ("role", Value::text("title")),
                ],
            ),
            button,
        ];
        assert_eq!(validator().to_ui(&open(stack)), Ok(()));
    }

    /// A row's quiet fact is a day the person reads (`Today`, `Overdue`), and the time of day it
    /// is due at reads with it (`Today 9:00 AM`): the day is the prop the row declares, and the
    /// time its companion.
    #[test]
    fn a_day_reads_with_the_time_of_day_it_is_due_at() {
        let row = component(
            "ListRow",
            "t",
            &[
                ("title", Value::text("Call the landlord")),
                ("meta", Value::text("2026-11-03")),
                ("meta:as", Value::text("date")),
                ("meta:time", Value::text("2026-11-03T17:00:00Z")),
            ],
        );
        assert_eq!(validator().to_ui(&open(row)), Ok(()));
        let mistyped = component(
            "ListRow",
            "t",
            &[("title", Value::text("x")), ("meta:tmie", Value::text("x"))],
        );
        assert!(
            validator().to_ui(&open(mistyped)).is_err(),
            "a companion is a name the component declares a prop for, spelled as the host reads it"
        );
    }

    #[test]
    fn what_a_component_does_not_declare_is_refused() {
        let unknown = component("Nothing", "x", &[]);
        assert!(validator().to_ui(&open(unknown)).is_err());
        let prop = component("Text", "t", &[("color", Value::text("red"))]);
        assert!(validator().to_ui(&open(prop)).is_err());
        let typed = component("Text", "t", &[("role", Value::text("shouting"))]);
        assert!(
            validator().to_ui(&open(typed)).is_err(),
            "a case not declared"
        );
        let mut event = component("Text", "t", &[("value", Value::text("x"))]);
        event.events.insert("press".to_owned(), Event::default());
        assert!(validator().to_ui(&open(event)).is_err());
        assert!(
            validator()
                .to_ui(&open(Node::empty("script", "s")))
                .is_err()
        );
    }

    /// A slider over a value the view does not hold (a device's volume) is given that value,
    /// and says through `change` what the person did with it.
    #[test]
    fn a_value_given_to_a_control_with_a_change_event_passes() {
        let mut slider = component("Slider", "s", &[("value", Value::Float(0.4))]);
        slider.events.insert("change".to_owned(), Event::default());
        assert_eq!(validator().to_ui(&open(slider)), Ok(()));
        let wrong = component("Slider", "s", &[("value", Value::text("loud"))]);
        assert!(validator().to_ui(&open(wrong)).is_err());
    }

    #[test]
    fn work_is_bounded() {
        let limits = PatchLimits {
            depth: 3,
            key_bytes: 16,
            ..PatchLimits::default()
        };
        let checked = Validator::new(tilo_ui_graph::component::catalogue(), limits);
        let mut deep = Node::empty("stack", "0");
        for level in 1..6 {
            deep = Node {
                children: vec![deep],
                ..Node::empty("stack", &level.to_string())
            };
        }
        assert_eq!(
            checked.to_ui(&open(deep)).map_err(|refused| refused.what),
            Err("over the limit of tree depth")
        );
        assert_eq!(
            checked
                .to_ui(&open(Node::empty(
                    "stack",
                    "a key far longer than sixteen bytes"
                )))
                .map_err(|refused| refused.what),
            Err("over the limit of key length")
        );
        assert!(
            validator()
                .to_ui(&open(component(
                    "Text",
                    "t",
                    &[("value", Value::Float(f64::NAN))]
                )))
                .is_err()
        );
    }
}