drawbar 0.7.0

Your Nord's sounds, in a window: browse, edit and send programs, samples and pianos, in the browser or on the desktop
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
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
//! One registry body as a document: the sections it reads in, the cell every field is
//! drawn as, and the morph lens over the lot.
//!
//! The division is `nord_format::panel`'s where the library authors one, the app's own
//! menu order for a settings body, and the registry's own path prefixes for a body
//! nothing has laid out. The cell is one renderer per [`ControlKind`], so a field the
//! library learns arrives here already drawn rather than waiting for a table here to
//! name it.
//!
//! Nothing here clamps: a moved control hands back the spelling `set_field` takes, the
//! document applies every set of the frame to a fresh decode, and a refused value leaves
//! the file untouched with the library's own words on screen.

use std::collections::{HashMap, HashSet};

use eframe::egui;
use nord_format::fields::{ControlKind, Field, PackedOrder, Unit};
use nord_format::panel::{Panel, Section as Placed, Selection};

use super::controls::{self, Ctx, Sets};
use super::keys::RADIUS;
use super::panel::{PianoLookup, PIANO_MODEL};
use crate::app;
use crate::icon::{icon, Glyph};
use crate::workspace::LocalEntity;
use crate::{drawbar_widget, knob, led, strings};

/// The two halves of the Electro 5 transpose control — see [`transpose`].
const TRANSPOSE_ENABLED: &str = "center_panel.transpose_enabled";
const TRANSPOSE: &str = "center_panel.transpose";

/// The name over a control, the edited dot beside it, and the morph dots below.
const LABEL: f32 = 9.5;
const DOT: f32 = 6.0;

/// A nested group's title, and the chip a nav row is made of.
const CARD_TITLE: f32 = 11.5;
const CHIP: f32 = 20.0;
const CHIP_TEXT: f32 = 11.0;
const COUNT_TEXT: f32 = 9.5;

/// The stepped counter a signed offset is set with: its square buttons, the room its
/// number keeps between them, and the size both are set in.
const NUDGE: f32 = 17.0;
const COUNTER: f32 = 22.0;
const COUNTER_TEXT: f32 = 11.0;

/// The reading beside a knob, and the caption that stands where there is none.
const READING: f32 = 10.0;

/// How long a legal-value list stays a menu for an unclassified field. Past it a
/// contiguous run turns instead.
const MENU_MAX: usize = 12;

/// The performance controls a morph slot may belong to: the suffix the declaration binds
/// on, the word for it, and the letter under a control.
///
/// ⚠️ The order is the lens order and the dot order; both are read as `W · AT · P`.
const SLOTS: [(&str, &str, &str); 3] = [
    ("_wheel", "Wheel", "W"),
    ("_aftertouch", "Aftertouch", "AT"),
    ("_ctrl_pedal", "Control pedal", "P"),
];

/// What the field document holds that is not an edit: which morph lens is on, where the
/// reader is, and the box a wide field is being typed into.
///
/// ⚠️ An edit is never here. Every set lands on the working copy in the frame it is
/// made, so leaving the tab drops all of this and none of that.
#[derive(Default)]
pub struct State {
    /// The morph slot every morphed control is showing, or the panel's own values.
    lens: Option<usize>,
    /// The section the reader is in, and the one a nav chip asked to be taken to.
    active: Option<String>,
    jump: Option<String>,
    /// Where each section's top was painted, and the top of the region they scroll in.
    /// Read a frame later, which is what lets a chip track the scroll.
    tops: Vec<(String, f32)>,
    view_top: f32,
    /// The decode of the bytes this document was last saved as, and the paths whose
    /// value the working copy spells differently — see [`crate::fields::changed`].
    settled: Vec<Field>,
    pending: Vec<String>,
    /// The bytes `settled` and `pending` were read from.
    read: Option<(u64, u64, Option<u32>)>,
}

impl State {
    /// Read the saved bytes and the working ones, where they have moved since last time.
    ///
    /// ⚠️ Both decodes walk the whole body, so they happen when the bytes change and not
    /// per frame: a Stage 4 declares eight hundred fields.
    pub fn follow(&mut self, entity: &LocalEntity) {
        let read = (entity.id, entity.stamp, entity.saved.crc32);
        if self.read == Some(read) {
            return;
        }
        self.read = Some(read);
        self.settled = crate::fields::decoded(&entity.saved.bytes).unwrap_or_default();
        self.pending = crate::fields::changed(&entity.saved.bytes, &entity.bytes);
    }

    /// The paths the working copy spells differently from the saved bytes.
    pub fn pending(&self) -> &[String] {
        &self.pending
    }

    /// The saved bytes' fields, which are what the Advanced table reads as raw.
    pub fn settled(&self) -> &[Field] {
        &self.settled
    }

    /// Turn the lens on as the nav row would, for a test that cannot click it.
    #[cfg(test)]
    pub(super) fn pretend_lens(&mut self, slot: usize) {
        self.lens = Some(slot);
    }
}

/// How a body arrived at its sections.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Shape {
    /// The library's own layout for this body.
    Authored { exhaustive: bool },
    /// The app's menu order, for the settings body the library lays out nowhere.
    Menus,
    /// The registry's own path prefixes, for a body nothing has laid out.
    Flat,
}

/// One registry body, divided the way it will be drawn.
pub struct Doc<'a> {
    sections: Vec<Sect<'a>>,
    /// Registered fields no group named, in registry order.
    leftovers: Vec<&'a Field>,
    /// The titles of the top-level groups the instrument is not using.
    idle: Vec<&'static str>,
    shape: Shape,
    /// Every field a section draws, so the Advanced table can flag the rest.
    shown: HashSet<&'a str>,
    /// The selectors that pick between stored alternatives. Each is the head of the
    /// cards it picks between, so none of them is also a cell.
    picks: HashSet<&'a str>,
    /// Each parameter's morph slots, by the parameter's path.
    morphs: HashMap<&'a str, [Option<&'a Field>; SLOTS.len()]>,
    fields: usize,
    slots: usize,
}

/// One section of the document, and the cards under it.
struct Sect<'a> {
    /// What a nav chip scrolls to, which two sections of the same name must not share.
    key: String,
    title: String,
    fields: Vec<&'a Field>,
    nested: Vec<Sect<'a>>,
    /// The selection that makes this one of several stored alternatives play.
    pick: Option<&'a Selection>,
    selected: bool,
    /// The titles of the groups under this one the instrument is not using.
    idle: Vec<&'static str>,
    count: usize,
}

/// A parameter and the performance controls that morph it.
struct Part<'a> {
    field: &'a Field,
    morphs: [Option<&'a Field>; SLOTS.len()],
}

/// What one cell of a section stands for.
enum Cell<'a> {
    One(Part<'a>),
    /// Nine single-bar drawbar fields, ranked 1..=9 under one prefix, as one register.
    Register(Vec<Part<'a>>),
    /// The Electro 5 transpose lamp and amount, which neither reads without the other.
    Transpose,
}

/// The document a decoded body is drawn as.
pub fn of<'a>(decoded: &nord_format::Entity, fields: &'a [Field]) -> Doc<'a> {
    let morphs = slots_of(fields);
    let mut doc = match nord_format::panel::of(decoded) {
        Some(layout) => authored(layout, fields, morphs),
        None if crate::fields::is_electro5_settings(decoded) => menus(fields, morphs),
        None => flat(fields, morphs),
    };
    doc.fields = fields.len();
    doc.slots = fields
        .iter()
        .filter(|field| matches!(field.spec.control, ControlKind::Morph { .. }))
        .count();
    for section in &mut doc.sections {
        count(section, &doc.morphs);
    }
    doc.shown = doc.sections.iter().flat_map(paths).collect();
    let lensed = lensed(&doc.morphs, &doc.shown);
    doc.shown.extend(lensed);
    doc.picks = doc.sections.iter().flat_map(selectors).collect();
    doc
}

impl Doc<'_> {
    /// Whether the Edit face draws this path at all, the morph slots a lens puts under a
    /// parameter's own control included.
    pub fn shows(&self, path: &str) -> bool {
        self.shown.contains(path)
    }

    pub fn shape(&self) -> Shape {
        self.shape
    }

    /// How many fields there are, and how many of them are morph slots.
    pub fn tally(&self) -> (usize, usize) {
        (self.fields, self.slots)
    }

    /// How many fields no group named, and how many of those the strings table names —
    /// which is all the "Also stored" section holds.
    pub fn unplaced(&self) -> (usize, usize) {
        let named = self
            .leftovers
            .iter()
            .filter(|field| strings::known(&field.path))
            .count();
        (self.leftovers.len(), named)
    }
}

/// Each parameter's three morph slots, found through the declaration rather than by
/// matching names.
///
/// ⚠️ Indexed rather than searched: a Stage body declares three hundred slots among
/// nine hundred fields, and this is rebuilt every frame.
fn slots_of(fields: &[Field]) -> HashMap<&str, [Option<&Field>; SLOTS.len()]> {
    let at: HashMap<&str, &Field> = fields
        .iter()
        .map(|field| (field.path.as_str(), field))
        .collect();
    let mut out: HashMap<&str, [Option<&Field>; SLOTS.len()]> = HashMap::new();
    for slot in fields {
        let Some(parent) = slot.spec.morph_parent() else {
            continue;
        };
        let Some(parent) = at.get(parent.as_str()) else {
            continue;
        };
        let Some(which) = which_slot(&slot.path) else {
            continue;
        };
        out.entry(parent.path.as_str()).or_default()[which] = Some(slot);
    }
    out
}

/// Which performance control a slot belongs to, off the suffix the declaration binds on.
fn which_slot(path: &str) -> Option<usize> {
    let leaf = path.rsplit('.').next().unwrap_or(path);
    SLOTS
        .iter()
        .position(|(suffix, _, _)| leaf.ends_with(suffix))
}

fn authored<'a>(
    layout: &'a Panel,
    fields: &'a [Field],
    morphs: HashMap<&'a str, [Option<&'a Field>; SLOTS.len()]>,
) -> Doc<'a> {
    let resolved = layout.resolve(fields);
    let mut sections = Vec::new();
    let mut idle = Vec::new();
    for (nth, placed) in resolved.sections.iter().enumerate() {
        if !placed.relevant {
            idle.push(placed.group.title);
            continue;
        }
        let mut nested = Vec::new();
        let mut under = Vec::new();
        hoist(&placed.groups, None, fields, &mut nested, &mut under);
        sections.push(Sect {
            key: format!("s{nth}"),
            title: placed.group.title.to_string(),
            fields: placed.fields.clone(),
            nested,
            pick: None,
            selected: true,
            idle: under,
            count: 0,
        });
    }
    let named: Vec<&Field> = resolved
        .leftovers
        .iter()
        .copied()
        .filter(|field| strings::known(&field.path))
        .collect();
    if !named.is_empty() {
        sections.push(plain_sect(
            "also".to_string(),
            strings::Section::Other.title(),
            named,
        ));
    }
    Doc {
        sections,
        leftovers: resolved.leftovers,
        idle,
        shape: Shape::Authored {
            exhaustive: layout.exhaustive,
        },
        shown: HashSet::new(),
        picks: HashSet::new(),
        morphs,
        fields: 0,
        slots: 0,
    }
}

/// The groups under a section, with the third level flattened onto the second.
///
/// Nesting has no depth limit and a card inside a card inside a card reads as an
/// indent rather than as a division, so a grandchild becomes a sibling called
/// `Parent · Child`.
fn hoist<'a>(
    groups: &[Placed<'a>],
    under: Option<&str>,
    fields: &'a [Field],
    into: &mut Vec<Sect<'a>>,
    idle: &mut Vec<&'static str>,
) {
    for group in groups {
        if !group.relevant {
            idle.push(group.group.title);
            continue;
        }
        let title = match under {
            Some(parent) => format!("{parent} · {}", group.group.title),
            None => group.group.title.to_string(),
        };
        let pick = group.group.selected_by.as_ref();
        into.push(Sect {
            key: String::new(),
            title: title.clone(),
            fields: group.fields.clone(),
            nested: Vec::new(),
            pick,
            selected: pick.is_some_and(|selection| selection.selected(fields)),
            idle: Vec::new(),
            count: 0,
        });
        hoist(&group.groups, Some(&title), fields, into, idle);
    }
}

/// The settings body, in the order the instrument's own menus run.
///
/// ⚠️ The library lays out no settings body, so the division is this app's own table —
/// see `strings::FIELDS`.
fn menus<'a>(
    fields: &'a [Field],
    morphs: HashMap<&'a str, [Option<&'a Field>; SLOTS.len()]>,
) -> Doc<'a> {
    let sections = strings::SETTINGS_SECTIONS
        .iter()
        .enumerate()
        .filter_map(|(nth, section)| {
            let rows: Vec<&Field> = fields
                .iter()
                .filter(|field| strings::section(&field.path) == *section)
                .collect();
            (!rows.is_empty()).then(|| plain_sect(format!("m{nth}"), section.title(), rows))
        })
        .collect();
    Doc {
        sections,
        leftovers: Vec::new(),
        idle: Vec::new(),
        shape: Shape::Menus,
        shown: HashSet::new(),
        picks: HashSet::new(),
        morphs,
        fields: 0,
        slots: 0,
    }
}

/// Any other registry-backed body: its own path prefixes as sections, because nothing
/// here knows how that instrument's panel is divided but the registry does say which
/// fields belong together.
fn flat<'a>(
    fields: &'a [Field],
    morphs: HashMap<&'a str, [Option<&'a Field>; SLOTS.len()]>,
) -> Doc<'a> {
    let sections = prefixes(fields)
        .into_iter()
        .enumerate()
        .map(|(nth, group)| plain_sect(format!("f{nth}"), &group.title, group.rows))
        .collect();
    Doc {
        sections,
        leftovers: Vec::new(),
        idle: Vec::new(),
        shape: Shape::Flat,
        shown: HashSet::new(),
        picks: HashSet::new(),
        morphs,
        fields: 0,
        slots: 0,
    }
}

fn plain_sect<'a>(key: String, title: &str, rows: Vec<&'a Field>) -> Sect<'a> {
    Sect {
        key,
        title: title.to_string(),
        fields: rows,
        nested: Vec::new(),
        pick: None,
        selected: true,
        idle: Vec::new(),
        count: 0,
    }
}

/// One titled run of a field list.
struct Group<'a> {
    /// What these fields share, which is not what their title is unique by.
    key: String,
    title: String,
    rows: Vec<&'a Field>,
}

/// The sections a field list falls into.
///
/// A nested body's fields are contiguous and share a dotted prefix, which is the
/// division the registry itself makes. A prefix too long to read in one run is divided
/// again on the leading word of each field's own name — the Stage bodies spell their
/// sections there (`slot_a.organ_preset_1_drawbar_1`) — and a word that recurs later
/// joins the division it opened rather than starting a second one.
fn prefixes(fields: &[Field]) -> Vec<Group<'_>> {
    let mut out: Vec<Group> = Vec::new();
    for field in fields {
        let prefix = field.path.rsplit_once('.').map_or("", |(head, _)| head);
        match out.last_mut() {
            Some(group) if group.key == prefix => group.rows.push(field),
            _ => out.push(Group {
                key: prefix.to_string(),
                title: match prefix.is_empty() {
                    true => strings::UNPREFIXED.to_string(),
                    false => strings::title(prefix),
                },
                rows: vec![field],
            }),
        }
    }
    out.into_iter().flat_map(divide).collect()
}

/// How many fields a section may hold before it is divided again on each field's own
/// leading word.
const SPLIT_ABOVE: usize = 128;

fn divide(group: Group<'_>) -> Vec<Group<'_>> {
    if group.rows.len() <= SPLIT_ABOVE {
        return vec![group];
    }
    let mut out: Vec<Group> = Vec::new();
    for field in group.rows {
        let leaf = field.path.rsplit('.').next().unwrap_or(&field.path);
        let word = leaf.split('_').next().unwrap_or(leaf);
        let key = format!("{}.{word}", group.key);
        match out.iter().position(|part| part.key == key) {
            Some(at) => out[at].rows.push(field),
            None => out.push(Group {
                title: match group.key.is_empty() {
                    true => strings::title(word),
                    false => format!("{}{word}", group.title),
                },
                key,
                rows: vec![field],
            }),
        }
    }
    out
}

/// How many registry fields a section stands for: its own, the morph slots riding on
/// them, and everything under it.
fn count(section: &mut Sect<'_>, morphs: &HashMap<&str, [Option<&Field>; SLOTS.len()]>) {
    let mut total = section.fields.len();
    for field in &section.fields {
        total += morphs.get(field.path.as_str()).map_or(0, |slots| {
            slots.iter().filter(|slot| slot.is_some()).count()
        });
    }
    for nested in &mut section.nested {
        count(nested, morphs);
        total += nested.count;
    }
    section.count = total;
}

/// The selectors that pick between a section's stored alternatives, however deep the
/// layout nested them before they were flattened onto one row.
fn selectors<'a>(section: &Sect<'a>) -> Vec<&'a str> {
    let mut out: Vec<&str> = section
        .pick
        .map(|selection| selection.field)
        .into_iter()
        .collect();
    for nested in &section.nested {
        out.extend(selectors(nested));
    }
    out
}

/// The morph slots the drawn parameters carry.
///
/// ⚠️ A slot is no section's own field — the library's layout leaves it to the parameter
/// it moves — so the face that drew the parameter is the face that draws the slot, under
/// the lens.
fn lensed<'a>(
    morphs: &HashMap<&'a str, [Option<&'a Field>; SLOTS.len()]>,
    shown: &HashSet<&'a str>,
) -> Vec<&'a str> {
    let mut out = Vec::new();
    for (parent, slots) in morphs {
        if shown.contains(parent) {
            out.extend(
                slots
                    .iter()
                    .copied()
                    .flatten()
                    .map(|slot| slot.path.as_str()),
            );
        }
    }
    out
}

/// Every path a section draws, its nested cards included.
fn paths<'a>(section: &Sect<'a>) -> Vec<&'a str> {
    let mut out: Vec<&str> = section
        .fields
        .iter()
        .map(|field| field.path.as_str())
        .collect();
    for nested in &section.nested {
        out.extend(paths(nested));
    }
    out
}

/// The row above the scroll region: one chip per section, and the morph lens where the
/// body has morph slots.
///
/// ⚠️ It wraps rather than scrolling sideways. The lens is at the right of it, and a row
/// that clipped would put the lens out of reach on a narrow window.
pub fn nav(ui: &mut egui::Ui, state: &mut State, doc: &Doc<'_>) {
    if doc.sections.is_empty() {
        return;
    }
    let quiet = app::caption(ui.visuals());
    ui.horizontal_wrapped(|ui| {
        ui.spacing_mut().item_spacing = egui::vec2(4.0, 2.0);
        for section in &doc.sections {
            let active = state.active.as_deref() == Some(section.key.as_str());
            if nav_chip(ui, &section.title, &section.count.to_string(), active).clicked() {
                state.jump = Some(section.key.clone());
            }
        }
        if doc.slots == 0 {
            return;
        }
        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
            ui.spacing_mut().item_spacing.x = 4.0;
            for (nth, (_, word, _)) in SLOTS.iter().enumerate().rev() {
                let count = stored_targets(doc, nth);
                if nav_chip(ui, word, &count.to_string(), state.lens == Some(nth)).clicked() {
                    state.lens = Some(nth);
                }
            }
            if nav_chip(ui, "Panel", "", state.lens.is_none()).clicked() {
                state.lens = None;
            }
            ui.label(
                egui::RichText::new("MORPH")
                    .font(egui::FontId::proportional(COUNT_TEXT))
                    .color(quiet),
            );
        });
    });
}

/// How many parameters have a target stored under one performance control.
fn stored_targets(doc: &Doc<'_>, slot: usize) -> usize {
    doc.morphs
        .values()
        .filter(|slots| slots[slot].is_some_and(|field| !is_neutral(field)))
        .count()
}

fn nav_chip(ui: &mut egui::Ui, title: &str, count: &str, active: bool) -> egui::Response {
    let visuals = ui.visuals().clone();
    let painter = ui.painter().clone();
    let ink = match active {
        true => visuals.text_color(),
        false => visuals.weak_text_color(),
    };
    let word = painter.layout_no_wrap(
        title.to_string(),
        egui::FontId::proportional(CHIP_TEXT),
        ink,
    );
    let tail = (!count.is_empty()).then(|| {
        painter.layout_no_wrap(
            count.to_string(),
            egui::FontId::monospace(COUNT_TEXT),
            match active {
                true => app::accent(&visuals),
                false => app::caption(&visuals),
            },
        )
    });
    let width = 16.0 + word.size().x + tail.as_ref().map_or(0.0, |laid| 5.0 + laid.size().x);
    let (rect, response) = ui.allocate_exact_size(egui::vec2(width, CHIP), egui::Sense::click());
    if active || response.hovered() {
        let fill = match active {
            true => visuals.widgets.active.weak_bg_fill,
            false => visuals.widgets.hovered.weak_bg_fill,
        };
        painter.rect_filled(rect, RADIUS, fill);
    }
    let mut x = rect.left() + 8.0;
    painter.galley(
        egui::pos2(x, rect.center().y - word.size().y / 2.0),
        word.clone(),
        ink,
    );
    x += word.size().x + 5.0;
    if let Some(tail) = tail {
        painter.galley(
            egui::pos2(x, rect.center().y - tail.size().y / 2.0),
            tail,
            ink,
        );
    }
    response
}

/// Draw the whole document. Returns whether something asked for the Advanced face.
pub fn body(
    ui: &mut egui::Ui,
    ctx: &Ctx,
    state: &mut State,
    doc: &Doc<'_>,
    piano: &mut PianoLookup,
    sets: &mut Sets,
) -> bool {
    let mut to_advanced = false;
    state.view_top = ui.clip_rect().top();
    let mut tops = Vec::with_capacity(doc.sections.len());
    if state.lens.is_some() {
        banner(ui, state);
    }
    for section in &doc.sections {
        let top = ui.cursor().top();
        if state.jump.as_deref() == Some(section.key.as_str()) {
            ui.scroll_to_rect(
                egui::Rect::from_min_size(ui.cursor().min, egui::vec2(1.0, 1.0)),
                Some(egui::Align::TOP),
            );
        }
        tops.push((section.key.clone(), top));
        to_advanced |= drew(ui, ctx, state, doc, section, piano, sets);
        ui.add_space(6.0);
        ui.separator();
    }
    state.jump = None;
    state.tops = tops;
    state.active = active(state);
    to_advanced |= foot(ui, doc);
    to_advanced
}

/// The section whose top is the last one above the region's own top.
fn active(state: &State) -> Option<String> {
    state
        .tops
        .iter()
        .rfind(|(_, top)| *top <= state.view_top + 1.0)
        .or_else(|| state.tops.first())
        .map(|(key, _)| key.clone())
}

/// The strip that says the panel values are not what is on screen.
fn banner(ui: &mut egui::Ui, state: &mut State) {
    let Some(slot) = state.lens else { return };
    let visuals = ui.visuals().clone();
    let drawn = egui::Frame::new()
        .fill(visuals.window_fill)
        .inner_margin(egui::Margin::symmetric(8, 6))
        .show(ui, |ui| {
            ui.set_width(ui.available_width());
            ui.horizontal_wrapped(|ui| {
                ui.spacing_mut().item_spacing.x = 8.0;
                icon(ui, Glyph::ScanEye, 13.0, app::accent(&visuals));
                ui.label(
                    egui::RichText::new(format!(
                        "Showing {} targets. A lit outline is a control with a morph stored, a \
                         grey one is neutral, and editing here writes the morph slot rather than \
                         the panel value.",
                        SLOTS[slot].1.to_lowercase()
                    ))
                    .font(egui::FontId::proportional(CHIP_TEXT))
                    .color(visuals.text_color()),
                );
                if ui
                    .small_button("Back to the panel")
                    .on_hover_text("the values the instrument holds with nothing moving")
                    .clicked()
                {
                    state.lens = None;
                }
            });
        });
    let rule = egui::Stroke::new(1.0_f32, app::accent(&visuals));
    let rect = drawn.response.rect;
    ui.painter()
        .hline(rect.x_range(), rect.bottom() - 0.5, rule);
}

/// One section: its own controls, the cards under it, the alternatives beside each
/// other, and the line that says what is stored and idle.
fn drew(
    ui: &mut egui::Ui,
    ctx: &Ctx,
    state: &State,
    doc: &Doc<'_>,
    section: &Sect<'_>,
    piano: &mut PianoLookup,
    sets: &mut Sets,
) -> bool {
    let quiet = app::caption(ui.visuals());
    let reading = match section.count {
        1 => "1 field".to_string(),
        n => format!("{n} fields"),
    };
    controls::heading(ui, &section.title, "", Some((&reading, quiet)));
    if section.fields.iter().any(|field| field.path == PIANO_MODEL) {
        piano.ui(ui);
    }
    cells(ui, ctx, state, doc, &section.fields, piano, sets);

    let (alternatives, cards): (Vec<&Sect>, Vec<&Sect>) = section
        .nested
        .iter()
        .partition(|nested| nested.pick.is_some());
    for card in cards {
        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::same(8))
            .outer_margin(egui::Margin::symmetric(12, 4))
            .show(ui, |ui| {
                ui.set_width(ui.available_width() - 24.0);
                card_title(ui, &card.title, None);
                cells(ui, ctx, state, doc, &card.fields, piano, sets);
            });
    }
    if !alternatives.is_empty() {
        side_by_side(ui, ctx, state, doc, &alternatives, piano, sets);
    }
    idle_line(ui, &section.idle)
}

/// The stored alternatives, side by side: one is playing and the other is kept.
///
/// ⚠️ Both stay on screen. The selector that picks between them is the head of each
/// card, and drawing only the one in use would put the switch inside the thing it
/// switches.
fn side_by_side(
    ui: &mut egui::Ui,
    ctx: &Ctx,
    state: &State,
    doc: &Doc<'_>,
    alternatives: &[&Sect<'_>],
    piano: &mut PianoLookup,
    sets: &mut Sets,
) {
    ui.horizontal_wrapped(|ui| {
        ui.spacing_mut().item_spacing = egui::vec2(10.0, 10.0);
        for alternative in alternatives {
            let stroke = match alternative.selected {
                true => app::accent(ui.visuals()),
                false => ui.visuals().widgets.noninteractive.bg_stroke.color,
            };
            let mut picked = false;
            let card = egui::Frame::new()
                .fill(ui.visuals().window_fill)
                .stroke(egui::Stroke::new(1.0_f32, stroke))
                .corner_radius(RADIUS)
                .inner_margin(egui::Margin::same(8))
                .show(ui, |ui| {
                    // The cards stand side by side, so each one stacks its own head over
                    // its own controls rather than inheriting the row they sit in.
                    ui.vertical(|ui| {
                        if alternative.pick.is_some() {
                            picked |=
                                card_title(ui, &alternative.title, Some(alternative.selected));
                        }
                        if !alternative.selected {
                            ui.set_opacity(0.45);
                        }
                        cells(ui, ctx, state, doc, &alternative.fields, piano, sets);
                    });
                });
            let Some(selection) = alternative.pick else {
                continue;
            };
            picked |= clicked_in(ui, card.response.rect);
            if picked && !alternative.selected {
                sets.push((selection.field.to_string(), selection.value.to_string()));
            }
        }
    });
}

/// Whether a click landed anywhere in `card`, whichever of its own controls took it.
///
/// ⚠️ The click is read off the pointer rather than claimed as a widget of its own:
/// a card-sized target over the controls would swallow every drawbar in it, and one
/// under them would hear only the clicks that missed. Pulling a drawbar of the stored
/// registration is a click on that card, and picks it.
fn clicked_in(ui: &egui::Ui, card: egui::Rect) -> bool {
    ui.rect_contains_pointer(card) && ui.input(|input| input.pointer.primary_clicked())
}

/// A card's own head. With `playing` it is the selector as well, and returns whether it
/// was clicked.
fn card_title(ui: &mut egui::Ui, title: &str, playing: Option<bool>) -> bool {
    let visuals = ui.visuals().clone();
    let mut clicked = false;
    ui.horizontal(|ui| {
        ui.spacing_mut().item_spacing.x = 8.0;
        if let Some(playing) = playing {
            let lit = match playing {
                true => app::accent(&visuals),
                false => app::unlit(&visuals),
            };
            clicked |= app::dot(ui, lit, 8.0).clicked();
        }
        clicked |= ui
            .add(
                egui::Label::new(
                    egui::RichText::new(title)
                        .font(egui::FontId::new(CARD_TITLE, app::bold()))
                        .color(visuals.text_color()),
                )
                .sense(match playing.is_some() {
                    true => egui::Sense::click(),
                    false => egui::Sense::hover(),
                }),
            )
            .clicked();
        match playing {
            Some(true) => {
                ui.label(
                    egui::RichText::new("playing")
                        .font(egui::FontId::proportional(READING))
                        .color(app::good(&visuals)),
                );
            }
            Some(false) => {
                clicked |= ui
                    .add(
                        egui::Label::new(
                            egui::RichText::new("select")
                                .font(egui::FontId::proportional(READING))
                                .color(app::caption(&visuals)),
                        )
                        .sense(egui::Sense::click()),
                    )
                    .on_hover_text("the other stays stored, it is simply not the one playing")
                    .clicked();
            }
            None => {}
        }
    });
    ui.add_space(4.0);
    clicked
}

/// The one line a section ends with when something under it is stored and idle.
fn idle_line(ui: &mut egui::Ui, idle: &[&'static str]) -> bool {
    if idle.is_empty() {
        return false;
    }
    let quiet = app::caption(ui.visuals());
    let mut asked = false;
    ui.horizontal_wrapped(|ui| {
        ui.spacing_mut().item_spacing.x = 6.0;
        ui.add_space(12.0);
        icon(ui, Glyph::EyeOff, 11.0, quiet);
        ui.label(
            egui::RichText::new(format!(
                "{} {} stored but not in use for the state this file holds — kept, not cleared.",
                listed(idle),
                match idle.len() {
                    1 => "is",
                    _ => "are",
                }
            ))
            .font(egui::FontId::proportional(READING))
            .color(quiet),
        );
        asked = ui
            .add(
                egui::Label::new(
                    egui::RichText::new("Advanced")
                        .font(egui::FontId::proportional(READING))
                        .color(app::accent(ui.visuals())),
                )
                .sense(egui::Sense::click()),
            )
            .on_hover_text("every field, including the ones this face does not draw")
            .clicked();
    });
    asked
}

/// `A`, `A and B`, `A, B and C`.
fn listed(words: &[&str]) -> String {
    match words {
        [] => String::new(),
        [one] => (*one).to_string(),
        [head @ .., last] => format!("{} and {last}", head.join(", ")),
    }
}

/// The line under the last section: what the layout does not place.
fn foot(ui: &mut egui::Ui, doc: &Doc<'_>) -> bool {
    let quiet = app::caption(ui.visuals());
    let mut asked = false;
    if !doc.idle.is_empty() {
        asked |= idle_line(ui, &doc.idle);
    }
    let unplaced = doc.leftovers.len();
    if matches!(doc.shape, Shape::Authored { exhaustive: false }) && unplaced > 0 {
        ui.horizontal_wrapped(|ui| {
            ui.spacing_mut().item_spacing.x = 6.0;
            ui.add_space(12.0);
            icon(ui, Glyph::CircleAlert, 11.0, quiet);
            ui.label(
                egui::RichText::new(format!(
                    "{unplaced} fields the layout does not place — under Advanced, and under \
                     {} once the strings table names them.",
                    strings::Section::Other.title()
                ))
                .font(egui::FontId::proportional(READING))
                .color(quiet),
            );
        });
    }
    asked
}

/// A run of fields as cells, wrapping where the window is narrow.
fn cells(
    ui: &mut egui::Ui,
    ctx: &Ctx,
    state: &State,
    doc: &Doc<'_>,
    rows: &[&Field],
    piano: &mut PianoLookup,
    sets: &mut Sets,
) {
    let built = clustered(rows, doc);
    if built.is_empty() {
        return;
    }
    let row = egui::Layout::left_to_right(egui::Align::TOP).with_main_wrap(true);
    ui.with_layout(row, |ui| {
        ui.spacing_mut().item_spacing = egui::vec2(14.0, 10.0);
        for cell in &built {
            match cell {
                Cell::One(part) => one(ui, ctx, state, part, rows, piano, sets),
                Cell::Register(bars) => register(ui, ctx, state, bars, sets),
                Cell::Transpose => transpose(ui, ctx, state, rows, sets),
            }
        }
    });
}

/// The cells a run of fields becomes: morph slots folded onto the parameters they move,
/// drawbar runs merged into registers, and the transpose pair as one control.
fn clustered<'a>(rows: &[&'a Field], doc: &Doc<'a>) -> Vec<Cell<'a>> {
    let mut parts: Vec<Part<'a>> = Vec::new();
    let mut transposed = false;
    for field in rows {
        // ⚠️ The selector that picks one of several stored alternatives is the head of
        // each alternative's own card. Drawn here as well it would be two controls for
        // one switch — and the layout keeps it in the group *above* the ones it picks
        // between, so it reaches a strip that has no alternatives of its own.
        if doc.picks.contains(field.path.as_str()) {
            continue;
        }
        if field.path == TRANSPOSE_ENABLED || field.path == TRANSPOSE {
            transposed = true;
            continue;
        }
        // A slot whose parameter is in this body rides on that parameter; one with no
        // parameter beside it stands as its own cell rather than disappearing.
        if field
            .spec
            .morph_parent()
            .is_some_and(|parent| doc.morphs.contains_key(parent.as_str()))
        {
            continue;
        }
        parts.push(Part {
            field,
            morphs: doc
                .morphs
                .get(field.path.as_str())
                .copied()
                .unwrap_or_default(),
        });
    }
    let mut out = merged(parts);
    if transposed {
        out.push(Cell::Transpose);
    }
    out
}

/// Nine single-bar drawbar fields under one prefix, ranked 1..=9 in order, as one
/// register.
///
/// ⚠️ Branch on the kind's bar count, never on the width: the Electro 5 packs a whole
/// registration into one field and the Stage bodies give each bar its own.
fn merged(parts: Vec<Part<'_>>) -> Vec<Cell<'_>> {
    let mut out: Vec<Cell> = Vec::new();
    let mut run: Vec<Part> = Vec::new();
    for part in parts {
        if !fitting(&run, part.field) {
            out.extend(run.drain(..).map(Cell::One));
        }
        match fitting(&run, part.field) {
            true => run.push(part),
            false => out.push(Cell::One(part)),
        }
        if run.len() == drawbar_widget::BARS {
            out.push(Cell::Register(std::mem::take(&mut run)));
        }
    }
    out.extend(run.into_iter().map(Cell::One));
    out
}

/// Whether a bar carries on the register the run has opened.
fn fitting(run: &[Part<'_>], field: &Field) -> bool {
    let Some((stem, rank)) = ranked(field) else {
        return false;
    };
    usize::from(rank) == run.len() + 1
        && run
            .first()
            .and_then(|first| ranked(first.field))
            .is_none_or(|(opened, _)| opened == stem)
}

/// A single-bar drawbar's register prefix and its one-based place in it, or `None` for
/// anything the widget cannot place.
fn ranked(field: &Field) -> Option<(&str, u8)> {
    let ControlKind::Drawbar {
        bars: 1,
        rank: Some(rank),
        ..
    } = field.spec.control
    else {
        return None;
    };
    if !(1..=drawbar_widget::BARS as u8).contains(&rank) {
        return None;
    }
    let (stem, _) = field.path.rsplit_once('_')?;
    Some((stem, rank))
}

/// The morph target a lens puts under a parameter's own control, or nothing where the
/// lens is off or the parameter has no target for it.
///
/// ⚠️ It is what the cell **writes** as well as what it reads: an edit made under a lens
/// goes to the morph slot, never to the panel value beside it.
fn shown<'a>(part: &Part<'a>, lens: Option<usize>) -> Option<&'a Field> {
    lens.and_then(|slot| part.morphs[slot])
}

/// One parameter as a cell: its name, the control under it, and the morph handles under
/// that.
fn one(
    ui: &mut egui::Ui,
    ctx: &Ctx,
    state: &State,
    part: &Part<'_>,
    rows: &[&Field],
    piano: &mut PianoLookup,
    sets: &mut Sets,
) {
    let lensed = shown(part, state.lens);
    let drawn = lensed.unwrap_or(part.field);
    let dim = state.lens.is_some() && lensed.is_none();
    let legal = ctx.legal(drawn);

    if lensed.is_none() && part.field.path == PIANO_MODEL && piano.model_cell(ui, part.field, sets)
    {
        return;
    }
    let named = piano.names(drawn);

    let span = width(drawn, &legal);
    let drawn_at = ui
        .allocate_ui(egui::vec2(span, 0.0), |ui| {
            if dim {
                ui.set_opacity(0.45);
            }
            ui.vertical(|ui| {
                ui.spacing_mut().item_spacing.y = 3.0;
                // The name is the parameter's; the dot is the slot the cell writes.
                caption(ui, part.field, state.pending.contains(&drawn.path));
                if let Some(value) = control(ui, drawn, &legal, rows, named) {
                    sets.push((drawn.path.clone(), value));
                }
                if state.lens.is_none() {
                    dots(ui, &part.morphs);
                }
            });
        })
        .response;
    if let Some(slot) = lensed {
        outline(ui, drawn_at.rect, is_neutral(slot));
    }
}

/// The lit or grey ring round a control the lens is showing a target for.
fn outline(ui: &egui::Ui, rect: egui::Rect, neutral: bool) {
    let ink = match neutral {
        true => app::unlit(ui.visuals()),
        false => app::accent(ui.visuals()),
    };
    ui.painter().rect_stroke(
        rect.expand(2.0),
        RADIUS,
        egui::Stroke::new(1.0_f32, ink),
        egui::StrokeKind::Inside,
    );
}

/// The name over a control: the app's word for it, or the prettified path in mono where
/// the table has no word yet.
fn caption(ui: &mut egui::Ui, field: &Field, edited: bool) {
    named_caption(ui, &field.path, edited, note(field));
}

/// The same caption over a path, for the register nine fields are drawn as.
fn named_caption(ui: &mut egui::Ui, path: &str, edited: bool, note: &str) {
    let known = strings::known(path);
    let quiet = app::caption(ui.visuals());
    let response = ui
        .horizontal(|ui| {
            ui.spacing_mut().item_spacing.x = 4.0;
            ui.add(egui::Label::new(
                egui::RichText::new(strings::label(path).to_uppercase())
                    .font(match known {
                        true => egui::FontId::proportional(LABEL),
                        false => egui::FontId::monospace(LABEL),
                    })
                    .color(quiet),
            ));
            if edited {
                app::dot(ui, app::warn(ui.visuals()), DOT);
            }
            if !known {
                icon(ui, Glyph::Tag, 9.0, quiet);
            }
        })
        .response;
    let mut hint = path.to_string();
    if !known {
        hint.push_str(" — no label yet; showing the prettified path");
    }
    if !note.is_empty() {
        hint.push_str(" · ");
        hint.push_str(note);
    }
    response.on_hover_text(hint);
}

/// What a kind is worth saying beside its own control, and nothing where it is not.
///
/// Each line is a fact the library states about the encoding, not a description of the
/// widget.
fn note(field: &Field) -> &'static str {
    match field.spec.control {
        // Inferred from specimens; not confirmed on hardware.
        ControlKind::Bipolar(_) => {
            "centre is the slot midpoint — accurate at the ends, approximate between"
        }
        // Inferred from specimens; not confirmed on hardware.
        ControlKind::Pattern { .. } => "step order inferred",
        ControlKind::Drawbar { .. } => "rank is a position, not a pitch",
        // Inferred from specimens; not confirmed on hardware.
        ControlKind::Morph { .. } => "a morph slot with no parameter beside it",
        _ => "",
    }
}

/// The three performance controls under a morphed parameter.
fn dots(ui: &mut egui::Ui, morphs: &[Option<&Field>; SLOTS.len()]) {
    if morphs.iter().all(Option::is_none) {
        return;
    }
    ui.horizontal(|ui| {
        ui.spacing_mut().item_spacing.x = 3.0;
        for (nth, (_, word, short)) in SLOTS.iter().enumerate() {
            let Some(slot) = morphs[nth] else { continue };
            let lit = !is_neutral(slot);
            let ink = match lit {
                true => app::accent(ui.visuals()),
                false => app::unlit(ui.visuals()),
            };
            let hint = match lit {
                true => format!("{word}{}", slot.value),
                false => format!("{word} — neutral"),
            };
            app::dot(ui, ink, DOT).on_hover_text(hint.clone());
            ui.label(
                egui::RichText::new(*short)
                    .font(egui::FontId::proportional(COUNT_TEXT))
                    .color(app::caption(ui.visuals())),
            )
            .on_hover_text(hint);
            ui.add_space(2.0);
        }
    });
}

/// The value a morph slot of this width holds when nothing morphs its parent.
///
/// ⚠️ The morph encoding is not established, and a `Field` carries the stored number
/// rather than the library's own answer — so the midpoint is read back off the library's
/// constant for the slot's width rather than restated here.
/// Inferred from specimens; not confirmed on hardware.
fn neutral(width: u32) -> Option<u64> {
    use nord_format::components::MorphOf;
    Some(u64::from(match width {
        1 => MorphOf::<1>::NEUTRAL,
        2 => MorphOf::<2>::NEUTRAL,
        3 => MorphOf::<3>::NEUTRAL,
        4 => MorphOf::<4>::NEUTRAL,
        5 => MorphOf::<5>::NEUTRAL,
        6 => MorphOf::<6>::NEUTRAL,
        7 => MorphOf::<7>::NEUTRAL,
        8 => MorphOf::<8>::NEUTRAL,
        _ => return None,
    }))
}

fn is_neutral(slot: &Field) -> bool {
    word(&slot.value) == neutral(slot.spec.width)
}

/// How wide a cell is, which is as wide as what stands in it.
fn width(field: &Field, legal: &[String]) -> f32 {
    match field.spec.control {
        ControlKind::Toggle => 84.0,
        ControlKind::Selector => 156.0,
        ControlKind::Shift(_) => 100.0,
        ControlKind::Drawbar { bars: 1, .. } => 44.0,
        ControlKind::Drawbar { .. } => 220.0,
        ControlKind::Pattern { steps, .. } => (f32::from(steps) * 13.0).max(110.0),
        ControlKind::Reference(_) => 176.0,
        _ if legal.is_empty() => 168.0,
        ControlKind::Knob(_) | ControlKind::Bipolar(_) => 78.0,
        ControlKind::Morph { .. } | ControlKind::Number => match legal.len() <= MENU_MAX {
            true => 156.0,
            false => 78.0,
        },
    }
}

/// The control alone, without its name. Returns the spelling `set_field` takes when it
/// has been moved.
///
/// ⚠️ Exhaustive over [`ControlKind`], so a kind the library adds is a compile error
/// here rather than a field that silently loses its widget.
fn control(
    ui: &mut egui::Ui,
    field: &Field,
    legal: &[String],
    rows: &[&Field],
    named: Option<&str>,
) -> Option<String> {
    match field.spec.control {
        ControlKind::Drawbar { bars: 1, rank, .. } => bar(ui, field, rank),
        ControlKind::Drawbar { order, .. } => packed(ui, field, order),
        ControlKind::Pattern {
            steps,
            bits_per_step,
            order,
        } => pattern(ui, field, steps, bits_per_step, order),
        ControlKind::Reference(library) => reference(ui, field, library, named),
        // Above the enumerable ceiling a field lists nothing to offer, so its stored
        // bits are the only spelling there is.
        _ if legal.is_empty() => wide(ui, field),
        ControlKind::Toggle => toggle(ui, field, legal),
        ControlKind::Selector => selector(ui, field, legal),
        ControlKind::Knob(unit) => turned(ui, field, legal, unit, false, rows),
        ControlKind::Bipolar(unit) => turned(ui, field, legal, unit, true, rows),
        ControlKind::Shift(unit) => shift(ui, field, legal, unit),
        ControlKind::Morph { .. } | ControlKind::Number => plain(ui, field, legal),
    }
}

/// A lamp and the word for the state it is in.
///
/// The two states may be named rather than spelled `true`/`false`, and what is written
/// back is whichever of the two the field itself lists.
fn toggle(ui: &mut egui::Ui, field: &Field, legal: &[String]) -> Option<String> {
    let named = match legal {
        [off, on] if off != "false" || on != "true" => Some((off.as_str(), on.as_str())),
        _ => None,
    };
    let (off, on) = named.unwrap_or(("off", "on"));
    let lit = match named {
        Some((_, on)) => field.value == on,
        None => field.value == "true",
    };
    let word = match lit {
        true => on,
        false => off,
    };
    let want = led::ui(ui, lit, word)?;
    Some(match named {
        Some((off, on)) => match want {
            true => on.to_string(),
            false => off.to_string(),
        },
        None => want.to_string(),
    })
}

/// A named-value picker over every position the field lists.
///
/// ⚠️ A position the library could not name is offered as `unknown (n)` and flagged, not
/// hidden: real files hold them, and that spelling is the only way to put one back.
fn selector(ui: &mut egui::Ui, field: &Field, legal: &[String]) -> Option<String> {
    let mut picked = None;
    ui.horizontal(|ui| {
        ui.spacing_mut().item_spacing.x = 4.0;
        if strings::unrecognised(&field.value).is_some() {
            icon(ui, Glyph::CircleHelp, 11.0, app::warn(ui.visuals()))
                .on_hover_text("the panel cannot produce this position, and the file holds it");
        }
        egui::ComboBox::from_id_salt(&field.path)
            .selected_text(
                egui::RichText::new(strings::value_label(&field.path, &field.value))
                    .text_style(egui::TextStyle::Small),
            )
            .width(ui.available_width().min(128.0))
            .show_ui(ui, |ui| {
                for value in offered(&field.path, legal, &field.value) {
                    let word = strings::value_label(&field.path, &value);
                    if ui.selectable_label(value == field.value, word).clicked() {
                        picked = Some(value);
                    }
                }
            });
    });
    picked.filter(|value| *value != field.value)
}

/// The values a picker offers.
fn offered(path: &str, legal: &[String], current: &str) -> Vec<String> {
    let mut out: Vec<String> = legal
        .iter()
        .filter(|value| offerable(path, value))
        .cloned()
        .collect();
    if !out.iter().any(|value| value == current) {
        out.push(current.to_string());
    }
    out
}

/// Whether a value is one a player would pick.
///
/// `Routing::Unknown` is a named variant rather than an unrecognised position, but it is
/// how older firmware spelled *off* and it presents as off. Two entries both meaning off
/// are not offered together.
/// Confirmed on hardware.
fn offerable(path: &str, value: &str) -> bool {
    !(value == "Unknown"
        && matches!(
            path,
            "effects_panel.fx1" | "effects_panel.fx2" | "effects_panel.fx3" | "effects_panel.fx4"
        ))
}

/// A knob, and beside it whatever reading the unit actually supports.
///
/// ⚠️ A unit is a label, not a promise of conversion. Where the panel's curve is not
/// published the knob prints the stored byte and the caption names the scale — nothing
/// here invents a reading the file does not support.
fn turned(
    ui: &mut egui::Ui,
    field: &Field,
    legal: &[String],
    unit: Unit,
    centred: bool,
    rows: &[&Field],
) -> Option<String> {
    let Some((min, max)) = contiguous(legal) else {
        return plain(ui, field, legal);
    };
    let value: i64 = field.value.trim_start_matches('+').parse().ok()?;
    let mut moved = None;
    // The panel reading stands beside the dial and the stored number under it: one is
    // what the operator is setting, the other what the file holds.
    ui.horizontal_top(|ui| {
        ui.spacing_mut().item_spacing.x = 6.0;
        let dial = ui
            .scope(|ui| moved = knob::ui(ui, &field.path, value, min, max))
            .response;
        if centred {
            detent(ui, dial.rect);
        }
        // What was typed may be no number at all, and the field is what refuses it;
        // until it does, the reading stands on the value the file holds.
        let shown = moved
            .as_deref()
            .and_then(|spelled| spelled.parse().ok())
            .unwrap_or(value);
        match reading(unit, centred, shown, min, max) {
            Some(text) => {
                ui.label(
                    egui::RichText::new(text)
                        .font(egui::FontId::monospace(READING))
                        .color(ui.visuals().text_color()),
                );
            }
            None => {
                if let Some(word) = scale(unit) {
                    let hint = clocked(field, rows);
                    let drawn = ui.label(
                        egui::RichText::new(word)
                            .font(egui::FontId::proportional(READING))
                            .color(app::warn(ui.visuals())),
                    );
                    match hint {
                        Some(sibling) => drawn.on_hover_text(sibling),
                        None => drawn.on_hover_text(
                            "the panel's curve for this unit is not published, so the stored \
                             value is what is shown",
                        ),
                    };
                }
            }
        }
    });
    moved
}

/// The mark at twelve o'clock on a knob whose musical zero is its centre.
///
/// ⚠️ The knob's sweep is symmetrical about straight up, so the slot's midpoint is
/// already where the tick goes — the lit arc still fills from the bottom stop, because
/// the stored range runs `0..=127` and nothing in it is negative.
fn detent(ui: &egui::Ui, dial: egui::Rect) {
    let top = egui::pos2(dial.center().x, dial.top());
    ui.painter().line_segment(
        [top, egui::pos2(top.x, top.y + 5.0)],
        egui::Stroke::new(1.0_f32, app::caption(ui.visuals())),
    );
}

/// The panel reading beside a knob, where the unit supports one.
fn reading(unit: Unit, centred: bool, value: i64, min: i64, max: i64) -> Option<String> {
    if centred {
        // The slot midpoint, which is where the library takes centre to be.
        let centre = (min + max + 1) / 2;
        return Some(format!("{:+}", value - centre));
    }
    match (unit.describes_a_known_transform(), unit) {
        (true, Unit::Panel10) if max > min => Some(format!(
            "{:.1}",
            (value - min) as f64 / (max - min) as f64 * 10.0
        )),
        _ => None,
    }
}

/// What a knob's axis is called where its curve is unpublished.
fn scale(unit: Unit) -> Option<&'static str> {
    match unit {
        Unit::Hertz => Some("Hz scale"),
        Unit::Milliseconds => Some("ms scale"),
        Unit::Bpm => Some("BPM scale"),
        Unit::ClockDivision => Some("division"),
        Unit::Pan => Some("stored"),
        _ => None,
    }
}

/// The sibling flag a clocked rate reads against, where the body declares one.
///
/// ⚠️ Neither field is a reading on its own: the same slot reads in hertz or as a
/// subdivision depending on the flag beside it.
/// Inferred from specimens; not confirmed on hardware.
fn clocked(field: &Field, rows: &[&Field]) -> Option<String> {
    if !matches!(field.spec.control, ControlKind::Knob(Unit::ClockDivision)) {
        return None;
    }
    let stem = field.path.rsplit_once('_').map(|(head, _)| head)?;
    let sibling = rows
        .iter()
        .find(|other| other.path.starts_with(stem) && other.path.ends_with("_clock"))?;
    Some(format!(
        "reads as a clock division or a rate depending on {}",
        sibling.path
    ))
}

/// A signed offset, stepped one at a time and stopped at the ends of its own travel.
fn shift(ui: &mut egui::Ui, field: &Field, legal: &[String], unit: Unit) -> Option<String> {
    let Some((min, max)) = contiguous(legal) else {
        return plain(ui, field, legal);
    };
    let value: i64 = field.value.trim_start_matches('+').parse().ok()?;
    let word = match unit {
        Unit::Semitones => "st",
        Unit::Octaves => "oct",
        _ => "",
    };
    let mut moved = None;
    ui.horizontal(|ui| {
        ui.spacing_mut().item_spacing.x = 3.0;
        if nudge(ui, "", value > min) {
            moved = Some(value - 1);
        }
        counted(ui, value, word);
        if nudge(ui, "+", value < max) {
            moved = Some(value + 1);
        }
    });
    moved.map(|moved| moved.to_string())
}

/// One end of a counter: a square button, the same size whichever way it steps.
fn nudge(ui: &mut egui::Ui, sign: &str, within: bool) -> bool {
    ui.add_enabled(
        within,
        egui::Button::new(egui::RichText::new(sign).font(egui::FontId::proportional(COUNTER_TEXT)))
            .min_size(egui::Vec2::splat(NUDGE)),
    )
    .clicked()
}

/// Where a counter stands: its own inset box, with the unit it counts in beside the
/// number.
///
/// The box holds a fixed width for the number, so stepping one does not walk the buttons
/// either side of it across the panel.
fn counted(ui: &mut egui::Ui, value: i64, unit: &str) {
    let spelled = match value {
        0 => "0".to_string(),
        _ => format!("{value:+}"),
    };
    egui::Frame::new()
        .fill(ui.visuals().extreme_bg_color)
        .corner_radius(RADIUS)
        .inner_margin(egui::Margin::symmetric(5, 2))
        .show(ui, |ui| {
            ui.spacing_mut().item_spacing.x = 3.0;
            ui.add_sized(
                egui::vec2(COUNTER, NUDGE),
                egui::Label::new(
                    egui::RichText::new(spelled)
                        .font(egui::FontId::monospace(COUNTER_TEXT))
                        .color(ui.visuals().text_color()),
                ),
            );
            if !unit.is_empty() {
                ui.label(
                    egui::RichText::new(unit)
                        .font(egui::FontId::proportional(LABEL))
                        .color(app::caption(ui.visuals())),
                );
            }
        });
}

/// One drawbar, for the bodies that give each bar its own field.
fn bar(ui: &mut egui::Ui, field: &Field, rank: Option<u8>) -> Option<String> {
    let position = field.value.trim().parse().ok()?;
    let rank = rank
        .and_then(|rank| usize::from(rank).checked_sub(1))
        .filter(|rank| *rank < drawbar_widget::BARS);
    drawbar_widget::ui_one(ui, rank, position, true).map(|moved| moved.to_string())
}

/// A whole register in one field.
///
/// ⚠️ Read from the wrong end a register comes out mirrored and looks like a plausible
/// registration, so the packing order is asked of the field rather than assumed.
fn packed(ui: &mut egui::Ui, field: &Field, order: PackedOrder) -> Option<String> {
    let bits = drawbar_widget::parse(&field.value)?;
    let stored = drawbar_widget::bars(bits);
    let shown = match order {
        PackedOrder::HighFirst => stored,
        PackedOrder::LowFirst => mirrored(stored),
    };
    let moved = bars(ui, shown)?;
    let back = match order {
        PackedOrder::HighFirst => moved,
        PackedOrder::LowFirst => mirrored(moved),
    };
    Some(drawbar_widget::spell(drawbar_widget::written(bits, back)?))
}

fn mirrored(positions: [u8; drawbar_widget::BARS]) -> [u8; drawbar_widget::BARS] {
    let mut out = positions;
    out.reverse();
    out
}

/// The drawbars themselves, plus the digits under them. No hex: the digits are the
/// readout.
fn bars(
    ui: &mut egui::Ui,
    positions: [u8; drawbar_widget::BARS],
) -> Option<[u8; drawbar_widget::BARS]> {
    let mut moved = None;
    ui.vertical(|ui| {
        moved = drawbar_widget::ui_ranks(ui, positions, true, &drawbar_widget::ALL_RANKS);
        ui.label(
            egui::RichText::new(drawbar_widget::digits(&moved.unwrap_or(positions)))
                .font(egui::FontId::monospace(READING))
                .color(ui.visuals().weak_text_color()),
        );
    });
    moved
}

/// Nine ranked single-bar fields as one register: each bar writes its own field, and
/// only the bars that moved are written.
fn register(ui: &mut egui::Ui, ctx: &Ctx, state: &State, run: &[Part<'_>], sets: &mut Sets) {
    if let Some(slot) = state.lens {
        // The targets keep the register's own order, so the bars stay side by side under
        // every lens — even where a slot is wider than the bar it morphs and has no
        // drawbar of its own to be drawn as.
        for (nth, part) in run.iter().enumerate() {
            let Some(target) = part.morphs[slot] else {
                continue;
            };
            let legal = ctx.legal(target);
            let at = ui
                .allocate_ui(egui::vec2(64.0, 0.0), |ui| {
                    ui.vertical(|ui| {
                        ui.spacing_mut().item_spacing.y = 3.0;
                        ui.horizontal(|ui| {
                            ui.spacing_mut().item_spacing.x = 4.0;
                            ui.label(
                                egui::RichText::new(format!("BAR {}", nth + 1))
                                    .font(egui::FontId::proportional(LABEL))
                                    .color(app::caption(ui.visuals())),
                            );
                            if state.pending.contains(&target.path) {
                                app::dot(ui, app::warn(ui.visuals()), DOT);
                            }
                        });
                        if let Some(value) = plain(ui, target, &legal) {
                            sets.push((target.path.clone(), value));
                        }
                    });
                })
                .response;
            outline(ui, at.rect, is_neutral(target));
        }
        return;
    }

    let positions: [u8; drawbar_widget::BARS] = std::array::from_fn(|n| {
        run.get(n)
            .and_then(|part| part.field.value.trim().parse().ok())
            .unwrap_or(0)
    });
    let edited = run
        .iter()
        .any(|part| state.pending.contains(&part.field.path));
    ui.allocate_ui(egui::vec2(220.0, 0.0), |ui| {
        ui.vertical(|ui| {
            ui.spacing_mut().item_spacing.y = 3.0;
            let stem = ranked(run[0].field).map_or(run[0].field.path.as_str(), |(stem, _)| stem);
            named_caption(ui, stem, edited, "rank is a position, not a pitch");
            if let Some(moved) = bars(ui, positions) {
                sets.extend(bar_sets(run, &positions, &moved));
            }
            let any: [Option<&Field>; SLOTS.len()] = std::array::from_fn(|slot| {
                run.iter()
                    .find_map(|part| part.morphs[slot].filter(|slot| !is_neutral(slot)))
                    .or_else(|| run.iter().find_map(|part| part.morphs[slot]))
            });
            dots(ui, &any);
        });
    });
}

/// What a moved register writes: the bars that landed somewhere else, and no others. A
/// bar nobody touched is a field that must not be written.
fn bar_sets(
    run: &[Part<'_>],
    was: &[u8; drawbar_widget::BARS],
    now: &[u8; drawbar_widget::BARS],
) -> Sets {
    run.iter()
        .zip(was)
        .zip(now)
        .filter(|((_, was), now)| was != now)
        .map(|((part, _), now)| (part.field.path.clone(), now.to_string()))
        .collect()
}

/// The bits one step of a pattern owns: how far up the stored word they sit, and the mask
/// that takes them. `None` for a step the declared width cannot address.
///
/// ⚠️ [`PackedOrder::HighFirst`] numbers the steps down from the top of the word, so step
/// 0 is the highest bits rather than the lowest.
fn step_bits(step: usize, steps: u8, bits_per_step: u8, order: PackedOrder) -> Option<(u32, u64)> {
    let last = usize::from(steps).checked_sub(1)?;
    if step > last {
        return None;
    }
    let nth = match order {
        PackedOrder::LowFirst => step,
        PackedOrder::HighFirst => last - step,
    };
    let width = u32::from(bits_per_step);
    let shift = width.checked_mul(u32::try_from(nth).ok()?)?;
    let mask = u64::MAX.checked_shr(u64::BITS.checked_sub(width)?)?;
    (shift.checked_add(width)? <= u64::BITS).then_some((shift, mask))
}

/// The stored word after a click on one step: that step's own bits move on to the next
/// value they can hold, wrapping at the top, and no other bit moves.
fn stepped(
    stored: u64,
    step: usize,
    steps: u8,
    bits_per_step: u8,
    order: PackedOrder,
) -> Option<u64> {
    let (shift, mask) = step_bits(step, steps, bits_per_step, order)?;
    let next = ((stored >> shift) & mask).wrapping_add(1) & mask;
    Some((stored & !(mask << shift)) | (next << shift))
}

/// A per-step grid. A click moves one step on to the next value it can hold.
fn pattern(
    ui: &mut egui::Ui,
    field: &Field,
    steps: u8,
    bits_per_step: u8,
    order: PackedOrder,
) -> Option<String> {
    let stored = word(&field.value)?;
    let mut moved = None;
    ui.horizontal_wrapped(|ui| {
        ui.spacing_mut().item_spacing = egui::vec2(2.0, 2.0);
        for step in 0..usize::from(steps) {
            let Some((shift, mask)) = step_bits(step, steps, bits_per_step, order) else {
                continue;
            };
            let held = (stored >> shift) & mask;
            let (rect, response) =
                ui.allocate_exact_size(egui::vec2(11.0, 14.0), egui::Sense::click());
            let ink = match held {
                0 => app::unlit(ui.visuals()),
                _ => app::accent(ui.visuals()),
            };
            ui.painter().rect_filled(rect, RADIUS, ink);
            if response
                .on_hover_text(format!("step {}{held} · step order inferred", step + 1))
                .clicked()
            {
                moved = stepped(stored, step, steps, bits_per_step, order);
            }
        }
    });
    moved.map(|bits| format!("{bits:#x}"))
}

/// An id into a library the file does not contain.
fn reference(
    ui: &mut egui::Ui,
    field: &Field,
    library: nord_format::fields::Library,
    named: Option<&str>,
) -> Option<String> {
    let quiet = app::caption(ui.visuals());
    ui.vertical_centered(|ui| {
        ui.spacing_mut().item_spacing.y = 2.0;
        let (text, ink, under) = match named {
            Some(name) => (
                name.to_string(),
                ui.visuals().text_color(),
                format!("{} {}", library.label(), field.value),
            ),
            None => (
                field.value.clone(),
                app::warn(ui.visuals()),
                format!("{} — not in the library", library.label()),
            ),
        };
        ui.label(
            egui::RichText::new(text)
                .font(egui::FontId::monospace(11.5))
                .color(ink),
        )
        .on_hover_text("the file stores the id; only the instrument knows the name");
        ui.label(
            egui::RichText::new(under)
                .font(egui::FontId::proportional(LABEL))
                .color(quiet),
        );
    });
    None
}

/// The unclassified default: a menu over a short list, a knob over a long run.
fn plain(ui: &mut egui::Ui, field: &Field, legal: &[String]) -> Option<String> {
    if legal.len() <= MENU_MAX && !legal.is_empty() {
        return selector(ui, field, legal);
    }
    let Some((min, max)) = contiguous(legal) else {
        return selector(ui, field, legal);
    };
    let value: i64 = field.value.trim_start_matches('+').parse().ok()?;
    knob::ui(ui, &field.path, value, min, max)
}

/// A field too wide to enumerate: its stored bits, typed as they are spelled.
fn wide(ui: &mut egui::Ui, field: &Field) -> Option<String> {
    // ⚠️ Half a value is not a value the format would take, so the box commits when it
    // is done rather than per keystroke — and what has been typed waits under the
    // field's own id until then.
    let id = ui.id().with(("wide", field.path.as_str()));
    let held: Option<String> = ui.data(|data| data.get_temp(id));
    let mut text = held.clone().unwrap_or_else(|| field.value.clone());
    let response = ui.add(
        egui::TextEdit::singleline(&mut text)
            .id(id)
            .desired_width(150.0)
            .font(egui::FontId::monospace(11.0)),
    );
    // ⚠️ Escape takes the focus away in the frame it is pressed, so it is read before the
    // box is: an unfocused box is one that was left, and leaving commits.
    if response.ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
        ui.data_mut(|data| data.remove::<String>(id));
        return None;
    }
    let entered = response.ctx.input(|i| i.key_pressed(egui::Key::Enter));
    if response.has_focus() && !entered {
        ui.data_mut(|data| data.insert_temp(id, text));
        return None;
    }
    held.as_ref()?;
    ui.data_mut(|data| data.remove::<String>(id));
    (text.trim() != field.value).then(|| text.trim().to_string())
}

/// The Electro 5 transpose control: a lamp and a number, written together the way the
/// panel's own button writes them.
///
/// ⚠️ Neither field reads on its own. `transpose_enabled` is sticky — the instrument
/// sets it the first time transposition is touched and never clears it — and an
/// untouched program stores `+1` in the value rather than `0`. The instrument ignores the
/// amount while the lamp is dark, and moving the amount is what lights it.
/// Confirmed on hardware.
fn transpose(ui: &mut egui::Ui, ctx: &Ctx, state: &State, rows: &[&Field], sets: &mut Sets) {
    let held = |path: &str| rows.iter().find(|field| field.path == path);
    let (Some(lamp), Some(amount)) = (held(TRANSPOSE_ENABLED), held(TRANSPOSE)) else {
        return;
    };
    let Some((least, most)) = contiguous(&ctx.legal(amount)) else {
        return;
    };
    let on = lamp.value == "true";
    let Some(semitones) = amount.value.trim_start_matches('+').parse::<i64>().ok() else {
        return;
    };
    let edited = state.pending.contains(&lamp.path) || state.pending.contains(&amount.path);

    let mut switched = None;
    let mut moved = None;
    ui.allocate_ui(egui::vec2(120.0, 0.0), |ui| {
        ui.vertical(|ui| {
            ui.spacing_mut().item_spacing.y = 3.0;
            caption(ui, lamp, edited);
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 6.0;
                switched = led::ui(ui, on, "");
                moved = knob::ui(ui, TRANSPOSE, semitones, least, most);
            });
        });
    })
    .response
    .on_hover_text("two fields, one control: the lamp and the semitones move together");

    // Moving the semitones turns the light on, which is what the panel does.
    let (on, semitones) = match (switched, moved) {
        (_, Some(want)) => (true, want),
        (Some(want_on), None) => (want_on, semitones.to_string()),
        (None, None) => return,
    };
    sets.push((TRANSPOSE_ENABLED.to_string(), on.to_string()));
    sets.push((TRANSPOSE.to_string(), semitones));
}

/// The rows of the Advanced face's "About this file": a label, a value, and a note.
pub fn about(doc: &Doc<'_>, entity: &LocalEntity) -> Vec<(&'static str, String, String)> {
    let (fields, slots) = doc.tally();
    let (badge, format) = super::header::badge(entity);
    let layout = match doc.shape() {
        Shape::Authored { exhaustive: true } => (
            "authored — exhaustive".to_string(),
            "every field the body declares is placed".to_string(),
        ),
        Shape::Authored { exhaustive: false } => {
            let (unplaced, named) = doc.unplaced();
            (
                "authored".to_string(),
                format!(
                    "{unplaced} fields no group names; {named} of them show under {}",
                    strings::Section::Other.title()
                ),
            )
        }
        Shape::Menus => (
            "menus".to_string(),
            "this app's own table, in the order the instrument's menus run".to_string(),
        ),
        Shape::Flat => (
            "flat, registry order".to_string(),
            "nothing knows how this panel is divided".to_string(),
        ),
    };
    vec![
        ("Format", badge, format),
        (
            "Fields",
            fields.to_string(),
            match slots {
                0 => "no morph slots in this body".to_string(),
                n => format!("{n} of them morph slots"),
            },
        ),
        ("Layout", layout.0, layout.1),
        ("Stored at", super::header::lives(entity), String::new()),
        (
            "Instrument",
            nord_format::accept::Family::of_tag(&entity.tag())
                .map(|family| family.label().to_string())
                .unwrap_or_else(|| "unknown".to_string()),
            String::new(),
        ),
    ]
}

/// What a field's kind is called in the Advanced table's own column.
///
/// ⚠️ Exhaustive over [`ControlKind`], so a kind the library adds is named here rather
/// than falling into a catch-all that says nothing.
pub fn kind_word(field: &Field) -> String {
    match field.spec.control {
        ControlKind::Toggle => "toggle".to_string(),
        ControlKind::Selector => "selector".to_string(),
        ControlKind::Knob(unit) => format!("knob {}", unit_word(unit)),
        ControlKind::Bipolar(unit) => format!("bipolar {}", unit_word(unit)),
        ControlKind::Shift(unit) => format!("shift {}", unit_word(unit)),
        ControlKind::Drawbar { bars: 1, rank, .. } => match rank {
            Some(rank) => format!("drawbar {rank}"),
            None => "drawbar".to_string(),
        },
        ControlKind::Drawbar { bars, .. } => format!("{bars} drawbars"),
        ControlKind::Pattern { steps, .. } => format!("{steps} steps"),
        ControlKind::Reference(library) => format!("{} id", library.label()),
        ControlKind::Morph { .. } => "morph".to_string(),
        ControlKind::Number => "number".to_string(),
    }
}

fn unit_word(unit: Unit) -> &'static str {
    match unit {
        Unit::Panel10 => "0-10",
        Unit::Decibels => "dB",
        Unit::Milliseconds => "ms",
        Unit::Hertz => "Hz",
        Unit::Bpm => "BPM",
        Unit::ClockDivision => "division",
        Unit::Semitones => "st",
        Unit::Octaves => "oct",
        Unit::Pan => "pan",
        Unit::None => "",
    }
}

/// A stored word as a field spells it: `0x…`, or decimal.
fn word(value: &str) -> Option<u64> {
    let text = value.trim();
    match text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
        Some(hex) => u64::from_str_radix(hex, 16).ok(),
        None => text.parse().ok(),
    }
}

/// The range a legal-value list covers, when every value is an integer and none is
/// missing.
///
/// ⚠️ A gapped set is not travel: a knob over it would stop on values the field refuses.
fn contiguous(legal: &[String]) -> Option<(i64, i64)> {
    let mut values = Vec::with_capacity(legal.len());
    for value in legal {
        values.push(value.trim_start_matches('+').parse::<i64>().ok()?);
    }
    let min = *values.iter().min()?;
    let max = *values.iter().max()?;
    (max.checked_sub(min)? + 1 == values.len() as i64 && min < max).then_some((min, max))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fields::apply;
    use crate::workspace::Fresh;
    use nord_format::formats::{ne5, ns4};
    use nord_format::{Entity, Program};

    fn electro5() -> (Vec<u8>, Vec<Field>) {
        let entity = Entity::Program(Program::Electro5(ne5::program::new(
            (0, 0).try_into().unwrap(),
        )));
        let bytes = nord_format::to_bytes(&entity).unwrap();
        let fields = apply(&bytes, &[]).unwrap().0;
        (bytes, fields)
    }

    /// A gapped legal set is not travel: a knob over it would stop on values the field
    /// refuses.
    #[test]
    fn only_a_gapless_run_of_integers_is_travel() {
        let full: Vec<String> = (0..128).map(|n| n.to_string()).collect();
        assert_eq!(contiguous(&full), Some((0, 127)));
        assert_eq!(contiguous(&["0".into(), "1".into(), "9".into()]), None);
        assert_eq!(contiguous(&["Organ".into(), "Piano".into()]), None);
        // A run of one value has no travel.
        assert_eq!(contiguous(&["3".into()]), None);
    }

    /// A Panel10 knob reads in the panel's own `0..10`; a unit whose curve is not
    /// published has no reading at all and names its scale instead.
    #[test]
    fn a_reading_appears_only_where_the_unit_supports_one() {
        assert_eq!(
            reading(Unit::Panel10, false, 96, 0, 127),
            Some("7.6".to_string())
        );
        assert_eq!(reading(Unit::Hertz, false, 71, 0, 127), None);
        assert_eq!(reading(Unit::Milliseconds, false, 12, 0, 127), None);
        // Bipolar reads either side of the slot midpoint, whatever the unit.
        assert_eq!(
            reading(Unit::Decibels, true, 70, 0, 127),
            Some("+6".to_string())
        );
        assert_eq!(scale(Unit::Hertz), Some("Hz scale"));
        assert_eq!(scale(Unit::Panel10), None);
    }

    /// A morph slot's neutral value comes off the library's own constant for its width,
    /// so a slot beside a drawbar and one beside a knob are not read by one number.
    #[test]
    fn a_morph_slots_neutral_follows_the_width_the_library_declares() {
        assert_eq!(neutral(8), Some(127));
        assert_eq!(neutral(5), Some(15));
        assert_eq!(neutral(3), Some(3));
        assert_eq!(neutral(9), None);
    }

    /// The sentence a section's idle line is built out of.
    #[test]
    fn the_idle_line_names_what_is_stored_and_not_played() {
        assert_eq!(listed(&["Vox"]), "Vox");
        assert_eq!(listed(&["Vox", "Farfisa"]), "Vox and Farfisa");
        assert_eq!(listed(&["Vox", "Farfisa", "Pipe"]), "Vox, Farfisa and Pipe");
    }

    /// ⚠️ Both spellings of a drawbar carry the one kind: the Electro 5 packs a whole
    /// registration into one field and the Stage 4 gives each bar its own nibble. The
    /// kind's bar count is what separates them.
    #[test]
    fn a_drawbar_is_a_register_or_a_bar_by_what_its_kind_counts() {
        let (_, electro5) = electro5();
        let packed = electro5
            .iter()
            .find(|field| field.path == "organ_panel.vox_preset1_drawbars")
            .expect("the Vox register");
        assert!(matches!(
            packed.spec.control,
            ControlKind::Drawbar { bars: 9, .. }
        ));
        assert!(ranked(packed).is_none());

        let (stage4, _) = apply(&Fresh::Stage4Program.bytes().unwrap(), &[]).unwrap();
        let bar = stage4
            .iter()
            .find(|field| field.path == "organ_a.drawbar_1")
            .expect("the first bar");
        assert_eq!(ranked(bar).map(|(_, rank)| rank), Some(1));
    }

    /// Nine ranked bars under one prefix are one register; anything short of nine stays
    /// nine cells rather than drawing a register that is not there.
    #[test]
    fn nine_ranked_bars_merge_into_one_register() {
        let (fields, _) = apply(&Fresh::Stage4Program.bytes().unwrap(), &[]).unwrap();
        let doc = Doc {
            sections: Vec::new(),
            leftovers: Vec::new(),
            idle: Vec::new(),
            shape: Shape::Flat,
            shown: HashSet::new(),
            picks: HashSet::new(),
            morphs: slots_of(&fields),
            fields: 0,
            slots: 0,
        };
        let rows: Vec<&Field> = fields
            .iter()
            .filter(|field| ranked(field).is_some() && field.path.starts_with("organ_a."))
            .take(drawbar_widget::BARS)
            .collect();
        assert_eq!(rows.len(), drawbar_widget::BARS);
        let built = clustered(&rows, &doc);
        assert_eq!(built.len(), 1);
        assert!(matches!(built.first(), Some(Cell::Register(run)) if run.len() == 9));

        let short = clustered(&rows[..4], &doc);
        assert_eq!(short.len(), 4);
        assert!(short.iter().all(|cell| matches!(cell, Cell::One(_))));
    }

    /// A morph target is the value its parameter is driven to, so it rides on that
    /// parameter and is never a cell of its own.
    #[test]
    fn a_morph_slot_is_drawn_on_the_parameter_it_moves() {
        let (fields, _) = apply(&Fresh::Stage4Program.bytes().unwrap(), &[]).unwrap();
        let morphs = slots_of(&fields);
        let slots = morphs
            .get("organ_a_volume")
            .expect("the volume knob is morphed");
        let named: Vec<&str> = slots
            .iter()
            .filter_map(|slot| slot.map(|field| field.path.as_str()))
            .collect();
        assert_eq!(
            named,
            [
                "organ_a_volume_wheel",
                "organ_a_volume_aftertouch",
                "organ_a_volume_ctrl_pedal",
            ]
        );
        assert!(!morphs.contains_key("organ_a_volume_wheel"));
    }

    /// A slot whose parameter the body does not declare has nothing to ride on, so it
    /// keeps a cell rather than disappearing.
    #[test]
    fn a_slot_with_no_parameter_beside_it_still_gets_a_cell() {
        let (fields, _) = apply(&Fresh::Stage4Program.bytes().unwrap(), &[]).unwrap();
        let mut morphs = slots_of(&fields);
        morphs.remove("organ_a_volume");
        let doc = Doc {
            sections: Vec::new(),
            leftovers: Vec::new(),
            idle: Vec::new(),
            shape: Shape::Flat,
            shown: HashSet::new(),
            picks: HashSet::new(),
            morphs,
            fields: 0,
            slots: 0,
        };
        let rows: Vec<&Field> = fields
            .iter()
            .filter(|field| field.path == "organ_a_volume_wheel")
            .collect();
        let built = clustered(&rows, &doc);
        assert_eq!(built.len(), 1);
    }

    /// An unrecognised position is offered, because the file holds it and that spelling
    /// is the only way to put it back. Two spellings of off are not offered together.
    #[test]
    fn a_picker_offers_every_position_but_a_second_spelling_of_off() {
        let legal: Vec<String> = ["B3", "B3Bass", "Pipe", "unknown (6)"]
            .iter()
            .map(|value| value.to_string())
            .collect();
        assert_eq!(
            offered("center_panel.organ_type", &legal, "B3"),
            ["B3", "B3Bass", "Pipe", "unknown (6)"]
        );

        let routing: Vec<String> = ["Off", "Unknown", "Lower", "Upper"]
            .iter()
            .map(|value| value.to_string())
            .collect();
        assert_eq!(
            offered("effects_panel.fx1", &routing, "Off"),
            ["Off", "Lower", "Upper"]
        );
        // A file holding it keeps it reachable.
        assert_eq!(
            offered("effects_panel.fx1", &routing, "Unknown"),
            ["Off", "Lower", "Upper", "Unknown"]
        );
        assert!(offerable("some_other_field", "Unknown"));
    }

    /// Every control the Electro 5 view offers comes off the library's layout, and a
    /// group the instrument is not using is named rather than silently absent.
    #[test]
    fn the_electro5_document_is_the_librarys_layout() {
        let (bytes, fields) = electro5();
        let decoded =
            nord_format::from_stream(&mut std::io::Cursor::new(&bytes)).expect("it decodes");
        let doc = of(&decoded, &fields);
        assert_eq!(doc.shape(), Shape::Authored { exhaustive: false });
        let titles: Vec<&str> = doc
            .sections
            .iter()
            .map(|section| section.title.as_str())
            .collect();
        assert!(titles.contains(&"Keyboard & split"), "{titles:?}");
        assert!(titles.contains(&"Organ"), "{titles:?}");
        // A fresh program plays organ on both parts, so piano is state rather than
        // controls — named as idle, never simply gone.
        assert!(!titles.contains(&"Piano"), "{titles:?}");
        assert!(doc.idle.contains(&"Piano"), "{:?}", doc.idle);
        let (unplaced, named) = doc.unplaced();
        assert!(unplaced > 0);
        assert!(named <= unplaced, "{named} named of {unplaced} unplaced");
    }

    /// The "Also stored" section holds the unplaced fields the strings table names, so
    /// the count beside the layout is those rather than every unplaced field.
    #[test]
    fn the_layout_line_counts_what_also_stored_will_hold() {
        let (bytes, fields) = electro5();
        let decoded =
            nord_format::from_stream(&mut std::io::Cursor::new(&bytes)).expect("it decodes");
        let doc = of(&decoded, &fields);
        let (unplaced, named) = doc.unplaced();
        let also = doc
            .sections
            .iter()
            .find(|section| section.title == strings::Section::Other.title())
            .expect("the named leftovers have a section");
        assert_eq!(also.fields.len(), named);
        assert!(named < unplaced, "{named} of {unplaced} are named");
    }

    /// The transpose pair is one control, which needs both halves in the same group —
    /// the layout is what puts them there.
    #[test]
    fn the_transpose_pair_stays_in_one_group() {
        let (_, fields) = electro5();
        let resolved = ne5::program::PANEL.resolve(&fields);
        let keyboard = resolved
            .sections
            .iter()
            .find(|section| section.group.title == "Keyboard & split")
            .expect("the keyboard section");
        let paths: Vec<&str> = keyboard
            .fields
            .iter()
            .map(|field| field.path.as_str())
            .collect();
        assert!(paths.contains(&TRANSPOSE_ENABLED));
        assert!(paths.contains(&TRANSPOSE));
    }

    /// A Stage 4 program has a layout as well, and every one of its sections is open —
    /// nothing folds above a field count.
    #[test]
    fn a_stage4_program_opens_every_section_it_has() {
        let bytes = Fresh::Stage4Program.bytes().unwrap();
        let (fields, _) = apply(&bytes, &[]).unwrap();
        let decoded =
            nord_format::from_stream(&mut std::io::Cursor::new(&bytes)).expect("it decodes");
        let doc = of(&decoded, &fields);
        assert!(!doc.sections.is_empty());
        assert!(fields.len() > 800, "{} fields", fields.len());
        let (all, slots) = doc.tally();
        assert_eq!(all, fields.len());
        assert!(slots > 300, "{slots} morph slots");
        assert!(ns4::program::PANEL.resolve(&fields).sections.len() > 1);
    }

    /// ⚠️ A stored alternative is picked by a click anywhere in its card, not by the
    /// label alone: an operator who reaches for its drawbars has said which registration
    /// they mean, and a card that answered only its own title would take the pull and go
    /// on playing the other one.
    #[test]
    fn a_click_anywhere_in_a_stored_alternative_picks_it() {
        /// The stroked card of the alternative that is not the one playing.
        fn kept_card(output: &egui::FullOutput, stroke: egui::Color32) -> Option<egui::Rect> {
            fn walk(shape: &egui::Shape, stroke: egui::Color32, found: &mut Vec<egui::Rect>) {
                match shape {
                    egui::Shape::Rect(drawn) if drawn.stroke.color == stroke => {
                        found.push(drawn.rect)
                    }
                    egui::Shape::Vec(shapes) => {
                        shapes.iter().for_each(|shape| walk(shape, stroke, found))
                    }
                    _ => {}
                }
            }
            let mut found = Vec::new();
            for clipped in &output.shapes {
                walk(&clipped.shape, stroke, &mut found);
            }
            found
                .into_iter()
                .find(|rect| rect.width() > 120.0 && rect.height() > 120.0)
        }

        let (bytes, fields) = electro5();
        let decoded =
            nord_format::from_stream(&mut std::io::Cursor::new(&bytes)).expect("it decodes");
        let doc = of(&decoded, &fields);
        let alternatives: Vec<&Sect> = doc
            .sections
            .iter()
            .flat_map(|section| &section.nested)
            .filter(|nested| nested.pick.is_some())
            .collect();
        assert!(
            alternatives.iter().filter(|kept| !kept.selected).count() > 0,
            "the Electro 5 stores a preset it is not playing",
        );
        let kept = alternatives
            .iter()
            .find(|kept| !kept.selected)
            .expect("a stored alternative");
        let wanted = kept.pick.expect("a card is picked by its own selector");

        let ctx = egui::Context::default();
        ctx.set_fonts(crate::app::fonts());
        ctx.all_styles_mut(crate::app::metrics);
        let screen = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(1600.0, 1200.0),
            )),
            ..Default::default()
        };
        let quiet = ctx.style().visuals.widgets.noninteractive.bg_stroke.color;
        let read = Ctx::default();
        let state = State::default();
        let mut sets = Sets::new();
        let mut body = egui::Rect::NOTHING;
        // The first pass lays the cards out; the second clicks the middle of the one
        // that is kept, which is a control of its own rather than its title.
        for pass in 0..2 {
            let mut piano = lookup();
            sets.clear();
            let input = egui::RawInput {
                events: match pass {
                    0 => Vec::new(),
                    _ => click(body.center()),
                },
                ..screen.clone()
            };
            let output = ctx.run(input, |ctx| {
                egui::CentralPanel::default().show(ctx, |ui| {
                    side_by_side(
                        ui,
                        &read,
                        &state,
                        &doc,
                        &alternatives,
                        &mut piano,
                        &mut sets,
                    );
                });
            });
            if pass == 0 {
                body = kept_card(&output, quiet).expect("the kept card is stroked");
            }
        }
        assert!(
            sets.contains(&(wanted.field.to_string(), wanted.value.to_string())),
            "a click at {:?} left {sets:?}",
            body.center(),
        );
    }

    /// Which kind a field is, for a sweep that has to see every one of them drawn.
    fn kind_key(field: &Field) -> &'static str {
        match field.spec.control {
            ControlKind::Toggle => "toggle",
            ControlKind::Selector => "selector",
            ControlKind::Knob(_) => "knob",
            ControlKind::Bipolar(_) => "bipolar",
            ControlKind::Shift(_) => "shift",
            ControlKind::Drawbar { bars: 1, .. } => "bar",
            ControlKind::Drawbar { .. } => "register",
            ControlKind::Pattern { .. } => "pattern",
            ControlKind::Reference(_) => "reference",
            ControlKind::Morph { .. } => "morph",
            ControlKind::Number => "number",
        }
    }

    /// The screen one headless frame is drawn on.
    fn headless() -> egui::RawInput {
        egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(900.0, 540.0),
            )),
            ..Default::default()
        }
    }

    /// A whole click at one point: the pointer arrives, presses and lets go.
    fn click(at: egui::Pos2) -> Vec<egui::Event> {
        let button = |pressed| egui::Event::PointerButton {
            pos: at,
            button: egui::PointerButton::Primary,
            pressed,
            modifiers: egui::Modifiers::default(),
        };
        vec![egui::Event::PointerMoved(at), button(true), button(false)]
    }

    /// How many filled circles of one colour a frame painted.
    fn circles(output: &egui::FullOutput, ink: egui::Color32) -> usize {
        fn count(shape: &egui::Shape, ink: egui::Color32) -> usize {
            match shape {
                egui::Shape::Circle(drawn) => usize::from(drawn.fill == ink),
                egui::Shape::Vec(shapes) => shapes.iter().map(|shape| count(shape, ink)).sum(),
                _ => 0,
            }
        }
        output
            .shapes
            .iter()
            .map(|clipped| count(&clipped.shape, ink))
            .sum()
    }

    /// A lookup that has asked the instrument nothing, for a cell that references no
    /// library.
    fn lookup() -> PianoLookup {
        PianoLookup {
            id: None,
            name: None,
            can_ask: false,
            asked: false,
            models: Vec::new(),
            scan_disagrees: None,
        }
    }

    /// One headless frame with a single control in it, and how many shapes it painted.
    fn drawn(field: &Field) -> usize {
        fn count(shape: &egui::Shape) -> usize {
            match shape {
                egui::Shape::Vec(shapes) => shapes.iter().map(count).sum(),
                _ => 1,
            }
        }
        let ctx = egui::Context::default();
        ctx.set_fonts(crate::app::fonts());
        ctx.all_styles_mut(crate::app::metrics);
        let legal = (field.spec.legal)();
        let output = ctx.run(headless(), |ctx| {
            egui::CentralPanel::default().show(ctx, |ui| {
                control(ui, field, &legal, &[], None);
            });
        });
        output
            .shapes
            .iter()
            .map(|clipped| count(&clipped.shape))
            .sum()
    }

    /// ⚠️ Every kind the library declares has a renderer, and every renderer paints. A
    /// kind that fell through would be a control the operator never sees at all — the
    /// field would still be in the file, and nothing on screen would say so.
    #[test]
    fn every_control_kind_the_registry_declares_paints_a_control() {
        let (_, electro5) = electro5();
        let (stage4, _) = apply(&Fresh::Stage4Program.bytes().unwrap(), &[]).unwrap();
        let (stage2, _) = apply(&Fresh::Stage2Program.bytes().unwrap(), &[]).unwrap();

        let mut seen: Vec<&'static str> = Vec::new();
        for field in stage4.iter().chain(&electro5).chain(&stage2) {
            let kind = kind_key(field);
            if seen.contains(&kind) {
                continue;
            }
            seen.push(kind);
            assert!(drawn(field) > 0, "{kind} ({}) painted nothing", field.path);
        }
        seen.sort_unstable();
        assert_eq!(
            seen,
            [
                "bar",
                "bipolar",
                "knob",
                "morph",
                "number",
                "pattern",
                "reference",
                "register",
                "selector",
                "shift",
                "toggle",
            ],
        );

        // A field too wide to enumerate is the eleventh shape: a box its stored bits are
        // typed into, and there is nothing else it could be.
        let wide = stage2
            .iter()
            .find(|field| {
                (field.spec.legal)().is_empty() && matches!(field.spec.control, ControlKind::Number)
            })
            .expect("the Stage 2 declares a wide unclassified field");
        assert!(wide.spec.width > nord_format::fields::ENUMERABLE_BITS);
        assert!(wide.value.starts_with("0x"), "{}", wide.value);
        assert!(drawn(wide) > 0);
    }

    /// A morph lens puts the target under the parameter's own control, and an edit made
    /// there writes the slot rather than the panel value beside it.
    #[test]
    fn an_edit_under_the_lens_writes_the_morph_slot() {
        let (fields, _) = apply(&Fresh::Stage4Program.bytes().unwrap(), &[]).unwrap();
        let morphs = slots_of(&fields);
        let part = Part {
            field: fields
                .iter()
                .find(|field| field.path == "organ_a_volume")
                .expect("the volume knob"),
            morphs: morphs["organ_a_volume"],
        };
        assert!(
            shown(&part, None).is_none(),
            "the panel writes the panel value"
        );
        assert_eq!(
            shown(&part, Some(0)).map(|field| field.path.as_str()),
            Some("organ_a_volume_wheel"),
        );
        assert_eq!(
            shown(&part, Some(2)).map(|field| field.path.as_str()),
            Some("organ_a_volume_ctrl_pedal"),
        );

        // A parameter nothing morphs keeps its own control, dimmed rather than swapped.
        let bare = Part {
            field: fields
                .iter()
                .find(|field| field.path == "split_enabled")
                .expect("the split switch"),
            morphs: Default::default(),
        };
        assert!(shown(&bare, Some(0)).is_none());
    }

    /// ⚠️ Read from the wrong end a register comes out mirrored, and mirrored looks like
    /// a plausible registration — so the packing order is asked of the field.
    #[test]
    fn a_packed_register_is_read_from_the_end_its_field_names() {
        let stored = drawbar_widget::bars(0x8_8880_0000);
        assert_eq!(stored, [8, 8, 8, 8, 0, 0, 0, 0, 0]);
        assert_eq!(mirrored(stored), [0, 0, 0, 0, 0, 8, 8, 8, 8]);
        assert_eq!(mirrored(mirrored(stored)), stored);

        let (_, electro5) = electro5();
        let register = electro5
            .iter()
            .find(|field| field.path == "organ_panel.vox_preset1_drawbars")
            .expect("the Vox register");
        assert!(matches!(
            register.spec.control,
            ControlKind::Drawbar {
                order: PackedOrder::HighFirst,
                ..
            }
        ));
    }

    /// A morph slot is drawn under the parameter it moves rather than beside it, so a
    /// face that places the parameter draws the slot too — the Advanced table must not
    /// flag a slot the lens draws as a field the Edit face hides.
    #[test]
    fn a_slot_is_shown_where_the_parameter_it_moves_is_placed() {
        // The layout draws the sections the program is using, so the organ has to be
        // playing for its parameters — and the slots riding on them — to be placed.
        let playing = [
            ("organ_section_enabled".to_string(), "true".to_string()),
            ("organ_a_layer_enabled".to_string(), "true".to_string()),
        ];
        let (_, bytes) = apply(&Fresh::Stage4Program.bytes().unwrap(), &playing).unwrap();
        let (fields, _) = apply(&bytes, &[]).unwrap();
        let decoded =
            nord_format::from_stream(&mut std::io::Cursor::new(&bytes)).expect("it decodes");
        let doc = of(&decoded, &fields);
        assert!(doc.shows("organ_a_volume"), "the organ layer is placed");
        assert!(doc.shows("organ_a_volume_wheel"));

        let mut ridden = 0;
        for field in &fields {
            let Some(parent) = field.spec.morph_parent() else {
                continue;
            };
            if !doc.shows(&parent) {
                continue;
            }
            ridden += 1;
            assert!(
                doc.shows(&field.path),
                "{} rides on {parent}, which is drawn",
                field.path,
            );
        }
        assert!(ridden > 20, "{ridden} slots ride on a drawn parameter");
    }

    /// Under a lens the cell writes the morph slot, so the edited dot beside the name is
    /// the slot's. The parameter it hangs on may be untouched.
    #[test]
    fn the_edited_dot_follows_the_field_the_cell_writes() {
        let (fields, _) = apply(&Fresh::Stage4Program.bytes().unwrap(), &[]).unwrap();
        let morphs = slots_of(&fields);
        let part = Part {
            field: fields
                .iter()
                .find(|field| field.path == "organ_a_volume")
                .expect("the volume knob"),
            morphs: morphs["organ_a_volume"],
        };

        let dots = |pending: &str, lens: Option<usize>| -> usize {
            let ctx = egui::Context::default();
            ctx.set_fonts(crate::app::fonts());
            ctx.all_styles_mut(crate::app::metrics);
            let mut state = State {
                pending: vec![pending.to_string()],
                ..Default::default()
            };
            if let Some(slot) = lens {
                state.pretend_lens(slot);
            }
            let read = Ctx::default();
            let mut piano = lookup();
            let mut sets = Sets::new();
            let ink = app::warn(&ctx.style().visuals);
            let output = ctx.run(headless(), |ctx| {
                egui::CentralPanel::default().show(ctx, |ui| {
                    one(ui, &read, &state, &part, &[], &mut piano, &mut sets);
                });
            });
            circles(&output, ink)
        };

        assert_eq!(
            dots("organ_a_volume_wheel", Some(0)),
            1,
            "the slot it writes"
        );
        assert_eq!(dots("organ_a_volume", Some(0)), 0, "not the panel value");
        assert_eq!(
            dots("organ_a_volume", None),
            1,
            "off the lens, the parameter"
        );
    }

    /// The three ways out of the box a wide field is typed into. Enter and leaving both
    /// mean it, and Escape means the file keeps what it had.
    #[test]
    fn a_wide_field_commits_on_enter_or_blur_and_drops_what_escape_typed() {
        const TYPED: &str = "0xfeed";

        let (stage2, _) = apply(&Fresh::Stage2Program.bytes().unwrap(), &[]).unwrap();
        let field = stage2
            .iter()
            .find(|field| {
                (field.spec.legal)().is_empty() && matches!(field.spec.control, ControlKind::Number)
            })
            .expect("the Stage 2 declares a wide unclassified field");
        assert_ne!(field.value, TYPED);

        /// What the last frame committed, and whether the typed text is still held.
        fn exit(field: &Field, focused: bool, events: Vec<egui::Event>) -> (Option<String>, bool) {
            let ctx = egui::Context::default();
            ctx.set_fonts(crate::app::fonts());
            let mut got = None;
            let mut held = false;
            // The first frame opens the box; the second delivers the way out of it.
            for events in [Vec::new(), events] {
                let input = egui::RawInput {
                    events,
                    ..headless()
                };
                let _ = ctx.run(input, |ctx| {
                    egui::CentralPanel::default().show(ctx, |ui| {
                        let id = ui.id().with(("wide", field.path.as_str()));
                        ui.data_mut(|data| data.insert_temp(id, TYPED.to_string()));
                        if focused {
                            ui.memory_mut(|memory| memory.request_focus(id));
                        }
                        got = wide(ui, field);
                        held = ui.data(|data| data.get_temp::<String>(id).is_some());
                    });
                });
            }
            (got, held)
        }

        fn key(key: egui::Key) -> Vec<egui::Event> {
            vec![egui::Event::Key {
                key,
                physical_key: None,
                pressed: true,
                repeat: false,
                modifiers: egui::Modifiers::default(),
            }]
        }

        assert_eq!(
            exit(field, true, Vec::new()),
            (None, true),
            "half a value waits in the box",
        );
        assert_eq!(
            exit(field, true, key(egui::Key::Enter)),
            (Some(TYPED.to_string()), false),
        );
        assert_eq!(
            exit(field, true, key(egui::Key::Escape)),
            (None, false),
            "escape drops what was typed",
        );
        assert_eq!(
            exit(field, false, Vec::new()),
            (Some(TYPED.to_string()), false),
            "leaving the box commits it",
        );
    }

    /// A lamp writes the field's own word for the state it was switched to: two states
    /// may be named rather than spelled `true`/`false`.
    #[test]
    fn a_lamp_writes_the_spelling_its_field_lists() {
        let (stage4, _) = apply(&Fresh::Stage4Program.bytes().unwrap(), &[]).unwrap();
        let field = stage4
            .iter()
            .find(|field| matches!(field.spec.control, ControlKind::Toggle))
            .expect("a stage 4 program has switches");

        let switched = |legal: &[String]| -> Option<String> {
            let ctx = egui::Context::default();
            ctx.set_fonts(crate::app::fonts());
            ctx.all_styles_mut(crate::app::metrics);
            let mut got = None;
            let mut at = egui::Pos2::ZERO;
            // The first pass lays the lamp out; the second clicks the rect it claimed.
            for pass in 0..2 {
                let input = egui::RawInput {
                    events: match pass {
                        0 => Vec::new(),
                        _ => click(at),
                    },
                    ..headless()
                };
                let _ = ctx.run(input, |ctx| {
                    egui::CentralPanel::default().show(ctx, |ui| {
                        let row = ui.horizontal(|ui| toggle(ui, field, legal));
                        got = row.inner;
                        at = row.response.rect.center();
                    });
                });
            }
            got
        };

        let named: Vec<String> = ["Off", "On"].iter().map(|word| word.to_string()).collect();
        assert_eq!(switched(&named).as_deref(), Some("On"));

        let plain: Vec<String> = ["false", "true"]
            .iter()
            .map(|word| word.to_string())
            .collect();
        let other = (field.value != "true").to_string();
        assert_eq!(switched(&plain), Some(other));
    }

    /// A click on one step moves that step's own bits and no others: a pattern edit must
    /// not disturb the steps beside it.
    #[test]
    fn a_click_on_a_step_moves_only_that_steps_bits() {
        for step in 0..8 {
            let moved = stepped(0, step, 8, 2, PackedOrder::LowFirst);
            assert_eq!(moved, Some(1 << (2 * step)), "step {step}");
        }
        // HighFirst numbers the steps down from the top of the word.
        assert_eq!(stepped(0, 0, 8, 2, PackedOrder::HighFirst), Some(1 << 14));
        assert_eq!(stepped(0, 7, 8, 2, PackedOrder::HighFirst), Some(1));
        // A step at the top of its range wraps to nothing, and takes nothing with it.
        let three = 0b11;
        assert_eq!(
            stepped((three << 2) | three, 1, 8, 2, PackedOrder::LowFirst),
            Some(three),
        );
        // A step outside the pattern, and a width no stored word can hold, address
        // nothing rather than some other step's bits.
        assert_eq!(stepped(0, 8, 8, 2, PackedOrder::LowFirst), None);
        assert_eq!(stepped(0, 8, 8, 2, PackedOrder::HighFirst), None);
        assert_eq!(stepped(0, 4, 8, 16, PackedOrder::LowFirst), None);
        assert_eq!(stepped(0, 0, 8, 65, PackedOrder::LowFirst), None);
    }

    /// A register is nine fields and a moved bar is one of them: the eight beside it are
    /// not rewritten with what they already hold.
    #[test]
    fn a_register_writes_only_the_bars_that_moved() {
        let (fields, _) = apply(&Fresh::Stage4Program.bytes().unwrap(), &[]).unwrap();
        let run: Vec<Part> = fields
            .iter()
            .filter(|field| ranked(field).is_some() && field.path.starts_with("organ_a."))
            .take(drawbar_widget::BARS)
            .map(|field| Part {
                field,
                morphs: Default::default(),
            })
            .collect();
        assert_eq!(run.len(), drawbar_widget::BARS);

        let was = [0_u8; drawbar_widget::BARS];
        let mut now = was;
        now[2] = 8;
        assert_eq!(
            bar_sets(&run, &was, &now),
            [(run[2].field.path.clone(), "8".to_string())],
        );
        assert!(bar_sets(&run, &was, &was).is_empty());
    }

    /// A stored word is read the way its field spells it, and a spelling that is no
    /// number at all is refused rather than read as zero.
    #[test]
    fn a_stored_word_is_refused_unless_it_spells_a_number() {
        assert_eq!(word("0x1f"), Some(31));
        assert_eq!(word("0X1F"), Some(31));
        assert_eq!(word(" 42 "), Some(42));
        assert_eq!(word("0x"), None);
        assert_eq!(word(""), None);
        assert_eq!(word("ff"), None);
        assert_eq!(word("-1"), None);
    }

    /// The transpose knob turns as far as the amount field says it may, which is the
    /// panel's own half-step either side of nothing.
    #[test]
    fn the_transpose_knob_turns_as_far_as_its_field_allows() {
        let (_, fields) = electro5();
        let amount = fields
            .iter()
            .find(|field| field.path == TRANSPOSE)
            .expect("the transpose amount");
        assert_eq!(contiguous(&(amount.spec.legal)()), Some((-6, 6)));
    }

    /// A body with no layout falls into the sections its paths name, and every field
    /// lands in exactly one of them.
    #[test]
    fn a_body_with_no_layout_falls_into_the_sections_its_paths_name() {
        let titles = |bytes: Vec<u8>| -> Vec<String> {
            let (fields, _) = apply(&bytes, &[]).unwrap();
            let groups = prefixes(&fields);
            assert_eq!(
                fields.len(),
                groups.iter().map(|group| group.rows.len()).sum::<usize>(),
            );
            groups.into_iter().map(|group| group.title).collect()
        };
        let stage4 = titles(Fresh::Stage4Program.bytes().unwrap());
        assert_eq!(stage4.first().map(String::as_str), Some("General"));
        assert!(stage4.contains(&"Organ a".to_string()), "{stage4:?}");

        let stage2 = titles(Fresh::Stage2Program.bytes().unwrap());
        assert!(stage2.contains(&"Slot a — organ".to_string()), "{stage2:?}");
        assert_eq!(titles(Fresh::Stage3Synth.bytes().unwrap()), ["General"]);
    }
}