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
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
//! The piano-library document.
//!
//! A `.npno` is hundreds of megabytes of recorded notes — one **stroke** per root note,
//! bank and velocity layer — and what an editor of one is for is deciding which of them
//! go on the instrument. So an edit here is not a field write: it is a **plan** over the
//! bytes the asset was last saved as, and the working bytes are what [`rebuild`] makes
//! of the two.
//!
//! ⚠️ An edit never makes those bytes. [`planned`] applies a plan over the borrowed
//! baseline and is what a switch is checked against; [`materialise`] is the one whole-
//! body copy, and it runs off the frame when the library is saved, sent or exported.
//!
//! ⚠️ Nothing decodes to draw a frame. The facts the sections read — the roots, the
//! layers, the banks and what each of them costs — are read out of the saved baseline
//! once and kept; a stroke's audio is decoded only when someone asks to hear it.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::ops::RangeInclusive;

use eframe::egui;
use nord_format::formats::npno::encode::{Kind, ALL_KEYS_DAMPED};
use nord_format::formats::npno::{self, Bank, FINE_TUNE_CENTS_PER_UNIT};
use nord_format::note;
use nord_format::Entity;
use nord_usb::ObjectClass;

use super::capability::{self, Offset, Row, State as Cap};
use super::controls::{self, Sets};
use super::keys::{self, Audition, Scale, SizeCell, Span};
use super::{Extras, Ink, Loud, SizeLine, StateLine, Tone};
use crate::app;
use crate::browser::Act;
use crate::device::DeviceState;
use crate::icon::{icon, painted, Glyph};
use crate::led;
use crate::room;
use crate::work;
use crate::workspace::{LocalEntity, Workspace};

pub fn is_piano(entity: &Entity) -> bool {
    matches!(entity, Entity::Piano(_))
}

fn piano(entity: &Entity) -> Option<&npno::Piano> {
    match entity {
        Entity::Piano(piano) => Some(piano),
        _ => None,
    }
}

/// The two halves of the name field, split on its separator.
#[derive(Clone, PartialEq, Eq)]
pub struct Snapshot {
    pub name: String,
    /// The text after the `#`, where the vendor records the voicing and the library's
    /// size. Empty where the field carries none.
    pub variant: String,
}

pub fn snapshot(entity: &Entity) -> Option<Result<Snapshot, String>> {
    Some(read(piano(entity)?))
}

fn read(piano: &npno::Piano) -> Result<Snapshot, String> {
    let (name, variant) = piano.name().map_err(|e| e.to_string())?;
    Ok(Snapshot { name, variant })
}

/// The stretch of keyboard the map draws: a full piano, A0 to C8.
const SPAN: Span = Span { low: 21, high: 108 };

/// What the asset was last saved as, as far as anything here tells two baselines apart.
/// A save moves both halves at once.
type Mark = (usize, Option<u32>);

fn mark(entity: &LocalEntity) -> Mark {
    (entity.saved.bytes.len(), entity.saved.crc32)
}

/// Every edit a piano document holds, against the baseline it is an edit of.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Plan {
    against: Mark,
    /// Banks dropped whole. [`Bank::Attack`] is never one: a library with no attack
    /// strokes answers no key at all.
    banks: BTreeSet<Bank>,
    /// Layer values dropped on every root.
    layers: BTreeSet<u8>,
    /// The exceptions one root makes to those switches, by `(root note, layer value)`.
    roots: BTreeMap<(u8, u8), bool>,
    /// The keys the library is cut to, where it is cut.
    range: Option<RangeInclusive<u8>>,
    name: Option<String>,
    variant: Option<String>,
    /// Retuned keys, in the file's own units — see [`FINE_TUNE_CENTS_PER_UNIT`].
    fine_tune: BTreeMap<u8, i8>,
    /// A gain over the whole library, in signed tenths of a decibel.
    gain: Option<i8>,
    /// The highest key damped at note-off; [`ALL_KEYS_DAMPED`] leaves none ringing.
    damper_top: Option<u8>,
    /// The kind of instrument the library files itself under.
    kind: Option<Kind>,
    /// Decibels a stroke is attenuated by, keyed by `(root, bank code, layer value)` —
    /// the stroke's place in the directory, which a drop moves.
    trims: BTreeMap<(u8, u8, u8), u16>,
    /// The root a re-routed key plays, `None` where it plays nothing.
    key_roots: BTreeMap<u8, Option<u8>>,
}

impl Plan {
    /// Whether it edits nothing at all. The baseline it stands against is not an edit.
    pub fn is_empty(&self) -> bool {
        let Plan {
            against: _,
            banks,
            layers,
            roots,
            range,
            name,
            variant,
            fine_tune,
            gain,
            damper_top,
            kind,
            trims,
            key_roots,
        } = self;
        banks.is_empty()
            && layers.is_empty()
            && roots.is_empty()
            && range.is_none()
            && name.is_none()
            && variant.is_none()
            && fine_tune.is_empty()
            && gain.is_none()
            && damper_top.is_none()
            && kind.is_none()
            && trims.is_empty()
            && key_roots.is_empty()
    }

    /// Whether one root keeps one layer: its own exception, or what the switch says.
    fn keeps_layer(&self, root: u8, layer: u8) -> bool {
        match self.roots.get(&(root, layer)) {
            Some(kept) => *kept,
            None => !self.layers.contains(&layer),
        }
    }

    /// A bank code the format does not name is kept: no row of the trim section
    /// selects it, so nothing can have asked for it to go.
    fn keeps_bank(&self, bank: Option<Bank>) -> bool {
        match bank {
            Some(bank) => !self.banks.contains(&bank),
            None => true,
        }
    }

    /// The keys the plan routes to the root at `index`, in no order: the ones the
    /// baseline sends it that no re-route has taken, and the ones a re-route has given
    /// it.
    fn routed<'a>(&'a self, facts: &'a Facts, index: usize) -> impl Iterator<Item = u8> + 'a {
        let note = facts.roots[index].note;
        facts.roots[index]
            .keys
            .iter()
            .copied()
            .filter(|key| !self.key_roots.contains_key(key))
            .chain(
                self.key_roots
                    .iter()
                    .filter(move |(_, root)| **root == Some(note))
                    .map(|(key, _)| *key),
            )
    }

    /// The keys the plan routes to the root at `index`, ascending.
    fn keys_of(&self, facts: &Facts, index: usize) -> Vec<u8> {
        let mut keys: Vec<u8> = self.routed(facts, index).collect();
        keys.sort_unstable();
        keys
    }

    /// The root the plan's map sends `key` to.
    fn answers(&self, facts: &Facts, key: u8) -> Option<usize> {
        match self.key_roots.get(&key) {
            Some(root) => root.and_then(|note| facts.index_of(note)),
            None => facts.answers(key),
        }
    }

    /// Whether a range cut still leaves this root a key to answer. A root keeping one
    /// key keeps every stroke it has.
    fn in_range(&self, facts: &Facts, index: usize) -> bool {
        match &self.range {
            None => true,
            Some(range) => self.routed(facts, index).any(|key| range.contains(&key)),
        }
    }

    fn keeps(&self, facts: &Facts, cell: &Cell) -> bool {
        let root = &facts.roots[cell.root];
        self.in_range(facts, cell.root)
            && self.keeps_bank(cell.bank)
            && self.keeps_layer(root.note, cell.layer)
    }

    /// Route `key` to a root, or to nothing, dropping an entry the baseline already
    /// says so that an empty plan stays empty.
    fn route(&mut self, facts: &Facts, key: u8, root: Option<usize>) {
        let note = root.map(|index| facts.roots[index].note);
        match facts.answers(key).map(|index| facts.roots[index].note) == note {
            true => self.key_roots.remove(&key),
            false => self.key_roots.insert(key, note),
        };
    }

    /// Throw one layer's switch for every root.
    ///
    /// ⚠️ It clears that layer's per-root exceptions. A master switch that left them
    /// standing would say one thing and do another.
    fn switch_layer(&mut self, layer: u8, keep: bool) {
        self.roots.retain(|(_, held), _| *held != layer);
        match keep {
            true => self.layers.remove(&layer),
            false => self.layers.insert(layer),
        };
    }

    /// Take one root's exception to a layer's switch.
    ///
    /// ⚠️ An exception that agrees with the switch is dropped rather than recorded: a
    /// plan holding one reads as an edit, and every save and send would lay the library
    /// out again for the bytes it already holds.
    fn except(&mut self, root: u8, layer: u8, keep: bool) {
        match keep == !self.layers.contains(&layer) {
            true => self.roots.remove(&(root, layer)),
            false => self.roots.insert((root, layer), keep),
        };
    }

    fn switch_bank(&mut self, bank: Bank, keep: bool) {
        match keep {
            true => self.banks.remove(&bank),
            false => self.banks.insert(bank),
        };
    }

    /// The keys `key` reads as retuned to, in file units.
    fn tune(&self, facts: &Facts, key: u8) -> i8 {
        match self.fine_tune.get(&key) {
            Some(units) => *units,
            None => facts.tune(key),
        }
    }
}

/// The library a plan makes of the baseline, with nothing copied: every stroke's audio
/// is still borrowed out of `saved`.
///
/// This is where a plan is checked — the format's own refusals, and the one this editor
/// adds — so throwing a switch costs a walk of the stroke directory and no more. From
/// the baseline every time, so a switch put back on puts its strokes back with it.
pub fn planned<'a>(saved: &'a [u8], plan: &Plan) -> Result<npno::Library<'a>, String> {
    let mut library = npno::Library::borrow(saved).map_err(|e| e.to_string())?;
    if let Some(name) = &plan.name {
        library.set_name(name).map_err(|e| e.to_string())?;
    }
    if let Some(variant) = &plan.variant {
        library.set_variant(variant).map_err(|e| e.to_string())?;
    }
    for (key, units) in &plan.fine_tune {
        library
            .set_fine_tune(*key, *units)
            .map_err(|e| e.to_string())?;
    }
    if let Some(tenths) = plan.gain {
        library.set_gain(tenths);
    }
    if let Some(key) = plan.damper_top {
        library.set_damper_top(key).map_err(|e| e.to_string())?;
    }
    if let Some(kind) = plan.kind {
        library.set_kind(kind);
    }
    // Before anything is dropped, so that a route to a root the directory no longer
    // records is refused by the format rather than accepted against a shorter list.
    for (key, root) in &plan.key_roots {
        library
            .set_key_root(*key, *root)
            .map_err(|e| e.to_string())?;
    }
    if let Some(range) = &plan.range {
        library
            .cut_range(range.clone())
            .map_err(|e| e.to_string())?;
    }
    for bank in &plan.banks {
        library.drop_bank(*bank);
    }
    // One predicate over both: an exception keeps a layer its switch dropped.
    if !plan.layers.is_empty() || !plan.roots.is_empty() {
        library.retain_strokes(|stroke| plan.keeps_layer(stroke.root, stroke.layer()));
    }
    if library.strokes().is_empty() {
        return Err("that would leave the library with no strokes at all".to_string());
    }
    // After the drops: a trim names the stroke it belongs to, and the index that stroke
    // sits at moves as strokes before it go. A trim on a stroke that has gone has no
    // record left to write.
    for ((root, bank, layer), decibels) in &plan.trims {
        let at = library.strokes().iter().position(|stroke| {
            (stroke.root, stroke.bank_code(), stroke.layer()) == (*root, *bank, *layer)
        });
        if let Some(at) = at {
            library.set_trim(at, *decibels).map_err(|e| e.to_string())?;
        }
    }
    Ok(library)
}

/// The bytes a planned library is written as: the directory and every audio offset
/// re-laid, the container's checksum recomputed.
///
/// ⚠️ The whole body is copied here, and a vendor library is hundreds of megabytes. It
/// is the one slow step, and [`State::start`] is what keeps it off the frame.
pub fn materialise(library: &npno::Library<'_>) -> Result<Vec<u8>, String> {
    let edited = library.to_piano().map_err(|e| e.to_string())?;
    nord_format::to_bytes(&Entity::Piano(edited)).map_err(|e| e.to_string())
}

/// The bytes a plan makes of the baseline: [`planned`] and then [`materialise`], which
/// the app itself keeps apart so that it checks a plan without laying one out.
#[cfg(test)]
pub fn rebuild(saved: &[u8], plan: &Plan) -> Result<Vec<u8>, String> {
    materialise(&planned(saved, plan)?)
}

/// One root note: the recording, and the keys the map sends to it.
struct Root {
    note: u8,
    keys: Vec<u8>,
}

/// Ascending `keys` as the stretches they run in.
///
/// A root's keys are one run.
///
/// Inferred from specimens; not confirmed on hardware.
///
/// The key map can hold anything, so a root whose keys are not contiguous gets one cell
/// per run rather than one cell over the keys between them.
fn runs(keys: &[u8]) -> Vec<(u8, u8)> {
    let mut out: Vec<(u8, u8)> = Vec::new();
    for key in keys {
        match out.last_mut() {
            Some((_, top)) if *top + 1 == *key => *top = *key,
            _ => out.push((*key, *key)),
        }
    }
    out
}

/// The audio one root's layer of one bank owns. Every stroke lands in exactly one.
struct Cell {
    root: usize,
    layer: u8,
    /// `None` for a bank code the format does not name.
    bank: Option<Bank>,
    bytes: u64,
}

/// One stroke as the open root's row lists it.
struct Strike {
    root: usize,
    /// The record's own bank byte, which is the half of a trim's key [`Bank`] cannot
    /// carry for a code the format does not name.
    bank: u8,
    layer: u8,
    /// The `+0x34` attenuation, in decibels.
    trim: u16,
    /// What the applied-decay ladder at `+0x36` states, in decibels a second; `None`
    /// where every entry of it applies nothing.
    decay: Option<f32>,
}

/// What the applied-decay ladder is worth, in decibels a second, read off its first
/// entry: a one-pole coefficient of `entry / 2^23` a frame at [`npno::codec::RATE`], so
/// `20·log10(e)·rate·(1 − entry/2^23)`.
///
/// Inferred from specimens; not confirmed on hardware.
///
/// `None` where every entry of it is [`npno::LADDER_UNITY`], which applies nothing.
fn decay_rate(ladder: &[u32; npno::DECAYS]) -> Option<f32> {
    let held = 1.0 - f64::from(ladder[0]) / f64::from(npno::LADDER_UNITY);
    ladder
        .iter()
        .any(|entry| *entry != npno::LADDER_UNITY)
        .then_some((8.686 * f64::from(npno::codec::RATE) * held) as f32)
}

/// Everything the piano editor draws from, read once out of the saved baseline.
///
/// ⚠️ The **baseline**, not the working bytes: the plan drops strokes, and every row has
/// to go on offering what putting its switch back would restore.
struct Facts {
    name: String,
    variant: String,
    stream: u16,
    channels: u16,
    /// The file's own size, which is the scale the trim section measures against.
    total: u64,
    strokes: usize,
    roots: Vec<Root>,
    /// Where each root note sits in `roots`.
    of_note: BTreeMap<u8, usize>,
    /// The layer values the directory holds, ascending — 0 the loudest.
    layers: Vec<u8>,
    /// The banks present, in [`Bank::ALL`] order.
    banks: Vec<Bank>,
    cells: Vec<Cell>,
    /// Every stroke, in directory order.
    strikes: Vec<Strike>,
    /// The per-key fine tune table, in file units.
    fine_tune: Vec<i8>,
    /// The root the map sends each of the 128 keys to.
    of_key: Vec<Option<usize>>,
    /// The keys the map routes somewhere, ascending.
    covered: Vec<u8>,
    /// A gain over the whole library, in signed tenths of a decibel.
    gain: i8,
    /// The highest key damped at note-off.
    damper_top: u8,
    /// The instrument kind the library files itself under; [`kind_name`] spells it.
    kind: u8,
}

impl Facts {
    fn of(saved: &[u8]) -> Result<Facts, String> {
        let library = npno::Library::borrow(saved).map_err(|e| e.to_string())?;
        let (name, variant) = library.name();
        let notes = library.roots();
        let roots: Vec<Root> = notes
            .iter()
            .map(|note| Root {
                note: *note,
                keys: library.keys_for(*note),
            })
            .collect();
        // `Library::roots` is the set of the strokes' own root notes, so every stroke
        // and every key the map covers names one of these.
        let of_note: BTreeMap<u8, usize> = notes.iter().copied().zip(0..).collect();

        let mut grouped: BTreeMap<(usize, u8, Option<Bank>), u64> = BTreeMap::new();
        let mut strikes: Vec<Strike> = Vec::with_capacity(library.strokes().len());
        for stroke in library.strokes() {
            let root = of_note[&stroke.root];
            *grouped
                .entry((root, stroke.layer(), stroke.bank()))
                .or_default() += stroke.audio().len() as u64;
            strikes.push(Strike {
                root,
                bank: stroke.bank_code(),
                layer: stroke.layer(),
                trim: stroke.trim(),
                decay: decay_rate(&stroke.ladder()),
            });
        }
        let cells: Vec<Cell> = grouped
            .into_iter()
            .map(|((root, layer, bank), bytes)| Cell {
                root,
                layer,
                bank,
                bytes,
            })
            .collect();
        let layers: BTreeSet<u8> = cells.iter().map(|cell| cell.layer).collect();
        let present: BTreeSet<Bank> = cells.iter().filter_map(|cell| cell.bank).collect();
        let of_key: Vec<Option<usize>> = library
            .key_map()
            .iter()
            .map(|note| of_note.get(note).copied())
            .collect();

        Ok(Facts {
            name,
            variant,
            stream: library.stream_version(),
            channels: library.channels(),
            total: saved.len() as u64,
            strokes: library.strokes().len(),
            roots,
            of_note,
            layers: layers.into_iter().collect(),
            banks: Bank::ALL
                .into_iter()
                .filter(|bank| present.contains(bank))
                .collect(),
            cells,
            strikes,
            fine_tune: (0..npno::NOTES)
                .map(|key| library.fine_tune(key as u8).unwrap_or(0))
                .collect(),
            covered: of_key
                .iter()
                .enumerate()
                .filter(|(_, root)| root.is_some())
                .map(|(key, _)| key as u8)
                .collect(),
            of_key,
            gain: library.gain(),
            damper_top: library.damper_top(),
            kind: library.kind_code(),
        })
    }

    fn tune(&self, key: u8) -> i8 {
        self.fine_tune.get(usize::from(key)).copied().unwrap_or(0)
    }

    /// The root the baseline's map sends `key` to.
    fn answers(&self, key: u8) -> Option<usize> {
        self.of_key.get(usize::from(key)).copied().flatten()
    }

    fn index_of(&self, note: u8) -> Option<usize> {
        self.of_note.get(&note).copied()
    }

    /// The layers as the sections list them, softest first, each with its rank among
    /// the layers the file holds — rank 0 is the loudest.
    fn shown_layers(&self) -> Vec<(usize, u8)> {
        let count = self.layers.len();
        (0..count)
            .rev()
            .map(|rank| (rank, self.layers[rank]))
            .collect()
    }

    fn channel_word(&self) -> &'static str {
        match self.channels {
            1 => "mono",
            _ => "stereo",
        }
    }
}

/// Bytes a plan keeps: the file, less the audio of every stroke it drops, so a plan
/// that drops nothing reads as the whole file.
fn kept_bytes(facts: &Facts, plan: &Plan) -> u64 {
    facts.total.saturating_sub(
        facts
            .cells
            .iter()
            .filter(|cell| !plan.keeps(facts, cell))
            .map(|cell| cell.bytes)
            .sum(),
    )
}

/// Bytes the cells `pick` selects still hold, which is what dropping them would shed.
fn shed_bytes(facts: &Facts, plan: &Plan, pick: impl Fn(&Cell) -> bool) -> u64 {
    facts
        .cells
        .iter()
        .filter(|cell| plan.keeps(facts, cell) && pick(cell))
        .map(|cell| cell.bytes)
        .sum()
}

/// One switch of the trim section, and what it selects.
#[derive(Clone, Copy, PartialEq, Eq)]
enum What {
    Layer(u8),
    Bank(Bank),
}

/// A cut the constraint sentence could name: what it would shed, and the switches it
/// would throw.
struct Cut {
    shed: u64,
    picked: Vec<String>,
}

/// How many switches the search walks. Every subset of them is tried, and a library
/// with more layers than this offers its softest ones and its banks — the cheap cuts.
const CUT_ITEMS: usize = 12;

/// The cheapest set of switches still on that would shed at least `over`.
///
/// Cheapest by megabytes first, then by layers spent, then by switches thrown: a trim
/// should cost the least audio, and of two that cost the same the one that keeps more
/// of the velocity range. Nothing already off is offered, and nothing that would leave
/// the library with no strokes at all.
fn cheapest_cut(facts: &Facts, plan: &Plan, over: u64) -> Option<Cut> {
    let items = droppable(facts, plan);
    let live = shed_bytes(facts, plan, |_| true);
    let mut best: Option<(u64, usize, usize, Vec<String>)> = None;
    for mask in 1..(1u32 << items.len()) {
        let pick: Vec<&(String, What)> = items
            .iter()
            .enumerate()
            .filter(|(index, _)| mask & (1 << index) != 0)
            .map(|(_, item)| item)
            .collect();
        let selects = |cell: &Cell| {
            pick.iter().any(|(_, what)| match what {
                What::Layer(layer) => cell.layer == *layer,
                What::Bank(bank) => cell.bank == Some(*bank),
            })
        };
        let shed = shed_bytes(facts, plan, selects);
        // A cut that sheds every stroke still kept would leave nothing to play.
        if shed < over || shed >= live {
            continue;
        }
        let layers = pick
            .iter()
            .filter(|(_, what)| matches!(what, What::Layer(_)))
            .count();
        let rank = (shed, layers, pick.len());
        if best
            .as_ref()
            .is_none_or(|held| rank < (held.0, held.1, held.2))
        {
            best = Some((
                shed,
                layers,
                pick.len(),
                pick.iter().map(|(name, _)| name.to_lowercase()).collect(),
            ));
        }
    }
    best.map(|(shed, _, _, picked)| Cut { shed, picked })
}

/// The switches still on, as the search offers them.
fn droppable(facts: &Facts, plan: &Plan) -> Vec<(String, What)> {
    let mut items: Vec<(String, What)> = Vec::new();
    for bank in &facts.banks {
        if *bank != Bank::Attack && plan.keeps_bank(Some(*bank)) {
            items.push((bank_name(*bank).to_string(), What::Bank(*bank)));
        }
    }
    for (rank, layer) in facts.shown_layers() {
        if shed_bytes(facts, plan, |cell| cell.layer == layer) > 0 {
            items.push((
                format!("{} layer", layer_name(rank, facts.layers.len())),
                What::Layer(layer),
            ));
        }
    }
    items.truncate(CUT_ITEMS);
    items
}

/// A list of switches as a sentence names them: `the soft layer, medium layer and
/// release samples`.
fn listed(names: &[String]) -> String {
    match names.split_last() {
        None => String::new(),
        Some((last, [])) => last.clone(),
        Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
    }
}

/// What a layer is called, by its rank among the layers the file holds — rank 0 is the
/// loudest. Three of them are the panel's own three words.
fn layer_name(rank: usize, count: usize) -> String {
    match (count, rank) {
        (3, 0) => "Hard".to_string(),
        (3, 1) => "Medium".to_string(),
        (3, 2) => "Soft".to_string(),
        (_, 0) => "Loudest".to_string(),
        (count, rank) if rank + 1 == count => "Softest".to_string(),
        (_, rank) => format!("Layer {}", rank + 1),
    }
}

/// The velocities each of a root's layer values is the one that sounds, in the order
/// the values are given.
///
/// A key sounds the largest value its root holds that is at most `(127 − v)·31/127`
/// ([`npno::Stroke::layer`]), so between a louder value `a` and the next softer `b` the
/// split is at `v = 127 − ⌈b·127/31⌉`: `b` plays up to there and `a` from the next
/// velocity up. A value no velocity ever reaches gets an empty range.
fn spans(values: &[u8]) -> Vec<(u8, RangeInclusive<u8>)> {
    let mut out: Vec<(u8, RangeInclusive<u8>)> = Vec::with_capacity(values.len());
    let mut below = 0u8;
    for value in values.iter().rev() {
        let over = (u32::from(*value) * 127).div_ceil(31).min(127) as u8;
        let top = 127 - over;
        out.push((*value, below.saturating_add(1)..=top));
        below = below.max(top);
    }
    out.reverse();
    out
}

/// A velocity span as the lanes print it.
fn span_text(span: &RangeInclusive<u8>) -> String {
    match span.start() > span.end() {
        true => "no velocity".to_string(),
        false => format!("v {}{}", span.start(), span.end()),
    }
}

/// The letter a layer wears on a root's row.
fn layer_short(rank: usize, count: usize) -> String {
    match (count, rank) {
        (3, 0) => "H".to_string(),
        (3, 1) => "M".to_string(),
        (3, 2) => "S".to_string(),
        (_, rank) => (rank + 1).to_string(),
    }
}

fn bank_name(bank: Bank) -> &'static str {
    match bank {
        Bank::Attack => "Attack samples",
        Bank::Resonance => "Pedal resonance",
        Bank::Release => "Release samples",
    }
}

/// What a bank is called on a stroke's line, a code the format does not name included.
fn bank_word(code: u8) -> String {
    match Bank::from_code(code) {
        Some(bank) => bank_name(bank).to_string(),
        None => format!("bank {code}"),
    }
}

fn kind_word(kind: Kind) -> &'static str {
    match kind {
        Kind::ElectricGrand => "Electric grand",
        Kind::ElectricPiano => "Electric piano",
        Kind::Wurlitzer => "Reed piano",
        Kind::Clavinet => "Clavinet",
        Kind::Grand => "Grand",
        Kind::Upright => "Upright",
        Kind::Harpsichord => "Harpsichord",
        Kind::DigitalPiano => "Digital piano",
        Kind::Hybrid => "Hybrid",
        Kind::Mallet => "Mallet",
    }
}

/// What the panel calls the kind a library files itself under, a code the format does
/// not name included.
fn kind_name(code: u8) -> String {
    match Kind::from_code(code) {
        Some(kind) => kind_word(kind).to_string(),
        None => format!("kind {code}"),
    }
}

fn bank_note(bank: Bank) -> &'static str {
    match bank {
        Bank::Attack => "every library has these",
        Bank::Resonance => "what the Small library leaves out",
        Bank::Release => "the key-up tail",
    }
}

/// The range the Keys switch cuts to when it goes off: the middle of the keyboard, as
/// far as the library reaches.
fn default_range(facts: &Facts) -> RangeInclusive<u8> {
    const MIDDLE: RangeInclusive<u8> = 36..=96;
    let low = facts.covered.first().copied().unwrap_or(*MIDDLE.start());
    let high = facts.covered.last().copied().unwrap_or(*MIDDLE.end());
    (*MIDDLE.start()).max(low)..=(*MIDDLE.end()).min(high)
}

/// One stroke, decoded.
struct Played {
    /// Frames interleaved by channel at [`npno::codec::RATE`], which is what both the
    /// speakers and a WAV take.
    samples: Vec<i16>,
    channels: u16,
}

/// The one stroke a decode names: `(root, bank code, layer value)`.
type Pick = (u8, u8, u8);

/// How many decoded strokes are kept. A vendor stroke is seconds of audio, so the cache
/// is small and the least recently heard one goes.
const KEPT_STROKES: usize = 8;

/// Strokes decoded on request, most recently used first.
///
/// ⚠️ Keyed by the asset's [`stamp`](LocalEntity::stamp) as well as its id, the way the
/// sample editor's cache is: a trim re-lays the file, and what was decoded from what it
/// held before came off another library.
#[derive(Default)]
struct Cache {
    of: Option<(u64, u64)>,
    strokes: Vec<(Pick, Result<Played, String>)>,
}

impl Cache {
    fn follow(&mut self, id: u64, stamp: u64) {
        if self.of != Some((id, stamp)) {
            self.of = Some((id, stamp));
            self.strokes.clear();
        }
    }

    /// The newest decode of this root, which is the one a decode of it just made or
    /// reached for.
    fn newest(&self, root: u8) -> Option<(Pick, &Played)> {
        self.strokes
            .iter()
            .find(|(stroke, _)| stroke.0 == root)
            .and_then(|(stroke, played)| Some((*stroke, played.as_ref().ok()?)))
    }

    /// Bring one stroke to the front, where it is held at all.
    fn touch(&mut self, stroke: Pick) -> Option<&Result<Played, String>> {
        let at = self.strokes.iter().position(|(held, _)| *held == stroke)?;
        let held = self.strokes.remove(at);
        self.strokes.insert(0, held);
        self.strokes.first().map(|(_, played)| played)
    }

    /// Decode one root's loudest kept attack stroke, once. A refusal by the codec is
    /// remembered like a success: asking again would only produce it a second time.
    ///
    /// ⚠️ One stroke, whatever else the library holds: the audio of a whole root is more
    /// than this app ever has a use for at once.
    fn decode(&mut self, bytes: &[u8], plan: &Plan, root: u8) -> Result<(), String> {
        let library = npno::Library::borrow(bytes).map_err(|e| e.to_string())?;
        let stroke = loudest(&library, plan, root)?;
        let key = (root, Bank::Attack.code(), stroke.layer());
        if let Some(held) = self.touch(key) {
            return held.as_ref().map(|_| ()).map_err(String::clone);
        }
        let made = npno::codec::decode(stroke, library.channels())
            .map_err(|e| e.to_string())
            .map(|audio| Played {
                samples: audio.interleaved(),
                channels: library.channels(),
            });
        let answer = made.as_ref().map(|_| ()).map_err(String::clone);
        self.strokes.insert(0, (key, made));
        self.strokes.truncate(KEPT_STROKES);
        answer
    }
}

/// The root's loudest stroke of [`Bank::Attack`] the plan keeps — the recording a key on
/// it reaches for at the top of the velocity range, which is
/// [`Stroke::layer`](npno::Stroke::layer)'s law. Confirmed on hardware.
fn loudest<'a>(
    library: &'a npno::Library<'a>,
    plan: &Plan,
    root: u8,
) -> Result<&'a npno::Stroke<'a>, String> {
    library
        .strokes()
        .iter()
        .filter(|stroke| stroke.root == root && stroke.bank() == Some(Bank::Attack))
        .filter(|stroke| plan.keeps_layer(root, stroke.layer()))
        .min_by_key(|stroke| stroke.layer())
        .ok_or_else(|| {
            format!(
                "root {} has no attack stroke left to play",
                note::name(root)
            )
        })
}

/// What a piano document's frame asked the app to do about one root's audio. The root
/// has to be decoded either way, so there is no separate ask for that.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Ask {
    /// Start this root, or stop it if it is the one sounding.
    Play(u8),
    /// Sound this root for a struck key, `semitones` from the root it was recorded at.
    Strike {
        root: u8,
        semitones: i16,
    },
    Save(u8),
}

impl Ask {
    pub fn root(self) -> u8 {
        match self {
            Ask::Play(root) | Ask::Save(root) | Ask::Strike { root, .. } => root,
        }
    }
}

/// One root's decoded stroke, ready to play or to write.
pub struct Sound<'a> {
    pub samples: &'a [i16],
    pub channels: u16,
    pub rate: u32,
    /// What a WAV of it is called — the spelling `nord piano decode` writes.
    pub name: String,
}

/// The row the map and the rows agree on, and what the keyboard is sounding. A tab
/// switch resets all of it — but never the plan, which is the edit.
#[derive(Default)]
struct View {
    picked: Option<usize>,
    open_rows: BTreeSet<usize>,
    /// A row to bring up under the map next frame, once it has a rect to scroll to.
    reveal: Option<usize>,
    key_table: bool,
    audition: Option<Audition>,
}

/// The document being drawn: its baseline, and the facts read out of it.
struct Open {
    id: u64,
    baseline: Mark,
    facts: Result<Facts, String>,
}

/// One plan being laid out, and the document it belongs to.
struct Laying {
    id: u64,
    /// What it is laying out, so an answer over a plan that has since moved is dropped.
    plan: Plan,
    job: work::Job<Result<Vec<u8>, String>>,
}

/// Where a document's plan stands between the switch being thrown and the bytes it
/// makes.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Standing {
    /// The working bytes hold it.
    Laid,
    /// It is an edit nothing has laid out yet.
    Pending,
    /// It is being laid out now.
    Applying,
}

/// One act waiting on a document's apply.
type Held = (u64, Act);

/// What a finished apply left: the bytes it made of one document's plan, and the acts
/// that have nothing left to wait for.
pub struct Applied {
    pub id: u64,
    /// `None` where the plan moved while the apply ran, and the bytes it made are of a
    /// library nobody asked for any more.
    pub made: Option<Result<Vec<u8>, String>>,
    pub acts: Vec<Act>,
}

#[derive(Default)]
pub struct State {
    /// The plan for each piano document, by id.
    ///
    /// ⚠️ Not dropped when the tab changes. The plan is the only record of what the
    /// working bytes were trimmed from, so leaving the tab must not throw it away.
    plans: HashMap<u64, Plan>,
    /// The plan each document's working bytes were laid out from. A plan they already
    /// hold is not pending, and laying it again would copy the body for nothing.
    laid: HashMap<u64, Plan>,
    /// The one apply in flight, and the acts held until it answers.
    job: Option<Laying>,
    held: Vec<Held>,
    open: Option<Open>,
    /// The plan as this frame's controls have left it, to be tried before it is kept.
    draft: Plan,
    /// What the sections read off that plan, worked out when it moves.
    summary: Option<Summary>,
    view: View,
    audio: Cache,
    /// What the attached instrument has free for pianos, read where the device is in
    /// hand — the sections are drawn where it is not.
    free: Option<u64>,
}

impl State {
    /// Read the baseline, take up the plan, and answer with what the header shows over
    /// a piano library that the asset alone does not say.
    ///
    /// [`Extras::default`] for anything that is no piano library, which is what leaves
    /// the header's own rules running.
    pub fn begin(&mut self, id: u64, entity: &LocalEntity, device: &DeviceState) -> Extras {
        if !entity.entity.as_ref().is_some_and(is_piano) {
            self.open = None;
            return Extras::default();
        }
        let baseline = mark(entity);
        let moved = self
            .open
            .as_ref()
            .is_none_or(|open| (open.id, open.baseline) != (id, baseline));
        if moved {
            self.open = Some(Open {
                id,
                baseline,
                facts: Facts::of(&entity.saved.bytes),
            });
            self.view = View::default();
            // The figures go with the facts they were worked out from.
            self.summary = None;
        }
        let plan = self.plans.entry(id).or_default();
        // A save makes what was dropped gone for good: the rows show the file as it now
        // is, and there is nothing left to put back.
        if plan.against != baseline {
            *plan = Plan {
                against: baseline,
                ..Plan::default()
            };
            self.laid.remove(&id);
        }
        self.draft = plan.clone();
        self.audio.follow(id, entity.stamp);
        self.free = room::free_bytes(ObjectClass::Piano, device);
        self.summarise();
        let standing = self.standing(id);

        let (Some(facts), Some(summary)) = (self.facts(), self.summary.as_ref()) else {
            return Extras::default();
        };
        extras(facts, summary.kept, self.free, standing)
    }

    /// Work the figures out again where the plan or the room it has to fit in has moved.
    /// A frame that changed neither reads what the last one left.
    fn summarise(&mut self) {
        let State {
            open,
            draft,
            free,
            summary,
            ..
        } = self;
        let Some(facts) = open.as_ref().and_then(|open| open.facts.as_ref().ok()) else {
            *summary = None;
            return;
        };
        if summary
            .as_ref()
            .is_none_or(|held| held.of != *draft || held.free != *free)
        {
            *summary = Some(Summary::of(facts, draft, *free));
        }
    }

    /// Where this document's plan stands.
    fn standing(&self, id: u64) -> Standing {
        match &self.job {
            Some(job) if job.id == id => Standing::Applying,
            _ => match self.pending(id) {
                true => Standing::Pending,
                false => Standing::Laid,
            },
        }
    }

    /// Whether this document's plan has yet to reach its working bytes.
    pub fn pending(&self, id: u64) -> bool {
        let Some(plan) = self.plans.get(&id) else {
            return false;
        };
        match self.laid.get(&id) {
            Some(laid) => plan != laid,
            None => !plan.is_empty(),
        }
    }

    fn facts(&self) -> Option<&Facts> {
        self.open.as_ref()?.facts.as_ref().ok()
    }

    /// Take one of the header's `path = value` sets into the plan.
    pub fn take(&mut self, sets: &Sets) -> Result<(), String> {
        let State { open, draft, .. } = self;
        let facts = open.as_ref().and_then(|open| open.facts.as_ref().ok());
        for (path, value) in sets {
            match path.as_str() {
                "name" => draft.name = renamed(value, facts.map(|facts| facts.name.as_str())),
                "variant" => {
                    draft.variant = renamed(value, facts.map(|facts| facts.variant.as_str()));
                }
                _ => return Err(format!("unknown field {path:?}")),
            }
        }
        Ok(())
    }

    /// What this document's plan will save its name and its variant as, where it renames
    /// them. The header's box holds what a save writes rather than what the bytes still
    /// say, so that typing the stored name back clears the rename.
    ///
    /// ⚠️ Nothing over a plan standing against another baseline: a save makes what it
    /// held gone, and [`State::begin`] is what starts the plan again.
    pub fn renaming(&self, entity: &LocalEntity) -> (Option<String>, Option<String>) {
        let plan = self
            .plans
            .get(&entity.id)
            .filter(|plan| plan.against == mark(entity));
        (
            plan.and_then(|plan| plan.name.clone()),
            plan.and_then(|plan| plan.variant.clone()),
        )
    }

    /// The plan this frame left behind, where it is not the one in hand.
    pub fn drafted(&self) -> Option<Plan> {
        let held = self
            .open
            .as_ref()
            .and_then(|open| self.plans.get(&open.id))?;
        (*held != self.draft).then(|| self.draft.clone())
    }

    /// Keep a plan the library accepted.
    pub fn commit(&mut self, plan: Plan) {
        if let Some(open) = &self.open {
            self.plans.insert(open.id, plan);
        }
    }

    /// Put back the plan in hand, because the library refused the drafted one.
    pub fn discard(&mut self) {
        if let Some(plan) = self.open.as_ref().and_then(|open| self.plans.get(&open.id)) {
            self.draft = plan.clone();
        }
    }

    /// Forget this document's plan, and anything waiting on it. Revert puts the saved
    /// bytes back and a removal takes them away, and a plan over bytes nothing holds is
    /// not an edit of anything.
    ///
    /// ⚠️ Only the document being drawn loses its draft and its facts: forgetting
    /// another document's plan must not close the open one.
    pub fn forget(&mut self, id: u64) {
        self.plans.remove(&id);
        self.laid.remove(&id);
        self.held.retain(|(held, _)| *held != id);
        if self.job.as_ref().is_some_and(|job| job.id == id) {
            self.job = None;
        }
        if self.open.as_ref().is_some_and(|open| open.id == id) {
            self.draft = Plan::default();
            self.summary = None;
            self.open = None;
        }
    }

    /// Nothing is open any more: the selection, the open rows, the key table and the
    /// audition go. The plans stay, and so does an apply in flight.
    pub fn leave(&mut self) {
        self.view = View::default();
        self.summary = None;
        self.open = None;
    }

    /// Whether a plan is being laid out, which is the one thing here that outlives a
    /// frame.
    pub fn applying(&self) -> bool {
        self.job.is_some()
    }

    /// Hold an act that must not run until the plan in hand has reached the bytes, and
    /// start or join the apply that puts it there. Answers with the act where it is free
    /// to run now.
    pub fn hold(&mut self, ctx: &egui::Context, act: Act, workspace: &Workspace) -> Option<Act> {
        let Some(id) = waits_on(&act).filter(|id| self.pending(*id)) else {
            return Some(act);
        };
        self.held.push((id, act));
        self.start(ctx, id, workspace);
        None
    }

    /// Lay one document's plan out, unless something else is already being laid.
    pub fn start(&mut self, ctx: &egui::Context, id: u64, workspace: &Workspace) {
        if self.job.is_some() || !self.pending(id) {
            return;
        }
        let Some(plan) = self.plans.get(&id).cloned() else {
            return;
        };
        let Some(entity) = workspace.get(id) else {
            return;
        };
        let saved = entity.saved.bytes.clone();
        let laying = plan.clone();
        let job = work::run(ctx, move |progress| {
            let library = planned(&saved, &laying)?;
            progress.say(format!("laying out {} strokes", library.strokes().len()));
            materialise(&library)
        });
        self.job = Some(Laying { id, plan, job });
    }

    /// The apply that has answered, where one has.
    ///
    /// ⚠️ An answer over a plan that has since moved, or over a document the workspace
    /// no longer holds, is dropped rather than written: the bytes it made are of a
    /// library nobody asked for any more. Whatever was waiting on that document waits on
    /// the apply of the plan in hand instead — unless the plan has caught up with the
    /// bytes on its own, or the document is gone, when there is nothing left to wait for.
    pub fn answered(&mut self, ctx: &egui::Context, workspace: &Workspace) -> Option<Applied> {
        let answer = self.job.as_ref()?.job.poll();
        self.finished(answer, ctx, workspace)
    }

    /// [`Self::answered`], waiting for the apply in flight instead of polling it.
    #[cfg(test)]
    pub fn awaited(&mut self, ctx: &egui::Context, workspace: &Workspace) -> Option<Applied> {
        let answer = self.job.as_ref()?.job.wait();
        self.finished(answer, ctx, workspace)
    }

    fn finished(
        &mut self,
        answer: work::Answer<Result<Vec<u8>, String>>,
        ctx: &egui::Context,
        workspace: &Workspace,
    ) -> Option<Applied> {
        let made = match answer {
            work::Answer::Running => return None,
            work::Answer::Answered(made) => made,
            work::Answer::Died => {
                Err("laying out the library stopped without an answer".to_string())
            }
        };
        let laying = self.job.take()?;
        let fresh =
            workspace.get(laying.id).is_some() && self.plans.get(&laying.id) == Some(&laying.plan);
        match (fresh, made.is_ok()) {
            (true, true) => {
                self.laid.insert(laying.id, laying.plan);
            }
            // A refusal is the end of the wait: nothing can carry bytes the format
            // would not make, and asking again would only produce it a second time.
            (true, false) => self.held.retain(|(id, _)| *id != laying.id),
            (false, _) => {}
        }
        let applied = Applied {
            id: laying.id,
            made: fresh.then_some(made),
            acts: self.freed(workspace),
        };
        self.next(ctx, workspace);
        Some(applied)
    }

    /// The held acts with nothing left to wait for: their document's bytes hold its
    /// plan, or there is no such document any more.
    fn freed(&mut self, workspace: &Workspace) -> Vec<Act> {
        let (free, waiting): (Vec<Held>, Vec<Held>) = std::mem::take(&mut self.held)
            .into_iter()
            .partition(|(id, _)| !self.pending(*id) || workspace.get(*id).is_none());
        self.held = waiting;
        free.into_iter().map(|(_, act)| act).collect()
    }

    /// Start the next apply something is waiting on.
    fn next(&mut self, ctx: &egui::Context, workspace: &Workspace) {
        let Some((id, _)) = self.held.first() else {
            return;
        };
        self.start(ctx, *id, workspace);
    }

    /// Decode one root's loudest kept attack stroke, once, and answer with the codec's
    /// own words where it will not.
    pub fn decode(&mut self, entity: &LocalEntity, root: u8) -> Result<(), String> {
        let held = self.plans.get(&entity.id);
        self.audio
            .decode(&entity.bytes, held.unwrap_or(&Plan::default()), root)
    }

    /// What the newest decode of this root holds.
    pub fn sound(&self, root: u8) -> Option<Sound<'_>> {
        let facts = self.facts()?;
        let ((root, bank, layer), played) = self.audio.newest(root)?;
        Some(Sound {
            samples: &played.samples,
            channels: played.channels,
            rate: npno::codec::RATE,
            name: crate::workspace::stroke_wav_name(&facts.name, root, bank, layer),
        })
    }
}

/// A typed half of the name field as the plan holds it: nothing where it is what the
/// baseline already states, and a plan that renames nothing is no edit.
fn renamed(typed: &str, stored: Option<&str>) -> Option<String> {
    (stored != Some(typed)).then(|| typed.to_string())
}

/// The document an act must wait for, where it is one that would carry a document's
/// bytes out of this app.
fn waits_on(act: &Act) -> Option<u64> {
    match act {
        Act::SaveDoc(id) | Act::WriteBack(id) | Act::Export(id) | Act::Send { id, .. } => Some(*id),
        _ => None,
    }
}

/// What the header shows over a piano library: what it keeps of what it holds, the word
/// for a library that has been trimmed, and its refusal to be queued when it will not
/// fit.
fn extras(facts: &Facts, kept: u64, free: Option<u64>, standing: Standing) -> Extras {
    let over = free
        .and_then(|free| kept.checked_sub(free))
        .filter(|over| *over > 0);
    let trimmed = kept < facts.total;
    let claim = claim(trimmed, standing);
    Extras {
        size: trimmed.then(|| SizeLine {
            text: room::measure_out_of(kept, facts.total),
            warn: over.is_some(),
            hint: match free {
                Some(free) => format!("{} free on the instrument", room::measure(free)),
                None => "the instrument has not reported its free piano memory".to_string(),
            },
        }),
        // ⚠️ Both slots, because a pending plan is not unsaved bytes: the strip reads
        // `edited` where the asset holds something other than what it was saved as, and
        // `state` where it does not — and a plan is an edit either way.
        edited: claim.clone(),
        state: claim,
        loud: match standing {
            Standing::Applying => Some(Loud {
                label: "Applying…".to_string(),
                short: "Applying".to_string(),
                glyph: Glyph::Clock,
                tone: Tone::Blocked,
                hint: "wait for the apply".to_string(),
                send: None,
            }),
            Standing::Laid | Standing::Pending => over.map(|over| Loud {
                label: format!("No room · {} over", room::measure(over)),
                short: format!("{} over", room::measure(over)),
                glyph: Glyph::CircleAlert,
                tone: Tone::Blocked,
                hint: format!("trim {} before this can be queued", room::measure(over)),
                send: None,
            }),
        },
    }
}

/// The one claim the header makes about a plan: what it does to the library, or that it
/// is being laid out now.
fn claim(trimmed: bool, standing: Standing) -> Option<StateLine> {
    let words = match trimmed {
        true => "trimmed",
        false => "edited",
    };
    match standing {
        Standing::Applying => Some(StateLine {
            words: "applying…".to_string(),
            ink: Ink::Quiet,
            hint: "laying the plan out over the library".to_string(),
        }),
        Standing::Pending => Some(StateLine {
            words: words.to_string(),
            ink: Ink::Warn,
            hint: "applied when this is saved, sent or exported".to_string(),
        }),
        Standing::Laid => trimmed.then(|| StateLine {
            words: words.to_string(),
            ink: Ink::Warn,
            hint: "the plan drops strokes the saved file holds".to_string(),
        }),
    }
}

/// The corner every rectangle here is drawn with, and the page's own margin.
const RADIUS: f32 = 2.0;
const PAD: f32 = 12.0;
const GAP: f32 = 10.0;

/// A switch row and a root's row are one height; a lane of segments and a head row are
/// shorter.
const ROW: f32 = 26.0;
const LANE: f32 = 20.0;
const HEAD: f32 = 20.0;

/// The words: a row's name, the note beside it, the mono figures, a caps label.
const NAME: f32 = 11.5;
const NOTE: f32 = 10.5;
const MONO: f32 = 10.5;
const MICRO: f32 = 9.5;

/// A lamp's own box, which is what a cell has to leave room for.
const LAMP: egui::Vec2 = egui::vec2(30.0, 20.0);

/// `text` laid out to at most `width` with an ellipsis where it did not fit, painted
/// from `left` and centred on `middle`. Answers with how wide it came out.
fn cell(
    painter: &egui::Painter,
    left: f32,
    middle: f32,
    width: f32,
    text: &str,
    font: egui::FontId,
    ink: egui::Color32,
) -> f32 {
    let mut job = egui::text::LayoutJob::default();
    job.append(text, 0.0, egui::TextFormat::simple(font, ink));
    job.wrap = egui::text::TextWrapping::truncate_at_width(width.max(0.0));
    let galley = painter.layout_job(job);
    let wide = galley.size().x;
    painter.galley(
        egui::pos2(left, middle - galley.size().y / 2.0),
        galley,
        ink,
    );
    wide
}

/// A figure ending at `right`, struck through where it is what a size *was*. Answers
/// with the x it reached back to.
fn figure(
    painter: &egui::Painter,
    right: f32,
    middle: f32,
    text: &str,
    font: egui::FontId,
    ink: egui::Color32,
    struck: bool,
) -> f32 {
    let mut job = egui::text::LayoutJob::default();
    job.append(
        text,
        0.0,
        egui::TextFormat {
            font_id: font,
            color: ink,
            strikethrough: match struck {
                true => egui::Stroke::new(1.0_f32, ink),
                false => egui::Stroke::NONE,
            },
            ..Default::default()
        },
    );
    let galley = painter.layout_job(job);
    let left = right - galley.size().x;
    painter.galley(
        egui::pos2(left, middle - galley.size().y / 2.0),
        galley,
        ink,
    );
    left
}

fn hairline(ui: &egui::Ui, rect: egui::Rect) {
    ui.painter().hline(
        rect.x_range(),
        rect.bottom() - 0.5,
        egui::Stroke::new(1.0_f32, ui.visuals().widgets.noninteractive.bg_stroke.color),
    );
}

/// A lamp inside `box_`, salted so two of them in one frame are two controls.
fn lamp(ui: &mut egui::Ui, box_: egui::Rect, on: bool, salt: impl std::hash::Hash) -> Option<bool> {
    let mut child = ui.new_child(
        egui::UiBuilder::new()
            .id_salt(salt)
            .max_rect(box_)
            .layout(egui::Layout::left_to_right(egui::Align::Center)),
    );
    led::ui(&mut child, on, "")
}

/// One outlined action of an open row.
fn action(ui: &mut egui::Ui, glyph: Glyph, label: &str, mark: egui::Color32) -> bool {
    let visuals = ui.visuals().clone();
    let painter = ui.painter().clone();
    let word = painter.layout_no_wrap(
        label.to_string(),
        egui::FontId::proportional(11.0),
        visuals.weak_text_color(),
    );
    let width = 8.0 * 2.0 + 12.0 + 5.0 + word.size().x;
    let (rect, response) = ui.allocate_exact_size(egui::vec2(width, LANE), egui::Sense::click());
    if response.hovered() {
        painter.rect_filled(rect, RADIUS, visuals.widgets.hovered.weak_bg_fill);
    }
    painter.rect_stroke(
        rect,
        RADIUS,
        egui::Stroke::new(1.0_f32, visuals.widgets.noninteractive.bg_stroke.color),
        egui::StrokeKind::Inside,
    );
    painted(
        ui,
        glyph,
        egui::Rect::from_center_size(
            egui::pos2(rect.left() + 8.0 + 6.0, rect.center().y),
            egui::Vec2::splat(12.0),
        ),
        mark,
    );
    painter.galley(
        egui::pos2(
            rect.left() + 8.0 + 12.0 + 5.0,
            rect.center().y - word.size().y / 2.0,
        ),
        word,
        visuals.weak_text_color(),
    );
    response.clicked()
}

/// A read-only fact of an open row: the caps label, and the value under an eye.
fn read_only(ui: &mut egui::Ui, label: &str, value: &str, hint: &str) {
    let response = ui
        .vertical(|ui| {
            ui.spacing_mut().item_spacing.y = 4.0;
            ui.label(crate::panel::caps(label).color(app::caption(ui.visuals())));
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 5.0;
                icon(ui, Glyph::Eye, 11.0, app::caption(ui.visuals()));
                ui.label(
                    egui::RichText::new(value)
                        .font(egui::FontId::monospace(NAME))
                        .color(ui.visuals().weak_text_color()),
                );
            });
        })
        .response;
    if !hint.is_empty() {
        response.on_hover_text(hint);
    }
}

/// What one root holds, or what it keeps where a plan is given.
fn root_bytes(facts: &Facts, plan: Option<&Plan>, index: usize) -> u64 {
    facts
        .cells
        .iter()
        .filter(|cell| cell.root == index && plan.is_none_or(|plan| plan.keeps(facts, cell)))
        .map(|cell| cell.bytes)
        .sum()
}

/// The keys the plan leaves answering something, given what each root keeps.
fn covered(facts: &Facts, plan: &Plan, roots: &[RootLine]) -> Vec<u8> {
    (0..npno::NOTES as u8)
        .filter(|key| {
            plan.range.as_ref().is_none_or(|range| range.contains(key))
                && plan
                    .answers(facts, *key)
                    .is_some_and(|root| roots[root].kept > 0)
        })
        .collect()
}

/// The stretches of [`SPAN`] the covered keys leave out, low to high.
fn gaps(covered: &[u8]) -> Vec<(u8, u8)> {
    let mut out: Vec<(u8, u8)> = Vec::new();
    for key in SPAN.low..=SPAN.high {
        if covered.contains(&key) {
            continue;
        }
        match out.last_mut() {
            Some((_, top)) if *top + 1 == key => *top = key,
            _ => out.push((key, key)),
        }
    }
    out
}

/// What every section of a frame reads off the plan.
///
/// ⚠️ Worked out when the plan or the instrument's free memory moves, never per frame:
/// the walks here are over every key, every cell and — while the library does not fit —
/// every subset of the switches still on.
struct Summary {
    /// The plan and the free memory these figures are of, which is what
    /// [`State::summarise`] checks before working any of them out again.
    of: Plan,
    free: Option<u64>,
    /// Bytes the plan keeps of the file.
    kept: u64,
    /// The keys it leaves answering something, and the stretches it leaves silent.
    covered: Vec<u8>,
    silent: Vec<(u8, u8)>,
    /// The cheapest cut left, where what is kept does not fit.
    cut: Option<Cut>,
    roots: Vec<RootLine>,
    /// One cell per stretch of keys a root answers, and the root each belongs to.
    cells: Vec<SizeCell>,
    of_root: Vec<usize>,
}

/// What one root's cell on the map and its row in the list read.
struct RootLine {
    note: u8,
    /// The stretches of keys the plan routes to it.
    runs: Vec<(u8, u8)>,
    /// What it keeps, against what the file holds for it.
    kept: u64,
    held: u64,
    in_range: bool,
    /// Those stretches as its row prints them.
    answers: String,
}

impl Summary {
    fn of(facts: &Facts, plan: &Plan, free: Option<u64>) -> Summary {
        let roots: Vec<RootLine> = facts
            .roots
            .iter()
            .enumerate()
            .map(|(index, root)| {
                let runs = runs(&plan.keys_of(facts, index));
                RootLine {
                    note: root.note,
                    answers: answered(&runs),
                    runs,
                    kept: root_bytes(facts, Some(plan), index),
                    held: root_bytes(facts, None, index),
                    in_range: plan.in_range(facts, index),
                }
            })
            .collect();
        let mut cells: Vec<SizeCell> = Vec::new();
        let mut of_root: Vec<usize> = Vec::new();
        for (index, line) in roots.iter().enumerate() {
            for (low, top) in &line.runs {
                of_root.push(index);
                cells.push(SizeCell {
                    low: *low,
                    top: *top,
                    name: note::name(line.note),
                    kept: mb(line.kept),
                    original: mb(line.held),
                    in_range: line.in_range,
                    hint: format!(
                        "root {} answers {}{} · {} of {}",
                        note::name(line.note),
                        note::name(*low),
                        note::name(*top),
                        room::measure(line.kept),
                        room::measure(line.held),
                    ),
                });
            }
        }
        let covered = covered(facts, plan, &roots);
        let kept = kept_bytes(facts, plan);
        Summary {
            of: plan.clone(),
            free,
            kept,
            silent: gaps(&covered),
            covered,
            cut: free
                .and_then(|free| kept.checked_sub(free))
                .filter(|over| *over > 0)
                .and_then(|over| cheapest_cut(facts, plan, over)),
            roots,
            cells,
            of_root,
        }
    }
}

/// The stretches of keys a root answers, as its row prints them.
fn answered(runs: &[(u8, u8)]) -> String {
    match runs {
        [(low, top)] => format!("{}{}", note::name(*low), note::name(*top)),
        runs => runs
            .iter()
            .map(|(low, top)| format!("{}{}", note::name(*low), note::name(*top)))
            .collect::<Vec<_>>()
            .join(", "),
    }
}

/// A column `width` wide, laid out top down, claiming only the height its contents
/// take.
///
/// ⚠️ Not `allocate_ui` with a zero height: inside a horizontal layout that hands the
/// child one row's worth of height, every row after the first overflows it — and egui
/// answers an overflowing horizontal by growing the page sideways.
fn column(ui: &mut egui::Ui, width: f32, body: impl FnOnce(&mut egui::Ui)) {
    let height = ui.available_height();
    ui.allocate_ui_with_layout(
        egui::vec2(width, height),
        egui::Layout::top_down(egui::Align::Min),
        body,
    );
}

/// Megabytes as the lanes print them.
fn mb(bytes: u64) -> f32 {
    bytes as f32 / (1024.0 * 1024.0)
}

/// What the keyboard last played, as the line under it reads: whether it sounded, and
/// the sentence.
fn status(facts: &Facts, plan: &Plan, key: u8) -> (bool, String) {
    let silent = |why: &str| (false, format!("{}{why}", note::name(key)));
    let answers = plan
        .answers(facts, key)
        .filter(|index| plan.in_range(facts, *index))
        .filter(|_| plan.range.as_ref().is_none_or(|range| range.contains(&key)));
    let Some(index) = answers else {
        return silent("no root answers this key; silence.");
    };
    let root = &facts.roots[index];
    let mut attack: Vec<u8> = facts
        .cells
        .iter()
        .filter(|cell| cell.root == index && cell.bank == Some(Bank::Attack))
        .map(|cell| cell.layer)
        .collect();
    attack.sort_unstable();
    let kept: Vec<u8> = attack
        .iter()
        .copied()
        .filter(|layer| plan.keeps_layer(root.note, *layer))
        .collect();
    let said = format!(
        "{} at vel {} → root {} · {}",
        note::name(key),
        keys::AUDITION_VELOCITY,
        note::name(root.note),
        keys::shifted(key, root.note),
    );
    match (attack.first(), kept.first()) {
        (_, None) => silent("every layer of this root is dropped; silence."),
        (Some(loudest), Some(playing)) if playing != loudest => (
            true,
            format!("{said} — the loudest layer is dropped, so the next kept layer plays"),
        ),
        _ => (true, said),
    }
}

/// The damper limit over the keyboard: a marker at the boundary above the highest
/// damped key, and the keys past it drawn quieter — they ring on at note-off. Nothing
/// where every key is damped.
fn damper_mark(ui: &egui::Ui, rect: egui::Rect, top: u8) {
    if top >= ALL_KEYS_DAMPED || top >= SPAN.high {
        return;
    }
    let at = SPAN.x_after(rect, top);
    let visuals = ui.visuals().clone();
    let painter = ui.painter();
    painter.rect_filled(
        egui::Rect::from_min_max(
            egui::pos2(at, rect.top() + 1.0),
            rect.max - egui::vec2(0.0, 1.0),
        ),
        0.0,
        visuals.window_fill.gamma_multiply(0.45),
    );
    painter.vline(
        at,
        rect.y_range(),
        egui::Stroke::new(1.0_f32, app::caption(&visuals)),
    );
    painter.text(
        egui::pos2(at + 3.0, rect.top() + 1.0),
        egui::Align2::LEFT_TOP,
        "damper stops here",
        egui::FontId::proportional(MICRO),
        app::caption(&visuals),
    );
}

/// Take a dragged lane of root boundaries into the plan's key map: each key the drag
/// moved plays the root whose cell now covers it, or nothing where no cell does.
fn reroute(facts: &Facts, plan: &mut Plan, of_root: &[usize], was: &[(u8, u8)], now: &[(u8, u8)]) {
    let holder = |bounds: &[(u8, u8)], key: u8| {
        bounds
            .iter()
            .position(|(low, top)| (*low..=*top).contains(&key))
    };
    for key in 0..npno::NOTES as u8 {
        let after = holder(now, key);
        if holder(was, key) == after {
            continue;
        }
        plan.route(facts, key, after.map(|cell| of_root[cell]));
    }
}

/// How many silent stretches the map leaves, as the heading reads it.
fn coverage(gaps: &[(u8, u8)]) -> String {
    match gaps.len() {
        0 => "every key answered".to_string(),
        1 => "1 silent range".to_string(),
        n => format!("{n} silent ranges"),
    }
}

impl State {
    /// The key map, pinned above the body: one cell per root over a clickable keyboard,
    /// and a line saying what the last key played.
    pub fn map(&mut self, ui: &mut egui::Ui) -> Option<Ask> {
        self.summarise();
        let State {
            open,
            draft,
            view,
            summary,
            ..
        } = self;
        let facts = match &open.as_ref()?.facts {
            Ok(facts) => facts,
            Err(why) => {
                ui.label(egui::RichText::new(why).color(app::bad(ui.visuals())));
                return None;
            }
        };
        let summary = summary.as_ref()?;

        let ink = match summary.silent.is_empty() {
            true => app::good(ui.visuals()),
            false => app::warn(ui.visuals()),
        };
        let reading = format!(
            "{}  {}{}",
            coverage(&summary.silent),
            note::name(SPAN.low),
            note::name(SPAN.high)
        );
        controls::heading(
            ui,
            "Key map",
            "click a key to hear which root answers it",
            Some((&reading, ink)),
        );

        let lit = view.audition.as_ref().map(|struck| struck.note);
        let answering = lit.and_then(|note| draft.answers(facts, note));
        let of_root = &summary.of_root;
        let marks: Vec<keys::Mark> = facts
            .roots
            .iter()
            .map(|root| keys::Mark {
                note: root.note,
                label: None,
            })
            .collect();

        let mut inner = ui.new_child(
            egui::UiBuilder::new()
                .max_rect(
                    ui.available_rect_before_wrap()
                        .shrink2(egui::vec2(PAD, 0.0)),
                )
                .layout(egui::Layout::top_down(egui::Align::Min)),
        );
        let picked = view
            .picked
            .and_then(|root| of_root.iter().position(|held| *held == root));
        let cell_lit = answering.and_then(|root| of_root.iter().position(|held| *held == root));
        let acted = keys::size_cells(
            &mut inner,
            SPAN,
            &summary.cells,
            picked,
            cell_lit,
            keys::Edges::Both,
        );
        let keyboard = egui::Rect::from_min_size(
            inner.next_widget_position(),
            egui::vec2(inner.available_width().max(1.0), keys::KEYBOARD_H),
        );
        let struck = keys::keyboard(&mut inner, SPAN, lit, &marks);
        damper_mark(
            &inner,
            keyboard,
            draft.damper_top.unwrap_or(facts.damper_top),
        );
        let room = inner.available_rect_before_wrap().width();
        let (line, _) = inner.allocate_exact_size(egui::vec2(room, LANE), egui::Sense::hover());
        if let Some(note) = lit {
            let (good, said) = status(facts, draft, note);
            let (glyph, ink) = match good {
                true => (Glyph::AudioLines, app::good(inner.visuals())),
                false => (Glyph::CircleAlert, app::warn(inner.visuals())),
            };
            painted(
                &inner,
                glyph,
                egui::Rect::from_center_size(
                    egui::pos2(line.left() + 6.0, line.center().y),
                    egui::Vec2::splat(12.0),
                ),
                ink,
            );
            cell(
                inner.painter(),
                line.left() + 19.0,
                line.center().y,
                line.width() - 19.0,
                &said,
                egui::FontId::proportional(11.0),
                inner.visuals().weak_text_color(),
            );
        }
        let drawn = inner.min_rect();
        ui.advance_cursor_after_rect(drawn);
        hairline(ui, drawn.expand2(egui::vec2(0.0, 4.0)));

        match acted {
            Some(keys::BandAct::Pick(index)) => {
                let root = of_root[index];
                view.picked = Some(root);
                view.open_rows.insert(root);
                view.reveal = Some(root);
            }
            Some(keys::BandAct::Drag { bounds, .. }) => {
                let was: Vec<(u8, u8)> = summary
                    .cells
                    .iter()
                    .map(|cell| (cell.low, cell.top))
                    .collect();
                reroute(facts, draft, of_root, &was, &bounds);
            }
            None => {}
        }
        let note = struck?;
        view.audition = Some(Audition::new(note, ui.input(|input| input.time)));
        // Only a key that sounds is asked for. A root with nothing left to play would
        // answer with the codec's refusal, and the line under the keyboard is where
        // silence is explained.
        let (sounds, _) = status(facts, draft, note);
        let root = draft.answers(facts, note).filter(|_| sounds)?;
        let root = facts.roots[root].note;
        Some(Ask::Strike {
            root,
            semitones: i16::from(note) - i16::from(root),
        })
    }

    /// Let go of an audition whose hold is up, and answer with how long a live one has
    /// left — the caller asks for the frame that will clear it.
    pub fn settle(&mut self, now: f64) -> Option<f64> {
        let struck = self.view.audition.as_ref()?;
        let left = Audition::HOLD - (now - struck.started);
        if left <= 0.0 {
            self.view.audition = None;
            return None;
        }
        Some(left)
    }
}

/// What throwing one switch row of the trim section does. The range is a switch of its
/// own: no cut the constraint sentence names offers it.
#[derive(Clone, Copy)]
enum Throw {
    Layer(u8),
    Bank(Bank),
    Range,
}

/// One switch of the trim section as its row draws it.
struct Switch {
    on: bool,
    name: String,
    note: String,
    /// Whether the note is a warning rather than a fact.
    loud: bool,
    size: String,
    /// What the size was, where the plan has changed it.
    was: Option<String>,
    hint: String,
    throws: Throw,
}

/// The switch rows of the trim section: what the plan keeps, against what it holds.
fn switches(ui: &mut egui::Ui, facts: &Facts, plan: &mut Plan, summary: &Summary) {
    let layers = facts.layers.len();
    let whole = spans(&facts.layers);
    let mut rows: Vec<Switch> = Vec::new();
    for (rank, layer) in facts.shown_layers() {
        let on_roots = facts
            .roots
            .iter()
            .enumerate()
            .filter(|(index, root)| {
                facts
                    .cells
                    .iter()
                    .any(|cell| cell.root == *index && cell.layer == layer)
                    && plan.in_range(facts, *index)
                    && plan.keeps_layer(root.note, layer)
            })
            .count();
        let holds = facts
            .roots
            .iter()
            .enumerate()
            .filter(|(index, _)| {
                facts
                    .cells
                    .iter()
                    .any(|cell| cell.root == *index && cell.layer == layer)
            })
            .count();
        let kept = layer_bytes(facts, Some(plan), layer);
        let held = layer_bytes(facts, None, layer);
        let partial = on_roots > 0 && on_roots < holds;
        rows.push(Switch {
            on: on_roots > 0,
            name: format!("{} layer", layer_name(rank, layers)),
            note: match (partial, rank) {
                (true, _) => format!("on {on_roots} of {holds} roots"),
                (false, 0) => "the loudest strokes".to_string(),
                (false, rank) if rank + 1 == layers => {
                    "the quietest layer — first thing a trim loses".to_string()
                }
                (false, _) => String::new(),
            },
            loud: partial,
            size: room::measure(kept),
            was: (kept != held).then(|| room::measure(held)),
            hint: format!(
                "layer index {layer} in the file — 0 is the loudest; a root holding \
                 every layer sounds it at {}",
                span_text(&whole[rank].1)
            ),
            throws: Throw::Layer(layer),
        });
    }
    for bank in &facts.banks {
        if *bank == Bank::Attack {
            continue;
        }
        let kept = bank_bytes(facts, Some(plan), *bank);
        let held = bank_bytes(facts, None, *bank);
        rows.push(Switch {
            on: plan.keeps_bank(Some(*bank)),
            name: bank_name(*bank).to_string(),
            note: bank_note(*bank).to_string(),
            loud: false,
            size: room::measure(kept),
            was: (kept != held).then(|| room::measure(held)),
            hint: format!("bank {} in the file", bank.code()),
            throws: Throw::Bank(*bank),
        });
    }
    rows.push(range_switch(facts, plan, summary.covered.len()));

    let mut thrown = None;
    for (index, row) in rows.iter().enumerate() {
        if let Some(keep) = switch_row(ui, index, row) {
            thrown = Some((row.throws, keep));
        }
    }
    match thrown {
        Some((Throw::Layer(layer), keep)) => plan.switch_layer(layer, keep),
        Some((Throw::Bank(bank), keep)) => plan.switch_bank(bank, keep),
        Some((Throw::Range, keep)) => plan.range = (!keep).then(|| default_range(facts)),
        None => {}
    }
}

/// The Keys row: the whole range, or the middle of it. `kept` is how many keys the plan
/// leaves answering something.
fn range_switch(facts: &Facts, plan: &Plan, kept: usize) -> Switch {
    let (low, high) = (
        facts.covered.first().copied().unwrap_or(SPAN.low),
        facts.covered.last().copied().unwrap_or(SPAN.high),
    );
    let held = facts.covered.len();
    Switch {
        on: plan.range.is_none(),
        name: format!("Keys {}{}", note::name(low), note::name(high)),
        note: match &plan.range {
            None => "the library's whole range".to_string(),
            Some(range) => {
                let dropped = (0..facts.roots.len())
                    .filter(|index| !plan.in_range(facts, *index))
                    .count();
                format!(
                    "trimmed to {}{} · {dropped} roots dropped",
                    note::name(*range.start()),
                    note::name(*range.end())
                )
            }
        },
        loud: plan.range.is_some(),
        size: format!("{kept} keys"),
        was: (kept != held).then(|| format!("{held} keys")),
        hint: "switch it off to keep the middle of the keyboard".to_string(),
        throws: Throw::Range,
    }
}

/// What one layer holds, or what it keeps where a plan is given.
fn layer_bytes(facts: &Facts, plan: Option<&Plan>, layer: u8) -> u64 {
    facts
        .cells
        .iter()
        .filter(|cell| cell.layer == layer && plan.is_none_or(|plan| plan.keeps(facts, cell)))
        .map(|cell| cell.bytes)
        .sum()
}

/// What one bank holds, or what it keeps where a plan is given.
fn bank_bytes(facts: &Facts, plan: Option<&Plan>, bank: Bank) -> u64 {
    facts
        .cells
        .iter()
        .filter(|cell| cell.bank == Some(bank) && plan.is_none_or(|plan| plan.keeps(facts, cell)))
        .map(|cell| cell.bytes)
        .sum()
}

/// A lamp, a name, a note and a size, with a hairline under them.
fn switch_row(ui: &mut egui::Ui, index: usize, row: &Switch) -> Option<bool> {
    const SIZE_W: f32 = 92.0;
    let (rect, _) =
        ui.allocate_exact_size(egui::vec2(ui.available_width(), ROW), egui::Sense::hover());
    hairline(ui, rect);
    // ⚠️ Before the lamp: egui gives a click to the last widget registered over it, and
    // a row-wide target added afterwards would swallow every throw of the switch.
    ui.interact(
        rect,
        ui.id().with(("trim_row", index)),
        egui::Sense::hover(),
    )
    .on_hover_text(&row.hint);
    let visuals = ui.visuals().clone();
    let ink = match row.on {
        true => visuals.weak_text_color(),
        false => app::caption(&visuals),
    };
    let rest = (rect.width() - LAMP.x - SIZE_W - GAP * 3.0).max(0.0);
    let name_w = rest / 2.2;
    let middle = rect.center().y;

    let thrown = lamp(
        ui,
        egui::Rect::from_min_size(egui::pos2(rect.left(), middle - LAMP.y / 2.0), LAMP),
        row.on,
        ("trim", index),
    );
    let painter = ui.painter().clone();
    let left = rect.left() + LAMP.x + GAP;
    cell(
        &painter,
        left,
        middle,
        name_w,
        &row.name,
        egui::FontId::proportional(NAME),
        ink,
    );
    let note_ink = match row.loud {
        true => app::warn(&visuals),
        false => app::caption(&visuals),
    };
    cell(
        &painter,
        left + name_w + GAP,
        middle,
        rest - name_w,
        &row.note,
        egui::FontId::proportional(NOTE),
        note_ink,
    );
    let mono = egui::FontId::monospace(MONO);
    let back = figure(
        &painter,
        rect.right(),
        middle,
        &row.size,
        mono.clone(),
        ink,
        false,
    );
    if let Some(was) = &row.was {
        figure(
            &painter,
            back - 5.0,
            middle,
            was,
            mono,
            app::caption(&visuals),
            true,
        );
    }
    thrown
}

/// The meter: what the file holds, what the plan keeps, what the instrument has free,
/// and the sentence that names the cheapest cut left.
fn meter(ui: &mut egui::Ui, facts: &Facts, plan: &Plan, summary: &Summary) {
    const TROUGH: f32 = 8.0;
    const LABEL: f32 = 14.0;

    let free = summary.free;
    let kept = summary.kept;
    let visuals = ui.visuals().clone();
    let width = ui.available_width();
    ui.horizontal(|ui| {
        ui.label(
            egui::RichText::new(format!("{} in the file", room::measure(facts.total)))
                .size(11.0)
                .color(visuals.weak_text_color()),
        );
        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
            ui.label(
                egui::RichText::new(format!("{} kept", room::measure(kept)))
                    .font(egui::FontId::monospace(NAME))
                    .color(visuals.text_color()),
            );
        });
    });
    ui.add_space(7.0);

    let (rect, _) = ui.allocate_exact_size(egui::vec2(width, TROUGH + LABEL), egui::Sense::hover());
    let trough = egui::Rect::from_min_size(rect.min, egui::vec2(width, TROUGH));
    let painter = ui.painter().clone();
    painter.rect_filled(trough, RADIUS, visuals.extreme_bg_color);
    let share = |bytes: u64| match facts.total {
        0 => 0.0,
        total => (bytes as f32 / total as f32).clamp(0.0, 1.0) * width,
    };
    let fits = free.is_none_or(|free| kept <= free);
    let filled = share(kept);
    if filled > 0.0 {
        painter.rect_filled(
            egui::Rect::from_min_size(trough.min, egui::vec2(filled, TROUGH)),
            RADIUS,
            match fits {
                true => app::good(&visuals),
                false => app::bad(&visuals),
            },
        );
    }
    let ghost =
        egui::Rect::from_min_max(egui::pos2(trough.left() + filled, trough.top()), trough.max);
    if ghost.width() > 0.0 {
        keys::hatch(&painter, ghost, app::unlit(&visuals), 1.0);
        ui.interact(ghost, ui.id().with("piano_dropped"), egui::Sense::hover())
            .on_hover_text(format!(
                "{} dropped",
                room::measure(facts.total.saturating_sub(kept))
            ));
    }
    if let Some(free) = free {
        let at = trough.left() + share(free);
        painter.rect_filled(
            egui::Rect::from_min_max(
                egui::pos2(at, trough.top() - 3.0),
                egui::pos2(at + 2.0, trough.bottom() + 3.0),
            ),
            0.0,
            visuals.text_color(),
        );
        painter.text(
            egui::pos2(at, trough.bottom() + 4.0),
            egui::Align2::CENTER_TOP,
            format!("{} free", room::measure(free)),
            egui::FontId::monospace(MICRO),
            visuals.weak_text_color(),
        );
    }

    ui.add_space(10.0);
    let (said, loud) = constraint(plan, summary);
    ui.label(egui::RichText::new(said).size(11.0).color(match loud {
        true => app::warn(&visuals),
        false => app::caption(&visuals),
    }));
}

/// The sentence under the meter: whether it fits, and what to throw if it does not.
fn constraint(plan: &Plan, summary: &Summary) -> (String, bool) {
    let kept = summary.kept;
    let Some(free) = summary.free else {
        return (
            "The instrument has not reported its free piano memory, so nothing here can \
             say whether this fits."
                .to_string(),
            false,
        );
    };
    let Some(over) = kept.checked_sub(free).filter(|over| *over > 0) else {
        return (
            format!(
                "At {} it fits with {} to spare.",
                room::measure(kept),
                room::measure(free - kept)
            ),
            false,
        );
    };
    let head = format!(
        "At {} it is {} over.",
        room::measure(kept),
        room::measure(over)
    );
    let rest = match &summary.cut {
        Some(cut) => format!(
            "Dropping {} sheds {} — the cheapest cut left that fits.",
            listed(&cut.picked),
            room::measure(cut.shed)
        ),
        None if plan.range.is_some() => {
            "Everything droppable is off and it still does not fit; this library cannot go \
             on this instrument."
                .to_string()
        }
        None => "Everything droppable is off — narrowing the key range is the only cut left."
            .to_string(),
    };
    (format!("{head} {rest}"), true)
}

/// A control of the playback section: the caps label, and the control under it.
fn field(ui: &mut egui::Ui, label: &str, hint: &str, body: impl FnOnce(&mut egui::Ui)) {
    let response = ui
        .vertical(|ui| {
            ui.spacing_mut().item_spacing.y = 4.0;
            ui.label(crate::panel::caps(label).color(app::caption(ui.visuals())));
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 6.0;
                body(ui);
            });
        })
        .response;
    response.on_hover_text(hint);
}

/// What the instrument applies over every stroke: a gain over the whole library, the
/// key above which notes ring on, and the kind of instrument the library is filed under.
fn playback(ui: &mut egui::Ui, facts: &Facts, plan: &mut Plan) {
    ui.spacing_mut().item_spacing = egui::vec2(24.0, 10.0);
    ui.horizontal_wrapped(|ui| {
        field(ui, "Instrument gain", "0x40c, tenths of a decibel", |ui| {
            let mut decibels = f64::from(plan.gain.unwrap_or(facts.gain)) / 10.0;
            let moved = ui.add(
                egui::Slider::new(&mut decibels, -12.7..=12.7)
                    .step_by(0.1)
                    .custom_formatter(|value, _| format!("{value:+.1} dB")),
            );
            if moved.changed() {
                let tenths = (decibels * 10.0).round() as i8;
                plan.gain = (tenths != facts.gain).then_some(tenths);
            }
        });
        let held = plan.damper_top.unwrap_or(facts.damper_top);
        let from_kind = plan
            .kind
            .is_some_and(|kind| plan.damper_top == Some(kind.damper_top()));
        let hint = match from_kind {
            true => "0x40d, set by the kind just picked: the highest key the damper reaches",
            false => "0x40d: the highest key the damper reaches; `none` damps every key",
        };
        field(ui, "Keys ring on above", hint, |ui| {
            if let Some(key) = damper_picker(ui, held) {
                plan.damper_top = (key != facts.damper_top).then_some(key);
            }
        });
        field(
            ui,
            "Kind",
            "0x18; the instrument files the library under it — it changes nothing the \
             library sounds like, and picking one only defaults the damper limit",
            |ui| {
                let held = plan.kind.map_or(facts.kind, |kind| kind.code());
                let mut picked = Kind::from_code(held);
                egui::ComboBox::from_id_salt("piano_kind")
                    .selected_text(kind_name(held))
                    .show_ui(ui, |ui| {
                        for kind in Kind::ALL {
                            ui.selectable_value(&mut picked, Some(kind), kind_name(kind.code()));
                        }
                    });
                let Some(kind) = picked.filter(|kind| kind.code() != held) else {
                    return;
                };
                if plan.damper_top.is_none() {
                    let top = kind.damper_top();
                    plan.damper_top = (top != facts.damper_top).then_some(top);
                }
                plan.kind = (kind.code() != facts.kind).then_some(kind);
            },
        );
    });
}

/// The damper limit as one control: a key, or `none` for a limit past the last key,
/// which damps every one of them.
fn damper_picker(ui: &mut egui::Ui, top: u8) -> Option<u8> {
    let mut value = f64::from(top.min(ALL_KEYS_DAMPED));
    let response = ui.push_id("piano_damper", |ui| {
        ui.add(
            egui::DragValue::new(&mut value)
                .range(0.0..=f64::from(ALL_KEYS_DAMPED))
                .speed(0.2)
                .custom_formatter(|n, _| match n as u8 > SPAN.high {
                    true => "none".to_string(),
                    false => note::name(n as u8),
                })
                .custom_parser(|text| match text.trim() {
                    "none" | "every" | "-" => Some(f64::from(ALL_KEYS_DAMPED)),
                    text => note::parse(text).ok().map(f64::from),
                }),
        )
    });
    let picked = value.round() as u8;
    (response.inner.changed() && picked != top).then_some(picked)
}

/// One lane per layer: the switch that speaks for every root, and one segment per root
/// so a per-root exception shows where it is.
fn lanes(ui: &mut egui::Ui, facts: &Facts, plan: &mut Plan, picked: Option<usize>) {
    const LEFT: f32 = 88.0;
    const RIGHT: f32 = 150.0;
    const SEG_H: f32 = 16.0;
    /// How wide a segment must be before its velocities are worth printing in it.
    const SPAN_W: f32 = 48.0;

    let layers = facts.layers.len();
    // A root missing a layer the file holds answers over the gap it leaves, so the
    // spans are the ones that root's own values give.
    let held: Vec<Vec<(u8, RangeInclusive<u8>)>> = (0..facts.roots.len())
        .map(|index| spans(&root_layers(facts, index)))
        .collect();
    let mut thrown: Option<(u8, bool)> = None;
    let mut excepted: Option<(u8, u8, bool)> = None;
    for (rank, layer) in facts.shown_layers() {
        let (rect, _) =
            ui.allocate_exact_size(egui::vec2(ui.available_width(), LANE), egui::Sense::hover());
        let visuals = ui.visuals().clone();
        let on: Vec<bool> = facts
            .roots
            .iter()
            .enumerate()
            .map(|(index, root)| plan.in_range(facts, index) && plan.keeps_layer(root.note, layer))
            .collect();
        let kept_roots = on.iter().filter(|kept| **kept).count();
        let all = kept_roots == facts.roots.len();
        let word = match (kept_roots, all) {
            (0, _) => "drop",
            (_, true) => "keep",
            _ => "partial",
        };
        let ink = match all || kept_roots == 0 {
            true => visuals.weak_text_color(),
            false => app::warn(&visuals),
        };
        if let Some(keep) = lamp(
            ui,
            egui::Rect::from_min_size(
                egui::pos2(rect.left(), rect.center().y - LAMP.y / 2.0),
                LAMP,
            ),
            kept_roots > 0,
            ("lane", layer),
        ) {
            thrown = Some((layer, keep));
        }
        let painter = ui.painter().clone();
        cell(
            &painter,
            rect.left() + LAMP.x + GAP,
            rect.center().y,
            LEFT - LAMP.x - GAP,
            word,
            egui::FontId::proportional(NOTE),
            ink,
        );

        let lane = egui::Rect::from_min_max(
            egui::pos2(rect.left() + LEFT, rect.center().y - SEG_H / 2.0),
            egui::pos2(rect.right() - RIGHT, rect.center().y + SEG_H / 2.0),
        );
        let step = lane.width() / facts.roots.len().max(1) as f32;
        let pointer = ui.input(|input| input.pointer.interact_pos());
        for (index, root) in facts.roots.iter().enumerate() {
            let seg = egui::Rect::from_min_size(
                egui::pos2(lane.left() + step * index as f32, lane.top()),
                egui::vec2((step - 1.0).max(1.0), SEG_H),
            );
            let kept = on[index];
            match kept {
                true => {
                    painter.rect_filled(
                        seg,
                        RADIUS,
                        match picked == Some(index) {
                            true => visuals.selection.bg_fill,
                            false => visuals.faint_bg_color,
                        },
                    );
                    painter.rect_stroke(
                        seg,
                        RADIUS,
                        egui::Stroke::new(
                            1.0_f32,
                            match picked == Some(index) {
                                true => app::accent(&visuals),
                                false => visuals.widgets.noninteractive.bg_stroke.color,
                            },
                        ),
                        egui::StrokeKind::Inside,
                    );
                }
                false => crate::panel::dashed_rect(
                    &painter,
                    seg,
                    egui::Stroke::new(1.0_f32, app::unlit(&visuals)),
                ),
            }
            let span = held[index]
                .iter()
                .find(|(value, _)| *value == layer)
                .map(|(_, span)| span_text(span))
                .unwrap_or_default();
            if seg.width() >= SPAN_W && !span.is_empty() {
                cell(
                    &painter,
                    seg.left() + 4.0,
                    seg.center().y,
                    seg.width() - 8.0,
                    &span,
                    egui::FontId::monospace(MICRO),
                    match kept {
                        true => visuals.weak_text_color(),
                        false => app::unlit(&visuals),
                    },
                );
            }
            if !pointer.is_some_and(|at| seg.contains(at)) {
                continue;
            }
            let mut said = format!(
                "{} on {}{} · {}",
                layer_name(rank, layers),
                note::name(root.note),
                match kept {
                    true => "kept · click to drop",
                    false => "dropped · click to keep",
                },
                room::measure(root_layer_bytes(facts, index, layer)),
            );
            if !span.is_empty() {
                said.push_str(&format!(" · {span}"));
            }
            if let Some(decibels) = segment_trim(facts, plan, index, layer) {
                said.push_str(&format!(" · trim {decibels} dB"));
            }
            let response = ui
                .interact(
                    seg,
                    ui.id().with(("segment", layer, root.note)),
                    egui::Sense::click(),
                )
                .on_hover_text(said);
            if response.clicked() {
                excepted = Some((root.note, layer, !kept));
            }
        }

        let kept = layer_bytes(facts, Some(plan), layer);
        let held = layer_bytes(facts, None, layer);
        figure(
            &painter,
            rect.right(),
            rect.center().y,
            &match kept == held {
                true => format!("{} · {}", layer_name(rank, layers), room::measure(held)),
                false => format!(
                    "{} · {} of {}",
                    layer_name(rank, layers),
                    room::measure(kept),
                    room::measure(held)
                ),
            },
            egui::FontId::monospace(10.0),
            match kept == held {
                true => app::caption(&visuals),
                false => app::warn(&visuals),
            },
            false,
        );
        ui.add_space(3.0);
    }
    if let Some((layer, keep)) = thrown {
        plan.switch_layer(layer, keep);
    }
    if let Some((root, layer, keep)) = excepted {
        plan.except(root, layer, keep);
    }
}

/// The layer values one root holds, ascending.
fn root_layers(facts: &Facts, root: usize) -> Vec<u8> {
    let mut values: Vec<u8> = facts
        .cells
        .iter()
        .filter(|cell| cell.root == root)
        .map(|cell| cell.layer)
        .collect();
    values.sort_unstable();
    values.dedup();
    values
}

/// Drop every layer one root still keeps: the ones it records whose switch is on. A
/// layer the root has no stroke of has nothing to drop, and one its switch has already
/// dropped needs no exception of its own.
fn drop_root(facts: &Facts, plan: &mut Plan, index: usize) {
    let note = facts.roots[index].note;
    for layer in root_layers(facts, index) {
        plan.except(note, layer, false);
    }
}

/// What a stroke is attenuated by under this plan, in decibels.
fn trim_of(facts: &Facts, plan: &Plan, strike: &Strike) -> u16 {
    let key = (facts.roots[strike.root].note, strike.bank, strike.layer);
    plan.trims.get(&key).copied().unwrap_or(strike.trim)
}

/// The trim a lane's segment reads: one segment covers a root's layer in every bank
/// that records it, and the attack stroke is the one a key sounds.
fn segment_trim(facts: &Facts, plan: &Plan, root: usize, layer: u8) -> Option<u16> {
    facts
        .strikes
        .iter()
        .filter(|strike| strike.root == root && strike.layer == layer)
        .min_by_key(|strike| strike.bank)
        .map(|strike| trim_of(facts, plan, strike))
}

/// What one root's layer holds, across every bank that records it.
fn root_layer_bytes(facts: &Facts, root: usize, layer: u8) -> u64 {
    facts
        .cells
        .iter()
        .filter(|cell| cell.root == root && cell.layer == layer)
        .map(|cell| cell.bytes)
        .sum()
}

/// The ink every cell of a row wears.
///
/// ⚠️ A selected row is one colour throughout, warn text included: a row lit by the
/// selection fill and carrying a warning in warn ink reads as two rows.
struct RowInk {
    text: egui::Color32,
    loud: egui::Color32,
    quiet: egui::Color32,
}

fn row_ink(visuals: &egui::Visuals, picked: bool, in_range: bool) -> RowInk {
    match (picked, in_range) {
        (true, _) => RowInk {
            text: visuals.selection.stroke.color,
            loud: visuals.selection.stroke.color,
            quiet: visuals.selection.stroke.color,
        },
        (false, true) => RowInk {
            text: visuals.weak_text_color(),
            loud: app::warn(visuals),
            quiet: app::caption(visuals),
        },
        (false, false) => RowInk {
            text: app::caption(visuals),
            loud: app::caption(visuals),
            quiet: app::caption(visuals),
        },
    }
}

/// How many lamps a root's row carries before the layers are better read in the lanes
/// above it.
const ROW_LAMPS: usize = 6;

/// How far the trim control reaches, in decibels. A stroke recording more than this is
/// shown as the file states it.
const TRIM_REACH: u16 = 48;

/// One row per root: what it answers, which of its layers it keeps, what it costs, and
/// the facts and actions under it when it is open.
fn roots(
    ui: &mut egui::Ui,
    facts: &Facts,
    plan: &mut Plan,
    summary: &Summary,
    view: &mut View,
    sounding: Option<u8>,
) -> Option<Ask> {
    const COL_A: f32 = 56.0;
    const SIZE_W: f32 = 74.0;
    const CHEVRON: f32 = 20.0;

    let head = ui
        .allocate_exact_size(egui::vec2(ui.available_width(), HEAD), egui::Sense::hover())
        .0;
    hairline(ui, head);
    let quiet = app::caption(ui.visuals());
    let rest = (head.width() - COL_A - SIZE_W - CHEVRON - GAP * 4.0).max(0.0);
    let answers_w = rest / 2.6 * 1.1;
    let layers_w = rest - answers_w;
    {
        let painter = ui.painter().clone();
        let mut at = head.left() + PAD;
        for (label, width) in [
            ("ROOT", COL_A),
            ("ANSWERS", answers_w),
            ("LAYERS", layers_w),
        ] {
            cell(
                &painter,
                at,
                head.center().y,
                width,
                label,
                egui::FontId::proportional(9.0),
                quiet,
            );
            at += width + GAP;
        }
        figure(
            &painter,
            head.right() - PAD - CHEVRON - GAP,
            head.center().y,
            "SIZE",
            egui::FontId::proportional(9.0),
            quiet,
            false,
        );
    }

    let mut ask = None;
    let mut clicked: Option<usize> = None;
    let mut excepted: Option<(u8, u8, bool)> = None;
    let mut dropped: Option<usize> = None;
    let layers = facts.shown_layers();
    for (index, root) in facts.roots.iter().enumerate() {
        let line = &summary.roots[index];
        let picked = view.picked == Some(index);
        let open = picked && view.open_rows.contains(&index);
        let in_range = line.in_range;
        let (rect, _) =
            ui.allocate_exact_size(egui::vec2(ui.available_width(), ROW), egui::Sense::hover());
        // ⚠️ Before the lamps drawn over it, for the reason [`switch_row`] states.
        let response = ui
            .interact(
                rect,
                ui.id().with(("root_row", root.note)),
                egui::Sense::click(),
            )
            .on_hover_text("one root, its own strokes; the layer index is the file's");
        let visuals = ui.visuals().clone();
        let ink = row_ink(&visuals, picked, in_range);
        let painter = ui.painter().clone();
        if picked {
            painter.rect_filled(rect, 0.0, visuals.selection.bg_fill);
        }
        hairline(ui, rect);
        let middle = rect.center().y;
        let left = rect.left() + PAD;
        painter.circle_filled(
            egui::pos2(left + 3.0, middle),
            3.0,
            match in_range {
                true => app::accent(&visuals),
                false => app::unlit(&visuals),
            },
        );
        cell(
            &painter,
            left + 12.0,
            middle,
            COL_A - 12.0,
            &note::name(root.note),
            egui::FontId::new(NAME, app::bold()),
            ink.text,
        );
        cell(
            &painter,
            left + COL_A + GAP,
            middle,
            answers_w,
            &line.answers,
            egui::FontId::monospace(11.0),
            ink.text,
        );

        let mut at = left + COL_A + GAP + answers_w + GAP;
        let lamps = layers.len() <= ROW_LAMPS;
        if lamps {
            for (rank, layer) in &layers {
                let kept = in_range && plan.keeps_layer(root.note, *layer);
                if let Some(keep) = lamp(
                    ui,
                    egui::Rect::from_min_size(egui::pos2(at, middle - LAMP.y / 2.0), LAMP),
                    kept,
                    ("root_lamp", root.note, layer),
                ) {
                    excepted = Some((root.note, *layer, keep));
                }
                at += LAMP.x + 2.0;
                at += cell(
                    &painter,
                    at,
                    middle,
                    12.0,
                    &layer_short(*rank, facts.layers.len()),
                    egui::FontId::proportional(MICRO),
                    ink.text,
                ) + GAP;
            }
        }
        let on = layers
            .iter()
            .filter(|(_, layer)| plan.keeps_layer(root.note, *layer))
            .count();
        let said = match (in_range, on == layers.len()) {
            (false, _) => "outside the trimmed range".to_string(),
            (true, false) => format!("{on} of {}", layers.len()),
            (true, true) => String::new(),
        };
        cell(
            &painter,
            at,
            middle,
            (left + COL_A + GAP + answers_w + GAP + layers_w - at).max(0.0),
            &said,
            egui::FontId::proportional(11.0),
            match in_range {
                true => ink.loud,
                false => ink.quiet,
            },
        );

        let (kept, held) = (line.kept, line.held);
        let right = rect.right() - PAD - CHEVRON - GAP;
        let mono = egui::FontId::monospace(MONO);
        let back = figure(
            &painter,
            right,
            middle,
            &room::measure(kept),
            mono.clone(),
            ink.text,
            false,
        );
        if kept != held {
            figure(
                &painter,
                back - 5.0,
                middle,
                &room::measure(held),
                mono,
                ink.quiet,
                true,
            );
        }
        painted(
            ui,
            match open {
                true => Glyph::ChevronDown,
                false => Glyph::ChevronRight,
            },
            egui::Rect::from_center_size(
                egui::pos2(rect.right() - PAD - CHEVRON / 2.0, middle),
                egui::Vec2::splat(12.0),
            ),
            ink.quiet,
        );
        if response.clicked() {
            clicked = Some(index);
        }
        if view.reveal == Some(index) {
            ui.scroll_to_rect(rect, Some(egui::Align::TOP));
        }

        if open {
            if let Some(asked) = open_row(ui, facts, plan, index, &line.runs, sounding) {
                match asked {
                    Opened::Audio(asked) => ask = Some(asked),
                    Opened::Drop => dropped = Some(index),
                }
            }
        }
    }
    view.reveal = None;
    if let Some(index) = clicked {
        match view.picked == Some(index) && view.open_rows.contains(&index) {
            true => {
                view.open_rows.remove(&index);
            }
            false => {
                view.open_rows.insert(index);
            }
        }
        view.picked = Some(index);
    }
    if let Some((root, layer, keep)) = excepted {
        plan.except(root, layer, keep);
    }
    if let Some(index) = dropped {
        drop_root(facts, plan, index);
    }
    ask
}

/// What an open root's row asked for.
enum Opened {
    Audio(Ask),
    Drop,
}

/// The facts and the actions under an open root: what the file says about it, and the
/// three things that can be done to it.
fn open_row(
    ui: &mut egui::Ui,
    facts: &Facts,
    plan: &mut Plan,
    index: usize,
    runs: &[(u8, u8)],
    sounding: Option<u8>,
) -> Option<Opened> {
    let mut asked = None;
    let root = &facts.roots[index];
    let (low, top) = (
        runs.first().map_or(root.note, |(low, _)| *low),
        runs.last().map_or(root.note, |(_, top)| *top),
    );
    let cents = f32::from(plan.tune(facts, root.note)) * FINE_TUNE_CENTS_PER_UNIT;
    egui::Frame::new()
        .fill(ui.visuals().window_fill)
        .inner_margin(egui::Margin {
            left: 68,
            right: 12,
            top: 10,
            bottom: 12,
        })
        .show(ui, |ui| {
            ui.set_width(ui.available_width());
            ui.spacing_mut().item_spacing = egui::vec2(20.0, 10.0);
            ui.horizontal_wrapped(|ui| {
                read_only(ui, "Root key", &note::name(root.note), "the recorded note");
                let dragged = "drag the root's boundary on the key map to move it";
                read_only(ui, "Answers from", &note::name(low), dragged);
                read_only(ui, "up to", &note::name(top), dragged);
                read_only(
                    ui,
                    "Channels",
                    facts.channel_word(),
                    "per file, not per stroke",
                );
                read_only(
                    ui,
                    "Fine tune",
                    &format!("{cents:+.1} c"),
                    "the per-key lane below is what edits it",
                );
            });
            ui.spacing_mut().item_spacing = egui::vec2(10.0, 6.0);
            let mut strikes: Vec<&Strike> = facts
                .strikes
                .iter()
                .filter(|strike| strike.root == index)
                .collect();
            strikes.sort_by_key(|strike| (strike.bank, strike.layer));
            for strike in strikes {
                let rank = facts
                    .layers
                    .iter()
                    .position(|value| *value == strike.layer)
                    .unwrap_or(0);
                ui.horizontal(|ui| {
                    ui.add_sized(
                        egui::vec2(170.0, LANE),
                        egui::Label::new(
                            egui::RichText::new(format!(
                                "{} · {}",
                                bank_word(strike.bank),
                                layer_name(rank, facts.layers.len())
                            ))
                            .size(NAME)
                            .color(ui.visuals().weak_text_color()),
                        )
                        .halign(egui::Align::LEFT),
                    );
                    let held = trim_of(facts, plan, strike);
                    let mut decibels = f64::from(held);
                    // ⚠️ `clamp_existing_to_range`: egui otherwise pulls a stored trim
                    // past the bound back to it and reports the change, which would
                    // plan a retrim of a stroke nobody touched.
                    let set = ui.add(
                        egui::DragValue::new(&mut decibels)
                            .range(0.0..=f64::from(TRIM_REACH))
                            .clamp_existing_to_range(false)
                            .speed(0.1)
                            .suffix(" dB"),
                    );
                    let set = match held > TRIM_REACH {
                        true => set.on_hover_text(format!(
                            "+0x34 in the stroke record, 1 dB a unit — it holds {held} dB, \
                             past the {TRIM_REACH} dB this control sets"
                        )),
                        false => set.on_hover_text("+0x34 in the stroke record, 1 dB a unit"),
                    };
                    if set.changed() {
                        let key = (root.note, strike.bank, strike.layer);
                        let picked = decibels.round() as u16;
                        match picked == strike.trim {
                            true => plan.trims.remove(&key),
                            false => plan.trims.insert(key, picked),
                        };
                    }
                    ui.label(
                        egui::RichText::new(match strike.decay {
                            Some(rate) => format!("decay {rate:.1} dB/s"),
                            None => "decay none".to_string(),
                        })
                        .font(egui::FontId::monospace(MONO))
                        .color(app::caption(ui.visuals())),
                    )
                    .on_hover_text("the fourteen coefficients at +0x36, carried as read");
                });
            }
            ui.spacing_mut().item_spacing = egui::vec2(6.0, 6.0);
            ui.horizontal_wrapped(|ui| {
                let playing = sounding == Some(root.note);
                let (glyph, label) = match playing {
                    true => (Glyph::X, "Stop"),
                    false => (Glyph::AudioLines, "Audition"),
                };
                if action(ui, glyph, label, app::accent(ui.visuals())) {
                    asked = Some(Opened::Audio(Ask::Play(root.note)));
                }
                if action(ui, Glyph::Waves, "Save WAV…", app::caption(ui.visuals())) {
                    asked = Some(Opened::Audio(Ask::Save(root.note)));
                }
                if action(ui, Glyph::X, "Drop this root", app::warn(ui.visuals())) {
                    asked = Some(Opened::Drop);
                }
            });
        });
    asked
}

/// What the lane draws a key's tune at, where full deflection is [`TUNE_CENTS`].
const TUNE_CENTS: i32 = 25;

/// A tune in file units as the lane's own reach, and back again.
///
/// The file stores units and the lane shows cents, so the two conversions are the one
/// place that knows which is which.
fn reach(units: i8) -> f32 {
    f32::from(units) * FINE_TUNE_CENTS_PER_UNIT / TUNE_CENTS as f32
}

fn units(reach: f32) -> i8 {
    let units = (reach * TUNE_CENTS as f32 / FINE_TUNE_CENTS_PER_UNIT).round();
    units.clamp(f32::from(i8::MIN), f32::from(i8::MAX)) as i8
}

/// The fine tune lane: one bar per key, drawn over by a drag across it.
fn per_key(ui: &mut egui::Ui, facts: &Facts, plan: &mut Plan, view: &mut View) {
    const LABEL: f32 = 80.0;
    const AXIS: f32 = 34.0;
    const RIGHT: f32 = 150.0;

    let values: Vec<f32> = (SPAN.low..=SPAN.high)
        .map(|key| reach(plan.tune(facts, key)))
        .collect();
    let edited: Vec<bool> = (SPAN.low..=SPAN.high)
        .map(|key| plan.tune(facts, key) != facts.tune(key))
        .collect();
    let count = edited.iter().filter(|held| **held).count();

    let painted_keys = ui
        .horizontal(|ui| {
            ui.spacing_mut().item_spacing.x = 8.0;
            ui.add_sized(
                egui::vec2(LABEL, LANE),
                egui::Label::new(
                    egui::RichText::new("Fine tune")
                        .size(11.0)
                        .color(ui.visuals().weak_text_color()),
                )
                .halign(egui::Align::LEFT),
            );
            let (top, bottom) = Scale::Cents(TUNE_CENTS).axis_labels();
            ui.allocate_ui(egui::vec2(AXIS, 38.0), |ui| {
                ui.spacing_mut().item_spacing.y = 0.0;
                ui.with_layout(egui::Layout::top_down(egui::Align::RIGHT), |ui| {
                    for label in [top.as_str(), "0", bottom.as_str()] {
                        ui.label(
                            egui::RichText::new(label)
                                .font(egui::FontId::monospace(9.0))
                                .color(app::caption(ui.visuals())),
                        );
                    }
                });
            });
            let lane = ui.available_width() - RIGHT - 8.0;
            let drawn = ui
                .allocate_ui(egui::vec2(lane.max(1.0), 38.0), |ui| {
                    keys::lane(ui, SPAN, &values, &edited, Scale::Cents(TUNE_CENTS))
                })
                .inner;
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                let said = match count {
                    0 => format!("{} keys · ±{TUNE_CENTS} c", SPAN.keys()),
                    n => format!("{} keys · ±{TUNE_CENTS} c · {n} edited", SPAN.keys()),
                };
                ui.label(
                    egui::RichText::new(said)
                        .font(egui::FontId::monospace(10.0))
                        .color(match count {
                            0 => app::caption(ui.visuals()),
                            _ => app::warn(ui.visuals()),
                        }),
                );
            });
            drawn
        })
        .inner;

    for (key, reach) in painted_keys {
        let units = units(reach);
        match units == facts.tune(key) {
            true => plan.fine_tune.remove(&key),
            false => plan.fine_tune.insert(key, units),
        };
    }

    ui.add_space(8.0);
    let chevron = match view.key_table {
        true => Glyph::ChevronDown,
        false => Glyph::ChevronRight,
    };
    let label = match view.key_table {
        true => "Hide the per-key table",
        false => "Show the 128-key fine tune table",
    };
    if ui
        .horizontal(|ui| {
            ui.spacing_mut().item_spacing.x = 6.0;
            icon(ui, chevron, 12.0, app::caption(ui.visuals()));
            ui.label(
                egui::RichText::new(label)
                    .size(11.0)
                    .color(app::caption(ui.visuals())),
            )
        })
        .response
        .interact(egui::Sense::click())
        .clicked()
    {
        view.key_table = !view.key_table;
    }
    if !view.key_table {
        return;
    }
    egui::Frame::new()
        .fill(ui.visuals().window_fill)
        .stroke(egui::Stroke::new(
            1.0_f32,
            ui.visuals().widgets.noninteractive.bg_stroke.color,
        ))
        .corner_radius(RADIUS)
        .inner_margin(egui::Margin::symmetric(8, 6))
        .show(ui, |ui| {
            ui.set_width(ui.available_width());
            egui::Grid::new("piano_key_table")
                .num_columns(8)
                .spacing(egui::vec2(18.0, 0.0))
                .show(ui, |ui| {
                    for key in 0..npno::NOTES as u8 {
                        let units = plan.tune(facts, key);
                        let cents = f32::from(units) * FINE_TUNE_CENTS_PER_UNIT;
                        ui.label(
                            egui::RichText::new(note::name(key))
                                .font(egui::FontId::monospace(MONO))
                                .color(ui.visuals().weak_text_color()),
                        );
                        ui.label(
                            egui::RichText::new(format!("{cents:+.1} c"))
                                .font(egui::FontId::monospace(MONO))
                                .color(match units == 0 {
                                    true => app::caption(ui.visuals()),
                                    false => ui.visuals().text_color(),
                                }),
                        );
                        if key % 4 == 3 {
                            ui.end_row();
                        }
                    }
                });
        });
}

impl State {
    /// The Edit face under the key map: what is kept, which layers, which roots, and
    /// the per-key tune.
    pub fn ui(&mut self, ui: &mut egui::Ui, sounding: Option<u8>) -> Option<Ask> {
        self.summarise();
        let id = self.open.as_ref()?.id;
        let saying =
            self.job
                .as_ref()
                .filter(|job| job.id == id)
                .map(|job| match job.job.progress() {
                    said if said.is_empty() => "applying…".to_string(),
                    said => said,
                });
        let State {
            open,
            draft,
            summary,
            view,
            free,
            ..
        } = self;
        let facts = match &open.as_ref()?.facts {
            Ok(facts) => facts,
            Err(why) => {
                ui.label(egui::RichText::new(why).color(app::bad(ui.visuals())));
                return None;
            }
        };
        let summary = summary.as_ref()?;
        let free = *free;

        let kept = summary.kept;
        let (badge, ink) = match (&saying, free) {
            (Some(saying), _) => (saying.clone(), app::caption(ui.visuals())),
            (None, Some(free)) if kept > free => (
                format!("{} over", room::measure(kept - free)),
                app::warn(ui.visuals()),
            ),
            (None, Some(free)) => (
                format!("fits · {} to spare", room::measure(free - kept)),
                app::good(ui.visuals()),
            ),
            (None, None) => (
                "no free piano memory reported".to_string(),
                app::caption(ui.visuals()),
            ),
        };
        controls::heading(
            ui,
            "Trim to fit",
            "what is kept, against what the instrument has free",
            Some((&badge, ink)),
        );
        let width = ui.available_width();
        let wide = width >= 640.0;
        let wide_column = match wide {
            true => (width - PAD * 2.0 - 24.0) / 2.0,
            false => width - PAD * 2.0,
        };
        match wide {
            true => {
                ui.horizontal_top(|ui| {
                    ui.add_space(PAD);
                    column(ui, wide_column, |ui| switches(ui, facts, draft, summary));
                    ui.add_space(24.0);
                    column(ui, wide_column, |ui| meter(ui, facts, draft, summary));
                });
            }
            false => {
                ui.horizontal_top(|ui| {
                    ui.add_space(PAD);
                    column(ui, wide_column, |ui| {
                        switches(ui, facts, draft, summary);
                        ui.add_space(10.0);
                        meter(ui, facts, draft, summary);
                    });
                });
            }
        }
        ui.add_space(12.0);

        controls::heading(
            ui,
            "Playback",
            "what the instrument applies over every stroke",
            None,
        );
        ui.horizontal_top(|ui| {
            ui.add_space(PAD);
            column(ui, width - PAD * 2.0, |ui| playback(ui, facts, draft));
        });
        ui.add_space(12.0);

        controls::heading(
            ui,
            "Velocity layers",
            "the switch speaks for every root; a segment is one root — click it to drop \
             that layer there only",
            None,
        );
        ui.horizontal_top(|ui| {
            ui.add_space(PAD);
            column(ui, width - PAD * 2.0, |ui| {
                lanes(ui, facts, draft, view.picked)
            });
        });
        ui.add_space(12.0);

        controls::heading(
            ui,
            "Roots",
            "each root keeps or drops its own layers",
            Some((
                &format!("{} roots", facts.roots.len()),
                app::caption(ui.visuals()),
            )),
        );
        let ask = roots(ui, facts, draft, summary, view, sounding);
        ui.add_space(12.0);

        controls::heading(
            ui,
            "Per key",
            "drag across a lane to draw values; the table below edits one key at a time",
            None,
        );
        ui.horizontal_top(|ui| {
            ui.add_space(PAD);
            column(ui, width - PAD * 2.0, |ui| per_key(ui, facts, draft, view));
        });
        ui.add_space(12.0);
        ask
    }

    /// What the file says about itself, above the container record every document has.
    pub fn meta(&mut self, ui: &mut egui::Ui) {
        let Some(facts) = self.facts() else {
            return;
        };
        controls::heading(
            ui,
            "Metadata",
            "what the file says about itself — read here, never written differently",
            None,
        );
        let rows = [
            ("Format", "npno".to_string(), "a piano library"),
            (
                "Stream version",
                format!("{:#05x}", facts.stream),
                "what decides the capability struct",
            ),
            ("Size", room::measure(facts.total), "before any trim"),
            (
                "Name",
                format!("{}#{}", facts.name, facts.variant),
                "Name#Variant at 0x1c",
            ),
            ("Channels", facts.channel_word().to_string(), "per file"),
            (
                "Strokes",
                format!("{} in {} roots", facts.strokes, facts.roots.len()),
                "one recorded note each",
            ),
            (
                "Keys answered",
                format!("{} of 128", facts.covered.len()),
                "the key map at 0x8c",
            ),
            ("Kind", kind_name(facts.kind), "0x18"),
            (
                "Gain",
                format!("{:+.1} dB", f32::from(facts.gain) / 10.0),
                "0x40c, tenths of a decibel",
            ),
        ];
        for (label, value, note) in rows {
            let (rect, _) = ui
                .allocate_exact_size(egui::vec2(ui.available_width(), 24.0), egui::Sense::hover());
            ui.painter().hline(
                rect.x_range(),
                rect.top() + 0.5,
                egui::Stroke::new(1.0_f32, ui.visuals().widgets.noninteractive.bg_stroke.color),
            );
            let painter = ui.painter().clone();
            let inner = rect.shrink2(egui::vec2(PAD, 0.0));
            let track = inner.width() / 3.8;
            cell(
                &painter,
                inner.left(),
                rect.center().y,
                track,
                label,
                egui::FontId::proportional(11.0),
                ui.visuals().weak_text_color(),
            );
            cell(
                &painter,
                inner.left() + track,
                rect.center().y,
                track,
                &value,
                egui::FontId::monospace(11.0),
                ui.visuals().text_color(),
            );
            cell(
                &painter,
                inner.left() + track * 2.0,
                rect.center().y,
                inner.right() - inner.left() - track * 2.0,
                note,
                egui::FontId::proportional(NOTE),
                app::caption(ui.visuals()),
            );
        }
        ui.add_space(10.0);
        ui.horizontal_top(|ui| {
            ui.add_space(PAD);
            ui.spacing_mut().item_spacing.x = 7.0;
            icon(ui, Glyph::CircleCheck, 12.0, app::good(ui.visuals()));
            ui.label(
                egui::RichText::new(
                    "Byte-exact: the stroke directory and audio stay verbatim; a trim \
                     re-lays the directory and every audio offset, and the container \
                     recomputes its checksum.",
                )
                .size(11.0)
                .color(ui.visuals().weak_text_color()),
            );
        });
        ui.add_space(10.0);
    }

    /// The Advanced face: what this format holds, and where the edited fields land.
    pub fn advanced(&mut self, ui: &mut egui::Ui) {
        if self.facts().is_none() {
            return;
        }
        capability::table(ui, CAPABILITIES);
        capability::offsets(ui, &offsets());
    }
}

/// What a piano library holds, in the state this editor puts each of them in.
const CAPABILITIES: &[Row] = &[
    Row {
        name: "name",
        state: Cap::Editable,
        note: "Name#Variant at 0x1c",
    },
    Row {
        name: "category / sub",
        state: Cap::Absent,
        note: "no category in a piano library",
    },
    Row {
        name: "key zones: root / top / low",
        state: Cap::Editable,
        note: "a root per key at 0x8c; the boundaries are dragged on the key map",
    },
    Row {
        name: "velocity layers",
        state: Cap::Editable,
        note: "per root; the index is the file's",
    },
    Row {
        name: "per-zone gain / detune",
        state: Cap::Editable,
        note: "trim per stroke at +0x34 (1 dB a unit); fine tune per key at 0x18c",
    },
    Row {
        name: "per-key table",
        state: Cap::Editable,
        note: "128 × fine tune at 0x18c",
    },
    Row {
        name: "instrument gain",
        state: Cap::Editable,
        note: "0x40c, signed tenths of a dB",
    },
    Row {
        name: "loop points / crossfade",
        state: Cap::ReadOnly,
        note: "marks in the stroke record, carried verbatim; meaning open",
    },
    Row {
        name: "loop decay / detune",
        state: Cap::ReadOnly,
        note: "the applied-decay ladder at +0x36, carried as read",
    },
    Row {
        name: "release samples",
        state: Cap::Editable,
        note: "bank 2 — drop or keep",
    },
    Row {
        name: "pedal resonance samples",
        state: Cap::Editable,
        note: "bank 1 — Small out of Medium",
    },
    Row {
        name: "sound parameters",
        state: Cap::Absent,
        note: "panel-side: acoustics, touch",
    },
    Row {
        name: "stereo / channels",
        state: Cap::ReadOnly,
        note: "per file",
    },
    Row {
        name: "replace / add a stroke",
        state: Cap::Editable,
        note: "File › New › piano library builds one from WAVs; a template is optional",
    },
    Row {
        name: "cut / move / drop strokes",
        state: Cap::Editable,
        note: "strokes are self-contained",
    },
    Row {
        name: "decode / audition",
        state: Cap::Editable,
        note: "one stroke at a time, on request",
    },
    Row {
        name: "size trim",
        state: Cap::Editable,
        note: "banks, layers, range",
    },
    Row {
        name: "write to the instrument",
        state: Cap::Editable,
        note: "class 1",
    },
    Row {
        name: "byte-exact round trip",
        state: Cap::Verified,
        note: "directory and audio re-laid, checksum recomputed",
    },
];

/// Where the fields this editor writes land in the body.
fn offsets() -> Vec<Offset> {
    vec![
        Offset {
            at: "body 0x04".to_string(),
            holds: "u16".to_string(),
            note: "stream version — the offsets below are pinned to it",
        },
        Offset {
            at: "body 0x1c".to_string(),
            holds: "Name#Variant".to_string(),
            note: "32 bytes, NUL-padded; patched on rename",
        },
        Offset {
            at: "body 0x8c".to_string(),
            holds: "128 entries".to_string(),
            note: "the root that plays each key; 0xFF where the library covers nothing",
        },
        Offset {
            at: "body 0x18c".to_string(),
            holds: "128 × i8".to_string(),
            note: "fine tune, 0.7 cents a unit",
        },
        Offset {
            at: "body 0x18".to_string(),
            holds: "u8".to_string(),
            note: "the kind of instrument the library is filed under",
        },
        Offset {
            at: "body 0x40c".to_string(),
            holds: "i8".to_string(),
            note: "a gain over the whole library, in tenths of a decibel",
        },
        Offset {
            at: "body 0x40d".to_string(),
            holds: "u8".to_string(),
            note: "the highest key damped at note-off; keys above it ring on",
        },
        Offset {
            at: "record +0x34".to_string(),
            holds: "u16".to_string(),
            note: "trim per stroke in the directory at 0x732, 118 bytes a record",
        },
    ]
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use nord_format::formats::npno::synthetic::{take, Build};
    use nord_usb::wire::Status;

    use super::*;
    use crate::device::{pretend_allocation_unit, Device};
    use crate::log::Log;
    use crate::workspace::{Fresh, Origin, Workspace};

    /// The roots the test library records, and the layer values it spreads them over.
    const ROOTS: [u8; 3] = [48, 60, 72];
    const LAYERS: [u8; 3] = [0, 6, 12];

    /// A library shaped like a small vendor one: three roots of three attack layers,
    /// one of them also carrying a pedal-resonance and a release stroke, and a map that
    /// answers every key from A0 to C8.
    ///
    /// The blocks per stroke differ, so every figure the sections print is a figure
    /// something could get wrong.
    fn built() -> Build {
        let mut takes = Vec::new();
        for (index, root) in ROOTS.into_iter().enumerate() {
            for (rank, layer) in LAYERS.into_iter().enumerate() {
                takes.push(take(
                    root,
                    Bank::Attack,
                    layer,
                    (8 - rank * 2 + index) as u16,
                ));
            }
            if root == 60 {
                takes.push(take(root, Bank::Resonance, 0, 5));
                takes.push(take(root, Bank::Release, 0, 3));
            }
        }
        let map = (SPAN.low..=SPAN.high)
            .map(|key| {
                let root = ROOTS
                    .into_iter()
                    .min_by_key(|root| root.abs_diff(key))
                    .expect("three roots");
                (key, root)
            })
            .collect();
        Build {
            version: 0x464,
            channels: 1,
            takes,
            map,
        }
    }

    fn bytes() -> Vec<u8> {
        built().bytes().expect("the builder lays out a library")
    }

    fn facts() -> Facts {
        Facts::of(&bytes()).expect("it reads")
    }

    /// The test library with every switch still on.
    fn plan() -> Plan {
        Plan::default()
    }

    #[test]
    fn a_plan_that_drops_nothing_rebuilds_the_bytes_it_was_saved_as() {
        let saved = bytes();
        assert_eq!(rebuild(&saved, &plan()).unwrap(), saved);
    }

    /// The release bank is its own set of strokes: dropping it takes exactly those and
    /// leaves every key still answering the root it did.
    #[test]
    fn dropping_the_release_bank_takes_its_strokes_and_uncovers_no_key() {
        let saved = bytes();
        let facts = facts();
        let mut plan = plan();
        plan.switch_bank(Bank::Release, false);

        let made = rebuild(&saved, &plan).unwrap();
        let entity = nord_format::from_stream(&mut Cursor::new(&made)).unwrap();
        let library = piano(&entity).unwrap().library().unwrap();
        assert_eq!(library.strokes().len(), facts.strokes - 1);
        assert!(
            library
                .strokes()
                .iter()
                .all(|stroke| stroke.bank() != Some(Bank::Release)),
            "a release stroke survived the drop"
        );
        let was = nord_format::from_stream(&mut Cursor::new(&saved)).unwrap();
        assert_eq!(
            library.key_map(),
            piano(&was).unwrap().library().unwrap().key_map(),
            "the release bank answers no key of its own"
        );
        assert_eq!(
            kept_bytes(&facts, &plan),
            facts.total - bank_bytes(&facts, None, Bank::Release)
        );
    }

    /// A per-root exception is the one selection no named transform expresses: it takes
    /// one layer off one root and leaves every other stroke where it was.
    #[test]
    fn a_per_root_layer_drop_leaves_every_other_stroke_where_it_was() {
        let saved = bytes();
        let before = nord_format::from_stream(&mut Cursor::new(&saved)).unwrap();
        let before = piano(&before).unwrap().library().unwrap();

        let mut plan = plan();
        plan.roots.insert((60, LAYERS[1]), false);
        let made = rebuild(&saved, &plan).unwrap();
        let after = nord_format::from_stream(&mut Cursor::new(&made)).unwrap();
        let after = piano(&after).unwrap().library().unwrap();

        assert_eq!(after.strokes().len(), before.strokes().len() - 1);
        let kept: Vec<(u8, u8, u8)> = before
            .strokes()
            .iter()
            .filter(|stroke| !(stroke.root == 60 && stroke.layer() == LAYERS[1]))
            .map(|stroke| (stroke.root, stroke.bank_code(), stroke.layer()))
            .collect();
        let left: Vec<(u8, u8, u8)> = after
            .strokes()
            .iter()
            .map(|stroke| (stroke.root, stroke.bank_code(), stroke.layer()))
            .collect();
        assert_eq!(left, kept);
        for (was, is) in before
            .strokes()
            .iter()
            .filter(|stroke| !(stroke.root == 60 && stroke.layer() == LAYERS[1]))
            .zip(after.strokes())
        {
            assert_eq!(
                was.audio(),
                is.audio(),
                "a span moved with its bytes changed"
            );
        }
        assert_eq!(
            after.key_root(60).unwrap(),
            Some(60),
            "root 60 still has layers, so its keys still answer"
        );
    }

    /// The name is a field in the prefix: writing it moves the bytes it owns and the
    /// container's checksum, and nothing else.
    #[test]
    fn renaming_a_library_changes_the_name_bytes_and_nothing_else() {
        let saved = bytes();
        let mut plan = plan();
        plan.name = Some("Wurly 200A".to_string());
        let made = rebuild(&saved, &plan).unwrap();

        assert_eq!(made.len(), saved.len(), "a rename moves no audio");
        let moved: Vec<usize> = (0..saved.len())
            .filter(|at| saved[*at] != made[*at])
            .collect();
        assert!(!moved.is_empty(), "the name did not land");
        let entity = nord_format::from_stream(&mut Cursor::new(&made)).unwrap();
        let library = piano(&entity).unwrap().library().unwrap();
        assert_eq!(library.name(), ("Wurly 200A".into(), "Variant".into()));

        let body_at = saved
            .windows(4)
            .position(|word| word == b"CNSP")
            .expect("a CNSP body");
        let body_len = library.body_len().unwrap();
        for at in &moved {
            // `Name#Variant` at body 0x1c, and on this stream the long name at 0x3c.
            // Anything outside the body is the container's own checksum.
            let inside = at.checked_sub(body_at).filter(|at| *at < body_len);
            if let Some(at) = inside {
                assert!(
                    (0x1c..0x5c).contains(&at),
                    "body byte {at:#x} is outside the name fields",
                );
            }
        }
    }

    /// The switches speak for every root, so throwing one has to clear the exceptions
    /// that root made — a switch that left them standing would say one thing and do
    /// another.
    #[test]
    fn a_master_switch_clears_the_per_root_exceptions_of_its_layer() {
        let mut plan = plan();
        plan.roots.insert((60, LAYERS[0]), false);
        plan.roots.insert((60, LAYERS[1]), false);
        assert!(!plan.keeps_layer(60, LAYERS[0]));

        plan.switch_layer(LAYERS[0], false);
        assert!(
            !plan.keeps_layer(48, LAYERS[0]),
            "the switch speaks for every root"
        );
        plan.switch_layer(LAYERS[0], true);
        assert!(
            plan.keeps_layer(60, LAYERS[0]),
            "and putting it back clears the exception it spoke over"
        );
        assert!(
            !plan.keeps_layer(60, LAYERS[1]),
            "another layer's exception is not this switch's business"
        );
    }

    /// A segment clicked off and back on is no edit: an exception that agrees with its
    /// switch is dropped, so nothing is left for a save to lay the library out for.
    #[test]
    fn a_per_root_exception_put_back_leaves_the_plan_empty() {
        let mut plan = plan();
        plan.except(ROOTS[1], LAYERS[0], false);
        assert!(!plan.keeps_layer(ROOTS[1], LAYERS[0]));
        assert!(!plan.is_empty());

        plan.except(ROOTS[1], LAYERS[0], true);
        assert!(plan.is_empty(), "{plan:?}");

        // Under a switch that is off it is the other way about: keeping the layer is
        // the exception, and dropping it again says only what the switch says.
        plan.switch_layer(LAYERS[0], false);
        plan.except(ROOTS[1], LAYERS[0], false);
        assert!(plan.roots.is_empty(), "the switch already drops it");
        plan.except(ROOTS[1], LAYERS[0], true);
        assert_eq!(plan.roots.get(&(ROOTS[1], LAYERS[0])), Some(&true));
    }

    /// Dropping a root takes the layers it records whose switch is still on, and the
    /// master switches speak over every exception it left.
    #[test]
    fn dropping_a_root_excepts_only_the_layers_its_switch_still_keeps() {
        let facts = facts();
        let mut plan = plan();
        plan.switch_layer(LAYERS[0], false);
        drop_root(&facts, &mut plan, 1);

        let excepted: Vec<(u8, u8)> = plan.roots.keys().copied().collect();
        assert_eq!(
            excepted,
            [(ROOTS[1], LAYERS[1]), (ROOTS[1], LAYERS[2])],
            "the layer its switch already dropped needs no exception",
        );
        assert!(
            plan.keeps_layer(ROOTS[0], LAYERS[1]),
            "and no other root moved"
        );

        for layer in LAYERS {
            plan.switch_layer(layer, false);
        }
        for layer in LAYERS {
            plan.switch_layer(layer, true);
        }
        assert!(plan.is_empty(), "{plan:?}");
    }

    /// A plan that would leave the library with nothing to play is refused, and the
    /// rebuild says so rather than writing an empty directory.
    #[test]
    fn a_plan_that_would_leave_no_strokes_at_all_is_refused() {
        let saved = bytes();
        let mut plan = plan();
        for layer in LAYERS {
            plan.switch_layer(layer, false);
        }
        let refused = rebuild(&saved, &plan).unwrap_err();
        assert!(refused.contains("no strokes at all"), "{refused}");
    }

    #[test]
    fn a_body_that_is_no_piano_library_is_refused_before_anything_is_written() {
        let mut plan = plan();
        plan.name = Some("Wurly 200A".to_string());
        let refused = rebuild(&Fresh::SetList.bytes().unwrap(), &plan);
        assert!(refused.is_err(), "a set list is not a piano library");
    }

    // Where the piano document writes, as the Advanced face states the offsets.
    const KIND_AT: usize = 0x18;
    const KEY_MAP_AT: usize = 0x8c;
    const GAIN_AT: usize = 0x40c;
    const DAMPER_TOP_AT: usize = 0x40d;
    const DIRECTORY_AT: usize = 0x732;
    const REC_TRIM: usize = 0x34;

    /// How long the file a plan makes comes out, and the body offsets it moves. Anything
    /// outside the body is the container's own checksum, which every write moves.
    fn moved(saved: &[u8], plan: &Plan) -> (usize, Vec<usize>) {
        let base = rebuild(saved, &Plan::default()).unwrap();
        let made = rebuild(saved, plan).unwrap();
        let body_at = saved
            .windows(4)
            .position(|word| word == b"CNSP")
            .expect("a CNSP body");
        let entity = nord_format::from_stream(&mut Cursor::new(&base)).unwrap();
        let body_len = piano(&entity)
            .unwrap()
            .library()
            .unwrap()
            .body_len()
            .unwrap();
        let offsets = (0..base.len())
            .filter(|at| base[*at] != made[*at])
            .filter_map(|at| at.checked_sub(body_at).filter(|at| *at < body_len))
            .collect();
        (made.len(), offsets)
    }

    /// Each of these is one field of the prefix or of a stroke's record: it writes the
    /// bytes it names, and it re-lays no audio.
    #[test]
    fn each_playback_field_writes_only_the_byte_it_names() {
        let saved = bytes();
        let whole = saved.len();

        let mut gained = plan();
        gained.gain = Some(-20);
        assert_eq!(moved(&saved, &gained), (whole, vec![GAIN_AT]));

        let mut damped = plan();
        damped.damper_top = Some(90);
        assert_eq!(moved(&saved, &damped), (whole, vec![DAMPER_TOP_AT]));

        let mut filed = plan();
        filed.kind = Some(Kind::Wurlitzer);
        assert_eq!(moved(&saved, &filed), (whole, vec![KIND_AT]));

        let mut routed = plan();
        routed.key_roots.insert(60, Some(ROOTS[0]));
        assert_eq!(moved(&saved, &routed), (whole, vec![KEY_MAP_AT + 60]));

        // The trim is a u16 in the record of the stroke it names — the first of them,
        // which is the lowest root's loudest attack.
        let mut trimmed = plan();
        trimmed
            .trims
            .insert((ROOTS[0], Bank::Attack.code(), LAYERS[0]), 6);
        assert_eq!(
            moved(&saved, &trimmed),
            (whole, vec![DIRECTORY_AT + REC_TRIM + 1])
        );
    }

    /// A trim names the stroke it belongs to, not the place in the directory that
    /// stroke sat at: dropping a layer moves every record after it, and the trim has to
    /// move with its own.
    #[test]
    fn a_trim_lands_on_its_own_stroke_after_another_layer_is_dropped() {
        let saved = bytes();
        let mut plan = plan();
        let wanted = (ROOTS[1], Bank::Attack.code(), LAYERS[2]);
        plan.trims.insert(wanted, 9);
        plan.switch_layer(LAYERS[0], false);

        let made = rebuild(&saved, &plan).unwrap();
        let entity = nord_format::from_stream(&mut Cursor::new(&made)).unwrap();
        let library = piano(&entity).unwrap().library().unwrap();
        for stroke in library.strokes() {
            let held = (stroke.root, stroke.bank_code(), stroke.layer());
            assert_eq!(
                stroke.trim(),
                match held == wanted {
                    true => 9,
                    false => 0,
                },
                "{stroke:?}"
            );
        }
    }

    /// The map is written before anything is dropped, so a route the library cannot
    /// play is the format's own refusal rather than a silently uncovered key.
    #[test]
    fn a_route_to_a_root_the_directory_does_not_record_is_refused_in_the_formats_words() {
        let saved = bytes();
        let mut plan = plan();
        plan.key_roots.insert(60, Some(100));
        let refused = rebuild(&saved, &plan).unwrap_err();
        assert!(refused.contains("root 100"), "{refused}");

        // A route to a root a later drop takes away is not refused: the drop uncovers
        // the key, which is what dropping a root has always done.
        let mut dropped = plan.clone();
        dropped.key_roots.insert(60, Some(ROOTS[0]));
        for layer in LAYERS {
            dropped.roots.insert((ROOTS[0], layer), false);
        }
        let made = rebuild(&saved, &dropped).unwrap();
        let entity = nord_format::from_stream(&mut Cursor::new(&made)).unwrap();
        let library = piano(&entity).unwrap().library().unwrap();
        assert_eq!(library.key_root(60).unwrap(), None);
    }

    /// Dragging the boundary between two roots moves the keys across it, and the map,
    /// the coverage and what a struck key sounds all read the plan rather than the file.
    #[test]
    fn a_dragged_root_boundary_moves_the_keys_across_it() {
        let facts = facts();
        let spread = |plan: &Plan| -> Vec<(u8, u8)> {
            (0..facts.roots.len())
                .flat_map(|index| runs(&plan.keys_of(&facts, index)))
                .collect()
        };
        let was = spread(&plan());
        assert_eq!(was, [(SPAN.low, 54), (55, 66), (67, SPAN.high)]);

        let mut moved = plan();
        let now = keys::boundary(&was, SPAN, 0, keys::Edge::Top, 57);
        reroute(&facts, &mut moved, &[0, 1, 2], &was, &now);
        assert_eq!(spread(&moved), [(SPAN.low, 57), (58, 66), (67, SPAN.high)]);
        assert!(
            status(&facts, &moved, 56).1.contains("root C3"),
            "the keys moved with the boundary"
        );
        assert!(
            Summary::of(&facts, &moved, None).silent.is_empty(),
            "and none fell silent"
        );
        assert_eq!(
            rebuild(&bytes(), &moved).unwrap().len(),
            bytes().len(),
            "a remap moves no audio"
        );

        // The outer end has no root to share with, so it uncovers keys instead.
        let mut cut = plan();
        let now = keys::boundary(&was, SPAN, 2, keys::Edge::Top, 100);
        reroute(&facts, &mut cut, &[0, 1, 2], &was, &now);
        assert_eq!(Summary::of(&facts, &cut, None).silent, [(101, SPAN.high)]);
        assert!(!status(&facts, &cut, 105).0);
    }

    /// A key sounds the largest layer value its root holds that is at most
    /// `(127 − v)·31/127`, so each value answers from the split with the value below it
    /// up to its own.
    #[test]
    fn a_layer_value_answers_the_velocities_no_softer_value_reaches() {
        assert_eq!(spans(&[0]), [(0, 1..=127)]);
        assert_eq!(
            spans(&[0, 6, 12]),
            [(0, 103..=127), (6, 78..=102), (12, 1..=77)]
        );

        // 31 is past the bound at every velocity a key can send, so nothing reaches it.
        let reach = spans(&[0, 31]);
        assert_eq!(reach[0], (0, 1..=127));
        assert!(reach[1].1.is_empty(), "{:?}", reach[1]);
        assert_eq!(span_text(&reach[1].1), "no velocity");
        assert_eq!(span_text(&reach[0].1), "v 1–127");
    }

    /// The ladder holds a per-frame coefficient, and the stroke's line reads it as the
    /// rate it decays at. Unity applies nothing at all.
    #[test]
    fn an_applied_decay_reads_as_the_rate_its_ladder_states() {
        let unity = [npno::LADDER_UNITY; npno::DECAYS];
        assert_eq!(decay_rate(&unity), None);

        let mut ladder = unity;
        ladder[0] = npno::LADDER_UNITY - 1000;
        let rate = decay_rate(&ladder).expect("an entry below unity applies something");
        // 8.686 × 35002 × 1000/2^23 = 36.2 dB a second.
        assert!((rate - 36.2).abs() < 0.1, "{rate}");
    }

    /// Every figure the trim section prints comes off the strokes' own byte lengths,
    /// and the file is the scale: a plan that drops nothing keeps all of it.
    #[test]
    fn kept_bytes_is_the_file_less_the_audio_the_plan_drops() {
        let facts = facts();
        let mut plan = plan();
        assert_eq!(kept_bytes(&facts, &plan), facts.total);

        let softest = *LAYERS.last().unwrap();
        let layer = layer_bytes(&facts, None, softest);
        assert!(layer > 0);
        plan.switch_layer(softest, false);
        assert_eq!(kept_bytes(&facts, &plan), facts.total - layer);

        // And the rebuilt file is no larger than what the arithmetic promised: the
        // directory loses a record per stroke as well.
        let made = rebuild(&bytes(), &plan).unwrap();
        assert!(
            made.len() as u64 <= kept_bytes(&facts, &plan),
            "{} against {}",
            made.len(),
            kept_bytes(&facts, &plan)
        );
    }

    /// A range cut drops whole roots, and a root keeping one key keeps every stroke it
    /// has.
    #[test]
    fn a_range_cut_costs_the_roots_it_leaves_no_key_to_answer() {
        let facts = facts();
        let mut plan = plan();
        plan.range = Some(55..=108);
        assert!(!plan.in_range(&facts, 0), "root 48 answers nothing now");
        assert!(plan.in_range(&facts, 1));
        assert_eq!(
            kept_bytes(&facts, &plan),
            facts.total - root_bytes(&facts, None, 0)
        );
        assert!(Summary::of(&facts, &plan, None)
            .covered
            .iter()
            .all(|key| *key >= 55));
    }

    /// The sentence names the smallest set of switches still on that clears the
    /// overage, and never one that is already off.
    #[test]
    fn the_cheapest_cut_is_the_smallest_set_of_switches_that_clears_the_overage() {
        let facts = facts();
        let plan = plan();
        let release = bank_bytes(&facts, None, Bank::Release);
        let resonance = bank_bytes(&facts, None, Bank::Resonance);
        assert!(release < resonance, "the release bank is the cheaper cut");

        // An overage the release bank alone covers is the release bank alone.
        let cut = cheapest_cut(&facts, &plan, release - 1).expect("something fits");
        assert_eq!(cut.picked, ["release samples"]);
        assert_eq!(cut.shed, release);

        // One it does not: the next cheapest single switch, not the release plus a
        // layer.
        let cut = cheapest_cut(&facts, &plan, release + 1).expect("something fits");
        assert_eq!(cut.picked.len(), 1, "{:?}", cut.picked);
        assert!(cut.shed > release);

        // Nothing left to throw once every switch is off.
        let mut spent = plan.clone();
        for layer in LAYERS {
            spent.switch_layer(layer, false);
        }
        for bank in [Bank::Resonance, Bank::Release] {
            spent.switch_bank(bank, false);
        }
        assert!(cheapest_cut(&facts, &spent, 1).is_none());

        // And a cut that would leave nothing at all to play is not a cut.
        let audio: u64 = facts.cells.iter().map(|cell| cell.bytes).sum();
        assert!(cheapest_cut(&facts, &plan, audio).is_none());
    }

    #[test]
    fn a_list_of_switches_reads_as_a_sentence_names_them() {
        let one = vec!["release samples".to_string()];
        assert_eq!(listed(&one), "release samples");
        let two = vec!["soft layer".to_string(), "release samples".to_string()];
        assert_eq!(listed(&two), "soft layer and release samples");
        let three = vec![
            "soft layer".to_string(),
            "medium layer".to_string(),
            "release samples".to_string(),
        ];
        assert_eq!(
            listed(&three),
            "soft layer, medium layer and release samples"
        );
        assert_eq!(listed(&[]), "");
    }

    /// Three layers are the panel's own three words; any other count is named by its
    /// place, loudest first.
    #[test]
    fn a_layer_is_named_by_its_place_among_the_layers_the_file_holds() {
        let three: Vec<String> = (0..3).map(|rank| layer_name(rank, 3)).collect();
        assert_eq!(three, ["Hard", "Medium", "Soft"]);
        let five: Vec<String> = (0..5).map(|rank| layer_name(rank, 5)).collect();
        assert_eq!(
            five,
            ["Loudest", "Layer 2", "Layer 3", "Layer 4", "Softest"]
        );
        assert_eq!(layer_name(0, 1), "Loudest");
        // The rows and the lamps read softest first, which is the order a trim spends
        // them in.
        let facts = facts();
        assert_eq!(
            facts.shown_layers(),
            [(2, LAYERS[2]), (1, LAYERS[1]), (0, LAYERS[0])]
        );
        assert_eq!(layer_short(2, 3), "S");
    }

    /// The file stores units and the lane shows cents, so the conversion has to come
    /// back to the unit it started at — including at the ends of an `i8`.
    #[test]
    fn a_fine_tune_reads_in_cents_and_writes_back_the_unit_it_came_from() {
        for held in [0i8, 1, -1, 27, -27, 35, -35] {
            assert_eq!(units(reach(held)), held, "{held} units");
        }
        // The lane reaches ±25 cents, which is ±35 units at 0.7 cents each; a value
        // drawn past that lands on the unit the lane's own end is worth.
        assert_eq!(units(1.0), 36);
        assert_eq!(units(-1.0), -36);
        // And nothing wraps: an `i8` is what the byte holds.
        assert_eq!(units(100.0), i8::MAX);
        assert_eq!(units(-100.0), i8::MIN);
    }

    #[test]
    fn a_retuned_key_lands_on_the_key_it_was_drawn_on() {
        let saved = bytes();
        let facts = facts();
        let mut plan = plan();
        plan.fine_tune.insert(60, -4);
        assert_eq!(plan.tune(&facts, 60), -4);
        assert_eq!(plan.tune(&facts, 61), 0, "and no neighbour moved");

        let made = rebuild(&saved, &plan).unwrap();
        let entity = nord_format::from_stream(&mut Cursor::new(&made)).unwrap();
        let library = piano(&entity).unwrap().library().unwrap();
        assert_eq!(library.fine_tune(60).unwrap(), -4);
        assert_eq!(library.fine_tune(61).unwrap(), 0);
    }

    /// A partition with about `free` bytes left for pianos, and nothing else attached.
    ///
    /// The pretend allocation unit is small, so a test can name a free size the
    /// partition's own counters can actually express.
    fn attached(free: u64) -> Device {
        const UNIT: u32 = 1024;
        let mut device = Device::new(egui::Context::default());
        device.pretend_partitions(&[(ObjectClass::Piano, "Piano", UNIT)]);
        let unit = pretend_allocation_unit(ObjectClass::Piano, UNIT);
        device.state.inventory.push(Status {
            class: ObjectClass::Piano,
            count: 1,
            free: u32::try_from(free / u64::from(unit.get())).expect("a small pretend"),
            used: 0,
            dirty: 0,
            spare: 0,
        });
        device
    }

    /// The header reads what is kept of what is held, says `trimmed` rather than
    /// `edited`, and refuses to queue a library the instrument has no room for.
    #[test]
    fn the_header_reads_what_is_kept_and_says_when_it_will_not_fit() {
        let facts = facts();
        let plenty = attached(facts.total * 2);
        let untouched = extras(
            &facts,
            kept_bytes(&facts, &plan()),
            room::free_bytes(ObjectClass::Piano, &plenty.state),
            Standing::Laid,
        );
        assert!(
            untouched.size.is_none(),
            "nothing is trimmed, so nothing is said"
        );
        assert!(untouched.edited.is_none());
        assert!(untouched.loud.is_none(), "the header's own rule runs");

        let mut plan = plan();
        plan.switch_bank(Bank::Release, false);
        let kept = kept_bytes(&facts, &plan);
        let trimmed = extras(
            &facts,
            kept,
            room::free_bytes(ObjectClass::Piano, &plenty.state),
            Standing::Laid,
        );
        assert_eq!(
            trimmed.size.as_ref().map(|size| size.text.clone()),
            Some(room::measure_out_of(kept, facts.total))
        );
        assert_eq!(
            trimmed.edited.as_ref().map(|line| line.words.as_str()),
            Some("trimmed")
        );
        assert!(!trimmed.size.unwrap().warn, "it fits");
        assert!(trimmed.loud.is_none());

        // A partition with room for half of it: the loud action carries the overage.
        let cramped = attached(kept / 2);
        let free = room::free_bytes(ObjectClass::Piano, &cramped.state).expect("a unit arrived");
        let held = extras(&facts, kept, Some(free), Standing::Laid);
        let loud = held.loud.expect("it will not fit");
        assert_eq!(loud.tone, Tone::Blocked);
        assert_eq!(loud.send, None, "a blocked action asks for nothing");
        assert_eq!(
            loud.label,
            format!("No room · {} over", room::measure(kept - free))
        );
        assert!(held.size.expect("a size line").warn);

        // And with no instrument attached there is no verdict to give.
        let alone = Device::new(egui::Context::default());
        let quiet = extras(
            &facts,
            kept,
            room::free_bytes(ObjectClass::Piano, &alone.state),
            Standing::Laid,
        );
        assert!(quiet.loud.is_none(), "nothing has reported its free memory");
        assert!(quiet
            .size
            .expect("it is still trimmed")
            .hint
            .contains("not reported"));
    }

    /// A plan that has not reached the bytes yet is still an edit, and the header says
    /// so on a document the workspace reads as saved — and says what it is doing while
    /// the library is being laid out.
    #[test]
    fn the_header_claims_a_plan_the_bytes_do_not_hold_yet() {
        let facts = facts();
        let free = room::free_bytes(ObjectClass::Piano, &attached(facts.total * 2).state);

        let renamed = Plan {
            name: Some("Wurly 200A".to_string()),
            ..plan()
        };
        let pending = extras(
            &facts,
            kept_bytes(&facts, &renamed),
            free,
            Standing::Pending,
        );
        let claim = pending.state.expect("the bytes are the saved ones");
        assert_eq!(claim.words, "edited");
        assert_eq!(claim.ink, Ink::Warn);
        assert_eq!(
            pending.edited.map(|line| line.words),
            Some("edited".to_string()),
            "the same claim in whichever slot the strip reads",
        );

        let mut dropped = plan();
        dropped.switch_bank(Bank::Release, false);
        let dropping = kept_bytes(&facts, &dropped);
        let trimming = extras(&facts, dropping, free, Standing::Pending);
        assert_eq!(
            trimming.state.map(|line| line.words),
            Some("trimmed".to_string()),
            "a plan that drops strokes keeps its own word",
        );

        let applying = extras(&facts, dropping, free, Standing::Applying);
        assert_eq!(
            applying.state.as_ref().map(|line| line.words.as_str()),
            Some("applying…")
        );
        assert_eq!(applying.state.map(|line| line.ink), Some(Ink::Quiet));
        let loud = applying.loud.expect("the write waits for the apply");
        assert_eq!(loud.tone, Tone::Blocked);
        assert_eq!(loud.hint, "wait for the apply");
        assert_eq!(loud.send, None);
    }

    /// The sentence under the meter says whether it fits, what to throw when it does
    /// not, and says nothing it cannot know.
    #[test]
    fn the_constraint_sentence_names_the_cut_or_says_it_cannot_tell() {
        let facts = facts();
        let plan = plan();
        let (said, loud) = constraint(&plan, &Summary::of(&facts, &plan, Some(facts.total * 2)));
        assert!(
            said.starts_with("At ") && said.contains("to spare"),
            "{said}"
        );
        assert!(!loud);

        let (said, loud) = constraint(&plan, &Summary::of(&facts, &plan, Some(facts.total / 2)));
        assert!(said.contains("over."), "{said}");
        assert!(said.contains("the cheapest cut left that fits"), "{said}");
        assert!(loud);

        let (said, _) = constraint(&plan, &Summary::of(&facts, &plan, None));
        assert!(said.contains("has not reported"), "{said}");
    }

    /// What a struck key says: which root answered it, how far it was shifted, and why
    /// it was silent where it was.
    #[test]
    fn a_struck_key_says_which_root_answered_it() {
        let facts = facts();
        let mut plan = plan();
        let (good, said) = status(&facts, &plan, 61);
        assert!(good);
        assert_eq!(
            said,
            format!(
                "C#4 at vel {} → root C4 · shifted +1 st",
                keys::AUDITION_VELOCITY
            )
        );

        // With the loudest layer of that root dropped, the next kept one plays.
        plan.roots.insert((60, LAYERS[0]), false);
        let (good, said) = status(&facts, &plan, 60);
        assert!(good, "{said}");
        assert!(said.ends_with("the loudest layer is dropped, so the next kept layer plays"));

        // With every layer of it dropped, nothing does.
        for layer in LAYERS {
            plan.roots.insert((60, layer), false);
        }
        let (good, said) = status(&facts, &plan, 60);
        assert!(!good);
        assert!(
            said.contains("every layer of this root is dropped"),
            "{said}"
        );

        // A key the trim has cut away answers nothing at all.
        let mut cut = plan.clone();
        cut.range = Some(21..=53);
        let (good, said) = status(&facts, &cut, 72);
        assert!(!good);
        assert!(said.contains("no root answers this key"), "{said}");
    }

    #[test]
    fn the_coverage_reading_counts_the_silent_stretches() {
        let facts = facts();
        let mut plan = plan();
        assert!(Summary::of(&facts, &plan, None).silent.is_empty());
        assert_eq!(
            coverage(&Summary::of(&facts, &plan, None).silent),
            "every key answered"
        );

        plan.range = Some(36..=96);
        let gaps = Summary::of(&facts, &plan, None).silent;
        assert_eq!(gaps, [(21, 35), (97, 108)]);
        assert_eq!(coverage(&gaps), "2 silent ranges");
        assert_eq!(coverage(&gaps[..1]), "1 silent range");
    }

    /// A root's keys are one run in every specimen, and a map that splits them gets one
    /// cell per run rather than one cell over the keys between.
    #[test]
    fn a_roots_keys_read_as_the_stretches_they_run_in() {
        assert_eq!(runs(&[58, 59, 60, 61]), [(58, 61)]);
        assert_eq!(runs(&[58, 59, 70, 71]), [(58, 59), (70, 71)]);
        assert!(runs(&[]).is_empty());
    }

    /// Every capability the Advanced face calls editable is something this editor
    /// actually does: a plan change that lands in the rebuilt bytes, a stroke it decodes
    /// when asked, or the send its header offers.
    #[test]
    fn every_editable_capability_is_something_the_editor_does() {
        let saved = bytes();
        let facts = facts();
        for row in CAPABILITIES.iter().filter(|row| row.state == Cap::Editable) {
            let Some(edit) = plan_for(row.name) else {
                match row.name {
                    "decode / audition" => {}
                    "replace / add a stroke" => assert!(crate::newproject::Making::FROM_WAVS
                        .contains(&crate::newproject::Making::Piano)),
                    "write to the instrument" => {
                        assert!(!crate::device::read_only(ObjectClass::Piano))
                    }
                    other => panic!("{other} claims editable with no plan behind it"),
                }
                continue;
            };
            let mut plan = plan();
            edit(&mut plan, &facts);
            assert_ne!(
                rebuild(&saved, &plan).unwrap(),
                saved,
                "{} changed nothing",
                row.name
            );
        }
    }

    /// The plan change one capability names, where it names one.
    fn plan_for(name: &str) -> Option<fn(&mut Plan, &Facts)> {
        match name {
            "name" => Some(|plan, _| plan.name = Some("Wurly 200A".to_string())),
            "key zones: root / top / low" => Some(|plan, facts| {
                plan.route(facts, facts.roots[1].keys[0], Some(0));
            }),
            "per-zone gain / detune" => Some(|plan, facts| {
                plan.trims.insert(
                    (facts.roots[0].note, Bank::Attack.code(), facts.layers[0]),
                    6,
                );
            }),
            "instrument gain" => Some(|plan, facts| plan.gain = Some(facts.gain - 20)),
            "velocity layers" => Some(|plan, facts| plan.switch_layer(facts.layers[2], false)),
            "per-key table" => Some(|plan, _| {
                plan.fine_tune.insert(60, -4);
            }),
            "release samples" => Some(|plan, _| plan.switch_bank(Bank::Release, false)),
            "pedal resonance samples" => Some(|plan, _| plan.switch_bank(Bank::Resonance, false)),
            "cut / move / drop strokes" => Some(|plan, facts| {
                plan.roots
                    .insert((facts.roots[0].note, facts.layers[0]), false);
            }),
            "size trim" => Some(|plan, facts| plan.range = Some(default_range(facts))),
            _ => None,
        }
    }

    /// The piano editor over the test library, in a headless window.
    struct Editor {
        ctx: egui::Context,
        workspace: Workspace,
        device: Device,
        log: Log,
        state: State,
        id: u64,
    }

    /// What one frame put on screen, and what it asked for.
    struct Painted {
        words: Vec<String>,
        /// The white keys of the keyboard, in ascending order.
        whites: Vec<egui::Rect>,
        /// Every lamp, in the order they were drawn: the trim switches, then one per
        /// lane, then the ones on each root's row.
        lamps: Vec<egui::Rect>,
        asked: Option<Ask>,
    }

    impl Painted {
        fn said(&self, wanted: &str) -> bool {
            self.words.iter().any(|word| word.contains(wanted))
        }

        /// The white key `note` is painted at.
        fn white(&self, note: u8) -> egui::Pos2 {
            let index = (SPAN.low..note).filter(|key| !keys::is_black(*key)).count();
            self.whites[index].center()
        }
    }

    impl Editor {
        fn new(free: u64) -> Editor {
            Editor::of(bytes(), free)
        }

        fn of(saved: Vec<u8>, free: u64) -> Editor {
            let ctx = egui::Context::default();
            // Dressed the way the app dresses it: without the bold face bound, laying
            // out a root's name panics mid-frame.
            ctx.set_fonts(crate::app::fonts());
            ctx.all_styles_mut(crate::app::metrics);
            let mut workspace = Workspace::new(ctx.clone());
            let mut log = Log::default();
            let id = workspace.ingest(
                "Test Piano.npno".into(),
                Origin::File("Test Piano.npno".into()),
                saved,
                &mut log,
            );
            Editor {
                device: attached(free),
                ctx,
                workspace,
                log,
                state: State::default(),
                id,
            }
        }

        fn frame(&mut self, events: Vec<egui::Event>) -> Painted {
            self.driven(events, |_| {})
        }

        /// What a settled name box does: the set into the plan, and the plan kept where
        /// the library takes it.
        fn typed(&mut self, path: &str, value: &str) {
            self.state
                .take(&vec![(path.to_string(), value.to_string())])
                .expect("the piano knows the field");
            if let Some(plan) = self.state.drafted() {
                self.state.commit(plan);
            }
        }

        /// What the header's box holds over this document.
        fn boxes(&self) -> (Option<String>, Option<String>) {
            self.state
                .renaming(self.workspace.get(self.id).expect("it is open"))
        }

        fn awaited(&mut self) -> Applied {
            self.state
                .awaited(&self.ctx, &self.workspace)
                .expect("an apply is in flight")
        }

        /// Lay the plan in hand out and put the bytes under the document, which is what
        /// the app does once something has to carry them.
        fn apply(&mut self) -> Applied {
            self.state.start(&self.ctx, self.id, &self.workspace);
            let applied = self.awaited();
            let made = applied
                .made
                .as_ref()
                .expect("the plan stood")
                .as_ref()
                .expect("the library lays out")
                .clone();
            self.workspace.replace_bytes(self.id, made, &mut self.log);
            applied
        }

        /// One frame, with `edit` throwing whatever switch a click on its lamp would.
        fn driven(&mut self, events: Vec<egui::Event>, edit: impl FnOnce(&mut Plan)) -> Painted {
            let input = egui::RawInput {
                events,
                screen_rect: Some(egui::Rect::from_min_size(
                    egui::Pos2::ZERO,
                    egui::vec2(1100.0, 900.0),
                )),
                ..Default::default()
            };
            let mut asked = None;
            let mut edit = Some(edit);
            let output = self.ctx.run(input, |ctx| {
                egui::CentralPanel::default().show(ctx, |ui| {
                    let entity = self.workspace.get(self.id).expect("it is open");
                    self.state.begin(self.id, entity, &self.device.state);
                    if let Some(edit) = edit.take() {
                        edit(&mut self.state.draft);
                    }
                    asked = self.state.map(ui);
                    asked = self.state.ui(ui, None).or(asked);
                });
            });
            // What [`Document::replan`] does with the plan a frame left behind: try it
            // over the baseline, and keep it where the library takes it.
            if let Some(plan) = self.state.drafted() {
                let saved = self.workspace.get(self.id).unwrap().saved.bytes.clone();
                match planned(&saved, &plan) {
                    Ok(_) => self.state.commit(plan),
                    Err(_) => self.state.discard(),
                }
            }
            let mut painted = Painted {
                words: Vec::new(),
                whites: Vec::new(),
                lamps: Vec::new(),
                asked,
            };
            for clipped in &output.shapes {
                walk(&clipped.shape, &mut painted);
            }
            painted.lamps.dedup();
            painted
        }
    }

    fn walk(shape: &egui::Shape, into: &mut Painted) {
        match shape {
            egui::Shape::Text(text) => into.words.push(text.galley.text().to_string()),
            egui::Shape::Rect(drawn) if drawn.rect.height() == keys::KEYBOARD_H => {
                into.whites.push(drawn.rect)
            }
            // A lamp is the one thing drawn at its own fixed width; it is painted
            // filled and then stroked, so the pair is deduplicated after the walk.
            egui::Shape::Rect(drawn) if drawn.rect.width() == LAMP.x => into.lamps.push(drawn.rect),
            egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| walk(shape, into)),
            _ => {}
        }
    }

    fn press(at: egui::Pos2) -> Vec<egui::Event> {
        vec![
            egui::Event::PointerMoved(at),
            egui::Event::PointerButton {
                pos: at,
                button: egui::PointerButton::Primary,
                pressed: true,
                modifiers: egui::Modifiers::NONE,
            },
            egui::Event::PointerButton {
                pos: at,
                button: egui::PointerButton::Primary,
                pressed: false,
                modifiers: egui::Modifiers::NONE,
            },
        ]
    }

    /// Every section paints, and the map names its roots and the keys they answer.
    #[test]
    fn the_editor_paints_its_sections_and_names_what_it_holds() {
        let mut editor = Editor::new(facts().total * 2);
        editor.frame(Vec::new());
        let painted = editor.frame(Vec::new());
        for heading in [
            "Key map",
            "Trim to fit",
            "Playback",
            "Velocity layers",
            "Roots",
            "Per key",
        ] {
            assert!(painted.said(heading), "{heading}: {:?}", painted.words);
        }
        assert!(painted.said("every key answered"));
        assert!(painted.said("3 roots"));
        assert!(painted.said("Soft layer"), "{:?}", painted.words);
        assert!(painted.said("Release samples"));
        assert!(painted.said("fits ·"));
        assert!(painted.said("INSTRUMENT GAIN"), "{:?}", painted.words);
        assert!(
            painted.said("v 78–102"),
            "a layer lane names its velocities"
        );
        assert_eq!(painted.whites.len(), 52, "a full piano's white keys");
    }

    /// Clicking a key auditions it: the root that answers it is asked for, and the line
    /// under the keyboard says what played.
    #[test]
    fn a_key_click_asks_for_the_root_that_answers_it_and_says_so() {
        let mut editor = Editor::new(facts().total * 2);
        let laid = editor.frame(Vec::new());
        let at = laid.white(62);

        let struck = editor.frame(press(at));
        assert_eq!(
            struck.asked,
            Some(Ask::Strike {
                root: 60,
                semitones: 2
            }),
            "root C4 answers D4, two semitones up"
        );

        let after = editor.frame(Vec::new());
        assert!(
            after.said("D4 at vel 90 → root C4 · shifted +2 st"),
            "{:?}",
            after.words
        );
    }

    /// Clicking a root's cell in the map opens that root's row, which is where its own
    /// facts and actions are.
    #[test]
    fn a_size_cell_click_opens_that_roots_row() {
        let mut editor = Editor::new(facts().total * 2);
        let laid = editor.frame(Vec::new());
        assert!(!laid.said("ANSWERS FROM"), "no row is open yet");

        // The size lane sits directly above the keyboard, a hair inside its own rect.
        let keyboard = laid.whites[0];
        let at = egui::pos2(laid.white(72).x, keyboard.top() - 10.0);
        editor.frame(press(at));
        let opened = editor.frame(Vec::new());
        assert!(opened.said("ANSWERS FROM"), "{:?}", opened.words);
        assert!(opened.said("Audition") && opened.said("Drop this root"));
        assert_eq!(editor.state.view.picked, Some(2), "root C5 is the third");
    }

    /// A lamp on a root's row takes that layer off that root alone, and leaves the row
    /// under it closed — the row-wide click target must not swallow the switch.
    #[test]
    fn a_lamp_on_a_roots_row_drops_that_layer_there_alone() {
        let mut editor = Editor::new(facts().total * 2);
        let laid = editor.frame(Vec::new());
        // Six trim switches, then one per lane, then three on each root's row.
        assert_eq!(laid.lamps.len(), 6 + 3 + 3 * 3, "every switch has a lamp");
        let softest_on_the_lowest_root = laid.lamps[9];

        editor.frame(press(softest_on_the_lowest_root.center()));
        let plan = &editor.state.plans[&editor.id];
        assert_eq!(plan.roots.get(&(ROOTS[0], LAYERS[2])), Some(&false));
        assert!(plan.layers.is_empty(), "every other root keeps it");
        assert!(
            editor.state.view.open_rows.is_empty(),
            "the row under the lamp did not open"
        );
    }

    /// The damper is one control, worded from the player's side: the key notes ring on
    /// above, or `none` where every key is damped.
    #[test]
    fn the_damper_limit_reads_as_a_key_or_none() {
        let mut editor = Editor::new(facts().total * 2);
        let every = editor.driven(Vec::new(), |plan| {
            plan.damper_top = Some(ALL_KEYS_DAMPED);
        });
        assert!(every.said("KEYS RING ON ABOVE"), "{:?}", every.words);
        assert!(every.said("none"), "{:?}", every.words);
        assert!(
            !every.words.iter().any(|word| word == "every key"),
            "{:?}",
            every.words
        );

        let some = editor.driven(Vec::new(), |plan| plan.damper_top = Some(90));
        assert!(some.said("F#6"), "{:?}", some.words);
        assert!(!some.said("none"), "{:?}", some.words);
    }

    /// The keyboard says where the damper stops reaching, and says nothing at all
    /// where it reaches every key.
    #[test]
    fn the_key_map_marks_the_damper_limit_only_where_a_key_rings_on() {
        let mut editor = Editor::new(facts().total * 2);
        let every = editor.driven(Vec::new(), |plan| {
            plan.damper_top = Some(ALL_KEYS_DAMPED);
        });
        assert!(!every.said("damper"), "{:?}", every.words);

        let some = editor.driven(Vec::new(), |plan| plan.damper_top = Some(90));
        assert!(some.said("damper"), "{:?}", some.words);
    }

    /// ⚠️ Throwing a switch copies nothing: the working bytes are the ones the library
    /// was saved as until something has to carry them. The header is what says an edit
    /// is standing, because the workspace reads the document as saved.
    #[test]
    fn a_switch_thrown_leaves_the_bytes_alone_and_the_header_says_so() {
        let mut editor = Editor::new(facts().total * 2);
        let saved = editor.workspace.get(editor.id).unwrap().saved.bytes.clone();

        editor.driven(Vec::new(), |plan| plan.switch_bank(Bank::Release, false));
        let held = editor.workspace.get(editor.id).unwrap();
        assert_eq!(held.bytes, saved, "no body was copied for a switch");
        assert!(!held.is_unsaved(), "and the workspace reads it as saved");
        assert!(editor.state.pending(editor.id));

        let said = editor
            .state
            .begin(editor.id, held, &editor.device.state)
            .state
            .expect("the header claims the plan");
        assert_eq!(said.words, "trimmed");
        assert_eq!(said.hint, "applied when this is saved, sent or exported");

        // And throwing it back is no edit at all.
        editor.driven(Vec::new(), |plan| plan.switch_bank(Bank::Release, true));
        assert!(!editor.state.pending(editor.id));
    }

    /// The name box holds what a save will write, so typing the stored name back into
    /// it clears the rename rather than leaving one standing over bytes that hold it.
    #[test]
    fn a_name_typed_back_to_the_stored_one_clears_the_rename() {
        let mut editor = Editor::new(facts().total * 2);
        editor.frame(Vec::new());
        let stored = facts().name;

        editor.typed("name", "Wurly 200A");
        assert_eq!(
            editor.boxes(),
            (Some("Wurly 200A".to_string()), None),
            "the box shows what a save would write",
        );
        assert!(editor.state.pending(editor.id));

        editor.typed("name", &stored);
        assert_eq!(editor.boxes(), (None, None), "the box is back on the bytes");
        assert!(
            editor.state.plans[&editor.id].is_empty(),
            "and the plan edits nothing at all: {:?}",
            editor.state.plans[&editor.id],
        );
        assert!(
            !editor.state.pending(editor.id),
            "so nothing is left to apply"
        );
    }

    /// A stored trim past what this editor's control reaches is shown as the file holds
    /// it. Pulling it back to the bound would retrim a stroke nobody touched.
    #[test]
    fn a_stored_trim_above_the_controls_reach_is_shown_rather_than_re_planned() {
        let mut held = plan();
        let stroke = (ROOTS[2], Bank::Attack.code(), LAYERS[0]);
        held.trims.insert(stroke, TRIM_REACH + 12);
        let saved = rebuild(&bytes(), &held).expect("the library takes the trim");

        let mut editor = Editor::of(saved, facts().total * 2);
        editor.frame(Vec::new());
        editor.state.view.picked = Some(2);
        editor.state.view.open_rows.insert(2);
        let opened = editor.frame(Vec::new());

        assert!(opened.said("ANSWERS FROM"), "the row is open");
        assert!(
            opened
                .words
                .iter()
                .any(|word| word.starts_with("60") && word.ends_with(" dB")),
            "{:?}",
            opened.words,
        );
        assert!(
            editor.state.plans[&editor.id].trims.is_empty(),
            "opening the row planned a retrim: {:?}",
            editor.state.plans[&editor.id].trims,
        );
    }

    /// A save lays the plan out first: the act waits, the bytes it makes are the ones a
    /// rebuild from the baseline makes, and only then is the document saved.
    #[test]
    fn a_save_waits_for_the_plan_to_be_laid_over_the_library() {
        let mut editor = Editor::new(facts().total * 2);
        let saved = editor.workspace.get(editor.id).unwrap().saved.bytes.clone();
        editor.driven(Vec::new(), |plan| plan.switch_bank(Bank::Release, false));

        let held = editor
            .state
            .hold(&editor.ctx, Act::SaveDoc(editor.id), &editor.workspace);
        assert!(held.is_none(), "the save is held back");

        let applied = editor.awaited();
        assert_eq!(applied.id, editor.id);
        assert_eq!(
            applied.made.expect("the plan stood").expect("it lays out"),
            rebuild(&saved, &editor.state.plans[&editor.id]).unwrap(),
            "what the apply made is what a rebuild from the baseline makes",
        );
        assert!(
            matches!(applied.acts.as_slice(), [Act::SaveDoc(id)] if *id == editor.id),
            "and the save is let go the moment it is laid",
        );
        assert!(
            !editor.state.pending(editor.id),
            "the bytes hold the plan now",
        );
    }

    /// One apply at a time: a second save while one runs waits on the same job and is
    /// let go with the first.
    #[test]
    fn two_saves_during_one_apply_are_one_apply() {
        let mut editor = Editor::new(facts().total * 2);
        editor.driven(Vec::new(), |plan| plan.switch_bank(Bank::Release, false));

        for _ in 0..2 {
            assert!(editor
                .state
                .hold(&editor.ctx, Act::SaveDoc(editor.id), &editor.workspace)
                .is_none());
        }
        assert_eq!(editor.state.held.len(), 2, "both are waiting");

        let applied = editor.awaited();
        assert_eq!(applied.acts.len(), 2, "on the one apply between them");
        assert!(editor.state.job.is_none(), "and nothing is left running");
    }

    /// ⚠️ An answer over a plan that has moved is of a library nobody asked for. It is
    /// dropped, and the apply starts again from the plan in hand.
    #[test]
    fn a_plan_changed_during_an_apply_starts_it_again() {
        let mut editor = Editor::new(facts().total * 2);
        let saved = editor.workspace.get(editor.id).unwrap().saved.bytes.clone();
        editor.driven(Vec::new(), |plan| plan.switch_bank(Bank::Release, false));
        assert!(editor
            .state
            .hold(&editor.ctx, Act::SaveDoc(editor.id), &editor.workspace)
            .is_none());

        editor.driven(Vec::new(), |plan| plan.switch_bank(Bank::Resonance, false));
        let wanted = editor.state.plans[&editor.id].clone();
        assert!(wanted.banks.contains(&Bank::Resonance));

        let dropped = editor.awaited();
        assert!(
            dropped.made.is_none(),
            "the first answer is of another plan"
        );
        assert!(dropped.acts.is_empty(), "so the save is still waiting");

        let applied = editor.awaited();
        assert_eq!(
            applied
                .made
                .expect("the plan stood")
                .expect("the second apply lays out"),
            rebuild(&saved, &wanted).unwrap(),
            "the bytes are of the plan in hand, not the one the job started on",
        );
        assert_eq!(applied.acts.len(), 1, "the save waited through both");
    }

    /// ⚠️ An edit undone while its apply ran leaves nothing to wait for. The save that
    /// was waiting still has to happen: held for a plan that no longer exists, it would
    /// never run at all.
    #[test]
    fn a_save_waiting_on_a_plan_that_was_undone_is_let_go() {
        let mut editor = Editor::new(facts().total * 2);
        editor.driven(Vec::new(), |plan| plan.switch_bank(Bank::Release, false));
        assert!(editor
            .state
            .hold(&editor.ctx, Act::SaveDoc(editor.id), &editor.workspace)
            .is_none());

        editor.driven(Vec::new(), |plan| plan.switch_bank(Bank::Release, true));
        assert!(!editor.state.pending(editor.id), "the edit is undone");

        let applied = editor.awaited();
        assert!(applied.made.is_none(), "the bytes it made are of nothing");
        assert_eq!(applied.acts.len(), 1, "and the save is let go regardless");
        assert!(editor.state.job.is_none(), "with nothing left to lay out");
    }

    /// ⚠️ The figures the sections read are of the library they were worked out from.
    /// Two documents can stand on the same plan — the empty one — and the second must
    /// not be drawn from the first's.
    #[test]
    fn opening_another_document_reads_the_figures_of_its_own_library() {
        let mut editor = Editor::new(facts().total * 2);
        editor.frame(Vec::new());
        assert_eq!(
            editor.state.summary.as_ref().map(|held| held.kept),
            Some(facts().total)
        );

        let mut dropped = plan();
        dropped.switch_bank(Bank::Release, false);
        let smaller = rebuild(&bytes(), &dropped).expect("the library lays out");
        let other = editor.workspace.ingest(
            "Other Piano.npno".into(),
            Origin::File("Other Piano.npno".into()),
            smaller.clone(),
            &mut editor.log,
        );
        editor.state.begin(
            other,
            editor.workspace.get(other).expect("it is open"),
            &editor.device.state,
        );
        assert_eq!(
            editor.state.summary.as_ref().map(|held| held.kept),
            Some(smaller.len() as u64),
            "the second document's figures are its own",
        );
    }

    /// A document that is removed takes its plan with it: nothing is left pending over
    /// bytes the workspace no longer holds, nothing is waiting on them, and no apply is
    /// still laying them out.
    #[test]
    fn a_removed_document_takes_its_plan_and_its_apply_with_it() {
        let mut editor = Editor::new(facts().total * 2);
        editor.driven(Vec::new(), |plan| plan.switch_bank(Bank::Release, false));
        assert!(editor
            .state
            .hold(&editor.ctx, Act::SaveDoc(editor.id), &editor.workspace)
            .is_none());
        assert!(editor.state.applying());

        let another = editor.workspace.ingest(
            "Other Piano.npno".into(),
            Origin::File("Other Piano.npno".into()),
            bytes(),
            &mut editor.log,
        );
        editor.state.forget(another);
        assert!(
            editor.state.open.is_some(),
            "another document's removal closed the open one",
        );

        editor.state.forget(editor.id);
        assert!(!editor.state.applying(), "nothing is still being laid out");
        assert!(!editor.state.pending(editor.id), "no plan is left standing");
        assert!(editor.state.held.is_empty(), "nor anything waiting on one");
    }

    /// ⚠️ An apply that answers over a document the workspace no longer holds made the
    /// bytes of a library nothing can carry. They are dropped rather than written back.
    #[test]
    fn an_apply_that_answers_for_a_removed_document_is_dropped() {
        let mut editor = Editor::new(facts().total * 2);
        editor.driven(Vec::new(), |plan| plan.switch_bank(Bank::Release, false));
        editor
            .state
            .start(&editor.ctx, editor.id, &editor.workspace);
        editor.workspace.remove(editor.id, &mut editor.log);

        let applied = editor.awaited();
        assert!(applied.made.is_none(), "nothing holds the bytes it made");
        assert!(applied.acts.is_empty(), "and nothing was waiting on them");
    }

    /// A save is the end of the plan: what was dropped is gone, and the rows show the
    /// file as it now is.
    #[test]
    fn a_save_starts_the_plan_again_from_the_bytes_that_were_saved() {
        let mut editor = Editor::new(facts().total * 2);
        editor.driven(Vec::new(), |plan| plan.switch_bank(Bank::Release, false));
        assert!(editor.state.plans[&editor.id]
            .banks
            .contains(&Bank::Release));

        editor.apply();
        let trimmed = editor.workspace.get(editor.id).unwrap();
        assert!(trimmed.bytes.len() < trimmed.saved.bytes.len());
        assert!(trimmed.is_unsaved(), "the apply is what makes it unsaved");

        editor.workspace.mark_saved(editor.id);
        editor.frame(Vec::new());
        assert_eq!(
            editor.state.plans[&editor.id],
            Plan {
                against: editor.state.plans[&editor.id].against,
                ..Plan::default()
            },
            "the plan starts again from what is now saved",
        );
        assert!(!editor.workspace.get(editor.id).unwrap().is_unsaved());
    }

    /// A library whose audio the codec can read: the same three roots of three attack
    /// layers, each a short tone.
    ///
    /// ⚠️ [`synthetic::Build`] fills its audio spans rather than coding them, and
    /// [`npno::codec::decode`] refuses that, so a test about hearing a stroke has to
    /// code its own.
    fn coded() -> Vec<u8> {
        use nord_format::formats::npno::encode::{self, Donor, Options, Recording, Rules};

        let recordings: Vec<Recording> = ROOTS
            .into_iter()
            .flat_map(|root| {
                LAYERS.into_iter().map(move |layer| Recording {
                    root,
                    bank: Bank::Attack,
                    layer,
                    channels: vec![(0..1024)
                        .map(|frame| {
                            let hz = f32::from(root) + f32::from(layer);
                            ((frame as f32 / hz).sin() * 8_000.0) as i16
                        })
                        .collect()],
                })
            })
            .collect();
        let library = encode::build(
            &Donor::Rules(Rules::default()),
            &Options::new("Test Piano"),
            &recordings,
        )
        .expect("the encoder codes the takes");
        materialise(&library).expect("it lays out")
    }

    /// Every decode is one stroke: the loudest attack layer of that root the plan keeps,
    /// and the least recently heard goes once nine of them have been asked for.
    #[test]
    fn one_root_decodes_one_stroke_and_the_cache_keeps_the_last_eight() {
        let ctx = egui::Context::default();
        let mut workspace = Workspace::new(ctx.clone());
        let mut log = Log::default();
        let id = workspace.ingest(
            "Test Piano.npno".into(),
            Origin::File("Test Piano.npno".into()),
            coded(),
            &mut log,
        );
        let entity = workspace.get(id).expect("it is open");
        let mut state = State::default();
        state.begin(id, entity, &Device::new(ctx).state);

        state.decode(entity, ROOTS[0]).expect("it decodes");
        assert_eq!(
            state.audio.strokes.len(),
            1,
            "one stroke, not one root's worth",
        );
        let loudest = state.audio.newest(ROOTS[0]).expect("it is held").0;
        assert_eq!(loudest, (ROOTS[0], Bank::Attack.code(), LAYERS[0]));
        assert_eq!(
            state.sound(ROOTS[0]).expect("it is ready").name,
            crate::workspace::stroke_wav_name(
                "Test Piano",
                ROOTS[0],
                Bank::Attack.code(),
                LAYERS[0]
            ),
        );

        state.decode(entity, ROOTS[1]).expect("it decodes");
        assert_eq!(
            state.audio.newest(ROOTS[0]).map(|held| held.0),
            Some(loudest),
            "another root's decode left this one where it was",
        );

        // Nine strokes: every root's three attack layers, reached by dropping the
        // louder ones on that root as it goes.
        let mut plan = state.plans[&id].clone();
        for root in ROOTS {
            for layer in LAYERS {
                state.plans.insert(id, plan.clone());
                let asked = state.decode(entity, root);
                assert!(asked.is_ok(), "{root} at layer {layer}: {asked:?}");
                assert_eq!(
                    state.audio.newest(root).expect("it is held").0,
                    (root, Bank::Attack.code(), layer),
                    "the loudest layer the plan keeps is what plays",
                );
                plan.roots.insert((root, layer), false);
            }
        }
        assert_eq!(state.audio.strokes.len(), KEPT_STROKES);
        assert!(
            !state.audio.strokes.iter().any(|(held, _)| *held == loudest),
            "the first stroke asked for is the first to go",
        );
    }

    /// Checking a plan and laying it out are the same edit: the body the borrowed
    /// library says it would occupy is the body the bytes come out holding.
    #[test]
    fn a_planned_library_is_the_size_of_the_bytes_it_makes() {
        let saved = bytes();
        let around = saved.len()
            - planned(&saved, &plan())
                .expect("the baseline plans")
                .body_len()
                .expect("it lays out");

        let mut plan = plan();
        plan.switch_bank(Bank::Release, false);
        let body = planned(&saved, &plan)
            .expect("the library takes it")
            .body_len()
            .expect("it lays out");
        assert_eq!(rebuild(&saved, &plan).unwrap().len(), body + around);
        assert!(body + around < saved.len(), "the release bank is gone");
    }
}