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
|
//! Predicted echo for a replica's terminal panes, mosh's way
//! (docs/next-daemon.md, "Phase 6: predicted echo notes"). A key typed into
//! a terminal goes to the authority, and its echo comes back as screen state
//! a round trip later: this shows it at once.
//!
//! Presentation only. The overlay is the replica's own (`Pardes.echo`, a
//! `.local` field the rollback copy skips), painted over a terminal's body
//! after it is drawn (`paint`, from body_layer.renderBody, which the tty and
//! the GUI share). The core's emulator stays the authority's, and no digest
//! sees any of this.
//!
//! What is predicted: a printable character at the cursor, backspace, and
//! left and right, in tty mode on the primary screen at the live bottom. Any
//! other input this replica could not apply itself (Enter, Tab, a chord, a
//! paste, a click) stops prediction until the authority has confirmed it and
//! its echo has had `grace` to come back: predictions start again from the
//! screen's own cursor. So a key typed after Tab waits a round trip; it is
//! never drawn where the completion was not.
//!
//! Judged as mosh does, once the authority confirmed the key and `grace`
//! passed: at a delta, a cell the screen shows goes, and one it does not is
//! a misprediction, and every prediction goes. With no delta (nothing
//! changed: no echo), a frame judges it `stale` later. Shown at once at a
//! shell's prompt (pardes's OSC 133 marks say its line editor echoes);
//! elsewhere only once an echo was confirmed there since the last key that
//! was not predicted (`cat`, a shell without marks), and underlined; never
//! after a shown misprediction until an echo is confirmed again. A password
//! prompt or a program that ignores input confirms none, so nothing typed
//! there is ever shown.
const std = @import("std");
const pardes = @import("pardes.zig");
const terminal = pardes.panes.terminal;
const Pardes = pardes.Pardes;
const Pane = pardes.Pane;
const Surface = pardes.Surface;
const Key = pardes.Key;
const ms = std.time.ns_per_ms;
/// After the authority confirmed a key, how long its echo has to come back
/// before a delta that does not show it makes a misprediction (mosh's
/// ECHO_TIMEOUT): the shell's echo, then the authority's next frame.
// ponytail: fixed; a loaded host's later echo makes a drawn character go and
// come back. The echo delay measured per terminal would be the bound.
pub const grace_ns = 50 * ms;
/// With no delta at all, how much longer a frame waits to judge a key.
pub const stale_ns = 250 * ms;
const never = std.math.maxInt(u64);
/// Cells predicted at once: a line typed a round trip ahead.
const max = 64;
/// A cell predicted: `cp` at column `x` of absolute row `row` (the
/// authority's numbering, screen_state's), a space for a cell backspace
/// cleared; `was` what the screen showed there before; `seq` the key's.
pub const Cell = struct { x: u16, row: u64, cp: u21, was: u21, seq: u32, due: u64 = never };
pub const Cursor = struct { x: u16, row: u64, seq: u32, due: u64 = never };
pub const Stats = struct {
/// Keys into a terminal predicted, and not.
predicted: u32 = 0,
unpredicted: u32 = 0,
/// Cells the screen showed when judged; cells and cursors it did not.
confirmed: u32 = 0,
mispredicted: u32 = 0,
cursor_missed: u32 = 0,
};
pub const Echo = struct {
/// Off: nothing predicted (the harness's baseline).
on: bool = true,
/// The harness's clock (ns); the monotonic one when null.
now: ?u64 = null,
/// Its client's view, and the terminal it predicts into.
view: u8 = 0,
pane: u8 = 0,
serial: u32 = 0,
/// Each terminal's last delta: its active area's first row, absolute.
tops: [pardes.MAX_PANES]u64 = @splat(0),
cells: [max]Cell = undefined,
n: u8 = 0,
cursor: ?Cursor = null,
/// The newest of its client's inputs the authority confirmed.
acked: u32 = 0,
/// The newest input not predicted, and when its echo is due: nothing is
/// predicted until then. `wait_key`: it was a key forwarded to this
/// terminal (no other pane's), so the keys typed into it meanwhile wait
/// in `deferred`, to be predicted over the screen that shows its doing.
wait: u32 = 0,
wait_due: u64 = 0,
wait_key: bool = false,
deferred: [max]Deferred = undefined,
nd: u8 = 0,
/// An echo confirmed since the last key not predicted: shown off a
/// prompt too. A shown misprediction since the last confirmed echo:
/// shown nowhere.
trusted: bool = false,
doubt: bool = false,
/// What it draws changed: the client draws a frame.
changed: bool = false,
stats: Stats = .{},
/// Each key's prediction as it is made, when set (the harness's; on
/// the C heap).
log: ?*std.ArrayListUnmanaged(Predicted) = null,
pub const Predicted = struct { seq: u32, cell: ?Cell, cursor: Cursor };
fn time(e: *const Echo) u64 {
return e.now orelse pardes.FrameStats.nowNs();
}
const Deferred = struct { seq: u32, kind: ?Kind, due: u64 = never };
fn drop(e: *Echo) void {
if (e.n > 0 or e.cursor != null) e.changed = true;
e.n = 0;
e.cursor = null;
}
/// Every prediction goes, and the keys that made them may still be on
/// their way: the keys typed next wait for the newest of them to show,
/// as keys typed behind one not predicted do (`deferred`). Predicted
/// at once from the screen's cursor, they would land where those keys'
/// echo is about to (found at 207 ms, where three keys are in flight:
/// one drop, and every key after it misjudged, drawn nowhere).
fn lose(e: *Echo) void {
// The cursor after the newest key: its `due` is that key's, never
// until the authority has it.
const newest = e.cursor;
e.drop();
const cur = newest orelse return;
if (e.waiting() or e.time() >= cur.due) return;
e.wait = cur.seq;
e.wait_key = true;
e.nd = 0;
e.wait_due = cur.due;
}
fn waiting(e: *const Echo) bool {
return e.acked < e.wait or e.time() < e.wait_due;
}
fn waitFor(e: *Echo, seq: u32, key: bool) void {
e.wait = seq;
e.wait_due = never;
e.wait_key = key;
e.nd = 0;
}
/// Its client's input `seq`, after the replica took it: `applied`,
/// it was applied here at once (so it was no key into a terminal).
pub fn typed(e: *Echo, c: *Pardes, view: u8, ev: pardes.Event, seq: u32, applied: bool) void {
e.view = view;
if (applied) return;
switch (ev) {
// ponytail: a motion or focus report a program asked for could
// move its cursor; the judgement catches that.
.mouse => |m| if (m.kind == .motion) return,
.pointer_leave, .focus => return,
else => {},
}
const id = keyboardPane(c, view) orelse {
// Another pane's, or not a key: where the keys after it go is
// not known here until the authority has it. ponytail: so they
// wait for it too, each, until a pause.
e.waitFor(seq, false);
return;
};
if (id != e.pane or c.panes[id].?.serial != e.serial) {
e.drop();
e.nd = 0;
e.pane = @intCast(id);
e.serial = c.panes[id].?.serial;
}
const kind = kindOf(ev);
const key = forwarded(c, ev);
// A key that is not one of those predicted says nothing of the
// program the keys after it reach (Enter: a password prompt's).
if (kind == null) e.trusted = false;
if (!e.on) {
e.stats.unpredicted += 1;
return e.waitFor(seq, key);
}
// Behind keys still deferred: after them, in order.
e.catchUp(c);
if (e.waiting() or e.nd > 0) {
if (e.wait_key and key and e.nd < max) {
e.deferred[e.nd] = .{ .seq = seq, .kind = kind };
e.nd += 1;
return;
}
e.stats.unpredicted += 1;
return e.waitFor(seq, false);
}
if (kind) |k| if (e.predict(c.panes[id].?, k, seq)) {
e.stats.predicted += 1;
e.changed = true;
return;
};
e.stats.unpredicted += 1;
e.waitFor(seq, key);
}
/// The wait over (its key's doing on the screen), the keys deferred
/// behind it that the screen does not show yet are predicted over it,
/// in order; those it shows are not. One the authority has whose echo
/// may be on its way puts it off until its grace has passed.
fn catchUp(e: *Echo, c: *Pardes) void {
if (e.nd == 0 or e.waiting()) return;
const now = e.time();
var i: usize = 0;
while (i < e.nd and e.deferred[i].due <= now) i += 1;
if (i < e.nd and e.deferred[i].due != never) return;
e.stats.unpredicted += @intCast(i);
const pane = c.panes[e.pane] orelse return e.waitFor(e.wait, false);
if (pane.serial != e.serial) return e.waitFor(e.wait, false);
while (i < e.nd) : (i += 1) {
const d = e.deferred[i];
if (d.kind) |k| if (e.predict(pane, k, d.seq)) {
e.stats.predicted += 1;
e.changed = true;
continue;
};
// The next to wait for, the rest behind it.
e.stats.unpredicted += 1;
const rest = e.nd - i - 1;
std.mem.copyForwards(Deferred, e.deferred[0..rest], e.deferred[i + 1 .. e.nd]);
e.wait = d.seq;
e.wait_due = never;
e.wait_key = true;
e.nd = @intCast(rest);
return;
}
e.nd = 0;
}
/// Whether a key `kind` into terminal `pane` was predicted.
fn predict(e: *Echo, pane: *Pane, kind: Kind, seq: u32) bool {
const state = pane.terminal orelse return false;
const vt = &state.vt;
if (vt.screens.active_key != .primary or !terminal.atBottom(pane) or !vt.modes.get(.cursor_visible)) return false;
const top = e.tops[e.pane];
const screen = vt.screens.active;
const cur: Cursor = e.cursor orelse .{ .x = @intCast(screen.cursor.x), .row = top + screen.cursor.y, .seq = 0 };
if (cur.row < top or cur.row - top >= vt.rows or e.n == max) return false;
var next: Cursor = .{ .x = cur.x, .row = cur.row, .seq = seq };
var cell: ?Cell = null;
switch (kind) {
.char => |cp| {
// The last column wraps as a program pleases; a cell that
// holds another character is a line edited in its middle,
// or a suggestion (fish's) being left: the shell redraws
// what is right of it. ponytail: mosh's shift of the rest
// would cover bash's middle, and mispredict fish's.
if (cur.x + 1 >= vt.cols) return false;
const under = e.cpAt(state, cur.x, cur.row);
if (!blank(under) and under != cp) return false;
cell = .{ .x = cur.x, .row = cur.row, .cp = cp, .was = under, .seq = seq };
next.x += 1;
},
// At the end of a line only: in its middle a line editor moves
// the rest left.
.backspace => {
if (cur.x == 0 or !e.isInput(state, cur.x - 1, cur.row) or !blank(e.cpAt(state, cur.x, cur.row))) return false;
cell = .{ .x = cur.x - 1, .row = cur.row, .cp = ' ', .was = e.cpAt(state, cur.x - 1, cur.row), .seq = seq };
next.x -= 1;
},
.left => {
if (cur.x == 0 or !e.isInput(state, cur.x - 1, cur.row)) return false;
next.x -= 1;
},
// Over typed text only: past its end, fish takes the right
// arrow for its suggestion (another colour).
.right => {
if (cur.x + 1 >= vt.cols or !e.isText(state, cur.x, cur.row)) return false;
next.x += 1;
},
}
if (cell) |want| e.put(want);
e.cursor = next;
if (e.log) |l| l.append(std.heap.c_allocator, .{ .seq = seq, .cell = cell, .cursor = next }) catch {};
return true;
}
fn put(e: *Echo, want: Cell) void {
for (e.cells[0..e.n]) |*have| if (have.x == want.x and have.row == want.row) {
const was = have.was;
have.* = want;
have.was = was;
return;
};
e.cells[e.n] = want;
e.n += 1;
}
fn mine(e: *const Echo, x: u16, row: u64) ?*const Cell {
for (e.cells[0..e.n]) |*have| if (have.x == x and have.row == row) return have;
return null;
}
/// What the screen shows at a cell as predicted so far.
fn cpAt(e: *const Echo, state: *terminal.State, x: u16, row: u64) u21 {
if (e.mine(x, row)) |have| return have.cp;
return e.screenCp(state, x, row);
}
/// What the screen itself shows there; off its active area, a
/// codepoint no key types.
fn screenCp(e: *const Echo, state: *terminal.State, x: u16, row: u64) u21 {
const ci = e.screenCell(state, x, row) orelse return 0x10ffff;
return ci.cell.codepoint();
}
fn screenCell(e: *const Echo, state: *terminal.State, x: u16, row: u64) ?terminal.PageCell {
const top = e.tops[e.pane];
if (row < top or row - top >= state.vt.rows) return null;
return state.vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = @intCast(row - top) } });
}
/// A prompt's input there, or a character predicted.
fn isInput(e: *const Echo, state: *terminal.State, x: u16, row: u64) bool {
if (e.mine(x, row)) |have| return !blank(have.cp);
const ci = e.screenCell(state, x, row) orelse return false;
return ci.cell.semantic_content == .input;
}
/// Typed text there: a character predicted, or a prompt's input in the
/// colour of the cell before it.
fn isText(e: *const Echo, state: *terminal.State, x: u16, row: u64) bool {
if (e.mine(x, row)) |have| return !blank(have.cp);
const ci = e.screenCell(state, x, row) orelse return false;
if (ci.cell.semantic_content != .input or blank(ci.cell.codepoint())) return false;
if (x == 0) return true;
const before = e.screenCell(state, x - 1, row) orelse return false;
return before.cell.style_id == ci.cell.style_id;
}
/// The authority confirmed its client's input `seq`.
pub fn confirmed(e: *Echo, c: *Pardes, seq: u32) void {
e.acked = seq;
const due = e.time() + grace_ns;
for (e.deferred[0..e.nd]) |*d| if (d.seq <= seq and d.due == never) {
d.due = due;
};
for (e.cells[0..e.n]) |*cell| if (cell.seq <= seq and cell.due == never) {
cell.due = due;
};
if (e.cursor) |*cur| if (cur.seq <= seq and cur.due == never) {
cur.due = due;
};
if (e.wait <= seq and e.wait_due == never) {
// The authority stepped a key this did not predict, after every
// one it did: its deltas from here show that key's doing, which
// no prediction knew of. They go, judged neither way.
e.wait_due = due;
e.drop();
}
e.catchUp(c);
}
/// Terminal `id`'s delta was applied, its active area's first row now
/// `top`.
pub fn delta(e: *Echo, c: *Pardes, id: u8, top: u64) void {
if (id == e.pane and top != e.tops[id] and (e.n > 0 or e.cursor != null)) {
// Scrolled: the rows predicted are others now.
e.tops[id] = top;
return e.lose();
}
e.tops[id] = top;
if (id == e.pane) e.judge(c, 0);
e.catchUp(c);
}
/// Once a frame: what is stale judged. Whether to draw.
pub fn frame(e: *Echo, c: *Pardes) bool {
if (e.n > 0 or e.cursor != null) e.judge(c, stale_ns);
e.catchUp(c);
defer e.changed = false;
return e.changed;
}
fn judge(e: *Echo, c: *Pardes, slack: u64) void {
if (e.n == 0 and e.cursor == null) return;
const now = e.time();
const pane = c.panes[e.pane] orelse return e.drop();
if (pane.serial != e.serial) return e.drop();
const state = pane.terminal orelse return e.drop();
if (state.vt.screens.active_key != .primary) return e.drop();
const shown = e.visible(c);
var i: usize = 0;
while (i < e.n) {
const cell = e.cells[i];
if (now < cell.due) {
i += 1;
continue;
}
if (!blank(cell.cp) and e.screenCp(state, cell.x, cell.row) != cell.cp) {
if (now < cell.due + slack) {
i += 1;
continue;
}
e.stats.mispredicted += 1;
if (std.c.getenv("PARDES_REPLICA_TRACE") != null) {
const cur = state.vt.screens.active.cursor;
std.debug.print("echo: key {d}'s {u} at {d},{d} not shown ({u} there) {d} ms past due; top {d}, the screen's cursor {d},{d}, acked {d}\n", .{ cell.seq, cell.cp, cell.x, cell.row, e.screenCp(state, cell.x, cell.row), (now - cell.due) / ms, e.tops[e.pane], cur.x, cur.y, e.acked });
}
if (shown) e.doubt = true;
e.trusted = false;
return e.lose();
}
// Shown, or a space (mosh: too easy to show by chance to vouch).
// A key before the last one not predicted vouches for nothing
// after it (a line's characters for the password prompt its
// Enter brought up).
if (!blank(cell.cp)) {
e.stats.confirmed += 1;
if (cell.was != cell.cp and cell.seq > e.wait) {
e.trusted = true;
e.doubt = false;
}
}
e.cells[i] = e.cells[e.n - 1];
e.n -= 1;
e.changed = true;
}
const cur = e.cursor orelse return;
if (now < cur.due) return;
const screen = state.vt.screens.active;
if (screen.cursor.x == cur.x and e.tops[e.pane] + screen.cursor.y == cur.row) {
e.cursor = null;
e.changed = true;
} else if (now >= cur.due + slack) {
e.stats.cursor_missed += 1;
e.lose();
}
}
/// Whether its predictions are drawn now.
pub fn visible(e: *const Echo, c: *const Pardes) bool {
if (e.doubt) return false;
if (e.trusted) return true;
const pane = c.panes[e.pane] orelse return false;
return atPrompt(pane);
}
/// Over terminal pane `id`'s body, as renderBody drew it: the
/// characters predicted and the cursor after them.
pub fn paint(e: *const Echo, p: *const Pardes, s: *Surface, pane: *const Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16, active: bool) void {
if (e.n == 0 and e.cursor == null) return;
if (id != e.pane or pane.serial != e.serial or p.view != e.view or pane.body.mode != .tty) return;
if (!e.visible(p)) return;
const state = pane.terminal orelse return;
const sb = state.vt.screens.active.pages.scrollbar();
const top = e.tops[id];
// Off a prompt, the trust is inferred: underlined, as mosh does.
const flag = !atPrompt(pane);
const at = struct {
fn f(sb_: @TypeOf(sb), pan: u16, h: u16, top_: u64, row: u64) ?u16 {
if (row < top_ or row - top_ >= sb_.len) return null;
const screen_row = sb_.total - sb_.len + (row - top_);
if (screen_row < sb_.offset + pan) return null;
const y = screen_row - sb_.offset - pan;
return if (y < h) @intCast(y) else null;
}
}.f;
for (e.cells[0..e.n]) |cell| {
const y = at(sb, pane.pan, body_h, top, cell.row) orelse continue;
if (cell.x >= tw) continue;
const dst = s.at(tx + cell.x, body_y + y);
// Typed text continues the text before it (mosh's heuristic).
var style = dst.style;
if (cell.x > 0) {
const before = s.at(tx + cell.x - 1, body_y + y);
if (!before.default and !blank(before.text[0])) style = before.style;
}
if (flag and !blank(cell.cp)) style.ul = .single;
dst.default = false;
dst.text[0] = @intCast(cell.cp);
dst.len = 1;
dst.style = style;
}
if (!active or pane.focus != .body) return;
const cur = e.cursor orelse return;
const y = at(sb, pane.pan, body_h, top, cur.row) orelse return;
if (cur.x < tw) s.cursor = .{ .x = tx + cur.x, .y = body_y + y };
}
};
const Kind = union(enum) { char: u21, backspace, left, right };
fn kindOf(ev: pardes.Event) ?Kind {
const k = switch (ev) {
.key => |k| k,
else => return null,
};
if (k.ctrl or k.alt) return null;
switch (k.cp) {
Key.backspace => return .backspace,
Key.left => return .left,
Key.right => return .right,
else => {},
}
// As forwardKey sends it. ponytail: ASCII only; a width table would
// let the rest in.
const cp: u21 = if (k.text.len == 1)
k.text[0]
else if (k.text.len == 0 and k.cp >= 'a' and k.cp <= 'z' and k.shift)
k.cp - 'a' + 'A'
else if (k.text.len == 0)
k.cp
else
return null;
return if (cp >= 0x20 and cp < 0x7f) .{ .char = cp } else null;
}
/// Whether key `ev` goes to the terminal's program as it is (forwardKey's)
/// and not to pardes: Esc backs out of the pane, the tty chord leaves tty
/// mode, Ctrl-V pastes the register.
fn forwarded(c: *const Pardes, ev: pardes.Event) bool {
const k = switch (ev) {
.key => |k| k,
else => return false,
};
if (k.cp == Key.escape) return false;
return !(k.ctrl and (k.cp == c.tty_toggle or k.cp == 'v' or k.cp == 'V'));
}
fn blank(cp: u21) bool {
return cp == 0 or cp == ' ';
}
/// At a shell's prompt, reading its input: pardes's marks (a B and no C
/// since) and the cursor's own, on the primary screen. A shell without
/// pardes's marks is trusted only once its echo is confirmed.
fn atPrompt(pane: *const Pane) bool {
const state = pane.terminal orelse return false;
return state.vt.screens.active_key == .primary and state.stream.handler.phase == .input and terminal.promptInputReady(pane);
}
/// The terminal view `view`'s keys go to, in tty mode: none when they go
/// elsewhere (a prompt, a header, window mode, another pane).
fn keyboardPane(c: *const Pardes, view: u8) ?usize {
const live = c.view == view;
const part = if (live) null else &(c.parked[view] orelse return null).view;
const id = if (part) |v| v.active else c.active;
if (if (part) |v| v.window_pick != null or v.header_focus else c.window_pick != null or c.header_focus) return null;
const pane = c.panes[id] orelse return null;
if (!pane.isTerminal() or pane.terminal == null or pane.prompt != .none) return null;
const mode = if (live) pane.body.mode else pane.pv[view].body.mode;
const focus = if (live) pane.focus else pane.pv[view].focus;
return if (mode == .tty and focus == .body) id else null;
}
// ---- tests: one authority and one replica, its shell played by hand ----
const testing = std.testing;
const replica = @import("replica.zig");
const Rig = struct {
a: *replica.Authority,
r: *replica.Replica,
screens: replica.Screens,
peer: u16,
shell: u8,
/// What the authority wrote its shell's pty.
written: std.ArrayListUnmanaged(u8) = .empty,
now: u64 = 1_000 * ms,
fn ptyWrite(ctx: ?*anyopaque, _: u8, bytes: []const u8) void {
const g: *Rig = @ptrCast(@alignCast(ctx.?));
g.written.appendSlice(testing.allocator, bytes) catch {};
}
fn watched(_: ?*anyopaque) bool {
return false;
}
const vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite };
fn init(g: *Rig) !void {
const gpa = testing.allocator;
g.written = .empty;
g.now = 1_000 * ms;
g.a = try replica.Authority.init(gpa, .{ .cols = 60, .rows = 16, .boot = .tty_shell }, .{ .ctx = g, .vtable = &vtable }, true);
g.screens = .init(gpa);
g.peer = try g.screens.addPeer();
g.r = try replica.Replica.init(gpa, 1, try g.a.unit(0, 0), true);
g.shell = for (g.a.core.panes, 0..) |slot, id| {
if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
} else return error.NoShell;
g.r.echo.now = g.now;
}
fn deinit(g: *Rig) void {
g.r.deinit();
g.screens.deinit(g.a.core);
g.a.deinit();
g.written.deinit(testing.allocator);
}
fn later(g: *Rig, dt: u64) void {
g.now += dt;
g.r.echo.now = g.now;
}
/// The shell prints `bytes`; the replica gets the unit and the delta.
fn prints(g: *Rig, bytes: []const u8) !void {
g.a.output(.{ .output = .{ .pane = g.shell, .bytes = bytes } });
try g.sync();
}
fn sync(g: *Rig) !void {
const gpa = testing.allocator;
if (try g.a.pending()) |u| g.r.confirm(u);
g.r.settle();
var msgs: std.ArrayListUnmanaged([]u8) = .empty;
defer {
for (msgs.items) |m| gpa.free(m);
msgs.deinit(gpa);
}
try g.screens.flush(g.a.core, g.peer, &msgs);
for (msgs.items) |m| if (g.r.screen(m)) |reply| {
_ = try g.screens.take(g.a.core, g.peer, reply);
};
}
/// The replica's client types `k`; the message for the authority.
fn key(g: *Rig, k: Key) ![]u8 {
return testing.allocator.dupe(u8, try g.r.input(.{ .key = k }));
}
/// The authority takes it, and the replica its unit.
fn take(g: *Rig, msg: []u8) !void {
defer testing.allocator.free(msg);
if (try g.a.pending()) |u| g.r.confirm(u);
g.r.confirm(try g.a.take(msg));
g.r.settle();
}
/// What the replica's screen shows at the shell's cursor row, drawn,
/// and whether the cell at `x` is underlined.
fn drawn(g: *Rig, arena: *std.heap.ArenaAllocator, x: u16) !struct { cp: u8, ul: bool, cursor: ?u16 } {
_ = arena.reset(.retain_capacity);
const c = g.r.core();
c.needs_frame = true;
const s = try c.render(arena.allocator());
const pane = c.panes[g.shell].?;
const body = s.region(.body, g.shell).?.rect;
const y = body.y + terminal.gridCursor(pane).y;
const cell = s.at(body.x + x, y);
return .{ .cp = cell.text[0], .ul = cell.style.ul != .off, .cursor = if (s.cursor) |cur| if (cur.y == y) cur.x - body.x else null else null };
}
};
const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
test "keys typed at a shell's prompt are drawn at once, and the authority's echo takes their place" {
var g: Rig = undefined;
try g.init();
defer g.deinit();
try g.prints(prompt);
var arena: std.heap.ArenaAllocator = .init(testing.allocator);
defer arena.deinit();
const before = try g.drawn(&arena, 2);
try testing.expectEqual(@as(?u16, 2), before.cursor);
// Typed: shown at once, the cursor past it, and nothing underlined at
// a prompt.
const l = try g.key(.{ .cp = 'l', .text = "l" });
const s = try g.key(.{ .cp = 's', .text = "s" });
try testing.expectEqual(@as(u32, 2), g.r.echo.stats.predicted);
var shown = try g.drawn(&arena, 2);
try testing.expectEqual(@as(u8, 'l'), shown.cp);
try testing.expect(!shown.ul);
try testing.expectEqual(@as(?u16, 4), shown.cursor);
try testing.expectEqual(@as(u8, 's'), (try g.drawn(&arena, 3)).cp);
// The authority's core draws no overlay of its own.
try testing.expect(g.a.core.echo == null);
// The authority takes them, its shell echoes, the delta lands after the
// grace: confirmed, and the screen's own cells and cursor shown.
try g.take(l);
try g.take(s);
try testing.expectEqualStrings("ls", g.written.items);
g.later(grace_ns);
try g.prints("ls");
try testing.expectEqual(@as(u8, 0), g.r.echo.n);
try testing.expect(g.r.echo.cursor == null);
try testing.expectEqual(@as(u32, 2), g.r.echo.stats.confirmed);
shown = try g.drawn(&arena, 3);
try testing.expectEqual(@as(u8, 's'), shown.cp);
try testing.expectEqual(@as(?u16, 4), shown.cursor);
// Backspace at the end of the line, shown at once.
const bs = try g.key(.{ .cp = Key.backspace });
shown = try g.drawn(&arena, 3);
try testing.expectEqual(@as(u8, ' '), shown.cp);
try testing.expectEqual(@as(?u16, 3), shown.cursor);
try g.take(bs);
g.later(grace_ns);
try g.prints("\x08\x1b[K");
try testing.expectEqual(@as(u32, 0), g.r.echo.stats.mispredicted + g.r.echo.stats.cursor_missed);
try testing.expect(g.r.quiet());
try testing.expectEqual(replica.digestOf(g.a), g.r.digest());
}
test "a password prompt shows nothing typed, and a full-screen program is not predicted" {
var g: Rig = undefined;
try g.init();
defer g.deinit();
try g.prints(prompt ++ "sudo ls\r\n\x1b]133;C;aid=pardes\x07[sudo] password: ");
var arena: std.heap.ArenaAllocator = .init(testing.allocator);
defer arena.deinit();
const x = terminal.gridCursor(g.r.core().panes[g.shell].?).x;
const k = try g.key(.{ .cp = 'h', .text = "h" });
// Predicted, and not drawn: nothing has confirmed an echo here.
try testing.expectEqual(@as(u32, 1), g.r.echo.stats.predicted);
try testing.expectEqual(@as(u8, ' '), (try g.drawn(&arena, x)).cp);
try g.take(k);
// No echo, so no delta: a frame lets it go once it is stale.
g.later(grace_ns + stale_ns);
_ = g.r.echoFrame();
try testing.expectEqual(@as(u8, 0), g.r.echo.n);
try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted);
// The next key still shows nothing.
const k2 = try g.key(.{ .cp = 'i', .text = "i" });
try testing.expectEqual(@as(u8, ' '), (try g.drawn(&arena, x)).cp);
try g.take(k2);
// vim: the alternate screen, never predicted.
try g.prints("\r\n\x1b]133;D;1;aid=pardes\x07" ++ prompt ++ "vim\r\n\x1b]133;C;aid=pardes\x07\x1b[?1049h\x1b[H~");
g.later(grace_ns + stale_ns);
_ = g.r.echoFrame();
const before = g.r.echo.stats.predicted;
try g.take(try g.key(.{ .cp = 'i', .text = "i" }));
try testing.expectEqual(before, g.r.echo.stats.predicted);
}
test "keys still on their way when their predictions go: the next waits for their echo, never predicted where it is about to land" {
var g: Rig = undefined;
try g.init();
defer g.deinit();
try g.prints(prompt);
// Three keys typed a round trip ahead; the authority has the first,
// and its shell echoes something else: every prediction goes.
const a = try g.key(.{ .cp = 'a', .text = "a" });
const b = try g.key(.{ .cp = 'b', .text = "b" });
const c = try g.key(.{ .cp = 'c', .text = "c" });
try testing.expectEqual(@as(u32, 3), g.r.echo.stats.predicted);
try g.take(a);
g.later(grace_ns);
try g.prints("A");
try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted);
try testing.expectEqual(@as(u8, 0), g.r.echo.n);
// The next key is not predicted at the screen's cursor, where b's
// echo lands: it waits for b and c.
const d = try g.key(.{ .cp = 'd', .text = "d" });
try testing.expectEqual(@as(u32, 3), g.r.echo.stats.predicted);
try testing.expectEqual(@as(u8, 0), g.r.echo.n);
try g.take(b);
try g.take(c);
g.later(grace_ns);
try g.prints("bc");
// Their echo shown: d is predicted after it.
try testing.expectEqual(@as(u32, 4), g.r.echo.stats.predicted);
try testing.expectEqual(@as(u8, 1), g.r.echo.n);
try testing.expectEqual(@as(u16, 5), g.r.echo.cells[0].x);
try g.take(d);
g.later(grace_ns);
try g.prints("d");
try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted);
try testing.expect(!g.r.echo.doubt);
try testing.expectEqual(@as(u8, 0), g.r.echo.n);
}
test "a misprediction takes every prediction back and shows none until an echo is confirmed; after Tab nothing is predicted until its echo" {
var g: Rig = undefined;
try g.init();
defer g.deinit();
try g.prints(prompt);
var arena: std.heap.ArenaAllocator = .init(testing.allocator);
defer arena.deinit();
// A line editor that echoes something else (vi's command mode): shown,
// then taken back.
const a = try g.key(.{ .cp = 'a', .text = "a" });
try testing.expectEqual(@as(u8, 'a'), (try g.drawn(&arena, 2)).cp);
try g.take(a);
g.later(grace_ns);
try g.prints("A");
try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted);
try testing.expect(g.r.echo.doubt);
try testing.expectEqual(@as(u8, 'A'), (try g.drawn(&arena, 2)).cp);
// Doubted: predicted, not drawn, until one is confirmed.
const b = try g.key(.{ .cp = 'b', .text = "b" });
try testing.expectEqual(@as(u8, ' '), (try g.drawn(&arena, 3)).cp);
try g.take(b);
g.later(grace_ns);
try g.prints("b");
try testing.expect(!g.r.echo.doubt);
const c = try g.key(.{ .cp = 'c', .text = "c" });
try testing.expectEqual(@as(u8, 'c'), (try g.drawn(&arena, 4)).cp);
// Tab: not predicted, and neither is what follows until the authority
// has it and its echo has had its grace.
const tab = try g.key(.{ .cp = Key.tab });
const d = try g.key(.{ .cp = 'd', .text = "d" });
try testing.expectEqual(@as(u32, 1), g.r.echo.stats.unpredicted);
try g.take(c);
try testing.expectEqual(@as(u8, 'c'), (try g.drawn(&arena, 4)).cp);
// The authority has Tab (and the key after it): what was predicted
// before it goes, the screen's own shown.
try g.take(tab);
try g.take(d);
try testing.expectEqual(@as(u8, 0), g.r.echo.n);
g.later(grace_ns);
try g.prints("c" ++ "ompleted d");
// `d`, typed behind Tab, the screen showed by then: not predicted.
try testing.expectEqual(@as(u32, 2), g.r.echo.stats.unpredicted);
const e = try g.key(.{ .cp = 'e', .text = "e" });
try testing.expectEqual(@as(u8, 'e'), (try g.drawn(&arena, 15)).cp);
try g.take(e);
g.later(grace_ns);
try g.prints("e");
// A key typed behind Tab that the authority does not have yet is
// predicted once Tab's doing is on the screen, where it now goes.
const tab2 = try g.key(.{ .cp = Key.tab });
const f = try g.key(.{ .cp = 'f', .text = "f" });
try g.take(tab2);
try g.prints("ff");
try testing.expectEqual(@as(u8, 0), g.r.echo.n);
g.later(grace_ns);
_ = g.r.echoFrame();
try testing.expectEqual(@as(u8, 1), g.r.echo.n);
try testing.expectEqual(@as(u8, 'f'), (try g.drawn(&arena, 18)).cp);
try g.take(f);
g.later(grace_ns);
try g.prints("f");
try testing.expectEqual(@as(u8, 0), g.r.echo.n);
try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted);
try testing.expectEqual(@as(u32, 0), g.r.echo.stats.cursor_missed);
try testing.expect(g.r.quiet());
try testing.expectEqual(replica.digestOf(g.a), g.r.digest());
}
|