monospace 0.1.0

The interactive full-screen terminal application: the chrome around a diagram being edited
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
//! The four signatures the framework dictates, and what the application does when each is called.
//!
//! **They are free functions because the signatures are fixed** by the parameters of `run_tui`.
//!
//! **This is where an event becomes an action.** A terminal event is answered here: a resize
//! repaints, and everything else is routed to the first handler that claims it — the shortcuts
//! that reach everything, the chrome, the diagram, and the shortcuts nobody has claimed — and the
//! action it names is carried out: the screen changed, the way out, or the forced exit. An entry of
//! the menu and the key that means the same thing therefore arrive at one place, and that place is
//! here.
//!
//! **The order is the whole of the policy, and it is written once.** Nothing here names a key:
//! which keys the application answers to, and whether a key has to be answered before the chrome,
//! is `shortcuts`' table. This module only says when each layer is asked.

use rat_salsa::Control;
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::{Position, Rect};
use ratatui_crossterm::crossterm::event::{Event, MouseButton, MouseEventKind};

use crate::about;
use crate::chrome::Target;
use crate::context::AppGlobal;
use crate::diagram_widget;
use crate::dialog;
use crate::error;
use crate::event::AppEvent;
use crate::export;
use crate::export::ExportDialogState;
use crate::frame;
use crate::menu;
use crate::open;
use crate::open::OpenDialogState;
use crate::save;
use crate::save::SaveDialogState;
use crate::shortcuts;
use crate::state::AppState;
use crate::text;
use crate::text::TextEditorState;
use crate::vocabulary::{Action, AppError, Reply};
use monospace_diagram::Shape;
#[cfg(test)]
use monospace_editing::Command;

/// The terminal is the framework's: it takes the screen and gives it back, and there is nothing
/// of ours to set up.
#[allow(clippy::unnecessary_wraps, reason = "the signature is the framework's")]
pub(crate) fn init(_state: &mut AppState, _global: &mut AppGlobal) -> Result<(), AppError> {
    Ok(())
}

/// Paints one frame.
#[allow(clippy::unnecessary_wraps, reason = "the signature is the framework's")]
pub(crate) fn render(
    area: Rect,
    buf: &mut Buffer,
    state: &mut AppState,
    global: &mut AppGlobal,
) -> Result<(), AppError> {
    frame::draw(area, buf, state, global);
    Ok(())
}

/// What the application does about an event.
#[allow(clippy::unnecessary_wraps, reason = "the signature is the framework's")]
pub(crate) fn event(
    event: &AppEvent,
    state: &mut AppState,
    _global: &mut AppGlobal,
) -> Result<Control<AppEvent>, AppError> {
    Ok(match event {
        // The loop reporting on itself: the frame it painted is the whole of the answer.
        AppEvent::Rendered(_) => Control::Continue,

        // **A resize is answered here and not by the handlers.** It is not a question about the
        // event — nobody wants a screen size — it is a fact about the frame: the layout it was
        // painted with is the one it no longer has, so it is painted again.
        AppEvent::Terminal(Event::Resize(_, _)) => Control::Changed,

        AppEvent::Terminal(event) => match route(event, state) {
            // **`Ignored` and `Consumed` are the same answer here**: neither owes a frame.
            Reply::Ignored | Reply::Consumed => Control::Continue,

            // **The frame is owed, but no action is carried out.** `route` has already addressed
            // any press, and this preserves that focus and the menu state instead of applying the
            // cleanup.
            Reply::Repaint => Control::Changed,

            // **The one that ends the loop**, and the only one that is not carried out: nothing
            // about the state changes, so there is no meaning to apply and no frame to owe.
            // **Whether it is forced stops here**: the loop ends either way.
            Reply::Quit { .. } => Control::Quit,

            // **A meaning is carried out, and carrying one out is the same three lines every
            // time.** What owes the frame is the meaning having been said, not the state having
            // changed, which is why the cleanup and the paint are here rather than in `apply`.
            Reply::Act(action) => {
                apply(&action, state);
                cleanup(state);
                Control::Changed
            }
        },
    })
}

/// Which handler answers the event, and what it answers.
///
/// **The order is the whole of the policy, and the chain is the order.** The shortcuts that reach
/// everything are asked first: a `Ctrl+Shift+Q` that reached the chrome as a key would be answered
/// by the chrome, and the point of it is that it is answered by nothing. **Then the dialog, while it
/// is up**: it is the overlay, it takes every key and every control, and an event it leaves alone
/// reaches nothing else. Then the bar, so that a key the widget uses is the widget's; then the
/// region, so that a click a drop-down covers is the drop-down's and the one it leaves is the
/// diagram's; then the shortcuts nobody has claimed. The first action wins, and an event all of
/// them leave alone is answered by nobody.
///
/// **The bar's keys that move the keyboard are read by the bar** (D4 and rule 5 of #189): `Alt` plus
/// a label's navigation character brings it with the press, `F10` asks for it, and the `Esc` that
/// has nothing left to close gives it back. **A leaf is not a meaning**, so these three keys move
/// the keyboard where they are read: the bar is handed the focus along with its own state, and no
/// action names a leaf.
///
/// **The one thing that is settled before a handler is asked is where the event is addressed**
/// (D1): a press moves the keyboard to the leaf it lands in, and it does so first because the label
/// a press opens and the drop-down a press closes are changes the handlers make while they are
/// asked — moving the keyboard afterwards would answer the wrong leaf. **A press that moved it owes
/// a frame even where nobody answers**: the label that was reversed is not any more.
///
/// **The state comes whole and the handler is handed the part it owns.** The chrome is given
/// `state.chrome_mut()`, the bar and the keyboard together, and the region `state.diagram_mut()`,
/// so what a handler may change about the application is what its own signature makes possible: the
/// selection, the drop-down and which leaf holds the keyboard, and never the session.
///
/// **A handler that consumed the event stops the chain**, and that is the difference the protocol
/// carries: `Ignored` is "not mine, ask the next one", `Consumed` is "mine, and nothing changed",
/// and only the first lets the region see a press the drop-down already trapped.
fn route(event: &Event, state: &mut AppState) -> Reply {
    // **The two reaches that answer before the press is addressed come first, and in this order.**
    // A `Ctrl+Shift+Q` that reached the chrome as a key would be answered by the chrome, and the
    // point of it is that it is answered by nothing; the overlays sit above the application, so
    // while one is up an event it leaves alone reaches nothing else. **`Ignored` is the overlay
    // being down**: the handler hands it back without asking the widget, so routing is one call and
    // not a question about whether the overlay is up followed by a question about the event.
    //
    // **Neither moves the keyboard**, which is why addressing sits below and not here: a
    // click on the bar behind an overlay moves nothing, and the press is addressed only once nobody
    // above has answered it.
    let before = shortcuts::handle_always(event)
        .or_else(|| text::handle(event, state.text_mut()))
        .or_else(|| dialog::handle(event, state.dialog_mut()))
        .or_else(|| open::handle(event, state.open_mut()))
        .or_else(|| save::handle(event, state.save_mut()))
        .or_else(|| export::handle(event, state.export_mut()));

    if before != Reply::Ignored {
        return before;
    }

    // **Where the event is addressed is read once**: the keyboard moves to the leaf the press
    // lands in, and the region is handed the same target rather than reading the press again.
    let target = target_of(event, state);
    let moved = state.chrome_mut().move_to(target);

    let answer = menu::handle(event, state.chrome_mut())
        .or_else(|| {
            // **The pair is taken together** so that the region is asked with the leaf the bar
            // left behind, which is the one the event was routed with.
            let (chrome, diagram) = state.chrome_and_diagram();
            diagram_widget::handle(event, diagram, chrome.leaf(), target)
        })
        .or_else(|| shortcuts::handle_unclaimed(event));

    // **The move is added last, and it is not part of the chain**: it is not an answer to the
    // event, it is a change the screen already made and that no handler was told about.
    if moved { answer.and_repaint() } else { answer }
}

/// Where the event is addressed, or [`Target::Nothing`] where it is not a press.
///
/// **Only a left press is addressed**: a release, a drag, a turn of the wheel and a key belong to
/// the handler that reads them, and the keyboard does not move for them.
fn target_of(event: &Event, state: &AppState) -> Target {
    let Event::Mouse(mouse) = event else {
        return Target::Nothing;
    };

    if mouse.kind != MouseEventKind::Down(MouseButton::Left) {
        return Target::Nothing;
    }

    state.target_at(Position::new(mouse.column, mouse.row))
}

/// Carries a meaning out into the state, and does nothing else.
///
/// **Applying and deciding are two jobs, and the framework's boundary is where they split.**
/// `apply` changes what the application knows; whether the loop continues, paints or ends is
/// `event`'s, because that is the framework's own vocabulary and nothing else here speaks it.
///
/// **An action need not change anything.** `Delete` with nothing selected removes nothing, and
/// `Undo` with nothing behind walks nothing; every action is applied all the same. **What leaves
/// the keyboard on the region is the carrying out and not the action** (rule 13 of #189), so it is
/// said once in [`event`], beside the paint.
fn apply(action: &Action, state: &mut AppState) {
    match action {
        // **The walks are the session's** (D2 of #181): each gives back one step and keeps no copy
        // of where the walk stands. At either end the session answers with itself.
        Action::Undo => state.diagram_mut().undo(),

        Action::Redo => state.diagram_mut().redo(),

        Action::Command(command) => {
            state.diagram_mut().perform(command.clone());
        }

        // **The editor is opened over the selected box and records no step.** The identity and the text
        // are read together, so the title and the buffer cannot name different figures.
        Action::EditText => {
            let opened = state
                .diagram()
                .selected_entry()
                .and_then(|(id, shape)| match shape {
                    Shape::Box { text, .. } => Some((id, text.clone())),
                    _ => None,
                });

            if let Some((id, text)) = opened {
                state
                    .text_mut()
                    .show(TextEditorState::new(id, text.as_ref()));
            }
        }

        // **The two actions that open the overlay.** The dialog is the chrome's own, so the
        // session is untouched: no command is performed and no step is recorded (D5 of #189).
        Action::About => state.dialog_mut().show(about::open()),

        // **The same overlay, over a failure's text**: it replaces whatever the dialog held.
        Action::ShowError(message) => state.dialog_mut().show(error::open(message)),

        // **The open dialog is the chrome's own too**, and opening it changes no session.
        Action::Open => state.open_mut().show(OpenDialogState::new()),

        // **The path is read and parsed before anything is replaced** (D3 and D4 of #260): a
        // file that cannot be read or parsed leaves the current session untouched, and reports
        // the failure in the message dialog through ShowError. A success starts a fresh session.
        Action::OpenFile(path) => match crate::load(path) {
            Ok(session) => *state = AppState::new(session),
            Err(error) => apply(&Action::ShowError(error.to_string()), state),
        },

        // **A fresh blank session is started immediately** (D3 of #273), discarding current work,
        // selection, and undo history without confirmation.
        Action::New => *state = AppState::new(crate::empty_session()),

        // **A fresh demonstration session is started immediately** (D3 of #273), discarding current
        // work, selection, and undo history without confirmation.
        Action::OpenDemo => match crate::demo() {
            Ok(session) => *state = AppState::new(session),
            Err(error) => apply(&Action::ShowError(error.to_string()), state),
        },

        // **The save dialog is the chrome's own too**, and opening it changes no session.
        Action::Save => state.save_mut().show(SaveDialogState::new()),

        // **The session's diagram is serialized and written to path** (D2 and D3 of #270): on
        // success the file is written and the current session is untouched; on any error it
        // leaves the session untouched and reports through ShowError.
        Action::SaveFile(path) => {
            if let Err(error) = crate::save(path, state.diagram().session()) {
                apply(&Action::ShowError(error.to_string()), state);
            }
        }

        // **The export dialog is the chrome's own too**, and opening it changes no session.
        Action::ExportText => state.export_mut().show(ExportDialogState::new()),

        // **The session's diagram is rendered over its footprint and written to path** (D3, D4
        // and D5 of #352): on success the file is written and the current session is untouched;
        // on any error it leaves the session untouched and reports through ShowError.
        Action::ExportTextFile(path) => {
            if let Err(error) = crate::export_text(path, state.diagram().session()) {
                apply(&Action::ShowError(error.to_string()), state);
            }
        }
    }
}

/// **A meaning that is carried out leaves the keyboard on the region** (rule 13 of #189): what a
/// person took from the bar is done, and what is left to do is in the drawing. The drop-down the
/// bar was showing closes with it, because a menu nobody holds the keyboard on is not open.
fn cleanup(state: &mut AppState) {
    state.chrome_mut().close();
}

/// What the application does about a failure.
///
/// **The error is reported once, and the loop does not spin on it.** The framework hands the
/// error to this handler and takes back a control; answering with the error again is the
/// framework re-queueing the same failure for ever. So the handler ends the loop and keeps the
/// error, and the error is written out with the terminal back.
#[allow(clippy::unnecessary_wraps, reason = "the signature is the framework's")]
pub(crate) fn error(
    error: AppError,
    _state: &mut AppState,
    global: &mut AppGlobal,
) -> Result<Control<AppEvent>, AppError> {
    global.set_failure(error);
    Ok(Control::Quit)
}

#[cfg(test)]
mod tests {
    use std::num::NonZeroU16;

    use super::*;
    use crate::chrome::Focus;
    use crate::config::Config;
    use crate::status;
    use crate::vocabulary::AppError;
    use monospace_core::{Offset, Pos};
    use monospace_diagram::{ShapeId, Text};
    use ratatui_core::layout::Rect;
    use ratatui_core::style::Modifier;
    use ratatui_crossterm::crossterm::event::{
        Event, KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
    };

    /// The width of the screen these tests draw.
    const WIDTH: u16 = 40;

    /// The height of the screen these tests draw.
    const HEIGHT: u16 = 10;

    /// The state of an application that starts with nothing in it.
    fn a_state() -> AppState {
        AppState::new(crate::empty_session())
    }

    /// The configuration the application starts with.
    fn a_global() -> AppGlobal {
        AppGlobal::new(Config::default(), monospace_glyph_sets::all())
    }

    /// A description whose only shape is a light 4×3 box at `(2, 1)` of the window.
    ///
    /// The window is the region's interior, which on a screen of the size these tests draw is
    /// `38×5` at `(1, 2)` of the screen: the box's top-left is the screen's `(3, 3)`.
    const A_BOX: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "box", "id": 1, "at": { "x": 2, "y": 1 },
                      "size": { "width": 4, "height": 3 }, "stroke": "light" } ]
    }"#;

    /// A description whose only shape is a light 4×3 box at `(2, 1)` holding `hi`.
    const A_BOX_WITH_TEXT: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "box", "id": 1, "at": { "x": 2, "y": 1 },
                      "size": { "width": 4, "height": 3 }, "stroke": "light",
                      "text": "hi" } ]
    }"#;

    /// A description whose only shape is a light connector between `(2, 1)` and `(10, 1)`.
    ///
    /// **`callbacks` does not have one yet**; it is the fixture `diagram_widget` already uses, added
    /// here because `t_is_ignored_off_a_box` needs a connector to select.
    const A_CONNECTOR: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "connector", "id": 1,
                      "from": { "at": { "kind": "point", "x": 2, "y": 1 },
                                "leaving": "right", "terminal": { "kind": "arm" } },
                      "to": { "at": { "kind": "point", "x": 10, "y": 1 },
                              "leaving": "left", "terminal": { "kind": "arm" } },
                      "stroke": "light" } ]
    }"#;

    /// A description whose only shape is a light `2×2` box at `(2, 1)`: the smallest a box shrinks to,
    /// so shrinking it again changes nothing.
    const A_BOX_AT_ITS_SMALLEST: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "box", "id": 1, "at": { "x": 2, "y": 1 },
                      "size": { "width": 2, "height": 2 }, "stroke": "light" } ]
    }"#;

    /// A description whose only shape is a light horizontal line of length 6 at `(2, 1)`.
    const A_HORIZONTAL_LINE: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "line", "id": 1, "at": { "x": 2, "y": 1 },
                      "len": 6, "orientation": "horizontal", "stroke": "light" } ]
    }"#;

    /// A description whose only shape is a light vertical line of length 3 at `(2, 1)`.
    const A_VERTICAL_LINE: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "line", "id": 1, "at": { "x": 2, "y": 1 },
                      "len": 3, "orientation": "vertical", "stroke": "light" } ]
    }"#;

    /// A description whose only shape is a horizontal line of length 1 at `(2, 1)`.
    const A_LINE_AT_ITS_MINIMUM: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "line", "id": 1, "at": { "x": 2, "y": 1 },
                      "len": 1, "orientation": "horizontal", "stroke": "light" } ]
    }"#;

    /// A description whose only shape is a horizontal line of length 0 at `(2, 1)`.
    const A_ZERO_LENGTH_LINE: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "line", "id": 1, "at": { "x": 2, "y": 1 },
                      "len": 0, "orientation": "horizontal", "stroke": "light" } ]
    }"#;

    /// The arrangement §4 and §6 of the diagram model are shown with: a box at the left, a box at
    /// the right, and one connector hung from the right side of the first and reaching the left
    /// side of the second.
    ///
    /// The left box is at `(0, 1)` of the window, so its top-left is the screen's `(1, 3)`; the
    /// right box's is at `(16, 1)`, the screen's `(17, 3)`.
    const A_BOX_AND_WHAT_HANGS_FROM_IT: &str = r#"{
        "next_id": 4,
        "shapes": [
            { "kind": "box", "id": 1, "at": { "x": 0, "y": 1 },
              "size": { "width": 4, "height": 3 }, "stroke": "light" },
            { "kind": "box", "id": 2, "at": { "x": 16, "y": 1 },
              "size": { "width": 4, "height": 3 }, "stroke": "light" },
            { "kind": "connector", "id": 3,
              "from": { "at": { "kind": "reference", "shape": 1, "anchor": "right" },
                        "terminal": { "kind": "arm" } },
              "to":   { "at": { "kind": "reference", "shape": 2, "anchor": "left" },
                        "terminal": { "kind": "arm" } },
              "stroke": "light" }
        ]
    }"#;

    /// A description whose only shape is a light `60×14` box at `(0, 0)`: larger than the window on
    /// both axes, so the view has room to travel.
    ///
    /// The window is `38×5`, so the content's span is `22` cells across and `9` down. The helper's
    /// step is a tenth of the window — `3` across, and `1` down because a tenth of five cells is
    /// nothing and the helper answers at least one.
    const A_BOX_TOO_BIG: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                      "size": { "width": 60, "height": 14 }, "stroke": "light" } ]
    }"#;

    /// Three boxes, at `(0, 0)`, `(27, 0)` and `(50, 0)`, the last two `3×3` and the first `4×3`.
    ///
    /// **The third gives the content its width**, so the view has `16` columns to travel, and the
    /// second is what a click after a scroll has to find: three columns across puts its corner at
    /// the window's `(24, 0)`, and the window's `(27, 0)` — what a click that added the origin would
    /// ask about — is a cell no shape wrote.
    const BOXES_APART: &str = r#"{
        "next_id": 4,
        "shapes": [
            { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
              "size": { "width": 4, "height": 3 }, "stroke": "light" },
            { "kind": "box", "id": 2, "at": { "x": 27, "y": 0 },
              "size": { "width": 3, "height": 3 }, "stroke": "light" },
            { "kind": "box", "id": 3, "at": { "x": 50, "y": 0 },
              "size": { "width": 3, "height": 3 }, "stroke": "light" }
        ]
    }"#;

    /// The state of an application over the diagram `json` describes.
    fn a_state_over(json: &str) -> AppState {
        let diagram =
            monospace_description::parse(json).expect("the test's description is readable");

        AppState::new(monospace_editing::Session::new(diagram))
    }

    /// The state of an application over the diagram `json` describes, with a frame painted.
    fn a_drawn_state_over(json: &str) -> AppState {
        let mut state = a_state_over(json);
        let _ = draw(&mut state);
        state
    }

    /// The event the terminal reports for a left press at the screen position `(column, row)`.
    fn click(column: u16, row: u16) -> Event {
        press(MouseButton::Left, column, row)
    }

    /// The event the terminal reports for a press of `button` at the screen position
    /// `(column, row)`.
    fn press(button: MouseButton, column: u16, row: u16) -> Event {
        Event::Mouse(MouseEvent {
            kind: MouseEventKind::Down(button),
            column,
            row,
            modifiers: KeyModifiers::NONE,
        })
    }

    /// The event the terminal reports for a turn of the wheel at the screen position
    /// `(column, row)`.
    fn wheel(kind: MouseEventKind, column: u16, row: u16) -> Event {
        wheel_with(kind, KeyModifiers::NONE, column, row)
    }

    /// The event the terminal reports for a turn of the wheel with `modifiers` held.
    fn wheel_with(kind: MouseEventKind, modifiers: KeyModifiers, column: u16, row: u16) -> Event {
        Event::Mouse(MouseEvent {
            kind,
            column,
            row,
            modifiers,
        })
    }

    /// The event the terminal reports for the pointer moving with the left button down.
    fn drag(column: u16, row: u16) -> Event {
        Event::Mouse(MouseEvent {
            kind: MouseEventKind::Drag(MouseButton::Left),
            column,
            row,
            modifiers: KeyModifiers::NONE,
        })
    }

    /// The event the terminal reports for the pointer moving to `(column, row)`.
    fn moved(column: u16, row: u16) -> Event {
        Event::Mouse(MouseEvent {
            kind: MouseEventKind::Moved,
            column,
            row,
            modifiers: KeyModifiers::NONE,
        })
    }

    /// The state of an application that has been on the screen once.
    ///
    /// **The frame comes first**: the bar knows where its labels are only once it has been
    /// drawn, and a key that arrives before that finds nothing to open.
    fn a_drawn_state() -> AppState {
        let mut state = a_state();
        let _ = draw(&mut state);
        state
    }

    /// Paints a frame and hands back the buffer it was painted into.
    fn draw(state: &mut AppState) -> ratatui_core::buffer::Buffer {
        let area = Rect::new(0, 0, WIDTH, HEIGHT);
        let mut buffer = ratatui_core::buffer::Buffer::empty(area);
        frame::draw(area, &mut buffer, state, &a_global());
        buffer
    }

    /// The event the terminal reports for a key.
    fn key(code: KeyCode) -> Event {
        Event::Key(KeyEvent::new(code, KeyModifiers::NONE))
    }

    /// The event the terminal reports for a key with modifiers.
    fn key_with(code: KeyCode, modifiers: KeyModifiers) -> Event {
        Event::Key(KeyEvent::new(code, modifiers))
    }

    /// The event the terminal reports for `Ctrl+Z`.
    fn undo_key() -> Event {
        key_with(KeyCode::Char('z'), KeyModifiers::CONTROL)
    }

    /// The event the terminal reports for `Ctrl+Shift+Z`.
    ///
    /// **The shifted character with both modifiers**, which is what a terminal that reports the
    /// combination at all reports: a terminal that folds the shift into the control character
    /// reports `undo_key` instead, and D1 of #181 names what that costs.
    fn redo_key() -> Event {
        key_with(
            KeyCode::Char('Z'),
            KeyModifiers::CONTROL | KeyModifiers::SHIFT,
        )
    }

    /// One row of a frame, as text.
    fn row_of(buffer: &Buffer, line: u16) -> String {
        (buffer.area.left()..buffer.area.right())
            .map(|column| buffer[(column, line)].symbol().to_string())
            .collect()
    }

    /// Whether the cell at a frame position is painted in reverse video.
    fn reversed(buffer: &Buffer, column: u16, line: u16) -> bool {
        buffer[(column, line)]
            .style()
            .add_modifier
            .contains(Modifier::REVERSED)
    }

    /// Hands an event to the application, the way the loop does.
    fn send(raw: &Event, state: &mut AppState) -> Control<AppEvent> {
        event(&AppEvent::Terminal(raw.clone()), state, &mut a_global())
            .expect("the event reached the application")
    }

    /// Opens the drop-down of `label` the way the region reaches the bar: `Alt` and the label's
    /// navigation character in one press (D4 of #189).
    fn open_the_drop_down(state: &mut AppState, label: char) {
        let outcome = send(&key_with(KeyCode::Char(label), KeyModifiers::ALT), state);
        let _ = draw(state);

        assert!(
            matches!(outcome, Control::Changed),
            "Alt+{label} did not owe a frame: {outcome:?}"
        );
        assert_eq!(
            state.chrome().leaf(),
            Focus::Bar,
            "Alt+{label} did not give the bar the keyboard"
        );
        assert!(
            state.chrome().popup_active(),
            "Alt+{label} did not open the drop-down"
        );
    }

    /// Takes the entry of `menu` whose text is `text`, by clicking it on the frame.
    ///
    /// **The entry is found by its name**: a menu that gains entries above one moves where it is
    /// but not what it says, and a test that pressed `Enter` would take whatever happens to be
    /// first. **The pointer moves onto it before the button goes down**, because the widget
    /// activates the entry it has selected and a press alone selects nothing.
    fn take_the_entry(state: &mut AppState, menu: char, text: &str) -> Control<AppEvent> {
        open_the_drop_down(state, menu);
        let buffer = draw(state);
        let (column, row) = frame::cell_of(&buffer, text);
        let _ = send(&moved(column, row), state);

        send(&click(column, row), state)
    }

    /// Opens the About dialog the way a person does: `Help > About` by pointer.
    ///
    /// **It also checks the keyboard goes back to the region** (rule 13): the dialog takes the
    /// whole screen while it is up, so the leaf is already where it will be given back, and every
    /// test that opens the dialog is checking that without saying so again.
    fn open_the_about_dialog(state: &mut AppState) {
        let outcome = take_the_entry(state, 'h', "About");

        assert!(
            matches!(outcome, Control::Changed),
            "taking About owed no frame: {outcome:?}"
        );
        assert!(state.dialog().is_up(), "taking About opened no dialog");
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "taking About left the keyboard on the bar"
        );
        assert!(
            !state.chrome().popup_active(),
            "taking About left the drop-down open"
        );
    }

    /// Opens the open dialog the way a person does: `File > Open` by pointer.
    ///
    /// **It also checks the keyboard goes back to the region** (rule 13): the dialog takes the
    /// whole screen while it is up, so the leaf is already where it will be given back.
    fn open_the_open_dialog(state: &mut AppState) {
        let outcome = take_the_entry(state, 'f', "Open");

        assert!(
            matches!(outcome, Control::Changed),
            "taking Open owed no frame: {outcome:?}"
        );
        assert!(state.open().is_up(), "taking Open opened no dialog");
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "taking Open left the keyboard on the bar"
        );
        assert!(
            !state.chrome().popup_active(),
            "taking Open left the drop-down open"
        );
    }

    /// Opens the save dialog the way a person does: `File > Save` by pointer.
    ///
    /// **It also checks the keyboard goes back to the region** (rule 13): the dialog takes the
    /// whole screen while it is up, so the leaf is already where it will be given back.
    fn open_the_save_dialog(state: &mut AppState) {
        let outcome = take_the_entry(state, 'f', "Save");

        assert!(
            matches!(outcome, Control::Changed),
            "taking Save owed no frame: {outcome:?}"
        );
        assert!(state.save().is_up(), "taking Save opened no dialog");
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "taking Save left the keyboard on the bar"
        );
        assert!(
            !state.chrome().popup_active(),
            "taking Save left the drop-down open"
        );
    }

    /// Opens the export dialog the way a person does: `File > Export as Text` by pointer.
    ///
    /// **It also checks the keyboard goes back to the region** (rule 13): the dialog takes the
    /// whole screen while it is up, so the leaf is already where it will be given back.
    fn open_the_export_dialog(state: &mut AppState) {
        let outcome = take_the_entry(state, 'f', "Export as Text");

        assert!(
            matches!(outcome, Control::Changed),
            "taking Export as Text owed no frame: {outcome:?}"
        );
        assert!(
            state.export().is_up(),
            "taking Export as Text opened no dialog"
        );
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "taking Export as Text left the keyboard on the bar"
        );
        assert!(
            !state.chrome().popup_active(),
            "taking Export as Text left the drop-down open"
        );
    }

    /// Writes `contents` to a fresh file under the system temp directory, named after the calling
    /// test so parallel tests never collide.
    fn write_description(name: &str, contents: &str) -> std::path::PathBuf {
        use std::io::Write as _;

        let path =
            std::env::temp_dir().join(format!("monospace-open-{name}-{}.json", std::process::id()));
        std::fs::File::create(&path)
            .and_then(|mut file| file.write_all(contents.as_bytes()))
            .expect("temp description file should be writable");
        path
    }

    /// **The chrome's own and no session** (rule 8): About opens an overlay and records no step,
    /// so the drawing and its history are exactly what they were.
    #[test]
    fn the_about_action_changes_no_session() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(
            selected.is_some(),
            "the box was not selected, so the test proves nothing"
        );

        open_the_about_dialog(&mut state);

        assert_eq!(
            state.diagram().selected(),
            selected,
            "the dialog changed the selection"
        );
        assert!(
            !state.diagram().can_undo(),
            "opening the dialog recorded a step"
        );
        assert!(
            !state.diagram().can_redo(),
            "opening the dialog left a step ahead"
        );
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "opening the dialog removed the box"
        );
    }

    /// **The error is the same overlay and no session** (rule 8): it opens the dialog over the
    /// text it carries, replaces the About it finds there, and records no step.
    #[test]
    fn showing_an_error_opens_the_dialog_over_its_text_and_changes_no_session() {
        let mut state = a_drawn_state_over(A_BOX);
        open_the_about_dialog(&mut state);

        apply(&Action::ShowError("Something failed".into()), &mut state);

        assert!(state.dialog().is_up(), "the error left the dialog down");

        let mut buffer = Buffer::empty(Rect::new(0, 0, 40, 10));
        crate::dialog::draw(
            Rect::new(0, 1, 40, 8),
            &mut buffer,
            state.dialog_mut(),
            &Config::default().theme,
        );
        let frame = crate::dialog::testing::picture(&buffer);
        assert!(
            frame.contains("Something failed"),
            "the dialog does not carry the error: {frame:?}"
        );
        assert!(
            !frame.contains("About"),
            "the error did not replace the About: {frame:?}"
        );
        assert!(
            !state.diagram().can_undo(),
            "showing the error recorded a step"
        );
    }

    /// **`Ctrl+N` and the File menu's first entry start a fresh session**, and both apply the same
    /// action.
    #[test]
    fn the_new_action_is_reached_by_the_shortcut_and_by_the_menus_entry() {
        // The shortcut.
        let mut state = a_drawn_state_over(A_BOX);
        let outcome = send(
            &key_with(KeyCode::Char('n'), KeyModifiers::CONTROL),
            &mut state,
        );

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().session().diagram().shapes().count(),
            0,
            "the shortcut did not reset to a blank diagram"
        );

        // The entry of the menu.
        let mut state = a_drawn_state_over(A_BOX);
        let outcome = take_the_entry(&mut state, 'f', "New");

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().session().diagram().shapes().count(),
            0,
            "the menu entry did not reset to a blank diagram"
        );
    }

    /// **`Ctrl+O` and the File menu's second entry open the same dialog**, and neither touches the
    /// session: the shortcut and the entry are one action.
    #[test]
    fn the_open_dialog_is_reached_by_the_shortcut_and_by_the_menus_entry() {
        // The shortcut.
        let mut state = a_drawn_state();
        let outcome = send(
            &key_with(KeyCode::Char('o'), KeyModifiers::CONTROL),
            &mut state,
        );

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(state.open().is_up(), "the shortcut did not open the dialog");

        // The entry of the menu.
        let mut state = a_drawn_state();
        open_the_open_dialog(&mut state);
        assert!(
            state.open().is_up(),
            "the menu entry did not open the dialog"
        );
    }

    /// **`Ctrl+S` and the File menu's third entry open the save dialog**, and neither touches the
    /// session: the shortcut and the entry are one action.
    #[test]
    fn the_save_dialog_is_reached_by_the_shortcut_and_by_the_menus_entry() {
        // The shortcut.
        let mut state = a_drawn_state();
        let outcome = send(
            &key_with(KeyCode::Char('s'), KeyModifiers::CONTROL),
            &mut state,
        );

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            state.save().is_up(),
            "the shortcut did not open the save dialog"
        );

        // The entry of the menu.
        let mut state = a_drawn_state();
        open_the_save_dialog(&mut state);
        assert!(
            state.save().is_up(),
            "the menu entry did not open the save dialog"
        );
    }

    /// **The closing event reaches nothing else** (rule 10): `Esc` closes the dialog, leaves the
    /// keyboard where the dialog was given it — the region, rule 13 — opens no drop-down, and
    /// changes neither the selection nor the history.
    #[test]
    fn escape_closes_the_about_dialog_and_the_event_reaches_nothing_else() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        open_the_about_dialog(&mut state);
        assert!(state.dialog().is_up(), "the dialog is not open");
        let focus = state.chrome().leaf();

        let outcome = send(&key(KeyCode::Esc), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(!state.dialog().is_up(), "escape did not close the dialog");
        assert_eq!(
            state.chrome().leaf(),
            focus,
            "the closing event moved the keyboard"
        );
        assert!(
            !state.chrome().popup_active(),
            "the closing event opened a drop-down"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the closing event changed the selection"
        );
        assert!(
            !state.diagram().can_undo(),
            "the closing event recorded a step"
        );
    }

    /// **The chrome's own and no session**: opening the open dialog records no step and changes
    /// no selection, so the drawing is exactly what it was.
    #[test]
    fn opening_the_open_dialog_changes_no_session() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(
            selected.is_some(),
            "the box was not selected, so the test proves nothing"
        );

        open_the_open_dialog(&mut state);

        assert_eq!(
            state.diagram().selected(),
            selected,
            "the dialog changed the selection"
        );
        assert!(
            !state.diagram().can_undo(),
            "opening the dialog recorded a step"
        );
        assert!(
            !state.diagram().can_redo(),
            "opening the dialog left a step ahead"
        );
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "opening the dialog removed the box"
        );
    }

    /// **The chrome's own and no session**: opening the save dialog records no step and changes
    /// no selection, so the drawing is exactly what it was.
    #[test]
    fn opening_the_save_dialog_changes_no_session() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(
            selected.is_some(),
            "the box was not selected, so the test proves nothing"
        );

        open_the_save_dialog(&mut state);

        assert_eq!(
            state.diagram().selected(),
            selected,
            "the dialog changed the selection"
        );
        assert!(
            !state.diagram().can_undo(),
            "opening the dialog recorded a step"
        );
        assert!(
            !state.diagram().can_redo(),
            "opening the dialog left a step ahead"
        );
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "opening the dialog removed the box"
        );
    }

    /// **The closing event reaches nothing else**: `Esc` closes the open dialog, leaves the
    /// keyboard on the region, opens no drop-down, and changes neither the selection nor history.
    #[test]
    fn escape_closes_the_open_dialog_and_the_event_reaches_nothing_else() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        open_the_open_dialog(&mut state);
        assert!(state.open().is_up(), "the open dialog is not open");
        let focus = state.chrome().leaf();

        let outcome = send(&key(KeyCode::Esc), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.open().is_up(),
            "escape did not close the open dialog"
        );
        assert_eq!(
            state.chrome().leaf(),
            focus,
            "the closing event moved the keyboard"
        );
        assert!(
            !state.chrome().popup_active(),
            "the closing event opened a drop-down"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the closing event changed the selection"
        );
        assert!(
            !state.diagram().can_undo(),
            "the closing event recorded a step"
        );
    }

    /// **The closing event reaches nothing else**: `Esc` closes the save dialog, leaves the
    /// keyboard on the region, opens no drop-down, and changes neither the selection nor history.
    #[test]
    fn escape_closes_the_save_dialog_and_the_event_reaches_nothing_else() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        open_the_save_dialog(&mut state);
        assert!(state.save().is_up(), "the save dialog is not open");
        let focus = state.chrome().leaf();

        let outcome = send(&key(KeyCode::Esc), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.save().is_up(),
            "escape did not close the save dialog"
        );
        assert_eq!(
            state.chrome().leaf(),
            focus,
            "the closing event moved the keyboard"
        );
        assert!(
            !state.chrome().popup_active(),
            "the closing event opened a drop-down"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the closing event changed the selection"
        );
        assert!(
            !state.diagram().can_undo(),
            "the closing event recorded a step"
        );
    }

    /// **The overlay takes the controls behind it**: `Ctrl+Q` does nothing while the open dialog
    /// is up, and a click on the bar behind it moves no keyboard and opens no menu.
    #[test]
    fn control_q_does_nothing_while_the_open_dialog_is_up() {
        let mut state = a_drawn_state_over(A_BOX);
        open_the_open_dialog(&mut state);
        let (column, row) = frame::cell_of(&draw(&mut state), "File");
        let focus = state.chrome().leaf();

        let outcome = send(
            &key_with(KeyCode::Char('q'), KeyModifiers::CONTROL),
            &mut state,
        );

        assert!(
            matches!(outcome, Control::Continue),
            "the way out was answered through the open dialog: {outcome:?}"
        );
        assert!(state.open().is_up(), "Ctrl+Q closed the open dialog");

        let _ = send(&click(column, row), &mut state);

        assert_eq!(
            state.chrome().leaf(),
            focus,
            "the click on the bar moved the keyboard"
        );
        assert!(
            !state.chrome().popup_active(),
            "the click behind the dialog opened a drop-down"
        );
        assert!(
            state.open().is_up(),
            "the click on the bar closed the open dialog"
        );
    }

    /// **The overlay takes the controls behind it**: `Ctrl+Q` does nothing while the save dialog
    /// is up, and a click on the bar behind it moves no keyboard and opens no menu.
    #[test]
    fn control_q_does_nothing_while_the_save_dialog_is_up() {
        let mut state = a_drawn_state_over(A_BOX);
        open_the_save_dialog(&mut state);
        let (column, row) = frame::cell_of(&draw(&mut state), "File");
        let focus = state.chrome().leaf();

        let outcome = send(
            &key_with(KeyCode::Char('q'), KeyModifiers::CONTROL),
            &mut state,
        );

        assert!(
            matches!(outcome, Control::Continue),
            "the way out was answered through the save dialog: {outcome:?}"
        );
        assert!(state.save().is_up(), "Ctrl+Q closed the save dialog");

        let _ = send(&click(column, row), &mut state);

        assert_eq!(
            state.chrome().leaf(),
            focus,
            "the click on the bar moved the keyboard"
        );
        assert!(
            !state.chrome().popup_active(),
            "the click behind the save dialog opened a drop-down"
        );
        assert!(
            state.save().is_up(),
            "the click on the bar closed the save dialog"
        );
    }

    /// **A file that loads starts a new session**: the diagram is the file's, the selection is
    /// gone, the history is empty, and no confirmation asked before the old one was discarded.
    #[test]
    fn a_file_that_loads_starts_a_new_session() {
        let path = write_description(
            "loaded",
            r#"{ "next_id": 2, "shapes": [ { "kind": "box", "id": 1, "at": { "x": 8, "y": 2 },
                                            "size": { "width": 3, "height": 2 }, "stroke": "light" } ] }"#,
        );

        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected, so the test proves nothing"
        );
        let _ = send(&key(KeyCode::Delete), &mut state);
        assert!(
            state.diagram().can_undo(),
            "the removal recorded no step, so the test proves nothing"
        );

        open_the_open_dialog(&mut state);
        state
            .open_mut()
            .get_mut()
            .expect("the open dialog is up")
            .set_path(path.to_str().expect("the temp path is UTF-8"));

        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(!state.open().is_up(), "the load left the dialog up");
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "the load moved the keyboard off the region"
        );
        assert_eq!(
            state.diagram().selected(),
            None,
            "the new session kept the old selection"
        );
        assert!(
            !state.diagram().can_undo(),
            "the new session kept the old history"
        );
        assert!(
            !state.diagram().can_redo(),
            "the new session kept the old history"
        );

        let _ = draw(&mut state);

        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_none(),
            "the old diagram is still there"
        );
        assert!(
            state.diagram().owner(Offset { x: 8, y: 2 }).is_some(),
            "the file's box is not there"
        );
    }

    /// **Taking New resets to an empty diagram immediately** (rule 4 of #273): the current
    /// session, selection, and undo history are discarded without confirmation.
    #[test]
    fn taking_new_discards_current_session_and_starts_blank() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected, so the test proves nothing"
        );
        let _ = send(&key(KeyCode::Delete), &mut state);
        assert!(
            state.diagram().can_undo(),
            "the removal recorded no step, so the test proves nothing"
        );

        let outcome = take_the_entry(&mut state, 'f', "New");

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "taking New moved the keyboard off the region"
        );
        assert_eq!(
            state.diagram().selected(),
            None,
            "the new session kept the old selection"
        );
        assert!(
            !state.diagram().can_undo(),
            "the new session kept the old history"
        );
        assert!(
            !state.diagram().can_redo(),
            "the new session kept the old history"
        );

        let _ = draw(&mut state);

        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_none(),
            "the old diagram is still there"
        );
        assert_eq!(
            state.diagram().session().diagram().shapes().count(),
            0,
            "the blank diagram is not empty"
        );
    }

    /// **Taking Open Demo resets to the demonstration diagram immediately** (rule 5 of #273): the
    /// current session, selection, and undo history are discarded without confirmation.
    #[test]
    fn taking_open_demo_discards_current_session_and_loads_demo() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected, so the test proves nothing"
        );
        let _ = send(&key(KeyCode::Delete), &mut state);
        assert!(
            state.diagram().can_undo(),
            "the removal recorded no step, so the test proves nothing"
        );

        let outcome = take_the_entry(&mut state, 'f', "Open Demo");

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "taking Open Demo moved the keyboard off the region"
        );
        assert_eq!(
            state.diagram().selected(),
            None,
            "the new session kept the old selection"
        );
        assert!(
            !state.diagram().can_undo(),
            "the new session kept the old history"
        );
        assert!(
            !state.diagram().can_redo(),
            "the new session kept the old history"
        );

        let _ = draw(&mut state);

        assert!(
            state.diagram().session().diagram().shapes().count() > 0,
            "the demonstration has no shapes"
        );
    }

    /// **Taking New or Open Demo leaves the keyboard on the region** (rule 6 of #273), and closes
    /// the drop-down.
    #[test]
    fn taking_new_or_open_demo_leaves_the_keyboard_on_the_region() {
        // Taking New from the menu.
        let mut state = a_drawn_state_over(A_BOX);
        let _ = take_the_entry(&mut state, 'f', "New");
        assert_eq!(state.chrome().leaf(), Focus::Region);
        assert!(!state.chrome().popup_active());

        // Pressing Ctrl+N with drop-down open.
        let mut state = a_drawn_state_over(A_BOX);
        open_the_drop_down(&mut state, 'f');
        assert_eq!(state.chrome().leaf(), Focus::Bar);
        let _ = send(
            &key_with(KeyCode::Char('n'), KeyModifiers::CONTROL),
            &mut state,
        );
        assert_eq!(state.chrome().leaf(), Focus::Region);
        assert!(!state.chrome().popup_active());

        // Taking Open Demo from the menu.
        let mut state = a_drawn_state_over(A_BOX);
        let _ = take_the_entry(&mut state, 'f', "Open Demo");
        assert_eq!(state.chrome().leaf(), Focus::Region);
        assert!(!state.chrome().popup_active());
    }

    /// **A missing file closes the open dialog and opens the error dialog**: the session is
    /// untouched and the failure names the missing file in the message dialog.
    #[test]
    fn a_missing_file_closes_the_open_dialog_and_opens_the_error_dialog() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();

        open_the_open_dialog(&mut state);
        state
            .open_mut()
            .get_mut()
            .expect("the open dialog is up")
            .set_path("missing.json");

        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(!state.open().is_up(), "the failure left the open dialog up");
        assert!(
            state.dialog().is_up(),
            "the failure did not open the error dialog"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the failure changed the selection"
        );
        assert!(!state.diagram().can_undo(), "the failure recorded a step");
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "the failure removed the box"
        );
    }

    /// **A file that does not parse closes the open dialog and opens the error dialog**: the
    /// session is untouched and the failure names the file in the message dialog.
    #[test]
    fn a_file_that_does_not_parse_closes_the_open_dialog_and_opens_the_error_dialog() {
        let path = write_description("bad", "not json");
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();

        open_the_open_dialog(&mut state);
        state
            .open_mut()
            .get_mut()
            .expect("the open dialog is up")
            .set_path(path.to_str().expect("the temp path is UTF-8"));

        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(!state.open().is_up(), "the failure left the open dialog up");
        assert!(
            state.dialog().is_up(),
            "the failure did not open the error dialog"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the failure changed the selection"
        );
        assert!(!state.diagram().can_undo(), "the failure recorded a step");
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "the failure removed the box"
        );
    }

    /// **A diagram is saved to a file and overwrites existing content**: saving serializes the
    /// current diagram to the path, creating or replacing the file.
    #[test]
    fn a_diagram_is_saved_to_a_file_and_overwrites_existing_content() {
        let path = std::env::temp_dir().join(format!(
            "monospace-save-overwrite-{}.json",
            std::process::id()
        ));
        let path_str = path.to_str().expect("temp path is UTF-8");
        std::fs::write(&path, "old content").expect("temp file is writable");

        let mut state = a_drawn_state_over(A_BOX);
        open_the_save_dialog(&mut state);
        state
            .save_mut()
            .get_mut()
            .expect("the save dialog is up")
            .set_path(path_str);

        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(!state.save().is_up(), "saving left the save dialog up");
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "saving moved the keyboard off the region"
        );

        let read = std::fs::read_to_string(&path).expect("saved file can be read");
        assert_ne!(
            read, "old content",
            "saving did not overwrite existing content"
        );
        let parsed = monospace_description::parse(&read).expect("saved JSON is valid description");
        assert_eq!(
            parsed.shapes().count(),
            1,
            "saved diagram is missing the box"
        );

        let _ = std::fs::remove_file(path);
    }

    /// **Saving leaves the current session and history intact** (rule 6 of #270): the file is
    /// written, but the current diagram, selection, and undo/redo stacks remain unchanged.
    #[test]
    fn saving_leaves_the_current_session_and_history_intact() {
        let path =
            std::env::temp_dir().join(format!("monospace-save-intact-{}.json", std::process::id()));
        let path_str = path.to_str().expect("temp path is UTF-8");

        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(selected.is_some(), "the box was not selected");

        // Perform a modification to create history
        let _ = send(&key(KeyCode::Right), &mut state);
        assert!(state.diagram().can_undo(), "movement created no undo step");

        open_the_save_dialog(&mut state);
        state
            .save_mut()
            .get_mut()
            .expect("the save dialog is up")
            .set_path(path_str);

        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(!state.save().is_up(), "saving left the save dialog up");
        assert_eq!(
            state.diagram().selected(),
            selected,
            "saving changed the selection"
        );
        assert!(state.diagram().can_undo(), "saving dropped the undo stack");
        assert!(!state.diagram().can_redo(), "saving modified redo stack");

        let _ = std::fs::remove_file(path);
    }

    /// **An empty path closes the save dialog and opens the error dialog** (rule 7 of #270): the
    /// session is untouched and the failure reports `": a file name is needed"`.
    #[test]
    fn an_empty_path_closes_the_save_dialog_and_opens_the_error_dialog() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();

        open_the_save_dialog(&mut state);
        assert_eq!(
            state.save().get().expect("the save dialog is up").path(),
            ""
        );

        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(!state.save().is_up(), "the failure left the save dialog up");
        assert!(
            state.dialog().is_up(),
            "the failure did not open the error dialog"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the failure changed the selection"
        );
        assert!(!state.diagram().can_undo(), "the failure recorded a step");

        let area = Rect::new(0, 0, WIDTH, 12);
        let mut buffer = Buffer::empty(area);
        frame::draw(area, &mut buffer, &mut state, &a_global());
        let shown: String = (0..12).map(|line| row_of(&buffer, line)).collect();
        assert!(
            shown.contains(": a file name is needed"),
            "the error dialog does not report the empty path message: {shown:?}"
        );
    }

    /// **A path in a missing directory closes the save dialog and opens the error dialog**
    /// (rule 7 of #270): the session is untouched and the failure names the missing directory.
    #[test]
    fn a_path_in_a_missing_directory_closes_the_save_dialog_and_opens_the_error_dialog() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();

        open_the_save_dialog(&mut state);
        let missing_path = "nonexistent_dir_12345/saved.json";
        state
            .save_mut()
            .get_mut()
            .expect("the save dialog is up")
            .set_path(missing_path);

        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(!state.save().is_up(), "the failure left the save dialog up");
        assert!(
            state.dialog().is_up(),
            "the failure did not open the error dialog"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the failure changed the selection"
        );
        assert!(!state.diagram().can_undo(), "the failure recorded a step");

        let area = Rect::new(0, 0, WIDTH, 12);
        let mut buffer = Buffer::empty(area);
        frame::draw(area, &mut buffer, &mut state, &a_global());
        let shown: String = (0..12).map(|line| row_of(&buffer, line)).collect();
        assert!(
            shown.contains("nonexistent_dir_12345"),
            "the error dialog does not name the missing directory: {shown:?}"
        );
    }

    /// **The chrome's own and no session**: opening the export dialog records no step and changes
    /// no selection, so the drawing is exactly what it was.
    #[test]
    fn opening_the_export_dialog_changes_no_session() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(
            selected.is_some(),
            "the box was not selected, so the test proves nothing"
        );

        open_the_export_dialog(&mut state);

        assert_eq!(
            state.diagram().selected(),
            selected,
            "the dialog changed the selection"
        );
        assert!(
            !state.diagram().can_undo(),
            "opening the dialog recorded a step"
        );
        assert!(
            !state.diagram().can_redo(),
            "opening the dialog left a step ahead"
        );
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "opening the dialog removed the box"
        );
    }

    /// **The closing event reaches nothing else**: `Esc` closes the export dialog, leaves the
    /// keyboard on the region, opens no drop-down, and changes neither the selection nor history.
    #[test]
    fn escape_closes_the_export_dialog_and_the_event_reaches_nothing_else() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        open_the_export_dialog(&mut state);
        assert!(state.export().is_up(), "the export dialog is not open");
        let focus = state.chrome().leaf();

        let outcome = send(&key(KeyCode::Esc), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.export().is_up(),
            "escape did not close the export dialog"
        );
        assert_eq!(
            state.chrome().leaf(),
            focus,
            "the closing event moved the keyboard"
        );
        assert!(
            !state.chrome().popup_active(),
            "the closing event opened a drop-down"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the closing event changed the selection"
        );
        assert!(
            !state.diagram().can_undo(),
            "the closing event recorded a step"
        );
    }

    /// **The overlay takes the controls behind it**: `Ctrl+Q` does nothing while the export dialog
    /// is up, and a click on the bar behind it moves no keyboard and opens no menu.
    #[test]
    fn control_q_does_nothing_while_the_export_dialog_is_up() {
        let mut state = a_drawn_state_over(A_BOX);
        open_the_export_dialog(&mut state);
        let (column, row) = frame::cell_of(&draw(&mut state), "File");
        let focus = state.chrome().leaf();

        let outcome = send(
            &key_with(KeyCode::Char('q'), KeyModifiers::CONTROL),
            &mut state,
        );

        assert!(
            matches!(outcome, Control::Continue),
            "the way out was answered through the export dialog: {outcome:?}"
        );
        assert!(state.export().is_up(), "Ctrl+Q closed the export dialog");

        let _ = send(&click(column, row), &mut state);

        assert_eq!(
            state.chrome().leaf(),
            focus,
            "the click on the bar moved the keyboard"
        );
        assert!(
            !state.chrome().popup_active(),
            "the click behind the export dialog opened a drop-down"
        );
        assert!(
            state.export().is_up(),
            "the click on the bar closed the export dialog"
        );
    }

    /// **A diagram is exported as text over its footprint and overwrites existing content** (rule
    /// 6 of #352): exporting renders the tight footprint of the current diagram to the path,
    /// creating or replacing the file.
    #[test]
    fn a_diagram_is_exported_as_text_over_its_footprint_and_overwrites_existing_content() {
        let path = std::env::temp_dir().join(format!(
            "monospace-export-overwrite-{}.txt",
            std::process::id()
        ));
        let path_str = path.to_str().expect("temp path is UTF-8");
        std::fs::write(&path, "old content").expect("temp file is writable");

        let mut state = a_drawn_state_over(A_BOX);
        open_the_export_dialog(&mut state);
        state
            .export_mut()
            .get_mut()
            .expect("the export dialog is up")
            .set_path(path_str);

        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.export().is_up(),
            "exporting left the export dialog up"
        );
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "exporting moved the keyboard off the region"
        );

        let read = std::fs::read_to_string(&path).expect("exported file can be read");
        assert_eq!(
            read, "┌──┐\n│  │\n└──┘\n",
            "exported text did not match the 4x3 box footprint"
        );

        let _ = std::fs::remove_file(path);
    }

    /// **An empty diagram exports an empty file** (rule 6 of #352): when nothing is drawn, the
    /// footprint is `None` and the exported file is `""` (0 bytes).
    #[test]
    fn an_empty_diagram_exports_an_empty_file() {
        let path =
            std::env::temp_dir().join(format!("monospace-export-empty-{}.txt", std::process::id()));
        let path_str = path.to_str().expect("temp path is UTF-8");
        std::fs::write(&path, "old content").expect("temp file is writable");

        let mut state = a_drawn_state_over(
            r#"{
                "next_id": 1,
                "shapes": []
            }"#,
        );
        open_the_export_dialog(&mut state);
        state
            .export_mut()
            .get_mut()
            .expect("the export dialog is up")
            .set_path(path_str);

        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.export().is_up(),
            "exporting left the export dialog up"
        );

        let read = std::fs::read_to_string(&path).expect("exported file can be read");
        assert_eq!(read, "", "empty diagram did not export an empty file");

        let _ = std::fs::remove_file(path);
    }

    /// **Exporting leaves the current session and history intact** (rule 6 of #352): the file is
    /// written, but the current diagram, selection, and undo/redo stacks remain unchanged.
    #[test]
    fn exporting_leaves_the_current_session_and_history_intact() {
        let path = std::env::temp_dir().join(format!(
            "monospace-export-intact-{}.txt",
            std::process::id()
        ));
        let path_str = path.to_str().expect("temp path is UTF-8");

        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(selected.is_some(), "the box was not selected");

        let _ = send(&key(KeyCode::Right), &mut state);
        assert!(state.diagram().can_undo(), "movement created no undo step");

        open_the_export_dialog(&mut state);
        state
            .export_mut()
            .get_mut()
            .expect("the export dialog is up")
            .set_path(path_str);

        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.export().is_up(),
            "exporting left the export dialog up"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "exporting changed the selection"
        );
        assert!(
            state.diagram().can_undo(),
            "exporting dropped the undo stack"
        );
        assert!(!state.diagram().can_redo(), "exporting modified redo stack");

        let _ = std::fs::remove_file(path);
    }

    /// **An empty path closes the export dialog and opens the error dialog** (rule 7 of #352): the
    /// session is untouched and the failure reports `": a file name is needed"`.
    #[test]
    fn an_empty_path_closes_the_export_dialog_and_opens_the_error_dialog() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();

        open_the_export_dialog(&mut state);
        assert_eq!(
            state
                .export()
                .get()
                .expect("the export dialog is up")
                .path(),
            ""
        );

        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.export().is_up(),
            "the failure left the export dialog up"
        );
        assert!(
            state.dialog().is_up(),
            "the failure did not open the error dialog"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the failure changed the selection"
        );
        assert!(!state.diagram().can_undo(), "the failure recorded a step");

        let area = Rect::new(0, 0, WIDTH, 12);
        let mut buffer = Buffer::empty(area);
        frame::draw(area, &mut buffer, &mut state, &a_global());
        let shown: String = (0..12).map(|line| row_of(&buffer, line)).collect();
        assert!(
            shown.contains(": a file name is needed"),
            "the error dialog does not report the empty path message: {shown:?}"
        );
    }

    /// **A path in a missing directory closes the export dialog and opens the error dialog**
    /// (rule 7 of #352): the session is untouched and the failure names the missing directory.
    #[test]
    fn a_path_in_a_missing_directory_closes_the_export_dialog_and_opens_the_error_dialog() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();

        open_the_export_dialog(&mut state);
        let missing_path = "nonexistent_dir_12345/exported.txt";
        state
            .export_mut()
            .get_mut()
            .expect("the export dialog is up")
            .set_path(missing_path);

        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.export().is_up(),
            "the failure left the export dialog up"
        );
        assert!(
            state.dialog().is_up(),
            "the failure did not open the error dialog"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the failure changed the selection"
        );
        assert!(!state.diagram().can_undo(), "the failure recorded a step");

        let area = Rect::new(0, 0, WIDTH, 12);
        let mut buffer = Buffer::empty(area);
        frame::draw(area, &mut buffer, &mut state, &a_global());
        let shown: String = (0..12).map(|line| row_of(&buffer, line)).collect();
        assert!(
            shown.contains("nonexistent_dir_12345"),
            "the error dialog does not name the missing directory: {shown:?}"
        );
    }

    /// **The overlay takes the controls behind it** (rule 10): `Ctrl+Q` is `Unclaimed`, so while
    /// the dialog is up the dialog answers it and nothing happens, and a click on the bar behind
    /// it moves no keyboard and opens no menu. `Ctrl+Shift+Q` is answered before the dialog, and
    /// [`the_forced_exit_ends_the_application_whatever_the_state_is`] is where that is proven.
    #[test]
    fn control_q_does_nothing_while_the_dialog_is_up() {
        let mut state = a_drawn_state_over(A_BOX);
        open_the_about_dialog(&mut state);
        let (column, row) = frame::cell_of(&draw(&mut state), "File");
        let focus = state.chrome().leaf();

        let outcome = send(
            &key_with(KeyCode::Char('q'), KeyModifiers::CONTROL),
            &mut state,
        );

        assert!(
            matches!(outcome, Control::Continue),
            "the way out was answered through the dialog: {outcome:?}"
        );
        assert!(state.dialog().is_up(), "Ctrl+Q closed the dialog");

        // The bar is behind the overlay even where the dialog does not cover it.
        let _ = send(&click(column, row), &mut state);

        assert_eq!(
            state.chrome().leaf(),
            focus,
            "the click on the bar moved the keyboard"
        );
        assert!(
            !state.chrome().popup_active(),
            "the click behind the dialog opened a drop-down"
        );
        assert!(
            state.dialog().is_up(),
            "the click on the bar closed the dialog"
        );
    }

    /// **Closing leaves the region byte-identical** (rule 11): the dialog is drawn over it and
    /// taken away, and every cell it covered is what it was, the selection's inversion included.
    #[test]
    fn the_region_is_byte_identical_after_the_dialog_closes() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let before = draw(&mut state);

        open_the_about_dialog(&mut state);
        let during = draw(&mut state);
        let shown: String = (0..HEIGHT).map(|line| row_of(&during, line)).collect();
        assert!(
            shown.contains(&format!("About {}", status::NAME)),
            "the dialog is not over the region: {shown:?}"
        );

        let outcome = send(&key(KeyCode::Esc), &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");

        let after = draw(&mut state);
        let region = frame::regions(Rect::new(0, 0, WIDTH, HEIGHT)).region;

        for line in region.top()..region.bottom() {
            for column in region.left()..region.right() {
                assert_eq!(
                    before[(column, line)].symbol(),
                    after[(column, line)].symbol(),
                    "({column}, {line}) is not what it was"
                );
                assert_eq!(
                    before[(column, line)].style(),
                    after[(column, line)].style(),
                    "({column}, {line}) is painted differently"
                );
            }
        }
    }

    #[test]
    fn the_way_out_is_reached_by_the_shortcut_and_by_the_menus_entry() {
        // The shortcut.
        let mut state = a_drawn_state();
        let outcome = send(
            &key_with(KeyCode::Char('q'), KeyModifiers::CONTROL),
            &mut state,
        );

        assert!(matches!(outcome, Control::Quit), "{outcome:?}");

        // The entry of the menu.
        let mut state = a_drawn_state();
        let outcome = take_the_entry(&mut state, 'f', "Quit");

        assert!(matches!(outcome, Control::Quit), "{outcome:?}");
    }

    #[test]
    fn a_click_on_the_entry_and_its_shortcut_apply_the_same_action() {
        // The shortcut.
        let mut state = a_drawn_state();
        let by_shortcut = send(
            &key_with(KeyCode::Char('q'), KeyModifiers::CONTROL),
            &mut state,
        );

        // The click on the entry of the menu.
        let mut state = a_drawn_state();
        let by_click = take_the_entry(&mut state, 'f', "Quit");

        assert_eq!(
            by_click, by_shortcut,
            "the click and the shortcut are two code paths"
        );
    }

    #[test]
    fn the_forced_exit_ends_the_application_whatever_the_state_is() {
        // The drop-down is open: the chrome holds the keyboard, and the forced exit is not the
        // chrome's to answer.
        let mut state = a_drawn_state();
        open_the_drop_down(&mut state, 'f');

        let outcome = send(
            &key_with(
                KeyCode::Char('Q'),
                KeyModifiers::CONTROL.union(KeyModifiers::SHIFT),
            ),
            &mut state,
        );

        assert!(matches!(outcome, Control::Quit), "{outcome:?}");

        // The About dialog is up: the overlay takes every control but this one, which is
        // answered before it (D6 of #189).
        let mut state = a_drawn_state();
        open_the_about_dialog(&mut state);
        assert!(state.dialog().is_up(), "the dialog is not open");

        let outcome = send(
            &key_with(
                KeyCode::Char('Q'),
                KeyModifiers::CONTROL.union(KeyModifiers::SHIFT),
            ),
            &mut state,
        );

        assert!(
            matches!(outcome, Control::Quit),
            "the dialog swallowed the forced exit: {outcome:?}"
        );

        // The save dialog is up: the overlay takes every control but this one.
        let mut state = a_drawn_state();
        open_the_save_dialog(&mut state);
        assert!(state.save().is_up(), "the save dialog is not open");

        let outcome = send(
            &key_with(
                KeyCode::Char('Q'),
                KeyModifiers::CONTROL.union(KeyModifiers::SHIFT),
            ),
            &mut state,
        );

        assert!(
            matches!(outcome, Control::Quit),
            "the save dialog swallowed the forced exit: {outcome:?}"
        );

        // The export dialog is up: the overlay takes every control but this one.
        let mut state = a_drawn_state();
        open_the_export_dialog(&mut state);
        assert!(state.export().is_up(), "the export dialog is not open");

        let outcome = send(
            &key_with(
                KeyCode::Char('Q'),
                KeyModifiers::CONTROL.union(KeyModifiers::SHIFT),
            ),
            &mut state,
        );

        assert!(
            matches!(outcome, Control::Quit),
            "the export dialog swallowed the forced exit: {outcome:?}"
        );

        // The text editor is up: the overlay takes every control but this one.
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::Char('t')), &mut state);
        assert!(state.text().is_up(), "the text editor is not open");

        let outcome = send(
            &key_with(
                KeyCode::Char('Q'),
                KeyModifiers::CONTROL.union(KeyModifiers::SHIFT),
            ),
            &mut state,
        );

        assert!(
            matches!(outcome, Control::Quit),
            "the text editor swallowed the forced exit: {outcome:?}"
        );
    }

    /// **Every shortcut of the first reach, and not the one that happens to be in the table
    /// today.** The promise is that nothing may consume these keys, and a test that named
    /// `Ctrl+Shift+Q` would keep passing the day a second one is added and the chrome swallows it.
    #[test]
    fn every_shortcut_answered_first_is_answered_with_the_drop_down_open() {
        for event in shortcuts::events_answered_first() {
            let mut state = a_drawn_state();
            open_the_drop_down(&mut state, 'f');

            let outcome = send(&event, &mut state);

            assert!(
                matches!(outcome, Control::Quit),
                "{event:?} was swallowed by the chrome: {outcome:?}"
            );
        }
    }

    /// **A key the table does not name is not an action**, and an action is the only thing the
    /// application's handling produces. What the chrome does with its own keys is the widget's
    /// state rather than the application's, and this is the application's half of it.
    #[test]
    fn a_key_with_no_action_changes_nothing() {
        let mut state = a_drawn_state();

        let outcome = send(&key(KeyCode::Char('z')), &mut state);

        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
        assert!(
            !state.chrome().popup_active(),
            "a key with no action changed the state"
        );
    }

    /// **A click asks the drawing rather than a drawing of its own**, and the identity it finds is
    /// what the state holds afterwards.
    #[test]
    fn a_left_click_selects_the_shape_that_owns_the_cell() {
        let mut state = a_drawn_state_over(A_BOX);
        let owner = state.diagram().owner(Offset { x: 2, y: 1 });
        assert!(owner.is_some(), "the box is not in the drawing");

        // The screen's `(3, 3)` is the window's `(2, 1)`: the region's interior starts one row
        // and one column in from the region's corner.
        let outcome = send(&click(3, 3), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().selected(),
            owner,
            "the click selected another shape"
        );
    }

    /// **A click on a cell nobody owns is the way out of a selection** (D3): the empty space is the
    /// target that always means nothing. A second click there has nothing left to drop.
    #[test]
    fn a_click_on_a_cell_nobody_owns_drops_the_selection() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected"
        );

        // The window's own corner: the interior, and no shape wrote it.
        let outcome = send(&click(1, 2), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().selected(),
            None,
            "the selection survived a blank cell"
        );

        let outcome = send(&click(1, 2), &mut state);

        assert!(
            matches!(outcome, Control::Continue),
            "there was nothing to drop and the frame was owed: {outcome:?}"
        );
    }

    /// **The region is where the keyboard starts** (D1 of #189): the diagram is what a person came
    /// to work on, so the bar does not promise a menu before a drawing.
    #[test]
    fn the_diagram_region_holds_the_keyboard_at_startup() {
        let state = a_state();

        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "the bar started with the keyboard"
        );
    }

    /// **A left press inside the region's rectangle gives it the keyboard, and inside the interior
    /// it selects as well.** The bar held it first, so the press is what moves it.
    #[test]
    fn a_press_inside_the_region_moves_the_keyboard_and_selects() {
        let mut state = a_drawn_state_over(A_BOX);
        state.chrome_mut().move_to_bar();
        let _ = draw(&mut state);

        let outcome = send(&click(3, 3), &mut state);

        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "the press left the keyboard on the bar"
        );
        assert!(
            state.diagram().selected().is_some(),
            "the press inside the interior selected nothing"
        );
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
    }

    /// **The border is the region's without being the window's**: a press there gives it the
    /// keyboard and selects nothing, and a selection already made survives.
    #[test]
    fn a_press_on_the_border_moves_the_keyboard_and_selects_nothing() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(
            selected.is_some(),
            "the box was not selected, so the test proves nothing"
        );

        for (column, row, what) in [
            (3, 1, "the top border"),
            (0, 3, "the left border"),
            (WIDTH - 1, 3, "the right border"),
            (3, HEIGHT - 3, "the bottom border"),
        ] {
            state.chrome_mut().move_to_bar();
            let _ = draw(&mut state);

            let outcome = send(&click(column, row), &mut state);

            assert_eq!(
                state.chrome().leaf(),
                Focus::Region,
                "{what} did not give the region the keyboard"
            );
            assert_eq!(
                state.diagram().selected(),
                selected,
                "{what} changed the selection"
            );
            assert!(matches!(outcome, Control::Changed), "{what}: {outcome:?}");
        }
    }

    /// **The status line is not a leaf**: a press there moves the keyboard nowhere and owes no
    /// frame.
    #[test]
    fn a_click_on_the_status_bar_moves_nothing() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        state.chrome_mut().move_to_bar();
        let _ = draw(&mut state);

        let outcome = send(&click(3, HEIGHT - 1), &mut state);

        assert_eq!(
            state.chrome().leaf(),
            Focus::Bar,
            "the status line took the keyboard"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the status line changed the selection"
        );
        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
    }

    /// **A press on a label gives the bar the keyboard and opens that label's drop-down**, which is
    /// what lets a person work by pointer without reaching for `Alt` first.
    #[test]
    fn a_press_on_a_label_moves_the_keyboard_and_opens_its_drop_down() {
        let mut state = a_drawn_state_over(A_BOX);
        let buffer = draw(&mut state);
        let (column, row) = frame::cell_of(&buffer, "File");

        let outcome = send(&click(column, row), &mut state);

        assert_eq!(
            state.chrome().leaf(),
            Focus::Bar,
            "the label did not give the bar the keyboard"
        );
        assert!(
            state.chrome().popup_active(),
            "the label did not open its drop-down"
        );
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
    }

    /// **A press in the region is not swallowed by an open drop-down** (D6): it moves the keyboard
    /// to the region, closes the drop-down on the same press, and selects inside the interior.
    #[test]
    fn a_press_in_the_region_closes_the_drop_down_and_selects() {
        let mut state = a_drawn_state_over(A_BOX_AND_WHAT_HANGS_FROM_IT);
        open_the_drop_down(&mut state, 'h');
        assert!(state.chrome().popup_active(), "the drop-down did not open");

        // The left box's top-left is outside the Help drop-down, so the press is the region's.
        let outcome = send(&click(1, 3), &mut state);

        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "the press left the keyboard on the bar; the drop-down is {:?}",
            state.chrome().menu().popup.area
        );
        assert!(
            !state.chrome().popup_active(),
            "the drop-down survived the keyboard leaving it"
        );
        assert!(
            state.diagram().selected().is_some(),
            "the press inside the interior selected nothing"
        );
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
    }

    /// **The arrows are not the bar's while the region holds the keyboard** (rule 5): they open no
    /// drop-down and move no label, so #179 and #176 can bind them from here. With nothing selected,
    /// each answers `Continue` because the arrow is ignored by the region.
    #[test]
    fn the_arrows_are_not_the_bars_while_the_region_holds_the_keyboard() {
        let mut state = a_drawn_state();
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "the bar started with the keyboard"
        );

        for arrow in [KeyCode::Left, KeyCode::Right, KeyCode::Up, KeyCode::Down] {
            let selected = state.chrome().menu().bar.selected;
            let outcome = send(&key(arrow), &mut state);

            assert!(
                matches!(outcome, Control::Continue),
                "{arrow:?}: {outcome:?}"
            );
            assert!(
                !state.chrome().popup_active(),
                "{arrow:?} opened a drop-down"
            );
            assert_eq!(
                state.chrome().menu().bar.selected,
                selected,
                "{arrow:?} moved the bar's label"
            );
        }
    }

    /// **The right arrow displaces the selected figure one cell** (rule 1): one command, one step,
    /// and the next frame draws the box where the move put it.
    #[test]
    fn the_right_arrow_moves_the_selected_shape_one_cell() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected"
        );
        let before = draw(&mut state);

        let outcome = send(&key(KeyCode::Right), &mut state);
        let after = draw(&mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(state.diagram().can_undo(), "the move recorded no step");
        assert_eq!(
            state.diagram().owner(Offset { x: 3, y: 1 }),
            state.diagram().selected(),
            "the drawing does not record the box one cell right"
        );
        assert_eq!(
            before[(3, 3)].symbol(),
            "┌",
            "the test's frame does not start where it says"
        );
        assert_eq!(
            after[(4, 3)].symbol(),
            "┌",
            "the frame does not draw the box one cell right"
        );
        assert_eq!(
            after[(3, 3)].symbol(),
            " ",
            "the frame still draws the box where it stood"
        );
    }

    /// **Each arrow moves along its own axis** (rule 1): Right, Left, Up and Down displace the
    /// figure by the sign their axis names and no other.
    #[test]
    fn each_arrow_moves_along_its_own_axis() {
        for (arrow, at) in [
            (KeyCode::Right, Offset { x: 3, y: 1 }),
            (KeyCode::Left, Offset { x: 1, y: 1 }),
            (KeyCode::Up, Offset { x: 2, y: 0 }),
            (KeyCode::Down, Offset { x: 2, y: 2 }),
        ] {
            let mut state = a_drawn_state_over(A_BOX);
            let _ = send(&click(3, 3), &mut state);
            assert!(
                state.diagram().selected().is_some(),
                "{arrow:?}: the box was not selected"
            );

            let outcome = send(&key(arrow), &mut state);
            let _ = draw(&mut state);

            assert!(
                matches!(outcome, Control::Changed),
                "{arrow:?}: {outcome:?}"
            );
            assert_eq!(
                state.diagram().owner(at),
                state.diagram().selected(),
                "{arrow:?} did not move the box along its own axis"
            );
            assert!(state.diagram().can_undo(), "{arrow:?} recorded no step");
        }
    }

    /// **Each press is its own step** (rule 2): two presses are two commands, and the undo gives
    /// back one cell per press rather than the whole walk.
    #[test]
    fn two_presses_are_two_steps() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);

        let _ = send(&key(KeyCode::Right), &mut state);
        let _ = send(&key(KeyCode::Right), &mut state);
        let _ = draw(&mut state);

        assert!(
            state.diagram().owner(Offset { x: 4, y: 1 }).is_some(),
            "the two presses did not move the box twice"
        );
        assert_eq!(
            state.diagram().owner(Offset { x: 3, y: 1 }),
            None,
            "the second press moved nothing"
        );

        let _ = send(&undo_key(), &mut state);
        let _ = draw(&mut state);

        assert!(
            state.diagram().owner(Offset { x: 3, y: 1 }).is_some(),
            "one undo did not give back one press"
        );

        let _ = send(&undo_key(), &mut state);
        let _ = draw(&mut state);

        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "the second undo did not give back the first press"
        );
        assert!(
            !state.diagram().can_undo(),
            "two presses were more than two steps"
        );
    }

    /// **The selection survives the move** (rule 3): the next frame inverts the cells the figure
    /// now owns rather than the ones it left.
    #[test]
    fn a_move_keeps_the_selection() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(selected.is_some(), "the box was not selected");

        let _ = send(&key(KeyCode::Right), &mut state);
        let buffer = draw(&mut state);

        assert_eq!(
            state.diagram().selected(),
            selected,
            "the move dropped the selection"
        );
        assert!(
            reversed(&buffer, 4, 3),
            "the frame does not invert the cells the box now owns"
        );
        assert!(
            !reversed(&buffer, 3, 3),
            "the frame still inverts the cell the box left"
        );
    }

    /// **The selection survives the resize**: applying `Command::Resize` keeps the selected shape.
    #[test]
    fn an_action_resize_resizes_the_selected_shape_and_keeps_selection() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(selected.is_some(), "the box was not selected");

        apply(
            &Action::Command(Command::Resize {
                id: selected.unwrap(),
                by: (1, 0).into(),
            }),
            &mut state,
        );

        assert_eq!(state.diagram().selected(), selected);
        assert!(state.diagram().can_undo());
        let shape = state.diagram().session().diagram().get(selected.unwrap());
        let Some(monospace_diagram::Shape::Box { size, .. }) = shape else {
            panic!("expected box");
        };
        assert_eq!(size.width, 5);
    }

    /// **Shift plus an arrow resizes the selected box by one cell** (rule 1 of #284).
    #[test]
    fn shift_arrows_resize_the_selected_box_by_one_cell() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(selected.is_some(), "the box was not selected");

        let shift_right = Event::Key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT));
        let outcome = send(&shift_right, &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");

        let shape = state.diagram().session().diagram().get(selected.unwrap());
        let Some(monospace_diagram::Shape::Box { size, .. }) = shape else {
            panic!("expected box");
        };
        assert_eq!(size.width, 5);
        assert_eq!(size.height, 3);
    }

    /// **A box at its minimum still accepts the resize and records no step** (#285).
    ///
    /// **The key is dispatched and the frame is owed**, which is what #288 settled: the box has a
    /// size, so the region answers. What does not happen is a step: the figure comes back 2×2, so
    /// `Undo` has nothing to give back.
    #[test]
    fn a_box_at_its_minimum_accepts_the_resize_and_records_no_step() {
        let mut state = a_drawn_state_over(A_BOX_AT_ITS_SMALLEST);
        let _ = send(&click(3, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected"
        );

        let shift_left = Event::Key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT));
        let outcome = send(&shift_left, &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.diagram().can_undo(),
            "a resize that changes no size records no step"
        );
    }

    /// **With nothing selected, Shift+arrow performs no command and records no step** (rule 4 of #284).
    #[test]
    fn a_resize_with_nothing_selected_performs_no_command() {
        let mut state = a_drawn_state_over(A_BOX);
        let shift_right = Event::Key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT));
        let outcome = send(&shift_right, &mut state);

        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
        assert!(!state.diagram().can_undo());
    }

    /// **A resize keeps the selection** (rule 5 of #284).
    #[test]
    fn a_resize_keeps_the_selection() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();

        let shift_right = Event::Key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT));
        let _ = send(&shift_right, &mut state);

        assert_eq!(state.diagram().selected(), selected);
    }

    /// **Two resizes are two steps** (rule 7 of #284): undo gives back one cell per press.
    #[test]
    fn two_resizes_are_two_steps() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();

        let shift_right = Event::Key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT));
        let _ = send(&shift_right, &mut state);
        let _ = send(&shift_right, &mut state);

        let shape = state.diagram().session().diagram().get(selected.unwrap());
        let Some(monospace_diagram::Shape::Box { size, .. }) = shape else {
            panic!("expected box");
        };
        assert_eq!(size.width, 6);

        state.diagram_mut().undo();
        let shape = state.diagram().session().diagram().get(selected.unwrap());
        let Some(monospace_diagram::Shape::Box { size, .. }) = shape else {
            panic!("expected box");
        };
        assert_eq!(size.width, 5);
    }

    /// **Shift arrows resize a horizontal line along its row; vertical arrows are ignored** (D1 of #301).
    #[test]
    fn shift_arrows_resize_the_selected_horizontal_line_along_its_orientation() {
        let mut state = a_drawn_state_over(A_HORIZONTAL_LINE);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(selected.is_some(), "the line was not selected");

        let shift_up = Event::Key(KeyEvent::new(KeyCode::Up, KeyModifiers::SHIFT));
        let shift_down = Event::Key(KeyEvent::new(KeyCode::Down, KeyModifiers::SHIFT));
        assert!(matches!(send(&shift_up, &mut state), Control::Continue));
        assert!(matches!(send(&shift_down, &mut state), Control::Continue));
        assert!(!state.diagram().can_undo());

        let shift_right = Event::Key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT));
        let outcome = send(&shift_right, &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");

        let shape = state.diagram().session().diagram().get(selected.unwrap());
        let Some(monospace_diagram::Shape::Line { len, .. }) = shape else {
            panic!("expected line");
        };
        assert_eq!(*len, 7);
        assert!(state.diagram().can_undo());

        let shift_left = Event::Key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT));
        let outcome = send(&shift_left, &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");

        let shape = state.diagram().session().diagram().get(selected.unwrap());
        let Some(monospace_diagram::Shape::Line { len, .. }) = shape else {
            panic!("expected line");
        };
        assert_eq!(*len, 6);
    }

    /// **Shift arrows resize a vertical line along its column; horizontal arrows are ignored** (D1 of #301).
    #[test]
    fn shift_arrows_resize_the_selected_vertical_line_along_its_orientation() {
        let mut state = a_drawn_state_over(A_VERTICAL_LINE);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(selected.is_some(), "the line was not selected");

        let shift_left = Event::Key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT));
        let shift_right = Event::Key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT));
        assert!(matches!(send(&shift_left, &mut state), Control::Continue));
        assert!(matches!(send(&shift_right, &mut state), Control::Continue));
        assert!(!state.diagram().can_undo());

        let shift_down = Event::Key(KeyEvent::new(KeyCode::Down, KeyModifiers::SHIFT));
        let outcome = send(&shift_down, &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");

        let shape = state.diagram().session().diagram().get(selected.unwrap());
        let Some(monospace_diagram::Shape::Line { len, .. }) = shape else {
            panic!("expected line");
        };
        assert_eq!(*len, 4);

        let shift_up = Event::Key(KeyEvent::new(KeyCode::Up, KeyModifiers::SHIFT));
        let outcome = send(&shift_up, &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");

        let shape = state.diagram().session().diagram().get(selected.unwrap());
        let Some(monospace_diagram::Shape::Line { len, .. }) = shape else {
            panic!("expected line");
        };
        assert_eq!(*len, 3);
    }

    /// **A line at its minimum length accepts the resize and records no step** (rule 3 of #301, #285).
    #[test]
    fn a_line_at_its_minimum_accepts_the_resize_and_records_no_step() {
        let mut state = a_drawn_state_over(A_LINE_AT_ITS_MINIMUM);
        let _ = send(&click(3, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the line was not selected"
        );

        let shift_left = Event::Key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT));
        let outcome = send(&shift_left, &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.diagram().can_undo(),
            "a resize that changes no length records no step"
        );
    }

    /// **A zero-length line is not shrunk and grows to one in the application** (rule 3 of #301).
    #[test]
    fn a_zero_length_line_is_not_shrunk_and_grows_to_one_in_the_application() {
        let mut state = a_drawn_state_over(A_ZERO_LENGTH_LINE);
        state
            .diagram_mut()
            .select(Some(ShapeId::new(NonZeroU16::new(1).unwrap())));

        let shift_left = Event::Key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT));
        let outcome = send(&shift_left, &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");

        let shape = state
            .diagram()
            .session()
            .diagram()
            .get(ShapeId::new(NonZeroU16::new(1).unwrap()));
        let Some(monospace_diagram::Shape::Line { len, .. }) = shape else {
            panic!("expected line");
        };
        assert_eq!(*len, 0);
        assert!(!state.diagram().can_undo());

        let shift_right = Event::Key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT));
        let outcome = send(&shift_right, &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");

        let shape = state
            .diagram()
            .session()
            .diagram()
            .get(ShapeId::new(NonZeroU16::new(1).unwrap()));
        let Some(monospace_diagram::Shape::Line { len, .. }) = shape else {
            panic!("expected line");
        };
        assert_eq!(*len, 1);
        assert!(state.diagram().can_undo());
    }

    /// **Two line resizes are two steps** (rule 5 of #301): undo gives back one cell per press.
    #[test]
    fn two_line_resizes_are_two_steps() {
        let mut state = a_drawn_state_over(A_HORIZONTAL_LINE);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();

        let shift_right = Event::Key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT));
        let _ = send(&shift_right, &mut state);
        let _ = send(&shift_right, &mut state);

        let shape = state.diagram().session().diagram().get(selected.unwrap());
        let Some(monospace_diagram::Shape::Line { len, .. }) = shape else {
            panic!("expected line");
        };
        assert_eq!(*len, 8);

        state.diagram_mut().undo();
        let shape = state.diagram().session().diagram().get(selected.unwrap());
        let Some(monospace_diagram::Shape::Line { len, .. }) = shape else {
            panic!("expected line");
        };
        assert_eq!(*len, 7);

        state.diagram_mut().undo();
        let shape = state.diagram().session().diagram().get(selected.unwrap());
        let Some(monospace_diagram::Shape::Line { len, .. }) = shape else {
            panic!("expected line");
        };
        assert_eq!(*len, 6);

        state.diagram_mut().redo();
        let shape = state.diagram().session().diagram().get(selected.unwrap());
        let Some(monospace_diagram::Shape::Line { len, .. }) = shape else {
            panic!("expected line");
        };
        assert_eq!(*len, 7);
    }

    /// **A line resize keeps the selection** (rule 5 of #301).
    #[test]
    fn a_line_resize_keeps_the_selection() {
        let mut state = a_drawn_state_over(A_HORIZONTAL_LINE);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();

        let shift_right = Event::Key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT));
        let _ = send(&shift_right, &mut state);

        assert_eq!(state.diagram().selected(), selected);
    }

    /// **A plain arrow still moves** (rule 8 of #284).
    #[test]
    fn a_plain_arrow_still_moves() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();

        let right = Event::Key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE));
        let _ = send(&right, &mut state);

        let shape = state.diagram().session().diagram().get(selected.unwrap());
        let Some(monospace_diagram::Shape::Box { at, size, .. }) = shape else {
            panic!("expected box");
        };
        assert_eq!(at.x, 3);
        assert_eq!(size.width, 4);
    }

    /// **No other modifier combination resizes** (rule 8 of #284): Ctrl+Shift is ignored.
    #[test]
    fn no_other_modifier_resizes() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);

        let ctrl_shift_right = Event::Key(KeyEvent::new(
            KeyCode::Right,
            KeyModifiers::CONTROL | KeyModifiers::SHIFT,
        ));
        let outcome = send(&ctrl_shift_right, &mut state);
        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
        assert!(!state.diagram().can_undo());
    }

    /// **While the bar holds the keyboard, Shift+arrow resizes nothing** (rule 9 of #284).
    #[test]
    fn shift_arrow_with_the_bar_focused_resizes_nothing() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::F(10)), &mut state);

        let shift_right = Event::Key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT));
        let _ = send(&shift_right, &mut state);

        assert!(!state.diagram().can_undo());
    }

    /// **A resize carries the connector hanging from the right side** (rule 6 of #284).
    #[test]
    fn a_resize_carries_the_connector_hanging_from_the_right_side() {
        let text = r#"{
  "next_id": 3,
  "shapes": [
    { "kind": "box", "id": 1, "at": { "x": 2, "y": 1 }, "size": { "width": 4, "height": 3 },
      "stroke": "light" },
    { "kind": "connector", "id": 2,
      "from": { "at": { "kind": "reference", "shape": 1, "anchor": "right",
                        "offset": { "dx": 2, "dy": 0 } },
                "terminal": { "kind": "arm" } },
      "to":   { "at": { "kind": "point", "x": 15, "y": 2 },
                "leaving": "left", "terminal": { "kind": "arm" } },
      "stroke": "light" }
  ]
}"#;
        let mut state = a_drawn_state_over(text);
        let _ = send(&click(3, 3), &mut state);
        let shift_right = Event::Key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT));
        let _ = send(&shift_right, &mut state);

        let shape = state
            .diagram()
            .session()
            .diagram()
            .get(state.diagram().selected().expect("shape was selected"));
        let Some(monospace_diagram::Shape::Box { size, .. }) = shape else {
            panic!("expected box");
        };
        assert_eq!(size.width, 5);
    }

    /// **A move with nothing selected moves nothing**: no figure is selected, so no step is
    /// recorded, no figure moves, and the answer is `Continue` because the arrow is ignored.
    #[test]
    fn a_move_with_nothing_selected_moves_nothing() {
        let mut state = a_drawn_state_over(A_BOX);

        let outcome = send(&key(KeyCode::Right), &mut state);

        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
        assert!(
            !state.diagram().can_undo(),
            "a move with nothing selected recorded a step"
        );
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "the box moved with nothing selected"
        );
    }

    /// **The dialog is the overlay and takes the arrow too** (rule 6): a move behind it changes
    /// nothing, because the event never reaches the region.
    #[test]
    fn an_arrow_while_the_dialog_is_up_moves_nothing() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected"
        );
        open_the_about_dialog(&mut state);

        let _ = send(&key(KeyCode::Right), &mut state);

        assert!(
            state.dialog().is_up(),
            "the arrow closed the dialog it should not have reached"
        );
        assert!(
            !state.diagram().can_undo(),
            "a key the dialog swallowed recorded a step"
        );
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "the box moved behind the dialog"
        );
    }

    /// **A carried-out move leaves the keyboard on the region** (rule 7), closing the drop-down
    /// the bar was showing, as every other carried-out meaning does.
    #[test]
    fn a_move_leaves_the_keyboard_on_the_region() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected"
        );
        state.chrome_mut().menu_mut().set_popup_active(true);

        let outcome = send(&key(KeyCode::Right), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "the move left the keyboard on the bar"
        );
        assert!(
            !state.chrome().popup_active(),
            "the move left a drop-down open"
        );
        assert!(state.diagram().can_undo(), "the move recorded no step");
    }

    /// **A frame after a move draws the figure one cell further on** (rule 9): the drawing is the
    /// session's, and the application adds no rule to it.
    #[test]
    fn a_frame_after_a_move_draws_the_shape_one_cell_further_on() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let before = draw(&mut state);

        let _ = send(&key(KeyCode::Right), &mut state);
        let after = draw(&mut state);

        assert_eq!(
            before[(3, 3)].symbol(),
            after[(4, 3)].symbol(),
            "the frame does not draw the figure one cell further on"
        );
        assert_eq!(
            after[(3, 3)].symbol(),
            " ",
            "the frame still draws the figure where it stood"
        );
    }

    /// **A figure moved past the window's edge is not drawn** (D2): its cells fall outside the
    /// window, and the frame draws what the window holds, which is nothing.
    #[test]
    fn a_frame_after_a_move_out_of_the_window_draws_nothing() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);

        for _ in 0..7 {
            let _ = send(&key(KeyCode::Left), &mut state);
        }
        let _ = draw(&mut state);

        assert!(state.diagram().can_undo(), "the presses recorded no step");

        // The region's own border is a box too, so the window is what is asked: no offset of the
        // drawing answers a glyph, and the copy therefore writes none.
        let catalog = monospace_glyph_sets::all();
        for y in 0..6 {
            for x in 0..38 {
                assert!(
                    state.diagram().glyph(Offset { x, y }, &catalog).is_none(),
                    "({x}, {y}) still draws the figure that left the window"
                );
            }
        }
    }

    /// **`Alt` and a label's character gives the bar the keyboard and opens that label's
    /// drop-down in one press** (D4), from the region.
    #[test]
    fn alt_and_a_labels_character_opens_that_labels_drop_down() {
        for (label, text) in [('f', "Quit"), ('e', "Undo"), ('h', "About")] {
            let mut state = a_drawn_state();
            assert_eq!(
                state.chrome().leaf(),
                Focus::Region,
                "the test starts on the bar"
            );

            open_the_drop_down(&mut state, label);

            let frame = draw(&mut state);
            let shown: String = (0..HEIGHT).map(|line| row_of(&frame, line)).collect();

            assert!(
                shown.contains(text),
                "Alt+{label} opened another drop-down: {shown:?}"
            );
        }
    }

    /// **A combination that names no label changes nothing and moves no keyboard** (D4): `Alt+Z`
    /// is not a character of any label, and a bar that does not hold the keyboard answers nothing.
    #[test]
    fn alt_with_a_character_that_names_no_label_changes_nothing() {
        let mut state = a_drawn_state();

        let outcome = send(&key_with(KeyCode::Char('z'), KeyModifiers::ALT), &mut state);

        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "a combination that names no label moved the keyboard"
        );
        assert!(!state.chrome().popup_active(), "a drop-down opened");
    }

    /// **`Esc` closes the drop-down, and the next one gives the keyboard back to the region**
    /// (rule 5): the key is the widget's while there is something to close, and the bar's way out
    /// after it. Neither press reaches the diagram.
    #[test]
    fn a_second_escape_gives_the_keyboard_back_to_the_region() {
        let mut state = a_drawn_state();
        open_the_drop_down(&mut state, 'f');

        let outcome = send(&key(KeyCode::Esc), &mut state);
        let frame = draw(&mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.chrome().popup_active(),
            "escape left the drop-down open"
        );
        assert_eq!(
            state.chrome().leaf(),
            Focus::Bar,
            "the first escape left the bar"
        );
        let (column, row) = frame::cell_of(&frame, "File");
        assert!(
            reversed(&frame, column, row),
            "the label stopped looking focused with the bar still holding the keyboard"
        );

        let outcome = send(&key(KeyCode::Esc), &mut state);
        let frame = draw(&mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "the second escape did not give the keyboard back"
        );
        assert!(
            !reversed(&frame, column, row),
            "a label is reversed with the region holding the keyboard"
        );
    }

    /// **`Esc` with nothing selected is not the region's**: with the keyboard there the key changes
    /// nothing, so the bar's way out is a press that acts on the chrome and never on the drawing.
    #[test]
    fn escape_in_the_region_changes_nothing() {
        let mut state = a_drawn_state();
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "the region does not start with the keyboard"
        );

        let outcome = send(&key(KeyCode::Esc), &mut state);

        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "escape moved the keyboard"
        );
        assert!(!state.chrome().popup_active(), "escape opened a drop-down");
    }

    /// **`F10` asks for the bar where a bare `Alt` cannot** (D4, amended): it moves the keyboard and
    /// opens nothing, so the bar looks focused while the region stays the picture under it.
    #[test]
    fn f10_gives_the_bar_the_keyboard_without_opening_a_drop_down() {
        let mut state = a_drawn_state();
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "the test starts on the bar"
        );

        let outcome = send(&key(KeyCode::F(10)), &mut state);
        let frame = draw(&mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.chrome().leaf(),
            Focus::Bar,
            "F10 did not give the bar the keyboard"
        );
        assert!(!state.chrome().popup_active(), "F10 opened a drop-down");

        let (column, row) = frame::cell_of(&frame, "File");
        assert!(
            reversed(&frame, column, row),
            "the bar does not look focused"
        );
    }

    /// **The drop-down is asked before the region**, so a click it answers never reaches the
    /// diagram — and a click on its `Quit` entry is the way out rather than a selection.
    #[test]
    fn a_click_the_drop_down_takes_never_reaches_the_diagram() {
        let mut state = a_drawn_state_over(A_BOX);
        let outcome = take_the_entry(&mut state, 'f', "Quit");

        assert!(matches!(outcome, Control::Quit), "{outcome:?}");
        assert_eq!(
            state.diagram().selected(),
            None,
            "the click the drop-down took reached the diagram"
        );
    }

    /// **The drop-down's own rectangle is the drop-down's, border and padding included** (rule 1
    /// of #189): a press between its entries is not a press on the drawing behind it. The cell is
    /// found on the frame rather than named, because where the pop-up hangs is the widget's
    /// arithmetic.
    #[test]
    fn a_click_on_the_drop_down_border_never_reaches_the_diagram() {
        let mut state = a_drawn_state_over(A_BOX);
        open_the_drop_down(&mut state, 'e');

        let popup = state.chrome().menu().popup.area;
        let mut border = None;

        for row in popup.top()..popup.bottom() {
            for column in popup.left()..popup.right() {
                let at = Position::new(column, row);

                if state.chrome().menu().popup.item_at((column, row)).is_some() {
                    continue;
                }

                let Some(offset) = state.diagram().offset_of(at) else {
                    continue;
                };

                if state.diagram().owner(offset).is_some() {
                    border = Some(at);
                    break;
                }
            }

            if border.is_some() {
                break;
            }
        }

        let border = border.unwrap_or_else(|| {
            panic!(
                "the Edit drop-down {popup:?} has no border cell over the box, so the test proves nothing"
            )
        });

        assert_eq!(
            state.diagram().selected(),
            None,
            "the test starts with a selection"
        );

        let outcome = send(&click(border.x, border.y), &mut state);

        assert_eq!(
            state.diagram().selected(),
            None,
            "the click on the drop-down's border reached the drawing behind it at {border:?}"
        );
        assert_eq!(
            state.chrome().leaf(),
            Focus::Bar,
            "the click on the drop-down's border moved the keyboard"
        );
        assert!(
            state.chrome().popup_active(),
            "the click on the drop-down's border closed the drop-down"
        );
        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
    }

    /// **The delete key is the first action that changes the session.** The selected shape is gone
    /// from the drawing the next frame makes, and the frame is owed because of it.
    #[test]
    fn the_delete_key_removes_the_selected_shape() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected"
        );

        let outcome = send(&key(KeyCode::Delete), &mut state);
        let buffer = draw(&mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_none(),
            "the drawing still records the removed box"
        );
        assert_eq!(
            buffer[(3, 3)].symbol(),
            " ",
            "the frame still draws the removed box"
        );
    }

    /// **The identity goes with the command** (rule 2): nothing is selected afterwards, and the
    /// next frame inverts no cell. The cell the click selected is inverted before the removal, so
    /// the answer after it proves the inversion went with the selection.
    #[test]
    fn the_delete_key_drops_the_selection() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        assert!(
            reversed(&draw(&mut state), 3, 3),
            "the click selected nothing, so the test proves nothing"
        );

        let _ = send(&key(KeyCode::Delete), &mut state);
        let buffer = draw(&mut state);

        assert_eq!(
            state.diagram().selected(),
            None,
            "the identity survived the removal"
        );
        assert!(
            !reversed(&buffer, 3, 3),
            "the frame after the removal inverts a cell"
        );
    }

    /// **A press with nothing selected is ignored** (D3 of #292). Deletion is contextual and
    /// offered only when a shape is selected; with nothing selected, the key is ignored and the
    /// loop continues without a step or repaint.
    #[test]
    fn the_delete_key_with_nothing_selected_is_ignored() {
        let mut state = a_drawn_state_over(A_BOX);

        let outcome = send(&key(KeyCode::Delete), &mut state);

        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
        assert!(
            !state.diagram().can_undo(),
            "a press with nothing selected recorded a step"
        );
        assert_eq!(
            state.diagram().selected(),
            None,
            "a press with nothing selected left a selection"
        );
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "the box was removed without a selection"
        );
    }

    /// **With the drop-down open, Delete is ignored and the menu stays open** (D3 of #292).
    /// Deletion is no longer a global unclaimed shortcut or an edit menu entry; with focus on the
    /// bar/drop-down, Delete does not remove the figure and the menu remains active.
    #[test]
    fn the_drop_down_keeps_the_delete_key() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        open_the_drop_down(&mut state, 'f');

        let outcome = send(&key(KeyCode::Delete), &mut state);

        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
        assert!(
            state.diagram().selected().is_some(),
            "the figure was deleted"
        );
        assert_eq!(state.chrome().leaf(), Focus::Bar, "focus left the bar");
        assert!(state.chrome().popup_active(), "the drop-down was closed");
    }

    /// **Delete on the bar does nothing** (D3 of #292). Even with a figure selected, when the bar
    /// holds the keyboard without a drop-down, Delete is ignored.
    #[test]
    fn the_delete_key_on_the_bar_does_nothing() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::F(10)), &mut state);
        assert_eq!(state.chrome().leaf(), Focus::Bar);

        let outcome = send(&key(KeyCode::Delete), &mut state);

        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
        assert!(
            state.diagram().selected().is_some(),
            "the figure was deleted"
        );
    }

    #[test]
    fn click_outside_cancels_sub_mode_and_clears_selection() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::Char('s')), &mut state);
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::StrokeSelect)
        );

        let _ = send(&click(1, 2), &mut state);
        assert_eq!(state.diagram().sub_mode(), None);
        assert_eq!(state.diagram().selected(), None);
    }

    #[test]
    fn clicking_another_figure_cancels_sub_mode_and_changes_selection() {
        let mut state = a_drawn_state_over(A_BOX_AND_WHAT_HANGS_FROM_IT);
        let _ = send(&click(3, 3), &mut state);
        let first = state.diagram().selected();
        assert!(first.is_some());
        let _ = send(&key(KeyCode::Char('s')), &mut state);
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::StrokeSelect)
        );

        let _ = send(&click(18, 3), &mut state);
        let second = state.diagram().selected();
        assert!(second.is_some());
        assert_ne!(first, second);
        assert_eq!(state.diagram().sub_mode(), None);
    }

    #[test]
    fn clicking_the_same_figure_in_sub_mode_preserves_sub_mode() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::Char('s')), &mut state);
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::StrokeSelect)
        );

        let _ = send(&click(3, 3), &mut state);
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::StrokeSelect)
        );
    }

    #[test]
    fn moving_focus_to_bar_and_returning_preserves_sub_mode() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::Char('s')), &mut state);
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::StrokeSelect)
        );

        let _ = send(&key(KeyCode::F(10)), &mut state);
        assert_eq!(state.chrome().leaf(), Focus::Bar);
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::StrokeSelect)
        );

        let _ = send(&key(KeyCode::Esc), &mut state);
        assert_eq!(state.chrome().leaf(), Focus::Region);
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::StrokeSelect)
        );
        assert!(state.diagram().selected().is_some());
    }

    #[test]
    fn opening_dialog_and_closing_preserves_sub_mode() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::Char('s')), &mut state);
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::StrokeSelect)
        );

        let _ = send(
            &key_with(KeyCode::Char('s'), KeyModifiers::CONTROL),
            &mut state,
        );
        assert!(state.save().is_up());
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::StrokeSelect)
        );

        let _ = send(&key(KeyCode::Esc), &mut state);
        assert!(!state.save().is_up());
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::StrokeSelect)
        );
        assert!(state.diagram().selected().is_some());
    }

    /// The stroke `shape` carries, whichever kind of figure it is.
    fn stroke_of(shape: &monospace_diagram::Shape) -> monospace_diagram::Stroke {
        match shape {
            monospace_diagram::Shape::Box { stroke, .. }
            | monospace_diagram::Shape::Line { stroke, .. }
            | monospace_diagram::Shape::Connector { stroke, .. } => stroke.clone(),
        }
    }

    /// **A stroke the figure already carries changes nothing** (#285): the command leaves the
    /// diagram as it found it, so the session records no step and an undo has nothing to give
    /// back. The key was offered and carried out all the same, so the sub-mode ends and the
    /// identity stays.
    #[test]
    fn setting_identical_stroke_leaves_diagram_untouched_and_records_no_step() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(selected.is_some(), "the box was not selected");
        let _ = send(&key(KeyCode::Char('s')), &mut state);

        let outcome = send(&key(KeyCode::Char('1')), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().sub_mode(),
            None,
            "the sub-mode survived the stroke it was asked for"
        );
        assert_eq!(
            stroke_of(
                state
                    .diagram()
                    .selected_shape()
                    .expect("the box is still there")
            ),
            monospace_diagram::Stroke::from("light"),
            "the stroke changed"
        );
        assert!(
            !state.diagram().can_undo(),
            "an unchanged stroke recorded a step"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the identity went with the stroke"
        );
    }

    /// **A stroke the figure does not carry is one step** (#292, behavior 5): the diagram holds
    /// the new stroke, and one undo gives the old one back with nothing behind it.
    #[test]
    fn setting_different_stroke_records_one_step_in_session_history() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(selected.is_some(), "the box was not selected");
        let _ = send(&key(KeyCode::Char('s')), &mut state);

        let outcome = send(&key(KeyCode::Char('2')), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().sub_mode(),
            None,
            "the sub-mode survived the stroke it was asked for"
        );
        assert_eq!(
            stroke_of(
                state
                    .diagram()
                    .selected_shape()
                    .expect("the box is still there")
            ),
            monospace_diagram::Stroke::from("double"),
            "the stroke did not change"
        );
        assert!(state.diagram().can_undo(), "no step was recorded");
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the identity went with the stroke"
        );

        let _ = send(&undo_key(), &mut state);

        assert_eq!(
            state.diagram().selected(),
            None,
            "the undo kept the selection"
        );
        let restored_shape = state
            .diagram()
            .session()
            .diagram()
            .get(selected.unwrap())
            .expect("the box is still in the diagram");
        assert_eq!(
            stroke_of(restored_shape),
            monospace_diagram::Stroke::from("light"),
            "one undo did not give the old stroke back"
        );
        assert!(
            !state.diagram().can_undo(),
            "the stroke recorded more than one step"
        );
    }

    /// **Undo and redo walk the history from inside the sub-mode and clear the selection** (#297):
    /// the global keys fall through the region, the walk clears the selection, and dropping the
    /// selection ends the active sub-mode.
    #[test]
    fn undo_and_redo_in_stroke_select_walk_history() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let selected = state.diagram().selected();
        assert!(selected.is_some(), "the box was not selected");
        let _ = send(&key(KeyCode::Char('s')), &mut state);
        let _ = send(&key(KeyCode::Char('2')), &mut state);
        let _ = send(&key(KeyCode::Char('s')), &mut state);
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::StrokeSelect),
            "the sub-mode was not entered again"
        );

        let outcome = send(&undo_key(), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        let restored_shape = state
            .diagram()
            .session()
            .diagram()
            .get(selected.unwrap())
            .expect("the box is still in the diagram");
        assert_eq!(
            stroke_of(restored_shape),
            monospace_diagram::Stroke::from("light"),
            "the undo did not give the old stroke back"
        );
        assert_eq!(
            state.diagram().sub_mode(),
            None,
            "the undo kept the sub-mode"
        );
        assert_eq!(
            state.diagram().selected(),
            None,
            "the undo kept the selection"
        );

        let outcome = send(&redo_key(), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        let redone_shape = state
            .diagram()
            .session()
            .diagram()
            .get(selected.unwrap())
            .expect("the box is still in the diagram");
        assert_eq!(
            stroke_of(redone_shape),
            monospace_diagram::Stroke::from("double"),
            "the redo did not give the new stroke back"
        );
        assert_eq!(
            state.diagram().sub_mode(),
            None,
            "the redo restored a sub-mode"
        );
        assert_eq!(
            state.diagram().selected(),
            None,
            "the redo restored a selection"
        );
    }

    /// Two overlapping boxes: id1 at the back, id2 in front. The cell `(0, 1)` of the window belongs
    /// only to id1, so a click there selects the back box without hitting the front one.
    const TWO_OVERLAPPING_BOXES: &str = r#"{
        "next_id": 3,
        "shapes": [
            { "kind": "box", "id": 1, "at": { "x": 0, "y": 1 },
              "size": { "width": 4, "height": 3 }, "stroke": "light", "fill": "░" },
            { "kind": "box", "id": 2, "at": { "x": 2, "y": 2 },
              "size": { "width": 4, "height": 3 }, "stroke": "light", "fill": "▓" }
        ]
    }"#;

    #[test]
    fn z_opens_order_mode_and_escape_leaves_it() {
        let mut state = a_drawn_state_over(TWO_OVERLAPPING_BOXES);
        let _ = send(&click(1, 3), &mut state);
        let id = state.diagram().selected();
        assert!(id.is_some(), "box #1 was not selected");

        let outcome = send(&key(KeyCode::Char('z')), &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::OrderMode),
            "z did not enter order mode"
        );

        let buffer = draw(&mut state);
        assert!(
            row_of(&buffer, HEIGHT - 2).starts_with("LAYER ORDER for Box #1"),
            "status row did not report layer order: {}",
            row_of(&buffer, HEIGHT - 2)
        );
        assert!(
            row_of(&buffer, HEIGHT - 1).contains("ORDER: [Home] Front"),
            "command row did not offer order commands: {}",
            row_of(&buffer, HEIGHT - 1)
        );

        let outcome = send(&key(KeyCode::Esc), &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().sub_mode(),
            None,
            "Esc did not leave order mode"
        );
        assert_eq!(state.diagram().selected(), id, "Esc dropped the selection");
    }

    #[test]
    fn page_up_moves_the_selected_figure_forward_and_records_one_step() {
        let mut state = a_drawn_state_over(TWO_OVERLAPPING_BOXES);
        let _ = send(&click(1, 3), &mut state);
        let id1 = state.diagram().selected().expect("box #1 selected");
        assert_eq!(
            state.diagram().session().diagram().place_of(id1),
            Some(0),
            "box #1 starts at the back"
        );

        let _ = send(&key(KeyCode::Char('z')), &mut state);
        let outcome = send(&key(KeyCode::PageUp), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().session().diagram().place_of(id1),
            Some(1),
            "PageUp did not move box #1 forward"
        );
        assert!(
            state.diagram().session().can_undo(),
            "moving forward recorded no step"
        );
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::OrderMode),
            "PageUp left order mode"
        );
    }

    #[test]
    fn page_down_moves_the_selected_figure_backward() {
        let mut state = a_drawn_state_over(TWO_OVERLAPPING_BOXES);
        let _ = send(&click(5, 4), &mut state);
        let id2 = state.diagram().selected().expect("box #2 selected");
        assert_eq!(
            state.diagram().session().diagram().place_of(id2),
            Some(1),
            "box #2 starts in front"
        );

        let _ = send(&key(KeyCode::Char('z')), &mut state);
        let outcome = send(&key(KeyCode::PageDown), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().session().diagram().place_of(id2),
            Some(0),
            "PageDown did not move box #2 backward"
        );
        assert!(
            state.diagram().session().can_undo(),
            "moving backward recorded no step"
        );
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::OrderMode),
            "PageDown left order mode"
        );
    }

    #[test]
    fn home_moves_the_selected_figure_to_the_front_in_one_step() {
        let mut state = a_drawn_state_over(TWO_OVERLAPPING_BOXES);
        let _ = send(&click(1, 3), &mut state);
        let id1 = state.diagram().selected().expect("box #1 selected");
        assert_eq!(state.diagram().session().diagram().place_of(id1), Some(0));

        let _ = send(&key(KeyCode::Char('z')), &mut state);
        let outcome = send(&key(KeyCode::Home), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().session().diagram().place_of(id1),
            Some(1),
            "Home did not move box #1 to the front"
        );
        assert!(state.diagram().session().can_undo());

        let undo_outcome = send(&undo_key(), &mut state);
        assert!(matches!(undo_outcome, Control::Changed), "{undo_outcome:?}");
        assert_eq!(
            state.diagram().session().diagram().place_of(id1),
            Some(0),
            "undo did not restore box #1 position"
        );
        assert!(
            !state.diagram().session().can_undo(),
            "more than one step recorded"
        );
        assert_eq!(state.diagram().selected(), None);
        assert_eq!(state.diagram().sub_mode(), None);
    }

    #[test]
    fn end_moves_the_selected_figure_to_the_back_in_one_step() {
        let mut state = a_drawn_state_over(TWO_OVERLAPPING_BOXES);
        let _ = send(&click(5, 4), &mut state);
        let id2 = state.diagram().selected().expect("box #2 selected");
        assert_eq!(state.diagram().session().diagram().place_of(id2), Some(1));

        let _ = send(&key(KeyCode::Char('z')), &mut state);
        let outcome = send(&key(KeyCode::End), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().session().diagram().place_of(id2),
            Some(0),
            "End did not move box #2 to the back"
        );
        assert!(state.diagram().session().can_undo());

        let undo_outcome = send(&undo_key(), &mut state);
        assert!(matches!(undo_outcome, Control::Changed), "{undo_outcome:?}");
        assert_eq!(
            state.diagram().session().diagram().place_of(id2),
            Some(1),
            "undo did not restore box #2 position"
        );
        assert!(
            !state.diagram().session().can_undo(),
            "more than one step recorded"
        );
    }

    #[test]
    fn a_move_at_the_limit_records_no_step() {
        // Case 1: id1 at back, PageDown
        let mut state = a_drawn_state_over(TWO_OVERLAPPING_BOXES);
        let _ = send(&click(1, 3), &mut state);
        let _ = send(&key(KeyCode::Char('z')), &mut state);
        let outcome = send(&key(KeyCode::PageDown), &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.diagram().session().can_undo(),
            "PageDown at back recorded a step"
        );
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::OrderMode),
            "PageDown at back left order mode"
        );

        // Case 2: id1 at back, End
        let mut state = a_drawn_state_over(TWO_OVERLAPPING_BOXES);
        let _ = send(&click(1, 3), &mut state);
        let _ = send(&key(KeyCode::Char('z')), &mut state);
        let outcome = send(&key(KeyCode::End), &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.diagram().session().can_undo(),
            "End at back recorded a step"
        );
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::OrderMode),
            "End at back left order mode"
        );

        // Case 3: id2 at front, PageUp
        let mut state = a_drawn_state_over(TWO_OVERLAPPING_BOXES);
        let _ = send(&click(5, 4), &mut state);
        let _ = send(&key(KeyCode::Char('z')), &mut state);
        let outcome = send(&key(KeyCode::PageUp), &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.diagram().session().can_undo(),
            "PageUp at front recorded a step"
        );
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::OrderMode),
            "PageUp at front left order mode"
        );

        // Case 4: id2 at front, Home
        let mut state = a_drawn_state_over(TWO_OVERLAPPING_BOXES);
        let _ = send(&click(5, 4), &mut state);
        let _ = send(&key(KeyCode::Char('z')), &mut state);
        let outcome = send(&key(KeyCode::Home), &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.diagram().session().can_undo(),
            "Home at front recorded a step"
        );
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::OrderMode),
            "Home at front left order mode"
        );
    }

    #[test]
    fn undo_and_redo_leave_order_mode() {
        let mut state = a_drawn_state_over(TWO_OVERLAPPING_BOXES);
        let _ = send(&click(1, 3), &mut state);
        let id1 = state.diagram().selected().expect("box #1 selected");
        let _ = send(&key(KeyCode::Char('z')), &mut state);
        let _ = send(&key(KeyCode::Home), &mut state);
        assert_eq!(state.diagram().session().diagram().place_of(id1), Some(1));

        let undo_outcome = send(&undo_key(), &mut state);
        assert!(matches!(undo_outcome, Control::Changed), "{undo_outcome:?}");
        assert_eq!(state.diagram().selected(), None);
        assert_eq!(state.diagram().sub_mode(), None);
        assert_eq!(
            state.diagram().session().diagram().place_of(id1),
            Some(0),
            "undo did not restore original place"
        );

        let redo_outcome = send(&redo_key(), &mut state);
        assert!(matches!(redo_outcome, Control::Changed), "{redo_outcome:?}");
        assert_eq!(state.diagram().selected(), None);
        assert_eq!(state.diagram().sub_mode(), None);
        assert_eq!(
            state.diagram().session().diagram().place_of(id1),
            Some(1),
            "redo did not restore forward place"
        );
    }

    #[test]
    fn clicking_another_figure_cancels_order_mode() {
        let mut state = a_drawn_state_over(TWO_OVERLAPPING_BOXES);
        let _ = send(&click(1, 3), &mut state);
        let id1 = state.diagram().selected();
        assert!(id1.is_some());
        let _ = send(&key(KeyCode::Char('z')), &mut state);
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::OrderMode)
        );

        let outcome = send(&click(5, 4), &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        let id2 = state.diagram().selected();
        assert!(id2.is_some());
        assert_ne!(id1, id2);
        assert_eq!(state.diagram().sub_mode(), None);
    }

    #[test]
    fn clicking_outside_cancels_order_mode_and_clears_the_selection() {
        let mut state = a_drawn_state_over(TWO_OVERLAPPING_BOXES);
        let _ = send(&click(1, 3), &mut state);
        assert!(state.diagram().selected().is_some());
        let _ = send(&key(KeyCode::Char('z')), &mut state);
        assert_eq!(
            state.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::OrderMode)
        );

        let outcome = send(&click(20, 2), &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(state.diagram().sub_mode(), None);
        assert_eq!(state.diagram().selected(), None);
    }

    /// **Escape drops the active selection** (D1 of #279): pressing Escape while a shape is
    /// selected drops the selection and owes a frame. Pressing Escape when nothing is selected
    /// changes nothing.
    #[test]
    fn escape_in_the_region_drops_the_selection() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected"
        );

        let outcome = send(&key(KeyCode::Esc), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().selected(),
            None,
            "Escape did not drop the selection"
        );

        let second = send(&key(KeyCode::Esc), &mut state);

        assert!(matches!(second, Control::Continue), "{second:?}");
    }

    #[test]
    fn t_opens_the_text_editor_on_a_box() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected"
        );

        let outcome = send(&key(KeyCode::Char('t')), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(state.text().is_up(), "t opened no editor");
        assert!(
            !state.diagram().can_undo(),
            "opening the editor recorded a step"
        );
    }

    #[test]
    fn t_is_ignored_off_a_box() {
        // **A line**, selected by clicking it. `click(1, 3)` would select nothing here, and on
        // `A_BOX_AND_WHAT_HANGS_FROM_IT` it is inside a box, so neither fixture is usable as-is.
        let mut line = a_drawn_state_over(A_HORIZONTAL_LINE);
        let _ = send(&click(3, 3), &mut line);
        assert!(
            line.diagram().selected().is_some(),
            "the line was not selected"
        );
        let outcome = send(&key(KeyCode::Char('t')), &mut line);
        assert!(matches!(outcome, Control::Continue), "line: {outcome:?}");
        assert!(!line.text().is_up(), "line: t opened an editor");

        // **A connector**, selected directly: its route is the drawing's, and what this test says
        // is that `t` is not accepted for it, not how a press selects one.
        let mut connector = a_drawn_state_over(A_CONNECTOR);
        connector
            .diagram_mut()
            .select(Some(ShapeId::new(NonZeroU16::new(1).unwrap())));
        let outcome = send(&key(KeyCode::Char('t')), &mut connector);
        assert!(
            matches!(outcome, Control::Continue),
            "connector: {outcome:?}"
        );
        assert!(!connector.text().is_up(), "connector: t opened an editor");

        // **Nothing selected.**
        let mut nothing = a_drawn_state_over(A_BOX);
        let outcome = send(&key(KeyCode::Char('t')), &mut nothing);
        assert!(
            matches!(outcome, Control::Continue),
            "nothing selected: {outcome:?}"
        );
        assert!(
            !nothing.text().is_up(),
            "nothing selected: t opened an editor"
        );

        // **A box in the stroke sub-mode**: that bar offers digits and `Esc`, and not `t` (rule 2).
        let mut sub_mode = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut sub_mode);
        let _ = send(&key(KeyCode::Char('s')), &mut sub_mode);
        assert_eq!(
            sub_mode.diagram().sub_mode(),
            Some(crate::diagram_state::SubMode::StrokeSelect)
        );
        let outcome = send(&key(KeyCode::Char('t')), &mut sub_mode);
        assert!(
            matches!(outcome, Control::Continue),
            "sub-mode: {outcome:?}"
        );
        assert!(!sub_mode.text().is_up(), "sub-mode: t opened an editor");
    }

    #[test]
    fn pressing_i_on_selected_connector_inverts_terminals() {
        let fixture = r#"{
            "next_id": 2,
            "shapes": [ { "kind": "connector", "id": 1,
                          "from": { "at": { "kind": "point", "x": 2, "y": 1 },
                                    "leaving": "right", "terminal": { "kind": "arm" } },
                          "to": { "at": { "kind": "point", "x": 10, "y": 1 },
                                  "leaving": "left", "terminal": { "kind": "symbol", "style": "solid" } },
                          "stroke": "light" } ]
        }"#;
        let mut state = a_drawn_state_over(fixture);
        let id = ShapeId::new(NonZeroU16::new(1).unwrap());
        state.diagram_mut().select(Some(id));

        let i_key = Event::Key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE));
        let outcome = send(&i_key, &mut state);
        assert!(matches!(outcome, Control::Changed));

        let shape = state.diagram().session().diagram().get(id);
        let Some(monospace_diagram::Shape::Connector { from, to, .. }) = shape else {
            panic!("expected connector");
        };
        assert_eq!(
            from.terminal,
            monospace_core::Terminal::Symbol {
                style: monospace_core::SymbolStyleName::from("solid")
            }
        );
        assert_eq!(to.terminal, monospace_core::Terminal::Arm);
        assert!(state.diagram().session().can_undo());

        // Pressing Undo restores the original terminals
        let undo_key = Event::Key(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::CONTROL));
        let undo_outcome = send(&undo_key, &mut state);
        assert!(matches!(undo_outcome, Control::Changed));

        let shape_restored = state.diagram().session().diagram().get(id);
        let Some(monospace_diagram::Shape::Connector { from, to, .. }) = shape_restored else {
            panic!("expected connector");
        };
        assert_eq!(from.terminal, monospace_core::Terminal::Arm);
        assert_eq!(
            to.terminal,
            monospace_core::Terminal::Symbol {
                style: monospace_core::SymbolStyleName::from("solid")
            }
        );
    }

    #[test]
    fn pressing_r_on_selected_line_toggles_orientation_and_updates_status() {
        let fixture = r#"{
            "next_id": 2,
            "shapes": [ { "kind": "line", "id": 1, "at": { "x": 1, "y": 1 },
                          "len": 5, "orientation": "vertical", "stroke": "light" } ]
        }"#;
        let mut state = a_drawn_state_over(fixture);
        let id = ShapeId::new(NonZeroU16::new(1).unwrap());
        state.diagram_mut().select(Some(id));

        assert_eq!(
            crate::status::status_line(state.diagram()),
            "Line #1 · Pos: (1, 1) · Length: 5 · Orientation: Vertical · Stroke: light"
        );
        assert!(
            crate::status::command_line(state.diagram()).contains("RESIZE: Shift+↑↓ · ROTATE: [r]")
        );

        let r_key = Event::Key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE));
        let outcome = send(&r_key, &mut state);
        assert!(matches!(outcome, Control::Changed));

        let shape = state.diagram().session().diagram().get(id);
        let Some(monospace_diagram::Shape::Line {
            orientation,
            at,
            len,
            stroke,
        }) = shape
        else {
            panic!("expected line");
        };
        assert_eq!(*orientation, monospace_core::Orientation::Horizontal);
        assert_eq!(*at, monospace_core::Pos { x: 1, y: 1 });
        assert_eq!(*len, 5);
        assert_eq!(*stroke, monospace_diagram::Stroke::from("light"));

        assert_eq!(
            crate::status::status_line(state.diagram()),
            "Line #1 · Pos: (1, 1) · Length: 5 · Orientation: Horizontal · Stroke: light"
        );
        assert!(
            crate::status::command_line(state.diagram()).contains("RESIZE: Shift+←→ · ROTATE: [r]")
        );
        assert!(state.diagram().session().can_undo());

        // Second 'r' toggles back to Vertical
        let outcome2 = send(&r_key, &mut state);
        assert!(matches!(outcome2, Control::Changed));
        assert_eq!(
            crate::status::status_line(state.diagram()),
            "Line #1 · Pos: (1, 1) · Length: 5 · Orientation: Vertical · Stroke: light"
        );

        // Undo restores Horizontal in a single step
        let undo_key = Event::Key(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::CONTROL));
        let undo_outcome = send(&undo_key, &mut state);
        assert!(matches!(undo_outcome, Control::Changed));

        let shape_restored = state.diagram().session().diagram().get(id);
        let Some(monospace_diagram::Shape::Line { orientation, .. }) = shape_restored else {
            panic!("expected line");
        };
        assert_eq!(*orientation, monospace_core::Orientation::Horizontal);
    }

    #[test]
    fn enter_remains_ignored_on_a_box() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);

        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
        assert!(!state.text().is_up(), "Enter opened the editor");
    }

    #[test]
    fn ok_saves_and_escape_discards() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::Char('t')), &mut state);

        for character in ['h', 'i'] {
            let _ = send(&key(KeyCode::Char(character)), &mut state);
        }
        let _ = send(&key(KeyCode::Tab), &mut state);
        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(!state.text().is_up(), "Ok did not close the editor");
        assert!(state.diagram().can_undo(), "saving recorded no step");
        assert_eq!(
            state.diagram().selected(),
            Some(ShapeId::new(NonZeroU16::new(1).unwrap())),
            "saving dropped the selection"
        );

        // The second opening starts from the saved text; Escape closes it without a step.
        let _ = send(&key(KeyCode::Char('t')), &mut state);
        let _ = send(&key(KeyCode::Char('x')), &mut state);
        let outcome = send(&key(KeyCode::Esc), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(!state.text().is_up(), "Escape did not close the editor");

        // **`Cancel` with `Enter` discards too** (rule 7): two `Tab`s reach it from the buffer.
        let _ = send(&key(KeyCode::Char('t')), &mut state);
        let _ = send(&key(KeyCode::Char('y')), &mut state);
        let _ = send(&key(KeyCode::Tab), &mut state);
        let _ = send(&key(KeyCode::Tab), &mut state);
        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.text().is_up(),
            "Enter on Cancel did not close the editor"
        );
        let Shape::Box { text: kept, .. } = state
            .diagram()
            .session()
            .diagram()
            .get(ShapeId::new(NonZeroU16::new(1).unwrap()))
            .expect("the box is there")
        else {
            panic!("expected box");
        };
        assert_eq!(
            *kept,
            Some(Text::new("hi").unwrap()),
            "Cancel saved the buffer"
        );
    }

    #[test]
    fn saving_the_same_text_records_no_step() {
        let mut state = a_drawn_state_over(A_BOX_WITH_TEXT);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::Char('t')), &mut state);
        let _ = send(&key(KeyCode::Tab), &mut state);
        let outcome = send(&key(KeyCode::Enter), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(!state.text().is_up(), "Ok did not close the editor");
        assert!(
            !state.diagram().can_undo(),
            "saving the same text recorded a step"
        );
    }

    #[test]
    fn ctrl_c_copies_while_the_text_editor_is_up() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::Char('t')), &mut state);

        for character in ['h', 'i'] {
            let _ = send(&key(KeyCode::Char(character)), &mut state);
        }
        let _ = send(
            &key_with(KeyCode::Char('a'), KeyModifiers::CONTROL),
            &mut state,
        );
        let outcome = send(
            &key_with(KeyCode::Char('c'), KeyModifiers::CONTROL),
            &mut state,
        );

        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
        assert!(state.text().is_up(), "Ctrl+C closed the editor");
        assert_eq!(
            rat_widget::text::clipboard::global_clipboard()
                .get_string()
                .as_deref()
                .ok(),
            Some("hi")
        );
    }

    #[test]
    fn the_editor_consumes_every_key() {
        // Ctrl+Q/S/O/N: nothing behind the overlay moves.
        for code in [
            KeyCode::Char('q'),
            KeyCode::Char('s'),
            KeyCode::Char('o'),
            KeyCode::Char('n'),
        ] {
            let mut state = a_drawn_state_over(A_BOX);
            let _ = send(&click(3, 3), &mut state);
            let _ = send(&key(KeyCode::Char('t')), &mut state);

            let outcome = send(&key_with(code, KeyModifiers::CONTROL), &mut state);

            assert!(
                matches!(outcome, Control::Continue),
                "{code:?}: {outcome:?}"
            );
            assert!(state.text().is_up(), "{code:?}: the editor closed");
            assert!(
                !state.dialog().is_up(),
                "{code:?}: the message dialog opened"
            );
            assert!(!state.open().is_up(), "{code:?}: the open dialog opened");
            assert!(!state.save().is_up(), "{code:?}: the save dialog opened");
            assert!(!state.diagram().can_undo(), "{code:?}: the diagram changed");
        }

        // `t` inside the editor is a character, not the key that opens it.
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::Char('t')), &mut state);
        let outcome = send(&key(KeyCode::Char('t')), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(state.text().is_up(), "t inside the editor closed it");
        assert_eq!(
            state.text().get().expect("the text editor is up").buffer(),
            "t"
        );

        // `Tab` moves the focus inside the editor and inserts no tab.
        let outcome = send(&key(KeyCode::Tab), &mut state);
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(state.text().is_up(), "Tab closed the editor");
        assert_eq!(
            state.text().get().expect("the text editor is up").buffer(),
            "t",
            "Tab inserted a tab"
        );

        // A click on the bar reaches nothing: the editor stays up and the keyboard does not move.
        let leaf = state.chrome().leaf();
        let outcome = send(&click(3, 0), &mut state);
        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
        assert!(state.text().is_up(), "a click on the bar closed the editor");
        assert_eq!(state.chrome().leaf(), leaf, "the click moved the keyboard");
    }

    /// **An entry with nothing to give back changes nothing and paints** (rule 11): the drop-down
    /// closes, the drawing is the one it already showed, and no step is recorded either way.
    #[test]
    fn taking_an_entry_with_nothing_to_give_back_changes_nothing() {
        let mut state = a_drawn_state_over(A_BOX);
        let before = draw(&mut state);

        let outcome = take_the_entry(&mut state, 'e', "Undo");

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.chrome().popup_active(),
            "the entry left the menu open"
        );
        assert!(!state.diagram().can_undo(), "the entry recorded a step");
        assert!(!state.diagram().can_redo(), "the entry left a step ahead");

        let after = draw(&mut state);

        for line in 0..HEIGHT {
            assert_eq!(
                row_of(&before, line),
                row_of(&after, line),
                "row {line} is not what it was"
            );
        }

        let outcome = take_the_entry(&mut state, 'e', "Redo");

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            !state.chrome().popup_active(),
            "the entry left the menu open"
        );
        assert!(
            !state.diagram().can_undo(),
            "the redo entry recorded a step"
        );
        assert!(
            !state.diagram().can_redo(),
            "the redo entry left a step ahead"
        );
    }

    /// **`Ctrl+Z` gives the step behind back** (rule 1). The deletion recorded one, and the undo
    /// takes the drawing to the state the step before it left: the box is back on the frame and
    /// there is a step ahead.
    #[test]
    fn the_undo_key_gives_the_step_back() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::Delete), &mut state);
        let _ = draw(&mut state);
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_none(),
            "the box was not removed, so the test proves nothing"
        );

        let outcome = send(&undo_key(), &mut state);
        let buffer = draw(&mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "the undo did not give the box back"
        );
        assert_eq!(
            buffer[(3, 3)].symbol(),
            "┌",
            "the frame after the undo does not draw the box"
        );
        assert!(!state.diagram().can_undo(), "the undo left a step behind");
        assert!(state.diagram().can_redo(), "the undo left nothing to redo");
    }

    /// **`Ctrl+Shift+Z` gives the step ahead back** (rule 2): the undo left one, and the redo takes
    /// the drawing to the state the step left.
    #[test]
    fn the_redo_key_gives_it_forward_again() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::Delete), &mut state);
        let _ = send(&undo_key(), &mut state);
        let _ = draw(&mut state);
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "the undo did not give the box back, so the test proves nothing"
        );

        let outcome = send(&redo_key(), &mut state);
        let buffer = draw(&mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_none(),
            "the redo did not take the box out again"
        );
        assert_eq!(
            buffer[(3, 3)].symbol(),
            " ",
            "the frame after the redo still draws the box"
        );
        assert!(state.diagram().can_undo(), "the redo left nothing to undo");
        assert!(!state.diagram().can_redo(), "the redo left a step ahead");
    }

    /// **At the oldest position `Ctrl+Z` walks nothing and paints** (rules 3 and 8): the session is
    /// unchanged, no step is recorded, and the frame is owed because the action was carried out.
    #[test]
    fn the_undo_key_with_nothing_behind_changes_nothing() {
        let mut state = a_drawn_state_over(A_BOX);

        let outcome = send(&undo_key(), &mut state);
        let buffer = draw(&mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(!state.diagram().can_undo(), "the press recorded a step");
        assert!(!state.diagram().can_redo(), "the press left a step ahead");
        assert_eq!(
            buffer[(3, 3)].symbol(),
            "┌",
            "the press changed the drawing"
        );
    }

    /// **At the newest position `Ctrl+Shift+Z` walks nothing and paints** (rules 3 and 8).
    #[test]
    fn the_redo_key_with_nothing_ahead_changes_nothing() {
        let mut state = a_drawn_state_over(A_BOX);

        let outcome = send(&redo_key(), &mut state);
        let buffer = draw(&mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(!state.diagram().can_undo(), "the press recorded a step");
        assert!(!state.diagram().can_redo(), "the press left a step ahead");
        assert_eq!(
            buffer[(3, 3)].symbol(),
            "┌",
            "the press changed the drawing"
        );
    }

    /// **Both keys are `Unclaimed`, so an open drop-down does not keep either** (rule 7): the
    /// history walks behind the menu, the shape comes back and goes again, and **the keyboard then
    /// goes back to the region, which closes the drop-down with it** (rule 13).
    #[test]
    fn the_walks_are_answered_with_the_drop_down_open_and_take_the_keyboard_back() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::Delete), &mut state);
        let _ = draw(&mut state);
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_none(),
            "the box was not removed, so the test proves nothing"
        );

        open_the_drop_down(&mut state, 'f');
        let outcome = send(&undo_key(), &mut state);
        let _ = draw(&mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "the drop-down kept the undo key from the history"
        );
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "the undo left the keyboard on the bar"
        );
        assert!(
            !state.chrome().popup_active(),
            "a drop-down is open with the keyboard on the region"
        );

        open_the_drop_down(&mut state, 'f');
        let outcome = send(&redo_key(), &mut state);
        let _ = draw(&mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_none(),
            "the drop-down kept the redo key from the history"
        );
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "the redo left the keyboard on the bar"
        );
        assert!(
            !state.chrome().popup_active(),
            "a drop-down is open with the keyboard on the region"
        );
    }

    /// **The table answers a meaning and not a count of steps** (rule 6): `Action::Undo` has no
    /// field, and the session is asked to walk where the action is carried out.
    #[test]
    fn the_undo_shortcut_says_only_that_it_undoes() {
        assert_eq!(
            shortcuts::handle_unclaimed(&undo_key()),
            Reply::Act(Action::Undo),
            "the undo key is not a row of the table, or says something else"
        );
        assert_eq!(
            shortcuts::handle_always(&undo_key()),
            Reply::Ignored,
            "the undo key reaches before the chrome"
        );
    }

    /// **The redo key says a meaning too**, and reaches after the chrome as the undo does.
    #[test]
    fn the_redo_shortcut_says_only_that_it_redoes() {
        assert_eq!(
            shortcuts::handle_unclaimed(&redo_key()),
            Reply::Act(Action::Redo),
            "the redo key is not a row of the table, or says something else"
        );
        assert_eq!(
            shortcuts::handle_always(&redo_key()),
            Reply::Ignored,
            "the redo key reaches before the chrome"
        );
    }

    /// **A walk clears the selection** (#297). The box is selected before the undo; the undo gives
    /// the step back and clears the selection, returning the application to `IDLE`. Selecting the
    /// box again and redoing clears the selection too, leaving the frame with no cell inverted.
    #[test]
    fn the_undo_and_redo_keys_clear_the_selection() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let _ = send(&key(KeyCode::Right), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected"
        );

        let outcome = send(&undo_key(), &mut state);
        let buffer = draw(&mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().selected(),
            None,
            "the undo kept the selection"
        );
        assert!(
            !reversed(&buffer, 3, 3),
            "the frame after the undo inverts a cell"
        );

        let _ = send(&click(3, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected again"
        );

        let outcome = send(&redo_key(), &mut state);
        let buffer = draw(&mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().selected(),
            None,
            "the redo kept the selection"
        );
        assert!(
            !reversed(&buffer, 4, 3),
            "the frame after the redo inverts a cell"
        );
    }

    /// **The next frame draws the restored diagram into the same window** (rule 13): the undo
    /// changes no region, and every figure is where the step left it.
    #[test]
    fn a_frame_after_an_undo_draws_the_restored_diagram() {
        let mut state = a_drawn_state_over(A_BOX);
        let _ = send(&click(3, 3), &mut state);
        let before = draw(&mut state);

        let _ = send(&key(KeyCode::Delete), &mut state);
        let _ = send(&undo_key(), &mut state);
        let after = draw(&mut state);

        let region = frame::regions(Rect::new(0, 0, WIDTH, HEIGHT)).region;
        for line in region.top()..region.bottom() {
            assert_eq!(
                row_of(&before, line),
                row_of(&after, line),
                "row {line} is not where the step left it"
            );
        }
    }

    /// **What hung from the removed shape stays drawn where it stood** (rule 8). The diagram model
    /// freezes the reference at the point it resolved to, and the frame that follows the removal
    /// draws the connector there rather than leaving it out.
    #[test]
    fn a_frame_after_a_removal_draws_the_connector_where_it_stood() {
        let mut state = a_drawn_state_over(A_BOX_AND_WHAT_HANGS_FROM_IT);
        let _ = send(&click(1, 3), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the left box was not selected"
        );

        let _ = send(&key(KeyCode::Delete), &mut state);
        let buffer = draw(&mut state);

        // The left box is gone, and its cells are blank.
        for (column, line) in [(1, 3), (4, 3), (1, 4), (1, 5), (4, 5)] {
            assert_eq!(
                buffer[(column, line)].symbol(),
                " ",
                "({column}, {line}) still holds the removed box"
            );
        }

        // The connector's near end was frozen at the point it resolved to: the window's `(3, 2)`
        // is the screen's `(4, 4)`, and the line reaches the right box's left side at `(17, 4)`.
        assert_eq!(
            row_of(&buffer, 4),
            "│   ─────────────┤  │                  │",
            "the frame does not draw the connector where it stood"
        );
        assert_eq!(
            buffer[(17, 3)].symbol(),
            "┌",
            "the right box went with the connector"
        );
        assert_eq!(
            buffer[(20, 3)].symbol(),
            "┐",
            "the right box is not four cells wide"
        );
    }

    /// **A turn of the wheel over the region moves the view by the helper's step** (rule 3): a
    /// tenth of the window on the axis the wheel reports, and at least one cell where the tenth is
    /// less. The step is the helper's rather than a rule of ours, so the numbers are its
    /// arithmetic: `38/10 = 3` across and `5/10 = 0`, which it answers as one cell down.
    ///
    /// **`Alt` is the wheel's across**: the helper reads a turn with `Alt` held as the horizontal
    /// axis, which is the one gesture the wheel and the bar share.
    #[test]
    fn the_wheel_moves_the_view_by_the_helpers_step() {
        let mut state = a_drawn_state_over(A_BOX_TOO_BIG);

        let outcome = send(&wheel(MouseEventKind::ScrollDown, 5, 4), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 0, y: 1 },
            "a turn down did not move the view by a tenth of the window, at least one cell"
        );

        let outcome = send(
            &wheel_with(MouseEventKind::ScrollDown, KeyModifiers::ALT, 5, 4),
            &mut state,
        );

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 3, y: 1 },
            "Alt and a turn down did not move the view across by a tenth of the window"
        );
    }

    /// **A turn the content refuses changes nothing and owes no frame** (rule 3): at the far end of
    /// the content there is nowhere left to go, so the region does not claim the event.
    #[test]
    fn a_wheel_at_the_end_moves_nothing_and_owes_no_frame() {
        let mut state = a_drawn_state_over(A_BOX_TOO_BIG);

        for _ in 0..8 {
            let _ = send(
                &wheel_with(MouseEventKind::ScrollDown, KeyModifiers::ALT, 5, 4),
                &mut state,
            );
        }
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 22, y: 0 },
            "eight turns did not reach the content's far end, so the test proves nothing"
        );

        let outcome = send(
            &wheel_with(MouseEventKind::ScrollDown, KeyModifiers::ALT, 5, 4),
            &mut state,
        );

        assert!(
            matches!(outcome, Control::Continue),
            "the end of the content owed a frame: {outcome:?}"
        );
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 22, y: 0 },
            "the view moved past the content"
        );
    }

    /// **A press on the bar takes the view to the position it names** (rule 4): the helper maps the
    /// track's cells over the content's reach, so the middle of the track names the middle of the
    /// content.
    ///
    /// The vertical track is the region's last column, rows `2` to `6`, and the content's span is
    /// `9`: the row `5` the press lands on is the fourth of the five cells the track maps, so the view
    /// stands six rows down.
    #[test]
    fn a_press_on_the_bar_jumps_the_view() {
        let mut state = a_drawn_state_over(A_BOX_TOO_BIG);

        let outcome = send(&click(39, 5), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 0, y: 6 },
            "the press did not take the view to the position it named"
        );
    }

    /// **A drag on the bar follows the pointer** (rule 4): the press starts the drag where the thumb
    /// stands, and every position the pointer reaches names the offset under it.
    ///
    /// The track is rows `2` to `6` of the region's last column. The press is at row `3`, which maps
    /// to the content's first row — where the view already stands, so it moves nothing and is only
    /// what starts the drag — and the two drags walk the track to its last cell, which is the end of
    /// the content.
    #[test]
    fn a_drag_on_the_bar_follows_the_pointer() {
        let mut state = a_drawn_state_over(A_BOX_TOO_BIG);

        let outcome = send(&click(39, 3), &mut state);
        assert!(matches!(outcome, Control::Continue), "{outcome:?}");
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 0, y: 0 },
            "the press where the thumb stands moved the view"
        );

        let outcome = send(&drag(39, 5), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 0, y: 6 },
            "the drag did not follow the pointer down the track"
        );

        let outcome = send(&drag(39, 6), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 0, y: 9 },
            "the drag across the track's last cell did not reach the content's end"
        );
    }

    /// **A drag past the track stops at the content's end** (rule 2): the helper keeps reading a drag
    /// once it began on the bar, so a pointer that leaves the track names an offset past the
    /// content's span — `10` where the span is `9` — and the origin's range is what holds it.
    ///
    /// The track is rows `2` to `6` of the region's last column, so row `7` is the region's bottom
    /// border: one cell past the track, and still a drag the helper answers.
    #[test]
    fn a_drag_past_the_track_is_clamped_to_the_content() {
        let mut state = a_drawn_state_over(A_BOX_TOO_BIG);

        let outcome = send(&click(39, 3), &mut state);
        assert!(
            matches!(outcome, Control::Continue),
            "the press moved the view: {outcome:?}"
        );

        let outcome = send(&drag(39, 7), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 0, y: 9 },
            "the drag past the track did not stop at the content's end"
        );
    }

    /// **A scroll changes no session and records no step** (rule 5): the view is the state's and the
    /// walk is the session's, so a turn of the wheel leaves the history and the drawing alone.
    #[test]
    fn a_scroll_records_no_step() {
        let mut state = a_drawn_state_over(A_BOX_TOO_BIG);
        let reach = state.diagram().footprint();
        assert!(reach.is_some(), "the drawing reached nothing");

        let outcome = send(&wheel(MouseEventKind::ScrollDown, 5, 4), &mut state);

        assert!(
            matches!(outcome, Control::Changed),
            "the view did not move, so the test proves nothing: {outcome:?}"
        );
        assert!(!state.diagram().can_undo(), "the scroll recorded a step");
        assert!(!state.diagram().can_redo(), "the scroll left a step ahead");
        assert_eq!(
            state.diagram().footprint(),
            reach,
            "the scroll changed what the drawing reaches"
        );
    }

    /// **Neither an undo nor a redo restores a view** (rule 5): the moves are the session's and the
    /// view is the state's, so walking the history changes what is drawn without changing where it
    /// is drawn from.
    #[test]
    fn neither_an_undo_nor_a_redo_restores_a_view() {
        let mut state = a_drawn_state_over(A_BOX_TOO_BIG);
        let _ = send(&click(2, 2), &mut state);
        assert!(
            state.diagram().selected().is_some(),
            "the box was not selected"
        );
        let _ = send(&key(KeyCode::Right), &mut state);
        assert!(state.diagram().can_undo(), "the move recorded no step");
        let _ = send(&wheel(MouseEventKind::ScrollDown, 5, 4), &mut state);
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 0, y: 1 },
            "the wheel did not move the view, so the test proves nothing"
        );

        let outcome = send(&undo_key(), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            state.diagram().can_redo(),
            "the undo did not walk the history"
        );
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 0, y: 1 },
            "the undo restored a view"
        );

        let outcome = send(&redo_key(), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert!(
            state.diagram().can_undo(),
            "the redo did not walk the history"
        );
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 0, y: 1 },
            "the redo restored a view"
        );
    }

    /// **A scroll keeps the selection** (rule 6): the identity is the drawing's rather than a
    /// cell's, so the frame after the scroll inverts the cells the drawing records for it inside the
    /// new window, and no others.
    #[test]
    fn a_scroll_keeps_the_selection() {
        let mut state = a_drawn_state_over(A_BOX_TOO_BIG);
        let _ = send(&click(2, 2), &mut state);
        let selected = state.diagram().selected();
        assert!(selected.is_some(), "the box was not selected");
        assert!(
            reversed(&draw(&mut state), 2, 2),
            "the selection is not inverted before the scroll"
        );

        let outcome = send(&wheel(MouseEventKind::ScrollDown, 5, 4), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 0, y: 1 },
            "the wheel did not move the view, so the test proves nothing"
        );

        let buffer = draw(&mut state);
        let region = frame::regions(Rect::new(0, 0, WIDTH, HEIGHT)).region;

        assert_eq!(
            state.diagram().selected(),
            selected,
            "the scroll dropped the selection"
        );
        for y in 0..region.height - 2 {
            for x in 0..region.width - 2 {
                let at = Offset { x, y };

                assert_eq!(
                    reversed(&buffer, region.left() + 1 + x, region.top() + 1 + y),
                    state.diagram().is_cell_selected(at),
                    "the cell at {at:?} is not the inversion the drawing records"
                );
            }
        }
    }

    /// **A click after a scroll is answered at the offset from the window's corner** (rule 7): the
    /// origin belongs to the plane and takes no part in the click's arithmetic, so the cell under
    /// the pointer is the cell the person saw.
    ///
    /// `Alt` and a turn of the wheel move the view three columns across, which puts the middle box's
    /// corner at the window's `(24, 0)` — the screen's `(25, 2)`. A click that added the origin to
    /// the offset would ask about the window's `(27, 0)`, which no shape wrote.
    #[test]
    fn a_click_after_a_scroll_selects_the_cell_under_the_pointer() {
        let mut state = a_drawn_state_over(BOXES_APART);

        let outcome = send(
            &wheel_with(MouseEventKind::ScrollDown, KeyModifiers::ALT, 20, 4),
            &mut state,
        );
        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 3, y: 0 },
            "the view did not move across, so the test proves nothing"
        );

        // **The frame comes before the click**, as it does in the loop: `Reply::Repaint` repaints,
        // and a click is answered from the picture the person saw.
        let _ = draw(&mut state);
        let outcome = send(&click(25, 2), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        let under = state.diagram().owner(Offset { x: 24, y: 0 });
        assert!(
            under.is_some(),
            "the cell under the pointer is not the middle box's corner"
        );
        assert_eq!(
            state.diagram().selected(),
            under,
            "the click selected another shape"
        );
    }

    /// **A press on the bar is the bar's and not the diagram's** (rule 7): it moves the view and
    /// keeps a selection that a press on a cell of the drawing would have dropped, and it still
    /// gives the region the keyboard, because a press on the border is the region's.
    #[test]
    fn a_press_on_the_bar_gives_the_region_the_keyboard() {
        let mut state = a_drawn_state_over(A_BOX_TOO_BIG);
        let _ = send(&click(2, 2), &mut state);
        let selected = state.diagram().selected();
        assert!(selected.is_some(), "the box was not selected");
        state.chrome_mut().move_to_bar();
        let _ = draw(&mut state);

        let outcome = send(&click(39, 5), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
        assert_eq!(
            state.chrome().leaf(),
            Focus::Region,
            "the press on the bar left the keyboard on the bar"
        );
        assert_eq!(
            state.diagram().selected(),
            selected,
            "the press on the bar changed the selection"
        );
        assert_eq!(
            state.diagram().origin(),
            Pos { x: 0, y: 6 },
            "the press on the bar did not move the view"
        );
    }

    #[test]
    fn a_resize_repaints_although_nobody_asked() {
        let mut state = a_drawn_state();

        let outcome = send(&Event::Resize(80, 24), &mut state);

        assert!(matches!(outcome, Control::Changed), "{outcome:?}");
    }

    #[test]
    fn the_error_handler_does_not_answer_with_the_error_again() {
        let mut state = a_state();
        let mut global = a_global();
        let failure: AppError = "no terminal".into();

        let outcome = error(failure, &mut state, &mut global);

        assert!(
            matches!(outcome, Ok(Control::Quit)),
            "the handler answered with the error again: {outcome:?}"
        );
        assert!(
            global.take_failure().is_some(),
            "the error was not kept to be written out"
        );
    }

    #[test]
    fn the_loop_set_the_terminal_up_itself_so_there_is_nothing_to_init() {
        assert!(init(&mut a_state(), &mut a_global()).is_ok());
    }

    #[test]
    fn pressing_d_duplicates_selected_shape_selects_new_id_and_undoes_in_one_step() {
        let fixture = r#"{
            "next_id": 2,
            "shapes": [ { "kind": "box", "id": 1, "at": { "x": 1, "y": 1 },
                          "size": { "width": 6, "height": 3 }, "stroke": "double", "text": "API" } ]
        }"#;
        let mut state = a_drawn_state_over(fixture);
        let id1 = ShapeId::new(NonZeroU16::new(1).unwrap());
        let id2 = ShapeId::new(NonZeroU16::new(2).unwrap());

        // In IDLE, 'd' is ignored.
        let d_key = Event::Key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE));
        let idle_outcome = send(&d_key, &mut state);
        assert!(matches!(idle_outcome, Control::Continue));
        assert_eq!(state.diagram().session().diagram().shape_count(), 1);

        // Select Box #1.
        state.diagram_mut().select(Some(id1));
        assert_eq!(
            crate::status::status_line(state.diagram()),
            "Box #1 \"API\" · Pos: (1, 1) · Size: 6×3 · Stroke: double · Fill: None"
        );
        assert!(
            crate::status::command_line(state.diagram())
                .ends_with("· [d] Duplicate · [Del] Delete · [Esc] Deselect")
        );

        // Pressing 'd' duplicates Box #1 into Box #2 and selects #2.
        let dup_outcome = send(&d_key, &mut state);
        assert!(matches!(dup_outcome, Control::Changed));
        assert_eq!(state.diagram().session().diagram().shape_count(), 2);
        assert_eq!(state.diagram().selected(), Some(id2));
        assert_eq!(
            crate::status::status_line(state.diagram()),
            "Box #2 \"API\" · Pos: (1, 1) · Size: 6×3 · Stroke: double · Fill: None"
        );

        // Undo (Ctrl+z) removes the duplicate in a single step and reconciles selection.
        let undo_key = Event::Key(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::CONTROL));
        let undo_outcome = send(&undo_key, &mut state);
        assert!(matches!(undo_outcome, Control::Changed));
        assert_eq!(state.diagram().session().diagram().shape_count(), 1);
        assert_eq!(state.diagram().selected(), None);
        assert!(!state.diagram().session().can_undo());

        // Redo (Ctrl+Shift+Z) restores the duplicate in a single step.
        let redo_key = Event::Key(KeyEvent::new(
            KeyCode::Char('Z'),
            KeyModifiers::CONTROL.union(KeyModifiers::SHIFT),
        ));
        let redo_outcome = send(&redo_key, &mut state);
        assert!(matches!(redo_outcome, Control::Changed));
        assert_eq!(state.diagram().session().diagram().shape_count(), 2);
        assert!(state.diagram().session().diagram().get(id2).is_some());
    }
}