summaryrefslogtreecommitdiff
path: root/anim/src/context.zig
blob: 874a22a38d7ed6b3831fb2dfb7af404a955e2392 (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
//! The state column (design/README.md, "3. Panels"): `registers`, all
//! seventeen, each followed as far as it points; `stack`, the words from
//! rsp with the frames they belong to as `call` spans down its right edge
//! and the registers that point at a word as `pin`s in its lane; and
//! `backtrace`, the call chain as rows, a panel of its own only in the
//! `none` split. Ink says what a thing is, paper what happened to it.
//! Reads `Moment.regs`, `Moment.read`, the mappings (through
//! `zt.telescope`), and the names the debugger recorded.
const std = @import("std");
const sk = @import("sketch");
const anim = @import("anim");
const zt = @import("ztrace");
const ui = @import("ui.zig");
const rows = @import("rows.zig");
const cursors = @import("cursor.zig");
const Recording = @import("Recording.zig");
const syscalls = @import("syscalls.zig");
const ties = @import("ties.zig");
const hexdump = @import("hexdump.zig");
const map = @import("map.zig");
const Stage = @import("stage.zig").Stage;
const theme = ui.theme;
const time = theme.time;
const Rect = ui.Rect;
const t = theme.color.text;
const m = theme.metric.context;

pub const ink = rows.ink;
pub const regionOf = rows.regionOf;

/// The registers' tag: the legend of what an address's ink says, always on screen, as pwndbg's is.
pub const legend = blk: {
    const c = theme.color.region;
    break :blk [_]ui.Legend{
        .{ .text = "stack", .ink = ui.rgb(c.stack) },
        .{ .text = "heap", .ink = ui.rgb(c.heap) },
        .{ .text = "code", .ink = ui.rgb(c.code_) },
        .{ .text = "data", .ink = ui.rgb(c.data) },
        .{ .text = "rwx", .ink = ui.rgb(c.data), .under = true },
        .{ .text = "read-only", .ink = ui.rgb(c.rodata) },
    };
};

/// While a `dive` or a `surface` plays (`map.Map`): each working panel's
/// box, and the rect it is drawn into instead, on its way between its
/// window on the map and its place; its tags, rules and lanes how much shown.
/// `fold`: how far the registers panel has folded its quiet rows (a dive lands it folded; `Registers.draw`).
pub const Zoom = struct { box: Rect, to: Rect, chrome: f32, shows: f32 = 1, fold: f32 = 1 };
pub var zoomed: [8]?Zoom = @splat(null);
/// How much the thread shows: it fades in (12 f) once a dive has landed, never in a frame.
pub var thread_shows: f32 = 1;

/// A panel's `Ui`, moved to where the stage has its box now (or, in a
/// dive, scaled into the rect it is on its way through).
pub fn at(f: *sk.Frame, placed: anim.Placed, box: Rect) ui.Ui {
    var p = placed;
    ui.chrome = 1;
    if (!ui.mapping) for (zoomed) |z| if (z) |zz| if (@abs(zz.box.x - box.x) < 0.5 and @abs(zz.box.y - box.y) < 0.5 and @abs(zz.box.h - box.h) < 0.5) {
        const k = zz.to.w / box.w;
        p.xf = p.xf.mul(.translate(zz.to.x, zz.to.y)).mul(.scale(k, k)).mul(.translate(-box.x, -box.y));
        p.scale *= k;
        p.pose.opacity *= zz.shows;
        // On its way it is opaque, over the panels that set off before it; its tag and rules come in at the end.
        const u = (ui.Ui{ .f = f, .at = p }).moved(box.x, box.y);
        u.fill(.{ .x = 0, .y = m.tag, .w = box.w, .h = box.h - m.tag }, theme.color.page);
        ui.chrome = zz.chrome;
        return u;
    };
    // Looking at the map alone (`map.looking`): the working panels stand aside.
    if (!ui.mapping and map.looking(f)) p.pose.opacity = 0;
    return (ui.Ui{ .f = f, .at = p }).moved(box.x, box.y);
}

pub fn veiled(u: ui.Ui, box: Rect, amount: f32) void {
    // Staging: what cannot be read at a sprint is dimmed, not removed.
    u.veil(.{ .x = theme.stroke.rule, .y = m.tag, .w = box.w - 2 * theme.stroke.rule, .h = box.h - m.tag - theme.stroke.rule }, amount);
}

/// The rows a panel `box` shows: while a relayout moves it, one more, cut by its edge.
pub fn rowsOf(box: Rect) usize {
    return @intFromFloat(@max(@ceil((box.h - m.tag - 2 * m.pad) / m.row), 0));
}

pub fn clipBody(u: ui.Ui, box: Rect) void {
    u.clip(.{ .x = theme.stroke.rule, .y = m.tag + m.pad - 1, .w = box.w - 2 * theme.stroke.rule, .h = box.h - m.tag - 2 * m.pad + 2 });
}

pub const Registers = struct {
    cursor: cursors.Cursor,
    stage: *const Stage,
    /// A step that makes a system call frames, as read, the registers
    /// that carry it, one at a time; and rax is struck when it returns.
    syscalls: bool = false,
    /// No strikes: for a program whose instrumentation uses the registers
    /// between any two lines, so that nearly all of them change at every one.
    quiet: bool = false,
    focus: bool = false,
    /// The registers the scene moves (`movedBy`), a bit each of `Regs.names`:
    /// a row each, with its chain; the rest folded three to a row
    /// (design/README.md, `registers` `quiet`). All of them on the map.
    moves: u32 = every,
    /// The quiet ones left out, not folded, rip under the rest: a `pair`'s four rows.
    folds: bool = true,
    /// Its tag's title (a `pair`'s names its run).
    title: []const u8 = "registers",

    const Shown = struct { regs: zt.Regs, moment: Recording.Moment };

    pub fn draw(r: *const Registers, f: *sk.Frame, placed: anim.Placed) void {
        const box = r.stage.box(placed, .registers);
        const u = at(f, placed, box);
        // In a dive the panel comes whole out of the map and folds as it lands (`Zoom.fold`).
        const fold = if (ui.mapping) 1 else foldOf(box);
        var shape = box;
        shape.h = std.math.lerp(theme.layout.panelH(@floatFromInt(theme.metric.all_registers.len)), box.h, fold);
        const now = r.cursor.now(placed);
        const rec = r.cursor.rec;
        const is: Shown = .{ .regs = (now.moment().regs(rec.tid) catch null) orelse zt.Regs{}, .moment = now.moment() };
        const was: Shown = .{ .regs = (now.before().regs(rec.tid) catch null) orelse is.regs, .moment = now.before() };
        // Taller than its place on its way in: its own page under it.
        if (fold < 1) u.fill(.{ .x = 0, .y = m.tag, .w = shape.w, .h = shape.h - m.tag }, theme.color.page);
        const body = u.panel(shape.w, shape.h, r.title, .{ .focus = r.focus, .legend = &legend });
        // A link leaves from the panel's edge, not through a name.
        ties.anchor(u, .registers, .{ .x = 0, .y = 0, .w = shape.w, .h = shape.h });
        clipBody(u, shape);
        defer u.unclip();
        const q = theme.metric.registers;
        const full = fullRows(r.moves);
        const top = body.y + m.pad;
        // The quiet ones under a rule across, in pwndbg's order; rip the last row.
        if (full < 16 and r.folds) u.faded(fold).fill(.{ .x = theme.stroke.rule, .y = top + @as(f32, @floatFromInt(full)) * m.row - 1, .w = shape.w - 2 * theme.stroke.rule, .h = theme.stroke.rule }, theme.color.rule);
        var rows_before: usize = 0;
        var quiet_before: usize = 0;
        for (theme.metric.all_registers[0..16], 0..) |name, i| {
            const unfolded = top + @as(f32, @floatFromInt(i)) * m.row;
            if (r.moves >> @intCast(i) & 1 != 0) {
                r.row(u, now, is, was, name, std.math.lerp(unfolded, top + @as(f32, @floatFromInt(rows_before)) * m.row, fold), shape.w);
                rows_before += 1;
                continue;
            }
            if (!r.folds) continue;
            const y = std.math.lerp(unfolded, top + @as(f32, @floatFromInt(full + quiet_before / q.quiet_per_row)) * m.row, fold);
            const x = std.math.lerp(theme.metric.context.side, q.quiet_from + @as(f32, @floatFromInt(quiet_before % q.quiet_per_row)) * q.quiet_pitch, fold);
            quiet_before += 1;
            r.quietRow(u, now, is, was, name, x, y, shape.w, fold);
        }
        r.rip(u, now, std.math.lerp(top + 16 * m.row, top + @as(f32, @floatFromInt(if (r.folds) registerRows(r.moves) - 1 else full)) * m.row, fold), shape.w, is, was);
        veiled(u, shape, now.veil);
    }

    /// A register no step of the scene changes, in its cell from `x` (its
    /// name's place); in a dive's fold (`fold` below 1), on its way from
    /// its whole row, its chain past the first hop gone over the move's first 24 f.
    fn quietRow(r: *const Registers, u: ui.Ui, now: cursors.Now, is: Shown, was: Shown, name: []const u8, x: f32, y: f32, w: f32, fold: f32) void {
        const i = index(name) orelse return;
        const value = is.regs.named(name) orelse return;
        const read_shows = if (r.carrier(now, name, was.regs.named(name) orelse value)) |c| c.shows else 0;
        if (fold < 1) {
            const dx = x - theme.metric.context.side;
            _ = rows.reg(u.faded(1 - fold).moved(dx, 0), y, w - dx, name, is.moment, value, .{ .hops = 1 - std.math.clamp(fold / 0.4, 0, 1) });
        }
        const hops = rows.quiet(u.faded(fold), x, y, name, is.moment, value, read_shows);
        anchor(u, i, hops, y, value, w);
    }

    /// Whether `name` carries the system call the step makes, holding
    /// `value_was` (the argument): which argument, and how much its frame shows.
    fn carrier(r: *const Registers, now: cursors.Now, name: []const u8, value_was: u64) ?struct { k: usize, made: Recording.Syscall, shows: f32 } {
        const made = (if (r.syscalls) syscalls.inStep(now) else null) orelse return null;
        // A register is framed as carrying the call only while it holds the
        // argument in the moment shown: the stop before the call, until the
        // call is back. (Set by the wrapper, between the stops, it carried
        // it where no stop saw it: the kernel's rows say it.)
        for (syscalls.carried(made), 1..) |carried, k| if (std.mem.eql(u8, carried, name) and value_was == made.args[k - 1]) {
            const framed = now.time - syscalls.Plan.in(now, made).registers - @as(f32, @floatFromInt(k - 1)) * time.flight.second;
            return .{ .k = k, .made = made, .shows = @min(std.math.clamp(framed / time.read.in, 0, 1), now.reading(.cpu, 0)) };
        };
        return null;
    }

    fn shownAt(rec: *const Recording, i: u64) ?Shown {
        const moment = rec.moment(i);
        return .{ .regs = (moment.regs(rec.tid) catch return null) orelse return null, .moment = moment };
    }

    /// rip: where execution is, a current mark like the source's and the
    /// disassembly's; it moves with them, at the advance.
    fn rip(r: *const Registers, u: ui.Ui, now: cursors.Now, y: f32, w: f32, is: Shown, was: Shown) void {
        const rec = r.cursor.rec;
        // The flags' corners are secondary: 6 f after the registers strike,
        // not with them; in a continue's wave, in its place after r15.
        const delay = if (now.plan.wave) ties.strikeDelay(now, index("eflags").?) else cursors.write_apart;
        const landed = now.landed(.cpu, delay);
        // The flags a step changed have a turned corner, for three steps.
        const eflags_index = comptime index("eflags").?;
        // Until this step's change lands, the corners are the last one's: no effect before its cause.
        const age = if (landed) now.registerAge(eflags_index) else now.registerAgeFrom(eflags_index, 1);
        var changed: u64 = 0;
        if (age) |a| changed = rec.register(now.stops[a], "eflags") ^ rec.register(now.stops[a + 1], "eflags");
        const heat = now.register(eflags_index, delay);
        const held = if (r.quiet) 0 else heat.level * heat.corner;
        // While a conditional jump runs, the flags it reads are framed (an echo of the row that set them).
        const reads: u64 = if (now.resting() or now.advancing() >= 0.5) 0 else @import("disasm.zig").readsFlags(rec, now.stops[1]);
        // rip crossfades with the advance; a flag set or cleared, over the 6 f it lands in.
        const flip = std.math.clamp(now.since(.cpu, delay) / time.strike.in, 0, 1);
        rows.rip(u, y, w, rec.moment(now.marks[1]), rec.register(now.marks[1], "rip"), is.regs.eflags, changed, held, 0, reads, now.reading(.cpu, 0), .{ .moment = rec.moment(now.marks[0]), .pc = rec.register(now.marks[0], "rip"), .eflags = was.regs.eflags, .going = now.advancing(), .flip = if (now.resting()) 1 else flip });
    }

    fn row(r: *const Registers, u: ui.Ui, now: cursors.Now, line_is: Shown, line_was: Shown, name: []const u8, y: f32, w: f32) void {
        const rec = r.cursor.rec;
        const i = index(name) orelse return;
        // Every register is the program's, at its line stops, as every
        // other panel is: what crossed into the kernel is the crossing's
        // to show, and a register is framed as carrying it only where it
        // still holds what crossed.
        const is = line_is;
        const was = line_was;
        const value_now = is.regs.named(name) orelse return;
        const value_was = was.regs.named(name) orelse value_now;
        var marks: rows.Marks = .{};
        var landed = now.landed(.cpu, 0);
        var note: []const u8 = "";
        var note_shows: f32 = 1;
        const crossing: ?Recording.Syscall = if (r.syscalls) syscalls.inStep(now) else null;
        if (r.carrier(now, name, value_was)) |c| {
            marks.read = 0;
            marks.read_shows = c.shows;
            // A descriptor says what it is open on: the `value` class `fd`.
            const names = zt.syscalls.names(c.made.nr);
            if (c.k <= names.len and std.mem.endsWith(u8, names[c.k - 1], "fd")) note = rec.openOn(u.f.scratch, value_was, c.made.enter);
            // In with its framing, over 12 f, and out with it: never in a frame.
            const framed = now.time - syscalls.Plan.in(now, c.made).registers - @as(f32, @floatFromInt(c.k - 1)) * time.flight.second;
            note_shows = @min(std.math.clamp(framed / time.quick, 0, 1), now.reading(.cpu, 0));
        }
        if (if (std.mem.eql(u8, name, "rax")) crossing else null) |made| {
            // rax: what was there, then the result, once the kernel's rows
            // have said it (the call's number went in at the wrapper).
            const back = now.time - syscalls.Plan.in(now, made).struck;
            const result = back >= time.strike.in / 2.0;
            const value: u64 = if (result) value_now else value_was;
            if (back >= -time.strike.arm) {
                marks = .{ .first = now.heat(0, null, back) };
                if (back >= 0 and now.walking()) marks.extend = back;
            }
            const hops = rows.reg(u, y, w, name, if (result) is.moment else was.moment, value, marks);
            // What `open` gave back is a descriptor: the `value` class
            // `fd`, this call's once it is back, the last one's before.
            const gave = if (result) made else if (syscalls.latest(rec, now.stops[1])) |n| rec.syscalls[n] else null;
            if (gave) |g| if (g.exit != null and g.result == value and std.mem.eql(u8, zt.syscalls.name(g.nr) orelse "", "open")) fdNote(u, hops, y, rec.openOn(u.f.scratch, value, g.exit.? + 1));
            return anchor(u, i, hops, y, value, w);
        } else if (r.quiet) {
            // Unmarked: the values change as the mark moves on.
            landed = now.advancing() >= 0.5;
        } else {
            const age = now.registerAge(i);
            // (In a step that crosses into the kernel, what else the line
            // changed is seen after the call is back, after rax: `strikeDelay`.)
            const delay = if (age == 0) ties.strikeDelay(now, i) else 0;
            landed = now.landed(.cpu, delay);
            marks.first = now.register(i, delay);
            // A register written: the rest of its chain is followed again.
            const since = now.since(.cpu, delay);
            if (age == 0 and now.walking() and since >= 0) marks.extend = since;
        }
        // At a run a value changes in place under an 8 f crossfade, unmarked, never in a frame; so does its chain where what it reads changed.
        const ran = runFade(now, .cpu);
        const fades = ran < 1 and (value_was != value_now or cursors.chainMoved(was.moment, is.moment, value_now));
        if (fades) _ = rows.reg(u.faded(1 - ran), y, w, name, was.moment, value_was, marks);
        // Its chain reads memory as the panels show it: what the step writes
        // there is followed again (`extend`) once the bytes have landed, never before.
        var memory = if (landed or ran < 1) is.moment else was.moment;
        if (ran >= 1 and landed and !r.quiet) {
            memory, const again, marks.hops = now.following(value_now);
            if (again) |ago| marks.extend = @min(marks.extend orelse ago, ago);
        }
        const hops = rows.reg(if (fades) u.faded(ran) else u, y, w, name, memory, if (landed or ran < 1) value_now else value_was, marks);
        fdNote(u.faded(note_shows), hops, y, note);
        anchor(u, i, hops, y, if (landed or ran < 1) value_now else value_was, w);
    }

    /// The `fd` class's note after a register's value: faint, what it is open on.
    fn fdNote(u: ui.Ui, hops: rows.Hops, y: f32, on: []const u8) void {
        if (hops.n > 0 and on.len > 0) u.text(.mono, theme.size.mono.context, hops.end + 8, rows.baseline(y), on, t.faint);
    }

    /// Its place, and its value shown there (a relation's join: `ties.show`).
    fn anchor(u: ui.Ui, i: usize, hops: rows.Hops, y: f32, value: u64, w: f32) void {
        if (hops.n == 0) return;
        const r: Rect = .{ .x = hops.x[0], .y = y, .w = hops.w[0], .h = m.row };
        ties.anchor(u, .{ .register = i }, r);
        ties.show(u, value, r, .registers, 0, @intCast(i), w);
    }
};

/// How far (0 to 1) a run's step has crossfaded its values at `level` (8 f from it); 1 at any other pace.
fn runFade(now: cursors.Now, level: cursors.Level) f32 {
    if (now.plan.gait != .run or now.resting()) return 1;
    return std.math.clamp(now.since(level, 0) / time.run_ease, 0, 1);
}

/// Every register of the seventeen, a bit each of `Regs.names`: none folded.
pub const every: u32 = (1 << 17) - 1;

/// The registers a scene moves (design/README.md, `registers` `quiet`): a
/// bit each of `Regs.names` for those any of its steps (of `by`, from
/// `way[0]` to `way[1]`: the clock's, `Cursor.journey`) changes, net, with
/// rsp, rbp and rip always. Chosen once: no row comes or goes while it
/// plays. A scene with no way of its own folds none.
pub fn movedBy(rec: *const Recording, by: Recording.Stop, way: [2]u64) u32 {
    if (way[1] <= way[0]) return every;
    var mask: u32 = comptime 1 << index("rsp").? | 1 << index("rbp").? | 1 << index("rip").?;
    var k = way[0];
    while (k < @min(way[1], rec.end())) {
        const n = @min(rec.next(by, k), way[1]);
        mask |= rec.registersChanged(k, n);
        k = n;
    }
    return mask & every;
}

/// How many of the sixteen keep a row of their own.
fn fullRows(moves: u32) usize {
    return @popCount(moves & 0xffff);
}

/// The registers panel's rows for `moves`: a row each for those the scene
/// moves, the quiet ones three to a row, and rip.
pub fn registerRows(moves: u32) usize {
    const full = fullRows(moves);
    return full + (16 - full + theme.metric.registers.quiet_per_row - 1) / theme.metric.registers.quiet_per_row + 1;
}

/// How far a dive has folded the registers panel at `box` (1: in its place, folded).
fn foldOf(box: Rect) f32 {
    for (zoomed) |z| if (z) |zz| if (@abs(zz.box.x - box.x) < 0.5 and @abs(zz.box.y - box.y) < 0.5 and @abs(zz.box.h - box.h) < 0.5) return zz.fold;
    return 1;
}

/// A register's place in `Regs.names`.
pub fn index(name: []const u8) ?usize {
    for (zt.Regs.names, 0..) |known, i| if (std.mem.eql(u8, known, name)) return i;
    return null;
}

/// One frame of the call chain, on the stack: its function's pc, and the
/// slots that are the frame, from `lo` to `hi` (the last; null: its end is
/// not known, past what the recording holds).
pub const Frame = struct { pc: u64, lo: u64, hi: ?u64 };

/// The frames at moment `i`, newest first, with their extents, as the
/// tracer reads them off the frame-pointer chain.
pub fn frames(rec: *const Recording, i: u64, out: []Frame) []Frame {
    const moment = rec.moment(i);
    const regs = (moment.regs(rec.tid) catch return out[0..0]) orelse return out[0..0];
    var buf: [24]zt.Debugger.Frame = undefined;
    const found = zt.telescope.frames(moment, &regs, buf[0..@min(buf.len, out.len)]) catch return out[0..0];
    for (found, out[0..found.len]) |f, *o| o.* = .{ .pc = f.pc, .lo = f.low, .hi = if (f.high > f.low) f.high - 8 else null };
    return out[0..found.len];
}

/// The register the newest frame's code addresses its words by
/// (design/README.md, `slot`): its call frame information's CFA register,
/// rbp in a body that keeps a frame pointer; rsp at its entry, in its
/// prologue before `mov rbp, rsp`, after its `pop rbp` or `leave`, in a
/// function that keeps none, and where the recording has no such rows.
pub const Base = struct {
    rbp: bool = false,

    pub fn name(b: Base) []const u8 {
        return if (b.rbp) "rbp" else "rsp";
    }

    pub fn value(b: Base, regs: zt.Regs) u64 {
        return if (b.rbp) regs.rbp else regs.rsp;
    }
};

pub fn frameBase(rec: *const Recording, i: u64, regs: zt.Regs) Base {
    const func = zt.telescope.function(rec.moment(i), regs.rip) orelse return .{};
    const size = @sizeOf(zt.Symbols.Row);
    var row: zt.Symbols.Row = .{};
    var o: usize = 0;
    while (o + size <= func.rows.len) : (o += size) {
        const r = std.mem.bytesToValue(zt.Symbols.Row, func.rows[o..][0..size]);
        if (r.offset > regs.rip -% func.start) break;
        row = r;
    }
    // DWARF's 6 is rbp; and rbp must be in the frame (under its return address).
    return .{ .rbp = row.cfa_reg == 6 and regs.rbp >= regs.rsp };
}

/// `d` bytes from base `name` (`rbp-18`, `rbp+8`, `rbp`), as the stack's tag writes a range.
fn fromBase(u: ui.Ui, name: []const u8, d: i64) []const u8 {
    const p = rows.hexMark(@abs(d));
    return if (d == 0) name else if (d > 0) u.print("{s}+{s}{x}", .{ name, p, @as(u64, @intCast(d)) }) else u.print("{s}-{s}{x}", .{ name, p, @as(u64, @intCast(-d)) });
}

/// A frame's span on the stack: its function's name, and as a call its
/// argument where it takes one (`fib(4)`): the digits on its node.
fn spanName(u: ui.Ui, rec: *const Recording, open: []const Recording.Call, i: usize, pc: u64) []const u8 {
    const name = frameName(u, rec, pc);
    if (i >= open.len) return name;
    const call = open[open.len - 1 - i];
    if (!std.mem.eql(u8, rec.name(call.function), name)) return name;
    const takes = for (rec.functions) |f| {
        if (std.mem.eql(u8, f.name, name)) break f.takes;
    } else false;
    const arg = call.arg orelse return name;
    if (!takes) return name;
    const v = ui.Value.of(arg, rows.regionOf(rec.moment(call.enter), arg) != .none);
    // A small number in decimal, as on the node; anything else as its class has it.
    return if (v.decimal) u.print("{s}({d})", .{ name, arg }) else u.print("{s}({s}{s})", .{ name, v.prefix, v.digits() });
}

/// Frame `i`'s arguments, from the call the recording knows it to be
/// (the `i`th open call from the newest, when it is of this frame's
/// function): "" where it knows none.
pub fn callArguments(u: ui.Ui, rec: *const Recording, open: []const Recording.Call, i: usize, pc: u64) []const u8 {
    if (i >= open.len) return "";
    const call = open[open.len - 1 - i];
    if (!std.mem.eql(u8, rec.name(call.function), frameName(u, rec, pc))) return "";
    return @import("calls.zig").arguments(u, rec, call);
}

/// Where frame `i` is in the program's source, `file:line`: the newest at
/// the moment's own line, when the moment is on one (in a library it is
/// not); an older one on its call's line, or where the recording only
/// knows a line near its return address, that one.
pub fn frameWhere(u: ui.Ui, rec: *const Recording, moment: u64, i: usize, pc: u64) []const u8 {
    const place = if (i == 0) rec.where(moment, pc) else rec.where(moment, callOf(rec, moment, pc) orelse pc);
    return if (place) |l| u.print("{s}:{d}", .{ l.file, l.line }) else "";
}

/// The call that returns to `ret`, where the recording has it: an outer
/// frame is on its call's line, not on the one it returns to.
fn callOf(rec: *const Recording, moment: u64, ret: u64) ?u64 {
    var buf: [256]u8 = undefined;
    const after = rec.instruction(moment, ret, &buf) orelse return null;
    if (after.back == 0) return null;
    return ret - after.back;
}

/// A frame's name: its function's (no offset), or its module's and offset where there is no symbol.
pub fn frameName(u: ui.Ui, rec: *const Recording, pc: u64) []const u8 {
    const name = rec.strings.get(pc) orelse return u.print("{x}", .{pc});
    const shown = ui.symbol(u, name);
    // A library's symbol (`libc.so.6!open+0`) by its name alone; one with none, `libc+27781`.
    if (std.mem.indexOfScalar(u8, name, '!') != null and shown.ptr != name.ptr + std.mem.indexOfScalar(u8, name, '!').? + 1) return shown;
    return shown[0 .. std.mem.lastIndexOfScalar(u8, shown, '+') orelse shown.len];
}

/// The registers (of the sixteen) that hold `addr` in `regs`.
fn pointing(u: ui.Ui, regs: zt.Regs, addr: u64) []const []const u8 {
    var out: std.ArrayList([]const u8) = .empty;
    for (theme.metric.all_registers[0..16]) |name| {
        if (regs.named(name) == addr) out.append(u.f.scratch, name) catch break;
    }
    return out.items;
}

pub const Stack = struct {
    cursor: cursors.Cursor,
    stage: *const Stage,
    focus: bool = false,
    /// On the map: the window from this many words above rsp, not scrolled
    /// (negative: below it, the stack going on in another column's rest).
    above: i32 = 0,
    /// Which box of its stage it is in: the map's `more` holds the stack continued.
    part: @import("stage.zig").Part = .stack,
    /// The introduction's: its offsets, roles and spans come in a `column` at a time.
    reveal: ?Reveal = null,

    /// The stack built a `column` at a time (design/README.md, 6. Verbs:
    /// `column`; motion.md, chapter II): each part a clock the scene plays
    /// (frames, negative before it begins), its rows coming in top down as
    /// shown, `apart` frames apart (2 by default), 12 f each; until then under the page.
    pub const Reveal = struct {
        offsets: anim.Value,
        roles: anim.Value,
        spans: anim.Value,
        apart: f32 = 2,

        /// How much of row (or span) `k`'s part is still under the page, its clock at `clock`.
        fn hidden(r: Reveal, clock: f32, k: f32) f32 {
            return 1 - std.math.clamp((clock - r.apart * @max(k, 0)) / 12, 0, 1);
        }
    };

    pub fn draw(k: *const Stack, f: *sk.Frame, placed: anim.Placed) void {
        const box = k.stage.box(placed, k.part);
        if (box.h < m.tag + m.row) return;
        const u = at(f, placed, box);
        const now = k.cursor.now(placed);
        const rec = k.cursor.rec;
        const slots = rowsOf(box);
        const is = (now.moment().regs(rec.tid) catch null) orelse return;
        const was = (now.before().regs(rec.tid) catch null) orelse is;
        rows.prefixed = now.introduction;
        defer rows.prefixed = false;
        // The window: from rsp, or further into the frame ([rsp, rbp+16))
        // when that is longer than the panel, so that the word the last
        // steps touched is in its middle. When a step moves it the rows
        // slide, with the stack's words, a level after the registers.
        // Under the camera the window holds still, `free` words above the
        // rsp it was held at: pushes fill them, and rsp's pin climbs.
        const hold = placed.value(k.stage.hold);
        const held = hold >= 0;
        const held_at: u64 = if (held) rec.register(@intFromFloat(hold), "rsp") -% 8 * @as(u64, @intFromFloat(placed.value(k.stage.hold_free))) else 0;
        // `tied`: two `free` words over rsp, the window's headroom; offsets from the frame's base; rsp's and rbp's moves as pins travelling.
        const tied = now.annotation == .tied;
        var window = if (held) [2]u64{ held_at, held_at } else if (k.above != 0) [2]u64{ is.rsp -% @as(u64, @bitCast(@as(i64, 8 * k.above))), was.rsp -% @as(u64, @bitCast(@as(i64, 8 * k.above))) } else [2]u64{ windowAt(now, is, slots, 0), windowAt(now, was, slots, 1) };
        // A window that goes farther than its own height (a continue to a
        // stop deeper or shallower than a call is) does not scroll: the old
        // rows fade out before memory strikes and the new ones in after,
        // each with the memory of its own stop.
        const jumped = far(window[0], window[1], slots);
        // Out over 12 f to memory's landing and in over 12 f (at a run, half
        // its step each, the turn no sooner than that): never in a frame.
        const fade = @min(time.quick, now.plan.total / 2.0);
        const turn = @max(now.plan.at[1] + time.strike.in / 2.0, fade);
        const landed = if (jumped and !now.resting()) now.time >= turn else now.landed(.memory, 0);
        // On the minimap the window glides there, whether it scrolls or fades here.
        const ways = window;
        const since_memory = now.since(.memory, 0);
        const jump_shows: f32 = if (!jumped or now.resting()) 1 else if (!landed) 1 - std.math.clamp((now.time - turn + fade) / fade, 0, 1) else std.math.clamp((now.time - turn) / fade, 0, 1);
        if (jumped) window = if (landed) .{ window[0], window[0] } else .{ window[1], window[1] };
        const v = u.faded(jump_shows);
        // Going to the hold and coming from it, the rows scroll: the
        // remaining way, in rows, from where the window would be.
        const natural = windowAt(now, is, slots, 0);
        // Under `tied`, the word the step touches, and the window over it before the touch goes there.
        const touch: ?cursors.Touched = if (tied and !now.resting()) cursors.stackTouch(rec, now.stops[1], now.stops[0]) else null;
        const touch_window = if (touch) |tt| if (!held and k.above == 0 and !jumped and (tt.addr < window[1] or tt.addr >= window[1] + 8 * @as(u64, slots))) windowOver(was, slots, tt.addr) else window[1] else window[1];
        // The frame's base, before the step and after it (`whole`: rsp).
        const bases = [2]Base{ if (tied) frameBase(rec, now.stops[1], was) else .{}, if (tied) frameBase(rec, now.stops[0], is) else .{} };
        const hold_scroll: f32 = if (held) @as(f32, @floatFromInt(@as(i64, @bitCast(held_at -% natural)))) / 8 * (1 - cursors.glide(placed.value(k.stage.hold_in))) else 0;
        // From rsp, or the range shown when the window is elsewhere: in
        // bytes from rsp, as the catalogue writes it (`rsp+20 to rsp+48`).
        const offset = struct {
            fn of(u_: ui.Ui, d: i64) []const u8 {
                return if (d == 0) "rsp" else if (d > 0) u_.print("rsp+{x}", .{@as(u64, @intCast(d))}) else u_.print("rsp-{x}", .{@as(u64, @intCast(-d))});
            }
        }.of;
        const numbers = [_][]const u8{ "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty" };
        const words = if (slots < numbers.len) numbers[slots] else u.print("{d}", .{slots});
        // The first word shown and the last.
        // The range before memory lands and after: one that changes crossfades (12 f), as a role does.
        // Under `tied` a walked step's labels change as its window follows, or its last pin lands (`Now.restacked`).
        const recast = if (now.resting()) 1 else if (tied and now.walking()) std.math.clamp((now.time - now.restacked()) / time.quick, 0, 1) else std.math.clamp(since_memory / time.quick, 0, 1);
        const ranges = [2]i64{ @bitCast(ways[1] -% was.rsp), @bitCast(ways[0] -% is.rsp) };
        var notes: [2][]const u8 = undefined;
        for (ranges, &notes, [2]zt.Regs{ was, is }, bases, 0..) |r_, *note, regs, base, side| {
            if (tied) {
                // From the base: `fourteen words` where the window is at its headroom, else the range.
                const from: i64 = @bitCast(ways[1 - side] -% base.value(regs));
                const range = if (ways[1 - side] == regs.rsp -% 16 and k.above == 0) u.print("{s} words", .{words}) else u.print("{s} to {s}", .{ fromBase(u, base.name(), from), fromBase(u, base.name(), from + 8 * (@as(i64, @intCast(slots)) - 1)) });
                note.* = u.print("{s} \u{00b7} offsets from {s} \u{00b7} the frames they belong to", .{ range, base.name() });
                continue;
            }
            const range = if (r_ == 0) u.print("{s} words from rsp", .{words}) else u.print("{s} to {s}", .{ offset(u, r_), offset(u, r_ + 8 * (@as(i64, @intCast(slots)) - 1)) });
            note.* = u.print("{s} \u{00b7} the frames they belong to", .{range});
        }
        const renote = !std.mem.eql(u8, notes[0], notes[1]) and recast < 1;
        const body = u.panel(box.w, box.h, if (k.part == .more) "stack, continued" else "stack", .{ .focus = k.focus, .note = if (renote) "" else notes[1] });
        if (renote) {
            u.faded(1 - recast).tagNote(box.w, notes[0]);
            u.faded(recast).tagNote(box.w, notes[1]);
        }
        var p = cursors.glide(now.moving(.memory, 0, time.move));
        const moved = @as(f32, @floatFromInt(@as(i64, @bitCast(window[0] -% window[1])))) / 8;
        var slide: f32 = (if (jumped) 0 else moved * (1 - p)) + hold_scroll;
        // Under `tied`, walked (design/README.md, `stack`): the rows hold while the pin travels;
        // a word the step touches outside the window is scrolled to before the touch goes there;
        // where the climb is longer than the room over the pin, the rows slide under it (the pin on
        // the top row); once it has landed the window follows (`Plan.follow`).
        const pin_sp = now.pinGone(0);
        if (tied and !jumped and !held and k.above == 0 and now.walking() and (now.plan.follow >= 0 or now.plan.touch >= 0 or pin_sp != null)) {
            const rows_at = struct {
                fn at(addr: u64, base: u64) f32 {
                    return @as(f32, @floatFromInt(@as(i64, @bitCast(addr -% base)))) / 8;
                }
                /// The window's top (rows from `window[0]`) with the pin at `pin`: never past it.
                fn keep(d: f32, pin: f32, n: usize) f32 {
                    return std.math.clamp(d, pin - @as(f32, @floatFromInt(n - 1)), pin);
                }
            };
            var d = rows_at.at(window[1], window[0]);
            if (touch_window != window[1]) d = std.math.lerp(d, rows_at.at(touch_window, window[0]), cursors.glide(std.math.clamp(now.time / @max(now.plan.touch, time.fire), 0, 1)));
            const pins_at = [2]f32{ rows_at.at(was.rsp, window[0]), rows_at.at(is.rsp, window[0]) };
            const landed_d = rows_at.keep(rows_at.at(touch_window, window[0]), pins_at[1], slots);
            if (pin_sp) |g| d = rows_at.keep(d, std.math.lerp(pins_at[0], pins_at[1], g), slots);
            if (now.plan.follow >= 0) {
                const span = @min(time.tied.follow + 2.0 / 60.0 * @max(@abs(landed_d) - 1, 0), time.tied.follow_most);
                const q = cursors.glide(std.math.clamp((now.time - now.plan.follow) / span, 0, 1));
                if (now.time >= now.plan.follow) d = std.math.lerp(landed_d, 0, q);
            } else d = std.math.lerp(d, 0, p);
            slide = -d;
            // The strip's window goes as the pane's does.
            p = if (moved != 0) std.math.clamp(1 - slide / moved, 0, 1) else 1;
        }
        const top = body.y + m.pad;
        clipBody(u, box);
        defer u.unclip();
        // The addresses' shared digits: the rows read by their ends, of the
        // window shown (it changes with the slide, not before it).
        const shown_at = if (landed) window[0] else window[1];
        const lead = ui.shared(&.{ shown_at, shown_at + 8 * @as(u64, slots) });
        const memory = now.shown(.memory);
        // Marks only for what the viewer saw change: the steps since the
        // window last faded to its place (none on a window that has just
        // faded in; the ticks it had on its way out).
        const watched_from: usize = if (jumped and !landed) 1 else 0;
        const watched_to = if (held) now.stops.len else watched(now, slots, watched_from);
        // rsp and rbp, moved by the step with no link to land: their tags
        // travel down the lane from the old word to the new, with the slide.
        var travel_buf: [2][]const u8 = undefined;
        var travelling: usize = 0;
        for ([_][]const u8{ "rsp", "rbp" }) |name| if (!now.resting() and !jumped and was.named(name) != is.named(name)) {
            travel_buf[travelling] = name;
            travelling += 1;
        };
        const travel = travel_buf[0..travelling];
        // The backtrace, drawn on the words that are each frame: each span
        // glides from the frame's old extent to its new one with the slide.
        // Worked out first: a name longer than the spans' room takes room
        // from the chains of the rows beside it, which end before it.
        var buf: [16]Frame = undefined;
        var old_buf: [16]Frame = undefined;
        const chain = frames(rec, now.stops[if (jumped and !landed) 1 else 0], &buf);
        const old_chain = frames(rec, now.stops[if (jumped and landed) 0 else 1], &old_buf);
        // Placed as the rows are: against the window after the step, and slid.
        const open_calls = rec.stack(u.f.scratch, if (landed) now.stops[0] else now.stops[1]);
        const named = if (landed) chain else old_chain;
        const rows_of = struct {
            fn at(addr: u64, base: u64) f32 {
                return @as(f32, @floatFromInt(@as(i64, @bitCast(addr -% base)))) / 8;
            }
        }.at;
        const Span = struct { y0: f32, y1: f32, name: []const u8, newest: bool, open: bool, was: ?[]const u8 = null, shows: f32 = 1 };
        // A frame whose name changes in place (on through a stub) crossfades over the 12 f before the advance.
        const renamed = now.renaming();
        const calls_was = rec.stack(u.f.scratch, now.stops[1]);
        const calls_is = rec.stack(u.f.scratch, now.stops[0]);
        var spans: [16]Span = undefined;
        var n_spans: usize = 0;
        // Under `tied` the spans ride rsp's pin: the newest stretches or shrinks with it.
        const p_span = pin_sp orelse p;
        // Each frame is the same frame before and after the step where it ends at the same
        // word (a call puts one on top, a return takes one off): never matched by depth.
        const sameAs = struct {
            fn of(fr: Frame, in: []const Frame) ?usize {
                for (in, 0..) |o, idx| if (std.meta.eql(o.hi, fr.hi)) return idx;
                return null;
            }
        }.of;
        const n_old = @min(old_chain.len, 16);
        var kept: [16]bool = @splat(false);
        for (chain, 0..) |frame, i| {
            const j = sameAs(frame, old_chain);
            if (j) |q| if (q < kept.len) {
                kept[q] = true;
            };
            // A new frame grows from its foot.
            const old_frame = if (j) |q| old_chain[q] else Frame{ .pc = frame.pc, .lo = frame.hi orelse frame.lo, .hi = frame.hi };
            const first = std.math.lerp(rows_of(old_frame.lo, window[0]), rows_of(frame.lo, window[0]), p_span) + slide;
            if (first >= @as(f32, @floatFromInt(slots))) break;
            const last = if (frame.hi) |hi| std.math.lerp(if (old_frame.hi) |oh| rows_of(oh, window[0]) else rows_of(hi, window[0]), rows_of(hi, window[0]), p_span) + slide else std.math.inf(f32);
            if (last < 0) continue;
            const open = last >= @as(f32, @floatFromInt(slots));
            const y1 = top + (@min(last, @as(f32, @floatFromInt(slots)) - 1) + 1) * m.row;
            // Named as the stop the panel shows has it: before the strike by the frame as it was.
            const name = if (j == null) spanName(u, rec, calls_is, i, frame.pc) else if (landed) spanName(u, rec, open_calls, i, if (i < named.len) named[i].pc else frame.pc) else spanName(u, rec, open_calls, j.?, old_chain[j.?].pc);
            // A new frame comes in as rsp's pin brings it; the newest is the new one from the pin's middle.
            spans[n_spans] = .{ .y0 = top + @max(first, 0) * m.row, .y1 = y1, .name = name, .newest = if (p_span < 0.5) (j != null and j.? == 0) or (j == null and i == 0 and old_chain.len == 0) else i == 0, .open = open, .shows = if (j == null and old_chain.len > 0) p_span else 1 };
            if (now.walking() and !jumped) if (j) |q| if (old_chain[q].lo == frame.lo) {
                const was_name = spanName(u, rec, calls_was, q, old_chain[q].pc);
                const is_name = spanName(u, rec, calls_is, i, frame.pc);
                if (!std.mem.eql(u8, was_name, is_name)) {
                    spans[n_spans].name = is_name;
                    spans[n_spans].was = was_name;
                }
            };
            n_spans += 1;
            if (n_spans == spans.len) break;
        }
        // A frame the step takes off shrinks to its foot as rsp's pin falls, and goes with it.
        for (old_chain[0..n_old], 0..) |o, q| if (!kept[q] and n_spans < spans.len and !jumped) {
            const hi = o.hi orelse continue;
            const first = std.math.lerp(rows_of(o.lo, window[0]), rows_of(hi, window[0]), p_span) + slide;
            const last = rows_of(hi, window[0]) + slide;
            if (last < 0 or first >= @as(f32, @floatFromInt(slots))) continue;
            spans[n_spans] = .{ .y0 = top + @max(first, 0) * m.row, .y1 = top + (@min(last, @as(f32, @floatFromInt(slots)) - 1) + 1) * m.row, .name = spanName(u, rec, calls_was, q, o.pc), .newest = q == 0 and p_span < 0.5, .open = false, .shows = 1 - p_span };
            n_spans += 1;
        };
        // rsp or rbp travelling alone keeps its place in the pin it leaves and
        // the one it joins: room there, closing and opening as it goes. It
        // sets off 18 f after rsp's strike (`time.pin`): 24 f to the next
        // row, 2 f a further row, 36 f at most.
        const goes = struct {
            fn of(n: cursors.Now, a: zt.Regs, b: zt.Regs, name: []const u8) f32 {
                if (n.resting()) return 1;
                // `tied`: as its plan travels it (`Now.pinGone`).
                if (n.pinGone(if (std.mem.eql(u8, name, "rsp")) 0 else 1)) |g| return g;
                const pin = time.pin;
                const rows_far: f32 = @floatFromInt(@abs(@as(i64, @bitCast((b.named(name) orelse 0) -% (a.named(name) orelse 0)))) / 8);
                const takes = @min(pin.row + pin.step_per_row * @max(rows_far - 1, 0), pin.row_max);
                // rsp's strike sets both off: rbp, struck first, goes with it.
                return cursors.standard(std.math.clamp((n.since(.cpu, ties.strikeDelay(n, index("rsp").?)) - pin.after) / takes, 0, 1));
            }
        }.of;
        const size = theme.size.mono.context;
        const lone: ?[]const u8 = if (travel.len == 1) travel[0] else null;
        // The offsets are from the rsp of the rows shown: they change with the slide, not before it.
        const rsp_shown = if (landed) is.rsp else was.rsp;
        // What each word is, where the recording says (`zt.telescope.slots`):
        // a register saved for the caller, a local, the process's first stack.
        // Of the rows of both windows: those sliding out keep theirs as they go.
        const roles_from = @min(window[0], window[1]) -% 16;
        const roles_n = slots + 4 + @abs(@as(i64, @bitCast(window[0] -% window[1]))) / 8;
        // Before the step and after it: a role that changes crossfades as memory strikes (12 f).
        var roles_buf: [2][80]zt.telescope.Slot = undefined;
        const roles = [2][]zt.telescope.Slot{
            zt.telescope.slots(now.before(), &was, roles_from, roles_buf[0][0..@min(roles_n, roles_buf[0].len)]) catch roles_buf[0][0..0],
            zt.telescope.slots(now.moment(), &is, roles_from, roles_buf[1][0..@min(roles_n, roles_buf[1].len)]) catch roles_buf[1][0..0],
        };
        // The words that point at other words of the window: `arc`s.
        var at_rows: std.ArrayList(hexdump.RowAt) = .empty;
        // Each with whether it is a saved rbp before the step and after it.
        var pointers: std.ArrayList(struct { hexdump.RowAt, [2]bool }) = .empty;
        var n: i64 = @as(i64, @intFromFloat(@floor(-slide))) - 1;
        while (n <= @as(i64, @intCast(slots)) - @as(i64, @intFromFloat(@floor(slide)))) : (n += 1) {
            const y = top + (@as(f32, @floatFromInt(n)) + slide) * m.row;
            if (y + m.row < body.y or y > box.h) continue;
            const addr = window[0] +% @as(u64, @bitCast(n * 8));
            // Not come in yet (`reveal`): the offset under the page (from past the pins to 172), the role with its row.
            const hide_offset = if (k.reveal) |rv| rv.hidden(placed.value(rv.offsets), (y - top) / m.row) else 0;
            const hide_role = if (k.reveal) |rv| rv.hidden(placed.value(rv.roles), (y - top) / m.row) else 0;
            // The page laid over them is opaque whatever the panel's own fade (a faded page over faded text leaves some).
            var page_u = u;
            page_u.at.pose.opacity = 1;
            defer if (hide_offset > 0) page_u.faded(hide_offset).fill(.{ .x = theme.metric.slot.lane_end, .y = y, .w = theme.metric.slot.offset + 4 - theme.metric.slot.lane_end, .h = m.row }, theme.color.page);
            // Who points here: a pin in the lane, landing with its link.
            const names = pins(u, now, is, was, addr, travel);
            var marks: rows.Marks = .{ .lead = lead, .first = now.writtenWatched(addr, 8, .memory, 0, watched_from, watched_to) };
            // Under `tied` the word a `pop`, a `ret` or a `leave` reads is read too (the recordings say no read there).
            const touched_here = if (touch) |tt| tt.addr & ~@as(u64, 7) == addr else false;
            if (watched_from == 0 and watched_to > 0 and (now.wasRead(addr, 8) or (touched_here and !touch.?.write)) and now.writeAge(addr, 8) != 0) {
                marks.read = 0;
                marks.read_shows = now.reading(.memory, 0);
            }
            // A word stored with the value it held (a `push rbp` over the old saved rbp): armed, and nothing struck;
            // in the introduction struck as any write, its mark gone by the step's end (nothing remembers it).
            if (touched_here and touch.?.write and now.walking() and now.writeAge(addr, 8) != 0) {
                const s_at = now.plan.at[1];
                if (now.introduction) {
                    marks.first = now.heat(0, null, now.time - s_at);
                    marks.first.corner = 0;
                    marks.first.level *= 1 - std.math.clamp((now.time - now.plan.advance) / @max(now.plan.total - now.plan.advance, 1.0 / 60.0), 0, 1);
                } else marks.first.arm = std.math.clamp((now.time - (s_at - time.strike.arm)) / time.stagger, 0, 1) * (1 - std.math.clamp((now.time - s_at) / time.quick, 0, 1));
            }
            const below_rsp: i64 = if (tied) @bitCast(addr -% bases[1].value(is)) else @bitCast(addr -% if (held) rsp_shown else is.rsp);
            map.row(.stack, addr, u, .{ .x = 0, .y = y, .w = box.w, .h = m.row });
            // `free`: above rsp, not yet reached: its address at 60%, its word faint.
            // A free word rsp reaches (a push, `sub rsp`) becomes a slot as memory strikes (12 f), never in a frame.
            // Under `tied` every word over rsp but a leaf's locals there (the red zone, its frame's).
            const k_free = (addr -% roles_from) / 8;
            // (A word a `push` is about to write has its role already, at the push's own stop: still free.)
            const free_was = (held or tied) and addr < was.rsp and !(tied and k_free < roles[0].len and roles[0][k_free].frame != null and roles[0][k_free].role == .local);
            const free_is = (held or tied) and addr < is.rsp and !(tied and k_free < roles[1].len and roles[1][k_free].frame != null and roles[1][k_free].role == .local);
            // `tied`: gained or released as rsp's pin reaches it (12 f).
            // A word the step writes over rsp (a push's, a call's, a store the line makes past the old rsp) is the frame's as its arm comes
            // (the touch's word as the touch lands): armed, struck, and then the pin climbs over it.
            const passed = if (touched_here and touch.?.write and now.walking() and now.plan.touch >= 0) now.time - now.plan.touch - time.tied.touch else if (tied and now.walking() and free_was and !free_is and now.writeAge(addr, 8) == 0) now.time - (now.plan.at[1] + now.writeDelay(addr, 8) - time.strike.arm) else if (pin_sp != null and !held) pinPassed(now, rows_of(was.rsp, window[0]), rows_of(is.rsp, window[0]), @as(f32, @floatFromInt(n))) else null;
            const turned = if (passed) |ago| std.math.clamp(ago / time.quick, 0, 1) else recast;
            const slot_shows: f32 = if (free_was == free_is or now.resting()) @as(f32, if (free_is) 0 else 1) else if (free_is) 1 - turned else turned;
            const offset_was: ?i64 = if (tied) @as(i64, @bitCast(addr -% bases[0].value(was))) else null;
            if (slot_shows < 1) rows.free(v.faded(1 - slot_shows), y, memory, addr, below_rsp, lead, .{ .name = "", .going = recast, .from_rsp = offset_was });
            if (slot_shows <= 0) {
                // `tied`: a free word is a place too (the touch of a push or a call goes to it).
                if (tied and y >= top - 1 and y + m.row <= box.h - m.pad + 1) {
                    ties.anchor(u, .{ .word = addr }, .{ .x = theme.metric.slot.address, .y = y, .w = 120, .h = m.row });
                    ties.anchor(u, .{ .slot_pin = addr }, .{ .x = theme.metric.slot.lane, .y = y, .w = theme.metric.slot.lane_end - theme.metric.slot.lane, .h = m.row });
                }
                continue;
            }
            const vs = v.faded(slot_shows);
            // A frame's name beside this row: the chain ends a character before it.
            var room_w = map.content(box.w);
            for (spans[0..n_spans]) |sp| {
                const mid = (sp.y0 + sp.y1) / 2;
                if (mid + m.row / 2 > y and mid - m.row / 2 < y + m.row) room_w = @min(room_w, rows.spanNameX(u, map.content(box.w), sp.name) - ui.advance(theme.size.mono.context) + theme.metric.slot.room);
            }
            var gap: f32 = 0;
            if (lone) |name| {
                const going = goes(now, was, is, name);
                const share: f32 = if (was.named(name) == addr) 1 - going else if (is.named(name) == addr) going else 0;
                gap = share * (u.width(.mono, size, name) + ui.advance(size));
            }
            const gapped = gap > 0 and names.names.len > 0 and names.shows > 0;
            if (gapped) pinGap(vs.faded(names.shows), y, names.names, lone.?, gap);
            const k_role = (addr -% roles_from) / 8;
            var role_at: [2]@TypeOf(roleName(u, .none, 0)) = undefined;
            for (&role_at, roles, [2]Recording.Moment{ now.before(), now.moment() }) |*r, of, mem| {
                const slot_is: zt.telescope.Slot = if (k_role < of.len) of[k_role] else .{};
                // The introduction names the way back too (its caption's words: `return address` would cut `main+50`).
                r.* = if (now.introduction and slot_is.role == .return_address) .{ .name = "the way back" } else slotName(u, slot_is, (Recording.word(mem, addr, 8) catch null) orelse 1);
            }
            const what: zt.telescope.Role = if (k_role < roles[1].len) roles[1][k_role].role else .none;
            const role = role_at[1];
            const role_was: rows.Role = .{ .name = role_at[0].name, .local = role_at[0].local, .going = if (passed != null) turned else recast, .from_rsp = if (tied) @bitCast(addr -% bases[0].value(was)) else @bitCast(addr -% was.rsp), .offset_going = recast };
            // At a run a word changes in place under an 8 f crossfade, as a register does.
            const ran = runFade(now, .memory);
            const word_was = Recording.word(now.before(), addr, 8) catch null;
            const word_is = Recording.word(now.moment(), addr, 8) catch null;
            const fades = ran < 1 and !std.meta.eql(word_was, word_is);
            if (fades) _ = rows.slot(vs.faded(1 - ran), y, room_w, now.before(), addr, below_rsp, &.{}, 0, marks, role.name, role.local, role_was);
            const hops = rows.slot(if (fades) vs.faded(ran) else vs, y, room_w, if (fades) now.moment() else now.shownAt(addr, 8), addr, below_rsp, if (gapped) &.{} else names.names, names.shows, marks, role.name, role.local, role_was);
            if (hide_role > 0) {
                // The role drawn, and the one it crossfades from while it does.
                const role_w = @max(if (role_was.going < 1) u.width(.mono, size, role_at[0].name) else 0, u.width(.mono, size, role.name));
                if (role_w > 0) page_u.faded(hide_role).fill(.{ .x = room_w - theme.metric.slot.room - role_w - 2, .y = y, .w = role_w + 4, .h = m.row }, theme.color.page);
            }
            // An arc's ends are rows on show (the row above the window, there for a slide, is not).
            if (y + m.row > top + 1 and y < box.h - m.pad - 1) at_rows.append(u.f.scratch, .{ .addr = addr, .y = y }) catch {};
            const what_was: zt.telescope.Role = if (k_role < roles[0].len) roles[0][k_role].role else .none;
            if (y + m.row > top + 1 and y < box.h - m.pad - 1) pointers.append(u.f.scratch, .{ .{ .addr = addr, .y = y }, .{ what_was == .saved and std.mem.eql(u8, what_was.saved, "rbp"), what == .saved and std.mem.eql(u8, what.saved, "rbp") } }) catch {};
            // Only a row on show is a place a tie can land.
            if (y >= top - 1 and y + m.row <= box.h - m.pad + 1) {
                ties.anchor(u, .{ .word = addr }, .{ .x = theme.metric.slot.address, .y = y, .w = if (hops.n > 0) hops.x[0] + hops.w[0] - theme.metric.slot.address else 120, .h = m.row });
                // Its value, where it may be an address: its first hop.
                if (hops.n > 0) if (if (fades) word_is else (Recording.word(now.shownAt(addr, 8), addr, 8) catch null)) |value| ties.show(u, value, .{ .x = hops.x[0], .y = y, .w = hops.w[0], .h = m.row }, .stack, addr, 0, box.w);
                ties.anchor(u, .{ .slot_pin = addr }, .{ .x = theme.metric.slot.lane, .y = y, .w = theme.metric.slot.lane_end - theme.metric.slot.lane, .h = m.row });
            }
        }
        if (k.part == .stack) map.window(.stack, .{ ways[0], ways[0] + 8 * (@as(u64, slots) -| 1) }, .{ ways[1], ways[1] + 8 * (@as(u64, slots) -| 1) }, p);
        // A frame's saved rbp is drawn by its span: its arc only in a step that touches it.
        var arcs: rows.Arcs = .{};
        for (pointers.items) |p_| {
            const word, const saved_was = p_;
            const saved = saved_was[1];
            const touched = now.writeAge(word.addr, 8) == 0 or now.wasRead(word.addr, 8);
            if (saved and saved_was[0] and !touched) continue;
            const before = arcs.n;
            hexdump.pointerArcs(&arcs, now, word.addr, word.y, at_rows.items, 8, .{ top - m.pad, box.h - m.pad }, false, false);
            if (arcs.n == before) continue;
            // Its step's alone: it goes with the advance (18 f), not in the next step's first frame.
            // And it comes as the step begins (12 f), not in its first frame.
            if ((saved or saved_was[0]) and touched) arcs.items[before].shows *= @min(1 - std.math.clamp((now.time - now.plan.advance) / time.read.out, 0, 1), if (now.resting()) 1 else std.math.clamp(now.time / time.quick, 0, 1));
            // A word becoming a saved rbp, or no longer one, with the step: its arc goes or comes as its role does (12 f).
            if (!touched and saved != saved_was[0]) arcs.items[before].shows *= if (saved) 1 - recast else recast;
        }
        arcs.draw(v, theme.metric.arc.stack_lanes);
        // Where the window is, for a link to a word outside it.
        const lane_at = u.at.xf.apply(.{ theme.metric.slot.lane, top });
        const row_px = u.at.xf.apply(.{ 0, top + m.row })[1] - lane_at[1];
        if (!ui.mapping) ties.of(u.f).stack_window = .{ .first = window[0], .slots = slots, .x = lane_at[0], .top = lane_at[1], .row = row_px };
        // The travelling tags: both of them at one word share a pin.
        var places: [2]f32 = undefined;
        var olds: [2]f32 = undefined;
        const slots_f: f32 = @floatFromInt(slots);
        for (travel, places[0..travel.len], olds[0..travel.len]) |name, *place, *old| {
            var at_old = @as(f32, @floatFromInt(@as(i64, @bitCast((was.named(name) orelse 0) -% window[0])))) / 8 + slide;
            const at_new = @as(f32, @floatFromInt(@as(i64, @bitCast((is.named(name) orelse 0) -% window[0])))) / 8 + slide;
            // `tied`: a pin from outside the window comes in at its edge (rbp in from the window's foot).
            if (tied) at_old = std.math.clamp(at_old, -1, slots_f);
            old.* = at_old;
            place.* = std.math.lerp(at_old, at_new, goes(now, was, is, name));
        }
        // `tied`: rsp's move on its pin as it travels, counting a row at a time, held to the advance and crossfading to the bare name (12 f).
        const amount_shows: f32 = if (tied and now.walking() and pin_sp != null and now.time >= now.plan.pins[0]) @min(std.math.clamp((now.time - now.plan.pins[0]) / time.strike.in, 0, 1), 1 - std.math.clamp((now.time - now.plan.advance) / time.quick, 0, 1)) else 0;
        for (travel, places[0..travel.len], olds[0..travel.len], 0..) |name, place, old, i| {
            if (i == 1 and @abs(places[0] - place) < 0.05) continue;
            if (place < (if (tied) @as(f32, -1) else -0.5) or place > (if (tied) slots_f else slots_f - 0.5)) continue;
            const both = i == 0 and travel.len == 2 and @abs(places[1] - place) < 0.05;
            // Alone, from its place among the names it leaves to its place among those it joins.
            const x = if (lone != null) std.math.lerp(pinPlace(u, pins(u, now, is, was, was.named(name) orelse 0, travel).names, name), pinPlace(u, pins(u, now, is, was, is.named(name) orelse 0, travel).names, name), goes(now, was, is, name)) else theme.metric.slot.lane;
            const names_: []const []const u8 = if (both) &.{ "rsp", "rbp" } else &.{name};
            if (amount_shows > 0 and std.mem.eql(u8, name, "rsp")) {
                const crossed = @abs(place - old);
                const total_rows = cursors.wordsApart(rec, now.stops[1], now.stops[0], "rsp");
                // Rows crossed, counted on its whole way (its start may be off the window).
                const count = std.math.clamp(@ceil(goes(now, was, is, "rsp") * total_rows - 0.01), 1, total_rows);
                const bytes: u64 = @intFromFloat(count * 8);
                pinAmount(u, x, top + place * m.row, names_, u.print("{s}{s}{x}", .{ if (is.rsp < was.rsp) "-" else "+", rows.hexMark(bytes), bytes }), amount_shows);
                // The rows it crossed, a 3-unit vermilion bracket in the outer arc lane.
                if (crossed > 0.05) u.faded(amount_shows).bracket(theme.metric.arc.lanes[0], top + @min(place, old) * m.row + 2, top + @max(place, old) * m.row - 2, theme.mark(.write).solid, theme.metric.bracket.tie, 1, false);
            } else if (lone != null and joinsBefore(pins(u, now, is, was, is.named(name) orelse 0, travel).names, name)) {
                // Joining a pin in front of a name there (rbp onto rsp's row): its own head goes as it lands
                // (the joined pin has one head, after the last name), never in the advance's frame.
                const y_pin = top + place * m.row;
                u.text(.mono_bold, size, x, theme.baseline(y_pin, m.row, size), name, t.primary);
                const head = theme.metric.pin;
                const hx = x + u.width(.mono, size, name) + head.row_gap;
                const mid = y_pin + m.row / 2;
                const v_head = u.faded(1 - goes(now, was, is, name));
                sk.draw.polygon(u.f, &.{ .{ hx + head.row_head[0], mid }, .{ hx, mid - head.row_head[1] / 2 }, .{ hx, mid + head.row_head[1] / 2 } }, v_head.at.pen(.{ .fill = ui.rgb(theme.color.region.stack) }));
            } else u.pinRow(x, top + place * m.row, names_, theme.color.region.stack);
        }
        for (spans[0..n_spans], 0..) |sp, i| if (sp.shows > 0) {
            const sv = if (k.reveal) |rv| v.faded(1 - rv.hidden(placed.value(rv.spans), @floatFromInt(i))) else v;
            if (sp.was) |was_name| {
                rows.span(sv.faded(1 - renamed), map.content(box.w), sp.y0, sp.y1, was_name, sp.newest, sp.open);
                rows.span(sv.faded(renamed), map.content(box.w), sp.y0, sp.y1, sp.name, sp.newest, sp.open);
            } else rows.span(sv.faded(sp.shows), map.content(box.w), sp.y0, sp.y1, sp.name, sp.newest, sp.open);
        };
        veiled(u, box, now.veil);
        if (k.part == .stack) map.strip(.stack, u, box);
    }

    /// A slot's role as the catalogue writes it: `saved rbx` (dim); a
    /// local's name (primary, `+8` a word into it); `argc`, `argv[0]`,
    /// `argv end`, `envp end`, `auxv` (dim). A return address needs none:
    /// its chain is code, named. `word`: what the slot holds (0 ends argv and envp).
    pub fn roleName(u: ui.Ui, role: zt.telescope.Role, word: u64) struct { name: []const u8, local: bool = false } {
        return switch (role) {
            .none, .return_address => .{ .name = "" },
            // The stack protector's copy is the `canary`, not a register saved.
            .saved => |r| .{ .name = if (std.mem.eql(u8, r, "canary")) "canary" else u.print("saved {s}", .{r}) },
            .local => |l| .{ .name = if (l.offset > 0) u.print("{s}+{x}", .{ l.name, @as(u32, @intCast(l.offset)) }) else if (l.offset == -4 and l.size == 4) u.print("{s}, high half", .{l.name}) else if (l.offset < 0) u.print("{s}, from byte {d}", .{ l.name, -l.offset }) else l.name, .local = true },
            .argc => .{ .name = "argc" },
            .argv => |i| .{ .name = if (word == 0) "argv end" else u.print("argv[{d}]", .{i}) },
            .envp => |i| .{ .name = if (word == 0) "envp end" else u.print("envp[{d}]", .{i}) },
            .auxv => |i| .{ .name = if (i == 0) "auxv" else "" },
        };
    }

    /// A slot's role (`roleName`), with the other locals that share its word: `i, n`.
    pub fn slotName(u: ui.Ui, slot: zt.telescope.Slot, word: u64) @TypeOf(roleName(u, .none, 0)) {
        if (slot.role != .local or slot.also[0] == null) return roleName(u, slot.role, word);
        var out: []const u8 = slot.role.local.name;
        for (slot.also) |a| if (a) |l| {
            out = u.print("{s}, {s}", .{ out, l.name });
        };
        return .{ .name = out, .local = true };
    }

    /// A row pin of `names` with rsp's move on it (`amount`, `-18`, bold in
    /// write's vermilion), `shows` of the amount; its head after it.
    fn pinAmount(u: ui.Ui, x: f32, y: f32, names: []const []const u8, amount: []const u8, shows: f32) void {
        const size = theme.size.mono.context;
        const p = theme.metric.pin;
        const shown = if (names.len == 2) u.print("{s} {s}", .{ names[0], names[1] }) else names[0];
        const base = theme.baseline(y, m.row, size);
        u.text(.mono_bold, size, x, base, shown, t.primary);
        const end = x + u.width(.mono, size, shown);
        u.faded(shows).text(.mono_bold, size, end + ui.advance(size), base, amount, theme.mark(.write).solid);
        const hx = end + shows * (ui.advance(size) + u.width(.mono, size, amount)) + p.row_gap;
        const mid = y + m.row / 2;
        sk.draw.polygon(u.f, &.{ .{ hx + p.row_head[0], mid }, .{ hx, mid - p.row_head[1] / 2 }, .{ hx, mid + p.row_head[1] / 2 } }, u.at.pen(.{ .fill = ui.rgb(theme.color.region.stack) }));
    }

    /// Where `name` goes in a row pin of `others` and it, in the registers' order.
    /// Whether `name` joining the pin of `others` comes before one of them (pwndbg's order).
    fn joinsBefore(others: []const []const u8, name: []const u8) bool {
        for (others) |o| if (index(o).? > index(name).?) return true;
        return false;
    }

    fn pinPlace(u: ui.Ui, others: []const []const u8, name: []const u8) f32 {
        const size = theme.size.mono.context;
        var x: f32 = theme.metric.slot.lane;
        for (others) |o| if (index(o).? < index(name).?) {
            x += u.width(.mono, size, o) + ui.advance(size);
        };
        return x;
    }

    /// A row pin of `names` with room `gap` wide where `name` goes in it.
    fn pinGap(u: ui.Ui, y: f32, names: []const []const u8, name: []const u8, gap: f32) void {
        const size = theme.size.mono.context;
        const p = theme.metric.pin;
        var x: f32 = theme.metric.slot.lane;
        var gapped = false;
        for (names) |o| {
            if (!gapped and index(o).? > index(name).?) {
                x += gap;
                gapped = true;
            }
            u.text(.mono_bold, size, x, theme.baseline(y, m.row, size), o, t.primary);
            x += u.width(.mono, size, o) + ui.advance(size);
        }
        if (!gapped) x += gap;
        const hx = x - ui.advance(size) + p.row_gap;
        const mid = y + m.row / 2;
        sk.draw.polygon(u.f, &.{ .{ hx + p.row_head[0], mid }, .{ hx, mid - p.row_head[1] / 2 }, .{ hx, mid + p.row_head[1] / 2 } }, u.at.pen(.{ .fill = ui.rgb(theme.color.region.stack) }));
    }

    /// Seconds since rsp's pin, going from row `from` to row `to` of the
    /// window, passed the middle of row `n` (negative before it): when a word
    /// it reaches is gained, or one it leaves released. Null where it does not cross it.
    fn pinPassed(now: cursors.Now, from: f32, to: f32, n: f32) ?f32 {
        if (from == to) return null;
        const q = (n + 0.5 - from) / (to - from);
        if (q < 0 or q > 1) return null;
        const run = now.plan.gait == .run;
        const start: f32 = if (run) 0 else now.plan.pins[0];
        // When its eased way reaches q.
        var lo: f32 = 0;
        var hi: f32 = 1;
        for (0..16) |_| {
            const mid = (lo + hi) / 2;
            if ((if (run) cursors.standard(mid) else cursors.glide(mid)) < q) lo = mid else hi = mid;
        }
        return now.time - (start + lo * cursors.pinTime(@abs(to - from), run));
    }

    /// Whether a window of `slots` going from word `a` to word `b` goes
    /// farther than its own height: it fades, and does not scroll.
    fn far(a: u64, b: u64, slots: usize) bool {
        return @abs(@as(i64, @bitCast(a -% b))) > 8 * @as(u64, slots);
    }

    /// The first step, from `age` steps ago back, in which the window faded
    /// to a new place (as many as the cursor remembers when none did).
    fn watched(now: cursors.Now, slots: usize, age: usize) usize {
        const rec = now.rec;
        for (age..now.stops.len - 1) |a| {
            // The index's registers: reading them from the trace was most of a frame's time.
            const to = rec.registers[@min(now.stops[a], rec.end())];
            const from = rec.registers[@min(now.stops[a + 1], rec.end())];
            if (far(windowAt(now, to, slots, a), windowAt(now, from, slots, a + 1), slots)) return a;
        }
        return now.stops.len;
    }

    /// The first word a window of `slots` shows, `skip` steps back: rsp,
    /// or within [rsp, rbp+16) (the frame, with its saved rbp and its way
    /// back) so that the word the newest of the last three steps wrote or
    /// read there is in the window's middle.
    fn windowAt(now: cursors.Now, regs: zt.Regs, slots: usize, skip: usize) u64 {
        const frame_end = regs.rbp +% 16;
        // `tied`: from its headroom, two `free` words over rsp (the room a push, a call or a `sub rsp` takes).
        const top = if (now.annotation == .tied) regs.rsp -% 16 else regs.rsp;
        if (frame_end <= regs.rsp or frame_end - regs.rsp > 8 * 64) return top;
        const words = (frame_end - top) / 8;
        if (words <= slots) return top;
        for (skip..skip + 3) |age| {
            if (age + 1 >= now.stops.len) break;
            for ([_][]const Recording.Span{ now.rec.written(now.stops[age + 1], now.stops[age]), now.rec.read(now.stops[age + 1], now.stops[age]) }) |spans| {
                var k = spans.len;
                while (k > 0) {
                    k -= 1;
                    const a = spans[k].addr;
                    if (a < top or a >= frame_end) continue;
                    const word = (a - top) / 8;
                    const first = @min(word -| (slots - 1) / 2, words - slots);
                    return top + 8 * first;
                }
            }
        }
        return top;
    }

    /// Under `tied`, a window of `slots` from the headroom over `regs`'s rsp
    /// that has word `addr` in its middle: where it scrolls before a touch.
    fn windowOver(regs: zt.Regs, slots: usize, addr: u64) u64 {
        const top = regs.rsp -% 16;
        if (addr < top) return addr & ~@as(u64, 7);
        const words = (@max(regs.rbp +% 16, addr + 8) - top) / 8;
        return top + 8 * @min(((addr - top) / 8) -| (slots - 1) / 2, words -| slots);
    }

    const Pins = struct { names: []const []const u8, shows: f32 };

    /// The registers whose value is `addr`: before the step, and after it
    /// once their link has landed (`ties.pinShows`).
    fn pins(u: ui.Ui, now: cursors.Now, is: zt.Regs, was: zt.Regs, addr: u64, apart: []const []const u8) Pins {
        var out: std.ArrayList([]const u8) = .empty;
        var shows: f32 = 0;
        for (theme.metric.all_registers[0..16]) |name| {
            // Those drawn apart, travelling.
            if (for (apart) |a| {
                if (std.mem.eql(u8, a, name)) break true;
            } else false) continue;
            const i = index(name).?;
            const before = was.named(name) == addr;
            const after = is.named(name) == addr;
            if (!before and !after) continue;
            const s = ties.pinShows(now, i, .slot);
            const this = if (before and after) 1 else if (after) s.new else s.old;
            if (this < 0.5) continue;
            out.append(u.f.scratch, name) catch break;
            shows = @max(shows, this);
        }
        return .{ .names = out.items, .shows = shows };
    }
};

pub const Backtrace = struct {
    cursor: cursors.Cursor,
    stage: *const Stage,
    focus: bool = false,
    /// The `backtrace` lens: in the band, as its drawing.
    lens: bool = false,

    pub fn draw(b: *const Backtrace, f: *sk.Frame, placed: anim.Placed) void {
        const box = b.stage.box(placed, if (b.lens) .band else .backtrace);
        if (box.h < m.tag) return;
        const u = if (b.lens) at(f, placed, box).faded(placed.value(b.stage.drawing)) else at(f, placed, box);
        const now = b.cursor.now(placed);
        backtraceRows(u, now, b.cursor.rec, box, b.focus, "");
        veiled(u, box, now.veil);
    }
};

/// A backtrace's panel and rows in `u`'s `box` (the panel, a lens's
/// drawing, the calls lens's view: its tag's note after `prefix`).
/// A frame is its words on the stack: the chain changes with memory. The
/// frames both chains have (the same way back, counted from the oldest)
/// slide to their new depth, as rows making room; those that end fade out
/// first, those that begin fade in after. What a kept row says that
/// changes (its depth, its pc's offset, its line) crossfades over the 12 f
/// before the advance, as a stack span's name does; the newest's wash goes
/// from one row to the other the same way. Nothing changes in a frame.
pub fn backtraceRows(u: ui.Ui, now: cursors.Now, rec: *const Recording, box: Rect, focus: bool, prefix: []const u8) void {
    var new_buf: [24]Frame = undefined;
    var old_buf: [24]Frame = undefined;
    const chains = [2][]Frame{ frames(rec, now.stops[1], &old_buf), frames(rec, now.stops[0], &new_buf) };
    var shared: usize = 0;
    while (shared < @min(chains[0].len, chains[1].len) and chains[0][chains[0].len - 1 - shared].pc == chains[1][chains[1].len - 1 - shared].pc) shared += 1;
    // The newest frame's pc is the step's: it is the same frame whatever its offset.
    if (shared < @min(chains[0].len, chains[1].len) and chains[0].len == chains[1].len and shared + 1 == chains[0].len) shared += 1;
    const since = if (now.walking()) now.since(.memory, 0) else if (now.landed(.memory, 0)) std.math.inf(f32) else -std.math.inf(f32);
    const leave = std.math.clamp(since / time.quick, 0, 1);
    const slide = cursors.glide(std.math.clamp((since - time.quick / 2.0) / time.move, 0, 1));
    const arrive = std.math.clamp((since - time.quick / 2.0 - time.move) / time.quick, 0, 1);
    const renamed = now.renaming();
    const room = rowsOf(box);
    map.measure(.backtrace, @max(chains[0].len, chains[1].len));
    const notes = [2][]const u8{ u.print("{s}{s}", .{ prefix, newestAtBottom(u, chains[0].len, room) }), u.print("{s}{s}", .{ prefix, newestAtBottom(u, chains[1].len, room) }) };
    const renote = !std.mem.eql(u8, notes[0], notes[1]);
    const body = u.panel(box.w, box.h, "backtrace", .{ .focus = focus, .note = if (renote) "" else notes[1] });
    if (renote) {
        u.faded(1 - slide).tagNote(box.w, notes[0]);
        u.faded(slide).tagNote(box.w, notes[1]);
    }
    clipBody(u, box);
    defer u.unclip();
    const opens = [2][]const Recording.Call{ rec.stack(u.f.scratch, now.stops[1]), rec.stack(u.f.scratch, now.stops[0]) };
    const top = body.y + m.pad;
    // Newest at the bottom, `#0` last: a frame's row is its place from
    // the oldest, less the oldest that do not fit (dropped from the top).
    const dropped = [2]usize{ chains[0].len -| room, chains[1].len -| room };
    const Row = struct { depth: usize, name: []const u8, args: []const u8, where: []const u8 };
    for (chains, 0..) |chain, side| {
        const shows = if (side == 0) 1 - leave else arrive;
        for (chain, 0..) |frame, i| {
            const from_end = chain.len - 1 - i;
            const kept = from_end < shared;
            // A frame both have is drawn once, from the old chain to its place in the new.
            if (kept and side == 1) continue;
            var at_row = @as(f32, @floatFromInt(from_end)) - @as(f32, @floatFromInt(dropped[side]));
            const here: Row = .{ .depth = i, .name = ui.symbol(u, rec.strings.get(frame.pc) orelse u.print("{x}", .{frame.pc})), .args = callArguments(u, rec, opens[side], i, frame.pc), .where = frameWhere(u, rec, now.marks[side], i, frame.pc) };
            if (!kept) {
                if (shows <= 0 or at_row <= -1 or at_row >= @as(f32, @floatFromInt(room))) continue;
                rows.callRow(u.faded(shows), top + at_row * m.row, box.w, here.depth, here.name, here.args, here.where, here.depth == 0);
                continue;
            }
            const to = chains[1].len - 1 - from_end;
            const next = chains[1][to];
            const there: Row = .{ .depth = to, .name = ui.symbol(u, rec.strings.get(next.pc) orelse u.print("{x}", .{next.pc})), .args = callArguments(u, rec, opens[1], to, next.pc), .where = frameWhere(u, rec, now.marks[1], to, next.pc) };
            at_row = std.math.lerp(at_row, @as(f32, @floatFromInt(from_end)) - @as(f32, @floatFromInt(dropped[1])), slide);
            if (at_row <= -1 or at_row >= @as(f32, @floatFromInt(room))) continue;
            const y = top + at_row * m.row;
            // The wash where the row is the newest, going and coming with the words.
            const washed = @as(f32, if (here.depth == 0) 1 - renamed else 0) + @as(f32, if (there.depth == 0) renamed else 0);
            if (washed > 0) rows.callCurrent(u.faded(washed), y, box.w);
            const same = here.depth == there.depth and std.mem.eql(u8, here.name, there.name) and std.mem.eql(u8, here.args, there.args) and std.mem.eql(u8, here.where, there.where);
            if (same) {
                rows.callLabels(u, y, box.w, there.depth, there.name, there.args, there.where, there.depth == 0);
            } else {
                rows.callLabels(u.faded(1 - renamed), y, box.w, here.depth, here.name, here.args, here.where, here.depth == 0);
                rows.callLabels(u.faded(renamed), y, box.w, there.depth, there.name, there.args, there.where, there.depth == 0);
            }
        }
    }
}

/// A backtrace's tag note: `newest at the bottom`, and how many of the
/// oldest a panel of `room` rows leaves out above.
pub fn newestAtBottom(u: ui.Ui, total: usize, room: usize) []const u8 {
    return if (total > room) u.print("newest at the bottom \u{00b7} {d} more above", .{total - room}) else "newest at the bottom";
}

test "the flags' bits" {
    try std.testing.expectEqual(@as(?usize, 17), index("eflags"));
}