denise-forms 0.28.0

Loads a DeniseUI form file into a widget tree at runtime: the engine behind .dform.
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
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
//! Turning a parsed form into a live widget tree.

use std::collections::HashMap;

use denise::{Rect, Size};
use denise_ui::widgets::describe::{
    ALIGNMENTS, FITS, ORIENTATIONS, PRESENCES, Payload, Property, PropertyKind, RADII, ROLES,
    Value, WidgetInfo, role_from_name,
};
use denise_ui::widgets::{
    Alert, Avatar, Badge, Button, Carousel, Checkbox, Collapse, Column, Divider, Fit, Image, Label,
    List, ListItem, MenuBar, Panel, Progress, RadialProgress, RadioGroup, Rating, Select, Slider,
    Spinner, Table, Tabs, TextArea, TextInput, Timeline, TimelineItem, Toggle, Tree, TreeItem,
    Video,
};
use denise_ui::{Anchors, Dock, NodeId, Ui};
use kdl::{KdlDocument, KdlNode, KdlValue};

use crate::error::{At, Error, Reason};
use crate::form::{Form, FormKind, MAX_DEPTH, Placement};

/// Pixels for a picture a form named, as [`Wiring::asset`] hands them back.
#[derive(Clone, Debug)]
pub struct Picture {
    /// Premultiplied `0xAARRGGBB`, which is `denise-ui`'s contract exactly.
    pub pixels: Vec<u32>,
    /// The picture's own size.
    pub size: Size,
}

/// A message a form named, in the shape the widget holding it needs.
///
/// Widgets do not all take a message the same way, and none of them takes a
/// closure: a `Button` holds an `M`, a `Checkbox` a `fn(bool) -> M`, a `List` a
/// `fn(usize) -> M`, a `Slider` a `fn(f32) -> M`. Those are **function
/// pointers**, so nothing this crate could build from a name would fit — but an
/// enum's tuple variant already is one:
///
/// ```
/// # use denise_forms::Handler;
/// #[derive(Clone, Copy)]
/// enum Message {
///     Save,
///     Notify(bool),
/// }
///
/// let save = Handler::Plain(Message::Save);
/// // `Message::Notify` *is* a `fn(bool) -> Message`.
/// let notify = Handler::Bool(Message::Notify);
/// # let _ = (save, notify);
/// ```
#[derive(Clone, Copy, Debug)]
pub enum Handler<M> {
    /// The message itself, for a widget that holds one: a button, a select, a
    /// text field's submit.
    Plain(M),
    /// `fn(bool) -> M` — a checkbox, a toggle, a collapse.
    Bool(fn(bool) -> M),
    /// `fn(usize) -> M` — anything that selects one of several.
    Index(fn(usize) -> M),
    /// `fn(f32) -> M` — a slider, a rating.
    Number(fn(f32) -> M),
}

impl<M> Handler<M> {
    fn wanted(payload: Payload) -> &'static str {
        match payload {
            Payload::None => "the message itself",
            Payload::Bool => "a `fn(bool) -> M`",
            Payload::Index => "a `fn(usize) -> M`",
            Payload::Number => "a `fn(f32) -> M`",
        }
    }
}

/// What an application supplies a form that this crate cannot: its own message
/// type, and its own pictures.
///
/// A plain closure implements this, which is all most forms need. Implement it on
/// a type when the form also names pictures.
pub trait Wiring<M> {
    /// Turns a message name from the file into a message of the application's
    /// own type. `payload` says which shape the widget needs.
    fn message(&mut self, name: &str, payload: Payload) -> Option<Handler<M>>;

    /// Loads a picture, by a path **relative to the form file**.
    ///
    /// The default has none, so a form naming a picture in an application that
    /// supplied no loader fails with the path in the message rather than drawing
    /// a hole. This crate decodes nothing and does not depend on `denise-image`:
    /// that keeps a board with its pictures compiled in from linking a decoder it
    /// will never call.
    fn asset(&mut self, path: &str) -> Option<Picture> {
        let _ = path;
        None
    }
}

impl<M, F> Wiring<M> for F
where
    F: FnMut(&str, Payload) -> Option<Handler<M>>,
{
    fn message(&mut self, name: &str, payload: Payload) -> Option<Handler<M>> {
        self(name, payload)
    }
}

/// One node the form put in the tree, and where in the file it came from.
///
/// A designer needs both halves: the [`NodeId`] to hit-test and draw a selection
/// around, and the [`path`](Placed::path) to edit when the selection moves. The
/// path is a list of child indices from the `form` node down, which is stable
/// across a rebuild in a way a byte offset is not — every edit shifts the offsets
/// after it, and the whole point is to edit and carry on.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Placed {
    /// The node in the tree.
    pub id: NodeId,
    /// Its parent in the tree, or `None` for a node directly under the form.
    pub parent: Option<NodeId>,
    /// What kind of widget it is.
    pub kind: &'static str,
    /// The name the file gave it, if it gave one.
    pub name: Option<String>,
    /// Child indices from the `form` node's children down to this node.
    pub path: Vec<usize>,
}

/// What a form built, so an application can find what it made.
#[derive(Clone, Debug, Default)]
pub struct Built {
    names: HashMap<String, NodeId>,
    placed: Vec<Placed>,
    pages: Vec<Page>,
}

/// One `tab`'s page: the container its subtree was built into.
///
/// Only a `tab` carrying children has one. A designer needs these because a
/// page that is not showing is not in the tree's order at all — nothing in it
/// paints, answers a press or takes the caret — so reaching the second tab's
/// contents means showing that page first.
#[derive(Clone, Debug)]
pub struct Page {
    /// The `tab` node's path in the document.
    pub path: Vec<usize>,
    /// Which tab it is, counting every `tab` in the strip. What `selected`
    /// names.
    pub ordinal: usize,
    /// The container the page's widgets were built into.
    pub id: NodeId,
}

impl Built {
    /// See [`Form::build`] for one of these being made and read.
    /// The node a form gave this name, if it gave one that name.
    pub fn node(&self, name: &str) -> Option<NodeId> {
        self.names.get(name).copied()
    }

    /// See [`Form::build`] for one of these being made and read.
    /// Every name the form gave a node, in no particular order.
    pub fn names(&self) -> impl Iterator<Item = (&str, NodeId)> {
        self.names.iter().map(|(name, &id)| (name.as_str(), id))
    }

    /// Every `tab` page the form built, in file order.
    ///
    /// Empty for a form whose tabs are bare labels, which is every form written
    /// before a `tab` could hold anything. See [`Page`].
    pub fn pages(&self) -> &[Page] {
        &self.pages
    }

    /// Every node the form built, in file order.
    ///
    /// See [`Form::build`] for one of these being made and read.
    /// Includes the ones with no name: a designer selects what a person clicked
    /// on, and most of what a person clicks on was never named.
    pub fn placed(&self) -> &[Placed] {
        &self.placed
    }

    /// See [`Form::build`] for one of these being made and read.
    /// The node at a path, if the form put one there.
    pub fn at(&self, path: &[usize]) -> Option<&Placed> {
        self.placed.iter().find(|p| p.path == path)
    }

    /// See [`Form::build`] for one of these being made and read.
    /// How many nodes were named.
    pub fn len(&self) -> usize {
        self.names.len()
    }

    /// See [`Form::build`] for one of these being made and read.
    /// Whether the form named nothing.
    pub fn is_empty(&self) -> bool {
        self.names.is_empty()
    }
}

const ANCHOR_EDGES: &[&str] = &["left", "top", "right", "bottom"];
const DOCK_SIDES: &[&str] = &["top", "bottom", "left", "right", "fill"];

/// Anywhere on a form's surface, and then some.
///
/// A rectangle is advice to an editor, not a rule: a node may sit outside its
/// parent and the tree will clip it, which is occasionally what somebody means.
const ANYWHERE: PropertyKind = PropertyKind::Int {
    min: -8192,
    max: 8192,
};

/// The properties the `form` node itself carries, whatever kind it is.
///
/// Not `version`, which is the file format's rather than the form's and is not
/// somebody's to edit; and not the title, which is the node's *argument* rather
/// than a property. Everything else about a form is here, which is what lets an
/// inspector show a form the same way it shows a widget — from a descriptor,
/// with no list of its own.
pub const FORM_PROPERTIES: &[Property] = &[
    Property::new(
        "name",
        PropertyKind::Text,
        "What the application calls this form. Names what the typed layer generates.",
    ),
    Property::new(
        "kind",
        PropertyKind::Enum(FormKind::NAMES),
        "What this form is for: a screen, a window, a dialog, a drawer, a shelf, or a fragment.",
    ),
    Property::new(
        "width",
        PropertyKind::Int { min: 1, max: 8192 },
        "The width the form was designed at, in logical pixels.",
    ),
    Property::new(
        "height",
        PropertyKind::Int { min: 1, max: 8192 },
        "The height the form was designed at, in logical pixels.",
    ),
    Property::new(
        "theme",
        PropertyKind::Enum(crate::form::THEMES),
        "Which built-in theme the form is drawn with.",
    ),
    Property::new(
        "background",
        PropertyKind::Enum(denise_ui::widgets::ROLES),
        "The surface the form is drawn on.",
    ),
    Property::new(
        "scaling",
        PropertyKind::Enum(crate::form::Scaling::NAMES),
        "Whether this form may be drawn at another size: none, proportional or stretch.",
    ),
];

/// What only a window has.
const WINDOW_PROPERTIES: &[Property] = &[
    Property::new(
        "resizable",
        PropertyKind::Bool,
        "Whether the window may be resized. Windows only.",
    ),
    Property::new(
        "min-width",
        PropertyKind::Int { min: 0, max: 8192 },
        "The narrowest the window may be made. Windows only.",
    ),
    Property::new(
        "min-height",
        PropertyKind::Int { min: 0, max: 8192 },
        "The shortest the window may be made. Windows only.",
    ),
];

/// What only a dialog has.
const DIALOG_PROPERTIES: &[Property] = &[Property::new(
    "dim",
    PropertyKind::Int { min: 0, max: 255 },
    "How dark the backdrop behind the dialog is, 0 to 255. Dialogs only.",
)];

/// What comes in from an edge: a drawer and a shelf, which differ in modality
/// and not in shape.
const EDGE_PROPERTIES: &[Property] = &[
    Property::new(
        "side",
        PropertyKind::Enum(denise_ui::widgets::SIDES),
        "Which edge it comes in from.",
    ),
    Property::new(
        "extent",
        PropertyKind::Int { min: 1, max: 8192 },
        "How far it comes in. Required; across the other axis it covers the surface.",
    ),
];

/// The properties a form of this kind carries **and no other kind does**.
///
/// A `resizable` on a screen is not a property with no effect; it is a mistake,
/// and saying so is the whole reason this is a function of the kind rather than
/// one long list.
/// ```
/// # use denise_forms::{FORM_PROPERTIES, FormKind, form_property, kind_properties};
/// // Everything every form has.
/// assert!(FORM_PROPERTIES.iter().any(|it| it.name == "width"));
///
/// // And what only this kind has.
/// assert!(kind_properties(FormKind::Window).iter().any(|it| it.name == "resizable"));
/// assert!(kind_properties(FormKind::Screen).is_empty());
///
/// // `form_property` is the two together, which is what "may a form of this
/// // kind say this?" means.
/// assert!(form_property(FormKind::Window, "resizable").is_some());
/// assert!(form_property(FormKind::Screen, "resizable").is_none());
/// assert!(form_property(FormKind::Screen, "width").is_some());
/// ```
pub const fn kind_properties(kind: FormKind) -> &'static [Property] {
    match kind {
        FormKind::Window => WINDOW_PROPERTIES,
        FormKind::Dialog => DIALOG_PROPERTIES,
        FormKind::Drawer | FormKind::Shelf => EDGE_PROPERTIES,
        FormKind::Screen | FormKind::Fragment => &[],
    }
}

/// Whether the `form` node may carry this property, given its kind.
/// See [`kind_properties`].
pub fn form_property(kind: FormKind, name: &str) -> Option<&'static Property> {
    FORM_PROPERTIES
        .iter()
        .chain(kind_properties(kind))
        .find(|property| property.name == name)
}

/// The properties the *tree* owns rather than the widget.
///
/// Geometry, visibility, ordering, placement. A widget's descriptor never
/// mentions them, so they are checked against this list before a widget is asked
/// whether it has heard of them.
///
/// Described the same way a widget describes its own, and for the same reason:
/// the designer's inspector draws an editor per [`Property`] and has no table of
/// its own, so `x` and `dock` get one from here exactly as `role` gets one from
/// the widget.
pub const NODE_PROPERTIES: &[Property] = &[
    Property::new(
        "name",
        PropertyKind::Text,
        "What the application calls this node. Unique within the form.",
    ),
    Property::new("x", ANYWHERE, "Left edge, relative to the parent."),
    Property::new("y", ANYWHERE, "Top edge, relative to the parent."),
    Property::new(
        "w",
        PropertyKind::Int { min: 0, max: 8192 },
        "Width in pixels.",
    ),
    Property::new(
        "h",
        PropertyKind::Int { min: 0, max: 8192 },
        "Height in pixels.",
    ),
    Property::new(
        "visible",
        PropertyKind::Bool,
        "Drawn and able to be touched, or neither.",
    ),
    Property::new(
        "enabled",
        PropertyKind::Bool,
        "Takes input, or is greyed out and does not.",
    ),
    Property::new(
        "z",
        PropertyKind::Int {
            min: -1000,
            max: 1000,
        },
        "Paint order among siblings; higher is nearer the front.",
    ),
    Property::new(
        "tooltip",
        PropertyKind::Text,
        "What resting the pointer on this node says.",
    ),
    Property::new(
        "scroll",
        PropertyKind::Bool,
        "Whether children reaching past this node can be scrolled to.",
    ),
    Property::new(
        "stack",
        PropertyKind::Int { min: 0, max: 1000 },
        "Stacks the children down the node with this many pixels between them.",
    ),
    Property::new(
        "focus",
        PropertyKind::Bool,
        "Whether this node holds the caret when the form opens. One per form.",
    ),
    Property::new(
        "anchor",
        PropertyKind::Text,
        "Edges held as the parent resizes: any of left, top, right, bottom.",
    ),
    Property::new(
        "dock",
        PropertyKind::Enum(DOCK_SIDES),
        "An edge of the parent this node takes for itself, before the rest are placed.",
    ),
];

/// The tree-owned property of this name, if there is one.
/// ```
/// # use denise_forms::node_property;
/// // The tree owns geometry and visibility; no widget declares them.
/// assert!(node_property("x").is_some());
/// assert!(node_property("dock").is_some());
/// // A widget's own property is not one of these.
/// assert!(node_property("role").is_none());
/// ```
pub fn node_property(name: &str) -> Option<&'static Property> {
    NODE_PROPERTIES.iter().find(|p| p.name == name)
}

/// Child nodes that are a parent's *content* rather than nodes of their own.
const COLLECTIONS: &[&str] = &[
    "option", "item", "column", "row", "event", "picture", "tab", "title",
];

/// The block a designer's placeholder content lives in.
///
/// A `table`'s rows and a `timeline`'s events are four names somebody typed so
/// the widget looks like itself on a canvas; the application supplies the real
/// ones. Written here, they are skipped by every build except a designer's, so
/// they never reach a kiosk. See [`PropertyKind::Placeholder`].
pub const DESIGN: &str = "design";

/// Whether `kind` reads a collection called `name` from a `design` block.
///
/// Asked of the widget's own descriptor rather than a table kept here, which is
/// the same rule the rest of the schema follows: a widget publishes what it
/// takes, and nothing enumerates widgets.
pub(crate) fn is_placeholder(kind: &str, name: &str) -> bool {
    denise_ui::widgets::all()
        .iter()
        .find(|info| info.kind == kind)
        .is_some_and(|info| {
            info.properties
                .iter()
                .any(|p| p.name == name && p.kind == PropertyKind::Placeholder)
        })
}

/// Whether a widget of this kind can hold nodes of their own.
///
/// Two do. Everything else either has no children or has *content* — a `select`
/// holds `option`s, a `table` holds `column`s — which is not the same thing: a
/// designer dropping a button on a `select` has missed, and dropping one on a
/// `panel` means it.
/// ```
/// # use denise_forms::owns_children;
/// assert!(owns_children("panel"));
/// assert!(owns_children("collapse"));
/// // Content is not children: a `select` holds options, and dropping a button
/// // on one has missed.
/// assert!(!owns_children("select"));
/// assert!(!owns_children("label"));
/// ```
pub fn owns_children(kind: &str) -> bool {
    matches!(kind, "panel" | "collapse")
}

/// The kinds that carry their text as the node's argument.
///
/// `label "Heading"` rather than `label text="Heading"`. Both build the same
/// thing; the first is how every form in this repository is written, and is what
/// [`seed`] produces.
const ARGUMENT: &[&str] = &[
    "label", "badge", "divider", "alert", "button", "checkbox", "toggle", "collapse",
];

/// How big a new widget of this kind should start out.
///
/// **Authoring defaults, not intrinsic sizes.** This toolkit has no layout engine
/// and nothing here has a size of its own: a button is whatever rectangle the
/// form gives it. These are the rectangles that make a dropped widget look like
/// what it is, so that somebody can see what they placed before they resize it —
/// which is a question about writing forms, and so this crate's, rather than a
/// question about widgets.
/// ```
/// # use denise_forms::default_size;
/// // A button is wider than it is tall; an avatar is square.
/// let button = default_size("button");
/// assert!(button.width > button.height);
/// let avatar = default_size("avatar");
/// assert_eq!(avatar.width, avatar.height);
/// // A kind nobody has heard of still gets something you can see and click.
/// assert!(default_size("banana").width > 0);
/// ```
pub fn default_size(kind: &str) -> Size {
    let (width, height) = match kind {
        "alert" => (320, 36),
        "avatar" => (40, 40),
        "badge" => (60, 20),
        "button" => (100, 32),
        "carousel" => (224, 120),
        "checkbox" | "toggle" => (200, 24),
        "collapse" => (224, 40),
        "divider" => (160, 16),
        "image" => (120, 90),
        "list" => (200, 160),
        "panel" => (200, 120),
        "progress" => (200, 8),
        "radial-progress" => (48, 48),
        "radio-group" => (220, 76),
        "rating" => (140, 24),
        "select" | "text-input" => (220, 34),
        "text-area" => (320, 180),
        "slider" => (200, 24),
        "spinner" => (24, 24),
        "table" => (320, 180),
        "tree" => (220, 180),
        "tabs" => (320, 36),
        "menubar" => (320, 28),
        "timeline" => (220, 140),
        "video" => (160, 90),
        // `label`, and anything this list has not heard of.
        _ => (120, 20),
    };
    Size::new(width, height)
}

/// The smallest node of this kind that a form can actually hold, as file text.
///
/// What a designer writes when somebody drops a widget on the canvas. A rectangle
/// is the most of it — but "a rect and nothing else" is not true of every widget,
/// because three of them have a property the builder *requires*: an `alert` has
/// no colour to draw itself in without a `role`, a `slider` has no range without
/// `min` and `max`, and an `image` has nothing to draw without a `src`. A node
/// missing one of those parses and then will not build, so a designer that wrote
/// one would place a widget and break the form.
///
/// `select` and `collapse` were a fourth and fifth until #118, and they were the
/// awkward ones: what they lacked was not a number but a *message*, so the seed
/// had to invent a name nobody had asked for. Both have an inert constructor
/// now, so a dropped one carries no message at all.
///
/// This lives beside the code that raises those requirements, so the two cannot
/// drift; a test seeds every widget in [`all`](denise_ui::widgets::all), builds
/// the result, and fails if a new one needs something this does not give it.
///
/// ```
/// # use denise_forms::{seed, Form};
/// use denise::Rect;
///
/// assert_eq!(
///     seed("button", Rect::new(16, 24, 100, 32)),
///     r#"button "button" x=16 y=24 w=100 h=32"#,
/// );
/// ```
pub fn seed(kind: &str, rect: Rect) -> String {
    let mut node = String::from(kind);
    if ARGUMENT.contains(&kind) {
        // The kind, as a placeholder. A label dropped with nothing to say draws
        // nothing, and a widget you cannot see is a widget you cannot find
        // again the moment you click somewhere else.
        node.push_str(&format!(" {:?}", kind));
    }
    node.push_str(&format!(
        " x={} y={} w={} h={}",
        rect.x, rect.y, rect.width, rect.height
    ));
    // Only what the engine *requires*, and nothing a person would have to
    // delete. `select` and `collapse` were here until #118 gave them inert
    // constructors: they had to be seeded with a message nobody wanted, named
    // after nothing, because a form file could not build either without one.
    node.push_str(match kind {
        "alert" => " role=info",
        "slider" => " min=0 max=100",
        // A path that is not there yet. An engine that cannot load it says so;
        // a designer draws a hole and carries on.
        "image" => " src=\"picture.png\"",
        _ => "",
    });
    node
}

/// A whole form file with nothing in it yet, writing **only** what is not a
/// default.
///
/// What *File → New* produces. A form that spelled out every default would read
/// as a form somebody had made decisions about, and the next person would have
/// to check each one against the schema to find out that none of them meant
/// anything. The exception is `extent`, which a drawer and a shelf must say:
/// this picks a third of the axis it comes in along, which is a drawer somebody
/// will recognise rather than one they have to fix before they can see it.
/// ```
/// # use denise::Size;
/// # use denise_forms::{Form, FormKind, seed_form};
/// // A screen is every default but its size, so it says nothing else.
/// let screen = seed_form("Untitled", FormKind::Screen, Size::new(800, 480));
/// assert_eq!(screen, "form \"Untitled\" version=1 width=800 height=480\n");
///
/// // What comes in from an edge has to say how far, so this picks one.
/// let drawer = seed_form("Filters", FormKind::Drawer, Size::new(1024, 600));
/// let form = Form::parse(&drawer)?;
/// assert_eq!(form.kind(), FormKind::Drawer);
/// assert_eq!(form.extent(), 1024 / 3);
/// # Ok::<(), denise_forms::Error>(())
/// ```
pub fn seed_form(title: &str, kind: FormKind, size: Size) -> String {
    let mut out = format!("form {title:?} version={}", crate::form::VERSION);
    if kind != FormKind::Screen {
        out.push_str(&format!(" kind={}", FormKind::NAMES[kind as usize]));
    }
    out.push_str(&format!(" width={} height={}", size.width, size.height));
    if matches!(kind, FormKind::Drawer | FormKind::Shelf) {
        let along = match kind.default_side() {
            denise_ui::Side::Above | denise_ui::Side::Below => size.height,
            denise_ui::Side::Before | denise_ui::Side::After => size.width,
        };
        out.push_str(&format!(" extent={}", (along / 3).max(1)));
    }
    out.push('\n');
    out
}

impl Form {
    /// ```
    /// # use denise_forms::{Form, Handler, Payload};
    /// # use denise_ui::Ui;
    /// #[derive(Clone, Copy, PartialEq, Debug)]
    /// enum Message {
    ///     Greet,
    /// }
    ///
    /// let form = Form::parse(
    ///     r#"form "Hello" version=1 width=320 height=120 { button "Greet" name=go x=8 y=8 w=90 h=30 on-press=greet }"#,
    /// )?;
    ///
    /// let mut ui: Ui<Message> = Ui::new(form.size(), form.theme());
    /// let root = ui.root();
    ///
    /// // The one thing a file cannot hold: this application's own message type.
    /// let built = form.build(&mut ui, root, &mut |name: &str, payload: Payload| {
    ///     match (name, payload) {
    ///         ("greet", Payload::None) => Some(Handler::Plain(Message::Greet)),
    ///         _ => None,
    ///     }
    /// })?;
    ///
    /// // What the file named, by the name it used.
    /// let button = built.node("go").expect("the form names it `go`");
    /// assert_eq!(built.len(), 1);
    /// assert!(!built.is_empty());
    ///
    /// // And everything it put on screen, named or not, in file order.
    /// assert_eq!(built.placed().len(), 1);
    /// assert_eq!(built.at(&[0]).map(|node| node.kind), Some("button"));
    /// assert_eq!(built.at(&[0]).map(|node| node.id), Some(button));
    /// assert_eq!(
    ///     built.names().map(|(name, _)| name).collect::<Vec<_>>(),
    ///     vec!["go"],
    /// );
    /// # Ok::<(), denise_forms::Error>(())
    /// ```
    ///
    /// Builds this form into `ui` under `parent`.
    ///
    /// Nodes are added in file order, so paint order is file order. See the
    /// [crate documentation](crate) for what `wiring` supplies and why.
    ///
    /// # Errors
    ///
    /// Every failure carries a line and a column. See [`Reason`](crate::Reason)
    /// for the whole list.
    pub fn build<M: Clone + 'static>(
        &self,
        ui: &mut Ui<M>,
        parent: NodeId,
        wiring: &mut impl Wiring<M>,
    ) -> Result<Built, Error> {
        self.build_fitted(
            ui,
            parent,
            Placement {
                x: 1.0,
                y: 1.0,
                rect: Rect::from_size(self.size()),
            },
            wiring,
        )
    }

    /// Builds this form at `scale`: every rectangle and every length in it
    /// multiplied once, on the way in.
    ///
    /// The DPI answer this toolkit gives, for a form. An application computing
    /// its own rectangles multiplies them itself — three lines, and
    /// `examples/hello` is those three lines. A form file has no application
    /// doing that, so the multiplying goes where the rectangles are computed,
    /// which is here.
    ///
    /// **Two things the caller still has to do**, because neither belongs to a
    /// subtree:
    ///
    /// ```no_run
    /// # use denise::{Size, theme};
    /// # use denise_forms::Form;
    /// # use denise_ui::{Ui, Void};
    /// # let form = Form::parse("").unwrap();
    /// # let scale = 2.0;
    /// // The theme's metrics, or every widget is the old size inside a new
    /// // rectangle — a 2x button with a 6px corner on it.
    /// let mut ui: Ui<Void> = Ui::new(Size::new(1920, 1080), form.theme().scaled(scale));
    /// ```
    ///
    /// ...and putting the form where it goes, which is [`Form::fit`].
    ///
    /// **Text scales like a rectangle here, and that is a choice.** A 1024x600
    /// form on a 1920x1080 panel gets 16 px text at 30 px. That is right when
    /// the panel is the same screen at a higher density and wrong when it is a
    /// bigger screen meant to show more. This does the first one. The second is
    /// not a multiplication and no file can express it.
    ///
    /// # Errors
    ///
    /// The same as [`Form::build`]; scaling adds no failure of its own.
    pub fn build_scaled<M: Clone + 'static>(
        &self,
        ui: &mut Ui<M>,
        parent: NodeId,
        scale: f32,
        wiring: &mut impl Wiring<M>,
    ) -> Result<Built, Error> {
        self.build_fitted(
            ui,
            parent,
            Placement {
                x: scale,
                y: scale,
                rect: Rect::from_size(self.size()).scaled(scale),
            },
            wiring,
        )
    }

    /// Builds the form **and the placeholder content a designer needs to see**.
    ///
    /// Every other build skips `design { … }` blocks, so a `table` comes up with
    /// its columns and no rows and a `timeline` with no events: those are the
    /// application's to supply, and a kiosk should not carry four names somebody
    /// typed to make a canvas look right. A designer is the one caller that
    /// wants them, because a table drawn with no rows is not a table anybody can
    /// lay out against.
    ///
    /// `scale` is [`Form::build_scaled`]'s, so a designer's canvas magnifies the
    /// same way.
    ///
    /// ```
    /// # use denise_forms::{Form, Payload, Handler, Wiring};
    /// # use denise_ui::{Ui, Void};
    /// let source = r#"
    /// form "F" version=1 width=200 height=80 {
    ///     table name=t x=0 y=0 w=200 h=80 {
    ///         column "Name"
    ///         design {
    ///             row "Ada"
    ///         }
    ///     }
    /// }
    /// "#;
    /// let form = Form::parse(source)?;
    /// let mut wiring = |_: &str, _: Payload| None::<Handler<Void>>;
    ///
    /// // What ships: the column, and no rows at all.
    /// let mut ui: Ui<Void> = Ui::new(form.size(), form.theme());
    /// let root = ui.root();
    /// form.build(&mut ui, root, &mut wiring)?;
    ///
    /// // What the designer draws.
    /// let mut canvas: Ui<Void> = Ui::new(form.size(), form.theme());
    /// let root = canvas.root();
    /// form.build_with_design(&mut canvas, root, 1.0, &mut wiring)?;
    /// # Ok::<(), denise_forms::Error>(())
    /// ```
    pub fn build_with_design<M: Clone + 'static>(
        &self,
        ui: &mut Ui<M>,
        parent: NodeId,
        scale: f32,
        wiring: &mut impl Wiring<M>,
    ) -> Result<Built, Error> {
        self.build_inner(
            ui,
            parent,
            Placement {
                x: scale,
                y: scale,
                rect: Rect::from_size(self.size()).scaled(scale),
            },
            wiring,
            true,
        )
    }

    /// Builds this form at a [`Fit`] — a factor per axis, which is what
    /// [`Scaling::Stretch`](crate::Scaling::Stretch) needs and [`Form::fit`] works
    /// out.
    ///
    /// Only [`Placement::x`] and [`Placement::y`] are read. [`Placement::rect`] is where the
    /// *caller* puts the node this builds into, and is none of this method's
    /// business: a form is built under whatever `parent` it is given.
    ///
    /// ```
    /// # use denise::{Rect, Size, theme};
    /// # use denise_forms::Form;
    /// # use denise_ui::{Ui, Void, widgets::Panel};
    /// let form = Form::parse(
    ///     r#"form "F" version=1 width=200 height=100 scaling=proportional {
    ///         label "Hi" name=hi x=10 y=10 w=100 h=20 size=16
    ///     }"#,
    /// )?;
    ///
    /// let surface = Size::new(400, 400);
    /// let fit = form.fit(surface);
    ///
    /// // The theme is scaled once, here, and the form is built into a panel at
    /// // the rectangle the fit worked out.
    /// let mut ui: Ui<Void> = Ui::new(surface, form.theme().scaled(fit.uniform()));
    /// let root = ui.root();
    /// let stage = ui.add(root, Panel::filled(form.background()), fit.rect).unwrap();
    /// let mut nothing = |_: &str, _: denise_forms::Payload| None;
    /// let built = form.build_fitted(&mut ui, stage, fit, &mut nothing)?;
    ///
    /// let hi = built.node("hi").expect("the form names it");
    /// assert_eq!(ui.layout(hi), Some(Rect::new(20, 20, 200, 40)), "twice as big");
    /// assert_eq!(
    ///     ui.get_property(hi, "size"),
    ///     Some(denise_ui::widgets::Value::Int(32)),
    ///     "and so is the text",
    /// );
    /// # Ok::<(), denise_forms::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// The same as [`Form::build`].
    pub fn build_fitted<M: Clone + 'static>(
        &self,
        ui: &mut Ui<M>,
        parent: NodeId,
        fit: Placement,
        wiring: &mut impl Wiring<M>,
    ) -> Result<Built, Error> {
        self.build_inner(ui, parent, fit, wiring, false)
    }

    /// See [`Form::build_fitted`] and [`Form::build_with_design`].
    fn build_inner<M: Clone + 'static>(
        &self,
        ui: &mut Ui<M>,
        parent: NodeId,
        fit: Placement,
        wiring: &mut impl Wiring<M>,
        designing: bool,
    ) -> Result<Built, Error> {
        let mut builder = Builder {
            form: self,
            ui,
            wiring,
            fit,
            designing,
            built: Built::default(),
            focused: None,
        };
        let children: Vec<&KdlNode> = self
            .root()
            .children()
            .map(|d| d.nodes().iter().collect())
            .unwrap_or_default();
        for (index, node) in children.into_iter().enumerate() {
            builder.node(node, parent, 0, &[index])?;
        }
        // The caret goes last, once every node exists: a form may name a field
        // that appears after the one before it in the file.
        let focused = builder.focused;
        let built = builder.built;
        if let Some(id) = focused {
            ui.focus(Some(id));
        }
        Ok(built)
    }
}

struct Builder<'a, M: 'static, W> {
    form: &'a Form,
    ui: &'a mut Ui<M>,
    wiring: &'a mut W,
    /// What every rectangle and every length is multiplied by on the way in.
    /// `1.0` on both axes for [`Form::build`], which is why that is this with
    /// nothing else said.
    fit: Placement,
    /// Whether the `design` blocks are read. False for every build but a
    /// designer's, which is what keeps placeholder rows out of a kiosk.
    designing: bool,
    built: Built,
    focused: Option<NodeId>,
}

impl<M: Clone + 'static, W: Wiring<M>> Builder<'_, M, W> {
    fn err(&self, node: &KdlNode, reason: Reason) -> Error {
        Error::new(self.form.at_node(node), reason)
    }

    /// Builds one node and everything under it.
    fn node(
        &mut self,
        node: &KdlNode,
        parent: NodeId,
        depth: usize,
        path: &[usize],
    ) -> Result<(), Error> {
        if depth >= MAX_DEPTH {
            return Err(self.err(node, Reason::TooDeep { limit: MAX_DEPTH }));
        }
        let kind = node.name().value();
        if COLLECTIONS.contains(&kind) {
            // Reaching here means a collection node is somewhere its parent does
            // not read it — `option` outside a `select`, say — which is a typo
            // that would otherwise vanish silently.
            return Err(self.err(
                node,
                Reason::UnexpectedChild {
                    parent: String::from("form"),
                    found: kind.to_string(),
                },
            ));
        }
        let info = *denise_ui::widgets::all()
            .iter()
            .find(|w| w.kind == kind)
            .ok_or_else(|| {
                self.err(
                    node,
                    Reason::UnknownWidget {
                        found: kind.to_string(),
                    },
                )
            })?;

        self.check_properties(node, &info)?;
        let rect = self.rect(node)?;
        let id = self.construct(node, &info, parent, rect)?;
        self.apply_properties(node, &info, id)?;
        self.apply_node_properties(node, id)?;
        self.built.placed.push(Placed {
            id,
            parent: (depth > 0).then_some(parent),
            kind: info.kind,
            name: self.string(node, "name"),
            path: path.to_vec(),
        });

        // Children that are not the parent's own content are nodes in their own
        // right. A widget that cannot lay children out says so.
        if let Some(children) = node.children() {
            let owns_children = owns_children(kind);
            // Which `tab` this is, counted over **every** tab and not only the
            // ones carrying a page: `selected` is an index into the strip, so a
            // file part-way through gaining pages must still show the right
            // one.
            let mut tabs_seen = 0usize;
            for (index, child) in children.nodes().iter().enumerate() {
                let name = child.name().value();
                if name == DESIGN {
                    self.check_design(child, kind)?;
                    continue;
                }
                // Placeholder content written where the engine would load it,
                // which is the shape this format used to have and the one thing
                // `design` exists to stop.
                if is_placeholder(kind, name) {
                    return Err(self.err(
                        child,
                        Reason::PlaceholderOutside {
                            kind: kind.to_string(),
                            found: name.to_string(),
                        },
                    ));
                }
                // A `tab` carrying children is a **page**: the labels are the
                // strip's content, and what is nested under one is a subtree
                // the file now describes. Everything else in COLLECTIONS is
                // content and has no children to walk.
                if name == "tab" && kind == "tabs" {
                    let ordinal = tabs_seen;
                    tabs_seen += 1;
                    if child.children().is_some_and(|b| !b.nodes().is_empty()) {
                        let mut below = path.to_vec();
                        below.push(index);
                        self.page(child, node, id, depth, &below, ordinal)?;
                    }
                    continue;
                }
                if COLLECTIONS.contains(&name) {
                    continue;
                }
                if !owns_children {
                    return Err(self.err(
                        child,
                        Reason::UnexpectedChild {
                            parent: kind.to_string(),
                            found: name.to_string(),
                        },
                    ));
                }
                let mut below = path.to_vec();
                below.push(index);
                self.node(child, id, depth + 1, &below)?;
            }
        }
        Ok(())
    }

    /// A `design` block holds this widget's placeholder collections and nothing
    /// else.
    ///
    /// Narrow on purpose. `design` is not a general "ignore this" block — a
    /// widget hidden in one would be a widget the file describes and the engine
    /// never builds, which is a bigger idea than #160 asked for and a worse one
    /// to discover by accident.
    fn check_design(&self, block: &KdlNode, kind: &str) -> Result<(), Error> {
        let Some(children) = block.children() else {
            return Ok(());
        };
        for child in children.nodes() {
            let name = child.name().value();
            if !is_placeholder(kind, name) {
                return Err(self.err(
                    child,
                    Reason::UnexpectedChild {
                        parent: format!("{kind}'s `design`"),
                        found: name.to_string(),
                    },
                ));
            }
        }
        Ok(())
    }

    /// Every property in the file is one the tree owns or one the widget declares.
    fn check_properties(&self, node: &KdlNode, info: &WidgetInfo) -> Result<(), Error> {
        for entry in node.entries() {
            let Some(name) = entry.name() else {
                continue;
            };
            let name = name.value();
            if node_property(name).is_some() || info.property(name).is_some() {
                continue;
            }
            return Err(Error::new(
                self.form.at(entry.span().offset()),
                Reason::UnknownProperty {
                    kind: info.kind,
                    found: name.to_string(),
                    accepted: info.properties,
                },
            ));
        }
        Ok(())
    }

    fn rect(&self, node: &KdlNode) -> Result<Rect, Error> {
        let mut axes = [0i32; 4];
        for (slot, name) in axes.iter_mut().zip(["x", "y", "w", "h"]) {
            let value = node
                .get(name)
                .and_then(KdlValue::as_integer)
                .ok_or_else(|| {
                    self.err(
                        node,
                        Reason::Missing {
                            kind: node.name().value().to_string(),
                            name: match name {
                                "x" => "x",
                                "y" => "y",
                                "w" => "w",
                                _ => "h",
                            },
                        },
                    )
                })?;
            *slot = i32::try_from(value).unwrap_or(i32::MAX);
        }
        // By its edges rather than its width and height: two panels designed to
        // touch still touch at a fractional scale. See [`Rect::scaled_by`].
        Ok(Rect::new(axes[0], axes[1], axes[2], axes[3]).scaled_by(self.fit.x, self.fit.y))
    }

    /// The node's single positional argument, as a string.
    fn arg(&self, node: &KdlNode) -> Option<String> {
        node.entries()
            .iter()
            .find(|e| e.name().is_none())
            .and_then(|e| e.value().as_string())
            .map(str::to_string)
    }

    fn string(&self, node: &KdlNode, name: &str) -> Option<String> {
        node.get(name)
            .and_then(KdlValue::as_string)
            .map(str::to_string)
    }

    fn number(&self, node: &KdlNode, name: &str) -> Option<f32> {
        node.get(name).and_then(|v| {
            v.as_float()
                .map(|f| f as f32)
                .or_else(|| v.as_integer().map(|i| i as f32))
        })
    }

    /// A message the file named, in the shape this widget needs.
    fn handler(
        &mut self,
        node: &KdlNode,
        property: &str,
        payload: Payload,
    ) -> Result<Option<Handler<M>>, Error> {
        let Some(name) = self.string(node, property) else {
            return Ok(None);
        };
        match self.wiring.message(&name, payload) {
            Some(handler) => Ok(Some(handler)),
            None => Err(self.err(node, Reason::UnknownMessage { found: name })),
        }
    }

    fn plain(&self, node: &KdlNode, name: &str, handler: Handler<M>) -> Result<M, Error> {
        match handler {
            Handler::Plain(message) => Ok(message),
            _ => Err(self.wrong(node, name, Payload::None)),
        }
    }

    fn on_bool(
        &self,
        node: &KdlNode,
        name: &str,
        handler: Handler<M>,
    ) -> Result<fn(bool) -> M, Error> {
        match handler {
            Handler::Bool(f) => Ok(f),
            _ => Err(self.wrong(node, name, Payload::Bool)),
        }
    }

    fn on_index(
        &self,
        node: &KdlNode,
        name: &str,
        handler: Handler<M>,
    ) -> Result<fn(usize) -> M, Error> {
        match handler {
            Handler::Index(f) => Ok(f),
            _ => Err(self.wrong(node, name, Payload::Index)),
        }
    }

    fn on_number(
        &self,
        node: &KdlNode,
        name: &str,
        handler: Handler<M>,
    ) -> Result<fn(f32) -> M, Error> {
        match handler {
            Handler::Number(f) => Ok(f),
            _ => Err(self.wrong(node, name, Payload::Number)),
        }
    }

    fn wrong(&self, node: &KdlNode, property: &str, payload: Payload) -> Error {
        self.err(
            node,
            Reason::WrongMessage {
                found: self.string(node, property).unwrap_or_default(),
                wanted: Handler::<M>::wanted(payload),
            },
        )
    }

    fn required(&self, node: &KdlNode, name: &'static str) -> Error {
        self.err(
            node,
            Reason::Missing {
                kind: node.name().value().to_string(),
                name,
            },
        )
    }

    /// The child nodes of one collection kind.
    /// The child nodes of `node` called `name`.
    ///
    /// A placeholder collection lives one level down, in the `design` block,
    /// and is read only when the caller asked for it — so an application's
    /// build sees no rows at all and a kiosk carries none.
    fn collection<'n>(&self, node: &'n KdlNode, name: &str) -> Vec<&'n KdlNode> {
        let holder = if is_placeholder(node.name().value(), name) {
            if !self.designing {
                return Vec::new();
            }
            let Some(design) = self.design_block(node) else {
                return Vec::new();
            };
            design
        } else {
            let Some(children) = node.children() else {
                return Vec::new();
            };
            children
        };
        holder
            .nodes()
            .iter()
            .filter(|n| n.name().value() == name)
            .collect()
    }

    /// Builds one tab's page: a container under the strip, and its subtree.
    ///
    /// The page fills what is left of the `tabs` node below the strip band, the
    /// way a `collapse`'s body fills what is left below its header. So a
    /// widget written at `y=0` inside a tab sits just under the strip, and a
    /// tab's rectangles are read the same way as any other container's.
    ///
    /// Only the selected page is visible. `selected` is the tab the
    /// *application* starts on; which page a designer is looking at is the
    /// designer's business and stays out of the file.
    fn page(
        &mut self,
        tab: &KdlNode,
        tabs: &KdlNode,
        strip: NodeId,
        depth: usize,
        path: &[usize],
        ordinal: usize,
    ) -> Result<(), Error> {
        let Some(bounds) = self.ui.bounds(strip) else {
            return Ok(());
        };
        // The band the strip draws in, read from the same place the widget
        // reads it: `Tabs::strip_height` is the theme's field height, and the
        // theme this tree holds is already in the units these rectangles are
        // in. Scaling it again here would put every page at twice the offset
        // the strip is drawn at.
        let band = self.ui.theme().metrics.size_field.max(1);
        let rect = Rect::new(0, band, bounds.width, (bounds.height - band).max(0));
        let page = self
            .ui
            .add(strip, Panel::bare(), rect)
            .ok_or_else(|| self.err(tab, Reason::TreeRefused))?;

        if let Some(children) = tab.children() {
            for (index, child) in children.nodes().iter().enumerate() {
                let mut below = path.to_vec();
                below.push(index);
                self.node(child, page, depth + 1, &below)?;
            }
        }

        // After the children, not before: hiding a node propagates to the
        // subtree it has *at the time*, and one hidden first would have its
        // pages added back into view behind it.
        let selected = tabs
            .get("selected")
            .and_then(KdlValue::as_integer)
            .unwrap_or(0);
        let shown = usize::try_from(selected).unwrap_or(0) == ordinal;
        self.ui.set_visible(page, shown);
        self.built.pages.push(Page {
            path: path.to_vec(),
            ordinal,
            id: page,
        });
        Ok(())
    }

    /// Whether any `tab` under `node` carries a page of its own.
    fn has_pages(&self, node: &KdlNode) -> bool {
        self.collection(node, "tab").into_iter().any(|tab| {
            tab.children()
                .is_some_and(|block| !block.nodes().is_empty())
        })
    }

    /// The `design` block of `node`, if it wrote one.
    fn design_block<'n>(&self, node: &'n KdlNode) -> Option<&'n KdlDocument> {
        node.children()?
            .nodes()
            .iter()
            .find(|n| n.name().value() == DESIGN)?
            .children()
    }

    fn strings(&self, node: &KdlNode, name: &str) -> Vec<String> {
        self.collection(node, name)
            .into_iter()
            .map(|n| self.arg(n).unwrap_or_default())
            .collect()
    }

    fn picture(&mut self, node: &KdlNode, path: &str) -> Result<Picture, Error> {
        self.wiring.asset(path).ok_or_else(|| {
            Error::new(
                self.form.at_node(node),
                Reason::Asset {
                    path: path.to_string(),
                },
            )
        })
    }
}

// The construction match is long because there are twenty-five widgets and no
// two constructors are alike. It is deliberately not clever: a table of
// constructors would need one type for all of them, and they differ in exactly
// the way that would make that a lie.
impl<M: Clone + 'static, W: Wiring<M>> Builder<'_, M, W> {
    fn construct(
        &mut self,
        node: &KdlNode,
        info: &WidgetInfo,
        parent: NodeId,
        rect: Rect,
    ) -> Result<NodeId, Error> {
        let text = self.arg(node).unwrap_or_default();
        let id = match info.kind {
            "label" => self.ui.add(parent, Label::new(text), rect),
            "panel" => self.ui.add(parent, Panel::default(), rect),
            "badge" => self.ui.add(parent, Badge::new(text), rect),
            "divider" => {
                let divider = if self.arg(node).is_some() {
                    Divider::labelled(text)
                } else {
                    Divider::new()
                };
                self.ui.add(parent, divider, rect)
            }
            "alert" => {
                let role = self
                    .string(node, "role")
                    .ok_or_else(|| self.required(node, "role"))?;
                let role = role_from_name(&role).ok_or_else(|| {
                    self.err(
                        node,
                        Reason::NotAName {
                            name: String::from("colour role"),
                            found: role.clone(),
                            accepted: ROLES,
                        },
                    )
                })?;
                self.ui.add(parent, Alert::new(role, text), rect)
            }
            "spinner" => self.ui.add(parent, Spinner::new(), rect),
            "video" => self.ui.add(parent, Video::new(), rect),
            "progress" => {
                let value = self.number(node, "value").unwrap_or(0.0);
                self.ui.add(parent, Progress::new(value), rect)
            }
            "radial-progress" => {
                let value = self.number(node, "value").unwrap_or(0.0);
                self.ui.add(parent, RadialProgress::new(value), rect)
            }
            "button" => {
                let button = match self.handler(node, "on-press", Payload::None)? {
                    Some(h) => Button::new(text, self.plain(node, "on-press", h)?),
                    None => Button::inert(text),
                };
                self.ui.add(parent, button, rect)
            }
            "text-area" => self.ui.add(parent, TextArea::<M>::from_text(&text), rect),
            "text-input" => {
                let mut field = TextInput::<M>::new();
                if let Some(h) = self.handler(node, "on-submit", Payload::None)? {
                    field = field.with_submit(self.plain(node, "on-submit", h)?);
                }
                self.ui.add(parent, field, rect)
            }
            "checkbox" => {
                let widget = match self.handler(node, "on-change", Payload::Bool)? {
                    Some(h) => Checkbox::new(text, self.on_bool(node, "on-change", h)?),
                    None => Checkbox::inert(text),
                };
                self.ui.add(parent, widget, rect)
            }
            "toggle" => {
                let widget = match self.handler(node, "on-change", Payload::Bool)? {
                    Some(h) => Toggle::new(text, self.on_bool(node, "on-change", h)?),
                    None => Toggle::inert(text),
                };
                self.ui.add(parent, widget, rect)
            }
            "slider" => {
                let min = self
                    .number(node, "min")
                    .ok_or_else(|| self.required(node, "min"))?;
                let max = self
                    .number(node, "max")
                    .ok_or_else(|| self.required(node, "max"))?;
                let value = self.number(node, "value").unwrap_or(min);
                let widget = match self.handler(node, "on-change", Payload::Number)? {
                    Some(h) => Slider::new(min, max, value, self.on_number(node, "on-change", h)?),
                    None => Slider::inert(min, max, value),
                };
                self.ui.add(parent, widget, rect)
            }
            "rating" => {
                let value = self.number(node, "value").unwrap_or(0.0);
                let widget = match self.handler(node, "on-change", Payload::Number)? {
                    Some(h) => Rating::new(value, self.on_number(node, "on-change", h)?),
                    None => Rating::display(value),
                };
                self.ui.add(parent, widget, rect)
            }
            "radio-group" => {
                let options = self.strings(node, "option");
                let widget = match self.handler(node, "on-change", Payload::Index)? {
                    Some(h) => RadioGroup::new(options, self.on_index(node, "on-change", h)?),
                    None => RadioGroup::inert(options),
                };
                self.ui.add(parent, widget, rect)
            }
            "menubar" => {
                let titles = self.strings(node, "title");
                // Without `on-open` there is nothing to press: the bar reports
                // which title was chosen and the application opens the menu, so
                // an inert one is titles and nothing else. See `MenuBar::inert`.
                let widget = match self.handler(node, "on-open", Payload::Index)? {
                    Some(h) => MenuBar::new(titles, self.on_index(node, "on-open", h)?),
                    None => MenuBar::inert(titles),
                };
                self.ui.add(parent, widget, rect)
            }
            "tabs" => {
                let labels = self.strings(node, "tab");
                let widget = match self.handler(node, "on-change", Payload::Index)? {
                    Some(h) => Tabs::new(labels, self.on_index(node, "on-change", h)?),
                    None => Tabs::inert(labels),
                };
                // A `tab` carrying children makes this a strip *over a page*,
                // drawn in a band along the top with the page below it. A file
                // whose tabs are bare labels is what a `tabs` node has always
                // been, and is untouched. See `Tabs::over_pages`.
                let widget = if self.has_pages(node) {
                    widget.over_pages()
                } else {
                    widget
                };
                self.ui.add(parent, widget, rect)
            }
            "select" => {
                let options = self.strings(node, "option");
                // Without `on-change` the list cannot be opened — the popup is a
                // scene the application pushes — so an inert one shows what is
                // chosen and stays shut. See `Select::inert`.
                let widget = match self.handler(node, "on-change", Payload::None)? {
                    Some(h) => Select::new(options, self.plain(node, "on-change", h)?),
                    None => Select::inert(options),
                };
                self.ui.add(parent, widget, rect)
            }
            "collapse" => {
                // An inert one folds itself, so a decorative section needs no
                // message. See `Collapse::inert`.
                let widget = match self.handler(node, "on-toggle", Payload::Bool)? {
                    Some(h) => Collapse::new(text, self.on_bool(node, "on-toggle", h)?),
                    None => Collapse::inert(text),
                };
                self.ui.add(parent, widget, rect)
            }
            "list" => {
                let items: Vec<ListItem> = self
                    .collection(node, "item")
                    .into_iter()
                    .map(|n| {
                        let mut item = ListItem::new(self.arg(n).unwrap_or_default());
                        if let Some(leading) = self.string(n, "leading") {
                            item = item.with_leading(leading);
                        }
                        if let Some(trailing) = self.string(n, "trailing") {
                            item = item.with_trailing(trailing);
                        }
                        if n.get("enabled").and_then(KdlValue::as_bool) == Some(false) {
                            item = item.disabled();
                        }
                        item
                    })
                    .collect();
                let mut widget = match self.handler(node, "on-select", Payload::Index)? {
                    Some(h) => List::new(items, self.on_index(node, "on-select", h)?),
                    None => List::inert(items),
                };
                if let Some(h) = self.handler(node, "on-activate", Payload::Index)? {
                    widget = widget.on_activate(self.on_index(node, "on-activate", h)?);
                }
                self.ui.add(parent, widget, rect)
            }
            "tree" => {
                let items: Vec<TreeItem> = self
                    .collection(node, "item")
                    .into_iter()
                    .map(|n| {
                        let mut item = TreeItem::new(self.arg(n).unwrap_or_default());
                        if let Some(depth) = n.get("depth").and_then(KdlValue::as_integer) {
                            item = item.at_depth(depth.clamp(0, i128::from(u16::MAX)) as u16);
                        }
                        if n.get("open").and_then(KdlValue::as_bool) == Some(false) {
                            item = item.shut();
                        }
                        if let Some(leading) = self.string(n, "leading") {
                            item = item.with_leading(leading);
                        }
                        if let Some(trailing) = self.string(n, "trailing") {
                            item = item.with_trailing(trailing);
                        }
                        if n.get("enabled").and_then(KdlValue::as_bool) == Some(false) {
                            item = item.disabled();
                        }
                        item
                    })
                    .collect();
                let mut widget = match self.handler(node, "on-select", Payload::Index)? {
                    Some(h) => Tree::new(items, self.on_index(node, "on-select", h)?),
                    None => Tree::inert(items),
                };
                if let Some(h) = self.handler(node, "on-activate", Payload::Index)? {
                    widget = widget.on_activate(self.on_index(node, "on-activate", h)?);
                }
                if let Some(h) = self.handler(node, "on-toggle", Payload::Index)? {
                    widget = widget.on_toggle(self.on_index(node, "on-toggle", h)?);
                }
                self.ui.add(parent, widget, rect)
            }
            "table" => {
                let columns: Vec<Column> = self
                    .collection(node, "column")
                    .into_iter()
                    .map(|n| {
                        let title = self.arg(n).unwrap_or_default();
                        let mut column = match n.get("width").and_then(KdlValue::as_integer) {
                            Some(width) => Column::new(title, width as i32),
                            None => Column::flex(title),
                        };
                        match n.get("align").and_then(KdlValue::as_string) {
                            Some("end") => column = column.align_end(),
                            Some("center") => column = column.align_center(),
                            _ => {}
                        }
                        column
                    })
                    .collect();
                let rows: Vec<Vec<String>> = self
                    .collection(node, "row")
                    .into_iter()
                    .map(|n| {
                        n.entries()
                            .iter()
                            .filter(|e| e.name().is_none())
                            .map(|e| e.value().as_string().unwrap_or_default().to_string())
                            .collect()
                    })
                    .collect();
                let mut widget = match self.handler(node, "on-select", Payload::Index)? {
                    Some(h) => Table::new(columns, self.on_index(node, "on-select", h)?),
                    None => Table::inert(columns),
                };
                widget = widget.with_rows(rows);
                if let Some(h) = self.handler(node, "on-activate", Payload::Index)? {
                    widget = widget.on_activate(self.on_index(node, "on-activate", h)?);
                }
                self.ui.add(parent, widget, rect)
            }
            "timeline" => {
                let events: Vec<TimelineItem> = self
                    .collection(node, "event")
                    .into_iter()
                    .map(|n| {
                        let mut item = TimelineItem::new(self.arg(n).unwrap_or_default());
                        if let Some(time) = self.string(n, "time") {
                            item = item.with_time(time);
                        }
                        if let Some(role) =
                            self.string(n, "role").as_deref().and_then(role_from_name)
                        {
                            item = item.with_role(role);
                        }
                        if n.get("pending").and_then(KdlValue::as_bool) == Some(true) {
                            item = item.pending();
                        }
                        item
                    })
                    .collect();
                self.ui.add(parent, Timeline::new(events), rect)
            }
            "image" => {
                let path = self
                    .string(node, "src")
                    .ok_or_else(|| self.required(node, "src"))?;
                let picture = self.picture(node, &path)?;
                self.ui
                    .add(parent, Image::new(picture.pixels, picture.size), rect)
            }
            "avatar" => {
                let avatar = match self.string(node, "src") {
                    Some(path) => {
                        let picture = self.picture(node, &path)?;
                        Avatar::new(picture.pixels, picture.size)
                    }
                    None => {
                        Avatar::initials(self.string(node, "initials").unwrap_or_default().as_str())
                    }
                };
                self.ui.add(parent, avatar, rect)
            }
            "carousel" => {
                let mut widget = match self.handler(node, "on-change", Payload::Index)? {
                    Some(h) => Carousel::new(self.on_index(node, "on-change", h)?),
                    None => Carousel::inert(),
                };
                for picture_node in self.collection(node, "picture") {
                    let path = self
                        .string(picture_node, "src")
                        .ok_or_else(|| self.required(picture_node, "src"))?;
                    let picture = self.picture(picture_node, &path)?;
                    let fit = match self.string(picture_node, "fit").as_deref() {
                        Some("fill") => Fit::Fill,
                        Some("cover") => Fit::Cover,
                        Some("center") => Fit::Center,
                        _ => Fit::Contain,
                    };
                    widget = widget.with_picture_fit(picture.pixels, picture.size, fit);
                }
                self.ui.add(parent, widget, rect)
            }
            other => {
                // `all()` matched a kind this match does not, which means a
                // widget joined the catalogue and not the builder.
                return Err(self.err(
                    node,
                    Reason::UnknownWidget {
                        found: other.to_string(),
                    },
                ));
            }
        };
        id.ok_or_else(|| self.err(node, Reason::TreeRefused))
    }

    /// Applies every widget property the file gives, **in descriptor order**.
    ///
    /// Descriptor order rather than file order, and deliberately: a slider's
    /// `value` is clamped into its `min`/`max`, so a file that wrote them the
    /// other way round would otherwise land somewhere else than one that did not.
    /// The widget publishes the order it wants to be told things in, and this
    /// obeys it — so two files that say the same thing build the same tree.
    fn apply_properties(
        &mut self,
        node: &KdlNode,
        info: &WidgetInfo,
        id: NodeId,
    ) -> Result<(), Error> {
        for property in info.properties {
            if !property.is_settable() {
                // A message or an asset; both were given to the constructor.
                continue;
            }
            let Some(entry) = node
                .entries()
                .iter()
                .find(|e| e.name().map(kdl::KdlIdentifier::value) == Some(property.name))
            else {
                continue;
            };
            let at = self.form.at(entry.span().offset());
            let mut value = self.convert(at, info.kind, property, entry.value())?;
            if property.pixels {
                value = self.lengthened(value);
            }
            if let Some(Err(error)) = self.ui.set_property(id, property.name, value) {
                return Err(Error::new(
                    at,
                    Reason::WrongType {
                        kind: info.kind,
                        name: property.name.to_string(),
                        wanted: match error.mismatch {
                            denise_ui::widgets::Mismatch::WrongType { expected } => expected.noun(),
                            _ => "something else",
                        },
                    },
                ));
            }
        }
        Ok(())
    }

    /// One length, at the scale this form is being built at.
    ///
    /// Which numbers are lengths is the **widget's** to say, not this crate's:
    /// see [`Property::pixels`](denise_ui::widgets::Property::pixels). A text
    /// size is a length and doubles at 2x; a duration in milliseconds is not and
    /// does not; a selected index is not and would be nonsense if it did.
    ///
    /// [`Placement::uniform`] rather than the axis factors, because none of these is
    /// horizontal or vertical: a text size is a size, and a border is as thick
    /// on the top as on the left.
    fn lengthened(&self, value: Value) -> Value {
        let scale = self.fit.uniform();
        match value {
            // At least one: a border that rounded to nothing at 0.75x has been
            // deleted rather than scaled, and the same for a one-pixel divider.
            // Zero stays zero, because zero was somebody saying "none".
            Value::Int(n) if n != 0 => {
                let scaled = (n as f32 * scale + 0.5) as i32;
                Value::Int(if n > 0 { scaled.max(1) } else { scaled.min(-1) })
            }
            Value::Float(f) => Value::Float(f * scale),
            other => other,
        }
    }

    /// A value from the file, in the shape the property takes.
    fn convert(
        &self,
        at: At,
        kind: &'static str,
        property: &Property,
        value: &KdlValue,
    ) -> Result<Value, Error> {
        let wrong = |wanted: &'static str| {
            Error::new(
                at,
                Reason::WrongType {
                    kind,
                    name: property.name.to_string(),
                    wanted,
                },
            )
        };
        Ok(match property.kind {
            PropertyKind::Text | PropertyKind::Color => {
                Value::text(value.as_string().ok_or_else(|| wrong("a string"))?)
            }
            PropertyKind::Bool => {
                Value::Bool(value.as_bool().ok_or_else(|| wrong("true or false"))?)
            }
            PropertyKind::Int { .. } => {
                let number = value.as_integer().ok_or_else(|| wrong("a whole number"))?;
                Value::Int(i32::try_from(number).map_err(|_| wrong("a whole number"))?)
            }
            PropertyKind::Float { .. } => {
                let number = value
                    .as_float()
                    .map(|f| f as f32)
                    .or_else(|| value.as_integer().map(|i| i as f32))
                    .ok_or_else(|| wrong("a number"))?;
                Value::Float(number)
            }
            PropertyKind::Enum(names) => {
                let found = value
                    .as_string()
                    .ok_or_else(|| wrong("one of the listed names"))?;
                let name = names.iter().copied().find(|n| *n == found).ok_or_else(|| {
                    Error::new(
                        at,
                        Reason::NotAName {
                            name: property.name.to_string(),
                            found: found.to_string(),
                            accepted: names,
                        },
                    )
                })?;
                Value::Enum(name)
            }
            // Filtered out by `is_settable` before this is reached.
            PropertyKind::Message(_) | PropertyKind::Asset => return Err(wrong("nothing here")),
            _ => return Err(wrong("a value this crate does not know")),
        })
    }

    /// The properties the tree owns.
    fn apply_node_properties(&mut self, node: &KdlNode, id: NodeId) -> Result<(), Error> {
        if let Some(name) = self.string(node, "name") {
            if self.built.names.contains_key(&name) {
                return Err(self.err(node, Reason::DuplicateName { name }));
            }
            self.built.names.insert(name, id);
        }
        if let Some(text) = self.string(node, "tooltip") {
            self.ui.set_tooltip(id, text);
        }
        if let Some(z) = node.get("z").and_then(KdlValue::as_integer) {
            self.ui.set_z(id, z as i32);
        }
        if node.get("scroll").and_then(KdlValue::as_bool) == Some(true) {
            self.ui.set_scrollable(id, true);
        }
        if let Some(spacing) = node.get("stack").and_then(KdlValue::as_integer) {
            self.ui.set_stack(id, spacing as i32);
        }
        if let Some(anchor) = self.string(node, "anchor") {
            let mut anchors = Anchors::new(false, false, false, false);
            for edge in anchor.split_whitespace() {
                match edge {
                    "left" => anchors.left = true,
                    "top" => anchors.top = true,
                    "right" => anchors.right = true,
                    "bottom" => anchors.bottom = true,
                    other => {
                        return Err(self.err(
                            node,
                            Reason::NotAName {
                                name: String::from("anchor edge"),
                                found: other.to_string(),
                                accepted: ANCHOR_EDGES,
                            },
                        ));
                    }
                }
            }
            self.ui.set_anchors(id, anchors);
        }
        if let Some(dock) = self.string(node, "dock") {
            let side = match dock.as_str() {
                "top" => Dock::Top,
                "bottom" => Dock::Bottom,
                "left" => Dock::Left,
                "right" => Dock::Right,
                "fill" => Dock::Fill,
                other => {
                    return Err(self.err(
                        node,
                        Reason::NotAName {
                            name: String::from("dock side"),
                            found: other.to_string(),
                            accepted: DOCK_SIDES,
                        },
                    ));
                }
            };
            self.ui.set_dock(id, Some(side));
        }
        if node.get("enabled").and_then(KdlValue::as_bool) == Some(false) {
            self.ui.set_enabled(id, false);
        }
        if node.get("focus").and_then(KdlValue::as_bool) == Some(true) {
            if self.focused.is_some() {
                return Err(self.err(node, Reason::TwoFocuses));
            }
            self.focused = Some(id);
        }
        // Last: a hidden node's children still had to be built and placed, and
        // hiding it first would have them laid out against a node with no bounds.
        if node.get("visible").and_then(KdlValue::as_bool) == Some(false) {
            self.ui.set_visible(id, false);
        }
        Ok(())
    }
}

// Unused-import guard: these name tables are the ones the schema documents, and
// referencing them here keeps a rename in `denise-ui` from silently drifting.
const _: &[&[&str]] = &[ALIGNMENTS, FITS, ORIENTATIONS, PRESENCES, RADII];