drawbar 0.6.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
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
//! The library: one table over every kind, in both places.
//!
//! A [`Row`] is what the table knows about one thing — where it is, where it goes, how
//! big it is, what it plays — and it is built from the list on this computer and the
//! scanned slots without a frame in sight. [`arrange`] narrows and orders a set of them.
//! Everything under those two is paint.

use std::cmp::Ordering;
use std::collections::BTreeSet;
use std::ops::Range;

use eframe::egui;
use nord_format::accept::Family;
use nord_usb::wire::ProgramInfo;
use nord_usb::{Location, ObjectClass};

use crate::app::{accent, micro, ui as ui_text, warn};
use crate::browser::{cell_ink, families_present, qualifier, Act, Browser, Bulk, Item, Kind};
use crate::device::{fit, read_only, Device, DeviceState};
use crate::filter::{Filter, Narrow, Place, State};
use crate::icon::{icon, painted, Glyph};
use crate::panel::{chip, Track};
use crate::queue::{Diff, Queue};
use crate::shell::{Page, Shell};
use crate::strings::{folder, place, shown};
use crate::tags::Tags;
use crate::workspace::{LocalEntity, Workspace};

/// Which of the two places a row's contents are in.
///
/// ⚠️ `Both` is a **link**: a slot this asset was matched to — see
/// [`crate::device::link`]. Its sign says whether the two still agree, which saving an
/// edit here turns to `false` while the link stays where it was.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Where {
    /// A link, and whether the two still agree — see [`agrees`]. `None` is a link the
    /// two places cannot be compared across.
    Both(Option<bool>),
    Computer,
    /// On this computer, and the attached instrument is not the one whose files these
    /// are. It is in one place and can only stay there.
    Foreign,
    Keyboard,
    /// It came off a slot nothing has read, so the other copy cannot be spoken about.
    Unread,
}

impl Where {
    /// The short word the column carries.
    pub fn short(self) -> &'static str {
        match self {
            Where::Both(Some(true)) => "both =",
            Where::Both(Some(false)) => "both ≠",
            Where::Both(None) => "both",
            Where::Computer | Where::Foreign => "computer",
            Where::Keyboard => "keyboard",
            Where::Unread => "",
        }
    }

    /// The whole of it, which is what the tooltip says.
    pub fn sentence(self) -> &'static str {
        match self {
            Where::Both(Some(true)) => "On this computer and in a slot holding these very bytes.",
            Where::Both(Some(false)) => {
                "On this computer and in a slot it was matched to, and the two bodies \
                 no longer agree."
            }
            Where::Both(None) => {
                "On this computer and in a slot matched by name. Nothing here can say \
                 whether the two bodies agree."
            }
            Where::Computer => "On this computer only.",
            Where::Foreign => "On this computer only — not for this keyboard.",
            Where::Keyboard => "On the instrument only.",
            Where::Unread => "It came off a slot this session has not read.",
        }
    }

    /// The places it is in, which is what a place filter asks about.
    fn places(self) -> &'static [Place] {
        match self {
            Where::Both(_) => &[Place::Computer, Place::Keyboard],
            Where::Computer | Where::Foreign | Where::Unread => &[Place::Computer],
            Where::Keyboard => &[Place::Keyboard],
        }
    }

    /// Both first, then this computer, the instrument, and the unsayable.
    fn rank(self) -> u8 {
        match self {
            Where::Both(Some(false)) => 0,
            Where::Both(None) => 1,
            Where::Both(Some(true)) => 2,
            Where::Computer => 3,
            Where::Foreign => 4,
            Where::Keyboard => 5,
            Where::Unread => 6,
        }
    }
}

/// The library object a row plays that the row's own bytes do not carry.
///
/// ⚠️ A name can only come from the instrument — a program file stores a bare id and no
/// name at all — so `Wanted` is an id **nothing has resolved**, never one the instrument
/// said it did not hold. No read this app makes reports a missing library.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Needs {
    Nothing,
    Named { class: ObjectClass, name: String },
    Wanted { class: ObjectClass, id: u32 },
}

impl Needs {
    /// The words the column carries.
    pub fn text(&self) -> String {
        match self {
            Needs::Nothing => String::new(),
            Needs::Named { name, .. } => name.clone(),
            Needs::Wanted { class, id } => {
                format!("{} {id:#010x}", Kind::from_class(*class).chip())
            }
        }
    }

    /// The whole of it, which is what the tooltip says.
    pub fn sentence(&self) -> String {
        match self {
            Needs::Nothing => "Nothing here says what it plays.".to_string(),
            Needs::Named { class, name } => format!(
                "It plays the {} the instrument calls “{name}”.",
                Kind::from_class(*class).chip()
            ),
            Needs::Wanted { class, id } => format!(
                "This names a {} the instrument has not listed by id ({id:#010x}). Only the \
                 instrument can put a name to one, and only for a slot it has been asked \
                 about.",
                Kind::from_class(*class).chip()
            ),
        }
    }

    fn short(&self) -> Option<ObjectClass> {
        match self {
            Needs::Wanted { class, .. } => Some(*class),
            _ => None,
        }
    }
}

/// One line of the library.
pub struct Row {
    pub item: Item,
    pub kind: Kind,
    /// The family to put in front of the kind's word, where the word alone would not say
    /// whose files these are. [`crate::browser::qualified`] is the rule.
    pub family: Option<Family>,
    pub name: String,
    pub tags: usize,
    /// It holds something other than what it was last saved as. Only a row on this
    /// computer can: a slot holds what it holds.
    pub unsaved: bool,
    pub where_: Where,
    /// The slot it came off, or the slot it is. Nothing on this computer that never came
    /// off one has an address at all.
    pub at: Option<(ObjectClass, Location)>,
    pub size: u64,
    pub needs: Needs,
}

impl Row {
    /// Where a send would write this row, which is [`crate::device::read_only`]'s rule
    /// over an asset that came off a slot. A row that is already on the instrument goes
    /// nowhere.
    fn destination(&self) -> Option<(ObjectClass, Location)> {
        let (class, at) = self.at?;
        (matches!(self.item, Item::Local(_)) && !read_only(class)).then_some((class, at))
    }
}

/// Everything the library holds, narrowed by kind, place and tags.
///
/// The list on this computer comes first, and a slot one of its assets came off is that
/// asset's row rather than a second one: a program read off 7:4 and kept is one thing in
/// two places, which is what [`Where::Both`] says.
pub fn rows(
    workspace: &Workspace,
    device: &DeviceState,
    queue: &Queue,
    tags: &Tags,
    filter: &Filter,
) -> Vec<Row> {
    let mut rows = Vec::new();
    let mut claimed: Vec<(ObjectClass, Location)> = Vec::new();
    let kept = families_present(workspace);
    let instrument = device.product().and_then(Family::from_product);
    for entity in workspace.listed() {
        // The slot the row stands for, so the instrument's own list does not repeat it.
        if let Some(slot) = entity.spot() {
            claimed.push(slot);
        }
        let worn = tags.worn(entity.id);
        let row = local(entity, device, queue, worn.len(), &kept, instrument);
        let state = state(row.item, row.where_, queue);
        if admits(filter, &row, worn, state) {
            rows.push(row);
        }
    }
    let untagged = BTreeSet::new();
    for class in device.classes() {
        for bank in device.banks_of(class) {
            let Some(slots) = device.bank(class, bank) else {
                continue;
            };
            for (index, held) in slots.iter().enumerate() {
                let Some(info) = held else {
                    continue;
                };
                let at = Location::from_user(bank, index as u32 + 1);
                if claimed.contains(&(class, at)) {
                    continue;
                }
                let row = slot(class, at, info, device);
                if admits(filter, &row, &untagged, None) {
                    rows.push(row);
                }
            }
        }
    }
    rows
}

/// Whether a row survives the narrowing. A row in both places survives a filter naming
/// either of them.
fn admits(filter: &Filter, row: &Row, tags: &BTreeSet<u64>, state: Option<State>) -> bool {
    row.where_
        .places()
        .iter()
        .any(|place| filter.admits(row.kind, *place, tags, state))
}

/// What a row wants doing about it: a write already waiting, or a slot that no longer
/// holds what this row was last saved as. A slot on the instrument wants nothing —
/// it *is* what the instrument holds.
///
/// ⚠️ A queued row is waiting rather than differing, however the two bodies compare. The
/// write already agreed to is what settles them, so counting it under both would ask
/// twice for one thing.
pub fn state(item: Item, where_: Where, queue: &Queue) -> Option<State> {
    match item {
        Item::Local(id) if queue.holds(id) => Some(State::Waiting),
        Item::Local(_) => (where_ == Where::Both(Some(false))).then_some(State::Differs),
        _ => None,
    }
}

/// How many rows the two places hold differently with no write waiting to settle it —
/// the count the tree's row and the library's chip both carry.
pub fn differing(workspace: &Workspace, device: &DeviceState, queue: &Queue) -> usize {
    workspace
        .listed()
        .filter(|entity| {
            state(
                Item::Local(entity.id),
                whereabouts(entity, device, queue),
                queue,
            ) == Some(State::Differs)
        })
        .count()
}

/// The row one item makes, for a caller holding an item rather than the whole table.
///
/// The same two builders [`rows`] uses, so what the inspector reads about a picked row
/// is what the table shows on it. A folder or a tag is a grouping rather than a thing,
/// and makes no row.
pub fn row_of(
    item: Item,
    workspace: &Workspace,
    device: &DeviceState,
    queue: &Queue,
    tags: &Tags,
) -> Option<Row> {
    match item {
        Item::Local(id) => {
            let entity = workspace.get(id)?;
            let instrument = device.product().and_then(Family::from_product);
            Some(local(
                entity,
                device,
                queue,
                tags.worn(id).len(),
                &families_present(workspace),
                instrument,
            ))
        }
        Item::Slot { class, at } => {
            Some(slot(class, at, device.slot(class, at).flatten()?, device))
        }
        Item::Folder(_) | Item::Tag(_) => None,
    }
}

fn local(
    entity: &LocalEntity,
    device: &DeviceState,
    queue: &Queue,
    tags: usize,
    kept: &[Family],
    instrument: Option<Family>,
) -> Row {
    Row {
        item: Item::Local(entity.id),
        kind: Kind::of(entity.entity.as_ref()),
        family: qualifier(entity, kept, instrument),
        name: entity.name.clone(),
        tags,
        unsaved: entity.is_unsaved(),
        where_: whereabouts(entity, device, queue),
        at: entity.spot(),
        size: entity.bytes.len() as u64,
        needs: wanted(entity, device),
    }
}

fn slot(class: ObjectClass, at: Location, info: &ProgramInfo, device: &DeviceState) -> Row {
    Row {
        item: Item::Slot { class, at },
        kind: Kind::from_class(class),
        // What is on the instrument is the instrument's own; the word never needs it.
        family: None,
        name: info.name.trim().to_string(),
        tags: 0,
        unsaved: false,
        where_: Where::Keyboard,
        at: Some((class, at)),
        size: u64::from(info.body_len),
        needs: played(class, at, device),
    }
}

/// Where a row's contents are, which for anything on this computer is decided by its
/// link: a linked asset is in both places, and the sign is [`agrees`].
fn whereabouts(entity: &LocalEntity, device: &DeviceState, queue: &Queue) -> Where {
    let held = entity
        .link
        .and_then(|(class, at)| Some((class, device.slot(class, at).flatten()?)));
    let Some((class, info)) = held else {
        if !fit(device, entity).allowed() {
            return Where::Foreign;
        }
        return match entity.origin.slot() {
            Some((class, at)) if device.slot(class, at).is_none() => Where::Unread,
            _ => Where::Computer,
        };
    };
    Where::Both(agrees(entity, class, info, queue))
}

/// Whether the slot an asset stands for still holds what that asset was last saved as.
///
/// The one comparison behind the library's sign, the tree's dot and what a "queue
/// changed" walks. Equality is claimed only where something says so:
///
/// - the checksum a walk reported for the slot against the checksum of the saved bytes,
///   which is read once at ingest and nothing hashes again;
/// - a write this app made into that slot, whose bytes are the ones it is saved as —
///   the one thing it knows about a slot without reading it back;
/// - a compare read that fetched the occupant and found the bodies equal.
///
/// ⚠️ `None` where none of them answers, which is *not known* rather than *the same*.
/// An address and a length are not evidence: a class reporting no checksum is linked by
/// name or by being the only slot there is, and neither says anything about the body in
/// it. Only a read settles one of those.
pub fn agrees(
    entity: &LocalEntity,
    class: ObjectClass,
    info: &ProgramInfo,
    queue: &Queue,
) -> Option<bool> {
    if let (Some(here), Some(there)) = (entity.saved.crc32, info.crc32) {
        return Some(here == there);
    }
    if wrote(entity, class, info.location) {
        return Some(true);
    }
    match queue.entry(entity.id).map(|held| &held.diff) {
        Some(Diff::Identical) => Some(true),
        Some(Diff::Fields(_) | Diff::Bytes { .. }) => Some(false),
        _ => None,
    }
}

/// Whether this app wrote what the asset is saved as into this very slot.
///
/// ⚠️ The checksums are the two sets of bytes: a save of anything else moves the
/// baseline off the bytes the write put there, and the write stops answering for it.
fn wrote(entity: &LocalEntity, class: ObjectClass, at: Location) -> bool {
    entity.wrote.is_some_and(|wrote| {
        (wrote.class, wrote.at) == (class, at) && Some(wrote.crc32) == entity.saved.crc32
    })
}

/// What a mark on a row claims: the dot the tree paints at a row's right end, the ink
/// the table's WHERE cell carries, and the star a name wears.
///
/// Four of them, and every one is explained by [`mark_words`] wherever it is drawn.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mark {
    Agrees,
    Differs,
    /// A slot nothing can say either way about, which is the unsigned `both` of
    /// [`Where::Both`].
    Unknown,
    Unsaved,
}

/// The ink a mark is painted in, wherever it is painted.
pub fn mark_ink(mark: Mark, visuals: &egui::Visuals) -> egui::Color32 {
    match mark {
        Mark::Agrees => crate::app::good(visuals),
        Mark::Differs => warn(visuals),
        Mark::Unknown => crate::app::caption(visuals),
        Mark::Unsaved => visuals.text_color(),
    }
}

/// What a mark says, in the only words that explain it.
///
/// The one place these are written: a dot's hover, a coloured WHERE cell's, and each
/// part of the queue's count line — so that line reads as the legend for every mark in
/// the window.
pub fn mark_words(mark: Mark) -> &'static str {
    match mark {
        Mark::Agrees => "on the keyboard, the same as saved here",
        Mark::Differs => {
            "on the keyboard, but different from what is saved here, or waiting to be sent"
        }
        Mark::Unknown => "on the keyboard; whether it matches is not known yet",
        Mark::Unsaved => "edited since it was last saved",
    }
}

/// The mark a local row wears at its right end: what the attached instrument holds where
/// this asset stands.
///
/// ⚠️ The one rule, and the only dot a local row wears. Nothing at all is an asset with
/// no slot to stand on — its link, which is the slot [`whereabouts`] reads and no other.
pub fn keyboard_mark(entity: &LocalEntity, device: &DeviceState, queue: &Queue) -> Option<Mark> {
    let (class, at) = entity.link?;
    let info = device.slot(class, at).flatten()?;
    if queue.holds(entity.id) {
        return Some(Mark::Differs);
    }
    match agrees(entity, class, info, queue) {
        Some(true) => Some(Mark::Agrees),
        Some(false) => Some(Mark::Differs),
        // A green dot is a claim, and nothing here has the evidence to make one.
        None => Some(Mark::Unknown),
    }
}

/// The library a file names, and the name the instrument gave it if it has been asked.
pub(crate) fn wanted(entity: &LocalEntity, device: &DeviceState) -> Needs {
    let Some(fields) = entity.entity.as_ref().and_then(crate::fields::fields_of) else {
        return Needs::Nothing;
    };
    // One cell, so the first of the two a program can name is the one it shows.
    for (path, class) in [
        ("piano_panel.id", ObjectClass::Piano),
        ("sample_panel.id", ObjectClass::Sample),
    ] {
        // Zero is "this program references no library", not an id to go looking for.
        let Some(id) = fields
            .iter()
            .find(|field| field.path == path)
            .and_then(|field| crate::document::library_id(&field.value))
            .filter(|id| *id != 0)
        else {
            continue;
        };
        return match device.dependency_name(entity.origin.slot(), class, id) {
            Some(name) => Needs::Named {
                class,
                name: name.to_string(),
            },
            None => Needs::Wanted { class, id },
        };
    }
    Needs::Nothing
}

/// What the instrument said a slot plays, where that slot is the one it was last asked
/// about.
///
/// ⚠️ Programs only: the piano or sample a program plays is what this column stands for.
fn played(class: ObjectClass, at: Location, device: &DeviceState) -> Needs {
    if class != ObjectClass::Program || device.detail.at != Some((class, at)) {
        return Needs::Nothing;
    }
    let Some(deps) = device.detail.deps.as_ref() else {
        return Needs::Nothing;
    };
    deps.iter()
        // ⚠️ `flag` is whether the section owning it is routed; an unrouted row names a
        // library the program does not play.
        .filter(|dep| dep.flag == 1)
        .find(|dep| matches!(dep.class, ObjectClass::Piano | ObjectClass::Sample))
        .map_or(Needs::Nothing, |dep| Needs::Named {
            class: dep.class,
            name: dep.name.trim().to_string(),
        })
}

/// One column of the table.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Column {
    Mark,
    Glyph,
    Kind,
    Name,
    Tags,
    Where,
    At,
    Size,
    Needs,
}

/// Which way a column is sorted.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Order {
    Up,
    Down,
}

impl Order {
    fn flipped(self) -> Order {
        match self {
            Order::Up => Order::Down,
            Order::Down => Order::Up,
        }
    }
}

impl Column {
    pub const ALL: [Column; 9] = [
        Column::Mark,
        Column::Glyph,
        Column::Kind,
        Column::Name,
        Column::Tags,
        Column::Where,
        Column::At,
        Column::Size,
        Column::Needs,
    ];

    /// The word over the column. The two that carry a mark rather than a word have none.
    fn head(self) -> &'static str {
        match self {
            Column::Mark | Column::Glyph => "",
            Column::Kind => "kind",
            Column::Name => "name",
            Column::Tags => "tags",
            Column::Where => "where",
            Column::At => "at",
            Column::Size => "size",
            Column::Needs => "needs",
        }
    }

    /// Where this column sits in a row, which is where its track is.
    fn index(self) -> usize {
        match self {
            Column::Mark => 0,
            Column::Glyph => 1,
            Column::Kind => 2,
            Column::Name => 3,
            Column::Tags => 4,
            Column::Where => 5,
            Column::At => 6,
            Column::Size => 7,
            Column::Needs => 8,
        }
    }

    /// What the column asks for: a fixed width, or a share of what the fixed ones leave.
    fn track(self) -> Track {
        match self {
            Column::Mark => Track::Px(18.0),
            Column::Glyph => Track::Px(20.0),
            // A kind is a handful of known words, and 96 px holds the longest of them —
            // asked for as a share so a narrow centre spends the room on the name.
            Column::Kind => Track::Capped {
                share: 0.7,
                max: 96.0,
            },
            Column::Name => Track::Share(1.9),
            Column::Tags => Track::Px(38.0),
            Column::Where => Track::Px(64.0),
            Column::At => Track::Px(50.0),
            Column::Size => Track::Px(54.0),
            Column::Needs => Track::Share(1.3),
        }
    }
}

/// The gap between two columns.
const GAP: f32 = 8.0;

/// Where each column sits across `width`, laid out by [`crate::panel::tracks`].
pub fn tracks(width: f32) -> [Range<f32>; 9] {
    let wanted = Column::ALL.map(Column::track);
    let held = crate::panel::tracks(width, &wanted, GAP);
    std::array::from_fn(|index| held[index].clone())
}

/// The rows the table shows: what the omnibox admits, in the order a column asks for.
///
/// ⚠️ Ties break on the name and then the row itself, so the order does not depend on
/// the order the rows happened to be built in.
pub fn arrange(mut rows: Vec<Row>, query: &str, by: Column, order: Order) -> Vec<Row> {
    let query = query.trim().to_lowercase();
    if !query.is_empty() {
        rows.retain(|row| row.name.to_lowercase().contains(&query));
    }
    rows.sort_by(|a, b| {
        let ranked = match order {
            Order::Up => compare(by, a, b),
            Order::Down => compare(by, a, b).reverse(),
        };
        ranked
            .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
            .then_with(|| a.item.cmp(&b.item))
    });
    rows
}

fn compare(by: Column, a: &Row, b: &Row) -> Ordering {
    match by {
        // A mark is a control rather than a fact about the row, so its head sorts
        // nothing and the tie-breakers stand.
        Column::Mark => Ordering::Equal,
        // The glyph and the word beside it are the same fact, so a click on either
        // orders the table the same way.
        Column::Glyph | Column::Kind => word(a).cmp(&word(b)),
        Column::Name => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
        Column::Tags => a.tags.cmp(&b.tags),
        Column::Where => a.where_.rank().cmp(&b.where_.rank()),
        Column::At => address(a).cmp(&address(b)),
        Column::Size => a.size.cmp(&b.size),
        Column::Needs => a.needs.text().cmp(&b.needs.text()),
    }
}

/// The word the KIND column carries, which is what the glyph beside it stands for.
fn word(row: &Row) -> String {
    crate::strings::kind_word(row.kind, row.family)
}

/// A row with no address sorts after every row that has one, rather than at `0:0`.
fn address(row: &Row) -> (bool, u32, u32, u32) {
    match row.at {
        Some((class, at)) => (false, class.to_raw(), at.bank, at.slot),
        None => (true, 0, 0, 0),
    }
}

/// What sending the picked rows would do, in one sentence.
pub fn consequence(rows: &[&Row], device: &DeviceState, queue: &Queue) -> String {
    let mut going: Vec<(ObjectClass, Location)> =
        rows.iter().filter_map(|row| row.destination()).collect();
    going.sort_unstable_by_key(|(class, at)| (class.to_raw(), at.bank, at.slot));

    let mut said = Vec::new();
    if !going.is_empty() {
        said.push(format!("{}", spans(&going)));
        let occupied = going
            .iter()
            .filter(|(class, at)| device.slot(*class, *at).flatten().is_some())
            .count();
        said.push(match occupied {
            0 => "every slot is empty".to_string(),
            1 => "1 slot occupied".to_string(),
            n => format!("{n} slots occupied"),
        });
    }
    let mine = rows.iter().filter(|row| matches!(row.item, Item::Local(_)));
    let (fits, of) = mine.fold((0, 0), |(fits, of), row| {
        (fits + usize::from(row.where_ != Where::Foreign), of + 1)
    });
    if let Some(unfit) = device
        .product()
        .and_then(|product| crate::strings::fitting(fits, of, product))
    {
        said.push(unfit);
    }
    let waiting = rows
        .iter()
        .filter(|row| matches!(row.item, Item::Local(id) if queue.holds(id)))
        .count();
    if waiting > 0 {
        said.push(format!("{waiting} already waiting"));
    }
    for class in [ObjectClass::Piano, ObjectClass::Sample] {
        let short = rows
            .iter()
            .filter(|row| row.needs.short() == Some(class))
            .count();
        let named = Kind::from_class(class).chip();
        match short {
            0 => {}
            1 => said.push(format!("1 needs a {named} the instrument has not named")),
            n => said.push(format!("{n} need a {named} the instrument has not named")),
        }
    }
    match said.is_empty() {
        true => "Nothing picked goes to the instrument.".to_string(),
        false => said.join(" · "),
    }
}

/// The destinations as one run per folder: `Programs 7:1–7:4`, in the order `going` is
/// sorted into.
fn spans(going: &[(ObjectClass, Location)]) -> String {
    let mut folders: Vec<ObjectClass> = going.iter().map(|(class, _)| *class).collect();
    folders.dedup();
    let mut runs: Vec<String> = Vec::new();
    for class in folders {
        let mut ats = going
            .iter()
            .filter(|(held, _)| *held == class)
            .map(|(_, at)| *at);
        let Some(first) = ats.next() else {
            continue;
        };
        let last = ats.next_back().unwrap_or(first);
        runs.push(match first == last {
            true => place(class, first),
            false => format!("{} {}{}", folder(class), shown(first), shown(last)),
        });
    }
    runs.join(", ")
}

/// The height of a row, of the head over them, and of the bar over that.
const ROW: f32 = 24.0;
const HEAD: f32 = 20.0;
const BAR: f32 = 28.0;

/// The room the bar, the table and the footer keep at each end.
///
/// ⚠️ The table's is the tree's own row indent. Without it the first track starts at the
/// panel's edge and the mark's left stroke is painted half outside the window.
const PAD: f32 = 8.0;

/// A kind glyph in a row, and the smaller ones beside a count.
const GLYPH: f32 = 13.0;
const SMALL: f32 = 10.0;

/// The selection mark's box.
const MARK: f32 = 11.0;

/// The faces a cell paints in. Painted rather than laid out, so the sizes are here
/// rather than resolved from the named styles in [`crate::app`].
const NAME: f32 = 12.0;
const MONO: f32 = 10.5;

/// The centre's default view.
pub struct Library {
    by: Column,
    order: Order,
}

impl Default for Library {
    fn default() -> Library {
        Library {
            by: Column::Name,
            order: Order::Up,
        }
    }
}

impl Library {
    pub fn ui(
        &mut self,
        ui: &mut egui::Ui,
        browser: &mut Browser,
        workspace: &Workspace,
        device: &Device,
        queue: &Queue,
        shell: &Shell,
    ) -> Vec<Act> {
        // The bar, the head and the rows are flush: the table's own lines are the only
        // horizontal rules in it.
        ui.spacing_mut().item_spacing.y = 0.0;
        let mut acts = Vec::new();
        let held = rows(
            workspace,
            &device.state,
            queue,
            browser.tags(),
            &shell.filter,
        );
        let held = arrange(held, &shell.omnibox, self.by, self.order);

        let counts = [queue.len(), differing(workspace, &device.state, queue)];
        bar(ui, counts, browser.tags(), &shell.filter, &mut acts);
        let picked: Vec<&Row> = held
            .iter()
            .filter(|row| browser.picked().holds(row.item))
            .collect();
        if !picked.is_empty() {
            // Claimed before the table, so the strip keeps its height whatever the table
            // does with what is left.
            egui::TopBottomPanel::bottom("library_footer")
                .resizable(false)
                .frame(egui::Frame::new())
                .show_inside(ui, |ui| {
                    footer(
                        ui,
                        &picked,
                        browser,
                        workspace,
                        &device.state,
                        queue,
                        &mut acts,
                    )
                });
        }
        self.table(ui, &held, browser, workspace, device, queue, &mut acts);
        acts
    }

    #[allow(clippy::too_many_arguments)]
    fn table(
        &mut self,
        ui: &mut egui::Ui,
        rows: &[Row],
        browser: &mut Browser,
        workspace: &Workspace,
        device: &Device,
        queue: &Queue,
        acts: &mut Vec<Act>,
    ) {
        // The head and every row start where a row of the tree starts, so the whole grid
        // moves together and the scroll bar stays at the panel's own edge.
        let room = ui.available_rect_before_wrap();
        let mut inset = ui.new_child(
            egui::UiBuilder::new()
                .max_rect(room.with_min_x(room.left() + PAD))
                .layout(*ui.layout()),
        );
        let ui = &mut inset;

        // The head and the rows are laid out to one width, so a scroll bar the rows make
        // room for must come off the head as well.
        let body = ui.available_height() - HEAD;
        let scrolls = rows.len() as f32 * ROW > body;
        let bar = match scrolls {
            true => ui.spacing().scroll.bar_width,
            false => 0.0,
        };
        let width = (ui.available_width() - bar).max(0.0);
        let tracks = tracks(width);
        self.head(ui, width, &tracks);
        if rows.is_empty() {
            return nothing(ui);
        }

        let list: Vec<Item> = rows.iter().map(|row| row.item).collect();
        let shown = egui::ScrollArea::vertical()
            .id_salt("library_table")
            .auto_shrink([false; 2])
            .show_rows(ui, ROW, rows.len(), |ui, shown| {
                for row in shown.filter_map(|index| rows.get(index)) {
                    paint(
                        ui, row, width, &tracks, browser, &list, workspace, device, queue, acts,
                    );
                }
            });
        // The room under the last row: a click there is a click on no row, which lets go
        // of everything picked.
        let rest = shown
            .inner_rect
            .with_min_y(shown.inner_rect.top() + shown.content_size.y);
        if rest.height() > 0.0
            && ui
                .interact(rest, ui.id().with("library_empty"), egui::Sense::click())
                .clicked()
        {
            browser.unpick();
        }
    }

    /// 20 px of column heads, each one a click that sorts by it.
    fn head(&mut self, ui: &mut egui::Ui, width: f32, tracks: &[Range<f32>; 9]) {
        let (rect, response) =
            ui.allocate_exact_size(egui::vec2(width, HEAD), egui::Sense::click());
        let visuals = ui.visuals().clone();
        let painter = ui.painter().clone();
        painter.rect_filled(rect, 0.0, visuals.faint_bg_color);
        let quiet = crate::app::caption(&visuals);
        let strong = visuals.widgets.active.fg_stroke.color;

        for (column, track) in Column::ALL.iter().zip(tracks) {
            if column.head().is_empty() {
                continue;
            }
            let sorted = self.by == *column;
            let ink = match sorted {
                true => strong,
                false => quiet,
            };
            let mut room = track.end - track.start;
            if sorted {
                // ⚠️ The vendored Lucide set has no chevron-up, so ascending points the
                // way the tree's shut branch does rather than upwards.
                let glyph = match self.order {
                    Order::Up => Glyph::ChevronRight,
                    Order::Down => Glyph::ChevronDown,
                };
                let box_ = egui::Rect::from_min_size(
                    egui::pos2(
                        rect.left() + track.end - SMALL,
                        rect.center().y - SMALL / 2.0,
                    ),
                    egui::Vec2::splat(SMALL),
                );
                painted(ui, glyph, box_, ink);
                room = (room - SMALL - 2.0).max(0.0);
            }
            let mut job = egui::text::LayoutJob::simple_singleline(
                column.head().to_uppercase(),
                egui::FontId::proportional(9.5),
                ink,
            );
            job.wrap = egui::text::TextWrapping::truncate_at_width(room);
            let galley = painter.layout_job(job);
            painter.galley(
                egui::pos2(
                    rect.left() + track.start,
                    rect.center().y - galley.size().y / 2.0,
                ),
                galley,
                egui::Color32::PLACEHOLDER,
            );
        }

        let Some(column) = response
            .clicked()
            .then(|| under(&response, rect, tracks))
            .flatten()
        else {
            return;
        };
        match self.by == column {
            true => self.order = self.order.flipped(),
            false => {
                self.by = column;
                self.order = Order::Up;
            }
        }
    }
}

/// 28 px: what the library is over, the tags narrowing it, and what wants attention.
///
/// ⚠️ Both counts are the whole list's, not this view's. They are the numbers the tree's
/// own rows carry and the toolbar's Send acts on — and a chip counting only what survives
/// its own narrowing would report a different number the moment it was clicked.
fn bar(ui: &mut egui::Ui, counts: [usize; 2], tags: &Tags, filter: &Filter, acts: &mut Vec<Act>) {
    let (rect, _) =
        ui.allocate_exact_size(egui::vec2(ui.available_width(), BAR), egui::Sense::hover());
    let mut inner = ui.new_child(
        egui::UiBuilder::new()
            .max_rect(rect.shrink2(egui::vec2(PAD, 0.0)))
            .layout(egui::Layout::left_to_right(egui::Align::Center)),
    );
    let ui = &mut inner;
    ui.spacing_mut().item_spacing.x = 6.0;
    let ink = ui.visuals().widgets.inactive.fg_stroke.color;
    icon(ui, Glyph::LibraryBig, GLYPH, ink);
    ui.label(
        egui::RichText::new(format!("Library · {}", over(filter)))
            .size(12.0)
            .color(ink),
    );
    for tag in filter.tags.iter().filter_map(|id| tags.name_of(*id)) {
        chip(ui, Glyph::Tag, SMALL, tag, ink, None);
    }
    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
        let states = [
            (State::Waiting, Glyph::Clock),
            (State::Differs, Glyph::CircleAlert),
        ];
        for ((state, glyph), count) in states.into_iter().zip(counts) {
            // A chip that has gone to nothing stays while it is the one narrowing, so
            // there is always something left to click to widen the table again.
            if count == 0 && !filter.on(Narrow::State(state)) {
                continue;
            }
            let text = format!("{count} {}", state.word());
            let drawn = chip(ui, glyph, SMALL, &text, warn(ui.visuals()), None);
            let picked = ui
                .interact(
                    drawn.rect,
                    drawn.id.with(state.word()),
                    egui::Sense::click(),
                )
                .on_hover_text(state.sentence());
            if picked.clicked() {
                acts.push(Act::Narrow(Narrow::State(state)));
            }
        }
    });
}

/// What the library is over, in the words the filter's own rows use.
fn over(filter: &Filter) -> String {
    let mut narrowed = Vec::new();
    if let Some(kind) = filter.kind {
        narrowed.push(kind.plural().to_string());
    }
    if let Some(place) = filter.place {
        narrowed.push(
            match place {
                Place::Computer => "this computer",
                Place::Keyboard => "the instrument",
            }
            .to_string(),
        );
    }
    if let Some(state) = filter.state {
        narrowed.push(state.word().to_string());
    }
    match narrowed.is_empty() {
        true => "everything".to_string(),
        false => narrowed.join(" · "),
    }
}

/// Which column the pointer is over, for the tooltip and for the head's sort click.
fn under(response: &egui::Response, rect: egui::Rect, tracks: &[Range<f32>; 9]) -> Option<Column> {
    let at = response.interact_pointer_pos().or(response.hover_pos())?;
    let x = at.x - rect.left();
    Column::ALL
        .iter()
        .zip(tracks)
        .find(|(_, track)| (track.start..track.end + GAP).contains(&x))
        .map(|(column, _)| *column)
}

/// One row of the table.
///
/// ⚠️ Nothing inside is a widget, for the reason [`crate::browser::Cells`] gives: a label
/// allocates a hover rect that wins the hit test over the row, and the click lands on
/// whichever word happens to be under it. The row is the only thing that senses, and the
/// tooltip is whichever cell the pointer is in.
#[allow(clippy::too_many_arguments)]
fn paint(
    ui: &mut egui::Ui,
    row: &Row,
    width: f32,
    tracks: &[Range<f32>; 9],
    browser: &mut Browser,
    list: &[Item],
    workspace: &Workspace,
    device: &Device,
    queue: &Queue,
    acts: &mut Vec<Act>,
) {
    let selected = browser.picked().holds(row.item);
    let (rect, response) =
        ui.allocate_exact_size(egui::vec2(width, ROW), egui::Sense::click_and_drag());
    let visuals = ui.visuals().clone();
    let painter = ui.painter().clone();
    let fill = match (selected, response.hovered()) {
        (true, _) => Some(visuals.selection.bg_fill),
        (false, true) => Some(visuals.faint_bg_color),
        (false, false) => None,
    };
    if let Some(fill) = fill {
        painter.rect_filled(rect, 3.0, fill);
    }
    let ink = match selected {
        true => visuals.selection.stroke.color,
        false => visuals.text_color(),
    };
    let quiet = cell_ink(selected, visuals.weak_text_color(), &visuals);

    let cell = |column: Column| {
        let track = &tracks[column.index()];
        egui::Rect::from_min_max(
            egui::pos2(rect.left() + track.start, rect.top()),
            egui::pos2(rect.left() + track.end, rect.bottom()),
        )
    };
    let write =
        |box_: egui::Rect, text: &str, font: egui::FontId, tint: egui::Color32, italics: bool| {
            let mut job = egui::text::LayoutJob::default();
            job.append(
                text,
                0.0,
                egui::TextFormat {
                    font_id: font,
                    color: tint,
                    italics,
                    ..egui::TextFormat::default()
                },
            );
            job.wrap = egui::text::TextWrapping::truncate_at_width(box_.width());
            let galley = painter.layout_job(job);
            painter.galley(
                egui::pos2(box_.left(), box_.center().y - galley.size().y / 2.0),
                galley,
                egui::Color32::PLACEHOLDER,
            );
        };

    let checkbox = mark(ui, cell(Column::Mark), selected, &response);
    let glyph = cell(Column::Glyph);
    if glyph.width() > 0.0 {
        painted(
            ui,
            row.kind.glyph(),
            egui::Rect::from_center_size(
                egui::pos2(glyph.left() + GLYPH / 2.0, glyph.center().y),
                egui::Vec2::splat(GLYPH),
            ),
            ink,
        );
    }
    write(
        cell(Column::Kind),
        &word(row),
        egui::FontId::proportional(NAME - 1.0),
        quiet,
        false,
    );
    write(
        cell(Column::Name),
        &crate::browser::starred(&row.name, row.unsaved),
        egui::FontId::proportional(NAME),
        ink,
        row.unsaved,
    );
    if row.tags > 0 {
        let tags = cell(Column::Tags);
        painted(
            ui,
            Glyph::Tag,
            egui::Rect::from_center_size(
                egui::pos2(tags.left() + SMALL / 2.0, tags.center().y),
                egui::Vec2::splat(SMALL),
            ),
            quiet,
        );
        let count = tags.with_min_x(tags.left() + SMALL + 3.0);
        write(
            count,
            &row.tags.to_string(),
            egui::FontId::monospace(MONO),
            quiet,
            false,
        );
    }
    // The same mark the tree's dot paints, in the words this column carries.
    let mark = row
        .item
        .local()
        .and_then(|id| workspace.get(id))
        .and_then(|entity| keyboard_mark(entity, &device.state, queue));
    write(
        cell(Column::Where),
        row.where_.short(),
        egui::FontId::proportional(NAME - 1.0),
        match mark {
            Some(mark) => cell_ink(selected, mark_ink(mark, &visuals), &visuals),
            None => quiet,
        },
        false,
    );
    if let Some((_, at)) = row.at {
        write(
            cell(Column::At),
            &shown(at),
            egui::FontId::monospace(MONO),
            quiet,
            false,
        );
    }
    write(
        cell(Column::Size),
        &crate::room::measure(row.size),
        egui::FontId::monospace(MONO),
        quiet,
        false,
    );
    // ⚠️ Quiet, id and all. An id nothing has resolved is a question nobody has asked
    // the instrument, not a library reported missing.
    write(
        cell(Column::Needs),
        &row.needs.text(),
        egui::FontId::proportional(NAME - 1.0),
        quiet,
        false,
    );

    // A row of the table is dragged like a row of the tree: the same payload, so it
    // lands on the same targets and means the same thing there.
    if response.dragged() {
        if let Some(head) = browser.held(row.item, workspace, &device.state) {
            let carried = browser.carrying(head, &row.name, workspace, &device.state);
            egui::DragAndDrop::set_payload(ui.ctx(), carried);
        }
    }

    let checked = checkbox
        .map(|box_| {
            box_.on_hover_text(tooltip(
                row,
                Column::Mark,
                mark,
                browser.tags(),
                workspace,
                device,
            ))
        })
        .is_some_and(|box_| box_.clicked());
    let response = match under(&response, rect, tracks) {
        Some(column) => response.on_hover_text(tooltip(
            row,
            column,
            mark,
            browser.tags(),
            workspace,
            device,
        )),
        None => response,
    };
    if checked {
        browser.check(row.item);
    } else if response.double_clicked() {
        acts.push(Act::Open(row.item));
    } else if response.clicked() {
        browser.pick(ui, row.item, list);
    }
    response.context_menu(|ui| browser.menu(ui, row.item, workspace, device, queue, acts));
}

/// The 11 px box that says whether a row is checked, and takes the click that changes
/// it. A column too narrow to draw the box offers none.
fn mark(
    ui: &egui::Ui,
    box_: egui::Rect,
    picked: bool,
    row: &egui::Response,
) -> Option<egui::Response> {
    if box_.width() < MARK {
        return None;
    }
    let visuals = ui.visuals().clone();
    let at = egui::Rect::from_center_size(
        egui::pos2(box_.left() + MARK / 2.0, box_.center().y),
        egui::Vec2::splat(MARK),
    );
    match picked {
        true => {
            ui.painter().rect_filled(at, 2.0, accent(&visuals));
            painted(
                ui,
                Glyph::Check,
                at.shrink(1.5),
                visuals.selection.stroke.color,
            );
        }
        false => {
            ui.painter().rect_stroke(
                at,
                2.0,
                egui::Stroke::new(1.0_f32, visuals.widgets.noninteractive.bg_stroke.color),
                egui::StrokeKind::Inside,
            );
        }
    }
    Some(ui.interact(at, row.id.with("mark"), egui::Sense::click()))
}

/// The whole of a cell, which is what a hover asks for.
///
/// Three columns grow a fact the row does not carry: the tags column holds a count and
/// the hover is where the names are, the address is one of possibly several slots holding
/// these very bytes, and the WHERE cell's ink is a [`Mark`] the row does not hold. All
/// three are worked out for the hovered row alone.
fn tooltip(
    row: &Row,
    column: Column,
    mark: Option<Mark>,
    tags: &Tags,
    workspace: &Workspace,
    device: &Device,
) -> String {
    match column {
        Column::Mark => {
            "check it to act on several at once; a click on the row picks it alone".to_string()
        }
        Column::Glyph | Column::Kind => word(row),
        Column::Name => row.name.clone(),
        Column::Tags => match worn(row, tags) {
            names if names.is_empty() => "no tags".to_string(),
            names => names.join(", "),
        },
        // The cell takes the mark's ink, so the hover says what that ink claims under
        // the sentence saying where it is.
        Column::Where => match mark {
            Some(mark) => format!("{}\n{}", row.where_.sentence(), mark_words(mark)),
            None => row.where_.sentence().to_string(),
        },
        Column::At => match row.at {
            Some((class, at)) => {
                let where_ = place(class, at);
                match (row.where_, also_holding(row, workspace, device)) {
                    // A class reporting no checksum is linked by the name it gave this
                    // asset, so the address is where the name is rather than where the
                    // body is.
                    (Where::Both(None), _) => format!("{where_}, matched by name"),
                    (_, 0) => where_,
                    (_, more) => format!("{where_}, and {more} more hold the same bytes"),
                }
            }
            None => "it never came off a slot".to_string(),
        },
        Column::Size => format!("{} bytes", row.size),
        Column::Needs => row.needs.sentence(),
    }
}

/// How many slots beyond the linked one hold this row's own bytes. A row that is a slot
/// is not linked to anything and answers zero.
fn also_holding(row: &Row, workspace: &Workspace, device: &Device) -> usize {
    row.item
        .local()
        .and_then(|id| workspace.get(id))
        .map_or(0, |entity| {
            crate::device::also_holding(&device.state, entity)
        })
}

/// What a row is labelled with. Only a kept asset wears anything: a tag hangs on a
/// workspace id, and a slot has none.
fn worn(row: &Row, tags: &Tags) -> Vec<String> {
    let Item::Local(id) = row.item else {
        return Vec::new();
    };
    tags.worn(id)
        .iter()
        .filter_map(|tag| tags.name_of(*tag))
        .map(str::to_string)
        .collect()
}

/// The strip under the table: what is checked, what sending it would do, and everything
/// that can be asked of the whole set.
#[allow(clippy::too_many_arguments)]
fn footer(
    ui: &mut egui::Ui,
    picked: &[&Row],
    browser: &mut Browser,
    workspace: &Workspace,
    device: &DeviceState,
    queue: &Queue,
    acts: &mut Vec<Act>,
) {
    let checked: Vec<Item> = picked.iter().map(|row| row.item).collect();
    egui::Frame::new()
        .stroke(egui::Stroke::new(1.0_f32, accent(ui.visuals())))
        .inner_margin(egui::Margin::symmetric(8, 4))
        .show(ui, |ui| {
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 6.0;
                ui.label(
                    egui::RichText::new(format!("{} selected", picked.len()))
                        .text_style(ui_text())
                        .strong(),
                );
                ui.scope(|ui| {
                    crate::panel::flat(ui);
                    if ui
                        .add(egui::Button::new(
                            egui::RichText::new("clear").text_style(ui_text()),
                        ))
                        .on_hover_text("let go of everything picked — or press Escape")
                        .clicked()
                    {
                        browser.unpick();
                    }
                });
                ui.label(
                    egui::RichText::new(consequence(picked, device, queue))
                        .text_style(ui_text())
                        .weak(),
                );
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    ui.spacing_mut().button_padding.y = 0.0;
                    if ui.small_button("Review send queue").clicked() {
                        acts.push(Act::ShowPage(Page::Queue));
                    }
                    // Backwards: the strip runs right to left, so [`Bulk::ALL`]'s first
                    // action has to be drawn last to sit furthest left.
                    for action in Bulk::ALL.iter().rev() {
                        browser.bulk_item(ui, *action, &checked, workspace, device, acts);
                    }
                });
            });
        });
}

/// The one line the table shows when nothing survives the narrowing.
fn nothing(ui: &mut egui::Ui) {
    ui.add_space(6.0);
    ui.label(
        egui::RichText::new(
            "Nothing here — drop Nord files in, attach an instrument, or ask for less.",
        )
        .text_style(micro())
        .weak()
        .italics(),
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::browser::apply;
    use crate::log::Log;
    use crate::tabs::Tabs;
    use crate::workspace::{Fresh, Origin};

    fn at(bank: u32, slot: u32) -> Location {
        Location { bank, slot }
    }

    /// A context dressed the way `DrawbarApp::new` dresses one: the named text styles a
    /// panel resolves are installed there, on both faces.
    fn context() -> egui::Context {
        let ctx = egui::Context::default();
        ctx.all_styles_mut(crate::app::metrics);
        ctx
    }

    fn row(name: &str, kind: Kind, where_: Where, at: Option<Location>, size: u64) -> Row {
        Row {
            item: Item::Local(size),
            kind,
            family: None,
            name: name.to_string(),
            tags: 0,
            unsaved: false,
            where_,
            at: at.map(|at| (ObjectClass::Program, at)),
            size,
            needs: Needs::Nothing,
        }
    }

    /// ⚠️ Every track shrinks and none goes negative. At the width the centre has with
    /// both docks open, the three that carry an address, a size and a dependency are
    /// still wide enough to say something.
    #[test]
    fn the_columns_share_the_width_without_overlapping_or_overflowing_it() {
        for width in [430.0_f32, 900.0] {
            let tracks = tracks(width);
            for (column, track) in Column::ALL.iter().zip(&tracks) {
                assert!(
                    track.start >= 0.0 && track.end >= track.start,
                    "{column:?} at {width}: {track:?}"
                );
                assert!(
                    track.end <= width + 0.01,
                    "{column:?} at {width}: {track:?}"
                );
            }
            for pair in tracks.windows(2) {
                assert!(
                    pair[1].start >= pair[0].end,
                    "columns overlap at {width}: {pair:?}"
                );
            }
            for column in [Column::At, Column::Size, Column::Needs] {
                let track = &tracks[column.index()];
                assert!(
                    track.end - track.start > 0.0,
                    "{column:?} vanished at {width}"
                );
            }
        }
    }

    /// ⚠️ The kind is worth 96 px and no more, and it is the name that must stay
    /// readable when the centre is narrow — two programs are told apart by their names,
    /// not by both being programs.
    #[test]
    fn the_kind_reaches_96_px_when_wide_and_yields_to_the_name_when_narrow() {
        let width_of = |tracks: &[Range<f32>; 9], column: Column| {
            let track = &tracks[column.index()];
            track.end - track.start
        };

        let wide = tracks(900.0);
        assert!(
            (width_of(&wide, Column::Kind) - 96.0).abs() < 0.01,
            "at 900 the kind holds the longest word: {}",
            width_of(&wide, Column::Kind)
        );

        let narrow = tracks(430.0);
        assert!(
            width_of(&narrow, Column::Name) >= 40.0,
            "at 430 the name is unreadable: {}",
            width_of(&narrow, Column::Name)
        );
        assert!(
            width_of(&narrow, Column::Kind) > 0.0,
            "at 430 the kind vanished"
        );
    }

    /// A column's track is the one at its own index, or every cell after the first
    /// mismatch is painted into the column beside it.
    #[test]
    fn every_column_indexes_its_own_track() {
        for (index, column) in Column::ALL.iter().enumerate() {
            assert_eq!(column.index(), index, "{column:?}");
        }
    }

    /// A width nothing fits in still lays out: the tracks shrink together rather than
    /// running past the edge or turning negative.
    #[test]
    fn a_width_below_the_fixed_columns_shrinks_every_track_instead_of_going_negative() {
        for width in [0.0_f32, 40.0, 120.0] {
            let tracks = tracks(width);
            for (column, track) in Column::ALL.iter().zip(&tracks) {
                assert!(track.start >= 0.0, "{column:?} at {width}: {track:?}");
                assert!(track.end >= track.start, "{column:?} at {width}: {track:?}");
                assert!(
                    track.end <= width + 0.01,
                    "{column:?} at {width}: {track:?}"
                );
            }
        }
    }

    /// The omnibox and the sort compose, and neither depends on the order the rows were
    /// built in.
    #[test]
    fn the_search_narrows_and_the_column_orders_what_is_left() {
        let held = || {
            vec![
                row("Africa Split", Kind::Program, Where::Computer, None, 300),
                row(
                    "africa bass",
                    Kind::Program,
                    Where::Both(Some(false)),
                    Some(at(6, 0)),
                    100,
                ),
                row(
                    "Squabble B",
                    Kind::Live,
                    Where::Keyboard,
                    Some(at(0, 0)),
                    200,
                ),
            ]
        };
        let names = |rows: &[Row]| -> Vec<String> { rows.iter().map(|r| r.name.clone()).collect() };

        // The search is a case-insensitive substring on the name and nothing else.
        let found = arrange(held(), "AFRICA", Column::Name, Order::Up);
        assert_eq!(names(&found), ["africa bass", "Africa Split"]);
        assert!(arrange(held(), "nothing at all", Column::Name, Order::Up).is_empty());

        // And the sort is over what the search left, either way round.
        let biggest = arrange(held(), "africa", Column::Size, Order::Down);
        assert_eq!(names(&biggest), ["Africa Split", "africa bass"]);
        let smallest = arrange(held(), "africa", Column::Size, Order::Up);
        assert_eq!(names(&smallest), ["africa bass", "Africa Split"]);
    }

    /// ⚠️ A row with no address sorts after every row that has one. Treating it as `0:0`
    /// would file everything on this computer at the top of the instrument's first bank.
    #[test]
    fn a_row_with_no_address_sorts_after_every_row_that_has_one() {
        let rows = arrange(
            vec![
                row("no slot", Kind::Program, Where::Computer, None, 1),
                row("later", Kind::Program, Where::Keyboard, Some(at(6, 3)), 2),
                row("first", Kind::Program, Where::Keyboard, Some(at(0, 0)), 3),
            ],
            "",
            Column::At,
            Order::Up,
        );
        let names: Vec<&str> = rows.iter().map(|row| row.name.as_str()).collect();
        assert_eq!(names, ["first", "later", "no slot"]);
    }

    /// A kind, a place and a tag narrow together, and a thing in both places survives a
    /// filter naming either of them.
    #[test]
    fn the_kind_place_and_tag_filters_compose_over_the_row_model() {
        use crate::filter::Narrow;

        let ctx = context();
        let mut workspace = Workspace::new(ctx.clone());
        let mut device = Device::new(ctx);
        let mut log = Log::default();
        let mut tags = Tags::default();

        let bytes = {
            let id = workspace.create(Fresh::Program, &mut log).unwrap();
            let bytes = workspace.get(id).unwrap().bytes.clone();
            workspace.remove(id, &mut log);
            bytes
        };
        device.pretend_partitions(&crate::device::ELECTRO5);
        device.pretend_scanned(ObjectClass::SetList, 1, &["Sunday"]);
        // One linked to the slot holding its bytes, so it is in both places, and one
        // that is on this computer alone.
        let both = workspace.ingest(
            "Africa-Split.ne5p".into(),
            Origin::Device {
                class: ObjectClass::Program,
                at: at(6, 0),
            },
            bytes,
            &mut log,
        );
        let crc = workspace
            .get(both)
            .and_then(|entity| entity.saved.crc32)
            .expect("every CBIN container has one");
        device.pretend_bodies(
            ObjectClass::Program,
            7,
            &[Some(("Africa Split", crc)), Some(("Squabble B", crc ^ 1))],
        );
        device.relink(&mut workspace);
        workspace.create(Fresh::Live, &mut log).unwrap();
        let sunday = tags.make("Sunday").unwrap();
        tags.set(both, sunday, true);

        let names = |filter: &Filter| -> Vec<String> {
            rows(&workspace, &device.state, &Queue::default(), &tags, filter)
                .into_iter()
                .map(|row| row.name)
                .collect()
        };
        let mut filter = Filter::default();
        // The slot the kept asset came off is that asset's row, not a second one.
        assert_eq!(
            names(&filter),
            ["Africa-Split.ne5p", "untitled.ne5l", "Squabble B", "Sunday"]
        );

        filter.narrow(Narrow::Kind(Kind::Program));
        assert_eq!(names(&filter), ["Africa-Split.ne5p", "Squabble B"]);

        // In both places, so either place admits it.
        filter.narrow(Narrow::Place(Place::Computer));
        assert_eq!(names(&filter), ["Africa-Split.ne5p"]);
        filter.narrow(Narrow::Place(Place::Computer));
        filter.narrow(Narrow::Place(Place::Keyboard));
        assert_eq!(names(&filter), ["Africa-Split.ne5p", "Squabble B"]);

        // And a tag narrows what the kind and the place left.
        filter.narrow(Narrow::Tag(sunday));
        assert_eq!(names(&filter), ["Africa-Split.ne5p"]);
    }

    /// A linked asset is in both places, and the sign says whether the slot still
    /// reports the asset's own checksum — which an edit here turns over while the link
    /// stays where it was.
    #[test]
    fn a_linked_asset_is_in_both_places_and_says_when_the_two_stop_agreeing() {
        let ctx = egui::Context::default();
        let mut workspace = Workspace::new(ctx.clone());
        let mut device = Device::new(ctx);
        let mut log = Log::default();
        let tags = Tags::default();

        let bytes = {
            let id = workspace.create(Fresh::Program, &mut log).unwrap();
            let bytes = workspace.get(id).unwrap().bytes.clone();
            workspace.remove(id, &mut log);
            bytes
        };
        let id = workspace.ingest(
            "Africa-Split.ne5p".into(),
            Origin::Device {
                class: ObjectClass::Program,
                at: at(6, 0),
            },
            bytes.clone(),
            &mut log,
        );
        let crc = workspace
            .get(id)
            .and_then(|entity| entity.saved.crc32)
            .expect("every CBIN container has one");
        let filter = Filter::default();
        let where_ = |workspace: &Workspace, device: &Device| {
            rows(workspace, &device.state, &Queue::default(), &tags, &filter)
                .into_iter()
                .find(|row| matches!(row.item, Item::Local(_)))
                .map(|row| row.where_)
        };
        // Nothing read: the other copy cannot be spoken about at all.
        device.relink(&mut workspace);
        assert_eq!(where_(&workspace, &device), Some(Where::Unread));

        device.pretend_bodies(ObjectClass::Program, 7, &[Some(("Africa Split", crc))]);
        device.relink(&mut workspace);
        assert_eq!(where_(&workspace, &device), Some(Where::Both(Some(true))));

        // Edited here and not saved: the slot still holds what this was saved as, so the
        // two places have not parted.
        let (_, edited) =
            crate::fields::apply(&bytes, &[("center_panel.gain".into(), "96".into())])
                .expect("the registry takes the set");
        workspace.replace_bytes(id, edited, &mut log);
        device.relink(&mut workspace);
        assert_eq!(where_(&workspace, &device), Some(Where::Both(Some(true))));

        // Saved: the link stays put and the sign turns over.
        workspace.mark_saved(id);
        device.relink(&mut workspace);
        assert_eq!(
            workspace.get(id).unwrap().link,
            Some((ObjectClass::Program, at(6, 0)))
        );
        assert_eq!(where_(&workspace, &device), Some(Where::Both(Some(false))));

        // A slot the scan found vacant holds nothing to link to.
        device.pretend_bodies(ObjectClass::Program, 7, &[None]);
        device.relink(&mut workspace);
        assert_eq!(where_(&workspace, &device), Some(Where::Computer));
    }

    /// ⚠️ One rule for the word, the dot and the count. An asset the attached instrument
    /// refuses stands on nothing however well its origin names a slot, so reading it
    /// against that slot would paint a difference and offer a send that
    /// [`crate::queue::enqueue`] refuses on every click.
    #[test]
    fn a_foreign_asset_is_neither_marked_against_a_slot_nor_counted_as_changed() {
        let ctx = context();
        let mut workspace = Workspace::new(ctx.clone());
        let mut device = Device::new(ctx);
        let mut log = Log::default();
        let queue = Queue::default();
        let class = ObjectClass::Program;
        let held_at = at(6, 0);

        let bytes = {
            let id = workspace.create(Fresh::Stage4Program, &mut log).unwrap();
            let bytes = workspace.get(id).unwrap().bytes.clone();
            workspace.remove(id, &mut log);
            bytes
        };
        let id = workspace.ingest(
            "Africa-Split.ns4p".into(),
            Origin::Device { class, at: held_at },
            bytes,
            &mut log,
        );
        let crc = workspace
            .get(id)
            .and_then(|entity| entity.saved.crc32)
            .expect("every CBIN container has one");
        // An Electro 5 whose Programs 7:1 holds something other than this.
        device.pretend_bodies(class, 7, &[Some(("Squabble B", crc ^ 1))]);
        device.relink(&mut workspace);

        let entity = workspace.get(id).expect("it is on the list");
        assert!(!fit(&device.state, entity).allowed(), "a Stage 4 program");
        assert_eq!(whereabouts(entity, &device.state, &queue), Where::Foreign);
        assert_eq!(keyboard_mark(entity, &device.state, &queue), None);
        assert!(crate::queue::changed(&workspace, &device.state, &queue).is_empty());
    }

    /// Equality is claimed only where something says so. A settings folder holds one
    /// slot and that slot reports no checksum, so an asset matched to it stands in both
    /// places with nothing said about the two bodies — until a read fetches the occupant,
    /// or this app writes the bytes there itself.
    #[test]
    fn a_slot_reporting_no_checksum_says_nothing_until_it_is_read_or_written() {
        let ctx = context();
        let mut workspace = Workspace::new(ctx.clone());
        let mut device = Device::new(ctx);
        let mut log = Log::default();
        let mut queue = Queue::default();
        let tags = Tags::default();
        let class = ObjectClass::Settings;
        let held_at = at(6, 0);

        let id = workspace.create(Fresh::Settings, &mut log).unwrap();
        let bytes = workspace.get(id).unwrap().bytes.clone();
        let held = workspace.get(id).unwrap();
        let crc = held.saved.crc32.expect("a container");
        let body_len = held.container.as_ref().expect("a container").body_len();

        // The walk reports what such a slot reports: a name and a length, and no
        // checksum at all — the length being this asset's own.
        device.pretend_attached();
        device.pretend(crate::device::DeviceEvent::BankScanned {
            class,
            bank: 7,
            slots: vec![Some(ProgramInfo {
                location: held_at,
                body_len: u32::try_from(body_len).unwrap(),
                format: "ne5s".into(),
                version: 1,
                crc32: None,
                name: "Live Settings".into(),
            })],
        });
        device.poll(&mut log, &mut workspace, &mut Tabs::default(), &mut queue);
        assert_eq!(
            workspace.get(id).unwrap().link,
            Some((class, held_at)),
            "the one slot the folder has"
        );

        let said = |workspace: &Workspace, device: &Device, queue: &Queue| {
            let entity = workspace.get(id).expect("it is on the list");
            let info = device
                .state
                .slot(class, held_at)
                .flatten()
                .expect("the slot was scanned");
            (
                agrees(entity, class, info, queue),
                rows(workspace, &device.state, queue, &tags, &Filter::default())
                    .into_iter()
                    .find(|row| matches!(row.item, Item::Local(_)))
                    .map(|row| row.where_),
                keyboard_mark(entity, &device.state, queue),
            )
        };

        assert_eq!(
            said(&workspace, &device, &queue),
            (None, Some(Where::Both(None)), Some(Mark::Unknown)),
            "an address and a length are not a body"
        );

        // A compare read fetched the occupant, and the two bodies are the same bytes.
        crate::queue::enqueue(
            &workspace,
            &mut device,
            &mut queue,
            &mut log,
            id,
            class,
            held_at,
        );
        queue.arrived(class, held_at, "Live Settings", &bytes, &workspace);
        assert_eq!(said(&workspace, &device, &queue).0, Some(true));

        // A write of this app's own, with nothing waiting to change it.
        queue.clear();
        workspace.landed(id, class, held_at, bytes.clone());
        device.relink(&mut workspace);
        assert_eq!(
            said(&workspace, &device, &queue),
            (
                Some(true),
                Some(Where::Both(Some(true))),
                Some(Mark::Agrees)
            ),
            "this app put those bytes there"
        );

        // A walk that reports a checksum, and it is not this body's.
        device.pretend_bodies(class, 7, &[Some(("Live Settings", crc ^ 1))]);
        device.relink(&mut workspace);
        assert_eq!(
            said(&workspace, &device, &queue),
            (
                Some(false),
                Some(Where::Both(Some(false))),
                Some(Mark::Differs)
            ),
            "what the instrument reports outlives our own write"
        );
    }

    /// ⚠️ An Electro 5 factory program is a type-0 file, and so is every copy Nord Sound
    /// Manager exports from one. Its header carries no body checksum, so nothing links
    /// it to the slot it came off unless that checksum is hashed from the body.
    #[test]
    fn a_type_0_asset_links_to_the_slot_reporting_its_body_checksum() {
        let ctx = context();
        let mut workspace = Workspace::new(ctx.clone());
        let mut device = Device::new(ctx);
        let mut log = Log::default();
        let (queue, tags) = (Queue::default(), Tags::default());
        let held_at = at(6, 0);

        let bytes = {
            let id = workspace.create(Fresh::Program, &mut log).unwrap();
            let bytes = crate::workspace::as_type_0(&workspace.get(id).unwrap().bytes);
            workspace.remove(id, &mut log);
            bytes
        };
        let id = workspace.ingest(
            "Circling Bells.ne5p".into(),
            Origin::File("Circling Bells.ne5p".into()),
            bytes,
            &mut log,
        );
        let crc = workspace
            .get(id)
            .and_then(|entity| entity.saved.crc32)
            .expect("hashed from the body the header does not checksum");

        device.pretend_bodies(
            ObjectClass::Program,
            7,
            &[Some(("Circling Bells", crc)), Some(("Squabble B", crc ^ 1))],
        );
        device.relink(&mut workspace);

        assert_eq!(
            workspace.get(id).unwrap().link,
            Some((ObjectClass::Program, held_at))
        );
        let where_ = rows(&workspace, &device.state, &queue, &tags, &Filter::default())
            .into_iter()
            .find(|row| matches!(row.item, Item::Local(_)))
            .map(|row| row.where_);
        assert_eq!(where_, Some(Where::Both(Some(true))));
        assert_eq!(
            keyboard_mark(workspace.get(id).unwrap(), &device.state, &queue),
            Some(Mark::Agrees)
        );
    }

    /// A link is matched on the saved bytes, which is what the sign and the dot are
    /// already read against. An asset holding an edit nothing has saved still finds the
    /// slot holding what it was saved as, however far its bytes have moved since; saving
    /// that edit takes the baseline off the slot and turns both signs over, leaving the
    /// link where it was matched.
    #[test]
    fn an_unsaved_edit_still_links_to_the_slot_holding_the_saved_bytes() {
        let ctx = context();
        let mut workspace = Workspace::new(ctx.clone());
        let mut device = Device::new(ctx);
        let mut log = Log::default();
        let (queue, tags) = (Queue::default(), Tags::default());
        let held_at = at(6, 0);

        let id = workspace.create(Fresh::Program, &mut log).unwrap();
        let bytes = workspace.get(id).unwrap().bytes.clone();
        let saved_as = workspace.get(id).unwrap().saved.crc32.unwrap();

        // Edited before anything is read, so there is no earlier link to fall back on.
        let (_, edited) =
            crate::fields::apply(&bytes, &[("center_panel.gain".into(), "96".into())])
                .expect("the registry takes the set");
        workspace.replace_bytes(id, edited, &mut log);
        assert!(workspace.get(id).unwrap().is_unsaved());
        assert_ne!(
            workspace
                .get(id)
                .unwrap()
                .container
                .as_ref()
                .map(|held| held.body_crc32),
            Some(saved_as),
            "the edit moved the bytes it holds now"
        );

        let where_ = |workspace: &Workspace, device: &Device| {
            rows(workspace, &device.state, &queue, &tags, &Filter::default())
                .into_iter()
                .find(|row| matches!(row.item, Item::Local(_)))
                .map(|row| row.where_)
        };
        let mark = |workspace: &Workspace, device: &Device| {
            keyboard_mark(workspace.get(id).unwrap(), &device.state, &queue)
        };

        device.pretend_bodies(ObjectClass::Program, 7, &[Some(("Africa Split", saved_as))]);
        device.relink(&mut workspace);
        assert_eq!(
            workspace.get(id).unwrap().link,
            Some((ObjectClass::Program, held_at)),
            "the slot holds what this was saved as"
        );
        assert_eq!(
            crate::device::also_holding(&device.state, workspace.get(id).unwrap()),
            0,
            "the one slot holding it is the one it is linked to"
        );
        assert_eq!(mark(&workspace, &device), Some(Mark::Agrees));
        assert_eq!(where_(&workspace, &device), Some(Where::Both(Some(true))));

        workspace.mark_saved(id);
        device.relink(&mut workspace);
        assert_eq!(
            workspace.get(id).unwrap().link,
            Some((ObjectClass::Program, held_at)),
            "no slot holds the new baseline, and where it stands is where it stands"
        );
        assert_eq!(mark(&workspace, &device), Some(Mark::Differs));
        assert_eq!(where_(&workspace, &device), Some(Where::Both(Some(false))));
    }

    /// The state axis narrows the library to what wants doing about it — and a write
    /// already waiting takes its row out of "differs" and into "waiting", so one thing
    /// to do is asked for once.
    #[test]
    fn a_row_waiting_to_be_sent_is_not_also_one_that_differs() {
        use crate::filter::{Narrow, State};

        let ctx = context();
        let mut workspace = Workspace::new(ctx.clone());
        let mut device = Device::new(ctx);
        let mut log = Log::default();
        let (tags, mut queue) = (Tags::default(), Queue::default());

        let id = workspace.create(Fresh::Program, &mut log).unwrap();
        let bytes = workspace.get(id).unwrap().bytes.clone();
        let crc = workspace
            .get(id)
            .and_then(|entity| entity.saved.crc32)
            .expect("every CBIN container has one");
        device.pretend_bodies(ObjectClass::Program, 7, &[Some(("Africa Split", crc))]);
        device.relink(&mut workspace);
        // Edited and saved: the link stays where it was and the two bodies part.
        let (_, edited) =
            crate::fields::apply(&bytes, &[("center_panel.gain".into(), "96".into())])
                .expect("the registry takes the set");
        workspace.replace_bytes(id, edited, &mut log);
        workspace.mark_saved(id);
        device.relink(&mut workspace);

        fn narrowed(
            workspace: &Workspace,
            device: &Device,
            queue: &Queue,
            tags: &Tags,
            state: crate::filter::State,
        ) -> usize {
            let mut filter = Filter::default();
            filter.narrow(Narrow::State(state));
            rows(workspace, &device.state, queue, tags, &filter)
                .into_iter()
                .filter(|row| matches!(row.item, Item::Local(_)))
                .count()
        }
        assert_eq!(differing(&workspace, &device.state, &queue), 1);
        assert_eq!(
            narrowed(&workspace, &device, &queue, &tags, State::Differs),
            1
        );
        assert_eq!(
            narrowed(&workspace, &device, &queue, &tags, State::Waiting),
            0
        );

        crate::queue::enqueue(
            &workspace,
            &mut device,
            &mut queue,
            &mut log,
            id,
            ObjectClass::Program,
            at(6, 0),
        );
        assert!(queue.holds(id), "it is owed back to the slot it came off");
        assert_eq!(
            differing(&workspace, &device.state, &queue),
            0,
            "the write already agreed to is what settles the two"
        );
        assert_eq!(
            narrowed(&workspace, &device, &queue, &tags, State::Waiting),
            1
        );
        assert_eq!(
            narrowed(&workspace, &device, &queue, &tags, State::Differs),
            0
        );
    }

    /// A class whose slots report no checksum is linked by name, and the table says so:
    /// the two places are named without a sign between them, and the address says what
    /// matched them.
    #[test]
    fn a_class_linked_by_name_reads_both_without_a_sign() {
        let ctx = context();
        let mut workspace = Workspace::new(ctx.clone());
        let mut device = Device::new(ctx);
        let mut log = Log::default();
        let (tags, filter, queue) = (Tags::default(), Filter::default(), Queue::default());

        workspace.create(Fresh::Settings, &mut log).unwrap();
        device.pretend_scanned(ObjectClass::Settings, 1, &["Settings"]);
        device.relink(&mut workspace);

        let row = rows(&workspace, &device.state, &queue, &tags, &filter)
            .into_iter()
            .find(|row| matches!(row.item, Item::Local(_)))
            .expect("the settings row");
        assert_eq!(row.where_, Where::Both(None));
        assert_eq!(row.where_.short(), "both");
        assert!(
            tooltip(&row, Column::At, None, &tags, &workspace, &device)
                .ends_with("matched by name"),
            "{}",
            tooltip(&row, Column::At, None, &tags, &workspace, &device)
        );
    }

    /// Four marks, four sentences, four inks. Two marks a reader cannot tell apart, or
    /// two that say the same thing, explain nothing between them.
    #[test]
    fn every_mark_is_painted_and_said_apart_from_the_others() {
        let all = [Mark::Agrees, Mark::Differs, Mark::Unknown, Mark::Unsaved];
        let said: BTreeSet<&str> = all.iter().map(|mark| mark_words(*mark)).collect();
        assert_eq!(said.len(), all.len(), "{said:?}");

        for visuals in [egui::Visuals::dark(), egui::Visuals::light()] {
            let inks: BTreeSet<[u8; 4]> = all
                .iter()
                .map(|mark| mark_ink(*mark, &visuals).to_array())
                .collect();
            assert_eq!(inks.len(), all.len(), "{inks:?}");
        }
    }

    /// A WHERE cell takes its ink from the mark the tree paints as a dot, so its hover
    /// says what that ink claims as well as where the row is.
    #[test]
    fn a_coloured_where_cell_says_what_its_colour_claims() {
        let ctx = context();
        let workspace = Workspace::new(ctx.clone());
        let device = Device::new(ctx);
        let tags = Tags::default();
        let held = row(
            "Africa Split",
            Kind::Program,
            Where::Both(Some(false)),
            Some(at(6, 0)),
            121,
        );

        let plain = tooltip(&held, Column::Where, None, &tags, &workspace, &device);
        assert_eq!(plain, Where::Both(Some(false)).sentence());
        let marked = tooltip(
            &held,
            Column::Where,
            Some(Mark::Differs),
            &tags,
            &workspace,
            &device,
        );
        assert!(marked.starts_with(&plain), "{marked}");
        assert!(marked.ends_with(mark_words(Mark::Differs)), "{marked}");
    }

    /// The sentence the footer says: where the picked rows go, how many of those slots
    /// are taken, what is already waiting, and what nothing has named.
    #[test]
    fn the_footer_says_where_a_selection_goes_and_what_it_would_replace() {
        let ctx = egui::Context::default();
        let mut device = Device::new(ctx.clone());
        let mut workspace = Workspace::new(ctx);
        let mut log = crate::log::Log::default();
        let mut queue = Queue::default();
        // Four destinations, two of them already holding something.
        device.pretend_scanned(ObjectClass::Program, 7, &["Africa Split", "Squabble B"]);

        let mut going: Vec<Row> = (0..4)
            .map(|slot| {
                row(
                    "owed",
                    Kind::Program,
                    Where::Computer,
                    Some(at(6, slot)),
                    121,
                )
            })
            .collect();
        going[0].needs = Needs::Wanted {
            class: ObjectClass::Piano,
            id: 0x0102_0304,
        };
        let picked: Vec<&Row> = going.iter().collect();
        assert_eq!(
            consequence(&picked, &device.state, &queue),
            "→ Programs 7:1–7:4 · 2 slots occupied · 1 needs a piano the instrument has not named"
        );

        // One of them is already in the queue, which the sentence says rather than
        // counting it twice over.
        let id = workspace.create(Fresh::Program, &mut log).unwrap();
        going[3].item = Item::Local(id);
        crate::queue::enqueue(
            &workspace,
            &mut device,
            &mut queue,
            &mut log,
            id,
            ObjectClass::Program,
            at(6, 3),
        );
        let picked: Vec<&Row> = going.iter().collect();
        assert!(
            consequence(&picked, &device.state, &queue).contains("1 already waiting"),
            "{}",
            consequence(&picked, &device.state, &queue)
        );

        // A row already on the instrument goes nowhere, so nothing is claimed for it.
        let there = vec![row(
            "held",
            Kind::Program,
            Where::Keyboard,
            Some(at(6, 0)),
            121,
        )];
        let mut only = there;
        only[0].item = Item::Slot {
            class: ObjectClass::Program,
            at: at(6, 0),
        };
        assert_eq!(
            consequence(&only.iter().collect::<Vec<_>>(), &device.state, &queue),
            "Nothing picked goes to the instrument."
        );
        assert_eq!(
            consequence(&[], &device.state, &queue),
            "Nothing picked goes to the instrument."
        );
    }

    /// A box is a checkbox: a plain click on one puts its row in the checked set and
    /// leaves whatever was checked before it alone, so several rows are checked with no
    /// modifier held.
    #[test]
    fn a_click_on_a_row_box_checks_it_beside_what_is_already_checked() {
        const WIDTH: f32 = 900.0;

        let ctx = context();
        let mut workspace = Workspace::new(ctx.clone());
        let device = Device::new(ctx.clone());
        let mut log = Log::default();
        let mut browser = Browser::default();
        let mut library = Library::default();
        let queue = Queue::default();
        let shell = Shell::default();
        for kind in [Fresh::Program, Fresh::Live, Fresh::Settings] {
            workspace.create(kind, &mut log).unwrap();
        }

        // The table starts PAD in, and the mark is the first track inside it.
        let box_x = PAD + tracks(WIDTH - PAD)[Column::Mark.index()].start + MARK / 2.0;
        let on_box = |index: f32| egui::pos2(box_x, BAR + HEAD + ROW * (index + 0.5));
        let mut frames = Vec::new();
        for index in [0.0_f32, 1.0] {
            let press = move |pressed| egui::Event::PointerButton {
                pos: on_box(index),
                button: egui::PointerButton::Primary,
                pressed,
                modifiers: egui::Modifiers::NONE,
            };
            frames.push(vec![egui::Event::PointerMoved(on_box(index))]);
            frames.push(vec![press(true), press(false)]);
            frames.push(Vec::new());
        }
        for events in frames {
            let input = egui::RawInput {
                events,
                screen_rect: Some(egui::Rect::from_min_size(
                    egui::Pos2::ZERO,
                    egui::vec2(WIDTH, 540.0),
                )),
                ..Default::default()
            };
            let _ = ctx.run(input, |ctx| {
                egui::CentralPanel::default()
                    .frame(egui::Frame::new())
                    .show(ctx, |ui| {
                        library.ui(ui, &mut browser, &workspace, &device, &queue, &shell);
                    });
            });
        }

        assert_eq!(
            browser.picked().items().count(),
            2,
            "both boxes were ticked, and neither click dropped the other row"
        );
    }

    /// Every word one frame painted, wherever in the tree of shapes it ended up.
    fn painted(output: &egui::FullOutput) -> Vec<String> {
        fn words(shape: &egui::Shape, into: &mut Vec<String>) {
            match shape {
                egui::Shape::Text(text) => into.push(text.galley.text().to_string()),
                egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| words(shape, into)),
                _ => {}
            }
        }
        let mut said = Vec::new();
        for clipped in &output.shapes {
            words(&clipped.shape, &mut said);
        }
        said
    }

    /// One mark, four states: no slot to stand on, a slot holding what this was saved
    /// as, a slot holding something else, and a write already waiting to change it.
    #[test]
    fn the_keyboard_mark_says_what_the_instrument_holds_where_this_stands() {
        let ctx = context();
        let mut workspace = Workspace::new(ctx.clone());
        let mut device = Device::new(ctx.clone());
        let mut log = Log::default();
        let mut queue = Queue::default();
        let (good, warn) = (Mark::Agrees, Mark::Differs);

        let bytes = {
            let id = workspace.create(Fresh::Program, &mut log).unwrap();
            let bytes = workspace.get(id).unwrap().bytes.clone();
            workspace.remove(id, &mut log);
            bytes
        };
        let off = |workspace: &mut Workspace, slot: u32, log: &mut Log| {
            workspace.ingest(
                format!("off-{slot}.ne5p"),
                Origin::Device {
                    class: ObjectClass::Program,
                    at: at(6, slot),
                },
                bytes.clone(),
                log,
            )
        };
        let same = off(&mut workspace, 0, &mut log);
        let other = off(&mut workspace, 1, &mut log);
        let waiting = off(&mut workspace, 2, &mut log);
        // Typed here, and no slot holds its body: there is nothing for it to stand on.
        let (_, typed) = crate::fields::apply(&bytes, &[("center_panel.gain".into(), "96".into())])
            .expect("the registry takes the set");
        let nowhere = workspace.ingest("typed.ne5p".into(), Origin::Fresh, typed, &mut log);
        let held = workspace.get(same).unwrap().saved.crc32.unwrap();

        let mark = |workspace: &Workspace, device: &Device, queue: &Queue, id: u64| {
            keyboard_mark(workspace.get(id).unwrap(), &device.state, queue)
        };
        // Nothing scanned: no slot holds anything, so no row says anything about one.
        assert_eq!(mark(&workspace, &device, &queue, same), None);

        device.pretend_bodies(
            ObjectClass::Program,
            7,
            &[
                Some(("off-0", held)),
                Some(("off-1", held ^ 1)),
                Some(("off-2", held)),
            ],
        );
        device.relink(&mut workspace);
        assert_eq!(mark(&workspace, &device, &queue, same), Some(good));
        assert_eq!(mark(&workspace, &device, &queue, other), Some(warn));
        assert_eq!(
            mark(&workspace, &device, &queue, nowhere),
            None,
            "it came off nowhere"
        );

        // Waiting to be written wins: the slot agrees now, and is about to stop.
        assert_eq!(mark(&workspace, &device, &queue, waiting), Some(good));
        crate::queue::enqueue(
            &workspace,
            &mut device,
            &mut queue,
            &mut log,
            waiting,
            ObjectClass::Program,
            at(6, 2),
        );
        assert_eq!(mark(&workspace, &device, &queue, waiting), Some(warn));
    }

    /// An asset holding an edit nothing has saved says so where its name is written.
    #[test]
    fn an_unsaved_name_wears_a_star_in_the_table() {
        const WIDTH: f32 = 900.0;

        let ctx = context();
        let mut workspace = Workspace::new(ctx.clone());
        let device = Device::new(ctx.clone());
        let mut log = Log::default();
        let mut browser = Browser::default();
        let mut library = Library::default();
        let (queue, shell) = (Queue::default(), Shell::default());

        let id = workspace.create(Fresh::Program, &mut log).unwrap();
        workspace.rename(id, "Africa Split".into());
        let draw = |library: &mut Library, browser: &mut Browser, workspace: &Workspace| {
            let input = egui::RawInput {
                screen_rect: Some(egui::Rect::from_min_size(
                    egui::Pos2::ZERO,
                    egui::vec2(WIDTH, 540.0),
                )),
                ..Default::default()
            };
            painted(&ctx.run(input, |ctx| {
                egui::CentralPanel::default()
                    .frame(egui::Frame::new())
                    .show(ctx, |ui| {
                        library.ui(ui, browser, workspace, &device, &queue, &shell);
                    });
            }))
        };

        let said = draw(&mut library, &mut browser, &workspace);
        assert!(said.contains(&"Africa Split".to_string()), "{said:?}");

        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);

        let said = draw(&mut library, &mut browser, &workspace);
        assert!(said.contains(&"Africa Split*".to_string()), "{said:?}");
    }

    /// The KIND column carries the word the browser's own note carries, so the table and
    /// the tree cannot call one thing two things; and the head over it orders by it.
    #[test]
    fn the_kind_column_writes_the_browsers_own_word_and_sorts_by_it() {
        const WIDTH: f32 = 900.0;

        let ctx = context();
        let mut workspace = Workspace::new(ctx.clone());
        let device = Device::new(ctx.clone());
        let mut log = Log::default();
        let mut browser = Browser::default();
        let mut library = Library::default();
        let (queue, shell) = (Queue::default(), Shell::default());
        for kind in [Fresh::Settings, Fresh::Program] {
            workspace.create(kind, &mut log).unwrap();
        }

        let input = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(WIDTH, 540.0),
            )),
            ..Default::default()
        };
        let said = painted(&ctx.run(input, |ctx| {
            egui::CentralPanel::default()
                .frame(egui::Frame::new())
                .show(ctx, |ui| {
                    library.ui(ui, &mut browser, &workspace, &device, &queue, &shell);
                });
        }));
        assert!(said.contains(&"KIND".to_string()), "{said:?}");
        for word in ["program", "settings"] {
            assert!(said.contains(&word.to_string()), "{word}: {said:?}");
        }

        let held = rows(
            &workspace,
            &device.state,
            &queue,
            browser.tags(),
            &Filter::default(),
        );
        let ordered: Vec<String> = arrange(held, "", Column::Kind, Order::Up)
            .iter()
            .map(word)
            .collect();
        assert_eq!(ordered, ["program", "settings"]);
    }

    /// ⚠️ A row of the table is a row of the tree: it starts the same drag, and a drop
    /// files the asset exactly as a drag from the tree's own row does. Two drag paths
    /// would be two sets of rules for one gesture.
    #[test]
    fn a_row_dragged_from_the_table_onto_a_folder_files_the_asset() {
        const WIDTH: f32 = 900.0;

        let ctx = context();
        let mut workspace = Workspace::new(ctx.clone());
        let mut device = Device::new(ctx.clone());
        let mut log = Log::default();
        let mut tabs = Tabs::default();
        let mut browser = Browser::default();
        let mut library = Library::default();
        let mut queue = Queue::default();
        let shell = Shell::default();
        let id = workspace.create(Fresh::Program, &mut log).unwrap();
        apply(
            &mut browser,
            &mut Shell::default(),
            vec![Act::NewFolder],
            &mut workspace,
            &mut device,
            &mut tabs,
            &mut queue,
            &mut log,
        );

        // The one row of the table, in its name column; and the folder row of the tree,
        // under the section header and the 22 px row for this computer.
        let from = egui::pos2(crate::shell::BROWSER + PAD + 60.0, BAR + HEAD + ROW / 2.0);
        let onto = egui::pos2(100.0, crate::panel::HEADER + 22.0 + 10.0);
        let button = |pos, pressed| egui::Event::PointerButton {
            pos,
            button: egui::PointerButton::Primary,
            pressed,
            modifiers: egui::Modifiers::NONE,
        };
        let escape = egui::Event::Key {
            key: egui::Key::Escape,
            physical_key: None,
            pressed: true,
            repeat: false,
            modifiers: egui::Modifiers::NONE,
        };
        // The new folder opens its rename editor, and Escape closes it; then the pointer
        // presses on the table's row, carries it over the folder, and lets go.
        let frames: [Vec<egui::Event>; 6] = [
            Vec::new(),
            vec![escape],
            vec![egui::Event::PointerMoved(from)],
            vec![button(from, true)],
            vec![egui::Event::PointerMoved(onto)],
            vec![button(onto, false)],
        ];

        let mut asked = Vec::new();
        for events in frames {
            let input = egui::RawInput {
                events,
                screen_rect: Some(egui::Rect::from_min_size(
                    egui::Pos2::ZERO,
                    egui::vec2(WIDTH, 540.0),
                )),
                ..Default::default()
            };
            let _ = ctx.run(input, |ctx| {
                egui::SidePanel::left("places")
                    .exact_width(crate::shell::BROWSER)
                    .frame(egui::Frame::new())
                    .show(ctx, |ui| {
                        asked.extend(browser.ui(
                            ui,
                            &workspace,
                            &device,
                            &queue,
                            &Filter::default(),
                        ));
                    });
                egui::CentralPanel::default()
                    .frame(egui::Frame::new())
                    .show(ctx, |ui| {
                        library.ui(ui, &mut browser, &workspace, &device, &queue, &shell);
                    });
            });
        }

        let filed: Vec<(u64, Option<u64>)> = asked
            .iter()
            .filter_map(|act| match act {
                Act::File { id, folder } => Some((*id, *folder)),
                _ => None,
            })
            .collect();
        assert!(
            matches!(filed.as_slice(), [(dragged, Some(_))] if *dragged == id),
            "the drag filed the row it started on: {filed:?}"
        );
    }

    /// Paint the table headlessly at the width the centre has with both docks open and
    /// at the width it has with none, and pick a row in each so the footer is drawn too.
    ///
    /// Nothing checks pixels. What this catches is a layout that panics, an id that
    /// collides, or a track that a row paints past.
    #[test]
    fn the_table_paints_at_every_width_the_centre_has() {
        let ctx = context();
        let mut workspace = Workspace::new(ctx.clone());
        let mut device = Device::new(ctx.clone());
        let mut log = Log::default();
        let mut tabs = Tabs::default();
        let mut browser = Browser::default();
        let mut library = Library::default();
        let mut queue = Queue::default();
        let shell = Shell::default();

        for kind in [Fresh::Program, Fresh::Live, Fresh::Settings] {
            workspace.create(kind, &mut log).unwrap();
        }
        device.pretend_scanned(ObjectClass::Program, 7, &["Africa Split", "", "Squabble B"]);
        device.pretend_scanned(ObjectClass::Piano, 1, &["Royal Grand 3D"]);
        device.pretend_scanned(ObjectClass::SetList, 1, &["Sunday"]);

        // The first row's middle: the bar, the head, and half a row down; and far enough
        // in to land in the name column at either width.
        let on_a_row = egui::pos2(60.0, BAR + HEAD + ROW / 2.0);
        let press = |pressed| egui::Event::PointerButton {
            pos: on_a_row,
            button: egui::PointerButton::Primary,
            pressed,
            modifiers: egui::Modifiers::NONE,
        };
        for width in [430.0_f32, 900.0] {
            // The pointer moves, then presses, then the next frame has a row picked and
            // draws the footer under the table.
            let frames: [Vec<egui::Event>; 4] = [
                Vec::new(),
                vec![egui::Event::PointerMoved(on_a_row)],
                vec![press(true), press(false)],
                Vec::new(),
            ];
            for events in frames {
                let input = egui::RawInput {
                    events,
                    screen_rect: Some(egui::Rect::from_min_size(
                        egui::Pos2::ZERO,
                        egui::vec2(width, 540.0),
                    )),
                    ..Default::default()
                };
                let _ = ctx.run(input, |ctx| {
                    // The frame the centre actually uses: panels own their own padding.
                    egui::CentralPanel::default()
                        .frame(egui::Frame::new())
                        .show(ctx, |ui| {
                            let acts =
                                library.ui(ui, &mut browser, &workspace, &device, &queue, &shell);
                            apply(
                                &mut browser,
                                &mut Shell::default(),
                                acts,
                                &mut workspace,
                                &mut device,
                                &mut tabs,
                                &mut queue,
                                &mut log,
                            );
                        });
                });
            }
            assert!(
                browser.picked().sole().is_some(),
                "a click on a row picked it at {width}"
            );
        }
    }
}