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
|
//! libpardes — the static library the native macOS app links against.
//!
//! The split, which is the whole design: Zig keeps the core, the ptys, every
//! effect and the worker threads; Swift owns NSApplication, the window, input
//! translation and drawing. src/macos/pardes.h is the contract between them and
//! docs/macos.md argues for the shape.
//!
//! This is deliberately src/web.zig's boundary with the wasm removed. Both
//! hosts are the same animal — someone else owns the clock, feeds events in
//! through flat functions and reads one packed cell buffer out — and the
//! browser already proved the shape works. The one real divergence is that the
//! browser has no processes, so it forwards every effect to JavaScript, whereas
//! forkpty is right here and this file performs them.
//!
//! Everything below is main-thread only. The single exception is the `wakeup`
//! callback, which a pty reader task calls; the host's job is to hop to the
//! main thread and call pardes_tick.
//!
//! The Zig half is ordinary POSIX and builds/tests on Linux — see the dev-loop
//! section of docs/macos.md. Only the Swift app needs a Mac.
const std = @import("std");
const builtin = @import("builtin");
const posix = std.posix;
const libc = std.c;
const pardes = @import("pardes.zig");
const look = @import("look.zig");
const temp_file = @import("temp_file.zig");
const shell_bin = @import("shell_bin.zig");
const message = @import("message.zig");
const nested = @import("nested.zig");
/// The geometry types the pixel-attachment ABI carries. Behind the same
/// comptime gate the placements themselves are: a build without MuPDF emits no
/// attachments, so nothing here is analysed.
const image = if (pardes.pdf_enabled) @import("image.zig") else struct {};
const fonts = if (pardes.font_picker) @import("fonts.zig") else struct {
pub const want: ?[]const u8 = null;
};
const user_config = @import("user_config.zig");
extern "c" fn forkpty(amaster: *c_int, name: ?[*:0]u8, termp: ?*const anyopaque, winp: ?*const posix.winsize) c_int;
extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int;
extern "c" fn chdir(path: [*:0]const u8) c_int;
extern "c" fn _exit(status: c_int) noreturn;
extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
// TIOCSWINSZ: absent from std.c.T on darwin — _IOW('t', 103, winsize). Same
// constant the tty and gui shells spell for the same reason.
const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467));
// A library linked into an AppKit process has no terminal to garble, but it
// does share the app's stderr with Console.app. Same filter as src/main.zig:
// ghostty-vt narrates every unimplemented escape a child writes, and nobody
// wants that in a crash report. PARDES_LOG=1 gets the real logger back.
pub const std_options: std.Options = .{ .logFn = logFn };
fn logFn(
comptime level: std.log.Level,
comptime scope: @EnumLiteral(),
comptime format: []const u8,
args: anytype,
) void {
if (scope != .macos and scope != .dump and std.c.getenv("PARDES_LOG") == null) return;
std.log.defaultLog(level, scope, format, args);
}
const log = std.log.scoped(.macos);
// ---------------------------------------------------------------- boundary
/// Sync with: pardes_cell_s. The identical encoding is spelled a second time
/// for the browser as WebCell in src/web.zig.
///
/// ponytail: two copies of a fifteen-line pure encoder, not a shared module.
/// The web ABI is snapshot-tested through a headless Chrome that does not run
/// here, so extracting it would refactor a backend I cannot exercise to save
/// thirty lines. Merge them the day a third host wants the same bytes.
pub const Cell = extern struct {
text: [8]u8,
fg: u32,
bg: u32,
attrs: u16,
len: u8,
flags: u8,
};
/// Sync with: pardes_image_s. One rasterized attachment — a PDF page, or an
/// image pane's pixels — and where on the grid it goes.
///
/// Geometry travels in PHYSICAL PIXELS, because that is the space the core
/// already computed it in (pardes_resize hands it the physical cell). `cell_x`
/// and `cell_y` are the pane BODY's origin in cells and the only thing the
/// host has to multiply out; `dst` is relative to that origin, and `src` is
/// the crop of the raster to take. The core has already clipped both to the
/// viewport, which is what lets a host draw a continuous-scroll page without
/// inventing an overflow clip of its own.
pub const Image = extern struct {
/// pane lifetime, page and raster generation: together the cache key. A
/// host keeps its decoded texture while all three hold still, and `fit`,
/// panning and scrolling deliberately do not move them.
serial: u32,
page: u32,
revision: u32,
cell_x: u16,
cell_y: u16,
/// the body this attachment may not paint outside of, in cells
cell_w: u16,
cell_h: u16,
dst_x: u32,
dst_y: u32,
dst_w: u32,
dst_h: u32,
src_x: u32,
src_y: u32,
src_w: u32,
src_h: u32,
/// subpixel vertical displacement a proportional wheel kept
offset_y: f32,
iw: u32,
ih: u32,
/// iw * ih * 4 bytes, RGBA8. Borrowed until the next pardes_frame.
rgba: [*]const u8,
};
/// Sync with: pardes_runtime_s. Two callbacks, because everything else the
/// core asks for it already does itself — it owns the ptys, and look.openLink
/// hands URLs to /usr/bin/open. Both are optional at the ABI level: a host that
/// passes null simply does without, rather than trapping inside the library.
pub const Runtime = extern struct {
userdata: ?*anyopaque = null,
wakeup: ?*const fn (?*anyopaque) callconv(.c) void = null,
set_clipboard: ?*const fn (?*anyopaque, [*]const u8, usize) callconv(.c) void = null,
};
const color_default: u32 = 0x01000000;
const color_indexed: u32 = 0x02000000;
const cell_flag_default: u8 = 1;
// ---------------------------------------------------------------- state
/// One pty, and the task draining it. `gen` is the per-slot spawn generation:
/// the core reuses pane ids and has no close effect, so a respawned slot must
/// ignore the previous shell's late bytes rather than feed them to the new one.
const Pty = struct {
file: std.Io.File,
pid: posix.pid_t,
gen: u32,
reader: std.Io.Future(anyerror!void),
};
/// What a reader task hands the main thread. `gen` travels with the message so
/// a shell that was replaced while its read was in flight cannot have its
/// stragglers parsed into the pty that took its slot.
const Msg = union(enum) {
output: struct { pane: u8, gen: u32, bytes: []u8 },
eof: struct { pane: u8, gen: u32 },
/// One `Look <path>` line from a pardes launched inside this one. Arrives
/// on the listener thread; runs, like everything else, on the main one.
command: []u8,
fn free(m: Msg, gpa: std.mem.Allocator) void {
switch (m) {
.output => |o| gpa.free(o.bytes),
.eof => {},
.command => |c| gpa.free(c),
}
}
};
const inbox_capacity = 512;
const MessageBatch = struct {
items: [inbox_capacity]Msg = undefined,
len: usize = 0,
fn slice(batch: *MessageBatch) []Msg {
return batch.items[0..batch.len];
}
};
const Inbox = struct {
mutex: std.atomic.Mutex = .unlocked,
items: [inbox_capacity]Msg = undefined,
head: usize = 0,
len: usize = 0,
closed: bool = false,
/// Set when a wakeup has been delivered and not yet answered by a tick.
wake_pending: std.atomic.Value(bool) = .init(false),
fn lock(q: *Inbox) void {
// AppKit's main thread runs at a higher QoS than reader tasks, so yield
// periodically rather than donating a full core to a preempted reader.
var spins: u8 = 0;
while (!q.mutex.tryLock()) {
spins +%= 1;
if (spins == 0) std.Thread.yield() catch {} else std.atomic.spinLoopHint();
}
}
fn removeAt(q: *Inbox, offset: usize) Msg {
const removed = q.items[(q.head + offset) % q.items.len];
var i = offset;
while (i + 1 < q.len) : (i += 1)
q.items[(q.head + i) % q.items.len] = q.items[(q.head + i + 1) % q.items.len];
q.len -= 1;
return removed;
}
/// Pty output is lossy under sustained backpressure. EOF is structural, and
/// so is a nested `Look`: one is a reader that must be reaped, the other is
/// a launch that already exited believing it was delivered. Admit both by
/// evicting queued output. Every switch below is exhaustive on purpose — a
/// new message kind has to say which of the two it is.
fn push(q: *Inbox, gpa: std.mem.Allocator, m: Msg) void {
q.lock();
defer q.mutex.unlock();
if (q.closed) {
m.free(gpa);
return;
}
if (q.len == q.items.len) {
const lossy = switch (m) {
.output => true,
.eof, .command => false,
};
if (lossy) {
m.free(gpa);
return;
}
var offset: usize = 0;
while (offset < q.len) : (offset += 1)
if (switch (q.items[(q.head + offset) % q.items.len]) {
.output => true,
.eof, .command => false,
}) break;
if (offset == q.len) return;
q.removeAt(offset).free(gpa);
}
q.items[(q.head + q.len) % q.items.len] = m;
q.len += 1;
}
fn take(q: *Inbox) MessageBatch {
q.lock();
defer q.mutex.unlock();
var batch: MessageBatch = .{};
while (q.len > 0) {
batch.items[batch.len] = q.items[q.head];
batch.len += 1;
q.head = (q.head + 1) % q.items.len;
q.len -= 1;
}
q.head = 0;
return batch;
}
fn close(q: *Inbox, gpa: std.mem.Allocator) void {
q.lock();
defer q.mutex.unlock();
q.closed = true;
while (q.len > 0) {
q.items[q.head].free(gpa);
q.head = (q.head + 1) % q.items.len;
q.len -= 1;
}
q.head = 0;
}
};
const State = struct {
gpa: std.mem.Allocator,
threaded: *std.Io.Threaded,
io: std.Io,
core: *pardes.Pardes,
arena: std.heap.ArenaAllocator,
runtime: Runtime,
cells: []Cell = &.{},
frame_len: usize = 0,
/// The grid `cells` actually holds. Not read back off the core: a render
/// can move screen_w/screen_h and then fail, and a host that sized its
/// loops from those would walk off the buffer.
frame_cols: u16 = 0,
frame_rows: u16 = 0,
/// This frame's pixel attachments, flattened out of Surface.images. Grown
/// and reused like `cells`, and emptied by the same failure path — the
/// accessors must never describe a different frame than the cell count.
images: []Image = &.{},
images_len: usize = 0,
ptys: [pardes.MAX_PANES]?Pty = @splat(null),
inbox: Inbox = .{},
/// Per-slot spawn generation, owned by the main thread. A reader carries a
/// copy in every message it posts; anything that no longer matches belongs
/// to a shell this slot has already replaced.
gens: [pardes.MAX_PANES]u32 = @splat(0),
/// Sub-cell wheel distance the core has not been told about yet, one
/// accumulator per axis. The core moves a whole row or column at a time,
/// so fractional trackpad travel banks here and is spent as wheel presses
/// — see pardes_scroll. Separate axes because a diagonal drift must not
/// let one direction's residue push the other over a notch.
scroll_lag: f32 = 0,
scroll_lag_x: f32 = 0,
/// Degrees of trackpad rotation not yet spent as a search step — the same
/// accumulate-and-keep-the-remainder shape as scroll_lag, see pardes_rotate.
rotate_lag: f32 = 0,
/// The dial's angular velocity, in degrees per second. While fingers are
/// down this is a running estimate off the event stream; when they lift it
/// becomes the fling that `coasting` spends. Zero is a dial at rest.
rotate_velocity: f32 = 0,
/// When the last rotation event arrived, so the estimate above has a dt.
rotate_last_ns: i128 = 0,
/// Fingers are off and the dial is still turning. Separate from a nonzero
/// velocity because during the gesture that velocity is a MEASUREMENT —
/// spending it then would double every twist under the hand making it.
rotate_coasting: bool = false,
/// Panes whose shell has produced output since we last read its cwd.
///
/// The cwd is wanted for pane tags and for resolving a relative Look, and
/// asking libproc costs a syscall per pane. Polling it on a clock spends
/// that forever to notice something that only ever changes when the shell
/// runs a command — and a shell that ran a command always writes at least
/// its next prompt. So the read is owed to output, not to time: mark here
/// on the way past and settle it once at the end of the drain, however
/// many chunks that burst arrived in.
cwd_stale: [pardes.MAX_PANES]bool = @splat(false),
/// The socket a pardes launched inside this app connects to (nested.zig),
/// or -1 when it could not be bound and nested launches open their own
/// window as they always did.
sock_fd: c_int = -1,
/// Owns the bytes of the user config, which Options only borrows.
config_arena: std.heap.ArenaAllocator,
};
var state: ?State = null;
// ---------------------------------------------------------------- lifecycle
export fn pardes_init(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) c_int {
if (state != null) return 1; // already up; deinit first
initCore(runtime, cols_arg, rows_arg) catch |err| {
log.err("init failed: {t}", .{err});
return 2;
};
return 0;
}
/// The body is split out purely so the cleanup below is real: `errdefer` fires
/// on an error return and nothing else, so writing this inside an export that
/// returns c_int would leave every one of these as dead code — and a half-built
/// init leaks an arena, leaves zstbi pointing at a dead allocator, and (because
/// Io.Threaded installs process-wide SIGIO/SIGPIPE handlers that only its
/// deinit restores) hands those handlers permanently to the host app.
fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void {
const gpa = std.heap.smp_allocator;
const allocs = pardes.allocators.init(gpa);
errdefer pardes.allocators.deinit();
const threaded = try gpa.create(std.Io.Threaded);
errdefer gpa.destroy(threaded);
threaded.* = .init(gpa, .{});
errdefer threaded.deinit();
const io = threaded.io();
var config_arena: std.heap.ArenaAllocator = .init(gpa);
errdefer config_arena.deinit();
var opts: pardes.Options = .{
.tty_only = true,
.image_allocator = allocs.image,
.pdf_allocator = allocs.pdf,
.tree_sitter_allocator = allocs.tree_sitter,
};
// Native shells opt into the user config, and every builtin in it must have
// run before the host can render a frame — so it is read here, before
// Pardes.init, exactly as src/main.zig does it. The env map is rebuilt from
// libc's environ because a library has no std.process.Init to inherit one.
if (captureEnv(config_arena.allocator())) |*env| {
const found = user_config.load(io, config_arena.allocator(), env);
opts.startup_config = found.bytes;
opts.startup_config_path = found.path;
}
pardes.image.start(io, allocs.image);
errdefer pardes.image.stop();
if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf);
errdefer if (comptime pardes.pdf_enabled) pardes.pdf.stop();
pardes.syntax.start(allocs.tree_sitter);
errdefer pardes.syntax.stop();
const core = try pardes.Pardes.init(allocs.pardes, opts);
errdefer core.deinit();
// This host draws pixels. Without it the core assumes a terminal that
// cannot, and a PDF pane degrades to counted page turns with nothing on
// screen at all — which is exactly what it did. The SDL shell sets the
// same flag; the tty one sets it from the terminal's kitty-graphics
// capability, because there it is a question rather than a fact.
core.native_images = true;
// Shells emit OSC 133 prompt marks through these, which is what makes
// prompt hiding and click-to-move work.
writeFile(shell_bin.bash_rc_path, shell_bin.bash_rc);
writeFile(shell_bin.fish_rc_path, shell_bin.fish_rc);
// Apple's bash 3.2 prints the zsh-deprecation banner into every pane unless
// this is in the environment BEFORE bash starts — the rc file is too late.
if (comptime builtin.os.tag.isDarwin()) _ = setenv("BASH_SILENCE_DEPRECATION_WARNING", "1", 1);
state = .{
.gpa = gpa,
.threaded = threaded,
.io = io,
.core = core,
.arena = .init(allocs.frame),
.config_arena = config_arena,
.runtime = if (runtime) |r| r.* else .{},
};
const st = &state.?;
// The real grid, delivered as an EVENT and not as Options.cols/rows: the
// core defers each shell's greeting until it has seen a resize, and the
// first forkpty below takes its winsize straight off the core.
const cols = @max(1, cols_arg);
const rows = @max(1, rows_arg);
core.update(.{ .resize = .{ .cols = cols, .rows = rows } });
// The initial spawns happen before any reader task exists, mirroring the
// tty shell. Note the difference in what that buys: tty.zig runs from
// main() and really is single-threaded there, whereas this is called from
// applicationDidFinishLaunching, by which point AppKit and libdispatch
// have long since spawned threads. What keeps the fork safe is the child
// itself — chdir and execv, raw syscalls with nothing allocated between
// fork and exec — not the thread count. Ordering it this way anyway keeps
// the two backends readable side by side.
_ = drainEffects(st, false);
for (&st.ptys, 0..) |*slot, id| if (slot.*) |*pt| startReader(st, pt, @intCast(id));
// Last, because it is the one thing here that publishes this process to
// the outside: nothing may connect before the core can answer. The shells
// above are already forked, which is why the listener's fd is CLOEXEC —
// an orphaned bash holding it would keep the socket bound after we quit.
st.sock_fd = nested.listen();
if (st.sock_fd >= 0) {
const thread = std.Thread.spawn(.{}, lookServer, .{st}) catch |err| {
// Bound but unattended would be worse than never bound: every
// nested launch would connect, be believed, and vanish.
log.warn("nested Look server did not start ({t})", .{err});
nested.unlisten(st.sock_fd);
st.sock_fd = -1;
return;
};
thread.detach();
}
}
/// Accept `Look <path>` lines from pardes instances launched inside this app
/// and post them where the main thread will run them.
///
/// A detached thread around a call that never returns, exactly like the tty
/// backend's: close(2) does not release a thread parked in accept(2), so this
/// dies with the process rather than with the socket. The window that leaves
/// is one connection accepted between the last tick and process exit posting
/// into an inbox nobody drains — the same bound the pty readers have, and a
/// self-pipe to close it would be more machinery than the window is worth.
fn lookServer(st: *State) void {
var buf: [nested.max_line]u8 = undefined;
while (nested.acceptLine(st.sock_fd, &buf)) |line| {
const owned = st.gpa.dupe(u8, line) catch continue;
st.inbox.push(st.gpa, .{ .command = owned });
wake(st);
}
}
export fn pardes_deinit() void {
const st = &(state orelse return);
// Before anything else: it is the only fd another process can reach us
// through, and unlinking the file is what stops the next launch from
// connecting to a session that is halfway through tearing itself down.
// The thread parked in accept(2) is not released by this and dies with
// the process, which is what its detach() already said.
nested.unlisten(st.sock_fd);
st.sock_fd = -1;
// Every reader is joined here, before anything it touches is freed. The
// runtime joins its tasks on exit, so a reader left parked in read(2) would
// hang the process instead of the app quitting.
for (0..pardes.MAX_PANES) |pane| reap(st, @intCast(pane));
// Only now is the inbox quiet. Anything still queued owns gpa bytes and
// would show up as a leak rather than as the shutdown it actually is.
st.inbox.close(st.gpa);
if (st.cells.len > 0) st.gpa.free(st.cells);
if (st.images.len > 0) st.gpa.free(st.images);
st.arena.deinit();
st.core.deinit();
pardes.image.stop();
if (comptime pardes.pdf_enabled) pardes.pdf.stop();
pardes.syntax.stop();
st.config_arena.deinit();
st.threaded.deinit();
st.gpa.destroy(st.threaded);
pardes.allocators.deinit();
state = null;
}
export fn pardes_should_quit() bool {
const st = &(state orelse return true);
return st.core.quit;
}
/// Something on screen moves on its own and wants ~60 Hz ticks until it stops:
/// a theme transition fading, or the rotation dial coasting after a flick.
/// Both are spent by pardes_tick, so this is the host's only cue to keep
/// pumping — an idle pardes costs nothing precisely because it says false.
export fn pardes_animating() bool {
const st = &(state orelse return false);
return st.core.themeAnimationActive() or st.rotate_coasting;
}
/// The colour the host should paint everything the grid does not: the window
/// background behind the titlebar, and behind every pixel of a live resize the
/// view has not caught up with yet.
///
/// The theme's OWN background, not the chrome's, and so not animated — the
/// same split every other shell draws. Chrome (taglines, the move box, the
/// scrollbar) fades between themes over a handful of frames; document
/// backgrounds switch the instant the theme does, and this is one of those.
///
/// PARDES_COLOR_DEFAULT means the active theme declares NO background of its
/// own (`bg = null`: the curated `dark`, and every vendored `*_transparent`).
/// In a terminal that means "wear whatever the terminal is wearing"; a window
/// has nothing to wear, so the host lets its own backdrop through — see the
/// NSVisualEffectView in AppDelegate.
export fn pardes_theme_bg() u32 {
// Before pardes_init there is no session, but there IS a theme: the ring's
// first entry is what the core boots wearing, so answering with it keeps
// the window from opening one colour and flipping to another a frame later.
const th = if (state) |*st| st.core.theme() else &pardes.themes[0];
const bg = th.bg orelse return color_default;
return @as(u32, bg[0]) << 16 | @as(u32, bg[1]) << 8 | bg[2];
}
/// Re-read the cwd of every shell that just spoke, and only those.
///
/// A pane's tag shows this and a relative `Look` resolves against it, so it has
/// to follow the shell around rather than stay at the directory the pane was
/// spawned in. The tty and SDL hosts poll all of them every frame; here the
/// drain has just said exactly which shells produced bytes, and nothing else
/// can have changed one — a `cd` is a command, and a shell that ran a command
/// writes at least its next prompt. So an idle session costs nothing at all,
/// and a busy one costs one libproc call per pane per burst.
fn refreshCwds(st: *State) void {
for (&st.cwd_stale, 0..) |*stale, id| {
if (!stale.*) continue;
stale.* = false;
const pt = st.ptys[id] orelse continue;
var buf: [1024]u8 = undefined;
if (look.shellCwd(pt.pid, &buf)) |wd| st.core.setCwd(id, wd);
}
}
/// Drain what the reader tasks collected into the core, then perform whatever
/// the core queued in response. Returns whether this tick did any IO.
///
/// NOT a repaint signal, however tempting: the core changes the grid on its own
/// for a cursor move, a selection, a mode change and a scroll, none of which
/// queue an effect or read a pty, so all four return false here. The macOS host
/// learned that the expensive way — see the comment on pump() in
/// src/macos/Sources/AppDelegate.swift.
export fn pardes_tick() bool {
const st = &(state orelse return false);
// Cleared before the drain: a reader that pushes during this tick must be
// able to schedule the next one.
st.inbox.wake_pending.store(false, .release);
var batch = st.inbox.take();
var changed = batch.len > 0;
for (batch.slice()) |msg| {
defer msg.free(st.gpa);
switch (msg) {
.output => |o| {
if (st.gens[o.pane] != o.gen) continue;
st.cwd_stale[o.pane] = true;
st.core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } });
},
.eof => |e| {
if (st.gens[e.pane] != e.gen) continue;
// The shell is gone: join its reader (a completed future that
// is never awaited leaks its allocation), close the master and
// free the slot.
reap(st, e.pane);
st.core.update(.{ .eof = .{ .pane = e.pane } });
},
// Already filtered down to `Look ` by the accept side — this
// socket may open things and that is all it may do.
.command => |c| st.core.update(.{ .command = c }),
}
}
refreshCwds(st);
if (drainEffects(st, true)) changed = true;
// ...and ADVANCE the transition, which is the whole reason the host keeps
// ticking. The tty and SDL loops call `core.update(.tick)` on their own
// clocks; this host has no loop of its own, so the pump IS the clock — and
// without this the fade never moved: `chromeTheme()` stayed on the OLD
// theme's chrome forever, so every tagline kept its previous colours until
// the next launch, and `themeAnimationActive()` never went false, so the
// 16 ms re-pump in AppDelegate.pump spun for the rest of the session.
if (st.core.themeAnimationActive()) {
st.core.update(.tick);
changed = true;
}
// ...and the dial, for the same reason and off the same clock: one frame
// of coast per tick, decayed, until it is slower than a notch a second.
if (st.rotate_coasting) {
spendRotation(st, st.rotate_velocity * rotation_fling_step);
st.rotate_velocity *= rotation_fling_decay;
if (@abs(st.rotate_velocity) < rotation_fling_stop) {
st.rotate_velocity = 0;
st.rotate_coasting = false;
// The remainder dies with the gesture: a banked half-notch
// surviving into the next twist is the hysteresis `rotate 0`
// exists to clear.
st.rotate_lag = 0;
}
changed = true;
}
return changed;
}
// ---------------------------------------------------------------- events in
export fn pardes_key(cp_arg: u32, text_ptr: ?[*]const u8, len: usize, mods: u32) void {
const st = &(state orelse return);
if (cp_arg > std.math.maxInt(u21)) return;
const text: []const u8 = if (text_ptr) |p| p[0..len] else "";
st.core.update(.{ .key = .{
.cp = @intCast(cp_arg),
.text = text,
.ctrl = mods & 1 != 0,
.alt = mods & 2 != 0,
.shift = mods & 4 != 0,
} });
}
export fn pardes_paste(text_ptr: ?[*]const u8, len: usize) void {
const st = &(state orelse return);
const text: []const u8 = if (text_ptr) |p| p[0..len] else "";
st.core.update(.{ .paste = text });
}
/// Button and kind arrive as their boundary ordinals. An out-of-range value is
/// dropped rather than reaching an unchecked enum cast — same rule the browser
/// ABI keeps, for the same reason: the host is not part of this build.
export fn pardes_mouse(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u32) void {
const st = &(state orelse return);
const button: pardes.Mouse.Button = switch (button_arg) {
0 => .left,
1 => .middle,
2 => .right,
3 => .wheel_up,
4 => .wheel_down,
5 => .wheel_left,
6 => .wheel_right,
7 => .none,
else => return,
};
const kind: pardes.Mouse.Kind = switch (kind_arg) {
0 => .press,
1 => .release,
2 => .motion,
3 => .drag,
else => return,
};
st.core.update(.{ .mouse = .{
.button = button,
.kind = kind,
.col = col,
.row = row,
.ctrl = mods & 1 != 0,
} });
}
export fn pardes_scroll(delta_rows: f32, delta_cols: f32, col: u16, row: u16) void {
const st = &(state orelse return);
var down_left = takeScrollTicks(&st.scroll_lag, delta_rows);
while (down_left != 0) {
const down = down_left > 0;
down_left += if (down) -1 else 1;
st.core.update(.{ .mouse = .{
.button = if (down) .wheel_down else .wheel_up,
.kind = .press,
.col = col,
.row = row,
} });
}
// Horizontal after vertical, and through the same quantizer: the core's
// own drift guard (config.wheelTick) is what decides whether a sideways
// wobble during a vertical flick counts, so the shell must not second-guess
// it by filtering here.
var right_left = takeScrollTicks(&st.scroll_lag_x, delta_cols);
while (right_left != 0) {
const right = right_left > 0;
right_left += if (right) -1 else 1;
st.core.update(.{ .mouse = .{
.button = if (right) .wheel_right else .wheel_left,
.kind = .press,
.col = col,
.row = row,
} });
}
}
/// Spend a trackpad rotation as search steps. AppKit reports degrees since the
/// last event, counterclockwise positive; the core has no rotation, so the
/// dial is quantized into the keys a hand would otherwise press — clockwise is
/// `n` (forward through the matches), counterclockwise `N`.
export fn pardes_rotate(degrees: f32) void {
const st = &(state orelse return);
// A gesture beginning re-zeros the dial: leftover travel from the last
// twist must not make the first degree of this one jump a match — and it
// catches a fling still coasting, because a finger back down is how a hand
// catches a dial.
if (degrees == 0) {
st.rotate_lag = 0;
st.rotate_velocity = 0;
st.rotate_coasting = false;
st.rotate_last_ns = monotonicNs();
return;
}
noteRotationVelocity(st, degrees);
spendRotation(st, degrees);
}
/// The fingers lifted. What happens next is decided entirely by how fast they
/// were moving when they did: `rotationFling` subtracts the floor, so a slow
/// twist stops dead where it was put and a flick keeps going in proportion to
/// how hard it was thrown.
export fn pardes_rotate_end() void {
const st = &(state orelse return);
const last = st.rotate_last_ns;
st.rotate_last_ns = 0;
st.rotate_coasting = false;
// A hand that turned the dial, STOPPED, and then lifted has released at
// rest however fast it was moving before — and the last sample is still
// sitting there saying otherwise. Without this the most deliberate twist
// of all (turn, look at it, let go) is the one that flings.
if (last == 0 or monotonicNs() - last > 90 * std.time.ns_per_ms) {
st.rotate_velocity = 0;
return;
}
st.rotate_velocity = rotationFling(st.rotate_velocity);
st.rotate_coasting = st.rotate_velocity != 0;
}
/// Monotonic nanoseconds, the clock lsp_zls.zig already times with. Monotonic
/// and not REALTIME on purpose: a dial that flung because NTP stepped the wall
/// clock backwards would be a bug nobody ever reproduces.
///
/// Zero on failure, which is also the "no sample yet" sentinel — so a clock
/// that will not answer makes the dial refuse to fling rather than fling on a
/// garbage dt.
fn monotonicNs() i128 {
var ts: libc.timespec = undefined;
if (libc.clock_gettime(.MONOTONIC, &ts) != 0) return 0;
return @as(i128, ts.sec) * std.time.ns_per_s + ts.nsec;
}
/// One event's contribution to the velocity estimate, in degrees per second.
/// Smoothed, because a single 120 Hz sample of a human wrist is mostly noise
/// and the fling would otherwise be decided by whichever one happened to land
/// last.
fn noteRotationVelocity(st: *State, degrees: f32) void {
const now = monotonicNs();
const last = st.rotate_last_ns;
st.rotate_last_ns = now;
st.rotate_coasting = false;
if (last == 0 or now == 0) return;
const dt_ns = now - last;
// A gap this long is a gesture nobody announced the start of, not a slow
// one: dividing by it would report a crawl and eat a real fling.
if (dt_ns <= 0 or dt_ns > 200 * std.time.ns_per_ms) return;
const seconds: f32 = @floatCast(@as(f64, @floatFromInt(dt_ns)) / @as(f64, std.time.ns_per_s));
const sample = degrees / seconds;
if (!std.math.isFinite(sample)) return;
st.rotate_velocity = st.rotate_velocity * 0.35 + sample * 0.65;
}
/// Turn degrees into whole search steps, keeping the remainder. The one place
/// the dial reaches the core, so a hand-turned notch and a coasted one are the
/// same keystroke by construction.
fn spendRotation(st: *State, degrees: f32) void {
var left = takeRotationNotches(&st.rotate_lag, degrees);
while (left != 0) {
const back = left > 0; // counterclockwise
left += if (back) -1 else 1;
st.core.update(.{ .key = .{ .cp = if (back) 'N' else 'n' } });
}
}
export fn pardes_command(text_ptr: ?[*]const u8, len: usize) void {
const st = &(state orelse return);
const text: []const u8 = if (text_ptr) |p| p[0..len] else "";
if (text.len == 0) return;
st.core.update(.{ .command = text });
}
export fn pardes_resize(cols_arg: u16, rows_arg: u16, cell_w: u16, cell_h: u16) void {
const st = &(state orelse return);
const cols = @max(1, cols_arg);
const rows = @max(1, rows_arg);
st.core.update(.{ .resize = .{
.cols = cols,
.rows = rows,
.cell_pixels = if (@hasField(pardes.CellPixels, "w"))
.{ .w = @max(1, cell_w), .h = @max(1, cell_h) }
else
.{},
} });
}
// ---------------------------------------------------------------- frame out
export fn pardes_frame() u32 {
const st = &(state orelse return 0);
_ = st.arena.reset(.retain_capacity);
// The accessors below must never describe a different frame than the count
// this returns, so a failure empties all of them together rather than
// leaving last frame's buffer behind a fresh cols/rows.
st.frame_len = 0;
st.frame_cols = 0;
st.frame_rows = 0;
st.images_len = 0;
const surface = st.core.render(st.arena.allocator()) catch |err| {
log.err("render failed: {t}", .{err});
return 0;
};
const count: usize = @as(usize, surface.cols) * surface.rows;
if (count != st.cells.len) {
if (count == 0) {
if (st.cells.len > 0) st.gpa.free(st.cells);
st.cells = &.{};
} else {
const resized = if (st.cells.len == 0)
st.gpa.alloc(Cell, count)
else
st.gpa.realloc(st.cells, count);
st.cells = resized catch return 0;
}
}
st.frame_len = count;
st.frame_cols = surface.cols;
st.frame_rows = surface.rows;
for (surface.cells, st.cells[0..count]) |cell, *out| {
out.* = .{
.text = @splat(0),
.fg = encodeColor(cell.style.fg),
.bg = encodeColor(cell.style.bg),
.attrs = encodeAttrs(cell.style),
.len = if (cell.default) 1 else cell.len,
.flags = @intFromBool(cell.default),
};
if (cell.default) out.text[0] = ' ' else @memcpy(out.text[0..cell.len], cell.grapheme());
}
collectImages(st, surface);
return @intCast(count);
}
/// Flatten Surface.images into the flat C array the host walks.
///
/// A dropped attachment is a page that does not draw, never a wrong one, so
/// every failure here just stops collecting: the frame is still valid, it
/// simply has fewer pictures in it than the core offered.
fn collectImages(st: *State, surface: *const pardes.Surface) void {
if (comptime !pardes.pdf_enabled) return;
if (surface.nimages == 0) return;
if (st.images.len < surface.nimages) {
const resized = if (st.images.len == 0)
st.gpa.alloc(Image, surface.nimages)
else
st.gpa.realloc(st.images, surface.nimages);
st.images = resized catch return;
}
for (surface.images[0..surface.nimages]) |maybe| {
const place = maybe orelse continue;
if (place.iw == 0 or place.ih == 0 or place.rgba.len == 0) continue;
// Continuous documents hand over geometry the core already clipped to
// the viewport. Anything else (a static image pane) is the whole
// raster scaled into the whole body, which is the same two rectangles
// spelled without a crop.
const geometry = place.native.geometry orelse image.NativeGeometry{
.src = .{ .x = 0, .y = 0, .w = @intCast(place.iw), .h = @intCast(place.ih) },
.dst = .{
.x = 0,
.y = 0,
.w = @as(u32, place.w) * st.core.cell_pixels.w,
.h = @as(u32, place.h) * st.core.cell_pixels.h,
},
};
if (geometry.dst.w == 0 or geometry.dst.h == 0) continue;
if (geometry.src.w == 0 or geometry.src.h == 0) continue;
st.images[st.images_len] = .{
.serial = place.serial,
.page = place.native.page,
.revision = place.native.revision,
.cell_x = place.x,
.cell_y = place.y,
.cell_w = place.w,
.cell_h = place.h,
.dst_x = geometry.dst.x,
.dst_y = geometry.dst.y,
.dst_w = geometry.dst.w,
.dst_h = geometry.dst.h,
.src_x = geometry.src.x,
.src_y = geometry.src.y,
.src_w = geometry.src.w,
.src_h = geometry.src.h,
.offset_y = place.native.pixel_offset_y,
.iw = @intCast(place.iw),
.ih = @intCast(place.ih),
.rgba = place.rgba.ptr,
};
st.images_len += 1;
}
}
export fn pardes_frame_images() u32 {
const st = &(state orelse return 0);
return @intCast(st.images_len);
}
export fn pardes_frame_image_list() ?[*]const Image {
const st = &(state orelse return null);
return if (st.images_len == 0) null else st.images.ptr;
}
export fn pardes_frame_cells() ?[*]const Cell {
const st = &(state orelse return null);
return if (st.frame_len == 0) null else st.cells.ptr;
}
export fn pardes_frame_cols() u16 {
const st = &(state orelse return 0);
return st.frame_cols;
}
export fn pardes_frame_rows() u16 {
const st = &(state orelse return 0);
return st.frame_rows;
}
export fn pardes_cursor_x() i32 {
const st = &(state orelse return -1);
return if (st.core.surface.cursor) |c| c.x else -1;
}
export fn pardes_cursor_y() i32 {
const st = &(state orelse return -1);
return if (st.core.surface.cursor) |c| c.y else -1;
}
export fn pardes_cursor_bar() bool {
const st = &(state orelse return false);
return if (st.core.surface.cursor) |c| c.bar else false;
}
/// The acme verb the core last performed, and clears it. Ordinals, not the
/// enum: the host is not part of this build, so the boundary speaks integers
/// and the ABI guard asserts they are the ones the header names.
export fn pardes_take_haptic() c_int {
const st = &(state orelse return 0);
return switch (st.core.takeHaptic()) {
.none => 0,
.exec => 1,
.look => 2,
};
}
/// The file the `Font` builtin asked for, and clears it — the same take-once
/// shape as the haptic above, and the same one the SDL shell uses on this
/// exact variable.
///
/// A copy rather than the borrowed slice: `fonts.want` is a length and no
/// terminator, and C wants a string. One static buffer because there is one
/// core and the header promises the value only until the next call.
var font_path_z: [4096:0]u8 = undefined;
export fn pardes_font_take() ?[*:0]const u8 {
_ = state orelse return null;
if (comptime !pardes.font_picker) return null;
const want = fonts.want orelse return null;
fonts.want = null;
if (want.len >= font_path_z.len) return null;
@memcpy(font_path_z[0..want.len], want);
font_path_z[want.len] = 0;
return &font_path_z;
}
/// The FILE behind the focused pane, or null when there is none — a terminal,
/// an output buffer (`+Search` names a directory, not a document), or nothing
/// focused at all. A PDF and an image both count: they are real paths on disk,
/// and the titlebar's proxy icon is about the file, not about who can edit it.
///
/// A copy into a static buffer for the reason pardes_font_take keeps one: the
/// core owns a length and no terminator, C wants a string, and there is one
/// core. Valid until the next call.
var active_path_z: [4096:0]u8 = undefined;
export fn pardes_active_path() ?[*:0]const u8 {
const st = &(state orelse return null);
const path = activeFilePath(st) orelse return null;
if (path.len == 0 or path.len >= active_path_z.len) return null;
@memcpy(active_path_z[0..path.len], path);
active_path_z[path.len] = 0;
return &active_path_z;
}
/// Does the focused pane hold edits that are not on disk? False for everything
/// that cannot be saved in the first place, which is the same set
/// pardes_active_path answers null for minus the PDFs and images — those have
/// a path but no buffer, so they are never dirty.
export fn pardes_active_dirty() bool {
const st = &(state orelse return false);
const pane = st.core.panes[st.core.active] orelse return false;
const f = if (pane.file) |*x| x else return false;
if (f.output != null) return false;
return f.revision != f.saved_revision;
}
fn activeFilePath(st: *State) ?[]const u8 {
const pane = st.core.panes[st.core.active] orelse return null;
if (pane.file) |*f| return if (f.output == null) f.path else null;
if (comptime pardes.pdf_enabled) if (pane.pdfPath()) |path| return path;
if (pane.image) |*iv| return iv.path;
return null;
}
// ---------------------------------------------------------------- effects
/// Perform the IO the core queued. `threads_ok` is false for the one drain
/// inside pardes_init, which runs before any reader task exists.
///
/// ponytail: the lsp, pipe and watch effects do no work here. Each wants real
/// machinery — a worker plus a snapshot of the pane's file for lsp
/// (src/tty/tty.zig:919), a job copy for pipe, and FSEvents for watch, since
/// inotify is Linux-only. Lift tty.zig's implementations when the app is past
/// first light. Pipe and watch may simply be dropped; lsp may NOT, see below.
fn drainEffects(st: *State, threads_ok: bool) bool {
const core = st.core;
var did = false;
while (core.nextEffect()) |effect| {
did = true;
switch (effect) {
.spawn => |sp| {
// The core reuses pane ids and has no close effect, so a
// deleted pane's shell lives in its slot until a respawn lands
// here. Reap it: cancel joins the reader, and the generation
// bump makes its late bytes and eof unreadable.
reap(st, sp.pane);
st.gens[sp.pane] +%= 1;
const gen = st.gens[sp.pane];
const cwd = sp.cwd.slice();
var cwd_buf: [256:0]u8 = undefined;
var cwd_z: ?[*:0]const u8 = null;
// <= because writing the sentinel slot of a [N:0]u8 is legal,
// and Effect's cwd buffer is exactly 256: `<` would silently
// drop a maximal path and start the shell wherever the app
// bundle was launched from instead.
if (cwd.len > 0 and cwd.len <= cwd_buf.len) {
@memcpy(cwd_buf[0..cwd.len], cwd);
cwd_buf[cwd.len] = 0;
cwd_z = @ptrCast(&cwd_buf);
}
const child = forkShell(core.shellBin(), cwd_z, core.screen_h, core.screen_w);
st.ptys[sp.pane] = .{
.file = child.file,
.pid = child.pid,
.gen = gen,
.reader = .{ .any_future = null, .result = {} },
};
// Report the pane's starting directory back to the core (tags).
var lbuf: [1024]u8 = undefined;
if (look.shellCwd(child.pid, &lbuf)) |wd| core.setCwd(sp.pane, wd);
if (threads_ok) if (st.ptys[sp.pane]) |*pt| startReader(st, pt, sp.pane);
},
.write => |w| {
if (st.ptys[w.pane]) |pt| writeFd(pt.file.handle, w.bytes.slice());
},
.resize_pty => |rs| {
if (st.ptys[rs.pane]) |pt| {
const ws: posix.winsize = .{ .row = rs.rows, .col = rs.cols, .xpixel = 0, .ypixel = 0 };
_ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws));
}
},
.open_link => |url| look.openLink(url.slice()),
.save_file => |sf| {
const pane = core.panes[sf.pane] orelse continue;
const f = pane.file orelse continue;
var pathbuf: [4096:0]u8 = undefined;
if (f.path.len >= pathbuf.len) continue;
@memcpy(pathbuf[0..f.path.len], f.path);
pathbuf[f.path.len] = 0;
const fd = libc.open(pathbuf[0..f.path.len :0], .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
if (fd < 0) continue;
writeFd(fd, f.content);
_ = libc.close(fd);
// After the write, not beside it: every `continue` above is a
// save that did not happen and must not be reported as one.
var mbuf: [256]u8 = undefined;
core.setMessage(sf.pane, message.stamp(&mbuf, "saved", f.path));
},
.new_file => |request| {
var path_buf: [4096:0]u8 = undefined;
const made = temp_file.create(&path_buf) orelse continue;
if (core.openNewFile(request.pane, request.serial, made.path))
made.adopt()
else
made.discard();
},
.write_dump => {
const out = core.dump_out orelse continue;
var pbuf: [1024:0]u8 = undefined;
const path = pardes.dump.outPath(&pbuf) orelse continue;
const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
if (fd < 0) continue;
writeFd(fd, out);
_ = libc.close(fd);
core.setLastDump(path);
},
.set_clipboard => {
const cb = st.runtime.set_clipboard orelse continue;
const y = core.yank orelse continue;
cb(st.runtime.userdata, y.ptr, y.len);
},
// An empty answer, immediately: the honest reply from a shell with
// no worker, and the only safe one. Tab after a `.` DIVERTS to the
// backend instead of indenting and indents late, when the answer
// comes back empty (lspResponse); drop the effect and lsp_wait
// stays armed, the retroactive indent never fires, and every
// dot-Tab for the rest of the session does nothing at all.
.lsp => |q| core.update(.{ .lsp_resp = .{ .id = q.id, .rows = "" } }),
.pipe, .watch => {},
.quit => {},
}
}
return did;
}
// ---------------------------------------------------------------- workers
fn startReader(st: *State, pt: *Pty, id: u8) void {
pt.reader = st.io.concurrent(readPty, .{ st, st.io, pt.file, id, pt.gen }) catch |err| {
// No reader means the shell fills its pty buffer, blocks in write(2)
// and the pane silently freezes. Nothing recovers it, so at least say
// so — this is what PARDES_LOG exists for.
log.err("pane {d} has no reader ({t}); it will not show output", .{ id, err });
return;
};
}
/// Release one pane's shell: join the reader, close the master, reap the child.
/// Order matters — cancel is what unblocks a task parked in read(2), and the fd
/// must not be closed under a live reader. Called on eof and again on a spawn
/// into the same slot, so it has to tolerate an empty slot.
fn reap(st: *State, pane: u8) void {
var pt = st.ptys[pane] orelse return;
st.ptys[pane] = null;
pt.reader.cancel(st.io) catch {};
_ = libc.close(pt.file.handle);
// A library inside an app that runs for hours cannot leave these: the tty
// shell gets away with never reaping because the process exits seconds
// later, but here it would be one zombie per shell ever opened. NOHANG
// because the child may still be dying and the UI thread must not wait for
// it; the next reap or process exit collects whatever is left.
_ = libc.waitpid(pt.pid, null, posix.W.NOHANG);
}
/// Drain one pty into its inbox and wake the host. The same shape as the tty
/// shell's reader, with the vaxis event queue replaced by a mutex and one
/// callback: do the blocking thing away from the loop, hand the bytes over,
/// leave the core a state machine that never waits.
fn readPty(st: *State, io: std.Io, pty: std.Io.File, id: u8, gen: u32) anyerror!void {
var read_buf: [0x10000]u8 = undefined;
var reader = pty.readerStreaming(io, &read_buf);
while (true) {
var buf: [0x10000]u8 = undefined;
var vec = [_][]u8{&buf};
const n = reader.interface.readVec(&vec) catch break;
if (n == 0) break;
// Duped outside the lock on purpose — see Inbox.
const bytes = st.gpa.dupe(u8, buf[0..n]) catch break;
st.inbox.push(st.gpa, .{ .output = .{ .pane = id, .gen = gen, .bytes = bytes } });
wake(st);
}
st.inbox.push(st.gpa, .{ .eof = .{ .pane = id, .gen = gen } });
wake(st);
}
/// Ask the host for a tick, at most once per tick. `pardes_tick` clears the
/// flag before it drains, so a push that lands mid-drain still wakes and no
/// message can be left sitting in the inbox with nobody scheduled to read it.
fn wake(st: *State) void {
const cb = st.runtime.wakeup orelse return;
if (st.inbox.wake_pending.swap(true, .acq_rel)) return;
cb(st.runtime.userdata);
}
// ---------------------------------------------------------------- helpers
fn forkShell(bin: []const u8, cwd: ?[*:0]const u8, rows: u16, cols: u16) struct { file: std.Io.File, pid: posix.pid_t } {
var master: c_int = undefined;
// Resolved BEFORE the fork, into this frame, which the child inherits:
// nothing between fork and exec may allocate, so a PATH search cannot
// happen there.
var path_buf: [std.fs.max_path_bytes]u8 = undefined;
const spawn = shell_bin.resolve(bin, &path_buf);
const ws = posix.winsize{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 };
const pid = forkpty(&master, null, null, &ws);
if (pid == 0) {
if (cwd) |c| _ = chdir(c);
_ = execv(spawn.path, &spawn.argv);
_exit(127);
}
return .{ .file = .{ .handle = master, .flags = .{ .nonblocking = false } }, .pid = pid };
}
fn writeFd(fd: c_int, data: []const u8) void {
var off: usize = 0;
while (off < data.len) {
const n = libc.write(fd, data[off..].ptr, data.len - off);
if (n < 0) {
if (libc.errno(n) == .INTR) continue;
return;
}
// A zero-byte write makes no progress; looping on it would spin the
// main thread forever, which here means a beachball rather than the
// tty shell's hung terminal.
if (n == 0) return;
off += @intCast(n);
}
}
fn writeFile(path: [*:0]const u8, contents: []const u8) void {
const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
if (fd < 0) return;
defer _ = libc.close(fd);
writeFd(fd, contents);
}
/// Rebuild the process environment as a Map, because a library never sees the
/// std.process.Init that main() gets one from. Only the config-path lookup
/// reads it, and the arena owns the copies for the life of the process.
fn captureEnv(arena: std.mem.Allocator) ?std.process.Environ.Map {
var map: std.process.Environ.Map = .init(arena);
const environ = std.c.environ;
var i: usize = 0;
while (environ[i]) |entry| : (i += 1) {
const line = std.mem.span(entry);
const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue;
map.put(line[0..eq], line[eq + 1 ..]) catch return null;
}
return map;
}
fn encodeColor(color: pardes.Color) u32 {
return switch (color) {
.default => color_default,
.index => |index| color_indexed | @as(u32, index),
.rgb => |rgb| (@as(u32, rgb[0]) << 16) | (@as(u32, rgb[1]) << 8) | rgb[2],
};
}
fn encodeAttrs(style: pardes.CellStyle) u16 {
var attrs: u16 = 0;
attrs |= @as(u16, @intFromBool(style.bold)) << 0;
attrs |= @as(u16, @intFromBool(style.dim)) << 1;
attrs |= @as(u16, @intFromBool(style.italic)) << 2;
attrs |= @as(u16, @intFromBool(style.blink)) << 3;
attrs |= @as(u16, @intFromBool(style.reverse)) << 4;
attrs |= @as(u16, @intFromBool(style.invisible)) << 5;
attrs |= @as(u16, @intFromBool(style.strikethrough)) << 6;
attrs |= @as(u16, @intFromEnum(style.ul)) << 8;
return attrs;
}
/// Spend accumulated sub-row travel as whole wheel notches, keeping the
/// remainder. The core has no fractional scroll — both other shells do this
/// too — and the clamp is so that an absurd delta (a momentum-phase kinetic
/// fling reported in points, a NaN) cannot spin the emit loop.
fn takeScrollTicks(lag: *f32, delta_rows: f32) i32 {
if (!std.math.isFinite(delta_rows)) return 0;
const next = std.math.clamp(lag.* + delta_rows, -256, 256);
if (!std.math.isFinite(next)) return 0;
const whole: i32 = @intFromFloat(@trunc(next));
lag.* = next - @as(f32, @floatFromInt(whole));
return whole;
}
/// One search step per this many degrees of twist. Every notch is a jump to
/// another match, so it stays coarse enough that a thumb resettling cannot
/// walk the cursor across the file — but 20 degrees was more than a wrist
/// gives without thinking about it, and the dial felt stuck. Ten is still a
/// deliberate twist, and 36 steps to a full turn.
const rotation_notch_degrees: f32 = 10;
/// Where momentum STARTS, in degrees per second — and it starts at zero.
///
/// The fling is the release speed MINUS this, so a slow twist coasts not a
/// little but not at all, and the faster the flick the more there is. A plain
/// threshold would hand out two free notches the instant it was crossed, which
/// is the one thing a dial must not do: the same gesture, a hair quicker,
/// jumping twice as far is how a control stops feeling like a control.
const rotation_fling_floor: f32 = 70;
/// ...and the ceiling on what is left after that subtraction. AppKit reports a
/// thousand degrees a second for one frame of a twitch, and this cap is what
/// decides how far the hardest possible flick throws the list: 400 deg/s is
/// about 111 degrees of coast, so eleven matches. Twenty read as the list
/// getting away from you.
const rotation_fling_max: f32 = 400;
/// One pump of coasting. Fixed rather than measured: the host re-pumps at
/// ~60 Hz for exactly as long as pardes_animating says to, and a fixed step
/// makes one fling spend the same travel every time — which is what lets a
/// golden assert it instead of asserting the machine's timer jitter.
const rotation_fling_step: f32 = 1.0 / 60.0;
/// Per-step decay. 0.94 at 60 Hz is a little over half a second of coast, the
/// same order as the trackpad's own inertial scrolling.
const rotation_fling_decay: f32 = 0.94;
/// Below this the dial is at rest: one notch a second is not momentum, it is a
/// list still stepping long after the hand has moved on.
const rotation_fling_stop: f32 = 18;
/// The velocity a release at `speed` degrees/second actually coasts at, after
/// the floor is subtracted and the remainder capped. Zero means the twist was
/// a placement, not a throw — which is most of them.
///
/// Total travel follows from it and the decay as a geometric series:
/// `v * step / (1 - decay)`, i.e. about 0.28 degrees per degree/second. A
/// 200 deg/s release therefore coasts ~36 degrees, three or four notches.
fn rotationFling(speed: f32) f32 {
const excess = @min(@abs(speed) - rotation_fling_floor, rotation_fling_max);
if (excess < rotation_fling_stop) return 0;
return std.math.copysign(excess, speed);
}
/// Spend accumulated rotation as whole search steps, keeping the remainder.
/// Same contract as takeScrollTicks, including the clamp: an absurd delta
/// spends a bounded number of notches instead of spinning the emit loop.
fn takeRotationNotches(lag: *f32, degrees: f32) i32 {
if (!std.math.isFinite(degrees)) return 0;
const limit = rotation_notch_degrees * 64;
const next = std.math.clamp(lag.* + degrees, -limit, limit);
if (!std.math.isFinite(next)) return 0;
const whole: i32 = @intFromFloat(@trunc(next / rotation_notch_degrees));
lag.* = next - @as(f32, @floatFromInt(whole)) * rotation_notch_degrees;
return whole;
}
// ---------------------------------------------------------------- ABI guard
// The header is hand-written, so nothing but a test keeps it honest. build.zig
// translate-C's src/macos/pardes.h into this test build and every constant and
// layout below is asserted against the Zig side — ghostty's trick, and the
// cheapest possible insurance against a silent ABI skew.
/// Compare one declaration's arity and scalar widths against the header's.
/// Not a type equality — translate-C spells pointers `[*c]` and mints its own
/// struct types, so nothing here would ever match exactly. Arity and width are
/// what actually break: a parameter added on one side only (which is how the
/// Swift host first got pardes_scroll wrong), or a u16 that became a u32.
fn expectSameAbi(comptime C: type, comptime Z: type) !void {
const c_fn = @typeInfo(C).@"fn";
const z_fn = @typeInfo(Z).@"fn";
try std.testing.expectEqual(c_fn.params.len, z_fn.params.len);
inline for (c_fn.params, z_fn.params) |cp, zp|
try std.testing.expectEqual(@sizeOf(cp.type.?), @sizeOf(zp.type.?));
try std.testing.expectEqual(@sizeOf(c_fn.return_type.?), @sizeOf(z_fn.return_type.?));
}
test "pardes.h declares every export the way it is defined" {
const c = @import("pardes.h");
try expectSameAbi(@TypeOf(c.pardes_init), @TypeOf(pardes_init));
try expectSameAbi(@TypeOf(c.pardes_deinit), @TypeOf(pardes_deinit));
try expectSameAbi(@TypeOf(c.pardes_tick), @TypeOf(pardes_tick));
try expectSameAbi(@TypeOf(c.pardes_should_quit), @TypeOf(pardes_should_quit));
try expectSameAbi(@TypeOf(c.pardes_animating), @TypeOf(pardes_animating));
try expectSameAbi(@TypeOf(c.pardes_key), @TypeOf(pardes_key));
try expectSameAbi(@TypeOf(c.pardes_paste), @TypeOf(pardes_paste));
try expectSameAbi(@TypeOf(c.pardes_mouse), @TypeOf(pardes_mouse));
try expectSameAbi(@TypeOf(c.pardes_scroll), @TypeOf(pardes_scroll));
try expectSameAbi(@TypeOf(c.pardes_rotate), @TypeOf(pardes_rotate));
try expectSameAbi(@TypeOf(c.pardes_rotate_end), @TypeOf(pardes_rotate_end));
try expectSameAbi(@TypeOf(c.pardes_command), @TypeOf(pardes_command));
try expectSameAbi(@TypeOf(c.pardes_resize), @TypeOf(pardes_resize));
try expectSameAbi(@TypeOf(c.pardes_frame), @TypeOf(pardes_frame));
try expectSameAbi(@TypeOf(c.pardes_frame_cells), @TypeOf(pardes_frame_cells));
try expectSameAbi(@TypeOf(c.pardes_frame_cols), @TypeOf(pardes_frame_cols));
try expectSameAbi(@TypeOf(c.pardes_frame_rows), @TypeOf(pardes_frame_rows));
try expectSameAbi(@TypeOf(c.pardes_frame_images), @TypeOf(pardes_frame_images));
try expectSameAbi(@TypeOf(c.pardes_frame_image_list), @TypeOf(pardes_frame_image_list));
try expectSameAbi(@TypeOf(c.pardes_cursor_x), @TypeOf(pardes_cursor_x));
try expectSameAbi(@TypeOf(c.pardes_cursor_y), @TypeOf(pardes_cursor_y));
try expectSameAbi(@TypeOf(c.pardes_cursor_bar), @TypeOf(pardes_cursor_bar));
try expectSameAbi(@TypeOf(c.pardes_take_haptic), @TypeOf(pardes_take_haptic));
try expectSameAbi(@TypeOf(c.pardes_font_take), @TypeOf(pardes_font_take));
try expectSameAbi(@TypeOf(c.pardes_active_path), @TypeOf(pardes_active_path));
try expectSameAbi(@TypeOf(c.pardes_active_dirty), @TypeOf(pardes_active_dirty));
try expectSameAbi(@TypeOf(c.pardes_theme_bg), @TypeOf(pardes_theme_bg));
}
test "pardes.h matches the Zig boundary" {
const c = @import("pardes.h");
const expectEqual = std.testing.expectEqual;
try expectEqual(@sizeOf(c.pardes_cell_s), @sizeOf(Cell));
try expectEqual(@offsetOf(c.pardes_cell_s, "text"), @offsetOf(Cell, "text"));
try expectEqual(@offsetOf(c.pardes_cell_s, "fg"), @offsetOf(Cell, "fg"));
try expectEqual(@offsetOf(c.pardes_cell_s, "bg"), @offsetOf(Cell, "bg"));
try expectEqual(@offsetOf(c.pardes_cell_s, "attrs"), @offsetOf(Cell, "attrs"));
try expectEqual(@offsetOf(c.pardes_cell_s, "len"), @offsetOf(Cell, "len"));
try expectEqual(@offsetOf(c.pardes_cell_s, "flags"), @offsetOf(Cell, "flags"));
// The attachment struct is a wide one and every field is read by hand on
// the Swift side, so its layout is checked at both ends rather than at the
// two that happen to be easy.
try expectEqual(@sizeOf(c.pardes_image_s), @sizeOf(Image));
inline for (@typeInfo(Image).@"struct".fields) |field|
try expectEqual(@offsetOf(c.pardes_image_s, field.name), @offsetOf(Image, field.name));
try expectEqual(@sizeOf(c.pardes_runtime_s), @sizeOf(Runtime));
try expectEqual(@as(u32, c.PARDES_COLOR_DEFAULT), color_default);
try expectEqual(@as(u32, c.PARDES_COLOR_INDEXED), color_indexed);
try expectEqual(@as(u8, c.PARDES_CELL_DEFAULT), cell_flag_default);
// Every key the host has a name for must be the codepoint the core reads.
try expectEqual(@as(u21, c.PARDES_KEY_ENTER), pardes.Key.enter);
try expectEqual(@as(u21, c.PARDES_KEY_ESCAPE), pardes.Key.escape);
try expectEqual(@as(u21, c.PARDES_KEY_TAB), pardes.Key.tab);
try expectEqual(@as(u21, c.PARDES_KEY_BACKSPACE), pardes.Key.backspace);
try expectEqual(@as(u21, c.PARDES_KEY_UP), pardes.Key.up);
try expectEqual(@as(u21, c.PARDES_KEY_DOWN), pardes.Key.down);
try expectEqual(@as(u21, c.PARDES_KEY_LEFT), pardes.Key.left);
try expectEqual(@as(u21, c.PARDES_KEY_RIGHT), pardes.Key.right);
try expectEqual(@as(u21, c.PARDES_KEY_HOME), pardes.Key.home);
try expectEqual(@as(u21, c.PARDES_KEY_END), pardes.Key.end);
try expectEqual(@as(u21, c.PARDES_KEY_PAGE_UP), pardes.Key.page_up);
try expectEqual(@as(u21, c.PARDES_KEY_PAGE_DOWN), pardes.Key.page_down);
try expectEqual(@as(u21, c.PARDES_KEY_DELETE), pardes.Key.delete);
// The mouse ordinals the switch in pardes_mouse decodes are the enum's own
// declaration order; a reorder there is a silent remap of acme's buttons.
try expectEqual(c.PARDES_MOUSE_LEFT, @intFromEnum(pardes.Mouse.Button.left));
try expectEqual(c.PARDES_MOUSE_MIDDLE, @intFromEnum(pardes.Mouse.Button.middle));
try expectEqual(c.PARDES_MOUSE_RIGHT, @intFromEnum(pardes.Mouse.Button.right));
try expectEqual(c.PARDES_MOUSE_WHEEL_UP, @intFromEnum(pardes.Mouse.Button.wheel_up));
try expectEqual(c.PARDES_MOUSE_WHEEL_DOWN, @intFromEnum(pardes.Mouse.Button.wheel_down));
try expectEqual(c.PARDES_MOUSE_WHEEL_LEFT, @intFromEnum(pardes.Mouse.Button.wheel_left));
try expectEqual(c.PARDES_MOUSE_WHEEL_RIGHT, @intFromEnum(pardes.Mouse.Button.wheel_right));
try expectEqual(c.PARDES_MOUSE_NONE, @intFromEnum(pardes.Mouse.Button.none));
try expectEqual(c.PARDES_MOUSE_PRESS, @intFromEnum(pardes.Mouse.Kind.press));
try expectEqual(c.PARDES_MOUSE_RELEASE, @intFromEnum(pardes.Mouse.Kind.release));
try expectEqual(c.PARDES_MOUSE_MOTION, @intFromEnum(pardes.Mouse.Kind.motion));
try expectEqual(c.PARDES_MOUSE_DRAG, @intFromEnum(pardes.Mouse.Kind.drag));
// The haptic ordinals pardes_take_haptic returns, against the header's
// names and the core's enum. Three places, checked as one.
try expectEqual(c.PARDES_HAPTIC_NONE, @intFromEnum(pardes.Haptic.none));
try expectEqual(c.PARDES_HAPTIC_EXEC, @intFromEnum(pardes.Haptic.exec));
try expectEqual(c.PARDES_HAPTIC_LOOK, @intFromEnum(pardes.Haptic.look));
// The attribute bits the host decodes, against the encoder that writes them.
try expectEqual(@as(u16, c.PARDES_ATTR_BOLD), encodeAttrs(.{ .bold = true }));
try expectEqual(@as(u16, c.PARDES_ATTR_DIM), encodeAttrs(.{ .dim = true }));
try expectEqual(@as(u16, c.PARDES_ATTR_ITALIC), encodeAttrs(.{ .italic = true }));
try expectEqual(@as(u16, c.PARDES_ATTR_BLINK), encodeAttrs(.{ .blink = true }));
try expectEqual(@as(u16, c.PARDES_ATTR_REVERSE), encodeAttrs(.{ .reverse = true }));
try expectEqual(@as(u16, c.PARDES_ATTR_INVISIBLE), encodeAttrs(.{ .invisible = true }));
try expectEqual(@as(u16, c.PARDES_ATTR_STRIKETHROUGH), encodeAttrs(.{ .strikethrough = true }));
try expectEqual(
@as(u16, c.PARDES_UL_CURLY) << c.PARDES_ATTR_UL_SHIFT,
encodeAttrs(.{ .ul = .curly }),
);
}
test "colors encode to the three tags the host decodes" {
const expectEqual = std.testing.expectEqual;
try expectEqual(@as(u32, 0x01000000), encodeColor(.default));
try expectEqual(@as(u32, 0x02000021), encodeColor(.{ .index = 33 }));
try expectEqual(@as(u32, 0x00112233), encodeColor(.{ .rgb = .{ 0x11, 0x22, 0x33 } }));
}
test "sub-row scroll spends whole notches and keeps the remainder" {
const expectEqual = std.testing.expectEqual;
var lag: f32 = 0;
// Four quarter-row flicks are one row, and not before the fourth.
try expectEqual(@as(i32, 0), takeScrollTicks(&lag, 0.25));
try expectEqual(@as(i32, 0), takeScrollTicks(&lag, 0.25));
try expectEqual(@as(i32, 0), takeScrollTicks(&lag, 0.25));
try expectEqual(@as(i32, 1), takeScrollTicks(&lag, 0.25));
try expectEqual(@as(f32, 0), lag);
// Direction reverses without the accumulated travel leaking across it.
try expectEqual(@as(i32, -2), takeScrollTicks(&lag, -2.5));
try expectEqual(@as(i32, 0), takeScrollTicks(&lag, 0.25));
// Garbage moves nothing and leaves the accumulator usable; a fling far
// past the clamp spends at most one screen and does not spin the caller.
lag = 0;
try expectEqual(@as(i32, 0), takeScrollTicks(&lag, std.math.nan(f32)));
try expectEqual(@as(i32, 0), takeScrollTicks(&lag, std.math.inf(f32)));
try expectEqual(@as(f32, 0), lag);
try expectEqual(@as(i32, 256), takeScrollTicks(&lag, 1e9));
}
test "trackpad rotation spends whole search steps and keeps the remainder" {
const expectEqual = std.testing.expectEqual;
var lag: f32 = 0;
// A twist under one notch moves nothing; crossing it moves exactly one,
// and the overshoot is credited to the next.
try expectEqual(@as(i32, 0), takeRotationNotches(&lag, 7));
try expectEqual(@as(i32, 1), takeRotationNotches(&lag, 5));
try expectEqual(@as(f32, 2), lag);
// Reversing spends the residue first, so a twist back is not amplified by
// travel the other direction already banked.
try expectEqual(@as(i32, -1), takeRotationNotches(&lag, -12));
try expectEqual(@as(f32, 0), lag);
// One deliberate half-turn is several matches, not a hundred.
lag = 0;
try expectEqual(@as(i32, 18), takeRotationNotches(&lag, 180));
// Garbage moves nothing and leaves the dial usable; an absurd delta is
// clamped rather than spinning the emit loop.
lag = 0;
try expectEqual(@as(i32, 0), takeRotationNotches(&lag, std.math.nan(f32)));
try expectEqual(@as(i32, 0), takeRotationNotches(&lag, -std.math.inf(f32)));
try expectEqual(@as(f32, 0), lag);
try expectEqual(@as(i32, 64), takeRotationNotches(&lag, 1e9));
}
test "the dial flings in proportion to the release, and not at all when placed" {
// The whole point of the curve: momentum ramps UP FROM ZERO at the floor
// rather than switching on at it, so no release speed exists where the
// same gesture a hair quicker suddenly jumps several matches further.
try std.testing.expectEqual(@as(f32, 0), rotationFling(0));
try std.testing.expectEqual(@as(f32, 0), rotationFling(40));
try std.testing.expectEqual(@as(f32, 0), rotationFling(rotation_fling_floor));
// Just over the floor is still nothing: what is left has to beat the
// at-rest threshold before it is worth waking the pump for.
try std.testing.expectEqual(@as(f32, 0), rotationFling(rotation_fling_floor + 5));
// ...and past that it is linear in the release speed, both ways.
try std.testing.expectEqual(@as(f32, 130), rotationFling(200));
try std.testing.expectEqual(@as(f32, -130), rotationFling(-200));
// A twitch is capped rather than emptying the list.
try std.testing.expectEqual(rotation_fling_max, rotationFling(100_000));
try std.testing.expectEqual(-rotation_fling_max, rotationFling(-100_000));
// What that buys, in the units a hand feels: total coast is the geometric
// series v*step/(1-decay), so a brisk 200 deg/s release is a few matches
// and the hardest flick the cap allows is bounded well short of a hundred.
const travel = struct {
fn of(speed: f32) f32 {
return @abs(rotationFling(speed)) * rotation_fling_step / (1 - rotation_fling_decay);
}
}.of;
try std.testing.expect(travel(200) / rotation_notch_degrees < 5);
try std.testing.expect(travel(200) / rotation_notch_degrees >= 3);
// ...and the hardest flick a trackpad can report is bounded at about a
// dozen matches. This is the number to change if the dial ever feels like
// it is getting away from the hand.
try std.testing.expect(travel(100_000) / rotation_notch_degrees < 12);
try std.testing.expect(travel(100_000) / rotation_notch_degrees > 8);
}
|