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
|
//! 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, 32 }, .{ 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, the place
// its kind says), 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", "jobs", "tokens", "record", "where_text", "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,
/// 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 and its `where`, kept whole.
record: ?[]u8 = null,
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: ?*@import("screen_state.zig").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);
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 {
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 "";
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;
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) };
} 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);
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;
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;
}
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 {
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 out: c.pa_paint = std.mem.zeroInit(c.pa_paint, .{ .placements = &frame.buf, .cap = frame.buf.len });
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;
frame.n = @min(out.n, frame.buf.len);
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 (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 (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 (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 (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));
}
/// 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, const notices = if (k == p.live) .{ pane.collapsed, pane.tag_rows, pane.notices.span() } else .{ pane.pv[k].collapsed, pane.pv[k].tag_rows, pane.pv[k].notices.span() };
if (collapsed) return out;
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 = pardes.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`, as the authority's kind says it (on the tape): what a step
/// keeps of it (a jump, Recent) a replica keeps alike.
pub fn placeOf(slot: *Slot, buf: *[32]u8) []const u8 {
const w = tape.value(.addon, where, .{ slot, buf });
// A Shadow's place is the authority's last (`where` says it after).
if (slot.ops == null) slot.where_text.set(w);
return w;
}
/// 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 (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)))];
}
fn authorityOnly(comptime why: []const u8) bool {
if (!tape.speculating()) return false;
tape.poison(why);
return true;
}
// ---- 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 = "",
/// 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 .{};
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, .jobs = cl.jobs, .cancels = cl.cancels }});
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;
}
};
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 return;
pardes.panes.Output.fillResults(p, id, std.fs.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 {
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.fs.path.dirname(slot.path) orelse p.sessionDir();
const content = p.gpa.dupe(u8, text) catch return;
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();
}
};
}
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);
}
|