summaryrefslogtreecommitdiff
path: root/anim/src/hexdump.zig
blob: 3ef1ac9ca081d6474dfe270985600a6d7e18baf1 (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
//! `hexdump` (design/README.md, "3. Panels"): memory as `bytes` rows,
//! sixteen a row, the right half of a lens: the pane its drawing is a view
//! of. A window of the region kept round the rows the step touches (five
//! beside, seven as the subject), in address order; a gap in the addresses
//! is one row of `more`'s dots and the count left out. Each row's runs
//! come from the types of what the program's pointers reach: a field's
//! bytes on raised paper in its ink, `loose` ones (the allocator's, a
//! struct's padding) dim, never read two dots; and its reading at 640:
//! what the runs read as, a list a character apart.
//! Bytes a step wrote are struck here before the drawing reacts.
//! Reads `Moment.read`, `Moment.allocation`, and the recording's types.
const std = @import("std");
const ui = @import("ui.zig");
const rows = @import("rows.zig");
const cursors = @import("cursor.zig");
const Recording = @import("Recording.zig");
const objects = @import("objects.zig");
const ties = @import("ties.zig");
const theme = ui.theme;
const Rect = ui.Rect;
const t = theme.color.text;
const m = theme.metric.context;
const b = theme.metric.bytes;
const adv = theme.size.mono.context * 3 / 5;

/// What a word of the region is.
pub const Kind = enum { number, pointer, loose, unread };

/// The kind of the word at `addr`, and its type where a field's is known:
/// a field of a struct the program's pointers reach (by its type), other
/// allocated bytes, `loose` (the allocator's own between allocations), or
/// never observed.
pub fn kindOf(rec: *const Recording, things: []const objects.Object, moment: Recording.Moment, addr: u64) struct { Kind, ?Recording.types.Type } {
    for (things) |o| {
        if (!o.holds(addr)) continue;
        for (o.type.record.fields) |field| if (o.addr + field.offset == addr) return .{ if (field.type == .pointer) .pointer else .number, field.type };
        return .{ .number, null };
    }
    var bytes: [8]u8 = undefined;
    var known: [8]bool = undefined;
    moment.read(addr, &bytes, &known) catch return .{ .unread, null };
    if (std.mem.indexOfScalar(bool, &known, true) == null) return .{ .unread, null };
    return .{ if (rec.allocated(moment, addr)) .number else .loose, null };
}

/// The rows of a region (`lo .. hi`, sixteen-aligned) a dump of `count`
/// rows shows: all of them, or a window round the first the step touched.
pub fn window(now: cursors.Now, lo: u64, hi: u64, count: usize) u64 {
    return windowAt(now.rec, now.stops[1], now.stops[0], lo, hi, count);
}

/// The same for the step from moment `from` to `to`.
pub fn windowAt(rec: *const Recording, from: u64, to: u64, lo: u64, hi: u64, count: usize) u64 {
    const all = (hi - lo) / 16;
    if (all <= count) return lo;
    var touched: ?u64 = null;
    for ([_][]const Recording.Span{ rec.written(from, to), rec.read(from, to) }) |spans| for (spans) |span| {
        if (touched == null and span.addr >= lo and span.addr < hi) touched = span.addr & ~@as(u64, 15);
    };
    const at = touched orelse lo;
    const row = (at - lo) / 16;
    const first = @min(row -| (count / 2), all - count);
    return lo + first * 16;
}

/// What a dump is of: the structs a drawing beside it draws, or an array
/// of numbers (an element a run, read as its type), and the ink of the
/// memory it is in.
pub const Of = struct {
    things: []const objects.Object = &.{},
    array: ?struct { addr: u64, len: u64, elem: u8, type: ?Recording.types.Type = null } = null,
    region: u24 = theme.color.region.heap,
    /// A lens's view: a row a register points into carries its pin (`rowPin`).
    pins: bool = false,
};

/// The band's view of bytes: its own panel over the state column, the
/// tag `its bytes` with the range shown (`about`) and the legend of runs.
/// Returns its `Ui` (the panel's origin) and how many rows it holds.
pub fn panel(f: *@import("sketch").Frame, placed: @import("anim").Placed, stage: *const @import("stage.zig").Stage, about: []const u8, legend: []const ui.Legend) View {
    const box = stage.box(placed, .view);
    const u = @import("context.zig").at(f, placed, box).faded(placed.value(stage.view));
    if (box.h < m.tag + m.row) return .{ .u = u, .rows = 0, .box = box };
    // Its own box, as it moves; the drawing's panel clips itself again after.
    u.clip(.{ .x = 0, .y = 0, .w = box.w, .h = box.h });
    _ = u.panel(box.w, box.h, "its bytes", .{ .legend = legend });
    const tag = theme.size.sans.tag;
    u.text(.sans, theme.size.sans.micro, 28 + u.width(.sans_medium, tag, "its bytes") + 12, m.tag - 6, about, t.faint);
    return .{ .u = u, .rows = theme.layout.rowsIn(box.h), .box = box };
}

/// A view of a region the scene names (`of`), by its fields: the band's
/// right half, over the state column. The scene marks fields as read
/// (`marks`, a value each: how much the frame shows). In a step that hands
/// the region to the kernel (a write's buffer), its fields are framed as
/// read while the kernel takes them, and the bytes the recording had not
/// seen come in from the call's capture, dots to digits, with no mark.
pub const Dump = struct {
    cursor: cursors.Cursor,
    stage: *const @import("stage.zig").Stage,
    /// The tag's words, after `its bytes`; and the legend of its fields.
    about: []const u8,
    legend: []const ui.Legend = &.{},
    of: Fields,
    marks: []const @import("anim").Value = &.{},
    /// The stop it comes in at: what changed before then, the viewer did
    /// not see change, and it is plain.
    since: u64 = 0,

    pub fn draw(d: *const Dump, f: *@import("sketch").Frame, placed: @import("anim").Placed) void {
        const v = panel(f, placed, d.stage, d.about, d.legend);
        defer v.u.unclip();
        if (v.rows == 0) return;
        const now = d.cursor.now(placed);
        var of = d.of;
        of.pins = true;
        of.watched = 0;
        while (of.watched + 1 < now.stops.len and now.stops[of.watched + 1] >= d.since) of.watched += 1;
        var shows: [8]f32 = @splat(0);
        const marked = @min(d.marks.len, shows.len);
        for (d.marks[0..marked], shows[0..marked]) |mark, *value| value.* = placed.value(mark);
        of.marks = shows[0..marked];
        // A call the step made that was given these bytes: as the kernel
        // took them, from when its work begins (and at the stop after it;
        // a step later the program may have written them again).
        const syscalls = @import("syscalls.zig");
        for (d.cursor.rec.syscalls) |made| {
            if (made.enter <= now.stops[1] or made.enter > now.stops[0]) continue;
            const span = syscalls.bufferRead(made) orelse continue;
            if (span.addr >= of.base + of.len or span.addr + span.len <= of.base) continue;
            var shown: f32 = 1;
            if (!now.resting()) {
                const p = syscalls.Plan.of(made);
                shown = std.math.clamp((now.time - p.work) / theme.time.quick, 0, 1);
                of.read = now.held(p.work);
            }
            of.given = .{ .addr = span.addr, .bytes = made.text[0..@min(made.text.len, span.len)], .shows = shown };
        }
        fielded(v, now, m.tag + m.pad, of);
        v.veil(now);
    }
};

/// The view's panel as drawn: its `Ui`, how many rows it holds, its box.
pub const View = struct {
    u: ui.Ui,
    rows: usize,
    box: Rect,

    /// What a sprint cannot show: veiled, over its rows; then, a dump's,
    /// its minimap: its window (published as it drew, `map.window`) on its
    /// column of the map, a strip of its own (`map.strip`).
    pub fn veil(v: View, now: cursors.Now) void {
        @import("context.zig").veiled(v.u, v.box, now.sprint_veil);
        @import("map.zig").strip(.view, v.u, v.box);
    }
};

/// The dump: `count` rows from `first`, at `x` in `u` (the view's
/// panel), the rows from `y`. The rows of what the drawing draws have
/// quiet brackets; a pointer to another of its rows, an `arc` (full ink
/// always, with `loud`: a loupe's). `rule`: the panel's top and bottom,
/// where a stub to a row past the window ends.
pub fn draw(u: ui.Ui, now: cursors.Now, x: f32, y: f32, first: u64, count: usize, of: Of) void {
    var view = of;
    view.pins = true;
    drawArcs(u, now, x, y, first, count, view, false, .{ y - m.pad, y + @as(f32, @floatFromInt(count)) * m.row + m.pad });
}

pub fn drawArcs(u: ui.Ui, now: cursors.Now, x: f32, y: f32, first: u64, count: usize, of: Of, loud: bool, rule: [2]f32) void {
    const dump = u.moved(x, 0);
    var arcs: rows.Arcs = .{};
    var at_rows: [64]RowAt = undefined;
    for (at_rows[0..@min(count, at_rows.len)], 0..) |*r, i| r.* = .{ .addr = first + 16 * i, .y = y + @as(f32, @floatFromInt(i)) * m.row };
    const shown_rows = at_rows[0..@min(count, at_rows.len)];
    const lead = ui.shared(&.{ first, first + 16 * @as(u64, count -| 1) });
    // Room for the addresses, once for the dump: by its widest.
    const shift = rows.addressRoom(first + 16 * @as(u64, count -| 1));
    // At a run the values crossfade (8 f), unmarked: the rows twice, the arcs once.
    const passes = crossfade(now);
    for (passes.moments[0..passes.n], passes.shows[0..passes.n], 0..) |moment, shows, pass| for (0..count) |i| {
        const v = dump.faded(shows);
        const addr = first + 16 * i;
        const ry = y + @as(f32, @floatFromInt(i)) * m.row;
        var values: [16]u8 = undefined;
        var known: [16]bool = undefined;
        moment.read(addr, &values, &known) catch return;
        var runs: [16]rows.Run = undefined;
        var readings: [16]Field = undefined;
        var keeps: [16]bool = @splat(false);
        var n: usize = 0;
        var holds_drawn = false;
        var at: u64 = 0;
        while (at < 16) {
            const here = addr + at;
            var run: rows.Run = .{ .first = @intCast(at), .len = 8, .kind = .unread };
            var kind: ?Recording.types.Type = null;
            if (of.array) |arr| if (here >= arr.addr and here < arr.addr + arr.len) {
                run.len = arr.elem;
                run.kind = .number;
                kind = arr.type;
                holds_drawn = true;
            };
            if (run.kind == .unread) {
                // A word, or what is left of one before an array begins.
                run.len = @intCast(@min(8 - (here % 8), 16 - at));
                if (of.array) |arr| if (here < arr.addr and arr.addr < here + run.len) {
                    run.len = @intCast(arr.addr - here);
                };
                const word, kind = kindOf(now.rec, of.things, moment, here);
                run.kind = switch (word) {
                    .number => .number,
                    .pointer => .pointer,
                    .loose => .loose,
                    .unread => .unread,
                };
                for (of.things) |o| if (o.holds(here)) {
                    holds_drawn = true;
                };
            }
            run.heat = now.written(here, run.len, .memory, 0);
            run.changed = now.changedBytes(here, run.len);
            if (now.struckAgo(here, run.len)) |ago| keeps[n] = ago < theme.time.strike.in / 2.0;
            if (now.wasRead(here, run.len) and now.writeAge(here, run.len) != 0) run.read = now.reading(.memory, 0);
            if (run.kind == .number or run.kind == .pointer) ties.anchor(v, .{ .dump_run = here }, .{ .x = shift + rows.byteX(run.first) - 4, .y = ry, .w = rows.byteX(run.first + run.len - 1) + 28 - rows.byteX(run.first) + 4, .h = m.row });
            readings[n] = .{ .at = run.first, .len = run.len, .reads = switch (run.kind) {
                .number => .number,
                .pointer => .pointer,
                else => .bytes,
            }, .type = kind };
            runs[n] = run;
            n += 1;
            at += run.len;
        }
        @import("map.zig").row(.view, addr, v, .{ .x = 0, .y = ry, .w = theme.layout.state.w, .h = m.row });
        keepOld(now, addr, &values, &known, runs[0..n], keeps[0..n]);
        rows.bytesAt(v, ry, addr, &values, &known, runs[0..n], of.region, lead, holds_drawn, moment, shift);
        if (pass + 1 == passes.n) for (runs[0..n]) |run| if (run.kind == .pointer and run.len == 8) pointerArcs(&arcs, now, addr + run.first, ry, shown_rows, 16, rule, loud, false);
        const room = if (!of.pins) full_room else if (pass == 0) rowPin(dump, now, addr, ry) else rowPinRoom(dump, now, addr);
        const end = readingIn(v, ry, shift, moment, &values, &known, readings[0..n], room);
        // The size word of the chunk after: malloc's, a note after the reading.
        const last = runs[n - 1];
        if (last.kind == .loose and last.first == 8 and last.len == 8 and std.mem.indexOfScalar(bool, known[8..], false) == null and chunkAfter(now.rec, moment, addr + 8)) {
            const size = std.mem.readInt(u64, values[8..16], .little) & ~@as(u64, 7);
            v.text(.sans, theme.size.sans.micro, end, rows.baseline(ry) - 1, v.print("malloc's: a chunk of {d}", .{size}), t.faint);
        }
    };
    arcs.draw(dump, theme.metric.arc.lanes.len);
}

/// The memory a dump draws now, and how much each shows: at a run, what
/// the step changed crossfades over 8 f, unmarked; otherwise memory's state.
const Passes = struct { moments: [2]Recording.Moment, shows: [2]f32, n: usize };
fn crossfade(now: cursors.Now) Passes {
    if (now.plan.gait == .run and !now.resting()) {
        const q = std.math.clamp(now.since(.memory, 0) / (8.0 / 60.0), 0, 1);
        if (q > 0 and q < 1) return .{ .moments = .{ now.before(), now.moment() }, .shows = .{ 1 - q, q }, .n = 2 };
    }
    return .{ .moments = .{ now.shown(.memory), undefined }, .shows = .{ 1, 0 }, .n = 1 };
}

/// `crossfade`, for one row: at a walk too, a row whose bytes the step
/// changed where the recording saw no write (memory nothing watches, read
/// anew at the stop), or that became known, crossfades over 12 f from
/// memory's slot. Nothing changes in a frame.
fn rowPasses(now: cursors.Now, addr: u64) Passes {
    const plain = crossfade(now);
    if (plain.n == 2 or now.resting() or now.plan.gait != .walk or now.writeAge(addr, 16) == 0) return plain;
    const q = std.math.clamp(now.since(.memory, 0) / theme.time.quick, 0, 1);
    if (q <= 0 or q >= 1) return plain;
    var was: [16]u8 = undefined;
    var is: [16]u8 = undefined;
    var known_was: [16]bool = undefined;
    var known_is: [16]bool = undefined;
    now.before().read(addr, &was, &known_was) catch return plain;
    now.moment().read(addr, &is, &known_is) catch return plain;
    for (0..16) |i| if (known_was[i] != known_is[i] or (known_is[i] and was[i] != is[i])) {
        return .{ .moments = .{ now.before(), now.moment() }, .shows = .{ 1 - q, q }, .n = 2 };
    };
    return plain;
}

/// The registers whose value is in the row `addr .. addr + 16`, as a step
/// moves them (`ties.pinShows`: a name joining or leaving fades through the
/// middle of its change), in pwndbg's order: a view's row a register points
/// into carries its pin, at the row's end (`Ui.pinEnd`). Draws it and
/// returns where the reading must end; publishes the row as a link's
/// target (`dump_pin`), its left edge.
fn rowPin(u: ui.Ui, now: cursors.Now, addr: u64, y: f32) f32 {
    ties.anchor(u, .{ .dump_pin = addr }, .{ .x = 0, .y = y, .w = b.bracket, .h = m.row });
    const at = pinned(u, now, addr);
    if (at.names.len == 0 or at.shows <= 0) return viewRoom();
    const x = u.faded(at.shows).pinEnd(viewRoom(), y, at.names, rows.ink(rows.regionOf(now.moment(), addr)));
    return x - adv;
}

/// Where the reading of a row must end for its pin (`rowPin`), not drawing it.
fn rowPinRoom(u: ui.Ui, now: cursors.Now, addr: u64) f32 {
    const at = pinned(u, now, addr);
    if (at.names.len == 0 or at.shows <= 0) return viewRoom();
    const p = theme.metric.pin;
    var shown: []const u8 = "";
    for (at.names[0..@min(at.names.len, 3)], 0..) |name, i| shown = if (i == 0) name else u.print("{s} {s}", .{ shown, name });
    if (at.names.len > 3) shown = u.print("{s} +{d}", .{ shown, at.names.len - 3 });
    return viewRoom() - u.width(.mono, theme.size.mono.context, shown) - p.row_gap - p.row_head[0] - adv;
}

fn pinned(u: ui.Ui, now: cursors.Now, addr: u64) struct { names: []const []const u8, shows: f32 } {
    const rec = now.rec;
    const context = @import("context.zig");
    const is = (now.moment().regs(rec.tid) catch null) orelse return .{ .names = &.{}, .shows = 0 };
    const was = (now.before().regs(rec.tid) catch null) orelse is;
    var names: std.ArrayList([]const u8) = .empty;
    var shows: f32 = 1;
    for (theme.metric.all_registers[0..16]) |name| {
        const in_was = if (was.named(name)) |v| v >= addr and v < addr + 16 else false;
        const in_is = if (is.named(name)) |v| v >= addr and v < addr + 16 else false;
        if (!in_was and !in_is) continue;
        const s = ties.pinShows(now, context.index(name).?, .node);
        const this: f32 = if (in_was and in_is) 1 else if (in_is) s.new else s.old;
        if (in_was != in_is) shows = @min(shows, @abs(2 * this - 1));
        if (this < 0.5) continue;
        names.append(u.f.scratch, name) catch break;
    }
    return .{ .names = names.items, .shows = shows };
}

/// The runs this step writes whose strike has not landed (`keeps`) keep
/// the bytes they had: the digits and the reading change at s+3, as the
/// fill comes in, never before the arm.
fn keepOld(now: cursors.Now, addr: u64, values: *[16]u8, known: *[16]bool, runs: []const rows.Run, keeps: []const bool) void {
    if (std.mem.indexOfScalar(bool, keeps, true) == null) return;
    var was: [16]u8 = undefined;
    var known_was: [16]bool = undefined;
    now.before().read(addr, &was, &known_was) catch return;
    for (runs, keeps) |run, old| if (old) {
        @memcpy(values[run.first..][0..run.len], was[run.first..][0..run.len]);
        @memcpy(known[run.first..][0..run.len], known_was[run.first..][0..run.len]);
    };
}

/// A row of a panel: its first byte's address and its top.
pub const RowAt = struct { addr: u64, y: f32 };

/// The `arc`s of the pointer at `field` (a word, on the row at `from`)
/// among `shown` (rows of 16 bytes, or of 8 on the stack): to the row its
/// target is in, as the step has it. Rewritten: the old arc goes dashed
/// with the arm, fades from 6 f after the strike as the new one draws at
/// full ink, and quiets with the cool. Read: full ink while the read is
/// framed. A target in the same region past the rows shown: a stub to the
/// panel's rule (`rule`: its top and bottom), only in the step that
/// touches it. `loud`: full ink always (a loupe's, opened to show them).
pub fn pointerArcs(arcs: *rows.Arcs, now: cursors.Now, field: u64, from: f32, shown: []const RowAt, size: u64, rule: [2]f32, loud: bool, protected: bool) void {
    const a = time_arc;
    // Safe-linked: to the pointer it protects (a NULL so stored is the mask alone).
    const mask: u64 = if (protected) field >> 12 else 0;
    const new = ((Recording.word(now.moment(), field, 8) catch null) orelse return) ^ mask;
    const old = if (Recording.word(now.before(), field, 8) catch null) |w| w ^ mask else new;
    const written = now.writeAge(field, 8) == 0 and old != new;
    const read = now.wasRead(field, 8) and !written;
    const hot = written or read;
    const full: f32 = if (loud) 1 else if (read) now.reading(.memory, 0) else 0;
    if (written and now.walking()) {
        const since = now.since(.memory, now.writeDelay(field, 8));
        const heat = now.written(field, 8, .memory, 0);
        const armed = since >= -theme.time.strike.arm;
        aim(arcs, now, field, old, from, shown, size, rule, .{ .full = full, .dashed = armed, .shows = 1 - std.math.clamp((since - a.after) / a.fade, 0, 1), .hot = true });
        if (since >= a.after) aim(arcs, now, field, new, from, shown, size, rule, .{ .full = if (loud) 1 else heat.solid, .drawn = cursors.standard(std.math.clamp((since - a.after) / a.draw, 0, 1)), .hot = true });
        return;
    }
    aim(arcs, now, field, if (written and !now.landed(.memory, 0)) old else new, from, shown, size, rule, .{ .full = full, .hot = hot });
}

const time_arc = theme.time.arc;

/// What the kernel fills strikes a byte every 2 f, as it lands: the
/// kernel's fill is no write the recording has, so by its own times,
/// cooling with the advance (`run` from `here`).
fn givenStrike(now: cursors.Now, of: anytype, here: u64, run: *rows.Run) void {
    const g = of.given orelse return;
    const since = g.since orelse return;
    if (here + run.len <= g.addr or here >= g.addr + g.bytes.len) return;
    const first = @max(here, g.addr) - g.addr;
    const struck = since - @as(f32, @floatFromInt(first)) * @import("syscalls.zig").Plan.byte;
    if (struck >= 0) run.heat = .{ .level = 1, .solid = 1 - std.math.clamp((now.time - now.plan.advance) / theme.time.strike.cool, 0, 1), .in = std.math.clamp(struck / theme.time.strike.in, 0, 1) };
    run.changed = .{ @intCast(@max(here, g.addr) - here), @intCast(@min(here + run.len, g.addr + g.bytes.len) - 1 - here) };
    run.apart = 2;
}

/// One arc from the row at `from` to the row of `shown` that holds
/// `target`; a stub toward the rule for one in the region past them, only
/// for the step's (`state.hot`).
fn aim(arcs: *rows.Arcs, now: cursors.Now, field: u64, target: u64, from: f32, shown: []const RowAt, size: u64, rule: [2]f32, state: rows.Arcs.Arc) void {
    if (target == 0 or shown.len < 2) return;
    const moment = now.moment();
    var arc = state;
    arc.from = from;
    // A run draws no arcs: they fade in, settled, as it ends.
    arc.shows *= 1 - now.hurried;
    arc.ink = rows.ink(rows.regionOf(moment, target));
    for (shown) |r| if (target >= r.addr and target < r.addr + size) {
        if (r.y == from) return;
        arc.to = r.y;
        // A loupe open on both rows carries this arc: the dump withholds it.
        if (size == 16 and arc.full < 1) for (@import("loupe.zig").holding) |h| if (h) |o| {
            if (field >= o.lo and field < o.hi and target >= o.lo and target < o.hi) arc.shows *= 1 - o.shows;
        };
        return arcs.add(arc);
    };
    // Past the rows: a stub, in the step that touches it, when it is the same region's.
    if (!state.hot or rows.regionOf(moment, target) != rows.regionOf(moment, field) or rows.regionOf(moment, target) == .none) return;
    arc.stub = true;
    // Its step's alone (not a loupe's, always full): in as the step begins (12 f), out with the advance, never in a frame.
    if (state.full < 1) arc.shows *= if (now.resting()) 0 else @min(std.math.clamp(now.time / theme.time.quick, 0, 1), 1 - std.math.clamp((now.time - now.plan.advance) / theme.time.read.out, 0, 1));
    arc.to = if (target < shown[0].addr) rule[0] else rule[1];
    arcs.add(arc);
}

/// Whether an allocation the recording has begins just after the word at
/// `word` (the chunk's size word, glibc's and musl's alike): only there are
/// bytes between allocations the allocator's own, to be read as its.
fn chunkAfter(rec: *const Recording, moment: Recording.Moment, word: u64) bool {
    if ((moment.allocation(word + 8) catch null)) |a| return a.ptr == word + 8;
    return rec.allocated(moment, word + 8) and !rec.allocated(moment, word);
}

/// What a field of a region reads as: a number (little-endian, or `big`),
/// a pointer, text (in quotes, C's escapes), or bytes the reading leaves
/// to the eye.
pub const Reads = enum {
    number,
    pointer,
    text,
    bytes,
    /// malloc's size word: the size, its three low bits cleared, in hex;
    /// then the bits as rip's flags are drawn, `A M P` (`0x20 a m P`).
    size,
    /// A pointer glibc stores safe-linked (xor its own address shifted
    /// right by 12): what it protects, `→ 405050`, or `NULL`, then the
    /// mask, faint, `^ 405`. Its arc goes to the pointer it protects.
    protected,
};

/// A field of the region a view is about, from the region's first byte.
pub const Field = struct {
    at: u64,
    len: u64,
    reads: Reads = .number,
    /// Stored high byte first (SQLite's pages are).
    big: bool = false,
    /// Which of the view's marks frames it as read (`Fields.marks`).
    mark: ?u8 = null,
    /// A number's type, where the debug info gives it: read as the lens's
    /// values are (`objects.reading`: a `char` quoted, a `bool` by name).
    type: ?Recording.types.Type = null,
    /// A note from the scene, Go 18 faint, after the reading (`key`, `slots left`).
    note: []const u8 = "",
    /// Where the field is: a `protected` word's mask is its address shifted
    /// right by 12 (`fieldRow` sets it).
    addr: u64 = 0,
};

/// What a dump of fields is of, and how it is marked now.
pub const Fields = struct {
    /// The region: where it begins, how long it is, the ink of its memory.
    base: u64,
    len: u64,
    fields: []const Field,
    region: u24 = theme.color.region.heap,
    /// How much each of the view's marks shows (a frame, read's colour).
    marks: []const f32 = &.{},
    /// Bytes known from elsewhere than the moment's memory (what a syscall
    /// was given, as the kernel took them), and how much they show (0 to 1).
    given: ?struct {
        addr: u64,
        bytes: []const u8,
        shows: f32,
        /// What a read fills: seconds since the kernel's work reached the
        /// first byte; they land a byte every 2 f from the low address (null: all at once).
        since: ?f32 = null,
    } = null,
    /// How much a frame round every field shows: the kernel reading them.
    read: f32 = 0,
    /// The part of the region the recording read at the stop shown (null:
    /// all of it as last seen). Memory nothing watches is read only where a
    /// pointer leads, 32 bytes at a stop; elsewhere its last seen bytes may
    /// be long out of date, and are drawn as not seen.
    seen: ?Recording.Span = null,
    /// How many of the newest steps it has been on screen through: only
    /// their changes are marked.
    watched: usize = std.math.maxInt(usize),
    /// Seconds since its strikes began, a field 6 f after the one before
    /// (a loupe's, once it has opened); null: memory's slot.
    struck: ?f32 = null,
    /// A view: a row a register points into carries its pin (`rowPin`).
    pins: bool = false,
    /// The fields before the step, where it retypes them: a run whose strike
    /// has not landed is read as what it was.
    was: []const Field = &.{},
};

/// The region's rows in view `v`, from `y`, sixteen bytes a row from its
/// first byte: those that hold a field (all of them, where they fit), and
/// for a stretch left out one row of `more`'s dots and how many rows it
/// stands for. More rows of fields than the window: it is kept round the
/// first row a mark or the step is on, and the others are `more` rows too.
/// A field is a run, cut where a row ends; a byte that is no field is
/// `loose` (dim, no paper) and reads as nothing.
pub fn fielded(v: View, now: cursors.Now, y: f32, of: Fields) void {
    const u = v.u;
    const moment = now.shown(.memory);
    const total = (of.len + 15) / 16;
    var held: std.ArrayList(u64) = .empty;
    for (0..total) |r| if (total <= v.rows or holdsField(of, r)) held.append(u.f.scratch, r) catch return;
    const all = held.items;
    if (all.len == 0) return;
    const range = keep(all, focus(now, of, all), v.rows, total - 1);
    const shown = all[range[0]..range[1]];
    const lead = ui.shared(&.{ of.base, of.base + 16 * (total -| 1) });
    // Room for the addresses, once for the dump: by the widest it shows.
    const shift = rows.addressRoom(of.base + 16 * shown[shown.len - 1]);
    const more = struct {
        fn row(at: ui.Ui, ry: f32, count: u64) void {
            const after = at.arrow(b.address, ry + m.row / 2, .more);
            at.text(.mono, theme.size.mono.context, after + adv, rows.baseline(ry), at.print("{d} rows", .{count}), t.faint);
        }
    }.row;
    var ry = y;
    var last: ?u64 = null;
    var at_rows: std.ArrayList(RowAt) = .empty;
    for (shown) |r| {
        // A stretch left out: one row, three dots and a count.
        const gap = if (last) |l| r - l - 1 else r;
        if (gap > 0) {
            more(u, ry, gap);
            ry += m.row;
        }
        last = r;
        const passes = rowPasses(now, of.base + 16 * r);
        const room = if (of.pins) rowPin(u, now, of.base + 16 * r, ry) else full_room;
        for (passes.moments[0..passes.n], passes.shows[0..passes.n]) |mm, shows| fieldRow(u.faded(shows), now, ry, of.base + 16 * r, if (passes.n == 2) mm else moment, of, lead, shift, room);
        at_rows.append(u.f.scratch, .{ .addr = of.base + 16 * r, .y = ry }) catch {};
        @import("map.zig").row(.view, of.base + 16 * r, u, .{ .x = 0, .y = ry, .w = 860, .h = m.row });
        ry += m.row;
    }
    if (shown[shown.len - 1] < total - 1) more(u, ry, total - 1 - shown[shown.len - 1]);
    // Its pointers to its own rows: arcs.
    var arcs: rows.Arcs = .{};
    if (at_rows.items.len > 1) for (of.fields) |field| if ((field.reads == .pointer or field.reads == .protected) and field.len == 8) {
        const addr = of.base + field.at;
        for (at_rows.items) |r| if (addr >= r.addr and addr < r.addr + 16) pointerArcs(&arcs, now, addr, r.y, at_rows.items, 16, .{ y - m.pad, ry + m.pad }, false, field.reads == .protected);
    };
    arcs.draw(u, theme.metric.arc.lanes.len);
    if (of.pins) @import("map.zig").window(.view, .{ of.base + 16 * shown[0], of.base + 16 * shown[shown.len - 1] }, .{ of.base + 16 * shown[0], of.base + 16 * shown[shown.len - 1] }, 1);
}

/// Which of `rs` (rows of fields, the region's last row `last`) a window
/// of `room` rows shows: as many as fit round `rs[focus_at]`, each row a
/// line and each stretch left out (before, between, after) a `more` line.
fn keep(rs: []const u64, focus_at: usize, room: usize, last: u64) [2]usize {
    const lines = struct {
        fn count(all: []const u64, lo: usize, hi: usize, end: u64) usize {
            var n = hi - lo + @intFromBool(all[lo] > 0) + @intFromBool(all[hi - 1] < end);
            for (all[lo .. hi - 1], all[lo + 1 .. hi]) |a, b2| n += @intFromBool(b2 > a + 1);
            return n;
        }
    }.count;
    var lo = focus_at;
    var hi = lo + 1;
    while (true) {
        const before = hi - lo;
        if (hi < rs.len and lines(rs, lo, hi + 1, last) <= room) hi += 1;
        if (lo > 0 and lines(rs, lo - 1, hi, last) <= room) lo -= 1;
        if (hi - lo == before) break;
    }
    return .{ lo, hi };
}

test "a dump of more rows of fields than its window keeps those round its focus" {
    // A page's header row, then two cells at its end: all fit in seven.
    try std.testing.expectEqual([2]usize{ 0, 3 }, keep(&.{ 0, 254, 255 }, 0, 7, 255));
    // Ten rows with gaps, a window of five round the sixth: two rows, a `more` before, between and after.
    const spread = [_]u64{ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18 };
    try std.testing.expectEqual([2]usize{ 5, 7 }, keep(&spread, 5, 5, 18));
    // Rows next to each other, the window of five round the last: four rows and a `more` before.
    const run = [_]u64{ 0, 1, 2, 3, 4, 5, 6, 7 };
    try std.testing.expectEqual([2]usize{ 4, 8 }, keep(&run, 7, 5, 7));
}

/// Whether row `r` of the region holds a field.
fn holdsField(of: Fields, r: u64) bool {
    const lo = of.base + 16 * r;
    for (of.fields) |field| if (of.base + field.at < lo + 16 and of.base + field.at + field.len > lo) return true;
    return false;
}

/// Which of `rs` (rows of fields) the window is kept round: the first a
/// mark shows on, else the first the step wrote or read, else the first.
fn focus(now: cursors.Now, of: Fields, rs: []const u64) usize {
    for (rs, 0..) |r, k| for (of.fields) |field| {
        if (field.at >= 16 * r + 16 or field.at + field.len <= 16 * r) continue;
        if (field.mark) |i| if (i < of.marks.len and of.marks[i] > 0) return k;
    };
    for (rs, 0..) |r, k| {
        const span: Recording.Span = .{ .addr = of.base + 16 * r, .len = 16 };
        if (Recording.touches(now.rec.written(now.stops[1], now.stops[0]), span.addr, span.len) or Recording.touches(now.rec.read(now.stops[1], now.stops[0]), span.addr, span.len)) return k;
    }
    return 0;
}

fn fieldRow(u: ui.Ui, now: cursors.Now, y: f32, addr: u64, moment: Recording.Moment, of: Fields, lead: usize, shift: f32, room: f32) void {
    var values: [16]u8 = undefined;
    var known: [16]bool = undefined;
    moment.read(addr, &values, &known) catch return;
    if (of.seen) |seen| for (&known, 0..) |*k, i| {
        if (addr + i < seen.addr or addr + i >= seen.addr + seen.len) k.* = false;
    };
    // What a call was given is as the kernel took it, and not what the
    // recording saw there before (a debugger reads a buffer it is not
    // watching only where a pointer leads, 32 bytes at a stop: the rest
    // is as it was when last seen): it comes in over what was drawn.
    var given_values = values;
    var given_known = known;
    var gives = false;
    var given_from: u8 = 16;
    var given_to: u8 = 0;
    if (of.given) |g| for (0..16) |i| {
        const a = addr + i;
        if (a < g.addr or a >= g.addr + g.bytes.len) continue;
        // Each byte as its strike lands (s+3), the fill coming in under it: never in a frame.
        if (g.since) |since| if (since < @as(f32, @floatFromInt(a - g.addr)) * @import("syscalls.zig").Plan.byte + theme.time.strike.in / 2.0) continue;
        given_values[i] = g.bytes[a - g.addr];
        given_known[i] = true;
        gives = true;
        given_from = @min(given_from, @as(u8, @intCast(i)));
        given_to = @max(given_to, @as(u8, @intCast(i)));
    };
    var runs: [16]rows.Run = undefined;
    var readings: [16]Field = undefined;
    var keeps: [16]bool = @splat(false);
    var n: usize = 0;
    var at: u8 = 0;
    while (at < 16 and addr + at < of.base + of.len) {
        const here = addr + at;
        var field_k: usize = 0;
        const field = for (of.fields, 0..) |field, fk| {
            if (of.base + field.at <= here and here < of.base + field.at + field.len) {
                field_k = fk;
                break field;
            }
        } else null;
        var run: rows.Run = .{ .first = at, .len = 1, .kind = .loose };
        if (field) |fl| {
            run.len = @intCast(@min(of.base + fl.at + fl.len - here, 16 - @as(u64, at)));
            run.kind = switch (fl.reads) {
                .number, .bytes, .size, .protected => .number,
                .pointer => .pointer,
                .text => .text,
            };
            run.heat = now.writtenWatched(here, run.len, .memory, 0, 0, of.watched);
            run.changed = now.changedBytes(here, run.len);
            // Until its own strike lands the old value stands: the loupe's own times, or memory's.
            const ago = if (of.struck) |since| (if (now.walking() and now.writeAge(here, run.len) == 0) since - @as(f32, @floatFromInt(field_k)) * cursors.write_apart else null) else if (of.watched > 0) now.struckAgo(here, run.len) else null;
            if (ago) |a| keeps[n] = a < theme.time.strike.in / 2.0;
            if (of.struck) |since| run.heat = now.writtenAt(here, run.len, since - @as(f32, @floatFromInt(field_k)) * cursors.write_apart);
            // What the kernel fills lands a byte every 2 f.
            if (@import("syscalls.zig").filledAt(now, here) != null) run.apart = 2;
            givenStrike(now, of, here, &run);
            var framed: f32 = 0;
            if (fl.mark) |k| if (k < of.marks.len) {
                framed = of.marks[k];
            };
            if (of.watched > 0 and now.wasRead(here, run.len) and now.writeAge(here, run.len) != 0) framed = @max(framed, now.reading(.memory, 0));
            run.read = framed;
            readings[n] = .{ .at = at, .len = run.len, .reads = fl.reads, .big = fl.big, .type = fl.type, .note = fl.note, .addr = here };
            // Its old bytes read as what they were until its strike lands (the step retypes the field: malloc's).
            if (keeps[n]) for (of.was) |old| if (of.base + old.at <= here and here < of.base + old.at + old.len) {
                readings[n] = .{ .at = at, .len = run.len, .reads = old.reads, .big = old.big, .type = old.type, .note = old.note, .addr = here };
                run.kind = switch (old.reads) {
                    .number, .bytes, .size, .protected => .number,
                    .pointer => .pointer,
                    .text => .text,
                };
                break;
            };
            ties.anchor(u, .{ .dump_run = here }, .{ .x = shift + rows.byteX(run.first) - 4, .y = y, .w = rows.byteX(run.first + run.len - 1) + 28 - rows.byteX(run.first) + 4, .h = m.row });
        } else {
            // Up to the next field, or the row's end.
            var end: u64 = @min(16, of.base + of.len - addr);
            for (of.fields) |other| if (of.base + other.at > here and of.base + other.at < addr + end) {
                end = of.base + other.at - addr;
            };
            run.len = @intCast(end - at);
            readings[n] = .{ .at = at, .len = run.len, .reads = .bytes };
            givenStrike(now, of, here, &run);
        }
        runs[n] = run;
        n += 1;
        at += run.len;
    }
    keepOld(now, addr, &values, &known, runs[0..n], keeps[0..n]);
    // The kernel reading them: one frame round what it took of the row.
    if (gives and of.read > 0) u.faded(of.read).frame(.{ .x = shift + rows.byteX(given_from) - 7, .y = y - 1, .w = rows.byteX(given_to) - rows.byteX(given_from) + 38, .h = m.row + 2 }, theme.mark(.read).solid, 2);
    const shows = if (of.given) |g| g.shows else 0;
    if (gives and shows > 0) {
        if (shows < 1) rows.bytesAt(u.faded(1 - shows), y, addr, &values, &known, runs[0..n], of.region, lead, true, moment, shift);
        rows.bytesAt(u.faded(shows), y, addr, &given_values, &given_known, runs[0..n], of.region, lead, true, moment, shift);
        _ = readingIn(u.faded(shows), y, shift, moment, &given_values, &given_known, readings[0..n], room);
    } else {
        rows.bytesAt(u, y, addr, &values, &known, runs[0..n], of.region, lead, true, moment, shift);
        _ = readingIn(u, y, shift, moment, &values, &known, readings[0..n], room);
    }
}

/// `bytes`'s reading, for every dump: what a row's runs (`fields`, from
/// the row's first byte) read as, left to right, a character apart, from
/// 508 after the first byte (`shift` right of 640): a number in decimal,
/// in its byte order, or as its type says (`objects.reading`: a `char`
/// quoted, a `bool` by name); a pointer as `points` and its address,
/// `NULL` dim; text in quotes, C's escapes; bytes left to the eye, or
/// `loose`, as nothing. Cut where the panel ends, with `…`. Returns where
/// it ends.
pub fn reading(u: ui.Ui, y: f32, shift: f32, moment: Recording.Moment, values: *const [16]u8, known: *const [16]bool, fields: []const Field) f32 {
    return readingIn(u, y, shift, moment, values, known, fields, full_room);
}

/// The panel's width less its side: where a reading ends with no pin at its row's end.
const full_room = theme.layout.state.w - theme.metric.context.side;

/// A view's: less its strip, in the working frame.
fn viewRoom() f32 {
    return @import("map.zig").content(full_room);
}

/// `reading`, ending at `room` (a pin at the row's end takes the rest).
pub fn readingIn(u: ui.Ui, y: f32, shift: f32, moment: Recording.Moment, values: *const [16]u8, known: *const [16]bool, fields: []const Field, room: f32) f32 {
    const size = theme.size.mono.context;
    const base = rows.baseline(y);
    var x: f32 = b.reading + shift;
    for (fields) |fl| {
        const first: usize = @intCast(fl.at);
        // A typed number is as wide as its type (an `int` in a word: 4 bytes).
        const len: usize = @intCast(if (fl.type) |ty| @min(fl.len, ty.size() orelse fl.len) else fl.len);
        if (len == 0 or std.mem.indexOfScalar(bool, known[first..][0..len], false) != null) continue;
        defer if (fl.note.len > 0) {
            // Cut where the panel ends, at a word, with `…`; never mid-word without it.
            var note = fl.note;
            while (note.len > 0 and x + u.width(.sans, theme.size.sans.micro, if (note.len == fl.note.len) note else u.print("{s}\u{2026}", .{note})) > room) {
                note = std.mem.trimEnd(u8, note[0 .. std.mem.lastIndexOfScalar(u8, note, ' ') orelse 0], " \u{00b7}");
            }
            if (note.len > 0) {
                const said = if (note.len == fl.note.len) note else u.print("{s}\u{2026}", .{note});
                u.text(.sans, theme.size.sans.micro, x, base - 1, said, t.faint);
                x += u.width(.sans, theme.size.sans.micro, said) + adv;
            }
        };
        if (fl.reads == .bytes) continue;
        const bytes = values[first..][0..len];
        var word_: u64 = 0;
        for (0..@min(len, 8)) |k| word_ |= @as(u64, bytes[k]) << @intCast(8 * k);
        switch (fl.reads) {
            .size => {
                const shown_size = u.print("0x{x}", .{word_ & ~@as(u64, 7)});
                u.text(.mono, size, x, base, shown_size, t.primary);
                x += u.width(.mono, size, shown_size) + adv;
                // A M P: set on a chip, clear in dim lower case.
                for ([_]struct { u8, u6 }{ .{ 'A', 2 }, .{ 'M', 1 }, .{ 'P', 0 } }) |bit| {
                    const set = word_ >> bit[1] & 1 != 0;
                    if (set) u.chip(.{ .x = x - 3, .y = y + 2, .w = adv + 6, .h = theme.metric.flags.chip[1] });
                    u.text(if (set) .mono_bold else .mono, size, x, base, &.{if (set) bit[0] else std.ascii.toLower(bit[0])}, if (set) t.bright else t.dim);
                    x += 2 * adv;
                }
                continue;
            },
            .protected => {
                const target = word_ ^ (fl.addr >> 12);
                if (target == 0) {
                    u.text(.mono, size, x, base, "NULL", t.dim);
                    x += 5 * adv;
                } else {
                    x = u.arrow(x, y + m.row / 2, .points);
                    x = u.address(x, base, target, .{ .ink = ui.rgb(rows.ink(rows.regionOf(moment, target))) }) + adv;
                }
                const masked = u.print("^ {x}", .{fl.addr >> 12});
                u.text(.mono, size, x, base, masked, t.faint);
                x += u.width(.mono, size, masked) + adv;
                continue;
            },
            else => {},
        }
        const words: []const u8 = switch (fl.reads) {
            .number => blk: {
                var word: u64 = 0;
                for (0..@min(len, 8)) |k| word |= @as(u64, bytes[if (fl.big) len - 1 - k else k]) << @intCast(8 * k);
                const ty = fl.type orelse break :blk u.print("{d}", .{word});
                const shift_bits: u6 = @intCast(64 - 8 * @as(u64, @min(len, 8)));
                const signed = ty == .scalar and ty.scalar.kind == .int;
                break :blk objects.reading(u.f.scratch, if (signed) @as(i64, @bitCast(word << shift_bits)) >> shift_bits else @bitCast(word), ty);
            },
            .pointer => blk: {
                var word: u64 = 0;
                for (0..@min(len, 8)) |k| word |= @as(u64, bytes[k]) << @intCast(8 * k);
                if (word == 0) break :blk "NULL";
                // The arrow has its own room, as in a chain: no character before it.
                const ax = if (x > b.reading + shift) x - adv else x;
                if (ax + theme.metric.context.arrow_w + @as(f32, @floatFromInt(ui.digits(word))) * adv > room) break :blk "\u{2026}";
                x = u.arrow(ax, y + m.row / 2, .points);
                x = u.address(x, base, word, .{ .ink = ui.rgb(rows.ink(rows.regionOf(moment, word))) }) + adv;
                continue;
            },
            .text => quoted(u, bytes),
            .bytes, .size, .protected => unreachable,
        };
        const w = u.width(.mono, size, words);
        const fits = x + w <= room;
        const shown = if (fits) words else rows.fitted(u, words, room - x);
        const ink = if (fl.reads == .text) theme.color.string else if (std.mem.eql(u8, words, "NULL")) t.dim else t.primary;
        u.text(.mono, size, x, base, shown, ink);
        if (!fits) return room;
        x += w + adv;
    }
    return x;
}

/// Bytes as C text, in quotes: the printable as they are, the rest by C's
/// escapes; a NUL ends it.
fn quoted(u: ui.Ui, bytes: []const u8) []const u8 {
    const a = u.f.scratch;
    var out: std.ArrayList(u8) = .empty;
    out.append(a, '"') catch return "";
    for (bytes) |c| {
        if (c == 0) break;
        switch (c) {
            '\n' => out.appendSlice(a, "\\n") catch {},
            '\t' => out.appendSlice(a, "\\t") catch {},
            '"', '\\' => out.appendSlice(a, &.{ '\\', c }) catch {},
            else => if (std.ascii.isPrint(c)) out.append(a, c) catch {} else out.print(a, "\\x{x:0>2}", .{c}) catch {},
        }
    }
    out.append(a, '"') catch {};
    return out.items;
}