summaryrefslogtreecommitdiff
path: root/src/layout.zig
blob: 1515b525af73d0d107dd3d745e5eef4f737852b5 (plain) (blame)
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
const std = @import("std");
const pardes = @import("pardes.zig");
const tagline = @import("tagline.zig");
const dump = @import("dump.zig");
const config = @import("config.zig");
const panes = @import("panes.zig");
const Pardes = pardes.Pardes;
const Layer = @import("Layer.zig");
const TagHit = Layer.TagHit;
const TOPBAR_H = pardes.TOPBAR_H;
const COLBAR_H = pardes.COLBAR_H;
const MAX_TAG_ROWS = pardes.MAX_TAG_ROWS;
const Pane = pardes.Pane;
pub const Rect = struct { x: u16 = 0, y: u16 = 0, w: u16 = 0, h: u16 = 0 };
const MAX_COLS = pardes.MAX_COLS;
const MAX_PANES = pardes.MAX_PANES;

const BOX_H = pardes.BOX_H;

pub const column_weight_unit: u64 = 1 << 32;
pub const max_column_weight: u64 = std.math.maxInt(u64) / MAX_COLS;

pub const MovePlacement = struct {
    preview_col: usize,
    /// The pane the moved one lands below; null when the column is empty
    /// and the moved pane takes it whole.
    above_id: ?usize,
    row: u16,
    above_y: u16,
    above_h: u16,
};

pub const Dir = enum { left, right, up, down };

/// Move the keyboard to the nearest pane in `dir`; false when there is none.
pub fn focusDir(p: *Pardes, from: usize, dir: Dir) bool {
    const b = nearest(p, from, dir) orelse return false;
    p.active = b;
    // a count typed before the hop was meant for the pane you left
    p.panes[b].?.body.normal.clear();
    return true;
}

/// The pane next to `from` in `dir`, by the screen.
pub fn nearest(p: *const Pardes, from: usize, dir: Dir) ?usize {
    const a = p.rects[from];
    var best: ?usize = null;
    var best_d: i32 = 0;
    for (p.panes, 0..) |slot, i| {
        if (slot == null or i == from) continue;
        const r = p.rects[i];
        const vov = a.y < r.y + r.h and r.y < a.y + a.h;
        const hov = a.x < r.x + r.w and r.x < a.x + a.w;
        const ok = switch (dir) {
            .left => r.x + r.w <= a.x and vov,
            .right => r.x >= a.x + a.w and vov,
            .up => r.y + r.h <= a.y and hov,
            .down => r.y >= a.y + a.h and hov,
        };
        if (!ok) continue;
        const d: i32 = switch (dir) {
            .left => @as(i32, a.x) - @as(i32, r.x + r.w),
            .right => @as(i32, r.x) - @as(i32, a.x + a.w),
            .up => @as(i32, a.y) - @as(i32, r.y + r.h),
            .down => @as(i32, r.y) - @as(i32, a.y + a.h),
        };
        if (best == null or d < best_d) {
            best = i;
            best_d = d;
        }
    }
    return best;
}

/// Window mode's labels, one a pane in reading order (columns left to
/// right, each top to bottom); h, j, k and l move instead, d deletes and c
/// collapses. ponytail: a pane past the 20th has no label and is reached
/// by moving.
pub const window_labels = "asfgqwertyuiopzxvbnm";

/// The letter window mode shows on pane `id`.
pub fn windowLabel(p: *const Pardes, id: usize) ?u8 {
    var n: usize = 0;
    for (0..p.ncol) |c| for (p.cols[c].panes[0..p.cols[c].n]) |pane| {
        if (n == window_labels.len) return null;
        if (pane == id) return window_labels[n];
        n += 1;
    };
    return null;
}

/// Window mode (SPC w, Ctrl-w): h/j/k/l (or the arrows) move an outline
/// from pane to pane and nothing else gets the keys; Enter or Esc focuses
/// the outlined pane, `:` its tag, and a pane's label letter that one. Up past a
/// column's top pane goes on to its tag, as the Up word does. `d` is Del
/// on the outlined pane and `c` Collapse, and the mode stays: a Del that
/// closes it moves the outline to the pane its rows went to (after the k/j
/// question, when Del asks one; keys.answerQuestion). Any other key
/// changes nothing.
pub fn windowKey(p: *Pardes, key: pardes.Key) void {
    const at = p.window_pick orelse return;
    if (p.panes[at] == null) {
        p.window_pick = null;
        return;
    }
    if (key.ctrl or key.alt) return;
    for (config.window_keys) |wk| if (pardes.hit(key, &.{ wk.letter, wk.arrow })) {
        const dir: Dir = switch (wk.cmd) {
            .Left => .left,
            .Down => .down,
            .Up => .up,
            else => .right,
        };
        if (nearest(p, at, dir)) |next| {
            p.window_pick = next;
        } else if (dir == .up) {
            p.window_pick = null;
            p.active = at;
            pardes.exec.runBuiltin(p, .Up, at, "", null);
        }
        return;
    };
    if (pardes.hit(key, config.window_collapse)) return pardes.exec.runBuiltin(p, .Collapse, at, "", null);
    if (pardes.hit(key, config.window_delete)) {
        // Del's focus follows the rows from the pane it closes, so the
        // outlined pane is the active one while it runs.
        p.active = at;
        pardes.exec.runBuiltin(p, .Del, at, "", null);
        if (p.panes[at] == null) p.window_pick = if (p.header != null) null else p.active;
        return;
    }
    const chosen = if (key.cp == pardes.Key.enter or key.cp == pardes.Key.escape or key.cp == ':') at else for (0..p.panes.len) |id| {
        if (p.panes[id] != null and key.cp < 128 and windowLabel(p, id) == @as(u8, @intCast(key.cp))) break id;
    } else return;
    p.window_pick = null;
    p.active = chosen;
    p.panes[chosen].?.body.normal.clear();
    if (key.cp == ':') tagline.enterTag(p, p.panes[chosen].?);
}

/// Column `c`'s serial, handed out the first time it is asked for.
pub fn columnSerial(p: *Pardes, c: usize) u32 {
    if (p.cols[c].serial == 0) {
        p.cols[c].serial = p.next_column_serial;
        p.next_column_serial +%= 1;
        if (p.next_column_serial == 0) p.next_column_serial = 1;
    }
    return p.cols[c].serial;
}

pub fn columnBySerial(p: *const Pardes, serial: u32) ?usize {
    if (serial == 0) return null;
    for (0..p.ncol) |column| if (p.cols[column].serial == serial) return column;
    return null;
}

/// What releasing column `source`'s grip at `x` does: past a neighbour's
/// middle it takes that column's place; short of it, as in acme, the
/// column's left edge moves to `x - grab`, clamped as setColumnPairWidth
/// clamps it. Still on the grip, or at the leftmost column, nothing moves.
/// The drag preview and the release both ask here, so they cannot disagree.
pub const ColumnDrop = union(enum) { stay, reorder: usize, edge: u16 };

pub fn columnDrop(p: *const Pardes, source: usize, x: u16, grab: u16) ColumnDrop {
    if (source >= p.ncol) return .stay;
    var insertion: usize = 0;
    for (0..p.ncol) |column| {
        if (column == source) continue;
        if (x >= p.col_x[column] + p.col_w[column] / 2) insertion += 1;
    }
    if (insertion != source) return .{ .reorder = insertion };
    if (source == 0 or (x >= p.col_x[source] and x < p.col_x[source] + config.GUTTER)) return .stay;
    if (p.col_w[source - 1] + p.col_w[source] < 2 * config.MINW) return .stay;
    const lo = p.col_x[source - 1] + config.MINW;
    const hi = (p.col_x[source] + p.col_w[source]) -| config.MINW;
    return .{ .edge = std.math.clamp(x -| grab, lo, @max(lo, hi)) };
}

/// Share out the width of columns `left` and `left + 1` so the left one is
/// `left_width` cells, neither below MINW. A border drag and a column grip
/// dropped inside its own place both end here.
pub fn setColumnPairWidth(p: *Pardes, left: usize, left_width: u64) void {
    if (left + 1 >= p.ncol) return;
    const combined: u64 = p.col_w[left] + p.col_w[left + 1];
    // Too narrow for both to keep MINW: any split would squeeze one away.
    if (combined < 2 * @as(u64, config.MINW)) return;
    const width = std.math.clamp(left_width, config.MINW, @max(@as(u64, config.MINW), combined -| config.MINW));
    const pair = p.cols[left].weight + p.cols[left + 1].weight;
    if (pair <= 1 or combined == 0) return;
    const numerator = @as(u128, pair) * width + combined / 2;
    const share = std.math.clamp(@as(u64, @intCast(numerator / combined)), 1, pair - 1);
    p.cols[left].weight = share;
    p.cols[left + 1].weight = pair - share;
}

pub fn reorderColumn(p: *Pardes, from: usize, to: usize) void {
    if (from >= p.ncol or to >= p.ncol or from == to) return;
    const moved = p.cols[from];
    const tag = p.col_tags[from];
    var at = from;
    while (at != to) {
        const next = if (at < to) at + 1 else at - 1;
        p.cols[at] = p.cols[next];
        p.col_tags[at] = p.col_tags[next];
        at = next;
    }
    p.cols[to] = moved;
    p.col_tags[to] = tag;
    if (p.header) |*h| if (h.* == .column) {
        const column = h.column;
        if (column == from) h.column = to else if (from < to and column > from and column <= to) {
            h.column = column - 1;
        } else if (from > to and column >= to and column < from) h.column = column + 1;
    };
    p.pointer_tag_hit = null;
    p.look_hover_wait = null;
    p.look_hover_preview = null;
    compute(p);
}

pub fn targetColumn(p: *Pardes, cur_x: u16) usize {
    var tc: usize = if (p.ncol > 0) p.ncol - 1 else 0;
    for (0..p.ncol) |c| {
        if (cur_x >= p.col_x[c] and cur_x < p.col_x[c] + p.col_w[c]) {
            tc = c;
            break;
        }
    }
    return tc;
}

/// The row that splits the `h` rows from `y` nearest `cur_y`, each side
/// keeping MINH rows when there are that many (else one), or `least` when
/// given: a pane dragged by its grip within its own column is how a
/// terminal resizes, and acme lets either window keep only its tag.
fn splitRowFor(y: u16, h: u16, cur_y: u16, least: ?u16) ?u16 {
    if (h < 2) return null;
    const min_each: u16 = least orelse if (h >= config.MINH * 2) config.MINH else 1;
    const lo = y +| min_each;
    const hi = y + h - min_each;
    if (lo > hi) return y + h / 2;
    return std.math.clamp(cur_y, lo, hi);
}

/// Where pane `id` dragged by its grip to (`cur_x`, `cur_y`) lands. An
/// owner's grip drags its group; an attachment's drags it alone, which
/// within its group resizes it and anywhere else detaches it (movePane).
/// Another group is one place: a pane dropped on it lands under all of it.
pub fn movePlacement(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) ?MovePlacement {
    const src = findPane(p, id) orelse return null;
    const span_end = if (ownerOf(p, id) == null) groupEnd(p, src.col, src.idx) else src.idx + 1;
    const own_root = groupRoot(p, id);
    const tc = targetColumn(p, cur_x);
    if (tc == src.col and p.cols[src.col].n == span_end - src.idx) return null;
    var span_h: u16 = 0;
    for (p.cols[src.col].panes[src.idx..span_end]) |k| span_h +|= p.rects[k].h;
    if (tc == src.col) {
        const top = p.rects[id].y;
        // Dropped on itself it stays, unless dragged down from its top with
        // a pane above: its top moves down there, the pane above taking the
        // rows, as acme's window dragged by its button does. With no rule
        // between panes, that is how a terminal resizes them.
        if (cur_y >= top and cur_y < top + span_h and (src.idx == 0 or cur_y <= top)) return null;
    }
    // Every pane's rows as laid out; only the placed panes' are read.
    var heights: [MAX_PANES]u16 = undefined;
    for (&heights, p.rects) |*h, r| h.* = r.h;
    if (p.cols[src.col].n > span_end - src.idx) {
        const sib = if (src.idx > 0) p.cols[src.col].panes[src.idx - 1] else p.cols[src.col].panes[span_end];
        heights[sib] +|= span_h;
    }
    var y: u16 = p.topBarHeight() + columnBarHeight(p);
    if (p.cols[tc].n == 0) return .{ .preview_col = tc, .above_id = null, .row = y, .above_y = y, .above_h = 0 };
    var last: ?MovePlacement = null;
    var k: usize = 0;
    while (k < p.cols[tc].n) {
        if (tc == src.col and k >= src.idx and k < span_end) {
            k += 1;
            continue;
        }
        // Its own group's panes are places of their own: that is how an
        // attachment's grip resizes it against its owner.
        const unit_end = if (groupRoot(p, p.cols[tc].panes[k]) == own_root) k + 1 else groupEnd(p, tc, k);
        var h: u16 = 0;
        for (k..unit_end) |j| {
            if (tc == src.col and j >= src.idx and j < span_end) continue;
            h +|= heights[p.cols[tc].panes[j]];
        }
        const above = p.cols[tc].panes[unit_end - 1];
        k = unit_end;
        const row = splitRowFor(y, h, cur_y, if (tc == src.col) BOX_H else null) orelse {
            y +|= h;
            continue;
        };
        const placement: MovePlacement = .{
            .preview_col = tc,
            .above_id = above,
            .row = row,
            .above_y = y,
            .above_h = h,
        };
        last = placement;
        if (cur_y < y + h) return placement;
        y +|= h;
    }
    return last;
}

/// Move pane `id`, and the group it owns, where movePlacement says. An
/// attachment moved anywhere but within its own group is detached there.
pub fn movePane(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) void {
    const placement = movePlacement(p, id, cur_x, cur_y) orelse return;
    const src = findPane(p, id) orelse return;
    const owner = ownerOf(p, id);
    const own_root = groupRoot(p, id);
    const span_end = if (owner == null) groupEnd(p, src.col, src.idx) else src.idx + 1;
    const count = span_end - src.idx;
    var moved: [MAX_PANES]usize = undefined;
    @memcpy(moved[0..count], p.cols[src.col].panes[src.idx..span_end]);
    const source_multi = p.cols[src.col].n > count;
    var heights: [MAX_PANES]u16 = undefined;
    for (&heights, p.rects) |*h, r| h.* = r.h;
    var span_h: u16 = 0;
    for (moved[0..count]) |m| span_h +|= heights[m];
    for (moved[0..count]) |m| removePane(p, m);
    if (source_multi) {
        const sib = if (src.idx > 0) p.cols[src.col].panes[src.idx - 1] else p.cols[src.col].panes[src.idx];
        heights[sib] +|= span_h;
    }
    const above = placement.above_id orelse {
        for (moved[0..count], 0..) |m, j| insert(p, placement.preview_col, j, m);
        if (count > 1) setColumnWeights(p, placement.preview_col, &heights);
        if (source_multi) setColumnWeights(p, src.col, &heights);
        if (owner != null) p.panes[id].?.attached_to = null;
        return;
    };
    const af = findPane(p, above) orelse return;
    const upper_h = @max(1, placement.row -| placement.above_y);
    var lower_h = @max(1, placement.above_h -| upper_h);
    const above_root = groupRoot(p, above);
    if (above_root != above and above_root != own_root) {
        // Dropped on another group: its owner gives the rows, keeping its tag.
        const pay = @min(placement.above_h -| upper_h, heights[above_root] -| BOX_H);
        heights[above_root] -= pay;
        lower_h = @max(1, pay);
    } else heights[above] = upper_h;
    // The group shares what it lands in as it shared what it had.
    var left = lower_h;
    for (moved[1..count]) |m| {
        const share: u16 = @intCast(@max(1, @as(u32, heights[m]) * lower_h / @max(1, span_h)));
        heights[m] = share;
        left -|= share;
    }
    heights[id] = @max(1, left);
    for (moved[0..count], 0..) |m, j| insert(p, af.col, af.idx + 1 + j, m);
    setColumnWeights(p, af.col, &heights);
    if (source_multi and src.col != af.col) setColumnWeights(p, src.col, &heights);
    if (owner) |o| {
        const pane = p.panes[id].?;
        // Still right under its owner's group: resized there. Anywhere
        // else it is a pane of its own.
        if (af.col != (findPane(p, o) orelse return).col or !descends(p, above, o)) pane.attached_to = null;
    }
}

pub fn setColumnWeights(p: *Pardes, col: usize, heights: *const [MAX_PANES]u16) void {
    if (col >= p.ncol) return;
    for (0..p.cols[col].n) |k| {
        const pid = p.cols[col].panes[k];
        if (p.panes[pid]) |pane| if (!pane.collapsed) {
            pane.vweight = @floatFromInt(@max(1, heights[pid]));
        };
    }
}

/// Give a newly opened report enough rows to read, borrowing only space
/// above the other panes' usable minima. Keep their tags and bodies visible.
pub fn givePaneRows(p: *Pardes, id: usize, wanted: u16, context: usize) void {
    const at = findPane(p, id) orelse return;
    compute(p);
    var heights: [MAX_PANES]u16 = @splat(0);
    for (p.cols[at.col].panes[0..p.cols[at.col].n]) |other| heights[other] = p.rects[other].h;
    var missing = wanted -| heights[id];
    for (p.cols[at.col].panes[0..p.cols[at.col].n]) |other| {
        if (other == id or p.panes[other].?.collapsed) continue;
        const body_rows: u16 = if (other == context) 6 else 3;
        const minimum = @max(minRows(p, other), p.panes[other].?.tag_rows + body_rows);
        const take = @min(missing, heights[other] -| minimum);
        heights[other] -= take;
        heights[id] += take;
        missing -= take;
        if (missing == 0) break;
    }
    setColumnWeights(p, at.col, &heights);
    p.sync();
}

pub fn applyRowSplit(p: *Pardes, cc: usize, k: usize, cur_y: u16) void {
    if (k + 1 >= p.cols[cc].n) return;
    const a = p.panes[p.cols[cc].panes[k]] orelse return;
    const b = p.panes[p.cols[cc].panes[k + 1]] orelse return;
    const ra = p.rects[p.cols[cc].panes[k]];
    const rb = p.rects[p.cols[cc].panes[k + 1]];
    const combined: f32 = @floatFromInt(ra.h + rb.h);
    var nt: f32 = @floatFromInt((cur_y + 1) -| ra.y);
    // A terminal keeps its tag and two body rows (floorRows); a text pane
    // gives up all but its tag, as acme's do.
    const lo: f32 = @floatFromInt(@max(BOX_H, floorRows(p, p.cols[cc].panes[k])));
    const hi = combined - @as(f32, @floatFromInt(@max(BOX_H, floorRows(p, p.cols[cc].panes[k + 1]))));
    nt = std.math.clamp(nt, @min(lo, @max(@as(f32, BOX_H), hi)), @max(@as(f32, BOX_H), hi));
    if (combined <= 0) return;
    // Dragging a folded tag open is an explicit resize, so switch this pair
    // back to visible-height weights without consuming other folded weights.
    if ((a.collapsed and nt > BOX_H) or (b.collapsed and combined - nt > BOX_H)) {
        snapColWeights(p, cc);
        a.vweight = @floatFromInt(@max(1, ra.h));
        b.vweight = @floatFromInt(@max(1, rb.h));
        if (nt > BOX_H) a.collapsed = false;
        if (combined - nt > BOX_H) b.collapsed = false;
    }
    if (a.collapsed or b.collapsed) return;
    const pair = a.vweight + b.vweight;
    a.vweight = pair * (nt / combined);
    b.vweight = pair - a.vweight;
}

pub fn findPane(p: *const Pardes, id: usize) ?struct { col: usize, idx: usize } {
    for (0..p.ncol) |c| {
        for (0..p.cols[c].n) |k| {
            if (p.cols[c].panes[k] == id) return .{ .col = c, .idx = k };
        }
    }
    return null;
}

pub fn insert(p: *Pardes, c: usize, idx: usize, id: usize) void {
    var k = p.cols[c].n;
    while (k > idx) : (k -= 1) p.cols[c].panes[k] = p.cols[c].panes[k - 1];
    p.cols[c].panes[idx] = id;
    p.cols[c].n += 1;
}

/// Take a pane out of its column. The column stays, empty if this was its
/// last pane, as acme's colclose leaves it (cols.c:186): only Delcol and
/// Joincol take a column away.
pub fn removePane(p: *Pardes, id: usize) void {
    const f = findPane(p, id) orelse return;
    const c = f.col;
    var k = f.idx;
    while (k + 1 < p.cols[c].n) : (k += 1) p.cols[c].panes[k] = p.cols[c].panes[k + 1];
    p.cols[c].n -= 1;
}

/// Close column `c` once its panes are gone, its width to the one left of
/// it (the first column's to its right), as acme's rowclose gives it.
pub fn dropColumn(p: *Pardes, c: usize) void {
    const serial = columnSerial(p, c);
    dropColumnUnannounced(p, c);
    noteColumn(p, "delcol", serial);
}

/// dropColumn with no `delcol`, for a column never announced.
pub fn dropColumnUnannounced(p: *Pardes, c: usize) void {
    std.debug.assert(p.cols[c].n == 0);
    tagline.exitHeader(p);
    const heir: ?usize = if (p.ncol <= 1) null else if (c > 0) c - 1 else c + 1;
    if (heir) |h| p.cols[h].weight +|= p.cols[c].weight;
    p.col_tags[c].deinit(p.gpa);
    var j = c;
    while (j + 1 < p.ncol) : (j += 1) {
        p.cols[j] = p.cols[j + 1];
        p.col_tags[j] = p.col_tags[j + 1];
    }
    p.ncol -= 1;
    p.col_tags[p.ncol] = .{ .what = .column, .gpa = p.gpa };
    p.cols[p.ncol].serial = 0;
}

/// `newcol <serial>` or `delcol <serial>` in the log: the column's serial,
/// as /layout and /col name it.
pub fn noteColumn(p: *Pardes, what: []const u8, serial: u32) void {
    var buf: [16]u8 = undefined;
    pardes.ctlfs.events.notePath(p, what, std.fmt.bufPrint(&buf, "{d}", .{serial}) catch return);
}

/// Fold column `c` into the one on its right, its panes below theirs.
pub fn joinCol(p: *Pardes, c: usize) void {
    if (c + 1 >= p.ncol) return;
    const dst = c + 1;
    joinPanes(p, c, dst);
    dropColumn(p, c);
}

/// Whether column `c` joined into the one on its right leaves every pane
/// its tag and 2 rows (minimaFit), tried in place and undone: nothing is
/// dropped or logged for a join that does not fit.
pub fn joinFits(p: *Pardes, c: usize) bool {
    if (c + 1 >= p.ncol) return true;
    const dst = c + 1;
    const kept = .{ p.cols[c], p.cols[dst] };
    joinPanes(p, c, dst);
    const fits = minimaFit(p);
    p.cols[c] = kept[0];
    p.cols[dst] = kept[1];
    compute(p);
    return fits;
}

fn joinPanes(p: *Pardes, c: usize, dst: usize) void {
    for (0..p.cols[c].n) |k| p.cols[dst].panes[p.cols[dst].n + k] = p.cols[c].panes[k];
    p.cols[dst].n += p.cols[c].n;
    p.cols[c].n = 0;
    // The width goes right, where the panes went.
    p.cols[dst].weight +|= p.cols[c].weight;
    p.cols[c].weight = 0;
}

/// Put new pane `id` in column `c` as acme's makenewwindow does
/// (util.c:449-495): an empty column it takes whole; asked from a tag or
/// from 9P (`origin` null, acme's t->w == nil) it takes the bottom half of
/// the column's last pane (coladd with y < 0, cols.c:62-65). Asked from a
/// pane's text, it goes under the text of the pane with the most blank rows
/// when there are many, else it halves the biggest pane, or `origin` when
/// that is in the column and not much smaller.
pub fn acmePlace(p: *Pardes, c: usize, origin: ?usize, id: usize) void {
    compute(p);
    const n = p.cols[c].n;
    if (n == 0) {
        insert(p, c, 0, id);
        p.panes[id].?.vweight = 1;
        return;
    }
    var big: ?usize = null;
    var empty: ?usize = null;
    for (p.cols[c].panes[0..n]) |k| {
        const pane = p.panes[k] orelse continue;
        // An attachment is its owner's: never halved for another pane.
        if (pane.collapsed or ownerOf(p, k) != null) continue;
        // `>=`: at a tie the one nearer the bottom, as acme picks.
        if (big == null or bodyRows(p, k) >= bodyRows(p, big.?)) big = k;
        if (empty == null or blankRows(p, k) >= blankRows(p, empty.?)) empty = k;
    }
    const v0 = big orelse {
        // Every pane folded: the new one goes last.
        insert(p, c, n, id);
        return;
    };
    const y: u16 = y: {
        const o = origin orelse {
            var last = v0;
            for (p.cols[c].panes[0..n]) |k| if (!p.panes[k].?.collapsed and ownerOf(p, k) == null) {
                last = k;
            };
            break :y bodyFrom(p, last) + bodyRows(p, last) / 2;
        };
        const e = empty.?;
        const el = blankRows(p, e);
        if (el > 15 or (el > 3 and el > (bodyRows(p, v0) -| 1) / 2))
            break :y bodyFrom(p, e) + bodyRows(p, e) - el;
        // Asked from a results pane, it is its owner that is split.
        const root = groupRoot(p, o);
        const mine = if (findPane(p, root)) |f| f.col == c and !p.panes[root].?.collapsed else false;
        const v = if (mine and @as(u32, p.rects[root].h) * 3 > @as(u32, p.rects[v0].h) * 2) root else v0;
        break :y p.rects[v].y + p.rects[v].h / 2;
    };
    splitAt(p, c, id, y);
}

/// The body rows a placement leaves every pane it makes or shrinks, under
/// its tag (acme's minht keeps one).
pub const min_body_rows = 2;

/// The rows a placement, and a `size`, leave a pane: its tag at its width
/// and `min_body_rows`. The one minimum both ask.
pub fn minRows(p: *Pardes, id: usize) u16 {
    return wantedTagRows(p, id) + min_body_rows;
}

/// Whether every column has the rows for each of its unfolded panes'
/// `minRows` (a folded one its tag row): the panes' own minima, not how
/// the weights happen to share the rows, so a size that fits keeps fitting
/// when it grows. One pane alone in its column always fits.
pub fn minimaFit(p: *Pardes) bool {
    compute(p);
    const avail = p.screen_h -| (p.topBarHeight() + columnBarHeight(p));
    for (0..p.ncol) |c| {
        if (p.cols[c].n < 2) continue;
        var need: u32 = 0;
        for (p.cols[c].panes[0..p.cols[c].n]) |k| {
            const pane = p.panes[k] orelse continue;
            need += if (pane.collapsed) BOX_H else minRows(p, k);
        }
        if (need > avail) return false;
    }
    return true;
}

/// Whether every unfolded pane of column `c` has its `minRows` (a pane
/// alone in its column always does).
pub fn columnAtMinimums(p: *Pardes, c: usize) bool {
    compute(p);
    if (p.cols[c].n < 2) return true;
    for (p.cols[c].panes[0..p.cols[c].n]) |k| {
        const pane = p.panes[k] orelse continue;
        if (!pane.collapsed and p.rects[k].h < minRows(p, k)) return false;
    }
    return true;
}

/// Shares column `c`'s rows out again so every unfolded pane has its
/// `minRows`, as evenly as that allows; false, changing nothing, when the
/// column has not the rows for all of them (or holds a folded pane).
pub fn shareColumn(p: *Pardes, c: usize) bool {
    compute(p);
    const n = p.cols[c].n;
    if (n == 0) return false;
    const avail = p.screen_h -| (p.topBarHeight() + columnBarHeight(p));
    var mins: [MAX_PANES]u16 = undefined;
    var need: u32 = 0;
    for (p.cols[c].panes[0..n], 0..) |k, i| {
        const pane = p.panes[k] orelse return false;
        if (pane.collapsed) return false;
        p.rects[k].w = p.col_w[c];
        mins[i] = minRows(p, k);
        need += mins[i];
    }
    if (need > avail) return false;
    // Each its minimum, then what is left a row at a time to the smallest.
    var hs: [MAX_PANES]u16 = undefined;
    @memcpy(hs[0..n], mins[0..n]);
    var left = avail - need;
    while (left > 0) : (left -= 1) {
        var low: usize = 0;
        for (1..n) |i| if (hs[i] < hs[low]) {
            low = i;
        };
        hs[low] += 1;
    }
    for (p.cols[c].panes[0..n], 0..) |k, i| p.panes[k].?.vweight = @floatFromInt(hs[i]);
    compute(p);
    return true;
}

/// Each pane's `minRows` now: what `restoreMinimaFrom` measures a step that
/// grows the minima (a narrower column wrapping tags) against.
pub fn minima(p: *Pardes) [MAX_PANES]u16 {
    compute(p);
    var mins: [MAX_PANES]u16 = @splat(0);
    for (0..p.ncol) |c| for (p.cols[c].panes[0..p.cols[c].n]) |k| {
        mins[k] = minRows(p, k);
    };
    return mins;
}

/// After a resize the minima fit: each unfolded pane the resize took below
/// its `minRows` (it had them in `before`) gets them back, a row at a time
/// from whichever pane of its column has the most above its own. A pane
/// dragged short before keeps what it had. With `before_min`, a pane's
/// minimum before the step (its tag may wrap onto more rows since): one
/// that had that minimum is lifted to its minimum now.
pub fn restoreMinimaFrom(p: *Pardes, before: *const [MAX_PANES]Rect, before_min: ?*const [MAX_PANES]u16) void {
    compute(p);
    for (0..p.ncol) |c| {
        const n = p.cols[c].n;
        if (n < 2) continue;
        var hs: [MAX_PANES]u16 = undefined;
        var mins: [MAX_PANES]u16 = undefined;
        var short = false;
        for (p.cols[c].panes[0..n], 0..) |k, i| {
            const pane = p.panes[k] orelse return;
            if (pane.collapsed) break;
            hs[i] = p.rects[k].h;
            mins[i] = minRows(p, k);
            if (hs[i] < mins[i] and before[k].h >= if (before_min) |bm| bm[k] else mins[i]) short = true;
        } else {
            if (!short) continue;
            for (p.cols[c].panes[0..n], 0..) |k, i| {
                if (hs[i] >= mins[i] or before[k].h < if (before_min) |bm| bm[k] else mins[i]) continue;
                while (hs[i] < mins[i]) {
                    var giver: ?usize = null;
                    var spare: u16 = 0;
                    for (0..n) |j| if (j != i and hs[j] -| mins[j] > spare) {
                        spare = hs[j] - mins[j];
                        giver = j;
                    };
                    const g = giver orelse break;
                    hs[g] -= 1;
                    hs[i] += 1;
                }
            }
            for (p.cols[c].panes[0..n], 0..) |k, i| p.panes[k].?.vweight = @floatFromInt(@max(1, hs[i]));
        }
    }
    compute(p);
}

/// Whether new column `c` (Newcol's) may stay. A narrower
/// column wraps long tags onto more rows, which can leave a pane under its
/// tag and two rows: each pane a column squeezed so (one that had its
/// minimum `before`, `before_min`, not one dragged short) takes rows back
/// from the panes with rows to spare, its column shared out again only
/// where that is not enough. False, `c` dropped unannounced, where nothing
/// holds every minimum, as a size too small is refused.
pub fn keepColumn(p: *Pardes, c: usize, before: *const [MAX_PANES]Rect, before_min: *const [MAX_PANES]u16) bool {
    restoreMinimaFrom(p, before, before_min);
    for (0..p.ncol) |k| {
        compute(p);
        if (p.cols[k].n < 2) continue;
        const squeezed = for (p.cols[k].panes[0..p.cols[k].n]) |id| {
            const pane = p.panes[id] orelse continue;
            if (!pane.collapsed and p.rects[id].h < minRows(p, id) and before[id].h >= before_min[id]) break true;
        } else false;
        if (squeezed and !shareColumn(p, k)) {
            dropColumnUnannounced(p, c);
            return false;
        }
    }
    return true;
}

/// Column `c`'s rows for `id`, last in it, at its minimum: a row at a
/// time from whichever pane has the most above its own minimum, so a pane
/// dragged short keeps its rows and the others give only what they must.
/// False, changing nothing, when the column has not the rows.
pub fn takeRoom(p: *Pardes, c: usize, id: usize) bool {
    compute(p);
    const n = p.cols[c].n;
    p.rects[id].w = p.col_w[c];
    var need = minRows(p, id);
    var hs: [MAX_PANES]u16 = undefined;
    var mins: [MAX_PANES]u16 = undefined;
    var spare: u32 = 0;
    for (p.cols[c].panes[0..n], 0..) |k, i| {
        const pane = p.panes[k] orelse return false;
        if (pane.collapsed) return false;
        hs[i] = p.rects[k].h;
        mins[i] = minRows(p, k);
        spare += hs[i] -| mins[i];
    }
    if (spare < need) return false;
    while (need > 0) : (need -= 1) {
        var giver: usize = 0;
        for (1..n) |i| if (hs[i] -| mins[i] > hs[giver] -| mins[giver]) {
            giver = i;
        };
        hs[giver] -= 1;
    }
    for (p.cols[c].panes[0..n], 0..) |k, i| p.panes[k].?.vweight = @floatFromInt(@max(1, hs[i]));
    insert(p, c, n, id);
    p.panes[id].?.vweight = @floatFromInt(minRows(p, id));
    compute(p);
    return true;
}

/// After placing `id`: whether it, and every pane of its column that the
/// placement shrank, still has its tag and `min_body_rows` (from `before`,
/// the rects as they were). A pane alone in its column always has room: the
/// window can be no taller.
pub fn placedRoomy(p: *Pardes, id: usize, before: *const [MAX_PANES]Rect) bool {
    compute(p);
    const f = findPane(p, id) orelse return true;
    if (p.cols[f.col].n == 1) return true;
    for (p.cols[f.col].panes[0..p.cols[f.col].n]) |k| {
        const pane = p.panes[k] orelse continue;
        if (pane.collapsed) continue;
        if (k != id and p.rects[k].h >= before[k].h) continue;
        if (p.rects[k].h < minRows(p, k)) return false;
    }
    return true;
}

/// Places `id` last in column `c`, where acme's coladd puts a new window,
/// with half the rows of the column's tallest unfolded pane, when that
/// leaves both their rows; false, and `id` in no column, when not.
pub fn splitTallest(p: *Pardes, c: usize, id: usize) bool {
    compute(p);
    var tall: ?usize = null;
    for (p.cols[c].panes[0..p.cols[c].n]) |k| {
        if (k == id or p.panes[k].?.collapsed or ownerOf(p, k) != null) continue;
        if (tall == null or p.rects[k].h > p.rects[tall.?].h) tall = k;
    }
    const v = tall orelse return false;
    const h = p.rects[v].h;
    // Its tag wraps at the column's width: measured there, not at none.
    p.rects[id].w = p.col_w[c];
    if (h < minRows(p, v) + minRows(p, id)) return false;
    snapColWeights(p, c);
    insert(p, c, p.cols[c].n, id);
    const given = std.math.clamp(h / 2, minRows(p, id), h - minRows(p, v));
    p.panes[v].?.vweight = @floatFromInt(h - given);
    p.panes[id].?.vweight = @floatFromInt(given);
    return true;
}

/// acme's coladd at row `y` (cols.c:66-126): the new pane goes under the
/// pane that `y` falls in, which keeps its rows above `y`.
///
/// `y` in a group: the new pane goes under all of it, its rows from the
/// group's owner, so nothing lands between a pane and its results.
fn splitAt(p: *Pardes, c: usize, id: usize, y: u16) void {
    const n = p.cols[c].n;
    var k: usize = 0;
    while (k + 1 < n and y >= p.rects[p.cols[c].panes[k]].y + p.rects[p.cols[c].panes[k]].h) k += 1;
    const v = groupRoot(p, p.cols[c].panes[k]);
    const r = p.rects[v];
    snapColWeights(p, c);
    insert(p, c, groupEnd(p, c, k), id);
    const pane = p.panes[id].?;
    // Each keeps a tag and min_body_rows, where acme's minht keeps one.
    const lo = r.y +| minRows(p, v);
    const hi = (r.y + r.h) -| minRows(p, id);
    const row = splitRowFor(r.y, r.h, if (lo <= hi) std.math.clamp(y, lo, hi) else r.y + r.h / 2, null) orelse {
        pane.vweight = BOX_H + 1;
        return;
    };
    // `y` fell in an unfolded pane: acmePlace picks from those.
    p.panes[v].?.vweight = @floatFromInt(@max(1, row - r.y));
    pane.vweight = @floatFromInt(@max(1, (r.y + r.h) - row));
}

/// A pane's top plus its tag's rows, as heights go: a split this far down
/// leaves the pane its tag and that much of its body.
fn bodyFrom(p: *const Pardes, id: usize) u16 {
    return p.rects[id].y + p.panes[id].?.tag_rows;
}

fn bodyRows(p: *const Pardes, id: usize) u16 {
    return p.rects[id].h -| p.panes[id].?.tag_rows;
}

/// The rows at the bottom of a pane's body that show nothing: acme's
/// maxlines - nlines. A picture or a PDF page fills its body.
fn blankRows(p: *const Pardes, id: usize) u16 {
    const pane = p.panes[id].?;
    const rows = bodyRows(p, id);
    const used: usize = if (pane.file) |*f|
        // The empty line after a final newline shows nothing.
        (panes.File.nlines(p.gpa, f) -| @intFromBool(std.mem.endsWith(u8, f.content, "\n"))) -| f.scroll
    else if (pane.isTerminal())
        @as(usize, panes.terminal.gridCursor(pane).y) + 1
    else
        rows;
    return rows -| @as(u16, @intCast(@min(used, rows)));
}

/// Whether column `col` has the width and the weight to halve for a new
/// column beside it.
pub fn canSplitCol(p: *Pardes, col: usize) bool {
    if (p.ncol >= MAX_COLS or col >= p.ncol) return false;
    // Refresh derived widths: public layout surgery may be chained between
    // syncs, and a cached width must never admit a now-too-narrow split.
    compute(p);
    if (p.col_w[col] < config.MINW * 2) return false;

    const weight = p.cols[col].weight;
    if (weight >= 2 and weight % 2 == 0) return true;
    for (0..p.ncol) |column| if (p.cols[column].weight > std.math.maxInt(u64) / 2)
        return false;
    return weight > 0;
}

/// An empty column beside column `col`, with half its width: acme's Newcol
/// (rowadd, rows.c:51). The new column's index, or null with no room.
/// A window with no column left (Delcol took the last, as acme lets it):
/// its first one, empty; null when it has columns.
pub fn firstColumn(p: *Pardes) ?usize {
    if (p.ncol != 0) return null;
    p.cols[0] = .{ .weight = 2 };
    p.col_tags[0] = .{ .what = .column, .gpa = p.gpa };
    p.ncol = 1;
    noteColumn(p, "newcol", columnSerial(p, 0));
    return 0;
}

pub fn insertColumn(p: *Pardes, col: usize, before: bool) ?usize {
    const c = insertColumnUnannounced(p, col, before) orelse return null;
    noteColumn(p, "newcol", columnSerial(p, c));
    return c;
}

/// insertColumn with no serial given and no `newcol`: a column that may
/// yet be taken back (Newcol's trial), which then leaves no trace.
pub fn insertColumnUnannounced(p: *Pardes, col: usize, before: bool) ?usize {
    if (!canSplitCol(p, col)) return null;
    var old_weight = p.cols[col].weight;
    if (old_weight < 2 or old_weight % 2 != 0) {
        old_weight *= 2;
        for (0..p.ncol) |column| p.cols[column].weight *= 2;
    }
    const source_weight = old_weight / 2;
    p.cols[col].weight = source_weight;
    const c = col + @intFromBool(!before);
    tagline.exitHeader(p);
    var j = p.ncol;
    while (j > c) : (j -= 1) {
        p.cols[j] = p.cols[j - 1];
        p.col_tags[j] = p.col_tags[j - 1];
    }
    p.cols[c] = .{ .weight = old_weight - source_weight };
    p.col_tags[c] = .{ .what = .column, .gpa = p.gpa };
    p.ncol += 1;
    return c;
}

/// Pane `id` alone in a new column beside `source_id`'s; `id` may be the
/// source itself when its column keeps another pane.
pub fn splitColumn(p: *Pardes, source_id: usize, id: usize, before: bool) bool {
    if (id >= MAX_PANES or p.panes[id] == null) return false;
    if (source_id >= MAX_PANES or p.panes[source_id] == null) return false;
    const source = findPane(p, source_id) orelse return false;
    if (!canSplitCol(p, source.col)) return false;
    if (id == source_id) {
        if (p.cols[source.col].n <= 1) return false;
        _ = absorbVWeight(p, id, null);
        removePane(p, id);
    } else if (findPane(p, id) != null) return false;
    const c = insertColumn(p, source.col, before).?;
    insert(p, c, 0, id);
    return true;
}

pub fn snapColWeights(p: *Pardes, c: usize) void {
    for (0..p.cols[c].n) |k| {
        const pid = p.cols[c].panes[k];
        if (p.panes[pid]) |pp| if (!pp.collapsed) {
            pp.vweight = @floatFromInt(@max(1, p.rects[pid].h));
        };
    }
}

/// Hand a closing pane's rows to `to`. With none named they go up: past any
/// results listing to the nearest pane above that is not one, or to the
/// pane below when the closing one is first in its column.
/// Give a closing pane's rows to `to`, or to the nearest document above it
/// (the pane below for the top one); the pane that got them is returned.
pub fn absorbVWeight(p: *Pardes, id: usize, to: ?usize) ?usize {
    const f = findPane(p, id) orelse return null;
    if (p.cols[f.col].n <= 1) return null;
    // A refused pane held no weight: the rows the others' rounding lent it
    // go back to them as they were, nobody's weight snapped.
    if (p.panes[id]) |pane| if (!pane.collapsed and pane.vweight == 0) return null;
    snapColWeights(p, f.col);
    var sib = to orelse if (f.idx > 0) p.cols[f.col].panes[f.idx - 1] else p.cols[f.col].panes[f.idx + 1];
    var k = f.idx;
    while (to == null and k > 0) : (k -= 1) {
        sib = p.cols[f.col].panes[k - 1];
        // nor to a pane attached to another: rows go to owners
        if (p.panes[sib]) |pp| if (if (pp.file) |ff| panes.Output.fileTraits(ff.output).doc else true) if (ownerOf(p, sib) == null) break;
    }
    const s = p.panes[sib] orelse return null;
    s.vweight += @as(f32, @floatFromInt(@max(1, p.rects[id].h)));
    return sib;
}

pub fn splitBelow(p: *Pardes, src_id: usize, nw: *Pane) void {
    const src = p.panes[src_id] orelse return;
    const src_h = p.rects[src_id].h;
    // Its tag may wrap to more than one row: the rows under it are its body.
    const tag_h = @max(BOX_H, src.tag_rows);
    const body: u16 = if (src_h > tag_h) src_h - tag_h else 1;
    const cur: u16 = if (!src.isTerminal()) body / 2 else panes.terminal.gridCursor(src).y + 1;
    // cap keep so a content-full source still leaves the new pane a tag +
    // a few body rows (an Alt-n from a full shell was born 0 rows tall)
    // ...and the source min_body_rows of its own (exec.placeNew), when it
    // has them: a boot layout splits before any row is laid out.
    const least = @min(min_body_rows, body);
    const keep = std.math.clamp(cur, least, @max(least, body -| (BOX_H + 3)));
    // The new pane's weight, and the source's, are set just below.
    if (findPane(p, src_id)) |f| snapColWeights(p, f.col);
    if (!src.collapsed) src.vweight = @floatFromInt(tag_h + keep);
    nw.vweight = @floatFromInt(@max(1, src_h -| (tag_h + keep)));
    if (nw.file) |f| if (!panes.Output.fileTraits(f.output).doc) {
        // trimmed: every row ends in a newline, and the empty line after
        // the last one is not a result
        const want: f32 = @floatFromInt(BOX_H + @max(min_body_rows, panes.File.lineCount(std.mem.trimEnd(u8, f.content, "\n"))));
        if (want < nw.vweight) {
            src.vweight += nw.vweight - want;
            nw.vweight = want;
        }
    };
}

// ---- Attached panes ----
//
// A results pane (+Search, +Callstack, +Diff, +Errors) is ATTACHED to the
// pane it answers for, its owner (Pane.attached_to). The owner and what is
// attached to it, and what is attached to those (a preview under a
// +Search), are a GROUP: contiguous in one column, the owner first. A group
// is one place to everything else in the layout: an unrelated pane is never
// put inside it (acmePlace, splitAt, splitTallest), a pane dragged onto it
// lands under all of it (movePlacement), and its owner's grip, Collapse and
// Del take all of it (movePane, toggleCollapse, Pardes.removePane). An
// attachment's rows come from its owner and go back to it, nobody else's.

/// The slot of `id`'s owner, when `id` is attached to a live pane.
pub fn ownerOf(p: *const Pardes, id: usize) ?usize {
    const serial = (p.panes[id] orelse return null).attached_to orelse return null;
    for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.serial == serial and i != id) return i;
    return null;
}

/// The owner at the top of `id`'s group: `id` itself when it is attached to
/// nothing. Bounded: a dump could name a ring of owners.
pub fn groupRoot(p: *const Pardes, id: usize) usize {
    var at = id;
    for (0..MAX_PANES) |_| at = ownerOf(p, at) orelse return at;
    return at;
}

/// Whether `id` is `root` or attached to it through any number of owners.
fn descends(p: *const Pardes, id: usize, root: usize) bool {
    var at = id;
    for (0..MAX_PANES) |_| {
        if (at == root) return true;
        at = ownerOf(p, at) orelse return false;
    }
    return false;
}

/// One past the last pane of the group that pane `idx` of column `c` is
/// in: `idx + 1` for a pane with nothing attached.
pub fn groupEnd(p: *const Pardes, c: usize, idx: usize) usize {
    const root = groupRoot(p, p.cols[c].panes[idx]);
    var k = idx + 1;
    while (k < p.cols[c].n and descends(p, p.cols[c].panes[k], root) and p.cols[c].panes[k] != root) k += 1;
    return k;
}

/// The attachments kept where they are attached: one whose owner is gone,
/// or that something (a 9P move, a pane split into a column of its own, an
/// owner moved by a route that does not carry its group) left anywhere but
/// right under its owner's group, is an ordinary pane from then on, where
/// it stands. Nothing moves. Top to bottom, so a nested attachment is
/// judged after the one it hangs from.
pub fn keepGroups(p: *Pardes) void {
    for (0..p.ncol) |c| for (p.cols[c].panes[0..p.cols[c].n], 0..) |id, k| {
        const pane = p.panes[id] orelse continue;
        if (pane.attached_to == null) continue;
        const kept = if (ownerOf(p, id)) |owner| k > 0 and descends(p, p.cols[c].panes[k - 1], owner) else false;
        if (kept) continue;
        pane.attached_to = null;
    };
}

/// Attach new pane `id`, in no column yet, to `owner`: under the owner's
/// group, `rows` of the owner's rows (tag included), from the owner and
/// from no other pane. The owner keeps its own minimum, else its tag (acme
/// lets a window shrink to it), so the attachment may get fewer. A folded
/// owner is unfolded first. The rows are the attachment's from then on:
/// nothing here ever resizes it again; the seam is the user's to drag.
/// False, `id` in no column, when the owner has not the rows for its tag
/// and the attachment's minimum. The rows are given by `giver`: the owner
/// itself or a pane of its group (a +Preview added under a query pane later
/// takes the text's rows, so the query pane, typed into, keeps its own).
pub fn attachFrom(p: *Pardes, owner: usize, id: usize, rows: u16, giver: usize) bool {
    const o = p.panes[owner] orelse return false;
    const g = p.panes[giver] orelse return false;
    const nw = p.panes[id] orelse return false;
    if (o.collapsed) toggleCollapse(p, owner);
    if (g.collapsed) toggleCollapse(p, giver);
    compute(p);
    const f = findPane(p, owner) orelse return false;
    if (giver != owner and groupRoot(p, owner) != groupRoot(p, giver)) return false;
    // Its tag wraps at the column's width: measured there.
    p.rects[id].w = p.col_w[f.col];
    const oh = p.rects[giver].h;
    const least = minRows(p, id);
    if (oh < least + BOX_H) return false;
    const giver_keeps = if (oh >= least + minRows(p, giver)) minRows(p, giver) else BOX_H;
    const give = std.math.clamp(rows, least, oh - giver_keeps);
    snapColWeights(p, f.col);
    insert(p, f.col, groupEnd(p, f.col, f.idx), id);
    g.vweight = @floatFromInt(oh - give);
    nw.vweight = @floatFromInt(give);
    nw.attached_to = o.serial;
    compute(p);
    return true;
}

/// A closed pane brought back (Store.reopen) where it was: next to
/// `gainer`, the pane its rows went to when it closed, below it (under its
/// group) or above it, `rows` tall, those rows taken from `gainer` alone,
/// so no other pane moves. False when the gainer is folded or too short
/// to give a pane its minimum and keep its own.
pub fn giveBack(p: *Pardes, id: usize, gainer: usize, below: bool, rows: u16) bool {
    const g = p.panes[gainer] orelse return false;
    const nw = p.panes[id] orelse return false;
    if (g.collapsed) return false;
    compute(p);
    const f = findPane(p, gainer) orelse return false;
    // Its tag wraps at the column's width: measured there.
    p.rects[id].w = p.col_w[f.col];
    const gh = p.rects[gainer].h;
    const least = minRows(p, id);
    const keeps = minRows(p, gainer);
    if (gh < least + keeps) return false;
    const give = std.math.clamp(rows, least, gh - keeps);
    snapColWeights(p, f.col);
    insert(p, f.col, if (below) groupEnd(p, f.col, f.idx) else f.idx, id);
    g.vweight = @floatFromInt(gh - give);
    nw.vweight = @floatFromInt(give);
    compute(p);
    return true;
}

/// Collapse on an owner with attachments: the whole group folds to its
/// tags, every row it gave up to the one unfolded neighbour outside it,
/// and unfolds again from that neighbour, as one pane's Collapse does.
/// ponytail: unfolding opens every attachment, one folded alone before
/// included; remembering which were is a bit a pane.
fn collapseGroup(p: *Pardes, c: usize, start: usize, end: usize) void {
    const root = p.panes[p.cols[c].panes[start]].?;
    const folding = !root.collapsed;
    snapColWeights(p, c);
    const neighbor = expandedNeighbor(p, c, start, .above) orelse expandedNeighbor(p, c, end - 1, .below);
    var spare: u16 = if (neighbor) |other| p.rects[other].h -| BOX_H else 0;
    for (p.cols[c].panes[start..end]) |k| {
        const pane = p.panes[k] orelse continue;
        if (folding) {
            if (pane.collapsed) continue;
            const h = p.rects[k].h;
            pane.vweight = @floatFromInt(@max(1, h));
            pane.collapsed = true;
            if (neighbor) |other| p.panes[other].?.vweight += @floatFromInt(h -| BOX_H);
        } else {
            if (!pane.collapsed) continue;
            const wanted: u16 = @intFromFloat(@min(@as(f32, @floatFromInt(std.math.maxInt(u16))), @max(1, @round(pane.vweight))));
            const give = if (neighbor != null) @min(wanted -| BOX_H, spare) else 0;
            spare -= give;
            if (neighbor) |other| p.panes[other].?.vweight -= @floatFromInt(give);
            pane.vweight = @floatFromInt(@max(1, BOX_H + give));
            pane.collapsed = false;
        }
    }
    compute(p);
}

pub fn columnBoundary(width: u16, prefix: u128, total: u128) u16 {
    if (total == 0) return 0;
    const pixels = (@as(u128, width) * prefix + total / 2) / total;
    return @intCast(@min(@as(u128, width), pixels));
}

pub fn toggleCollapse(p: *Pardes, id: usize) void {
    const pane = p.panes[id] orelse return;
    const at = findPane(p, id) orelse return;
    compute(p);
    // An owner folds and unfolds with what is attached to it.
    if (ownerOf(p, id) == null) {
        const end = groupEnd(p, at.col, at.idx);
        if (end > at.idx + 1) return collapseGroup(p, at.col, at.idx, end);
    }
    const was_collapsed = pane.collapsed;
    const old_height = p.rects[id].h;
    const remembered_height = pane.vweight;
    // Convert only visible panes to row weights. The toggle then changes one
    // pair, rather than letting the column redistribute the released space.
    snapColWeights(p, at.col);
    const neighbor = expandedNeighbor(p, at.col, at.idx, .above) orelse expandedNeighbor(p, at.col, at.idx, .below);
    if (was_collapsed) {
        if (neighbor) |other| {
            const wanted: u16 = @intFromFloat(@min(@as(f32, @floatFromInt(std.math.maxInt(u16))), @max(1, @round(remembered_height))));
            const give = @min(wanted -| old_height, p.rects[other].h -| BOX_H);
            p.panes[other].?.vweight -= @floatFromInt(give);
            pane.vweight = @floatFromInt(@max(1, old_height + give));
        }
        pane.collapsed = false;
    } else {
        // A folded pane's weight stores its former height, including its tag,
        // so Dump/Restore and a later expansion retain a useful target size.
        pane.vweight = @floatFromInt(@max(1, old_height));
        pane.collapsed = true;
        if (neighbor) |other|
            p.panes[other].?.vweight += @floatFromInt(old_height -| BOX_H);
    }
    compute(p);
}

/// The nearest pane on one side of `index` in its column that is not folded
/// to its tag: the one Collapse lends rows to and Del k / Del j gives them
/// to. A folded pane only keeps its weight for later, so rows handed to it
/// would spread over the whole column instead.
pub fn expandedNeighbor(p: *const Pardes, col: usize, index: usize, side: enum { above, below }) ?usize {
    var k = index;
    while (if (side == .above) k > 0 else k + 1 < p.cols[col].n) {
        k = if (side == .above) k - 1 else k + 1;
        const id = p.cols[col].panes[k];
        if (p.panes[id]) |pane| if (!pane.collapsed) return id;
    }
    return null;
}

fn computeCollapsedColumn(p: *Pardes, c: usize, x: u16, width: u16, folded: usize) void {
    var y: u16 = p.topBarHeight() + columnBarHeight(p);
    const available = p.screen_h -| y;
    var expanded_left: usize = 0;
    var weight: f32 = 0;
    for (p.cols[c].panes[0..p.cols[c].n]) |id| if (p.panes[id]) |pane| {
        if (!pane.collapsed) {
            expanded_left += 1;
            weight += pane.vweight;
        }
    };
    const expanded_height = available -| @as(u16, @intCast(folded));
    var budget = expanded_height;
    var folded_left = folded;
    for (p.cols[c].panes[0..p.cols[c].n]) |id| {
        const pane = p.panes[id] orelse continue;
        const room = p.screen_h -| y;
        const height: u16 = if (pane.collapsed) blk: {
            folded_left -= 1;
            break :blk @min(room, BOX_H);
        } else blk: {
            expanded_left -= 1;
            const limit = @min(budget, room -| @as(u16, @intCast(folded_left)));
            const share = @as(f32, @floatFromInt(expanded_height)) * pane.vweight / (if (weight > 0) weight else 1);
            const h = if (expanded_left == 0) limit else @min(limit -| @as(u16, @intCast(expanded_left)), @max(1, @as(u16, @intFromFloat(@round(share)))));
            budget -|= h;
            break :blk h;
        };
        p.rects[id] = .{ .x = x, .y = y, .w = width, .h = height };
        y +|= height;
    }
}

pub fn compute(p: *Pardes) void {
    p.rects = @splat(.{});
    if (p.ncol == 0) return;
    keepGroups(p);
    for (0..p.ncol) |column| _ = columnSerial(p, column);
    var wsum: u128 = 0;
    for (0..p.ncol) |c| wsum += p.cols[c].weight;
    if (wsum == 0) wsum = 1;

    // Round cumulative boundaries so widths still sum to the available screen.
    var prefix: u128 = 0;
    for (0..p.ncol) |c| {
        const x = columnBoundary(p.screen_w, prefix, wsum);
        prefix += p.cols[c].weight;
        const end: u16 = if (c == p.ncol - 1) p.screen_w else columnBoundary(p.screen_w, prefix, wsum);
        const cw = end -| x;
        p.col_x[c] = x;
        p.col_w[c] = cw;

        var folded: usize = 0;
        for (p.cols[c].panes[0..p.cols[c].n]) |id| if (p.panes[id]) |pane| {
            if (pane.collapsed) folded += 1;
        };
        if (folded > 0) {
            computeCollapsedColumn(p, c, x, cw, folded);
            continue;
        }

        var vsum: f32 = 0;
        for (0..p.cols[c].n) |k| {
            if (p.panes[p.cols[c].panes[k]]) |pane| vsum += pane.vweight;
        }
        if (vsum <= 0) vsum = 1;

        var y: u16 = p.topBarHeight() + columnBarHeight(p);
        const top = y;
        const avail_h = p.screen_h -| y;
        var hs: [MAX_PANES]u16 = undefined;
        const n = p.cols[c].n;
        for (0..n) |k| {
            const id = p.cols[c].panes[k];
            const pane = p.panes[id] orelse {
                hs[k] = 0;
                continue;
            };
            const lastk = k + 1 == n;
            const fh = @as(f32, @floatFromInt(avail_h)) * pane.vweight / vsum;
            const room = p.screen_h -| y;
            hs[k] = if (lastk) room else @min(room, @max(1, @as(u16, @intFromFloat(@round(fh)))));
            y +|= hs[k];
        }
        keepTerminalFloors(p, c, hs[0..n]);
        y = top;
        for (0..n) |k| {
            const id = p.cols[c].panes[k];
            if (p.panes[id] == null) continue;
            p.rects[id] = .{ .x = x, .y = y, .w = cw, .h = hs[k] };
            y +|= hs[k];
        }
    }
}

/// The fewest rows a pane is laid out with: a terminal keeps its tag and
/// `min_body_rows` (a shorter one loses its prompt and reads busy for
/// ever), a text pane may shrink to its tag, as acme's windows do.
fn floorRows(p: *Pardes, id: usize) u16 {
    const pane = p.panes[id] orelse return 0;
    return if (pane.isTerminal()) @max(1, pane.tag_rows) + min_body_rows else 1;
}

/// Raises each terminal in column `c` below its floor to it, a row at a
/// time from whichever pane has the most rows above its own floor. Where
/// the column has not the rows, the terminal keeps what it could get.
// ponytail: a row per step, O(panes x rows); a column holds few of both.
fn keepTerminalFloors(p: *Pardes, c: usize, hs: []u16) void {
    for (hs, 0..) |*h, k| {
        const floor = floorRows(p, p.cols[c].panes[k]);
        while (h.* < floor) {
            var giver: ?usize = null;
            var spare: u16 = 0;
            for (hs, 0..) |other, j| {
                if (j == k) continue;
                const extra = other -| floorRows(p, p.cols[c].panes[j]);
                if (extra > spare) {
                    spare = extra;
                    giver = j;
                }
            }
            const g = giver orelse break;
            hs[g] -= 1;
            h.* += 1;
        }
    }
}

test "collapse transfers height upward and restores the original layout" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 32 });
    defer p.deinit();
    _ = try p.newShell(1, "");
    _ = try p.newShell(2, "");
    insert(p, 0, 1, 1);
    insert(p, 0, 2, 2);
    p.panes[0].?.vweight = 3;
    p.panes[1].?.vweight = 2;
    compute(p);
    const original = p.rects;
    toggleCollapse(p, 1);
    try std.testing.expectEqual(@as(u16, 1), p.rects[1].h);
    try std.testing.expectEqual(@as(f32, @floatFromInt(original[1].h)), p.panes[1].?.vweight);
    try std.testing.expectEqual(p.screen_h, p.rects[2].y + p.rects[2].h);
    try std.testing.expect(p.rects[0].h > original[0].h);
    try std.testing.expectEqualDeep(original[2], p.rects[2]);
    toggleCollapse(p, 1);
    try std.testing.expectEqualDeep(original, p.rects);
    toggleCollapse(p, 2);
    try std.testing.expectEqual(@as(u16, 1), p.rects[2].h);
    try std.testing.expectEqual(p.screen_h, p.rects[2].y + p.rects[2].h);
}

test "collapse changes only one neighbor at the top middle and bottom" {
    for (0..4) |target| {
        const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 58 });
        defer p.deinit();
        for (1..4) |id| {
            _ = try p.newShell(id, "");
            insert(p, 0, id, id);
        }
        for ([_]f32{ 11, 7, 5, 3 }, 0..) |weight, id| p.panes[id].?.vweight = weight;
        compute(p);
        const original = p.rects;
        const recipient = if (target > 0) target - 1 else 1;
        for (0..5) |_| {
            toggleCollapse(p, target);
            try std.testing.expectEqual(@as(u16, BOX_H), p.rects[target].h);
            try std.testing.expectEqual(original[recipient].h + original[target].h - BOX_H, p.rects[recipient].h);
            for (0..4) |id| if (id != target and id != recipient)
                try std.testing.expectEqualDeep(original[id], p.rects[id]);
            toggleCollapse(p, target);
            try std.testing.expectEqualDeep(original, p.rects);
        }
    }
}

test "collapse skips folded neighbors and expansion reclaims only its neighbor" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 62 });
    defer p.deinit();
    for (1..5) |id| {
        _ = try p.newShell(id, "");
        insert(p, 0, id, id);
    }
    compute(p);
    toggleCollapse(p, 1);
    toggleCollapse(p, 2);
    const original = p.rects;
    toggleCollapse(p, 3);
    try std.testing.expectEqual(original[0].h + original[3].h - BOX_H, p.rects[0].h);
    try std.testing.expectEqualDeep(original[4], p.rects[4]);
    for (1..4) |id| try std.testing.expectEqual(@as(u16, BOX_H), p.rects[id].h);
    toggleCollapse(p, 3);
    try std.testing.expectEqualDeep(original, p.rects);
    // With no expanded pane above, give the space to the first one below.
    toggleCollapse(p, 0);
    const with_folded_above = p.rects;
    toggleCollapse(p, 3);
    try std.testing.expectEqual(with_folded_above[4].h + with_folded_above[3].h - BOX_H, p.rects[4].h);
    for (0..3) |id| try std.testing.expectEqualDeep(with_folded_above[id], p.rects[id]);
    toggleCollapse(p, 3);
    try std.testing.expectEqualDeep(with_folded_above, p.rects);
}

test "collapse local transfers remain bounded through repeated tiny window resizes" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 58 });
    defer p.deinit();
    for (1..5) |id| {
        _ = try p.newShell(id, "");
        insert(p, 0, id, id);
    }
    for (0..180) |step| {
        p.screen_h = @intCast((step * 17) % 81);
        compute(p);
        toggleCollapse(p, step % 5);
        var used: u16 = 0;
        for (0..5) |id| {
            const pane = p.panes[id].?;
            const rect = p.rects[id];
            try std.testing.expect(std.math.isFinite(pane.vweight) and pane.vweight > 0);
            try std.testing.expect(rect.h <= p.screen_h -| rect.y);
            if (pane.collapsed) try std.testing.expect(rect.h <= BOX_H);
            used += rect.h;
        }
        try std.testing.expect(used <= p.screen_h);
    }
}

test "collapse expansion is limited to space available in one neighbor" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 42 });
    defer p.deinit();
    // Text panes: a terminal would keep its tag and two rows (floorRows).
    for (1..4) |id| {
        p.newScratchBelow(0);
        try std.testing.expectEqual(id, p.cols[0].panes[id]);
    }
    compute(p);
    toggleCollapse(p, 2);
    snapColWeights(p, 0);
    // An intervening resize gave most of the donor's space to another pane.
    p.panes[0].?.vweight += p.panes[1].?.vweight - 2;
    p.panes[1].?.vweight = 2;
    compute(p);
    const before = p.rects;
    toggleCollapse(p, 2);
    try std.testing.expectEqual(@as(u16, 2), p.rects[2].h);
    try std.testing.expectEqual(@as(u16, BOX_H), p.rects[1].h);
    try std.testing.expectEqualDeep(before[0], p.rects[0]);
    try std.testing.expectEqualDeep(before[3], p.rects[3]);
}

test "collapse single and all panes leave unused column space" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 32 });
    defer p.deinit();
    toggleCollapse(p, 0);
    try std.testing.expectEqual(@as(u16, 1), p.rects[0].h);
    _ = try p.newShell(1, "");
    insert(p, 0, 1, 1);
    toggleCollapse(p, 1);
    try std.testing.expectEqual(@as(u16, 1), p.rects[0].h);
    try std.testing.expectEqual(@as(u16, 1), p.rects[1].h);
    try std.testing.expectEqual(p.rects[0].y + 1, p.rects[1].y);
    try std.testing.expect(p.rects[1].y + 1 < p.screen_h);
    toggleCollapse(p, 0);
    try std.testing.expectEqual(p.screen_h - 1, p.rects[1].y);
}

test "collapse survives tiny resizes" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 32 });
    defer p.deinit();
    _ = try p.newShell(1, "");
    _ = try p.newShell(2, "");
    insert(p, 0, 1, 1);
    insert(p, 0, 2, 2);
    p.panes[1].?.collapsed = true;
    for (0..50) |height| {
        p.screen_h = @intCast(height);
        compute(p);
        var used: u16 = 0;
        for (p.cols[0].panes[0..p.cols[0].n]) |id| {
            const rect = p.rects[id];
            try std.testing.expect(rect.h <= p.screen_h -| rect.y);
            used += rect.h;
        }
        try std.testing.expect(used <= p.screen_h);
        if (height >= 5) try std.testing.expectEqual(@as(u16, 1), p.rects[1].h);
    }
    p.screen_h = 32;
    compute(p);
    try std.testing.expectEqual(@as(u16, 1), p.rects[1].h);
}

test "collapse can be expanded by dragging its boundary" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 32 });
    defer p.deinit();
    _ = try p.newShell(1, "");
    insert(p, 0, 1, 1);
    toggleCollapse(p, 0);
    applyRowSplit(p, 0, 0, p.rects[0].y + 5);
    compute(p);
    try std.testing.expect(!p.panes[0].?.collapsed);
    try std.testing.expectEqual(@as(u16, 6), p.rects[0].h);
    toggleCollapse(p, 1);
    applyRowSplit(p, 0, 0, p.rects[1].y - 6);
    compute(p);
    try std.testing.expect(!p.panes[1].?.collapsed);
    try std.testing.expectEqual(@as(u16, 6), p.rects[1].h);
}

test "collapse dump restores folded state and retained expansion weight" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 32 });
    defer p.deinit();
    p.panes[0].?.vweight = 7;
    compute(p);
    const original_height = p.rects[0].h;
    toggleCollapse(p, 0);
    try dump.dumpState(p);
    const restored = try dump.initFromDump(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 32 }, p.dump_out.?);
    defer restored.deinit();
    try std.testing.expect(restored.panes[0].?.collapsed);
    try std.testing.expectEqual(@as(f32, @floatFromInt(original_height)), restored.panes[0].?.vweight);
    try std.testing.expectEqual(@as(u16, 1), restored.rects[0].h);
    toggleCollapse(restored, 0);
    try std.testing.expectEqual(restored.screen_h - restored.rects[0].y, restored.rects[0].h);
}

test "column reorder moves only crossed state and preserves weights" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 173, .rows = 20 });
    defer p.deinit();
    p.ncol = 4;
    for (0..4) |c| {
        p.cols[c].n = 0;
        p.cols[c].weight = c * 13 + 7;
        p.cols[c].serial = @intCast(c + 10);
        p.cols[c].panes[0] = c;
        p.col_tags[c].cur_col = @intCast(c + 20);
    }
    compute(p);
    const original_weights = weightsOf(p);
    const outer_x = p.col_x[0];
    const outer_w = p.col_w[0];
    p.header = .{ .column = 1 };
    p.header_scroll = 9;
    reorderColumn(p, 1, 3);
    try std.testing.expectEqual(original_weights[1], p.cols[3].weight);
    try std.testing.expectEqual(original_weights[2], p.cols[1].weight);
    try std.testing.expectEqual(@as(u32, 11), p.cols[3].serial);
    try std.testing.expectEqual(@as(?usize, 3), p.headerColumn());
    try std.testing.expectEqual(@as(i32, 21), tagline.focusedHeader(p).?.cur_col);
    try std.testing.expectEqual(@as(usize, 9), p.header_scroll);
    try std.testing.expectEqual(outer_x, p.col_x[0]);
    try std.testing.expectEqual(outer_w, p.col_w[0]);
    reorderColumn(p, 3, 1);
    try std.testing.expectEqualSlices(u64, original_weights[0..4], weightsOf(p)[0..4]);
    try std.testing.expectEqual(@as(i32, 21), p.col_tags[1].cur_col);
}

/// A test's attachment: an empty +Search in a new slot, in no column.
fn testAttachment(p: *Pardes) !usize {
    const free = p.freeSlot().?;
    _ = try panes.Output.open(p, free, "/tmp", .search, "", try p.gpa.dupe(u8, "q\n"));
    return free;
}

test "an attachment takes its rows from its owner alone, keeps them, and moves, folds and closes with it" {
    const exec = pardes.exec;
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 48 });
    defer p.deinit();
    _ = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma\nalpha two\ndelta\nepsilon\nzeta\n");
    p.newScratchBelow(0);
    p.newScratchBelow(0);
    const other_col = p.cols[0].panes[2];
    try std.testing.expect(splitColumn(p, other_col, other_col, false));
    const below = p.cols[0].panes[1];
    p.active = 0;
    compute(p);
    const before = p.rects;
    const unrelated = [_]usize{ below, other_col };

    // Under its owner, the rows asked for, the owner's and nobody else's.
    const s = try testAttachment(p);
    try std.testing.expect(attachFrom(p, 0, s, 9, 0));
    try std.testing.expectEqual(@as(?usize, 0), ownerOf(p, s));
    try std.testing.expectEqual(s, p.cols[0].panes[1]);
    for (unrelated) |k| try std.testing.expectEqualDeep(before[k], p.rects[k]);
    try std.testing.expectEqual(before[0].h, p.rects[0].h + p.rects[s].h);
    try std.testing.expectEqual(before[0].y, p.rects[0].y);
    try std.testing.expectEqual(@as(u16, 9), p.rects[s].h);
    // A second level (a preview under a query pane): out of the first's rows.
    const pv = try testAttachment(p);
    try std.testing.expect(attachFrom(p, s, pv, 4, s));
    try std.testing.expectEqual(pv, p.cols[0].panes[2]);
    try std.testing.expectEqual(@as(usize, 0), groupRoot(p, pv));
    try std.testing.expectEqual(@as(usize, 3), groupEnd(p, 0, 0));
    for (unrelated) |k| try std.testing.expectEqualDeep(before[k], p.rects[k]);
    try std.testing.expectEqual(@as(u16, 5), p.rects[s].h);
    // Its text changing never resizes it: nothing here fits it to content.
    const sf = &p.panes[s].?.file.?;
    var many: [2 + 4 * 30]u8 = @splat('\n');
    for (0..30) |i| @memcpy(many[2 + 4 * i ..][0..3], "row");
    many[0] = 'q';
    panes.File.setContent(p, sf, try p.gpa.dupe(u8, &many));
    compute(p);
    try std.testing.expectEqual(@as(u16, 5), p.rects[s].h);

    // An unrelated New, from the owner or from its attachment, never lands
    // inside the group.
    exec.runBuiltin(p, .New, 0, "", null);
    exec.runBuiltin(p, .New, s, "", null);
    var at = findPane(p, 0).?;
    try std.testing.expectEqual(s, p.cols[at.col].panes[at.idx + 1]);
    try std.testing.expectEqual(pv, p.cols[at.col].panes[at.idx + 2]);

    // The seam between owner and attachment is the user's: the pair alone.
    compute(p);
    const pre_drag = p.rects;
    applyRowSplit(p, at.col, at.idx, p.rects[s].y - 3);
    compute(p);
    try std.testing.expectEqual(pre_drag[0].h + pre_drag[s].h, p.rects[0].h + p.rects[s].h);
    for (p.cols[at.col].panes[0..p.cols[at.col].n]) |k| if (k != 0 and k != s) try std.testing.expectEqualDeep(pre_drag[k], p.rects[k]);

    // Collapse folds the group and unfolds it.
    compute(p);
    const open = p.rects;
    exec.runBuiltin(p, .Collapse, 0, "", null);
    try std.testing.expect(p.panes[0].?.collapsed and p.panes[s].?.collapsed and p.panes[pv].?.collapsed);
    exec.runBuiltin(p, .Collapse, 0, "", null);
    try std.testing.expect(!p.panes[0].?.collapsed and !p.panes[s].?.collapsed);
    try std.testing.expectEqual(open[0].h + open[s].h + open[pv].h, p.rects[0].h + p.rects[s].h + p.rects[pv].h);

    // The owner's grip dragged to the other column takes its group along.
    movePane(p, 0, p.col_x[1] + 4, p.rects[other_col].y + p.rects[other_col].h / 2);
    at = findPane(p, 0).?;
    try std.testing.expectEqual(@as(usize, 1), at.col);
    try std.testing.expectEqual(s, p.cols[1].panes[at.idx + 1]);
    try std.testing.expectEqual(pv, p.cols[1].panes[at.idx + 2]);
    try std.testing.expectEqual(@as(?usize, 0), ownerOf(p, s));

    // Del of the preview gives its rows to its owner, the query pane.
    compute(p);
    var pair = p.rects;
    exec.runBuiltin(p, .Del, pv, "", null);
    try std.testing.expect(p.panes[pv] == null);
    compute(p);
    try std.testing.expectEqual(pair[s].h + pair[pv].h, p.rects[s].h);
    // Del of the attachment gives its rows back to the owner, nobody else.
    pair = p.rects;
    exec.runBuiltin(p, .Del, s, "", null);
    try std.testing.expect(p.panes[s] == null);
    compute(p);
    try std.testing.expectEqual(pair[0].h + pair[s].h, p.rects[0].h);
    for (p.cols[1].panes[0..p.cols[1].n]) |k| if (k != 0) try std.testing.expectEqualDeep(pair[k], p.rects[k]);

    // Del of the owner closes what is attached to it.
    const again = try testAttachment(p);
    try std.testing.expect(attachFrom(p, 0, again, 6, 0));
    exec.runBuiltin(p, .Del, 0, "", null);
    try std.testing.expect(p.panes[0] == null and p.panes[again] == null);
}

test "an attachment survives Dump and Restore, and one left away from its owner is a pane of its own" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 });
    defer p.deinit();
    _ = try p.setTestFile("alpha\nbeta\nalphabet\n");
    const s = try testAttachment(p);
    try std.testing.expect(attachFrom(p, 0, s, 8, 0));
    try std.testing.expectEqual(@as(?usize, 0), ownerOf(p, s));
    try dump.dumpState(p);
    const restored = try dump.initFromDump(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }, p.dump_out.?);
    defer restored.deinit();
    try std.testing.expectEqual(@as(?usize, 0), ownerOf(restored, s));
    // Unattach: a pane of its own where it stands.
    pardes.exec.runBuiltin(p, .Unattach, s, "", null);
    try std.testing.expect(p.panes[s].?.attached_to == null);
    // Put above its owner by a route that does not carry groups: detached.
    const t = try testAttachment(p);
    try std.testing.expect(attachFrom(p, 0, t, 8, 0));
    try std.testing.expectEqual(@as(?usize, 0), ownerOf(p, t));
    removePane(p, t);
    insert(p, 0, 0, t);
    compute(p);
    try std.testing.expect(p.panes[t].?.attached_to == null);
}

// ---- the session's columns and the rows its chrome takes ----

/// The workspace tag's height: one row while the setting keeps it, as
/// acme's row tag is, zero once a native shell takes its commands over.
/// Layout and hit testing read this rather than the constant, the way
/// they read `columnBarHeight`.
pub fn topBarHeight(p: *const Pardes) u16 {
    if (!p.settings.workspace_tag) return 0;
    return TOPBAR_H;
}

/// The column tags' height: one row, as acme's (cols.c:244, colresize,
/// gives a column tag one font height); a newline in one is a space
/// (tagline.flattenHeaders).
pub fn columnBarHeight(p: *const Pardes) u16 {
    if (p.screen_h < 3) return 0;
    return COLBAR_H;
}

/// Newcol: an empty column right of the calling pane's, the keyboard
/// on its tag, for the next pane made to fill.
pub fn newColumn(p: *Pardes, from_id: usize) void {
    // An empty window (Delcol took the last column): its first column.
    if (firstColumn(p)) |c| return tagline.enterHeader(p, c);
    const col = keyboardColumn(p, from_id) orelse return;
    // A trial: laying it out gives it a serial (layout.compute), which a
    // refusal takes back. Every other column has its own already, so
    // the counter as it is now is the trial's to return to.
    for (0..p.ncol) |k| _ = columnSerial(p, k);
    const unspent = p.next_column_serial;
    const before_min = minima(p);
    const before = p.rects;
    // Said, not silently nothing: "no space" is 9ns's word for ENOSPC.
    const c = insertColumnUnannounced(p, col, false) orelse {
        var said: [96]u8 = undefined;
        return p.reportFailure(from_id, if (p.ncol >= MAX_COLS)
            std.fmt.bufPrint(&said, "Newcol: no space for a column: {d} max", .{MAX_COLS}) catch "Newcol: no space for a column"
        else
            "Newcol: no space for a column: this one is too narrow to split");
    };
    if (!keepColumn(p, c, &before, &before_min)) {
        p.next_column_serial = unspent;
        compute(p);
        return p.reportFailure(from_id, "Newcol: no space for a column: the panes' tags would not fit");
    }
    // Kept: now it has a serial, and the log hears of it.
    noteColumn(p, "newcol", columnSerial(p, c));
    tagline.enterHeader(p, c);
}

pub fn setActiveColumn(p: *Pardes, c: usize) void {
    if (c < p.ncol) p.active_column = columnSerial(p, c);
}

/// The active column, while it is still there.
pub fn activeColumn(p: *const Pardes) ?usize {
    return columnBySerial(p, p.active_column);
}

pub fn noteTyped(p: *Pardes) void {
    if (p.header != null) {
        if (p.headerColumn()) |c| p.setActiveColumn(c);
    } else if (findPane(p, p.active)) |f| p.setActiveColumn(f.col);
}

/// New, run from column `c`'s tag.
pub fn newScratchIn(p: *Pardes, from_id: usize, c: usize) void {
    p.exec_column = c;
    defer p.exec_column = null;
    p.newScratchBelow(from_id);
}

/// The column a command acts on: the one whose tag it came from, else
/// the one whose tag has the keyboard, else `id`'s.
pub fn keyboardColumn(p: *Pardes, id: usize) ?usize {
    if (p.exec_column) |c| return c;
    if (p.headerColumn()) |c| return c;
    return if (findPane(p, id)) |f| f.col else null;
}

/// Delcol: close column `col` and every pane in it.
pub fn removeColumn(p: *Pardes, col: usize) !void {
    if (col >= p.ncol) return;
    const had_focus = keyboardColumn(p, p.active) == col;
    const beside = if (had_focus) besideColumn(p, col, if (p.header != null) null else p.rects[p.active]) else null;
    var ids: [MAX_PANES]usize = undefined;
    var parents: [MAX_PANES]*Pane = undefined;
    const count = p.cols[col].n;
    for (0..count) |i| {
        ids[i] = p.cols[col].panes[i];
        parents[i] = p.panes[ids[i]].?;
    }
    try panes.detachCwds(p, parents[0..count]);
    for (ids[0..count], parents[0..count]) |closed, pane| {
        // Kept for Panes; its column goes, so it comes back as a new pane.
        if (p.store.keep(p, closed)) |k| p.store.close(p, k, null);
        panes.retirePane(p, pane);
        removePane(p, closed);
        p.panes[closed] = null;
    }
    dropColumn(p, col);
    // The last column gone, the window stays, empty but for the
    // workspace tag, as acme's does; Newcol starts again from there.
    if (p.panes[p.active] == null) p.active = beside orelse panes.anyPane(p) orelse return tagline.enterHeader(p, null);
}

/// The pane that takes over the keyboard from column `col`: in the
/// column layout.dropColumn gives the width to, the one level with the
/// middle of `r` (of the screen without one). Asked while rects hold.
pub fn besideColumn(p: *const Pardes, col: usize, r: ?Rect) ?usize {
    if (p.ncol < 2) return null;
    const next = if (col > 0) col - 1 else col + 1;
    const mid = if (r) |at| at.y + at.h / 2 else p.screen_h / 2;
    var pick: ?usize = null;
    for (p.cols[next].panes[0..p.cols[next].n]) |k| {
        if (p.panes[k] == null) continue;
        pick = k;
        if (p.rects[k].y +| p.rects[k].h > mid) break;
    }
    return pick;
}

/// The rows pane `id`'s tag takes at its width, wrapped as `sync` wraps
/// it: what a placement must leave it above its body rows.
pub fn wantedTagRows(p: *Pardes, id: usize) u16 {
    const pane = p.panes[id] orelse return BOX_H;
    if (pane.collapsed or !pane.tag_expanded) return BOX_H;
    if (p.rects[id].w == 0) return pane.tag_rows; // never laid out
    var wrap_room: [32 * 1024]u8 = undefined;
    var wrap_fba = std.heap.FixedBufferAllocator.init(&wrap_room);
    const wa = wrap_fba.allocator();
    const prefix = tagline.prefixIn(p, wa, pane) catch return pane.tag_rows;
    const whole = std.mem.concat(wa, u8, &.{ prefix, tagline.curTail(pane) }) catch return pane.tag_rows;
    const shown = tagline.wrapTag(wa, whole, tagline.tagWidth(p, id)) catch return pane.tag_rows;
    return @intCast(@max(BOX_H, @min(shown.rows(), MAX_TAG_ROWS)));
}

/// The pane's first body row, under its tag. Notice bands do NOT move it
/// -- they are an overlay, drawn over the top rows rather than taking them.
pub fn bodyTop(_: *const Pardes, pane: *const Pane, r: Rect) u16 {
    return r.y + pane.tag_rows;
}

/// The tag's first row: the pane's top.
pub fn tagTop(_: *const Pardes, _: *const Pane, r: Rect) u16 {
    return r.y;
}

pub fn tagCapacity(p: *const Pardes, physical_width: u16) u16 {
    const layer: Layer = .{ .kind = .pane, .viewport = .{ .x = 0, .y = 0, .w = physical_width, .h = 1 } };
    return layer.capacity(p.row_metrics);
}

// ---- render: build the canonical surface (draw.zig) ----

/// A frontend's tag hit, if what it names is still there: resolved on
/// the place it carries (Layer.Place), not on this process's frame.
pub fn reprojectTagHit(p: *const Pardes, tag_hit: TagHit) ?TagHit {
    if (tag_hit.kind == .pane) {
        if (tag_hit.id >= p.panes.len) return null;
        const pane = p.panes[tag_hit.id] orelse return null;
        if (pane.serial != tag_hit.serial) return null;
    }
    if (tag_hit.kind == .column and (tag_hit.id >= p.ncol or p.cols[tag_hit.id].serial != tag_hit.serial)) return null;
    return Layer.tagAgain(tag_hit);
}

test "a new column takes width only from the column that created it" {
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 124, .rows = 24 });
    defer p.deinit();

    _ = try p.newShell(1, "");
    try std.testing.expect(splitColumn(p, 0, 1, false));
    _ = try p.newShell(2, "");
    try std.testing.expect(splitColumn(p, 0, 2, true));
    p.sync();

    const left_before = p.rects[2];
    const right_before = p.rects[1];
    _ = try p.newShell(3, "");
    try std.testing.expect(splitColumn(p, 0, 3, false));
    p.sync();

    try std.testing.expectEqual(left_before.x, p.rects[2].x);
    try std.testing.expectEqual(left_before.w, p.rects[2].w);
    try std.testing.expectEqual(right_before.x, p.rects[1].x);
    try std.testing.expectEqual(right_before.w, p.rects[1].w);
    try std.testing.expectEqual(@as(u16, 16), p.rects[0].w);
    try std.testing.expectEqual(@as(u16, 15), p.rects[3].w);

    const narrow = try Pardes.init(std.testing.allocator, .{ .cols = config.MINW * 2 - 1, .rows = 10 });
    defer narrow.deinit();
    try std.testing.expect(!splitColumn(narrow, 0, 1, false));
    try std.testing.expectEqual(@as(usize, 1), narrow.ncol);

    const sequential = try Pardes.init(std.testing.allocator, .{ .cols = config.MINW * 2, .rows = 10 });
    defer sequential.deinit();
    _ = try sequential.newShell(1, "");
    try std.testing.expect(splitColumn(sequential, 0, 1, false));
    _ = try sequential.newShell(2, "");
    try std.testing.expect(!splitColumn(sequential, 0, 2, false));
    try std.testing.expectEqual(@as(usize, 2), sequential.ncol);

    const coarse = try Pardes.init(std.testing.allocator, .{ .cols = 22, .rows = 10 });
    defer coarse.deinit();
    coarse.cols[0].weight = 3;
    _ = try coarse.newShell(1, "");
    try std.testing.expect(splitColumn(coarse, 0, 1, false));
    coarse.sync();
    try std.testing.expectEqual(@as(u16, 11), coarse.col_w[0]);
    try std.testing.expectEqual(@as(u16, 11), coarse.col_w[1]);

    const extreme = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 20 });
    defer extreme.deinit();
    _ = try extreme.newShell(1, "");
    try std.testing.expect(splitColumn(extreme, 0, 1, false));
    _ = try extreme.newShell(2, "");
    insert(extreme, 0, 1, 2);
    extreme.cols[0].weight = std.math.maxInt(u64) / 2 + 2; // odd and cannot double
    extreme.cols[1].weight = 1;
    compute(extreme);
    const cols_before = extreme.cols;
    const source_vweight = extreme.panes[0].?.vweight;
    const sibling_vweight = extreme.panes[2].?.vweight;
    try std.testing.expect(!splitColumn(extreme, 0, 0, false));
    try std.testing.expectEqual(cols_before, extreme.cols);
    try std.testing.expectEqual(source_vweight, extreme.panes[0].?.vweight);
    try std.testing.expectEqual(sibling_vweight, extreme.panes[2].?.vweight);
}

test "Newcol refuses an unsplittable restored weight before spawning" {
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 200, .rows = 20 });
    defer p.deinit();

    for (1..4) |id| {
        _ = try p.newShell(id, "");
        try std.testing.expect(splitColumn(p, id - 1, id, false));
    }
    const restored_cap = std.math.maxInt(u64) / 6;
    for (0..4) |column| p.cols[column].weight = restored_cap;
    p.cols[3].weight -= 1;
    for ([_]usize{ 3, 2, 1 }) |id| {
        const pane = p.panes[id].?;
        try panes.deinitPane(p, pane);
        removePane(p, id);
        dropColumn(p, id);
        p.panes[id] = null;
    }
    while (p.nextEffect()) |_| {}

    try std.testing.expect(p.cols[0].weight > std.math.maxInt(u64) / 2);
    try std.testing.expect(p.cols[0].weight % 2 == 1);
    try std.testing.expect(!canSplitCol(p, findPane(p, 0).?.col));
    const panes_before = p.panes;
    const serial_before = p.next_serial;
    try std.testing.expect(p.executeBuiltinLine(0, "Newcol"));
    try std.testing.expectEqual(panes_before, p.panes);
    try std.testing.expectEqual(serial_before, p.next_serial);
    try std.testing.expect(p.nextEffect() == null);
}

test "repeated non-dyadic column splits preserve every unrelated boundary" {
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 979, .rows = 20 });
    defer p.deinit();

    _ = try p.newShell(1, "");
    try std.testing.expect(splitColumn(p, 0, 1, false));
    p.sync();

    const handle = p.col_x[0] + p.col_w[0] - 1;
    const untouched = weightsOf(p);
    p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = TOPBAR_H + 1 } });
    p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = TOPBAR_H + 1 } });
    try std.testing.expectEqual(untouched, weightsOf(p));

    p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = TOPBAR_H + 1 } });
    p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = 417, .row = TOPBAR_H + 1 } });
    p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 417, .row = TOPBAR_H + 1 } });
    p.sync();
    try std.testing.expectEqual(@as(u16, 418), p.rects[0].w);

    _ = try p.newShell(2, "");
    try std.testing.expect(splitColumn(p, 1, 2, false));
    p.sync();
    const left_before = p.rects[0];
    const middle_before = p.rects[1];

    _ = try p.newShell(3, "");
    try std.testing.expect(splitColumn(p, 2, 3, false));
    p.sync();
    try std.testing.expectEqual(left_before, p.rects[0]);
    try std.testing.expectEqual(middle_before, p.rects[1]);
}

test "dragging a column's only pane to another leaves that column in place, empty" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 32 });
    defer p.deinit();
    newColumn(p, 0);
    newScratchIn(p, 0, activeColumn(p).?);
    const moved = p.active;
    p.sync();
    const weights = weightsOf(p);
    const tag_serial = p.cols[1].serial;
    movePane(p, moved, p.col_x[0] + 4, p.rects[0].y + p.rects[0].h / 2);
    p.sync();
    // acme's coldragwin: colclose then coladd (cols.c:516-517); the column
    // left behind keeps its place, width and tag.
    try std.testing.expectEqual(@as(usize, 2), p.ncol);
    try std.testing.expectEqual(@as(usize, 0), p.cols[1].n);
    try std.testing.expectEqual(tag_serial, p.cols[1].serial);
    try std.testing.expectEqualDeep(weights, weightsOf(p));
    try std.testing.expectEqual(@as(usize, 2), p.cols[0].n);
    // ...and a pane dragged into the empty column takes it whole.
    movePane(p, moved, p.col_x[1] + 4, p.screen_h / 2);
    p.sync();
    try std.testing.expectEqualSlices(usize, &.{moved}, p.cols[1].panes[0..p.cols[1].n]);
    try std.testing.expectEqual(@as(usize, 1), p.cols[0].n);
}

test "tiny screens keep pane space before adding a column tag" {
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 8, .rows = 2, .tty_only = true });
    defer p.deinit();
    try std.testing.expectEqual(@as(u16, 0), columnBarHeight(p));
    try std.testing.expectEqual(TOPBAR_H, p.rects[0].y);
    _ = try p.render(p.scratch.allocator());
}

/// Each column's weight, as a test compares them.
fn weightsOf(p: *const Pardes) [MAX_COLS]u64 {
    var out: [MAX_COLS]u64 = undefined;
    for (&out, p.cols) |*w, c| w.* = c.weight;
    return out;
}