summaryrefslogtreecommitdiff
path: root/src/Kind.zig
blob: 04db2579a154cc9ad56874566e41fd908e0ac07f (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
//! A kind of pane that is neither text nor a terminal: a picture, a game,
//! anything an addon (a library, Addon.zig) brings. Its records and
//! functions are the C ABI of src/kinds/pardes_addon.h (translated, the
//! one copy); this file is the core's side of it: the kinds a core has
//! (`Registry`, what libraries brought, with their words and extensions),
//! and a pane's `Slot`, the state the core keeps round the kind's own.
//!
//! The core is deterministic and a kind is only the authority's: a
//! replica's core has the same registry (its words, its extensions) but no
//! code for a kind a library brought, and draws its panes from the
//! authority's frames (a Shadow, screen_state.zig). So every call into a
//! kind whose answer the core acts on is made at a place both cores reach,
//! and its `Outcome` (the answer, what it said, a Look) is taped: a replica
//! takes it off the tape. Paint and the reads (body, ctl, a dump) change
//! nothing and are not taped.
const std = @import("std");
const builtin = @import("builtin");
pub const c = @import("pardes_addon");
const pardes = @import("pardes.zig");
const walk = @import("walk.zig");
const tape = @import("tape.zig");
const surface = @import("surface.zig");
const views = @import("views.zig");
const Addon = @import("Addon.zig");
pub const Loaded = Addon.Loaded;
pub const LoadedWord = Addon.LoadedWord;
pub const loadedOf = Addon.loadedOf;
const Placement = surface.Placement;
const Pardes = pardes.Pardes;
const Pane = pardes.panes.Pane;

pub const Ops = c.pa_ops;
pub const abi_major: u32 = c.PA_ABI_MAJOR;
pub const abi: u32 = c.PA_ABI;

// The header's own sizes (its _Static_asserts), seen from here: the
// records the core reads are the ones addons are built to.
comptime {
    if (@sizeOf(usize) == 8) for (.{
        .{ c.pa_cell, 20 },      .{ c.pa_window, 24 }, .{ c.pa_rect, 16 },  .{ c.pa_cells, 8 },
        .{ c.pa_placement, 80 }, .{ c.pa_paint, 48 },  .{ c.pa_key, 8 },    .{ c.pa_mouse, 16 },
        .{ c.pa_api, 112 },      .{ c.pa_out, 16 },    .{ c.pa_word, 32 },  .{ c.pa_head, 56 },
        .{ c.pa_ops, 208 },      .{ c.pa_view, 32 },   .{ c.pa_tick, 128 },
    }) |r| if (@sizeOf(r[0]) != r[1]) @compileError(std.fmt.comptimePrint("{s} is {d} bytes, the header says {d}", .{ @typeName(r[0]), @sizeOf(r[0]), r[1] }));
}

// ---- the kinds a core has ----

pub const max_kinds = 16;

/// Which of its functions a kind has: what both cores decide by.
pub const Caps = packed struct(u16) {
    tick: bool = false,
    key: bool = false,
    mouse: bool = false,
    ctl: bool = false,
    jobs: bool = false,
    load: bool = false,
    search: bool = false,
    address: bool = false,
    view: bool = false,
    /// PA_PICTURES: its tag says how its pictures show, from the first frame.
    pictures: bool = false,
    pad: u6 = 0,
};

pub const Entry = struct {
    name: [16]u8 = @splat(0),
    version: u32 = 0,
    abi: u32 = 0,
    hash: [32]u8 = @splat(0),
    /// One more at each reload: a job's answer of another is dropped.
    gen: u32 = 0,
    caps: Caps = .{},
    path: Buf(256) = .{},
    /// A library refused, listed with `why`.
    refused: bool = false,
    why: Buf(128) = .{},

    pub fn nameOf(e: *const Entry) []const u8 {
        return std.mem.sliceTo(&e.name, 0);
    }
};

pub const Word = struct { kind: u8, name: Buf(32) = .{}, leader: Buf(8) = .{}, arg: u8 = 0, opens: u8 = 0, doc: Buf(96) = .{} };
pub const Ext = struct { kind: u8, ext: Buf(16) = .{} };

/// A core's kinds: what libraries brought (Addon.zig), as data both cores
/// hold alike; and each one's code here, which a replica has none of.
pub const Registry = struct {
    pub const replica = .{
        .local = .{"ops"},
        .len = .{ .{ "kinds", "n" }, .{ "words", "nwords" }, .{ "exts", "nexts" } },
    };
    kinds: [max_kinds]Entry = undefined,
    n: u8 = 0,
    words: [64]Word = undefined,
    nwords: u8 = 0,
    exts: [32]Ext = undefined,
    nexts: u8 = 0,
    ops: [max_kinds]?*const Ops = @splat(null),

    /// What the scan at start found.
    pub fn started(found: []const Loaded) Registry {
        var r: Registry = .{};
        for (found) |l| _ = r.take(l, "");
        return r;
    }

    pub fn byName(r: *const Registry, name: []const u8) ?u8 {
        for (r.kinds[0..r.n], 0..) |*e, i| if (!e.refused and std.mem.eql(u8, e.nameOf(), name)) return @intCast(i);
        return null;
    }

    // What libraries bring, the loader's (Addon.zig).
    pub const forPath = Addon.forPath;
    pub const word = Addon.word;
    pub const leader = Addon.leader;
    pub const take = Addon.take;
    pub const collides = Addon.collides;
    pub const drop = Addon.drop;
};

// ---- a pane of a kind ----

/// What the core keeps of a pane of a kind, round the kind's own state.
/// A rollback copy leaves it be, as a terminal's emulator; a dump writes
/// its record by hand (dump.zig). A digest walks every field a step reads
/// (17.2), which a dump carries and test/panes.zig's parity walk checks.
pub const Slot = struct {
    pub const replica = .{
        // The kind's own and the authority's (its code and memory, its
        // jobs' inputs, its file's hash, a placeholder's record), and what
        // a frame makes (the thumb, the pointer, whether one was drawn: a
        // view's, never a step's).
        .local = .{ "ops", "st", "gpa", "arena", "opened", "reloads", "jobs", "tokens", "record", "thumb_at", "thumb_span", "pointer", "painted", "over", "shadow", "used" },
    };
    /// Its kind's code here; null in a placeholder (`live` false: its kind
    /// not in the registry, its record kept for the day it comes) or a
    /// Shadow (a replica's pane of a library's kind).
    ops: ?*const Ops = null,
    live: bool = false,
    st: ?*anyopaque = null,
    /// The kind's allocations are its arena's, freed at the close.
    gpa: std.mem.Allocator,
    arena: std.heap.ArenaAllocator,
    name: [16]u8 = @splat(0),
    version: u32 = 0,
    /// The hash of the file's bytes it was opened from, 0 for none (a
    /// record's): whether the file a watch arms on is still those.
    opened: u64 = 0,
    /// Times its file changed under it (fileChanged): its pictures' keys
    /// carry it, since its kind numbers them afresh from each open, and a
    /// frontend keeps what it uploaded by key.
    reloads: u32 = 0,
    /// Its kind's generation when it was opened (Entry.gen).
    gen: u32 = 0,
    path: []u8 = &.{},
    /// Petscii, Palette and Ascii: how a frontend shows its placements.
    art: Placement.Art = .{},
    /// When `tick` is next due; 0, never; 1, at the next step.
    next_tick: u64 = 0,
    /// PA_FOCUSED as `tick` was last told.
    focused: bool = false,
    /// Its jobs' inputs, until the host takes them (Effect.job).
    jobs: [4]?Job = @splat(null),
    tokens: u32 = 0,
    /// A placeholder's: the kind's record, kept whole.
    record: ?[]u8 = null,
    /// Its `where` as its kind's last call left it (the call's outcome, on
    /// the tape): the place a step reads (a jump, Recent) on every core.
    where_text: Buf(32) = .{},
    /// What the kind said refusing its open (or a load), or `<path> is not here`.
    refused: Buf(160) = .{},
    /// Its words' last values, a `Word arg` line each, which a kind with
    /// no `dump` is given again when its pane comes back.
    values: Buf(256) = .{},
    /// Its prefix as its last tick set it (the tick's outcome, on the
    /// tape: a Shadow's is the authority's); where its window is in its
    /// whole (the rail's thumb), 0 and 0 for none, as its last frame says.
    prefix: Buf(96) = .{},
    thumb_at: f32 = 0,
    thumb_span: f32 = 0,
    /// The pointer its last frame asked for over it (PA_POINTER_*), and
    /// whether a frame was painted since its last tick.
    pointer: u8 = 0,
    painted: bool = false,
    /// Each view's facts (a hash of its pa_view) as `view` was last told
    /// them, 0 for none: a change tells it again.
    views: [views.max]u64 = @splat(0),
    /// The jobs whose answers it cancelled (`api.cancel`), dropped as they come.
    cancelled: [4]u32 = @splat(0),
    /// Debug: the sites a call over budget (or a raster over the bound) was said at.
    over: u32 = 0,
    /// What it has selected (`api.select`): a yank's, a chord's, a
    /// keyboard Look's.
    selection: []u8 = &.{},
    /// Its tag's default words: Term, its kind's words for its panes,
    /// Collapse Del.
    tail: Buf(160) = .{},
    /// A replica's frame of it, as the authority painted it.
    shadow: ?*Shadow = null,
    /// Debug: the kind's allocations, which paint must leave as they are
    /// (the list the page allocator's: a region's first is slow in Debug).
    used: if (checked) std.ArrayList([]u8) else void = if (checked) .empty else {},

    pub const Job = struct { token: u32, in: []u8 };

    pub const dumpWrite = @import("dump.zig").slotWrite;
    pub const dumpRead = @import("dump.zig").slotRead;
    pub const dumpFree = @import("dump.zig").slotFree;

    pub fn nameOf(s: *const Slot) []const u8 {
        return std.mem.sliceTo(&s.name, 0);
    }

    pub fn is(s: *const Slot, name: []const u8) bool {
        return std.mem.eql(u8, s.nameOf(), name);
    }

    pub fn free(s: *Slot) void {
        for (&s.jobs) |*j| if (j.*) |job| s.gpa.free(job.in);
        s.gpa.free(s.selection);
        if (checked) s.used.deinit(std.heap.page_allocator);
        if (s.shadow) |sh| sh.deinit(s.gpa);
        s.arena.deinit();
        s.gpa.free(s.path);
        if (s.record) |r| s.gpa.free(r);
        s.* = undefined;
    }
};

const checked = builtin.mode == .debug;

fn caps(p: *const Pardes, s: *const Slot) Caps {
    const k = p.kinds.byName(s.nameOf()) orelse return .{};
    return if (s.live) p.kinds.kinds[k].caps else .{};
}

/// A new slot of kind `k` for pane `id`, showing `path` (null for one a
/// word opened) from `bytes`: made whatever the kind says, with what it
/// refused in `slot.refused` for the caller to say.
pub fn open(p: *Pardes, id: usize, k: u8, path: ?[]const u8, bytes: ?[]const u8) !*Pane {
    const gpa = p.image_gpa;
    const e = &p.kinds.kinds[k];
    const s = try gpa.create(Slot);
    s.* = .{ .ops = p.kinds.ops[k], .live = true, .gpa = gpa, .arena = .init(gpa), .version = e.version, .gen = e.gen, .name = e.name };
    errdefer {
        s.free();
        gpa.destroy(s);
    }
    s.path = try gpa.dupe(u8, path orelse "");
    const pane = try p.newDocPane(id);
    pane.addon = s;
    _ = reopen(p, id, s, bytes);
    // Its file watched, as a text's is: changed on disk, it opens again
    // from it (fileChanged); retirePane lets the watch go.
    if (s.path.len > 0 and @import("fs.zig").localPath(s.path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } });
    return pane;
}

/// `open` of the file at `path`, read here (a file that cannot be read
/// is no bytes: its kind may refuse it). The slot stays ours across the
/// read: another request may make a pane meanwhile.
pub fn openFile(p: *Pardes, id: usize, k: u8, path: []const u8) !*Pane {
    p.reserved_slots[id] = true;
    const bytes: ?[]u8 = @import("fs.zig").read(p, path) catch null;
    p.reserved_slots[id] = false;
    defer if (bytes) |b| p.gpa.free(b);
    return open(p, id, k, path, bytes orelse "");
}

/// The slot's kind state made (`open`, then `load` with its record, or
/// `address` with its place and its words' last values): its refusal,
/// if the kind refused, in `slot.refused`. One call for both cores.
pub fn reopen(p: ?*Pardes, id: usize, s: *Slot, bytes: ?[]const u8) bool {
    // A replica has no kind's code: what the open says is the authority's.
    if (tape.authorityOnly("a kind's open")) return false;
    var cl: Call = .{ .p = p, .id = id, .slot = s };
    const prev = cl.begin("open");
    if (p) |core| if (core.kinds.byName(s.nameOf())) |k| {
        var w: std.Io.Writer = .fixed(&s.tail.bytes);
        w.writeAll(" Term") catch {};
        for (core.kinds.words[0..core.kinds.nwords]) |*kw| if (kw.kind == k and kw.opens == 0) w.print(" {s}", .{kw.name.slice()}) catch {};
        w.writeAll(" Collapse Del") catch {};
        s.tail.len = @intCast(w.buffered().len);
    };
    s.opened = if (bytes) |b| std.hash.Wyhash.hash(0, b) else 0;
    // Its file not read (not here): it waits for it, a placeholder.
    if (s.ops != null and bytes == null and s.path.len > 0) _ = cl.refused.print("{s} is not here", .{s.path}) else if (s.ops) |ops| {
        const path_z = s.arena.allocator().dupeSentinel(u8, s.path, 0) catch "";
        // (the budget's from here: the file's hash and the tag are the core's)
        if (checked) cl.began = @import("FrameStats.zig").nowNs();
        cl.opening = true;
        if (ops.open) |f| s.st = f(if (s.path.len > 0) path_z.ptr else null, if (bytes) |b| b.ptr else null, if (bytes) |b| b.len else 0);
        cl.opening = false;
        if (cl.refused.len == 0) if (s.record) |rec| if (ops.load) |f| if (f(s.st, rec.ptr, @intCast(rec.len), s.version) != c.PA_OK) {
            cl.refused.set("its load refused the record");
        };
        if (cl.refused.len == 0 and s.record == null) {
            if (s.where_text.len > 0) if (ops.address) |f| {
                _ = f(s.st, s.where_text.slice().ptr, @intCast(s.where_text.len));
            };
            var lines = std.mem.tokenizeScalar(u8, s.values.slice(), '\n');
            var reply: [160]u8 = undefined;
            if (ops.ctl) |f| while (lines.next()) |line| {
                _ = f(s.st, line.ptr, @intCast(line.len), &reply, reply.len);
            };
        }
        if (cl.refused.len > 0) if (ops.close) |f| f(s.st);
    }
    const o = cl.end(prev);
    s.refused.set(o.text);
    if (o.text.len > 0) return false;
    if (s.record) |r| s.gpa.free(r);
    s.record = null;
    s.live = true;
    if (p) |core| poke(core, s);
    return true;
}

/// Tick at the next step, once (16.2's rule 2).
fn poke(p: *const Pardes, s: *Slot) void {
    if (caps(p, s).tick) s.next_tick = 1;
}

/// Its file changed on disk: the pane opened again from the file as it is
/// now, its record kept for its `load` (a PDF's place, fit and tint: the
/// state `open` made from the new bytes takes them) or else its place and
/// its words. The authority's: a replica's Shadow follows its frames.
pub fn fileChanged(p: *Pardes, id: usize, _: []const u8) bool {
    const pane = p.panes[id] orelse return false;
    const s = pane.addon orelse return false;
    if (s.path.len == 0) return false;
    // A placeholder waiting for its file: here now, it opens.
    if (!s.live) {
        @import("dump.zig").reviveSlot(p, id, s);
        return s.live;
    }
    // Both cores read it and reopen it alike (the read and its open's
    // outcome on the tape); the kind's record only the authority has.
    const bytes: ?[]u8 = @import("fs.zig").read(p, s.path) catch null;
    defer if (bytes) |b| p.gpa.free(b);
    const record = @import("dump.zig").slotRecord(s) catch null;
    var place: [32]u8 = undefined;
    s.where_text.set(where(s, &place));
    if (s.ops) |o| if (o.close) |f| {
        var cl: Call = .{ .p = null, .id = 0, .slot = s, .quiet = true };
        const prev = cl.begin("close");
        f(s.st);
        _ = cl.end(prev);
    };
    s.st = null;
    s.arena.deinit();
    s.arena = .init(s.gpa);
    if (checked) s.used.clearRetainingCapacity();
    if (s.record) |r| s.gpa.free(r);
    s.record = record;
    s.reloads +%= 1;
    return reopen(p, id, s, bytes orelse "");
}

/// Its kind's close, then everything it had.
pub fn close(p: *Pardes, pane: *Pane) void {
    const s = pane.addon orelse return;
    if (s.ops) |ops| if (ops.close) |f| {
        var cl: Call = .{ .p = null, .id = 0, .slot = s, .quiet = true };
        const prev = cl.begin("close");
        f(s.st);
        _ = cl.end(prev);
    };
    _ = p;
    const gpa = s.gpa;
    s.free();
    gpa.destroy(s);
    pane.addon = null;
}

/// The pane's body painted over the `cols` x `rows` cells at (x, y):
/// its cells into `s`, its placements after the frame's others. A Shadow
/// draws the authority's frame of it; a placeholder says what it waits for.
pub fn draw(p: *Pardes, s: *surface.Surface, arena: std.mem.Allocator, pane: *Pane, id: usize, x: u16, y: u16, cols: u16, rows: u16) void {
    const slot = pane.addon orelse return;
    if (cols == 0 or rows == 0) return;
    const th = p.theme();
    const fg: surface.Color = if (th.fg) |f| .{ .rgb = f } else .default;
    const bg: surface.Color = if (th.bg) |b| .{ .rgb = b } else .default;
    var frame: Frame = .{ .cols = cols, .rows = rows };
    if (slot.ops == null and slot.live) {
        const sh = slot.shadow orelse return;
        frame = .{ .cells = sh.cells, .cols = sh.cols, .rows = sh.rows, .places = sh.places.items, .n = @intCast(sh.places.items.len), .gpu = sh.gpu };
    } else if (slot.ops == null) {
        var line: [160]u8 = undefined;
        const why = if (slot.refused.len > 0) slot.refused.slice() else "Addon load <path>";
        // Its kind here, it waits for its file (`<path> is not here`).
        const text = if (p.kinds.byName(slot.nameOf()) != null) why else std.fmt.bufPrint(&line, "addon {s} {d} is not loaded: {s}", .{ slot.nameOf(), slot.version, why }) catch &line;
        _ = s.print(x, y, cols, text, .{ .fg = fg, .bg = bg });
        return;
    } else frame.cells = (paint(p, slot, id, arena, cols, rows, &frame) orelse return);
    if (frame.gpu.len != 0) s.gpu_frames[id] = .{ .bytes = frame.gpu, .serial = pane.serial, .dst = .{ .x = x, .y = y, .w = cols, .h = rows } };
    for (0..@min(rows, frame.rows)) |r| for (0..@min(cols, frame.cols)) |col| {
        const cell = &frame.cells[r * frame.cols + col];
        if (cell.flags & c.PA_PAINTED == 0) continue;
        const len = @min(cell.len, 7);
        s.set(x + @as(u16, @intCast(col)), y + @as(u16, @intCast(r)), if (len == 0) " " else cell.text[0..len], styleOf(cell, fg, bg));
    };
    for (frame.places[0..frame.n]) |pl| {
        if (pl.rgba == null or pl.w == 0 or pl.h == 0) continue;
        const dx = @min(pl.dst.x, cols);
        const dy = @min(pl.dst.y, rows);
        _ = p.appendPlacement(.{
            .pane = @intCast(id),
            .raster = .{ .ptr = pl.rgba, .w = pl.w, .h = pl.h, .stride = pl.w * 4 },
            .src = .{ .x = pl.src.x, .y = pl.src.y, .w = pl.src.w, .h = pl.src.h },
            .dst = .{ .x = x + dx, .y = y + dy, .w = @min(pl.dst.w, cols - dx), .h = @min(pl.dst.h, rows - dy) },
            .at = if (pl.at.w == 0) null else .{ .x = pl.at.x, .y = pl.at.y, .w = pl.at.w, .h = pl.at.h },
            .key = Placement.keyOf(pane.serial, @truncate(pl.key >> 32), @truncate(pl.key)),
            .dirty = if (pl.from == 0) null else .{ .from = Placement.keyOf(pane.serial, @truncate(pl.from >> 32), @truncate(pl.from)), .y = pl.dirty_y, .h = pl.dirty_h },
            .art = slot.art,
        });
    }
}

/// A frame of a kind's pane: its cells, `cols` a row, and its placements.
pub const Frame = struct {
    gpu: []const u8 = &.{},
    cells: []c.pa_cell = &.{},
    cols: u16,
    rows: u16,
    places: []c.pa_placement = &.{},
    n: u32 = 0,
    buf: [64]c.pa_placement = undefined,
};

/// The one paint of a frame in the live view: its cells (in `arena`) and
/// placements into `frame`, its thumb and pointer into the slot. Debug
/// checks it changed none of the kind's memory.
pub fn paint(p: *const Pardes, slot: *Slot, id: usize, arena: std.mem.Allocator, cols: u16, rows: u16, frame: *Frame) ?[]c.pa_cell {
    const ops = slot.ops orelse return null;
    const cells = arena.alloc(c.pa_cell, @as(usize, cols) * rows) catch return null;
    @memset(std.mem.sliceAsBytes(cells), 0);
    var gpu: GpuPaint = .{ .arena = arena, .frame = frame };
    var out: c.pa_paint = std.mem.zeroInit(c.pa_paint, .{ .placements = &frame.buf, .cap = frame.buf.len, .gpu = GpuPaint.emit, .gpu_ctx = &gpu });
    const px = p.view().cell_pixels;
    const win = std.mem.zeroInit(c.pa_window, .{ .cells = cells.ptr, .stride = cols, .rows = rows, .cols = cols, .cell_w = px.w, .cell_h = px.h, .focused = @intFromBool(focusedAnywhere(p, id)), .view = p.live + 1, .glyphs = @intFromBool(!p.view().frontend.native_images) });
    var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true };
    const prev = cl.begin("paint");
    const before = if (checked) usedHash(slot) else {};
    ops.paint.?(slot.st, &win, &out);
    if (checked and usedHash(slot) != before) std.debug.panic("addon {s}: paint changed its state (paint must be pure)", .{slot.nameOf()});
    _ = cl.end(prev);
    frame.places = &frame.buf;
    // A picture over the bound is dropped, said once a pane (17.3).
    frame.n = 0;
    for (frame.buf[0..@min(out.n, frame.buf.len)]) |pl| {
        if (@as(u64, pl.w) * pl.h * 4 > c.PA_RASTER_MAX) {
            if (slot.over & 1 << 31 == 0) std.log.warn("{s}: a picture of {d} MB, over {d} MiB", .{ slot.nameOf(), @as(u64, pl.w) * pl.h * 4 >> 20, c.PA_RASTER_MAX >> 20 });
            slot.over |= 1 << 31;
            continue;
        }
        frame.buf[frame.n] = pl;
        if (slot.reloads != 0) {
            frame.buf[frame.n].key = std.hash.Wyhash.hash(slot.reloads, std.mem.asBytes(&pl.key));
            if (pl.from != 0) frame.buf[frame.n].from = std.hash.Wyhash.hash(slot.reloads, std.mem.asBytes(&pl.from));
        }
        frame.n += 1;
    }
    slot.thumb_at = std.math.clamp(out.at, 0, 1);
    slot.thumb_span = std.math.clamp(out.span, 0, 1);
    slot.pointer = @intCast(@min(out.pointer, 255));
    slot.painted = true;
    return cells;
}

fn usedHash(slot: *const Slot) u64 {
    var h = std.hash.Wyhash.init(0);
    for (slot.used.items) |m| h.update(m);
    return h.final();
}

fn styleOf(cell: *const c.pa_cell, fg: surface.Color, bg: surface.Color) surface.CellStyle {
    const a = cell.attrs;
    return .{
        .fg = colorOf(cell.fg, fg),
        .bg = colorOf(cell.bg, bg),
        .bold = a & c.PA_BOLD != 0,
        .dim = a & c.PA_DIM != 0,
        .italic = a & c.PA_ITALIC != 0,
        .reverse = a & c.PA_REVERSE != 0,
        .ul = if (a & c.PA_UNDERLINE != 0) .single else .off,
    };
}

fn colorOf(v: u32, default: surface.Color) surface.Color {
    return switch (v & 0xff000000) {
        c.PA_DEFAULT => default,
        0x02000000 => .{ .index = @truncate(v) },
        else => .{ .rgb = .{ @truncate(v >> 16), @truncate(v >> 8), @truncate(v) } },
    };
}

/// The start of its tag: its kind's prefix from its last tick (else the
/// kind's name), the core's art words for a kind of PA_PICTURES, and its
/// path. The authority's: a step reads it off the tape on a replica.
pub fn prefix(p: *const Pardes, arena: std.mem.Allocator, pane: *const Pane) ![]const u8 {
    const slot = pane.addon.?;
    var buf: [400]u8 = undefined;
    return arena.dupe(u8, tape.value(.addon, prefixOf, .{ p, slot, &buf }));
}

fn prefixOf(p: *const Pardes, slot: *const Slot, buf: *[400]u8) []const u8 {
    if (!slot.live) return if (slot.path.len > 0) slot.path else slot.nameOf();
    const own = slot.prefix.slice();
    var w: std.Io.Writer = .fixed(buf);
    w.writeAll(if (own.len > 0) own else slot.nameOf()) catch {};
    // The same bytes whichever view's step lays the tag out (17.2): glyph
    // art when Petscii says or the session's first view shows no pictures.
    const first = &p.views[@min(@ctz(p.views_open), views.max - 1)].?;
    if (caps(p, slot).pictures) w.print(" petscii:{s} palette:{t} ascii:{s}", .{
        if (slot.art.glyph or !first.frontend.native_images) "on" else "off",
        slot.art.palette,
        if (slot.art.ascii) "on" else "off",
    }) catch {};
    if (slot.path.len > 0) w.print(" {s}", .{slot.path}) catch {};
    return w.buffered();
}

/// A key at a pane whose kind takes keys: whether it did. A replica's
/// speculation leaves it to the authority.
pub fn key(p: *Pardes, id: usize, k: pardes.Key) bool {
    const slot = (p.panes[id] orelse return false).addon orelse return false;
    if (!caps(p, slot).key) return false;
    if (tape.authorityOnly("a key into a kind's pane")) return true;
    const pk: c.pa_key = .{ .cp = k.cp, .ctrl = @intFromBool(k.ctrl), .alt = @intFromBool(k.alt), .shift = @intFromBool(k.shift), .view = p.live + 1 };
    var cl: Call = .{ .p = p, .id = id, .slot = slot };
    const prev = cl.begin("key");
    if (slot.ops) |o| cl.ret = o.key.?(slot.st, &pk);
    return taken(p, slot, cl.end(prev));
}

fn taken(p: *Pardes, slot: *Slot, o: Outcome) bool {
    if (o.ret == 0) return false;
    poke(p, slot);
    return true;
}

pub fn takesKeys(p: *const Pardes, s: *const Slot) bool {
    return caps(p, s).key;
}

/// The kind's own rows for the core's `/`, those it found in the call
/// (`api.found`; later ones go to its +Search as they come); null for a
/// kind with no search.
pub fn search(p: *Pardes, id: usize, pat: []const u8) ?[]const u8 {
    const slot = (p.panes[id] orelse return null).addon orelse return null;
    if (!caps(p, slot).search) return null;
    if (tape.authorityOnly("a kind's search")) return null;
    var cl: Call = .{ .p = p, .id = id, .slot = slot };
    const prev = cl.begin("search");
    if (slot.ops) |o| o.search.?(slot.st, pat.ptr, @intCast(pat.len));
    // The rows are the authority's, on the tape: a replica's are those.
    const o = cl.end(prev);
    poke(p, slot);
    return o.rows;
}

/// A place in it (`address`): taken, or null and what the kind said of
/// the miss (empty when it said nothing).
pub fn address(p: *Pardes, id: usize, text: []const u8, said: *Buf(160)) bool {
    const slot = (p.panes[id] orelse return false).addon orelse return false;
    // By its caps, not its code: a Shadow calls as the authority does.
    if (!caps(p, slot).address) return false;
    if (tape.authorityOnly("a kind's address")) return true;
    var cl: Call = .{ .p = p, .id = id, .slot = slot, .missing = said };
    const prev = cl.begin("address");
    if (slot.ops) |o| cl.ret = o.address.?(slot.st, text.ptr, @intCast(text.len));
    const o = cl.end(prev);
    poke(p, slot);
    return o.ret != 0;
}

pub fn takesMouse(p: *const Pardes, s: *const Slot) bool {
    return caps(p, s).mouse;
}

/// The pointer at (col, row) of its body.
pub fn mouse(p: *Pardes, id: usize, m: pardes.Mouse, col: u16, row: u16) bool {
    const slot = (p.panes[id] orelse return false).addon orelse return false;
    if (!caps(p, slot).mouse) return false;
    if (tape.authorityOnly("the mouse in a kind's pane")) return true;
    const pm: c.pa_mouse = .{
        .button = switch (m.button) {
            .left => c.PA_LEFT,
            .middle => c.PA_MIDDLE,
            .right => c.PA_RIGHT,
            .wheel_up => c.PA_WHEEL_UP,
            .wheel_down => c.PA_WHEEL_DOWN,
            .wheel_left => c.PA_WHEEL_LEFT,
            .wheel_right => c.PA_WHEEL_RIGHT,
            else => 255,
        },
        .action = switch (m.kind) {
            .press => c.PA_PRESS,
            .release => c.PA_RELEASE,
            .motion => c.PA_MOTION,
            .drag => c.PA_DRAG,
        },
        .ctrl = @intFromBool(m.ctrl),
        .shift = @intFromBool(m.shift),
        .alt = @intFromBool(m.alt),
        .view = p.live + 1,
        .col = col,
        .row = row,
        .amount = m.amount,
    };
    var cl: Call = .{ .p = p, .id = id, .slot = slot };
    const prev = cl.begin("mouse");
    if (slot.ops) |o| cl.ret = o.mouse.?(slot.st, &pm);
    return taken(p, slot, cl.end(prev));
}

/// The end of a step: each pane of a kind ticked that a call into it in
/// the step asked for (16.2's rule 2). At a step of the session's own
/// (`due`: a tick, a job's answer, a 9P request; never a client's input,
/// which a replica guesses), also each told of each view whose facts
/// changed (17.1), and ticked when its focus changed or its time came:
/// units of the session's origin, which a replica replays (17.2).
pub fn step(p: *Pardes, due: bool) void {
    const now = p.clock.stepped_ns;
    // A kind's call is the authority's alone: a speculation's tick after a
    // call into the pane waits with that call's input (it stopped there).
    if (tape.speculating()) {
        for (p.panes) |pslot| if (pslot) |pane| if (pane.addon) |slot| if (slot.next_tick == 1) return tape.poison("a kind's tick");
        return;
    }
    for (p.panes, 0..) |pslot, id| if (pslot) |pane| if (pane.addon) |slot| {
        if (due and caps(p, slot).view) for (0..views.max) |k| {
            var v = viewOf(p, @intCast(k), id);
            if (seen(&v) == slot.views[k]) continue;
            slot.views[k] = seen(&v);
            var cl: Call = .{ .p = p, .id = id, .slot = slot };
            const prev = cl.begin("view");
            if (slot.ops) |o| o.view.?(slot.st, &v);
            _ = cl.end(prev);
            poke(p, slot);
            p.needs_frame = true;
        };
        if (!caps(p, slot).tick) continue;
        const focused = focusedAnywhere(p, id);
        if (due and focused != slot.focused) slot.next_tick = 1;
        // 1 is the next step, whatever the clock says (a session whose
        // clock has not moved yet reads 0).
        if (slot.next_tick == 0 or (slot.next_tick > 1 and (!due or now < slot.next_tick))) continue;
        slot.focused = focused;
        var cl: Call = .{ .p = p, .id = id, .slot = slot };
        const prev = cl.begin("tick");
        // A frame drawn since its last tick: a fling's frames are counted by them.
        const flags = (if (focused) c.PA_FOCUSED else 0) | (if (slot.painted) c.PA_FRAMED else 0);
        slot.painted = false;
        // The clock's now for a tick after an event (a key, a focus): the
        // stepped frame lags it while the next wake is still to come.
        var t = std.mem.zeroInit(c.pa_tick, .{ .now = if (slot.next_tick == 1) @max(now, p.clock.now_ns) else now, .flags = flags });
        if (slot.ops) |o| {
            o.tick.?(slot.st, &t);
            cl.ret = @bitCast(t.next);
            cl.prefix = t.prefix[0..@min(t.prefix_len, t.prefix.len)];
        }
        const o = cl.end(prev);
        slot.next_tick = @bitCast(o.ret);
        slot.prefix.set(o.prefix);
        p.needs_frame = true;
    };
}

/// Whether some view's facts are not what its kind was told.
pub fn viewOwed(p: *const Pardes, slot: *const Slot, id: usize) bool {
    if (caps(p, slot).view) for (0..views.max) |k| if (seen(&viewOf(p, @intCast(k), id)) != slot.views[k]) return true;
    return false;
}

/// A view's facts as `view` is told them: 0 for one that shows it not.
fn seen(v: *const c.pa_view) u64 {
    return if (v.cols == 0) 0 else std.hash.Wyhash.hash(0, std.mem.asBytes(v));
}

/// The raster a frontend wants a kind's picture at (Kind.viewOf, a
/// `pa_view`): a terminal's kitty images go down a wire, so smaller; a
/// window rasterizes for its display.
const RasterPolicy = struct { dpi: u16, max_dimension: u16, match_viewport: bool };
/// A view's: a window's denser than a terminal's. By the view's frontend,
/// never the build's, so every core of a session asks a kind alike.
fn rasterPolicy(windowed: bool) RasterPolicy {
    return if (windowed) .{ .dpi = 192, .max_dimension = 4096, .match_viewport = true } else .{ .dpi = 96, .max_dimension = 1200, .match_viewport = false };
}

/// Pane `id` as view `k` shows it (its id k + 1): its body below its
/// notices, as draw.zig paints it, a cell's pixels, the theme's colours and
/// the raster that view's frontend wants a picture at; no cells when the
/// view is closed or shows it not.
pub fn viewOf(p: *const Pardes, k: u8, id: usize) c.pa_view {
    var out = std.mem.zeroes(c.pa_view);
    out.id = k + 1;
    const v = if (views.isOpen(p, k)) &(p.views[k] orelse return out) else return out;
    const pane = p.panes[id] orelse return out;
    const r = v.rects[id];
    // The live view's share of the pane is in its own fields, another's parked.
    const collapsed, const tag_rows = if (k == p.live) .{ pane.collapsed, pane.tag_rows } else .{ pane.pv[k].collapsed, pane.pv[k].tag_rows };
    if (collapsed) return out;
    // Its bands made again, never the copy a step or a park left: they are
    // derived, so a client joined from a dump has none.
    const notices = pardes.Messages.bands(p, v, pane, tag_rows, r, id).span();
    const th = p.theme();
    const rgb = struct {
        fn f(x: [3]u8) u32 {
            return @as(u32, x[0]) << 16 | @as(u32, x[1]) << 8 | x[2];
        }
    }.f;
    const policy = rasterPolicy(v.frontend.windowed);
    return .{
        .cols = r.w -| pardes.config.GUTTER,
        .rows = (r.h -| tag_rows) -| notices,
        .cell_w = v.cell_pixels.w,
        .cell_h = v.cell_pixels.h,
        .fg = rgb(th.fg orelse th.tag_fg),
        .bg = rgb(th.bg orelse th.tag_bg),
        .sel = rgb(th.sel_bg),
        .link = rgb(th.box),
        .dpi = policy.dpi,
        .max_px = policy.max_dimension,
        .fill = @intFromBool(policy.match_viewport),
        .glyphs = @intFromBool(!v.frontend.native_images),
        .id = k + 1,
        .pad = 0,
    };
}

/// Whether pane `id` has the keyboard in some view (its window focused).
fn focusedAnywhere(p: *const Pardes, id: usize) bool {
    for (&p.views) |*v| if (v.*) |*vw| if (vw.active == id and vw.window_focused) return true;
    return false;
}

/// When the kinds next want a step of the session's own: the soonest
/// deadline (now, for a view whose facts changed after the kind was told
/// them, or a focus), or null.
pub fn wake(p: *const Pardes) ?u64 {
    var soonest: ?u64 = null;
    for (p.panes, 0..) |pslot, id| if (pslot) |pane| if (pane.addon) |slot| {
        const moved = viewOwed(p, slot, id) or (caps(p, slot).tick and focusedAnywhere(p, id) != slot.focused);
        const due = if (moved) @max(1, p.clock.stepped_ns) else slot.next_tick;
        if (due != 0) soonest = @min(soonest orelse due, due);
    };
    return soonest;
}

/// A job's answer (Event.job): to its kind, unless its pane or its
/// kind's generation is another's since it was asked.
pub fn jobDone(p: *Pardes, pane_id: u8, serial: u32, token: u32, gen: u32, bytes: []const u8) void {
    const pane = p.panes[pane_id] orelse return;
    const slot = pane.addon orelse return;
    if (pane.serial != serial or slot.gen != gen or !caps(p, slot).jobs) return;
    // Cancelled: dropped, on every core (the cancel was on the tape).
    if (std.mem.indexOfScalar(u32, &slot.cancelled, token)) |i| {
        slot.cancelled[i] = 0;
        return;
    }
    var cl: Call = .{ .p = p, .id = pane_id, .slot = slot };
    const prev = cl.begin("job_done");
    if (slot.ops) |o| o.job_done.?(slot.st, token, bytes.ptr, @intCast(bytes.len));
    _ = cl.end(prev);
    poke(p, slot);
    p.needs_frame = true;
}

/// The pane's body as text (its 9P body), from the kind's `body`.
pub fn body(pane: *const Pane, gpa: std.mem.Allocator) ![]u8 {
    const slot = pane.addon orelse return gpa.alloc(u8, 0);
    const ops = slot.ops orelse return gpa.alloc(u8, 0);
    const len_f = ops.body_len orelse return gpa.alloc(u8, 0);
    const read = ops.body orelse return gpa.alloc(u8, 0);
    var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true };
    const prev = cl.begin("body");
    defer _ = cl.end(prev);
    const n: usize = @intCast(@min(len_f(slot.st), 64 << 20));
    const buf = try gpa.alloc(u8, n);
    var off: usize = 0;
    while (off < n) {
        const got = read(slot.st, off, buf[off..].ptr, @intCast(@min(n - off, 1 << 20)));
        if (got == 0) break;
        off += got;
    }
    return buf[0..off];
}

/// The kind's `dump` into `buf`, a quiet call.
pub fn dumpCall(slot: *Slot, f: anytype, buf: []u8) u32 {
    var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true };
    const prev = cl.begin("dump");
    defer _ = cl.end(prev);
    return f(slot.st, buf.ptr, @intCast(buf.len));
}

/// Where in it the pane is, as a text its `address` takes back.
pub fn where(slot: *Slot, buf: *[32]u8) []const u8 {
    const ops = slot.ops orelse return slot.where_text.slice();
    const f = ops.where orelse return "";
    var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true };
    const prev = cl.begin("where");
    defer _ = cl.end(prev);
    return buf[0..@min(buf.len, f(slot.st, buf, buf.len))];
}

/// A kind's word as written to its pane: null taken, else why not.
pub fn ctl(p: *Pardes, id: usize, line: []const u8, reply: *[160]u8) ?[]const u8 {
    const slot = (p.panes[id] orelse return "no such pane").addon orelse return "not a kind's pane";
    if (!slot.live) return "its addon is not loaded";
    if (!caps(p, slot).ctl) return "its kind takes no words";
    if (tape.authorityOnly("a kind's word")) return null;
    var cl: Call = .{ .p = p, .id = id, .slot = slot };
    const prev = cl.begin("ctl");
    @memset(reply, 0);
    if (slot.ops) |o| if (o.ctl.?(slot.st, line.ptr, @intCast(line.len), reply, reply.len) != c.PA_OK) {
        const said = std.mem.sliceTo(reply, 0);
        cl.refused.set(if (said.len > 0) said else "refused");
    };
    const o = cl.end(prev);
    poke(p, slot);
    if (o.text.len == 0) return null;
    const n = @min(o.text.len, reply.len);
    @memcpy(reply[0..n], o.text[0..n]);
    return reply[0..n];
}

/// What its ctl file reads after the core's fields.
pub fn ctlRead(pane: *const Pane, buf: []u8) []const u8 {
    const slot = pane.addon orelse return "";
    const f = (slot.ops orelse return "").ctl_read orelse return "";
    var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true };
    const prev = cl.begin("ctl_read");
    defer _ = cl.end(prev);
    return buf[0..@min(buf.len, f(slot.st, buf.ptr, @intCast(buf.len)))];
}

// ---- a call into a kind ----

/// What a call into a kind did that the core takes on: its answer, a
/// refusal or reply, what it said, a Look, a text pane. The authority's
/// is taped; a replica's core takes it off the tape, kind or none.
pub const Outcome = struct {
    ret: i64 = 0,
    text: []const u8 = "",
    said: []const u8 = "",
    err: bool = false,
    look: []const u8 = "",
    pane_name: []const u8 = "",
    pane_text: []const u8 = "",
    exec: []const u8 = "",
    selected: ?[]const u8 = null,
    rows: []const u8 = "",
    /// A tick's: the start of its tag (pa_tick.prefix).
    prefix: []const u8 = "",
    /// Its `where` after the call (a key, a view, a job's answer may move
    /// it); null for a refused call.
    where: ?[]const u8 = null,
    /// The jobs it asked for (their tokens, 0 past the last): every core
    /// emits them, so a replica's effects are the authority's; and those
    /// it cancelled, every core drops.
    jobs: [8]u32 = @splat(0),
    cancels: [4]u32 = @splat(0),
};

/// The call under way: what `api` acts on, and what it gathers.
const Call = struct {
    p: ?*Pardes,
    id: usize,
    slot: *Slot,
    /// Paint and the reads: what the kind asks of `api` is dropped, and
    /// nothing is taped.
    quiet: bool = false,
    opening: bool = false,
    /// An address's: what it says of a miss is the Look's to say.
    missing: ?*Buf(160) = null,
    name: []const u8 = "",
    ret: i64 = 0,
    refused: Buf(160) = .{},
    said: Buf(160) = .{},
    err: bool = false,
    look: Buf(256) = .{},
    pane_name: Buf(64) = .{},
    pane_text: []const u8 = "",
    exec: Buf(256) = .{},
    selected: ?[]const u8 = null,
    rows: []const u8 = "",
    prefix: []const u8 = "",
    jobs: [8]u32 = @splat(0),
    cancels: [4]u32 = @splat(0),
    /// Debug: when it began, for the budget.
    began: u64 = 0,

    fn begin(cl: *Call, comptime name: []const u8) ?*Call {
        cl.name = name;
        if (checked) cl.began = @import("FrameStats.zig").nowNs();
        const prev = current;
        current = cl;
        return prev;
    }

    /// The call's outcome, as the authority's took it, done.
    fn end(cl: *Call, prev: ?*Call) Outcome {
        current = prev;
        if (checked) overBudget(cl);
        if (cl.quiet) return .{};
        var place: [32]u8 = undefined;
        // A refused open closed its state: no `where` to ask.
        const at: ?[]const u8 = if (cl.refused.len == 0) where(cl.slot, &place) else null;
        const o = tape.value(.addon, same, .{Outcome{ .ret = cl.ret, .text = cl.refused.slice(), .said = cl.said.slice(), .err = cl.err, .look = cl.look.slice(), .pane_name = cl.pane_name.slice(), .pane_text = cl.pane_text, .exec = cl.exec.slice(), .selected = cl.selected, .rows = cl.rows, .prefix = cl.prefix, .where = at, .jobs = cl.jobs, .cancels = cl.cancels }});
        if (o.where) |w| cl.slot.where_text.set(w);
        if (cl.p) |p| if (p.panes[cl.id]) |pane| for (o.jobs) |token| if (token != 0) p.emit(.{ .job = .{ .pane = @intCast(cl.id), .serial = pane.serial, .token = token } });
        for (o.cancels) |token| if (token != 0) {
            for (&cl.slot.jobs) |*j| if (j.*) |job| if (job.token == token) {
                cl.slot.gpa.free(job.in);
                j.* = null;
            };
            std.mem.copyForwards(u32, cl.slot.cancelled[1..], cl.slot.cancelled[0..3]);
            cl.slot.cancelled[0] = token;
        };
        if (o.selected) |sel| {
            cl.slot.gpa.free(cl.slot.selection);
            cl.slot.selection = cl.slot.gpa.dupe(u8, sel) catch &.{};
        }
        if (cl.missing) |m| if (o.err and o.ret == 0) {
            m.set(o.said);
            return o;
        };
        const p = cl.p orelse return o;
        if (o.said.len > 0) if (o.err) p.reportFailure(cl.id, o.said) else p.setMessage(cl.id, o.said);
        if (o.pane_name.len > 0) textPane(p, cl.id, cl.slot, o.pane_name, o.pane_text);
        if (o.look.len > 0) @import("look.zig").lookAt(p, cl.id, o.look);
        if (o.exec.len > 0) @import("mouse.zig").dispatchPointerBuiltin(p, cl.id, pardes.config.exec_cmd, o.exec, null);
        // Rows found after its search (a job's): onto its +Search.
        if (o.rows.len > 0 and !std.mem.eql(u8, cl.name, "search")) moreFound(p, cl.id, o.rows);
        return o;
    }
};
/// (The loop's: a job on a worker is in none.)
threadlocal var current: ?*Call = null;

/// A call's budget, in Debug: a frame (17.4; 2 ms in ReleaseFast, which
/// Debug's kinds run three to four times slower than).
const budget_ns = 16 * std.time.ns_per_ms;
const sites = [_][]const u8{ "open", "close", "tick", "paint", "view", "key", "mouse", "body", "address", "where", "ctl", "ctl_read", "job_done", "dump", "search" };
/// The first call over budget, `pdf: search took 118 ms, over 16 ms`:
/// what `--addon-test` fails on.
pub var breach: Buf(96) = .{};

fn overBudget(cl: *Call) void {
    const took = @import("FrameStats.zig").nowNs() -| cl.began;
    const site = for (sites, 0..) |n, i| {
        if (std.mem.eql(u8, n, cl.name)) break i;
    } else return;
    if (took <= budget_ns or cl.slot.over & @as(u32, 1) << @intCast(site) != 0) return;
    cl.slot.over |= @as(u32, 1) << @intCast(site);
    var line: Buf(96) = .{};
    std.log.warn("{s}", .{line.print("{s}: {s} took {d} ms, over {d} ms", .{ cl.slot.nameOf(), cl.name, took / std.time.ns_per_ms, budget_ns / std.time.ns_per_ms })});
    if (breach.len == 0) breach = line;
}

/// Rows a kind found after its search answered, appended to the pane's
/// +Search (the list its last `/` made), as a file search's stream in.
fn moreFound(p: *Pardes, id: usize, rows: []const u8) void {
    const pane = p.panes[id] orelse return;
    const rp = p.panes[pane.search_pane orelse return] orelse return;
    const rf = if (rp.file) |*f| f else return;
    const o = if (rf.output) |*x| x else return;
    const content = std.mem.concat(p.gpa, u8, &.{ rf.content, rows }) catch |err| return p.reportError(id, "found", err);
    pardes.panes.Output.fillResults(p, id, std.Io.Dir.path.dirname(rf.path) orelse p.sessionDir(), .search, o.arg(), content, null) catch |err| p.reportError(id, "found", err);
}

fn same(o: Outcome) Outcome {
    return o;
}

/// The call into an addon under way, for a crash record: `in addon
/// fake, paint`. Null outside one.
pub fn calling(buf: []u8) ?[]const u8 {
    const cl = current orelse return null;
    return std.fmt.bufPrint(buf, "in addon {s}, {s}", .{ cl.slot.nameOf(), cl.name }) catch null;
}

pub const api: c.pa_api = .{
    .size = @sizeOf(c.pa_api),
    .abi = c.PA_ABI,
    .pad = 0,
    .alloc = struct {
        fn f(n: usize) callconv(.c) ?*anyopaque {
            const cl = current orelse return null;
            // Its time the core's, not the kind's budget's (a region's
            // first allocation is slow in Debug), as a job's copy is.
            const t0 = if (checked) @import("FrameStats.zig").nowNs();
            defer if (checked) {
                cl.began += @import("FrameStats.zig").nowNs() -| t0;
            };
            const mem = cl.slot.arena.allocator().alignedAlloc(u8, .@"16", @max(n, 1)) catch return null;
            @memset(mem, 0);
            if (checked) cl.slot.used.append(std.heap.page_allocator, mem) catch {};
            return mem.ptr;
        }
    }.f,
    .free = struct {
        fn f(ptr: ?*anyopaque, n: usize) callconv(.c) void {
            const cl = current orelse return;
            const at: [*]align(16) u8 = @ptrCast(@alignCast(ptr orelse return));
            if (checked) for (cl.slot.used.items, 0..) |m, i| if (m.ptr == at) {
                _ = cl.slot.used.swapRemove(i);
                break;
            };
            cl.slot.arena.allocator().free(at[0..@max(n, 1)]);
        }
    }.f,
    .job = struct {
        /// Its input kept for the host, which runs it (Effect.job).
        fn f(in: ?*const anyopaque, n: u32) callconv(.c) u32 {
            const cl = current orelse return 0;
            if (cl.p == null or cl.quiet) return 0;
            const t0 = if (checked) @import("FrameStats.zig").nowNs();
            defer if (checked) {
                cl.began += @import("FrameStats.zig").nowNs() -| t0;
            };
            const s = cl.slot;
            const free = for (&s.jobs) |*j| {
                if (j.* == null) break j;
            } else return 0;
            const asked = std.mem.indexOfScalar(u32, &cl.jobs, 0) orelse return 0;
            const copy = s.gpa.dupe(u8, if (in) |b| @as([*]const u8, @ptrCast(b))[0..n] else "") catch return 0;
            s.tokens +%= 1;
            if (s.tokens == 0) s.tokens = 1;
            free.* = .{ .token = s.tokens, .in = copy };
            // Emitted as the call ends (Call.end), on every core.
            cl.jobs[asked] = s.tokens;
            return s.tokens;
        }
    }.f,
    .look = struct {
        fn f(text: [*c]const u8, n: u32) callconv(.c) void {
            const cl = current orelse return;
            if (!cl.quiet and text != null) cl.look.set(text[0..n]);
        }
    }.f,
    .say = struct {
        fn f(text: [*c]const u8, n: u32, err: c_int) callconv(.c) void {
            const cl = current orelse return;
            if (cl.quiet or text == null) return;
            // Refusing its open: the opener says why.
            if (err != 0 and cl.opening) return cl.refused.set(text[0..n]);
            cl.said.set(text[0..n]);
            cl.err = err != 0;
        }
    }.f,
    .text = struct {
        /// The pane is made as the call ends; its serial is the next.
        fn f(name: [*c]const u8, name_len: u32, bytes: [*c]const u8, n: u32) callconv(.c) u32 {
            const cl = current orelse return 0;
            const p = cl.p orelse return 0;
            if (cl.quiet or name == null or cl.pane_name.len > 0) return 0;
            cl.pane_name.set(name[0..name_len]);
            cl.pane_text = p.scratch.allocator().dupe(u8, if (bytes == null) "" else bytes[0..n]) catch "";
            return p.next_serial + 1;
        }
    }.f,
    .seed = struct {
        /// The same pane seeds the same on every machine.
        fn f() callconv(.c) u64 {
            const cl = current orelse return seed_base;
            const serial: u32 = if (cl.p) |p| (if (p.panes[cl.id]) |pane| pane.serial else 0) else 0;
            return std.hash.Wyhash.hash(seed_base, std.mem.asBytes(&serial));
        }
    }.f,
    .heap = struct {
        /// `heap`'s, any thread: realloc's, n 0 a free.
        fn f(ptr: ?*anyopaque, n: usize) callconv(.c) ?*anyopaque {
            // Its time the core's, as an arena's is (a region's first
            // allocation in Debug took 23 ms of a PDF's open).
            const t0 = if (checked) @import("FrameStats.zig").nowNs();
            defer if (checked) if (current) |cl| {
                cl.began += @import("FrameStats.zig").nowNs() -| t0;
            };
            if (n == 0) {
                kind_heap.free(ptr);
                return null;
            }
            return kind_heap.realloc(ptr, n);
        }
    }.f,
    .exec = struct {
        fn f(text: [*c]const u8, n: u32) callconv(.c) void {
            const cl = current orelse return;
            if (!cl.quiet and text != null) cl.exec.set(text[0..n]);
        }
    }.f,
    .select = struct {
        fn f(text: [*c]const u8, n: u32) callconv(.c) void {
            const cl = current orelse return;
            if (cl.quiet) return;
            const p = cl.p orelse return;
            cl.selected = p.scratch.allocator().dupe(u8, if (text == null) "" else text[0..n]) catch return;
        }
    }.f,
    .cancel = struct {
        fn f(token: u32) callconv(.c) void {
            const cl = current orelse return;
            if (cl.quiet or token == 0) return;
            const free = std.mem.indexOfScalar(u32, &cl.cancels, 0) orelse return;
            cl.cancels[free] = token;
        }
    }.f,
    .found = struct {
        /// Gathered in the call: the search's answer, or onto its +Search after.
        fn f(rows: [*c]const u8, n: u32) callconv(.c) void {
            const cl = current orelse return;
            const p = cl.p orelse return;
            if (cl.quiet or rows == null) return;
            cl.rows = std.mem.concat(p.scratch.allocator(), u8, &.{ cl.rows, rows[0..n] }) catch return;
        }
    }.f,
};

/// What `api.heap` hands out: memory that outlives a call, from any
/// thread (a document a kind keeps, its pixels, MuPDF's own). A host sets
/// it to its region for kinds (memory.zig); the C heap otherwise.
pub var heap: std.mem.Allocator = std.heap.c_allocator;
const kind_heap = @import("c_heap").Heap(&heap);

/// What every pane's seed is made from: 0, or `--addon-test`'s `seed N`.
pub var seed_base: u64 = 0;

/// A kind's list (`api.text`): a pane named `name` in its file's
/// directory, refilled when one is there, whose rows n and N walk from the
/// kind's pane, a Look of one going to its kind (look.zig lookKind).
fn textPane(p: *Pardes, id: usize, slot: *const Slot, name: []const u8, text: []const u8) void {
    const dir = std.Io.Dir.path.dirname(slot.path) orelse p.sessionDir();
    const content = p.gpa.dupe(u8, text) catch |err| return p.reportError(id, name, err);
    pardes.panes.Output.fillResults(p, id, dir, .kind, name, content, null) catch |err| p.reportError(id, name, err);
}

/// A kind for tests of the core's side of a kind's pane, no library: a
/// picture of one pixel over its body.
pub const test_kind = struct {
    const pixel = [4]u8{ 255, 0, 0, 255 };
    fn picture(_: ?*anyopaque, win: [*c]const c.pa_window, out: [*c]c.pa_paint) callconv(.c) void {
        out.*.placements[0] = std.mem.zeroInit(c.pa_placement, .{ .rgba = &pixel, .w = 1, .h = 1, .src = .{ .x = 0, .y = 0, .w = 1, .h = 1 }, .dst = .{ .x = 0, .y = 0, .w = win.*.cols, .h = win.*.rows } });
        out.*.n = 1;
    }
    const ops = std.mem.zeroInit(Ops, .{ .head = std.mem.zeroInit(c.pa_head, .{ .size = @sizeOf(c.pa_head), .abi = abi, .name = "test".* ++ @as([12]u8, @splat(0)), .version = 1, .flags = c.PA_PICTURES }), .paint = picture });

    /// Its index in `p`'s kinds, taken in at the first ask.
    pub fn of(p: *Pardes) u8 {
        if (p.kinds.byName("test")) |k| return k;
        var words: [64]LoadedWord = undefined;
        _ = p.kinds.take(loadedOf(&ops, "", @splat(0), &words), "");
        return p.kinds.n - 1;
    }
};

// ---- small things ----

pub fn Buf(comptime n: usize) type {
    return struct {
        pub const replica = .{ .len = .{.{ "bytes", "len" }} };
        bytes: [n]u8 = undefined,
        len: u16 = 0,

        const Self = @This();
        pub fn set(b: *Self, s: []const u8) void {
            const k = @min(s.len, n);
            std.mem.copyForwards(u8, b.bytes[0..k], s[0..k]);
            b.len = @intCast(k);
        }
        pub fn slice(b: *const Self) []const u8 {
            return b.bytes[0..b.len];
        }
        pub fn print(b: *Self, comptime fmt: []const u8, args: anytype) []const u8 {
            const s = std.fmt.bufPrint(&b.bytes, fmt, args) catch &b.bytes;
            b.len = @intCast(s.len);
            return b.slice();
        }
    };
}

// ---- a pane of a kind, as a Shadow (architecture §16.5) ----
//
// A replica's core has no code for a library's kind: such a pane is drawn
// from the authority's frame of it, painted at the size the peer's view
// gives it. A frame crosses as its size and the pointer it asks for, each
// row by its hash (with its cells when the peer's row there is another),
// then each placement by its key; its raster's pixels cross before it, as
// strips of rows (`raster` messages, `encodeStrip`), those over its `src`
// the peer was not sent with the frame before. The stream is ordered and
// loses nothing, so what the authority last sent a peer is what the peer
// holds, but for a raster its `Blobs` let go, which it asks for again.

const ShadowCell = c.pa_cell;
const Place = c.pa_placement;
/// A row's or a frame's content address, as a terminal's rows have one.
const Hash = u64;

/// A replica's frame of a pane of a kind: what Kind.draw draws for it, its
/// placements' pixels its peer's `Blobs`.
pub const Shadow = struct {
    gpu: []const u8 = &.{},
    cols: u16 = 0,
    rows: u16 = 0,
    cells: []ShadowCell = &.{},
    hashes: []Hash = &.{},
    places: std.ArrayList(Place) = .empty,
    pointer: u8 = 0,
    /// The raster it last asked for again (`apply`'s): asked once.
    wanted: u64 = 0,

    pub fn deinit(sh: *Shadow, gpa: std.mem.Allocator) void {
        gpa.free(sh.gpu);
        gpa.free(sh.cells);
        gpa.free(sh.hashes);
        sh.places.deinit(gpa);
        gpa.destroy(sh);
    }

    /// A frame message applied (`encodeShadow`'s), of the pane `serial`,
    /// each placement's pixels from `blobs`: one it lacks is not shown, and
    /// its name is what to ask for (once), else 0.
    pub fn apply(sh: *Shadow, gpa: std.mem.Allocator, bytes: []const u8, serial: u32, blobs: *Blobs) !u64 {
        var r: std.Io.Reader = .fixed(bytes);
        const cols = try r.takeInt(u16, .little);
        const rows = try r.takeInt(u16, .little);
        if (cols != sh.cols or rows != sh.rows) {
            gpa.free(sh.cells);
            gpa.free(sh.hashes);
            sh.cells = try gpa.alloc(ShadowCell, @as(usize, cols) * rows);
            sh.hashes = try gpa.alloc(Hash, rows);
            @memset(std.mem.sliceAsBytes(sh.cells), 0);
            @memset(sh.hashes, 0);
            sh.cols = cols;
            sh.rows = rows;
        }
        sh.pointer = try r.takeByte();
        for (0..rows) |y| {
            sh.hashes[y] = try r.takeInt(u64, .little);
            if (try r.takeByte() == 0) continue;
            for (sh.cells[y * cols ..][0..cols]) |*cell| {
                @memcpy(&cell.text, try r.take(8));
                cell.fg = try r.takeInt(u32, .little);
                cell.bg = try r.takeInt(u32, .little);
                cell.attrs = try r.takeInt(u16, .little);
                cell.len = try r.takeByte();
                cell.flags = try r.takeByte();
            }
        }
        sh.places.clearRetainingCapacity();
        var lacking: u64 = 0;
        for (0..try r.takeByte()) |_| {
            var pl = std.mem.zeroes(Place);
            pl.w = try r.takeInt(u32, .little);
            pl.h = try r.takeInt(u32, .little);
            inline for (.{ &pl.src.x, &pl.src.y, &pl.src.w, &pl.src.h, &pl.at.x, &pl.at.y, &pl.at.w, &pl.at.h }) |f| f.* = try r.takeInt(u32, .little);
            inline for (.{ &pl.dst.x, &pl.dst.y, &pl.dst.w, &pl.dst.h }) |f| f.* = try r.takeInt(u16, .little);
            pl.key = try r.takeInt(u64, .little);
            const name = std.hash.Wyhash.hash(serial, std.mem.asBytes(&pl.key));
            pl.rgba = (blobs.shows(name, &pl) orelse {
                lacking = name;
                continue;
            }).ptr;
            try sh.places.append(gpa, pl);
        }
        // Older frames have no optional GPU tail.
        const n = if (r.seek < r.end) try r.takeInt(u32, .little) else 0;
        if (n > 4 << 20) return error.BadGpuFrame;
        const gpu = try gpa.dupe(u8, try r.take(n));
        gpa.free(sh.gpu);
        sh.gpu = gpu;
        if (lacking == sh.wanted) return 0;
        sh.wanted = lacking;
        return lacking;
    }
};

/// A raster's strip: at most this many bytes of its rows (17.3).
pub const strip_max = 4 << 20;

/// How many of a `w`-pixel raster's rows a strip holds.
pub fn stripRows(w: u32) u32 {
    return @max(1, strip_max / (@as(u32, @max(w, 1)) * 4));
}

/// The strips of `pl`'s raster over its `src` rows, a bit each.
fn stripsOver(pl: *const Place) u64 {
    const per = stripRows(pl.w);
    const lo = @min(pl.src.y, pl.h) / per;
    const hi = (@min(pl.src.y +| pl.src.h, pl.h) + per - 1) / per;
    var bits: u64 = 0;
    for (lo..@min(hi, 64)) |i| bits |= @as(u64, 1) << @intCast(i);
    return bits;
}

/// Strip `i` of `pl`'s raster, a `raster` message's payload: its key, its
/// size, its first row, and its rows' bytes.
pub fn encodeStrip(pl: *const Place, i: u32, w: *std.Io.Writer) !void {
    const y0 = i * stripRows(pl.w);
    const row = @as(usize, pl.w) * 4;
    try w.writeInt(u64, pl.key, .little);
    try w.writeInt(u32, pl.w, .little);
    try w.writeInt(u32, pl.h, .little);
    try w.writeInt(u32, y0, .little);
    try w.writeAll(pl.rgba[y0 * row .. @min(pl.h, y0 + stripRows(pl.w)) * row]);
}

/// A peer's rasters of the panes of a kind, made from their strips by
/// name (the key with its pane's serial), kept to `max` bytes by least
/// recent use but for those a Shadow shows (17.3).
pub const Blobs = struct {
    list: std.ArrayList(Blob) = .empty,
    clock: u64 = 0,

    pub const max = 64 << 20;
    const Blob = struct { name: u64, w: u32, h: u32, bytes: []u8, have: u64 = 0, used: u64 = 0 };

    pub fn deinit(b: *Blobs, gpa: std.mem.Allocator) void {
        for (b.list.items) |x| gpa.free(x.bytes);
        b.list.deinit(gpa);
    }

    /// A `raster` message's payload (`encodeStrip`'s) into raster `name`,
    /// made at its first strip; `shown`, the pixels Shadows show now.
    pub fn strip(b: *Blobs, gpa: std.mem.Allocator, name: u64, payload: []const u8, shown: []const [*]const u8) !void {
        var r: std.Io.Reader = .fixed(payload);
        _ = try r.takeInt(u64, .little);
        const w = try r.takeInt(u32, .little);
        const h = try r.takeInt(u32, .little);
        const y0 = try r.takeInt(u32, .little);
        const rows = r.buffered();
        const row = @as(usize, w) * 4;
        if (row == 0 or rows.len % row != 0 or y0 % stripRows(w) != 0 or y0 + rows.len / row > h) return error.BadShadow;
        const x = for (b.list.items) |*x| {
            if (x.name == name) break x;
        } else made: {
            var held: usize = row * h;
            for (b.list.items) |x| held += x.bytes.len;
            while (held > max) {
                var old: ?usize = null;
                for (b.list.items, 0..) |x, i| if (std.mem.indexOfScalar([*]const u8, shown, x.bytes.ptr) == null and (old == null or x.used < b.list.items[old.?].used)) {
                    old = i;
                };
                const i = old orelse break;
                held -= b.list.items[i].bytes.len;
                gpa.free(b.list.swapRemove(i).bytes);
            }
            const bytes = try gpa.alloc(u8, row * h);
            errdefer gpa.free(bytes);
            try b.list.append(gpa, .{ .name = name, .w = w, .h = h, .bytes = bytes });
            break :made &b.list.items[b.list.items.len - 1];
        };
        if (x.w != w or x.h != h) return error.BadShadow;
        @memcpy(x.bytes[y0 * row ..][0..rows.len], rows);
        x.have |= @as(u64, 1) << @intCast(@min(63, y0 / stripRows(w)));
        b.clock += 1;
        x.used = b.clock;
    }

    /// Raster `name`'s pixels when it has every strip `pl` shows.
    fn shows(b: *Blobs, name: u64, pl: *const Place) ?[]u8 {
        for (b.list.items) |*x| if (x.name == name and x.w == pl.w and x.h == pl.h and stripsOver(pl) & ~x.have == 0) {
            b.clock += 1;
            x.used = b.clock;
            return x.bytes;
        };
        return null;
    }
};

/// What the authority last sent one peer of a pane of a kind: its rows'
/// hashes, its placements, and which strips of each raster it holds.
pub const ShadowSent = struct {
    serial: u32 = 0,
    cols: u16 = 0,
    hashes: std.ArrayList(Hash) = .empty,
    places: Hash = 0,
    keys: std.ArrayList(struct { key: u64, have: u64 }) = .empty,

    pub fn deinit(s: *ShadowSent, gpa: std.mem.Allocator) void {
        s.hashes.deinit(gpa);
        s.keys.deinit(gpa);
        s.* = .{};
    }

    /// The strips of `pl`'s raster over its `src` the peer lacks (a bit
    /// each, `encodeStrip`'s `i`), counted sent now.
    pub fn owed(s: *ShadowSent, gpa: std.mem.Allocator, pl: *const Place) !u64 {
        const need = stripsOver(pl);
        for (s.keys.items) |*k| if (k.key == pl.key) {
            defer k.have |= need;
            return need & ~k.have;
        };
        try s.keys.append(gpa, .{ .key = pl.key, .have = need });
        return need;
    }
};

/// Frame `f` of a pane (the pointer its paint asked for) for a peer that
/// was last sent `sent`: false, and nothing written, when it holds this
/// frame already. Its placements cross by key, their pixels as strips
/// before it (`ShadowSent.owed`), so a frame is small whatever it shows.
pub fn encodeShadow(gpa: std.mem.Allocator, sent: *ShadowSent, f: *const Frame, pointer: u8, w: *std.Io.Writer) !bool {
    var hashes: std.ArrayList(Hash) = .empty;
    errdefer hashes.deinit(gpa);
    for (0..f.rows) |y| try hashes.append(gpa, std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(f.cells[y * f.cols ..][0..f.cols])));
    const places = f.places[0..@min(f.n, 64)];
    var ph = std.hash.Wyhash.init(pointer);
    for (places) |*pl| inline for (.{ pl.w, pl.h, pl.src, pl.at, pl.dst, pl.key }) |v| ph.update(std.mem.asBytes(&v));
    if (f.gpu.len != 0) ph.update(f.gpu);
    const places_hash = ph.final();
    if (sent.cols == f.cols and std.mem.eql(Hash, sent.hashes.items, hashes.items) and sent.places == places_hash) {
        hashes.deinit(gpa);
        return false;
    }
    try w.writeInt(u16, f.cols, .little);
    try w.writeInt(u16, f.rows, .little);
    try w.writeByte(pointer);
    for (hashes.items, 0..) |h, y| {
        try w.writeInt(u64, h, .little);
        // Held only at the same size: a peer's Shadow of another starts afresh.
        const held = sent.cols == f.cols and sent.hashes.items.len == f.rows and sent.hashes.items[y] == h;
        try w.writeByte(@intFromBool(!held));
        if (!held) for (f.cells[y * f.cols ..][0..f.cols]) |*cell| {
            try w.writeAll(&cell.text);
            try w.writeInt(u32, cell.fg, .little);
            try w.writeInt(u32, cell.bg, .little);
            try w.writeInt(u16, cell.attrs, .little);
            try w.writeByte(cell.len);
            try w.writeByte(cell.flags);
        };
    }
    try w.writeByte(@intCast(places.len));
    for (places) |pl| {
        try w.writeInt(u32, pl.w, .little);
        try w.writeInt(u32, pl.h, .little);
        inline for (.{ pl.src.x, pl.src.y, pl.src.w, pl.src.h, pl.at.x, pl.at.y, pl.at.w, pl.at.h }) |v| try w.writeInt(u32, v, .little);
        inline for (.{ pl.dst.x, pl.dst.y, pl.dst.w, pl.dst.h }) |v| try w.writeInt(u16, v, .little);
        try w.writeInt(u64, pl.key, .little);
    }
    if (f.gpu.len > 4 << 20) return error.BadGpuFrame;
    try w.writeInt(u32, @intCast(f.gpu.len), .little);
    try w.writeAll(f.gpu);
    sent.hashes.deinit(gpa);
    sent.hashes = hashes;
    sent.cols = f.cols;
    sent.places = places_hash;
    // The strips of the rasters this frame shows: a key gone is sent whole again.
    var i: usize = 0;
    while (i < sent.keys.items.len) {
        const kept = for (places) |pl| {
            if (pl.key == sent.keys.items[i].key) break true;
        } else false;
        if (kept) i += 1 else _ = sent.keys.swapRemove(i);
    }
    return true;
}

test "a kind's head is checked before a core takes it, and a core's kinds are its own" {
    const Fake = struct {
        fn paint(_: ?*anyopaque, _: [*c]const c.pa_window, _: [*c]c.pa_paint) callconv(.c) void {}
    };
    var ops = std.mem.zeroInit(Ops, .{ .head = std.mem.zeroInit(c.pa_head, .{ .size = @sizeOf(c.pa_head), .abi = abi, .version = 3 }), .paint = Fake.paint });
    @memcpy(ops.head.name[0..5], "zzzab");
    var a: Registry = .{};
    var b: Registry = .{};
    var words: [64]LoadedWord = undefined;
    try std.testing.expect(a.take(loadedOf(&ops, "", @splat(1), &words), "") == null);
    try std.testing.expect(a.byName("zzzab") != null);
    try std.testing.expect(b.byName("zzzab") == null);
    try std.testing.expectEqualStrings("refused: kind zzzab is here already", a.take(loadedOf(&ops, "", @splat(1), &words), "").?);
    a.drop(a.byName("zzzab").?);
    try std.testing.expect(a.byName("zzzab") == null);
}

const GpuPaint = struct {
    arena: std.mem.Allocator,
    frame: *Frame,
    fn emit(ctx: ?*anyopaque, bytes: [*c]const u8, n: u32) callconv(.c) c_int {
        const self: *GpuPaint = @ptrCast(@alignCast(ctx orelse return 1));
        if (bytes == null or n > 4 << 20) return 1;
        self.frame.gpu = self.arena.dupe(u8, bytes[0..n]) catch return 1;
        return 0;
    }
};

test "a pane of a kind's frame a row taller or shorter is drawn whole at its peer, never a row it let go" {
    const gpa = std.testing.allocator;
    var cells: [2 * 3]ShadowCell = @splat(std.mem.zeroes(ShadowCell));
    cells[0] = .{ .text = "a".* ++ @as([7]u8, @splat(0)), .fg = 1, .bg = 2, .attrs = 0, .len = 1, .flags = c.PA_PAINTED };
    var f: Frame = .{ .cells = &cells, .cols = 2, .rows = 2 };
    var sent: ShadowSent = .{};
    defer sent.deinit(gpa);
    var blobs: Blobs = .{};
    const sh = try gpa.create(Shadow);
    sh.* = .{};
    defer sh.deinit(gpa);
    var out: std.Io.Writer.Allocating = .init(gpa);
    defer out.deinit();
    for ([_]u16{ 2, 3, 2 }) |rows| {
        f.rows = rows;
        out.clearRetainingCapacity();
        try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer));
        _ = try sh.apply(gpa, out.written(), 1, &blobs);
        try std.testing.expectEqualStrings("a", sh.cells[0].text[0..1]);
    }
}

test "a pane of a kind crosses as its frame, a row the peer holds as its hash, a raster by key after its strips over what it shows" {
    const gpa = std.testing.allocator;
    var cells: [3 * 2]ShadowCell = @splat(std.mem.zeroes(ShadowCell));
    cells[0] = .{ .text = "a".* ++ @as([7]u8, @splat(0)), .fg = 1, .bg = 2, .attrs = 0, .len = 1, .flags = c.PA_PAINTED };
    // A raster of three strips (4 MiB a strip at 1,024 px), of which it shows the second.
    const w: u32 = 1024;
    const per = stripRows(w);
    const pixels = try gpa.alloc(u8, @as(usize, w) * per * 3 * 4);
    defer gpa.free(pixels);
    @memset(pixels, 5);
    var f: Frame = .{ .cells = &cells, .cols = 3, .rows = 2, .n = 1 };
    f.buf[0] = std.mem.zeroInit(Place, .{ .rgba = pixels.ptr, .w = w, .h = per * 3, .src = .{ .x = 0, .y = per + 1, .w = w, .h = 10 }, .key = 9 });
    f.places = &f.buf;
    var sent: ShadowSent = .{};
    defer sent.deinit(gpa);
    var blobs: Blobs = .{};
    defer blobs.deinit(gpa);
    const sh = try gpa.create(Shadow);
    sh.* = .{};
    defer sh.deinit(gpa);
    var out: std.Io.Writer.Allocating = .init(gpa);
    defer out.deinit();
    const name = std.hash.Wyhash.hash(1, std.mem.asBytes(&f.buf[0].key));
    try std.testing.expectEqual(@as(u64, 0b010), try sent.owed(gpa, &f.buf[0]));
    try encodeStrip(&f.buf[0], 1, &out.writer);
    try std.testing.expect(out.written().len <= strip_max + 20);
    try blobs.strip(gpa, name, out.written(), &.{});
    out.clearRetainingCapacity();
    try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer));
    try std.testing.expectEqual(@as(u64, 0), try sh.apply(gpa, out.written(), 1, &blobs));
    try std.testing.expectEqualStrings("a", sh.cells[0].text[0..1]);
    try std.testing.expectEqual(@as(u8, 5), sh.places.items[0].rgba[per * w * 4]);
    // The same frame again: nothing to send, no strip owed.
    out.clearRetainingCapacity();
    try std.testing.expect(!try encodeShadow(gpa, &sent, &f, 0, &out.writer));
    try std.testing.expectEqual(@as(u64, 0), try sent.owed(gpa, &f.buf[0]));
    // Its src moves into the third strip: that one is owed, and a peer
    // without it does not show the raster and asks for it, once.
    f.buf[0].src.y = 2 * per + 1;
    try std.testing.expectEqual(@as(u64, 0b100), try sent.owed(gpa, &f.buf[0]));
    out.clearRetainingCapacity();
    try std.testing.expect(try encodeShadow(gpa, &sent, &f, 0, &out.writer));
    try std.testing.expect(out.written().len < 4 + 1 + 2 * 9 + 60 + 8);
    try std.testing.expectEqual(name, try sh.apply(gpa, out.written(), 1, &blobs));
    try std.testing.expectEqual(@as(usize, 0), sh.places.items.len);
    try std.testing.expectEqual(@as(u64, 0), try sh.apply(gpa, out.written(), 1, &blobs));
}

test "optional GPU frames cross shadows, change independently, and disappear" {
    const gpa = std.testing.allocator;
    var sent: ShadowSent = .{};
    defer sent.deinit(gpa);
    const shadow = try gpa.create(Shadow);
    shadow.* = .{};
    defer shadow.deinit(gpa);
    var blobs: Blobs = .{};
    defer blobs.deinit(gpa);
    var cell = std.mem.zeroes(ShadowCell);
    var frame: Frame = .{ .cols = 1, .rows = 1, .cells = @as([*]ShadowCell, @ptrCast(&cell))[0..1], .gpu = "first scene" };
    var out: std.Io.Writer.Allocating = .init(gpa);
    defer out.deinit();
    for ([_][]const u8{ "first scene", "second scene", "" }) |bytes| {
        frame.gpu = bytes;
        out.clearRetainingCapacity();
        try std.testing.expect(try encodeShadow(gpa, &sent, &frame, 0, &out.writer));
        _ = try shadow.apply(gpa, out.written(), 1, &blobs);
        try std.testing.expectEqualStrings(bytes, shadow.gpu);
        out.clearRetainingCapacity();
        try std.testing.expect(!try encodeShadow(gpa, &sent, &frame, 0, &out.writer));
    }
}