facet-egui 0.0.2

An egui inspector/editor widget for any type that implements Facet
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
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
#![allow(clippy::too_many_arguments)]

use std::{borrow::Cow, ops::DerefMut};

use derive_more::{Deref, DerefMut as DeriveDerefMut, From};
use egui::{Align, Checkbox, Color32, Id, Layout, Response, TextEdit, Ui, UiBuilder, WidgetText};
use facet::{Def, Facet, ListDef, OptionDef, ScalarType, Type, UserType};
use facet_reflect::{
    HasFields, Partial, Peek, PeekEnum, PeekListLike, PeekMap, PeekOption, PeekPointer, PeekStruct,
    PeekTuple, Poke, PokeEnum, PokeList, PokeStruct,
};

use crate::{
    Attr, MaybeMut,
    layout::{ProbeHeader, ProbeLayout},
    maybe_mut::{Guard, MakeLockErrorKind},
};

/// Returns `true` if the given attributes slice contains `Attr::Skip`.
fn has_egui_skip(attributes: &[facet::Attr]) -> bool {
    attributes
        .iter()
        .filter_map(|a| a.get_as::<crate::Attr>())
        .any(|a| matches!(a, Attr::Skip))
}

/// Returns `true` if the given attributes slice contains `Attr::AsDisplay`.
fn has_egui_as_display(attributes: &[facet::Attr]) -> bool {
    attributes
        .iter()
        .any(|a| matches!((a.ns, a.key), (Some("egui"), "as_display")))
}

/// Returns the `Attr::Rename` value from the attributes, if present.
fn egui_rename(attributes: &[facet::Attr]) -> Option<&'static str> {
    attributes
        .iter()
        .filter_map(|a| a.get_as::<crate::Attr>())
        .find_map(|a| match a {
            Attr::Rename(name) => Some(*name),
            _ => None,
        })
}

/// Returns the display name for a field: uses `egui::rename` if present,
/// otherwise falls back to `effective_name()`.
fn field_display_name(field: &facet::Field) -> String {
    egui_rename(field.attributes)
        .unwrap_or_else(|| field.effective_name())
        .to_owned()
}

/// Returns the display name for a shape: uses `egui::rename` if present,
/// otherwise falls back to `effective_name()`.
fn shape_display_name(shape: &facet::Shape) -> &str {
    egui_rename(shape.attributes).unwrap_or_else(|| shape.effective_name())
}

fn should_render_as_display(shape: &facet::Shape, attributes: &[facet::Attr]) -> bool {
    has_egui_as_display(attributes) || has_egui_as_display(shape.attributes)
}

/// The container that stores a [`MaybeMut`] of the type `T` that should be shown
/// in the [`Ui`](egui::Ui)
#[must_use = "use [`FacetProbe::show`] to display the probe in the [`Ui`]"]
#[derive(Deref, DeriveDerefMut)]
pub struct FacetProbe<'mem, 'facet> {
    header: Option<WidgetText>,
    id: Option<Id>,
    read_only: bool,
    expand_all: bool,
    /// SAFETY: if used, there is a high chance what you do is unsound.
    ///
    /// If you use this, you will have to manually ensure your variances are
    /// okay for use with reborrowing. Normally, this is determined by facet but
    /// there may be cases where a type does not implement Facet or has opaque
    /// parts that would (if used with facet) be ok.
    force_reborrow: bool,
    #[deref]
    #[deref_mut]
    inner: MaybeMut<'mem, 'facet>,
}

#[derive(Debug, From)]
pub enum MaybeMutT<'mem, T> {
    Not(&'mem T),
    Mut(&'mem mut T),
}

impl<'mem, 'facet> FacetProbe<'mem, 'facet> {
    pub fn readonly(self) -> Self {
        Self {
            read_only: true,
            ..self
        }
    }

    pub fn expand_all(self) -> Self {
        Self {
            expand_all: true,
            ..self
        }
    }

    pub fn with_header(mut self, label: impl Into<WidgetText>) -> Self {
        self.header = Some(label.into());
        self
    }

    /// Set a stable egui id source for this probe.
    ///
    /// Use this when the probe can move in the UI hierarchy (e.g. draggable tabs),
    /// so collapse/expand state remains stable.
    pub fn with_id_source(mut self, id_source: impl std::hash::Hash) -> Self {
        self.id = Some(Id::new(id_source));
        self
    }

    /// # Safety
    ///
    /// If used, there is a high chance what you do is unsound.
    ///
    /// If you use this, you will have to manually ensure your variances are
    /// okay for use with reborrowing. Normally, this is determined by facet but
    /// there may be cases where a type does not implement Facet or has opaque
    /// parts that would (if used with facet) be ok.
    pub unsafe fn force_reborrow(self) -> Self {
        Self {
            force_reborrow: true,
            ..self
        }
    }

    pub fn new_peek(value: Peek<'mem, 'facet>) -> Self {
        Self {
            header: None,
            id: None,
            read_only: true,
            expand_all: false,
            force_reborrow: false,
            inner: MaybeMut::Not(value),
        }
    }

    pub fn new_poke(value: Poke<'mem, 'facet>) -> Self {
        Self {
            header: None,
            id: None,
            read_only: false,
            expand_all: false,
            force_reborrow: false,
            inner: MaybeMut::Mut(value),
        }
    }

    pub fn new<T>(value: impl Into<MaybeMutT<'mem, T>>) -> Self
    where
        T: Facet<'facet> + 'mem,
    {
        let v: MaybeMutT<'mem, T> = value.into();
        let inner: MaybeMut = match v {
            MaybeMutT::Mut(v) => Poke::new(v).into(),
            MaybeMutT::Not(v) => Peek::new(v).into(),
        };
        Self {
            header: None,
            id: None,
            read_only: false,
            expand_all: false,
            force_reborrow: false,
            inner,
        }
    }

    pub fn show<'lock>(self, ui: &mut Ui) -> Response
    where
        'mem: 'lock,
    {
        // Container-level skip: hide the entire probe
        if has_egui_skip(self.shape().attributes) {
            return ui.label("");
        }

        let mut changed = false;

        let mut attributes = self
            .shape()
            .attributes
            .iter()
            .filter_map(|x| x.get_as::<crate::Attr>());
        let readonly = attributes.any(|x| matches!(x, Attr::Readonly)) || self.read_only;

        // Check for expand_all attribute (or use self.expand_all)
        let expand_all = self.expand_all
            || self
                .shape()
                .attributes
                .iter()
                .filter_map(|x| x.get_as::<crate::Attr>())
                .any(|x| matches!(x, Attr::ExpandAll));

        let mut guard: Guard<'lock, 'facet> = if readonly {
            let Ok(read) = self.inner.read() else {
                return ui.colored_label(Color32::RED, "Read Failure");
            };
            read
        } else {
            match self.inner.write() {
                Ok(write) => write,
                // fallback to readonly
                Err(e) if matches!(e.kind, MakeLockErrorKind::NotLockable) => {
                    let Ok(read) = MaybeMut::Not(e.unchanged).read() else {
                        return ui.colored_label(Color32::RED, "Fallback Read Failure");
                    };
                    read
                }
                Err(e) if matches!(e.kind, MakeLockErrorKind::LockFailure) => {
                    return ui.colored_label(Color32::RED, "Lock Failure");
                }
                Err(e) => {
                    return ui.colored_label(Color32::RED, format!("Error: {e}"));
                }
            }
        };

        let maybe_mut = guard.deref_mut();
        // Anchor persistent widget state to a probe root id that does not depend
        // on current Ui ancestry, so tab moves don't reset collapsed sections.
        let ptr_salt = maybe_mut.as_peek().data().as_byte_ptr() as usize;
        let probe_id = self
            .id
            .unwrap_or_else(|| Id::new(("facet_egui::probe", ptr_salt)));
        let mut r = ui
            .push_id(probe_id, |ui| {
                let child_ui = &mut ui.new_child(
                    UiBuilder::new()
                        .max_rect(ui.max_rect())
                        .layout(Layout::top_down(Align::Min)),
                );

                let mut layout = ProbeLayout::load(child_ui.ctx(), probe_id.with("layout"));
                let root_as_display = should_render_as_display(maybe_mut.shape(), &[]);

                if let Some(label) = self.header {
                    // Show with a top-level header (like Probe::new(x).with_header("name"))
                    let mut header = show_header(
                        label,
                        maybe_mut,
                        &mut layout,
                        0,
                        child_ui,
                        probe_id.with("root"),
                        &mut changed,
                        self.force_reborrow,
                        expand_all,
                        root_as_display,
                    );

                    if header.openness > 0.0 && !root_as_display {
                        show_body(
                            maybe_mut,
                            &mut header,
                            &mut layout,
                            0,
                            child_ui,
                            probe_id.with("root"),
                            &mut changed,
                            self.force_reborrow,
                            expand_all,
                            root_as_display,
                        );
                    }

                    header.store(child_ui.ctx());
                } else {
                    // Show directly without a top-level header (table of fields)
                    show_body_direct(
                        maybe_mut,
                        &mut layout,
                        0,
                        child_ui,
                        probe_id.with("root"),
                        &mut changed,
                        self.force_reborrow,
                        expand_all,
                        root_as_display,
                    );
                }

                layout.store(child_ui.ctx());

                let final_rect = child_ui.min_rect();
                ui.advance_cursor_after_rect(final_rect);
            })
            .response;

        drop(guard);

        if changed {
            r.mark_changed();
            ui.ctx().request_repaint();
        }

        r
    }
}

// ---------------------------------------------------------------------------
// Core layout functions (egui-probe style)
// ---------------------------------------------------------------------------

/// Returns true if the given `MaybeMut` has inner fields/items to display
/// (i.e. it should get a collapse arrow).
fn has_inner(value: &MaybeMut<'_, '_>) -> bool {
    let peek = value.as_peek();
    // Structs with fields, enums with variant fields, lists, maps, options
    // with inner, tuples, sets, pointers to inner — all have inner content.
    // Option/Result must be checked before enum, since they also match into_enum().
    if let Ok(opt) = peek.into_option()
        && let Some(inner) = opt.value()
    {
        return has_inner(&MaybeMut::Not(inner));
    }
    if let Ok(s) = peek.into_struct() {
        return s.field_count() > 0;
    }
    if let Ok(e) = peek.into_enum()
        && let Ok(v) = e.active_variant()
    {
        return !v.data.fields.is_empty();
    }
    if let Ok(l) = peek.into_list_like() {
        return !l.is_empty();
    }
    if let Ok(m) = peek.into_map() {
        return !m.is_empty();
    }
    if let Ok(t) = peek.into_tuple() {
        return !t.is_empty();
    }
    if let Ok(p) = peek.into_pointer()
        && let Some(inner) = p.borrow_inner()
    {
        return has_inner(&MaybeMut::Not(inner));
    }
    false
}

/// Show a single row: label on the left, inline value widget on the right.
/// Returns the ProbeHeader for the row (which tracks collapse state).
#[expect(clippy::too_many_arguments)]
fn show_header(
    label: impl Into<WidgetText>,
    value: &mut MaybeMut<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    ui: &mut Ui,
    id: Id,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
    as_display: bool,
) -> ProbeHeader {
    let mut header = ProbeHeader::load(ui.ctx(), id);
    let row_has_inner = !as_display && has_inner(value);
    header.set_has_inner(row_has_inner);
    if !row_has_inner {
        header.set_open(false);
    }

    if expand_all && row_has_inner {
        header.set_open(true);
    }

    ui.horizontal(|ui| {
        let label_response = layout.inner_label_ui(indent, id.with("label"), ui, |ui| {
            if header.has_inner() {
                header.collapse_button(ui);
            }
            ui.label(label)
        });

        layout.inner_value_ui(id.with("value"), ui, |ui| {
            *changed |= show_inline_value(value, ui, id, force_reborrow, as_display)
                .labelled_by(label_response.id)
                .changed();
        });
    });

    header
}

/// Show the collapsible body (the inner fields/items) below a header row.
#[expect(clippy::too_many_arguments)]
fn show_body(
    value: &mut MaybeMut<'_, '_>,
    header: &mut ProbeHeader,
    layout: &mut ProbeLayout,
    indent: usize,
    ui: &mut Ui,
    id: Id,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
    as_display: bool,
) {
    if as_display {
        header.set_has_inner(false);
        header.set_open(false);
        return;
    }

    let cursor = ui.cursor();
    let table_rect = egui::Rect::from_min_max(
        egui::pos2(cursor.min.x, cursor.min.y - header.body_shift()),
        ui.max_rect().max,
    );

    let mut table_ui = ui.new_child(
        UiBuilder::new()
            .max_rect(table_rect)
            .layout(Layout::top_down(Align::Min))
            .id_salt(id.with("body")),
    );
    table_ui.set_clip_rect(
        ui.clip_rect()
            .intersect(egui::Rect::everything_below(ui.min_rect().max.y)),
    );

    let got_inner = show_inner_rows(
        value,
        layout,
        indent + 1,
        id,
        &mut table_ui,
        changed,
        force_reborrow,
        expand_all,
    );
    header.set_has_inner(got_inner);

    let final_table_rect = table_ui.min_rect();
    ui.advance_cursor_after_rect(final_table_rect);
    let table_height = ui.cursor().min.y - table_rect.min.y;
    header.set_body_height(table_height);
}

/// Show the body directly (no collapse header wrapper). Used when there is no
/// top-level header.
fn show_body_direct(
    value: &mut MaybeMut<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    ui: &mut Ui,
    id: Id,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
    as_display: bool,
) {
    if as_display {
        *changed |= show_inline_value(value, ui, id, force_reborrow, true).changed();
        return;
    }

    let cursor = ui.cursor();
    let table_rect =
        egui::Rect::from_min_max(egui::pos2(cursor.min.x, cursor.min.y), ui.max_rect().max);

    let mut table_ui = ui.new_child(
        UiBuilder::new()
            .max_rect(table_rect)
            .layout(Layout::top_down(Align::Min))
            .id_salt(id.with("body")),
    );
    table_ui.set_clip_rect(
        ui.clip_rect()
            .intersect(egui::Rect::everything_below(ui.min_rect().max.y)),
    );

    show_inner_rows(
        value,
        layout,
        indent + 1,
        id,
        &mut table_ui,
        changed,
        force_reborrow,
        expand_all,
    );

    let final_table_rect = table_ui.min_rect();
    ui.advance_cursor_after_rect(final_table_rect);
}

/// Iterate over the "inner" rows of a value and render each as a header+body pair.
/// Returns `true` if any inner rows were emitted.
fn show_inner_rows(
    value: &mut MaybeMut<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    match value {
        MaybeMut::Mut(poke) => show_inner_rows_poke(
            poke,
            layout,
            indent,
            id,
            ui,
            changed,
            force_reborrow,
            expand_all,
        ),
        MaybeMut::Not(peek) => show_inner_rows_peek(
            *peek,
            layout,
            indent,
            id,
            ui,
            changed,
            force_reborrow,
            expand_all,
        ),
    }
}

/// Attempt to write-lock a child [`MaybeMut`]. If the child is already
/// [`MaybeMut::Mut`] or wraps a lockable pointer (e.g. `RwLock`), this
/// returns a [`Guard`] with mutable access. Otherwise it falls back to
/// a read lock.
fn lock_child<'mem, 'facet>(child: MaybeMut<'mem, 'facet>) -> Option<Guard<'mem, 'facet>> {
    match child.write() {
        Ok(guard) => Some(guard),
        Err(e) if matches!(e.kind, MakeLockErrorKind::NotLockable) => {
            MaybeMut::Not(e.unchanged).read().ok()
        }
        Err(_) => None,
    }
}

fn show_inner_rows_poke(
    poke: &mut Poke<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    // Option/Result have Def::Option/Def::Result but Type::User(UserType::Enum),
    // so check Def before is_enum() to avoid misrouting.
    if let Def::Option(option_def) = poke.shape().def {
        return show_inner_rows_poke_option(
            poke,
            option_def,
            layout,
            indent,
            id,
            ui,
            changed,
            force_reborrow,
            expand_all,
        );
    }

    // For enums, we can use into_enum directly without reborrowing,
    // since PokeEnum.field() takes &mut self.
    if poke.is_enum() {
        let enu_poke = match poke.try_reborrow() {
            Some(rb) => rb,
            None if force_reborrow => unsafe {
                Poke::from_raw_parts(poke.data_mut(), poke.shape())
            },
            None => {
                return show_inner_rows_peek(
                    poke.as_peek(),
                    layout,
                    indent,
                    id,
                    ui,
                    changed,
                    force_reborrow,
                    expand_all,
                );
            }
        };
        if let Ok(enu) = enu_poke.into_enum() {
            return show_inner_rows_poke_enum(
                enu,
                layout,
                indent,
                id,
                ui,
                changed,
                force_reborrow,
                expand_all,
            );
        }
        return show_inner_rows_peek(
            poke.as_peek(),
            layout,
            indent,
            id,
            ui,
            changed,
            force_reborrow,
            expand_all,
        );
    }

    // For structs, reborrow to get mutable field access
    if poke.is_struct() {
        let reborrow = match poke.try_reborrow() {
            Some(rb) => rb,
            None if force_reborrow => unsafe {
                Poke::from_raw_parts(poke.data_mut(), poke.shape())
            },
            None => {
                return show_inner_rows_peek(
                    poke.as_peek(),
                    layout,
                    indent,
                    id,
                    ui,
                    changed,
                    force_reborrow,
                    expand_all,
                );
            }
        };
        if let Ok(struc) = reborrow.into_struct() {
            return show_inner_rows_poke_struct(
                struc,
                layout,
                indent,
                id,
                ui,
                changed,
                force_reborrow,
                expand_all,
            );
        }
    }

    let data_mut = poke.data_mut();
    let shape = poke.shape();
    let poke = match poke.try_reborrow() {
        Some(rb) => rb,
        None if force_reborrow => unsafe { Poke::from_raw_parts(poke.data_mut(), poke.shape()) },
        None => {
            return show_inner_rows_peek(
                poke.as_peek(),
                layout,
                indent,
                id,
                ui,
                changed,
                force_reborrow,
                expand_all,
            );
        }
    };
    if let Ok(poke_list) = poke.into_list() {
        show_inner_rows_poke_list(
            poke_list,
            layout,
            indent,
            id,
            ui,
            changed,
            force_reborrow,
            expand_all,
        )
    } else {
        // restore old poke
        // SAFETY: this is ok because there still is only one access to poke due to the if
        // branch not being reached
        let poke = unsafe { Poke::from_raw_parts(data_mut, shape) };
        // For list, list, map, tuple, option, pointer — fall through to peek
        ui.weak("fallback");
        ui.weak("fallback");
        show_inner_rows_peek(
            poke.as_peek(),
            layout,
            indent,
            id,
            ui,
            changed,
            force_reborrow,
            expand_all,
        )
    }
}

fn show_inner_rows_poke_list(
    mut list: PokeList<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    let len = list.len();
    if len == 0 {
        return false;
    }
    for idx in 0..len {
        let label = format!("[{idx}]");
        if let Some(field_poke) = list.get_mut(idx) {
            let row_id = id.with(("list", idx));
            let Some(mut guard) = lock_child(MaybeMut::Mut(field_poke)) else {
                continue;
            };
            let child = &mut *guard;
            let as_display = should_render_as_display(child.shape(), &[]);
            let mut header = show_header(
                &label,
                child,
                layout,
                indent,
                ui,
                row_id,
                changed,
                force_reborrow,
                expand_all,
                as_display,
            );
            if header.openness > 0.0 && !as_display {
                show_body(
                    child,
                    &mut header,
                    layout,
                    indent,
                    ui,
                    row_id,
                    changed,
                    force_reborrow,
                    expand_all,
                    as_display,
                );
            }
            header.store(ui.ctx());
        }
    }
    true
}

fn show_inner_rows_poke_struct(
    mut struc: PokeStruct<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    let count = struc.field_count();
    if count == 0 {
        return false;
    }
    let mut got_inner = false;
    for idx in 0..count {
        let field = &struc.ty().fields[idx];
        if has_egui_skip(field.attributes) {
            continue;
        }
        if let Ok(field_poke) = struc.field(idx) {
            let row_id = id.with(("struct", idx));
            let Some(mut guard) = lock_child(MaybeMut::Mut(field_poke)) else {
                continue;
            };
            let child = &mut *guard;
            if field.is_flattened() {
                ui.push_id(row_id, |ui| {
                    got_inner |= show_inner_rows(
                        child,
                        layout,
                        indent,
                        row_id,
                        ui,
                        changed,
                        force_reborrow,
                        expand_all,
                    );
                });
                continue;
            }
            got_inner = true;
            let field_name = field_display_name(field);
            let as_display = should_render_as_display(child.shape(), field.attributes);
            let mut header = show_header(
                &field_name,
                child,
                layout,
                indent,
                ui,
                row_id,
                changed,
                force_reborrow,
                expand_all,
                as_display,
            );
            if header.openness > 0.0 && !as_display {
                show_body(
                    child,
                    &mut header,
                    layout,
                    indent,
                    ui,
                    row_id,
                    changed,
                    force_reborrow,
                    expand_all,
                    as_display,
                );
            }
            header.store(ui.ctx());
        }
    }
    got_inner
}

fn show_inner_rows_poke_enum(
    mut enu: PokeEnum<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    let variant = match enu.active_variant() {
        Ok(v) => v,
        Err(_) => return false,
    };
    let field_count = variant.data.fields.len();
    if field_count == 0 {
        return false;
    }
    let mut got_inner = false;
    for idx in 0..field_count {
        let field = &variant.data.fields[idx];
        if has_egui_skip(field.attributes) {
            continue;
        }
        if let Ok(Some(field_poke)) = enu.field(idx) {
            let row_id = id.with(("enum", idx));
            let Some(mut guard) = lock_child(MaybeMut::Mut(field_poke)) else {
                continue;
            };
            let child = &mut *guard;
            if field.is_flattened() {
                ui.push_id(row_id, |ui| {
                    got_inner |= show_inner_rows(
                        child,
                        layout,
                        indent,
                        row_id,
                        ui,
                        changed,
                        force_reborrow,
                        expand_all,
                    );
                });
                continue;
            }
            let field_name = field_display_name(field);
            let as_display = should_render_as_display(child.shape(), field.attributes);
            let mut header = show_header(
                &field_name,
                child,
                layout,
                indent,
                ui,
                row_id,
                changed,
                force_reborrow,
                expand_all,
                as_display,
            );
            if header.openness > 0.0 && !as_display {
                show_body(
                    child,
                    &mut header,
                    layout,
                    indent,
                    ui,
                    row_id,
                    changed,
                    force_reborrow,
                    expand_all,
                    as_display,
                );
            }
            header.store(ui.ctx());
        }
    }
    got_inner
}

fn show_inner_rows_peek(
    peek: Peek<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    if let Ok(opt) = peek.into_option() {
        show_inner_rows_peek_option(
            opt,
            layout,
            indent,
            id,
            ui,
            changed,
            force_reborrow,
            expand_all,
        )
    } else if let Ok(struc) = peek.into_struct() {
        show_inner_rows_peek_struct(
            struc,
            layout,
            indent,
            id,
            ui,
            changed,
            force_reborrow,
            expand_all,
        )
    } else if let Ok(enu) = peek.into_enum() {
        show_inner_rows_peek_enum(
            enu,
            layout,
            indent,
            id,
            ui,
            changed,
            force_reborrow,
            expand_all,
        )
    } else if let Ok(list) = peek.into_list_like() {
        show_inner_rows_peek_list(
            list,
            layout,
            indent,
            id,
            ui,
            changed,
            force_reborrow,
            expand_all,
        )
    } else if let Ok(map) = peek.into_map() {
        show_inner_rows_peek_map(
            map,
            layout,
            indent,
            id,
            ui,
            changed,
            force_reborrow,
            expand_all,
        )
    } else if let Ok(tuple) = peek.into_tuple() {
        show_inner_rows_peek_tuple(
            tuple,
            layout,
            indent,
            id,
            ui,
            changed,
            force_reborrow,
            expand_all,
        )
    } else if let Ok(ptr) = peek.into_pointer() {
        show_inner_rows_peek_pointer(
            ptr,
            layout,
            indent,
            id,
            ui,
            changed,
            force_reborrow,
            expand_all,
        )
    } else {
        false
    }
}

fn show_inner_rows_peek_struct(
    struc: PeekStruct<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    let mut got_inner = false;
    for (idx, (field, value)) in struc.fields().enumerate() {
        let row_id = id.with(("struct", idx));
        if has_egui_skip(field.attributes) {
            continue;
        }
        let Some(mut guard) = lock_child(MaybeMut::Not(value)) else {
            continue;
        };
        let child = &mut *guard;
        if field.is_flattened() {
            ui.push_id(row_id, |ui| {
                got_inner |= show_inner_rows(
                    child,
                    layout,
                    indent,
                    row_id,
                    ui,
                    changed,
                    force_reborrow,
                    expand_all,
                );
            });
            continue;
        }
        got_inner = true;
        let field_name = field_display_name(&field);
        let as_display = should_render_as_display(child.shape(), field.attributes);
        let mut header = show_header(
            &field_name,
            child,
            layout,
            indent,
            ui,
            row_id,
            changed,
            force_reborrow,
            expand_all,
            as_display,
        );
        if header.openness > 0.0 && !as_display {
            show_body(
                child,
                &mut header,
                layout,
                indent,
                ui,
                row_id,
                changed,
                force_reborrow,
                expand_all,
                as_display,
            );
        }
        header.store(ui.ctx());
    }
    got_inner
}

fn show_inner_rows_peek_enum(
    enu: PeekEnum<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    let mut got_inner = false;
    for (idx, (field, value)) in enu.fields().enumerate() {
        let row_id = id.with(("enum", idx));
        if has_egui_skip(field.attributes) {
            continue;
        }
        let Some(mut guard) = lock_child(MaybeMut::Not(value)) else {
            continue;
        };
        let child = &mut *guard;
        if field.is_flattened() {
            ui.push_id(row_id, |ui| {
                got_inner |= show_inner_rows(
                    child,
                    layout,
                    indent,
                    row_id,
                    ui,
                    changed,
                    force_reborrow,
                    expand_all,
                );
            });
            continue;
        }
        got_inner = true;
        let field_name = field_display_name(&field);
        let as_display = should_render_as_display(child.shape(), field.attributes);
        let mut header = show_header(
            &field_name,
            child,
            layout,
            indent,
            ui,
            row_id,
            changed,
            force_reborrow,
            expand_all,
            as_display,
        );
        if header.openness > 0.0 && !as_display {
            show_body(
                child,
                &mut header,
                layout,
                indent,
                ui,
                row_id,
                changed,
                force_reborrow,
                expand_all,
                as_display,
            );
        }
        header.store(ui.ctx());
    }
    got_inner
}

fn show_inner_rows_peek_list(
    list: PeekListLike<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    let mut got_inner = false;
    for (idx, item) in list.iter().enumerate() {
        let row_id = id.with(("list", idx));
        got_inner = true;
        let label = format!("[{idx}]");
        let Some(mut guard) = lock_child(MaybeMut::Not(item)) else {
            continue;
        };
        let child = &mut *guard;
        let as_display = should_render_as_display(child.shape(), &[]);
        let mut header = show_header(
            &label,
            child,
            layout,
            indent,
            ui,
            row_id,
            changed,
            force_reborrow,
            expand_all,
            as_display,
        );
        if header.openness > 0.0 && !as_display {
            show_body(
                child,
                &mut header,
                layout,
                indent,
                ui,
                row_id,
                changed,
                force_reborrow,
                expand_all,
                as_display,
            );
        }
        header.store(ui.ctx());
    }
    got_inner
}

fn show_inner_rows_peek_map(
    map: PeekMap<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    let mut got_inner = false;
    for (idx, (key, value)) in map.iter().enumerate() {
        let row_id = id.with(("map", idx));
        got_inner = true;
        let label = format!("{}", key);
        let Some(mut guard) = lock_child(MaybeMut::Not(value)) else {
            continue;
        };
        let child = &mut *guard;
        let as_display = should_render_as_display(child.shape(), &[]);
        let mut header = show_header(
            &label,
            child,
            layout,
            indent,
            ui,
            row_id,
            changed,
            force_reborrow,
            expand_all,
            as_display,
        );
        if header.openness > 0.0 && !as_display {
            show_body(
                child,
                &mut header,
                layout,
                indent,
                ui,
                row_id,
                changed,
                force_reborrow,
                expand_all,
                as_display,
            );
        }
        header.store(ui.ctx());
    }
    got_inner
}

fn show_inner_rows_peek_option(
    opt: PeekOption<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    if let Some(inner) = opt.value() {
        let Some(mut guard) = lock_child(MaybeMut::Not(inner)) else {
            return false;
        };
        let child = &mut *guard;
        return show_inner_rows(
            child,
            layout,
            indent,
            id.with("option"),
            ui,
            changed,
            force_reborrow,
            expand_all,
        );
    }
    false
}

fn show_inner_rows_peek_tuple(
    tuple: PeekTuple<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    let mut got_inner = false;
    for (idx, (_field, value)) in tuple.fields().enumerate() {
        let row_id = id.with(("tuple", idx));
        got_inner = true;
        let label = format!("[{idx}]");
        let Some(mut guard) = lock_child(MaybeMut::Not(value)) else {
            continue;
        };
        let child = &mut *guard;
        let as_display = should_render_as_display(child.shape(), &[]);
        let mut header = show_header(
            &label,
            child,
            layout,
            indent,
            ui,
            row_id,
            changed,
            force_reborrow,
            expand_all,
            as_display,
        );
        if header.openness > 0.0 && !as_display {
            show_body(
                child,
                &mut header,
                layout,
                indent,
                ui,
                row_id,
                changed,
                force_reborrow,
                expand_all,
                as_display,
            );
        }
        header.store(ui.ctx());
    }
    got_inner
}

fn show_inner_rows_peek_pointer(
    ptr: PeekPointer<'_, '_>,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    if let Some(inner) = ptr.borrow_inner() {
        let Some(mut guard) = lock_child(MaybeMut::Not(inner)) else {
            return false;
        };
        let child = &mut *guard;
        return show_inner_rows(
            child,
            layout,
            indent,
            id.with("ptr"),
            ui,
            changed,
            force_reborrow,
            expand_all,
        );
    }
    false
}

// ---------------------------------------------------------------------------
// Inline value rendering (the right-side widget for a row)
// ---------------------------------------------------------------------------

/// Show the inline (right-side) widget for a value. Returns the Response.
fn show_inline_value(
    value: &mut MaybeMut<'_, '_>,
    ui: &mut Ui,
    id: Id,
    force_reborrow: bool,
    as_display: bool,
) -> Response {
    match value {
        MaybeMut::Mut(poke) => show_inline_poke(poke, ui, id, force_reborrow, as_display),
        MaybeMut::Not(peek) => show_inline_peek(*peek, ui, id, as_display),
    }
}

/// Show inline widget for a mutable value.
fn show_inline_poke(
    poke: &mut Poke<'_, '_>,
    ui: &mut Ui,
    id: Id,
    force_reborrow: bool,
    as_display: bool,
) -> Response {
    if as_display || should_render_as_display(poke.shape(), &[]) {
        return ui.label(format!("{}", poke.as_peek()));
    }

    if let Some(scalar_type) = poke.as_peek().scalar_type() {
        return show_inline_poke_scalar(poke, scalar_type, ui);
    }

    // For non-scalar types, show a type summary label
    // Option/Result have Def::Option/Def::Result but Type::User(UserType::Enum),
    // so check Def before is_enum() to avoid misrouting.
    if let Def::Option(option_def) = poke.shape().def {
        return show_inline_poke_option(poke, option_def, ui, id, force_reborrow);
    }
    if poke.is_enum() {
        return show_inline_poke_enum(poke, ui, id);
    }
    if poke.is_struct() {
        return ui.weak(shape_display_name(poke.shape()));
    }
    if let Def::List(list_def) = poke.shape().def {
        return show_inline_poke_list(poke, list_def, ui);
    }
    if let Ok(map) = poke.as_peek().into_map() {
        return ui.weak(format!("[{}]", map.len()));
    }
    if let Ok(tuple) = poke.as_peek().into_tuple() {
        return ui.weak(format!("({})", tuple.len()));
    }
    if let Ok(ptr) = poke.as_peek().into_pointer()
        && let Some(inner) = ptr.borrow_inner()
    {
        return show_inline_peek(inner, ui, id, false);
    }

    ui.weak(shape_display_name(poke.shape()))
}

/// Show inline widget for a mutable list: `[len]` with +/- buttons.
fn show_inline_poke_list(poke: &mut Poke<'_, '_>, list_def: ListDef, ui: &mut Ui) -> Response {
    let len = poke
        .as_peek()
        .into_list_like()
        .map(|l| l.len())
        .unwrap_or(0);
    let item_shape = list_def.t();
    let has_default = item_shape.is_default();
    let has_push = list_def.push().is_some();
    let has_set_len = list_def.set_len().is_some();

    let mut changed = false;
    let r = ui.horizontal(|ui| {
        ui.weak(format!("[{len}]"));

        if has_push && has_default && ui.small_button("+").clicked() {
            changed |= try_push_default_to_list(poke, list_def);
        }

        if has_set_len && len > 0 && ui.small_button("-").clicked() {
            changed |= try_pop_from_list(poke, list_def, item_shape);
        }
    });

    let mut r = r.response;
    if changed {
        r.mark_changed();
    }
    r
}

/// Push a default-constructed element to the list using `Partial`.
fn try_push_default_to_list(poke: &mut Poke<'_, '_>, list_def: ListDef) -> bool {
    let item_shape = list_def.t();
    let push_fn = match list_def.push() {
        Some(f) => f,
        None => return false,
    };

    // SAFETY: item_shape comes from the ListDef of this poke's shape.
    let partial = match unsafe { Partial::alloc_shape(item_shape) } {
        Ok(p) => p,
        Err(_) => return false,
    };
    let partial = match partial.set_default() {
        Ok(p) => p,
        Err(_) => return false,
    };
    let heap_value = match partial.build() {
        Ok(v) => v,
        Err(_) => return false,
    };

    // push_fn moves the value out via ptr::read — ownership transfers to the list.
    // SAFETY: heap_value contains an initialized, aligned value of the correct item type.
    unsafe {
        let item_ptr = heap_value.peek().data().as_byte_ptr() as *mut u8;
        push_fn(poke.data_mut(), facet::PtrMut::new(item_ptr));
    }
    // The value has been moved into the list. Prevent HeapValue from dropping
    // the (now-moved) inner value. This leaks the HeapValue's backing allocation
    // but is correct per the ListPushFn contract.
    core::mem::forget(heap_value);

    true
}

/// Pop the last element from the list by moving it out, shrinking the Vec,
/// then dropping the extracted element.
fn try_pop_from_list(
    poke: &mut Poke<'_, '_>,
    list_def: ListDef,
    item_shape: &'static facet::Shape,
) -> bool {
    let set_len_fn = match list_def.set_len() {
        Some(f) => f,
        None => return false,
    };
    let len_fn = list_def.vtable.len;
    let get_mut_fn = match list_def.vtable.get_mut {
        Some(f) => f,
        None => return false,
    };
    // SAFETY: poke points to an initialized, aligned list value (Vec<T>).
    // len_fn and get_mut_fn come from the same ListDef as the poke's shape.
    let len = unsafe { len_fn(poke.data_mut().as_const()) };
    if len == 0 {
        return false;
    }

    // SAFETY: poke.shape() is the list's shape (Vec<T>), which get_mut_fn
    // uses to compute element size from type_params[0]. Index is in bounds.
    let Some(last_ptr) = (unsafe { get_mut_fn(poke.data_mut(), len - 1, poke.shape()) }) else {
        return false;
    };

    // SAFETY: After set_len(len - 1) the Vec no longer considers this slot
    // occupied, but its backing buffer is still allocated — last_ptr remains
    // valid. We drop in place, mirroring Vec::pop semantics (shrink length,
    // then drop the element).
    unsafe { set_len_fn(poke.data_mut(), len - 1) };
    unsafe { item_shape.call_drop_in_place(last_ptr) };

    true
}

/// Show inline widget for a mutable option: toggle between None and Some.
fn show_inline_poke_option(
    poke: &mut Poke<'_, '_>,
    option_def: OptionDef,
    ui: &mut Ui,
    id: Id,
    force_reborrow: bool,
) -> Response {
    let is_some = unsafe { (option_def.vtable.is_some)(poke.data_mut().as_const()) };

    let mut changed = false;
    let r = ui.horizontal(|ui| {
        if ui.selectable_label(!is_some, "None").clicked() && is_some {
            // Switch from Some to None
            // SAFETY:
            // According to facet docs, it should be set to a null pointer to
            // set it to Option::None
            // See <https://docs.rs/facet-core/0.44.3/facet_core/type.OptionReplaceWithFn.html>
            unsafe {
                (option_def.vtable.replace_with)(poke.data_mut(), std::ptr::null_mut());
            }
            changed = true;
        }
        if ui.selectable_label(is_some, "Some").clicked() && !is_some {
            // Switch from None to Some(default)
            changed = try_set_option_to_some_default(poke, option_def);
        }
        if is_some {
            let inner_ptr = unsafe { (option_def.vtable.get_value)(poke.data_mut().as_const()) };
            if !inner_ptr.is_null() {
                // SAFETY: We have unique mutable access through poke, and the inner value
                // is stored within the Option's memory. The shape matches the inner type.
                let mut inner_poke = unsafe {
                    Poke::from_raw_parts(facet::PtrMut::new(inner_ptr as *mut u8), option_def.t())
                };
                show_inline_poke(&mut inner_poke, ui, id.with("some"), force_reborrow, false);
            }
        }
    });

    let mut r = r.response;
    if changed {
        r.mark_changed();
    }
    r
}

/// Set an Option from None to Some(T::default()) using the OptionVTable.
fn try_set_option_to_some_default(poke: &mut Poke<'_, '_>, option_def: OptionDef) -> bool {
    let inner_shape = option_def.t();

    // Allocate and default-construct the inner value
    // SAFETY: inner_shape comes from the OptionDef of this poke's shape.
    let partial = match unsafe { Partial::alloc_shape(inner_shape) } {
        Ok(p) => p,
        Err(_) => return false,
    };
    let partial = match partial.set_default() {
        Ok(p) => p,
        Err(_) => return false,
    };
    let heap_value = match partial.build() {
        Ok(v) => v,
        Err(_) => return false,
    };

    // Move the default value into the Option via replace_with.
    // SAFETY: heap_value contains an initialized, aligned value of the correct inner type.
    // replace_with moves from the pointer (ptr::read), so we must forget the heap_value
    // to avoid double-free.
    unsafe {
        let value_ptr = heap_value.peek().data().as_byte_ptr() as *mut u8;
        (option_def.vtable.replace_with)(poke.data_mut(), value_ptr);
    }
    core::mem::forget(heap_value);

    true
}

/// Show inner rows for a mutable Option. When Some, shows the inner value mutably.
fn show_inner_rows_poke_option(
    poke: &mut Poke<'_, '_>,
    option_def: OptionDef,
    layout: &mut ProbeLayout,
    indent: usize,
    id: Id,
    ui: &mut Ui,
    changed: &mut bool,
    force_reborrow: bool,
    expand_all: bool,
) -> bool {
    let is_some = unsafe { (option_def.vtable.is_some)(poke.data_mut().as_const()) };
    if !is_some {
        return false;
    }

    let inner_ptr = unsafe { (option_def.vtable.get_value)(poke.data_mut().as_const()) };
    if inner_ptr.is_null() {
        return false;
    }

    // SAFETY: We have unique mutable access through poke, and the inner value
    // is stored within the Option's memory. The shape matches the inner type.
    let inner_poke =
        unsafe { Poke::from_raw_parts(facet::PtrMut::new(inner_ptr as *mut u8), option_def.t()) };

    let mut child = MaybeMut::Mut(inner_poke);
    show_inner_rows(
        &mut child,
        layout,
        indent,
        id.with("option"),
        ui,
        changed,
        force_reborrow,
        expand_all,
    )
}

/// Show inline widget for a mutable enum: ComboBox to select variant.
fn show_inline_poke_enum(poke: &mut Poke<'_, '_>, ui: &mut Ui, id: Id) -> Response {
    let shape = poke.shape();
    let Type::User(UserType::Enum(enum_type)) = shape.ty else {
        return ui.weak("enum");
    };

    // Get the active variant name (Peek is Copy, variant names are 'static)
    let active_name = poke
        .as_peek()
        .into_enum()
        .ok()
        .and_then(|e| e.active_variant().ok())
        .map(|v| v.effective_name())
        .unwrap_or("?");

    let mut changed = false;
    let r = egui::ComboBox::from_id_salt(id)
        .selected_text(active_name)
        .show_ui(ui, |ui| {
            for (idx, variant) in enum_type.variants.iter().enumerate() {
                let variant_name: &str = variant.effective_name();
                let is_active = variant_name == active_name;
                if ui.selectable_label(is_active, variant_name).clicked()
                    && !is_active
                    && try_change_variant(poke, idx)
                {
                    changed = true;
                }
            }
        });

    let mut r = r.response;
    if changed {
        r.mark_changed();
    }
    r
}

/// Try to change the enum variant by constructing a new value via `Partial`.
///
/// Returns `true` if the variant was successfully changed.
fn try_change_variant(poke: &mut Poke<'_, '_>, variant_idx: usize) -> bool {
    let shape = poke.shape();
    // Build a new enum value with the selected variant using Partial.
    // SAFETY: The shape used is from the provided Poke
    let partial = match unsafe { Partial::alloc_shape(shape) } {
        Ok(p) => p,
        Err(e) => {
            log::debug!("alloc_shape failed: {e}");
            return false;
        }
    };
    // this is the partial of the to be active variant
    let mut partial = match partial.select_nth_variant(variant_idx) {
        Ok(p) => p,
        Err(e) => {
            log::debug!("select_nth_variant failed: {e}");
            return false;
        }
    };

    // Explicitly default each field of the variant.
    // The variant's fields are available from the shape's enum type.
    let Type::User(UserType::Enum(enum_type)) = shape.ty else {
        return false;
    };
    let variant = &enum_type.variants[variant_idx];
    for field_idx in 0..variant.data.fields.len() {
        partial = match partial.set_nth_field_to_default(field_idx) {
            Ok(p) => p,
            Err(e) => {
                log::debug!(
                    "set_nth_field_to_default({field_idx}) failed for variant '{}': {e}",
                    variant.effective_name()
                );
                return false;
            }
        };
    }

    let heap_value = match partial.build() {
        Ok(v) => v,
        Err(e) => {
            log::debug!("build failed: {e}");
            return false;
        }
    };

    let size = shape
        .layout
        .sized_layout()
        .expect("enum must be sized")
        .size();

    // FIXME: replace once <https://github.com/facet-rs/facet/issues/2152> is implemented
    assert_eq!(poke.shape(), heap_value.shape());
    // SAFETY: the Shape is the same and this is the same as core::mem::replace
    // if we had T
    unsafe {
        // Swap the old enum value (in poke) with the new one (in heap_value).
        // After the swap, heap_value holds the old value — its Drop impl will
        // call drop_in_place on it and then free the allocation.
        let dst = poke.data_mut().as_mut_byte_ptr();
        let src = heap_value.peek().data().as_byte_ptr() as *mut u8;
        core::ptr::swap_nonoverlapping(dst, src, size);
    }
    drop(heap_value);

    true
}

fn show_inline_poke_scalar(
    poke: &mut Poke<'_, '_>,
    scalar_type: ScalarType,
    ui: &mut Ui,
) -> Response {
    match scalar_type {
        ScalarType::Bool => {
            if let Ok(v) = poke.get_mut::<bool>() {
                return ui.add(Checkbox::without_text(v));
            }
        }
        ScalarType::U8 => {
            if let Ok(v) = poke.get_mut::<u8>() {
                return ui.add(egui::DragValue::new(v));
            }
        }
        ScalarType::U16 => {
            if let Ok(v) = poke.get_mut::<u16>() {
                return ui.add(egui::DragValue::new(v));
            }
        }
        ScalarType::U32 => {
            if let Ok(v) = poke.get_mut::<u32>() {
                return ui.add(egui::DragValue::new(v));
            }
        }
        ScalarType::U64 => {
            if let Ok(v) = poke.get_mut::<u64>() {
                return ui.add(egui::DragValue::new(v));
            }
        }
        ScalarType::U128 => {
            // DragValue doesn't support u128, show as label
            if let Ok(v) = poke.get::<u128>() {
                return ui.label(format!("{v}"));
            }
        }
        ScalarType::USize => {
            if let Ok(v) = poke.get_mut::<usize>() {
                return ui.add(egui::DragValue::new(v));
            }
        }
        ScalarType::I8 => {
            if let Ok(v) = poke.get_mut::<i8>() {
                return ui.add(egui::DragValue::new(v));
            }
        }
        ScalarType::I16 => {
            if let Ok(v) = poke.get_mut::<i16>() {
                return ui.add(egui::DragValue::new(v));
            }
        }
        ScalarType::I32 => {
            if let Ok(v) = poke.get_mut::<i32>() {
                return ui.add(egui::DragValue::new(v));
            }
        }
        ScalarType::I64 => {
            if let Ok(v) = poke.get_mut::<i64>() {
                return ui.add(egui::DragValue::new(v));
            }
        }
        ScalarType::I128 => {
            if let Ok(v) = poke.get::<i128>() {
                return ui.label(format!("{v}"));
            }
        }
        ScalarType::ISize => {
            if let Ok(v) = poke.get_mut::<isize>() {
                return ui.add(egui::DragValue::new(v));
            }
        }
        ScalarType::F32 => {
            if let Ok(v) = poke.get_mut::<f32>() {
                return ui.add(egui::DragValue::new(v));
            }
        }
        ScalarType::F64 => {
            if let Ok(v) = poke.get_mut::<f64>() {
                return ui.add(egui::DragValue::new(v));
            }
        }
        ScalarType::String => {
            if let Ok(v) = poke.get_mut::<String>() {
                return ui.add(TextEdit::singleline(v));
            }
        }
        ScalarType::Char => {
            if let Ok(v) = poke.get::<char>() {
                let s = v.to_string();
                return ui.add_enabled(false, TextEdit::singleline(&mut s.as_str()));
            }
        }
        ScalarType::Str => {
            // str is unsized, fall through to display
            if poke.shape().is_display() {
                return ui.label(format!("{}", poke.as_peek()));
            }
        }
        ScalarType::CowStr => {
            if let Ok(v) = poke.get::<Cow<'_, str>>() {
                let mut s = v.clone();
                return ui.add_enabled(false, TextEdit::singleline(&mut s));
            }
        }
        _ if poke.shape().is_display() => {
            return ui.label(format!("{}", poke.as_peek()));
        }
        _ if poke.shape().is_debug() => {
            return ui.label(format!("{:?}", poke.as_peek()));
        }
        _ => {}
    }
    ui.colored_label(
        Color32::YELLOW,
        format!("unsupported scalar: {scalar_type:?}"),
    )
}

fn show_inline_peek(peek: Peek<'_, '_>, ui: &mut Ui, id: Id, as_display: bool) -> Response {
    if as_display || should_render_as_display(peek.shape(), &[]) {
        return ui.label(format!("{}", peek));
    }

    if let Some(scalar_type) = peek.scalar_type() {
        return show_inline_peek_scalar(peek, scalar_type, ui);
    }

    // Option/Result have Def::Option/Def::Result but Type::User(UserType::Enum),
    // so check into_option before into_enum to avoid misrouting.
    if let Ok(opt) = peek.into_option() {
        return show_inline_peek_option(opt, ui, id);
    }
    if let Ok(enu) = peek.into_enum() {
        if let Ok(variant) = enu.active_variant() {
            return ui.weak(variant.effective_name());
        }
        return ui.weak("enum");
    }
    if let Ok(_struc) = peek.into_struct() {
        return ui.weak(shape_display_name(peek.shape()));
    }
    if let Ok(list) = peek.into_list_like() {
        return ui.weak(format!("[{}]", list.len()));
    }
    if let Ok(map) = peek.into_map() {
        return ui.weak(format!("[{}]", map.len()));
    }
    if let Ok(tuple) = peek.into_tuple() {
        return ui.weak(format!("({})", tuple.len()));
    }
    if let Ok(ptr) = peek.into_pointer()
        && let Some(inner) = ptr.borrow_inner()
    {
        return show_inline_peek(inner, ui, id.with("ptr"), false);
    }

    ui.weak(shape_display_name(peek.shape()))
}

fn show_inline_peek_scalar(peek: Peek<'_, '_>, scalar_type: ScalarType, ui: &mut Ui) -> Response {
    match scalar_type {
        ScalarType::Bool => {
            if let Ok(v) = peek.get::<bool>() {
                let mut value = *v;
                return ui.add_enabled(false, Checkbox::without_text(&mut value));
            }
        }
        ScalarType::Char => {
            if let Ok(c) = peek.get::<char>() {
                let s = c.to_string();
                return ui.add_enabled(false, TextEdit::singleline(&mut s.as_str()));
            }
        }
        ScalarType::Str => {
            if let Ok(v) = peek.get::<str>() {
                return ui.add_enabled(false, TextEdit::singleline(&mut &*v));
            }
        }
        ScalarType::CowStr => {
            if let Ok(v) = peek.get::<Cow<'_, str>>() {
                let mut s = v.clone();
                return ui.add_enabled(false, TextEdit::singleline(&mut s));
            }
        }
        ScalarType::String => {
            if let Ok(v) = peek.get::<String>() {
                let mut s: Cow<'_, str> = Cow::Borrowed(v.as_str());
                return ui.add_enabled(false, TextEdit::singleline(&mut s));
            }
        }
        _ if peek.shape().is_display() => {
            return ui.label(format!("{}", peek));
        }
        _ if peek.shape().is_debug() => {
            return ui.label(format!("{:?}", peek));
        }
        _ => {}
    }
    ui.colored_label(
        Color32::YELLOW,
        format!("unsupported scalar: {scalar_type:?}"),
    )
}

fn show_inline_peek_option(opt: PeekOption<'_, '_>, ui: &mut Ui, id: Id) -> Response {
    ui.horizontal(|ui| {
        let is_some = opt.value().is_some();
        let _ = ui.selectable_label(!is_some, "None");
        let _ = ui.selectable_label(is_some, "Some");
        if let Some(inner) = opt.value() {
            show_inline_peek(inner, ui, id.with("some"), false);
        }
    })
    .response
}