summaryrefslogtreecommitdiff
path: root/src/views.zig
blob: 953b39a42ac1ed9483a850f50fc6ae06693bafb8 (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
//! Views: several clients on one session, kakoune's way (docs/next-daemon.md,
//! "Phase 4 notes"). Each view has its own layout, focus, selections and
//! scroll over the panes every view shares: their text, terminals, tags,
//! registers and messages.
//!
//! A view's share of the session is `Pardes.View`, one of `Pardes.views`,
//! and the live one is `views[view]` (`Pardes.view()`): going into another
//! is an index. Each view's share of a pane (`PaneView`) is still swapped:
//! the live view's is in the pane's own fields, the others' in `Pane.pv`
//! (copied out when another view goes live, `park`, and back, `unpark`),
//! so the ~3,000 references to a pane's cursor, mode, scroll and geometry
//! read it as they always did. A pane closing leaves every view's layout
//! at once (`gone`).
//!
//! The views are in the digest; the panes' shares of the views not live
//! (Pane's `pv`) are not: a pane's slot is written whenever its view goes
//! out, so the live view's is stale by design, and a share that diverged
//! shows when its view is live again. A view drawn out of turn (`drawOne`,
//! `within`) is put back after exactly as it was.
const std = @import("std");
const pardes = @import("pardes.zig");
const Pardes = pardes.Pardes;
const View = Pardes.View;
const Pane = pardes.Pane;
const Text = pardes.panes.Text;
const File = pardes.panes.File;
const layout = pardes.layout;
const MAX_PANES = pardes.MAX_PANES;

/// Views at once: a window or terminal each.
pub const max = 4;

/// A pane's fields that are each view's own: where it is in the view's
/// layout, which of its texts has the keyboard, how far it is scrolled, and
/// what the view's step measured of it (its tag's rows, its bands).
const pane_fields = [_][:0]const u8{ "focus", "vweight", "collapsed", "attached_to", "hscroll", "tag_scroll", "tag_top", "tag_rows", "view", "notices", "pan", "follow_scroll" };

/// The body's: its cursor, selections and mode. Its undo stays the pane's.
const body_fields = [_][:0]const u8{ "mode", "cur_pinned", "cur_row", "cur_col", "vsel", "sels", "nsel", "select", "sticky_col", "restore_cursor", "last_edit", "reg_wait", "normal", "find_op", "find_ch" };

/// Named field by field, not taken from Pane's type: a pane holds its own.
pub const PaneView = struct {
    focus: Pane.Focus = .body,
    vweight: f32 = 1,
    collapsed: bool = false,
    attached_to: ?u32 = null,
    hscroll: i32 = 0,
    tag_scroll: u16 = 0,
    tag_top: u16 = 0,
    tag_rows: u16 = 1,
    view: Pane.SessionView = .{},
    notices: Pane.Notices = .{},
    pan: u16 = 0,
    follow_scroll: usize = 0,
    body: Part(Text, &body_fields) = .{},
    /// A document's scroll and size; a terminal's size is its pty's, which
    /// every view shows (sized by its last typist, `Pardes.sync`).
    scroll: usize = 0,
    cols: u16 = 1,
    rows: u16 = 1,

    /// In a dump (`Shares`): what a pane's step works out again. Its `view`
    /// is dumped: the step after `unpark` reads it before it syncs.
    pub const replica = .{ .derived = .{ "notices", "pan" } };
};

/// The panes' shares of a view not live, as a session's dump keeps them
/// (dump.zig): the live view's are the panes' own fields.
pub const Shares = struct {
    k: u8,
    panes: []const Share = &.{},

    pub const Share = struct { id: u16, pv: PaneView };
};

/// A view not live as a dump before `Pardes.views` kept it: its share of
/// the session beside its panes' (read once, by name, into `views[k]`).
pub const OldDumped = struct {
    k: u8,
    view: View = .{},
    panes: []const Shares.Share = &.{},
};

fn bit(k: usize) u8 {
    return @as(u8, 1) << @intCast(k);
}

/// The panes' shares of the views not live, as a dump keeps them: the
/// slices `gpa`'s, what they hold the session's.
pub fn dumped(p: *const Pardes, gpa: std.mem.Allocator) ![]Shares {
    var out: std.ArrayList(Shares) = .empty;
    errdefer {
        for (out.items) |d| gpa.free(d.panes);
        out.deinit(gpa);
    }
    for (0..max) |k| {
        if (k == p.live or !isOpen(p, @intCast(k))) continue;
        var shares: std.ArrayList(Shares.Share) = .empty;
        errdefer shares.deinit(gpa);
        // A view not live has a share of every pane: written when it went
        // out, made with one made since (`installed`).
        for (p.panes, 0..) |s, id| if (s) |pane| {
            try shares.append(gpa, .{ .id = @intCast(id), .pv = pane.pv[k] });
        };
        try out.append(gpa, .{ .k = @intCast(k), .panes = try shares.toOwnedSlice(gpa) });
    }
    return out.toOwnedSlice(gpa);
}

/// The panes' shares a dump kept (`dumped`) parked again in `p`, a
/// session just loaded with its views: each pane its share in each view
/// (one a view had none of as the live view has it). What they hold is
/// the session's then, the slices the caller's. A view the core says open
/// that the dump has no shares of is not.
pub fn undumped(p: *Pardes, others: []const Shares) void {
    var take: u8 = 0;
    for (others) |d| if (d.k < max and d.k != p.live and isOpen(p, d.k) and take & bit(d.k) == 0) {
        take |= bit(d.k);
    };
    for (0..max) |k| if (k != p.live and isOpen(p, @intCast(k)) and take & bit(k) == 0) dropView(p, @intCast(k));
    p.views_open &= take | bit(p.live);
    p.views_away &= p.views_open;
    // The live view's slot owning nothing, as `installed` makes it.
    for (p.panes) |s| if (s) |pane| {
        if (take != 0) pane.pv[p.live] = fresh(pane);
        pane.pv_known |= bit(p.live);
    };
    var left = take;
    for (others) |d| {
        if (left & bit(d.k) == 0) {
            // Refused (another build's, or twice): what it holds goes.
            for (d.panes) |sh| if (sh.pv.body.sels.len > 0) p.gpa.free(sh.pv.body.sels);
            continue;
        }
        left &= ~bit(d.k);
        for (d.panes) |sh| {
            const pane = (if (sh.id < MAX_PANES) p.panes[sh.id] else null) orelse {
                if (sh.pv.body.sels.len > 0) p.gpa.free(sh.pv.body.sels);
                continue;
            };
            if (pane.pv_known & bit(d.k) != 0) {
                if (sh.pv.body.sels.len > 0) p.gpa.free(sh.pv.body.sels);
                continue;
            }
            pane.pv[d.k] = sh.pv;
            pane.pv_known |= bit(d.k);
        }
        for (p.panes) |s| if (s) |pane| if (pane.pv_known & bit(d.k) == 0) {
            pane.pv[d.k] = fresh(pane);
            pane.pv_known |= bit(d.k);
        };
    }
}

/// The views a dump before `Pardes.views` kept (`OldDumped`): each its
/// share of the session into `views[k]`, the rest as `undumped`. What
/// each view holds is the session's then; one refused is freed.
pub fn undumpedOld(p: *Pardes, others: []const OldDumped, gpa: std.mem.Allocator) !void {
    var shares: std.ArrayList(Shares) = .empty;
    defer shares.deinit(gpa);
    var took: u8 = 0;
    for (others) |d| {
        var view = d.view;
        if (d.k >= max or d.k == p.live or !isOpen(p, d.k) or took & bit(d.k) != 0) {
            freeView(p, &view);
            continue;
        }
        took |= bit(d.k);
        p.views[d.k] = view;
        try shares.append(gpa, .{ .k = d.k, .panes = d.panes });
    }
    undumped(p, shares.items);
}

/// The live view alone, as view 0: every other closed. A session loaded
/// for one client (a Restore, `-l`) is one view.
pub fn only(p: *Pardes) void {
    p.views_away = 0;
    for (0..max) |k| if (k != p.live) close(p, @intCast(k));
    const k = p.live;
    if (k == 0) return;
    std.mem.swap(?View, &p.views[0], &p.views[k]);
    for (p.panes) |s| if (s) |pane| {
        // The live slot is stale: as `installed` makes it, owning nothing.
        pane.pv[0] = fresh(pane);
        pane.pv_known = if (pane.pv_known & bit(k) != 0) 1 else 0;
        if (pane.sized_by == k) pane.sized_by = 0;
        if (pane.prompt_view == k) pane.prompt_view = 0;
    };
    p.live = 0;
    p.views_open = 1;
}

/// The fields of `T` named, as a struct of their own, each of its type and
/// default.
fn Part(comptime T: type, comptime names: []const [:0]const u8) type {
    @setEvalBranchQuota(100_000);
    const s = @typeInfo(T).@"struct";
    var types: [names.len]type = undefined;
    var attrs: [names.len]std.lang.Type.Struct.FieldAttributes = undefined;
    for (names, 0..) |name, i| {
        const at = for (s.field_names, 0..) |n, j| {
            if (std.mem.eql(u8, n, name)) break j;
        } else @compileError("views: " ++ @typeName(T) ++ " has no field " ++ name);
        types[i] = s.field_types[at];
        attrs[i] = .{ .default_value_ptr = s.field_attrs[at].default_value_ptr };
    }
    return @Struct(.auto, null, names, &types, &attrs);
}

fn copy(comptime names: []const [:0]const u8, dst: anytype, src: anytype) void {
    inline for (names) |name| @field(dst, name) = @field(src, name);
}

pub fn isOpen(p: *const Pardes, k: u8) bool {
    return k < max and p.views_open & (@as(u8, 1) << @intCast(k)) != 0;
}

/// Kept for its client's rejoin (`away`).
pub fn isAway(p: *const Pardes, k: u8) bool {
    return k < max and p.views_away & (@as(u8, 1) << @intCast(k)) != 0;
}

/// The views someone looks at: open, none kept for a rejoin.
pub fn count(p: *const Pardes) usize {
    return @popCount(p.views_open & ~p.views_away);
}

/// An open view but `k` someone looks at (`count`), if there is one.
fn looked(p: *const Pardes, k: u8) ?u8 {
    for (0..max) |i| if (i != k and isOpen(p, @intCast(i)) and !isAway(p, @intCast(i))) return @intCast(i);
    return null;
}

/// More than one view: the one test the single client's path pays.
pub fn several(p: *const Pardes) bool {
    return p.views_open & (p.views_open -% 1) != 0;
}

/// Pane `pane`'s share of the live view.
fn extract(pane: *const Pane) PaneView {
    var v: PaneView = .{ .cols = pane.cols, .rows = pane.rows };
    copy(&pane_fields, &v, pane);
    copy(&body_fields, &v.body, &pane.body);
    if (pane.file) |f| v.scroll = f.scroll;
    return v;
}

/// Its share of view `v` put back.
fn apply(pane: *Pane, v: *const PaneView) void {
    copy(&pane_fields, pane, v);
    copy(&body_fields, &pane.body, &v.body);
    if (!pane.isTerminal()) {
        pane.cols = v.cols;
        pane.rows = v.rows;
    }
    const f = if (pane.file) |*file| file else return;
    // The text may have changed while the view was out: what it held is
    // brought back inside it.
    const lines = File.nlines(pane.gpa, f);
    f.scroll = @min(v.scroll, lines -| 1);
    if (pane.body.cur_row >= lines) {
        pane.body.vsel.active = false;
        pane.body.nsel = 0;
    }
    _ = pardes.edit.clampFileCursor(&pane.body);
}

/// A copy of the live view's share for another view, owning nothing of the
/// live one's (its extra selections stay behind).
fn fresh(pane: *const Pane) PaneView {
    var v = extract(pane);
    v.body.sels = &.{};
    v.body.nsel = 0;
    return v;
}

/// A new pane is in each other view as it was made, there to be shown.
pub fn installed(p: *Pardes, pane: *Pane) void {
    pane.sized_by = p.live;
    if (!several(p)) return;
    // The live view's slot too, owning nothing: a pane closed before its
    // view next parks is torn down with that slot never written, and
    // `tornDown` frees what the slots of the views not live hold.
    for (0..max) |k| if (isOpen(p, @intCast(k))) {
        pane.pv[k] = fresh(pane);
    };
    pane.pv_known = p.views_open;
}

/// A pane going: the other views' selections of it go too.
pub fn tornDown(p: *Pardes, pane: *Pane) void {
    for (0..max) |k| if (k != p.live and pane.pv_known & (@as(u8, 1) << @intCast(k)) != 0) {
        const sels = pane.pv[k].body.sels;
        if (sels.len > 0) p.gpa.free(sels);
        pane.pv[k].body.sels = &.{};
    };
}

/// Pane `id` closed: it leaves the layout of every view not live, and the
/// keyboard of one it had moves to that view's first pane left (the live
/// view's is the closing's to move, panes.removePane).
pub fn gone(p: *Pardes, id: usize) void {
    if (!several(p)) return;
    for (&p.views, 0..) |*slot, k| {
        if (k == p.live) continue;
        const v = &(slot.* orelse continue);
        for (v.cols[0..v.ncol]) |*col| {
            var n: usize = 0;
            for (col.panes[0..col.n]) |other| if (other != id) {
                col.panes[n] = other;
                n += 1;
            };
            col.n = n;
        }
        if (v.active != id) continue;
        v.active = for (v.cols[0..v.ncol]) |col| {
            if (col.n > 0) break col.panes[0];
        } else for (p.panes, 0..) |s, i| {
            if (s != null and i != id) break i;
        } else 0;
    }
}

fn park(p: *Pardes) void {
    for (p.panes) |s| if (s) |pane| {
        pane.pv[p.live] = extract(pane);
    };
}

fn unpark(p: *Pardes, k: u8) void {
    p.live = k;
    for (p.panes) |s| if (s) |pane| {
        apply(pane, &pane.pv[k]);
        // The live body owns the selections now; the slot, stale while its
        // view is live, holds none (a pane closed before the view parks
        // again would otherwise free them twice).
        pane.pv[k].body.sels = &.{};
        pane.pv[k].body.nsel = 0;
    };
    layout.compute(p);
    // Its terminals' cursors moved while it was out: each pan follows.
    for (p.panes, 0..) |s, id| if (s) |pane| {
        pane.pan = pardes.panes.terminal.panFor(p, pane, p.view().rects[id]);
    };
}

/// The pane with the keyboard is one the live view shows: focused where its
/// layout has it not (a Look at a file another view opened, a jump, a 9P
/// focus), it goes into the view's active column, as kakoune shows a buffer
/// in the window that asked for it.
pub fn show(p: *Pardes) void {
    const v = p.view();
    if (p.panes[v.active] == null or layout.findPane(p, v.active) != null) return;
    const c = layout.firstColumn(p) orelse layout.columnBySerial(p, v.active_column) orelse v.ncol - 1;
    layout.acmePlace(p, c, null, v.active);
}

/// Into view `k`: the live one's pane shares parked, `k`'s put in their place.
pub fn to(p: *Pardes, k: u8) void {
    std.debug.assert(isOpen(p, k));
    if (k == p.live) return;
    park(p);
    unpark(p, k);
}

/// A new view, as the live one is laid out and focused, with its panes
/// where they are scrolled and its cursors where they are; the rest of it
/// (column tags, gestures) as a session starts. Null when there
/// are `max` already.
pub fn open(p: *Pardes) ?u8 {
    const k: u8 = for (0..max) |i| {
        if (!isOpen(p, @intCast(i))) break @intCast(i);
    } else return null;
    const live = p.view();
    p.views[k] = .{ .screen_w = live.screen_w, .screen_h = live.screen_h };
    const v = &p.views[k].?;
    inline for (sized ++ laid_out ++ .{"frontend"}) |name|
        @field(v, name) = @field(live, name);
    // A query's mark on the jumps is the view's that asked it.
    v.jumps.force = false;
    v.col_tags = @splat(.{ .what = .column, .gpa = p.gpa });
    for (p.panes) |s| {
        const pane = s orelse continue;
        pane.pv[k] = fresh(pane);
        pane.pv_known |= bit(k);
    }
    p.views_open |= bit(k);
    return k;
}

/// How a view is laid out and focused: what a new one takes of the live
/// one (`open`), and what one going leaves the view that stays (`closeKeeping`).
const laid_out = .{ "ncol", "cols", "active", "active_column", "jumps" };
const sized = .{ "screen_w", "screen_h", "cell_pixels", "row_metrics" };

/// View `k` gone, and the view that stays live laid out as `k` was: its
/// columns, its focus, its panes where they were scrolled and its cursors
/// where they were. For a session's last client while no one else watches
/// it (replica.Peers.leave): the client's rejoin (an Upgrade's, a diverged
/// one's) copies the live view (`open`), so it finds its own again.
pub fn closeKeeping(p: *Pardes, k: u8) void {
    if (!isOpen(p, k) or count(p) == 1) return;
    to(p, k);
    // Never into one kept for a rejoin (`away`): that one is its client's.
    const other = looked(p, k).?;
    const v = &p.views[other].?;
    // Its size too: the terminals it sized keep theirs, no shell redrawn for
    // a size it is given back at the rejoin.
    const force = v.jumps.force;
    inline for (sized ++ laid_out) |name| @field(v, name) = @field(p.views[k].?, name);
    v.jumps.force = force;
    for (p.panes) |s| if (s) |pane| {
        if (pane.pv_known & bit(other) != 0 and pane.pv[other].body.sels.len > 0) p.gpa.free(pane.pv[other].body.sels);
        pane.pv[other] = fresh(pane);
        pane.pv_known |= bit(other);
    };
    close(p, k);
}

/// What view `v`'s own share holds, freed.
fn freeView(p: *Pardes, v: *View) void {
    for (&v.col_tags) |*t| t.deinit(p.gpa);
    if (v.chord_arg) |a| p.gpa.free(a);
}

/// View `k` closed outright (not live): its share and its panes' shares freed.
fn dropView(p: *Pardes, k: u8) void {
    if (p.views[k]) |*v| freeView(p, v);
    p.views[k] = null;
    for (p.panes) |s| if (s) |pane| {
        if (pane.pv_known & bit(k) != 0) {
            const sels = pane.pv[k].body.sels;
            if (sels.len > 0) p.gpa.free(sels);
        }
        pane.pv[k].body.sels = &.{};
        pane.pv_known &= ~bit(k);
        // A name it was drafting goes with it.
        if (pane.prompt == .name and pane.prompt_view == k) pane.closePrompt();
    };
    p.views_open &= ~bit(k);
    p.views_away &= ~bit(k);
}

/// View `k` gone, and all it held; the live one moves to another first.
/// The last view someone looks at stays: a session without a client keeps
/// its own. One kept for a rejoin (`away`) goes whenever it is closed.
pub fn close(p: *Pardes, k: u8) void {
    if (!isOpen(p, k) or @popCount(p.views_open) == 1 or (!isAway(p, k) and count(p) == 1)) return;
    if (k == p.live) {
        const other: u8 = looked(p, k) orelse for (0..max) |i| {
            if (i != k and isOpen(p, @intCast(i))) break @intCast(i);
        } else unreachable;
        to(p, other);
    }
    dropView(p, k);
}

/// View `k`'s client gone a moment, to join again for it (an Upgrade's
/// rejoin, a divergence's): the view kept as it is, layout, focus and the
/// panes opened in it, until its client is back (Pardes.rejoinView) or a
/// join wants its place (Pardes.openView). Dumped with the rest, so an
/// Upgrade's new build has it too. The live view is never one: the session
/// goes into another someone looks at, or into a copy of this one of its own.
pub fn away(p: *Pardes, k: u8) void {
    if (!isOpen(p, k)) return;
    if (k == p.live) if (looked(p, k) orelse open(p)) |other| to(p, other);
    p.views_away |= bit(k);
}

/// The session's end: what each view holds.
pub fn deinit(p: *Pardes) void {
    for (&p.views) |*slot| if (slot.*) |*v| freeView(p, v);
}

pub const Present = struct { ctx: ?*anyopaque, f: ?*const fn (?*anyopaque, *const pardes.Surface) void };

/// The view this process's frontend shows: the one open view that is no
/// replica client's (`undrawn`) and kept for none (`away`), if there is one.
pub fn shown(p: *const Pardes) ?u8 {
    for (0..max) |i| if (isOpen(p, @intCast(i)) and (p.undrawn | p.views_away) & bit(i) == 0) return @intCast(i);
    return null;
}

fn drawLive(present: Present, p: *Pardes) anyerror!void {
    _ = p.frame_arena.reset(.{ .retain_with_limit = pardes.memory.limits.frame_kept });
    const surface = try p.render(p.frame_arena.allocator());
    if (present.f) |f| f(present.ctx, surface);
}

/// View `k` drawn and presented outside any step (the pump's other views,
/// a replica client's own): the live view put back after exactly as it
/// was, so the digest is the same. No post_present.
pub fn drawOne(p: *Pardes, k: u8, present: Present) !void {
    try within(p, k, present, drawLive);
}

/// `f(ctx, p)` with view `k` live, outside any step, and the live view put
/// back after exactly as it was, as `drawOne` draws one: what a replica
/// client's frontend reads of its own view (its pointer's cells, its size)
/// while another client's input was the session's last. What going into
/// `k` and drawing it made of it (its layout worked out, a cursor brought
/// inside a changed text) is not kept: it is done again, in every replica
/// alike, when `k` is next live by an input.
pub fn within(p: *Pardes, k: u8, ctx: anytype, comptime f: fn (@TypeOf(ctx), *Pardes) anyerror!void) !void {
    if (k == p.live or !isOpen(p, k)) return f(ctx, p);
    const live = p.live;
    const kept = p.views[k];
    var sels: [MAX_PANES]struct { []Text.SelRange, u16 } = undefined;
    for (p.panes, 0..) |s, id| if (s) |pane| {
        sels[id] = .{ pane.pv[k].body.sels, pane.pv[k].body.nsel };
    };
    park(p);
    unpark(p, k);
    defer {
        p.views[k] = kept;
        p.live = live;
        for (p.panes, 0..) |s, id| if (s) |pane| {
            // `k`'s slot its selections again (else a frame drawn would
            // take them from a view, and a replica that draws nothing
            // would keep them); the live view's fields its own again, and
            // its slot, stale while it is live, owning nothing.
            pane.pv[k].body.sels = sels[id][0];
            pane.pv[k].body.nsel = sels[id][1];
            const pv = &pane.pv[live];
            copy(&pane_fields, pane, pv);
            copy(&body_fields, &pane.body, &pv.body);
            if (!pane.isTerminal()) {
                pane.cols = pv.cols;
                pane.rows = pv.rows;
            }
            if (pane.file) |*file| file.scroll = pv.scroll;
            pv.body.sels = &.{};
            pv.body.nsel = 0;
        };
    }
    try f(ctx, p);
}

// ---- tests ----

const testing = std.testing;
const Key = pardes.Key;

fn typeKeys(p: *Pardes, text: []const u8) void {
    for (text) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
}

fn escape(p: *Pardes) void {
    p.update(.{ .key = .{ .cp = Key.escape } });
}

fn numbered(gpa: std.mem.Allocator, n: usize) ![]u8 {
    var out: std.ArrayList(u8) = .empty;
    for (1..n + 1) |i| try out.print(gpa, "line {d}\n", .{i});
    return out.toOwnedSlice(gpa);
}

/// The cursor put on `row`, as a jump puts it, and the step after.
fn cursorTo(p: *Pardes, pane: *Pane, row: i32) void {
    pane.body.vsel.active = false;
    pane.body.nsel = 0;
    pane.body.cur_row = row;
    pane.body.cur_col = 0;
    pane.body.cur_pinned = true;
    pane.ensureCursorVisible();
    p.sync();
}

test "each view has its own cursor and scroll, and an edit in one is in the other" {
    const gpa = testing.allocator;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
    defer p.deinit();
    const text = try numbered(gpa, 200);
    defer gpa.free(text);
    const pane = try p.setTestFile(text);
    try testing.expectEqual(@as(?u8, 1), p.openView());
    cursorTo(p, pane, 119);
    const scrolled = pane.file.?.scroll;
    try testing.expect(scrolled > 0);
    // The other view is where the session was when it came.
    p.toView(1);
    try testing.expectEqual(@as(i32, 0), pane.body.cur_row);
    try testing.expectEqual(@as(usize, 0), pane.file.?.scroll);
    typeKeys(p, "ix");
    escape(p);
    try testing.expectEqual(Text.Mode.normal, pane.body.mode);
    p.toView(0);
    try testing.expectEqual(@as(i32, 119), pane.body.cur_row);
    try testing.expectEqual(scrolled, pane.file.?.scroll);
    try testing.expect(std.mem.startsWith(u8, pane.file.?.content, "xline 1\n"));
    // Its mode is its own: insert here leaves the other in normal.
    typeKeys(p, "i");
    try testing.expectEqual(Text.Mode.insert, pane.body.mode);
    p.toView(1);
    try testing.expectEqual(Text.Mode.normal, pane.body.mode);
}

test "each view has its own layout and focus over the same panes" {
    const gpa = testing.allocator;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
    defer p.deinit();
    _ = try p.setTestFile("one\ntwo\n");
    const k = p.openView().?;
    const ncol = p.view().ncol;
    p.toView(k);
    p.update(.{ .command = "Newcol" });
    p.update(.{ .command = "New" });
    const made = p.view().active;
    try testing.expect(made != 0);
    try testing.expectEqual(ncol + 1, p.view().ncol);
    p.toView(0);
    try testing.expectEqual(ncol, p.view().ncol);
    try testing.expectEqual(@as(usize, 0), p.view().active);
    try testing.expect(layout.findPane(p, made) == null);
    try testing.expectEqual(pardes.Rect{}, p.view().rects[made]);
    // The pane is the session's: focused here, this view shows it too.
    p.view().active = made;
    p.sync();
    try testing.expect(layout.findPane(p, made) != null);
    try testing.expect(p.view().rects[made].h > 0);
    // Closed here, it leaves the other view's layout, and its keyboard.
    try p.removePane(made, null);
    p.sync();
    p.toView(k);
    try testing.expect(layout.findPane(p, made) == null);
    try testing.expect(p.panes[p.view().active] != null);
    try testing.expect(layout.findPane(p, p.view().active) != null);
}

test "registers are the session's: yanked in one view, put in another" {
    const gpa = testing.allocator;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
    defer p.deinit();
    const pane = try p.setTestFile("alpha\nbeta\n");
    const k = p.openView().?;
    typeKeys(p, "xy");
    p.toView(k);
    cursorTo(p, pane, 1);
    typeKeys(p, "p");
    try testing.expectEqualStrings("alpha\nbeta\nalpha\n", pane.file.?.content);
}

test "a terminal shown at two sizes takes the size of the view that typed into it last" {
    const gpa = testing.allocator;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
    defer p.deinit();
    const term = p.panes[p.view().active].?;
    try testing.expect(term.isTerminal());
    const small = .{ term.cols, term.rows };
    const k = p.openView().?;
    p.toView(k);
    p.update(.{ .resize = .{ .cols = 120, .rows = 40 } });
    // Shown bigger here, it keeps the size of the view that typed last.
    try testing.expect(p.view().rects[p.view().active].w > 80);
    try testing.expectEqual(small, .{ term.cols, term.rows });
    p.update(.{ .key = .{ .cp = Key.right } });
    try testing.expect(term.cols > small[0] and term.rows > small[1]);
    const big = .{ term.cols, term.rows };
    p.toView(0);
    p.sync();
    try testing.expectEqual(big, .{ term.cols, term.rows });
    p.update(.{ .key = .{ .cp = Key.right } });
    try testing.expectEqual(small, .{ term.cols, term.rows });
    // That view gone, the one left sizes it.
    p.toView(k);
    p.closeView(0);
    try testing.expectEqual(k, p.live);
    try testing.expectEqual(big, .{ term.cols, term.rows });
}

test "a view closing leaves the others as they were" {
    const gpa = testing.allocator;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
    defer p.deinit();
    const text = try numbered(gpa, 100);
    defer gpa.free(text);
    const pane = try p.setTestFile(text);
    const a = p.openView().?;
    const b = p.openView().?;
    try testing.expectEqual(@as(usize, 3), count(p));
    p.toView(b);
    p.update(.{ .command = "Newcol" });
    cursorTo(p, pane, 40);
    typeKeys(p, "xy");
    p.toView(a);
    cursorTo(p, pane, 70);
    p.toView(0);
    cursorTo(p, pane, 10);
    const ncol = p.view().ncol;
    // The live one closing: the session goes into another.
    p.toView(b);
    p.closeView(b);
    try testing.expect(p.live != b);
    try testing.expectEqual(@as(usize, 2), count(p));
    p.toView(a);
    try testing.expectEqual(@as(i32, 70), pane.body.cur_row);
    p.closeView(0);
    try testing.expectEqual(a, p.live);
    try testing.expectEqual(ncol, p.view().ncol);
    // The last stays.
    p.closeView(a);
    try testing.expectEqual(@as(usize, 1), count(p));
    try testing.expectEqual(@as(i32, 70), pane.body.cur_row);
}

test "the last client's view going leaves the session its layout, which a rejoin copies" {
    const gpa = testing.allocator;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
    defer p.deinit();
    const text = try numbered(gpa, 100);
    defer gpa.free(text);
    const pane = try p.setTestFile(text);
    const k = p.openView().?;
    p.toView(k);
    p.update(.{ .resize = .{ .cols = 120, .rows = 40 } });
    p.update(.{ .command = "Newcol" });
    p.update(.{ .command = "New" });
    const made = p.view().active;
    const ncol = p.view().ncol;
    p.view().active = 0;
    p.sync();
    cursorTo(p, pane, 60);
    p.leaveView(k);
    try testing.expectEqual(@as(usize, 1), count(p));
    try testing.expectEqual(ncol, p.view().ncol);
    try testing.expect(layout.findPane(p, made) != null);
    try testing.expectEqual(@as(i32, 60), pane.body.cur_row);
    try testing.expectEqual(@as(u16, 120), p.view().screen_w);
    // Its client back (a view copied from the live one): all of it again.
    const again = p.openView().?;
    p.toView(again);
    try testing.expectEqual(ncol, p.view().ncol);
    try testing.expect(layout.findPane(p, made) != null);
    try testing.expectEqual(@as(usize, 0), p.view().active);
    try testing.expectEqual(@as(i32, 60), pane.body.cur_row);
}

test "a client's view kept for its rejoin: through an Upgrade's dump, each client back in its own; a join with no room lets one go" {
    const gpa = testing.allocator;
    const opts: pardes.Options = .{ .tty_only = true, .cols = 100, .rows = 30 };
    const p = try Pardes.init(gpa, opts);
    defer p.deinit();
    _ = try p.setTestFile("one\ntwo\n");
    // Two clients, each a pane of its own in its own view.
    const ks: [2]u8 = .{ p.openView().?, p.openView().? };
    var made: [2]usize = undefined;
    for (ks, &made) |k, *m| {
        p.toView(k);
        p.update(.{ .command = "New" });
        m.* = p.view().active;
    }
    // Both let go to upgrade, the live view one of theirs: theirs are kept,
    // and the session's own is live.
    for (ks) |k| p.awayView(k);
    try testing.expectEqual(@as(usize, 1), count(p));
    try testing.expect(!isAway(p, p.live));
    // The new build loads the dump; each client is back in its own view.
    const bytes = try pardes.dump.dumpBytes(p);
    defer gpa.free(bytes);
    const q = try pardes.dump.load(gpa, opts, bytes, null);
    defer q.deinit();
    for (ks, made, 0..) |k, m, i| {
        try testing.expect(isAway(q, k));
        try testing.expect(q.rejoinView(k));
        q.toView(k);
        try testing.expectEqual(m, q.view().active);
        try testing.expect(layout.findPane(q, m) != null);
        try testing.expect(layout.findPane(q, made[1 - i]) == null);
    }
    try testing.expect(!q.rejoinView(ks[0]));
    // A client that never comes back: its view goes when a join has no room.
    p.toView(0);
    try testing.expectEqual(@as(?u8, 3), p.openView());
    try testing.expectEqual(ks[0], p.openView());
    try testing.expect(!isAway(p, ks[0]) and isAway(p, ks[1]));
}

test "drawing another view leaves the live one as it was, to the digest" {
    const gpa = testing.allocator;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
    defer p.deinit();
    const text = try numbered(gpa, 100);
    defer gpa.free(text);
    const pane = try p.setTestFile(text);
    const k = p.openView().?;
    p.toView(k);
    cursorTo(p, pane, 60);
    typeKeys(p, "dd");
    p.toView(0);
    cursorTo(p, pane, 95);
    const before = pardes.walk.digest(Pardes, p);
    try drawOne(p, k, .{ .ctx = null, .f = null });
    try testing.expectEqual(@as(u8, 0), p.live);
    try testing.expectEqual(before, pardes.walk.digest(Pardes, p));
    p.toView(k);
    try testing.expectEqual(@as(i32, 60), pane.body.cur_row);
}

test "a view drawn while another is live keeps its own cursors" {
    const gpa = testing.allocator;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
    defer p.deinit();
    const pane = try p.setTestFile("ab\ncd\nef\n");
    const k = p.openView().?;
    p.toView(k);
    p.update(.{ .key = .{ .cp = 'C', .text = "C" } });
    try testing.expectEqual(@as(u16, 1), pane.body.nsel);
    p.toView(0);
    const before = pardes.walk.digest(Pardes, p);
    try drawOne(p, k, .{ .ctx = null, .f = null });
    try testing.expectEqual(before, pardes.walk.digest(Pardes, p));
    p.toView(k);
    try testing.expectEqual(@as(u16, 1), pane.body.nsel);
}

test "a view not live keeps its place in a text another view edits" {
    const gpa = testing.allocator;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
    defer p.deinit();
    const text = try numbered(gpa, 200);
    defer gpa.free(text);
    const pane = try p.setTestFile(text);
    const k = p.openView().?;
    p.toView(k);
    cursorTo(p, pane, 100);
    const scrolled = pane.file.?.scroll;
    p.toView(0);
    // Three lines put above it, one taken below it.
    typeKeys(p, "xyppp");
    cursorTo(p, pane, 150);
    typeKeys(p, "xd");
    p.toView(k);
    try testing.expectEqual(@as(i32, 103), pane.body.cur_row);
    try testing.expectEqual(scrolled + 3, pane.file.?.scroll);
    try testing.expect(std.mem.startsWith(u8, pardes.panes.File.sourceLine(pane, 103), "line 101"));
}

test "a terminal shown in a view shorter than it keeps its cursor in sight" {
    const gpa = testing.allocator;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 20 });
    defer p.deinit();
    const id = p.view().active;
    const term = p.panes[id].?;
    const k = p.openView().?;
    p.toView(k);
    p.update(.{ .resize = .{ .cols = 100, .rows = 50 } });
    p.update(.{ .key = .{ .cp = Key.right } });
    const rows = term.rows;
    try testing.expect(rows > 30);
    var out: std.ArrayList(u8) = .empty;
    defer out.deinit(gpa);
    for (1..rows) |i| try out.print(gpa, "row-{d}\r\n", .{i});
    try out.appendSlice(gpa, "LAST$ ");
    p.update(.{ .output = .{ .pane = @intCast(id), .bytes = out.items } });
    // Sized for the tall view, it fits there whole: nothing is passed over.
    try testing.expectEqual(@as(u16, 0), term.pan);
    p.toView(0);
    p.sync();
    try testing.expectEqual(rows, term.rows);
    try testing.expect(term.pan > 0);
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const s = try p.render(arena.allocator());
    const r = p.view().rects[id];
    // The cursor's row, the last, is on screen in the short view, inside
    // the pane, and so is the line it is on.
    const cursor = s.cursor.?;
    try testing.expect(cursor.y >= r.y and cursor.y < r.y + r.h);
    var row_text: std.ArrayList(u8) = .empty;
    defer row_text.deinit(gpa);
    for (0..s.cols) |x| try row_text.appendSlice(gpa, s.cells[@as(usize, cursor.y) * s.cols + x].grapheme());
    try testing.expect(std.mem.indexOf(u8, row_text.items, "LAST$") != null);
    // Back in the tall view, its top is where it was.
    p.toView(k);
    try testing.expectEqual(@as(u16, 0), term.pan);
}

test "a session's dump keeps its views: loaded, each where it was; revived for one client, the live one alone" {
    const gpa = testing.allocator;
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
    defer p.deinit();
    const text = try numbered(gpa, 200);
    defer gpa.free(text);
    const pane = try p.setTestFile(text);
    const id = for (p.panes, 0..) |s, i| {
        if (s == pane) break i;
    } else unreachable;
    const k = p.openView().?;
    cursorTo(p, pane, 119);
    p.toView(k);
    p.update(.{ .command = "Newcol" });
    p.toView(0);
    p.toView(k);
    cursorTo(p, pane, 30);
    const ncol = p.view().ncol;
    const bytes = try pardes.dump.dumpBytes(p);
    defer gpa.free(bytes);
    const loaded = try pardes.dump.load(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }, bytes, null);
    defer loaded.deinit();
    try testing.expectEqual(pardes.walk.digest(Pardes, p), pardes.walk.digest(Pardes, loaded));
    const again = try pardes.dump.dumpBytes(loaded);
    defer gpa.free(again);
    try testing.expectEqualSlices(u8, bytes, again);
    const lp = loaded.panes[id].?;
    loaded.toView(0);
    try testing.expectEqual(@as(i32, 119), lp.body.cur_row);
    try testing.expectEqual(ncol - 1, loaded.view().ncol);
    loaded.toView(k);
    try testing.expectEqual(@as(i32, 30), lp.body.cur_row);
    try testing.expectEqual(ncol, loaded.view().ncol);
    // For one client: the view live when dumped, as view 0.
    const one = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }, bytes);
    defer one.deinit();
    try testing.expectEqual(@as(usize, 1), count(one));
    try testing.expectEqual(@as(u8, 0), one.live);
    try testing.expectEqual(ncol, one.view().ncol);
    try testing.expectEqual(@as(i32, 30), one.panes[id].?.body.cur_row);
    try testing.expectEqual(@as(?u8, 1), one.openView());
}