summaryrefslogtreecommitdiff
path: root/anim/src/rows.zig
blob: 0e4f58cad84f501b9ff62879c91a0e95598a38cd (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
//! The catalogue's rows (design/README.md, "2. Rows"): every row is 24
//! high and one line, made of atoms, and none wraps: what does not fit is
//! cut at its far end and says so. A row draws what it is given, in the
//! states it is given; the panels (`context.zig`, `disasm.zig`,
//! `source.zig`, `hexdump.zig`) read the recording and the cursor and say
//! which. x is from the panel's left edge, y is the row's top.
const std = @import("std");
const sk = @import("sketch");
const zt = @import("ztrace");
const ui = @import("ui.zig");
const Recording = @import("Recording.zig");
const theme = ui.theme;
const Rect = ui.Rect;
const t = theme.color.text;
const m = theme.metric.context;
const size = theme.size.mono.context;
const adv = size * 3 / 5;
const row_h = m.row;

/// What an address into `region` is inked in.
pub fn ink(region: zt.telescope.Region) u24 {
    const c = theme.color.region;
    return switch (region) {
        .none => c.number,
        .code => c.code_,
        // Writable and executable: its region's ink (data's, here) and an underline.
        .rwx => c.data,
        .stack => c.stack,
        .heap => c.heap,
        .data => c.data,
        .rodata => c.rodata,
    };
}

pub fn regionOf(moment: Recording.Moment, value: u64) zt.telescope.Region {
    return zt.telescope.region(moment, value) catch .none;
}

pub fn baseline(y: f32) f32 {
    return theme.baseline(y, row_h, size);
}

pub const NumberFormat = enum { hex, unsigned, signed, float };

pub fn numberText(buf: []u8, octets: []const u8, format: NumberFormat) []const u8 {
    var value: u64 = 0;
    std.debug.assert(octets.len == 1 or octets.len == 2 or octets.len == 4 or octets.len == 8);
    for (octets, 0..) |byte, i| value |= @as(u64, byte) << @intCast(i * 8);
    return switch (format) {
        .hex => switch (octets.len) {
            1 => std.fmt.bufPrint(buf, "{x:0>2}", .{value}),
            2 => std.fmt.bufPrint(buf, "{x:0>4}", .{value}),
            4 => std.fmt.bufPrint(buf, "{x:0>8}", .{value}),
            else => std.fmt.bufPrint(buf, "{x:0>16}", .{value}),
        },
        .unsigned => std.fmt.bufPrint(buf, "{d}", .{value}),
        .signed => blk: {
            const shift: u6 = @intCast(64 - octets.len * 8);
            const signed: i64 = @bitCast(value << shift);
            break :blk std.fmt.bufPrint(buf, "{d}", .{signed >> shift});
        },
        .float => if (octets.len == 4) std.fmt.bufPrint(buf, "{e}", .{@as(f32, @bitCast(@as(u32, @truncate(value))))}) else if (octets.len == 8) std.fmt.bufPrint(buf, "{e}", .{@as(f64, @bitCast(value))}) else return "—",
    } catch "?";
}

/// Sixteen octets, grouped as little-endian values; pointer hits use the same geometry as hex rows.
pub fn wordsAt(u: ui.Ui, y: f32, addr: u64, values: *const [16]u8, known: *const [16]bool, unit: u8, format: NumberFormat, moment: Recording.Moment) f32 {
    std.debug.assert(unit == 1 or unit == 2 or unit == 4 or unit == 8);
    _ = u.address(theme.metric.bytes.address, baseline(y), addr, .{ .ink = ui.rgb(ink(regionOf(moment, addr))) });
    var x = theme.metric.bytes.first + addressRoom(addr);
    var at_byte: usize = 0;
    while (at_byte < 16) : (at_byte += unit) {
        const octets = values[at_byte..][0..unit];
        const captured = std.mem.indexOfScalar(bool, known[at_byte..][0..unit], false) == null;
        var buf: [64]u8 = undefined;
        const text = if (captured) numberText(&buf, octets, format) else "?";
        const digits: usize = switch (format) {
            .hex => unit * 2,
            .unsigned => if (unit == 8) 20 else if (unit == 4) 10 else if (unit == 2) 5 else 3,
            .signed => if (unit == 8) 20 else if (unit == 4) 11 else if (unit == 2) 6 else 4,
            .float => if (unit == 8) 25 else 16,
        };
        const width = @as(f32, @floatFromInt(digits)) * adv;
        const value = if (unit == 8) std.mem.readInt(u64, octets[0..8], .little) else 0;
        const pointer = captured and unit == 8 and format != .float and regionOf(moment, value) != .none;
        u.text(.mono, size, x, baseline(y), text, if (pointer) ink(regionOf(moment, value)) else t.primary);
        if (pointer) u.hitAddress(value, .{ .x = x, .y = y, .w = width, .h = row_h });
        x += width + adv * 2;
    }
    return x;
}

test "memory scalar formats preserve byte order, sign and width" {
    var buf: [64]u8 = undefined;
    try std.testing.expectEqualStrings("1234", numberText(&buf, &.{ 0x34, 0x12 }, .hex));
    try std.testing.expectEqualStrings("-1", numberText(&buf, &.{ 255, 255 }, .signed));
    try std.testing.expectEqualStrings("18446744073709551615", numberText(&buf, &@as([8]u8, @splat(255)), .unsigned));
    try std.testing.expectEqualStrings("-9223372036854775808", numberText(&buf, &.{ 0, 0, 0, 0, 0, 0, 0, 128 }, .signed));
    try std.testing.expectEqualStrings("1e0", numberText(&buf, &.{ 0, 0, 128, 63 }, .float));
}

/// The marks on a chain's hops.
pub const Marks = struct {
    /// The first hop: a register (or a word) written: armed, struck, held.
    first: ui.Heat = .none,
    /// A later hop, the memory under a pointer that did not change: the
    /// turned corner sits on that hop alone.
    changed: ?usize = null,
    changed_heat: ui.Heat = .ember,
    /// A hop read, and how much its frame shows.
    read: ?usize = null,
    read_shows: f32 = 0,
    /// `extend`: seconds since the first hop was struck; the hops after it
    /// are followed again 4 f apart, each fading in over 6 f.
    extend: ?f32 = null,
    /// The first hop's `lead` (a column of addresses).
    lead: usize = 0,
    /// How much the hops after the first show: they fade out as the memory
    /// they read is about to change (`Now.following`).
    hops: f32 = 1,
    /// How many hops at most: a `tied` annotation's register is its first value (`rax 405010`).
    most: usize = 6,
};

/// `chain` of a memory access narrower than a word: its address, then what
/// the access reads there at its width (`7fffffffecc4 ◂ 15`), the marks
/// as `chain` takes them (`first`, `read` on the address; `changed` 1 on the value).
pub fn narrow(u: ui.Ui, x: f32, y: f32, moment: Recording.Moment, addr: u64, len: u64, room: f32, marks: Marks) Hops {
    const base = baseline(y);
    const w = ui.Value.of(addr, true).width();
    const at_addr: Rect = .{ .x = x, .y = y, .w = w, .h = row_h };
    var face_ink: ui.Ink = .{ .ink = ui.rgb(ink(regionOf(moment, addr))) };
    if (u.written(at_addr, marks.first)) |struck| face_ink = struck;
    if (marks.read == 0) u.read(at_addr, marks.read_shows);
    _ = u.address(x, base, addr, .{ .ink = face_ink.ink, .face = face_ink.face, .lead = marks.lead });
    var hops: Hops = .{ .n = 1, .end = x + w };
    hops.x[0] = x;
    hops.w[0] = w;
    var raw: [8]u8 = @splat(0);
    var known: [8]bool = @splat(false);
    moment.read(addr, raw[0..@min(len, 8)], known[0..@min(len, 8)]) catch return hops;
    if (std.mem.indexOfScalar(bool, known[0..@min(len, 8)], false) != null) return hops;
    const value = std.mem.readInt(u64, &raw, .little);
    const shown = ui.Value.of(value, false);
    if (hops.end + m.arrow_w + shown.width() > room) return hops;
    const at = u.arrow(hops.end, y + row_h / 2, .holds);
    const marked: Rect = .{ .x = at, .y = y, .w = shown.width(), .h = row_h };
    var value_ink: ui.Ink = .{ .ink = ui.rgb(t.primary) };
    if (marks.changed == 1) if (u.written(marked, marks.changed_heat)) |struck| {
        value_ink = struck;
    };
    _ = u.value(at, base, value, false, value_ink);
    hops.x[1] = at;
    hops.w[1] = shown.width();
    hops.n = 2;
    hops.end = at + shown.width() + if (shown.decimal) 8 + @as(f32, @floatFromInt(std.fmt.count("{d}", .{value}))) * adv else 0;
    return hops;
}

/// Where a chain's hops were drawn: x and width of each one's digits.
pub const Hops = struct {
    x: [6]f32 = undefined,
    w: [6]f32 = undefined,
    n: usize = 0,
    end: f32 = 0,
};

/// `chain`: a telescope, `address (points address)* (holds value)?`, of
/// `value` at `moment`, from `x` on the row at `y`, cut where `room`
/// ends. A code address ends it with its name, a string in quotes; depth
/// is the recording's. Cut at its far end: a string is shortened first,
/// then the chain ends early in `more`; nothing is taken from the middle.
pub fn chain(u: ui.Ui, x: f32, y: f32, moment: Recording.Moment, value: u64, room: f32, marks: Marks) Hops {
    var links_buf: [6]zt.telescope.Link = undefined;
    var text_buf: [256]u8 = undefined;
    const links = zt.telescope.chase(moment, value, &links_buf, &text_buf) catch return .{};
    const base = baseline(y);
    const mid = y + row_h / 2;
    var hops: Hops = .{};
    var at = x;
    for (links[0..@min(links.len, marks.most)], 0..) |link, i| {
        const pointer = link.region != .none;
        const shown = ui.Value.of(link.value, pointer);
        const w = shown.width();
        // The hops after a struck first one are followed again, one at a time.
        const followed: f32 = if (marks.extend) |e| std.math.clamp((e - @as(f32, @floatFromInt(i -| 1)) * theme.time.extend) / (6.0 / 60.0), 0, 1) else 1;
        const v = if (i > 0) u.faded(followed * marks.hops) else u;
        if (i > 0) {
            const named: f32 = if (link.region == .code and link.text.len > 0 and !link.string) 10 + @as(f32, @floatFromInt(link.text.len)) * adv else 0;
            // Room for it, and for saying there is more.
            if (pointer and at + m.arrow_w + w + named + 40 > room) {
                _ = v.arrow(at, mid, .more);
                break;
            }
            if (!pointer and at + m.arrow_w + w > room) {
                // The value it ends on has no room: it says so.
                if (at + 2 * adv <= room) v.text(.mono, size, at + 4, base, "\u{2026}", t.faint);
                break;
            }
            at = v.arrow(at, mid, if (pointer) .points else .holds);
        }
        const marked: Rect = .{ .x = at, .y = y, .w = w, .h = row_h };
        var face_ink: ui.Ink = .{ .ink = ui.rgb(if (pointer) ink(link.region) else t.primary) };
        if (i == 0) {
            if (v.written(marked, marks.first)) |struck| face_ink = struck;
        } else if (marks.changed == i) {
            if (v.written(marked, marks.changed_heat)) |struck| face_ink = struck;
        }
        if (marks.read == i) v.read(marked, marks.read_shows);
        if (pointer) {
            _ = v.address(at, base, link.value, .{ .ink = face_ink.ink, .face = face_ink.face, .lead = if (i == 0) marks.lead else 0, .rwx = link.region == .rwx });
        } else if (i == 0 and at + w > room) {
            // A word too long for its row's room (a stack word beside its role): cut, with `…`.
            const all = u.print("{s}{s}", .{ shown.prefix, shown.digits() });
            const fits: usize = @intFromFloat(std.math.clamp((room - at) / adv, 2, @as(f32, @floatFromInt(all.len))));
            v.text(face_ink.face, size, at, base, u.print("{s}\u{2026}", .{all[0 .. fits - 1]}), face_ink.ink);
            at += @as(f32, @floatFromInt(fits)) * adv;
            hops.x[0] = at - @as(f32, @floatFromInt(fits)) * adv;
            hops.w[0] = @as(f32, @floatFromInt(fits)) * adv;
            hops.n = 1;
            break;
        } else _ = v.value(at, base, link.value, false, face_ink);
        if (hops.n < hops.x.len) {
            hops.x[hops.n] = at;
            hops.w[hops.n] = w;
            hops.n += 1;
        }
        at += w;
        if (!pointer and shown.decimal) at += 8 + @as(f32, @floatFromInt(std.fmt.count("{d}", .{link.value}))) * adv;
        if (link.text.len == 0) {
            // Still a pointer where the recording stopped following.
            if (i + 1 == links.len and pointer and link.region != .code and link.region != .rwx and at + m.arrow_w + 24 <= room) at = v.arrow(at, mid, .more);
            continue;
        }
        if (link.string) {
            // What a pointer leads to, when it is text: quoted, cut to the room
            // there is (never under six characters), with `…` and no closing quote.
            const fits: usize = @intFromFloat(std.math.clamp((room - at - m.arrow_w) / adv, 0, 4096));
            if (fits < @as(usize, @min(m.string_min, link.text.len)) + 2) break;
            at = v.arrow(at, mid, .holds);
            const whole = link.text.len + 2 <= fits;
            const text = if (whole) u.print("\"{s}\"", .{link.text}) else u.print("\"{s}\u{2026}", .{link.text[0 .. fits - 2]});
            v.text(.mono, size, at, base, text, theme.color.string);
            at += @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(text) catch text.len)) * adv;
        } else {
            // A code address's name.
            const name = ui.symbol(u, link.text);
            if (room - at - 10 >= 3 * adv) {
                const cut = fitted(u, name, room - at - 10);
                v.text(.mono, size, at + 10, base, cut, t.primary);
                at += 10 + u.width(.mono, size, cut);
            }
        }
        break;
    }
    hops.end = at;
    return hops;
}

/// The cell a mark goes on for `value` drawn at `x` in a row at `y`.
pub fn cell(x: f32, y: f32, moment: Recording.Moment, value: u64) Rect {
    return .{ .x = x, .y = y, .w = ui.Value.of(value, regionOf(moment, value) != .none).width(), .h = row_h };
}

/// `reg`: a register's name (dim) 12 in, its chain from 72, room to 12
/// from the edge `w`.
pub fn reg(u: ui.Ui, y: f32, w: f32, name: []const u8, moment: Recording.Moment, value: u64, marks: Marks) Hops {
    u.text(.mono, size, m.side, baseline(y), name, t.dim);
    return chain(u, m.chain_x, y, moment, value, w - m.side, marks);
}

/// `registers` `quiet`: a register the scene never changes, in its cell
/// at `x`: its name faint, its value 48 in, in its ink; a pointer's chain
/// cut to `more` at once (a code address alone: its name is on the map),
/// framed as read while a step reads it (`read_shows`).
pub fn quiet(u: ui.Ui, x: f32, y: f32, name: []const u8, moment: Recording.Moment, value: u64, read_shows: f32) Hops {
    u.text(.mono, size, x, baseline(y), name, t.faint);
    const vx = x + theme.metric.registers.quiet_value;
    const region = regionOf(moment, value);
    const pointer = region != .none;
    const shown = ui.Value.of(value, pointer);
    if (read_shows > 0) u.read(.{ .x = vx, .y = y, .w = shown.width(), .h = row_h }, read_shows);
    var hops: Hops = .{ .n = 1, .end = vx + shown.width() };
    hops.x[0] = vx;
    hops.w[0] = shown.width();
    if (pointer) {
        _ = u.address(vx, baseline(y), value, .{ .ink = ui.rgb(ink(region)), .rwx = region == .rwx });
        if (region != .code) hops.end = u.arrow(hops.end, y + row_h / 2, .more) + 24;
    } else _ = u.value(vx, baseline(y), value, false, .{ .ink = ui.rgb(t.primary) });
    return hops;
}

/// The flags, in rip's row: their names, the value.
pub const Flag = struct { name: []const u8, bit: u6 };
pub const flags = [_]Flag{ .{ .name = "CF", .bit = 0 }, .{ .name = "PF", .bit = 2 }, .{ .name = "AF", .bit = 4 }, .{ .name = "ZF", .bit = 6 }, .{ .name = "SF", .bit = 7 }, .{ .name = "IF", .bit = 9 }, .{ .name = "DF", .bit = 10 }, .{ .name = "OF", .bit = 11 } };

/// `reg` rip: gold plaque on the name, the wash across, the address in
/// code's ink and its name; never struck. At its right end the `flags`,
/// eight names on a pitch of 42: set, upper case on a chip, bold, bright;
/// clear, lower case, dim; changed, a turned corner (`changed`: a bit per
/// flag, and how much of the corner shows); read, framed (`read`: a bit per
/// flag, while a conditional reads them: an echo of the row that set them,
/// `read_shows` how much). The value of eflags is not drawn: the names are the value.
pub fn rip(u: ui.Ui, y: f32, w: f32, moment: Recording.Moment, pc: u64, eflags: u64, changed: u64, held: f32, fire: f32, read: u64, read_shows: f32, was: ?RipWas) void {
    const gold = theme.mark(.current);
    u.current(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = row_h }, theme.metric.plaque.rip, fire);
    u.text(.mono_bold, size, m.side, baseline(y), "rip", gold.on_solid);
    const fl = theme.metric.flags;
    const x = w - m.side - @as(f32, flags.len) * fl.pitch + 10;
    // Where execution is changes with the advance: the old value goes as the new one comes, over it.
    const before = was orelse RipWas{ .moment = moment, .pc = pc, .eflags = eflags };
    if (before.pc != pc and before.going < 1) {
        _ = chain(u.faded(1 - before.going), m.chain_x, y, before.moment, before.pc, x - 16, .{});
        _ = chain(u.faded(before.going), m.chain_x, y, moment, pc, x - 16, .{});
    } else _ = chain(u, m.chain_x, y, moment, pc, x - 16, .{});
    ripFlags(u, x, y, eflags, changed, held, read, read_shows, before);
}

/// The flag chips on their own row, for narrower live register panes.
pub fn ripFlags(u: ui.Ui, start: f32, y: f32, eflags: u64, changed: u64, held: f32, read: u64, read_shows: f32, before: RipWas) void {
    const fl = theme.metric.flags;
    var x = start;
    for (flags) |flag| {
        const set = eflags >> flag.bit & 1 != 0;
        // A flag the step sets or clears crossfades as it lands (`flip`).
        if (set != (before.eflags >> flag.bit & 1 != 0) and before.flip < 1) {
            ripFlag(u.faded(1 - before.flip), x, y, flag, !set);
            ripFlag(u.faded(before.flip), x, y, flag, set);
        } else ripFlag(u, x, y, flag, set);
        if (changed >> flag.bit & 1 != 0) u.corner(x, y + 2, m.corner, held);
        if (read >> flag.bit & 1 != 0 and read_shows > 0) u.read(.{ .x = x, .y = y + 2, .w = fl.chip[0], .h = fl.chip[1] }, read_shows);
        x += fl.pitch;
    }
}

/// rip's row as it was before the step: its value, going to the new one
/// `going` of the way (the advance), and the flags, `flip` of the way.
pub const RipWas = struct { moment: Recording.Moment, pc: u64, eflags: u64, going: f32 = 1, flip: f32 = 1 };

fn ripFlag(u: ui.Ui, x: f32, y: f32, flag: Flag, set: bool) void {
    const fl = theme.metric.flags;
    if (set) {
        u.chip(.{ .x = x, .y = y + 2, .w = fl.chip[0], .h = fl.chip[1] });
        u.text(.mono_bold, size, x + 4, baseline(y), flag.name, t.bright);
    } else u.text(.mono, size, x + 4, baseline(y), u.print("{c}{c}", .{ std.ascii.toLower(flag.name[0]), std.ascii.toLower(flag.name[1]) }), ui.mix(t.dim, theme.mark(.current).ember, 0.2));
}

/// A slot's role as it was before the step, and how far (0 to 1) the role it has now has come in over it.
pub const Role = struct { name: []const u8, local: bool = false, going: f32 = 1, from_rsp: ?i64 = null, offset_going: ?f32 = null };

/// `slot`: a word of the stack: a lane to 112 for `row` pins (`pins`, the
/// registers that hold its address); its offset from rsp (`from_rsp`
/// bytes), hex, faint, ranged right to 172 (`+18`, `-8` above rsp); its
/// address in stack ink with `lead` from 184; then its chain, beginning
/// with the word it holds; and its `role` (what the word is, where the
/// recording knows it: `saved rbp` dim, a `local`'s name primary), ranged right where the room ends
/// (136 from the right edge `w`: the `call` spans'), the chain ending a
/// character before it.
pub fn slot(u: ui.Ui, y: f32, w: f32, moment: Recording.Moment, addr: u64, from_rsp: i64, pins: []const []const u8, pin_shows: f32, marks: Marks, role: []const u8, local: bool, was: ?Role) Hops {
    const s = theme.metric.slot;
    if (pins.len > 0 and pin_shows > 0) u.faded(pin_shows).pinRow(s.lane, y, pins, theme.color.region.stack);
    // An offset that changes with rsp (the window held, or moved by more than the slide) crossfades as a role does.
    if (was) |o| if (o.from_rsp) |old| if (old != from_rsp and (o.offset_going orelse o.going) < 1) {
        offset(u.faded(1 - (o.offset_going orelse o.going)), y, old);
        offset(u.faded(o.offset_going orelse o.going), y, from_rsp);
    } else offset(u, y, from_rsp) else offset(u, y, from_rsp) else offset(u, y, from_rsp);
    var lead = marks;
    lead.first = .none;
    const base = baseline(y);
    const end = u.address(s.address, base, addr, .{ .ink = ui.rgb(theme.color.region.stack), .lead = marks.lead });
    var room = w - s.room;
    // A role that changes in place (the step makes the word another's) crossfades, `was.going` of the way.
    const before = was orelse Role{ .name = role, .local = local };
    const changes = !std.mem.eql(u8, before.name, role) or before.local != local;
    const right = room;
    for ([2]Role{ before, .{ .name = role, .local = local } }, [2]f32{ if (changes) 1 - before.going else 0, if (changes) before.going else 1 }) |r, shows| {
        if (r.name.len == 0 or shows <= 0) continue;
        const rx = right - u.width(.mono, size, r.name);
        u.faded(shows).text(.mono, size, rx, base, r.name, if (r.local) t.primary else t.dim);
        room = @min(room, rx - adv);
    }
    const held = (Recording.word(moment, addr, 8) catch null) orelse {
        _ = u.arrow(end, y + row_h / 2, .points);
        u.unknown(.{ .x = end + m.arrow_w, .y = y, .w = 24, .h = row_h });
        return .{ .end = end + m.arrow_w + 24 };
    };
    // The word there: a pointer, or what the slot holds.
    const pointer = regionOf(moment, held) != .none;
    const at = u.arrow(end, y + row_h / 2, if (pointer) .points else .holds);
    lead.lead = 0;
    lead.first = marks.first;
    return chain(u, at, y, moment, held, room, lead);
}

/// The stack panel's offsets written with `0x` while it draws its rows
/// (`Levels.introduction`), where hex and decimal differ (10 and over), as
/// an instruction's operands and a value are (`-8`, `-0x18`).
pub var prefixed = false;

/// `0x` in front of `n` (`prefixed`), or nothing.
pub fn hexMark(n: u64) []const u8 {
    return if (prefixed and n >= 10) "0x" else "";
}

/// A slot's offset from rsp, `from_rsp` bytes: hex, faint, ranged right to 172.
fn offset(u: ui.Ui, y: f32, from_rsp: i64) void {
    const p = hexMark(@abs(from_rsp));
    const text = if (from_rsp < 0) u.print("-{s}{x}", .{ p, @as(u64, @intCast(-from_rsp)) }) else u.print("+{s}{x}", .{ p, @as(u64, @intCast(from_rsp)) });
    u.text(.mono, size, theme.metric.slot.offset - u.width(.mono, size, text), baseline(y), text, t.faint);
}

/// `slot` `free`: a word above rsp the stack has not reached, shown while
/// the window is held for the camera: its offset, its address at 60%, its
/// word faint, no chain, no pin.
pub fn free(u: ui.Ui, y: f32, moment: Recording.Moment, addr: u64, from_rsp: i64, lead: usize, was: ?Role) void {
    const s = theme.metric.slot;
    const base = baseline(y);
    // An offset whose base the step moves crossfades, as a slot's does.
    if (was) |o| if (o.from_rsp) |old| if (old != from_rsp and o.going < 1) {
        offset(u.faded(1 - o.going), y, old);
        offset(u.faded(o.going), y, from_rsp);
    } else offset(u, y, from_rsp) else offset(u, y, from_rsp) else offset(u, y, from_rsp);
    const end = u.address(s.address, base, addr, .{ .ink = ui.mix(theme.color.region.stack, theme.color.page, theme.metric.context.lead_alpha), .lead = lead });
    const word = (Recording.word(moment, addr, 8) catch null) orelse return u.unknown(.{ .x = end + m.arrow_w, .y = y, .w = 24, .h = row_h });
    u.text(.mono, size, end + m.arrow_w, base, u.print("{x}", .{word}), t.faint);
}

/// `call` `span`: one frame of the call chain on the stack, a bracket 14
/// in from the panel's right edge `w` down the slots `y0 .. y1` that are
/// the frame, and the function's name left of it (Go Medium 18). `newest`
/// gold and bright; older, rule and dim. `open`: it runs past the panel.
pub fn span(u: ui.Ui, w: f32, y0: f32, y1: f32, name: []const u8, newest: bool, open: bool) void {
    const x = w - theme.metric.slot.span;
    const c = if (newest) theme.mark(.current).solid else theme.color.rule;
    u.bracket(x, y0 + 3, y1 - @as(f32, if (open) 0 else 3), c, theme.metric.bracket.quiet, -1, open);
    const mid = (y0 + y1) / 2 + 6;
    u.text(.sans_medium, theme.size.sans.micro, spanNameX(u, w, name), mid, name, if (newest) t.bright else t.dim);
}

/// Where a `span`'s name begins, in a panel `w` wide.
pub fn spanNameX(u: ui.Ui, w: f32, name: []const u8) f32 {
    return w - theme.metric.slot.span - 14 - u.width(.sans_medium, theme.size.sans.micro, name);
}

/// `call` `row`: `#n` at 12 (a gold plaque 40 wide on the newest), the
/// name and offset in primary at 60, the arguments at 384 (`n=4`,
/// primary), file and line ranged right, dim. A name cut only where the
/// arguments begin, saying so.
pub fn callRow(u: ui.Ui, y: f32, w: f32, n: usize, name: []const u8, args: []const u8, where: []const u8, newest: bool) void {
    if (newest) callCurrent(u, y, w);
    callLabels(u, y, w, n, name, args, where, newest);
}

/// The newest call's wash and plaque, apart from its words: for a row that becomes or stops being the newest.
pub fn callCurrent(u: ui.Ui, y: f32, w: f32) void {
    u.current(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = row_h }, 40, 0);
}

/// A `call` row's words, apart from its wash: for one whose words crossfade.
pub fn callLabels(u: ui.Ui, y: f32, w: f32, n: usize, name: []const u8, args: []const u8, where: []const u8, newest: bool) void {
    const gold = theme.mark(.current);
    u.text(if (newest) .mono_bold else .mono, size, m.side, baseline(y), u.print("#{d}", .{n}), if (newest) gold.on_solid else t.faint);
    const where_x = w - m.side - u.width(.mono, size, where);
    const args_x: f32 = 384;
    const shown = fitted(u, name, (if (args.len > 0) args_x else where_x) - 60 - adv);
    u.text(.mono, size, 60, baseline(y), shown, t.primary);
    u.text(.mono, size, @max(args_x, 60 + u.width(.mono, size, shown) + adv), baseline(y), args, t.primary);
    u.text(.mono, size, where_x, baseline(y), where, t.dim);
}

/// `text` in `width` units of mono 20: whole, or cut at its far end with `…`.
pub fn fitted(u: ui.Ui, text: []const u8, width: f32) []const u8 {
    // (A width measured without a room is infinite: whole.)
    const chars: usize = @intFromFloat(std.math.clamp(width / adv, 1, 1 << 16));
    if (text.len <= chars) return text;
    return u.print("{s}\u{2026}", .{text[0 .. chars - 1]});
}

/// `line`: a line of source, its number ranged right in three characters
/// (faint), the text from 64 in the four code inks, 67 characters and
/// then a faint `…`. `current`: a gold plaque 50 wide on the number (its
/// edges out `fire`), ember across; `marked`: the number as on the plaque,
/// which its panel draws where the mark is (it slides). `trail`: the bar
/// (0 newest). `widen`: how much more room the program's line numbers
/// take than three characters (`numberRoom`); the text moves right by as much.
pub fn line(u: ui.Ui, y: f32, w: f32, number: u32, widen: f32, text: []const u8, styles: []const u8, state: union(enum) { plain, current: f32, marked, trail: usize }) void {
    const gold = theme.mark(.current);
    switch (state) {
        .current => |fire| u.current(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = row_h }, theme.metric.plaque.line + widen, fire),
        .trail => |k| u.trail(theme.stroke.rule, y, k),
        .plain, .marked => {},
    }
    const on = state == .current or state == .marked;
    const num = u.print("{d}", .{number});
    u.text(if (on) .mono_bold else .mono, size, m.line_number_end + widen - @as(f32, @floatFromInt(num.len)) * adv, baseline(y), num, if (on) gold.on_solid else t.faint);
    // Cut as much sooner as the row is narrower than its column (a pane's strip takes 48: four characters).
    const cut: usize = @intFromFloat(@max(theme.layout.program.w - w, 0) / adv);
    const limit: usize = m.source_chars -| @as(usize, @intFromFloat(widen / adv)) -| cut;
    const end = @min(text.len, limit);
    var i: usize = 0;
    while (i < end) {
        var j = i + 1;
        while (j < end and styles[j] == styles[i]) j += 1;
        if (std.mem.indexOfNone(u8, text[i..j], " ") != null) {
            const class = styles[i];
            u.text(codeFace(class), size, m.line_text + widen + @as(f32, @floatFromInt(i)) * adv, baseline(y), text[i..j], codeInk(class));
        }
        i = j;
    }
    if (text.len > limit) u.text(.mono, size, m.line_text + widen + @as(f32, @floatFromInt(limit)) * adv, baseline(y), "\u{2026}", t.faint);
}

/// How much wider than three characters a column of line numbers up to
/// `widest` is: nothing for a small program; SQLite's lines have six digits.
pub fn numberRoom(widest: u32) f32 {
    return @as(f32, @floatFromInt(@max(std.fmt.count("{d}", .{widest}), 3) - 3)) * adv;
}

/// pardes's classes: none, keyword, string, number, comment.
fn codeInk(class: u8) u24 {
    const c = theme.color.code;
    return switch (class) {
        1 => c.keyword,
        2, 3 => c.literal,
        4 => c.comment,
        else => c.plain,
    };
}

fn codeFace(class: u8) ui.Face {
    return switch (class) {
        1 => .mono_bold,
        4 => .mono_italic,
        else => .mono,
    };
}

/// A run of a `bytes` row: what the bytes are, from the types of what the
/// program's pointers reach.
pub const Run = struct {
    first: u8,
    len: u8,
    kind: enum { number, pointer, text, loose, unread },
    /// Its mark: struck (heat), read (shows), held is in the heat.
    heat: ui.Heat = .none,
    read: f32 = 0,
    /// The bytes of it whose value the heat's step changed, first and last
    /// (from `first`): what the strike, the arm and the corner cover. Null: all of it.
    changed: ?[2]u8 = null,
    /// Frames between the strikes of its bytes, from the low address.
    apart: f32 = 1,
};

/// `bytes`: a hexdump row of sixteen bytes at `addr`: a bracket at 7
/// (`bracket`: quiet on a row that holds a drawn thing), the address in
/// region ink with `lead` at 18 (at 60% on a row that holds no drawn
/// thing), the bytes from 132 on a pitch of 30, 12 more after the
/// eighth; a field's bytes on raised paper in their ink (a pointer's in
/// the region it points into, text's in a string's), `loose` ones (of no
/// field: the allocator's, a struct's padding, past what the dump is of)
/// dim with no paper, never read two dots a byte; a word's padding bytes
/// faint. Its reading is `hexdump.reading`, at 640.
pub fn bytes(u: ui.Ui, y: f32, addr: u64, values: *const [16]u8, known: *const [16]bool, runs: []const Run, region: u24, lead: usize, holds_drawn: bool, moment: Recording.Moment) void {
    bytesAt(u, y, addr, values, known, runs, region, lead, holds_drawn, moment, 0);
}

/// How far right of their column a dump's bytes (and its reading) go to
/// leave its widest address room: none up to seven digits, 58 for a stack
/// address's twelve. A dump sets it once, so its rows keep one column.
pub fn addressRoom(addr: u64) f32 {
    const b = theme.metric.bytes;
    return @max(b.address + @as(f32, @floatFromInt(ui.digits(addr))) * adv + adv - b.first, 0);
}

/// `bytes`, the sixteen bytes `shift` right of their column (`addressRoom`).
pub fn bytesAt(at: ui.Ui, y: f32, addr: u64, values: *const [16]u8, known: *const [16]bool, runs: []const Run, region: u24, lead: usize, holds_drawn: bool, moment: Recording.Moment, shift: f32) void {
    const b = theme.metric.bytes;
    const base = baseline(y);
    _ = at.address(b.address, base, addr, .{ .ink = if (holds_drawn) ui.rgb(region) else ui.mix(region, theme.color.page, theme.metric.context.lead_alpha), .lead = lead });
    if (holds_drawn) at.bracket(b.bracket, y + 3, y + row_h - 3, ui.mix(region, theme.color.page, theme.metric.context.lead_alpha), theme.metric.bracket.quiet, 1, false);
    const u = at.moved(shift, 0);
    for (runs) |run| {
        const x0 = byteX(run.first) - 4;
        const x1 = byteX(run.first + run.len - 1) + 28;
        const r: Rect = .{ .x = x0, .y = y + 1, .w = x1 - x0, .h = row_h - 2 };
        const field = run.kind == .number or run.kind == .pointer or run.kind == .text;
        if (field) u.fill(r, theme.color.raised);
        // Read is per run (a frame 3 out). A write's marks cover the bytes
        // whose value changed, first to last (`changed`): armed, then struck
        // a byte a frame from the low address (the softened paper, the
        // digits bold and bright), held by a turned corner on the first.
        const h = run.heat;
        const lo: u8 = if (run.changed) |c| c[0] else 0;
        const hi: u8 = if (run.changed) |c| c[1] else run.len - 1;
        const s0 = byteX(run.first + lo) - 4;
        const s1 = byteX(run.first + hi) + 28;
        if (h.arm > 0) u.faded(h.arm).frame(.{ .x = s0 - 3, .y = y - 1, .w = s1 - s0 + 6, .h = row_h + 2 }, theme.mark(.write).solid, 2);
        var solid_of: [16]f32 = @splat(0);
        if (h.level >= 1 and h.solid > 0) for (lo..@as(usize, hi) + 1) |j| {
            const i: u8 = @intCast(run.first + j);
            const solid = h.solid * std.math.clamp(h.in - @as(f32, @floatFromInt(j - lo)) * run.apart / (60.0 * theme.time.strike.in), 0, 1);
            solid_of[j] = solid;
            if (solid <= 0) continue;
            // Each byte's paper up to the next one's, the pulse on the span's outer edges.
            const bx0 = byteX(i) - 4 - if (j == lo) h.out else 0;
            const bx1 = (if (j < hi) byteX(i + 1) - 4 else byteX(i) + 28) + if (j == hi) h.out else 0;
            u.fill(.{ .x = bx0, .y = r.y - h.out, .w = bx1 - bx0, .h = r.h + 2 * h.out }, ui.mix(theme.color.raised, theme.color.struck, solid));
        };
        u.corner(s0, y + 2, m.corner, h.level * h.corner);
        if (ui.strokes) {
            if (h.level >= 1 and h.solid * h.in > 0) ui.collectMark(u, s0, y + row_h / 2, .struck, h.solid * h.in) else ui.collectMark(u, s0, y + row_h / 2, .held, h.level * h.corner);
            ui.collectMark(u, x0, y + row_h / 2, .read, run.read);
        }
        if (run.read > 0) u.faded(run.read).frame(.{ .x = x0 - 3, .y = y - 1, .w = x1 - x0 + 6, .h = row_h + 2 }, theme.mark(.read).solid, 2);
        // A little-endian word: the bytes above its highest non-zero one are its padding.
        var top: usize = 0;
        for (0..run.len) |j| if (values[run.first + j] != 0) {
            top = j;
        };
        const word: u64 = if (run.len == 8) std.mem.readInt(u64, values[run.first..][0..8], .little) else 0;
        const run_ink: ui.Color = switch (run.kind) {
            .number => ui.rgb(t.primary),
            .pointer => ui.rgb(if (run.len == 8) ink(regionOf(moment, word)) else t.primary),
            .text => ui.rgb(theme.color.string),
            .loose => ui.rgb(t.dim),
            .unread => ui.rgb(t.faint),
        };
        for (0..run.len) |j| {
            const i = run.first + j;
            const x = byteX(@intCast(i));
            if (run.kind == .unread or !known[i]) {
                u.fill(.{ .x = x + 5, .y = y + 11, .w = 4, .h = 4 }, t.faint);
                u.fill(.{ .x = x + 15, .y = y + 11, .w = 4, .h = 4 }, t.faint);
                continue;
            }
            const struck = solid_of[j] >= 0.5;
            const c = if (struck) ui.rgb(t.bright) else if (j <= top) run_ink else ui.mix(run_ink, theme.color.page, theme.metric.context.pad_alpha);
            u.text(if (struck) .mono_bold else .mono, size, x, base, u.print("{x:0>2}", .{values[i]}), c);
        }
    }
}

/// Where byte `i` of a `bytes` row is.
pub fn byteX(i: u8) f32 {
    const b = theme.metric.bytes;
    return b.first + @as(f32, @floatFromInt(i)) * b.pitch + @as(f32, if (i >= 8) b.middle else 0);
}

/// `arc`s: the pointers of a panel of rows whose targets are rows of the
/// same panel, each drawn from its row along a lane at the panel's left
/// edge to the target's row, head first. A panel adds the pointers it
/// draws (`add`), then `draw`s them over its rows.
pub const Arcs = struct {
    items: [32]Arc = undefined,
    n: usize = 0,

    pub const Arc = struct {
        /// The rows' tops: the pointer's, its target's (or the panel's
        /// rule, for a `stub`: a target in the same region past the window).
        from: f32 = 0,
        to: f32 = 0,
        ink: u24 = 0,
        /// 0 standing, 1 full ink: the step writes or reads the pointer.
        full: f32 = 0,
        /// How much of it is drawn from its pointer (it draws head first),
        /// and how much shows (it fades).
        drawn: f32 = 1,
        shows: f32 = 1,
        dashed: bool = false,
        stub: bool = false,
        /// The step's: its lane comes first.
        hot: bool = false,
    };

    pub fn add(a: *Arcs, arc: Arc) void {
        if (a.n == a.items.len or arc.shows <= 0 or arc.from == arc.to) return;
        a.items[a.n] = arc;
        a.n += 1;
    }

    /// Nested spans take separate lanes, the longest outermost; spans that
    /// do not overlap share one; past `lanes` the step's come first, then
    /// the shorter, and the rest are only read. A lane change glides: while
    /// an arc draws or fades (12 f), the others go from the lanes they have
    /// without it to those they have with it, as far as it has drawn or shows.
    pub fn draw(a: *Arcs, u: ui.Ui, lanes: usize) void {
        const k = theme.metric.arc;
        // For a strip: each arc's rows, the middles of its pointer's and its target's.
        if (ui.strokes) {
            const c = &ui.collected;
            for (a.items[0..a.n]) |arc| if (!arc.stub and c.n_arcs < c.arcs.len) {
                const p = u.at.xf.apply(.{ 0, arc.from + row_h / 2 });
                const q = u.at.xf.apply(.{ 0, arc.to + row_h / 2 });
                c.arcs[c.n_arcs] = .{ .x = p[0], .from = p[1], .to = q[1], .ink = u.faded(arc.shows).at.faded(ui.rgb(arc.ink)) };
                c.n_arcs += 1;
            };
            return;
        }
        var spans: [32]Span = undefined;
        for (a.items[0..a.n], spans[0..a.n], 0..) |arc, *sp, i| {
            const up = arc.to < arc.from;
            const high: f32 = k.high;
            const low: f32 = k.low;
            sp.y0 = arc.from + if (up) high else low;
            sp.y1 = if (arc.stub) arc.to else arc.to + if (up) low else high;
            sp.lo = @min(sp.y0, sp.y1);
            sp.hi = @max(sp.y0, sp.y1);
            sp.i = i;
        }
        // The longest first, so it takes the outermost lane free.
        std.mem.sort(Span, spans[0..a.n], {}, struct {
            fn longer(_: void, x: Span, y: Span) bool {
                return x.hi - x.lo > y.hi - y.lo;
            }
        }.longer);
        // Arriving or leaving: how far (the least of them), and the lanes without them.
        var settled: f32 = 1;
        for (a.items[0..a.n]) |arc| settled = @min(settled, @min(arc.drawn, arc.shows));
        const with = a.assign(spans[0..a.n], lanes, false);
        const without = if (settled < 1) a.assign(spans[0..a.n], lanes, true) else with;
        for (spans[0..a.n]) |sp| {
            const arc = a.items[sp.i];
            const lane = with[sp.i] orelse continue;
            const was = without[sp.i] orelse lane;
            const x = std.math.lerp(k.lanes[was], k.lanes[lane], cursorGlide(settled));
            const shade = ui.mix(arc.ink, theme.color.page, k.standing * (1 - std.math.clamp(arc.full, 0, 1)));
            const v = u.faded(arc.shows);
            if (arc.stub) {
                v.route(&.{ .{ k.out, sp.y0 }, .{ x, sp.y0 }, .{ x, sp.y1 } }, shade, .{ .width = k.width, .head = k.head, .radius = k.radius, .progress = arc.drawn, .dashed = arc.dashed });
            } else v.route(&.{ .{ k.out, sp.y0 }, .{ x, sp.y0 }, .{ x, sp.y1 }, .{ k.in, sp.y1 } }, shade, .{ .width = k.width, .head = k.head, .radius = k.radius, .progress = arc.drawn, .dashed = arc.dashed });
        }
    }

    const Span = struct { lo: f32, hi: f32, y0: f32, y1: f32, i: usize };

    /// Each span's lane (`spans` longest first), the step's first; `settled`:
    /// only of the arcs neither drawing nor fading (those keep their lane in full).
    fn assign(a: *const Arcs, spans: []const Span, lanes: usize, settled: bool) [32]?usize {
        var taken: [3][32][2]f32 = undefined;
        var counts = [3]usize{ 0, 0, 0 };
        var lane_of: [32]?usize = @splat(null);
        for ([_]bool{ true, false }) |hot| for (spans) |sp| {
            const arc = a.items[sp.i];
            if (arc.hot != hot or (settled and (arc.drawn < 1 or arc.shows < 1))) continue;
            lane_of[sp.i] = for (0..@min(lanes, 3)) |l| {
                const clear = for (taken[l][0..counts[l]]) |t2| {
                    if (!(sp.hi < t2[0] or sp.lo > t2[1])) break false;
                } else true;
                if (clear) {
                    taken[l][counts[l]] = .{ sp.lo, sp.hi };
                    counts[l] += 1;
                    break l;
                }
            } else null;
        };
        return lane_of;
    }

    fn cursorGlide(p: f32) f32 {
        return theme.ease(.glide, std.math.clamp(p, 0, 1));
    }
};

test "arcs of a chain share a lane; nested ones take the next" {
    var a: Arcs = .{};
    // 1004090 -> 1004070 -> 1004050, rows 4, 2, 0: one lane.
    a.add(.{ .from = 96, .to = 48, .ink = 0 });
    a.add(.{ .from = 48, .to = 0, .ink = 0 });
    // One across both: the outer lane.
    a.add(.{ .from = 120, .to = 0, .ink = 0 });
    const k = theme.metric.arc;
    const up_from = 96 + k.high;
    const into = 48 + k.low;
    try std.testing.expect(into < up_from and 48 + k.high < into);
}