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
|
//! What goes out: the effects the core asks its host for (a child, a pty's
//! bytes, a save, a dump, a language server's question), and `perform`,
//! which hands one to the host, or to the in-process fallback a host
//! without that method has.
const std = @import("std");
const pardes = @import("pardes.zig");
const tape = @import("tape.zig");
const panes = @import("panes.zig");
const ctlfs = @import("ninep/tree.zig");
const filesystem = @import("fs.zig");
const host_io = @import("host_io.zig");
const exec = @import("exec.zig");
const lsp = @import("lsp/lsp.zig");
const Stream = @import("Stream.zig");
const edit = @import("edit.zig");
const tagline = @import("tagline.zig");
const Pardes = pardes.Pardes;
const Pane = panes.Pane;
const Host = pardes.Host;
/// `command` is Kill's: SIGTERM to the terminal's foreground job, and never
/// to the shell itself when the shell is in the foreground.
pub const PtySignal = enum(u8) { int, term, hup, quit, kill };
/// IO the core wants done. Payloads are inline (fixed buffers): effects are
/// queued values with no lifetime ties back into the core.
pub const WatchMode = enum { reconcile, baseline_disk };
pub const effect_path_cap = 256;
/// The bytes one `write` carries, a pty write in the hosts: as many as a
/// path's, which already size the union, so they cost the ring no room
/// (268 bytes an effect at 64 and at 256).
pub const effect_write_cap = 256;
pub const Effect = union(enum) {
/// A child for the pane in slot `pane` -- the one whose serial is
/// `serial`: a pane closed and its slot taken before the effect is
/// performed is not the one it was for (perform).
spawn: struct { pane: u8, serial: u32, cwd: Buf(effect_path_cap) },
write: struct { pane: u8, bytes: Buf(effect_write_cap) },
resize_pty: struct { pane: u8, cols: u16, rows: u16 },
/// For the pane whose serial is `serial`, as `spawn` is (perform).
signal_pty: struct { pane: u8, serial: u32, sig: PtySignal },
/// The terminal pane in this slot is gone: the shell hangs up its pty
/// and ends the shell, rather than leave it running with nobody to read.
close_pty: struct { pane: u8 },
open_link: Buf(256),
/// write this pane's file content to its path; the shell reads both off
/// the core (content is unbounded, effects are fixed-size values)
save_file: struct { pane: u8 },
save_text: struct { pane: u8, serial: u32, path: Buf(effect_path_cap), promote: bool = false },
write_dump,
set_clipboard,
read_clipboard,
/// `arg` up to 128 bytes, or for `explain` the query it explains,
/// `<kind> <arg>`.
lsp: struct { id: u32, kind: lsp.Kind, pane: u8, offset: u32, arg: Buf(160) },
/// Snapshot the matching request with pipeRequest(id), then run it away
/// from the UI/event loop and answer with pipe_resp.
pipe: struct { id: u32 },
/// Start the disk search of this generation (Stream.start) on a worker
/// posting into the shell's inbox.
search: struct { gen: u32 },
/// Carry `handover.bytes`, the dump of handover `seq`, to another
/// window, answering with `handed` (Handover.zig).
hand_over: struct { seq: u32 },
/// Write what an Edit's `w` took (`Pipe.writes`), in order.
edit_write,
watch: struct { pane: u8, on: bool, mode: WatchMode = .reconcile },
theme_file: struct { generation: u32, on: bool },
/// Write the build-time theme ring below the per-user config directory.
/// The pane receives the completion/error message from the native host.
dump_themes: struct { pane: u8 },
detach: struct { pane: u8 },
/// An addon loaded, let go, or let go and loaded again (Addon.zig):
/// `arg` its path, or for unload its kind's name. Answered by an
/// `addon` event.
addon: struct { op: @import("Addon.zig").Op, pane: u8, arg: Buf(effect_path_cap) },
/// A kind's job for the host's workers (host_io.Job), answered by a
/// `job` event.
job: struct { pane: u8, serial: u32, token: u32 },
quit,
pub fn Buf(comptime n: usize) type {
return struct {
pub const replica = .{ .len = .{.{ "data", "len" }} };
data: [n]u8 = undefined,
len: u16 = 0,
pub const cap = n;
pub fn slice(b: *const @This()) []const u8 {
return b.data[0..b.len];
}
pub fn from(text: []const u8) @This() {
var b: @This() = .{};
std.debug.assert(text.len <= n);
@memcpy(b.data[0..text.len], text);
b.len = @intCast(text.len);
return b;
}
};
}
};
comptime {
// A write is never the union's largest variant, so its bytes cost the
// ring of effects no room (effect_write_cap).
std.debug.assert(@sizeOf(@FieldType(Effect, "write")) <= @sizeOf(@FieldType(Effect, "spawn")));
}
pub fn perform(p: *Pardes, e: Effect) void {
const taped = tape.enter(p, .{ .perform = e });
defer tape.leave(p, taped);
// A Save performed on one twin is every twin's (File.syncTwins).
defer panes.File.syncTwins(p);
const v = p.host.vtable;
switch (e) {
// The host reads the pane (its command, its shell) as it forks,
// so the slot must still hold the pane the spawn was for.
.spawn => |s| if (if (p.panes[s.pane]) |pane| pane.serial != s.serial else true) {} else if (v.spawn) |f| f(p.host.ctx, s.pane, if (s.cwd.len == 0) (p.spawn_dirs[s.pane] orelse "") else s.cwd.slice()) else {
p.fallback.spawned[s.pane] = true;
},
// A pane with no child is silent: nothing invents output on its
// screen, and the bytes are dropped rather than transcribed.
.write => |w| if (v.pty_write) |f| f(p.host.ctx, w.pane, w.bytes.slice()),
.resize_pty => |r| if (v.pty_resize) |f| f(p.host.ctx, r.pane, r.cols, r.rows),
// A signal for a pane that closed, its slot retaken in the same
// step, would reach another pane's child.
.signal_pty => |s| if (if (p.panes[s.pane]) |pane| pane.serial != s.serial else true) {} else if (v.pty_signal) |f| f(p.host.ctx, s.pane, s.sig),
.close_pty => |c| if (v.close_pty) |f| f(p.host.ctx, c.pane),
.open_link => |u| if (v.open_link) |f|
f(p.host.ctx, u.slice())
else
p.fallback.setLink(u.slice()),
.save_file => |sf| {
const pane = p.panes[sf.pane] orelse return;
const f = if (pane.file) |*file| file else return;
const was = f.saved_revision;
f.saved_revision = f.revision;
// A save the host could not do (saveFailed) is its err
// record alone, not a `save`, and changes nothing: a clean
// file stays clean.
const saved_pane = writeChecked(p, sf.pane, pane.serial, f.path, f.content, was) orelse return;
const saved = if (saved_pane.file) |*file| file else return;
// Edited while it was written: what is on disk is not this.
if (saved.saved_revision != saved.revision) return;
saved.disk_gone = false;
ctlfs.events.noteLog(p, .save, saved_pane);
// On disk now, a new file too: Recent has it, open.
if (saved.output == null and Pardes.recentKeeps(saved.path)) p.recent.opened(p.recentGpa(), saved.path);
if (!saved.watch_after_save) return;
saved.watch_after_save = false;
if (filesystem.localPath(saved.path) != null)
p.emit(.{ .watch = .{ .pane = sf.pane, .on = true } });
},
.save_text => |st| {
const pane = p.panes[st.pane] orelse return;
if (pane.serial != st.serial) return; // a recycled slot: not ours
if (pane.file) |*f| {
// Failed, it changes nothing: not the name, not dirty.
const after = writeChecked(p, st.pane, st.serial, st.path.slice(), f.content, f.saved_revision) orelse return;
if (after.file == null) return;
if (st.promote) promoteSaved(p, st.pane, st.path.slice()) else ctlfs.events.noteLogAs(p, .save, after, st.path.slice());
return;
}
if (!pane.isTerminal()) return;
const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch return;
defer p.gpa.free(text);
if (writeChecked(p, st.pane, st.serial, st.path.slice(), text, 0)) |still|
ctlfs.events.noteLogAs(p, .save, still, st.path.slice());
},
.write_dump => {
const out = p.dump_out orelse return;
if (v.write_dump) |f| {
f(p.host.ctx, out);
} else {
_ = p.fallback.writeFile(host_io.Fallback.dump_path, out);
p.setLastDump(host_io.Fallback.dump_path);
}
},
.set_clipboard => {
const text = p.registers.text(p.gpa, '+') orelse "";
if (v.set_clipboard) |f| f(p.host.ctx, text) else p.fallback.setClipboard(text);
},
// No desktop to ask: answer from the in-process clipboard at once,
// which is the same shape as a host answering later.
.read_clipboard => if (v.read_clipboard) |f|
f(p.host.ctx)
else
p.update(.{ .paste = p.fallback.clipboard.items }),
.lsp => |q| if (v.lsp) |f|
f(p.host.ctx, .{ .id = q.id, .kind = q.kind, .pane = q.pane, .offset = q.offset, .arg = q.arg.slice() })
else
p.update(.{ .lsp_resp = .{ .id = q.id, .rows = "" } }),
.pipe => |q| if (v.pipe) |f|
f(p.host.ctx, q.id)
else
p.update(.{ .pipe_resp = .{ .id = q.id, .success = false, .outputs = &.{} } }),
// No workers here (a test, a board): it runs on the loop.
.search => |q| if (v.search) |f| f(p.host.ctx, q.gen) else Stream.runHere(p, q.gen),
// No windows here (a test, the tty): it stays.
.hand_over => |h| if (v.hand_over) |f| {
if (p.handover.bytes) |bytes| f(p.host.ctx, h.seq, bytes);
} else p.update(.{ .handed = .{ .seq = h.seq, .failure = "no other windows here" } }),
.edit_write => {
// Each write takes the bytes `w` took when it ran: the text
// as it was before the Edit's changes.
var writes = p.pipe.writes;
p.pipe.writes = .empty;
defer {
for (writes.items) |*w| w.deinit(p.gpa);
writes.deinit(p.gpa);
}
for (writes.items) |w| {
const was = if (p.panes[w.pane]) |pane| (if (pane.file) |f| f.saved_revision else 0) else 0;
// Failed, it changes nothing, as save_text's does not.
const pane = writeChecked(p, w.pane, w.serial, w.path, w.bytes, was) orelse continue;
const f = if (pane.file) |*file| file else continue;
if (w.promote) {
promoteSaved(p, w.pane, w.path);
} else if (w.clean != null and w.clean.? == f.revision) {
f.saved_revision = f.revision;
f.disk_gone = false;
ctlfs.events.noteLog(p, .save, pane);
} else ctlfs.events.noteLogAs(p, .save, pane, w.path);
}
},
.watch => |w| if (v.watch_file) |f| {
// What a watch is about: a real file, or a PDF.
const path: []const u8 = if (p.panes[w.pane]) |pane| (if (pane.file) |file| (if (file.output == null) file.path else "") else pane.pdfPath() orelse "") else "";
f(p.host.ctx, w.pane, path, w.on, w.mode);
} else {
p.fallback.watched[w.pane] = w.on;
},
.theme_file => |t| if (v.watch_theme) |f| f(p.host.ctx, t.generation, t.on),
.dump_themes => |d| if (v.dump_themes) |f| f(p.host.ctx, d.pane),
.detach => |d| if (v.detach) |f|
f(p.host.ctx)
else
p.reportError(d.pane, "detach", error.NotAttached),
// dlopen is the same on every host, so none has a method of its
// own; a replica's core holds no library (what it brought comes in
// the event this taped).
.addon => |a| if (!tape.replaying()) @import("Addon.zig").perform(p, a.op, a.pane, a.arg.slice()),
.job => |j| if (v.job) |f| f(p.host.ctx, j.pane, j.serial, j.token) else if (!tape.replaying()) host_io.KindJob.runHere(p, j.pane, j.serial, j.token),
// the loop's own condition; a host tears down after its own loop
.quit => p.quit = true,
}
}
/// Writes `bytes` to `path` for pane `id`, its directories made first:
/// the pane after it, if it is still the one `serial` names and the
/// write did not fail. A failed write changes nothing: its file goes
/// back to the saved revision `was`, dirty as it was.
pub fn writeChecked(p: *Pardes, id: u8, serial: u32, path: []const u8, bytes: []const u8, was: u32) ?*Pane {
const failures = p.fs.failures;
// A Save makes the directories its file goes in, and any above them,
// first: one rule, for the pane's own name and `Save path` alike. A
// directory it cannot make leaves the write to fail and say why.
if (filesystem.localPath(path)) |local| filesystem.makeDirs(std.fs.path.dirname(local) orelse "/");
// The in-process filesystem reports the same way a real host does,
// so an OOM there leaves the pane dirty rather than looking saved.
if (p.host.vtable.write_file) |f| f(p.host.ctx, id, path, bytes) else if (!p.fallback.writeFile(path, bytes)) p.saveFailed(id, path, error.OutOfMemory);
const pane = p.panes[id] orelse return null;
if (pane.serial != serial) return null;
if (p.fs.failures == failures) return pane;
if (pane.file) |*f| f.saved_revision = was;
return null;
}
/// A write of `path` the host could not do: the pane stays dirty, the
/// message row says `Save <path>: <why>`, and the 9P write that asked
/// for it, waiting on the save, fails with that (`fs.late_failure`).
/// A scratch written to `path` is that file from here on: named, an
/// ordinary file pane, clean, and watched (exec.saveTo).
fn promoteSaved(p: *Pardes, id: u8, path: []const u8) void {
const pane = p.panes[id] orelse return;
const f = if (pane.file) |*file| file else return;
const owned = p.gpa.dupe(u8, path) catch return;
p.gpa.free(f.path);
f.path = owned;
f.output = null;
pane.clearCwd();
// re-derive the tag as a plain file's
if (pane.tag.own) |own| p.gpa.free(own);
pane.tag.own = null;
f.saved_revision = f.revision;
f.disk_gone = false;
ctlfs.events.noteLog(p, .save, pane);
p.recent.opened(p.recentGpa(), f.path);
if (filesystem.localPath(f.path) != null)
p.emit(.{ .watch = .{ .pane = id, .on = true } });
}
fn drainForSavePath(p: *Pardes, buf: []u8) ?[]const u8 {
var len: ?usize = null;
while (p.nextEffect()) |effect| {
switch (effect) {
.save_text => |st| {
const path = st.path.slice();
@memcpy(buf[0..path.len], path);
len = path.len;
},
else => {},
}
p.perform(effect);
}
return if (len) |n| buf[0..n] else null;
}
test "Detach asks the host to let its terminal go, and says so when there is nothing to leave" {
if (comptime !pardes.can_attach) return; // the word is compiled out elsewhere: see `can_attach`
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
while (p.nextEffect()) |_| {}
try std.testing.expect(p.executeBuiltinLine(0, "Detach"));
const asked = while (p.nextEffect()) |effect| switch (effect) {
.detach => |d| break d,
else => {},
} else return error.NoDetachAsked;
try std.testing.expectEqual(@as(u8, 0), asked.pane);
p.perform(.{ .detach = asked });
const pane = p.panes[0].?;
try std.testing.expectEqualStrings("detach: not attached", pane.msg[0..pane.msg_len]);
try std.testing.expect(!p.quit);
}
test "Save on a scratch asks for a path in its inherited dir and makes it a file" {
const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const source: usize = 2;
p.setCwd(source, "/tmp/pardes-save-dir");
try std.testing.expect(p.executeBuiltinLine(source, "New"));
const id = p.view().active;
const np = p.panes[id].?;
p.sync(); // the frame boundary that gives the new pane its geometry
while (p.nextEffect()) |_| {}
// Save on a scratch arms a PATH input, prefilled with the inherited dir
try std.testing.expect(p.executeBuiltinLine(id, "Save"));
try std.testing.expect(np.prompt == .save);
try std.testing.expectEqualStrings(" Save /tmp/pardes-save-dir/", np.promptText().?);
// typing the filename and submitting converts it into an ordinary file
edit.insertKey(p, &np.input, .{ .cp = 'n', .text = "note.txt" });
exec.submitSave(p, id);
// The write asked for, the pane is the file once it is done.
var saved = false;
while (p.nextEffect()) |effect| {
if (effect == .save_text and @as(usize, effect.save_text.pane) == id) saved = true;
p.perform(effect);
}
try std.testing.expect(saved);
try std.testing.expect(np.file.?.output == null);
try std.testing.expectEqualStrings("/tmp/pardes-save-dir/note.txt", np.file.?.path);
try std.testing.expectEqual(np.file.?.revision, np.file.?.saved_revision);
}
test "Save on a terminal writes its plaintext scrollback and stays a terminal" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 8 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = p.panes[0].?;
p.setCwd(0, "/tmp/pardes-tty-save");
p.update(.{ .output = .{ .pane = 0, .bytes = "hello scrollback\r\n" } });
while (p.nextEffect()) |_| {}
try std.testing.expect(p.executeBuiltinLine(0, "Save"));
try std.testing.expect(pane.prompt == .save);
edit.insertKey(p, &pane.input, .{ .cp = 'l', .text = "log.txt" });
exec.submitSave(p, 0);
// the pane is untouched: still a terminal, no file behind it
try std.testing.expect(pane.isTerminal());
try std.testing.expect(pane.file == null);
// the host performs it, reading the scrollback off the pane as it goes
var buf: [256]u8 = undefined;
try std.testing.expectEqualStrings(
"/tmp/pardes-tty-save/log.txt",
drainForSavePath(p, &buf) orelse return error.NoSaveAsked,
);
const written = p.fallback.get("/tmp/pardes-tty-save/log.txt") orelse return error.NothingWritten;
try std.testing.expect(std.mem.indexOf(u8, written, "hello scrollback") != null);
}
test "Save on an output buffer writes its rows out and leaves the buffer alone" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .shells = 3, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const source: usize = 2;
p.setCwd(source, "/tmp/pardes-output-save");
try std.testing.expect(p.executeBuiltinLine(source, "Help"));
p.sync(); // the frame boundary that gives the new pane its geometry
while (p.nextEffect()) |_| {}
const help: panes.Output.Origin = .{ .cmd = .Help };
const id = blk: {
for (p.panes, 0..) |slot, i| {
const pane = slot orelse continue;
const f = pane.file orelse continue;
const o = f.output orelse continue;
if (std.meta.eql(o.from, help)) break :blk i;
}
return error.MissingHelpBuffer;
};
const out = p.panes[id].?;
const path = try gpa.dupe(u8, out.file.?.path);
defer gpa.free(path);
const rows = try gpa.dupe(u8, out.file.?.content);
defer gpa.free(rows);
// Save leads its tagline now, and the path is REQUIRED: a bare Save asks
try std.testing.expectEqualStrings(tagline.file_pane_tail, tagline.curTail(out));
try std.testing.expect(p.executeBuiltinLine(id, "Save"));
try std.testing.expect(out.prompt == .save);
edit.insertKey(p, &out.input, .{ .cp = 'h', .text = "help.txt" });
exec.submitSave(p, id);
// the buffer itself is untouched: same origin, same name, still refillable
// and still walked by n/N, because a saved copy of a list is only a copy
try std.testing.expect(out.file.?.output != null);
try std.testing.expectEqual(help, out.file.?.output.?.from);
try std.testing.expectEqualStrings(path, out.file.?.path);
var buf: [256]u8 = undefined;
try std.testing.expectEqualStrings(
"/tmp/pardes-output-save/help.txt",
drainForSavePath(p, &buf) orelse return error.NoSaveAsked,
);
try std.testing.expectEqualStrings(
rows,
p.fallback.get("/tmp/pardes-output-save/help.txt") orelse return error.NothingWritten,
);
}
test "Save takes the path as an argument, relative to the pane's own directory" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 8 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = p.panes[0].?;
p.setCwd(0, "/tmp/pardes-arg-save");
p.update(.{ .output = .{ .pane = 0, .bytes = "typed and gone\r\n" } });
while (p.nextEffect()) |_| {}
var buf: [256]u8 = undefined;
try std.testing.expect(p.executeBuiltinLine(0, "Save session.txt"));
try std.testing.expect(pane.prompt != .save);
try std.testing.expectEqualStrings(
"/tmp/pardes-arg-save/session.txt",
drainForSavePath(p, &buf) orelse return error.NoSaveAsked,
);
const written = p.fallback.get("/tmp/pardes-arg-save/session.txt") orelse return error.NothingWritten;
try std.testing.expect(std.mem.indexOf(u8, written, "typed and gone") != null);
// `.` and `..` normalize with it, so this is that same file and not a
// second one spelled differently
try std.testing.expect(p.executeBuiltinLine(0, "Save ./sub/../session.txt"));
try std.testing.expectEqualStrings(
"/tmp/pardes-arg-save/session.txt",
drainForSavePath(p, &buf) orelse return error.NoSaveAsked,
);
try std.testing.expect(p.executeBuiltinLine(0, "Save /tmp/pardes-elsewhere/abs.txt"));
try std.testing.expectEqualStrings(
"/tmp/pardes-elsewhere/abs.txt",
drainForSavePath(p, &buf) orelse return error.NoSaveAsked,
);
try std.testing.expect(pane.isTerminal());
p.panes[0].?.clearCwd();
try std.testing.expect(p.executeBuiltinLine(0, "Save nowhere.txt"));
try std.testing.expect(drainForSavePath(p, &buf) == null);
}
test "a save the host could not do leaves the pane dirty" {
const gpa = std.testing.allocator;
const Refusing = struct {
fn writeFile(ctx: ?*anyopaque, pane: u8, _: []const u8, _: []const u8) void {
const core: *Pardes = @ptrCast(@alignCast(ctx.?));
core.saveFailed(pane, "/x/y.txt", error.PermissionDenied);
}
};
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = try p.setTestFile("before\n");
panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "after\n"));
try std.testing.expect(pane.file.?.revision != pane.file.?.saved_revision);
p.host = .{ .ctx = p, .vtable = &.{ .write_file = Refusing.writeFile } };
try std.testing.expect(p.executeBuiltinLine(0, "Save"));
while (p.nextEffect()) |effect| p.perform(effect);
try std.testing.expect(pane.file.?.revision != pane.file.?.saved_revision);
// ...and the same save against a host that CAN write does come clean, so
// the guard above is not simply "never clean".
p.host = .{};
try std.testing.expect(p.executeBuiltinLine(0, "Save"));
while (p.nextEffect()) |effect| p.perform(effect);
try std.testing.expectEqual(pane.file.?.revision, pane.file.?.saved_revision);
try std.testing.expectEqualStrings("after\n", p.fallback.get("/test.txt").?);
}
test "Save elsewhere copies a file's bytes and keeps the pane on its own file" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = try p.setTestFile("before\n");
panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "after\n"));
try std.testing.expect(pane.file.?.revision != pane.file.?.saved_revision);
var buf: [256]u8 = undefined;
try std.testing.expect(p.executeBuiltinLine(0, "Save /tmp/pardes-copy/other.txt"));
// a copy, never a rename: the pane keeps its file, and that file is still
// unsaved, so the marker stays where it was
try std.testing.expectEqualStrings("/test.txt", pane.file.?.path);
try std.testing.expect(pane.file.?.revision != pane.file.?.saved_revision);
try std.testing.expectEqualStrings(
"/tmp/pardes-copy/other.txt",
drainForSavePath(p, &buf) orelse return error.NoSaveAsked,
);
try std.testing.expectEqualStrings(
"after\n",
p.fallback.get("/tmp/pardes-copy/other.txt") orelse return error.NothingWritten,
);
// its own path, spelled out, is the in-place write — nothing is asked of
// the host but save_file, and the pane comes clean
try std.testing.expect(p.executeBuiltinLine(0, "Save /test.txt"));
try std.testing.expect(drainForSavePath(p, &buf) == null);
try std.testing.expectEqual(pane.file.?.revision, pane.file.?.saved_revision);
}
test "saves armed in one batch stay with their own panes" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .shells = 3, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const tty_id = p.freeSlot() orelse return error.NoPaneSlots;
const shell = try p.newShell(tty_id, "/tmp/pardes-batch");
p.setCwd(tty_id, "/tmp/pardes-batch");
p.update(.{ .output = .{ .pane = @intCast(tty_id), .bytes = "shell text\r\n" } });
const file = try p.setTestFile("file text\n");
const file_id = panes.paneIdOf(p, file) orelse return error.MissingFilePane;
try std.testing.expect(shell.isTerminal());
try std.testing.expect(tty_id != file_id);
while (p.nextEffect()) |_| {}
// both armed before the host drains anything — the path rides inside its
// own effect, so neither can be written with the other pane's text
try std.testing.expect(p.executeBuiltinLine(tty_id, "Save tty.txt"));
try std.testing.expect(p.executeBuiltinLine(file_id, "Save /tmp/pardes-batch/file.txt"));
while (p.nextEffect()) |effect| p.perform(effect);
const tty_bytes = p.fallback.get("/tmp/pardes-batch/tty.txt") orelse return error.NothingWritten;
try std.testing.expect(std.mem.indexOf(u8, tty_bytes, "shell text") != null);
try std.testing.expectEqualStrings(
"file text\n",
p.fallback.get("/tmp/pardes-batch/file.txt") orelse return error.NothingWritten,
);
}
test "a save whose pane is gone before the drain writes nothing" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .shells = 3, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const doomed = p.freeSlot() orelse return error.NoPaneSlots;
const shell = try p.newShell(doomed, "/tmp/pardes-gone");
p.update(.{ .output = .{ .pane = @intCast(doomed), .bytes = "doomed text\r\n" } });
while (p.nextEffect()) |_| {}
try std.testing.expect(shell.isTerminal());
// Save, then close the pane, then let the host drain: the bytes are read
// off the pane at drain time, so there are none to read...
try std.testing.expect(p.executeBuiltinLine(doomed, "Save /tmp/pardes-gone/log.txt"));
try std.testing.expect(p.executeBuiltinLine(doomed, "Del"));
while (p.nextEffect()) |effect| p.perform(effect);
try std.testing.expect(p.fallback.get("/tmp/pardes-gone/log.txt") == null);
// ...and a pane that took the freed slot in the meantime is NOT the pane
// that asked, which is what the serial in the effect is for
try std.testing.expect(p.executeBuiltinLine(0, "Save /tmp/pardes-gone/recycled.txt"));
try std.testing.expect(p.executeBuiltinLine(0, "Del"));
const reused = p.freeSlot() orelse return error.NoPaneSlots;
_ = try p.newShell(reused, "/tmp/pardes-gone");
while (p.nextEffect()) |effect| p.perform(effect);
try std.testing.expect(p.fallback.get("/tmp/pardes-gone/recycled.txt") == null);
}
test "Save reaches every tagline with text behind it and no other" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const out = try p.setTestFile("build.zig:1:1 pub fn main\n");
out.file.?.output = .{ .from = .search };
try std.testing.expectEqualStrings(tagline.locations_pane_tail, tagline.curTail(out));
// A scratch is an output buffer that wears the FILE tails.
out.file.?.output = .{ .from = .{ .cmd = std.meta.stringToEnum(pardes.Builtin, "New").? } };
try std.testing.expectEqualStrings(" Save Term Collapse Del", tagline.curTail(out));
// An image's bytes on disk already are what they are: nothing of the
// pane's own is unwritten, so the word is absent and inert.
const img_id = p.freeSlot().?;
const img = try pardes.Kind.open(p, img_id, pardes.Kind.test_kind.of(p), "/tmp/pardes-tag.ppm", "");
try std.testing.expectEqualStrings(" Term Collapse Del", tagline.curTail(img));
try std.testing.expect(p.executeBuiltinLine(img_id, "Save"));
try std.testing.expect(img.prompt != .save);
var buf: [256]u8 = undefined;
try std.testing.expect(drainForSavePath(p, &buf) == null);
}
test "a save path that names no file is refused before anything is rewritten" {
const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const source: usize = 2;
p.setCwd(source, "/tmp/pardes-refuse");
try std.testing.expect(p.executeBuiltinLine(source, "New"));
const id = p.view().active;
const scratch = p.panes[id].?;
p.sync();
while (p.nextEffect()) |_| {}
try std.testing.expect(p.executeBuiltinLine(id, "Save"));
try std.testing.expect(scratch.prompt == .save);
exec.submitSave(p, id);
var buf: [256]u8 = undefined;
try std.testing.expect(drainForSavePath(p, &buf) == null);
try std.testing.expect(scratch.file.?.output != null);
try std.testing.expectEqualStrings("/tmp/pardes-refuse/+New", scratch.file.?.path);
// ...and neither is a multi-line selection chorded onto the word
try std.testing.expect(p.executeBuiltinLine(id, "Save one\ntwo"));
try std.testing.expect(drainForSavePath(p, &buf) == null);
try std.testing.expect(scratch.file.?.output != null);
}
test "a Save the host could not do logs no save record" {
const th = @import("ninep/testing.zig");
const p = try th.withFile(std.testing.allocator, "x\n");
defer p.deinit();
const Failing = struct {
core: *Pardes,
const vtable: Host.VTable = .{ .write_file = write };
fn write(ctx: ?*anyopaque, pane: u8, path: []const u8, _: []const u8) void {
const f: *@This() = @ptrCast(@alignCast(ctx.?));
f.core.saveFailed(pane, path, error.AccessDenied);
}
};
var host: Failing = .{ .core = p };
p.host = .{ .ctx = &host, .vtable = &Failing.vtable };
_ = th.wr(p, ctlfs.Node.of(p.panes[0].?.serial, .body), "more\n");
p.perform(.{ .save_file = .{ .pane = 0 } });
try std.testing.expect(!th.logHas(p, "\nsave "));
try std.testing.expect(p.panes[0].?.file.?.saved_revision != p.panes[0].?.file.?.revision);
// With the host's write done, it is logged.
p.host = .{};
p.perform(.{ .save_file = .{ .pane = 0 } });
try std.testing.expect(th.logHas(p, "\nsave "));
}
|