gantz_egui 0.6.1

UI traits and widgets that make up the GUI for gantz, an environment for creative systems.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
use crate::{
    Action, CopyNodes, CreateNestedGraph, CreateNode, CutNodes, DuplicateNodes, Env,
    ExportAllNamed, ExportHead, HeadAccess, Keymap, NodeCtx, NodeUi, OpenLogs, OpenNodePalette,
    OpenNodeView, Paste, Redo, ReplaceHead, ResetTilesLayout, Undo, export,
    node::NodeCodec,
    response::{DynResponse, Responses},
    widget::{self, GraphScene, GraphSceneState, graph_scene},
};
use gantz_core::node;
use petgraph::visit::IntoNodeIdentifiers;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use steel::steel_vm::engine::Engine;

/// A file dropped onto a gantz pane.
#[derive(Debug)]
pub struct FileDrop {
    pub bytes: Vec<u8>,
    pub target: FileDropTarget,
}

/// Which pane received the file drop.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FileDropTarget {
    /// Graphs pane: merge registry + views only.
    Graphs,
    /// GraphScene pane: merge + open the root graph if unique.
    GraphScene,
}

/// The reserved node-type name that creates a new nested graph.
///
/// Selecting this entry in the node palette emits a
/// [`CreateNestedGraph`] rather than a [`CreateNode`], so a nested graph is
/// created like any other node but routed through the registry-aware op.
pub const NESTED_GRAPH_TYPE: &str = "graph";

/// The top-level gantz widget.
pub struct Gantz<'a> {
    env: &'a Env<'a>,
    /// The value-level codec through which working-graph nodes reify for
    /// their UI passes (and erase back on change).
    codec: &'a NodeCodec,
    base_names: &'a crate::reg::Names,
    log_source: Option<LogSource>,
    perf_vm: Option<&'a mut widget::PerfCapture>,
    perf_gui: Option<&'a mut widget::PerfCapture>,
    base_immutable: bool,
    compile_config: Option<gantz_core::compile::Config>,
    validate_change_tracking: Option<bool>,
    settings_tabs: &'a mut [&'a mut dyn widget::SettingsTab],
    ext_panes: &'a mut [&'a mut dyn widget::ExtPane],
    ref_ext_uis: &'a [&'a dyn crate::node::RefExtUi],
    edge_styles: &'a [&'a dyn widget::EdgeStyle],
    base_sources: Option<BaseSourcesCtx<'a>>,
    pane_window_mode: PaneWindowMode,
    collab: Option<&'a crate::collab::CollabUiState>,
    /// A host-provided clipboard reader for widget paste affordances (egui
    /// alone cannot read the clipboard); `None` hides them.
    clipboard: Option<&'a dyn Fn() -> Option<String>>,
}

/// Base-source authoring context for the graph config pane's "source"
/// dropdown (see [`widget::GraphConfig::base_sources`]). Supplied only by
/// base-authoring hosts like `update-base`, where the per-source write-back
/// makes an association change durable.
#[derive(Clone, Copy)]
pub struct BaseSourcesCtx<'a> {
    /// The available base source names, in load order.
    pub sources: &'a [&'a str],
    /// Each base name's owning source.
    pub name_sources: &'a HashMap<String, &'static str>,
    /// The source an unattributed (session-created) name is written to.
    pub default_source: &'a str,
}

/// Selects who draws the windows that popped-out panes live in.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum PaneWindowMode {
    /// The widget draws each windowed pane as a floating `egui::Window`. Used on
    /// web, in the eframe demo, and as the native fallback. The default.
    #[default]
    EguiWindow,
    /// The host owns real OS windows and renders each windowed pane itself (via
    /// [`Gantz::render_windowed_pane`]); the widget only reports the windowed set
    /// via [`GantzResponse::windowed_panes`].
    HostNative,
}

enum LogSource {
    Logger(widget::log_view::Logger),
    #[cfg(feature = "tracing")]
    TraceCapture(
        widget::trace_view::TraceCapture,
        tracing::level_filters::LevelFilter,
    ),
}

/// All state for the widget.
#[derive(serde::Deserialize, serde::Serialize)]
pub struct GantzState {
    /// State for each open head.
    #[serde(serialize_with = "gantz_ca::serde_sorted::serialize_map")]
    pub open_heads: OpenHeadStates,
    pub view_toggles: ViewToggles,
    #[serde(default, alias = "command_palette")]
    pub node_palette: widget::NodePalette,
    /// Global auto-layout parameters (the non-flow `egui_graph` layout params;
    /// flow stays per-head in [`OpenHeadState::layout_flow`]).
    #[serde(default)]
    pub layout_config: LayoutConfig,
    /// Global interactive-scene parameters: dot grid, drag snapping, and
    /// snap-align. Mirror the per-frame `egui_graph::Graph` builder options and
    /// apply to every open head.
    #[serde(default)]
    pub scene_config: SceneConfig,
    /// The command keyboard shortcuts. The single source of truth for editor
    /// command bindings (see [`crate::keybind`]); edited in Settings -> Keybinds.
    #[serde(default)]
    pub keymap: Keymap,
    /// User-editable collaboration configuration (Settings -> Collab).
    #[serde(default)]
    pub collab: crate::collab::CollabConfig,
    /// How graph merges resolve conflicts; edited via the merge row's "â›­"
    /// menu in the Graph Config pane.
    #[serde(default)]
    pub merge_resolutions: gantz_ca::merge::Resolutions,
    /// Per-head redo stacks for undo/redo support.
    #[serde(default, serialize_with = "gantz_ca::serde_sorted::serialize_map")]
    pub redo_stacks: HashMap<gantz_ca::Head, Vec<gantz_ca::CommitAddr>>,
    /// Per-head stepping state for session (revert-commit) undo/redo (see
    /// [`crate::ops::session_undo`]). Lives and migrates beside
    /// [`Self::redo_stacks`].
    #[serde(default, serialize_with = "gantz_ca::serde_sorted::serialize_map")]
    pub undo_cursors: HashMap<gantz_ca::Head, crate::ops::RevertCursor>,
    /// The sidebar's pixel width, maintained across window resizes (fixed, not
    /// proportional). Updated when the user drags the divider.
    #[serde(default = "default_sidebar_width")]
    pub sidebar_width: f32,
    /// The bottom tray's pixel height, maintained across window resizes.
    #[serde(default = "default_tray_height")]
    pub tray_height: f32,
    /// Last-seen size of each pane popped out into its own OS window, keyed by
    /// [`pane_key`], so a native host can restore it across sessions. Only the
    /// native window backend populates this (web `egui::Window`s persist their
    /// own geometry in egui memory).
    #[serde(default)]
    pub windowed_geometry: HashMap<String, PaneWindowGeometry>,
}

/// The persisted geometry of a pane's pop-out window, in logical pixels.
#[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)]
pub struct PaneWindowGeometry {
    pub width: f32,
    pub height: f32,
}

/// The default fixed sidebar width, in points.
fn default_sidebar_width() -> f32 {
    270.0
}

/// The default fixed bottom-tray height, in points.
fn default_tray_height() -> f32 {
    300.0
}

pub type OpenHeadStates = HashMap<gantz_ca::Head, OpenHeadState>;

/// State associated with a single open graph.
#[derive(serde::Deserialize, serde::Serialize)]
pub struct OpenHeadState {
    /// State associated with the `GraphScene` widget.
    pub scene: GraphSceneState,
    /// The per-head flow direction used when auto-layout is invoked.
    #[serde(default = "default_layout_flow")]
    pub layout_flow: egui::Direction,
}

fn default_layout_flow() -> egui::Direction {
    GantzState::DEFAULT_DIRECTION
}

impl Default for OpenHeadState {
    fn default() -> Self {
        Self {
            scene: GraphSceneState::default(),
            layout_flow: GantzState::DEFAULT_DIRECTION,
        }
    }
}

/// Global auto-layout parameters, mirroring the non-flow fields of
/// [`egui_graph::LayoutParams`]. Flow stays per-head (see
/// [`OpenHeadState::layout_flow`]); these apply to every head's auto-layout.
#[derive(Clone, Copy, serde::Deserialize, serde::Serialize)]
pub struct LayoutConfig {
    /// The gap between adjacent layers along the flow direction.
    #[serde(default = "default_layer_gap")]
    pub layer_gap: f32,
    /// The gap between adjacent nodes within a layer.
    #[serde(default = "default_node_gap")]
    pub node_gap: f32,
    /// The gap between disconnected components of the graph.
    #[serde(default = "default_component_gap")]
    pub component_gap: f32,
    /// Whether the layout accounts for the socket each edge connects to.
    #[serde(default = "default_socket_aware")]
    pub socket_aware: bool,
}

fn default_layer_gap() -> f32 {
    egui_graph::LayoutParams::DEFAULT_LAYER_GAP
}

fn default_node_gap() -> f32 {
    egui_graph::LayoutParams::DEFAULT_NODE_GAP
}

fn default_component_gap() -> f32 {
    egui_graph::LayoutParams::DEFAULT_COMPONENT_GAP
}

fn default_socket_aware() -> bool {
    true
}

impl Default for LayoutConfig {
    fn default() -> Self {
        Self {
            layer_gap: default_layer_gap(),
            node_gap: default_node_gap(),
            component_gap: default_component_gap(),
            socket_aware: default_socket_aware(),
        }
    }
}

impl LayoutConfig {
    /// Build [`egui_graph::LayoutParams`] from these globals plus a per-head
    /// `flow` direction.
    pub fn to_params(&self, flow: egui::Direction) -> egui_graph::LayoutParams {
        egui_graph::LayoutParams::new(flow)
            .layer_gap(self.layer_gap)
            .node_gap(self.node_gap)
            .component_gap(self.component_gap)
            .socket_aware(self.socket_aware)
    }
}

/// Global interactive-scene configuration: the dot grid, drag snapping and
/// snap-align. Mirrors the per-frame snap/grid/align options on
/// [`egui_graph::Graph`] and applies to every open head (like [`LayoutConfig`]).
#[derive(Clone, Copy, Default, serde::Deserialize, serde::Serialize)]
pub struct SceneConfig {
    #[serde(default)]
    pub grid: GridConfig,
    #[serde(default)]
    pub snap: SnapConfig,
    #[serde(default)]
    pub align: AlignConfig,
}

/// The dot grid drawn behind the graph (see [`egui_graph::Graph::dot_grid`]).
#[derive(Clone, Copy, serde::Deserialize, serde::Serialize)]
pub struct GridConfig {
    /// Whether the dot grid is drawn.
    #[serde(default = "default_grid_show")]
    pub show: bool,
    /// The base spacing of the dot grid, in graph-space units.
    #[serde(default = "default_grid_step")]
    pub step: f32,
}

fn default_grid_show() -> bool {
    true
}

fn default_grid_step() -> f32 {
    20.0
}

impl Default for GridConfig {
    fn default() -> Self {
        Self {
            show: default_grid_show(),
            step: default_grid_step(),
        }
    }
}

/// How a dragged node's position is snapped.
#[derive(Clone, Copy, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub enum SnapMode {
    /// Snap to the nearest unit point (`snap_step = 1.0`); effectively free.
    #[default]
    Point,
    /// Snap to a relative fraction of the dot grid (see [`SnapConfig::grid_ratio`]).
    Grid,
}

/// Drag snapping configuration (see [`egui_graph::Graph::snap`]).
#[derive(Clone, Copy, serde::Deserialize, serde::Serialize)]
pub struct SnapConfig {
    #[serde(default)]
    pub mode: SnapMode,
    /// In [`SnapMode::Grid`], the snap step relative to the grid step:
    /// `snap_step = grid.step * grid_ratio`. `1.0` snaps to the full grid,
    /// `0.5` to half, `0.25` to quarter, and so on.
    #[serde(default = "default_grid_ratio")]
    pub grid_ratio: f32,
}

fn default_grid_ratio() -> f32 {
    1.0
}

impl Default for SnapConfig {
    fn default() -> Self {
        Self {
            mode: SnapMode::default(),
            grid_ratio: default_grid_ratio(),
        }
    }
}

/// Drag-time snap-align configuration (see [`egui_graph::Graph::align`]).
#[derive(Clone, Copy, serde::Deserialize, serde::Serialize)]
pub struct AlignConfig {
    /// Whether a dragged node snap-aligns to its neighbours.
    #[serde(default = "default_align_enabled")]
    pub enabled: bool,
    /// Align to neighbours' left/right/top/bottom edges.
    #[serde(default = "default_align_edges")]
    pub edges: bool,
    /// Align to neighbours' horizontal/vertical centres.
    #[serde(default = "default_align_centers")]
    pub centers: bool,
}

fn default_align_enabled() -> bool {
    true
}

fn default_align_edges() -> bool {
    true
}

fn default_align_centers() -> bool {
    false
}

impl Default for AlignConfig {
    fn default() -> Self {
        Self {
            enabled: default_align_enabled(),
            edges: default_align_edges(),
            centers: default_align_centers(),
        }
    }
}

impl SceneConfig {
    /// Apply the grid, snap and align options onto an [`egui_graph::Graph`]
    /// builder. The snap step is derived from the mode: [`SnapMode::Point`]
    /// snaps to unit points, [`SnapMode::Grid`] to a fraction of the grid.
    pub fn apply(self, graph: egui_graph::Graph) -> egui_graph::Graph {
        let snap_step = match self.snap.mode {
            SnapMode::Point => 1.0,
            SnapMode::Grid => self.grid.step * self.snap.grid_ratio,
        };
        graph
            // gantz owns zoom persistence (the camera stores centre + zoom, and
            // the scene rect is rebuilt from it each frame against the live
            // viewport). Use `MaintainView` so `egui_graph` does not *also*
            // rescale the rect on resize and double-adjust the zoom.
            .resize_behavior(egui_graph::ResizeBehavior::MaintainView)
            .dot_grid(self.grid.show)
            .dot_grid_step(self.grid.step)
            .snap(Some(egui_graph::Snap::Round))
            .snap_step(snap_step)
            .align(self.align.enabled)
            .align_targets(egui_graph::AlignTargets {
                edges: self.align.edges,
                centers: self.align.centers,
            })
    }
}

/// A pane within the outer tree.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum Pane {
    /// An application-supplied pane, identified by its provider's stable key
    /// (see [`ExtPane::key`][widget::ExtPane::key]). Renders a placeholder
    /// while no provider supplies the key.
    Ext(String),
    GraphConfig,
    /// Contains the inner graph tree with all open graph tabs.
    GraphScene,
    Graphs,
    /// An editable GUI tree literal rendered live through the
    /// [`ui_tree`][crate::ui_tree] interpreter against the focused head's VM.
    GuiDebug,
    GuiPerf,
    History,
    Logs,
    NodeInspector,
    /// A node detached from a graph via the "open view" action, rendered via
    /// [`NodeUi::view_ui`] for monitoring. A data-carrying pane (unlike the
    /// singleton variants), so any number can be opened and freely placed
    /// anywhere in the top-level tree.
    NodeView(NodeViewPane),
    /// Globally relevant configuration grouped into Panes / Style / Global
    /// subtabs (pane visibility, style, compile options, reset all demos).
    Settings,
    Steel,
    VmPerf,
}

/// A pane within the inner graph tree.
/// Contains the head (branch or commit) that this pane displays.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
struct GraphPane(gantz_ca::Head);

/// The payload of a [`Pane::NodeView`]: one detached node view, identified by
/// its `head` and `path` within that head's graph. `ty_name` is the node's type
/// name ([`NodeUi::name`]), cached at open-time so the tab title is stable even
/// while the head is closed (the node type never changes; only its index does,
/// and that is migrated by `migrate_node_view_paths`).
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct NodeViewPane {
    head: gantz_ca::Head,
    path: Vec<node::Id>,
    ty_name: String,
}

/// The egui ID used to store the inner graph tree.
const GRAPH_TREE_ID: &str = "gantz-graph-tiles-tree";

/// Load a value persisted in egui memory as a RON `String`.
///
/// Values are stored as a RON `String` rather than typed: a `String`'s `TypeId`
/// is stable across recompiles, whereas many of our types' `TypeId`s (e.g.
/// `Tree<Pane>`, `Vec<Pane>`) change whenever this crate is rebuilt. Storing the
/// typed value would leave a stale copy behind in egui's per-type persisted map
/// on every dev build (egui never evicts entries of a type the running build no
/// longer uses), bloating the persisted memory without bound.
fn load_ron<T: serde::de::DeserializeOwned>(ctx: &egui::Context, id: egui::Id) -> Option<T> {
    let ron = ctx.memory_mut(|m| m.data.get_persisted::<String>(id))?;
    ron::from_str(&ron).ok()
}

/// Persist a value to egui memory as a RON `String` (see [`load_ron`]).
fn store_ron<T: serde::Serialize>(ctx: &egui::Context, id: egui::Id, value: &T) {
    if let Ok(ron) = ron::to_string(value) {
        ctx.memory_mut(|m| m.data.insert_persisted(id, ron));
    }
}

/// Load a tile tree from egui's persisted memory (see [`load_ron`]).
fn load_tree<P: serde::de::DeserializeOwned>(
    ctx: &egui::Context,
    id: egui::Id,
) -> Option<egui_tiles::Tree<P>> {
    load_ron(ctx, id)
}

/// Persist a tile tree to egui memory as a RON `String` (see [`load_ron`]).
fn store_tree<P: serde::Serialize>(ctx: &egui::Context, id: egui::Id, tree: &egui_tiles::Tree<P>) {
    store_ron(ctx, id, tree)
}

/// egui temp-memory flag id for a pending "clear egui memory" request.
fn clear_egui_memory_id() -> egui::Id {
    egui::Id::new("gantz-clear-egui-memory-request")
}

/// Request that egui's persisted memory be cleared at the start of the next
/// `Gantz::show`.
///
/// A recovery tool (exposed in Global settings) for when egui's persisted memory
/// accumulates stale state: it discards the UI memory (panel layout, widget
/// state) but leaves the graph registry and other app storage untouched.
/// Deferring to the next frame keeps the clear deterministic - it runs before
/// any persisted UI state is loaded, rather than racing this frame's widgets.
pub fn request_clear_egui_memory(ctx: &egui::Context) {
    ctx.data_mut(|d| d.insert_temp(clear_egui_memory_id(), true));
}

/// Update the head stored in a graph pane when a commit CA changes.
///
/// This should be called after `commit_graph_to_head` modifies a head's commit CA.
/// It updates the persisted graph tree to reflect the new head value.
pub fn update_graph_pane_head(
    ctx: &egui::Context,
    old_head: &gantz_ca::Head,
    new_head: &gantz_ca::Head,
) {
    if old_head == new_head {
        return;
    }
    let graph_tree_id = egui::Id::new(GRAPH_TREE_ID);
    let Some(mut tree) = load_tree::<GraphPane>(ctx, graph_tree_id) else {
        return;
    };
    // Find and update the pane with the old head.
    let mut changed = false;
    for (_, tile) in tree.tiles.iter_mut() {
        if let egui_tiles::Tile::Pane(GraphPane(head)) = tile {
            if head == old_head {
                *head = new_head.clone();
                changed = true;
                break;
            }
        }
    }
    if changed {
        store_tree(ctx, graph_tree_id, &tree);
    }
}

/// Migrate the [`Pane::NodeView`] panes for `head` after a node removal
/// reindexed its graph, mirroring the state/layout/selection migration in
/// [`crate::ops::remove_nodes`]: a view whose node was removed is dropped; a view
/// whose node was swapped to a new index has its path rewritten. This keeps a
/// detached view pointing at the same node across deletions, with no staleness
/// guard. Operates on the top-level `tree` (where node views live as tiles).
fn migrate_node_view_paths(
    tree: &mut egui_tiles::Tree<Pane>,
    head: &gantz_ca::Head,
    reindex: &crate::ops::Reindex,
) {
    if reindex.is_empty() {
        return;
    }
    let mut to_remove = Vec::new();
    for (id, tile) in tree.tiles.iter_mut() {
        let egui_tiles::Tile::Pane(Pane::NodeView(pane)) = tile else {
            continue;
        };
        if pane.head != *head {
            continue;
        }
        // Root-level node views have a single-element path.
        let [ix] = pane.path[..] else { continue };
        match reindex.apply_to_index(ix) {
            Some(new_ix) => pane.path = vec![new_ix],
            None => to_remove.push(*id),
        }
    }
    for id in to_remove {
        tree.tiles.remove(id);
    }
}

/// The data a single pane needs to render, independent of where the pane lives.
///
/// Extracted from [`TreeBehaviour`] so the same [`render_pane`] can draw a pane
/// as a tile in the tree, as a floating `egui::Window` (web / fallback), or (on
/// a native host) into its own OS window.
struct PaneCtx<'a, 's, Access>
where
    Access: HeadAccess,
{
    gantz: &'a mut Gantz<'s>,
    state: &'a mut GantzState,
    access: &'a mut Access,
    focused_head: usize,
    base_names: &'a crate::reg::Names,
    response: &'a mut GantzResponse,
}

/// The context passed to the `egui_tiles::Tree` widget.
struct TreeBehaviour<'a, 's, Access>
where
    Access: HeadAccess,
{
    gantz: &'a mut Gantz<'s>,
    state: &'a mut GantzState,
    access: &'a mut Access,
    focused_head: usize,
    base_names: &'a crate::reg::Names,
    gantz_response: &'a mut GantzResponse,
    /// Panes detached into windows. The tab context menu pushes to this when a
    /// pane is popped out.
    windowed: &'a mut Vec<Pane>,
}

/// Response from the top-level gantz widget.
///
/// Whole-widget outcomes (focus, tab management, file drops, config) are
/// plain fields; operations emitted from deeper within the widget tree
/// (node UIs, context menus, shortcuts) arrive as dynamic payloads in
/// [`responses`][Self::responses] for the application to drain and handle.
#[derive(Debug)]
pub struct GantzResponse {
    /// The focused head index (may have changed due to user interaction).
    pub focused_head: usize,
    pub graph_select: Option<widget::graph_select::GraphSelectResponse>,
    /// Heads that were closed via the tab close button.
    pub closed_heads: Vec<gantz_ca::Head>,
    /// New branch created from tab double-click: (original_head, new_branch_name).
    pub new_branch: Option<(gantz_ca::Head, String)>,
    /// Files dropped onto gantz panes.
    pub file_drops: Vec<FileDrop>,
    /// Demo graph association changed: (head, Some(demo_name) | None).
    pub demo_changed: Option<(gantz_ca::Head, Option<String>)>,
    /// A named graph's description was edited: (head, new_description). An empty
    /// string clears the description.
    pub description_changed: Option<(gantz_ca::Head, String)>,
    /// A base graph should be reset to its original state.
    pub reset_base_graph: Option<gantz_ca::Head>,
    /// All `demo-*` base graphs should be reset to their original state.
    pub reset_all_demos: bool,
    /// The global compile config was changed via the Graph Config pane.
    pub compile_config: Option<gantz_core::compile::Config>,
    /// The change-tracking validation toggle was changed (its new value).
    pub validate_change_tracking: Option<bool>,
    /// The graph's base source association was changed via the graph config
    /// pane (see [`Gantz::base_sources`]).
    pub base_source_changed: Option<(gantz_ca::Head, String)>,
    /// Heads whose graph had a CA-affecting edit this frame (from a node UI, an
    /// inspector edit, or a structural scene edit). Lets the application
    /// commit/recompile only the changed heads instead of re-hashing every open
    /// graph each frame. May contain duplicates; treat membership as a set.
    pub changed_heads: Vec<gantz_ca::Head>,
    /// Dynamic payloads emitted from within the widget tree, tagged with the
    /// emitting head. See [`crate::response`] for the handling contract.
    pub responses: Responses,
    /// Panes currently popped out into windows, reported every frame. Populated
    /// in both [`PaneWindowMode`]s; under [`PaneWindowMode::HostNative`] a host
    /// diffs this to create / title / destroy its OS windows and renders each
    /// via [`Gantz::render_windowed_pane`].
    pub windowed_panes: Vec<WindowedPane>,
    /// Per-head node index remappings from this frame's deletions, collected
    /// during traversal and applied to the top-level tree's [`Pane::NodeView`]
    /// paths by `Gantz::show` after layout. Internal scratch - drained before
    /// the response is returned, so applications can ignore it.
    pub(crate) node_view_reindexes: Vec<(gantz_ca::Head, crate::ops::Reindex)>,
}

/// A pane currently popped out into a window, reported via
/// [`GantzResponse::windowed_panes`].
#[derive(Clone, Debug)]
pub struct WindowedPane {
    /// The pane's identity and payload; pass back to
    /// [`Gantz::render_windowed_pane`] to draw it into the host's window.
    pub pane: Pane,
    /// The pane's display title (the same text as its tab).
    pub title: String,
}

/// State for editing a tab name via double-click.
#[derive(Clone, Default)]
struct TabEditState {
    /// The tile currently being edited, if any.
    editing_tile_id: Option<egui_tiles::TileId>,
    /// The text being edited.
    edit_text: String,
    /// Whether we need to request focus on the next frame.
    request_focus: bool,
}

#[derive(serde::Deserialize, serde::Serialize)]
#[serde(default)]
pub struct ViewToggles {
    /// Whether the sidebar (left column) is open. Toggled by the hamburger.
    pub sidebar_open: bool,
    pub graphs: bool,
    pub history: bool,
    pub settings: bool,
    pub logs: bool,
    pub node_inspector: bool,
    pub perf_gui: bool,
    pub perf_vm: bool,
    pub steel: bool,
    pub gui_debug: bool,
    pub graph_config: bool,
    /// Per-[`Pane::Ext`] visibility, keyed by the provider key. A missing
    /// entry means hidden (matching the tray panes' default). Keys of
    /// long-gone providers linger harmlessly.
    pub ext: BTreeMap<String, bool>,
}

impl Default for ViewToggles {
    fn default() -> Self {
        // The sidebar starts closed so a fresh launch shows only the graph
        // scene, but its content panes default to visible so that opening the
        // sidebar reveals the full arrangement. The Logs/Steel tray stays
        // hidden until toggled.
        Self {
            sidebar_open: false,
            graphs: true,
            history: true,
            settings: true,
            logs: false,
            node_inspector: true,
            perf_gui: false,
            perf_vm: false,
            steel: false,
            gui_debug: false,
            graph_config: true,
            ext: BTreeMap::new(),
        }
    }
}

struct NodeTyCmd<'a> {
    env: &'a Env<'a>,
    name: &'a str,
}

impl GantzResponse {
    /// An empty response for the given focused head.
    fn new(focused_head: usize) -> Self {
        GantzResponse {
            focused_head,
            graph_select: None,
            closed_heads: Vec::new(),
            new_branch: None,
            file_drops: Vec::new(),
            demo_changed: None,
            description_changed: None,
            reset_base_graph: None,
            reset_all_demos: false,
            compile_config: None,
            validate_change_tracking: None,
            base_source_changed: None,
            changed_heads: Vec::new(),
            responses: Responses::default(),
            windowed_panes: Vec::new(),
            node_view_reindexes: Vec::new(),
        }
    }

    /// Indicates the new graph button was clicked.
    pub fn new_graph(&self) -> bool {
        self.graph_select
            .as_ref()
            .map(|g| g.new_graph)
            .unwrap_or(false)
    }

    /// Replace the focused head with this one.
    pub fn graph_replaced(&self) -> Option<&gantz_ca::Head> {
        self.graph_select.as_ref().and_then(|g| g.replaced.as_ref())
    }

    /// Open this head as a new tab, or focus it if already open.
    pub fn graph_opened(&self) -> Option<&gantz_ca::Head> {
        self.graph_select.as_ref().and_then(|g| g.opened.as_ref())
    }

    /// Close this head.
    pub fn graph_closed(&self) -> Option<&gantz_ca::Head> {
        self.graph_select.as_ref().and_then(|g| g.closed.as_ref())
    }

    /// The given graph name was removed.
    pub fn graph_name_removed(&self) -> Option<gantz_ca::Name> {
        self.graph_select
            .as_ref()
            .and_then(|g| g.name_removed.clone())
    }

    /// New branch created from tab double-click: (original_head, new_branch_name).
    pub fn new_branch(&self) -> Option<&(gantz_ca::Head, String)> {
        self.new_branch.as_ref()
    }

    /// Indicates the import button was clicked.
    pub fn import(&self) -> bool {
        self.graph_select
            .as_ref()
            .map(|g| g.import)
            .unwrap_or(false)
    }
}

impl<'a> Gantz<'a> {
    /// Instantiate the full top-level gantz widget.
    pub fn new(env: &'a Env<'a>, base_names: &'a crate::reg::Names) -> Self {
        Self {
            env,
            codec: env.codec,
            base_names,
            log_source: None,
            perf_vm: None,
            perf_gui: None,
            base_immutable: true,
            compile_config: None,
            validate_change_tracking: None,
            settings_tabs: &mut [],
            ext_panes: &mut [],
            ref_ext_uis: &[],
            edge_styles: &[],
            base_sources: None,
            pane_window_mode: PaneWindowMode::default(),
            collab: None,
            clipboard: None,
        }
    }

    /// Provide the collaborative-session display state so the Graph Config
    /// pane shows the collab row for shared (or shareable) graphs.
    pub fn collab(mut self, collab: &'a crate::collab::CollabUiState) -> Self {
        self.collab = Some(collab);
        self
    }

    /// Provide a clipboard reader for widget paste affordances (e.g. the
    /// join popup's right-click paste). Ctrl+V works through egui's own
    /// event path regardless.
    pub fn clipboard(mut self, clipboard: &'a dyn Fn() -> Option<String>) -> Self {
        self.clipboard = Some(clipboard);
        self
    }

    /// Choose whether the widget draws popped-out panes as `egui::Window`s
    /// (the default) or leaves them to the host as native OS windows.
    pub fn pane_window_mode(mut self, mode: PaneWindowMode) -> Self {
        self.pane_window_mode = mode;
        self
    }

    /// Provide the current compile config so the Graph Config pane shows
    /// the compile toggles. The config is global: it applies to all open
    /// heads, and a change is reported via [`GantzResponse::compile_config`].
    pub fn compile_config(mut self, config: gantz_core::compile::Config) -> Self {
        self.compile_config = Some(config);
        self
    }

    /// Provide the current change-tracking validation state so the Settings >
    /// Global pane shows its toggle. A change is reported via
    /// [`GantzResponse::validate_change_tracking`].
    ///
    /// When not provided, validation defaults on in debug builds (the node
    /// instance cache would otherwise mask a missed `changed` flag) and off
    /// in release.
    pub fn validate_change_tracking(mut self, enabled: bool) -> Self {
        self.validate_change_tracking = Some(enabled);
        self
    }

    /// Provide extension settings subtabs (see
    /// [`SettingsTab`][widget::SettingsTab]). One subtab appears per entry,
    /// and any payloads a tab emits are reported via
    /// [`GantzResponse::responses`].
    pub fn settings_tabs(mut self, tabs: &'a mut [&'a mut dyn widget::SettingsTab]) -> Self {
        self.settings_tabs = tabs;
        self
    }

    /// Provide extension top-level panes (see [`ExtPane`][widget::ExtPane]).
    /// One tray tile appears per entry, and any payloads a pane emits are
    /// reported via [`GantzResponse::responses`] tagged with the focused head.
    pub fn ext_panes(mut self, panes: &'a mut [&'a mut dyn widget::ExtPane]) -> Self {
        self.ext_panes = panes;
        self
    }

    /// Provide domain extensions for the `NamedRef` node inspector (see
    /// [`RefExtUi`][crate::node::RefExtUi]). Each applicable extension's rows
    /// are appended after the ref's own inspector rows.
    pub fn ref_ext_uis(mut self, uis: &'a [&'a dyn crate::node::RefExtUi]) -> Self {
        self.ref_ext_uis = uis;
        self
    }

    /// Provide domain edge stylers for the graph scenes (see
    /// [`EdgeStyle`][widget::EdgeStyle]). Each edge is styled by the first
    /// styler returning `Some`; unclaimed edges keep the default styling.
    pub fn edge_styles(mut self, styles: &'a [&'a dyn widget::EdgeStyle]) -> Self {
        self.edge_styles = styles;
        self
    }

    /// Provide base-source authoring context so the graph config pane shows
    /// a "source" dropdown selecting which base file a graph belongs to. A
    /// change is reported via [`GantzResponse::base_source_changed`].
    pub fn base_sources(mut self, ctx: BaseSourcesCtx<'a>) -> Self {
        self.base_sources = Some(ctx);
        self
    }

    /// Enable the logging window with a basic env logger.
    pub fn logger(mut self, logger: widget::log_view::Logger) -> Self {
        self.log_source = Some(LogSource::Logger(logger));
        self
    }

    /// Enable the logging window for tracking tracing.
    #[cfg(feature = "tracing")]
    pub fn trace_capture(
        mut self,
        trace_capture: widget::trace_view::TraceCapture,
        level: tracing::level_filters::LevelFilter,
    ) -> Self {
        self.log_source = Some(LogSource::TraceCapture(trace_capture, level));
        self
    }

    /// Set the performance capture sources for VM and GUI timing.
    pub fn perf_captures(
        mut self,
        perf_vm: &'a mut widget::PerfCapture,
        perf_gui: &'a mut widget::PerfCapture,
    ) -> Self {
        self.perf_vm = Some(perf_vm);
        self.perf_gui = Some(perf_gui);
        self
    }

    /// Whether base node graphs should be immutable (view-only).
    ///
    /// When `true` (the default), graphs for heads whose branch name
    /// appears in `base_names` are shown in immutable mode - navigation
    /// and selection work, but structural edits are disabled.
    ///
    /// Set to `false` for developer tools like `update-base` that need
    /// to edit base nodes.
    pub fn base_immutable(mut self, base_immutable: bool) -> Self {
        self.base_immutable = base_immutable;
        self
    }

    /// Present the gantz UI.
    ///
    /// The `access` parameter provides access to all open heads and their data.
    /// The `focused_head` is the index of the currently focused head.
    ///
    /// Returns a response containing the (possibly updated) focused head index.
    pub fn show<'s, Access>(
        mut self,
        state: &'s mut GantzState,
        focused_head: usize,
        access: &'s mut Access,
        ui: &'s mut egui::Ui,
    ) -> GantzResponse
    where
        's: 'a,
        Access: HeadAccess,
    {
        // Honour a pending "clear egui memory" request (from Global settings)
        // before loading any persisted UI state this frame.
        if ui
            .ctx()
            .data(|d| d.get_temp::<bool>(clear_egui_memory_id()))
            .unwrap_or(false)
        {
            ui.ctx().memory_mut(|m| m.data.clear());
        }

        // The persisted outer tree. The version suffix invalidates any tree
        // persisted before the latest default-layout change (v4: perf panes
        // side by side at half height), forcing a rebuild via `create_tree`.
        let tree_id = egui::Id::new("gantz-tiles-tree-storage-v4");

        // Retrieve the tree from persistent storage, or load the default.
        let mut tree: egui_tiles::Tree<Pane> =
            load_tree(ui.ctx(), tree_id).unwrap_or_else(create_tree);

        // The set of panes popped out into windows, persisted alongside the tree.
        let mut windowed: Vec<Pane> = load_ron(ui.ctx(), windowed_panes_id()).unwrap_or_default();

        // Ensure every supplied extension pane has a tile.
        let ext_keys: Vec<&str> = self.ext_panes.iter().map(|p| p.key()).collect();
        sync_ext_panes(&mut tree, &ext_keys);

        // Ensure the GUI Debug pane has a tile (trees persisted before it
        // existed).
        sync_singleton_pane(&mut tree, Pane::GuiDebug);

        // Check the `view_toggles` match the pane visibility.
        set_tile_visibility(&mut tree, &state.view_toggles);

        // Simplify the tree, and ensure tabs are where they should be.
        simplify_tree(&mut tree, ui.ctx());

        // Maintain a fixed sidebar width / tray height across window resizes by
        // imposing the stored pixel sizes on the share splits before layout.
        // `available_rect_before_wrap` matches the root rect `Tree::ui` uses.
        let widget_area = ui.available_rect_before_wrap();
        impose_fixed_sizes(&mut tree, state, widget_area);

        // Initialise the response.
        // We'll collect it during traversal of the tree of tiles.
        let mut response = GantzResponse::new(focused_head);

        // The context for traversing the tree of tiles.
        let base_names = self.base_names;
        let mut behaviour = TreeBehaviour {
            gantz: &mut self,
            state: &mut *state,
            access: &mut *access,
            focused_head,
            base_names,
            gantz_response: &mut response,
            windowed: &mut windowed,
        };
        tree.ui(&mut behaviour, ui);

        // Update the response with the final focused head.
        response.focused_head = behaviour.focused_head;

        // Capture the sidebar width / tray height from the laid-out tree (which
        // reflects any manual divider drag) to re-impose next frame.
        capture_fixed_sizes(&tree, state, widget_area);

        // Detect .gantz file drops globally (not per-pane, since pointer
        // position may be unavailable during OS file drags on some platforms).
        response.file_drops = collect_gantz_file_drops(ui.ctx());

        // Apply payloads that only affect the widget's own state, so
        // applications never see them: node palette toggling and resetting
        // the tile layout to its default arrangement.
        for _ in response.responses.take::<OpenNodePalette>() {
            state.node_palette.toggle();
        }
        for _ in response.responses.take::<ResetTilesLayout>() {
            tree = create_tree();
            // Restore the default sidebar width / tray height too.
            state.sidebar_width = default_sidebar_width();
            state.tray_height = default_tray_height();
            // Restore default pane visibility (e.g. the perf panes turn off),
            // but keep the sidebar's open/closed state since the user just
            // acted from within it.
            let sidebar_open = state.view_toggles.sidebar_open;
            state.view_toggles = ViewToggles::default();
            state.view_toggles.sidebar_open = sidebar_open;
        }
        for _ in response.responses.take::<OpenLogs>() {
            state.view_toggles.logs = true;
        }
        // Migrate node-view tiles past this frame's node deletions (collected
        // during traversal, since the live top-level tree wasn't reachable then).
        for (head, reindex) in &response.node_view_reindexes {
            migrate_node_view_paths(&mut tree, head, reindex);
            migrate_windowed_node_views(&mut windowed, head, reindex);
        }
        // "open view": add (or focus) a node-view tile in the top-level tree.
        // The node's head is the payload's head tag.
        for (head, view) in response.responses.take::<OpenNodeView>() {
            let Some(head) = head else { continue };
            // Skip if this view is already popped out into a window.
            let windowed_already = windowed.iter().any(
                |p| matches!(p, Pane::NodeView(np) if np.head == head && np.path == view.path),
            );
            if windowed_already {
                continue;
            }
            add_node_view_pane(&mut tree, head, view.path, view.ty_name);
        }

        // Reconcile the windowed set: a singleton whose toggle was turned back
        // on (e.g. via Settings -> Panes) re-docks, so drop it here. Node views
        // stay windowed until their window is closed.
        windowed
            .retain(|p| matches!(p, Pane::NodeView(_)) || !pane_is_visible(&state.view_toggles, p));

        // Redock / close intents queued by a native host between frames (its
        // OS-window buttons call `redock_windowed_pane` / `close_windowed_pane`).
        let mut redock: Vec<Pane> = drain_pending(ui.ctx(), pending_redock_id());
        let close: Vec<Pane> = drain_pending(ui.ctx(), pending_close_id());

        // In the egui-window backend, draw each windowed pane as a floating
        // `egui::Window`; its title-bar close returns the pane to the tile tree.
        // Under `HostNative` the host draws them as OS windows instead.
        if self.pane_window_mode == PaneWindowMode::EguiWindow {
            for pane in &mut windowed {
                let title = pane_title(&self, &*access, focused_head, pane);
                let mut open = true;
                egui::Window::new(title)
                    .id(egui::Id::new(("gantz-windowed-pane", pane_key(pane))))
                    .open(&mut open)
                    .show(ui.ctx(), |ui| {
                        // Namespace child ids so a windowed pane never collides
                        // with its (briefly still-visible) docked instance.
                        ui.push_id(("gantz-windowed", pane_key(pane)), |ui| {
                            let mut cx = PaneCtx {
                                gantz: &mut self,
                                state: &mut *state,
                                access: &mut *access,
                                focused_head,
                                base_names,
                                response: &mut response,
                            };
                            render_pane(&mut cx, ui, pane);
                        });
                    });
                if !open {
                    redock.push(pane.clone());
                }
            }
        }

        // Apply redocks (return to the tree) and closes (destroy node views;
        // singletons have no destroy, so re-dock them).
        for pane in redock {
            let key = pane_key(&pane);
            windowed.retain(|p| pane_key(p) != key);
            redock_pane(&mut state.view_toggles, &mut tree, pane);
        }
        for pane in close {
            let key = pane_key(&pane);
            windowed.retain(|p| pane_key(p) != key);
            if !matches!(pane, Pane::NodeView(_)) {
                redock_pane(&mut state.view_toggles, &mut tree, pane);
            }
        }

        // Report the final windowed set so a native host can match its OS windows.
        response.windowed_panes = windowed
            .iter()
            .map(|pane| WindowedPane {
                pane: pane.clone(),
                title: pane_title(&self, &*access, focused_head, pane),
            })
            .collect();

        // Persist the tree and the windowed set.
        store_tree(ui.ctx(), tree_id, &tree);
        store_ron(ui.ctx(), windowed_panes_id(), &windowed);

        response
    }

    /// Render a single popped-out pane into `ui` - typically a native host's
    /// OS-window egui context under [`PaneWindowMode::HostNative`].
    ///
    /// Mirrors [`Self::show`]'s per-pane rendering. The returned [`GantzResponse`]
    /// carries this pane's `changed_heads` and payloads; apply it exactly as you
    /// apply `show`'s response.
    pub fn render_windowed_pane<'s, Access>(
        mut self,
        state: &'s mut GantzState,
        focused_head: usize,
        access: &'s mut Access,
        pane: &mut Pane,
        ui: &mut egui::Ui,
    ) -> GantzResponse
    where
        's: 'a,
        Access: HeadAccess,
    {
        let mut response = GantzResponse::new(focused_head);
        let base_names = self.base_names;
        let mut cx = PaneCtx {
            gantz: &mut self,
            state,
            access,
            focused_head,
            base_names,
            response: &mut response,
        };
        render_pane(&mut cx, ui, pane);
        response
    }
}

impl GantzState {
    pub const DEFAULT_DIRECTION: egui::Direction = egui::Direction::TopDown;

    /// Shorthand for initialising graph state, with no intial layout so that on
    /// the first pass, the layout is automatically determined.
    pub fn new() -> Self {
        Self::from_open_heads(Default::default())
    }

    pub fn from_open_heads(open_heads: OpenHeadStates) -> Self {
        Self {
            open_heads,
            node_palette: widget::NodePalette::default(),
            view_toggles: ViewToggles::default(),
            layout_config: LayoutConfig::default(),
            scene_config: SceneConfig::default(),
            keymap: Keymap::default(),
            collab: Default::default(),
            merge_resolutions: Default::default(),
            redo_stacks: HashMap::new(),
            undo_cursors: HashMap::new(),
            sidebar_width: default_sidebar_width(),
            tray_height: default_tray_height(),
            windowed_geometry: HashMap::new(),
        }
    }

    /// Migrate GUI state when a head's identity changes.
    ///
    /// Moves `open_heads` entry from old to new key. When `clear_redo` is
    /// true (new edit commit), removes redo stacks for both keys. Otherwise
    /// migrates the redo stack to the new key.
    pub fn migrate_head(&mut self, old: &gantz_ca::Head, new: &gantz_ca::Head, clear_redo: bool) {
        if let Some(state) = self.open_heads.remove(old) {
            self.open_heads.insert(new.clone(), state);
        }
        migrate_or_clear(&mut self.redo_stacks, old, new, clear_redo);
        migrate_or_clear(&mut self.undo_cursors, old, new, clear_redo);
    }
}

/// Migrate one per-head map entry across a head-identity change: cleared for
/// both keys when `clear` (a new edit invalidates it), otherwise moved to
/// the new key.
fn migrate_or_clear<V>(
    map: &mut HashMap<gantz_ca::Head, V>,
    old: &gantz_ca::Head,
    new: &gantz_ca::Head,
    clear: bool,
) {
    if clear {
        map.remove(old);
        map.remove(new);
    } else if let Some(v) = map.remove(old) {
        map.insert(new.clone(), v);
    }
}

impl<'a, 's, Access> egui_tiles::Behavior<Pane> for TreeBehaviour<'a, 's, Access>
where
    Access: HeadAccess,
{
    fn tab_title_for_pane(&mut self, pane: &Pane) -> egui::WidgetText {
        pane_title(self.gantz, self.access, self.focused_head, pane).into()
    }

    fn on_tab_button(
        &mut self,
        tiles: &mut egui_tiles::Tiles<Pane>,
        tile_id: egui_tiles::TileId,
        button_response: egui::Response,
    ) -> egui::Response {
        // Right-click a tab for pane actions: hide (hideable panes) and/or pop
        // out into a window (any pane but the graph scene).
        let pane = match tiles.get(tile_id) {
            Some(egui_tiles::Tile::Pane(pane))
                if pane_is_hideable(pane) || pane_is_poppable(pane) =>
            {
                pane.clone()
            }
            _ => return button_response,
        };
        button_response.context_menu(|ui| {
            if pane_is_hideable(&pane) && ui.button("hide").clicked() {
                set_pane_visible(&mut self.state.view_toggles, &pane, false);
                ui.close();
            }
            if pane_is_poppable(&pane) && ui.button("pop out to window").clicked() {
                detach_pane(
                    &mut self.state.view_toggles,
                    self.windowed,
                    tiles,
                    tile_id,
                    &pane,
                );
                ui.close();
            }
        });
        button_response
    }

    fn is_tab_closable(
        &self,
        tiles: &egui_tiles::Tiles<Pane>,
        tile_id: egui_tiles::TileId,
    ) -> bool {
        // The tray panes and detached node views get a close button; the rest
        // are toggled via the Panes settings or the tab right-click menu.
        matches!(
            tiles.get_pane(&tile_id),
            Some(Pane::Logs | Pane::Steel | Pane::NodeView(_))
        )
    }

    fn on_tab_close(
        &mut self,
        tiles: &mut egui_tiles::Tiles<Pane>,
        tile_id: egui_tiles::TileId,
    ) -> bool {
        match tiles.get_pane(&tile_id) {
            // Node views are user-created tiles: closing removes them entirely.
            Some(Pane::NodeView(_)) => true,
            // Hide other panes via their toggle (so they can be reopened) rather
            // than letting egui_tiles remove the tile from the tree.
            Some(pane) => {
                let pane = pane.clone();
                set_pane_visible(&mut self.state.view_toggles, &pane, false);
                false
            }
            None => false,
        }
    }

    fn tab_ui(
        &mut self,
        tiles: &mut egui_tiles::Tiles<Pane>,
        ui: &mut egui::Ui,
        id: egui::Id,
        tile_id: egui_tiles::TileId,
        state: &egui_tiles::TabState,
    ) -> egui::Response {
        // Render with the shared `Tab` widget so the sidebar/tray tabs (and
        // their small close button) match the graph tabs.
        let title = self.tab_title_for_tile(tiles, tile_id);
        let res = widget::Tab::new(title, id)
            .active(state.active)
            .closable(state.closable)
            .show(ui);
        if res.close.is_some_and(|r| r.clicked()) && self.on_tab_close(tiles, tile_id) {
            tiles.remove(tile_id);
        }
        // Preserve the right-click-to-hide menu.
        self.on_tab_button(tiles, tile_id, res.tab)
    }

    fn tab_bar_color(&self, visuals: &egui::Visuals) -> egui::Color32 {
        // This matches the `CentralPanel` fill so that the color looks
        // continuous.
        visuals.panel_fill
    }

    fn resize_stroke(
        &self,
        style: &egui::Style,
        _resize_state: egui_tiles::ResizeState,
    ) -> egui::Stroke {
        let w = 2.0;
        egui::Stroke::new(w, style.visuals.extreme_bg_color)
    }

    fn tab_outline_stroke(
        &self,
        _visuals: &egui::Visuals,
        _tiles: &egui_tiles::Tiles<Pane>,
        _tile_id: egui_tiles::TileId,
        _state: &egui_tiles::TabState,
    ) -> egui::Stroke {
        egui::Stroke::NONE
    }

    fn simplification_options(&self) -> egui_tiles::SimplificationOptions {
        // We will manually simplify before calling `tree.ui`. See `simplify_tree`.
        egui_tiles::SimplificationOptions::OFF
    }

    fn pane_ui(
        &mut self,
        ui: &mut egui::Ui,
        _tile_id: egui_tiles::TileId,
        pane: &mut Pane,
    ) -> egui_tiles::UiResponse {
        let mut cx = PaneCtx {
            gantz: &mut *self.gantz,
            state: &mut *self.state,
            access: &mut *self.access,
            focused_head: self.focused_head,
            base_names: self.base_names,
            response: &mut *self.gantz_response,
        };
        render_pane(&mut cx, ui, pane);
        // Propagate a focus change made while rendering (the graph scene changes
        // focus on graph-tab clicks).
        self.focused_head = cx.focused_head;
        egui_tiles::UiResponse::None
    }
}

/// Render a single pane into `ui`.
///
/// Shared by the tile tree ([`TreeBehaviour::pane_ui`]), floating `egui::Window`s
/// (the web / fallback backend), and a native host's OS windows - so a pane
/// looks and behaves identically wherever it is shown.
fn render_pane<Access>(cx: &mut PaneCtx<'_, '_, Access>, ui: &mut egui::Ui, pane: &mut Pane)
where
    Access: HeadAccess,
{
    let PaneCtx {
        gantz,
        state,
        access,
        focused_head,
        base_names,
        response: gantz_response,
    } = cx;
    match pane {
        Pane::Ext(key) => {
            let focused = access.heads().get(*focused_head).cloned();
            // The focused head's selection, as sorted root-level node ids
            // (mirroring the Steel pane's span-highlight input).
            let mut selection: Vec<node::Id> = focused
                .as_ref()
                .and_then(|h| state.open_heads.get(h))
                .map(|hs| {
                    hs.scene
                        .interaction
                        .selection
                        .nodes
                        .iter()
                        .map(|n| n.index())
                        .collect()
                })
                .unwrap_or_default();
            selection.sort_unstable();
            match gantz.ext_panes.iter_mut().find(|p| p.key() == *key) {
                Some(p) => {
                    let cx = widget::ExtPaneCtx {
                        focused: focused.as_ref(),
                        selection: &selection,
                    };
                    let res = pane_ui(ui, |ui| p.ui(cx, ui));
                    let mut ext_responses = res.inner;
                    gantz_response
                        .responses
                        .extend(focused.as_ref(), ext_responses.drain().map(|(_, d)| d));
                }
                None => {
                    ui.centered_and_justified(|ui| {
                        ui.weak(format!("'{key}' pane unavailable (no provider)"));
                    });
                }
            }
        }
        Pane::GraphConfig => match access.heads().get(*focused_head).cloned() {
            Some(head) => {
                let merge_resolutions = &mut state.merge_resolutions;
                let head_state = state.open_heads.entry(head.clone()).or_default();
                let names = crate::reg::names(gantz.env.registry);
                let is_base = match &head {
                    gantz_ca::Head::Branch(name) => base_names.contains_key(name),
                    _ => false,
                };
                let immutable = head_immutable(&head, gantz.base_immutable, base_names);

                // Collect demo-* names for the dropdown.
                let demo_names: Vec<String> = names
                    .iter()
                    .filter(|(n, _)| widget::graph_select::is_demo(n))
                    .map(|(n, _)| n.to_string())
                    .collect();
                let demo_names_vec: Vec<&str> = demo_names.iter().map(|s| s.as_str()).collect();

                // Look up the current demo association for this head.
                let current_demo = match &head {
                    gantz_ca::Head::Branch(name) => gantz.env.demo_graph(&name.to_string()),
                    _ => None,
                };

                // The graph's current description (named graphs only).
                let current_description = match &head {
                    gantz_ca::Head::Branch(name) => {
                        crate::section::description(gantz.env.registry, name)
                    }
                    _ => None,
                };

                // The head's session display, when a collab layer is wired.
                let session = gantz.collab.map(|c| match &head {
                    gantz_ca::Head::Branch(name) => c.sessions.get(name),
                    _ => None,
                });

                let res = pane_ui(ui, |ui| {
                    let mut config = widget::GraphConfig::new(&head, head_state, &names)
                        .is_base(is_base)
                        .immutable(immutable)
                        .demo_names(&demo_names_vec)
                        .current_demo(current_demo.as_deref())
                        .current_description(current_description.as_deref())
                        .merge_env(gantz.env, merge_resolutions);
                    // The base source dropdown, when authoring context was
                    // supplied (see `Gantz::base_sources`).
                    if let (Some(ctx), gantz_ca::Head::Branch(name)) = (&gantz.base_sources, &head)
                    {
                        let current = ctx
                            .name_sources
                            .get(&name.to_string())
                            .copied()
                            .unwrap_or(ctx.default_source);
                        config = config.base_sources(ctx.sources, Some(current));
                    }
                    if let Some(session) = session {
                        config = config.collab(session);
                    }
                    config.show(ui)
                });
                if res.inner.new_branch.is_some() {
                    gantz_response.new_branch = res.inner.new_branch;
                }
                if let Some(merge) = res.inner.merge {
                    gantz_response.responses.push(Some(head.clone()), merge);
                }
                if res.inner.share {
                    gantz_response
                        .responses
                        .push(Some(head.clone()), crate::ShareHead { public: true });
                }
                if res.inner.stop_sharing {
                    gantz_response
                        .responses
                        .push(Some(head.clone()), crate::StopSharing);
                }
                if let Some(demo_val) = res.inner.demo_changed {
                    gantz_response.demo_changed = Some((head.clone(), demo_val));
                }
                if let Some(description) = res.inner.description_changed {
                    gantz_response.description_changed = Some((head.clone(), description));
                }
                if res.inner.reset_base_graph {
                    gantz_response.reset_base_graph = Some(head.clone());
                }
                if let Some(source) = res.inner.base_source_changed {
                    gantz_response.base_source_changed = Some((head.clone(), source));
                }
                if res.inner.export {
                    gantz_response.responses.push(Some(head), ExportHead);
                }
            }
            None => {
                pane_ui(ui, |ui| {
                    ui.label("No graph focused");
                });
            }
        },
        Pane::GraphScene => {
            paint_gantz_file_hover_overlay(ui);

            // We'll use this to position the floating sidebar toggle.
            let rect = ui.available_rect_before_wrap();

            // Extension-pane toggle entries for the graph-area context menu.
            let ext_panes = ext_pane_entries(gantz);

            // Retrieve the inner graph tree from persistent storage, or create empty.
            let graph_tree_id = egui::Id::new(GRAPH_TREE_ID);
            let mut graph_tree: egui_tiles::Tree<GraphPane> =
                load_tree(ui.ctx(), graph_tree_id).unwrap_or_else(create_empty_graph_tree);

            // Sync the graph tree panes with the heads list.
            sync_graph_panes(&mut graph_tree, access.heads());

            // Activate the tab corresponding to the focused head.
            if let Some(fh) = access.heads().get(*focused_head) {
                let fh = fh.clone();
                graph_tree.make_active(|_, tile| match tile {
                    egui_tiles::Tile::Pane(GraphPane(head)) => *head == fh,
                    _ => false,
                });
            }

            // Render the inner tree.
            let mut graph_behaviour = GraphTreeBehaviour {
                env: gantz.env,
                codec: gantz.codec,
                access: *access,
                state,
                focused_head,
                closed_heads: &mut gantz_response.closed_heads,
                new_branch: &mut gantz_response.new_branch,
                responses: &mut gantz_response.responses,
                changed_heads: &mut gantz_response.changed_heads,
                reindexes: &mut gantz_response.node_view_reindexes,
                base_names,
                base_immutable: gantz.base_immutable,
                // With the instance cache, an unmarked weight mutation
                // persists in the cached instance instead of visibly
                // reverting next pass, so debug builds default the validator
                // on to keep the contract violation loud.
                validate_change_tracking: gantz
                    .validate_change_tracking
                    .unwrap_or(cfg!(debug_assertions)),
                ext_panes: &ext_panes,
                edge_styles: gantz.edge_styles,
                collab: gantz.collab,
            };
            graph_tree.ui(&mut graph_behaviour, ui);

            // Persist the inner tree.
            store_tree(ui.ctx(), graph_tree_id, &graph_tree);

            // Show the node palette once (not per-pane), operating on the focused head.
            if let Some(fh) = access.heads().get(*focused_head).cloned() {
                let focused_immutable = head_immutable(&fh, gantz.base_immutable, base_names);

                let head_state = state.open_heads.entry(fh.clone()).or_default();

                // Command keyboard shortcuts, sourced from the keymap.
                if !ui.ctx().egui_wants_keyboard_input() {
                    let keymap = &state.keymap;
                    // Copy is always allowed.
                    if keymap.consume(ui, Action::Copy) {
                        let nodes = head_state.scene.interaction.selection.nodes.clone();
                        gantz_response
                            .responses
                            .push(Some(fh.clone()), CopyNodes(nodes));
                    }
                    // New graph.
                    if keymap.consume(ui, Action::NewGraph) {
                        let gs = gantz_response
                            .graph_select
                            .get_or_insert_with(Default::default);
                        gs.new_graph = true;
                    }
                    // Paste, undo, redo are gated by immutable.
                    if !focused_immutable {
                        // Detect paste: an `Event::Paste` (eframe/web) or the
                        // Paste shortcut (bevy_egui desktop sends `Event::Text`
                        // instead of `Event::Paste`).
                        let paste_text = ui.input(|i| {
                            i.events.iter().find_map(|e| match e {
                                egui::Event::Paste(s) => Some(s.clone()),
                                _ => None,
                            })
                        });
                        if paste_text.is_some() || keymap.consume(ui, Action::Paste) {
                            let paste = Paste {
                                text: paste_text,
                                pos: crate::PastePos::Offset(egui::vec2(20.0, 20.0)),
                            };
                            gantz_response.responses.push(Some(fh.clone()), paste);
                        }
                        // Redo before Undo: `consume_shortcut` matches
                        // modifiers logically, so `Cmd+Z` also matches a
                        // `Cmd+Shift+Z` event - check (and consume) the more
                        // specific binding first.
                        if keymap.consume(ui, Action::Redo) {
                            gantz_response.responses.push(Some(fh.clone()), Redo);
                        }
                        if keymap.consume(ui, Action::Undo) {
                            gantz_response.responses.push(Some(fh.clone()), Undo);
                        }
                        // Cut: copy the selection, then remove it.
                        if keymap.consume(ui, Action::Cut) {
                            let nodes = head_state.scene.interaction.selection.nodes.clone();
                            gantz_response
                                .responses
                                .push(Some(fh.clone()), CutNodes(nodes));
                        }
                        // Duplicate the selection in place.
                        if keymap.consume(ui, Action::Duplicate) {
                            let nodes = head_state.scene.interaction.selection.nodes.clone();
                            gantz_response
                                .responses
                                .push(Some(fh.clone()), DuplicateNodes(nodes));
                        }
                    }
                }

                // Skip node palette when immutable.
                if !focused_immutable {
                    let editing_name = match &fh {
                        gantz_ca::Head::Branch(name) => Some(name.to_string()),
                        _ => None,
                    };
                    let editing = editing_name.as_deref();
                    // The pointer position over the focused head's scene
                    // (graph coords) recorded this frame; new nodes are placed
                    // here. `Copy`, so no borrow is held across the call.
                    let pointer_pos = head_state.scene.interaction.last_pointer_pos;
                    let created = node_palette(
                        gantz.env,
                        editing,
                        &mut state.node_palette,
                        &state.keymap,
                        ui,
                    );
                    match created {
                        Some(PaletteChoice::Node(mut create)) => {
                            create.pos = pointer_pos;
                            gantz_response.responses.push(Some(fh), create);
                        }
                        Some(PaletteChoice::NestedGraph(mut create)) => {
                            create.pos = pointer_pos;
                            gantz_response.responses.push(Some(fh), create);
                        }
                        None => {}
                    }
                }
            }

            // Floating hamburger over the bottom-left corner of the graph
            // scene that opens/closes the sidebar (left column).
            let space = ui.style().interaction.interact_radius * 3.0;
            let anchor = rect.left_bottom() + egui::vec2(space, -space);
            sidebar_toggle(ui.ctx(), anchor, &mut state.view_toggles.sidebar_open);
        }
        Pane::Graphs => {
            // Store the pane rect for file drop targeting.
            ui.ctx().memory_mut(|m| {
                m.data
                    .insert_temp(egui::Id::new(GRAPHS_PANE_RECT_ID), ui.max_rect())
            });
            paint_gantz_file_hover_overlay(ui);

            let heads = access.heads();
            let mut res = graph_select(
                gantz.env,
                heads,
                *focused_head,
                *base_names,
                gantz.collab,
                gantz.clipboard,
                ui,
            );

            if res.inner.export_all {
                gantz_response.responses.push(None, ExportAllNamed);
            }
            if let Some(ticket) = res.inner.join_ticket.take() {
                gantz_response
                    .responses
                    .push(None, crate::JoinSession { ticket });
            }
            match &mut gantz_response.graph_select {
                Some(gs) => *gs |= res.inner,
                None => gantz_response.graph_select = Some(res.inner),
            }
        }
        Pane::GuiPerf => {
            if let Some(ref mut capture) = gantz.perf_gui {
                perf_view("GUI Perf", capture, ui);
            }
        }
        Pane::History => {
            let heads = access.heads();
            let res = history_view(gantz.env, heads, *focused_head, ui);
            match &mut gantz_response.graph_select {
                Some(gs) => *gs |= res.inner,
                None => gantz_response.graph_select = Some(res.inner),
            }
        }
        Pane::Logs => match &gantz.log_source {
            None => (),
            Some(LogSource::Logger(logger)) => {
                // Resolve labels for entries emitted by nodes of the
                // focused head (the target encodes the node's path).
                let focused = access.heads().get(*focused_head).cloned();
                let mut labels: HashMap<Vec<node::Id>, String> = HashMap::new();
                if let Some(fh) = &focused {
                    let paths: BTreeSet<Vec<node::Id>> = logger
                        .get_entries()
                        .iter()
                        .filter_map(|e| gantz_std::log::parse_log_target(&e.target))
                        .collect();
                    if !paths.is_empty() {
                        let env = gantz.env;
                        let codec = gantz.codec;
                        access.with_head_mut(fh, |data| {
                            for path in paths {
                                // Log targets are state paths; only root-level
                                // (single-segment) ones name a node in this graph.
                                let [ix] = path[..] else { continue };
                                let Some(weight) =
                                    data.graph.node_weight(graph_scene::NodeIndex::new(ix))
                                else {
                                    continue;
                                };
                                let Ok(inst) = codec.reify_ui(weight) else {
                                    continue;
                                };
                                labels.insert(path, inst.node.name(env).to_string());
                            }
                        });
                    }
                }
                let res = log_view(logger, &labels, ui);
                // Clicking an entry selects its node. Only root-level nodes
                // live in the focused head; entries from a nested graph
                // (deeper path) are skipped until name-based navigation lands.
                if let (Some(path), Some(fh)) = (res.inner.clicked_path, focused) {
                    if let [node_id] = path[..] {
                        let head_state = state.open_heads.entry(fh.clone()).or_default();
                        let selection = &mut head_state.scene.interaction.selection;
                        selection.clear();
                        selection.nodes.insert(graph_scene::NodeIndex::new(node_id));
                    }
                }
            }
            #[cfg(feature = "tracing")]
            Some(LogSource::TraceCapture(trace_capture, level)) => {
                trace_view(trace_capture, *level, ui);
            }
        },
        Pane::NodeInspector => {
            // Use the focused head for the node inspector.
            if let Some(fh) = access.heads().get(*focused_head).cloned() {
                let immutable = head_immutable(&fh, gantz.base_immutable, base_names);
                let head_state = state.open_heads.entry(fh.clone()).or_default();
                let ref_ext_uis = gantz.ref_ext_uis;
                let codec = gantz.codec;
                let result = access.with_head_mut(&fh, |data| {
                    node_inspector(
                        gantz.env,
                        codec,
                        data.graph,
                        data.instances,
                        data.vm,
                        head_state,
                        &fh,
                        immutable,
                        ref_ext_uis,
                        ui,
                    )
                    .inner
                });
                if let Some((changed, payloads)) = result {
                    if changed {
                        gantz_response.changed_heads.push(fh.clone());
                    }
                    gantz_response.responses.extend(Some(&fh), payloads);
                }
            }
        }
        Pane::NodeView(view) => {
            // A detached node view: render the node's `view_ui` against its
            // head's live graph + VM (a mirror sharing state with the
            // in-graph node). A `CentralPanel` gives it the same background
            // as the other panes; no-margin views (e.g. plot) drop the pane
            // margin so they fill edge-to-edge. A placeholder shows when the
            // head is closed.
            let head = view.head.clone();
            let path = view.path.clone();
            let codec = gantz.codec;
            let no_margin = access
                .with_head_mut(&head, |data| {
                    let &[ix] = path.as_slice() else {
                        return false;
                    };
                    data.graph
                        .node_weight(graph_scene::NodeIndex::new(ix))
                        .is_some_and(|w| match data.instances.peek(ix, w) {
                            Some(inst) => inst.node.view_no_margin(),
                            None => codec
                                .reify_ui(w)
                                .is_ok_and(|inst| inst.node.view_no_margin()),
                        })
                })
                .unwrap_or(false);
            let mut frame = egui::Frame::central_panel(ui.style());
            if no_margin {
                frame.inner_margin = egui::Margin::ZERO;
            }
            egui::CentralPanel::default()
                .frame(frame)
                .show_inside(ui, |ui| {
                    if !access.heads().iter().any(|h| h == &head) {
                        ui.centered_and_justified(|ui| {
                            ui.weak("node's graph is not open");
                        });
                        return;
                    }
                    let env = gantz.env;
                    // VM-state writes recorded by the node's `NodeCtx`.
                    let mut writes = Vec::new();
                    // Scope child widget ids by (head, path) so views never share
                    // ids with each other or the in-graph node.
                    let result = ui
                        .push_id((&head, &path), |ui| {
                            access.with_head_mut(&head, |data| {
                                let &[n_ix] = path.as_slice() else {
                                    return None;
                                };
                                let (inlets, outlets) = crate::inlet_outlet_ids(env, data.graph);
                                let n_id = graph_scene::NodeIndex::new(n_ix);
                                let weight = data.graph.node_weight(n_id)?;
                                // Take the one node's cached instance (see
                                // `graph_scene::nodes` - panes render
                                // sequentially, so each take/put pair
                                // completes within its site); erase back iff
                                // changed, updating the witness.
                                let mut entry = data.instances.take(codec, n_ix, weight).ok()?;
                                let ctx = NodeCtx::new(
                                    env,
                                    &path,
                                    &inlets,
                                    &outlets,
                                    &[],
                                    data.vm,
                                    &mut writes,
                                );
                                let r = entry.inst.node.view_ui(ctx, ui);
                                if r.changed {
                                    match entry.inst.erase() {
                                        Ok(node_data) => {
                                            entry.src = node_data.clone();
                                            data.graph[n_id] = node_data;
                                            data.instances.put(n_ix, entry);
                                        }
                                        Err(e) => log::error!(
                                            "node view {n_ix}: failed to erase edited node, \
                                             edit dropped: {e}"
                                        ),
                                    }
                                } else {
                                    data.instances.put(n_ix, entry);
                                }
                                Some((r.changed, r.payloads))
                            })
                        })
                        .inner;
                    match result {
                        Some(Some((changed, payloads))) => {
                            if changed {
                                gantz_response.changed_heads.push(head.clone());
                            }
                            gantz_response.responses.extend(Some(&head), payloads);
                            gantz_response
                                .responses
                                .extend(Some(&head), crate::action::state_written(&mut writes));
                        }
                        _ => {
                            // Head open but node missing at `path` (e.g. removed
                            // this frame, before migration drops the view).
                            ui.centered_and_justified(|ui| {
                                ui.weak("node not found");
                            });
                        }
                    }
                });
        }
        Pane::Steel => {
            // Use the focused head's compiled module, highlighting the
            // selected nodes' emitted fns/call sites and any diagnostic
            // spans. A failed compile's error renders above the code.
            let focused = access.heads().get(*focused_head).cloned();
            let compile_error = focused.as_ref().and_then(|h| access.compile_error(h));
            let compiled_steel = focused
                .as_ref()
                .and_then(|h| access.module(h))
                .map(|m| m.src.as_str())
                .unwrap_or("");
            let mut highlights: Vec<std::ops::Range<usize>> = vec![];
            let mut scroll_to = None;
            let mut errors: Vec<std::ops::Range<usize>> = vec![];
            if let Some(h) = &focused {
                errors = access
                    .diagnostics(h)
                    .iter()
                    .filter_map(|d| d.span.clone())
                    .collect();
                let head_state = state.open_heads.get(h);
                if let (Some(module), Some(head_state)) = (access.module(h), head_state) {
                    let mut selected: Vec<node::Id> = head_state
                        .scene
                        .interaction
                        .selection
                        .nodes
                        .iter()
                        .map(|n| n.index())
                        .collect();
                    selected.sort_unstable();
                    for &ix in &selected {
                        // A node at this (root) level has the single-element
                        // path `[ix]` in the compiled module's source map.
                        let spans = module.map.node_spans(&[ix]);
                        highlights.extend(spans.defs);
                        highlights.extend(spans.refs);
                    }
                    // Scroll to the first highlighted span when the
                    // selection changes.
                    let state_id = egui::Id::new("steel_view_selection");
                    let current = egui::Id::new(("steel_sel", h, &selected));
                    let prev: Option<egui::Id> = ui.ctx().data(|d| d.get_temp(state_id));
                    if prev != Some(current) {
                        ui.ctx().data_mut(|d| d.insert_temp(state_id, current));
                        scroll_to = highlights.iter().map(|r| r.start).min();
                    }
                }
            }
            steel_view(
                compiled_steel,
                compile_error,
                &highlights,
                &errors,
                scroll_to,
                ui,
            );
        }
        Pane::GuiDebug => {
            // Mode selector: the focused graph's own marker tree (default),
            // or the scratch editor for vocabulary experiments.
            let scratch_id = egui::Id::new("gantz-gui-debug-scratch-mode");
            let mut scratch: bool = ui
                .ctx()
                .data_mut(|d| d.get_persisted(scratch_id))
                .unwrap_or(false);
            egui::Panel::top(egui::Id::new("gui-debug-mode-panel")).show_inside(ui, |ui| {
                ui.horizontal(|ui| {
                    if ui
                        .selectable_label(!scratch, "marker")
                        .on_hover_text("the focused graph's own gui marker tree")
                        .clicked()
                    {
                        scratch = false;
                    }
                    if ui
                        .selectable_label(scratch, "scratch")
                        .on_hover_text("an editable tree literal")
                        .clicked()
                    {
                        scratch = true;
                    }
                });
            });
            ui.ctx()
                .data_mut(|d| d.insert_persisted(scratch_id, scratch));

            if scratch {
                // The editor (plus its eval error and decode warnings) on the
                // left, the interpreted tree on the right, rendered against
                // the focused head's live VM: bindings resolve into its node
                // state and pushes fire its entrypoints.
                let cache = egui::Panel::left(egui::Id::new("gui-debug-editor-panel"))
                    .resizable(true)
                    .show_inside(ui, |ui| {
                        egui::ScrollArea::vertical()
                            .show(ui, |ui| {
                                let id = egui::Id::new("gantz-gui-debug-editor");
                                let out = super::gui_debug::tree_editor(id, ui);
                                if let Some(err) = &out.cache.eval_err {
                                    ui.colored_label(ui.visuals().error_fg_color, err);
                                }
                                if let Some(decoded) = &out.cache.decoded {
                                    gui_debug_warnings(decoded, ui);
                                }
                                out.cache
                            })
                            .inner
                    })
                    .inner;
                egui::CentralPanel::default().show_inside(ui, |ui| {
                    let Some(decoded) = &cache.decoded else {
                        ui.weak("nothing to render");
                        return;
                    };
                    let Some(head) = access.heads().get(*focused_head).cloned() else {
                        ui.weak("no focused graph");
                        return;
                    };
                    let env = gantz.env;
                    let codec = gantz.codec;
                    egui::ScrollArea::both().show(ui, |ui| {
                        let payloads = access.with_head_mut(&head, |data| {
                            gui_debug_tree(
                                env, codec, &head, data.graph, data.vm, decoded, "scratch", ui,
                            )
                        });
                        if let Some(payloads) = payloads {
                            gantz_response.responses.extend(Some(&head), payloads);
                        }
                    });
                });
            } else {
                // Marker mode: the raw stored tree of one of the focused
                // graph's own gui markers as text on the left, the decoded
                // tree rendered live on the right. Bindings are correct by
                // construction here - the tree IS this graph's GUI.
                let Some(head) = access.heads().get(*focused_head).cloned() else {
                    ui.weak("no focused graph");
                    return;
                };
                let env = gantz.env;
                let codec = gantz.codec;
                let payloads = access.with_head_mut(&head, |data| {
                    let markers = crate::node::gui::markers(data.graph);
                    let decoded = egui::Panel::left(egui::Id::new("gui-debug-marker-panel"))
                        .resizable(true)
                        .show_inside(ui, |ui| {
                            egui::ScrollArea::vertical()
                                .show(ui, |ui| {
                                    if markers.is_empty() {
                                        ui.weak("add a `gui` node to this graph to define its GUI");
                                        return None;
                                    }
                                    // Role picker over the roles that exist,
                                    // remembered per head.
                                    let role_id = egui::Id::new(("gantz-gui-debug-role", &head));
                                    let role = ui
                                        .ctx()
                                        .data(|d| d.get_temp::<crate::node::GuiRole>(role_id))
                                        .filter(|r| markers.iter().any(|(_, g)| g.role == *r))
                                        .unwrap_or_else(|| {
                                            markers
                                                .iter()
                                                .map(|&(_, g)| g.role)
                                                .find(|&r| r == crate::node::GuiRole::Body)
                                                .unwrap_or(markers[0].1.role)
                                        });
                                    let mut role = role;
                                    ui.horizontal(|ui| {
                                        for r in crate::node::GuiRole::ALL {
                                            if markers.iter().any(|(_, g)| g.role == r)
                                                && ui
                                                    .selectable_label(role == r, r.as_str())
                                                    .clicked()
                                            {
                                                role = r;
                                            }
                                        }
                                    });
                                    ui.ctx().data_mut(|d| d.insert_temp(role_id, role));

                                    // First marker of the role, in index order.
                                    let &(ix, _) = markers
                                        .iter()
                                        .find(|(_, g)| g.role == role)
                                        .expect("role picked from existing markers");
                                    let val = node::state::extract_value(data.vm, &[ix])
                                        .ok()
                                        .flatten()
                                        .filter(|v| !matches!(v, steel::SteelVal::Void));
                                    let Some(val) = val else {
                                        ui.weak("the marker has no stored tree yet");
                                        return None;
                                    };
                                    ui.separator();
                                    ui.add(
                                        egui::Label::new(
                                            egui::RichText::new(format!("{val}")).monospace(),
                                        )
                                        .selectable(true),
                                    );
                                    let decoded = gantz_ui::codec::steel::decode(
                                        &val,
                                        &gantz_ui::Limits::default(),
                                    );
                                    gui_debug_warnings(&decoded, ui);
                                    Some(decoded)
                                })
                                .inner
                        })
                        .inner;
                    let mut payloads = Vec::new();
                    egui::CentralPanel::default().show_inside(ui, |ui| {
                        let Some(decoded) = &decoded else {
                            ui.weak("nothing to render");
                            return;
                        };
                        egui::ScrollArea::both().show(ui, |ui| {
                            payloads = gui_debug_tree(
                                env, codec, &head, data.graph, data.vm, decoded, "marker", ui,
                            );
                        });
                    });
                    payloads
                });
                if let Some(payloads) = payloads {
                    gantz_response.responses.extend(Some(&head), payloads);
                }
            }
        }
        Pane::VmPerf => {
            if let Some(ref mut capture) = gantz.perf_vm {
                perf_view("VM Perf", capture, ui);
            }
        }
        Pane::Settings => {
            let compile_config = gantz.compile_config;
            let validate_change_tracking = gantz.validate_change_tracking;
            let ext_panes = ext_pane_entries(gantz);
            let ext_tabs = &mut *gantz.settings_tabs;
            let res = pane_ui(ui, |ui| {
                widget::settings(
                    &mut state.view_toggles,
                    compile_config,
                    validate_change_tracking,
                    &mut state.layout_config,
                    &mut state.scene_config,
                    &mut state.keymap,
                    ext_tabs,
                    &ext_panes,
                    ui,
                )
            });
            if let Some(cfg) = res.inner.compile_config {
                gantz_response.compile_config = Some(cfg);
            }
            if let Some(v) = res.inner.validate_change_tracking {
                gantz_response.validate_change_tracking = Some(v);
            }
            if res.inner.reset_all_demos {
                gantz_response.reset_all_demos = true;
            }
            if res.inner.reset_layout {
                gantz_response.responses.push(None, ResetTilesLayout);
            }
            let mut ext_responses = res.inner.responses;
            gantz_response
                .responses
                .extend(None, ext_responses.drain().map(|(_, d)| d));
        }
    }
}

/// The context passed to the inner graph `egui_tiles::Tree` widget.
struct GraphTreeBehaviour<'a, Access>
where
    Access: HeadAccess,
{
    env: &'a Env<'a>,
    codec: &'a NodeCodec,
    access: &'a mut Access,
    state: &'a mut GantzState,
    focused_head: &'a mut usize,
    /// Heads closed via the tab close button.
    closed_heads: &'a mut Vec<gantz_ca::Head>,
    /// New branch created from tab double-click: (original_head, new_branch_name).
    new_branch: &'a mut Option<(gantz_ca::Head, String)>,
    /// Dynamic payloads emitted from within the graph scenes.
    responses: &'a mut Responses,
    /// Heads whose graph had a CA-affecting edit this frame.
    changed_heads: &'a mut Vec<gantz_ca::Head>,
    /// Per-head node index remappings from this frame's deletions, applied to
    /// the top-level tree's node views after layout (see `migrate_node_view_paths`).
    reindexes: &'a mut Vec<(gantz_ca::Head, crate::ops::Reindex)>,
    base_names: &'a crate::reg::Names,
    base_immutable: bool,
    /// Whether the per-node change-tracking validator is enabled (see
    /// [`GraphScene::validate_change_tracking`]).
    validate_change_tracking: bool,
    /// Extension-pane toggle entries for the scene's "Panes" context submenu
    /// (see [`ext_pane_entries`]).
    ext_panes: &'a [widget::ExtPaneEntry],
    /// Domain edge stylers for the graph scenes (see [`widget::EdgeStyle`]).
    edge_styles: &'a [&'a dyn widget::EdgeStyle],
    /// Collaborative-session display state, when a collab layer is wired:
    /// drives the per-tab session dot and the connecting/error overlay.
    collab: Option<&'a crate::collab::CollabUiState>,
}

impl<'a, Access> egui_tiles::Behavior<GraphPane> for GraphTreeBehaviour<'a, Access>
where
    Access: HeadAccess,
{
    fn tab_title_for_pane(&mut self, pane: &GraphPane) -> egui::WidgetText {
        let GraphPane(head) = pane;
        head.to_string().into()
    }

    fn tab_bar_color(&self, visuals: &egui::Visuals) -> egui::Color32 {
        visuals.panel_fill
    }

    fn resize_stroke(
        &self,
        style: &egui::Style,
        _resize_state: egui_tiles::ResizeState,
    ) -> egui::Stroke {
        let w = 2.0;
        egui::Stroke::new(w, style.visuals.extreme_bg_color)
    }

    fn tab_outline_stroke(
        &self,
        _visuals: &egui::Visuals,
        _tiles: &egui_tiles::Tiles<GraphPane>,
        _tile_id: egui_tiles::TileId,
        _state: &egui_tiles::TabState,
    ) -> egui::Stroke {
        egui::Stroke::NONE
    }

    fn simplification_options(&self) -> egui_tiles::SimplificationOptions {
        egui_tiles::SimplificationOptions {
            all_panes_must_have_tabs: true,
            ..Default::default()
        }
    }

    fn is_tab_closable(
        &self,
        _tiles: &egui_tiles::Tiles<GraphPane>,
        _tile_id: egui_tiles::TileId,
    ) -> bool {
        // Allow closing tabs if there's more than one head open.
        self.access.heads().len() > 1
    }

    fn on_tab_close(
        &mut self,
        tiles: &mut egui_tiles::Tiles<GraphPane>,
        tile_id: egui_tiles::TileId,
    ) -> bool {
        // Get the head from the pane being closed.
        if let Some(GraphPane(head)) = tiles.get_pane(&tile_id).cloned() {
            self.closed_heads.push(head);
        }
        // Return true to allow egui_tiles to remove the tile.
        true
    }

    fn tab_ui(
        &mut self,
        tiles: &mut egui_tiles::Tiles<GraphPane>,
        ui: &mut egui::Ui,
        id: egui::Id,
        tile_id: egui_tiles::TileId,
        state: &egui_tiles::TabState,
    ) -> egui::Response {
        // Load tab edit state from temp memory.
        let edit_state_id = egui::Id::new("tab_edit_state");
        let mut edit_state: TabEditState = ui
            .memory_mut(|m| m.data.get_temp(edit_state_id))
            .unwrap_or_default();

        let is_editing = edit_state.editing_tile_id == Some(tile_id);

        let response = if is_editing {
            let head = tiles.get_pane(&tile_id).map(|GraphPane(h)| h.clone());
            let names = crate::reg::names(self.env.registry);

            let name_res = head.as_ref().map(|h| {
                ui.scope(|ui| {
                    ui.set_max_width(ui.available_width().min(150.0));
                    widget::head_name_edit(h, &mut edit_state.edit_text, &names, ui)
                })
                .inner
            });

            let Some(name_res) = name_res else {
                edit_state.editing_tile_id = None;
                edit_state.edit_text.clear();
                // Store edit state back to temp memory.
                ui.memory_mut(|m| m.data.insert_temp(edit_state_id, edit_state));
                return ui.label("");
            };

            // Request focus on the first frame after entering edit mode.
            if edit_state.request_focus {
                name_res.response.request_focus();
                edit_state.request_focus = false;
            }

            // head_name_edit resets the text on commit/cancel, so detect
            // focus loss or escape to clear the tab editing state.
            let editing_ended =
                name_res.response.lost_focus() || ui.input(|i| i.key_pressed(egui::Key::Escape));
            if editing_ended {
                if let Some(new_branch) = name_res.new_branch {
                    *self.new_branch = Some(new_branch);
                }
                edit_state.editing_tile_id = None;
                edit_state.edit_text.clear();
            }

            name_res.response
        } else {
            // Render the tab using our custom widget.
            // Append a filled circle if this head is focused.
            let mut title = self.tab_title_for_tile(tiles, tile_id).text().to_string();
            let mut session = None;
            if let Some(GraphPane(head)) = tiles.get_pane(&tile_id) {
                let heads = self.access.heads();
                if crate::head_is_focused(heads, *self.focused_head, head) {
                    title.push_str(" âš«");
                }
                // The head's collab session, when shared.
                if let (Some(collab), gantz_ca::Head::Branch(name)) = (self.collab, head) {
                    session = collab.sessions.get(name);
                }
            }
            let mut tab = widget::Tab::new(title, id)
                .active(state.active)
                .closable(state.closable)
                .hint("double-click to rename");
            if let Some(display) = session {
                tab = tab.status_dot(display.conn.color(), display.hover_text());
            }
            let res = tab.show(ui);

            // Handle double-click to enter edit mode.
            if res.tab.double_clicked() {
                if let Some(GraphPane(head)) = tiles.get_pane(&tile_id) {
                    // Initialize edit text based on head type.
                    let initial_text = match head {
                        gantz_ca::Head::Branch(name) => name.to_string(),
                        gantz_ca::Head::Commit(_) => String::new(),
                    };
                    edit_state.editing_tile_id = Some(tile_id);
                    edit_state.edit_text = initial_text;
                    edit_state.request_focus = true;
                }
            }

            // Update focused_head when this tab is clicked.
            if res.tab.clicked() {
                if let Some(GraphPane(head)) = tiles.get_pane(&tile_id) {
                    if let Some(ix) = self.access.heads().iter().position(|h| h == head) {
                        *self.focused_head = ix;
                    }
                }
            }

            // Handle close button click directly, like egui_tiles default does.
            if res.close.is_some_and(|r| r.clicked()) {
                if self.on_tab_close(tiles, tile_id) {
                    tiles.remove(tile_id);
                }
            }

            res.tab
        };

        // Store edit state back to temp memory.
        ui.memory_mut(|m| m.data.insert_temp(edit_state_id, edit_state));

        response
    }

    fn pane_ui(
        &mut self,
        ui: &mut egui::Ui,
        _tile_id: egui_tiles::TileId,
        pane: &mut GraphPane,
    ) -> egui_tiles::UiResponse {
        let GraphPane(pane_head) = pane;

        // Find the index of this head (for updating focused_head).
        let ix = self
            .access
            .heads()
            .iter()
            .position(|h| h == pane_head)
            .expect("pane head not found in heads");

        let immutable = head_immutable(pane_head, self.base_immutable, self.base_names);
        let diagnostics = self.access.diagnostics(pane_head).to_vec();

        // Global layout params (Copy) combined with this head's flow.
        let layout_config = self.state.layout_config;
        // Global grid/snap/align options (Copy), applied to every head.
        let scene_config = self.state.scene_config;
        let head_state = self.state.open_heads.entry(pane_head.clone()).or_default();
        let layout_params = layout_config.to_params(head_state.layout_flow);
        // Disjoint borrow of a sibling field of `open_heads` for the graph
        // scene's "Panes" context submenu.
        let view_toggles = &mut self.state.view_toggles;
        // Disjoint borrow for the scene-level Select-all shortcut.
        let keymap = &self.state.keymap;

        // We'll use this for positioning the fixed path labels window.
        let rect = ui.available_rect_before_wrap();

        // Get mutable access to this head's data and render the graph scene.
        // The camera rides out for overlays that map graph-space positions
        // (e.g. peer pointers) to the pane.
        let (graph_response, camera) = match self.access.with_head_mut(pane_head, |data| {
            let camera = data.view.camera;
            let res = graph_scene(
                self.env,
                self.codec,
                data.graph,
                data.instances,
                pane_head,
                head_state,
                view_toggles,
                self.ext_panes,
                self.edge_styles,
                data.view,
                layout_params,
                scene_config,
                immutable,
                self.validate_change_tracking,
                keymap,
                &diagnostics,
                data.vm,
                ui,
            );
            (res, camera)
        }) {
            Some((res, camera)) => (res, Some(camera)),
            None => (None, None),
        };

        if let Some(response) = graph_response {
            // Focus this head when clicking on the graph or any of its nodes.
            if response.scene.clicked() || response.any_node_interacted() {
                *self.focused_head = ix;
            }
            // Record a CA-affecting edit so the app can commit just this head.
            if response.changed {
                self.changed_heads.push(pane_head.clone());
            }
            // Collect this frame's deletions; `Gantz::show` migrates the
            // top-level tree's node-view paths past them after layout (the live
            // top-level tree isn't reachable here, mid-traversal).
            if !response.reindex.is_empty() {
                self.reindexes.push((pane_head.clone(), response.reindex));
            }
            // Tag the scene's emissions with this head.
            self.responses.extend(Some(&*pane_head), response.responses);
        }

        // Floating name breadcrumb for nested graphs.
        let crumbs = name_breadcrumb(rect, pane_head, ui);
        self.responses.extend(Some(&*pane_head), crumbs);

        // A collab-session overlay: while a join is still connecting (or has
        // failed) the pane's graph is only a placeholder - dim the scene and
        // say what is happening. Peers' live pointers paint beneath it.
        if let (Some(collab), gantz_ca::Head::Branch(name)) = (self.collab, &*pane_head) {
            if let Some(display) = collab.sessions.get(name) {
                if self.state.collab.show_pointers && !display.pointers.is_empty() {
                    if let Some(camera) = camera {
                        paint_peer_pointers(rect, camera, &display.pointers, ui);
                        // Cursors move between this peer's frames.
                        ui.ctx()
                            .request_repaint_after(std::time::Duration::from_millis(100));
                    }
                }
                paint_session_overlay(rect, display, ui);
            }
        }

        egui_tiles::UiResponse::None
    }
}

/// Paint session peers' live pointers (presence cursors) over the pane.
///
/// Positions arrive in graph-space coordinates; the head's camera maps them
/// to screen space, so cursors land on the right nodes regardless of either
/// peer's viewport. Painted on a foreground layer for the same reason as
/// [`paint_session_overlay`]: the scene's sublayer background would hide a
/// plain `ui.painter()` overlay.
fn paint_peer_pointers(
    rect: egui::Rect,
    camera: crate::Camera,
    pointers: &[crate::collab::PointerDisplay],
    ui: &egui::Ui,
) {
    let layer = egui::LayerId::new(egui::Order::Foreground, ui.id().with("peer_pointers"));
    let mut painter = ui.ctx().layer_painter(layer);
    painter.set_clip_rect(rect);
    for pointer in pointers {
        let screen = rect.center() + (pointer.pos - camera.center) * camera.zoom;
        // Skip cursors far outside the viewport (the clip rect would hide
        // them anyway; this skips the label layout too).
        if !rect.expand(24.0).contains(screen) {
            continue;
        }
        painter.circle(
            screen,
            4.0,
            pointer.color,
            egui::Stroke::new(1.0, egui::Color32::from_black_alpha(160)),
        );
        painter.text(
            screen + egui::vec2(8.0, 6.0),
            egui::Align2::LEFT_TOP,
            &pointer.label,
            egui::FontId::proportional(11.0),
            pointer.color,
        );
    }
}

/// Dim a joining session's still-empty scene with its sync progress, or the
/// error when the join failed. Painted only while the join placeholder is
/// shown (`awaiting_snapshot`); once the snapshot arrives - or for a host,
/// which never shows a placeholder - the graph renders unobscured.
fn paint_session_overlay(rect: egui::Rect, display: &crate::collab::SessionDisplay, ui: &egui::Ui) {
    use crate::collab::SessionConn;
    // Only ever cover the empty placeholder scene. Once the graph has loaded a
    // mid-session error surfaces through the tab's status dot, not a full-scene
    // overlay that would obscure a usable graph.
    if !display.awaiting_snapshot {
        return;
    }
    let (heading, detail, color) = if let Some(error) = &display.error {
        (
            "Failed to connect".to_string(),
            Some(error.clone()),
            SessionConn::Degraded.color(),
        )
    } else {
        // Animated ellipsis while we wait.
        let dots = 1 + (ui.input(|i| i.time) * 2.0) as usize % 3;
        ui.ctx()
            .request_repaint_after(std::time::Duration::from_millis(250));
        let heading = format!("Connecting{}", ".".repeat(dots));
        (
            heading,
            Some(display.sync_status()),
            ui.visuals().strong_text_color(),
        )
    };
    // egui_graph draws the scene in a sublayer with an opaque background,
    // composited directly above this pane's own layer, so a `ui.painter()`
    // overlay would be hidden beneath it. Paint on a foreground layer instead.
    let layer = egui::LayerId::new(egui::Order::Foreground, ui.id().with("session_overlay"));
    let mut painter = ui.ctx().layer_painter(layer);
    painter.set_clip_rect(rect);
    painter.rect_filled(rect, 0.0, egui::Color32::from_black_alpha(120));
    painter.text(
        rect.center(),
        egui::Align2::CENTER_CENTER,
        heading,
        egui::FontId::proportional(20.0),
        color,
    );
    if let Some(detail) = detail {
        painter.text(
            rect.center() + egui::vec2(0.0, 28.0),
            egui::Align2::CENTER_CENTER,
            detail,
            egui::FontId::proportional(14.0),
            ui.visuals().weak_text_color(),
        );
    }
}

/// The tab title for a node-view pane: `<head>:<path>` with the final path
/// segment rendered as `<index>-<ty_name>` (e.g. `main:3-plot`, or for a nested
/// path `main:2:5-plot`). Intermediate segments are shown as raw indices.
fn node_view_title(pane: &NodeViewPane) -> String {
    use std::fmt::Write;
    let mut s = format!("{}", pane.head);
    let last = pane.path.len().saturating_sub(1);
    for (i, seg) in pane.path.iter().enumerate() {
        if i == last {
            let _ = write!(s, ":{seg}-{}", pane.ty_name);
        } else {
            let _ = write!(s, ":{seg}");
        }
    }
    s
}

/// The display title for a pane, shared by the tab bar, floating windows, and
/// the `windowed_panes` report. Panes tied to the focused head (graph config,
/// node inspector, Steel) suffix it, e.g. `Steel - main`.
fn pane_title<Access>(
    gantz: &Gantz<'_>,
    access: &Access,
    focused_head: usize,
    pane: &Pane,
) -> String
where
    Access: HeadAccess,
{
    let with_head = |label: &str| match access.heads().get(focused_head) {
        Some(head) => format!("{label} - {head}"),
        None => label.to_string(),
    };
    match pane {
        Pane::Ext(key) => match gantz.ext_panes.iter().find(|p| p.key() == *key) {
            Some(p) => with_head(p.title()),
            None => key.clone(),
        },
        Pane::GraphConfig => with_head("Graph"),
        Pane::GraphScene => "Graphs".to_string(),
        Pane::Graphs => "Graphs".to_string(),
        Pane::GuiPerf => "GUI Perf".to_string(),
        Pane::History => "History".to_string(),
        Pane::Settings => "Settings".to_string(),
        Pane::Logs => match gantz.log_source {
            None => "Logs (No Source)".to_string(),
            Some(LogSource::Logger(_)) => "Logs".to_string(),
            #[cfg(feature = "tracing")]
            Some(LogSource::TraceCapture(..)) => "Tracing".to_string(),
        },
        Pane::NodeInspector => with_head("Node Inspector"),
        Pane::NodeView(p) => node_view_title(p),
        Pane::Steel => with_head("Steel"),
        Pane::GuiDebug => with_head("GUI Debug"),
        Pane::VmPerf => "VM Perf".to_string(),
    }
}

impl widget::node_palette::Command for NodeTyCmd<'_> {
    fn text(&self) -> &str {
        self.name
    }

    fn description(&self) -> Option<std::borrow::Cow<'static, str>> {
        self.env.node_description(self.name)
    }

    fn info_ui(&self, ui: &mut egui::Ui) {
        crate::node_info_ui(&self.env.command_info(self.name), ui);
    }

    fn formatted_kb_shortcut(&self, ctx: &egui::Context) -> Option<String> {
        self.env.command_formatted_kb_shortcut(ctx, self.name)
    }
}

impl Clone for NodeTyCmd<'_> {
    fn clone(&self) -> Self {
        Self {
            env: self.env,
            name: self.name,
        }
    }
}

impl Copy for NodeTyCmd<'_> {}

impl Default for GantzState {
    fn default() -> Self {
        Self::new()
    }
}

/// Create the initial layout of the tree of tiles.
///
/// Roughly something like this:
///
/// -----------------------------------------
/// |grs/hist/settings |scene               |
/// |------------------|                     |
/// |vm/gui            |                     |
/// |------------------|---------------------|
/// |conf              |logs      |steel     |
/// |------------------|          |          |
/// |insp              |          |          |
/// -----------------------------------------
///
/// The active tab of each tab container defaults to its first child (see
/// `egui_tiles::Tabs::new`), so child ordering picks the default tabs.
fn create_tree() -> egui_tiles::Tree<Pane> {
    let mut tiles = egui_tiles::Tiles::default();

    // The leaf panes. The GUI Debug pane is not created here: it joins the
    // tray via `sync_singleton_pane` (the same path that serves persisted
    // trees predating it).
    let graph_config = tiles.insert_pane(Pane::GraphConfig);
    let graph_scene = tiles.insert_pane(Pane::GraphScene);
    let graphs = tiles.insert_pane(Pane::Graphs);
    let gui_perf = tiles.insert_pane(Pane::GuiPerf);
    let history = tiles.insert_pane(Pane::History);
    let logs = tiles.insert_pane(Pane::Logs);
    let node_inspector = tiles.insert_pane(Pane::NodeInspector);
    let settings = tiles.insert_pane(Pane::Settings);
    let steel = tiles.insert_pane(Pane::Steel);
    let vm_perf = tiles.insert_pane(Pane::VmPerf);

    // Sidebar tab containers (first child is the default-active tab).
    let graphs_history_settings = tiles.insert_tab_tile(vec![graphs, history, settings]);
    // VM Perf and GUI Perf sit side by side rather than as tabs, so both plots
    // are visible at once.
    let perf = tiles.insert_horizontal_tile(vec![vm_perf, gui_perf]);

    // The left column (sidebar).
    let mut shares = egui_tiles::Shares::default();
    shares.set_share(graphs_history_settings, 0.30);
    shares.set_share(perf, 0.05);
    shares.set_share(graph_config, 0.13);
    shares.set_share(node_inspector, 0.25);
    let left_column = tiles.insert_container(egui_tiles::Linear {
        children: vec![graphs_history_settings, perf, graph_config, node_inspector],
        dir: egui_tiles::LinearDir::Vertical,
        shares,
    });

    // Logs and steel code in bottom "tray".
    let tray = tiles.insert_horizontal_tile(vec![logs, steel]);

    // The right column with main area (graph scene above logs and steel code).
    let right_column = tiles.insert_container(egui_tiles::Linear::new_binary(
        egui_tiles::LinearDir::Vertical,
        [graph_scene, tray],
        0.7,
    ));

    // The root with both columns. The split here is only a fallback; the
    // sidebar normally has a fixed pixel width maintained across window resizes
    // (see `impose_fixed_sizes` / `default_sidebar_width`).
    let root = tiles.insert_container(egui_tiles::Linear::new_binary(
        egui_tiles::LinearDir::Horizontal,
        [left_column, right_column],
        0.18,
    ));

    egui_tiles::Tree::new("gantz-tiles-tree", root, tiles)
}

/// Create an empty graph tree. Panes will be added by `sync_graph_panes`.
fn create_empty_graph_tree() -> egui_tiles::Tree<GraphPane> {
    egui_tiles::Tree::empty("graph-tiles")
}

/// Insert a [`Pane::NodeView`] for `(head, path)` into the top-level `tree`, or
/// activate the existing one (deduped by head + path). `ty_name` is the node's
/// type name used for the tab title. New views land in the tray - a layout-safe
/// default (opaque to the fixed-size anchors); the user can then drag them
/// anywhere in the tree.
fn add_node_view_pane(
    tree: &mut egui_tiles::Tree<Pane>,
    head: gantz_ca::Head,
    path: Vec<node::Id>,
    ty_name: String,
) {
    // Dedupe: if a view for this (head, path) already exists, just focus it.
    let existing = tree.tiles.iter().find_map(|(id, tile)| match tile {
        egui_tiles::Tile::Pane(Pane::NodeView(p)) if p.head == head && p.path == path => Some(*id),
        _ => None,
    });
    if let Some(id) = existing {
        tree.make_active(|tile_id, _| tile_id == id);
        return;
    }
    let pane = Pane::NodeView(NodeViewPane {
        head,
        path,
        ty_name,
    });
    insert_tray_pane(tree, pane);
}

/// Insert a new tile for `pane`, defaulting to the tray and falling back to
/// the root if the layout isn't canonical.
fn insert_tray_pane(tree: &mut egui_tiles::Tree<Pane>, pane: Pane) {
    let pane_id = tree.tiles.insert_pane(pane);
    let container = layout_anchors(tree).map(|a| a.tray).or_else(|| tree.root());
    match container {
        Some(c) => tree.move_tile_to_container(pane_id, c, usize::MAX, true),
        None => tree.root = Some(pane_id),
    }
}

/// Ensure a [`Pane::Ext`] tile exists for each supplied provider key, adding
/// missing ones to the tray (hidden until toggled, like Logs/Steel). Tiles
/// whose provider is absent are left in place: they render a placeholder and
/// keep their spot in the layout for when the provider returns.
fn sync_ext_panes(tree: &mut egui_tiles::Tree<Pane>, keys: &[&str]) {
    for &key in keys {
        let exists = tree
            .tiles
            .iter()
            .any(|(_, tile)| matches!(tile, egui_tiles::Tile::Pane(Pane::Ext(k)) if k == key));
        if !exists {
            insert_tray_pane(tree, Pane::Ext(key.to_string()));
        }
    }
}

/// Ensure a tile exists for the given singleton pane, adding it to the tray
/// when missing (a tree persisted before the pane existed).
fn sync_singleton_pane(tree: &mut egui_tiles::Tree<Pane>, pane: Pane) {
    let exists = tree
        .tiles
        .iter()
        .any(|(_, tile)| matches!(tile, egui_tiles::Tile::Pane(p) if *p == pane));
    if !exists {
        insert_tray_pane(tree, pane);
    }
}

/// Sync the graph tree panes with the current heads.
///
/// Adds missing panes for new heads and removes panes for heads that no longer exist.
fn sync_graph_panes(tree: &mut egui_tiles::Tree<GraphPane>, heads: &[gantz_ca::Head]) {
    use std::collections::HashSet;

    // Collect existing heads in panes.
    let existing: HashSet<gantz_ca::Head> = tree
        .tiles
        .iter()
        .filter_map(|(_, tile)| match tile {
            egui_tiles::Tile::Pane(GraphPane(head)) => Some(head.clone()),
            _ => None,
        })
        .collect();

    // Collect current heads.
    let current: HashSet<gantz_ca::Head> = heads.iter().cloned().collect();

    // Add missing panes for heads that don't have a pane yet.
    for head in heads {
        if !existing.contains(head) {
            let pane_id = tree.tiles.insert_pane(GraphPane(head.clone()));
            // Add to root container, or set as root if tree is empty.
            if let Some(root_id) = tree.root() {
                tree.move_tile_to_container(pane_id, root_id, usize::MAX, true);
            } else {
                // Tree is empty, create a tabs container as root.
                let root = tree.tiles.insert_tab_tile(vec![pane_id]);
                tree.root = Some(root);
            }
        }
    }

    // Remove panes for heads that no longer exist.
    let orphaned: Vec<egui_tiles::TileId> = tree
        .tiles
        .iter()
        .filter_map(|(id, tile)| match tile {
            egui_tiles::Tile::Pane(GraphPane(head)) if !current.contains(head) => Some(*id),
            _ => None,
        })
        .collect();
    for id in orphaned {
        tree.tiles.remove(id);
    }
}

/// All panes should have tab bars besides the main graph scene.
///
/// In the case that a tile is being dragged, even the graph scene should show a
/// tab bar in case the user wants to add a tab there.
fn simplify_tree(tree: &mut egui_tiles::Tree<Pane>, ctx: &egui::Context) {
    // Default options, but ensure panes have tabs.
    tree.simplify(&egui_tiles::SimplificationOptions {
        all_panes_must_have_tabs: true,
        ..Default::default()
    });
    // If a tile is being dragged, show all tab bars.
    if tree.dragged_id(ctx).is_some() {
        return;
    }
    // Otherwise, find the graph scene ID.
    let Some(graph_scene_id) = tree.tiles.find_pane(&Pane::GraphScene) else {
        return;
    };
    // Find its parent. This must be `Tabs` after the `simplify` pass above.
    let Some(parent_id) = tree.tiles.parent_of(graph_scene_id) else {
        return;
    };
    // If the parent has one child, replace it with the graph scene.
    let Some(parent) = tree.tiles.get_container(parent_id) else {
        return;
    };
    if parent.num_children() == 1 {
        tree.tiles.remove(graph_scene_id);
        tree.tiles
            .insert(parent_id, egui_tiles::Tile::Pane(Pane::GraphScene));
    }
}

/// The gap between sibling tiles, in points. Must match the (unoverridden)
/// default `egui_tiles::Behavior::gap_width`, so imposed pixel sizes are exact
/// and don't drift when re-imposed each frame.
const TILE_GAP: f32 = 1.0;

/// The minimum sidebar width / tray height, in points.
const MIN_PANE_SIZE: f32 = 80.0;

/// The tiles whose Linear share splits hold the sidebar width and tray height,
/// when the tree has its default top-level shape.
struct LayoutAnchors {
    /// Root horizontal Linear: `[left_column | right_column]`.
    root: egui_tiles::TileId,
    left_column: egui_tiles::TileId,
    /// Right column vertical Linear: `[graph_scene / tray]`.
    right_column: egui_tiles::TileId,
    graph_scene: egui_tiles::TileId,
    tray: egui_tiles::TileId,
}

/// Identify the layout anchors, or `None` if the tree isn't in its default
/// top-level shape (mid-drag, or after the user rearranged panes), in which
/// case the proportional layout is left untouched.
fn layout_anchors(tree: &egui_tiles::Tree<Pane>) -> Option<LayoutAnchors> {
    let graph_scene = tree.tiles.find_pane(&Pane::GraphScene)?;
    let right_column = tree.tiles.parent_of(graph_scene)?;
    let root = tree.root()?;
    let &[a, b] = linear_children(tree, root, egui_tiles::LinearDir::Horizontal)?.as_slice() else {
        return None;
    };
    let left_column = match (a == right_column, b == right_column) {
        (false, true) => a,
        (true, false) => b,
        _ => return None,
    };
    let &[c, d] = linear_children(tree, right_column, egui_tiles::LinearDir::Vertical)?.as_slice()
    else {
        return None;
    };
    let tray = match (c == graph_scene, d == graph_scene) {
        (true, false) => d,
        (false, true) => c,
        _ => return None,
    };
    Some(LayoutAnchors {
        root,
        left_column,
        right_column,
        graph_scene,
        tray,
    })
}

/// The children of `id` if it is a Linear container with direction `dir`.
fn linear_children(
    tree: &egui_tiles::Tree<Pane>,
    id: egui_tiles::TileId,
    dir: egui_tiles::LinearDir,
) -> Option<Vec<egui_tiles::TileId>> {
    match tree.tiles.get_container(id)? {
        egui_tiles::Container::Linear(l) if l.dir == dir => Some(l.children.clone()),
        _ => None,
    }
}

/// Set the two shares of a binary Linear container.
fn set_linear_shares(
    tree: &mut egui_tiles::Tree<Pane>,
    container: egui_tiles::TileId,
    a: egui_tiles::TileId,
    a_share: f32,
    b: egui_tiles::TileId,
    b_share: f32,
) {
    if let Some(egui_tiles::Tile::Container(egui_tiles::Container::Linear(l))) =
        tree.tiles.get_mut(container)
    {
        l.shares.set_share(a, a_share);
        l.shares.set_share(b, b_share);
    }
}

/// Impose the stored sidebar width / tray height (in points) on the tree's
/// share splits so they stay fixed as the window resizes. Call after
/// `simplify_tree`, before `tree.ui`.
fn impose_fixed_sizes(tree: &mut egui_tiles::Tree<Pane>, state: &GantzState, area: egui::Rect) {
    let Some(anchors) = layout_anchors(tree) else {
        return;
    };
    // Both columns span the full height, so the tray's available height is the
    // area height less the gap; the sidebar's available width likewise.
    if state.view_toggles.sidebar_open {
        let avail = area.width() - TILE_GAP;
        let width = state
            .sidebar_width
            .clamp(MIN_PANE_SIZE, (avail - MIN_PANE_SIZE).max(MIN_PANE_SIZE));
        set_linear_shares(
            tree,
            anchors.root,
            anchors.left_column,
            width,
            anchors.right_column,
            (avail - width).max(1.0),
        );
    }
    if state.view_toggles.logs || state.view_toggles.steel || state.view_toggles.gui_debug {
        let avail = area.height() - TILE_GAP;
        let height = state
            .tray_height
            .clamp(MIN_PANE_SIZE, (avail - MIN_PANE_SIZE).max(MIN_PANE_SIZE));
        set_linear_shares(
            tree,
            anchors.right_column,
            anchors.graph_scene,
            (avail - height).max(1.0),
            anchors.tray,
            height,
        );
    }
}

/// Capture the sidebar width / tray height (in points) from the laid-out tree,
/// so they can be re-imposed next frame (including after manual divider drags).
/// Call after `tree.ui`.
///
/// This reads the post-layout *shares* rather than the cached rects: a resize
/// drag updates the shares during `tree.ui`, but the rects it computes reflect
/// the pre-drag split, so reading rects would never see the drag.
fn capture_fixed_sizes(tree: &egui_tiles::Tree<Pane>, state: &mut GantzState, area: egui::Rect) {
    let Some(anchors) = layout_anchors(tree) else {
        return;
    };
    // Gate on the *laid-out* visibility, not `sidebar_open`: the hamburger can
    // flip `sidebar_open` mid-frame, but `set_tile_visibility` only runs at the
    // frame start, so the layout (and thus the captured share) reflects the
    // visibility from frame start. Capturing against a stale layout would
    // compute the column's size against the wrong set of visible siblings.
    if tree.is_visible(anchors.left_column) {
        if let Some(width) = linear_child_points(
            tree,
            anchors.root,
            anchors.left_column,
            area.width() - TILE_GAP,
        ) {
            if width > 1.0 {
                state.sidebar_width = width;
            }
        }
    }
    if tree.is_visible(anchors.tray) {
        if let Some(height) = linear_child_points(
            tree,
            anchors.right_column,
            anchors.tray,
            area.height() - TILE_GAP,
        ) {
            if height > 1.0 {
                state.tray_height = height;
            }
        }
    }
}

/// The points a Linear child currently occupies, derived from its share of the
/// visible children (mirroring `egui_tiles::Shares::split`).
fn linear_child_points(
    tree: &egui_tiles::Tree<Pane>,
    container: egui_tiles::TileId,
    child: egui_tiles::TileId,
    available: f32,
) -> Option<f32> {
    let egui_tiles::Container::Linear(l) = tree.tiles.get_container(container)? else {
        return None;
    };
    let total: f32 = l
        .children
        .iter()
        .filter(|&&c| tree.is_visible(c))
        .map(|&c| l.shares[c])
        .sum();
    (total > 0.0).then(|| available * l.shares[child] / total)
}

/// The supplied extension panes' checkbox entries - the single source both
/// pane-toggle UIs (Settings -> Panes and the graph-area context menu's
/// "panes" submenu) render from, so a new pane cannot appear in one and not
/// the other.
fn ext_pane_entries(gantz: &Gantz) -> Vec<widget::ExtPaneEntry> {
    gantz
        .ext_panes
        .iter()
        .map(|p| widget::ExtPaneEntry {
            key: p.key().to_string(),
            title: p.title().to_string(),
            description: p.description().to_string(),
        })
        .collect()
}

/// Whether a tab's pane can be hidden via its right-click menu. The main graph
/// scene is not hideable; node views are closed (removed), not hidden.
fn pane_is_hideable(pane: &Pane) -> bool {
    !matches!(pane, Pane::GraphScene | Pane::NodeView(_))
}

/// Set a pane's visibility toggle. No-op for panes without one.
fn set_pane_visible(view: &mut ViewToggles, pane: &Pane, visible: bool) {
    match pane {
        Pane::Ext(key) => {
            view.ext.insert(key.clone(), visible);
        }
        Pane::Graphs => view.graphs = visible,
        Pane::History => view.history = visible,
        Pane::Settings => view.settings = visible,
        Pane::GraphConfig => view.graph_config = visible,
        Pane::NodeInspector => view.node_inspector = visible,
        Pane::VmPerf => view.perf_vm = visible,
        Pane::GuiPerf => view.perf_gui = visible,
        Pane::Logs => view.logs = visible,
        Pane::Steel => view.steel = visible,
        Pane::GuiDebug => view.gui_debug = visible,
        // No visibility toggle: always-visible scene / closable node views.
        Pane::GraphScene | Pane::NodeView(_) => {}
    }
}

/// Whether a pane's visibility toggle is currently on. Panes without a toggle
/// (the graph scene and node views) are always considered visible.
fn pane_is_visible(view: &ViewToggles, pane: &Pane) -> bool {
    match pane {
        Pane::Ext(key) => view.ext.get(key).copied().unwrap_or(false),
        Pane::Graphs => view.graphs,
        Pane::History => view.history,
        Pane::Settings => view.settings,
        Pane::GraphConfig => view.graph_config,
        Pane::NodeInspector => view.node_inspector,
        Pane::VmPerf => view.perf_vm,
        Pane::GuiPerf => view.perf_gui,
        Pane::Logs => view.logs,
        Pane::Steel => view.steel,
        Pane::GuiDebug => view.gui_debug,
        Pane::GraphScene | Pane::NodeView(_) => true,
    }
}

/// Whether a pane may be popped out into a window. Every pane but the graph
/// scene (which hosts the inner graph tile tree) qualifies.
fn pane_is_poppable(pane: &Pane) -> bool {
    !matches!(pane, Pane::GraphScene)
}

/// A stable identity for a pane, used to key its window and to dedupe the
/// windowed set. Singletons key on their variant; a node view keys on its
/// `(head, path)` - the same identity `add_node_view_pane` dedupes on. Public so
/// a native host can key a pop-out window's persisted geometry
/// ([`GantzState::windowed_geometry`]) by the same identity.
pub fn pane_key(pane: &Pane) -> String {
    match pane {
        Pane::Ext(key) => format!("ext:{key}"),
        Pane::GraphConfig => "graph-config".to_string(),
        Pane::GraphScene => "graph-scene".to_string(),
        Pane::Graphs => "graphs".to_string(),
        Pane::GuiDebug => "gui-debug".to_string(),
        Pane::GuiPerf => "gui-perf".to_string(),
        Pane::History => "history".to_string(),
        Pane::Logs => "logs".to_string(),
        Pane::NodeInspector => "node-inspector".to_string(),
        Pane::Settings => "settings".to_string(),
        Pane::Steel => "steel".to_string(),
        Pane::VmPerf => "vm-perf".to_string(),
        Pane::NodeView(p) => {
            use std::fmt::Write;
            let mut s = format!("node-view:{}", p.head);
            for seg in &p.path {
                let _ = write!(s, ":{seg}");
            }
            s
        }
    }
}

/// egui-memory id under which the set of windowed (popped-out) panes persists,
/// stored as a RON `String` alongside the tile tree (see [`load_ron`]).
fn windowed_panes_id() -> egui::Id {
    egui::Id::new("gantz-windowed-panes-storage-v1")
}

/// egui-memory id for panes a host has requested be re-docked before the next
/// `Gantz::show` (see [`redock_windowed_pane`]).
fn pending_redock_id() -> egui::Id {
    egui::Id::new("gantz-pending-redock")
}

/// egui-memory id for node views a host has requested be closed before the next
/// `Gantz::show` (see [`close_windowed_pane`]).
fn pending_close_id() -> egui::Id {
    egui::Id::new("gantz-pending-close")
}

/// Load and clear a pending-pane list stored in egui memory.
fn drain_pending(ctx: &egui::Context, id: egui::Id) -> Vec<Pane> {
    let pending: Vec<Pane> = load_ron(ctx, id).unwrap_or_default();
    if !pending.is_empty() {
        store_ron(ctx, id, &Vec::<Pane>::new());
    }
    pending
}

/// Append a pane to a pending-intent list in egui memory.
fn enqueue_pending(ctx: &egui::Context, id: egui::Id, pane: &Pane) {
    let mut pending: Vec<Pane> = load_ron(ctx, id).unwrap_or_default();
    pending.push(pane.clone());
    store_ron(ctx, id, &pending);
}

/// Request that a popped-out pane return to the tile tree, from outside a
/// [`Gantz::show`] call (e.g. a native host's OS-window close button).
///
/// The request is queued in egui memory and applied on the next `show`, so it
/// works from any egui context. A no-op if the pane isn't windowed.
pub fn redock_windowed_pane(ctx: &egui::Context, pane: &Pane) {
    enqueue_pending(ctx, pending_redock_id(), pane);
}

/// Request that a popped-out node view be closed (destroyed) rather than
/// re-docked. Queued and applied like [`redock_windowed_pane`]. Singletons have
/// no destructive close, so they are re-docked instead.
pub fn close_windowed_pane(ctx: &egui::Context, pane: &Pane) {
    enqueue_pending(ctx, pending_close_id(), pane);
}

/// Add `pane` to the windowed set unless one with the same identity is already
/// there.
fn push_windowed(windowed: &mut Vec<Pane>, pane: Pane) {
    let key = pane_key(&pane);
    if windowed.iter().all(|p| pane_key(p) != key) {
        windowed.push(pane);
    }
}

/// Pop a pane out of the tile tree into a window.
///
/// Node views are real tiles, so the tile is removed; singletons stay in the
/// tree but hidden (their window shows them instead). Either way the pane joins
/// the windowed set.
fn detach_pane(
    view: &mut ViewToggles,
    windowed: &mut Vec<Pane>,
    tiles: &mut egui_tiles::Tiles<Pane>,
    tile_id: egui_tiles::TileId,
    pane: &Pane,
) {
    match pane {
        Pane::NodeView(_) => {
            tiles.remove(tile_id);
        }
        _ => set_pane_visible(view, pane, false),
    }
    push_windowed(windowed, pane.clone());
}

/// Return a windowed pane to the tile tree: a node view re-enters as a tray
/// tile, a singleton just becomes visible again (its tile stayed in the tree).
fn redock_pane(view: &mut ViewToggles, tree: &mut egui_tiles::Tree<Pane>, pane: Pane) {
    match pane {
        Pane::NodeView(p) => add_node_view_pane(tree, p.head, p.path, p.ty_name),
        pane => set_pane_visible(view, &pane, true),
    }
}

/// Migrate windowed [`Pane::NodeView`] entries for `head` after a node removal,
/// mirroring [`migrate_node_view_paths`] for the windowed set: a view of a
/// removed node is dropped; a view of a swapped node has its path rewritten.
fn migrate_windowed_node_views(
    windowed: &mut Vec<Pane>,
    head: &gantz_ca::Head,
    reindex: &crate::ops::Reindex,
) {
    if reindex.is_empty() {
        return;
    }
    windowed.retain_mut(|pane| {
        let Pane::NodeView(p) = pane else {
            return true;
        };
        if p.head != *head {
            return true;
        }
        let [ix] = p.path[..] else {
            return true;
        };
        match reindex.apply_to_index(ix) {
            Some(new_ix) => {
                p.path = vec![new_ix];
                true
            }
            None => false,
        }
    });
}

/// Ensure the view toggles match the pane visibility.
fn set_tile_visibility(tree: &mut egui_tiles::Tree<Pane>, view: &ViewToggles) {
    let ids: Vec<_> = tree.tiles.tile_ids().collect();
    let open = view.sidebar_open;
    // Set visibility for panes. Sidebar content panes are gated by both the
    // sidebar being open and their individual toggle; the Settings control
    // pane is gated only by the sidebar being open; the tray panes
    // (Logs/Steel) are independent of the sidebar.
    for &id in &ids {
        if let Some(pane) = tree.tiles.get_pane(&id) {
            match pane {
                Pane::GraphScene => (),
                Pane::Ext(key) => tree.set_visible(id, view.ext.get(key).copied().unwrap_or(false)),
                Pane::Settings => tree.set_visible(id, open && view.settings),
                Pane::GraphConfig => tree.set_visible(id, open && view.graph_config),
                Pane::Graphs => tree.set_visible(id, open && view.graphs),
                Pane::GuiPerf => tree.set_visible(id, open && view.perf_gui),
                Pane::History => tree.set_visible(id, open && view.history),
                Pane::NodeInspector => tree.set_visible(id, open && view.node_inspector),
                Pane::VmPerf => tree.set_visible(id, open && view.perf_vm),
                Pane::Logs => tree.set_visible(id, view.logs),
                Pane::Steel => tree.set_visible(id, view.steel),
                Pane::GuiDebug => tree.set_visible(id, view.gui_debug),
                // Always visible: a node view is removed by closing, not hiding.
                Pane::NodeView(_) => tree.set_visible(id, true),
            }
        }
    }
    // Set visibility for containers.
    for &id in &ids {
        if let Some(container) = tree.tiles.get_container(id) {
            let has_visible_child = container.children().any(|&id| tree.is_visible(id));
            tree.set_visible(id, has_visible_child);
        }
    }
}

/// The egui ID used to store the Graphs pane rect for file drop targeting.
const GRAPHS_PANE_RECT_ID: &str = "gantz-graphs-pane-rect";

/// Paint a hover overlay when `.gantz` files are being dragged over this pane.
///
/// The overlay is best-effort: it only appears when the pointer position is
/// available and within the pane (some platforms don't track the pointer
/// during OS file drags).
fn paint_gantz_file_hover_overlay(ui: &mut egui::Ui) {
    let rect = ui.max_rect();
    let latest_pos = ui.ctx().input(|i| i.pointer.latest_pos());
    let pointer_over = latest_pos.map(|p| rect.contains(p)).unwrap_or(false);
    let has_hovered = ui.ctx().input(|i| {
        i.raw
            .hovered_files
            .iter()
            .any(|f| export::is_maybe_gantz(f.path.as_deref()))
    });

    if has_hovered && pointer_over {
        let painter = ui.painter();
        painter.rect_filled(rect, 0.0, egui::Color32::from_black_alpha(100));
        painter.text(
            rect.center(),
            egui::Align2::CENTER_CENTER,
            "Drop to import",
            egui::FontId::proportional(24.0),
            egui::Color32::WHITE,
        );
    }
}

/// Detect `.gantz` file drops from egui's raw input.
///
/// Called from [`Gantz::show`] after the tile tree renders, so that detection
/// is independent of pointer position (which may be unavailable during OS
/// file drags on some platforms). The target pane is determined by checking
/// the pointer against the stored Graphs pane rect when available, defaulting
/// to [`FileDropTarget::GraphScene`].
fn collect_gantz_file_drops(ctx: &egui::Context) -> Vec<FileDrop> {
    let dropped = ctx.input(|i| i.raw.dropped_files.clone());
    if dropped.is_empty() {
        return Vec::new();
    }

    // Determine target: Graphs if pointer is over the Graphs pane, else GraphScene.
    let graphs_rect: Option<egui::Rect> =
        ctx.memory(|m| m.data.get_temp(egui::Id::new(GRAPHS_PANE_RECT_ID)));
    let latest_pos = ctx.input(|i| i.pointer.latest_pos());
    let over_graphs = match (graphs_rect, latest_pos) {
        (Some(rect), Some(pos)) => rect.contains(pos),
        _ => false,
    };
    let target = if over_graphs {
        FileDropTarget::Graphs
    } else {
        FileDropTarget::GraphScene
    };

    dropped
        .iter()
        .filter(|f| export::is_maybe_gantz(f.path.as_deref()))
        .filter_map(|f| export::read_dropped_file(f))
        .map(|bytes| FileDrop { bytes, target })
        .collect()
}

/// Render a decoded tree against a head's live VM: the GuiDebug pane's
/// central-panel body, shared by the marker and scratch modes. Bindings
/// resolve into the head's node state both ways, and the returned payloads
/// carry the tree's push evaluations and state writes.
#[allow(clippy::too_many_arguments)]
fn gui_debug_tree(
    env: &Env<'_>,
    codec: &crate::node::NodeCodec,
    head: &gantz_ca::Head,
    graph: &gantz_ca::DataGraph,
    vm: &mut Engine,
    decoded: &gantz_ui::Decoded,
    salt: &'static str,
    ui: &mut egui::Ui,
) -> Vec<crate::response::DynResponse> {
    let (inlets, outlets) = crate::inlet_outlet_ids(env, graph);
    // The focused head's committed graph address: resolver hops into
    // instances go through the registry (instances always resolve committed
    // children).
    let head_ca: Option<gantz_ca::ContentAddr> = env
        .registry
        .head_commit(head)
        .map(|commit| commit.graph.into());
    let n_outs = super::gui_debug::node_output_counts(env, codec, graph);
    let resolver = |p: &[node::Id]| -> Option<usize> {
        match p {
            // Top-level nodes read the working graph.
            [ix] => n_outs.get(ix).copied(),
            _ => crate::reg::n_outputs_at(env, head_ca.as_ref()?, p),
        }
    };
    let ref_gui = |chain: &[node::Id]| -> Option<node::Id> {
        let (_, marker) = crate::reg::resolve_ref_chain(env, head_ca?, chain)?;
        Some(marker)
    };
    let mut writes = Vec::new();
    let mut node_ctx = NodeCtx::new(env, &[], &inlets, &outlets, &[], vm, &mut writes);
    let root_id = egui::Id::new(("gantz-gui-debug", head, salt));
    let r = crate::ui_tree::UiTree::new(root_id)
        .n_outputs(&resolver)
        .ref_gui(&ref_gui)
        .show(&decoded.root, &mut node_ctx, ui);
    let mut payloads = r.payloads;
    payloads.extend(
        writes
            .drain(..)
            .map(|w| crate::DynResponse::new(crate::StateWritten(w))),
    );
    payloads
}

/// The GuiDebug pane's collapsible decode-warnings list, shared by both
/// modes.
fn gui_debug_warnings(decoded: &gantz_ui::Decoded, ui: &mut egui::Ui) {
    if decoded.warnings.is_empty() {
        return;
    }
    let title = format!("warnings ({})", decoded.warnings.len());
    egui::CollapsingHeader::new(title).show(ui, |ui| {
        for w in &decoded.warnings {
            ui.horizontal_wrapped(|ui| {
                ui.weak(format!("{:?}", w.path.0));
                ui.label(w.kind.to_string());
            });
        }
    });
}

/// Provides a consistent frame and styling for the panes.
fn pane_ui<R>(ui: &mut egui::Ui, pane: impl FnOnce(&mut egui::Ui) -> R) -> egui::InnerResponse<R> {
    egui::CentralPanel::default().show_inside(ui, |ui| pane(ui))
}

/// The size of the floating sidebar toggle glyph, also used to offset the
/// nested-graph breadcrumb to its right (they share the scene's bottom-left
/// corner).
const SIDEBAR_TOGGLE_ICON_SIZE: f32 = 18.0;

/// A floating hamburger button that toggles the sidebar open/closed.
///
/// Anchored to the given bottom-left position over the graph scene, so it
/// tracks the scene's corner rather than the whole window.
fn sidebar_toggle(ctx: &egui::Context, anchor_pos: egui::Pos2, open: &mut bool) {
    let id = egui::Id::new("gantz-sidebar-toggle");
    egui::Area::new(id)
        .pivot(egui::Align2::LEFT_BOTTOM)
        .fixed_pos(anchor_pos)
        .order(egui::Order::Foreground)
        .show(ctx, |ui| {
            egui::Frame::NONE.show(ui, |ui| {
                // A hamburger that toggles the sidebar. Idle, it matches the
                // faint colour of egui_graph's dot grid; on hover it brightens a
                // little to signal it's interactive (no selection colour when
                // open). Laid out manually so the colour can depend on hover.
                let font = egui::FontId::proportional(SIDEBAR_TOGGLE_ICON_SIZE);
                let galley =
                    ui.painter()
                        .layout_no_wrap("☰".to_owned(), font, egui::Color32::PLACEHOLDER);
                let (rect, response) = ui.allocate_exact_size(galley.size(), egui::Sense::click());
                let color = if response.hovered() {
                    ui.visuals().weak_text_color()
                } else {
                    ui.style().noninteractive().bg_stroke.color
                };
                ui.painter().galley(rect.min, galley, color);
                if response.clicked() {
                    *open = !*open;
                }
                let hint = if *open {
                    "close sidebar"
                } else {
                    "open sidebar"
                };
                response
                    .on_hover_cursor(egui::CursorIcon::PointingHand)
                    .on_hover_text(hint);
            });
        });
}

fn graph_select(
    env: &Env<'_>,
    heads: &[gantz_ca::Head],
    focused_head: usize,
    base_names: &crate::reg::Names,
    collab: Option<&crate::collab::CollabUiState>,
    clipboard: Option<&dyn Fn() -> Option<String>>,
    ui: &mut egui::Ui,
) -> egui::InnerResponse<widget::graph_select::GraphSelectResponse> {
    pane_ui(ui, |ui| {
        widget::GraphSelect::new(env, heads, base_names)
            .focused_head(focused_head)
            .collab(collab)
            .clipboard(clipboard)
            .show(ui)
    })
}

fn history_view(
    env: &Env<'_>,
    heads: &[gantz_ca::Head],
    focused_head: usize,
    ui: &mut egui::Ui,
) -> egui::InnerResponse<widget::graph_select::GraphSelectResponse> {
    pane_ui(ui, |ui| {
        widget::HistoryView::new(env, heads)
            .focused_head(focused_head)
            .show(ui)
    })
}

fn perf_view(title: &str, capture: &mut widget::PerfCapture, ui: &mut egui::Ui) {
    // Use Frame::NONE to fill the entire pane with no padding.
    egui::CentralPanel::default()
        .frame(egui::Frame::NONE)
        .show_inside(ui, |ui| {
            widget::PerfView::new(title, capture).show(ui);
        });
}

/// Returns the response from the graph scene if it was shown.
///
/// Payloads emitted within the scene are returned in
/// [`GraphSceneResponse::responses`][graph_scene::GraphSceneResponse] for the
/// caller to tag and merge.
#[allow(clippy::too_many_arguments)]
fn graph_scene(
    registry: &Env<'_>,
    codec: &NodeCodec,
    graph: &mut gantz_ca::DataGraph,
    instances: &mut crate::node::NodeInstances,
    head: &gantz_ca::Head,
    head_state: &mut OpenHeadState,
    view_toggles: &mut ViewToggles,
    ext_panes: &[widget::ExtPaneEntry],
    edge_styles: &[&dyn widget::EdgeStyle],
    head_view: &mut crate::SceneView,
    layout_params: egui_graph::LayoutParams,
    scene_config: SceneConfig,
    immutable: bool,
    validate_change_tracking: bool,
    keymap: &Keymap,
    diagnostics: &[gantz_core::Diagnostic],
    vm: &mut Engine,
    ui: &mut egui::Ui,
) -> Option<graph_scene::GraphSceneResponse> {
    // A head shows exactly its root graph (nested graphs are separate heads).
    let id = egui::Id::new(head);

    // Select-all: replace the selection with every node. Handled here (not the
    // outer command block) because this is where the graph is in scope. Gated
    // like other command shortcuts so it does not fire while typing.
    if !ui.ctx().egui_wants_keyboard_input() && keymap.consume(ui, Action::SelectAll) {
        head_state.scene.interaction.selection.nodes = graph.node_indices().collect();
        head_state.scene.interaction.selection.edges.clear();
    }

    // Seed the node layout the first time this graph is shown, and centre the
    // camera on it at zoom 1. Without an explicit camera the scene would fall
    // back to egui's fit-to-bounds, zooming out to frame every node; a freshly
    // opened graph should instead sit at its natural 1:1 zoom.
    if head_view.layout.is_empty() {
        head_view.layout =
            widget::graph_scene::layout(registry, codec, graph, id, &layout_params, ui.ctx(), None);
        let mut bounds: Option<egui::Rect> = None;
        for &pos in head_view.layout.values() {
            let r = egui::Rect::from_min_size(pos, egui::Vec2::ZERO);
            bounds = Some(bounds.map_or(r, |b| b.union(r)));
        }
        head_view.camera = crate::Camera {
            center: bounds.map_or(egui::Pos2::ZERO, |b| b.center()),
            zoom: 1.0,
        };
    }

    let response = GraphScene::new(registry, codec, graph, instances)
        .with_id(id)
        .layout_params(layout_params)
        .scene_config(scene_config)
        .immutable(immutable)
        .validate_change_tracking(validate_change_tracking)
        .view_toggles(view_toggles)
        .ext_panes(ext_panes)
        .edge_styles(head, edge_styles)
        .show(head_view, &mut head_state.scene, vm, ui);

    graph_scene::paint_diagnostics(diagnostics, &[], &response, ui);

    Some(response)
}

/// Floating name breadcrumb over the bottom-left corner of the scene, shown
/// when viewing a nested graph (a `parent:child` head). Each crumb is a
/// `:`-separated name segment; the prefix it represents is the head it
/// navigates to.
///
/// Returns the [`ReplaceHead`] payloads emitted by clicked crumbs, which
/// navigate the focused tab to an ancestor level in place.
fn name_breadcrumb(
    scene_rect: egui::Rect,
    head: &gantz_ca::Head,
    ui: &mut egui::Ui,
) -> Vec<DynResponse> {
    let mut responses = Vec::new();
    let gantz_ca::Head::Branch(name) = head else {
        return responses;
    };
    if !name.is_nested() {
        return responses; // a root graph has no ancestor levels
    }
    let segs: Vec<&str> = name.segments().iter().map(|s| s.as_str()).collect();
    let sep_str = gantz_ca::name::SEP.to_string();
    let space = ui.style().interaction.interact_radius * 3.0;
    // Sit to the right of the floating sidebar toggle, which occupies the very
    // bottom-left corner of the scene, so the levels stay on the bottom row.
    let toggle_w = SIDEBAR_TOGGLE_ICON_SIZE + ui.style().spacing.item_spacing.x;
    egui::Window::new("breadcrumb_window")
        .pivot(egui::Align2::LEFT_BOTTOM)
        .fixed_pos(scene_rect.left_bottom() + egui::vec2(space + toggle_w, -space))
        .title_bar(false)
        .resizable(false)
        .collapsible(false)
        .frame(egui::Frame::NONE)
        .show(ui.ctx(), |ui| {
            fn button(s: &str) -> widget::LabelButton {
                let text = egui::RichText::new(s).size(24.0);
                widget::LabelButton::new(text)
            }
            let col_w = ui.style().interaction.interact_radius * 4.0;
            egui::Grid::new("breadcrumb")
                .min_col_width(col_w)
                .max_col_width(col_w)
                .show(ui, |ui| {
                    for (i, seg) in segs.iter().enumerate() {
                        let is_current = i + 1 == segs.len();
                        let prefix = segs[..=i].join(&sep_str);
                        // The crumbs are tiny: the root is `R` (its name is too
                        // big to fit), and each nested level is its short leaf.
                        let (label, hover) = if i == 0 {
                            ("R".to_string(), format!("navigate to {seg} root"))
                        } else {
                            (seg.to_string(), format!("navigate to {prefix}"))
                        };
                        ui.vertical_centered_justified(|ui| {
                            let resp = ui.add(button(&label)).on_hover_text(hover);
                            if resp.clicked() && !is_current {
                                responses.push(DynResponse::new(ReplaceHead(
                                    gantz_ca::Head::Branch(prefix.parse().expect("infallible")),
                                )));
                            }
                        });
                    }
                })
        });
    responses
}

/// A node-creation choice made in the node palette.
enum PaletteChoice {
    /// Create an ordinary node of the given type.
    Node(CreateNode),
    /// Create a new nested graph (the reserved [`NESTED_GRAPH_TYPE`] entry).
    NestedGraph(CreateNestedGraph),
}

/// Returns a node-creation payload when a node type is chosen.
///
/// `editing` is the focused head's name (when it is a branch), used to hide node
/// types whose reference would cycle back to the graph being edited.
fn node_palette(
    env: &Env<'_>,
    editing: Option<&str>,
    node_palette: &mut widget::NodePalette,
    keymap: &Keymap,
    ui: &mut egui::Ui,
) -> Option<PaletteChoice> {
    // Toggle node palette visibility via its keymap binding.
    if !ui.ctx().egui_wants_keyboard_input() && keymap.consume(ui, Action::ToggleNodePalette) {
        node_palette.toggle();
    }

    // Map the node types to commands for the node palette, dropping any type
    // whose reference would form a cycle back to the editing graph. The reserved
    // nested-graph entry always mints a fresh child, so it is never cyclic.
    let types: Vec<&str> = env
        .node_types()
        .into_iter()
        .filter(|&k| k == NESTED_GRAPH_TYPE || editing.is_none_or(|e| !env.would_ref_cycle(k, e)))
        .collect();
    let cmds = types.iter().map(|&k| NodeTyCmd { env, name: k });

    // The chosen node type becomes a creation payload. The reserved
    // `NESTED_GRAPH_TYPE` routes to the registry-aware nested-graph op. The
    // palette is centered over the graph scene (this `ui`'s rect).
    let scene_rect = ui.max_rect();
    node_palette.show(ui.ctx(), scene_rect, cmds).map(|cmd| {
        // The placement position is filled in by the caller, which has access to
        // the focused head's last pointer position.
        if cmd.name == NESTED_GRAPH_TYPE {
            PaletteChoice::NestedGraph(CreateNestedGraph { pos: None })
        } else {
            PaletteChoice::Node(CreateNode {
                node_type: cmd.name.to_string(),
                pos: None,
            })
        }
    })
}

fn log_view(
    logger: &widget::log_view::Logger,
    node_labels: &HashMap<Vec<node::Id>, String>,
    ui: &mut egui::Ui,
) -> egui::InnerResponse<widget::log_view::LogViewResponse> {
    pane_ui(ui, |ui| {
        widget::log_view::LogView::new("log-view".into(), logger.clone())
            .node_labels(node_labels)
            .show(ui)
    })
}

fn trace_view(
    trace_capture: &widget::trace_view::TraceCapture,
    level: tracing::level_filters::LevelFilter,
    ui: &mut egui::Ui,
) -> egui::InnerResponse<()> {
    pane_ui(ui, |ui| {
        widget::trace_view::TraceView::new("trace-view".into(), trace_capture.clone(), level)
            .show(ui);
    })
}

/// Whether the given head should be treated as immutable.
///
/// A head is immutable when `base_immutable` is enabled and the head is a base
/// graph that is not a demo (demo base graphs are always mutable so users can
/// experiment).
fn head_immutable(
    head: &gantz_ca::Head,
    base_immutable: bool,
    base_names: &crate::reg::Names,
) -> bool {
    let is_base = matches!(head, gantz_ca::Head::Branch(name) if base_names.contains_key(name));
    let is_demo =
        matches!(head, gantz_ca::Head::Branch(name) if widget::graph_select::is_demo(name));
    base_immutable && is_base && !is_demo
}

/// Returns whether any inspected node had a CA-affecting edit, together with
/// the payloads emitted by node UIs within the inspector.
#[allow(clippy::too_many_arguments)]
fn node_inspector<'a>(
    registry: &'a Env<'a>,
    codec: &NodeCodec,
    root: &mut gantz_ca::DataGraph,
    instances: &mut crate::node::NodeInstances,
    vm: &mut Engine,
    head_state: &mut OpenHeadState,
    head: &gantz_ca::Head,
    immutable: bool,
    ref_ext_uis: &'a [&'a dyn crate::node::RefExtUi],
    ui: &mut egui::Ui,
) -> egui::InnerResponse<(bool, Vec<DynResponse>)> {
    pane_ui(ui, |ui| {
        let mut responses = Vec::new();
        let mut changed = false;
        egui::ScrollArea::vertical()
            .auto_shrink(egui::Vec2b::FALSE)
            .show(ui, |ui| {
                let graph = &mut *root;
                let ids: Vec<_> = graph.node_identifiers().collect();
                // Collect the inlets and outlets.
                let (inlets, outlets) = crate::inlet_outlet_ids(registry, graph);
                // The rect of the first selected node, used to scroll to it.
                let mut selected_rect: Option<egui::Rect> = None;
                // VM-state writes recorded by each node's `NodeCtx` (drained
                // per node into `StateWritten` payloads).
                let mut writes = Vec::new();
                for id in ids {
                    let mut frame = egui::Frame::group(ui.style());
                    let is_selected = head_state.scene.interaction.selection.nodes.contains(&id);
                    if is_selected {
                        frame.stroke.color = ui.visuals().selection.stroke.color;
                    }
                    let frame_resp = frame.show(ui, |ui| {
                        let Some(weight) = graph.node_weight(id) else {
                            return;
                        };
                        let ix = id.index();
                        // Take the node's cached instance (see
                        // `graph_scene::nodes`); erase back below iff changed,
                        // updating the witness. An unknown tag shows a weak
                        // placeholder row.
                        let Ok(mut entry) = instances.take(codec, ix, weight) else {
                            ui.weak(format!("{} (unknown node type)", weight.tag));
                            return;
                        };
                        let path = [ix];
                        let ctx = NodeCtx::new(
                            registry,
                            &path[..],
                            &inlets,
                            &outlets,
                            ref_ext_uis,
                            vm,
                            &mut writes,
                        );
                        let resp = widget::NodeInspector::new(&mut entry.inst.node, ctx, immutable)
                            .show(ui);
                        if resp.changed {
                            changed = true;
                            match entry.inst.erase() {
                                Ok(node_data) => {
                                    entry.src = node_data.clone();
                                    graph[id] = node_data;
                                    instances.put(ix, entry);
                                }
                                Err(e) => log::error!(
                                    "inspector: failed to erase edited node {ix}, \
                                     edit dropped: {e}"
                                ),
                            }
                        } else {
                            instances.put(ix, entry);
                        }
                        responses.extend(resp.payloads);
                        if resp.label_response.clicked() {
                            let sel = &mut head_state.scene.interaction.selection.nodes;
                            if ui.input(|i| i.modifiers.command) {
                                if !sel.remove(&id) {
                                    sel.insert(id);
                                }
                            } else {
                                sel.clear();
                                sel.insert(id);
                            }
                        }
                    });
                    responses.extend(crate::action::state_written(&mut writes));
                    if is_selected && selected_rect.is_none() {
                        selected_rect = Some(frame_resp.response.rect);
                    }
                }

                // Scroll to the first selected node when the selection changes,
                // mirroring the Steel view's scroll-to-span on selection.
                let state_id = egui::Id::new("node_inspector_selection");
                let mut selected: Vec<node::Id> = head_state
                    .scene
                    .interaction
                    .selection
                    .nodes
                    .iter()
                    .map(|n| n.index())
                    .collect();
                selected.sort_unstable();
                let current = egui::Id::new(("inspector_sel", head, &selected));
                let prev: Option<egui::Id> = ui.ctx().data(|d| d.get_temp(state_id));
                if prev != Some(current) {
                    ui.ctx().data_mut(|d| d.insert_temp(state_id, current));
                    if let Some(rect) = selected_rect {
                        ui.scroll_to_rect(rect, Some(egui::Align::Center));
                    }
                }
            });
        (changed, responses)
    })
}

fn steel_view(
    compiled_steel: &str,
    compile_error: Option<&str>,
    highlights: &[std::ops::Range<usize>],
    errors: &[std::ops::Range<usize>],
    scroll_to: Option<usize>,
    ui: &mut egui::Ui,
) -> egui::InnerResponse<()> {
    pane_ui(ui, |ui| {
        egui::ScrollArea::vertical()
            .auto_shrink(egui::Vec2b::FALSE)
            .show(ui, |ui| {
                if let Some(error) = compile_error {
                    let color = ui.visuals().error_fg_color;
                    let text = egui::RichText::new(error).monospace().color(color);
                    ui.add(egui::Label::new(text).selectable(true));
                    if !compiled_steel.is_empty() {
                        ui.separator();
                    }
                }
                widget::SteelView::new(compiled_steel)
                    .highlights(highlights)
                    .errors(errors)
                    .scroll_to(scroll_to)
                    .show(ui);
            });
    })
}

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

    /// The fixed sidebar width must be imposed on the sidebar (left column),
    /// not the main area, and the anchors must identify the sidebar as the
    /// column that does not contain the graph scene.
    #[test]
    fn impose_sets_sidebar_width_on_left_column() {
        let mut tree = create_tree();
        let anchors = layout_anchors(&tree).expect("default tree has layout anchors");

        let graph_scene = tree.tiles.find_pane(&Pane::GraphScene).unwrap();
        assert_ne!(anchors.left_column, anchors.right_column);
        assert_eq!(
            tree.tiles.parent_of(graph_scene),
            Some(anchors.right_column)
        );

        let mut state = GantzState::new();
        state.view_toggles.sidebar_open = true;
        state.sidebar_width = 240.0;
        let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0));
        impose_fixed_sizes(&mut tree, &state, area);

        let Some(egui_tiles::Container::Linear(root)) = tree.tiles.get_container(anchors.root)
        else {
            panic!("root is not a linear container");
        };
        let avail = 1000.0 - TILE_GAP;
        // The sidebar gets the fixed width; the main area gets the remainder.
        assert!((root.shares[anchors.left_column] - 240.0).abs() < 0.01);
        assert!((root.shares[anchors.right_column] - (avail - 240.0)).abs() < 0.01);
    }

    /// `capture_fixed_sizes` must recover the same width `impose_fixed_sizes`
    /// set, so a sidebar that isn't dragged doesn't drift frame to frame.
    #[test]
    fn capture_round_trips_imposed_sidebar_width() {
        let mut tree = create_tree();
        let mut state = GantzState::new();
        state.view_toggles.sidebar_open = true;
        state.sidebar_width = 240.0;
        let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0));
        impose_fixed_sizes(&mut tree, &state, area);
        capture_fixed_sizes(&tree, &mut state, area);
        assert!((state.sidebar_width - 240.0).abs() < 0.01);
    }

    /// Reopening the sidebar must not inflate its width. On the open-transition
    /// frame `sidebar_open` is already true but the layout still has the left
    /// column hidden; capturing then would size it against the wrong siblings.
    #[test]
    fn capture_skips_while_sidebar_laid_out_hidden() {
        let mut tree = create_tree();
        let anchors = layout_anchors(&tree).unwrap();
        // Layout state: sidebar hidden (as at frame start)...
        tree.set_visible(anchors.left_column, false);
        let mut state = GantzState::new();
        // ...but `sidebar_open` was just toggled on mid-frame.
        state.view_toggles.sidebar_open = true;
        state.sidebar_width = 240.0;
        let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0));
        capture_fixed_sizes(&tree, &mut state, area);
        assert!((state.sidebar_width - 240.0).abs() < 0.01);
    }

    fn node_view(head: &str, path: &[node::Id]) -> Pane {
        Pane::NodeView(NodeViewPane {
            head: gantz_ca::Head::Branch(head.parse().unwrap()),
            path: path.to_vec(),
            ty_name: "plot".to_string(),
        })
    }

    /// Pane identity keys are stable per pane and independent of a node view's
    /// `ty_name` (two views of the same node are the same identity).
    #[test]
    fn pane_key_identity() {
        assert_eq!(pane_key(&Pane::Logs), "logs");
        assert_ne!(pane_key(&Pane::Logs), pane_key(&Pane::Steel));

        let plot = node_view("main", &[3]);
        let same_node_number = Pane::NodeView(NodeViewPane {
            head: gantz_ca::Head::Branch("main".parse().unwrap()),
            path: vec![3],
            ty_name: "number".to_string(),
        });
        assert_eq!(pane_key(&plot), pane_key(&same_node_number));
        assert_ne!(pane_key(&plot), pane_key(&node_view("main", &[4])));
        assert_ne!(pane_key(&plot), pane_key(&node_view("other", &[3])));
    }

    /// `push_windowed` dedupes by pane identity, so a repeated pop-out (or a
    /// same-node view with a different `ty_name`) does not add a second entry.
    #[test]
    fn push_windowed_dedupes() {
        let mut windowed = Vec::new();
        push_windowed(&mut windowed, Pane::Logs);
        push_windowed(&mut windowed, Pane::Logs);
        push_windowed(&mut windowed, node_view("main", &[3]));
        push_windowed(
            &mut windowed,
            Pane::NodeView(NodeViewPane {
                head: gantz_ca::Head::Branch("main".parse().unwrap()),
                path: vec![3],
                ty_name: "number".to_string(),
            }),
        );
        assert_eq!(windowed.len(), 2);
    }

    /// After a node removal, a windowed view of the removed node is dropped and a
    /// view of a swapped node has its path rewritten; other heads and non-view
    /// panes are untouched.
    #[test]
    fn migrate_windowed_node_views_drops_and_rewrites() {
        let head = gantz_ca::Head::Branch("main".parse().unwrap());
        let mut windowed = vec![
            node_view("main", &[1]),  // removed node -> dropped
            node_view("main", &[3]),  // swapped 3 -> 1
            node_view("main", &[2]),  // unaffected
            node_view("other", &[1]), // different head -> untouched
            Pane::Logs,               // non-view -> untouched
        ];
        // Node 1 removed; the node that was at index 3 swapped down into slot 1.
        let reindex = crate::ops::Reindex(vec![crate::ops::RemoveOp {
            removed: 1,
            moved_from: Some(3),
        }]);
        migrate_windowed_node_views(&mut windowed, &head, &reindex);

        let main_paths: Vec<Vec<node::Id>> = windowed
            .iter()
            .filter_map(|p| match p {
                Pane::NodeView(nv) if nv.head == head => Some(nv.path.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(main_paths, vec![vec![1], vec![2]]);
        assert!(windowed.iter().any(|p| matches!(p, Pane::Logs)));
        assert!(
            windowed
                .iter()
                .any(|p| matches!(p, Pane::NodeView(nv) if matches!(&nv.head, gantz_ca::Head::Branch(n) if n.to_string() == "other")))
        );
        assert_eq!(windowed.len(), 4);
    }
}