neovm-core 0.0.1

Core runtime structures for NeoVM
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
//! Window and frame management for the editor.
//!
//! Implements the Emacs window tree model:
//! - A **frame** contains a root window (which may be split).
//! - A **window** is either a *leaf* (displays a buffer) or an *internal*
//!   node with children (horizontal or vertical split).
//! - The **selected window** is the one receiving input.
//! - The **minibuffer window** is a special single-line window at the bottom.

use crate::buffer::BufferId;
use crate::emacs_core::value::{HashTableTest, Value};
use crate::face::Face as RuntimeFace;
use crate::gc_trace::GcTrace;
use std::collections::{HashMap, HashSet};

mod display;
mod history;
mod parameters;

pub use display::WindowBufferDisplayDefaults;

// ---------------------------------------------------------------------------
// IDs
// ---------------------------------------------------------------------------

/// Opaque window identifier.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct WindowId(pub u64);

/// Opaque frame identifier.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FrameId(pub u64);

/// Keep frame and window numeric domains disjoint while both are represented
/// as Lisp integers.
pub(crate) const FRAME_ID_BASE: u64 = 1 << 32;
/// Synthetic window-id domain reserved for per-frame minibuffer windows.
pub(crate) const MINIBUFFER_WINDOW_ID_BASE: u64 = 1 << 48;

// ---------------------------------------------------------------------------
// Window geometry
// ---------------------------------------------------------------------------

/// Pixel-based rectangle for window placement.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

impl Rect {
    pub fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    pub fn right(&self) -> f32 {
        self.x + self.width
    }

    pub fn bottom(&self) -> f32 {
        self.y + self.height
    }

    pub fn contains(&self, px: f32, py: f32) -> bool {
        px >= self.x && px < self.right() && py >= self.y && py < self.bottom()
    }
}

// ---------------------------------------------------------------------------
// Split direction
// ---------------------------------------------------------------------------

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SplitDirection {
    Horizontal, // side by side
    Vertical,   // stacked
}

// ---------------------------------------------------------------------------
// Window display state
// ---------------------------------------------------------------------------

/// Per-window display settings that GNU Emacs stores on `struct window`.
#[derive(Clone, Debug)]
pub struct WindowDisplayState {
    /// Window-local display table; nil means inherit from the buffer/frame.
    pub display_table: Value,
    /// Window-local cursor type; t means use the buffer-local value.
    pub cursor_type: Value,
    /// Raw fringe widths; `-1` means use the frame default.
    pub left_fringe_width: i32,
    pub right_fringe_width: i32,
    pub fringes_outside_margins: bool,
    pub fringes_persistent: bool,
    /// Raw scroll bar sizes; `-1` means use the frame default.
    pub scroll_bar_width: i32,
    pub vertical_scroll_bar_type: Value,
    pub scroll_bar_height: i32,
    pub horizontal_scroll_bar_type: Value,
    pub scroll_bars_persistent: bool,
}

impl Default for WindowDisplayState {
    fn default() -> Self {
        Self {
            display_table: Value::NIL,
            cursor_type: Value::T,
            left_fringe_width: -1,
            right_fringe_width: -1,
            fringes_outside_margins: false,
            fringes_persistent: false,
            scroll_bar_width: -1,
            vertical_scroll_bar_type: Value::T,
            scroll_bar_height: -1,
            horizontal_scroll_bar_type: Value::T,
            scroll_bars_persistent: false,
        }
    }
}

/// Live-window history state that GNU Emacs stores directly on `struct window`.
#[derive(Clone, Debug)]
pub struct WindowHistoryState {
    pub prev_buffers: Value,
    pub next_buffers: Value,
    pub use_time: i64,
}

impl Default for WindowHistoryState {
    fn default() -> Self {
        Self {
            prev_buffers: Value::NIL,
            next_buffers: Value::NIL,
            use_time: 0,
        }
    }
}

pub(crate) type WindowParameters = Vec<(Value, Value)>;

// ---------------------------------------------------------------------------
// Window
// ---------------------------------------------------------------------------

/// A window in the window tree.
#[derive(Clone, Debug)]
pub enum Window {
    /// Leaf window displaying a buffer.
    Leaf {
        id: WindowId,
        buffer_id: BufferId,
        /// Pixel bounds within the frame.
        bounds: Rect,
        /// Character position of the first visible character.
        window_start: usize,
        /// Offset of the last displayed character position from buffer `Z`.
        ///
        /// Mirrors GNU Emacs `w->window_end_pos`, so Lisp-visible
        /// `window-end` can continue to track buffer growth/shrinkage even
        /// between redisplays.
        window_end_pos: usize,
        /// Offset of the last displayed byte position from buffer `Z_BYTE`.
        ///
        /// This is the byte-position companion to `window_end_pos`.
        window_end_bytepos: usize,
        /// Visual row that produced `window_end_pos`.
        window_end_vpos: usize,
        /// Whether the last completed redisplay recorded window-end state.
        window_end_valid: bool,
        /// Cursor (point) position in this window.
        point: usize,
        /// Previous point value mirrored from GNU `w->old_pointm`.
        old_point: usize,
        /// Whether this is a dedicated window.
        dedicated: bool,
        /// Lisp-visible per-window parameter alist, newest entries first.
        parameters: WindowParameters,
        /// Live-window history state mirrored from GNU `struct window`.
        history: WindowHistoryState,
        /// Desired height in lines (for fixed windows, 0 = flexible).
        fixed_height: usize,
        /// Desired width in columns (for fixed windows, 0 = flexible).
        fixed_width: usize,
        /// Horizontal scroll offset (columns).
        hscroll: usize,
        /// Raw GNU `w->vscroll` value in pixels: zero or negative.
        ///
        /// Lisp-visible `window-vscroll` reports `-vscroll`, either in pixels
        /// or in canonical line units depending on the call site.
        vscroll: i32,
        /// Mirrors GNU `w->preserve_vscroll_p`.
        preserve_vscroll_p: bool,
        /// Window margins (left, right) in columns.
        margins: (usize, usize),
        /// Window-local display settings mirrored from GNU `struct window`.
        display: WindowDisplayState,
    },

    /// Internal node: contains children split in a direction.
    Internal {
        id: WindowId,
        direction: SplitDirection,
        children: Vec<Window>,
        bounds: Rect,
        /// Lisp-visible per-window parameter alist, newest entries first.
        parameters: WindowParameters,
        /// Combination limit — prevents recombination when non-nil.
        /// Mirrors GNU Emacs `w->combination_limit`.
        combination_limit: bool,
    },
}

impl Window {
    /// Create a new leaf window.
    pub fn new_leaf(id: WindowId, buffer_id: BufferId, bounds: Rect) -> Self {
        Window::Leaf {
            id,
            buffer_id,
            bounds,
            window_start: 1,
            window_end_pos: 0,
            window_end_bytepos: 0,
            window_end_vpos: 0,
            window_end_valid: false,
            point: 1,
            old_point: 1,
            dedicated: false,
            parameters: Vec::new(),
            history: WindowHistoryState::default(),
            fixed_height: 0,
            fixed_width: 0,
            hscroll: 0,
            vscroll: 0,
            preserve_vscroll_p: false,
            margins: (0, 0),
            display: WindowDisplayState::default(),
        }
    }

    /// Window ID.
    pub fn id(&self) -> WindowId {
        match self {
            Window::Leaf { id, .. } | Window::Internal { id, .. } => *id,
        }
    }

    /// Pixel bounds.
    pub fn bounds(&self) -> &Rect {
        match self {
            Window::Leaf { bounds, .. } | Window::Internal { bounds, .. } => bounds,
        }
    }

    /// Mutable reference to bounds.
    pub fn bounds_mut(&mut self) -> &mut Rect {
        match self {
            Window::Leaf { bounds, .. } | Window::Internal { bounds, .. } => bounds,
        }
    }

    /// Set bounds.
    pub fn set_bounds(&mut self, new_bounds: Rect) {
        match self {
            Window::Leaf { bounds, .. } | Window::Internal { bounds, .. } => {
                *bounds = new_bounds;
            }
        }
    }

    /// Whether this is a leaf window.
    pub fn is_leaf(&self) -> bool {
        matches!(self, Window::Leaf { .. })
    }

    /// Return this leaf window's display state.
    pub fn display(&self) -> Option<&WindowDisplayState> {
        match self {
            Window::Leaf { display, .. } => Some(display),
            Window::Internal { .. } => None,
        }
    }

    /// Return a mutable reference to this leaf window's display state.
    pub fn display_mut(&mut self) -> Option<&mut WindowDisplayState> {
        match self {
            Window::Leaf { display, .. } => Some(display),
            Window::Internal { .. } => None,
        }
    }

    /// Return this window's Lisp-visible parameter alist.
    pub fn parameters(&self) -> &WindowParameters {
        match self {
            Window::Leaf { parameters, .. } | Window::Internal { parameters, .. } => parameters,
        }
    }

    /// Return a mutable reference to this window's Lisp-visible parameter alist.
    pub fn parameters_mut(&mut self) -> &mut WindowParameters {
        match self {
            Window::Leaf { parameters, .. } | Window::Internal { parameters, .. } => parameters,
        }
    }

    /// Return this live window's history state.
    pub fn history(&self) -> Option<&WindowHistoryState> {
        match self {
            Window::Leaf { history, .. } => Some(history),
            Window::Internal { .. } => None,
        }
    }

    /// Return a mutable reference to this live window's history state.
    pub fn history_mut(&mut self) -> Option<&mut WindowHistoryState> {
        match self {
            Window::Leaf { history, .. } => Some(history),
            Window::Internal { .. } => None,
        }
    }

    /// Get the combination limit for an internal window.
    pub fn combination_limit(&self) -> Option<bool> {
        match self {
            Window::Internal {
                combination_limit, ..
            } => Some(*combination_limit),
            Window::Leaf { .. } => None,
        }
    }

    /// Set the combination limit for an internal window.
    pub fn set_combination_limit(&mut self, limit: bool) {
        if let Window::Internal {
            combination_limit, ..
        } = self
        {
            *combination_limit = limit;
        }
    }

    /// Buffer displayed in this window (leaf only).
    pub fn buffer_id(&self) -> Option<BufferId> {
        match self {
            Window::Leaf { buffer_id, .. } => Some(*buffer_id),
            Window::Internal { .. } => None,
        }
    }

    /// Set the buffer displayed in this window (leaf only).
    pub fn set_buffer(&mut self, new_id: BufferId) {
        if let Window::Leaf {
            buffer_id,
            window_start,
            window_end_pos,
            window_end_bytepos,
            window_end_vpos,
            window_end_valid,
            point,
            ..
        } = self
        {
            *buffer_id = new_id;
            // Emacs positions are 1-based; switching the displayed buffer resets
            // window-start/point to point-min.
            *window_start = 1;
            *window_end_pos = 0;
            *window_end_bytepos = 0;
            *window_end_vpos = 0;
            *window_end_valid = false;
            *point = 1;
        }
    }

    /// Stored Lisp-visible `window-end` for this leaf window.
    pub fn window_end_charpos(&self, buffer_z: usize) -> Option<usize> {
        match self {
            Window::Leaf { window_end_pos, .. } => Some(buffer_z.saturating_sub(*window_end_pos)),
            Window::Internal { .. } => None,
        }
    }

    /// Stored byte-position `window-end` for this leaf window.
    pub fn window_end_bytepos(&self, buffer_z_byte: usize) -> Option<usize> {
        match self {
            Window::Leaf {
                window_end_bytepos, ..
            } => Some(buffer_z_byte.saturating_sub(*window_end_bytepos)),
            Window::Internal { .. } => None,
        }
    }

    /// Whether the stored window-end came from a completed redisplay.
    pub fn window_end_valid(&self) -> Option<bool> {
        match self {
            Window::Leaf {
                window_end_valid, ..
            } => Some(*window_end_valid),
            Window::Internal { .. } => None,
        }
    }

    /// Publish the last redisplay's window-end state for this leaf window.
    pub fn set_window_end_from_positions(
        &mut self,
        buffer_z_char: usize,
        buffer_z_byte: usize,
        end_charpos: usize,
        end_bytepos: usize,
        vpos: usize,
    ) {
        if let Window::Leaf {
            window_end_pos,
            window_end_bytepos,
            window_end_vpos,
            window_end_valid,
            ..
        } = self
        {
            *window_end_pos = buffer_z_char.saturating_sub(end_charpos.min(buffer_z_char));
            *window_end_bytepos = buffer_z_byte.saturating_sub(end_bytepos.min(buffer_z_byte));
            *window_end_vpos = vpos;
            *window_end_valid = true;
        }
    }

    /// Replace a displayed buffer id in all leaf windows under this node.
    ///
    /// This is used when a buffer is killed; any window still attached to the
    /// dead buffer is moved back to a replacement buffer (typically `*scratch*`).
    pub fn replace_buffer_id(&mut self, old_id: BufferId, new_id: BufferId) {
        match self {
            Window::Leaf { buffer_id, .. } => {
                if *buffer_id == old_id {
                    self.set_buffer(new_id);
                }
            }
            Window::Internal { children, .. } => {
                for child in children {
                    child.replace_buffer_id(old_id, new_id);
                }
            }
        }
    }

    /// Find a leaf window by ID in this subtree.
    pub fn find(&self, target: WindowId) -> Option<&Window> {
        if self.id() == target {
            return Some(self);
        }
        if let Window::Internal { children, .. } = self {
            for child in children {
                if let Some(w) = child.find(target) {
                    return Some(w);
                }
            }
        }
        None
    }

    /// Find a mutable leaf window by ID in this subtree.
    pub fn find_mut(&mut self, target: WindowId) -> Option<&mut Window> {
        if self.id() == target {
            return Some(self);
        }
        if let Window::Internal { children, .. } = self {
            for child in children {
                if let Some(w) = child.find_mut(target) {
                    return Some(w);
                }
            }
        }
        None
    }

    /// Collect all leaf window IDs.
    pub fn leaf_ids(&self) -> Vec<WindowId> {
        let mut result = Vec::new();
        self.collect_leaves(&mut result);
        result
    }

    fn collect_leaves(&self, out: &mut Vec<WindowId>) {
        match self {
            Window::Leaf { id, .. } => out.push(*id),
            Window::Internal { children, .. } => {
                for child in children {
                    child.collect_leaves(out);
                }
            }
        }
    }

    /// Find the window at pixel coordinates.
    pub fn window_at(&self, px: f32, py: f32) -> Option<WindowId> {
        match self {
            Window::Leaf { id, bounds, .. } => {
                if bounds.contains(px, py) {
                    Some(*id)
                } else {
                    None
                }
            }
            Window::Internal {
                children, bounds, ..
            } => {
                if !bounds.contains(px, py) {
                    return None;
                }
                for child in children {
                    if let Some(id) = child.window_at(px, py) {
                        return Some(id);
                    }
                }
                None
            }
        }
    }

    /// Count leaf windows in this subtree.
    pub fn leaf_count(&self) -> usize {
        match self {
            Window::Leaf { .. } => 1,
            Window::Internal { children, .. } => children.iter().map(|c| c.leaf_count()).sum(),
        }
    }

    /// Invalidate redisplay-derived window-end state for this subtree.
    pub fn invalidate_display_state(&mut self) {
        match self {
            Window::Leaf {
                window_end_valid, ..
            } => {
                *window_end_valid = false;
            }
            Window::Internal { children, .. } => {
                for child in children {
                    child.invalidate_display_state();
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Last Display Snapshot
// ---------------------------------------------------------------------------

/// Authoritative glyph geometry for a single visible buffer position.
///
/// These records are published by redisplay after layout so editor-side
/// queries like `posn-at-point` can answer from the actual rendered result.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DisplayPointSnapshot {
    /// 1-based buffer position of the source character.
    pub buffer_pos: usize,
    /// X relative to the text area's left edge, in pixels.
    pub x: i64,
    /// Y relative to the window's top edge, in pixels.
    pub y: i64,
    /// Rendered advance/width in pixels.
    pub width: i64,
    /// Rendered glyph height in pixels.
    pub height: i64,
    /// Visual row number in the window (0-based).
    pub row: i64,
    /// Visual column start for this source position.
    pub col: i64,
}

/// Per-row metrics from the last redisplay of a window.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DisplayRowSnapshot {
    /// Visual row number in the window (0-based).
    pub row: i64,
    /// Y relative to the window's top edge, in pixels.
    pub y: i64,
    /// Row height in pixels.
    pub height: i64,
    /// First buffer position represented on this row, if any.
    pub start_buffer_pos: Option<usize>,
    /// Last visible/source position associated with this row, if any.
    pub end_buffer_pos: Option<usize>,
}

/// Last authoritative redisplay geometry for a live leaf window.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WindowDisplaySnapshot {
    /// Window identifier this snapshot belongs to.
    pub window_id: WindowId,
    /// Text-area offset from the window's left edge, in pixels.
    pub text_area_left_offset: i64,
    /// Last redisplay mode-line height in pixels.
    pub mode_line_height: i64,
    /// Last redisplay header-line height in pixels.
    pub header_line_height: i64,
    /// Last redisplay tab-line height in pixels.
    pub tab_line_height: i64,
    /// Visible source-position geometry, sorted by `buffer_pos`.
    pub points: Vec<DisplayPointSnapshot>,
    /// Visible row metrics, sorted by `row`.
    pub rows: Vec<DisplayRowSnapshot>,
}

impl WindowDisplaySnapshot {
    pub fn visible_buffer_span(&self) -> Option<(usize, usize)> {
        let start = self
            .rows
            .iter()
            .find_map(|row| row.start_buffer_pos)
            .or_else(|| self.points.first().map(|point| point.buffer_pos))?;
        let end = self
            .rows
            .iter()
            .rev()
            .find_map(|row| row.end_buffer_pos)
            .or_else(|| self.points.last().map(|point| point.buffer_pos))?;
        Some((start, end))
    }

    fn row_for_buffer_pos(&self, pos: usize) -> Option<&DisplayRowSnapshot> {
        self.rows.iter().find(|row| {
            let Some(start) = row.start_buffer_pos else {
                return false;
            };
            let Some(end) = row.end_buffer_pos else {
                return false;
            };
            start <= pos && pos <= end
        })
    }

    /// Return the visible point for POS, or the nearest visible neighbor when
    /// POS itself is hidden by redisplay within the visible span.
    ///
    /// Off-window positions return `None`, matching GNU Emacs `posn-at-point`
    /// and `pos-visible-in-window-p` semantics.
    pub fn point_for_buffer_pos(&self, pos: usize) -> Option<&DisplayPointSnapshot> {
        if self.points.is_empty() {
            return None;
        }
        let (visible_start, visible_end) = self.visible_buffer_span()?;
        if pos < visible_start || pos > visible_end {
            return None;
        }
        match self
            .points
            .binary_search_by_key(&pos, |point| point.buffer_pos)
        {
            Ok(idx) => self.points.get(idx),
            Err(_) => {
                let row = self.row_for_buffer_pos(pos)?;
                let next_on_row = self
                    .points
                    .iter()
                    .find(|point| point.row == row.row && point.buffer_pos > pos);
                let prev_on_row = self
                    .points
                    .iter()
                    .rev()
                    .find(|point| point.row == row.row && point.buffer_pos < pos);
                match (prev_on_row, next_on_row) {
                    // GNU `posn-at-point` may report neighboring positions when
                    // the requested buffer position is hidden by redisplay
                    // within the same visible row, but it returns nil when the
                    // position is not visible at all.
                    (Some(_), Some(next)) => Some(next),
                    _ => None,
                }
            }
        }
    }

    /// Return the visible point nearest to window-relative coordinates.
    ///
    /// `x` is relative to the text area's left edge. `y` is relative to the
    /// window's top edge, matching GNU Emacs `posn-at-x-y` conventions.
    pub fn point_at_coords(&self, x: i64, y: i64) -> Option<&DisplayPointSnapshot> {
        let row = self
            .rows
            .iter()
            .find(|row| y >= row.y && y < row.y.saturating_add(row.height.max(1)))?;
        let mut row_points = self.points.iter().filter(|point| point.row == row.row);
        let mut last = row_points.next()?;
        if x <= last.x {
            return Some(last);
        }
        for point in row_points {
            let right = last.x.saturating_add(last.width.max(1));
            if x < right {
                return Some(last);
            }
            if x < point.x {
                return Some(last);
            }
            last = point;
        }
        Some(last)
    }

    /// Row metrics for visual row ROW.
    pub fn row_metrics(&self, row: i64) -> Option<&DisplayRowSnapshot> {
        self.rows.iter().find(|metrics| metrics.row == row)
    }
}

impl Default for WindowDisplaySnapshot {
    fn default() -> Self {
        Self {
            window_id: WindowId(0),
            text_area_left_offset: 0,
            mode_line_height: 0,
            header_line_height: 0,
            tab_line_height: 0,
            points: Vec::new(),
            rows: Vec::new(),
        }
    }
}

/// Redisplay-owned runtime state used to decide which GNU window hooks fire.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WindowHookSnapshot {
    /// Buffer currently shown in the window.
    pub buffer_id: BufferId,
    /// Last known live bounds of the window.
    pub bounds: Rect,
}

/// Per-frame redisplay record for GNU window change hook ownership.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FrameWindowHookRecord {
    /// Last known live windows on the frame.
    pub windows: HashMap<WindowId, WindowHookSnapshot>,
    /// Selected window the last time window change hooks were recorded.
    pub selected_window: Option<WindowId>,
    /// Whether this frame was the selected frame at last record time.
    pub was_selected_frame: bool,
}

// ---------------------------------------------------------------------------
// Frame
// ---------------------------------------------------------------------------

/// A frame (top-level window/screen).
pub struct Frame {
    pub id: FrameId,
    pub name: String,
    /// Terminal owner id for GNU `frame-terminal` / terminal lifecycle.
    pub terminal_id: u64,
    /// Root of the window tree.
    pub root_window: Window,
    /// The selected (active) window.
    pub selected_window: WindowId,
    /// Minibuffer window (always a leaf).
    pub minibuffer_window: Option<WindowId>,
    /// Storage for the minibuffer leaf, which is not part of the split tree.
    pub minibuffer_leaf: Option<Window>,
    /// Frame pixel dimensions.
    pub width: u32,
    pub height: u32,
    /// Internal window-system kind, mirroring GNU Emacs frame state rather
    /// than the mutable Lisp-visible frame parameter alist.
    pub window_system: Option<Value>,
    /// Frame parameters.
    pub parameters: HashMap<String, Value>,
    /// Whether the frame is visible.
    pub visible: bool,
    /// Frame title.
    pub title: String,
    /// Menu bar height in pixels.
    pub menu_bar_height: u32,
    /// Tool bar height in pixels.
    pub tool_bar_height: u32,
    /// Tab bar height in pixels.
    pub tab_bar_height: u32,
    /// Default font size in pixels.
    pub font_pixel_size: f32,
    /// Default character width.
    pub char_width: f32,
    /// Default character height.
    pub char_height: f32,
    /// Authoritative last-redisplay geometry keyed by live leaf window.
    pub display_snapshots: HashMap<WindowId, WindowDisplaySnapshot>,
    /// Last recorded redisplay state for GNU window change hooks.
    pub(crate) window_hook_record: FrameWindowHookRecord,
    /// GNU `frame-window-state-change` flag.
    pub(crate) window_state_change: bool,
    /// Real frame-local Lisp face hash table, mirroring GNU `frame->face_hash_table`.
    pub face_hash_table: Value,
    /// Per-frame realized Lisp faces, mirroring GNU's `frame->face_hash_table`
    /// runtime surface for renderer-facing consumers.
    pub realized_faces: HashMap<String, RuntimeFace>,
}

impl Frame {
    pub fn new(
        id: FrameId,
        name: String,
        terminal_id: u64,
        width: u32,
        height: u32,
        root_window: Window,
    ) -> Self {
        let minibuffer_window = WindowId(MINIBUFFER_WINDOW_ID_BASE + id.0);
        let minibuffer_buffer_id = root_window.buffer_id().unwrap_or(BufferId(0));
        let mut minibuffer_leaf = Window::new_leaf(
            minibuffer_window,
            minibuffer_buffer_id,
            Rect::new(0.0, height as f32, width as f32, 16.0),
        );
        if let Window::Leaf {
            window_start,
            point,
            ..
        } = &mut minibuffer_leaf
        {
            *window_start = 1;
            *point = 1;
        }
        let selected = root_window
            .leaf_ids()
            .first()
            .copied()
            .unwrap_or(WindowId(0));
        Self {
            id,
            name,
            terminal_id,
            root_window,
            selected_window: selected,
            minibuffer_window: Some(minibuffer_window),
            minibuffer_leaf: Some(minibuffer_leaf),
            width,
            height,
            window_system: None,
            parameters: HashMap::new(),
            visible: true,
            title: String::new(),
            menu_bar_height: 0,
            tool_bar_height: 0,
            tab_bar_height: 0,
            font_pixel_size: 16.0,
            char_width: 8.0,
            char_height: 16.0,
            display_snapshots: HashMap::new(),
            window_hook_record: FrameWindowHookRecord::default(),
            window_state_change: false,
            face_hash_table: Value::hash_table(HashTableTest::Eq),
            realized_faces: HashMap::new(),
        }
    }

    /// Recalculate minibuffer bounds based on the root window's current bounds.
    ///
    /// Like GNU Emacs's `resize_frame_windows()` which sets:
    ///   `m->pixel_top = r->pixel_top + r->pixel_height`
    ///
    /// Must be called after any operation that changes the window tree
    /// (split, delete, resize).
    pub fn recalculate_minibuffer_bounds(&mut self) {
        self.sync_window_area_bounds();
    }

    /// Get the selected window.
    pub fn selected_window(&self) -> Option<&Window> {
        self.root_window.find(self.selected_window)
    }

    /// Get a mutable reference to the selected window.
    pub fn selected_window_mut(&mut self) -> Option<&mut Window> {
        self.root_window.find_mut(self.selected_window)
    }

    /// Replace all leaf window buffer bindings for `old_id` with `new_id`.
    pub fn replace_buffer_bindings(&mut self, old_id: BufferId, new_id: BufferId) {
        self.root_window.replace_buffer_id(old_id, new_id);
        if let Some(minibuffer_leaf) = self.minibuffer_leaf.as_mut() {
            minibuffer_leaf.replace_buffer_id(old_id, new_id);
        }
    }

    /// Return the effective window-system symbol for this frame.
    pub fn effective_window_system(&self) -> Option<Value> {
        self.window_system
            .or_else(|| self.parameters.get("window-system").copied())
    }

    /// Update the frame's internal window-system kind and keep the Lisp-visible
    /// frame parameter in sync.
    pub fn set_window_system(&mut self, window_system: Option<Value>) {
        self.window_system = window_system;
        match window_system {
            Some(value) => {
                self.parameters.insert("window-system".to_string(), value);
            }
            None => {
                self.parameters.remove("window-system");
            }
        }
    }

    pub fn frame_parameter_int(&self, key: &str) -> Option<i64> {
        self.parameters.get(key).and_then(|v| v.as_int())
    }

    pub fn realized_face(&self, name: &str) -> Option<&RuntimeFace> {
        self.realized_faces.get(name)
    }

    pub fn face_hash_table(&self) -> Value {
        self.face_hash_table
    }

    pub fn set_realized_face(&mut self, name: String, face: RuntimeFace) {
        self.realized_faces.insert(name, face);
    }

    pub fn clear_realized_faces(&mut self) {
        self.realized_faces.clear();
        if self.face_hash_table.is_hash_table() {
            let _ = self.face_hash_table.with_hash_table_mut(|table| {
                table.data.clear();
                table.key_snapshots.clear();
                table.insertion_order.clear();
            });
        }
    }

    fn chrome_top_height(&self) -> f32 {
        self.menu_bar_height
            .saturating_add(self.tool_bar_height)
            .saturating_add(self.tab_bar_height) as f32
    }

    fn window_text_area_bounds(&self) -> Rect {
        let frame_w = self.width as f32;
        let frame_h = self.height as f32;
        let chrome_top = self.chrome_top_height().min(frame_h);
        let minibuffer_height = self
            .minibuffer_leaf
            .as_ref()
            .map(|mini| mini.bounds().height.max(0.0))
            .unwrap_or(0.0)
            .min((frame_h - chrome_top).max(0.0));
        let root_height = (frame_h - chrome_top - minibuffer_height).max(0.0);
        Rect::new(0.0, chrome_top, frame_w, root_height)
    }

    pub fn sync_window_area_bounds(&mut self) {
        let root_bounds = self.window_text_area_bounds();
        resize_window_subtree(&mut self.root_window, root_bounds);

        if let Some(mini) = self.minibuffer_leaf.as_mut() {
            let mini_h = mini
                .bounds()
                .height
                .max(0.0)
                .min((self.height as f32 - (root_bounds.y + root_bounds.height)).max(0.0));
            mini.set_bounds(Rect::new(
                root_bounds.x,
                root_bounds.y + root_bounds.height,
                root_bounds.width,
                mini_h,
            ));
            mini.invalidate_display_state();
        }

        self.root_window.invalidate_display_state();
        self.display_snapshots.clear();
    }

    pub fn sync_tab_bar_height_from_parameters(&mut self) {
        let lines = self
            .frame_parameter_int("tab-bar-lines")
            .unwrap_or(0)
            .max(0) as u32;
        let char_height = self.char_height.max(1.0).round() as u32;
        self.tab_bar_height = lines.saturating_mul(char_height);
        self.sync_window_area_bounds();
    }

    /// Select a window by ID.
    pub fn select_window(&mut self, id: WindowId) -> bool {
        if self.find_window(id).is_some() {
            self.selected_window = id;
            true
        } else {
            false
        }
    }

    /// Find a window by ID.
    pub fn find_window(&self, id: WindowId) -> Option<&Window> {
        if let Some(window) = self.root_window.find(id) {
            return Some(window);
        }
        self.minibuffer_leaf.as_ref().and_then(|window| {
            if window.id() == id {
                Some(window)
            } else {
                None
            }
        })
    }

    /// Find a mutable window by ID.
    pub fn find_window_mut(&mut self, id: WindowId) -> Option<&mut Window> {
        if let Some(window) = self.root_window.find_mut(id) {
            return Some(window);
        }
        self.minibuffer_leaf.as_mut().and_then(|window| {
            if window.id() == id {
                Some(window)
            } else {
                None
            }
        })
    }

    /// All leaf window IDs.
    pub fn window_list(&self) -> Vec<WindowId> {
        self.root_window.leaf_ids()
    }

    /// Number of visible windows (leaves).
    pub fn window_count(&self) -> usize {
        self.root_window.leaf_count()
    }

    /// Find which window is at pixel coordinates.
    pub fn window_at(&self, px: f32, py: f32) -> Option<WindowId> {
        self.root_window.window_at(px, py)
    }

    /// Columns (based on default char width).
    pub fn columns(&self) -> u32 {
        (self.width as f32 / self.char_width) as u32
    }

    /// Lines (based on default char height).
    pub fn lines(&self) -> u32 {
        (self.height as f32 / self.char_height) as u32
    }

    /// Replace the last-redisplay geometry for this frame's live windows.
    pub fn replace_display_snapshots(&mut self, snapshots: Vec<WindowDisplaySnapshot>) {
        self.display_snapshots.clear();
        for snapshot in snapshots {
            if self.find_window(snapshot.window_id).is_some() {
                self.display_snapshots.insert(snapshot.window_id, snapshot);
            }
        }
    }

    /// Last redisplay geometry for WINDOW-ID, if available.
    pub fn window_display_snapshot(&self, id: WindowId) -> Option<&WindowDisplaySnapshot> {
        self.display_snapshots.get(&id)
    }

    /// Resize the frame and window tree to new pixel dimensions.
    pub fn resize_pixelwise(&mut self, width: u32, height: u32) {
        self.width = width;
        self.height = height;
        self.sync_window_area_bounds();

        let char_width = self.char_width.max(1.0);
        let char_height = self.char_height.max(1.0);
        let root_height = self.root_window.bounds().height;
        let cols = ((width as f32) / char_width).floor().max(1.0) as i64;
        let text_lines = (root_height / char_height).floor().max(1.0) as i64;
        let total_lines = text_lines.saturating_add(1);
        self.parameters
            .insert("width".to_string(), Value::fixnum(cols));
        self.parameters
            .insert("height".to_string(), Value::fixnum(total_lines));
    }
}

// ---------------------------------------------------------------------------
// FrameManager
// ---------------------------------------------------------------------------

/// Manages all frames and tracks the selected frame.
pub struct FrameManager {
    frames: HashMap<FrameId, Frame>,
    selected: Option<FrameId>,
    next_frame_id: u64,
    next_window_id: u64,
    old_selected_window: Option<WindowId>,
    deleted_windows: HashSet<WindowId>,
    deleted_window_parameters: HashMap<WindowId, WindowParameters>,
    window_select_count: i64,
}

impl FrameManager {
    pub fn new() -> Self {
        Self {
            frames: HashMap::new(),
            selected: None,
            next_frame_id: FRAME_ID_BASE,
            next_window_id: 1,
            old_selected_window: None,
            deleted_windows: HashSet::new(),
            deleted_window_parameters: HashMap::new(),
            window_select_count: 0,
        }
    }

    /// Allocate a new window ID.
    pub fn next_window_id(&mut self) -> WindowId {
        let id = WindowId(self.next_window_id);
        self.next_window_id += 1;
        self.deleted_windows.remove(&id);
        self.deleted_window_parameters.remove(&id);
        id
    }

    /// Create a new frame with a single window displaying `buffer_id`.
    pub fn create_frame(
        &mut self,
        name: &str,
        width: u32,
        height: u32,
        buffer_id: BufferId,
    ) -> FrameId {
        self.create_frame_on_terminal(name, 0, width, height, buffer_id)
    }

    pub fn create_frame_on_terminal(
        &mut self,
        name: &str,
        terminal_id: u64,
        width: u32,
        height: u32,
        buffer_id: BufferId,
    ) -> FrameId {
        let frame_id = FrameId(self.next_frame_id);
        self.next_frame_id += 1;

        let window_id = self.next_window_id();
        let bounds = Rect::new(0.0, 0.0, width as f32, height as f32);
        let root = Window::new_leaf(window_id, buffer_id, bounds);

        let frame = Frame::new(frame_id, name.to_string(), terminal_id, width, height, root);
        let selected_wid = frame.selected_window;
        self.frames.insert(frame_id, frame);
        self.note_window_selected(selected_wid);

        if self.selected.is_none() {
            self.selected = Some(frame_id);
            self.old_selected_window = Some(selected_wid);
        }

        frame_id
    }

    /// Get a frame by ID.
    pub fn get(&self, id: FrameId) -> Option<&Frame> {
        self.frames.get(&id)
    }

    /// Get a mutable frame by ID.
    pub fn get_mut(&mut self, id: FrameId) -> Option<&mut Frame> {
        self.frames.get_mut(&id)
    }

    /// Get the selected frame.
    pub fn selected_frame(&self) -> Option<&Frame> {
        self.selected.and_then(|id| self.frames.get(&id))
    }

    /// Get a mutable reference to the selected frame.
    pub fn selected_frame_mut(&mut self) -> Option<&mut Frame> {
        self.selected.and_then(|id| self.frames.get_mut(&id))
    }

    /// Select a frame.
    pub fn select_frame(&mut self, id: FrameId) -> bool {
        if self.frames.contains_key(&id) {
            self.selected = Some(id);
            true
        } else {
            false
        }
    }

    /// Delete a frame.
    pub fn delete_frame(&mut self, id: FrameId) -> bool {
        if let Some(frame) = self.frames.remove(&id) {
            for wid in frame.window_list() {
                self.deleted_windows.insert(wid);
                if let Some(window) = frame.find_window(wid) {
                    self.deleted_window_parameters
                        .insert(wid, window.parameters().clone());
                }
            }
            if let Some(minibuffer_wid) = frame.minibuffer_window {
                self.deleted_windows.insert(minibuffer_wid);
                if let Some(window) = frame.find_window(minibuffer_wid) {
                    self.deleted_window_parameters
                        .insert(minibuffer_wid, window.parameters().clone());
                }
            }
            if self.selected == Some(id) {
                self.selected = self.frames.keys().next().copied();
            }
            true
        } else {
            false
        }
    }

    /// List all frame IDs.
    pub fn frame_list(&self) -> Vec<FrameId> {
        self.frames.keys().copied().collect()
    }

    /// Split a window horizontally or vertically.
    /// Returns the new window's ID, or None if the window wasn't found.
    ///
    /// `size` controls how space is divided:
    /// - `None` or `Some(0)`: split 50/50
    /// - `Some(n)` where n > 0: the **new** window gets `n` units (lines or
    ///   columns), the old window gets the remainder.
    /// - `Some(n)` where n < 0: the **old** window gets `|n|` units, the new
    ///   window gets the remainder.
    pub fn split_window(
        &mut self,
        frame_id: FrameId,
        window_id: WindowId,
        direction: SplitDirection,
        new_buffer_id: BufferId,
        size: Option<i64>,
    ) -> Option<WindowId> {
        let internal_id = self.alloc_window_id();
        let new_id = self.alloc_window_id();
        let frame = self.frames.get_mut(&frame_id)?;

        split_window_in_tree(
            &mut frame.root_window,
            window_id,
            direction,
            internal_id,
            new_id,
            new_buffer_id,
            size,
        )?;

        frame.recalculate_minibuffer_bounds();
        Some(new_id)
    }

    /// Delete a window from a frame. Cannot delete the last window.
    pub fn delete_window(&mut self, frame_id: FrameId, window_id: WindowId) -> bool {
        let Some(frame) = self.frames.get_mut(&frame_id) else {
            return false;
        };
        if frame.root_window.leaf_count() <= 1 {
            return false; // Can't delete last window
        }

        let deleted_parameters = frame
            .find_window(window_id)
            .map(|window| window.parameters().clone());
        let removed = delete_window_in_tree(&mut frame.root_window, window_id);
        if removed {
            self.deleted_windows.insert(window_id);
            self.deleted_window_parameters
                .insert(window_id, deleted_parameters.unwrap_or_default());
            frame.recalculate_minibuffer_bounds();
        }

        if removed && frame.selected_window == window_id {
            // Select the first remaining leaf.
            if let Some(first) = frame.root_window.leaf_ids().first() {
                frame.selected_window = *first;
            }
        }

        removed
    }

    fn alloc_window_id(&mut self) -> WindowId {
        let id = WindowId(self.next_window_id);
        self.next_window_id += 1;
        self.deleted_windows.remove(&id);
        self.deleted_window_parameters.remove(&id);
        id
    }

    /// Replace dead-buffer bindings in every live frame.
    pub fn replace_buffer_in_windows(&mut self, old_id: BufferId, new_id: BufferId) {
        for frame in self.frames.values_mut() {
            frame.replace_buffer_bindings(old_id, new_id);
        }
    }

    /// Return the frame containing a live window ID, if any.
    pub fn find_window_frame_id(&self, window_id: WindowId) -> Option<FrameId> {
        self.frames.iter().find_map(|(frame_id, frame)| {
            if frame.minibuffer_window == Some(window_id) {
                return Some(*frame_id);
            }
            frame.find_window(window_id).and_then(|window| {
                if window.is_leaf() {
                    Some(*frame_id)
                } else {
                    None
                }
            })
        })
    }

    /// Return the frame containing a valid window ID, if any.
    ///
    /// Valid windows include live leaf windows, internal windows, and the
    /// minibuffer window of a live frame.
    pub fn find_valid_window_frame_id(&self, window_id: WindowId) -> Option<FrameId> {
        self.frames.iter().find_map(|(frame_id, frame)| {
            if frame.minibuffer_window == Some(window_id) {
                return Some(*frame_id);
            }
            frame.find_window(window_id).map(|_| *frame_id)
        })
    }

    /// Return true when WINDOW-ID designates a live window in any frame.
    pub fn is_live_window_id(&self, window_id: WindowId) -> bool {
        self.find_window_frame_id(window_id).is_some()
    }

    /// Return true when WINDOW-ID designates a valid live or internal window.
    pub fn is_valid_window_id(&self, window_id: WindowId) -> bool {
        self.find_valid_window_frame_id(window_id).is_some()
    }

    /// Return true when WINDOW-ID designates a live or stale window object.
    pub fn is_window_object_id(&self, window_id: WindowId) -> bool {
        self.is_valid_window_id(window_id) || self.deleted_windows.contains(&window_id)
    }
}

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

// ---------------------------------------------------------------------------
// Tree manipulation helpers
// ---------------------------------------------------------------------------

/// Split a window in the tree by wrapping it in an Internal node.
///
/// `size` semantics (lines for vertical, columns for horizontal — 1 unit = 1.0
/// pixel in the abstract coordinate system):
/// - `None` / `Some(0)`: 50/50 split.
/// - `Some(n)` (n > 0): new window (right/bottom) gets `n` units.
/// - `Some(n)` (n < 0): old window (left/top) keeps `|n|` units.
fn split_window_in_tree(
    tree: &mut Window,
    target: WindowId,
    direction: SplitDirection,
    internal_id: WindowId,
    new_id: WindowId,
    new_buffer_id: BufferId,
    size: Option<i64>,
) -> Option<()> {
    if tree.id() == target {
        let old_id = tree.id();
        let old_bounds = *tree.bounds();
        let old_window = tree.clone();

        if let Window::Leaf {
            buffer_id: buf_id, ..
        } = old_window
        {
            let (left_bounds, right_bounds) = match direction {
                SplitDirection::Horizontal => {
                    let total = old_bounds.width;
                    // Compute size for the NEW window (right pane).
                    let new_size = match size {
                        Some(n) if n > 0 => (n as f32).min(total - 1.0).max(1.0),
                        Some(n) if n < 0 => (total - (-n) as f32).max(1.0).min(total - 1.0),
                        _ => total / 2.0,
                    };
                    let old_size = total - new_size;
                    (
                        Rect::new(old_bounds.x, old_bounds.y, old_size, old_bounds.height),
                        Rect::new(
                            old_bounds.x + old_size,
                            old_bounds.y,
                            new_size,
                            old_bounds.height,
                        ),
                    )
                }
                SplitDirection::Vertical => {
                    let total = old_bounds.height;
                    // Compute size for the NEW window (bottom pane).
                    let new_size = match size {
                        Some(n) if n > 0 => (n as f32).min(total - 1.0).max(1.0),
                        Some(n) if n < 0 => (total - (-n) as f32).max(1.0).min(total - 1.0),
                        _ => total / 2.0,
                    };
                    let old_size = total - new_size;
                    (
                        Rect::new(old_bounds.x, old_bounds.y, old_bounds.width, old_size),
                        Rect::new(
                            old_bounds.x,
                            old_bounds.y + old_size,
                            old_bounds.width,
                            new_size,
                        ),
                    )
                }
            };

            let mut old_leaf = old_window;
            old_leaf.set_bounds(left_bounds);

            let mut new_leaf = old_leaf.clone();
            if let Window::Leaf {
                id,
                buffer_id,
                bounds,
                parameters,
                history,
                window_start,
                window_end_pos,
                window_end_bytepos,
                window_end_vpos,
                window_end_valid,
                point,
                old_point,
                vscroll,
                preserve_vscroll_p,
                ..
            } = &mut new_leaf
            {
                *id = new_id;
                *buffer_id = new_buffer_id;
                *bounds = right_bounds;
                parameters.clear();
                *history = WindowHistoryState::default();
                *window_start = 1;
                *window_end_pos = 0;
                *window_end_bytepos = 0;
                *window_end_vpos = 0;
                *window_end_valid = false;
                *point = 1;
                *old_point = 1;
                *vscroll = 0;
                *preserve_vscroll_p = false;
            }

            *tree = Window::Internal {
                id: internal_id,
                direction,
                children: vec![old_leaf, new_leaf],
                bounds: old_bounds,
                parameters: Vec::new(),
                combination_limit: false,
            };

            return Some(());
        }
    }

    // Recurse into children.
    if let Window::Internal { children, .. } = tree {
        for child in children {
            if split_window_in_tree(
                child,
                target,
                direction,
                internal_id,
                new_id,
                new_buffer_id,
                size,
            )
            .is_some()
            {
                return Some(());
            }
        }
    }

    None
}

/// Delete a window from the tree. Returns true if found and removed.
fn delete_window_in_tree(tree: &mut Window, target: WindowId) -> bool {
    if let Window::Internal {
        children, bounds, ..
    } = tree
    {
        // Check if any direct child is the target.
        if let Some(idx) = children.iter().position(|c| c.id() == target) {
            children.remove(idx);

            // If only one child remains, replace this internal node with it.
            if children.len() == 1 {
                let mut remaining = children.pop().unwrap();
                remaining.set_bounds(*bounds);
                *tree = remaining;
            } else {
                // Redistribute space among remaining children.
                redistribute_bounds(children, *bounds);
            }
            return true;
        }

        // Recurse.
        for child in children {
            if delete_window_in_tree(child, target) {
                return true;
            }
        }
    }

    false
}

fn find_parent_in_tree(node: &Window, target: WindowId) -> Option<WindowId> {
    let Window::Internal { children, .. } = node else {
        return None;
    };

    for child in children {
        if child.id() == target {
            return Some(node.id());
        }
        if let Some(parent) = find_parent_in_tree(child, target) {
            return Some(parent);
        }
    }

    None
}

fn find_sibling_in_tree(node: &Window, target: WindowId, next: bool) -> Option<WindowId> {
    let Window::Internal { children, .. } = node else {
        return None;
    };

    if let Some(index) = children.iter().position(|child| child.id() == target) {
        let sibling = if next {
            children.get(index + 1)
        } else {
            index.checked_sub(1).and_then(|idx| children.get(idx))
        };
        return sibling.map(Window::id);
    }

    children
        .iter()
        .find_map(|child| find_sibling_in_tree(child, target, next))
}

fn find_first_child_in_tree(
    node: &Window,
    target: WindowId,
    direction: SplitDirection,
) -> Option<WindowId> {
    match node {
        Window::Leaf { .. } => None,
        Window::Internal {
            id,
            direction: node_direction,
            children,
            ..
        } => {
            if *id == target {
                return (*node_direction == direction)
                    .then(|| children.first().map(Window::id))
                    .flatten();
            }
            children
                .iter()
                .find_map(|child| find_first_child_in_tree(child, target, direction))
        }
    }
}

/// Return the parent of WINDOW-ID inside FRAME, if any.
pub fn window_parent_id(frame: &Frame, window_id: WindowId) -> Option<WindowId> {
    if frame.minibuffer_window == Some(window_id) {
        return None;
    }
    find_parent_in_tree(&frame.root_window, window_id)
}

/// Return the first child of WINDOW-ID when it is combined in DIRECTION.
pub fn window_first_child_id(
    frame: &Frame,
    window_id: WindowId,
    direction: SplitDirection,
) -> Option<WindowId> {
    if frame.minibuffer_window == Some(window_id) {
        return None;
    }
    find_first_child_in_tree(&frame.root_window, window_id, direction)
}

/// Return the next sibling of WINDOW-ID, if any.
pub fn window_next_sibling_id(frame: &Frame, window_id: WindowId) -> Option<WindowId> {
    if frame.minibuffer_window == Some(window_id) {
        return None;
    }
    find_sibling_in_tree(&frame.root_window, window_id, true)
}

/// Return the previous sibling of WINDOW-ID, if any.
pub fn window_prev_sibling_id(frame: &Frame, window_id: WindowId) -> Option<WindowId> {
    if frame.minibuffer_window == Some(window_id) {
        return None;
    }
    find_sibling_in_tree(&frame.root_window, window_id, false)
}

/// Apply pixel-based resize values to a window tree.
///
/// Mirrors GNU Emacs `window_resize_apply()` in window.c:
/// - Reads `new_pixel` for each window from the provided map
/// - Sets window bounds accordingly
/// - Recursively processes children, tracking edge positions
/// - For vertical combinations: accumulates vertical edge
/// - For horizontal combinations: accumulates horizontal edge
///
/// `horflag`: true = applying horizontal sizes, false = applying vertical sizes.
pub fn window_resize_apply(
    window: &mut Window,
    horflag: bool,
    new_pixel_map: &HashMap<u64, i64>,
    new_normal_map: &HashMap<u64, f64>,
    char_width: f32,
    char_height: f32,
) {
    let wid = window.id().0;
    let new_px = new_pixel_map.get(&wid).copied();

    // Apply new_pixel to this window's bounds.
    let bounds = *window.bounds();
    if let Some(px) = new_px {
        let px = px.max(0) as f32;
        if horflag {
            window.set_bounds(Rect::new(bounds.x, bounds.y, px, bounds.height));
        } else {
            window.set_bounds(Rect::new(bounds.x, bounds.y, bounds.width, px));
        }
    }

    // Get updated bounds after applying new_pixel.
    let bounds = *window.bounds();
    let edge = if horflag { bounds.x } else { bounds.y };

    if let Window::Internal {
        direction,
        children,
        ..
    } = window
    {
        let mut edge = edge;
        let dir = *direction;
        for child in children.iter_mut() {
            // Position child at current edge.
            let cb = *child.bounds();
            if horflag {
                child.set_bounds(Rect::new(edge, cb.y, cb.width, cb.height));
            } else {
                child.set_bounds(Rect::new(cb.x, edge, cb.width, cb.height));
            }

            // Recurse.
            window_resize_apply(
                child,
                horflag,
                new_pixel_map,
                new_normal_map,
                char_width,
                char_height,
            );

            // Accumulate edge in the combination direction.
            let child_bounds = *child.bounds();
            match (dir, horflag) {
                (SplitDirection::Horizontal, true) => edge += child_bounds.width,
                (SplitDirection::Vertical, false) => edge += child_bounds.height,
                _ => {}
            }
        }
    }
}

/// Check that a resize is valid: the sum of children's new_pixel values
/// must equal the parent's new_pixel value in the combination direction.
pub fn window_resize_check(
    window: &Window,
    horflag: bool,
    new_pixel_map: &HashMap<u64, i64>,
) -> bool {
    let wid = window.id().0;
    let my_new = new_pixel_map.get(&wid).copied().unwrap_or_else(|| {
        let b = window.bounds();
        if horflag {
            b.width as i64
        } else {
            b.height as i64
        }
    });

    match window {
        Window::Leaf { .. } => true,
        Window::Internal {
            direction,
            children,
            ..
        } => {
            // In the combination direction, sum of children must equal parent.
            let combines = (*direction == SplitDirection::Horizontal) == horflag;
            if combines {
                let child_sum: i64 = children
                    .iter()
                    .map(|c| {
                        let cid = c.id().0;
                        new_pixel_map.get(&cid).copied().unwrap_or_else(|| {
                            let b = c.bounds();
                            if horflag {
                                b.width as i64
                            } else {
                                b.height as i64
                            }
                        })
                    })
                    .sum();
                if child_sum != my_new {
                    return false;
                }
            }
            // All children must also pass the check.
            children
                .iter()
                .all(|c| window_resize_check(c, horflag, new_pixel_map))
        }
    }
}

/// Apply character-cell-based resize values to a window tree.
///
/// Mirrors GNU Emacs `window_resize_apply_total()` in window.c:
/// - Reads `new_total` for each window from the provided map
/// - Sets character-cell sizes and positions accordingly
/// - This does NOT modify pixel bounds — it only updates the character-cell
///   grid positions used by Emacs internals.
///
/// Since neomacs uses pixel bounds as the source of truth, this function
/// converts new_total back to pixels using char_width/char_height and
/// applies the result to window bounds.
pub fn window_resize_apply_total(
    window: &mut Window,
    horflag: bool,
    new_total_map: &HashMap<u64, i64>,
    char_width: f32,
    char_height: f32,
) {
    let wid = window.id().0;
    let new_total = new_total_map.get(&wid).copied();

    // Apply new_total converted to pixels.
    let bounds = *window.bounds();
    if let Some(total) = new_total {
        let total = total.max(0) as f32;
        if horflag {
            let px = total * char_width;
            window.set_bounds(Rect::new(bounds.x, bounds.y, px, bounds.height));
        } else {
            let px = total * char_height;
            window.set_bounds(Rect::new(bounds.x, bounds.y, bounds.width, px));
        }
    }

    let bounds = *window.bounds();
    let edge = if horflag { bounds.x } else { bounds.y };

    if let Window::Internal {
        direction,
        children,
        ..
    } = window
    {
        let mut edge = edge;
        let dir = *direction;
        for child in children.iter_mut() {
            // Position child at current edge.
            let cb = *child.bounds();
            if horflag {
                child.set_bounds(Rect::new(edge, cb.y, cb.width, cb.height));
            } else {
                child.set_bounds(Rect::new(cb.x, edge, cb.width, cb.height));
            }

            // Recurse.
            window_resize_apply_total(child, horflag, new_total_map, char_width, char_height);

            // Accumulate edge.
            let child_bounds = *child.bounds();
            match (dir, horflag) {
                (SplitDirection::Horizontal, true) => edge += child_bounds.width,
                (SplitDirection::Vertical, false) => edge += child_bounds.height,
                _ => {}
            }
        }
    }
}

/// Redistribute bounds equally among children.
fn redistribute_bounds(children: &mut [Window], parent: Rect) {
    if children.is_empty() {
        return;
    }

    let n = children.len() as f32;

    // Detect direction from first two children if possible.
    if children.len() >= 2 {
        let first = children[0].bounds();
        let second = children[1].bounds();

        if (first.x - second.x).abs() > 0.1 {
            // Horizontal split
            let w = parent.width / n;
            for (i, child) in children.iter_mut().enumerate() {
                child.set_bounds(Rect::new(
                    parent.x + i as f32 * w,
                    parent.y,
                    w,
                    parent.height,
                ));
            }
        } else {
            // Vertical split
            let h = parent.height / n;
            for (i, child) in children.iter_mut().enumerate() {
                child.set_bounds(Rect::new(
                    parent.x,
                    parent.y + i as f32 * h,
                    parent.width,
                    h,
                ));
            }
        }
    } else {
        // Single child gets full bounds.
        children[0].set_bounds(parent);
    }
}

fn resize_window_subtree(window: &mut Window, bounds: Rect) {
    window.set_bounds(bounds);
    if let Window::Internal { children, .. } = window {
        redistribute_bounds(children, bounds);
        for child in children {
            let child_bounds = *child.bounds();
            resize_window_subtree(child, child_bounds);
        }
    }
}

// ===========================================================================
// GcTrace
// ===========================================================================

impl GcTrace for FrameManager {
    fn trace_roots(&self, roots: &mut Vec<Value>) {
        // Deleted window parameter maps
        for params in self.deleted_window_parameters.values() {
            for (k, v) in params {
                roots.push(*k);
                roots.push(*v);
            }
        }
        // Frame and window tree parameters
        for frame in self.frames.values() {
            for v in frame.parameters.values() {
                roots.push(*v);
            }
            roots.push(frame.face_hash_table);
            trace_window(&frame.root_window, roots);
            if let Some(mb) = &frame.minibuffer_leaf {
                trace_window(mb, roots);
            }
        }
    }
}

fn trace_window(window: &Window, roots: &mut Vec<Value>) {
    match window {
        Window::Leaf { display, .. } => {
            for (key, value) in window.parameters() {
                roots.push(*key);
                roots.push(*value);
            }
            if let Some(history) = window.history() {
                roots.push(history.prev_buffers);
                roots.push(history.next_buffers);
            }
            roots.push(display.display_table);
            roots.push(display.cursor_type);
            roots.push(display.vertical_scroll_bar_type);
            roots.push(display.horizontal_scroll_bar_type);
        }
        Window::Internal { children, .. } => {
            for (key, value) in window.parameters() {
                roots.push(*key);
                roots.push(*value);
            }
            for child in children {
                trace_window(child, roots);
            }
        }
    }
}

// ===========================================================================
// Tests
// ===========================================================================

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

    #[test]
    fn create_frame_and_window() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let frame = mgr.get(fid).unwrap();

        assert_eq!(frame.window_count(), 1);
        assert!(frame.selected_window().is_some());
        assert!(frame.selected_window().unwrap().is_leaf());
    }

    #[test]
    fn split_window_horizontal() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let wid = mgr.get(fid).unwrap().window_list()[0];

        let new_wid = mgr.split_window(fid, wid, SplitDirection::Horizontal, BufferId(2), None);
        assert!(new_wid.is_some());

        let frame = mgr.get(fid).unwrap();
        assert_eq!(frame.window_count(), 2);
    }

    #[test]
    fn split_window_vertical() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let wid = mgr.get(fid).unwrap().window_list()[0];

        let new_wid = mgr.split_window(fid, wid, SplitDirection::Vertical, BufferId(2), None);
        assert!(new_wid.is_some());

        let frame = mgr.get(fid).unwrap();
        assert_eq!(frame.window_count(), 2);
    }

    #[test]
    fn split_window_copies_window_display_state() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        {
            let frame = mgr.get_mut(fid).unwrap();
            frame.set_window_system(Some(Value::symbol("neo")));
            let wid = frame.window_list()[0];
            let display = frame
                .find_window_mut(wid)
                .and_then(Window::display_mut)
                .expect("leaf display");
            display.display_table = Value::fixnum(17);
            display.cursor_type = Value::NIL;
            display.left_fringe_width = 3;
            display.right_fringe_width = 5;
            display.fringes_outside_margins = true;
            display.fringes_persistent = true;
            display.scroll_bar_width = 11;
            display.vertical_scroll_bar_type = Value::T;
            display.scroll_bar_height = 7;
            display.horizontal_scroll_bar_type = Value::NIL;
            display.scroll_bars_persistent = true;
        }

        let original_wid = mgr.get(fid).unwrap().window_list()[0];
        let new_wid = mgr
            .split_window(
                fid,
                original_wid,
                SplitDirection::Horizontal,
                BufferId(2),
                None,
            )
            .expect("split");

        let frame = mgr.get(fid).unwrap();
        let original_display = frame
            .find_window(original_wid)
            .and_then(Window::display)
            .expect("original display");
        let new_display = frame
            .find_window(new_wid)
            .and_then(Window::display)
            .expect("new display");

        assert_eq!(original_display.display_table, Value::fixnum(17));
        assert_eq!(new_display.display_table, Value::fixnum(17));
        assert_eq!(original_display.cursor_type, Value::NIL);
        assert_eq!(new_display.cursor_type, Value::NIL);
        assert_eq!(original_display.left_fringe_width, 3);
        assert_eq!(new_display.left_fringe_width, 3);
        assert_eq!(original_display.right_fringe_width, 5);
        assert_eq!(new_display.right_fringe_width, 5);
        assert!(original_display.fringes_outside_margins);
        assert!(new_display.fringes_outside_margins);
        assert!(original_display.fringes_persistent);
        assert!(new_display.fringes_persistent);
        assert_eq!(original_display.scroll_bar_width, 11);
        assert_eq!(new_display.scroll_bar_width, 11);
        assert_eq!(original_display.vertical_scroll_bar_type, Value::T);
        assert_eq!(new_display.vertical_scroll_bar_type, Value::T);
        assert_eq!(original_display.scroll_bar_height, 7);
        assert_eq!(new_display.scroll_bar_height, 7);
        assert_eq!(original_display.horizontal_scroll_bar_type, Value::NIL);
        assert_eq!(new_display.horizontal_scroll_bar_type, Value::NIL);
        assert!(original_display.scroll_bars_persistent);
        assert!(new_display.scroll_bars_persistent);
    }

    #[test]
    fn split_window_resets_new_leaf_vscroll_state() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let original_wid = mgr.get(fid).unwrap().window_list()[0];

        if let Some(Window::Leaf {
            vscroll,
            preserve_vscroll_p,
            ..
        }) = mgr
            .get_mut(fid)
            .and_then(|frame| frame.find_window_mut(original_wid))
        {
            *vscroll = -19;
            *preserve_vscroll_p = true;
        }

        let new_wid = mgr
            .split_window(
                fid,
                original_wid,
                SplitDirection::Horizontal,
                BufferId(2),
                None,
            )
            .expect("split");

        let frame = mgr.get(fid).unwrap();
        let Window::Leaf {
            vscroll: original_vscroll,
            preserve_vscroll_p: original_preserve,
            ..
        } = frame.find_window(original_wid).unwrap()
        else {
            panic!("expected original leaf");
        };
        let Window::Leaf {
            vscroll: new_vscroll,
            preserve_vscroll_p: new_preserve,
            ..
        } = frame.find_window(new_wid).unwrap()
        else {
            panic!("expected new leaf");
        };

        assert_eq!(*original_vscroll, -19);
        assert!(*original_preserve);
        assert_eq!(*new_vscroll, 0);
        assert!(!*new_preserve);
    }

    #[test]
    fn delete_window() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let wid = mgr.get(fid).unwrap().window_list()[0];

        // Split first.
        let new_wid = mgr
            .split_window(fid, wid, SplitDirection::Horizontal, BufferId(2), None)
            .unwrap();

        // Delete the new window.
        assert!(mgr.delete_window(fid, new_wid));
        assert_eq!(mgr.get(fid).unwrap().window_count(), 1);
    }

    #[test]
    fn cannot_delete_last_window() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let wid = mgr.get(fid).unwrap().window_list()[0];

        assert!(!mgr.delete_window(fid, wid));
    }

    #[test]
    fn select_window() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let wid = mgr.get(fid).unwrap().window_list()[0];

        let new_wid = mgr
            .split_window(fid, wid, SplitDirection::Horizontal, BufferId(2), None)
            .unwrap();

        assert!(mgr.get_mut(fid).unwrap().select_window(new_wid));
        assert_eq!(mgr.get(fid).unwrap().selected_window.0, new_wid.0,);
    }

    #[test]
    fn window_at_coordinates() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let wid = mgr.get(fid).unwrap().window_list()[0];

        mgr.split_window(fid, wid, SplitDirection::Horizontal, BufferId(2), None);

        let frame = mgr.get(fid).unwrap();
        // Left half
        let left = frame.window_at(100.0, 300.0);
        assert!(left.is_some());
        // Right half
        let right = frame.window_at(600.0, 300.0);
        assert!(right.is_some());
        // Should be different windows
        assert_ne!(left, right);
    }

    #[test]
    fn frame_columns_and_lines() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let frame = mgr.get(fid).unwrap();

        assert_eq!(frame.columns(), 100); // 800/8
        assert_eq!(frame.lines(), 37); // 600/16 = 37
    }

    #[test]
    fn delete_frame() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        assert!(mgr.delete_frame(fid));
        assert!(mgr.get(fid).is_none());
    }

    #[test]
    fn multiple_frames() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let f1 = mgr.create_frame("F1", 800, 600, BufferId(1));
        let f2 = mgr.create_frame("F2", 1024, 768, BufferId(2));

        assert_eq!(mgr.frame_list().len(), 2);
        assert!(mgr.select_frame(f2));
        assert_eq!(mgr.selected_frame().unwrap().id, f2);

        mgr.delete_frame(f1);
        assert_eq!(mgr.frame_list().len(), 1);
    }

    #[test]
    fn rect_contains() {
        crate::test_utils::init_test_tracing();
        let r = Rect::new(10.0, 20.0, 100.0, 50.0);
        assert!(r.contains(10.0, 20.0));
        assert!(r.contains(50.0, 40.0));
        assert!(!r.contains(9.0, 20.0));
        assert!(!r.contains(110.0, 70.0));
    }

    #[test]
    fn find_window_frame_id() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let wid = mgr.get(fid).unwrap().window_list()[0];

        assert_eq!(mgr.find_window_frame_id(wid), Some(fid));
        assert_eq!(mgr.find_window_frame_id(WindowId(99999)), None);
    }

    #[test]
    fn is_live_window_id() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let wid = mgr.get(fid).unwrap().window_list()[0];

        assert!(mgr.is_live_window_id(wid));
        assert!(!mgr.is_live_window_id(WindowId(99999)));
    }

    #[test]
    fn window_parameters() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let wid = mgr.get(fid).unwrap().window_list()[0];

        let key = Value::symbol("my-param");
        let val = Value::fixnum(42);

        // Initially no parameter
        assert!(mgr.window_parameter(wid, &key).is_none());

        mgr.set_window_parameter(wid, key, val);
        assert_eq!(mgr.window_parameter(wid, &key), Some(Value::fixnum(42)));
    }

    #[test]
    fn split_window_does_not_copy_window_parameters() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let wid = mgr.get(fid).unwrap().window_list()[0];
        let key = Value::symbol("my-param");

        mgr.set_window_parameter(wid, key, Value::fixnum(42));
        let new_wid = mgr
            .split_window(fid, wid, SplitDirection::Horizontal, BufferId(2), None)
            .expect("split");

        assert_eq!(mgr.window_parameter(wid, &key), Some(Value::fixnum(42)));
        assert_eq!(mgr.window_parameter(new_wid, &key), None);
    }

    #[test]
    fn deleted_window_retains_window_parameters() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let wid = mgr.get(fid).unwrap().window_list()[0];
        let other = mgr
            .split_window(fid, wid, SplitDirection::Horizontal, BufferId(2), None)
            .expect("split");
        let key = Value::symbol("deleted-param");

        mgr.set_window_parameter(other, key, Value::fixnum(7));
        assert!(mgr.delete_window(fid, other));
        assert_eq!(mgr.window_parameter(other, &key), Some(Value::fixnum(7)));
    }

    #[test]
    fn replace_buffer_in_windows() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let wid = mgr.get(fid).unwrap().window_list()[0];

        // Window should show buffer 1
        let frame = mgr.get(fid).unwrap();
        assert_eq!(
            frame.find_window(wid).unwrap().buffer_id(),
            Some(BufferId(1))
        );

        // Replace buffer 1 with buffer 2
        mgr.replace_buffer_in_windows(BufferId(1), BufferId(2));

        let frame = mgr.get(fid).unwrap();
        assert_eq!(
            frame.find_window(wid).unwrap().buffer_id(),
            Some(BufferId(2))
        );
    }

    #[test]
    fn deep_split_and_delete() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let w1 = mgr.get(fid).unwrap().window_list()[0];

        // Split w1 horizontally → w2
        let w2 = mgr
            .split_window(fid, w1, SplitDirection::Horizontal, BufferId(2), None)
            .unwrap();

        // Split w2 vertically → w3
        let w3 = mgr
            .split_window(fid, w2, SplitDirection::Vertical, BufferId(3), None)
            .unwrap();

        assert_eq!(mgr.get(fid).unwrap().window_count(), 3);

        // Delete w3
        assert!(mgr.delete_window(fid, w3));
        assert_eq!(mgr.get(fid).unwrap().window_count(), 2);

        // Delete w2
        assert!(mgr.delete_window(fid, w2));
        assert_eq!(mgr.get(fid).unwrap().window_count(), 1);

        // w1 is the last one, can't delete
        assert!(!mgr.delete_window(fid, w1));
    }

    #[test]
    fn note_window_selected_updates_use_time() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let w1 = mgr.get(fid).unwrap().window_list()[0];
        let w2 = mgr
            .split_window(fid, w1, SplitDirection::Horizontal, BufferId(2), None)
            .unwrap();

        let t1 = mgr.note_window_selected(w1);
        let t2 = mgr.note_window_selected(w2);
        // Each selection should get a monotonically increasing use-time
        assert!(t2 > t1);
    }

    #[test]
    fn window_set_buffer_resets_position() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let wid = mgr.get(fid).unwrap().window_list()[0];

        // Modify point
        let frame = mgr.get_mut(fid).unwrap();
        if let Some(w) = frame.find_window_mut(wid) {
            if let Window::Leaf { point, .. } = w {
                *point = 100;
            }
        }

        // Set buffer resets point to 1
        let frame = mgr.get_mut(fid).unwrap();
        if let Some(w) = frame.find_window_mut(wid) {
            w.set_buffer(BufferId(2));
        }

        let frame = mgr.get(fid).unwrap();
        let w = frame.find_window(wid).unwrap();
        if let Window::Leaf {
            point, buffer_id, ..
        } = w
        {
            assert_eq!(*buffer_id, BufferId(2));
            assert_eq!(*point, 1);
        }
    }

    #[test]
    fn frame_resize_pixelwise_updates_window_tree_and_invalidates_display_state() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let w1 = mgr.get(fid).unwrap().window_list()[0];
        let w2 = mgr
            .split_window(fid, w1, SplitDirection::Horizontal, BufferId(2), None)
            .unwrap();

        let frame = mgr.get_mut(fid).unwrap();
        frame.char_width = 10.0;
        frame.char_height = 20.0;
        frame.replace_display_snapshots(vec![WindowDisplaySnapshot {
            window_id: w1,
            ..WindowDisplaySnapshot::default()
        }]);

        frame
            .find_window_mut(w1)
            .unwrap()
            .set_window_end_from_positions(200, 200, 50, 50, 3);
        frame
            .find_window_mut(w2)
            .unwrap()
            .set_window_end_from_positions(200, 200, 60, 60, 3);

        frame.resize_pixelwise(400, 260);

        assert_eq!(frame.width, 400);
        assert_eq!(frame.height, 260);
        assert!(frame.display_snapshots.is_empty());
        assert_eq!(frame.parameters.get("width"), Some(&Value::fixnum(40)));
        assert_eq!(frame.parameters.get("height"), Some(&Value::fixnum(13)));

        let root_bounds = *frame.root_window.bounds();
        assert_eq!(root_bounds, Rect::new(0.0, 0.0, 400.0, 244.0));

        let mini_bounds = *frame.minibuffer_leaf.as_ref().unwrap().bounds();
        assert_eq!(mini_bounds, Rect::new(0.0, 244.0, 400.0, 16.0));

        assert_eq!(
            frame.find_window(w1).unwrap().bounds(),
            &Rect::new(0.0, 0.0, 200.0, 244.0)
        );
        assert_eq!(
            frame.find_window(w2).unwrap().bounds(),
            &Rect::new(200.0, 0.0, 200.0, 244.0)
        );
        assert_eq!(
            frame.find_window(w1).unwrap().window_end_valid(),
            Some(false)
        );
        assert_eq!(
            frame.find_window(w2).unwrap().window_end_valid(),
            Some(false)
        );
        assert_eq!(
            frame.minibuffer_leaf.as_ref().unwrap().window_end_valid(),
            Some(false)
        );
    }

    #[test]
    fn frame_resize_pixelwise_reserves_tab_bar_height_above_root_window_tree() {
        crate::test_utils::init_test_tracing();
        let mut mgr = FrameManager::new();
        let fid = mgr.create_frame("F1", 800, 600, BufferId(1));
        let frame = mgr.get_mut(fid).unwrap();
        frame.char_width = 10.0;
        frame.char_height = 20.0;
        frame
            .parameters
            .insert("tab-bar-lines".to_string(), Value::fixnum(1));

        frame.sync_tab_bar_height_from_parameters();
        frame.resize_pixelwise(400, 260);

        assert_eq!(frame.tab_bar_height, 20);
        assert_eq!(
            *frame.root_window.bounds(),
            Rect::new(0.0, 20.0, 400.0, 224.0)
        );
        assert_eq!(
            *frame.minibuffer_leaf.as_ref().unwrap().bounds(),
            Rect::new(0.0, 244.0, 400.0, 16.0)
        );
        assert_eq!(frame.parameters.get("height"), Some(&Value::fixnum(12)));
    }
}