paneru 0.5.2

A sliding, tiling window manager for MacOS.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
use bevy::app::{App, Plugin, Update};
use bevy::ecs::change_detection::{DetectChanges, DetectChangesMut, Ref};
use bevy::ecs::component::Component;
use bevy::ecs::entity::{Entity, EntityHashMap, EntityHashSet};
use bevy::ecs::hierarchy::ChildOf;
use bevy::ecs::query::{Changed, Has, Or, With, Without};
use bevy::ecs::schedule::IntoScheduleConfigs as _;
use bevy::ecs::schedule::common_conditions::{not, resource_exists};
use bevy::ecs::system::{Commands, ParamSet, Populated, Query, Res};
use bevy::math::IRect;
use std::collections::VecDeque;
use stdext::function_name;
use tracing::{Level, instrument, trace};

use crate::config::Config;
use crate::ecs::params::Windows;
use crate::ecs::workspace::SnapStripMarker;
use crate::ecs::{
    ActiveWorkspaceMarker, Bounds, DockPosition, EnsureVisibleMarker, Initializing, LayoutPosition,
    ManualStripOffset, Position, RepositionMarker, ReshuffleAroundMarker, Scrolling,
    SpawnCommandsExt,
};
use crate::errors::{Error, Result};
use crate::manager::{Display, Origin, Size, Window};
use crate::platform::WorkspaceId;
use crate::util::round_px;

/// The floor every window in a column is packed against. Heights that would
/// starve a sibling below it make [`binpack_heights`] fall back to averaging.
pub(crate) const MIN_WINDOW_HEIGHT: i32 = 200;

pub struct LayoutEventsPlugin;

/// How much of a hidden virtual workspace stays on its own display. Hiding a
/// workspace parks its strip this many pixels inside the display's bottom-right
/// corner, which keeps a small sliver on screen: macOS reassigns a window whose
/// frame has left the display entirely to whichever display it landed on.
pub(crate) const PARKED_STRIP_SLIVER: i32 = 10;

/// A strip, its entity, origin, display, whether it's the active one, and the
/// offset it is animating toward if a move is already in flight.
/// Shared by [`reshuffle_layout_strip`] and [`ensure_visible_in_strip`].
type StripPlacements<'w, 's> = Query<
    'w,
    's,
    (
        &'static LayoutStrip,
        Entity,
        &'static Position,
        &'static ChildOf,
        Option<Ref<'static, ActiveWorkspaceMarker>>,
        Option<&'static RepositionMarker>,
    ),
>;

/// Displays paired with the Dock's current edge, which is what turns a display's
/// raw bounds into the usable viewport.
type DisplayViewports<'w, 's> = Query<'w, 's, (&'static Display, Option<&'static DockPosition>)>;

/// A strip, its entity, its own scroll position, whether it's mid-swipe, and
/// its parent display. Used by [`position_layout_windows`] to build each
/// window's [`StripWindowContext`].
type StripsForWindowPositioning<'w, 's> = Query<
    'w,
    's,
    (
        Entity,
        &'static LayoutStrip,
        &'static Position,
        Has<Scrolling>,
        &'static ChildOf,
    ),
    With<LayoutStrip>,
>;

/// Windows whose size or origin changed this tick — either one means the strip
/// holding them has to re-run its layout.
type ResizedWindows<'w, 's> = Populated<
    'w,
    's,
    Entity,
    Or<(
        (Changed<Bounds>, With<Window>),
        (Changed<Position>, With<Window>),
    )>,
>;

/// Window frames as the layout writes them: the current origin, and the size and
/// slot the layout pass is free to overwrite.
type WindowFrames<'w, 's> = Query<
    'w,
    's,
    (
        &'static Position,
        &'static mut Bounds,
        &'static mut LayoutPosition,
    ),
    (Without<LayoutStrip>, With<Window>),
>;

/// Windows the layout just assigned a new slot to, with the frame fields that
/// slot has to be translated into.
type RepositionedWindows<'w, 's> = Populated<
    'w,
    's,
    (
        Entity,
        &'static Window,
        &'static LayoutPosition,
        &'static mut Position,
        &'static mut Bounds,
    ),
    (Changed<LayoutPosition>, With<Window>, Without<LayoutStrip>),
>;

/// Clamp a window origin to the range where it still touches both viewport
/// edges. For an oversized window this range is reversed: from right-aligned
/// to left-aligned, which lets the strip pan across the hidden content.
pub(crate) fn clamp_origin_to_viewport(origin: Origin, size: Size, viewport: IRect) -> Origin {
    let far_edge = viewport.max - size;
    let minimum = viewport.min.min(far_edge);
    let maximum = viewport.min.max(far_edge);
    origin.clamp(minimum, maximum)
}

/// How far a stored width may drift before a [`ManualStripOffset`] counts as
/// stale. `window_resized_update_frame` writes back the OS geometry, which can
/// land a pixel or two off the size the layout asked for.
const SIGNATURE_WIDTH_TOLERANCE: i32 = 2;

/// Fingerprints the shape of a strip for [`ManualStripOffset`]: the ordered
/// column tops with the widths they are heading for.
///
/// Column tops only, so promoting a tab or a stacked window to the front of its
/// column — which happens on every focus event — is not a layout change. Widths
/// from `moving_frame`, so a resize counts once it is requested rather than
/// once per animation frame. Neither depends on the strip's offset, which is
/// the point: scrolling must not invalidate a deliberate placement.
pub(crate) fn strip_signature(strip: &LayoutStrip, windows: &Windows) -> Vec<(Entity, i32)> {
    strip
        .all_columns()
        .into_iter()
        .filter_map(|entity| {
            windows
                .moving_frame(entity)
                .map(|frame| (entity, frame.width()))
        })
        .collect()
}

fn signature_matches(current: &[(Entity, i32)], stored: &[(Entity, i32)]) -> bool {
    current.len() == stored.len()
        && current.iter().zip(stored).all(|(now, before)| {
            now.0 == before.0 && (now.1 - before.1).abs() <= SIGNATURE_WIDTH_TOLERANCE
        })
}

/// The strip offset that shows all of a window sitting at `layout` within the
/// strip, starting from `origin` and moving no further than the window's
/// shortfall past a viewport edge. Returns `origin` unchanged when the window
/// already fits.
pub(crate) fn origin_exposing(
    layout: Origin,
    size: Size,
    origin: Origin,
    viewport: IRect,
) -> Origin {
    clamp_origin_to_viewport(layout + origin, size, viewport) - layout
}

impl Plugin for LayoutEventsPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(
            Update,
            (
                // Wait for finish_setup before tiling: until then every window
                // sits in the active strip regardless of its real display.
                (
                    layout_sizes_changed,
                    layout_strip_changed,
                    reshuffle_layout_strip,
                    ensure_visible_in_strip,
                    position_layout_strips,
                    position_layout_windows,
                )
                    .chain()
                    .after(super::systems::finish_setup)
                    .after(super::triggers::apply_window_positions)
                    .before(super::workspace::show_active_workspace)
                    .run_if(not(resource_exists::<Initializing>)),
            ),
        );
    }
}

/// Represents an item within a stack, which can either be a single window or a group of tabs.
#[derive(Clone, Debug, PartialEq)]
pub enum StackItem {
    /// A single window within the stack.
    Single(Entity),
    /// A group of tabs within the stack.
    Tabs(Vec<Entity>),
}

impl StackItem {
    /// Returns the top window entity in the item.
    pub fn top(&self) -> Option<Entity> {
        match self {
            StackItem::Single(id) => Some(*id),
            StackItem::Tabs(tabs) => tabs.first().copied(),
        }
    }

    /// Returns true if the item contains the specified entity.
    pub fn contains(&self, entity: Entity) -> bool {
        match self {
            StackItem::Single(id) => *id == entity,
            StackItem::Tabs(tabs) => tabs.contains(&entity),
        }
    }

    /// Returns an iterator over all window entities in this stack item.
    pub fn window_iter(&self) -> StackItemIter<'_> {
        match self {
            StackItem::Single(entity) => StackItemIter::Single(std::iter::once(*entity)),
            StackItem::Tabs(tabs) => StackItemIter::Tabs(tabs.iter().copied()),
        }
    }
}

pub enum StackItemIter<'a> {
    Single(std::iter::Once<Entity>),
    Tabs(std::iter::Copied<std::slice::Iter<'a, Entity>>),
}

impl Iterator for StackItemIter<'_> {
    type Item = Entity;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            StackItemIter::Single(iter) => iter.next(),
            StackItemIter::Tabs(iter) => iter.next(),
        }
    }
}

impl DoubleEndedIterator for StackItemIter<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        match self {
            StackItemIter::Single(iter) => iter.next_back(),
            StackItemIter::Tabs(iter) => iter.next_back(),
        }
    }
}

/// Represents a single panel within a `LayoutStrip`, which can either hold a single window, a stack of items, or a group of tabs.
#[derive(Clone, Debug)]
pub enum Column {
    /// A panel containing a single window, identified by its `Entity`.
    Single(Entity),
    /// A panel containing a stack of items (windows or tabs), ordered from top to bottom.
    Stack(Vec<StackItem>),
    /// A panel containing a group of native tabs.
    Tabs(Vec<Entity>),
    Fullscren(Entity),
}

impl Column {
    /// Returns the top window entity in the panel.
    /// For a `Single` panel, it's the contained window.
    /// For a `Stack` or `Tabs`, it's the first window in the vector.
    pub fn top(&self) -> Option<Entity> {
        match self {
            Column::Single(id) | Column::Fullscren(id) => Some(*id),
            Column::Stack(stack) => stack.first().and_then(StackItem::top),
            Column::Tabs(tabs) => tabs.first().copied(),
        }
    }

    /// Returns an iterator over all window entities in this column
    pub fn window_iter(&self) -> ColumnWindowIter<'_> {
        match self {
            Column::Single(entity) | Column::Fullscren(entity) => {
                ColumnWindowIter::Single(std::iter::once(*entity))
            }
            Column::Tabs(tabs) => ColumnWindowIter::Tabs(tabs.iter().copied()),
            Column::Stack(items) => {
                ColumnWindowIter::Stack(items.iter().flat_map(StackItem::window_iter))
            }
        }
    }

    pub fn width<W>(&self, get_window_frame: &W) -> Option<i32>
    where
        W: Fn(Entity) -> Option<IRect>,
    {
        self.window_iter()
            .filter_map(get_window_frame)
            .map(|frame| frame.width())
            .max()
    }

    /// Returns the entity at the given index, or the last entity if the index exceeds the size.
    pub fn at_or_last(&self, index: usize) -> Option<Entity> {
        match self {
            Column::Single(id) | Column::Fullscren(id) => Some(*id),
            Column::Stack(stack) => stack
                .get(index)
                .or_else(|| stack.last())
                .and_then(StackItem::top),
            Column::Tabs(tabs) => tabs.first().copied(),
        }
    }

    /// Returns the position of an entity within this column (0 for Single/Tabs, index for Stack).
    pub fn position_of(&self, entity: Entity) -> Option<usize> {
        match self {
            Column::Single(id) | Column::Fullscren(id) => (*id == entity).then_some(0),
            Column::Stack(stack) => stack.iter().position(|item| item.contains(entity)),
            Column::Tabs(tabs) => tabs.contains(&entity).then_some(0),
        }
    }

    /// Moves the specified entity to the front of stack-local ordering.
    /// Native tab ordering is stable; the focused tab is tracked by `FocusedMarker`.
    pub fn move_to_front(&mut self, entity: Entity) {
        match self {
            Column::Single(_) | Column::Fullscren(_) => {}
            Column::Stack(stack) => {
                if let Some(StackItem::Tabs(tabs)) =
                    stack.iter_mut().find(|item| item.contains(entity))
                    && let Some(pos) = tabs.iter().position(|&e| e == entity)
                {
                    tabs.swap(0, pos);
                }
            }
            Column::Tabs(tabs) => {
                if let Some(pos) = tabs.iter().position(|&e| e == entity) {
                    tabs.swap(0, pos);
                }
            }
        }
    }
}

pub enum ColumnWindowIter<'a> {
    Single(std::iter::Once<Entity>),
    Tabs(std::iter::Copied<std::slice::Iter<'a, Entity>>),
    Stack(
        std::iter::FlatMap<
            std::slice::Iter<'a, StackItem>,
            StackItemIter<'a>,
            fn(&'a StackItem) -> StackItemIter<'a>,
        >,
    ),
}

impl Iterator for ColumnWindowIter<'_> {
    type Item = Entity;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::Single(iter) => iter.next(),
            Self::Tabs(iter) => iter.next(),
            Self::Stack(iter) => iter.next(),
        }
    }
}

/// `LayoutStrip` manages a horizontal strip of `Panel`s, where each panel can contain a single window or a stack of windows.
/// It provides methods for manipulating the arrangement and access to windows within the pane.
#[derive(Component, Debug, Default)]
pub struct LayoutStrip {
    id: WorkspaceId,
    pub virtual_index: u32,
    columns: VecDeque<Column>,
    /// Entities belonging to a `Column::Stack` currently displayed as tabs (one visible, sharing
    /// the full column rect) instead of split heights. Membership, not a `Column` variant — a Stack
    /// is "tabbed" iff any of its member entities is in this set; the invariant that either all or
    /// none of one Stack's members are present is maintained by `toggle_tabbed_display` and by the
    /// cleanup in `remove_column`/ `unstack`/`stack`. This is deliberately independent of
    /// `Column::Tabs`/`StackItem::Tabs` (native-OS-tab detection, see `tabbed`/`tab_group` below)
    /// and of `LayoutStrip::tabbed()`, which callers like
    /// `apply_window_positions`/`give_away_focus` already key off for that unrelated feature.
    tabbed_stacks: EntityHashSet,
}

impl LayoutStrip {
    pub fn new(id: WorkspaceId, virtual_index: u32) -> Self {
        Self {
            id,
            virtual_index,
            columns: VecDeque::new(),
            tabbed_stacks: EntityHashSet::default(),
        }
    }

    pub fn fullscreen(id: WorkspaceId, entity: Entity) -> Self {
        let mut columns = VecDeque::new();
        columns.push_back(Column::Fullscren(entity));
        Self {
            id,
            virtual_index: 0,
            columns,
            tabbed_stacks: EntityHashSet::default(),
        }
    }

    /// Finds the index of a window within the pane.
    /// If the window is part of a stack, it returns the index of the panel containing the stack.
    ///
    /// # Arguments
    ///
    /// * `entity` - Entity of the window to find.
    ///
    /// # Returns
    ///
    /// `Ok(usize)` with the index if found, otherwise `Err(Error)`.
    pub fn index_of(&self, entity: Entity) -> Result<usize> {
        self.columns
            .iter()
            .position(|column| match column {
                Column::Single(id) | Column::Fullscren(id) => *id == entity,
                Column::Stack(stack) => stack.iter().any(|item| item.contains(entity)),
                Column::Tabs(stack) => stack.contains(&entity),
            })
            .ok_or(Error::NotFound(format!(
                "{}: can not find window {entity} in the current pane.",
                function_name!()
            )))
    }

    /// Returns `true` if the strip contains the given entity.
    pub fn contains(&self, entity: Entity) -> bool {
        self.columns.iter().any(|column| match column {
            Column::Single(id) | Column::Fullscren(id) => *id == entity,
            Column::Stack(stack) => stack.iter().any(|item| item.contains(entity)),
            Column::Tabs(stack) => stack.contains(&entity),
        })
    }

    /// Inserts a window ID into the pane at a specified position.
    /// The new window will be placed as a `Single` panel.
    ///
    /// # Arguments
    ///
    /// * `after` - The index at which to insert the window. If `after` is greater than or equal to the entity length,
    ///   the window is appended to the end.
    /// * `entity` - Entity of the window to insert.
    pub fn insert_at(&mut self, index: usize, entity: Entity) {
        if index >= self.len() {
            self.columns.push_back(Column::Single(entity));
        } else {
            self.columns.insert(index, Column::Single(entity));
        }
    }

    /// Appends a window ID as a `Single` panel to the end of the pane.
    ///
    /// # Arguments
    ///
    /// * `entity` - Entity of the window to append.
    pub fn append(&mut self, entity: Entity) {
        if self.contains(entity) {
            return;
        }
        self.columns.push_back(Column::Single(entity));
    }

    pub(crate) fn append_strip(&mut self, other: &mut Self) {
        self.columns.append(&mut other.columns);
    }

    pub fn append_tab_group(&mut self, entities: &[Entity]) {
        let group = dedup_entities(entities);
        if group.is_empty() {
            return;
        }

        // Re-grouping existing members keeps them at their lowest current index;
        // a foreign group lands at the end.
        let index = group
            .iter()
            .filter_map(|entity| self.index_of(*entity).ok())
            .min()
            .unwrap_or(self.len());

        self.insert_tab_group_at(index, &group);
    }

    /// Inserts `entities` as a single column at `index` (clamped to the column
    /// count), after removing any existing occurrences. A one-element group
    /// becomes a `Single` column, more than one a `Tabs` column.
    pub fn insert_tab_group_at(&mut self, index: usize, entities: &[Entity]) {
        let group = dedup_entities(entities);
        if group.is_empty() {
            return;
        }

        for entity in &group {
            self.remove(*entity);
        }

        let index = index.min(self.len());
        if group.len() == 1 {
            self.insert_at(index, group[0]);
        } else if index >= self.len() {
            self.columns.push_back(Column::Tabs(group));
        } else {
            self.columns.insert(index, Column::Tabs(group));
        }
    }

    /// Converts a column containing `leader` to a `Tabs` column and adds `follower`.
    pub fn convert_to_tabs(&mut self, leader: Entity, follower: Entity) -> Result<()> {
        self.remove(follower);
        let index = self.index_of(leader)?;
        let column = self.columns.remove(index).unwrap();
        match column {
            Column::Single(id) | Column::Fullscren(id) => {
                self.columns.insert(index, Column::Tabs(vec![follower, id]));
            }
            Column::Stack(mut items) => {
                if let Some(pos) = items.iter().position(|item| item.contains(leader)) {
                    match &mut items[pos] {
                        StackItem::Single(id) => {
                            let id = *id;
                            items[pos] = StackItem::Tabs(vec![follower, id]);
                        }
                        StackItem::Tabs(tabs) => {
                            if !tabs.contains(&follower) {
                                tabs.insert(0, follower);
                            }
                        }
                    }
                }
                self.columns.insert(index, Column::Stack(items));
            }
            Column::Tabs(mut tabs) => {
                if !tabs.contains(&follower) {
                    tabs.insert(0, follower);
                }
                self.columns.insert(index, Column::Tabs(tabs));
            }
        }
        Ok(())
    }

    /// Removes a window ID from the pane.
    /// If the window is part of a stack or tabs, it is removed from the vector.
    /// If the collection becomes empty or contains only one window, the panel type adjusts accordingly.
    ///
    /// # Arguments
    ///
    /// * `entity` - Entity of the window to remove.
    pub fn remove(&mut self, entity: Entity) {
        let removed = self
            .index_of(entity)
            .ok()
            .and_then(|index| self.columns.remove(index).zip(Some(index)));

        if let Some((column, index)) = removed {
            match column {
                Column::Single(_) | Column::Fullscren(_) => {
                    // Already removed from self.columns.
                }
                Column::Stack(mut stack) => {
                    self.tabbed_stacks.remove(&entity);
                    for item in &mut stack {
                        match item {
                            StackItem::Single(_) => {}
                            StackItem::Tabs(tabs) => {
                                tabs.retain(|id| *id != entity);
                            }
                        }
                    }
                    stack.retain(|item| match item {
                        StackItem::Single(id) => *id != entity,
                        StackItem::Tabs(tabs) => !tabs.is_empty(),
                    });
                    if stack.len() > 1 {
                        self.columns.insert(index, Column::Stack(stack));
                    } else if let Some(remaining_item) = stack.first() {
                        // A single surviving item can no longer be a tabbed
                        // display (nothing left to switch between) — drop
                        // its membership so a stale entry can't linger.
                        for e in remaining_item.window_iter() {
                            self.tabbed_stacks.remove(&e);
                        }
                        match remaining_item {
                            StackItem::Single(id) => {
                                self.columns.insert(index, Column::Single(*id));
                            }
                            StackItem::Tabs(tabs) => {
                                self.columns.insert(index, Column::Tabs(tabs.clone()));
                            }
                        }
                    }
                }
                Column::Tabs(mut tabs) => {
                    tabs.retain(|id| *id != entity);
                    if tabs.len() > 1 {
                        self.columns.insert(index, Column::Tabs(tabs));
                    } else if let Some(remaining_id) = tabs.first() {
                        self.columns.insert(index, Column::Single(*remaining_id));
                    }
                }
            }
        }
    }

    /// Retrieves the `Panel` at a specified index in the pane.
    ///
    /// # Arguments
    ///
    /// * `at` - The index from which to retrieve the panel.
    ///
    /// # Returns
    ///
    /// `Ok(Panel)` with the panel if the index is valid, otherwise `Err(Error)`.
    pub fn get(&self, at: usize) -> Result<Column> {
        self.columns
            .get(at)
            .cloned()
            .ok_or(Error::InvalidInput(format!(
                "{}: {at} out of bounds",
                function_name!()
            )))
    }

    /// Swaps the positions of two panels within the pane.
    ///
    /// # Arguments
    ///
    /// * `left` - The index of the first panel.
    /// * `right` - The index of the second panel.
    pub fn swap(&mut self, left: usize, right: usize) {
        self.columns.swap(left, right);
    }

    /// Returns the number of panels in the pane.
    ///
    /// # Returns
    ///
    /// The number of panels as `usize`.
    pub fn len(&self) -> usize {
        self.columns.len()
    }

    /// Returns the first `Panel` in the pane.
    ///
    /// # Returns
    ///
    /// `Ok(Panel)` with the first panel, otherwise `Err(Error)` if the pane is empty.
    pub fn first(&self) -> Result<Column> {
        self.columns.front().cloned().ok_or(Error::NotFound(format!(
            "{}: can not find first element.",
            function_name!()
        )))
    }

    /// Returns the last `Panel` in the pane.
    ///
    /// # Returns
    ///
    /// `Ok(Panel)` with the last panel, otherwise `Err(Error)` if the pane is empty.
    pub fn last(&self) -> Result<Column> {
        self.columns.back().cloned().ok_or(Error::NotFound(format!(
            "{}: can not find last element.",
            function_name!()
        )))
    }

    pub fn right_neighbour(&self, entity: Entity) -> Option<Entity> {
        let index = self.index_of(entity).ok()?;
        let stack_pos = self.columns.get(index)?.position_of(entity)?;
        (index < self.columns.len())
            .then_some(index + 1)
            .and_then(|i| self.columns.get(i))
            .and_then(|col| col.at_or_last(stack_pos))
    }

    pub fn left_neighbour(&self, entity: Entity) -> Option<Entity> {
        let index = self.index_of(entity).ok()?;
        let stack_pos = self.columns.get(index)?.position_of(entity)?;
        (index > 0)
            .then(|| index - 1)
            .and_then(|i| self.columns.get(i))
            .and_then(|col| col.at_or_last(stack_pos))
    }

    /// Stacks the window with the given ID onto the panel to its left.
    /// If the window is already in a stack or is the leftmost window, no action is taken.
    ///
    /// # Arguments
    ///
    /// * `entity` - Entity of the window to stack.
    ///
    /// # Returns
    ///
    /// `Ok(())` if the stacking is successful or not needed, otherwise `Err(Error)` if the window is not found.
    pub fn stack(&mut self, entity: Entity) -> Result<()> {
        let index = self.index_of(entity)?;
        if index == 0 {
            // Can not stack to the left if left most window already.
            return Ok(());
        }

        let column_to_stack = self.columns.remove(index).unwrap();
        let items_to_stack = match column_to_stack {
            Column::Fullscren(_) => return Ok(()),
            Column::Single(id) => vec![StackItem::Single(id)],
            Column::Tabs(tabs) => vec![StackItem::Tabs(tabs)],
            Column::Stack(items) => items,
        };

        let target_column = self.columns.remove(index - 1).unwrap();
        // If the column being merged into is already a tabbed display, the
        // newly-joined items must join `tabbed_stacks` too — otherwise the
        // merged Stack would end up with a mix of tabbed and split members,
        // which `relative_positions`'s tabbed-column geometry branch isn't
        // designed to represent.
        if let Column::Stack(items) = &target_column
            && items
                .iter()
                .flat_map(StackItem::window_iter)
                .any(|e| self.tabbed_stacks.contains(&e))
        {
            for item in &items_to_stack {
                self.tabbed_stacks.extend(item.window_iter());
            }
        }
        let new_column = match target_column {
            Column::Fullscren(_) => return Ok(()),
            Column::Single(id) => {
                Column::Stack([vec![StackItem::Single(id)], items_to_stack].concat())
            }
            Column::Tabs(tabs) => {
                Column::Stack([vec![StackItem::Tabs(tabs)], items_to_stack].concat())
            }
            Column::Stack(items) => Column::Stack([items, items_to_stack].concat()),
        };

        self.columns.insert(index - 1, new_column);
        Ok(())
    }

    /// Unstacks the window with the given ID from its entity stack.
    /// If the window is in a single panel, no action is taken.
    ///
    /// # Arguments
    ///
    /// * `entity` - Entity of the window to unstack.
    ///
    /// # Returns
    ///
    /// `Ok(())` if the unstacking is successful or not needed, otherwise `Err(Error)` if the window is not found.
    pub fn unstack(&mut self, entity: Entity) -> Result<()> {
        let index = self.index_of(entity)?;
        let column = self.columns.remove(index).unwrap();

        if let Column::Stack(mut items) = column {
            let item_index = items
                .iter()
                .position(|item| item.contains(entity))
                .ok_or(Error::NotFound(format!("Entity {entity} not in stack")))?;

            let removed_item = items.remove(item_index);

            // The unstacked item no longer shares a column with its former
            // stack-mates, so it can't remain part of a tabbed display.
            for e in removed_item.window_iter() {
                self.tabbed_stacks.remove(&e);
            }

            // Re-insert the unstacked item as a single/tabs panel
            let unstacked_column = match removed_item {
                StackItem::Single(id) => Column::Single(id),
                StackItem::Tabs(tabs) => Column::Tabs(tabs),
            };
            self.columns.insert(index, unstacked_column);

            // Re-insert the modified stack (if not empty) at the original position
            if !items.is_empty() {
                let new_column = if items.len() == 1 {
                    // A single surviving item can no longer be a tabbed
                    // display — drop its membership (see remove_column).
                    for e in items[0].window_iter() {
                        self.tabbed_stacks.remove(&e);
                    }
                    match items.remove(0) {
                        StackItem::Single(id) => Column::Single(id),
                        StackItem::Tabs(tabs) => Column::Tabs(tabs),
                    }
                } else {
                    Column::Stack(items)
                };
                self.columns.insert(index, new_column);
            }
            Ok(())
        } else {
            // Not in a stack, put it back
            self.columns.insert(index, column);
            Ok(())
        }
    }

    /// Returns a vector of all window IDs present in all panels within the pane, maintaining their order.
    /// For stacked panels, all windows in the stack are included.
    ///
    /// # Returns
    ///
    /// A `Vec<Entity>` containing all window IDs.
    pub fn all_windows(&self) -> Vec<Entity> {
        self.columns
            .iter()
            .flat_map(|column| match column {
                Column::Single(entity) | Column::Fullscren(entity) => vec![*entity],
                Column::Stack(items) => items.iter().flat_map(StackItem::window_iter).collect(),
                Column::Tabs(ids) => ids.clone(),
            })
            .collect()
    }

    pub fn get_column_mut(&mut self, index: usize) -> Option<&mut Column> {
        self.columns.get_mut(index)
    }

    pub fn all_columns(&self) -> Vec<Entity> {
        self.columns.iter().filter_map(Column::top).collect()
    }

    pub fn id(&self) -> WorkspaceId {
        self.id
    }

    pub fn columns(&self) -> impl Iterator<Item = &Column> {
        self.columns.iter()
    }

    #[instrument(level = Level::TRACE, skip_all, fields(layout_strip_height))]
    pub fn relative_positions<W>(
        &self,
        layout_strip_height: i32,
        get_window_frame: &W,
    ) -> impl Iterator<Item = (Entity, IRect)>
    where
        W: Fn(Entity) -> Option<IRect>,
    {
        self.column_positions(get_window_frame)
            .filter_map(move |(column, position)| {
                let items: Vec<StackItem> = match column {
                    Column::Single(entity) | Column::Fullscren(entity) => {
                        vec![StackItem::Single(*entity)]
                    }
                    Column::Stack(stack) => stack.clone(),
                    Column::Tabs(tabs) => vec![StackItem::Tabs(tabs.clone())],
                };

                // A tabbed display shares one frame across every member,
                // sized to the whole column — the same "shared frame" idiom
                // this function already uses for native-tab `StackItem::Tabs`
                // members, just applied to the whole outer Stack. This also
                // sidesteps `binpack_heights`'s `MIN_WINDOW_HEIGHT` capacity
                // limit entirely, since it isn't called for this branch.
                let is_tabbed_column = matches!(column, Column::Stack(_))
                    && items
                        .iter()
                        .flat_map(StackItem::window_iter)
                        .any(|e| self.tabbed_stacks.contains(&e));

                let heights = if is_tabbed_column {
                    vec![layout_strip_height; items.len()]
                } else {
                    let current_heights = items
                        .iter()
                        .filter_map(|item| item.top().and_then(get_window_frame))
                        .map(|frame| frame.height())
                        .collect::<Vec<_>>();
                    binpack_heights(&current_heights, MIN_WINDOW_HEIGHT, layout_strip_height)?
                };

                // Every window in a column shares the master's (top item's)
                // width, so a window stacked onto a master of a different width
                // resizes to match it instead of keeping its own width. This
                // also matches the column slot width from column_positions,
                // which is the widest member.
                let column_width = items
                    .first()
                    .and_then(StackItem::top)
                    .and_then(&get_window_frame)
                    .map(|frame| frame.width())?;

                let mut next_y = 0;
                let frames = items
                    .into_iter()
                    .zip(heights)
                    .filter_map(|(item, height)| {
                        let entity = item.top()?;
                        let mut frame = get_window_frame(entity)?;
                        frame.min.x = position;
                        frame.max.x = frame.min.x + column_width;

                        frame.min.y = next_y;
                        frame.max.y = frame.min.y + height;

                        if !is_tabbed_column {
                            next_y = frame.max.y;
                        }

                        // Return ALL windows in the item with the same frame
                        let results = item.window_iter().map(|e| (e, frame)).collect::<Vec<_>>();
                        Some(results)
                    })
                    .flatten()
                    .collect::<Vec<_>>();

                Some(frames)
            })
            .flatten()
    }

    #[instrument(level = Level::TRACE, skip_all)]
    pub fn column_positions<W>(&self, get_window_frame: &W) -> impl Iterator<Item = (&Column, i32)>
    where
        W: Fn(Entity) -> Option<IRect>,
    {
        let mut left_edge = 0;

        self.columns().filter_map(move |column| {
            let width = column.width(get_window_frame);

            width.map(|width| {
                let temp = left_edge;
                left_edge += width;
                (column, temp)
            })
        })
    }

    pub fn above(&self, entity: Entity) -> Option<Entity> {
        let index = self.index_of(entity).ok()?;
        let column = self.get(index).ok()?;
        match column {
            Column::Single(_) | Column::Tabs(_) | Column::Fullscren(_) => None,
            Column::Stack(items) => {
                let pos = items.iter().position(|item| item.contains(entity))?;
                (pos > 0).then(|| items[pos - 1].top()).flatten()
            }
        }
    }

    pub fn tabbed(&self, entity: Entity) -> bool {
        self.index_of(entity)
            .and_then(|idx| self.get(idx))
            .map(|col| match col {
                Column::Tabs(tabs) => tabs.contains(&entity),
                Column::Stack(items) => items.iter().any(|item| {
                    if let StackItem::Tabs(tabs) = item {
                        tabs.contains(&entity)
                    } else {
                        false
                    }
                }),
                Column::Single(_) | Column::Fullscren(_) => false,
            })
            .is_ok_and(|t| t)
    }

    pub fn tab_group(&self, entity: Entity) -> Option<Vec<Entity>> {
        self.columns.iter().find_map(|column| match column {
            Column::Tabs(tabs) if tabs.contains(&entity) && tabs.len() > 1 => Some(tabs.clone()),
            Column::Stack(items) => items.iter().find_map(|item| match item {
                StackItem::Tabs(tabs) if tabs.contains(&entity) && tabs.len() > 1 => {
                    Some(tabs.clone())
                }
                StackItem::Single(_) | StackItem::Tabs(_) => None,
            }),
            Column::Single(_) | Column::Fullscren(_) | Column::Tabs(_) => None,
        })
    }

    pub fn is_fullscreen(&self) -> bool {
        self.columns
            .front()
            .is_some_and(|column| matches!(column, Column::Fullscren(_)))
    }

    /// Toggles tabbed display (one window visible at a time, sharing the
    /// full column rect) for the `Column::Stack` containing `entity`.
    /// Returns `None` — not applicable, nothing changed — unless `entity` is
    /// in a `Stack` with more than one item; matches niri, where the toggle
    /// is only meaningful on a column that actually holds multiple windows.
    /// `None` is distinct from `Some(false)` (successfully toggled *off*) so
    /// callers can tell "did nothing" from "turned tabs off" instead of
    /// reporting both the same way.
    ///
    /// Returns `Some(is_tabbed)` — whether the column is tabbed after the
    /// call — when the toggle actually applied.
    pub fn toggle_tabbed_display(&mut self, entity: Entity) -> Option<bool> {
        let index = self.index_of(entity).ok()?;
        let Column::Stack(items) = self.get(index).ok()? else {
            return None;
        };
        if items.len() < 2 {
            return None;
        }
        let members: Vec<Entity> = items.iter().flat_map(StackItem::window_iter).collect();
        let now_tabbed = !members.iter().any(|e| self.tabbed_stacks.contains(e));
        if now_tabbed {
            self.tabbed_stacks.extend(members);
        } else {
            for member in members {
                self.tabbed_stacks.remove(&member);
            }
        }
        Some(now_tabbed)
    }

    /// Whether `entity` belongs to a `Column::Stack` currently displayed as
    /// tabs. Independent of `tabbed()` (native-OS-tab detection).
    pub fn is_tabbed_display(&self, entity: Entity) -> bool {
        self.tabbed_stacks.contains(&entity)
    }

    /// Given `entity` in a tabbed `Column::Stack`, returns the next tab,
    /// falling back to the previous one when `entity` is last. Used only by
    /// the close-active-tab focus fallback — normal cycling reuses
    /// `Operation::Focus` North/South directly.
    pub fn tab_display_sibling(&self, entity: Entity) -> Option<Entity> {
        let index = self.index_of(entity).ok()?;
        let Column::Stack(items) = self.get(index).ok()? else {
            return None;
        };
        let pos = items.iter().position(|item| item.contains(entity))?;
        items
            .get(pos + 1)
            .or_else(|| pos.checked_sub(1).and_then(|p| items.get(p)))
            .and_then(StackItem::top)
    }
}

impl std::fmt::Display for LayoutStrip {
    /// Formats the `LayoutStrip` for display, showing the arrangement of its panels.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let out = self
            .columns
            .iter()
            .map(|column| format!("{column:?}"))
            .collect::<Vec<_>>();
        write!(f, "[{}]", out.join(", "))
    }
}

/// Deduplicates `entities`, preserving first-seen order.
fn dedup_entities(entities: &[Entity]) -> Vec<Entity> {
    let mut seen = EntityHashSet::default();
    entities
        .iter()
        .copied()
        .filter(|entity| seen.insert(*entity))
        .collect()
}

fn binpack_heights(heights: &[i32], min_height: i32, total_height: i32) -> Option<Vec<i32>> {
    let mut count = heights.len();
    let mut output = vec![];

    loop {
        let mut idx = 0;

        let mut remaining = total_height;
        while idx < count {
            let remaining_windows = heights.len() - idx;

            if heights[idx] < remaining {
                if idx + 1 == count {
                    output.push(remaining);
                } else {
                    output.push(heights[idx]);
                }
                remaining -= heights[idx];
            } else if remaining >= min_height * i32::try_from(remaining_windows).ok()? {
                output.push(remaining);
                remaining = 0;
            } else {
                break;
            }
            idx += 1;
        }

        if idx == count {
            break;
        }
        count -= 1;
        output.clear();
    }

    let remaining = i32::try_from(heights.len() - count).ok()?;
    if remaining > 0 && count > 0 {
        count -= 1;
        output.truncate(count);
        let sum = output.iter().sum::<i32>();
        // Integer division (floor) on purpose: rounding here could make the
        // heights sum past `total_height`.
        let avg_height = (total_height - sum) / (remaining + 1);
        if avg_height < min_height {
            return None;
        }

        while count < heights.len() {
            output.push(avg_height);
            count += 1;
        }
    }

    Some(output)
}

/// Watches for size changes to windows and if they are changed, signals to the layout strip.
#[instrument(level = Level::DEBUG, skip_all)]
fn layout_sizes_changed(changed_sizes: ResizedWindows, workspaces: Query<&mut LayoutStrip>) {
    let changed_entities = changed_sizes.iter().collect::<EntityHashSet>();
    workspaces.into_iter().for_each(|mut strip| {
        if strip_has_changed_window(&strip, &changed_entities) {
            strip.set_changed();
        }
    });
}

fn strip_has_changed_window(strip: &LayoutStrip, changed_entities: &EntityHashSet) -> bool {
    strip
        .columns
        .iter()
        .any(|column| column_has_changed_window(column, changed_entities))
}

fn column_has_changed_window(column: &Column, changed_entities: &EntityHashSet) -> bool {
    match column {
        Column::Single(entity) | Column::Fullscren(entity) => changed_entities.contains(entity),
        Column::Stack(stack) => stack
            .iter()
            .any(|item| stack_item_has_changed_window(item, changed_entities)),
        Column::Tabs(entities) => entities
            .iter()
            .any(|entity| changed_entities.contains(entity)),
    }
}

fn stack_item_has_changed_window(item: &StackItem, changed_entities: &EntityHashSet) -> bool {
    match item {
        StackItem::Single(entity) => changed_entities.contains(entity),
        StackItem::Tabs(entities) => entities
            .iter()
            .any(|entity| changed_entities.contains(entity)),
    }
}

/// Watches for changes to `LayoutStrip` (i.e. a window added or window order changed) and
/// re-calculates the logical positions of all the windows in the layout strip.
#[instrument(level = Level::DEBUG, skip_all)]
fn layout_strip_changed(
    changed_strips: Populated<(&LayoutStrip, &ChildOf), Changed<LayoutStrip>>,
    mut windows: WindowFrames,
    displays: DisplayViewports,
    config: Res<Config>,
) {
    let get_window_frame = |entity| {
        windows
            .get(entity)
            .map(|(position, bounds, _)| IRect::from_corners(position.0, position.0 + bounds.0))
            .ok()
    };

    let changed = changed_strips
        .into_iter()
        .filter_map(|(layout_strip, child_of)| {
            displays
                .get(child_of.parent())
                .map(|(display, dock)| {
                    let height = display.actual_display_bounds(dock, &config).height();
                    layout_strip.relative_positions(height, &get_window_frame)
                })
                .ok()
        })
        .flatten()
        .collect::<Vec<_>>();

    for (entity, frame) in changed {
        if let Ok((_, mut bounds, mut layout_position)) = windows.get_mut(entity) {
            if layout_position.0 != frame.min {
                layout_position.0 = frame.min;
            }
            if bounds.0 != frame.size() {
                bounds.0 = frame.size();
            }
        }
    }
}

#[instrument(level = Level::DEBUG, skip_all)]
fn reshuffle_layout_strip(
    markers: Query<(Entity, &LayoutPosition), With<ReshuffleAroundMarker>>,
    strips: StripPlacements,
    manual_offsets: Query<&ManualStripOffset>,
    displays: DisplayViewports,
    windows: Windows,
    config: Res<Config>,
    mut commands: Commands,
) {
    markers.into_iter().for_each(|(entity, layout_position)| {
        if let Ok(mut cmd) = commands.get_entity(entity) {
            cmd.try_remove::<ReshuffleAroundMarker>();
        }
        let Some((strip, strip_entity, active_strip, child, active_marker, strip_reposition)) =
            strips.into_iter().find(|strip| strip.0.contains(entity))
        else {
            return;
        };

        if active_marker.is_some_and(|m| m.is_added()) {
            trace!("reshuffle_layout_strip: skipping newly active workspace {strip_entity}");
            return;
        }
        let Ok((active_display, dock)) = displays.get(child.parent()) else {
            return;
        };
        let display_bounds = active_display.actual_display_bounds(dock, &config);
        let Some(mut frame) = windows.moving_frame(entity) else {
            return;
        };

        let size = frame.size();
        let visible_width = display_bounds.intersect(frame).width();

        // A deliberate offset (center, snap) outranks the derived one, but only
        // while the window this reshuffle is about is still fully on screen: a
        // focus event for a window scrolled past an edge has to bring it back,
        // and at that point the placement is stale. Project against the strip's
        // *target* offset — mid-animation the window's own frame is a tick
        // behind a strip that is still moving.
        if let Ok(manual) = manual_offsets.get(strip_entity) {
            // The offset only ever meant "the user placed *this* layout here",
            // so a strip that has since gained, lost, reordered or resized a
            // column no longer has a placement to keep.
            let current = strip_signature(strip, &windows);
            let strip_target = strip_reposition.map_or(active_strip.0, |reposition| reposition.0);
            let projected = layout_position.0 + strip_target;
            if signature_matches(&current, &manual.signature)
                && clamp_origin_to_viewport(projected, size, display_bounds) == projected
            {
                trace!("reshuffle_layout_strip: keeping manual offset on {strip_entity}");
                return;
            }
            trace!("reshuffle_layout_strip: manual offset on {strip_entity} is stale");
            if let Ok(mut cmd) = commands.get_entity(strip_entity) {
                cmd.try_remove::<ManualStripOffset>();
            }
        }

        // Expose the window by clamping it into the viewport.
        frame.min = clamp_origin_to_viewport(frame.min, size, display_bounds);
        frame.max = frame.min + size;

        let mut strip_position = (frame.min - layout_position.0).with_y(display_bounds.min.y);

        // Enforce the edge invariant when auto-center is off: the leftmost
        // window must touch the left edge and the rightmost the right edge
        // if more than 1 windows in workspace.
        if !config.auto_center()
            && !config.continuous_swipe()
            && let Some(total_strip_width) = strip
                .last()
                .ok()
                .and_then(|column| column.top())
                .and_then(|last| {
                    windows
                        .layout_position(last)
                        .map(|position| position.0.x)
                        .zip(windows.moving_frame(last).map(|frame| frame.width()))
                })
                .map(|(last_x, last_width)| last_x + last_width)
        {
            strip_position.x = if display_bounds.width() < total_strip_width {
                strip_position.x.clamp(
                    display_bounds.max.x - total_strip_width,
                    display_bounds.min.x,
                )
            } else {
                // Strip fits entirely: pin the leftmost window to the left edge.
                display_bounds.min.x
            };
        }

        // Check how much of the window is hidden. Slivers don't count as
        // meaningfully visible, so subtract sliver_width from the visible
        // portion. If the hidden fraction is within the allowed ratio, skip.
        let hidden_ratio = config.window_hidden_ratio();
        if hidden_ratio > 0.0 {
            let meaningful = (visible_width - config.sliver_width()).max(0);
            let visible_fraction = f64::from(meaningful) / f64::from(frame.width().max(1));
            let hidden_fraction = 1.0 - visible_fraction;

            // Do not move the window if the hidden fraction is lower than threshold
            // or if the layout strip movement is shorter than the hidden width.
            let strip_movement = (active_strip.x - strip_position.x).abs();
            if hidden_fraction <= hidden_ratio && frame.width() - visible_width >= strip_movement {
                return;
            }
        }

        trace!("reshuffle_layout_strip: triggered for entity {entity}, offset {strip_position}");
        commands.reposition_entity(strip_entity, strip_position);
    });
}

/// Scrolls the strip the minimum amount needed to keep `EnsureVisibleMarker`
/// entities on-screen at their new layout position. If the entity already fits
/// inside the viewport with the strip where it is, the strip is left alone and
/// the per-window animator slides the entity into its slot. Only when the new
/// slot would fall past an edge does the strip translate, and only by the
/// shortfall — never to anchor the entity to a particular position.
#[allow(clippy::type_complexity)]
#[instrument(level = Level::DEBUG, skip_all)]
fn ensure_visible_in_strip(
    markers: Query<(Entity, &LayoutPosition, &EnsureVisibleMarker)>,
    mut strip_params: ParamSet<(
        StripPlacements,
        Query<&mut Position, (With<LayoutStrip>, Without<Window>)>,
    )>,
    displays: DisplayViewports,
    windows: Windows,
    config: Res<Config>,
    mut commands: Commands,
) {
    for (entity, layout_position, marker) in markers {
        if let Ok(mut cmd) = commands.get_entity(entity) {
            cmd.try_remove::<EnsureVisibleMarker>();
        }
        // Each marker is independent, and its own marker was already consumed
        // above: bailing out of the loop would silently drop the rest.
        // Copied out of the `StripPlacements` borrow so it can be dropped
        // before the `&mut Position` query below is touched — Bevy treats
        // the two queries as conflicting system params even though they're
        // never live at the same time here.
        let Some((strip_entity, display_entity, strip_target, is_new_activation)) = strip_params
            .p0()
            .into_iter()
            .find(|s| s.0.contains(entity))
            .map(
                |(_, strip_entity, strip_position, child, active_marker, strip_reposition)| {
                    let target = strip_reposition.map_or(strip_position.0, |r| r.0);
                    (
                        strip_entity,
                        child.parent(),
                        target,
                        active_marker.is_some_and(|m| m.is_added()),
                    )
                },
            )
        else {
            continue;
        };

        if is_new_activation {
            trace!("ensure_visible_in_strip: skipping newly active workspace {strip_entity}");
            continue;
        }
        let Ok((display, dock)) = displays.get(display_entity) else {
            continue;
        };
        let Some(size) = windows.size(entity) else {
            continue;
        };
        let viewport = display.actual_display_bounds(dock, &config);

        // Where the entity would appear once the strip settles. Mid-animation
        // the strip's current position is on its way somewhere else, so the
        // target offset is what the window's slot will actually be measured
        // against - the same projection `reshuffle_layout_strip` makes.
        let candidate_min = layout_position.0 + strip_target;
        // Clamp into the viewport. If already on-screen, this is a no-op and
        // the strip target equals its current position — no movement.
        let clamped_min = clamp_origin_to_viewport(candidate_min, size, viewport);
        if clamped_min == candidate_min {
            continue;
        }
        // Both axes come from the clamp: it is still the minimum shortfall, and
        // keeping the strip's own y here would silently drop the vertical
        // correction for a window sitting above the menu bar.
        let scroll_to = clamped_min - layout_position.0;
        trace!("ensure_visible_in_strip: entity {entity}, scroll strip to {scroll_to}");
        // Scrolling to expose a window overrides whatever the user placed here.
        if let Ok(mut cmd) = commands.get_entity(strip_entity) {
            cmd.try_remove::<ManualStripOffset>();
        }
        if marker.snap {
            // This correction is standing in for the virtual-workspace
            // restore itself (deferred one tick past its `is_added` guard —
            // see `show_active_workspace`), so it must respect
            // `virtual_workspace_animations` the same way the restore did,
            // not always animate like an ordinary reshuffle correction.
            if let Ok(mut position) = strip_params.p1().get_mut(strip_entity) {
                position.0 = scroll_to;
            }
            if let Ok(mut cmd) = commands.get_entity(strip_entity) {
                cmd.try_remove::<RepositionMarker>();
            }
        } else {
            commands.reposition_entity(strip_entity, scroll_to);
        }
    }
}

/// Reacts to changes in the position of the `LayoutStrip` to Display, and if changed,
/// marks all the windows in the strip as requiring re-positioning.
#[instrument(level = Level::DEBUG, skip_all)]
fn position_layout_strips(
    moved_strips: Populated<&LayoutStrip, Changed<Position>>,
    mut windows: Query<&mut LayoutPosition, (With<Window>, Without<LayoutStrip>)>,
) {
    for strip in moved_strips {
        for entity in strip.all_windows() {
            if let Ok(mut position) = windows.get_mut(entity) {
                position.set_changed();
            }
        }
    }
}

#[derive(Clone, Copy)]
struct StripWindowContext {
    strip_position: Origin,
    swiping: bool,
    display_entity: Entity,
    stacked: bool,
    /// See [`crate::ecs::workspace::SnapStripMarker`]: forces this window to
    /// snap directly to its target in `position_layout_windows`, bypassing
    /// the offscreen/parking magnitude heuristic.
    snap_settling: bool,
}

#[allow(clippy::too_many_arguments)]
fn insert_strip_window_contexts(
    contexts: &mut EntityHashMap<StripWindowContext>,
    strip: &LayoutStrip,
    strip_position: Origin,
    swiping: bool,
    display_entity: Entity,
    snap_settling: bool,
) {
    for column in &strip.columns {
        insert_column_window_contexts(
            contexts,
            column,
            strip_position,
            swiping,
            display_entity,
            matches!(column, Column::Stack(_)),
            snap_settling,
        );
    }
}

#[allow(clippy::too_many_arguments)]
fn insert_column_window_contexts(
    contexts: &mut EntityHashMap<StripWindowContext>,
    column: &Column,
    strip_position: Origin,
    swiping: bool,
    display_entity: Entity,
    stacked: bool,
    snap_settling: bool,
) {
    match column {
        Column::Single(entity) | Column::Fullscren(entity) => {
            contexts.insert(
                *entity,
                StripWindowContext {
                    strip_position,
                    swiping,
                    display_entity,
                    stacked,
                    snap_settling,
                },
            );
        }
        Column::Stack(items) => {
            for item in items {
                insert_stack_item_window_contexts(
                    contexts,
                    item,
                    strip_position,
                    swiping,
                    display_entity,
                    stacked,
                    snap_settling,
                );
            }
        }
        Column::Tabs(entities) => {
            for entity in entities {
                contexts.insert(
                    *entity,
                    StripWindowContext {
                        strip_position,
                        swiping,
                        display_entity,
                        stacked,
                        snap_settling,
                    },
                );
            }
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn insert_stack_item_window_contexts(
    contexts: &mut EntityHashMap<StripWindowContext>,
    item: &StackItem,
    strip_position: Origin,
    swiping: bool,
    display_entity: Entity,
    stacked: bool,
    snap_settling: bool,
) {
    match item {
        StackItem::Single(entity) => {
            contexts.insert(
                *entity,
                StripWindowContext {
                    strip_position,
                    swiping,
                    display_entity,
                    stacked,
                    snap_settling,
                },
            );
        }
        StackItem::Tabs(entities) => {
            for entity in entities {
                contexts.insert(
                    *entity,
                    StripWindowContext {
                        strip_position,
                        swiping,
                        display_entity,
                        stacked,
                        snap_settling,
                    },
                );
            }
        }
    }
}

/// Reacts to changes of logical window layout in the strip and any have been changed, reposition
/// the layout strip against the current display viewport.
#[instrument(level = Level::DEBUG, skip_all)]
fn position_layout_windows(
    positioned_windows: RepositionedWindows,
    workspaces: StripsForWindowPositioning,
    snap_guards: Query<&SnapStripMarker>,
    displays: DisplayViewports,
    config: Res<Config>,
    mut commands: Commands,
) {
    let offscreen_sliver_width = config.sliver_width();
    let (_, pad_right, _, pad_left) = config.edge_padding();
    let mut strip_contexts = EntityHashMap::default();
    for (strip_entity, layout_strip, Position(strip_position), swiping, child_of) in &workspaces {
        let snap_settling = snap_guards.iter().any(|guard| guard.strip == strip_entity);
        insert_strip_window_contexts(
            &mut strip_contexts,
            layout_strip,
            *strip_position,
            swiping,
            child_of.parent(),
            snap_settling,
        );
    }

    for (entity, window, layout_position, mut position, mut bounds) in positioned_windows {
        let Some(context) = strip_contexts.get(&entity) else {
            return;
        };
        let Ok((display, dock)) = displays.get(context.display_entity) else {
            return;
        };
        let viewport = display.actual_display_bounds(dock, &config);
        // Gets 80% of the display height as threshold.
        let Ok(vertical_move_threshold) = u32::try_from(viewport.height() * 8 / 10) else {
            continue;
        };

        // Account for per-window horizontal_padding: reposition() adds
        // h_pad to the virtual x, so subtract it here so the OS window
        // lands exactly sliver_width pixels from the screen edge.
        let h_pad = window.horizontal_padding();
        let mut frame = IRect::from_corners(layout_position.0, layout_position.0 + bounds.0);
        let width = frame.width();
        frame.min += context.strip_position;
        frame.max += context.strip_position;

        let mut offscreen = false;
        if frame.max.x <= viewport.min.x + h_pad {
            // Window hidden to the left — position so exactly
            // sliver_width CG pixels are visible from the real
            // display edge.  The +h_pad accounts for the gap that
            // reposition() adds, which can leave a window just
            // inside the viewport edge while its CG frame is fully
            // past it.
            frame.min.x = viewport.min.x - width + offscreen_sliver_width - pad_left + h_pad;
            offscreen = true;
        } else if frame.min.x >= viewport.max.x - h_pad {
            // Window hidden to the right — mirror of above.
            frame.min.x = viewport.max.x - offscreen_sliver_width + pad_right - h_pad;
            offscreen = true;
        }
        frame.max.x = frame.min.x + width;

        // During swipe, keep full height. The vertical sliver inset only
        // applies to horizontally off-screen windows, so they expose just
        // a `sliver_height` fraction of their height at the viewport's
        // vertical center.
        if !context.swiping && offscreen {
            // Don't compress stacked windows vertically when off-screen.
            // The height reduction corrupts their proportions: when the
            // column scrolls back on-screen, binpack_heights makes the
            // last window absorb all remaining space.
            if !context.stacked {
                let inset =
                    round_px(f64::from(viewport.height()) * (1.0 - config.sliver_height()) / 2.0);
                frame.min.y += inset;
                frame.max.y += inset;
            }
        }

        // Keep the window anchored to its own display. The parked strip origin
        // only accounts for the first window: everything sitting below it in a
        // stack picks up that offset on top of the corner and lands past the
        // bottom edge, fully inside the display underneath. macOS then adopts
        // the window onto that display, and showing the workspace again brings
        // it back there instead of here. Park those at the corner as well.
        let park_row = viewport.max.y - PARKED_STRIP_SLIVER;
        if frame.min.y > park_row {
            let height = frame.height();
            frame.min.y = park_row;
            frame.max.y = park_row + height;
        }

        if bounds.0 != frame.size() {
            bounds.0 = frame.size();
        }

        if position.0 != frame.min {
            // Direct-assign (snap) when:
            //   - The user is actively swiping: windows must track the finger in lockstep.
            //   - A workspace switch just moved the strip vertically: jumping the full off-screen
            //   distance should be instantaneous.
            // Otherwise (programmatic strip animation, or pure layout change), animate toward the
            // new position so layout changes (swap/add/remove) slide instead of teleport. When the
            // strip is also being animated, the per-window target is recomputed each tick from the
            // strip's current position, so the two motions compose: e.g., on swap, the focused
            // window's target converges back to its old visual position as the strip settles, while
            // the other window slides past.
            // Parking and un-parking have to snap as one move. The clamp above
            // leaves the lower stack members a short hop from their visible
            // slot, which the distance threshold alone reads as an ordinary
            // layout change - they would slide across the screen while the
            // window above them teleports.
            let parking = frame.min.y >= park_row || position.0.y >= park_row;
            let offscreen_move =
                parking || position.0.y.abs_diff(frame.min.y) > vertical_move_threshold;
            // `snap_settling`: a strip restore only fixes the strip's own
            // offset instantly - a member window (a lower stack member
            // especially) can still need a correction that neither
            // `parking` nor the distance threshold recognizes as
            // restore-driven, since its last position can land close enough
            // to its target. See `SnapStripMarker`.
            if context.swiping
                || context.snap_settling
                || offscreen_move && !config.virtual_workspace_animations()
            {
                position.0 = frame.min;
                if let Ok(mut entity_commands) = commands.get_entity(entity) {
                    entity_commands.try_remove::<RepositionMarker>();
                }
            } else {
                commands.reposition_entity(entity, frame.min);
            }
        }
    }
}

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

    #[test]
    fn signature_tolerates_pixel_drift_but_not_a_reshape() {
        let mut world = World::new();
        let first = world.spawn_empty().id();
        let second = world.spawn_empty().id();
        let stored = vec![(first, 400), (second, 400)];

        assert!(signature_matches(&[(first, 401), (second, 399)], &stored));
        assert!(!signature_matches(&[(first, 420), (second, 400)], &stored));
        assert!(!signature_matches(&[(second, 400), (first, 400)], &stored));
        assert!(!signature_matches(&[(first, 400)], &stored));
    }

    #[test]
    fn origin_exposing_moves_only_by_the_shortfall() {
        let viewport = IRect::new(0, 0, 1000, 800);
        let size = Size::new(400, 700);

        // Window at layout x 0 with the strip scrolled 600px to the left sits
        // entirely off-screen; the strip has to come back to 0.
        assert_eq!(
            origin_exposing(Origin::new(0, 0), size, Origin::new(-600, 0), viewport),
            Origin::new(0, 0)
        );

        // A window past the right edge only moves by what hangs over it.
        assert_eq!(
            origin_exposing(Origin::new(800, 0), size, Origin::ZERO, viewport),
            Origin::new(-200, 0)
        );

        // Already fully visible: the offset is left alone.
        assert_eq!(
            origin_exposing(Origin::new(100, 0), size, Origin::new(50, 0), viewport),
            Origin::new(50, 0)
        );
    }

    #[test]
    fn clamp_origin_supports_oversized_windows() {
        let viewport = IRect::new(0, 20, 1024, 768);
        let size = Size::new(2048, 748);

        assert_eq!(
            clamp_origin_to_viewport(Origin::new(300, 20), size, viewport),
            Origin::new(0, 20)
        );
        assert_eq!(
            clamp_origin_to_viewport(Origin::new(-1600, 20), size, viewport),
            Origin::new(-1024, 20)
        );
        assert_eq!(
            clamp_origin_to_viewport(Origin::new(-600, 20), size, viewport),
            Origin::new(-600, 20)
        );
    }

    #[test]
    fn clamp_origin_keeps_regular_windows_inside_viewport() {
        let viewport = IRect::new(0, 20, 1024, 768);
        let size = Size::new(400, 300);

        assert_eq!(
            clamp_origin_to_viewport(Origin::new(-100, 900), size, viewport),
            Origin::new(0, 468)
        );
    }

    fn setup_world_and_strip() -> (World, LayoutStrip, Vec<Entity>) {
        let mut world = World::new();
        let entities = world.spawn_batch(vec![(), (), ()]).collect::<Vec<Entity>>();

        let mut strip = LayoutStrip::default();
        strip.append(entities[0]);
        strip.append(entities[1]);
        strip.append(entities[2]);

        (world, strip, entities)
    }

    #[test]
    fn strip_has_changed_window_matches_nested_entities() {
        let (mut world, mut strip, entities) = setup_world_and_strip();
        strip.stack(entities[1]).unwrap();
        strip.convert_to_tabs(entities[0], entities[1]).unwrap();

        let mut changed = EntityHashSet::default();
        changed.insert(entities[1]);

        assert!(strip_has_changed_window(&strip, &changed));

        changed.clear();
        changed.insert(world.spawn_empty().id());

        assert!(!strip_has_changed_window(&strip, &changed));
    }

    #[test]
    fn strip_window_contexts_capture_stack_membership_once() {
        let (mut world, mut strip, entities) = setup_world_and_strip();
        strip.stack(entities[1]).unwrap();
        let display_entity = world.spawn_empty().id();
        let strip_position = Origin::new(10, 20);
        let mut contexts = EntityHashMap::default();

        insert_strip_window_contexts(
            &mut contexts,
            &strip,
            strip_position,
            true,
            display_entity,
            false,
        );

        let stacked_leader = contexts.get(&entities[0]).unwrap();
        let stacked_follower = contexts.get(&entities[1]).unwrap();
        let single_window = contexts.get(&entities[2]).unwrap();

        assert_eq!(stacked_leader.strip_position, strip_position);
        assert_eq!(stacked_leader.display_entity, display_entity);
        assert!(stacked_leader.swiping);
        assert!(stacked_leader.stacked);
        assert!(stacked_follower.stacked);
        assert!(!single_window.stacked);
    }

    #[test]
    fn test_window_pane_index_of() {
        let (_world, strip, entities) = setup_world_and_strip();
        assert_eq!(strip.index_of(entities[0]).unwrap(), 0);
        assert_eq!(strip.index_of(entities[1]).unwrap(), 1);
        assert_eq!(strip.index_of(entities[2]).unwrap(), 2);
    }

    #[test]
    fn test_window_pane_swap() {
        let (_world, mut strip, entities) = setup_world_and_strip();
        strip.swap(0, 2);
        assert_eq!(strip.index_of(entities[2]).unwrap(), 0);
        assert_eq!(strip.index_of(entities[0]).unwrap(), 2);
    }

    #[test]
    fn test_window_pane_stack_and_unstack() {
        let (_world, mut strip, entities) = setup_world_and_strip();

        // Stack [1] onto [0]
        strip.stack(entities[1]).unwrap();
        assert_eq!(strip.len(), 2);
        assert_eq!(strip.index_of(entities[0]).unwrap(), 0);
        assert_eq!(strip.index_of(entities[1]).unwrap(), 0); // Both in the same panel

        // Check internal structure
        match strip.get(0).unwrap() {
            Column::Stack(stack) => {
                assert_eq!(stack.len(), 2);
                assert_eq!(stack[0], StackItem::Single(entities[0]));
                assert_eq!(stack[1], StackItem::Single(entities[1]));
            }
            Column::Single(_) | Column::Fullscren(_) | Column::Tabs(_) => {
                panic!("Expected a stack")
            }
        }

        // Unstack [0]
        strip.unstack(entities[0]).unwrap();
        assert_eq!(strip.len(), 3);
        assert_eq!(strip.index_of(entities[1]).unwrap(), 0);
        assert_eq!(strip.index_of(entities[0]).unwrap(), 1);
        assert_eq!(strip.index_of(entities[2]).unwrap(), 2);
    }

    #[test]
    fn test_binpack() {
        const MIN_HEIGHT: i32 = 100;
        let heights = [300, 300, 300, 300];

        let out = binpack_heights(&heights, MIN_HEIGHT, 1500).unwrap();
        assert_eq!(out, vec![300, 300, 300, 600]);

        let out = binpack_heights(&heights, MIN_HEIGHT, 1024).unwrap();
        assert_eq!(out, vec![300, 300, 300, 124]);

        let out = binpack_heights(&heights, MIN_HEIGHT, 800).unwrap();
        assert_eq!(out, vec![300, 300, 100, 100]);

        let out = binpack_heights(&heights, MIN_HEIGHT, 440).unwrap();
        assert_eq!(out, vec![110, 110, 110, 110]);

        let out = binpack_heights(&heights, MIN_HEIGHT, 390);
        assert_eq!(out, None);
    }

    #[test]
    fn test_layout_positioning() {
        let mut world = World::new();
        let entities = world
            .spawn_batch(vec![(), (), (), ()])
            .collect::<Vec<Entity>>();
        let sizes = [
            IRect::new(0, 0, 300, 300),
            IRect::new(0, 0, 300, 300),
            IRect::new(0, 0, 300, 300),
            IRect::new(0, 0, 300, 300),
        ];

        let mut strip = LayoutStrip::default();
        strip.append(entities[0]);
        strip.append(entities[1]);
        strip.append(entities[2]);
        strip.append(entities[3]);

        _ = strip.stack(entities[2]);
        let get_window_frame = |_| Some(sizes[0]);
        let out = strip
            .relative_positions(500, &get_window_frame)
            .collect::<Vec<_>>();

        let xpos = out.iter().map(|(_, frame)| frame.min.x).collect::<Vec<_>>();
        assert_eq!(xpos, vec![0, 300, 300, 600]);

        let height = out
            .iter()
            .map(|(_, frame)| frame.height())
            .collect::<Vec<_>>();
        assert_eq!(height, vec![500, 300, 200, 500]);
    }

    /// Every single-column window must fill the full viewport height.
    #[test]
    fn test_layout_singles_get_full_viewport_height() {
        let mut world = World::new();
        let entities = world.spawn_batch(vec![(), (), ()]).collect::<Vec<Entity>>();

        let mut strip = LayoutStrip::default();
        for &e in &entities {
            strip.append(e);
        }

        let get_window_frame = |_| Some(IRect::new(0, 0, 300, 400));
        let out: Vec<_> = strip.relative_positions(800, &get_window_frame).collect();

        assert_eq!(out.len(), 3);
        for (_, f) in &out {
            assert_eq!(f.height(), 800, "single window should fill viewport height");
            assert_eq!(f.min.y, 0);
        }
        // x positions: 0, 300, 600
        let xs: Vec<_> = out.iter().map(|(_, f)| f.min.x).collect();
        assert_eq!(xs, vec![0, 300, 600]);
    }

    /// Stacked windows share the viewport height; all use the top window's width.
    #[test]
    fn test_layout_stack_shares_height_and_width() {
        let mut world = World::new();
        let entities = world
            .spawn_batch(vec![(), (), (), ()])
            .collect::<Vec<Entity>>();

        let mut strip = LayoutStrip::default();
        for &e in &entities {
            strip.append(e);
        }
        // Stack e1, e2 onto e0: [Stack(e0, e1, e2), Single(e3)]
        strip.stack(entities[1]).unwrap();
        strip.stack(entities[2]).unwrap();

        // Give the master (e0) a distinct width so we can verify children
        // adopt it. Here e0 is 500px while its stacked children are 300px;
        // children must widen to the master's 500, not keep their own width.
        let get_window_frame = |e: Entity| {
            if e == entities[0] {
                Some(IRect::new(0, 0, 500, 200))
            } else if e == entities[1] || e == entities[2] {
                Some(IRect::new(0, 0, 300, 200))
            } else {
                Some(IRect::new(0, 0, 400, 500))
            }
        };

        let out: Vec<_> = strip.relative_positions(600, &get_window_frame).collect();
        assert_eq!(out.len(), 4);

        // Every window in the stacked column must adopt the master's width.
        for e in [entities[0], entities[1], entities[2]] {
            let frame = out.iter().find(|(entity, _)| *entity == e).unwrap().1;
            assert_eq!(
                frame.width(),
                500,
                "stacked window must share the master's (top) width"
            );
        }

        // Stacked heights should sum to viewport height.
        let stack_heights: i32 = out
            .iter()
            .filter(|(e, _)| *e != entities[3])
            .map(|(_, f)| f.height())
            .sum();
        assert_eq!(stack_heights, 600, "stack heights must sum to viewport");

        // Stacked y positions should be contiguous from 0.
        let stack_frames: Vec<_> = out
            .iter()
            .filter(|(e, _)| *e != entities[3])
            .map(|(_, f)| *f)
            .collect();
        assert_eq!(stack_frames[0].min.y, 0);
        assert_eq!(stack_frames[0].max.y, stack_frames[1].min.y);
        assert_eq!(stack_frames[1].max.y, stack_frames[2].min.y);
        assert_eq!(stack_frames[2].max.y, 600);

        // e3 (single) gets full viewport height.
        let e3_frame = out.iter().find(|(e, _)| *e == entities[3]).unwrap().1;
        assert_eq!(e3_frame.height(), 600);
    }

    #[test]
    fn test_toggle_tabbed_display_marks_and_unmarks_all_stack_members() {
        let mut world = World::new();
        let entities = world.spawn_batch(vec![(), (), ()]).collect::<Vec<Entity>>();

        let mut strip = LayoutStrip::default();
        for &e in &entities {
            strip.append(e);
        }
        strip.stack(entities[1]).unwrap();
        strip.stack(entities[2]).unwrap();

        assert!(entities.iter().all(|&e| !strip.is_tabbed_display(e)));

        let now_tabbed = strip.toggle_tabbed_display(entities[1]);
        assert_eq!(now_tabbed, Some(true));
        assert!(entities.iter().all(|&e| strip.is_tabbed_display(e)));

        let now_tabbed = strip.toggle_tabbed_display(entities[0]);
        assert_eq!(now_tabbed, Some(false));
        assert!(entities.iter().all(|&e| !strip.is_tabbed_display(e)));
    }

    #[test]
    fn test_toggle_tabbed_display_noop_on_single_column() {
        let mut world = World::new();
        let entity = world.spawn_empty().id();

        let mut strip = LayoutStrip::default();
        strip.append(entity);

        assert_eq!(
            strip.toggle_tabbed_display(entity),
            None,
            "toggling a lone Single column must be a no-op, not report 'off'"
        );
        assert!(!strip.is_tabbed_display(entity));
    }

    #[test]
    fn test_tabbed_stack_shares_full_column_frame() {
        let mut world = World::new();
        let entities = world.spawn_batch(vec![(), (), ()]).collect::<Vec<Entity>>();

        let mut strip = LayoutStrip::default();
        for &e in &entities {
            strip.append(e);
        }
        strip.stack(entities[1]).unwrap();
        strip.stack(entities[2]).unwrap();
        strip.toggle_tabbed_display(entities[1]);

        let get_window_frame = |_| Some(IRect::new(0, 0, 400, 300));
        let out: Vec<_> = strip.relative_positions(700, &get_window_frame).collect();

        assert_eq!(out.len(), 3);
        for (_, frame) in &out {
            assert_eq!(frame.min.y, 0, "every tab must start at the column's top");
            assert_eq!(
                frame.height(),
                700,
                "every tab must fill the full column height"
            );
            assert_eq!(frame.width(), 400);
        }
        // All three must be at the identical x too (same column slot).
        let xs: std::collections::HashSet<_> = out.iter().map(|(_, f)| f.min.x).collect();
        assert_eq!(xs.len(), 1, "every tab must share the same column x");
    }

    #[test]
    fn test_tabbed_stack_untoggle_restores_split_heights() {
        let mut world = World::new();
        let entities = world.spawn_batch(vec![(), (), ()]).collect::<Vec<Entity>>();

        let mut strip = LayoutStrip::default();
        for &e in &entities {
            strip.append(e);
        }
        strip.stack(entities[1]).unwrap();
        strip.stack(entities[2]).unwrap();

        let get_window_frame = |_| Some(IRect::new(0, 0, 400, 200));

        strip.toggle_tabbed_display(entities[1]);
        strip.toggle_tabbed_display(entities[1]);

        let out: Vec<_> = strip.relative_positions(600, &get_window_frame).collect();
        let heights: Vec<_> = out.iter().map(|(_, f)| f.height()).collect();
        assert_eq!(
            heights.iter().sum::<i32>(),
            600,
            "heights must fill the viewport"
        );
        assert!(
            heights.iter().any(|&h| h != 600),
            "split display must not leave every window at full column height"
        );
    }

    /// Regression: an earlier version of tabbed-display support reordered
    /// the outer `Vec<StackItem>` on every focus change (mirroring how
    /// native-tab `Column::move_to_front` reorders `StackItem::Tabs`), so
    /// `Column::top()` would track the active tab. That broke cycling:
    /// `get_window_in_direction`'s North/South arms walk the stack purely by
    /// stable index, so reordering it out from under them made focus jump
    /// unpredictably instead of advancing. Tabbed-display columns must never
    /// reorder — `Column::top()` intentionally stays whatever the first item
    /// was, and the true "active tab" is tracked only by `FocusedMarker`.
    #[test]
    fn test_toggle_tabbed_display_never_reorders_the_stack() {
        let mut world = World::new();
        let entities = world.spawn_batch(vec![(), (), ()]).collect::<Vec<Entity>>();

        let mut strip = LayoutStrip::default();
        for &e in &entities {
            strip.append(e);
        }
        strip.stack(entities[1]).unwrap();
        strip.stack(entities[2]).unwrap();
        strip.toggle_tabbed_display(entities[1]);

        let index = strip.index_of(entities[2]).unwrap();
        let Column::Stack(items) = strip.get(index).unwrap() else {
            panic!("expected a Stack column");
        };
        let order: Vec<_> = items.iter().filter_map(StackItem::top).collect();
        assert_eq!(
            order, entities,
            "toggling tabbed display must not reorder the stack"
        );
    }

    #[test]
    fn test_tab_display_sibling_falls_back_at_ends() {
        let mut world = World::new();
        let entities = world.spawn_batch(vec![(), (), ()]).collect::<Vec<Entity>>();

        let mut strip = LayoutStrip::default();
        for &e in &entities {
            strip.append(e);
        }
        strip.stack(entities[1]).unwrap();
        strip.stack(entities[2]).unwrap();
        strip.toggle_tabbed_display(entities[1]);

        assert_eq!(strip.tab_display_sibling(entities[0]), Some(entities[1]));
        assert_eq!(strip.tab_display_sibling(entities[1]), Some(entities[2]));
        // Last item falls back to the previous one instead of wrapping.
        assert_eq!(strip.tab_display_sibling(entities[2]), Some(entities[1]));
    }

    #[test]
    fn test_removing_from_tabbed_stack_collapsing_to_single_clears_membership() {
        let mut world = World::new();
        let entities = world.spawn_batch(vec![(), ()]).collect::<Vec<Entity>>();

        let mut strip = LayoutStrip::default();
        for &e in &entities {
            strip.append(e);
        }
        strip.stack(entities[1]).unwrap();
        strip.toggle_tabbed_display(entities[1]);
        assert!(strip.is_tabbed_display(entities[0]));

        strip.remove(entities[1]);

        assert!(
            !strip.is_tabbed_display(entities[0]),
            "a lone surviving window can't remain a tabbed display"
        );
        let index = strip.index_of(entities[0]).unwrap();
        assert!(matches!(strip.get(index).unwrap(), Column::Single(_)));
    }

    #[test]
    fn test_tabs_in_stack() {
        let mut world = World::new();
        let e1 = world.spawn_empty().id();
        let e2 = world.spawn_empty().id();
        let e3 = world.spawn_empty().id();
        let e4 = world.spawn_empty().id();

        let mut strip = LayoutStrip::default();
        strip.append(e1);
        strip.append(e2);
        strip.append(e3);

        // [Single(e1), Single(e2), Single(e3)]
        strip.stack(e2).unwrap();
        // [Stack([Single(e1), Single(e2)]), Single(e3)]

        // Convert e1 (in stack) to tabs with e4
        strip.convert_to_tabs(e1, e4).unwrap();
        // [Stack([Tabs([e1, e4]), Single(e2)]), Single(e3)]

        assert_eq!(strip.len(), 2);
        match strip.get(0).unwrap() {
            Column::Stack(items) => {
                assert_eq!(items.len(), 2);
                match &items[0] {
                    StackItem::Tabs(tabs) => assert_eq!(tabs, &vec![e4, e1]),
                    StackItem::Single(_) => panic!("Expected Tabs in stack"),
                }
            }
            _ => panic!("Expected Stack"),
        }

        // relative_positions should yield e1, e4 (same frame) and e2
        let get_window_frame = |_| Some(IRect::new(0, 0, 100, 100));
        let out: Vec<_> = strip.relative_positions(400, &get_window_frame).collect();

        // We expect e1, e4, e2 from the first column, and e3 from the second.
        assert_eq!(out.len(), 4);

        let e1_frame = out.iter().find(|(e, _)| *e == e1).unwrap().1;
        let e4_frame = out.iter().find(|(e, _)| *e == e4).unwrap().1;
        let e2_frame = out.iter().find(|(e, _)| *e == e2).unwrap().1;

        assert_eq!(e1_frame, e4_frame);
        assert_eq!(e1_frame.max.y, e2_frame.min.y);
    }

    /// Unstacking a window from a stack gives it its own column with full height.
    #[test]
    fn test_layout_unstack_gives_full_height() {
        let mut world = World::new();
        let entities = world.spawn_batch(vec![(), (), ()]).collect::<Vec<Entity>>();

        let mut strip = LayoutStrip::default();
        for &e in &entities {
            strip.append(e);
        }
        // [Stack(e0, e1), Single(e2)]
        strip.stack(entities[1]).unwrap();

        let get_window_frame = |_| Some(IRect::new(0, 0, 300, 250));

        // Before unstack: e0 and e1 share 500px height.
        let out: Vec<_> = strip.relative_positions(500, &get_window_frame).collect();
        let e1_height = out
            .iter()
            .find(|(e, _)| *e == entities[1])
            .unwrap()
            .1
            .height();
        assert!(e1_height < 500, "stacked e1 should not have full height");

        // Unstack e1: [Single(e0), Single(e1), Single(e2)]
        strip.unstack(entities[1]).unwrap();
        assert_eq!(strip.len(), 3);

        let out: Vec<_> = strip.relative_positions(500, &get_window_frame).collect();
        for (_, f) in &out {
            assert_eq!(
                f.height(),
                500,
                "after unstack every single column gets full viewport height"
            );
        }
    }

    /// Re-stacking after unstack restores shared height distribution.
    #[test]
    fn test_layout_restack_restores_shared_heights() {
        let mut world = World::new();
        let entities = world.spawn_batch(vec![(), ()]).collect::<Vec<Entity>>();

        let mut strip = LayoutStrip::default();
        strip.append(entities[0]);
        strip.append(entities[1]);

        let get_window_frame = |_| Some(IRect::new(0, 0, 300, 250));

        // Stack: [Stack(e0, e1)]
        strip.stack(entities[1]).unwrap();
        let out: Vec<_> = strip.relative_positions(500, &get_window_frame).collect();
        let heights: Vec<_> = out.iter().map(|(_, f)| f.height()).collect();
        assert_eq!(heights.iter().sum::<i32>(), 500);
        assert_eq!(heights.len(), 2);

        // Unstack: [Single(e0), Single(e1)]
        strip.unstack(entities[1]).unwrap();
        let out: Vec<_> = strip.relative_positions(500, &get_window_frame).collect();
        for (_, f) in &out {
            assert_eq!(f.height(), 500);
        }

        // Re-stack: [Stack(e0, e1)] — e1 stacks onto left neighbor e0
        strip.stack(entities[1]).unwrap();
        let out: Vec<_> = strip.relative_positions(500, &get_window_frame).collect();
        let heights: Vec<_> = out.iter().map(|(_, f)| f.height()).collect();
        assert_eq!(heights.iter().sum::<i32>(), 500);
        assert_eq!(heights.len(), 2);
    }

    /// When window frames include padding (logical frame is wider than the visual
    /// window), columns must be placed edge-to-edge using the full logical width.
    /// This ensures the visual gap between windows equals the sum of their padding.
    #[test]
    fn test_column_positions_with_padded_frames() {
        let mut world = World::new();
        let entities = world.spawn_batch(vec![(), (), ()]).collect::<Vec<Entity>>();

        let mut strip = LayoutStrip::default();
        for &e in &entities {
            strip.append(e);
        }

        // Simulate windows with padding=8: logical width = OS_width + 2*8.
        // Window 0: OS width 284, logical width 300
        // Window 1: OS width 384, logical width 400
        // Window 2: OS width 484, logical width 500
        let padded_frames = [
            IRect::new(0, 0, 300, 600), // logical frame with padding included
            IRect::new(0, 0, 400, 600),
            IRect::new(0, 0, 500, 600),
        ];

        let get_window_frame = |e: Entity| {
            if e == entities[0] {
                Some(padded_frames[0])
            } else if e == entities[1] {
                Some(padded_frames[1])
            } else {
                Some(padded_frames[2])
            }
        };

        let out: Vec<_> = strip.relative_positions(600, &get_window_frame).collect();
        assert_eq!(out.len(), 3);

        // Columns must be edge-to-edge: each column starts where the previous ends.
        let xs: Vec<_> = out.iter().map(|(_, f)| f.min.x).collect();
        assert_eq!(
            xs,
            vec![0, 300, 700],
            "columns must be edge-to-edge using logical widths"
        );

        // Right edge of each window must equal left edge of the next.
        for i in 0..out.len() - 1 {
            assert_eq!(
                out[i].1.max.x,
                out[i + 1].1.min.x,
                "window {} right edge must equal window {} left edge",
                i,
                i + 1
            );
        }
    }

    /// Frames with no padding (padding=0) should still produce edge-to-edge layout.
    #[test]
    fn test_column_positions_no_padding() {
        let mut world = World::new();
        let entities = world.spawn_batch(vec![(), (), ()]).collect::<Vec<Entity>>();

        let mut strip = LayoutStrip::default();
        for &e in &entities {
            strip.append(e);
        }

        let get_window_frame = |_| Some(IRect::new(0, 0, 300, 600));

        let out: Vec<_> = strip.relative_positions(600, &get_window_frame).collect();
        let xs: Vec<_> = out.iter().map(|(_, f)| f.min.x).collect();
        assert_eq!(xs, vec![0, 300, 600]);

        // No gaps or overlaps.
        for i in 0..out.len() - 1 {
            assert_eq!(out[i].1.max.x, out[i + 1].1.min.x);
        }
    }

    #[test]
    fn test_convert_to_tabs() {
        let mut world = World::new();
        let e1 = world.spawn_empty().id();
        let e2 = world.spawn_empty().id();
        let e3 = world.spawn_empty().id();

        let mut strip = LayoutStrip::default();
        strip.append(e1);
        strip.append(e3);

        // Convert e1 to a tab group with follower e2
        strip.convert_to_tabs(e1, e2).unwrap();

        assert_eq!(strip.len(), 2);
        match strip.get(0).unwrap() {
            Column::Tabs(tabs) => {
                assert_eq!(tabs, vec![e2, e1]);
            }
            _ => panic!("Expected Tabs column"),
        }

        // Add another tab e4
        let e4 = world.spawn_empty().id();
        strip.convert_to_tabs(e1, e4).unwrap();
        assert_eq!(strip.len(), 2);
        match strip.get(0).unwrap() {
            Column::Tabs(tabs) => {
                assert_eq!(tabs, vec![e4, e2, e1]);
            }
            _ => panic!("Expected Tabs column"),
        }
    }

    #[test]
    fn test_remove_from_tabs() {
        let mut world = World::new();
        let e1 = world.spawn_empty().id();
        let e2 = world.spawn_empty().id();
        let e3 = world.spawn_empty().id();

        let mut strip = LayoutStrip::default();
        strip.append(e1);
        strip.convert_to_tabs(e1, e2).unwrap();
        strip.convert_to_tabs(e1, e3).unwrap();

        assert_eq!(strip.len(), 1);

        // Remove e2 (follower)
        strip.remove(e2);
        assert_eq!(strip.len(), 1);
        match strip.get(0).unwrap() {
            Column::Tabs(tabs) => assert_eq!(tabs, vec![e3, e1]),
            _ => panic!(),
        }

        // Remove e1 (leader)
        strip.remove(e1);
        assert_eq!(strip.len(), 1);
        // Should convert back to Single since only e3 remains
        match strip.get(0).unwrap() {
            Column::Single(id) => assert_eq!(id, e3),
            _ => panic!("Expected Single column after removing all but one tab"),
        }
    }

    #[test]
    fn test_tab_group_returns_all_siblings() {
        let mut world = World::new();
        let e1 = world.spawn_empty().id();
        let e2 = world.spawn_empty().id();
        let e3 = world.spawn_empty().id();

        let mut strip = LayoutStrip::default();
        strip.append(e1);
        strip.convert_to_tabs(e1, e2).unwrap();
        strip.append(e3);

        assert_eq!(strip.tab_group(e1), Some(vec![e2, e1]));
        assert_eq!(strip.tab_group(e2), Some(vec![e2, e1]));
        assert_eq!(strip.tab_group(e3), None);
    }

    #[test]
    fn test_append_tab_group_merges_existing_members_without_duplicate_columns() {
        let mut world = World::new();
        let e1 = world.spawn_empty().id();
        let e2 = world.spawn_empty().id();
        let e3 = world.spawn_empty().id();

        let mut strip = LayoutStrip::default();
        strip.append(e2);
        strip.append(e3);

        strip.append_tab_group(&[e1, e2]);

        assert_eq!(strip.len(), 2);
        match strip.get(0).unwrap() {
            Column::Tabs(tabs) => assert_eq!(tabs, vec![e1, e2]),
            _ => panic!("Expected merged Tabs column"),
        }
        assert_eq!(strip.index_of(e1).unwrap(), 0);
        assert_eq!(strip.index_of(e2).unwrap(), 0);
        assert_eq!(strip.index_of(e3).unwrap(), 1);
        assert_eq!(strip.all_windows(), vec![e1, e2, e3]);
    }

    #[test]
    fn test_tab_relative_positions_use_stable_slot_representative() {
        let mut world = World::new();
        let e1 = world.spawn_empty().id();
        let e2 = world.spawn_empty().id();

        let mut strip = LayoutStrip::default();
        strip.append(e1);
        strip.convert_to_tabs(e1, e2).unwrap();
        strip
            .get_column_mut(0)
            .expect("tab column")
            .move_to_front(e2);

        let get_window_frame = |entity| {
            if entity == e1 {
                Some(IRect::new(0, 0, 300, 600))
            } else {
                Some(IRect::new(900, 0, 1200, 400))
            }
        };

        let out = strip
            .relative_positions(600, &get_window_frame)
            .collect::<Vec<_>>();

        assert_eq!(out.len(), 2);
        assert!(
            out.iter()
                .all(|(_, frame)| *frame == IRect::new(0, 0, 300, 600))
        );
    }

    #[test]
    fn test_overlapping_frame_strategy_simulation() {
        let mut world = World::new();
        let e1 = world.spawn_empty().id();
        let e2 = world.spawn_empty().id();

        let mut strip = LayoutStrip::default();
        strip.append(e1);

        // Simulate detection logic from spawn_window_trigger
        let leader_match = Some(e1); // Mocked match from frame comparison

        if let Some(leader) = leader_match {
            strip.convert_to_tabs(leader, e2).unwrap();
        } else {
            strip.append(e2);
        }

        assert_eq!(strip.len(), 1);
        match strip.get(0).unwrap() {
            Column::Tabs(tabs) => assert_eq!(tabs, vec![e2, e1]),
            _ => panic!(),
        }
    }

    // Mirrors the real `detect_tabbed_windows` flow: spawn_window_trigger
    // appends the new window to the strip first, and only then does the
    // tab detector merge it into the leader's column. Before the fix, the
    // follower was left in both columns, and right_neighbour from the
    // duplicated entity would self-loop because index_of returned the Tabs
    // column index, while the column at the next index was the orphaned
    // Single(follower).
    #[test]
    fn test_convert_to_tabs_removes_pre_existing_follower_column() {
        let mut world = World::new();
        let leader = world.spawn_empty().id();
        let follower = world.spawn_empty().id();

        let mut strip = LayoutStrip::default();
        strip.append(leader);
        strip.append(follower);

        strip.convert_to_tabs(leader, follower).unwrap();

        assert_eq!(
            strip.len(),
            1,
            "follower must not remain in its own column after being tabbed onto leader",
        );
        match strip.get(0).unwrap() {
            Column::Tabs(tabs) => assert_eq!(tabs, vec![follower, leader]),
            other => panic!("expected Tabs column, got {other:?}"),
        }
    }

    #[test]
    fn test_convert_to_tabs_no_self_loop_on_neighbour() {
        let mut world = World::new();
        let a = world.spawn_empty().id();
        let leader = world.spawn_empty().id();
        let follower = world.spawn_empty().id();
        let b = world.spawn_empty().id();

        let mut strip = LayoutStrip::default();
        strip.append(a);
        strip.append(leader);
        strip.append(follower);
        strip.append(b);

        strip.convert_to_tabs(leader, follower).unwrap();

        // Both leader-as-focus and follower-as-focus must navigate to `b`
        // east, not back onto themselves.
        assert_eq!(strip.right_neighbour(leader), Some(b));
        assert_eq!(strip.right_neighbour(follower), Some(b));
        assert_eq!(strip.left_neighbour(leader), Some(a));
        assert_eq!(strip.left_neighbour(follower), Some(a));
    }

    #[test]
    fn test_convert_to_tabs_handles_follower_left_of_leader() {
        let mut world = World::new();
        let follower = world.spawn_empty().id();
        let leader = world.spawn_empty().id();
        let b = world.spawn_empty().id();

        let mut strip = LayoutStrip::default();
        strip.append(follower);
        strip.append(leader);
        strip.append(b);

        strip.convert_to_tabs(leader, follower).unwrap();

        assert_eq!(strip.len(), 2);
        match strip.get(0).unwrap() {
            Column::Tabs(tabs) => assert_eq!(tabs, vec![follower, leader]),
            other => panic!("expected Tabs column, got {other:?}"),
        }
        assert_eq!(strip.right_neighbour(leader), Some(b));
        assert_eq!(strip.right_neighbour(follower), Some(b));
    }
}