drawbar 0.7.0

Your Nord's sounds, in a window: browse, edit and send programs, samples and pianos, in the browser or on the desktop
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
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
//! This computer: the assets held in memory, and the ways bytes get in and out of them.
//!
//! An entity is bytes first and a decode second — a file that does not parse still
//! gets a row, with its error and its raw body still exportable, because reporting a
//! bad file is the point of opening it.
//!
//! The list draws itself in [`crate::browser`]; what lives here is the model and the
//! file dialogs.

use std::sync::mpsc::{Receiver, Sender};

use eframe::egui;
use nord_format::cbin::{Cbin, Generation, Header};
use nord_format::formats::{ne5, ns2, ns3, ns4, nsmpproj};
use nord_format::{Entity, Live, OrganPreset, PianoPreset, Program, Settings, Song, Synth};
use nord_usb::{Location, ObjectClass};

use crate::log::Log;
use crate::newproject::{Draft, Making};
use crate::queue::Queue;

/// Where an entity came from.
#[derive(Clone)]
pub enum Origin {
    File(String),
    Device {
        class: ObjectClass,
        at: Location,
    },
    Fresh,
    /// The occupant of a slot that a failed write could not put back.
    Rescued {
        at: Location,
    },
}

impl Origin {
    pub fn label(&self) -> String {
        match self {
            Origin::File(name) => format!("Opened from {name}"),
            Origin::Device { class, at } => {
                format!("Copied from {}", crate::strings::place(*class, *at))
            }
            Origin::Fresh => "New, not saved anywhere yet".into(),
            Origin::Rescued { at } => format!("Rescued from {}", crate::strings::shown(*at)),
        }
    }

    /// The slot this came off, for the tab header's way back.
    pub fn slot(&self) -> Option<(ObjectClass, Location)> {
        match self {
            Origin::Device { class, at } => Some((*class, *at)),
            _ => None,
        }
    }
}

/// Whether re-encoding a decode reproduced the bytes it came from.
#[derive(Clone)]
pub enum VerifyState {
    Ok,
    /// Offset of the first byte that came back different.
    Differs {
        at: usize,
    },
    /// Re-encoding refused.
    Failed(String),
    /// Nothing to check, and why.
    NotApplicable(&'static str),
}

impl VerifyState {
    pub fn badge(&self) -> &'static str {
        match self {
            VerifyState::Ok => "ok",
            VerifyState::Differs { .. } => "differs",
            VerifyState::Failed(_) => "failed",
            VerifyState::NotApplicable(_) => "n/a",
        }
    }

    pub fn detail(&self) -> String {
        match self {
            VerifyState::Ok => "re-encoded byte-for-byte".into(),
            VerifyState::Differs { at } => format!("first difference at byte {at:#06x}"),
            VerifyState::Failed(why) => why.clone(),
            VerifyState::NotApplicable(why) => (*why).to_string(),
        }
    }

    pub fn color(&self, visuals: &egui::Visuals) -> egui::Color32 {
        match self {
            VerifyState::Ok => crate::app::good(visuals),
            VerifyState::Differs { .. } | VerifyState::Failed(_) => crate::app::bad(visuals),
            VerifyState::NotApplicable(_) => visuals.weak_text_color(),
        }
    }
}

/// The container facts, read once at ingest.
///
/// ⚠️ Reading them streams the whole file to check the checksum and hash its body, so
/// it happens on the way in and never per frame — a piano library is hundreds of
/// megabytes.
#[derive(Clone)]
pub struct Container {
    pub header: Header,
    /// Where the body sits in the file, checked against the file's own length when it
    /// was read. The one derivation of it: anything wanting the body reads this rather
    /// than adding a declared length to a start of its own.
    pub body: std::ops::Range<usize>,
    pub checksum_ok: bool,
    /// `crc32:` or `crc16:` — the two generations keep it in different places.
    pub checksum_label: &'static str,
    pub checksum: String,
    /// The CRC-32 of the wire body, which is what the device reports for a slot — so a
    /// file and the slot it came off compare without either body being hashed again.
    ///
    /// Computed rather than read: a type-1 container carries the same number at `0x18`,
    /// and a type-0 one carries no such word — only a CRC-16 over the whole file.
    pub body_crc32: u32,
}

impl Container {
    fn read(bytes: &[u8]) -> Option<Container> {
        let info = nord_format::cbin::inspect(&mut std::io::Cursor::new(bytes)).ok()?;
        let start = usize::try_from(info.header.generation.body_start()).ok()?;
        let end = start.checked_add(usize::try_from(info.body_len).ok()?)?;
        let body = start..end;
        let body_crc32 = nord_usb::envelope::crc32(bytes.get(body.clone())?);
        // `Header` omits the generation-specific checksum field. What the file stores is
        // what is shown; it parts from the body's own hash exactly when the file is bad.
        let (checksum_label, checksum) = match info.header.generation {
            Generation::V0 => {
                let tail = bytes.get(bytes.len().checked_sub(2)?..)?;
                let crc = u16::from_le_bytes(tail.try_into().ok()?);
                ("crc16:", format!("{crc:#06x}"))
            }
            Generation::V1 => {
                let crc = u32::from_le_bytes(bytes.get(0x18..0x1c)?.try_into().ok()?);
                ("crc32:", format!("{crc:#010x}"))
            }
        };
        Some(Container {
            header: info.header,
            body,
            checksum_ok: info.checksum_ok,
            checksum_label,
            checksum,
            body_crc32,
        })
    }

    pub fn tag(&self) -> String {
        String::from_utf8_lossy(&self.header.tag).into_owned()
    }

    /// How long the body is, which is the length of the range it sits in.
    pub fn body_len(&self) -> u64 {
        self.body.len() as u64
    }
}

/// What an asset was last saved as: the bytes, and the checksum a slot holding them
/// would report.
///
/// ⚠️ The checksum is read when the baseline moves and never per frame. Reading one
/// streams the whole body, and every listed row asks for it while the library is up.
#[derive(Clone, Default)]
pub struct Baseline {
    pub bytes: Vec<u8>,
    /// The checksum a slot holding these bytes would report, which is what a link and
    /// the sign beside it are both decided on — [`crate::device::link`] and
    /// [`crate::library::agrees`].
    ///
    /// `None` for bytes that are no CBIN container at all — see
    /// [`Container::body_crc32`].
    pub crc32: Option<u32>,
    /// Which [`LocalEntity::stamp`] these bytes are: the asset's own where it still
    /// holds them, and one of its own where it does not.
    ///
    /// ⚠️ This is what unsaved is read from. Comparing two bodies is O(the library),
    /// and the header alone asks twice a frame — see [`LocalEntity::is_unsaved`].
    pub stamp: u64,
}

impl Baseline {
    /// The baseline of bytes nothing has inspected yet, stamped as `stamp` — which is
    /// [`Workspace::stamp_for`]'s to decide.
    pub(crate) fn read(bytes: Vec<u8>, stamp: u64) -> Baseline {
        let crc32 = Container::read(&bytes).map(|held| held.body_crc32);
        Baseline {
            bytes,
            crc32,
            stamp,
        }
    }
}

/// A write this app made: the slot it put bytes in, and the checksum of the bytes it
/// put there.
///
/// The one thing this app knows about a slot without reading it back. It answers for a
/// class whose slots report no checksum of their own — those bytes are in that slot
/// because this app put them there — and only while the asset is still saved as them:
/// `crc32` is compared with [`Baseline::crc32`], which moves the moment the asset is
/// saved as anything else.
#[derive(Clone, Copy)]
pub struct Wrote {
    pub class: ObjectClass,
    pub at: Location,
    pub crc32: u32,
}

/// One object held in memory: its bytes, what they decode to, and how they got here.
pub struct LocalEntity {
    /// Stable across reordering, so a selection survives a removal.
    pub id: u64,
    pub name: String,
    pub origin: Origin,
    pub bytes: Vec<u8>,
    pub entity: Option<Entity>,
    pub parse_error: Option<String>,
    pub container: Option<Container>,
    pub verify: VerifyState,
    /// What this asset was last saved as. Unsaved is not a flag: it is bytes that are
    /// not these — see [`LocalEntity::is_unsaved`].
    pub saved: Baseline,
    /// Whether this is on this computer, as opposed to a view of a slot.
    ///
    /// A view is a working copy like any other — it is edited and sent back the same
    /// way — but it is not in the local list and goes when its tab does. Only
    /// [`Workspace::keep`] promotes one.
    pub kept: bool,
    /// Distinct for every set of bytes this id has held, so anything caching a decode
    /// of them can tell it is looking at the old ones.
    ///
    /// It is the list revision at the moment the bytes landed, so a rename or a send
    /// does not spend one.
    pub stamp: u64,
    /// The slot on the attached instrument that holds these bytes, from
    /// [`crate::device::link`].
    ///
    /// Derived from the scan cache and never stored: it is re-made whenever that cache
    /// changes and goes when the instrument does. An edit leaves it alone, so an asset
    /// that has been changed still points at the slot it was matched to.
    pub link: Option<(ObjectClass, Location)>,
    /// The last write this app made from this asset, which is the one thing it knows
    /// about a slot without reading it back — see [`Wrote`] and
    /// [`crate::library::agrees`].
    ///
    /// It goes with the instrument that took it: [`Workspace::forget_writes`].
    pub wrote: Option<Wrote>,
}

impl LocalEntity {
    fn new(id: u64, name: String, origin: Origin, bytes: Vec<u8>, stamp: u64) -> LocalEntity {
        let container = Container::read(&bytes);
        let (entity, parse_error) =
            match nord_format::from_stream(&mut std::io::Cursor::new(&bytes)) {
                Ok(entity) => (Some(entity), None),
                Err(e) => (None, Some(e.to_string())),
            };
        let verify = match &entity {
            Some(entity) => verify(entity, &bytes),
            None => VerifyState::NotApplicable("the file did not decode"),
        };
        let mut held = LocalEntity {
            id,
            name,
            origin,
            bytes,
            entity,
            parse_error,
            container,
            verify,
            saved: Baseline::default(),
            kept: true,
            stamp,
            link: None,
            wrote: None,
        };
        held.saved = held.baseline();
        held
    }

    /// Whether it holds something other than what it was last saved as.
    ///
    /// ⚠️ Two stamps, not two bodies: every listed row and every frame of the header
    /// ask this, and a piano library is hundreds of megabytes. The stamps are settled
    /// wherever a baseline moves — see [`Baseline::stamp`].
    pub fn is_unsaved(&self) -> bool {
        self.stamp != self.saved.stamp
    }

    /// The bytes it holds now, as a baseline: what saving it settles on.
    fn baseline(&self) -> Baseline {
        Baseline {
            bytes: self.bytes.clone(),
            crc32: self.container.as_ref().map(|held| held.body_crc32),
            stamp: self.stamp,
        }
    }

    /// The slot this asset stands for: the one holding its bytes, and otherwise the one
    /// it came off.
    pub fn spot(&self) -> Option<(ObjectClass, Location)> {
        self.link.or_else(|| self.origin.slot())
    }

    /// The format tag, from the decode where there is one and the container otherwise.
    pub fn tag(&self) -> String {
        match (&self.entity, &self.container) {
            (Some(entity), _) => entity.identity().format.to_string(),
            (None, Some(container)) => container.tag(),
            (None, None) => "?".into(),
        }
    }

    /// The bytes the wire would carry: the file with its container stripped.
    ///
    /// The counterpart of `nord … get --body` pointed at a file. `None` for anything
    /// that is not a CBIN container.
    pub fn raw_body(&self) -> Option<Vec<u8>> {
        nord_usb::envelope::unwrap(&self.bytes)
            .ok()
            .map(|read| read.body.0)
    }
}

/// Whether an asset holds something no other copy of it does.
///
/// The one rule that decides what happens to a view when the last thing looking at it
/// goes: **an unsaved or owed view is precious, a saved one is disposable.** A saved
/// view is the slot's own bytes, which the instrument still has; an unsaved one is the
/// only copy there is.
pub fn precious(entity: &LocalEntity, queue: &Queue) -> bool {
    entity.is_unsaved() || queue.holds(entity.id)
}

/// The filename an export suggests for a verbatim name: made path-safe, and given the
/// extension the bytes say it should have unless the name already carries one.
fn export_filename(name: &str, bytes: &[u8]) -> String {
    let stem = match filename_stem(name) {
        s if s.is_empty() => "unnamed".to_string(),
        s => s,
    };
    match crate::strings::carries_tag(&stem) {
        true => stem,
        false => format!("{stem}.{}", format_tag(bytes)),
    }
}

/// The filename a decoded zone's WAV suggests: the instrument's own name, made
/// path-safe, and the zone numbered the way the document numbers it.
///
/// The same spelling `nord sample decode --out` writes, so a zone exported from either
/// tool lands under one name.
pub fn zone_wav_name(instrument: &str, zone: usize) -> String {
    let stem = match filename_stem(instrument) {
        s if s.is_empty() => "unnamed".to_string(),
        s => s,
    };
    format!("{stem}-zone{zone}.wav")
}

/// The filename a decoded piano stroke's WAV suggests: the library's own name, made
/// path-safe, and the stroke spelled the way `nord piano decode` spells it —
/// `<root>-b<bank>-l<layer>`, the MIDI note zero-padded to three digits.
pub fn stroke_wav_name(library: &str, root: u8, bank: u8, layer: u8) -> String {
    let stem = match filename_stem(library) {
        s if s.is_empty() => "unnamed".to_string(),
        s => s,
    };
    format!("{stem}-{root:03}-b{bank}-l{layer:02}.wav")
}

/// A verbatim name reduced to what a path can carry: whitespace runs and path
/// separators become one `-`, control characters drop, and nothing hidden or
/// option-like survives at the edges. Filenames only — the name itself stays verbatim.
fn filename_stem(label: &str) -> String {
    // A separator is owed rather than written, so a run of them collapses to one `-`
    // and nothing trailing survives.
    let mut owed = false;
    let mut out = String::with_capacity(label.len());
    for c in label.chars() {
        match c {
            '-' => owed = !out.is_empty(),
            _ if c.is_whitespace() => owed = !out.is_empty(),
            // Path separators, plus the characters a Windows filename cannot hold.
            '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => owed = !out.is_empty(),
            _ if c.is_control() => {}
            _ => {
                if std::mem::take(&mut owed) {
                    out.push('-');
                }
                out.push(c);
            }
        }
    }
    // A leading dot hides the file and dots alone spell `.` and `..`; a leading dash is
    // an option to every tool that later reads it.
    out.trim_matches(['.', '-']).to_string()
}

/// The extension a nameless export gets: the CBIN tag the bytes themselves carry,
/// the non-CBIN container's own name, or `bin` for bytes that carry neither.
fn format_tag(bytes: &[u8]) -> String {
    // ⚠️ Offset 8 only means anything under the CBIN magic — a text format can
    // hold alphanumerics there by accident.
    if bytes.starts_with(nord_format::cbin::MAGIC) {
        return bytes
            .get(8..12)
            .filter(|tag| tag.iter().all(|b| b.is_ascii_alphanumeric()))
            .map(|tag| String::from_utf8_lossy(tag).into_owned())
            .unwrap_or_else(|| "bin".to_string());
    }
    if bytes.starts_with(nsmpproj::MAGIC) {
        return nsmpproj::FORMAT.to_string();
    }
    "bin".to_string()
}

/// Re-encode and compare — the check `nord verify` runs on a file.
fn verify(entity: &Entity, bytes: &[u8]) -> VerifyState {
    if matches!(entity, Entity::Bundle(_)) {
        return VerifyState::NotApplicable("a bundle is an archive; it does not re-encode");
    }
    let out = match nord_format::to_bytes(entity) {
        Ok(out) => out,
        Err(e) => return VerifyState::Failed(e.to_string()),
    };
    match out.iter().zip(bytes).position(|(a, b)| a != b) {
        Some(at) => VerifyState::Differs { at },
        None if out.len() == bytes.len() => VerifyState::Ok,
        // A shared prefix and a different length: they part at the end of the shorter.
        None => VerifyState::Differs {
            at: out.len().min(bytes.len()),
        },
    }
}

/// One product family and the objects it can be started from nothing, which is how the
/// New menu is arranged: a family, then a kind inside it.
pub struct Family {
    pub label: &'static str,
    pub kinds: &'static [Fresh],
}

/// A body of every zero is a legal body: each field's type decodes the whole of its
/// slot, so nothing in it is out of range. Build one under the newest version the
/// decode is validated against.
///
/// ⚠️ Legal is not the same as **default**. What comes out is every control at zero,
/// which is not a state any panel ships in — see [`Fresh::zeroed`], which is what puts
/// that in front of the operator before they make one.
macro_rules! zeroed {
    ($body:ty, $len:expr, $format:expr, $versions:expr, $wrap:expr) => {{
        let body = <$body>::try_from([0u8; $len]).map_err(|e| format!("{e}"))?;
        let version = *$versions.last().ok_or("the format knows no version")?;
        $wrap(Cbin {
            header: Header::new($format, (0, 0), version),
            body,
        })
    }};
}

/// The objects the New menu offers, across every format this app can build from
/// nothing.
///
/// ⚠️ Only bodies that **decode** are here. A stub format — the Stage 3's song, the
/// settings of any Stage — round-trips its container and nothing more, so a zeroed one
/// is 45 bytes of nothing under a tag rather than an object, and offering it would put a
/// file in front of the operator that this app cannot say a single true thing about.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Fresh {
    /// The Electro 5's four, each from the library's own constructor.
    Program,
    Live,
    SetList,
    Settings,
    Stage2Program,
    Stage3Program,
    Stage3Synth,
    Stage4Program,
    Stage4Organ,
    Stage4Piano,
    Stage4Synth,
}

impl Fresh {
    pub const ALL: [Fresh; 11] = [
        Fresh::Program,
        Fresh::Live,
        Fresh::SetList,
        Fresh::Settings,
        Fresh::Stage2Program,
        Fresh::Stage3Program,
        Fresh::Stage3Synth,
        Fresh::Stage4Program,
        Fresh::Stage4Organ,
        Fresh::Stage4Piano,
        Fresh::Stage4Synth,
    ];

    pub const FAMILIES: [Family; 4] = [
        Family {
            label: "Electro 5",
            kinds: &[Fresh::Program, Fresh::Live, Fresh::SetList, Fresh::Settings],
        },
        Family {
            label: "Stage 2",
            kinds: &[Fresh::Stage2Program],
        },
        Family {
            label: "Stage 3",
            kinds: &[Fresh::Stage3Program, Fresh::Stage3Synth],
        },
        Family {
            label: "Stage 4",
            kinds: &[
                Fresh::Stage4Program,
                Fresh::Stage4Organ,
                Fresh::Stage4Piano,
                Fresh::Stage4Synth,
            ],
        },
    ];

    /// What the kind is called inside its family's menu.
    pub fn label(self) -> &'static str {
        match self {
            Fresh::Program | Fresh::Stage2Program | Fresh::Stage3Program | Fresh::Stage4Program => {
                "Program"
            }
            Fresh::Live => "Live slot",
            Fresh::SetList => "Set list",
            Fresh::Settings => "Settings",
            Fresh::Stage3Synth | Fresh::Stage4Synth => "Synth preset",
            Fresh::Stage4Organ => "Organ preset",
            Fresh::Stage4Piano => "Piano preset",
        }
    }

    pub fn tag(self) -> &'static str {
        match self {
            Fresh::Program => ne5::program::FORMAT,
            Fresh::Live => ne5::live::FORMAT,
            Fresh::SetList => ne5::song::FORMAT,
            Fresh::Settings => ne5::settings::FORMAT,
            Fresh::Stage2Program => ns2::program::FORMAT,
            Fresh::Stage3Program => ns3::program::FORMAT,
            Fresh::Stage3Synth => ns3::synth::FORMAT,
            Fresh::Stage4Program => ns4::program::FORMAT,
            Fresh::Stage4Organ => ns4::organ_preset::FORMAT,
            Fresh::Stage4Piano => ns4::piano_preset::FORMAT,
            Fresh::Stage4Synth => ns4::synth::FORMAT,
        }
    }

    /// Whether what this makes is a zeroed body rather than a constructed object.
    ///
    /// The distinction the menu has to carry: an Electro 5 program comes from the
    /// library's own constructor, and a Stage anything is every control at zero.
    pub fn zeroed(self) -> bool {
        !matches!(
            self,
            Fresh::Program | Fresh::Live | Fresh::SetList | Fresh::Settings
        )
    }

    /// The sentence a hover puts on the menu entry, where there is something the
    /// operator would otherwise have to find out by opening the file.
    pub fn note(self) -> Option<&'static str> {
        self.zeroed().then_some(
            "Every control at zero. The file decodes and re-saves byte for byte, but it \
             is not a factory program — nothing here knows what one would hold.",
        )
    }

    /// The file this makes, byte for byte what [`Workspace::create`] puts on the list.
    pub(crate) fn bytes(self) -> Result<Vec<u8>, String> {
        let at = |slot: u16| -> Result<ne5::program::Location, String> {
            (0, slot).try_into().map_err(|e| format!("{e}"))
        };
        let entity = match self {
            Fresh::Program => Entity::Program(Program::Electro5(ne5::program::new(at(0)?))),
            Fresh::Live => Entity::Live(Live::Electro5(ne5::live::new(
                (0, 0).try_into().map_err(|e| format!("{e}"))?,
            ))),
            // A set list is four pointers and nothing else, so the only starting point
            // there is one is the first four programs.
            Fresh::SetList => Entity::Song(Song::Electro5(
                ne5::song::new(
                    (0, 0).try_into().map_err(|e| format!("{e}"))?,
                    ne5::song::DEFAULT_VERSION,
                    [at(0)?, at(1)?, at(2)?, at(3)?],
                )
                .map_err(|e| format!("{e}"))?,
            )),
            Fresh::Settings => Entity::Settings(Settings::Electro5(ne5::settings::new())),
            Fresh::Stage2Program => zeroed!(
                ns2::Program,
                ns2::program::BODY_LEN,
                ns2::program::FORMAT,
                ns2::program::KNOWN_VERSIONS,
                |f| Entity::Program(Program::Stage2(f))
            ),
            Fresh::Stage3Program => zeroed!(
                ns3::Program,
                ns3::program::BODY_LEN,
                ns3::program::FORMAT,
                ns3::program::KNOWN_VERSIONS,
                |f| Entity::Program(Program::Stage3(f))
            ),
            Fresh::Stage3Synth => zeroed!(
                ns3::SynthPreset,
                ns3::synth::BODY_LEN,
                ns3::synth::FORMAT,
                ns3::synth::KNOWN_VERSIONS,
                |f| Entity::Synth(Synth::Stage3(f))
            ),
            Fresh::Stage4Program => zeroed!(
                ns4::Program,
                ns4::program::BODY_LEN,
                ns4::program::FORMAT,
                ns4::program::KNOWN_VERSIONS,
                |f| Entity::Program(Program::Stage4(f))
            ),
            Fresh::Stage4Organ => zeroed!(
                ns4::organ_preset::OrganPreset,
                ns4::organ_preset::BODY_LEN,
                ns4::organ_preset::FORMAT,
                ns4::organ_preset::KNOWN_VERSIONS,
                |f| Entity::OrganPreset(OrganPreset::Stage4(f))
            ),
            Fresh::Stage4Piano => zeroed!(
                ns4::piano_preset::PianoPreset,
                ns4::piano_preset::BODY_LEN,
                ns4::piano_preset::FORMAT,
                ns4::piano_preset::KNOWN_VERSIONS,
                |f| Entity::PianoPreset(PianoPreset::Stage4(f))
            ),
            Fresh::Stage4Synth => zeroed!(
                ns4::synth::SynthPreset,
                ns4::synth::BODY_LEN,
                ns4::synth::FORMAT,
                ns4::synth::KNOWN_VERSIONS,
                |f| Entity::Synth(Synth::Stage4(f))
            ),
        };
        nord_format::to_bytes(&entity).map_err(|e| e.to_string())
    }
}

/// What the decode made of a set of bytes arriving, for the one line the status bar
/// carries about them. The detail is in the log either way.
enum Arrival {
    Read,
    /// It decoded, but it does not re-encode to the bytes it came from.
    Unverified,
    Unreadable,
}

/// One asset as a store holds it.
pub struct Saved {
    pub id: u64,
    pub name: String,
    pub origin: Origin,
    /// What it was last saved as.
    pub saved: Vec<u8>,
    /// What it holds now, where that is not what it was saved as.
    pub unsaved: Option<Vec<u8>>,
}

/// What a background task hands back to the UI thread.
enum Incoming {
    Opened {
        name: String,
        bytes: Vec<u8>,
    },
    /// Everything one *New → WAVs* pick came back with, together: the draft is one
    /// question about the whole set, not one per file.
    Wavs {
        making: Making,
        files: Vec<(String, Vec<u8>)>,
    },
    Note(String),
    Failed(String),
}

pub struct Workspace {
    entities: Vec<LocalEntity>,
    next_id: u64,
    /// Bumped by every change to the list, so the shell can tell when the store is
    /// behind without comparing every asset's bytes.
    revision: u64,
    ctx: egui::Context,
    tx: Sender<Incoming>,
    rx: Receiver<Incoming>,
    /// The WAVs a New pick came back with, waiting on their root keys. See
    /// [`crate::newproject`].
    draft: Option<Draft>,
}

impl Workspace {
    pub fn new(ctx: egui::Context) -> Workspace {
        let (tx, rx) = std::sync::mpsc::channel();
        Workspace {
            entities: Vec::new(),
            next_id: 1,
            revision: 0,
            ctx,
            tx,
            rx,
            draft: None,
        }
    }

    /// The context the app draws in, for the acts that ask the window itself for
    /// something rather than the list.
    pub fn ctx(&self) -> &egui::Context {
        &self.ctx
    }

    /// Counts changes to the list, not to any one asset.
    pub fn revision(&self) -> u64 {
        self.revision
    }

    /// Everything held in memory, views included. The local **list** is
    /// [`Workspace::listed`].
    pub fn entities(&self) -> &[LocalEntity] {
        &self.entities
    }

    /// What "This computer" shows: everything except the views of a slot.
    pub fn listed(&self) -> impl Iterator<Item = &LocalEntity> {
        self.entities.iter().filter(|e| e.kept)
    }

    pub fn get(&self, id: u64) -> Option<&LocalEntity> {
        self.entities.iter().find(|e| e.id == id)
    }

    /// Whether this is a view of a slot rather than something on this computer.
    pub fn is_view(&self, id: u64) -> bool {
        self.get(id).is_some_and(|entity| !entity.kept)
    }

    /// Take a copy of a slot without putting it in the local list.
    ///
    /// What a double-click on a slot opens: a tab and a document over a working copy,
    /// which is edited and sent back like any other, and which goes when its tab does.
    pub fn view(&mut self, name: String, origin: Origin, bytes: Vec<u8>, log: &mut Log) -> u64 {
        let (id, _) = self.add(name, origin, bytes, log);
        let Some(entity) = self.entities.iter_mut().find(|e| e.id == id) else {
            return id;
        };
        entity.kept = false;
        let where_ = match entity.origin.slot() {
            Some((class, at)) => crate::strings::place(class, at),
            None => "the instrument".to_string(),
        };
        log.say(format!(
            "Viewing {where_} — “{}” is not kept on this computer.",
            entity.name
        ));
        id
    }

    /// The view of a slot, if one is open. A slot has at most one: a second would be two
    /// working copies of one place, editable apart and both sendable back to it.
    pub fn view_of(&self, class: ObjectClass, at: Location) -> Option<u64> {
        self.entities
            .iter()
            .find(|e| !e.kept && e.origin.slot() == Some((class, at)))
            .map(|e| e.id)
    }

    /// Promote a view into the local list. Its edits and its debt come with it.
    pub fn keep(&mut self, id: u64, log: &mut Log) {
        let Some(entity) = self.entities.iter_mut().find(|e| e.id == id) else {
            return;
        };
        if std::mem::replace(&mut entity.kept, true) {
            return;
        }
        let name = entity.name.clone();
        self.revision += 1;
        log.say(format!("{name}” is on this computer."));
    }

    /// Drop the views nothing is looking at any more — except the ones holding changes.
    ///
    /// A view lives for as long as its tab: nothing lists it, so a view left behind is
    /// one nothing can reach and nothing can remove.
    ///
    /// ⚠️ **A view is the only copy of what it holds.** Nothing lists it and the store
    /// skips it, so closing its tab is the one gesture in this app that can destroy an
    /// edit — and the × sits beside the badge saying the edit is owed back to a slot.
    /// So an edited or owed view is promoted into the list instead, and only an
    /// untouched one is dropped.
    ///
    /// `pending` says an id holds an edit its bytes do not — a piano library's plan,
    /// which is an edit like any other and the only copy of itself.
    pub fn close_views(
        &mut self,
        open: impl Fn(u64) -> bool,
        pending: impl Fn(u64) -> bool,
        queue: &Queue,
        log: &mut Log,
    ) {
        let mut rescued = Vec::new();
        let before = self.entities.len();
        self.entities.retain_mut(|entity| {
            if entity.kept || open(entity.id) {
                return true;
            }
            if !precious(entity, queue) && !pending(entity.id) {
                return false;
            }
            entity.kept = true;
            rescued.push(entity.name.clone());
            true
        });
        for name in &rescued {
            log.say(format!(
                "{name}” is kept on this computer — it has changes the instrument does \
                 not."
            ));
        }
        if self.entities.len() == before && rescued.is_empty() {
            return;
        }
        self.revision += 1;
    }

    /// Re-derive every asset's link. Call whenever the instrument's scan cache changes;
    /// [`crate::device::link`] is what answers.
    pub fn relink(&mut self, held_by: impl Fn(&LocalEntity) -> Option<(ObjectClass, Location)>) {
        for entity in &mut self.entities {
            entity.link = held_by(entity);
        }
    }

    /// Rename an asset held here. Nothing leaves this computer.
    pub fn rename(&mut self, id: u64, name: String) {
        if let Some(entity) = self.entities.iter_mut().find(|e| e.id == id) {
            entity.name = name;
            self.revision += 1;
        }
    }

    /// Decode `bytes`, badge them, and add the row, with the detail of what arrived in
    /// the log. Every way in — drop, picker, fresh default, device read — lands here.
    ///
    /// What the status line says is the caller's: [`Workspace::ingest`] announces
    /// something on this computer and [`Workspace::view`] a slot being looked at, and
    /// they are not the same arrival.
    fn add(
        &mut self,
        name: String,
        origin: Origin,
        bytes: Vec<u8>,
        log: &mut Log,
    ) -> (u64, Arrival) {
        let id = self.next_id;
        self.next_id += 1;
        let entity = LocalEntity::new(id, name, origin, bytes, self.stamp());
        let arrival = match (&entity.parse_error, &entity.verify) {
            (Some(e), _) => {
                log.error(format!("{}: {e}", entity.name));
                Arrival::Unreadable
            }
            (None, VerifyState::Ok) => {
                log.info(format!(
                    "{}: {} ({} bytes), verified",
                    entity.name,
                    entity.tag(),
                    entity.bytes.len(),
                ));
                Arrival::Read
            }
            (None, state) => {
                log.warn(format!(
                    "{}: {} — verify {}: {}",
                    entity.name,
                    entity.tag(),
                    state.badge(),
                    state.detail(),
                ));
                Arrival::Unverified
            }
        };
        self.entities.push(entity);
        (id, arrival)
    }

    /// Take `bytes` onto this computer, and say so.
    pub fn ingest(&mut self, name: String, origin: Origin, bytes: Vec<u8>, log: &mut Log) -> u64 {
        let (id, arrival) = self.add(name.clone(), origin, bytes, log);
        match arrival {
            Arrival::Unreadable => {
                log.trouble(format!("{name}” is not a file this app understands."))
            }
            Arrival::Read => log.say(format!("{name}” is on this computer.")),
            Arrival::Unverified => log.say(format!(
                "{name}” opened, but it does not re-save byte for byte."
            )),
        }
        id
    }

    /// Spend one revision, and hand it out as the stamp on a set of bytes.
    fn stamp(&mut self) -> u64 {
        self.revision += 1;
        self.revision
    }

    /// The stamp a baseline of `bytes` takes under `id`: the asset's own where it holds
    /// those very bytes, and one of its own where it holds something else.
    ///
    /// ⚠️ The one place two bodies are compared. It runs where a baseline moves —
    /// never per frame — so that [`LocalEntity::is_unsaved`] and the caches over the
    /// pair are two integers.
    fn stamp_for(&mut self, id: u64, bytes: &[u8]) -> u64 {
        match self
            .get(id)
            .map(|entity| (entity.stamp, entity.bytes == bytes))
        {
            Some((stamp, true)) => stamp,
            _ => self.stamp(),
        }
    }

    /// Drain whatever the pickers finished with. Call once per frame.
    pub fn poll(&mut self, log: &mut Log) {
        while let Ok(message) = self.rx.try_recv() {
            match message {
                Incoming::Opened { name, bytes } => {
                    self.ingest(name.clone(), Origin::File(name), bytes, log);
                }
                Incoming::Wavs { making, files } => self.draft = Draft::plan(making, files),
                Incoming::Note(text) => log.say(text),
                Incoming::Failed(text) => log.trouble(text),
            }
        }
    }

    pub fn open_dialog(&self) {
        let tx = self.tx.clone();
        let ctx = self.ctx.clone();
        spawn(async move {
            let picked = rfd::AsyncFileDialog::new()
                .set_title("Open Nord files")
                .pick_files()
                .await;
            for handle in picked.unwrap_or_default() {
                let bytes = handle.read().await;
                let _ = tx.send(Incoming::Opened {
                    name: handle.file_name(),
                    bytes,
                });
            }
            ctx.request_repaint();
        });
    }

    /// Pick the WAVs a new project or instrument is laid out from.
    pub fn pick_wavs(&self, making: Making) {
        let tx = self.tx.clone();
        let ctx = self.ctx.clone();
        spawn(async move {
            let picked = rfd::AsyncFileDialog::new()
                .set_title(format!("Pick the WAVs for a {}", making.label()))
                .add_filter("WAV", &["wav"])
                .pick_files()
                .await;
            let mut files = Vec::new();
            for handle in picked.unwrap_or_default() {
                let bytes = handle.read().await;
                files.push((handle.file_name(), bytes));
            }
            let _ = tx.send(Incoming::Wavs { making, files });
            ctx.request_repaint();
        });
    }

    /// The picked WAVs waiting on their root keys, for the dialog to edit.
    pub fn draft_mut(&mut self) -> Option<&mut Draft> {
        self.draft.as_mut()
    }

    /// Take the draft away, whether it is about to be made or abandoned.
    pub fn take_draft(&mut self) -> Option<Draft> {
        self.draft.take()
    }

    /// The filename an export suggests.
    ///
    /// ⚠️ The one place a name becomes a filename — and the one place a name is made
    /// path-safe. Everywhere else the name is verbatim: what the instrument or the
    /// operator called the thing, spaces and all, and that spelling is what a rename
    /// sends back to the instrument.
    pub fn export_name(&self, id: u64) -> Option<String> {
        let entity = self.get(id)?;
        Some(export_filename(&entity.name, &entity.bytes))
    }

    pub fn export(&self, id: u64) {
        let Some(entity) = self.entities.iter().find(|e| e.id == id) else {
            return;
        };
        let name = match self.export_name(id) {
            Some(name) => name,
            None => return,
        };
        self.save_bytes(name, entity.bytes.clone());
    }

    /// Hand any bytes to the user under `name`, through whichever save this target has.
    ///
    /// What an export of a whole asset uses, and what a per-zone WAV uses: the bytes
    /// being offered are the only difference between them.
    pub fn save_bytes(&self, name: String, bytes: Vec<u8>) {
        let tx = self.tx.clone();
        let ctx = self.ctx.clone();
        spawn(async move {
            let _ = tx.send(save(name, bytes).await);
            ctx.request_repaint();
        });
    }

    /// Put back the bytes this asset was last saved as. What was saved is what it holds
    /// again, so it is not unsaved any more.
    pub fn revert(&mut self, id: u64, log: &mut Log) {
        let Some(saved) = self.get(id).map(|entity| entity.saved.bytes.clone()) else {
            return;
        };
        if self.respell(id, saved).is_none() {
            return;
        }
        if let Some(entity) = self.get(id) {
            log.say(format!("{}” is back as it was last saved.", entity.name));
        }
    }

    /// The bytes it holds are what it is saved as, from now on.
    ///
    /// ⚠️ Not a new set of bytes, so the stamp does not move: nothing cached over them
    /// is looking at anything else. The list revision does, so the store is written
    /// again without the unsaved tail.
    pub fn mark_saved(&mut self, id: u64) {
        let Some(entity) = self.entities.iter_mut().find(|e| e.id == id) else {
            return;
        };
        if !entity.is_unsaved() {
            return;
        }
        entity.saved = entity.baseline();
        self.revision += 1;
    }

    /// It reached a slot: the bytes the write carried are what it is saved as, and that
    /// slot is where it stands.
    ///
    /// ⚠️ The bytes the send carried, never the bytes it holds now. A write takes as
    /// long as the instrument takes, and an edit made while one was in flight is on this
    /// computer alone — calling it saved would let it be discarded with the tab it is
    /// open in.
    ///
    /// ⚠️ The one place a link is set rather than derived. A write is the only evidence
    /// about a slot this app does not have to read back, and [`crate::device::link`]
    /// keeps it until a walk of that slot says otherwise.
    pub fn landed(&mut self, id: u64, class: ObjectClass, at: Location, sent: Vec<u8>) {
        let stamp = self.stamp_for(id, &sent);
        let Some(entity) = self.entities.iter_mut().find(|e| e.id == id) else {
            return;
        };
        entity.saved = Baseline::read(sent, stamp);
        entity.link = Some((class, at));
        entity.wrote = entity.saved.crc32.map(|crc32| Wrote { class, at, crc32 });
        self.revision += 1;
    }

    /// Forget every write this app made.
    ///
    /// ⚠️ A write is evidence about the instrument that took it. With none attached, or
    /// another one in its place, it says nothing about what is in any slot.
    pub fn forget_writes(&mut self) {
        for entity in &mut self.entities {
            entity.wrote = None;
        }
    }

    /// Swap in re-encoded bytes, keeping the entity's identity.
    ///
    /// The decode and the verify are re-run: an editor's output is bytes like any other,
    /// and it earns its badge the same way a file off disk does.
    pub fn replace_bytes(&mut self, id: u64, bytes: Vec<u8>, log: &mut Log) {
        let Some(verify) = self.respell(id, bytes) else {
            return;
        };
        if let VerifyState::Ok = verify {
            return;
        }
        log.warn(format!(
            "after editing, verify {}: {}",
            verify.badge(),
            verify.detail()
        ));
    }

    /// Put a different set of bytes under one id, rebuilding everything derived from
    /// them, and answer with what the re-encode check made of them.
    ///
    /// ⚠️ The saved baseline is not one of those things: it moves only when the asset is
    /// saved, so an edit and the revert of it are measured against the same bytes. Nor is
    /// the link, or the write this app made — both are evidence about a slot, which an
    /// edit here says nothing about.
    fn respell(&mut self, id: u64, bytes: Vec<u8>) -> Option<VerifyState> {
        if self.get(id).is_none_or(|entity| entity.bytes == bytes) {
            return None;
        }
        let stamp = self.stamp();
        // The baseline stays where it is; whether the asset is holding it does not. A
        // revert, and an edit made and then unmade, each put back what it was saved as.
        let held = self
            .get(id)
            .is_some_and(|entity| entity.saved.bytes == bytes);
        let entity = self.entities.iter_mut().find(|e| e.id == id)?;
        let (kept, link, wrote) = (entity.kept, entity.link, entity.wrote);
        let saved = std::mem::take(&mut entity.saved);
        let saved = Baseline {
            stamp: match held {
                true => stamp,
                false => saved.stamp,
            },
            ..saved
        };
        let replaced =
            LocalEntity::new(id, entity.name.clone(), entity.origin.clone(), bytes, stamp);
        let verify = replaced.verify.clone();
        *entity = LocalEntity {
            kept,
            link,
            saved,
            wrote,
            ..replaced
        };
        Some(verify)
    }

    pub fn duplicate(&mut self, id: u64, log: &mut Log) -> Option<u64> {
        let source = self.entities.iter().find(|e| e.id == id)?;
        let name = format!("{} copy", source.name);
        let (origin, bytes) = (source.origin.clone(), source.bytes.clone());
        Some(self.ingest(name, origin, bytes, log))
    }

    pub fn remove(&mut self, id: u64, log: &mut Log) {
        let Some(at) = self.entities.iter().position(|e| e.id == id) else {
            return;
        };
        let gone = self.entities.remove(at);
        self.revision += 1;
        log.say(format!("Removed “{}” from this computer.", gone.name));
    }

    /// The next id a new asset would take, for the store to carry over.
    pub fn next_id(&self) -> u64 {
        self.next_id
    }

    /// Put back what a previous session held, answering with how many of them were
    /// refused.
    ///
    /// Every asset is decoded and re-checked on the way in: bytes out of a store have
    /// been sitting somewhere this app does not control and get no more trust than bytes
    /// off a disk. An id is refused on the same terms: one that leaves no room for the
    /// next, and one already standing in the list, are each a line nothing can restore.
    ///
    /// ⚠️ Restore decodes and re-encodes every asset before the first wasm frame. The
    /// tab cannot yield while checking up to the store budget.
    pub fn restore(&mut self, saved: Vec<Saved>, next_id: Option<u64>, log: &mut Log) -> usize {
        let mut refused = 0;
        for Saved {
            id,
            name,
            origin,
            saved,
            unsaved,
        } in saved
        {
            let Some(next) = id.checked_add(1) else {
                refused += 1;
                continue;
            };
            if self.entities.iter().any(|e| e.id == id) {
                refused += 1;
                continue;
            }
            let stamp = self.stamp();
            let bytes = unsaved.unwrap_or_else(|| saved.clone());
            // The store says what was saved and what was held; the two are one asset's
            // bytes exactly when they are the same bytes.
            let held = match bytes == saved {
                true => stamp,
                false => self.stamp(),
            };
            let entity = LocalEntity {
                saved: Baseline::read(saved, held),
                ..LocalEntity::new(id, name, origin, bytes, stamp)
            };
            if let Some(e) = &entity.parse_error {
                log.warn(format!("{}: {e}", entity.name));
            }
            self.next_id = self.next_id.max(next);
            self.entities.push(entity);
        }
        if let Some(next) = next_id {
            self.next_id = self.next_id.max(next);
        }
        self.revision += 1;
        refused
    }

    /// Make one of the fresh defaults and add it to the list.
    pub fn create(&mut self, kind: Fresh, log: &mut Log) -> Option<u64> {
        match kind.bytes() {
            Ok(bytes) => {
                let name = format!("untitled.{}", kind.tag());
                Some(self.ingest(name, Origin::Fresh, bytes, log))
            }
            Err(e) => {
                log.error(format!("new {}: {e}", kind.label()));
                log.trouble(format!("Could not make a new {}.", kind.label()));
                None
            }
        }
    }
}

/// Hand `bytes` to the user under `name`, however this target saves a file.
#[cfg(not(target_arch = "wasm32"))]
async fn save(name: String, bytes: Vec<u8>) -> Incoming {
    let Some(handle) = rfd::AsyncFileDialog::new()
        .set_file_name(&name)
        .save_file()
        .await
    else {
        return Incoming::Note(format!("{name}: save cancelled"));
    };
    match write_beside(handle.path(), &bytes) {
        Ok(()) => Incoming::Note(format!(
            "wrote {} ({} bytes)",
            handle.file_name(),
            bytes.len(),
        )),
        Err(e) => Incoming::Failed(format!("{name}: {e}")),
    }
}

/// Write `bytes` to a sibling of `path` and rename it over `path`.
///
/// ⚠️ A library is hundreds of megabytes, and a write that stops halfway through one the
/// operator chose would leave the file it replaced as neither. The rename is the only
/// moment the chosen path changes, and the temp file goes when anything fails.
#[cfg(not(target_arch = "wasm32"))]
fn write_beside(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
    let mut temp = path.as_os_str().to_owned();
    temp.push(".tmp");
    let temp = std::path::PathBuf::from(temp);
    let wrote = std::fs::write(&temp, bytes).and_then(|()| std::fs::rename(&temp, path));
    if wrote.is_err() {
        let _ = std::fs::remove_file(&temp);
    }
    wrote
}

/// The browser has no save picker: the bytes become a Blob behind an object URL, and
/// a synthetic anchor click hands that to the downloader.
#[cfg(target_arch = "wasm32")]
async fn save(name: String, bytes: Vec<u8>) -> Incoming {
    match download(&name, &bytes) {
        Ok(()) => Incoming::Note(format!("downloaded {name} ({} bytes)", bytes.len())),
        Err(e) => Incoming::Failed(format!("{name}: {e:?}")),
    }
}

#[cfg(target_arch = "wasm32")]
fn download(name: &str, bytes: &[u8]) -> Result<(), wasm_bindgen::JsValue> {
    use wasm_bindgen::JsCast as _;
    use wasm_bindgen::JsValue;

    let document = web_sys::window()
        .and_then(|w| w.document())
        .ok_or_else(|| JsValue::from_str("no document"))?;

    // `Uint8Array::from` copies into the JS heap, so the Blob does not alias Rust
    // memory that is about to be freed.
    let parts = js_sys::Array::new();
    parts.push(&js_sys::Uint8Array::from(bytes).into());
    let options = web_sys::BlobPropertyBag::new();
    options.set_type("application/octet-stream");
    let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &options)?;

    let url = web_sys::Url::create_object_url_with_blob(&blob)?;
    let anchor: web_sys::HtmlAnchorElement = document.create_element("a")?.unchecked_into();
    anchor.set_href(&url);
    anchor.set_download(name);
    anchor.click();
    web_sys::Url::revoke_object_url(&url)?;
    Ok(())
}

/// The same body under the shorter type-0 header the Electro 5's factory banks carry:
/// no CRC-32 word, and a CRC-16 over the whole file in the last two bytes.
#[cfg(test)]
pub(crate) fn as_type_0(bytes: &[u8]) -> Vec<u8> {
    let mut file = nord_usb::envelope::unwrap(bytes).expect("a CBIN file with a body");
    file.header.generation = Generation::V0;
    let mut out = std::io::Cursor::new(Vec::new());
    file.write_to(&mut out).expect("a type-0 container writes");
    out.into_inner()
}

/// Run a task that outlives the frame that started it.
///
/// ⚠️ wasm has one thread and cannot block: the future has to go to the microtask
/// queue, never to a thread, or the picker never resolves.
#[cfg(not(target_arch = "wasm32"))]
fn spawn<F: std::future::Future<Output = ()> + Send + 'static>(future: F) {
    std::thread::spawn(move || nord_usb::block_on(future));
}

#[cfg(target_arch = "wasm32")]
fn spawn<F: std::future::Future<Output = ()> + 'static>(future: F) {
    wasm_bindgen_futures::spawn_local(future);
}

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

    fn ingest(name: &str, bytes: Vec<u8>) -> LocalEntity {
        LocalEntity::new(1, name.into(), Origin::Fresh, bytes, 0)
    }

    #[test]
    fn a_fresh_program_decodes_and_verifies() {
        let entity = ingest("untitled.ne5p", Fresh::Program.bytes().unwrap());
        assert!(entity.parse_error.is_none());
        assert_eq!(entity.tag(), "ne5p");
        assert!(
            matches!(entity.verify, VerifyState::Ok),
            "{}",
            entity.verify.detail()
        );

        let container = entity.container.expect("a fresh program is a CBIN file");
        assert!(container.checksum_ok);
        assert_eq!(container.header.generation, Generation::V1);
        assert_eq!(container.body.len(), ne5::program::BODY_LEN);
        assert_eq!(container.checksum_label, "crc32:");
    }

    /// The number a file and a slot are compared on is the CRC-32 of the wire body, and
    /// the word a type-1 header stores at `0x18` is that same number.
    #[test]
    fn the_body_checksum_is_the_word_a_type_1_header_stores() {
        let bytes = Fresh::Program.bytes().unwrap();
        let entity = ingest("untitled.ne5p", bytes.clone());
        let container = entity.container.expect("a fresh program is a CBIN file");
        assert_eq!(container.header.generation, Generation::V1);
        let body = nord_usb::envelope::unwrap(&bytes).expect("a file the wire takes");
        assert_eq!(
            container.body_crc32,
            nord_usb::envelope::crc32(&body.body.0)
        );
        assert_eq!(
            container.body_crc32,
            u32::from_le_bytes(bytes[0x18..0x1c].try_into().unwrap()),
        );
    }

    /// ⚠️ A type-0 container stores no body checksum — its own is a CRC-16 over the
    /// whole file — so the number the instrument reports for a slot is hashed from the
    /// body rather than read out of the header, which is the only way an Electro 5
    /// factory program is comparable to the slot holding it at all.
    #[test]
    fn a_type_0_file_has_the_body_checksum_its_header_does_not_carry() {
        let bytes = as_type_0(&Fresh::Program.bytes().unwrap());
        let entity = ingest("Circling Bells.ne5p", bytes.clone());
        let container = entity.container.as_ref().expect("still a CBIN file");
        assert_eq!(container.header.generation, Generation::V0);
        assert!(container.checksum_ok);
        assert_eq!(container.checksum_label, "crc16:");

        let body = nord_usb::envelope::unwrap(&bytes).expect("a file the wire takes");
        let hashed = nord_usb::envelope::crc32(&body.body.0);
        assert_eq!(container.body_crc32, hashed);
        assert_eq!(entity.saved.crc32, Some(hashed));
    }

    /// Each fresh default carries its own tag, and each one round-trips.
    ///
    /// The whole claim the New menu makes about a zeroed body: it decodes, and it
    /// re-saves byte for byte.
    #[test]
    fn every_fresh_default_round_trips_under_its_own_tag() {
        for kind in Fresh::ALL {
            let entity = ingest("untitled", kind.bytes().unwrap());
            assert!(entity.parse_error.is_none(), "{:?}", kind);
            assert_eq!(entity.tag(), kind.tag(), "{kind:?}");
            assert!(matches!(entity.verify, VerifyState::Ok), "{kind:?}");
            assert!(
                entity.container.expect("a CBIN file").checksum_ok,
                "{kind:?}"
            );
        }
    }

    /// The menu is the families, and the families are the menu: a kind reachable from
    /// neither or from two places is one nobody can find or one offered twice.
    #[test]
    fn every_kind_sits_in_exactly_one_family() {
        let mut seen: Vec<Fresh> = Fresh::FAMILIES
            .iter()
            .flat_map(|family| family.kinds.iter().copied())
            .collect();
        assert_eq!(seen.len(), Fresh::ALL.len());
        for kind in Fresh::ALL {
            let at = seen.iter().position(|held| *held == kind);
            seen.remove(at.unwrap_or_else(|| panic!("{kind:?} is in no family")));
        }
        assert!(seen.is_empty());
    }

    /// A zeroed body is not a factory program, and the menu has to say so rather than
    /// let the operator find out.
    #[test]
    fn a_zeroed_body_says_that_it_is_one() {
        assert!(!Fresh::Program.zeroed() && Fresh::Program.note().is_none());
        for kind in Fresh::ALL.iter().filter(|kind| kind.zeroed()) {
            let note = kind.note().unwrap_or_else(|| panic!("{kind:?}"));
            assert!(note.contains("zero"), "{kind:?}: {note}");
        }
    }

    /// Two tags the same would be two menu entries making the same file.
    #[test]
    fn no_two_kinds_share_a_tag() {
        let mut tags: Vec<&str> = Fresh::ALL.iter().map(|kind| kind.tag()).collect();
        tags.sort_unstable();
        let held = tags.len();
        tags.dedup();
        assert_eq!(tags.len(), held);
    }

    /// A slot opened for a look is a working copy that nothing lists, and it goes when
    /// the tab looking at it does.
    #[test]
    fn a_view_is_not_on_this_computer_until_it_is_kept() {
        let ctx = egui::Context::default();
        let mut workspace = Workspace::new(ctx);
        let mut log = Log::default();
        let at = Location { bank: 6, slot: 3 };
        let device = || Origin::Device {
            class: ObjectClass::Program,
            at,
        };

        let viewed = workspace.view(
            "Africa-Split.ne5p".into(),
            device(),
            Fresh::Program.bytes().unwrap(),
            &mut log,
        );
        let copied = workspace.ingest(
            "Squabble-B.ne5p".into(),
            device(),
            Fresh::Program.bytes().unwrap(),
            &mut log,
        );

        assert!(workspace.is_view(viewed) && !workspace.is_view(copied));
        let listed: Vec<u64> = workspace.listed().map(|e| e.id).collect();
        assert_eq!(listed, vec![copied], "a view is not in the local list");
        // It is still an entity in every other way — a tab and a send both find it.
        assert!(workspace.get(viewed).is_some());
        assert_eq!(workspace.entities().len(), 2);

        // Edited, it stays a view; kept, it stops being one and keeps its edit.
        let edited = workspace.get(viewed).unwrap().bytes.clone();
        workspace.replace_bytes(viewed, [edited, vec![]].concat(), &mut log);
        assert!(workspace.is_view(viewed));
        workspace.keep(viewed, &mut log);
        assert!(!workspace.is_view(viewed));
        assert_eq!(workspace.listed().count(), 2);
    }

    /// ⚠️ A view is not on this computer, and the activity log is the record of where a
    /// slot's bytes went. One line, and it says what actually happened.
    #[test]
    fn viewing_a_slot_says_that_and_not_that_it_was_kept() {
        let mut workspace = Workspace::new(egui::Context::default());
        let mut log = Log::default();
        let id = workspace.view(
            "Africa-Split.ne5p".into(),
            Origin::Device {
                class: ObjectClass::Program,
                at: Location { bank: 6, slot: 3 },
            },
            Fresh::Program.bytes().unwrap(),
            &mut log,
        );

        assert!(workspace.is_view(id));
        assert!(log.status().1.starts_with("Viewing "), "{}", log.status().1);
        assert!(
            !log.iter()
                .any(|entry| entry.text.contains("is on this computer.")),
            "a view was never taken onto this computer"
        );
        // The detail of what arrived is still recorded, view or not.
        assert!(log.iter().any(|entry| entry.text.contains("verified")));
    }

    /// ⚠️ A write is what this app knows about a slot without reading it back — the
    /// whole of the Agrees mark for a class whose slots report no checksum. An edit and
    /// the revert of it leave the slot alone, so they must leave that evidence alone.
    #[test]
    fn an_edit_and_a_revert_leave_the_write_this_app_made() {
        let mut workspace = Workspace::new(egui::Context::default());
        let mut log = Log::default();
        let at = Location { bank: 6, slot: 3 };
        let id = workspace.create(Fresh::Program, &mut log).unwrap();
        let sent = workspace.get(id).unwrap().bytes.clone();
        workspace.landed(id, ObjectClass::Program, at, sent.clone());
        let wrote = |workspace: &Workspace| {
            workspace
                .get(id)
                .unwrap()
                .wrote
                .map(|held| (held.class, held.at, held.crc32))
        };
        let landed = wrote(&workspace).expect("a write this app made");

        let (_, edited) =
            crate::fields::apply(&sent, &[("center_panel.gain".into(), "96".into())]).unwrap();
        workspace.replace_bytes(id, edited, &mut log);
        assert_eq!(wrote(&workspace), Some(landed), "an edit is not a write");

        workspace.revert(id, &mut log);
        assert_eq!(wrote(&workspace), Some(landed), "and neither is a revert");
    }

    /// A view outlives nothing: once no tab holds it, it is gone. What was kept stays
    /// whether anything is looking at it or not.
    #[test]
    fn a_view_goes_when_the_last_tab_on_it_closes() {
        let ctx = egui::Context::default();
        let mut workspace = Workspace::new(ctx);
        let mut log = Log::default();
        let at = Location { bank: 6, slot: 3 };
        let viewed = workspace.view(
            "Africa-Split.ne5p".into(),
            Origin::Device {
                class: ObjectClass::Program,
                at,
            },
            Fresh::Program.bytes().unwrap(),
            &mut log,
        );
        let local = workspace.create(Fresh::Program, &mut log).unwrap();

        let queue = Queue::default();
        workspace.close_views(|id| id == viewed, |_| false, &queue, &mut log);
        assert!(workspace.get(viewed).is_some(), "its tab is still open");

        workspace.close_views(|_| false, |_| false, &queue, &mut log);
        assert!(workspace.get(viewed).is_none());
        assert!(workspace.get(local).is_some(), "kept is kept");
    }

    /// ⚠️ The loss this rule exists to stop. A view is the only copy of what it holds —
    /// nothing lists it and the store skips it — so the × on its tab sits next to a
    /// badge saying the edit is owed to a slot, with no undo behind it. An edited view
    /// is kept; only an untouched one is dropped.
    #[test]
    fn a_view_with_changes_in_it_is_kept_rather_than_dropped() {
        let ctx = egui::Context::default();
        let mut workspace = Workspace::new(ctx);
        let mut log = Log::default();
        let at = |slot| Location { bank: 6, slot };
        let view = |workspace: &mut Workspace, slot, log: &mut Log| {
            workspace.view(
                format!("view-{slot}.ne5p"),
                Origin::Device {
                    class: ObjectClass::Program,
                    at: at(slot),
                },
                Fresh::Program.bytes().unwrap(),
                log,
            )
        };

        let edited = view(&mut workspace, 0, &mut log);
        let owed = view(&mut workspace, 1, &mut log);
        let untouched = view(&mut workspace, 2, &mut log);

        let bytes = workspace.get(edited).unwrap().bytes.clone();
        workspace.replace_bytes(edited, [bytes, vec![0]].concat(), &mut log);
        let mut queue = Queue::default();
        crate::queue::enqueue(
            &workspace,
            &mut crate::device::Device::new(workspace.ctx().clone()),
            &mut queue,
            &mut log,
            owed,
            ObjectClass::Program,
            at(1),
        );
        assert!(precious(workspace.get(edited).unwrap(), &queue));
        assert!(precious(workspace.get(owed).unwrap(), &queue));
        assert!(!precious(workspace.get(untouched).unwrap(), &queue));

        // Every tab closes at once.
        workspace.close_views(|_| false, |_| false, &queue, &mut log);

        assert!(workspace.get(untouched).is_none(), "the slot still has it");
        let listed: Vec<u64> = workspace.listed().map(|e| e.id).collect();
        assert_eq!(listed, vec![edited, owed], "and the changes survive");
        assert!(!workspace.is_view(edited) && !workspace.is_view(owed));
        // What was owed is still owed: promoting it must not pay a debt.
        assert!(queue.holds(owed));
        assert!(log.status().1.contains("kept on this computer"));
    }

    /// ⚠️ An edit that has not reached the bytes yet is the same loss: a piano library's
    /// plan is held by the document rather than by the file, and dropping the view would
    /// take it with nothing said.
    #[test]
    fn a_view_whose_edit_is_still_a_plan_is_kept_rather_than_dropped() {
        let ctx = egui::Context::default();
        let mut workspace = Workspace::new(ctx);
        let mut log = Log::default();
        let planning = workspace.view(
            "Africa-Split.ne5p".into(),
            Origin::Device {
                class: ObjectClass::Program,
                at: Location { bank: 6, slot: 3 },
            },
            Fresh::Program.bytes().unwrap(),
            &mut log,
        );
        let queue = Queue::default();
        assert!(!precious(workspace.get(planning).unwrap(), &queue));

        workspace.close_views(|_| false, |id| id == planning, &queue, &mut log);
        assert!(workspace.get(planning).is_some(), "the plan survives");
        assert!(!workspace.is_view(planning), "and is listed to survive in");
    }

    /// ⚠️ A library is hundreds of megabytes. The file the operator picked is replaced
    /// only by a rename, so a write that stops halfway leaves what was there; and
    /// nothing is left beside it whether the write lands or not.
    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn a_save_lands_whole_and_leaves_no_temporary_beside_it() {
        let dir = std::env::temp_dir().join("drawbar-save-beside");
        std::fs::create_dir_all(&dir).expect("a directory to save into");
        let path = dir.join("Royal Grand.npno");
        std::fs::write(&path, b"what was there before").expect("a file to replace");

        write_beside(&path, b"the bytes the editor made").expect("it writes");
        assert_eq!(
            std::fs::read(&path).expect("it is there"),
            b"the bytes the editor made"
        );
        let left: Vec<std::ffi::OsString> = std::fs::read_dir(&dir)
            .expect("it is still a directory")
            .map(|entry| entry.expect("an entry").file_name())
            .collect();
        assert_eq!(left, [path.file_name().expect("a name")], "{left:?}");

        let nowhere = dir.join("no-such-folder").join("Royal Grand.npno");
        assert!(write_beside(&nowhere, b"anything").is_err());
        assert!(!nowhere.with_extension("npno.tmp").exists());
        std::fs::remove_dir_all(&dir).ok();
    }

    /// One view per slot, so a second double-click has something to be pointed at rather
    /// than a second working copy to make.
    #[test]
    fn a_slot_has_at_most_one_view() {
        let ctx = egui::Context::default();
        let mut workspace = Workspace::new(ctx);
        let mut log = Log::default();
        let at = Location { bank: 6, slot: 3 };
        let elsewhere = Location { bank: 6, slot: 4 };
        let class = ObjectClass::Program;

        assert_eq!(workspace.view_of(class, at), None);
        let id = workspace.view(
            "Africa-Split.ne5p".into(),
            Origin::Device { class, at },
            Fresh::Program.bytes().unwrap(),
            &mut log,
        );
        assert_eq!(workspace.view_of(class, at), Some(id));
        assert_eq!(workspace.view_of(class, elsewhere), None);
        assert_eq!(workspace.view_of(ObjectClass::SetList, at), None);

        // A copy on this computer is not a view of the slot, however it got here.
        workspace.ingest(
            "Africa-Split.ne5p".into(),
            Origin::Device { class, at },
            Fresh::Program.bytes().unwrap(),
            &mut log,
        );
        assert_eq!(workspace.view_of(class, at), Some(id));
        // And once the view is kept, the slot has none.
        workspace.keep(id, &mut log);
        assert_eq!(workspace.view_of(class, at), None);
    }

    /// The raw-body export is the file with its container stripped — for a type-1
    /// file, everything from `body_start` on.
    #[test]
    fn the_raw_body_export_drops_the_container_header() {
        let entity = ingest("untitled.ne5p", Fresh::Program.bytes().unwrap());
        let body = entity.raw_body().expect("a CBIN file has a body");
        assert_eq!(body.len(), ne5::program::BODY_LEN);
        assert_eq!(
            body.as_slice(),
            &entity.bytes[Generation::V1.body_start() as usize..],
        );
    }

    /// The name is verbatim everywhere; only the export dialog sees a path-safe form,
    /// with the extension supplied from the bytes when the name carries none.
    #[test]
    fn an_export_sanitises_the_name_and_supplies_the_extension() {
        let bytes = Fresh::Program.bytes().unwrap();
        let file = |name: &str| export_filename(name, &bytes);
        assert_eq!(file("Big strings"), "Big-strings.ne5p");
        assert_eq!(file("patch.ne5p"), "patch.ne5p", "a carried tag is kept");
        assert_eq!(file("Bass 2.0"), "Bass-2.0.ne5p", "a dot is not a tag");
        assert_eq!(file("../../etc/passwd"), "etc-passwd.ne5p");
        assert_eq!(file("  "), "unnamed.ne5p");
        assert_eq!(
            export_filename("Big strings", b"no header"),
            "Big-strings.bin",
        );
    }

    #[test]
    fn a_zone_wav_is_named_after_its_instrument_and_number() {
        assert_eq!(zone_wav_name("Bass Clarinet", 2), "Bass-Clarinet-zone2.wav");
        assert_eq!(zone_wav_name("../../etc/passwd", 1), "etc-passwd-zone1.wav");
        assert_eq!(zone_wav_name("  ", 1), "unnamed-zone1.wav");
    }

    #[test]
    fn bytes_carry_a_stamp_that_changes_only_when_they_do() {
        let ctx = egui::Context::default();
        let mut workspace = Workspace::new(ctx);
        let mut log = Log::default();

        let id = workspace.create(Fresh::Program, &mut log).unwrap();
        let opened = workspace.get(id).unwrap().bytes.clone();
        let stamp = |workspace: &Workspace| workspace.get(id).unwrap().stamp;
        let first = stamp(&workspace);

        workspace.rename(id, "Africa-Split".into());
        assert_eq!(stamp(&workspace), first, "the bytes did not move");

        let (_, edited) =
            crate::fields::apply(&opened, &[("center_panel.gain".into(), "96".into())]).unwrap();
        workspace.replace_bytes(id, edited, &mut log);
        let second = stamp(&workspace);
        assert_ne!(second, first);

        workspace.revert(id, &mut log);
        let third = stamp(&workspace);
        assert_ne!(third, second);
        assert_ne!(third, first, "back to the same bytes is still a new decode");

        // Putting back what is already there is not a change and spends nothing.
        workspace.revert(id, &mut log);
        assert_eq!(stamp(&workspace), third);
    }

    /// Unsaved is not a flag anything sets: it is holding bytes other than the ones this
    /// asset was last saved as. An edit makes it so, saving and reverting each end it.
    #[test]
    fn an_asset_is_unsaved_while_it_holds_something_its_baseline_does_not() {
        let ctx = egui::Context::default();
        let mut workspace = Workspace::new(ctx);
        let mut log = Log::default();

        let id = workspace.create(Fresh::Program, &mut log).unwrap();
        let opened = workspace.get(id).unwrap().bytes.clone();
        let unsaved = |workspace: &Workspace| workspace.get(id).unwrap().is_unsaved();
        assert!(!unsaved(&workspace), "a fresh asset starts saved");

        let (_, edited) =
            crate::fields::apply(&opened, &[("center_panel.gain".into(), "96".into())]).unwrap();
        workspace.replace_bytes(id, edited.clone(), &mut log);
        assert!(unsaved(&workspace));
        assert_eq!(workspace.get(id).unwrap().saved.bytes, opened);

        // Saving moves the baseline onto what it holds; the bytes do not move.
        workspace.mark_saved(id);
        assert!(!unsaved(&workspace));
        assert_eq!(workspace.get(id).unwrap().saved.bytes, edited);
        assert_eq!(workspace.get(id).unwrap().bytes, edited);

        // Reverting moves the bytes back onto the baseline, which stays where it is.
        let (_, again) =
            crate::fields::apply(&edited, &[("center_panel.gain".into(), "12".into())]).unwrap();
        workspace.replace_bytes(id, again, &mut log);
        assert!(unsaved(&workspace));
        workspace.revert(id, &mut log);
        assert!(!unsaved(&workspace));
        assert_eq!(workspace.get(id).unwrap().bytes, edited);

        // And an edit unmade by hand is the baseline again, whatever route it took.
        let (_, away) =
            crate::fields::apply(&edited, &[("center_panel.gain".into(), "12".into())]).unwrap();
        workspace.replace_bytes(id, away, &mut log);
        assert!(unsaved(&workspace));
        workspace.replace_bytes(id, edited, &mut log);
        assert!(!unsaved(&workspace), "it holds what it was saved as again");
    }

    /// A write that reached a slot saves the bytes it carried and not the ones the
    /// asset holds now: an edit made while the write was in flight is on this computer
    /// alone, and calling it saved would let it be discarded with the tab it is in.
    #[test]
    fn a_write_that_landed_saves_what_it_carried_rather_than_a_later_edit() {
        let mut workspace = Workspace::new(egui::Context::default());
        let mut log = Log::default();
        let at = Location { bank: 6, slot: 3 };
        let id = workspace.create(Fresh::Program, &mut log).unwrap();
        let sent = workspace.get(id).unwrap().bytes.clone();

        let (_, edited) =
            crate::fields::apply(&sent, &[("center_panel.gain".into(), "96".into())]).unwrap();
        workspace.replace_bytes(id, edited.clone(), &mut log);
        workspace.landed(id, ObjectClass::Program, at, sent.clone());
        assert!(
            workspace.get(id).unwrap().is_unsaved(),
            "the edit made in flight is still owed"
        );
        assert_eq!(workspace.get(id).unwrap().saved.bytes, sent);

        workspace.landed(id, ObjectClass::Program, at, edited);
        assert!(
            !workspace.get(id).unwrap().is_unsaved(),
            "a write of what it holds leaves nothing owed"
        );
    }

    /// The baseline's checksum is the one a slot holding those bytes reports, so a saved
    /// asset and its slot are compared without either body being hashed again.
    #[test]
    fn the_baseline_carries_the_checksum_a_slot_holding_it_reports() {
        let entity = ingest("untitled.ne5p", Fresh::Program.bytes().unwrap());
        let body = nord_usb::envelope::unwrap(&entity.bytes).expect("a file the wire takes");
        assert_eq!(
            entity.saved.crc32,
            Some(nord_usb::envelope::crc32(&body.body.0))
        );
    }

    /// A project is text, so nothing at the CBIN tag offset means anything —
    /// the export must not read one out of the prose, and the long extension
    /// counts as carried.
    #[test]
    fn a_project_export_keeps_its_own_extension() {
        let project = nord_format::formats::nsmpproj::Project::new(
            "One",
            &[nord_format::formats::nsmpproj::NewZone {
                path: "one.wav".into(),
                sample_rate: 44100,
                frames: 44100,
                root_key: 60,
            }],
            0,
        )
        .unwrap();
        let bytes = nord_format::to_bytes(&Entity::SampleProject(project)).unwrap();
        assert_eq!(
            export_filename("proj.nsmpproj", &bytes),
            "proj.nsmpproj",
            "a carried project extension is kept"
        );
        assert_eq!(export_filename("My Kit", &bytes), "My-Kit.nsmpproj");
    }

    /// A file that does not decode is still a row: the error is the report.
    #[test]
    fn bytes_that_do_not_decode_are_kept_with_their_error() {
        let entity = ingest("junk.bin", b"not a nord file at all".to_vec());
        assert!(entity.entity.is_none());
        assert!(entity.parse_error.is_some());
        assert!(entity.container.is_none());
        assert!(matches!(entity.verify, VerifyState::NotApplicable(_)));
        assert_eq!(entity.tag(), "?");
    }

    /// The name is this app's metadata and the only record of what an object is — a
    /// file stores none. It has to survive the whole way: off the instrument, into a
    /// tab, through an edit, out to a filename.
    #[test]
    fn a_name_survives_being_fetched_opened_edited_and_exported() {
        use nord_usb::{Location, ObjectClass};

        let ctx = egui::Context::default();
        let mut workspace = Workspace::new(ctx);
        let mut log = Log::default();
        let at = Location { bank: 6, slot: 3 };

        // As a read off the instrument arrives: the device supplies the name, nothing
        // else ever does.
        let id = workspace.ingest(
            "Africa-Split.ne5p".into(),
            Origin::Device {
                class: ObjectClass::Program,
                at,
            },
            Fresh::Program.bytes().unwrap(),
            &mut log,
        );
        assert_eq!(workspace.get(id).unwrap().name, "Africa-Split.ne5p");

        // An edit: new bytes, same name.
        let bytes = workspace.get(id).unwrap().bytes.clone();
        let (_, edited) =
            crate::fields::apply(&bytes, &[("center_panel.gain".into(), "96".into())]).unwrap();
        workspace.replace_bytes(id, edited, &mut log);
        assert_eq!(workspace.get(id).unwrap().name, "Africa-Split.ne5p");
        assert!(workspace.get(id).unwrap().is_unsaved());

        // Reverting is not renaming either.
        workspace.revert(id, &mut log);
        assert_eq!(workspace.get(id).unwrap().bytes, bytes);
        assert_eq!(workspace.get(id).unwrap().name, "Africa-Split.ne5p");

        // And the filename an export offers is that same name, not one worked back out
        // of the bytes.
        assert_eq!(
            workspace.export_name(id).as_deref(),
            Some("Africa-Split.ne5p")
        );
    }

    /// What a previous session held comes back decoded and checked, keeping its name,
    /// its origin and its id.
    #[test]
    fn a_restored_asset_keeps_what_it_was() {
        let ctx = egui::Context::default();
        let mut workspace = Workspace::new(ctx);
        let mut log = Log::default();
        workspace.restore(
            vec![Saved {
                id: 9,
                name: "Africa-Split.ne5p".into(),
                origin: Origin::Fresh,
                saved: Fresh::Program.bytes().unwrap(),
                unsaved: None,
            }],
            Some(10),
            &mut log,
        );
        let entity = workspace.get(9).expect("restored under its own id");
        assert_eq!(entity.name, "Africa-Split.ne5p");
        assert!(matches!(entity.verify, VerifyState::Ok));
        assert!(!entity.is_unsaved());
        // A new asset cannot land on an id something restored is already using.
        let fresh = workspace.create(Fresh::Live, &mut log).unwrap();
        assert!(fresh >= 10);
    }

    /// A flipped body byte is reported rather than absorbed: the container's own
    /// checksum no longer matches, and the decode says so.
    #[test]
    fn a_tampered_body_byte_is_reported() {
        let mut bytes = Fresh::Program.bytes().unwrap();
        let at = Generation::V1.body_start() as usize + 0x30;
        bytes[at] ^= 0xff;
        let entity = ingest("tampered.ne5p", bytes);
        assert!(entity.parse_error.is_some());
        assert!(!entity.container.expect("still a CBIN file").checksum_ok);
    }
}