summaryrefslogtreecommitdiff
path: root/src/layout.zig
blob: cbf0fd960cac568e96b8655c82b7060d6977a9bb (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
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 animation = @import("animation.zig");
const Box = animation.Box;
const Pardes = pardes.Pardes;
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,
};

/// Move the keyboard to the nearest pane in `dir`; false when there is none.
pub fn focusDir(p: *Pardes, from: usize, dir: enum { left, right, up, down }) bool {
    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;
        }
    }
    const b = best 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;
}

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

pub fn columnBySerial(p: *const Pardes, serial: u32) ?usize {
    if (serial == 0) return null;
    for (0..p.ncol) |column| if (p.col_serial[column] == 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.col_weight[left] + p.col_weight[left + 1];
    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.col_weight[left] = share;
    p.col_weight[left + 1] = 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 ids = p.col_panes[from];
    const count = p.col_n[from];
    const weight = p.col_weight[from];
    const tag = p.col_tags[from];
    const serial = p.col_serial[from];
    var at = from;
    while (at != to) {
        const next = if (at < to) at + 1 else at - 1;
        p.col_panes[at] = p.col_panes[next];
        p.col_n[at] = p.col_n[next];
        p.col_weight[at] = p.col_weight[next];
        p.col_tags[at] = p.col_tags[next];
        p.col_serial[at] = p.col_serial[next];
        at = next;
    }
    p.col_panes[to] = ids;
    p.col_n[to] = count;
    p.col_weight[to] = weight;
    p.col_tags[to] = tag;
    p.col_serial[to] = serial;
    if (p.header_column) |column| {
        if (column == from) p.header_column = to else if (from < to and column > from and column <= to) {
            p.header_column = column - 1;
        } else if (from > to and column >= to and column < from) p.header_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;
}

pub fn splitRowForExtent(y: u16, h: u16, cur_y: u16) ?u16 {
    return splitRowFor(y, h, cur_y, null);
}

/// As `splitRowForExtent`, each pane keeping at least `least` rows 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);
}

pub fn movePlacement(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) ?MovePlacement {
    const src = findPane(p, id) orelse return null;
    const tc = targetColumn(p, cur_x);
    if (tc == src.col and p.col_n[src.col] == 1) return null;
    if (tc == src.col) {
        const sr = p.rects[id];
        // 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 >= sr.y and cur_y < sr.y + sr.h and (src.idx == 0 or cur_y <= sr.y)) return null;
    }
    var heights: [MAX_PANES]u16 = @splat(0);
    for (0..p.ncol) |c| {
        for (0..p.col_n[c]) |k| {
            const pid = p.col_panes[c][k];
            heights[pid] = p.rects[pid].h;
        }
    }
    if (p.col_n[src.col] > 1) {
        const sib = if (src.idx > 0) p.col_panes[src.col][src.idx - 1] else p.col_panes[src.col][src.idx + 1];
        heights[sib] +|= p.rects[id].h;
    }
    var y: u16 = p.topBarHeight() + p.columnBarHeight();
    if (p.col_n[tc] == 0) return .{ .preview_col = tc, .above_id = null, .row = y, .above_y = y, .above_h = 0 };
    var last: ?MovePlacement = null;
    for (0..p.col_n[tc]) |k| {
        const pid = p.col_panes[tc][k];
        if (pid == id) continue;
        const h = heights[pid];
        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 = pid,
            .row = row,
            .above_y = y,
            .above_h = h,
        };
        last = placement;
        if (cur_y < y + h) return placement;
        y +|= h;
    }
    return last;
}

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 source_multi = p.col_n[src.col] > 1;
    var heights: [MAX_PANES]u16 = @splat(0);
    for (0..p.ncol) |c| {
        for (0..p.col_n[c]) |k| {
            const pid = p.col_panes[c][k];
            heights[pid] = p.rects[pid].h;
        }
    }
    removePane(p, id);
    if (source_multi) {
        const sib = if (src.idx > 0) p.col_panes[src.col][src.idx - 1] else p.col_panes[src.col][src.idx];
        heights[sib] +|= p.rects[id].h;
    }
    const above = placement.above_id orelse {
        insert(p, placement.preview_col, 0, id);
        if (source_multi) setColumnWeights(p, src.col, &heights);
        return;
    };
    const af = findPane(p, above) orelse return;
    const upper_h = @max(1, placement.row -| placement.above_y);
    const lower_h = @max(1, placement.above_h -| upper_h);
    heights[above] = upper_h;
    heights[id] = lower_h;
    insert(p, af.col, af.idx + 1, id);
    setColumnWeights(p, af.col, &heights);
    if (source_multi and src.col != af.col) setColumnWeights(p, src.col, &heights);
}

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

pub fn applyRowSplit(p: *Pardes, cc: usize, k: usize, cur_y: u16) void {
    if (k + 1 >= p.col_n[cc]) return;
    const a = p.panes[p.col_panes[cc][k]] orelse return;
    const b = p.panes[p.col_panes[cc][k + 1]] orelse return;
    const ra = p.rects[p.col_panes[cc][k]];
    const rb = p.rects[p.col_panes[cc][k + 1]];
    const combined: f32 = @floatFromInt(ra.h + rb.h);
    var nt: f32 = @floatFromInt(if (p.settings.tag_bottom) cur_y -| ra.y else (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.col_panes[cc][k])));
    const hi = combined - @as(f32, @floatFromInt(@max(BOX_H, floorRows(p, p.col_panes[cc][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.col_n[c]) |k| {
            if (p.col_panes[c][k] == id) return .{ .col = c, .idx = k };
        }
    }
    return null;
}

pub fn insert(p: *Pardes, c: usize, idx: usize, id: usize) void {
    var k = p.col_n[c];
    while (k > idx) : (k -= 1) p.col_panes[c][k] = p.col_panes[c][k - 1];
    p.col_panes[c][idx] = id;
    p.col_n[c] += 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.col_n[c]) : (k += 1) p.col_panes[c][k] = p.col_panes[c][k + 1];
    p.col_n[c] -= 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 {
    std.debug.assert(p.col_n[c] == 0);
    const serial = columnSerial(p, c);
    tagline.exitHeader(p);
    if (p.ncol > 1) p.col_weight[if (c > 0) c - 1 else c + 1] +|= p.col_weight[c];
    p.col_tags[c].deinit(p.gpa);
    var j = c;
    while (j + 1 < p.ncol) : (j += 1) {
        p.col_panes[j] = p.col_panes[j + 1];
        p.col_n[j] = p.col_n[j + 1];
        p.col_weight[j] = p.col_weight[j + 1];
        p.col_tags[j] = p.col_tags[j + 1];
        p.col_serial[j] = p.col_serial[j + 1];
    }
    p.ncol -= 1;
    p.col_tags[p.ncol] = .{ .what = .column, .gpa = p.gpa };
    p.col_serial[p.ncol] = 0;
    noteColumn(p, "delcol", serial);
}

/// `newcol <serial>` or `delcol <serial>` in the log: the column's serial,
/// as /layout and /col name it.
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;
    for (0..p.col_n[c]) |k| p.col_panes[dst][p.col_n[dst] + k] = p.col_panes[c][k];
    p.col_n[dst] += p.col_n[c];
    p.col_n[c] = 0;
    // The width goes right, where the panes went.
    p.col_weight[dst] +|= p.col_weight[c];
    p.col_weight[c] = 0;
    dropColumn(p, c);
}

/// 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.col_n[c];
    if (n == 0) {
        insert(p, c, 0, id);
        p.panes[id].?.vweight = 1;
        return;
    }
    var big: ?usize = null;
    var empty: ?usize = null;
    for (p.col_panes[c][0..n]) |k| {
        const pane = p.panes[k] orelse continue;
        if (pane.collapsed) 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.col_panes[c][0..n]) |k| if (!p.panes[k].?.collapsed) {
                last = k;
            };
            break :y bodyTop(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 bodyTop(p, e) + bodyRows(p, e) - el;
        const mine = if (findPane(p, o)) |f| f.col == c and !p.panes[o].?.collapsed else false;
        const v = if (mine and @as(u32, p.rects[o].h) * 3 > @as(u32, p.rects[v0].h) * 2) o 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;

fn minRows(p: *Pardes, id: usize) u16 {
    return p.wantedTagRows(id) + min_body_rows;
}

/// 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.col_n[f.col] == 1) return true;
    for (p.col_panes[f.col][0..p.col_n[f.col]]) |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;
}

/// Whether every unfolded pane sharing its column has its tag and
/// `min_body_rows` (one alone in its column always fits).
pub fn everyPaneRoomy(p: *Pardes) bool {
    compute(p);
    for (0..p.ncol) |c| {
        if (p.col_n[c] < 2) continue;
        for (p.col_panes[c][0..p.col_n[c]]) |k| {
            const pane = p.panes[k] orelse continue;
            if (!pane.collapsed and 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.col_panes[c][0..p.col_n[c]]) |k| {
        if (k == id or p.panes[k].?.collapsed) 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.col_n[c], 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`.
fn splitAt(p: *Pardes, c: usize, id: usize, y: u16) void {
    const n = p.col_n[c];
    var k: usize = 0;
    while (k + 1 < n and y >= p.rects[p.col_panes[c][k]].y + p.rects[p.col_panes[c][k]].h) k += 1;
    const v = p.col_panes[c][k];
    const r = p.rects[v];
    snapColWeights(p, c);
    insert(p, c, k + 1, 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 = splitRowForExtent(r.y, r.h, if (lo <= hi) std.math.clamp(y, lo, hi) else r.y + r.h / 2) 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));
}

fn bodyTop(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)));
}

pub fn canSplitColumn(p: *Pardes, source_id: usize) bool {
    if (source_id >= MAX_PANES or p.panes[source_id] == null) return false;
    const source = findPane(p, source_id) orelse return false;
    return canSplitCol(p, source.col);
}

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.col_weight[col];
    if (weight >= 2 and weight % 2 == 0) return true;
    for (0..p.ncol) |column| if (p.col_weight[column] > 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.
pub fn insertColumn(p: *Pardes, col: usize, before: bool) ?usize {
    if (!canSplitCol(p, col)) return null;
    var old_weight = p.col_weight[col];
    if (old_weight < 2 or old_weight % 2 != 0) {
        old_weight *= 2;
        for (0..p.ncol) |column| p.col_weight[column] *= 2;
    }
    const source_weight = old_weight / 2;
    p.col_weight[col] = source_weight;
    const c = col + @intFromBool(!before);
    tagline.exitHeader(p);
    var j = p.ncol;
    while (j > c) : (j -= 1) {
        p.col_panes[j] = p.col_panes[j - 1];
        p.col_n[j] = p.col_n[j - 1];
        p.col_weight[j] = p.col_weight[j - 1];
        p.col_tags[j] = p.col_tags[j - 1];
        p.col_serial[j] = p.col_serial[j - 1];
    }
    p.col_weight[c] = old_weight - source_weight;
    p.col_tags[c] = .{ .what = .column, .gpa = p.gpa };
    p.col_serial[c] = 0;
    p.col_n[c] = 0;
    p.ncol += 1;
    noteColumn(p, "newcol", columnSerial(p, c));
    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 (!canSplitColumn(p, source_id)) return false;
    const source = findPane(p, source_id) orelse return false;
    if (id == source_id) {
        if (p.col_n[source.col] <= 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.col_n[c]) |k| {
        const pid = p.col_panes[c][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.col_n[f.col] <= 1) return null;
    snapColWeights(p, f.col);
    var sib = to orelse if (f.idx > 0) p.col_panes[f.col][f.idx - 1] else p.col_panes[f.col][f.idx + 1];
    var k = f.idx;
    while (to == null and k > 0) : (k -= 1) {
        sib = p.col_panes[f.col][k - 1];
        if (p.panes[sib]) |pp| if (if (pp.file) |ff| panes.Output.fileTraits(ff.output).doc else true) break;
    }
    const s = p.panes[sib] orelse return null;
    s.vweight += @as(f32, @floatFromInt(@max(1, p.rects[id].h)));
    return sib;
}

pub fn splitParent(p: *Pardes, want: usize) usize {
    const need = 2 * (BOX_H + min_body_rows);
    if (p.rects[want].h >= need) return want;
    if (findPane(p, want)) |f| for (0..p.col_n[f.col]) |k| {
        if (p.rects[p.col_panes[f.col][k]].h >= need) return p.col_panes[f.col][k];
    };
    var tallest = want;
    for (0..p.ncol) |c| for (0..p.col_n[c]) |k| {
        const pid = p.col_panes[c][k];
        if (p.rects[pid].h >= need) return pid;
        if (p.rects[pid].h > p.rects[tallest].h) tallest = pid;
    };
    return tallest;
}

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)));
    if (findPane(p, src_id)) |f| for (0..p.col_n[f.col]) |k| {
        const pid = p.col_panes[f.col][k];
        if (p.panes[pid]) |pp| if (pp != nw and !pp.collapsed) {
            pp.vweight = @floatFromInt(@max(1, p.rects[pid].h));
        };
    };
    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;
        }
    };
}

pub fn columnFitsHalves(p: *Pardes, source_id: usize, min_cells: u16) bool {
    const f = findPane(p, source_id) orelse return false;
    compute(p);
    return p.col_w[f.col] >= min_cells * 2;
}

pub fn panelBox(rect: Rect) Box {
    return .{
        .x = @floatFromInt(rect.x),
        .y = @floatFromInt(rect.y),
        .w = @floatFromInt(rect.w),
        .h = @floatFromInt(rect.h),
    };
}

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);
    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.col_n[col]) {
        k = if (side == .above) k - 1 else k + 1;
        const id = p.col_panes[col][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() + p.columnBarHeight();
    const available = p.screen_h -| y;
    var expanded_left: usize = 0;
    var weight: f32 = 0;
    for (p.col_panes[c][0..p.col_n[c]]) |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.col_panes[c][0..p.col_n[c]]) |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;
    for (0..p.ncol) |column| _ = columnSerial(p, column);
    var wsum: u128 = 0;
    for (0..p.ncol) |c| wsum += p.col_weight[c];
    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 last = c + 1 == p.ncol;
        const x = columnBoundary(p.screen_w, prefix, wsum);
        prefix += p.col_weight[c];
        const end: u16 = if (last)
            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.col_panes[c][0..p.col_n[c]]) |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.col_n[c]) |k| {
            if (p.panes[p.col_panes[c][k]]) |pane| vsum += pane.vweight;
        }
        if (vsum <= 0) vsum = 1;

        var y: u16 = p.topBarHeight() + p.columnBarHeight();
        const top = y;
        const avail_h = p.screen_h -| y;
        var hs: [MAX_PANES]u16 = undefined;
        const n = p.col_n[c];
        for (0..n) |k| {
            const id = p.col_panes[c][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.col_panes[c][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.col_panes[c][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.col_panes[c][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);
        p.settings.tag_bottom = step % 3 == 0;
        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.col_panes[0][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 and TagBottom" {
    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 ([_]bool{ false, true }) |bottom| {
        p.settings.tag_bottom = bottom;
        {
            for (0..50) |height| {
                p.screen_h = @intCast(height);
                compute(p);
                var used: u16 = 0;
                for (p.col_panes[0][0..p.col_n[0]]) |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);
    p.settings.tag_bottom = true;
    applyRowSplit(p, 0, 0, p.rects[1].y - 5);
    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;
    p.col_n = @splat(0);
    for (0..4) |c| {
        p.col_weight[c] = c * 13 + 7;
        p.col_serial[c] = @intCast(c + 10);
        p.col_panes[c][0] = c;
        p.col_tags[c].cur_col = @intCast(c + 20);
    }
    compute(p);
    const original_weights = p.col_weight;
    const outer_x = p.col_x[0];
    const outer_w = p.col_w[0];
    p.header_focus = true;
    p.header_column = 1;
    p.header_scroll = 9;
    reorderColumn(p, 1, 3);
    try std.testing.expectEqual(original_weights[1], p.col_weight[3]);
    try std.testing.expectEqual(original_weights[2], p.col_weight[1]);
    try std.testing.expectEqual(@as(u32, 11), p.col_serial[3]);
    try std.testing.expectEqual(@as(?usize, 3), p.header_column);
    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], p.col_weight[0..4]);
    try std.testing.expectEqual(@as(i32, 21), p.col_tags[1].cur_col);
}