summaryrefslogtreecommitdiff
path: root/gui/src/app.zig
blob: f5ebf3dbbf53867c9d3bd6438d886655541a6e98 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
const std = @import("std");
const sk = @import("sketch");
const canim = @import("canim");
const zt = @import("ztrace");
const ui = canim.ui;
const Client = @import("Client.zig");
const Navigation = @import("Navigation.zig");
const Geometry = @import("Geometry.zig");
const Sources = @import("Sources.zig");
var sources: Sources = .{};
pub const name = "ztrace debugger";
pub const width = 2240;
pub const height = 1260;
pub var io: std.Io = undefined;
pub var gpa: std.mem.Allocator = undefined;
var trace: ?zt.Trace = null;
var client: ?*Client = null;
var latest: Client.Update = .{};
var loaded: u64 = 0;
var launch_command: ?[]const u8 = null;
pub const State = struct {
    launches: u32 = 0,
    moment: u64 = 0,
    tid: u32 = 0,
    following: bool = true,
    status: zt.control.Status = .stopped,
    stops: u64 = 0,
    execution: u64 = 0,
    pc: u64 = 0,
    action: sk.Request(Action) = .{},
    nav: [3]Navigation = @splat(.{}),
    focus: Pane = .code,
    maps: [3]bool = @splat(true),
    source: bool = true,
    source_column: u16 = 0,
    annotations: bool = true,
    depth: u8 = 4,
    ascii: bool = true,
    unit: u8 = 1,
    number_format: canim.rows.NumberFormat = .hex,
    selected_address: u64 = 0,
    selected_box: Box = .{},
    glass: bool = true,
    zoom: u16 = 100,
    page_scroll: f32 = 0,
    register_scroll: f32 = 0,
    horizontal: [3]f32 = @splat(0),
    graph: bool = false,
    dim: u8 = 75,
    segments: bool = false,
    segment_query: [128]u8 = @splat(0),
    segment_len: u8 = 0,
    segment_row: u32 = 0,
    origin: u64 = 0,
    lenses: [32]Lens = @splat(.{}),
    lens_count: u8 = 0,
    lens_scroll: f32 = 0,
    lens: bool = false,
    lens_address: u64 = 0,
    lens_origin: Box = .{},
    help: bool = false,
    prefix: u8 = 0,
    command_open: bool = false,
    command_text: [512]u8 = @splat(0),
    command_len: u16 = 0,
    drag_map: ?Pane = null,
    drag_content: bool = false,
};
pub const Session = struct {
    launches: u32 = 0,
    action: sk.Handled = .{},
    graph: bool = false,
    scroll: [3]f64 = @splat(0),
    base: [3]u64 = @splat(0),
    mini: [3]ui.Collected = @splat(.{}),
    mini_key: [3]u64 = @splat(0),
    listing_at: ?u64 = null,
    listing_base: u64 = 0,
    code: [256]canim.disasm.Insn = undefined,
    code_text: [256][1024]u8 = undefined,
    code_lines: [256]?zt.store.Line = undefined,
    code_count: usize = 0,
    aligned: [512]canim.aligned.LiveRow = undefined,
    aligned_count: usize = 0,
    marker_key: u64 = 0,
    marker_base: u64 = 0,
    marker_from: f32 = 0,
    marker_to: f32 = 0,
    marker_shown: f32 = 0,
    marker_at: u64 = 0,
    inspected: [3]u64 = @splat(0),
    capture_stop: u64 = 0,
    origin_line: ?zt.store.Line = null,
    lens_at: u64 = 0,
    lens_previous: u64 = 0,
    lens_inspected: [32]u64 = @splat(0),
    match_address: u64 = 0,
    match_box: Box = .{},
    match_at: u64 = 0,

    shown: ?u64 = null,
    tid: u32 = 0,
    changed_at: u64 = 0,
    changed_regs: u32 = 0,
    changed_stack: u16 = 0,
    changed_flags: u64 = 0,
    code_start: u64 = 0,
    trail: [3]u64 = @splat(0),
    result_at: ?u64 = null,
    touch: ?canim.Recording.Touch = null,
    branch: ?canim.Recording.Branch = null,
};
const Pane = enum { code, stack, memory };
const Lens = struct { address: u64 = 0, first: u64 = 0, focus_end: u64 = 0, origin: Box = .{}, cycle: bool = false };
const Kind = enum { unit, number_format, restart, graph, dim, segments, select_segment, cont, pause, stepi, step, previous, next, live, follow, back, forward, source, map, annotate, shallower, deeper, ascii, lens, close_lens, help, breakpoint, command, go, submit };
const Action = struct { kind: Kind, pane: Pane = .code, address: u64 = 0, manual: bool = false };
const Box = sk.Rect;
var geometry = Geometry.init(width, height, 0);
var display_scale: f32 = 1;
var panes = Geometry.init(width, height, 0).panes;
var ranges: [3]zt.store.Mapping = @splat(.{ .addr = 0, .len = 2048, .prot = 0, .offset = 0 });
var code_after: u64 = 0;
var code_before: u64 = 0;
var code_top: f32 = 32;
var origin_height: f32 = 72;
var source_height: f32 = 48;
var compact_rows: [256]usize = undefined;
var compact_count: usize = 0;
var compact_addresses: [3][128]u64 = undefined;
var compact_counts: [3]usize = @splat(0);
var current_lens: ?u8 = null;
var lens_boxes: [32]Box = undefined;
var segment_hits: [64]struct { box: Box, address: u64 } = undefined;
var segment_hit_count: usize = 0;
var segment_total: u32 = 0;
const Hit = struct { address: u64, box: Box, lens: ?u8 };
const Button = struct { action: Action, box: Box, label: []const u8, enabled: bool };
var hits: [2048]Hit = undefined;
var hit_count: usize = 0;
var buttons: [128]Button = undefined;
var button_count: usize = 0;
var extents: [3]f64 = @splat(0);
var bases: [3]u64 = @splat(0);
var shown_scroll: [3]f64 = @splat(0);
var tooltip: ?Button = null;
var lens_box: ?Box = null;
var drawn_lenses: usize = 0;

pub fn close() void {
    sources.close(gpa);
    if (trace) |*t| t.close();
    trace = null;
    if (client) |c| c.close();
    client = null;
    if (launch_command) |saved| gpa.free(saved);
    launch_command = null;
}

pub fn command(s: *State, c: *sk.Console, line: []const u8) !bool {
    var words = std.mem.tokenizeScalar(u8, line, ' ');
    const cmd = words.next() orelse return false;
    if (std.mem.eql(u8, cmd, "launch") or std.mem.eql(u8, cmd, "restart")) {
        const restart = std.mem.eql(u8, cmd, "restart");
        if (client != null and !restart) return error.AlreadyLaunched;
        const args = if (restart) launch_command orelse return error.NoLaunchCommand else words.rest();
        const saved = try gpa.dupe(u8, args);
        var retained = false;
        defer if (!retained) gpa.free(saved);
        var arguments = std.mem.tokenizeScalar(u8, saved, ' ');
        var argv: std.ArrayList([]const u8) = .empty;
        defer argv.deinit(gpa);
        // shortcut: whitespace-separated argv; add quoting when launch needs arguments containing spaces.
        while (arguments.next()) |word| try argv.append(gpa, word);
        if (argv.items.len == 0) return error.MissingProgram;
        if (launch_command) |old| gpa.free(old);
        launch_command = saved;
        retained = true;
        if (client) |old| old.close();
        client = null;
        if (trace) |*old| old.close();
        trace = null;
        sources.clear(gpa);
        latest = .{};
        loaded = 0;
        s.* = .{ .launches = s.launches + 1, .status = .running, .zoom = s.zoom, .maps = s.maps, .source = s.source, .annotations = s.annotations, .depth = s.depth, .ascii = s.ascii, .unit = s.unit, .number_format = s.number_format, .glass = s.glass, .dim = s.dim };
        client = Client.start(gpa, io, argv.items) catch |err| {
            s.status = .failed;
            return err;
        };
        if (sources.paths) |paths| for (paths.source_maps.items) |map| {
            const mapped = try std.fmt.allocPrint(gpa, "source-map {s} {s}", .{ map.from, map.to });
            defer gpa.free(mapped);
            try client.?.send(mapped);
        };
        return true;
    }
    if (std.mem.eql(u8, cmd, "observed")) {
        if (latest.moments != s.stops and (std.mem.eql(u8, latest.reason(), "step") or std.mem.startsWith(u8, latest.reason(), "signal ") or (std.mem.startsWith(u8, latest.reason(), "breakpoint ") and !std.mem.endsWith(u8, latest.reason(), " set")))) {
            s.execution += 1;
            if (s.nav[0].place.follow) s.page_scroll = 0;
            for (&s.nav) |*n| if (n.place.follow) {
                n.place.manual = false;
            };
        }
        s.status = latest.status;
        s.stops = latest.moments;
        s.pc = latest.pc;
        if (s.following) {
            s.moment = latest.moments -| 1;
            s.tid = latest.tid;
        }
        return true;
    }
    if (std.mem.eql(u8, cmd, "live")) {
        s.following = true;
        s.moment = latest.moments -| 1;
        return true;
    }
    if (std.mem.eql(u8, cmd, "source-map")) {
        const from = words.next() orelse return error.MissingPrefix;
        const to = words.next() orelse return error.MissingPath;
        if (words.next() != null) return error.InvalidSourceMap;
        try sources.map(gpa, io, from, to);
        if (client) |target| try target.send(line);
        return true;
    }
    if (std.mem.eql(u8, cmd, "inspect") or std.mem.eql(u8, cmd, "symbols") or std.mem.eql(u8, cmd, "break") or std.mem.eql(u8, cmd, "clear") or std.mem.eql(u8, cmd, "signal") or std.mem.eql(u8, cmd, "continue") or std.mem.eql(u8, cmd, "interrupt") or std.mem.eql(u8, cmd, "stepi") or std.mem.eql(u8, cmd, "nextline")) {
        try (client orelse return error.NoTarget).send(if (std.mem.eql(u8, cmd, "interrupt")) "pause" else if (std.mem.eql(u8, cmd, "nextline")) "step" else line);
        if (std.mem.eql(u8, cmd, "continue") or (std.mem.eql(u8, cmd, "stepi") or std.mem.eql(u8, cmd, "nextline"))) s.following = true;
        return true;
    }
    if (std.mem.eql(u8, cmd, "lens")) {
        const address = try std.fmt.parseInt(u64, words.next() orelse return error.MissingAddress, 0);
        if (words.next() != null) return error.InvalidAddress;
        openLens(s, .{ .address = address, .box = .{}, .lens = null });
        return true;
    }
    if (std.mem.eql(u8, cmd, "memory-format")) {
        const unit = try std.fmt.parseInt(u8, words.next() orelse return error.MissingSize, 10);
        if (unit != 1 and unit != 2 and unit != 4 and unit != 8) return error.InvalidSize;
        const format = std.meta.stringToEnum(canim.rows.NumberFormat, words.next() orelse return error.MissingFormat) orelse return error.InvalidFormat;
        if (words.next() != null or (format == .float and unit < 4)) return error.InvalidFormat;
        s.unit = unit;
        s.number_format = format;
        return true;
    }
    if (std.mem.eql(u8, cmd, "origin")) {
        s.origin = try std.fmt.parseInt(u64, words.next() orelse return error.MissingAddress, 0);
        return true;
    }
    if (std.mem.eql(u8, cmd, "goto") or std.mem.eql(u8, cmd, "browse")) {
        const which = words.next() orelse return error.MissingPane;
        const pane = std.meta.stringToEnum(Pane, which) orelse return error.InvalidPane;
        const address = try std.fmt.parseInt(u64, words.next() orelse return error.MissingAddress, 0);
        if (std.mem.eql(u8, cmd, "goto")) s.nav[@backingInt(pane)].visit(address) else {
            s.nav[@backingInt(pane)].place.address = address;
            s.nav[@backingInt(pane)].place.row = 0;
            s.nav[@backingInt(pane)].place.manual = true;
        }
        s.focus = pane;
        if (client != null and s.status == .stopped and s.following) {
            var buf: [96]u8 = undefined;
            try client.?.send(try std.fmt.bufPrint(&buf, "inspect {s} 0x{x} {d}", .{ if (pane == .code) "code" else "memory", address, @as(u32, if (pane == .code) 128 else 2048) }));
        }
        return true;
    }
    if (std.mem.eql(u8, cmd, "mouse-button")) {
        // The headless host has no non-left click syntax; exercise the actual handler.
        const code = try std.fmt.parseInt(u16, words.next() orelse return error.MissingButton, 10);
        const x = try std.fmt.parseFloat(f32, words.next() orelse return error.MissingX);
        const y = try std.fmt.parseFloat(f32, words.next() orelse return error.MissingY);
        pointer(s, code, x / display_scale, y / display_scale);
        return true;
    }
    if (!std.mem.eql(u8, cmd, "open")) return false;
    if (client != null) return error.TargetActive;
    const path = words.next() orelse return error.MissingPath;
    var next = try zt.Trace.open(gpa, io, path);
    errdefer next.close();
    if (next.len == 0) return error.EmptyRecording;
    var events = try (try next.moment(next.len - 1)).events(gpa);
    defer events.deinit(gpa);
    if (trace) |*t| t.close();
    sources.close(gpa);
    trace = next;
    s.moment = next.len -| 1;
    s.stops = next.len;
    s.following = false;
    while (events.next()) |e| if (e.ev.tid != 0) {
        s.tid = e.ev.tid;
    };
    c.print("opened {d} moments", .{next.len});
    return true;
}

fn contains(r: Box, x: f32, y: f32) bool {
    return x >= r.x and y >= r.y and x < r.x + r.w and y < r.y + r.h;
}
fn paneAt(x: f32, y: f32) ?Pane {
    for (panes, 0..) |box, i| if (contains(box, x, y)) return @fromBackingInt(@intCast(i));
    return null;
}
fn addressAt(x: f32, y: f32) ?Hit {
    var i = hit_count;
    var owner: ?u8 = null;
    for (lens_boxes[0..drawn_lenses], 0..) |box, k| if (lens_box != null and contains(lens_box.?, x, y) and contains(box, x, y)) {
        owner = @intCast(k);
    };
    const floor: usize = 0;
    while (i > floor) {
        i -= 1;
        if (hits[i].lens == owner and contains(hits[i].box, x, y)) return hits[i];
    }
    return null;
}
fn collectAddress(_: *anyopaque, address: u64, box: Box) void {
    if (hit_count == hits.len) return;
    hits[hit_count] = .{ .address = address, .box = Geometry.scaled(box, 1 / display_scale), .lens = current_lens };
    hit_count += 1;
}
fn scroll(s: *State, pane: Pane, delta: f64) void {
    const p = @backingInt(pane);
    const n = &s.nav[p];
    if (!n.place.manual) n.place.row = shown_scroll[p];
    n.place.manual = true;
    const next = n.place.row + delta;
    if (pane == .code and !s.graph and (next < 0 or next > extents[0])) {
        const address = if (next < 0) code_before else code_after;
        if (address >= ranges[0].addr and address < ranges[0].addr +| ranges[0].len) {
            n.place.address = address;
            n.place.row = 0;
            s.action.send(.{ .kind = .go, .pane = .code, .address = address, .manual = true });
            return;
        }
    }
    n.place.row = std.math.clamp(next, 0, extents[p]);
}
fn act(s: *State, a: Action) void {
    const p = @backingInt(a.pane);
    switch (a.kind) {
        .graph => {
            s.graph = !s.graph;
            s.nav[0].place.row = 0;
            s.nav[0].place.manual = s.graph;
            s.horizontal[0] = 0;
        },
        .dim => s.dim = if (s.dim >= 100) 25 else s.dim + 25 - s.dim % 25,
        .segments => {
            s.segments = !s.segments;
            s.segment_len = 0;
            s.segment_row = 0;
        },
        .select_segment => {
            s.segments = false;
            s.action.send(.{ .kind = .go, .pane = a.pane, .address = a.address });
        },
        .previous => {
            s.following = false;
            s.moment -|= 1;
        },
        .next => {
            s.following = false;
            s.moment = @min(s.moment +| 1, s.stops -| 1);
        },
        .live => {
            s.following = true;
            s.moment = s.stops -| 1;
        },
        .follow => {
            s.nav[p].place = .{};
        },
        .back => s.nav[p].back(),
        .forward => s.nav[p].forward(),
        .source => s.source = !s.source,
        .map => s.maps[p] = !s.maps[p],
        .annotate => s.annotations = !s.annotations,
        .shallower => s.depth = @max(1, s.depth -| 1),
        .deeper => s.depth = @min(6, s.depth + 1),
        .ascii => s.ascii = !s.ascii,
        .unit => {
            s.unit = if (s.unit >= 8) 1 else s.unit * 2;
            if (s.number_format == .float and s.unit < 4) s.number_format = .hex;
        },
        .number_format => {
            s.number_format = @fromBackingInt(@intCast(@backingInt(s.number_format) +% 1));
            if (s.number_format == .float and s.unit < 4) s.unit = 4;
        },
        .lens => {
            if (s.lens) {
                s.lens = false;
                s.lens_count = 0;
            } else openLens(s, .{ .address = a.address, .box = .{}, .lens = null });
        },
        .close_lens => {
            s.lens_count = @intCast(@min(a.address, s.lens_count));
            s.lens = s.lens_count > 0;
            s.lens_scroll = @min(s.lens_scroll, lensScroll(s.lens_count, true));
        },
        .help => s.help = !s.help,
        .command => {
            s.command_open = true;
            s.command_len = 0;
        },
        else => s.action.send(a),
    }
}
fn semantic(s: *State, address: u64) void {
    const t = if (trace) |*t| t else return;
    const m = t.moment(@min(s.moment, t.len -| 1)) catch return;
    const pane: Pane = if (canim.rows.regionOf(m, address) == .stack) .stack else .memory;
    s.lens_address = address;
    s.focus = pane;
    s.action.send(.{ .kind = .go, .pane = pane, .address = address });
}
fn mapDrag(s: *State, pane: Pane, y: f32) void {
    const p = @backingInt(pane);
    const box = panes[p];
    const ratio = std.math.clamp((y - box.y - 32) / (box.h - 40), 0, 1);
    if (pane == .code and s.drag_content and compact_count > 0) {
        const index: usize = @min(compact_count - 1, @as(usize, @intFromFloat(ratio * @as(f32, @floatFromInt(compact_count)))));
        s.nav[0].place.manual = true;
        s.nav[0].place.row = @min(extents[0], @as(f64, @floatFromInt(compact_rows[index])));
    } else if (pane != .code and s.drag_content and compact_counts[p] > 0) {
        const index: usize = @min(compact_counts[p] - 1, @as(usize, @intFromFloat(ratio * @as(f32, @floatFromInt(compact_counts[p])))));
        s.nav[p].place.manual = true;
        s.nav[p].place.row = @floatFromInt((compact_addresses[p][index] - ranges[p].addr) / (if (p == 1) @as(u64, 8) else 16));
    } else if (pane == .code) {
        const address = ranges[p].addr + @as(u64, @intFromFloat(ratio * @as(f64, @floatFromInt(ranges[p].len -| 1))));
        s.action.send(.{ .kind = .go, .pane = pane, .address = address, .manual = true });
    } else {
        s.nav[p].place.manual = true;
        s.nav[p].place.row = ratio * extents[p];
    }
}
fn openLens(s: *State, hit: Hit) void {
    const at: u8 = if (hit.lens) |i| i + 1 else 0;
    if (at == s.lenses.len) return;
    var cycle = false;
    for (s.lenses[0..at]) |lens| if (lens.address == hit.address) {
        cycle = true;
    };
    const m = if (trace) |*t| t.moment(@min(s.moment, t.len -| 1)) catch return else return;
    const first = if (executable(m, hit.address)) hit.address else (hit.address & ~@as(u64, 15)) -| 32;
    var focus_end = first +| 80;
    if (executable(m, hit.address)) {
        focus_end = first;
        for (0..6) |_| {
            var text: [1024]u8 = undefined;
            const insn = (zt.telescope.instruction(m, focus_end, &text) catch null) orelse break;
            if (insn.len == 0) break;
            focus_end +|= insn.len;
        }
        if (focus_end == first) focus_end = first +| 24;
    }
    s.lenses[at] = .{ .address = hit.address, .first = first, .focus_end = focus_end, .origin = hit.box, .cycle = cycle };
    s.lens_count = at + 1;
    s.lens = true;
    s.lens_address = hit.address;
    s.lens_scroll = lensScroll(s.lens_count, true);
}
fn executable(m: zt.store.Moment, address: u64) bool {
    const map = (m.mapping(address, null, &.{}) catch null) orelse return false;
    return map.prot & 4 != 0;
}
fn scrollLens(s: *State, index: usize, rows: f32) void {
    const m = if (trace) |*t| t.moment(@min(s.moment, t.len -| 1)) catch return else return;
    const lens = &s.lenses[index];
    if (lens.cycle) return;
    const map = (m.mapping(lens.address, null, &.{}) catch null) orelse return;
    const count: usize = @min(64, @as(usize, @intFromFloat(@ceil(@abs(rows)))));
    for (0..count) |_| {
        var buf: [1024]u8 = undefined;
        const insn = if (executable(m, lens.address)) zt.telescope.instruction(m, lens.first, &buf) catch null else null;
        const step: u64 = if (executable(m, lens.address)) (if (insn) |v| if (rows < 0) @max(1, v.back) else @max(1, v.len) else 1) else 16;
        lens.first = std.math.clamp(if (rows < 0) lens.first -| step else lens.first +| step, map.addr, map.addr +| map.len -| 1);
    }
}

fn lensViewport() Box {
    const y = @max(140, geometry.top + 12);
    return .{ .x = @max(24, geometry.w - 1132), .y = y, .w = @min(1108, geometry.w - 48), .h = @max(0, geometry.h - y - 40) };
}
fn lensScroll(count: u8, reveal_header: bool) f32 {
    const room = if (reveal_header) @max(188, lensViewport().h) else lensViewport().h;
    return @max(0, @as(f32, @floatFromInt(count)) * 204 - 16 - room);
}
fn enabled(s: *const State, a: Action) bool {
    return switch (a.kind) {
        .restart => launch_command != null,
        .cont, .stepi, .step, .breakpoint => client != null and s.status == .stopped,
        .pause => client != null and s.status == .running,
        .back => s.nav[@backingInt(a.pane)].cursor > 0,
        .forward => s.nav[@backingInt(a.pane)].cursor + 1 < s.nav[@backingInt(a.pane)].len,
        else => true,
    };
}
fn pointer(s: *State, mouse_button: u16, x: f32, y: f32) void {
    if (s.help) return;
    if (s.segments) {
        if (mouse_button == 1) for (segment_hits[0..segment_hit_count]) |hit| if (contains(hit.box, x, y)) {
            act(s, .{ .kind = .select_segment, .pane = s.focus, .address = hit.address });
            return;
        };
        return;
    }
    if (addressAt(x, y)) |hit| {
        s.selected_address = hit.address;
        s.selected_box = hit.box;
    }
    if (paneAt(x, y)) |pane| s.focus = pane;
    if (mouse_button == 4 or mouse_button == 5) {
        act(s, .{ .kind = if (mouse_button == 4) .back else .forward, .pane = s.focus });
        return;
    }
    if (mouse_button == 3) {
        if (addressAt(x, y)) |hit| semantic(s, hit.address);
        return;
    }
    if (mouse_button != 1) return;
    var b = button_count;
    while (b > 0) {
        b -= 1;
        if (contains(buttons[b].box, x, y)) {
            if (enabled(s, buttons[b].action)) act(s, buttons[b].action);
            return;
        }
    }
    for (lens_boxes[0..drawn_lenses]) |box| if (lens_box != null and contains(lens_box.?, x, y) and contains(box, x, y)) {
        if (addressAt(x, y)) |hit| openLens(s, hit);
        return;
    };
    if (paneAt(x, y)) |pane| {
        const p = @backingInt(pane);
        if (s.maps[p] and x >= panes[p].x + panes[p].w - 54 and y >= panes[p].y + 32) {
            s.drag_map = pane;
            s.drag_content = (pane != .code or !s.graph) and x < panes[p].x + panes[p].w - 18;
            mapDrag(s, pane, y);
            return;
        }
    }
    if (addressAt(x, y)) |hit| openLens(s, hit);
}

pub fn update(s: *State, in: *const sk.Input) void {
    if (in.console) return;
    s.page_scroll = std.math.clamp(s.page_scroll, 0, @max(0, geometry.content - geometry.h));
    for (in.events) |event| {
        var e = event;
        e.x /= display_scale;
        e.y /= display_scale;
        if (s.segments) {
            if (e.kind == .text and e.value >= 32 and e.value < 127 and s.segment_len < s.segment_query.len) {
                s.segment_query[s.segment_len] = @intCast(e.value);
                s.segment_len += 1;
                s.segment_row = 0;
            }
            if (e.kind == .wheel) s.segment_row = @intFromFloat(std.math.clamp(@as(f32, @floatFromInt(s.segment_row)) - e.wheel() * 3, 0, @as(f32, @floatFromInt(segment_total -| 1))));
            if (e.kind == .mouse_down) pointer(s, e.code, e.x, e.y);
            if (e.kind == .key_down) switch (@as(sk.Key, @fromBackingInt(@intCast(e.code)))) {
                .escape => s.segments = false,
                .backspace => {
                    s.segment_len -|= 1;
                    s.segment_row = 0;
                },
                .down => s.segment_row = @min(s.segment_row + 1, segment_total -| 1),
                .up => s.segment_row -|= 1,
                .@"return" => if (segment_hit_count > 0) {
                    act(s, .{ .kind = .select_segment, .pane = s.focus, .address = segment_hits[0].address });
                },
                else => {},
            };
            continue;
        }
        if (s.command_open) {
            if (e.kind == .text and e.value >= 32 and e.value < 127 and s.command_len < s.command_text.len) {
                if (s.command_len != 0 or e.value != ':') {
                    s.command_text[s.command_len] = @intCast(e.value);
                    s.command_len += 1;
                }
            }
            if (e.kind == .key_down) switch (@as(sk.Key, @fromBackingInt(@intCast(@as(u8, @intCast(e.code)))))) {
                .escape => s.command_open = false,
                .backspace => s.command_len -|= 1,
                .@"return" => {
                    s.command_open = false;
                    s.action.send(.{ .kind = .submit });
                },
                else => {},
            };
            continue;
        }
        switch (e.kind) {
            .text => switch (e.value) {
                ':' => act(s, .{ .kind = .command }),
                '?' => act(s, .{ .kind = .help }),
                else => {},
            },
            .mouse_down => pointer(s, e.code, e.x, e.y),
            .mouse_up, .cancel => s.drag_map = null,
            .mouse_move => if (s.drag_map) |pane| {
                mapDrag(s, pane, e.y);
            },
            .wheel => {
                if (s.lens and lens_box != null and contains(lens_box.?, e.x, e.y)) {
                    var body: ?usize = null;
                    for (lens_boxes[0..drawn_lenses], 0..) |box, i| if (contains(box, e.x, e.y) and e.y >= box.y + 30) {
                        body = i;
                    };
                    if (body != null and !in.held(sk.Key.left_shift) and !in.held(sk.Key.right_shift)) scrollLens(s, body.?, -e.wheel() * 3) else s.lens_scroll = std.math.clamp(s.lens_scroll - e.wheel() * 48, 0, lensScroll(s.lens_count, false));
                } else if (contains(geometry.registers, e.x, e.y) and e.y >= geometry.registers.y + 30) {
                    s.register_scroll = std.math.clamp(s.register_scroll - e.wheel() * 3, 0, @max(0, 29 - Geometry.visible(geometry.registers)));
                } else if (paneAt(e.x, e.y)) |pane| {
                    s.focus = pane;
                    if (e.y < panes[@backingInt(pane)].y + 30) s.page_scroll = std.math.clamp(s.page_scroll - e.wheel() * 80, 0, @max(0, geometry.content - geometry.h)) else scroll(s, pane, -e.wheel() * 3);
                } else s.page_scroll = std.math.clamp(s.page_scroll - e.wheel() * 80, 0, @max(0, geometry.content - geometry.h));
            },
            .key_down => {
                const key: sk.Key = @fromBackingInt(@intCast(@as(u8, @intCast(e.code))));
                const ctrl = e.value & sk.Key.Mod.ctrl != 0 or in.held(sk.Key.left_ctrl) or in.held(sk.Key.right_ctrl);
                const shift = e.value & sk.Key.Mod.shift != 0 or in.held(sk.Key.left_shift) or in.held(sk.Key.right_shift);
                if (ctrl) {
                    switch (key) {
                        .equals => s.zoom = @min(200, s.zoom + 10),
                        .minus => s.zoom = @max(60, s.zoom -| 10),
                        .@"0" => s.zoom = 100,
                        .d => scroll(s, s.focus, Geometry.visible(panes[@backingInt(s.focus)]) / 2),
                        .u => scroll(s, s.focus, -Geometry.visible(panes[@backingInt(s.focus)]) / 2),
                        .o => act(s, .{ .kind = .back, .pane = s.focus }),
                        .i => act(s, .{ .kind = .forward, .pane = s.focus }),
                        .w => s.prefix = 'w',
                        .c => if (s.status == .running) {
                            act(s, .{ .kind = .pause });
                        },
                        else => {},
                    }
                    continue;
                }
                if (s.prefix == 'w') {
                    s.focus = switch (key) {
                        .h => .stack,
                        .l => .memory,
                        .k => .code,
                        .j => .stack,
                        else => s.focus,
                    };
                    s.prefix = 0;
                    continue;
                }
                const was_g = s.prefix == 'g';
                s.prefix = 0;
                switch (key) {
                    .h => if (s.focus == .code and s.source and !s.graph and !shift) {
                        s.source_column -|= 4;
                    } else {
                        s.horizontal[@backingInt(s.focus)] = @max(0, s.horizontal[@backingInt(s.focus)] - 48);
                    },
                    .l => if (s.focus == .code and s.source and !s.graph and !shift) {
                        s.source_column = @min(s.source_column +| 4, 4096);
                    } else {
                        s.horizontal[@backingInt(s.focus)] = @min(1600, s.horizontal[@backingInt(s.focus)] + 48);
                    },
                    .page_down => s.page_scroll = @min(@max(0, geometry.content - geometry.h), s.page_scroll + geometry.h * 0.7),
                    .page_up => s.page_scroll = @max(0, s.page_scroll - geometry.h * 0.7),
                    .p => act(s, .{ .kind = .segments, .pane = s.focus }),
                    .t => act(s, .{ .kind = .graph }),
                    .d => act(s, .{ .kind = .dim }),
                    .j => scroll(s, s.focus, 1),
                    .k => scroll(s, s.focus, -1),
                    .g => if (shift) {
                        scroll(s, s.focus, extents[@backingInt(s.focus)]);
                    } else if (was_g) {
                        scroll(s, s.focus, -extents[@backingInt(s.focus)]);
                    } else {
                        s.prefix = 'g';
                    },
                    .s => if (s.status == .stopped) {
                        act(s, .{ .kind = .stepi });
                    },
                    .n => if (s.status == .stopped) {
                        act(s, .{ .kind = .step });
                    },
                    .c => if (s.status == .stopped) {
                        act(s, .{ .kind = .cont });
                    },
                    .r => if (shift and launch_command != null) {
                        act(s, .{ .kind = .restart });
                    },
                    .escape => if (s.lens or s.help) {
                        s.lens = false;
                        s.lens_count = 0;
                        s.help = false;
                    } else if (s.status == .running) {
                        act(s, .{ .kind = .pause });
                    },
                    .left_bracket => act(s, .{ .kind = .previous }),
                    .right_bracket => act(s, .{ .kind = .next }),
                    .f => if (shift) {
                        act(s, .{ .kind = .live });
                    } else {
                        act(s, .{ .kind = .follow, .pane = s.focus });
                    },
                    .b => act(s, .{ .kind = .breakpoint, .address = s.pc }),
                    .m => act(s, .{ .kind = .map, .pane = s.focus }),
                    .v => act(s, .{ .kind = .source }),
                    .a => act(s, .{ .kind = .annotate }),
                    .z => act(s, .{ .kind = .lens, .address = if (addressAt(in.mouse_x / display_scale, in.mouse_y / display_scale)) |h| h.address else s.pc }),
                    .tab => s.focus = @fromBackingInt(@intCast((@backingInt(s.focus) + 1) % 3)),
                    else => {},
                }
            },
            else => {},
        }
    }
}

fn icon(u: ui.Ui, kind: Kind, active: bool) void {
    const c = if (active) ui.theme.mark(.current).solid else ui.theme.color.text.primary;
    const v = u.moved(6, 5);
    switch (kind) {
        .restart => v.route(&.{ .{ 5, 5 }, .{ 17, 5 }, .{ 21, 10 }, .{ 21, 16 }, .{ 16, 21 }, .{ 7, 21 }, .{ 2, 16 } }, c, .{ .width = 2, .head = .{ 6, 6 }, .radius = 4 }),
        .cont => sk.draw.polygon(u.f, &.{ .{ 3, 2 }, .{ 3, 20 }, .{ 18, 11 } }, v.at.pen(.{ .fill = ui.rgb(c) })),
        .pause => {
            v.fill(.{ .x = 4, .y = 3, .w = 4, .h = 16 }, c);
            v.fill(.{ .x = 13, .y = 3, .w = 4, .h = 16 }, c);
        },
        .stepi, .step => {
            v.route(&.{ .{ 2, 11 }, .{ 18, 11 } }, c, .{ .width = 2, .head = .{ 6, 6 } });
            v.line(.{ 20, 3 }, .{ 20, 19 }, c, 2);
            if (kind == .step) {
                v.line(.{ 2, 2 }, .{ 12, 2 }, c, 2);
                v.line(.{ 2, 20 }, .{ 12, 20 }, c, 2);
            }
        },
        .previous, .back, .next, .forward => {
            const left = kind == .previous or kind == .back;
            v.route(&.{ .{ if (left) 19 else 3, 11 }, .{ if (left) 3 else 19, 11 } }, c, .{ .width = 2, .head = .{ 6, 7 } });
            if (kind == .previous or kind == .next) v.disc(.{ if (left) 21 else 1, 11 }, 2, ui.rgb(c), null, 0);
        },
        .live, .follow => {
            v.disc(.{ 11, 11 }, 7, null, ui.rgb(c), 2);
            v.disc(.{ 11, 11 }, 2, ui.rgb(c), null, 0);
            v.line(.{ 11, 0 }, .{ 11, 5 }, c, 1);
            v.line(.{ 11, 17 }, .{ 11, 22 }, c, 1);
        },
        .breakpoint => v.disc(.{ 11, 11 }, 7, ui.rgb(ui.theme.mark(.write).solid), null, 0),
        .source => {
            v.line(.{ 10, 3 }, .{ 4, 11 }, c, 2);
            v.line(.{ 4, 11 }, .{ 10, 19 }, c, 2);
            v.line(.{ 14, 3 }, .{ 20, 11 }, c, 2);
            v.line(.{ 20, 11 }, .{ 14, 19 }, c, 2);
        },
        .map => {
            v.frame(.{ .x = 1, .y = 1, .w = 20, .h = 20 }, c, 1);
            for (0..5) |i| {
                const y = 4 + @as(f32, @floatFromInt(i)) * 3;
                v.line(.{ 4, y }, .{ if (i % 2 == 0) 18 else 13, y }, c, 1);
            }
            v.frame(.{ .x = 2, .y = 8, .w = 18, .h = 7 }, c, 1);
        },
        .lens => {
            v.disc(.{ 9, 9 }, 7, null, ui.rgb(c), 2);
            v.line(.{ 14, 14 }, .{ 21, 21 }, c, 3);
        },
        .shallower, .deeper => {
            v.line(.{ 3, 11 }, .{ 19, 11 }, c, 2);
            if (kind == .deeper) v.line(.{ 11, 3 }, .{ 11, 19 }, c, 2);
        },
        .annotate => {
            v.route(&.{ .{ 2, 18 }, .{ 2, 5 }, .{ 20, 5 } }, c, .{ .width = 2, .head = .{ 6, 6 } });
            v.line(.{ 8, 14 }, .{ 20, 14 }, c, 2);
            v.line(.{ 8, 19 }, .{ 17, 19 }, c, 2);
        },
        .segments => v.text(.mono_bold, 20, 1, 19, "≡", c),
        .graph => {
            v.frame(.{ .x = 1, .y = 1, .w = 8, .h = 7 }, c, 1);
            v.frame(.{ .x = 13, .y = 14, .w = 8, .h = 7 }, c, 1);
            v.line(.{ 5, 8 }, .{ 17, 14 }, c, 1);
        },
        .dim => v.text(.mono_bold, 19, 1, 19, "◐", c),
        .ascii => v.text(.mono_bold, 20, 1, 19, "Aa", c),
        .close_lens => {
            v.line(.{ 3, 3 }, .{ 19, 19 }, c, 2);
            v.line(.{ 19, 3 }, .{ 3, 19 }, c, 2);
        },
        .help => v.text(.mono_bold, 22, 5, 19, "?", c),
        .command => {
            v.route(&.{ .{ 2, 4 }, .{ 10, 11 }, .{ 2, 18 } }, c, .{ .width = 2, .head = null });
            v.line(.{ 12, 18 }, .{ 21, 18 }, c, 2);
        },
        else => {},
    }
}
fn button(u: ui.Ui, x: f32, y: f32, action: Action, label: []const u8, available: bool, active: bool) void {
    const a = u.at.xf.apply(.{ x, y });
    var box: Box = .{ .x = a[0], .y = a[1], .w = 34 * display_scale, .h = 32 * display_scale };
    if (ui.bound) |clip| {
        const x0 = @max(box.x, clip.x);
        const y0 = @max(box.y, clip.y);
        box = .{ .x = x0, .y = y0, .w = @max(0, @min(box.x + box.w, clip.x + clip.w) - x0), .h = @max(0, @min(box.y + box.h, clip.y + clip.h) - y0) };
    }
    box = Geometry.scaled(box, 1 / display_scale);
    const b: Button = .{ .action = action, .box = box, .label = label, .enabled = available };
    if (box.w > 0 and box.h > 0 and button_count < buttons.len) {
        buttons[button_count] = b;
        button_count += 1;
    }
    const hover = !u.f.in.console and contains(box, u.f.in.mouse_x / display_scale, u.f.in.mouse_y / display_scale);
    if (hover) tooltip = b;
    const v = (if (available) u else u.faded(0.32)).moved(x, y);
    v.fill(.{ .x = 0, .y = 0, .w = 34, .h = 32 }, if (hover or active) ui.theme.color.rule else ui.theme.color.raised);
    if (hover or active) v.frame(.{ .x = 0, .y = 0, .w = 34, .h = 32 }, if (active) ui.theme.mark(.current).solid else ui.theme.color.text.dim, 1);
    if (action.kind == .unit) v.text(.mono_bold, 17, 5, 23, v.print("{d}", .{action.address * 8}), ui.theme.color.text.primary) else if (action.kind == .number_format) {
        const labels = [_][]const u8{ "x", "u", "d", "f" };
        v.text(.mono_bold, 20, 10, 23, labels[@min(action.address, 3)], ui.theme.color.text.primary);
    } else icon(v, action.kind, active);
}
fn paneButtons(u: ui.Ui, s: *const State, pane: Pane) void {
    const p = @backingInt(pane);
    const n = s.nav[p];
    const w = panes[p].w;
    if (w < 600) {
        button(u, w - 78, -3, .{ .kind = .follow, .pane = pane }, "Follow live address · f", true, n.place.follow);
        button(u, w - 40, -3, .{ .kind = .map, .pane = pane }, "Minimap · right rail spans whole segment · m", true, s.maps[p]);
        return;
    }
    button(u, w - 230, -3, .{ .kind = .back, .pane = pane }, "Back · Ctrl-o / Mouse4", n.cursor > 0, false);
    button(u, w - 192, -3, .{ .kind = .forward, .pane = pane }, "Forward · Ctrl-i / Mouse5", n.cursor + 1 < n.len, false);
    button(u, w - 154, -3, .{ .kind = .follow, .pane = pane }, "Follow live address · f", true, n.place.follow);
    button(u, w - 116, -3, .{ .kind = .map, .pane = pane }, "Minimap · right rail spans whole segment · m", true, s.maps[p]);
    button(u, w - 78, -3, .{ .kind = if (pane == .code) .source else if (pane == .stack) .shallower else .ascii, .pane = pane }, if (pane == .code) "Aligned source · v" else if (pane == .stack) "Fewer pointer hops" else "ASCII / pointer words", true, if (pane == .code) s.source else if (pane == .memory) s.ascii else false);
    button(u, w - 40, -3, .{ .kind = if (pane == .stack) .deeper else .annotate, .pane = pane }, if (pane == .stack) "More pointer hops" else "Read / result annotations · a", true, if (pane == .stack) false else s.annotations);
}

pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
    if (ss.launches != s.launches) ss.* = .{ .launches = s.launches };
    if (ss.action.take(s.action)) |action| switch (action.kind) {
        .restart => f.run("restart"),
        .cont => f.run("continue"),
        .pause => f.run("interrupt"),
        .stepi => f.run("stepi"),
        .step => f.run("nextline"),
        .go => f.run(ui.Ui.init(f).print("{s} {s} 0x{x}", .{ if (action.manual) "browse" else "goto", @tagName(action.pane), action.address })),
        .breakpoint => f.run(ui.Ui.init(f).print("break *0x{x}", .{action.address})),
        .submit => f.run(s.command_text[0..s.command_len]),
        else => {},
    };
    if (client) |c| if (c.poll()) |update_| if (update_.generation != latest.generation) {
        latest = update_;
        if (latest.status != .running and latest.moments > loaded) {
            if (zt.Trace.open(gpa, io, c.path)) |next| {
                if (trace) |*t| t.close();
                trace = next;
                loaded = next.len;
            } else |err| f.host.print("recording: {t}", .{err});
        }
        f.run("observed");
    };
    const scale = @as(f32, @floatFromInt(s.zoom)) / 100;
    const w = @max(1, @round(f.in.window_width / scale));
    const h = @max(1, @round(f.in.window_height / scale));
    // canvas() also resizes the native window: only its real dimensions belong here.
    f.canvas(@intFromFloat(@max(1, f.in.window_width)), @intFromFloat(@max(1, f.in.window_height)));
    display_scale = scale;
    const next_geometry = Geometry.init(w, h, s.page_scroll);
    if (geometry.w != w or geometry.h != h) {
        ss.mini_key = @splat(0);
        ss.marker_key = 0;
        ss.marker_base = 0;
    }
    geometry = next_geometry;
    panes = geometry.panes;
    f.clear(ui.theme.color.page);
    var u = ui.Ui.init(f);
    u.at.xf = .scale(scale, scale);
    u.at.scale = scale;
    const ink = ui.theme.color.text;
    const gold = ui.theme.mark(.current);
    hit_count = 0;
    button_count = 0;
    tooltip = null;
    lens_box = null;
    drawn_lenses = 0;
    current_lens = null;
    ui.address_hit = .{ .ctx = ss, .emit = collectAddress };
    defer ui.address_hit = null;
    u.text(.sans_medium, 24, 24, 28, if (geometry.w < 700) "ztrace" else "ztrace / debugger", ink.primary);
    const status = if (client == null) (if (trace == null) "READY" else "RECORDING") else @tagName(s.status);
    u.fill(.{ .x = if (geometry.w < 700) 150 else 300, .y = 9, .w = 118, .h = 24 }, ui.theme.color.raised);
    u.text(.mono_bold, 17, if (geometry.w < 700) 162 else 312, 27, status, if (s.status == .failed) ui.theme.mark(.write).solid else gold.solid);
    if (geometry.w > 850) u.text(.sans, 18, 434, 27, canim.rows.fitted(u, latest.reason(), geometry.w - 740), ink.dim);
    if (client != null and geometry.w > 1200) u.text(.mono, 17, geometry.w - 310, 27, u.print("command {d:.3} ms", .{@as(f64, @floatFromInt(latest.elapsed_ns)) / 1e6}), ink.dim);
    const kinds = [_]Kind{ if (s.status == .running) .pause else .cont, .stepi, .step, .breakpoint, .previous, .next, .live, .source, .map, .annotate, .lens, .segments, .graph, .dim, .command, .help, .restart };
    const labels = [_][]const u8{ if (s.status == .running) "Pause · Esc / Ctrl-c" else "Continue · c", "Single instruction · s", "Next source line (enters calls) · n", "Breakpoint at PC · b", "Previous recorded stop · [", "Next recorded stop · ]", "Live stop · F (Shift-f)", "Aligned source · v", "Focused pane minimap · m", "Operand annotations · a", "Address lens · z", "Memory segments · p (active pane)", "Control-flow graph · t", "Unobserved instruction opacity · d", "Command line · :", "Keyboard help · ?", "Restart at entry · Shift-r (fresh breakpoints)" };
    comptime std.debug.assert(kinds.len == Geometry.toolbar_count);
    for (kinds, labels, 0..) |kind, label, i| {
        const available = switch (kind) {
            .restart => launch_command != null,
            .cont, .pause, .stepi, .step, .breakpoint => client != null and s.status != .exited and (kind == .pause or s.status == .stopped),
            else => true,
        };
        button(u, 24 + @as(f32, @floatFromInt(i % geometry.columns)) * 42, 42 + @as(f32, @floatFromInt(i / geometry.columns)) * 34, .{ .kind = kind, .pane = s.focus, .address = s.pc }, label, available, switch (kind) {
            .source => s.source,
            .map => s.maps[@backingInt(s.focus)],
            .annotate => s.annotations,
            .lens => s.lens,
            .live => s.following,
            else => false,
        });
    }
    if (geometry.w > 1500) u.text(.sans, 17, 740, 63, u.print("t graph · d unobserved {d}% · p segments · Ctrl +/− {d}%", .{ s.dim, s.zoom }), ink.dim);
    const t = if (trace) |*t| t else {
        _ = u.moved(24, 112).panel(geometry.w - 48, geometry.h - 160, "session", .{ .focus = true });
        u.text(.sans_medium, 34, 72, 174, "Start with a real process.", ink.primary);
        u.text(.mono, 22, 72, 226, "launch PROGRAM [ARGS]", gold.solid);
        u.text(.sans, 22, 72, 268, "Open commands with : or backtick, then set a breakpoint and continue.", ink.dim);
        u.text(.mono, 20, 72, 328, "break FUNCTION    break *ADDRESS    clear ID", ink.primary);
        overlays(u, s, ss, null);
        return;
    };
    const m = t.moment(@min(s.moment, t.len -| 1)) catch return;
    const regs = (m.regs(s.tid) catch null) orelse return;
    const low = (regs.rsp -| 24) & ~@as(u64, 7);
    if (ss.shown != m.index or ss.tid != s.tid) selected(ss, t, m, regs, s.tid, low, f.in.now);
    if (ss.graph != s.graph) {
        ss.graph = s.graph;
        ss.scroll[0] = 0;
    }
    const seconds = @as(f32, @floatFromInt(f.in.now -| ss.changed_at)) / 1e9;
    const heat = changedHeat(seconds);
    const fire = if (seconds < ui.theme.time.fire) ui.theme.pulse(seconds / ui.theme.time.fire) else 0;
    const travel = ui.theme.ease(.standard, std.math.clamp(seconds / ui.theme.time.step, 0, 1));
    const mode = if (!s.following) "HISTORY" else if (s.status == .running) "LAST STOP" else "LIVE";
    u.text(.mono_bold, 17, 24, geometry.top - 12, mode, gold.solid);
    u.text(.mono, 17, 150, geometry.top - 12, canim.rows.fitted(u, u.print("moment {d}/{d} · tid {d}", .{ m.index, t.len -| 1, s.tid }), geometry.w - 174), ink.dim);
    const live_bases = [3]u64{ ss.code_start, low, (ss.touch orelse canim.Recording.Touch{ .addr = regs.rsp, .len = 8, .how = 1 }).addr & ~@as(u64, 15) };
    for (0..3) |p| {
        const nav = s.nav[p].place;
        const address = if (nav.follow and !nav.manual) live_bases[p] else if (nav.address != 0) nav.address else live_bases[p];
        ranges[p] = (m.mapping(address, null, &.{}) catch null) orelse .{ .addr = address, .len = 2048, .prot = 0, .offset = 0 };
        bases[p] = if (p == 0) address else ranges[p].addr;
        if (ss.base[p] != bases[p]) {
            ss.scroll[p] = 0;
            ss.base[p] = bases[p];
        }
        if (p > 0) extents[p] = @max(0, @as(f64, @floatFromInt(ranges[p].len / (if (p == 1) @as(u64, 8) else 16))) - Geometry.visible(panes[p]));
        const target = if (nav.manual) nav.row else if (p == 0) @as(f64, 0) else @as(f64, @floatFromInt((address -| bases[p]) / (if (p == 1) @as(u64, 8) else 16)));
        const dt = @as(f32, @floatFromInt(f.in.dt)) / 1e9;
        // Avoid animating across millions of uncaptured rows after an address jump.
        if (p == 0 and nav.follow and !nav.manual) continue;
        if (@abs(ss.scroll[p] - target) > Geometry.visible(panes[p]) * 2) ss.scroll[p] = target else ss.scroll[p] = std.math.lerp(ss.scroll[p], target, 1 - @exp(-dt * 18));
        shown_scroll[p] = ss.scroll[p];
    }
    listing(ss, m, bases[0]);
    if (s.origin != 0) {
        var buf: [1024]u8 = undefined;
        if ((zt.telescope.instruction(m, s.origin, &buf) catch null)) |insn| ss.origin_line = insn.line;
    }
    if (ss.capture_stop != s.execution) {
        ss.capture_stop = s.execution;
        ss.inspected = @splat(0);
        ss.lens_inspected = @splat(0);
    }
    // Captures are bounded and only requested from the selected live stop.
    if (client != null and s.following and s.status == .stopped) for (0..3) |p| {
        const address = bases[p] +| (if (p == 0) @as(u64, 0) else @as(u64, @intFromFloat(@floor(if (s.nav[p].place.manual) s.nav[p].place.row else ss.scroll[p]))) * (if (p == 1) @as(u64, 8) else 16));
        const key = address ^ (s.pc *% 0x9e3779b97f4a7c15);
        if (ss.inspected[p] != key and (s.nav[p].place.manual or !s.nav[p].place.follow) and (p != 0 or ss.code_count == 0)) {
            ss.inspected[p] = key;
            f.run(u.print("inspect {s} 0x{x} {d}", .{ if (p == 0) "code" else "memory", address, @as(u32, if (p == 0) 128 else 2048) }));
            break;
        }
    };
    const content: Box = .{ .x = 0, .y = geometry.top, .w = geometry.w, .h = @max(0, geometry.h - geometry.top - 40) };
    ui.bound = Geometry.scaled(content, scale);
    u.clip(.{ .x = content.x, .y = content.y, .w = content.w, .h = content.h });
    drawCode(u.moved(panes[0].x, panes[0].y), s, ss, m, regs, heat, fire, travel);
    drawRegisters(u.moved(geometry.registers.x, geometry.registers.y), s, ss, m, regs, heat, seconds, fire);
    drawStack(u.moved(panes[1].x, panes[1].y), s, ss, m, regs, heat, seconds);
    drawMemory(u.moved(panes[2].x, panes[2].y), s, ss, m, heat);
    ui.bound = null;
    u.unclip();
    const place = if (t.len <= 1) 1 else @as(f32, @floatFromInt(m.index)) / @as(f32, @floatFromInt(t.len - 1));
    u.fill(.{ .x = 24, .y = geometry.h - 34, .w = geometry.w - 48, .h = 2 }, ui.theme.color.rule);
    u.fill(.{ .x = 24, .y = geometry.h - 34, .w = (geometry.w - 48) * place, .h = 2 }, gold.solid);
    u.fill(.{ .x = 22 + (geometry.w - 48) * place, .y = geometry.h - 37, .w = 4, .h = 8 }, gold.solid);
    if (geometry.w >= 1200 and geometry.content <= geometry.h + 1) u.text(.sans, 17, 24, geometry.h - 9, if (s.following) "Live stop · right-click: stack / memory · click for a lens" else "Recorded state · inspecting and navigating leave the target unchanged", ink.dim);
    if (geometry.content > geometry.h) u.text(.sans, 16, 24, geometry.h - 9, "PgUp/PgDn · scroll pane headers", ink.dim);
    overlays(u, s, ss, m);
    ties(u, s, ss);
}
fn listing(ss: *Session, m: zt.store.Moment, base: u64) void {
    if (ss.listing_at == m.index and ss.listing_base == base) return;
    ss.listing_at = m.index;
    ss.listing_base = base;
    ss.code_count = 0;
    var pc = base;
    for (&ss.code, &ss.code_text, &ss.code_lines) |*row, *buf, *line| {
        const insn = (zt.telescope.instruction(m, pc, buf) catch null) orelse break;
        var bytes: [15]u8 = undefined;
        var known: [15]bool = @splat(false);
        if (insn.len == 0 or insn.len > bytes.len) break;
        m.read(pc, bytes[0..insn.len], known[0..insn.len]) catch break;
        if (std.mem.indexOfScalar(bool, known[0..insn.len], false) != null) break;
        row.* = .{ .addr = pc, .len = insn.len, .text = insn.text, .line = if (insn.line) |l| l.line else null, .params = insn.params };
        line.* = insn.line;
        ss.code_count += 1;
        pc +|= insn.len;
    }
    code_after = if (pc > base) pc else base +| 128;
    code_before = base -| 128;
    if (ss.code_count > 0) {
        var previous: [1024]u8 = undefined;
        if ((zt.telescope.instruction(m, base, &previous) catch null)) |insn| if (insn.back > 0) {
            code_before = base -| insn.back;
        };
    }
    var prefix: usize = 0;
    if (ss.code_count > 0) if (ss.code_lines[0]) |first| {
        prefix = @min(2, first.line -| 1);
        for (0..prefix) |i| ss.aligned[i] = .{ .instruction = null, .source = .{ .file = first.file, .line = first.line - @as(u32, @intCast(prefix - i)) } };
    };
    ss.aligned_count = prefix + canim.aligned.livePlan(ss.code_lines[0..ss.code_count], ss.aligned[prefix..]).len;
}
fn sourceLine(u: ui.Ui, column: usize, m: zt.store.Moment, line: zt.store.Line, y: f32, w: f32, current: bool, fire: f32, again: bool) void {
    const file = sources.get(gpa, io, m, line.file) orelse return;
    const text = file.text orelse {
        u.text(.mono, 18, 64, y + 18, canim.rows.fitted(u, "source file unavailable", @max(0, w - 64)), ui.theme.color.text.faint);
        return;
    };
    if (line.line == 0 or line.line > text.lines.len) return;
    const range = text.lines[line.line - 1];
    canim.rows.line(u, y, w, line.line, canim.rows.numberRoom(@intCast(text.lines.len)), text.bytes[@min(range[0] + column, range[1])..range[1]], text.styles[@min(range[0] + column, range[1])..range[1]], if (current) .{ .current = fire } else .plain);
    if (again) u.text(.mono, 18, 3, y + 19, "↻", ui.theme.color.text.dim);
}
fn codeVisible() f32 {
    return @max(1, @floor((@min(panes[0].y + panes[0].h, geometry.h - 40) - @max(panes[0].y + code_top, geometry.top)) / 24));
}
fn columns(s: *const State) bool {
    return s.source and panes[0].w >= 900;
}
fn codeRows(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: zt.Regs, first: f32, heat: ui.Heat, fire: f32, travel: f32, miniature: bool) void {
    const seam: f32 = if (columns(s)) Geometry.seam(panes[0]) else 0;
    const room: f32 = panes[0].w - seam - if (s.maps[0]) @as(f32, 58) else 6;
    const count = if (columns(s)) ss.aligned_count else ss.code_count;
    var current_group: ?usize = null;
    var group_start: usize = 0;
    for (ss.aligned[0..ss.aligned_count], 0..) |row, i| {
        if (row.source != null) group_start = i;
        if (row.instruction) |j| if (ss.code[j].addr == regs.rip) {
            current_group = group_start;
        };
    }
    var pc_row: ?f32 = null;
    var branch_row: ?f32 = null;
    for (0..count) |i| {
        const r: canim.aligned.LiveRow = if (columns(s)) ss.aligned[i] else .{ .instruction = i };
        const y = (if (miniature) @as(f32, 0) else code_top) + @as(f32, @floatCast((@as(f64, @floatFromInt(i)) - first) * 24));
        if (!miniature and (y < code_top - 24 or y >= panes[0].h - 2)) continue;
        if (columns(s)) if (r.source) |line| {
            const current = current_group == i;
            sourceLine(if (r.instruction == null) u.faded(0.45) else u, if (miniature) 0 else s.source_column, m, line, y, seam - 32, current, fire, r.again);
            if (r.instruction != null) u.route(&.{ .{ seam - 30, y + 12 }, .{ seam - 8, y + 12 }, .{ seam + 2, y + 12 } }, if (current) ui.theme.mark(.current).solid else ui.theme.color.rule, .{ .width = 1.5, .head = .{ 5, 6 }, .progress = if (current) travel else 1 });
        };
        const index = r.instruction orelse continue;
        const row = ss.code[index];
        const observed = std.mem.indexOfScalar(u64, &ss.trail, row.addr) != null;
        const predicted = if (ss.branch) |branch| (branch.kind == .jump and branch.taken and branch.to == row.addr) else false;
        const d = u.moved(seam, 0).faded(if (row.addr == regs.rip or observed or predicted) 1 else @max(0.15, @as(f32, @floatFromInt(s.dim)) / 100));
        const current = row.addr == regs.rip;
        if (current) {
            const marker_y = if (miniature) y else code_top + (ss.marker_shown - first) * 24;
            pc_row = marker_y;
            d.current(.{ .x = 2, .y = marker_y, .w = room - 4, .h = 24 }, ui.theme.metric.plaque.pc, fire);
            sk.draw.polygon(u.f, &.{ .{ 20, marker_y + 12 }, .{ 10, marker_y + 6 }, .{ 10, marker_y + 18 } }, d.at.pen(.{ .fill = ui.rgb(ui.theme.mark(.current).on_solid) }));
        }
        for (ss.trail, 0..) |old, k| if (old == row.addr and !current) {
            d.trail(2, y, k);
            break;
        };
        canim.disasm.liveRow(d, row, y, room, m, regs, .{ .compact = room < 520, .current = current and s.annotations, .executed = ss.result_at == row.addr and s.annotations, .heat = heat, .lead = ui.shared(&.{ bases[0], bases[0] +| 512 }), .touch = if (current and s.annotations) ss.touch else null, .branch = if (current and s.annotations) ss.branch else null });
        if (ss.branch) |branch| if (branch.to == row.addr) {
            branch_row = y;
        };
    }
    if (!miniature and columns(s) and pc_row != null and current_group != null) {
        const from = code_top + (@as(f32, @floatFromInt(current_group.?)) - first) * 24 + 12;
        if (@abs(from - pc_row.? - 12) > 1) u.route(&.{ .{ seam - 30, from }, .{ seam - 12, from }, .{ seam - 12, pc_row.? + 12 }, .{ seam + 2, pc_row.? + 12 } }, ui.theme.mark(.current).solid, .{ .width = 2, .head = .{ 6, 7 }, .progress = travel });
    }
    if (!miniature and pc_row != null and branch_row != null) if (ss.branch) |branch| if (branch.kind == .jump) {
        u.route(&.{ .{ seam + 37, pc_row.? + 12 }, .{ seam + 28, pc_row.? + 12 }, .{ seam + 28, branch_row.? + 12 }, .{ seam + 38, branch_row.? + 12 } }, if (branch.taken) ui.theme.mark(.current).solid else ui.theme.color.text.faint, .{ .width = 2, .head = .{ 7, 8 }, .radius = 4, .dashed = !branch.taken, .progress = travel });
    };
}
fn drawCode(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: zt.Regs, heat: ui.Heat, fire: f32, travel: f32) void {
    code_top = 32;
    const actual_height = @min(panes[0].h, geometry.h - 40 - panes[0].y);
    origin_height = if (actual_height < 250) 48 else 72;
    source_height = if (actual_height < 250) 24 else 48;
    const native_line = m.line(s.tid) catch null;
    if (!s.graph) if (ss.origin_line) |origin| if (native_line == null or native_line.?.file != origin.file) {
        code_top += origin_height;
    };
    if (!columns(s) and s.source and !s.graph) code_top += source_height;
    const count = if (columns(s)) ss.aligned_count else ss.code_count;
    const marker_key = (m.index + 1) *% 0x9e3779b97f4a7c15 ^ bases[0] ^ @as(u64, @intFromBool(columns(s)));
    if (ss.marker_key != marker_key) {
        for (0..count) |i| {
            const index = if (columns(s)) ss.aligned[i].instruction else i;
            if (index) |j| if (ss.code[j].addr == regs.rip) {
                ss.marker_to = @floatFromInt(i);
                ss.marker_from = if (ss.marker_base == bases[0]) ss.marker_shown else ss.marker_to;
            };
        }
        ss.marker_key = marker_key;
        ss.marker_base = bases[0];
        ss.marker_at = u.f.in.now;
    }
    if (!s.graph and s.nav[0].place.follow and !s.nav[0].place.manual) {
        var start: f32 = ss.marker_to;
        if (columns(s)) {
            var group: usize = 0;
            for (ss.aligned[0..ss.aligned_count], 0..) |r, k| {
                if (r.source != null) group = k;
                if (r.instruction) |j| if (ss.code[j].addr == regs.rip) {
                    start = @floatFromInt(group);
                    break;
                };
            }
        }
        const visible = codeVisible();
        const target = @max(0, @max(start - 2, ss.marker_to - visible + @min(3, visible)));
        const dt = @as(f32, @floatFromInt(u.f.in.dt)) / 1e9;
        ss.scroll[0] = std.math.lerp(ss.scroll[0], target, 1 - @exp(-dt * 18));
        shown_scroll[0] = ss.scroll[0];
    }
    const marker_time = @as(f32, @floatFromInt(u.f.in.now -| ss.marker_at)) / 1e9;
    ss.marker_shown = std.math.lerp(ss.marker_from, ss.marker_to, ui.theme.ease(.standard, std.math.clamp(marker_time / ui.theme.time.step, 0, 1)));
    extents[0] = @max(0, @as(f32, @floatFromInt(count)) - codeVisible());
    _ = u.panel(panes[0].w, panes[0].h, if (s.graph) "control flow" else if (panes[0].w < 600) "code" else if (s.source) "source / disassembly" else "disassembly", .{ .focus = s.focus == .code });
    var file_name: []const u8 = "no recorded source mapping";
    for (ss.code_lines[0..ss.code_count]) |line| if (line) |l| {
        if (sources.get(gpa, io, m, l.file)) |file| file_name = file.path;
        break;
    };
    u.text(.sans, 17, 250, 19, canim.rows.fitted(u, file_name, @max(0, panes[0].w - 500)), ui.theme.color.text.dim);
    paneButtons(u, s, .code);
    if (!s.graph and code_top >= 32 + origin_height) if (ss.origin_line) |origin| {
        if (sources.get(gpa, io, m, origin.file)) |file| {
            u.text(.sans, 17, 12, 50, canim.rows.fitted(u, u.print("Originating JS · {s}:{d}", .{ std.fs.path.basename(file.path), origin.line }), panes[0].w - 30), ui.theme.mark(.current).solid);
            sourceLine(u, 0, m, origin, if (origin_height < 72) 52 else 58, panes[0].w - 64, false, 0, false);
            u.line(.{ 8, 32 + origin_height - 4 }, .{ panes[0].w - 60, 32 + origin_height - 4 }, ui.theme.color.rule, 1);
        }
    };
    if (!columns(s) and s.source and !s.graph) {
        const line = if (s.nav[0].place.follow and !s.nav[0].place.manual) native_line else if (ss.code_count > 0) ss.code_lines[0] else null;
        if (line) |l| sourceLine(u, s.source_column, m, l, code_top - source_height, panes[0].w - 64, true, 0, false);
    }
    u.clip(.{ .x = 2, .y = code_top, .w = panes[0].w - 4 - if (s.maps[0]) @as(f32, 56) else 0, .h = panes[0].h - code_top - 2 });
    if (columns(s) and !s.graph) u.line(.{ Geometry.seam(panes[0]) - 6, 30 }, .{ Geometry.seam(panes[0]) - 6, panes[0].h - 2 }, ui.theme.color.rule, 1);
    if (s.graph) {
        const size = canim.graph.live(u.moved(-s.horizontal[0], 32 - @as(f32, @floatCast(ss.scroll[0] * 24))), m, regs.rip, ss.trail, @as(f32, @floatFromInt(s.dim)) / 100);
        extents[0] = @max(0, (size - panes[0].h + 40) / 24);
    } else codeRows(u.moved(-s.horizontal[0], 0), s, ss, m, regs, @floatCast(ss.scroll[0]), heat, fire, travel, false);
    if (!s.graph and ss.code_count == 0) u.text(.sans, 20, if (columns(s)) Geometry.seam(panes[0]) + 14 else 24, 64, "Code not captured · use goto code ADDRESS at a live stop", ui.theme.color.text.dim);
    if (!s.graph and columns(s) and std.mem.eql(u8, file_name, "no recorded source mapping")) {
        u.text(.sans_medium, 22, 28, 72, "Source mapping unavailable", ui.theme.color.text.dim);
        u.text(.sans, 18, 28, 106, "This code has no recorded file / line table.", ui.theme.color.text.faint);
        u.text(.sans, 18, 28, 136, "Machine instructions remain fully inspectable.", ui.theme.color.text.faint);
    }
    u.unclip();
    if (s.maps[0]) {
        segmentMini(u, 0, bases[0], @max(1, code_after -| bases[0]), regs.rip);
        compact_count = ss.code_count;
        for (ss.code[0..ss.code_count], 0..) |_, j| {
            compact_rows[j] = j;
            if (columns(s)) for (ss.aligned[0..ss.aligned_count], 0..) |r, k| if (r.instruction == j) {
                compact_rows[j] = k;
                break;
            };
        }
        const key = (m.index + 1) *% 0x9e3779b97f4a7c15 ^ bases[0];
        if (ss.mini_key[0] != key) {
            ui.collected.reset();
            ui.strokes = true;
            u.clip(.{ .x = 0, .y = 0, .w = 0, .h = 0 });
            const v = ui.Ui.init(u.f);
            for (ss.code[0..ss.code_count], 0..) |row, i| {
                v.text(.mono, 20, 0, @as(f32, @floatFromInt(i)) * 24 + 20, row.text, ui.theme.color.text.dim);
            }
            ui.strokes = false;
            u.unclip();
            ss.mini[0] = ui.collected;
            ss.mini_key[0] = key;
        }
        var mini = Geometry.mini(panes[0]);
        mini.w -= 16;
        var first: f32 = 0;
        for (compact_rows[0..compact_count], 0..) |row, i| if (@as(f64, @floatFromInt(row)) <= ss.scroll[0]) {
            first = @floatFromInt(i);
        };
        const shown = ui.Rect{ .x = mini.x, .y = mini.y, .w = mini.w, .h = mini.h };
        canim.minimap.liveStrip(u, ss.mini[0].runs[0..ss.mini[0].n_runs], shown, 900, ss.code_count, first, Geometry.visible(panes[0]), null);
    }
}
fn drawRegisters(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: zt.Regs, heat: ui.Heat, seconds: f32, fire: f32) void {
    _ = u.panel(geometry.registers.w, geometry.registers.h, "registers / call stack", .{ .note = u.print("{d} changed", .{@popCount(ss.changed_regs)}) });
    u.clip(.{ .x = 2, .y = 30, .w = geometry.registers.w - 4, .h = geometry.registers.h - 34 });
    const v = u.moved(0, -s.register_scroll * 24);
    for (zt.Regs.names[0..16], 0..) |reg, i| {
        const changed = ss.changed_regs & (@as(u32, 1) << @intCast(i)) != 0;
        _ = canim.rows.reg(v, 34 + @as(f32, @floatFromInt(i)) * 24, geometry.registers.w, reg, m, regs.named(reg).?, .{ .first = if (changed) heat else .none, .extend = if (changed) seconds else null, .most = s.depth });
    }
    v.current(.{ .x = 1, .y = 430, .w = geometry.registers.w - 2, .h = 24 }, ui.theme.metric.plaque.rip, fire);
    v.text(.mono_bold, 20, 14, canim.rows.baseline(430), "rip", ui.theme.mark(.current).on_solid);
    _ = canim.rows.chain(v, 74, 430, m, regs.rip, geometry.registers.w - 12, .{});
    canim.rows.ripFlags(v, 224, 458, regs.eflags, ss.changed_flags, heat.corner, if (ss.branch != null) flagsReadAt(m, regs.rip) else 0, 1, .{ .moment = m, .pc = regs.rip, .eflags = regs.eflags });
    v.line(.{ 12, 484 }, .{ geometry.registers.w - 12, 484 }, ui.theme.color.rule, 1);
    v.text(.sans_medium, 18, 14, 510, "call stack", ui.theme.color.text.primary);
    var frame_buf: [10]zt.Debugger.Frame = undefined;
    const frames = zt.telescope.frames(m, &regs, &frame_buf) catch &.{};
    for (frames[0..@min(frames.len, 3)], 0..) |frame, i| {
        const y = 522 + @as(f32, @floatFromInt(i)) * 52;
        if (i == 0) canim.rows.callCurrent(v, y, geometry.registers.w);
        v.text(.mono, 20, 12, canim.rows.baseline(y), v.print("{d}", .{i}), if (i == 0) ui.theme.mark(.current).on_solid else ui.theme.color.text.dim);
        _ = v.address(60, canim.rows.baseline(y), frame.pc, .{ .ink = ui.rgb(ui.theme.color.region.code_) });
        var buf: [256]u8 = undefined;
        const name_ = (m.string(frame.pc, &buf) catch null) orelse "anonymous code";
        v.text(.mono, 18, 60, y + 44, canim.rows.fitted(v, ui.symbol(v, name_), geometry.registers.w - 72), ui.theme.color.text.dim);
    }
    u.unclip();
}
fn stackRows(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: zt.Regs, first: f64, heat: ui.Heat, seconds: f32, miniature: bool) void {
    const start: usize = if (miniature) 0 else @intFromFloat(@floor(@max(0, first)));
    const count: usize = if (miniature) 128 else @intFromFloat(Geometry.visible(panes[1]) + 2);
    const base = bases[1] & ~@as(u64, 7);
    var slots: [128]zt.telescope.Slot = undefined;
    _ = zt.telescope.slots(m, &regs, base +| start * 8, slots[0..@min(count, 128)]) catch {
        @memset(&slots, .{});
    };
    for (start..@min(start + @min(count, 128), @as(usize, @intCast(ranges[1].len / 8)))) |i| {
        const addr = base +| i * 8;
        const y = (if (miniature) @as(f32, 0) else 32) + @as(f32, @floatCast((@as(f64, @floatFromInt(i)) - first) * 24));
        const changed = addr >= regs.rsp -| 24 and addr < (regs.rsp -| 24) + 88 and ss.changed_stack & (@as(u16, 1) << @as(u4, @intCast((addr - (regs.rsp -| 24)) / 8))) != 0;
        const touched = if (ss.touch) |touch| touch.how & 1 != 0 and addr < touch.addr +| touch.len and addr +| 8 > touch.addr else false;
        const pins: []const []const u8 = if (addr == regs.rsp and addr == regs.rbp) &.{ "rsp", "rbp" } else if (addr == regs.rsp) &.{"rsp"} else if (addr == regs.rbp) &.{"rbp"} else &.{};
        const role = canim.Stack.slotName(u, slots[i - start], (canim.Recording.word(m, addr, 8) catch null) orelse 0);
        _ = canim.rows.slot(u, y, panes[1].w - if (s.maps[1]) @as(f32, 60) else 0, m, addr, @bitCast(addr -% regs.rsp), pins, 1, .{ .first = if (changed) heat else .none, .read = if (touched) 1 else null, .read_shows = 1, .lead = ui.shared(&.{ base, base +| 1024 }), .extend = if (changed) seconds else null, .most = s.depth }, role.name, role.local, null);
    }
}
fn drawStack(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: zt.Regs, heat: ui.Heat, seconds: f32) void {
    _ = u.panel(panes[1].w, panes[1].h, if (panes[1].w < 600) "stack" else "stack / telescope", .{ .focus = s.focus == .stack });
    if (panes[1].w > 800) u.text(.sans, 17, 235, 19, u.print("{d} pointer hops", .{s.depth}), ui.theme.color.text.dim);
    paneButtons(u, s, .stack);
    u.clip(.{ .x = 2, .y = 30, .w = panes[1].w - if (s.maps[1]) @as(f32, 60) else 4, .h = panes[1].h - 38 });
    stackRows(u.moved(-s.horizontal[1], 0), s, ss, m, regs, ss.scroll[1], heat, seconds, false);
    var frame_buf: [10]zt.Debugger.Frame = undefined;
    const frames = zt.telescope.frames(m, &regs, &frame_buf) catch &.{};
    const low = (bases[1] & ~@as(u64, 7)) + @as(u64, @intFromFloat(ss.scroll[1])) * 8;
    for (frames, 0..) |frame, k| {
        const from = @max(frame.low, low);
        const to = @min(frame.high, low + @as(u64, @intFromFloat(Geometry.visible(panes[1]))) * 8);
        if (from >= to) continue;
        canim.rows.span(u, panes[1].w - if (s.maps[1]) @as(f32, 60) else 0, 32 + @as(f32, @floatFromInt((from - low) / 8)) * 24, 32 + @as(f32, @floatFromInt((to - low) / 8)) * 24, u.print("#{d}", .{k}), k == 0, frame.high > low + @as(u64, @intFromFloat(Geometry.visible(panes[1]))) * 8);
    }
    u.unclip();
    if (s.maps[1]) {
        segmentMini(u, 1, bases[1] + @as(u64, @intFromFloat(ss.scroll[1])) * 8, @as(u64, @intFromFloat(Geometry.visible(panes[1]))) * 8, regs.rsp);
        memoryMini(u, ss, m, 1);
    }
}
fn memoryRow(u: ui.Ui, m: zt.store.Moment, addr: u64, y: f32, room: f32, ascii: bool, unit: u8, format: canim.rows.NumberFormat, touch: ?canim.Recording.Touch, heat: ui.Heat, before: ?zt.store.Moment) void {
    var values: [16]u8 = @splat(0);
    var known: [16]bool = @splat(false);
    m.read(addr, &values, &known) catch {};
    var previous: [16]u8 = @splat(0);
    var was_known: [16]bool = @splat(false);
    if (before) |b| b.read(addr, &previous, &was_known) catch {};
    var runs: [2]canim.rows.Run = undefined;
    for (&runs, 0..) |*run, i| {
        const offset = i * 8;
        const word = std.mem.readInt(u64, values[offset..][0..8], .little);
        var changed: ?[2]u8 = null;
        for (offset..offset + 8) |j| if (known[j] and was_known[j] and values[j] != previous[j]) {
            if (changed == null) changed = .{ @intCast(j - offset), @intCast(j - offset) } else changed.?[1] = @intCast(j - offset);
        };
        const read: f32 = if (touch) |t| if (t.addr < addr +| offset +| 8 and t.addr +| t.len > addr +| offset) 1 else 0 else 0;
        run.* = .{ .first = @intCast(offset), .len = 8, .background = false, .kind = if (canim.rows.regionOf(m, word) != .none) .pointer else .number, .read = read, .heat = if (changed != null) heat else .none, .changed = changed };
    }
    const shift = canim.rows.addressRoom(addr);
    const text_x: f32 = if (unit == 1 and format == .hex) blk: {
        canim.rows.bytesAt(u, y, addr, &values, &known, &runs, canim.rows.ink(canim.rows.regionOf(m, addr)), 0, false, m, shift);
        break :blk 640 + shift;
    } else canim.rows.wordsAt(u, y, addr, &values, &known, unit, format, m);
    if (ascii) {
        var chars: [16]u8 = undefined;
        for (&chars, values, known) |*c, v, k| c.* = if (!k) '?' else if (v >= 32 and v < 127) v else '.';
        u.text(.mono, 20, text_x, canim.rows.baseline(y), &chars, ui.theme.color.text.dim);
    } else if (unit == 1 and format == .hex) {
        const fields = [_]canim.hexdump.Field{ .{ .at = 0, .len = 8, .reads = if (runs[0].kind == .pointer) .pointer else .number }, .{ .at = 8, .len = 8, .reads = if (runs[1].kind == .pointer) .pointer else .number } };
        _ = canim.hexdump.readingIn(u, y, shift, m, &values, &known, &fields, room);
    }
}
fn memoryRows(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, first: f64, heat: ui.Heat, miniature: bool) void {
    const start: usize = if (miniature) 0 else @intFromFloat(@floor(@max(0, first)));
    const count: usize = if (miniature) 128 else @intFromFloat(Geometry.visible(panes[2]) + 2);
    const before = if (m.index > 0) trace.?.moment(m.index - 1) catch null else null;
    for (start..@min(start + count, @as(usize, @intCast(ranges[2].len / 16)))) |i| {
        const y = (if (miniature) @as(f32, 0) else 32) + @as(f32, @floatCast((@as(f64, @floatFromInt(i)) - first) * 24));
        memoryRow(u, m, bases[2] +| i * 16, y, panes[2].w - if (s.maps[2]) @as(f32, 60) else 0, s.ascii, s.unit, s.number_format, ss.touch, heat, if (miniature) null else before);
    }
}
fn drawMemory(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, heat: ui.Heat) void {
    _ = u.panel(panes[2].w, panes[2].h, "memory", .{ .focus = s.focus == .memory });
    paneButtons(u, s, .memory);
    button(u, 112, -3, .{ .kind = .unit, .address = s.unit }, "Group size: 8 / 16 / 32 / 64 bits", true, false);
    button(u, 150, -3, .{ .kind = .number_format, .address = @backingInt(s.number_format) }, "Format: hex / unsigned / signed / float", true, false);
    if (panes[2].w > 800) u.text(.sans, 16, 195, 19, u.print("{d}-bit {s}", .{ s.unit * 8, @tagName(s.number_format) }), ui.theme.color.text.dim);
    u.clip(.{ .x = 2, .y = 30, .w = panes[2].w - if (s.maps[2]) @as(f32, 60) else 4, .h = panes[2].h - 38 });
    memoryRows(u.moved(-s.horizontal[2], 0), s, ss, m, ss.scroll[2], heat, false);
    u.unclip();
    if (s.maps[2]) {
        segmentMini(u, 2, bases[2] + @as(u64, @intFromFloat(ss.scroll[2])) * 16, @as(u64, @intFromFloat(Geometry.visible(panes[2]))) * 16, if (ss.touch) |t| t.addr else bases[2]);
        memoryMini(u, ss, m, 2);
    }
}
fn memoryMini(u: ui.Ui, ss: *Session, m: zt.store.Moment, p: usize) void {
    const stride: u64 = if (p == 1) 8 else 16;
    const current = bases[p] + @as(u64, @intFromFloat(ss.scroll[p])) * stride;
    const first = @max(bases[p], current -| 32 * stride);
    const key = (m.index + 1) *% 0x9e3779b97f4a7c15 ^ first;
    if (ss.mini_key[p] != key) {
        compact_counts[p] = 0;
        ui.collected.reset();
        ui.strokes = true;
        u.clip(.{ .x = 0, .y = 0, .w = 0, .h = 0 });
        const v = ui.Ui.init(u.f);
        for (0..128) |i| {
            const address = first +| i * stride;
            if (address >= ranges[p].addr +| ranges[p].len) break;
            var bytes: [16]u8 = undefined;
            var known: [16]bool = @splat(false);
            m.read(address, bytes[0..stride], known[0..stride]) catch continue;
            if (std.mem.indexOfScalar(bool, known[0..stride], true) == null) continue;
            const row = compact_counts[p];
            compact_addresses[p][row] = address;
            compact_counts[p] += 1;
            const y = @as(f32, @floatFromInt(row)) * 24;
            if (p == 1) {
                _ = canim.rows.slot(v, y, panes[p].w - 60, m, address, 0, &.{}, 0, .{ .most = 2 }, "", false, null);
            } else memoryRow(v, m, address, y, panes[p].w - 60, true, 1, .hex, null, .none, null);
        }
        ui.strokes = false;
        u.unclip();
        ss.mini[p] = ui.collected;
        ss.mini_key[p] = key;
    }
    var mini = Geometry.mini(panes[p]);
    mini.w -= 16;
    var first_row: f32 = 0;
    for (compact_addresses[p][0..compact_counts[p]], 0..) |addr, i| if (addr <= current) {
        first_row = @floatFromInt(i);
    };
    canim.minimap.liveStrip(u, ss.mini[p].runs[0..ss.mini[p].n_runs], .{ .x = mini.x, .y = mini.y, .w = mini.w, .h = mini.h }, panes[p].w - 60, compact_counts[p], first_row, Geometry.visible(panes[p]), null);
}
fn segmentMini(u: ui.Ui, p: usize, first: u64, len: u64, current: u64) void {
    var box = Geometry.mini(panes[p]);
    box.x += 34;
    box.w -= 34;
    u.fill(.{ .x = box.x, .y = box.y, .w = box.w, .h = box.h }, ui.theme.color.raised);
    const total: f64 = @floatFromInt(@max(1, ranges[p].len));
    const at: f32 = @floatCast(@as(f64, @floatFromInt(first -| ranges[p].addr)) / total);
    const size: f32 = @floatCast(@as(f64, @floatFromInt(len)) / total);
    u.frame(.{ .x = box.x, .y = box.y + at * (box.h - 3), .w = box.w, .h = @max(3, @min(box.h, size * box.h)) }, ui.theme.color.text.dim, 1);
    if (current >= ranges[p].addr and current - ranges[p].addr < ranges[p].len) {
        const y = box.y + @as(f32, @floatCast(@as(f64, @floatFromInt(current - ranges[p].addr)) / total)) * (box.h - 2);
        u.line(.{ box.x, y }, .{ box.x + box.w, y }, ui.theme.mark(.current).solid, 2);
    }
}
fn visibleHit(hit: Hit) bool {
    if (hit.lens != null) return true;
    const overlay = lens_box orelse return true;
    const x = hit.box.x + hit.box.w / 2;
    const y = hit.box.y + hit.box.h / 2;
    if (contains(overlay, x, y)) for (lens_boxes[0..drawn_lenses]) |box| if (contains(box, x, y)) return false;
    return true;
}
fn ties(u: ui.Ui, s: *const State, ss: *Session) void {
    if (s.help or s.segments or s.command_open) return;
    const hovered = addressAt(u.f.in.mouse_x / display_scale, u.f.in.mouse_y / display_scale);
    const address = if (hovered) |hit| hit.address else if (s.selected_address != 0) s.selected_address else if (ss.touch) |touch| touch.addr else return;
    var from: ?Box = if (hovered) |hit| hit.box else if (s.selected_address != 0) s.selected_box else null;
    if (from == null) for (hits[0..hit_count]) |hit| if (hit.address == address) {
        from = hit.box;
        break;
    };
    var first_visible: ?Box = null;
    var origin_visible = false;
    for (hits[0..hit_count]) |hit| if (hit.address == address and visibleHit(hit)) {
        if (first_visible == null) first_visible = hit.box;
        if (from != null and std.meta.eql(hit.box, from.?)) origin_visible = true;
    };
    if (!origin_visible) from = first_visible;
    const origin = from orelse return;
    if (ss.match_address != address or !std.meta.eql(ss.match_box, origin)) {
        ss.match_address = address;
        ss.match_box = origin;
        ss.match_at = u.f.in.now;
    }
    const seconds = @as(f32, @floatFromInt(u.f.in.now -| ss.match_at)) / 1e9;
    var rank: usize = 1;
    for (hits[0..hit_count]) |hit| if (hit.address == address and visibleHit(hit)) {
        const first = std.meta.eql(origin, hit.box);
        u.matchHighlight(.{ .x = hit.box.x, .y = hit.box.y, .w = hit.box.w, .h = hit.box.h }, seconds, if (first) 0 else rank, .{});
        if (!first) rank += 1;
    };
}
fn overlays(u: ui.Ui, s: *const State, ss: *Session, moment: ?zt.store.Moment) void {
    const ink = ui.theme.color.text;
    if (!s.lens) ss.lens_previous = 0;
    if (s.lens and moment != null) {
        const overlay = lensViewport();
        lens_box = overlay;
        const previous_bound = ui.bound;
        ui.bound = Geometry.scaled(overlay, display_scale);
        u.clip(.{ .x = overlay.x, .y = overlay.y, .w = overlay.w, .h = overlay.h });
        if (ss.lens_previous != s.lens_address) {
            ss.lens_at = u.f.in.now;
            ss.lens_previous = s.lens_address;
        }
        const seconds = @as(f32, @floatFromInt(u.f.in.now -| ss.lens_at)) / 1e9;
        const amount = ui.theme.ease(.standard, std.math.clamp(seconds / 0.2, 0, 1));
        for (s.lenses[0..s.lens_count], 0..) |lens, k| {
            const box: Box = .{ .x = overlay.x, .y = overlay.y + @as(f32, @floatFromInt(k)) * 204 - s.lens_scroll + (if (k + 1 == s.lens_count) 8 * (1 - amount) else 0), .w = overlay.w, .h = 188 };
            lens_boxes[k] = box;
            drawn_lenses = k + 1;
            const v = u.moved(box.x, box.y);
            if (box.y + box.h <= overlay.y or box.y >= overlay.y + overlay.h) continue;
            current_lens = @intCast(k);
            const code = executable(moment.?, lens.address);
            if (s.glass and u.f.host.gpu()) {
                const uniforms = [4]f32{ box.w * display_scale, box.h * display_scale, display_scale, 0 };
                u.f.backdrop(Geometry.scaled(box, display_scale), @embedFile("glass"), std.mem.asBytes(&uniforms));
                v.faded(0.25).fill(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }, ui.theme.color.lift);
            } else v.fill(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }, ui.theme.color.lift);
            _ = v.faded(if (s.glass) 0.8 else 1).panel(box.w, box.h, v.print("lens {d}", .{k + 1}), .{});
            if (box.w > 520) v.text(.sans, 15, 320, 21, if (code) "disassembly · wheel browse · Shift-wheel chain" else "memory · wheel browse · Shift-wheel chain", ink.dim);
            if (client != null and s.following and s.status == .stopped and !lens.cycle) {
                const key = lens.first ^ (s.pc *% 0x9e3779b97f4a7c15);
                if (ss.lens_inspected[k] != key) {
                    ss.lens_inspected[k] = key;
                    u.f.run(v.print("inspect {s} 0x{x} {d}", .{ if (code) "code" else "memory", lens.first, @as(u32, if (code) 32 else 128) }));
                }
            }
            _ = v.address(90, 21, lens.address, .{ .ink = ui.rgb(canim.rows.ink(canim.rows.regionOf(moment.?, lens.address))) });
            button(v, box.w - 40, -2, .{ .kind = .close_lens, .address = k }, "Close lens and descendants", true, false);
            v.clip(.{ .x = 2, .y = 30, .w = box.w - 4, .h = box.h - 32 });
            if (lens.cycle) {
                v.text(.sans_medium, 20, 16, 65, "Cycle · this address is already an ancestor", ui.theme.mark(.current).solid);
            } else {
                const first = lens.first;
                const focus_start = if (code) lens.address else (lens.address & ~@as(u64, 15)) -| 32;
                var bytes: [80]u8 = undefined;
                var known: [80]bool = @splat(false);
                moment.?.read(first, &bytes, &known) catch {};
                if (std.mem.indexOfScalar(bool, &known, true) == null) {
                    v.text(.sans, 18, 16, 62, if (s.following and s.status == .stopped) "Unreadable pointer · no bytes captured" else "Uncaptured at this recorded stop", ink.dim);
                } else if (code) {
                    var pc = first;
                    for (0..6) |i| {
                        var text: [1024]u8 = undefined;
                        const insn = (zt.telescope.instruction(moment.?, pc, &text) catch null) orelse {
                            v.text(.sans, 18, 16, 53 + @as(f32, @floatFromInt(i)) * 24, "Instructions not captured at this stop", ink.dim);
                            break;
                        };
                        var encoded: [15]u8 = undefined;
                        var captured: [15]bool = @splat(false);
                        if (insn.len == 0 or insn.len > 15) break;
                        moment.?.read(pc, encoded[0..insn.len], captured[0..insn.len]) catch break;
                        if (std.mem.indexOfScalar(bool, captured[0..insn.len], false) != null) break;
                        const row: canim.disasm.Insn = .{ .addr = pc, .len = insn.len, .text = insn.text };
                        const context = pc < focus_start or pc >= lens.focus_end;
                        canim.disasm.liveRow(v.faded(if (context) 0.4 else 1), row, 34 + @as(f32, @floatFromInt(i)) * 24, box.w - 12, moment.?, (moment.?.regs(s.tid) catch null) orelse .{}, .{ .compact = box.w < 520 });
                        pc +|= insn.len;
                    }
                } else for (0..6) |i| {
                    const address = first +| i * 16;
                    const context = address < focus_start or address >= lens.focus_end;
                    memoryRow(v.faded(if (context) 0.4 else 1), moment.?, address, 34 + @as(f32, @floatFromInt(i)) * 24, box.w - 12, false, s.unit, s.number_format, null, .none, null);
                }
            }
            v.unclip();
            current_lens = null;
            const from = if (k > 0) lens_boxes[k - 1] else lens.origin;
            const lane = overlay.x + 8;
            u.route(&.{ .{ from.x + @min(from.w, 40), from.y + from.h }, .{ lane, from.y + from.h + 8 }, .{ lane, box.y - 8 }, .{ box.x + 40, box.y } }, ui.theme.mark(.read).solid, .{ .width = 2, .head = .{ 6, 6 }, .progress = amount });
        }
        ui.bound = previous_bound;
        u.unclip();
    }
    if (s.segments and moment != null) {
        const box: Box = .{ .x = 24, .y = 112, .w = geometry.w - 48, .h = geometry.h - 160 };
        const v = u.moved(box.x, box.y);
        v.fill(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }, ui.theme.color.lift);
        _ = v.panel(box.w, box.h, v.print("segments → {s}", .{@tagName(s.focus)}), .{ .focus = true });
        v.text(.mono, 19, 12, 53, v.print("/ {s}▏", .{s.segment_query[0..s.segment_len]}), ink.primary);
        v.text(.sans, 15, 12, 76, "Enter opens · Esc closes · type to search", ink.dim);
        segment_hit_count = 0;
        segment_total = 0;
        const maps = moment.?.mappings(u.f.scratch) catch &.{};
        v.clip(.{ .x = 2, .y = 64, .w = box.w - 4, .h = box.h - 66 });
        for (maps) |map| {
            var buf: [4096]u8 = undefined;
            var path: []const u8 = "";
            _ = moment.?.mapping(map.addr, &path, &buf) catch null;
            const title = v.print("{s}  0x{x}–0x{x}  {d} KiB  {c}{c}{c}", .{ if (path.len == 0) "[anonymous]" else path, map.addr, map.addr +| map.len, map.len / 1024, @as(u8, if (map.prot & 1 != 0) 'r' else '-'), @as(u8, if (map.prot & 2 != 0) 'w' else '-'), @as(u8, if (map.prot & 4 != 0) 'x' else '-') });
            if (std.ascii.findIgnoreCase(title, s.segment_query[0..s.segment_len]) == null) continue;
            const row = segment_total;
            segment_total += 1;
            if (row < s.segment_row) continue;
            const y = 90 + @as(f32, @floatFromInt(row - s.segment_row)) * 78;
            if (y + 74 > box.h or segment_hit_count == segment_hits.len) continue;
            if (row == s.segment_row) v.fill(.{ .x = 2, .y = y, .w = box.w - 4, .h = 76 }, ui.theme.color.raised);
            v.text(.mono, 15, 12, y + 18, v.print("{x}–{x}", .{ map.addr, map.addr +| map.len }), ink.primary);
            v.text(.mono, 15, 12, y + 40, v.print("{c}{c}{c} · {d} KiB", .{ @as(u8, if (map.prot & 1 != 0) 'r' else '-'), @as(u8, if (map.prot & 2 != 0) 'w' else '-'), @as(u8, if (map.prot & 4 != 0) 'x' else '-'), map.len / 1024 }), ink.primary);
            v.text(.sans, 15, 12, y + 62, canim.rows.fitted(v, if (path.len == 0) "[anonymous]" else path, box.w - 24), ink.dim);
            segment_hits[segment_hit_count] = .{ .box = .{ .x = box.x, .y = box.y + y, .w = box.w, .h = 76 }, .address = map.addr };
            segment_hit_count += 1;
        }
        if (segment_total == 0) v.text(.sans, 20, 12, 90, "No matching mappings", ink.dim);
        v.unclip();
    }
    if (s.help) {
        const w = @min(860, geometry.w - 48);
        const v = u.moved((geometry.w - w) / 2, 112);
        v.fill(.{ .x = 0, .y = 0, .w = w, .h = @min(560, geometry.h - 160) }, ui.theme.color.lift);
        _ = v.panel(w, @min(560, geometry.h - 160), "Keys · Esc closes", .{ .focus = true });
        v.clip(.{ .x = 0, .y = 32, .w = w, .h = @max(0, geometry.h - 192) });
        const lines = [_][]const u8{ "s instruction · n source · c run", "Esc / Ctrl-c pause · Shift-r restart", "Ctrl +/− font · Ctrl-0 reset", "j/k scroll · PgUp/PgDn page", "h/l source · Shift-h/l horizontal", "Ctrl-d/u half page · Tab focus", "Ctrl-o/i address history", "[ / ] stops · F live · f follow", "t graph · d unobserved opacity", "p segments · v source · m minimap", "click: lens · right-click: stack/memory", "Lens wheel: browse · Shift: chain", "z lens · : command · ? help", "Gold current · bright observed", "Branch target: prediction only", "Dim: unknown between live stops" };
        for (lines, 0..) |line, i| v.text(.mono, 16, 12, 58 + @as(f32, @floatFromInt(i)) * 30, canim.rows.fitted(v, line, w - 24), ink.primary);
        v.unclip();
    }
    if (s.command_open) {
        u.fill(.{ .x = 24, .y = geometry.h - 42, .w = geometry.w - 48, .h = 40 }, ui.theme.color.lift);
        u.text(.mono, 22, 36, geometry.h - 11, u.print(":{s}▏", .{s.command_text[0..s.command_len]}), ink.primary);
    }
    if (tooltip) |b| {
        u.fill(.{ .x = 24, .y = geometry.h - 40, .w = geometry.w - 48, .h = 32 }, ui.theme.color.page);
        u.text(.sans_medium, 18, 36, geometry.h - 17, u.print("{s}{s}", .{ b.label, if (b.enabled) "" else " · unavailable in this state" }), if (b.enabled) ink.primary else ink.dim);
    }
}

fn changedHeat(seconds: f32) ui.Heat {
    const timing = ui.theme.time.strike;
    const cool = std.math.clamp((seconds - timing.hold) / timing.cool, 0, 1);
    return .{ .level = 1, .solid = 1 - ui.theme.ease(.standard, cool), .in = std.math.clamp(seconds / timing.in, 0, 1), .out = if (seconds < timing.pulse) ui.theme.pulse(seconds / timing.pulse) else 0, .corner = std.math.clamp((seconds - timing.hold - timing.cool + timing.corner) / timing.corner, 0, 1) };
}

fn flagsReadAt(m: zt.store.Moment, pc: u64) u16 {
    var buf: [1024]u8 = undefined;
    const insn = (zt.telescope.instruction(m, pc, &buf) catch null) orelse return 0;
    const row: canim.disasm.Insn = .{ .addr = pc, .len = insn.len, .text = insn.text };
    return canim.disasm.flagsRead(row.mnemonic());
}

fn rowOf(m: zt.store.Moment, start: u64, address: u64) ?usize {
    var pc = start;
    for (0..24) |i| {
        if (pc == address) return i;
        var buf: [1024]u8 = undefined;
        const insn = (zt.telescope.instruction(m, pc, &buf) catch null) orelse return null;
        pc += insn.len;
    }
    return null;
}

fn selected(ss: *Session, t: *zt.Trace, m: zt.store.Moment, regs: zt.Regs, tid: u32, low: u64, now: u64) void {
    if (rowOf(m, ss.code_start, regs.rip) == null) {
        ss.code_start = regs.rip;
        for (0..6) |_| {
            var buf: [1024]u8 = undefined;
            const insn = (zt.telescope.instruction(m, ss.code_start, &buf) catch null) orelse break;
            if (insn.back == 0) break;
            ss.code_start -|= insn.back;
        }
    }
    if (ss.shown) |old| if (old != m.index) {
        const prior = t.moment(old) catch m;
        if ((prior.line(ss.tid) catch null)) |line| if (sources.get(gpa, io, prior, line.file)) |file| {
            if (std.mem.endsWith(u8, file.path, ".js")) ss.origin_line = line;
        };
    };
    ss.shown = m.index;
    ss.tid = tid;
    ss.changed_at = now;
    ss.changed_regs = 0;
    ss.changed_stack = 0;
    ss.changed_flags = 0;
    ss.trail = @splat(0);
    ss.result_at = null;
    for (0..@min(m.index, 3)) |k| {
        const previous = t.moment(m.index - 1 - k) catch continue;
        const before = (previous.regs(tid) catch null) orelse continue;
        ss.trail[k] = before.rip;
        if (k != 0) continue;
        var code: [1024]u8 = undefined;
        if ((zt.telescope.instruction(previous, before.rip, &code) catch null)) |insn| {
            if (before.rip + insn.len == regs.rip) ss.result_at = before.rip;
        }
        for (zt.Regs.names[0..16], 0..) |reg, i| if (regs.named(reg).? != before.named(reg).?) {
            ss.changed_regs |= @as(u32, 1) << @intCast(i);
        };
        ss.changed_flags = regs.eflags ^ before.eflags;
        for (0..11) |i| {
            const addr = low + i * 8;
            const a = (canim.Recording.word(previous, addr, 8) catch null) orelse continue;
            const b = (canim.Recording.word(m, addr, 8) catch null) orelse continue;
            if (a != b) ss.changed_stack |= @as(u16, 1) << @intCast(i);
        }
    }
    ss.touch = null;
    ss.branch = null;
    var events = m.events(gpa) catch return;
    defer events.deinit(gpa);
    while (events.next()) |event| {
        if (event.ev.tid != tid) continue;
        const e = event.ev;
        if (e.kind == .touch and ss.touch == null) ss.touch = .{ .addr = e.a[0], .len = e.a[1], .how = @intCast(e.aux & 3) };
        if (e.kind == .branch) ss.branch = .{ .to = e.a[0], .taken = e.a[1] != 0, .kind = switch (e.aux) {
            1 => .call,
            2 => .jump,
            3 => .ret,
            else => .none,
        } };
    }
}