native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
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
//! `PropertyGrid`: an inspector for a typed [`PropertyModel`], built from
//! native controls.
//!
//! None of the three desktop toolkits ships a property grid (Win32 has no
//! common control for it, AppKit has no inspector view, and GTK4 has none
//! either), so the grid is composed in the shared layer from widgets every
//! backend already implements natively:
//!
//! | Value | Editor widget |
//! |---|---|
//! | `Text`, `Path`, numbers, `Aggregate` | `TextInput` (commits on Enter or focus loss; Escape restores) |
//! | `Bool` | `Checkbox` |
//! | `Enum` | `ComboBox` |
//! | `Flags` | `MultiSelect` |
//! | `Date` | `DatePicker` |
//! | `Color` | `ColorDialog` (opens the system color panel) |
//!
//! Categories become titled `GroupBox` frames, each property is a row of a
//! label and its editor, and the host is a vertical `Container`. The host
//! does not scroll by itself; give it a window or parent tall enough for the
//! model, or place it in a scrolling container. Because every editor is a
//! real platform control, keyboard navigation, focus rings, screen-reader
//! roles, and theming come from the OS, and the composition uses only
//! portable widget kinds, so any backend that implements them can show it.
//!
//! # Events
//!
//! User edits run through the model's two-phase change protocol and surface
//! as [`UiEvent::PropertyChanged`]. With veto mode on
//! ([`Ui::set_property_grid_veto`]) each edit first arrives as
//! [`UiEvent::PropertyChanging`] and waits for
//! [`Ui::resolve_property_change`]. Input that cannot be parsed for the
//! property's type, and edits the model refuses, arrive as
//! [`UiEvent::PropertyEditRejected`] and the editor is restored to the stored
//! value. Focusing an editor selects its property
//! ([`UiEvent::PropertySelected`]).
//!
//! Programmatic changes ([`Ui::set_property_grid_value`],
//! [`Ui::update_property_grid`]) are silent: they update the editors without
//! producing events, matching the rest of the widget API.
//!
//! The editor widgets are ordinary widgets, so their own events
//! (`TextChanged`, `Toggled`, ...) still arrive alongside the grid events;
//! applications normally match only the grid events.

use std::collections::HashMap;

use crate::error::{GuiError, GuiResult};
use crate::events::UiEvent;
use crate::pickers::{ColorDialogData, Rgba};
use crate::properties::{
    ChangeToken, ProjectionMode, PropertyEvent, PropertyId, PropertyModel, PropertyValue,
};
use crate::ui::{Backend, Ui};
use crate::widgets::{Color, ContainerDirection, WidgetKind};
use crate::WidgetId;

/// Default width of the label column, in logical pixels.
pub const DEFAULT_PROPERTY_LABEL_WIDTH: u32 = 140;

/// Left indent applied per nesting level for properties nested under another
/// property, in logical pixels.
const NESTED_INDENT: f32 = 16.0;

/// Minimum height of a property row, in logical pixels. Native editors are
/// usually taller; the floor keeps rows even on lanes that report small or
/// no natural sizes.
const MIN_ROW_HEIGHT: i32 = 26;
/// Vertical gap between rows inside a category frame.
const CATEGORY_GAP: i32 = 6;
/// Inner padding of a category frame.
const CATEGORY_PADDING: i32 = 8;
/// Room reserved for a category caption. Native group boxes draw their
/// caption inside their own bounds and place children below it, so the
/// frame's minimum height includes this band on top of its rows.
const CATEGORY_CAPTION_BAND: i32 = 24;

/// Which native control edits a property row.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PropertyEditorWidget {
    /// `TextInput`, parsed for the property's value type.
    TextInput,
    /// `Checkbox` for `Bool` values.
    Checkbox,
    /// `ComboBox` for `Enum` values.
    ComboBox,
    /// `MultiSelect` for `Flags` values.
    MultiSelect,
    /// `DatePicker` for `Date` values.
    DatePicker,
    /// `ColorDialog` button for `Color` values.
    ColorDialog,
}

impl PropertyEditorWidget {
    /// The editor widget used for a value.
    pub fn for_value(value: &PropertyValue) -> Self {
        match value {
            PropertyValue::Bool(_) => Self::Checkbox,
            PropertyValue::Enum { .. } => Self::ComboBox,
            PropertyValue::Flags { .. } => Self::MultiSelect,
            PropertyValue::Date(_) => Self::DatePicker,
            PropertyValue::Color(_) => Self::ColorDialog,
            PropertyValue::Text(_)
            | PropertyValue::Path(_)
            | PropertyValue::Int(_)
            | PropertyValue::Uint(_)
            | PropertyValue::Float(_)
            | PropertyValue::Aggregate(_) => Self::TextInput,
        }
    }

    /// The widget kind created for this editor.
    pub const fn widget_kind(self) -> WidgetKind {
        match self {
            Self::TextInput => WidgetKind::TextInput,
            Self::Checkbox => WidgetKind::Checkbox,
            Self::ComboBox => WidgetKind::ComboBox,
            Self::MultiSelect => WidgetKind::MultiSelect,
            Self::DatePicker => WidgetKind::DatePicker,
            Self::ColorDialog => WidgetKind::ColorDialog,
        }
    }
}

/// Runtime capabilities of the composed property grid.
///
/// The grid is the same composition on every backend, so this record is a
/// constant; it exists so applications and diagnostics pages can report
/// what the grid does without hard-coding it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PropertyGridFeatures {
    /// Every editor is a native platform control.
    pub native_editors: bool,
    /// Rows are virtualized (only visible rows exist as widgets).
    pub virtualization: bool,
    /// Categories can be expanded and collapsed by the user from the grid
    /// itself (they can always be toggled programmatically).
    pub user_collapsible_categories: bool,
    /// Edits can be vetoed by the application before they apply.
    pub veto: bool,
}

/// The capabilities every backend reports for the composed grid.
pub const PROPERTY_GRID_FEATURES: PropertyGridFeatures = PropertyGridFeatures {
    native_editors: true,
    virtualization: false,
    user_collapsible_categories: false,
    veto: true,
};

/// Minimum editor height for values that need more than one line: a flags
/// list needs room for its options (a dropdown lane ignores it).
fn editor_min_height(value: &PropertyValue) -> i32 {
    match value {
        PropertyValue::Flags { options, .. } => (options.len().clamp(1, 6) * 22 + 6) as i32,
        _ => 0,
    }
}

/// Formats a value the way the text editor shows it.
///
/// Numbers use Rust's shortest round-trip formatting, colors use `#RRGGBB`,
/// and aggregates join their parts with `", "`.
pub fn format_property_value(value: &PropertyValue) -> String {
    match value {
        PropertyValue::Text(text) | PropertyValue::Path(text) | PropertyValue::Date(text) => {
            text.clone()
        }
        PropertyValue::Bool(flag) => flag.to_string(),
        PropertyValue::Int(number) => number.to_string(),
        PropertyValue::Uint(number) => number.to_string(),
        PropertyValue::Float(number) => number.to_string(),
        PropertyValue::Enum { selected, options } => {
            options.get(*selected).cloned().unwrap_or_default()
        }
        PropertyValue::Flags { selected, options } => selected
            .iter()
            .filter_map(|index| options.get(*index).cloned())
            .collect::<Vec<_>>()
            .join(", "),
        PropertyValue::Color(color) => format!("#{:02X}{:02X}{:02X}", color.r, color.g, color.b),
        PropertyValue::Aggregate(parts) => parts
            .iter()
            .map(format_property_value)
            .collect::<Vec<_>>()
            .join(", "),
    }
}

/// Parses editor text into a value of the same type as `current`.
///
/// Returns a short, user-facing reason when the text does not fit the type.
/// Aggregates must keep their arity and each part is parsed against the
/// matching part of `current`.
pub fn parse_property_text(current: &PropertyValue, text: &str) -> Result<PropertyValue, String> {
    let trimmed = text.trim();
    match current {
        PropertyValue::Text(_) => Ok(PropertyValue::Text(text.to_owned())),
        PropertyValue::Path(_) => Ok(PropertyValue::Path(text.to_owned())),
        PropertyValue::Date(_) => Ok(PropertyValue::Date(trimmed.to_owned())),
        PropertyValue::Int(_) => trimmed
            .parse::<i64>()
            .map(PropertyValue::Int)
            .map_err(|_| format!("'{trimmed}' is not a whole number")),
        PropertyValue::Uint(_) => trimmed
            .parse::<u64>()
            .map(PropertyValue::Uint)
            .map_err(|_| format!("'{trimmed}' is not a non-negative whole number")),
        PropertyValue::Float(_) => match trimmed.parse::<f64>() {
            Ok(number) if number.is_finite() => Ok(PropertyValue::Float(number)),
            _ => Err(format!("'{trimmed}' is not a number")),
        },
        PropertyValue::Bool(_) => match trimmed.to_ascii_lowercase().as_str() {
            "true" | "yes" | "on" | "1" => Ok(PropertyValue::Bool(true)),
            "false" | "no" | "off" | "0" => Ok(PropertyValue::Bool(false)),
            _ => Err(format!("'{trimmed}' is not true or false")),
        },
        PropertyValue::Color(_) => parse_hex_color(trimmed)
            .map(PropertyValue::Color)
            .ok_or_else(|| format!("'{trimmed}' is not a #RRGGBB color")),
        PropertyValue::Enum { options, .. } => options
            .iter()
            .position(|option| option == trimmed)
            .map(|selected| PropertyValue::Enum {
                selected,
                options: options.clone(),
            })
            .ok_or_else(|| format!("'{trimmed}' is not one of the options")),
        PropertyValue::Flags { options, .. } => {
            let mut selected = Vec::new();
            for part in trimmed.split(',').map(str::trim).filter(|p| !p.is_empty()) {
                let index = options
                    .iter()
                    .position(|option| option == part)
                    .ok_or_else(|| format!("'{part}' is not one of the options"))?;
                selected.push(index);
            }
            selected.sort_unstable();
            selected.dedup();
            Ok(PropertyValue::Flags {
                selected,
                options: options.clone(),
            })
        }
        PropertyValue::Aggregate(parts) => {
            let pieces: Vec<&str> = text.split(',').collect();
            if pieces.len() != parts.len() {
                return Err(format!(
                    "expected {} comma-separated values, found {}",
                    parts.len(),
                    pieces.len()
                ));
            }
            parts
                .iter()
                .zip(pieces)
                .map(|(part, piece)| parse_property_text(part, piece))
                .collect::<Result<Vec<_>, _>>()
                .map(PropertyValue::Aggregate)
        }
    }
}

fn parse_hex_color(text: &str) -> Option<Color> {
    let hex = text.strip_prefix('#').unwrap_or(text);
    if hex.len() != 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
        return None;
    }
    let channel = |range: std::ops::Range<usize>| u8::from_str_radix(&hex[range], 16).ok();
    Some(Color::rgb(channel(0..2)?, channel(2..4)?, channel(4..6)?))
}

/// One built row of the grid.
#[derive(Debug, Clone)]
struct RowWidgets {
    /// The row container (properties) or the group frame (categories).
    frame: WidgetId,
    label: Option<WidgetId>,
    editor: Option<(WidgetId, PropertyEditorWidget)>,
}

/// Shape of the built widgets; a model change that keeps the shape only
/// refreshes editor values, anything else rebuilds the rows.
#[derive(Debug, Clone, PartialEq)]
struct RowShape {
    id: PropertyId,
    depth: usize,
    category: bool,
    label: String,
    editor: Option<PropertyEditorWidget>,
    options: Vec<String>,
}

#[derive(Debug, Clone)]
struct GridState {
    model: PropertyModel,
    mode: ProjectionMode,
    label_width: u32,
    veto: bool,
    rows: HashMap<PropertyId, RowWidgets>,
    /// Widgets attached directly to the host, removed on rebuild.
    top_level: Vec<WidgetId>,
    shape: Vec<RowShape>,
}

/// Per-`Ui` property grid bookkeeping.
#[derive(Debug, Default)]
pub(crate) struct PropertyGridRegistry {
    grids: HashMap<WidgetId, GridState>,
    /// Editor widget -> (grid host, property).
    editors: HashMap<WidgetId, (WidgetId, PropertyId)>,
}

impl PropertyGridRegistry {
    /// Drops every record that refers to a removed widget.
    pub(crate) fn forget(&mut self, widget_id: WidgetId) {
        if self.grids.remove(&widget_id).is_some() {
            self.editors.retain(|_, (grid, _)| *grid != widget_id);
        }
        self.editors.remove(&widget_id);
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.grids.is_empty()
    }
}

fn shape_of(model: &PropertyModel, mode: ProjectionMode) -> Vec<RowShape> {
    model
        .rows(mode)
        .into_iter()
        .map(|row| RowShape {
            id: row.id,
            depth: row.depth,
            category: row.category,
            label: row.label.to_owned(),
            editor: row.value.map(PropertyEditorWidget::for_value),
            options: match row.value {
                Some(PropertyValue::Enum { options, .. })
                | Some(PropertyValue::Flags { options, .. }) => options.clone(),
                _ => Vec::new(),
            },
        })
        .collect()
}

fn is_text_editor(state: &GridState, id: PropertyId) -> bool {
    state
        .rows
        .get(&id)
        .and_then(|row| row.editor)
        .is_some_and(|(_, kind)| kind == PropertyEditorWidget::TextInput)
}

fn to_rgba(color: Color) -> Rgba {
    Rgba::rgb(color.r, color.g, color.b)
}

impl<B: Backend> Ui<B> {
    /// Creates a property grid showing `model` and returns its host widget.
    ///
    /// Attach the host like any other widget. The grid owns `model`; read it
    /// back with [`Self::property_grid_model`].
    pub fn create_property_grid(&mut self, model: PropertyModel) -> GuiResult<WidgetId> {
        model.validate()?;
        let host = self.create(WidgetKind::Container, None)?;
        let built = (|| -> GuiResult<()> {
            self.set_container_direction(host, ContainerDirection::Vertical)?;
            self.set_container_gap(host, 6)?;
            self.set_container_padding(host, 8)?;
            let _ = self.set_accessible_name(host, "Properties");
            Ok(())
        })();
        if let Err(error) = built {
            let _ = self.remove(host);
            return Err(error);
        }
        let mut state = GridState {
            model,
            mode: ProjectionMode::Categorized,
            label_width: DEFAULT_PROPERTY_LABEL_WIDTH,
            veto: false,
            rows: HashMap::new(),
            top_level: Vec::new(),
            shape: Vec::new(),
        };
        state.model.clear_events();
        if let Err(error) = self.build_property_rows(host, &mut state) {
            let _ = self.remove(host);
            return Err(error);
        }
        self.property_grids.grids.insert(host, state);
        Ok(host)
    }

    /// The model shown by a property grid.
    pub fn property_grid_model(&self, grid: WidgetId) -> GuiResult<&PropertyModel> {
        self.property_grids
            .grids
            .get(&grid)
            .map(|state| &state.model)
            .ok_or(GuiError::WidgetNotFound(grid.0))
    }

    /// Replaces the grid's model and rebuilds its rows (silent).
    pub fn set_property_grid_model(
        &mut self,
        grid: WidgetId,
        model: PropertyModel,
    ) -> GuiResult<()> {
        model.validate()?;
        self.with_grid(grid, |ui, state| {
            state.model = model;
            state.model.clear_events();
            ui.build_property_rows(grid, state)
        })
    }

    /// Runs `edit` against the grid's model, then brings the editors in line
    /// with the result (silent).
    ///
    /// Value changes refresh the existing editors in place; structural
    /// changes (added, removed, hidden, or collapsed nodes, new labels or
    /// option lists) rebuild the rows. Model events produced by `edit` are
    /// discarded because the change came from the application.
    pub fn update_property_grid<R>(
        &mut self,
        grid: WidgetId,
        edit: impl FnOnce(&mut PropertyModel) -> R,
    ) -> GuiResult<R> {
        self.with_grid(grid, |ui, state| {
            let result = edit(&mut state.model);
            state.model.clear_events();
            ui.sync_property_rows(grid, state)?;
            Ok(result)
        })
    }

    /// Sets one property's value through the programmatic path (silent).
    pub fn set_property_grid_value(
        &mut self,
        grid: WidgetId,
        id: PropertyId,
        value: PropertyValue,
    ) -> GuiResult<()> {
        self.with_grid(grid, |ui, state| {
            state.model.set_value(id, value)?;
            state.model.clear_events();
            ui.refresh_property_editor(state, id)
        })
    }

    /// Switches between the categorized and the category-free (flat) view.
    pub fn set_property_grid_projection(
        &mut self,
        grid: WidgetId,
        mode: ProjectionMode,
    ) -> GuiResult<()> {
        self.with_grid(grid, |ui, state| {
            if state.mode == mode {
                return Ok(());
            }
            state.mode = mode;
            ui.build_property_rows(grid, state)
        })
    }

    /// The grid's current projection.
    pub fn property_grid_projection(&self, grid: WidgetId) -> GuiResult<ProjectionMode> {
        self.property_grids
            .grids
            .get(&grid)
            .map(|state| state.mode)
            .ok_or(GuiError::WidgetNotFound(grid.0))
    }

    /// Expands or collapses a category (or a property with children).
    pub fn set_property_expanded(
        &mut self,
        grid: WidgetId,
        id: PropertyId,
        expanded: bool,
    ) -> GuiResult<()> {
        self.update_property_grid(grid, |model| model.set_expanded(id, expanded))?
            .map_err(GuiError::from)
    }

    /// Sets the width of the label column, in logical pixels.
    pub fn set_property_grid_label_width(&mut self, grid: WidgetId, width: u32) -> GuiResult<()> {
        if width == 0 {
            return Err(GuiError::InvalidLayoutGeometry);
        }
        self.with_grid(grid, |ui, state| {
            state.label_width = width;
            let labels: Vec<WidgetId> = state.rows.values().filter_map(|row| row.label).collect();
            for label in labels {
                ui.apply_property_label_width(label, width)?;
            }
            Ok(())
        })
    }

    /// The width of the label column, in logical pixels.
    pub fn property_grid_label_width(&self, grid: WidgetId) -> GuiResult<u32> {
        self.property_grids
            .grids
            .get(&grid)
            .map(|state| state.label_width)
            .ok_or(GuiError::WidgetNotFound(grid.0))
    }

    /// Turns veto mode on or off.
    ///
    /// With veto on, each user edit is staged and reported as
    /// [`UiEvent::PropertyChanging`]; nothing is stored until the
    /// application answers with [`Self::resolve_property_change`]. Turning
    /// veto off denies a change that is still waiting.
    pub fn set_property_grid_veto(&mut self, grid: WidgetId, enabled: bool) -> GuiResult<()> {
        self.with_grid(grid, |ui, state| {
            state.veto = enabled;
            if !enabled {
                if let Some(pending) = state.model.pending_change().cloned() {
                    state.model.resolve_change(pending.token)?;
                    ui.emit_property_events(grid, state)?;
                }
            }
            Ok(())
        })
    }

    /// Answers a staged edit: `accept` stores it and reports
    /// [`UiEvent::PropertyChanged`]; otherwise the editor goes back to the
    /// stored value and [`UiEvent::PropertyEditRejected`] reports the veto.
    pub fn resolve_property_change(
        &mut self,
        grid: WidgetId,
        token: ChangeToken,
        accept: bool,
    ) -> GuiResult<()> {
        self.with_grid(grid, |ui, state| {
            if accept {
                state.model.commit_change(token)?;
            } else {
                state.model.deny_change(token)?;
            }
            ui.emit_property_events(grid, state)
        })
    }

    /// The editor widget of a property, when its row is currently shown.
    ///
    /// Useful for tests, focus management, and accessibility checks.
    pub fn property_grid_editor(
        &self,
        grid: WidgetId,
        id: PropertyId,
    ) -> GuiResult<Option<WidgetId>> {
        let state = self
            .property_grids
            .grids
            .get(&grid)
            .ok_or(GuiError::WidgetNotFound(grid.0))?;
        Ok(state
            .rows
            .get(&id)
            .and_then(|row| row.editor.map(|(editor, _)| editor)))
    }

    /// The frame widget of a row: the `GroupBox` of a category or the row
    /// container of a property.
    pub fn property_grid_row(&self, grid: WidgetId, id: PropertyId) -> GuiResult<Option<WidgetId>> {
        let state = self
            .property_grids
            .grids
            .get(&grid)
            .ok_or(GuiError::WidgetNotFound(grid.0))?;
        Ok(state.rows.get(&id).map(|row| row.frame))
    }

    /// Whether `widget_id` is the host of a property grid.
    pub fn is_property_grid(&self, widget_id: WidgetId) -> bool {
        self.property_grids.grids.contains_key(&widget_id)
    }

    /// Selects a property and moves keyboard focus to its editor (silent).
    pub fn select_property(&mut self, grid: WidgetId, id: Option<PropertyId>) -> GuiResult<()> {
        self.with_grid(grid, |ui, state| {
            state.model.set_selected(id)?;
            state.model.clear_events();
            if let Some(editor) = id
                .and_then(|id| state.rows.get(&id))
                .and_then(|row| row.editor.map(|(editor, _)| editor))
            {
                ui.focus(editor)?;
            }
            Ok(())
        })
    }

    fn with_grid<R>(
        &mut self,
        grid: WidgetId,
        run: impl FnOnce(&mut Self, &mut GridState) -> GuiResult<R>,
    ) -> GuiResult<R> {
        let mut state = self
            .property_grids
            .grids
            .remove(&grid)
            .ok_or(GuiError::WidgetNotFound(grid.0))?;
        let result = run(self, &mut state);
        if self.widget(grid).is_some() {
            self.property_grids.grids.insert(grid, state);
        }
        result
    }

    fn apply_property_label_width(&mut self, label: WidgetId, width: u32) -> GuiResult<()> {
        let mut style = self.layout_style(label)?;
        style.size.width = crate::layout::Dimension::Length(width as f32);
        style.flex_shrink = 0.0;
        self.set_layout_style(label, style)
    }

    fn sync_property_rows(&mut self, grid: WidgetId, state: &mut GridState) -> GuiResult<()> {
        if shape_of(&state.model, state.mode) != state.shape {
            return self.build_property_rows(grid, state);
        }
        let ids: Vec<PropertyId> = state.rows.keys().copied().collect();
        for id in ids {
            self.refresh_property_editor(state, id)?;
        }
        Ok(())
    }

    /// Removes the current rows and builds them again from the model.
    fn build_property_rows(&mut self, grid: WidgetId, state: &mut GridState) -> GuiResult<()> {
        for widget in std::mem::take(&mut state.top_level) {
            if self.widget(widget).is_some() {
                self.remove(widget)?;
            }
        }
        for row in state.rows.values() {
            if let Some((editor, _)) = row.editor {
                self.property_grids.editors.remove(&editor);
            }
        }
        state.rows.clear();
        state.shape = shape_of(&state.model, state.mode);

        // Containers by category depth: rows attach to the nearest open
        // category frame, or to the host.
        let mut open: Vec<(usize, WidgetId)> = Vec::new();
        // Minimum heights, so each category frame can reserve room for its
        // caption and rows (see `CATEGORY_CAPTION_BAND`).
        let mut categories: Vec<WidgetId> = Vec::new();
        let mut children: HashMap<WidgetId, Vec<WidgetId>> = HashMap::new();
        let mut min_heights: HashMap<WidgetId, i32> = HashMap::new();
        let shape = state.shape.clone();
        for row in &shape {
            while open.last().is_some_and(|(depth, _)| *depth >= row.depth) {
                open.pop();
            }
            let (parent, base_depth) = open
                .last()
                .map(|(depth, frame)| (*frame, depth + 1))
                .unwrap_or((grid, 0));
            let frame = if row.category {
                let frame = self.create(WidgetKind::GroupBox, Some(&row.label))?;
                self.attach(parent, frame)?;
                self.set_container_direction(frame, ContainerDirection::Vertical)?;
                self.set_container_gap(frame, CATEGORY_GAP)?;
                self.set_container_padding(frame, CATEGORY_PADDING)?;
                open.push((row.depth, frame));
                categories.push(frame);
                state.rows.insert(
                    row.id,
                    RowWidgets {
                        frame,
                        label: None,
                        editor: None,
                    },
                );
                frame
            } else {
                let (frame, row_height) = self.build_property_row(grid, state, row, parent)?;
                min_heights.insert(frame, row_height);
                let indent = row.depth.saturating_sub(base_depth) as f32 * NESTED_INDENT;
                if indent > 0.0 {
                    let mut style = self.layout_style(frame)?;
                    style.margin.left = crate::layout::LengthPercentageAuto::Length(indent);
                    self.set_layout_style(frame, style)?;
                }
                frame
            };
            if parent == grid {
                state.top_level.push(frame);
            } else {
                children.entry(parent).or_default().push(frame);
            }
        }
        // Inner categories come after their parents, so walking backwards
        // sizes children first.
        for frame in categories.into_iter().rev() {
            let rows = children.get(&frame).map(Vec::as_slice).unwrap_or(&[]);
            let content: i32 = rows
                .iter()
                .map(|child| min_heights.get(child).copied().unwrap_or(MIN_ROW_HEIGHT))
                .sum::<i32>()
                + CATEGORY_GAP * (rows.len().saturating_sub(1) as i32);
            let height = content + 2 * CATEGORY_PADDING + CATEGORY_CAPTION_BAND;
            min_heights.insert(frame, height);
            self.set_min_size(frame, 0, height)?;
        }
        Ok(())
    }

    fn build_property_row(
        &mut self,
        grid: WidgetId,
        state: &mut GridState,
        row: &RowShape,
        parent: WidgetId,
    ) -> GuiResult<(WidgetId, i32)> {
        let node = state
            .model
            .get(row.id)
            .ok_or(GuiError::WidgetNotFound(row.id.0))?
            .clone();
        let value = node
            .value
            .clone()
            .ok_or_else(|| GuiError::Backend(format!("property {} has no value", row.id)))?;
        let kind = PropertyEditorWidget::for_value(&value);

        let frame = self.create(WidgetKind::Container, None)?;
        self.attach(parent, frame)?;
        self.set_container_direction(frame, ContainerDirection::Horizontal)?;
        self.set_container_gap(frame, 8)?;
        let mut style = self.layout_style(frame)?;
        style.align_items = Some(crate::layout::AlignItems::Center);
        self.set_layout_style(frame, style)?;

        let label = self.create(WidgetKind::Label, Some(&node.label))?;
        self.attach(frame, label)?;
        self.apply_property_label_width(label, state.label_width)?;

        let editor = match kind {
            PropertyEditorWidget::TextInput => {
                self.create(WidgetKind::TextInput, Some(&format_property_value(&value)))?
            }
            PropertyEditorWidget::Checkbox => self.create(WidgetKind::Checkbox, Some(""))?,
            PropertyEditorWidget::ComboBox => match &value {
                PropertyValue::Enum { options, .. } => self.create_combo_box(options)?,
                _ => unreachable!("combo editors hold enum values"),
            },
            PropertyEditorWidget::MultiSelect => match &value {
                PropertyValue::Flags { options, .. } => {
                    self.create(WidgetKind::MultiSelect, Some(&options.join("|")))?
                }
                _ => unreachable!("multi-select editors hold flag values"),
            },
            PropertyEditorWidget::DatePicker => self.create(WidgetKind::DatePicker, None)?,
            PropertyEditorWidget::ColorDialog => self.create(
                WidgetKind::ColorDialog,
                Some(&format_property_value(&value)),
            )?,
        };
        self.attach(frame, editor)?;
        self.set_flex_grow(editor, 1.0)?;
        let _ = self.set_accessible_name(editor, &node.label);
        // Row height: the taller of the label and the editor as the backend
        // measures them, at least `MIN_ROW_HEIGHT`. A flags list gets a fixed
        // height for its options so a lane's large default list size does
        // not stretch the row.
        let list_height = editor_min_height(&value);
        let editor_height = if list_height > 0 {
            let mut style = self.layout_style(editor)?;
            style.size.height = crate::layout::Dimension::Length(list_height as f32);
            self.set_layout_style(editor, style)?;
            list_height
        } else {
            self.backend()
                .natural_size(editor)
                .map_or(0, |(_, height)| height)
        };
        let label_height = self
            .backend()
            .natural_size(label)
            .map_or(0, |(_, height)| height);
        let row_height = MIN_ROW_HEIGHT.max(editor_height).max(label_height);
        self.set_min_size(frame, 0, row_height)?;

        state.rows.insert(
            row.id,
            RowWidgets {
                frame,
                label: Some(label),
                editor: Some((editor, kind)),
            },
        );
        self.property_grids.editors.insert(editor, (grid, row.id));
        self.refresh_property_editor(state, row.id)?;
        Ok((frame, row_height))
    }

    /// Writes the stored value and the enabled/validation state of one
    /// property into its editor, touching only what differs.
    fn refresh_property_editor(&mut self, state: &GridState, id: PropertyId) -> GuiResult<()> {
        let Some(RowWidgets {
            editor: Some((editor, kind)),
            ..
        }) = state.rows.get(&id).cloned()
        else {
            return Ok(());
        };
        let Some(node) = state.model.get(id) else {
            return Ok(());
        };
        let Some(value) = node.value.clone() else {
            return Ok(());
        };
        let editable = node.enabled && !node.read_only;
        let tooltip = node.validation.clone();
        let Some(spec) = self.widget(editor).cloned() else {
            return Ok(());
        };
        match (kind, &value) {
            (PropertyEditorWidget::Checkbox, PropertyValue::Bool(checked)) => {
                if spec.checked != Some(*checked) {
                    self.set_checked(editor, *checked)?;
                }
            }
            (PropertyEditorWidget::ComboBox, PropertyValue::Enum { selected, .. }) => {
                if spec.selected_index != Some(*selected) {
                    self.set_selected_index(editor, *selected)?;
                }
            }
            (PropertyEditorWidget::MultiSelect, PropertyValue::Flags { selected, .. }) => {
                if spec.selected_indices != *selected {
                    self.set_selected_indices(editor, selected)?;
                }
            }
            (PropertyEditorWidget::DatePicker, PropertyValue::Date(date)) => {
                if spec.date_value.as_deref() != Some(date.as_str()) {
                    self.set_date_value(editor, date)?;
                }
            }
            (PropertyEditorWidget::ColorDialog, PropertyValue::Color(color)) => {
                let text = format_property_value(&value);
                if spec.text.as_deref() != Some(text.as_str()) {
                    self.set_text(editor, &text)?;
                }
                let rgba = to_rgba(*color);
                if spec.color_dialog_data.as_ref().map(|data| data.initial) != Some(rgba) {
                    let mut data = spec
                        .color_dialog_data
                        .clone()
                        .unwrap_or_else(|| ColorDialogData::new(rgba));
                    data.initial = rgba;
                    // Lanes without a native chooser mapping refuse the data;
                    // the button still shows the value.
                    let _ = self.set_color_dialog_data(editor, data);
                }
            }
            _ => {
                let text = format_property_value(&value);
                if spec.text.as_deref() != Some(text.as_str()) {
                    self.set_text(editor, &text)?;
                }
            }
        }
        if spec.enabled.unwrap_or(true) != editable {
            self.set_enabled(editor, editable)?;
        }
        let _ = self.set_tooltip(editor, tooltip.as_deref().unwrap_or(""));
        Ok(())
    }

    /// Turns an editor widget's user event into a property edit.
    ///
    /// Called from the event path for every event; it returns quickly for
    /// widgets that are not grid editors.
    pub(crate) fn observe_property_grid_event(&mut self, event: &UiEvent) {
        if self.property_grids.is_empty() {
            return;
        }
        let editor = match event {
            UiEvent::Toggled { widget_id, .. }
            | UiEvent::SelectionChanged { widget_id, .. }
            | UiEvent::MultiSelectionChanged { widget_id, .. }
            | UiEvent::TextSubmitted { widget_id, .. }
            | UiEvent::DateChanged { widget_id, .. }
            | UiEvent::ColorSelected { widget_id, .. }
            | UiEvent::FocusChanged { widget_id, .. }
            | UiEvent::KeyDown { widget_id, .. } => *widget_id,
            _ => return,
        };
        let Some(&(grid, id)) = self.property_grids.editors.get(&editor) else {
            return;
        };
        let _ = self.with_grid(grid, |ui, state| {
            ui.handle_property_editor_event(grid, state, id, editor, event)
        });
    }

    fn handle_property_editor_event(
        &mut self,
        grid: WidgetId,
        state: &mut GridState,
        id: PropertyId,
        editor: WidgetId,
        event: &UiEvent,
    ) -> GuiResult<()> {
        let Some(current) = state.model.value(id).cloned() else {
            return Ok(());
        };
        let proposal: Result<PropertyValue, String> = match (event, &current) {
            (UiEvent::FocusChanged { focused: true, .. }, _) => {
                if state.model.selected() != Some(id) {
                    state.model.set_selected(Some(id))?;
                    self.emit_property_events(grid, state)?;
                }
                return Ok(());
            }
            (UiEvent::KeyDown { key, .. }, _) if is_text_editor(state, id) => {
                match key.as_str() {
                    "Escape" => return self.refresh_property_editor(state, id),
                    "Enter" | "Return" => {}
                    _ => return Ok(()),
                }
                let text = self
                    .widget(editor)
                    .and_then(|spec| spec.text.clone())
                    .unwrap_or_default();
                parse_property_text(&current, &text)
            }
            (UiEvent::FocusChanged { focused: false, .. }, _) => {
                if !is_text_editor(state, id) {
                    return Ok(());
                }
                let text = self
                    .widget(editor)
                    .and_then(|spec| spec.text.clone())
                    .unwrap_or_default();
                parse_property_text(&current, &text)
            }
            (UiEvent::TextSubmitted { text, .. }, _) => parse_property_text(&current, text),
            (UiEvent::Toggled { checked, .. }, PropertyValue::Bool(_)) => {
                Ok(PropertyValue::Bool(*checked))
            }
            (
                UiEvent::SelectionChanged {
                    index: Some(index), ..
                },
                PropertyValue::Enum { options, .. },
            ) => Ok(PropertyValue::Enum {
                selected: *index,
                options: options.clone(),
            }),
            (
                UiEvent::MultiSelectionChanged { indices, .. },
                PropertyValue::Flags { options, .. },
            ) => {
                let mut selected = indices.clone();
                selected.sort_unstable();
                selected.dedup();
                Ok(PropertyValue::Flags {
                    selected,
                    options: options.clone(),
                })
            }
            (UiEvent::DateChanged { iso_date, .. }, PropertyValue::Date(_)) => {
                Ok(PropertyValue::Date(iso_date.clone()))
            }
            (
                UiEvent::ColorSelected {
                    color: Some(color), ..
                },
                PropertyValue::Color(_),
            ) => Ok(PropertyValue::Color(Color::rgb(color.r, color.g, color.b))),
            _ => return Ok(()),
        };
        let proposed = match proposal {
            Ok(value) => value,
            Err(reason) => {
                self.reject_property_edit(grid, state, id, reason)?;
                return Ok(());
            }
        };
        if proposed == current {
            // Echo of a programmatic update, or an edit back to the stored
            // value: nothing to report. Still tidy up text formatting such
            // as surrounding spaces.
            return self.refresh_property_editor(state, id);
        }
        let token = match state.model.request_change(id, proposed) {
            Ok(token) => token,
            Err(error) => {
                state.model.clear_events();
                self.reject_property_edit(grid, state, id, error.to_string())?;
                return Ok(());
            }
        };
        if !state.veto {
            state.model.commit_change(token)?;
        }
        self.emit_property_events(grid, state)
    }

    fn reject_property_edit(
        &mut self,
        grid: WidgetId,
        state: &mut GridState,
        id: PropertyId,
        reason: String,
    ) -> GuiResult<()> {
        self.refresh_property_editor(state, id)?;
        self.queue_event(UiEvent::PropertyEditRejected {
            widget_id: grid,
            property: id,
            reason,
        });
        Ok(())
    }

    /// Translates the model's event log into UI events after a user edit.
    fn emit_property_events(&mut self, grid: WidgetId, state: &mut GridState) -> GuiResult<()> {
        for event in state.model.drain_events() {
            match event {
                PropertyEvent::Changing {
                    token,
                    id,
                    proposed,
                    ..
                } => {
                    if state.veto {
                        self.queue_event(UiEvent::PropertyChanging {
                            widget_id: grid,
                            property: id,
                            token,
                            proposed,
                        });
                    }
                }
                PropertyEvent::Changed {
                    id,
                    previous,
                    current,
                } => {
                    self.refresh_property_editor(state, id)?;
                    self.queue_event(UiEvent::PropertyChanged {
                        widget_id: grid,
                        property: id,
                        previous,
                        value: current,
                    });
                }
                PropertyEvent::ChangeDenied { id, reason, .. } => {
                    self.refresh_property_editor(state, id)?;
                    self.queue_event(UiEvent::PropertyEditRejected {
                        widget_id: grid,
                        property: id,
                        reason: reason.as_str().to_owned(),
                    });
                }
                PropertyEvent::SelectionChanged { current, .. } => {
                    self.queue_event(UiEvent::PropertySelected {
                        widget_id: grid,
                        property: current,
                    });
                }
                _ => {}
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::properties::{PropertyEditor, PropertyModel};
    use crate::test_support::MockBackend;

    struct Fixture {
        ui: Ui<MockBackend>,
        grid: WidgetId,
        title: PropertyId,
        visible: PropertyId,
        tint: PropertyId,
        width: PropertyId,
        opacity: PropertyId,
        align: PropertyId,
        borders: PropertyId,
        due: PropertyId,
        locked: PropertyId,
        layout: PropertyId,
    }

    fn fixture() -> Fixture {
        let mut model = PropertyModel::new();
        let appearance = model.add_category(None, "Appearance").unwrap();
        let title = model
            .add_property(
                Some(appearance),
                "Title",
                PropertyEditor::Text,
                PropertyValue::Text("Untitled".into()),
            )
            .unwrap();
        let visible = model
            .add_property(
                Some(appearance),
                "Visible",
                PropertyEditor::Checkbox,
                PropertyValue::Bool(true),
            )
            .unwrap();
        let tint = model
            .add_property(
                Some(appearance),
                "Tint",
                PropertyEditor::Color,
                PropertyValue::Color(Color::rgb(0x41, 0x69, 0xE1)),
            )
            .unwrap();
        let layout = model.add_category(None, "Layout").unwrap();
        let width = model
            .add_property(
                Some(layout),
                "Width",
                PropertyEditor::Numeric,
                PropertyValue::Int(320),
            )
            .unwrap();
        let opacity = model
            .add_property(
                Some(layout),
                "Opacity",
                PropertyEditor::Numeric,
                PropertyValue::Float(0.5),
            )
            .unwrap();
        let align = model
            .add_property(
                Some(layout),
                "Align",
                PropertyEditor::Choice,
                PropertyValue::Enum {
                    selected: 0,
                    options: vec!["Start".into(), "Center".into(), "End".into()],
                },
            )
            .unwrap();
        let borders = model
            .add_property(
                Some(layout),
                "Borders",
                PropertyEditor::Choice,
                PropertyValue::Flags {
                    selected: vec![0],
                    options: vec!["Top".into(), "Bottom".into()],
                },
            )
            .unwrap();
        let due = model
            .add_property(
                Some(layout),
                "Due",
                PropertyEditor::Date,
                PropertyValue::Date("2026-12-04".into()),
            )
            .unwrap();
        let locked = model
            .add_property(
                Some(layout),
                "Id",
                PropertyEditor::Text,
                PropertyValue::Text("node-7".into()),
            )
            .unwrap();
        model.set_read_only(locked, true).unwrap();

        let mut ui = Ui::new(MockBackend::default());
        let window = ui.create(WidgetKind::Window, Some("Grid")).unwrap();
        let grid = ui.create_property_grid(model).unwrap();
        ui.attach(window, grid).unwrap();
        Fixture {
            ui,
            grid,
            title,
            visible,
            tint,
            width,
            opacity,
            align,
            borders,
            due,
            locked,
            layout,
        }
    }

    fn editor(f: &Fixture, id: PropertyId) -> WidgetId {
        f.ui.property_grid_editor(f.grid, id).unwrap().unwrap()
    }

    fn user(f: &mut Fixture, event: UiEvent) -> Vec<UiEvent> {
        f.ui.backend_mut().push_event(event);
        let mut events = Vec::new();
        while let Some(event) = f.ui.poll_event().unwrap() {
            events.push(event);
        }
        events
    }

    fn grid_events(events: &[UiEvent]) -> Vec<UiEvent> {
        events
            .iter()
            .filter(|event| {
                matches!(
                    event,
                    UiEvent::PropertyChanged { .. }
                        | UiEvent::PropertyChanging { .. }
                        | UiEvent::PropertyEditRejected { .. }
                        | UiEvent::PropertySelected { .. }
                )
            })
            .cloned()
            .collect()
    }

    #[test]
    fn builds_one_native_editor_per_property_inside_category_frames() {
        let f = fixture();
        let kinds = [
            (f.title, WidgetKind::TextInput),
            (f.visible, WidgetKind::Checkbox),
            (f.tint, WidgetKind::ColorDialog),
            (f.width, WidgetKind::TextInput),
            (f.opacity, WidgetKind::TextInput),
            (f.align, WidgetKind::ComboBox),
            (f.borders, WidgetKind::MultiSelect),
            (f.due, WidgetKind::DatePicker),
        ];
        for (id, kind) in kinds {
            let spec = f.ui.widget(editor(&f, id)).unwrap();
            assert_eq!(spec.kind, kind, "editor kind for {id}");
        }
        let frame = f.ui.property_grid_row(f.grid, f.layout).unwrap().unwrap();
        assert_eq!(f.ui.widget(frame).unwrap().kind, WidgetKind::GroupBox);
        assert_eq!(f.ui.widget(frame).unwrap().text.as_deref(), Some("Layout"));
        assert_eq!(f.ui.text(editor(&f, f.width)).unwrap(), "320");
        assert_eq!(f.ui.text(editor(&f, f.tint)).unwrap(), "#4169E1");
        assert!(f.ui.is_checked(editor(&f, f.visible)).unwrap());
        assert_eq!(
            f.ui.widget(editor(&f, f.borders)).unwrap().selected_indices,
            vec![0]
        );
        assert_eq!(
            f.ui.widget(editor(&f, f.due))
                .unwrap()
                .date_value
                .as_deref(),
            Some("2026-12-04")
        );
        let locked = f.ui.widget(editor(&f, f.locked)).unwrap();
        assert_eq!(
            locked.enabled,
            Some(false),
            "read-only rows are not editable"
        );
        assert!(f.ui.is_property_grid(f.grid));
    }

    #[test]
    fn user_edits_become_property_changed_events() {
        let mut f = fixture();
        let check = editor(&f, f.visible);
        let events = user(
            &mut f,
            UiEvent::Toggled {
                widget_id: check,
                checked: false,
            },
        );
        assert_eq!(
            grid_events(&events),
            vec![UiEvent::PropertyChanged {
                widget_id: f.grid,
                property: f.visible,
                previous: PropertyValue::Bool(true),
                value: PropertyValue::Bool(false),
            }]
        );
        let model = f.ui.property_grid_model(f.grid).unwrap();
        assert_eq!(model.value(f.visible), Some(&PropertyValue::Bool(false)));
        assert!(model.is_modified(f.visible));

        let combo = editor(&f, f.align);
        let events = user(
            &mut f,
            UiEvent::SelectionChanged {
                widget_id: combo,
                selected: Some("End".into()),
                index: Some(2),
            },
        );
        assert!(matches!(
            grid_events(&events).as_slice(),
            [UiEvent::PropertyChanged {
                value: PropertyValue::Enum { selected: 2, .. },
                ..
            }]
        ));

        let list = editor(&f, f.borders);
        let events = user(
            &mut f,
            UiEvent::MultiSelectionChanged {
                widget_id: list,
                indices: vec![1, 0],
            },
        );
        assert!(matches!(
            grid_events(&events).as_slice(),
            [UiEvent::PropertyChanged { value: PropertyValue::Flags { selected, .. }, .. }]
                if selected == &vec![0, 1]
        ));

        let date = editor(&f, f.due);
        let events = user(
            &mut f,
            UiEvent::DateChanged {
                widget_id: date,
                iso_date: "2027-01-15".into(),
            },
        );
        assert!(matches!(
            grid_events(&events).as_slice(),
            [UiEvent::PropertyChanged { value: PropertyValue::Date(date), .. }] if date == "2027-01-15"
        ));

        let color = editor(&f, f.tint);
        let events = user(
            &mut f,
            UiEvent::ColorSelected {
                widget_id: color,
                color: Some(Rgba::rgb(255, 0, 0)),
            },
        );
        assert!(matches!(
            grid_events(&events).as_slice(),
            [UiEvent::PropertyChanged { value: PropertyValue::Color(c), .. }] if *c == Color::rgb(255, 0, 0)
        ));
        assert_eq!(f.ui.text(color).unwrap(), "#FF0000");

        // A cancelled color panel changes nothing.
        let events = user(
            &mut f,
            UiEvent::ColorSelected {
                widget_id: color,
                color: None,
            },
        );
        assert!(grid_events(&events).is_empty());
    }

    #[test]
    fn text_editors_parse_on_submit_and_on_focus_loss() {
        let mut f = fixture();
        let width = editor(&f, f.width);
        let events = user(
            &mut f,
            UiEvent::TextSubmitted {
                widget_id: width,
                text: "wide".into(),
            },
        );
        assert!(matches!(
            grid_events(&events).as_slice(),
            [UiEvent::PropertyEditRejected { property, .. }] if *property == f.width
        ));
        assert_eq!(f.ui.text(width).unwrap(), "320", "editor restored");
        assert_eq!(
            f.ui.property_grid_model(f.grid).unwrap().value(f.width),
            Some(&PropertyValue::Int(320))
        );

        let events = user(
            &mut f,
            UiEvent::TextSubmitted {
                widget_id: width,
                text: " 480 ".into(),
            },
        );
        assert!(matches!(
            grid_events(&events).as_slice(),
            [UiEvent::PropertyChanged {
                value: PropertyValue::Int(480),
                ..
            }]
        ));
        assert_eq!(
            f.ui.text(width).unwrap(),
            "480",
            "editor shows the stored form"
        );

        let opacity = editor(&f, f.opacity);
        user(
            &mut f,
            UiEvent::TextChanged {
                widget_id: opacity,
                text: "0.75".into(),
            },
        );
        let events = user(
            &mut f,
            UiEvent::FocusChanged {
                widget_id: opacity,
                focused: false,
            },
        );
        assert!(matches!(
            grid_events(&events).as_slice(),
            [UiEvent::PropertyChanged { value: PropertyValue::Float(v), .. }] if *v == 0.75
        ));

        // Losing focus without a change reports nothing.
        let events = user(
            &mut f,
            UiEvent::FocusChanged {
                widget_id: opacity,
                focused: false,
            },
        );
        assert!(grid_events(&events).is_empty());
    }

    #[test]
    fn enter_commits_and_escape_restores_text_editors() {
        let mut f = fixture();
        let title = editor(&f, f.title);
        user(
            &mut f,
            UiEvent::TextChanged {
                widget_id: title,
                text: "Draft".into(),
            },
        );
        let escape = UiEvent::KeyDown {
            widget_id: title,
            key: "Escape".into(),
            ctrl: false,
            shift: false,
            alt: false,
        };
        assert!(grid_events(&user(&mut f, escape)).is_empty());
        assert_eq!(f.ui.text(title).unwrap(), "Untitled");
        user(
            &mut f,
            UiEvent::TextChanged {
                widget_id: title,
                text: "Report".into(),
            },
        );
        let enter = UiEvent::KeyDown {
            widget_id: title,
            key: "Enter".into(),
            ctrl: false,
            shift: false,
            alt: false,
        };
        assert!(matches!(
            grid_events(&user(&mut f, enter)).as_slice(),
            [UiEvent::PropertyChanged { value: PropertyValue::Text(t), .. }] if t == "Report"
        ));
    }

    #[test]
    fn echoes_of_the_stored_value_are_silent() {
        let mut f = fixture();
        let check = editor(&f, f.visible);
        let events = user(
            &mut f,
            UiEvent::Toggled {
                widget_id: check,
                checked: true,
            },
        );
        assert!(grid_events(&events).is_empty());
        assert!(!f
            .ui
            .property_grid_model(f.grid)
            .unwrap()
            .is_modified(f.visible));
    }

    #[test]
    fn read_only_rows_reject_edits_that_reach_them() {
        let mut f = fixture();
        let locked = editor(&f, f.locked);
        let events = user(
            &mut f,
            UiEvent::TextSubmitted {
                widget_id: locked,
                text: "other".into(),
            },
        );
        assert!(matches!(
            grid_events(&events).as_slice(),
            [UiEvent::PropertyEditRejected { property, .. }] if *property == f.locked
        ));
        assert_eq!(f.ui.text(locked).unwrap(), "node-7");
    }

    #[test]
    fn veto_mode_waits_for_the_application() {
        let mut f = fixture();
        f.ui.set_property_grid_veto(f.grid, true).unwrap();
        let title = editor(&f, f.title);
        let events = user(
            &mut f,
            UiEvent::TextSubmitted {
                widget_id: title,
                text: "Draft".into(),
            },
        );
        let token = match grid_events(&events).as_slice() {
            [UiEvent::PropertyChanging {
                token, proposed, ..
            }] => {
                assert_eq!(proposed, &PropertyValue::Text("Draft".into()));
                *token
            }
            other => panic!("expected one PropertyChanging, got {other:?}"),
        };
        assert_eq!(
            f.ui.property_grid_model(f.grid).unwrap().value(f.title),
            Some(&PropertyValue::Text("Untitled".into()))
        );
        f.ui.resolve_property_change(f.grid, token, true).unwrap();
        let events: Vec<_> = std::iter::from_fn(|| f.ui.poll_event().unwrap()).collect();
        assert!(matches!(
            grid_events(&events).as_slice(),
            [UiEvent::PropertyChanged { value: PropertyValue::Text(t), .. }] if t == "Draft"
        ));
        assert!(
            f.ui.resolve_property_change(f.grid, token, true).is_err(),
            "tokens are one-shot"
        );

        let events = user(
            &mut f,
            UiEvent::TextSubmitted {
                widget_id: title,
                text: "Final".into(),
            },
        );
        let Some(UiEvent::PropertyChanging { token, .. }) = grid_events(&events).pop() else {
            panic!("expected a staged change");
        };
        f.ui.resolve_property_change(f.grid, token, false).unwrap();
        let events: Vec<_> = std::iter::from_fn(|| f.ui.poll_event().unwrap()).collect();
        assert!(matches!(
            grid_events(&events).as_slice(),
            [UiEvent::PropertyEditRejected { reason, .. }] if reason == "vetoed"
        ));
        assert_eq!(
            f.ui.text(title).unwrap(),
            "Draft",
            "editor shows the stored value"
        );
    }

    #[test]
    fn programmatic_updates_are_silent_and_refresh_editors_in_place() {
        let mut f = fixture();
        let width = editor(&f, f.width);
        f.ui.set_property_grid_value(f.grid, f.width, PropertyValue::Int(99))
            .unwrap();
        assert_eq!(f.ui.text(width).unwrap(), "99");
        f.ui.update_property_grid(f.grid, |model| {
            model
                .set_value(f.visible, PropertyValue::Bool(false))
                .unwrap();
            model.set_enabled(f.title, false).unwrap();
        })
        .unwrap();
        assert_eq!(
            editor(&f, f.width),
            width,
            "value-only updates keep widgets"
        );
        assert!(!f.ui.is_checked(editor(&f, f.visible)).unwrap());
        assert_eq!(
            f.ui.widget(editor(&f, f.title)).unwrap().enabled,
            Some(false)
        );
        let events: Vec<_> = std::iter::from_fn(|| f.ui.poll_event().unwrap()).collect();
        assert!(grid_events(&events).is_empty());
        assert!(f
            .ui
            .set_property_grid_value(f.grid, f.locked, PropertyValue::Text("x".into()))
            .is_err());
    }

    #[test]
    fn structure_changes_rebuild_rows() {
        let mut f = fixture();
        let layout = f.layout;
        let added =
            f.ui.update_property_grid(f.grid, |model| {
                model.add_property(
                    Some(layout),
                    "Height",
                    PropertyEditor::Numeric,
                    PropertyValue::Uint(200),
                )
            })
            .unwrap()
            .unwrap();
        assert_eq!(f.ui.text(editor(&f, added)).unwrap(), "200");

        f.ui.set_property_expanded(f.grid, f.layout, false).unwrap();
        assert!(f
            .ui
            .property_grid_editor(f.grid, f.width)
            .unwrap()
            .is_none());
        assert!(f.ui.property_grid_row(f.grid, f.layout).unwrap().is_some());
        f.ui.set_property_expanded(f.grid, f.layout, true).unwrap();
        assert!(f
            .ui
            .property_grid_editor(f.grid, f.width)
            .unwrap()
            .is_some());

        let before = f.ui.widget_count();
        f.ui.set_property_grid_projection(f.grid, ProjectionMode::CategoryFree)
            .unwrap();
        assert!(f.ui.property_grid_row(f.grid, f.layout).unwrap().is_none());
        assert_eq!(
            f.ui.widget_count(),
            before - 2,
            "two category frames dropped"
        );
        assert_eq!(
            f.ui.property_grid_projection(f.grid).unwrap(),
            ProjectionMode::CategoryFree
        );
        f.ui.set_property_grid_projection(f.grid, ProjectionMode::Categorized)
            .unwrap();
        assert_eq!(f.ui.widget_count(), before);
    }

    #[test]
    fn focus_selects_and_label_width_applies() {
        let mut f = fixture();
        let title = editor(&f, f.title);
        let events = user(
            &mut f,
            UiEvent::FocusChanged {
                widget_id: title,
                focused: true,
            },
        );
        assert_eq!(
            grid_events(&events),
            vec![UiEvent::PropertySelected {
                widget_id: f.grid,
                property: Some(f.title),
            }]
        );
        f.ui.set_property_grid_label_width(f.grid, 200).unwrap();
        assert_eq!(f.ui.property_grid_label_width(f.grid).unwrap(), 200);
        let label = f.ui.property_grids.grids[&f.grid].rows[&f.title]
            .label
            .unwrap();
        assert_eq!(
            f.ui.layout_style(label).unwrap().size.width,
            crate::layout::Dimension::Length(200.0)
        );
        assert!(f.ui.set_property_grid_label_width(f.grid, 0).is_err());
    }

    #[test]
    fn removing_the_grid_forgets_its_editors() {
        let mut f = fixture();
        let check = editor(&f, f.visible);
        f.ui.remove(f.grid).unwrap();
        assert!(!f.ui.is_property_grid(f.grid));
        assert!(f.ui.property_grid_model(f.grid).is_err());
        f.ui.backend_mut().push_event(UiEvent::Toggled {
            widget_id: check,
            checked: false,
        });
        while f.ui.poll_event().unwrap().is_some() {}
    }

    #[test]
    fn a_model_with_only_an_empty_category_builds() {
        let mut ui = Ui::new(MockBackend::default());
        let mut model = PropertyModel::new();
        model.add_category(None, "Empty").unwrap();
        assert!(ui.create_property_grid(model).is_ok());
    }

    #[test]
    fn text_round_trips_for_every_value_type() {
        let values = [
            PropertyValue::Text("a b".into()),
            PropertyValue::Int(-5),
            PropertyValue::Uint(7),
            PropertyValue::Float(1.25),
            PropertyValue::Bool(true),
            PropertyValue::Color(Color::rgb(1, 2, 255)),
            PropertyValue::Path("/tmp/x".into()),
            PropertyValue::Date("2026-01-02".into()),
            PropertyValue::Enum {
                selected: 1,
                options: vec!["a".into(), "b".into()],
            },
            PropertyValue::Flags {
                selected: vec![0, 2],
                options: vec!["x".into(), "y".into(), "z".into()],
            },
            PropertyValue::Aggregate(vec![PropertyValue::Int(3), PropertyValue::Float(4.5)]),
        ];
        for value in values {
            let text = format_property_value(&value);
            assert_eq!(
                parse_property_text(&value, &text),
                Ok(value.clone()),
                "{text}"
            );
        }
        assert!(parse_property_text(&PropertyValue::Uint(1), "-1").is_err());
        assert!(parse_property_text(&PropertyValue::Float(1.0), "inf").is_err());
        assert!(parse_property_text(&PropertyValue::Color(Color::rgb(0, 0, 0)), "#12345").is_err());
        assert!(parse_property_text(
            &PropertyValue::Aggregate(vec![PropertyValue::Int(1)]),
            "1, 2"
        )
        .is_err());
    }
}