diff options
Diffstat (limited to 'src/pardes.zig')
| -rw-r--r-- | src/pardes.zig | 3949 |
1 files changed, 5 insertions, 3944 deletions
diff --git a/src/pardes.zig b/src/pardes.zig index 153a07c9..dee1db2d 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -266,6 +266,7 @@ test "a compact tagline anchors at its own pane, and both shells step from the s test { _ = @import("rollback.zig"); + _ = @import("Core.zig"); _ = @import("lsp/Ask.zig"); _ = @import("Jump.zig"); _ = @import("keys.zig"); @@ -347,1223 +348,6 @@ pub const test_api = if (@import("builtin").is_test) struct { } } else struct {}; -test "startup config runs builtin lines in order and isolates bad lines" { - const p = try Pardes.init(std.testing.allocator, .{ - .startup_config = - \\Theme dark - \\DefinitelyNotABuiltin - \\Exit trailing-garbage - \\Theme no-such-theme - \\Theme acme - , - }); - defer p.deinit(); - - try std.testing.expectEqualStrings("acme", p.theme().name); - // The theme lands without a tween (the chrome is the theme's at once); - // the bad lines are said, so a notice may be up. - try std.testing.expectEqual(ChromeTheme.fromTheme(p.theme()), p.chromeTheme().*); - try std.testing.expect(!p.quit); - for (0..p.effects_len) |i| switch (p.effects[(p.effects_head + i) % p.effects.len]) { - .write => |w| { - try std.testing.expect(std.mem.indexOf(u8, w.bytes.slice(), "DefinitelyNotABuiltin") == null); - try std.testing.expect(std.mem.indexOf(u8, w.bytes.slice(), "Exit") == null); - }, - else => {}, - }; -} - -test "topbar hover highlights exactly the executable word" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - var frame = std.heap.ArenaAllocator.init(std.testing.allocator); - defer frame.deinit(); - - _ = try p.render(frame.allocator()); - p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = TAG_TEXT_INSET + 1, .row = 0 } }); - _ = frame.reset(.retain_capacity); - const hovered = try p.render(frame.allocator()); - for (0.."Newcol".len) |col| { - const cell = hovered.at(TAG_TEXT_INSET + @as(u16, @intCast(col)), 0); - try std.testing.expectEqual(Color{ .rgb = p.theme().sel_bg }, cell.style.bg); - try std.testing.expectEqual(Color{ .rgb = p.theme().sel_fg }, cell.style.fg); - } - try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, hovered.at(TAG_TEXT_INSET + 6, 0).style.bg); - - p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = TAG_TEXT_INSET + 6, .row = 0 } }); - _ = frame.reset(.retain_capacity); - const whitespace = try p.render(frame.allocator()); - try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, whitespace.at(TAG_TEXT_INSET + 1, 0).style.bg); - - p.update(.pointer_leave); - _ = frame.reset(.retain_capacity); - const left = try p.render(frame.allocator()); - try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, left.at(TAG_TEXT_INSET + 1, 0).style.bg); -} - -test "pane-tag Exec prefers Term and argument builtins before shell fallback" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} // initial shell spawn/geometry - p.acknowledgeShell(0, "/bin/sh", false); - - // The Term word names the shell the host ran, and opens another of it. - const pane = p.panes[0].?; - try std.testing.expectEqualStrings(" Term+sh" ++ tagline.terminal_pane_tail[" Term".len..], tagline.curTail(pane)); - const tag_x = p.rects[0].x + TAG_TEXT_INSET; - const tag_y = p.rects[0].y; - - const rendered = try tagline.tagText(p, p.scratch.allocator(), pane); - const new_x = tag_x + @as(u16, @intCast(std.mem.indexOf(u8, rendered, "Term").?)) + 1; - var panes_before: usize = 0; - for (p.panes) |s| if (s != null) { - panes_before += 1; - }; - p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = new_x, .row = tag_y } }); - p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = new_x, .row = tag_y } }); - while (p.nextEffect()) |effect| switch (effect) { - .write => return error.NewFellThroughToPty, - else => {}, - }; - var panes_after: usize = 0; - for (p.panes) |s| if (s != null) { - panes_after += 1; - }; - try std.testing.expectEqual(panes_before + 1, panes_after); - try std.testing.expect(p.panes[p.active].?.isTerminal()); - try std.testing.expectEqualStrings("sh", p.panes[p.active].?.shell.?); - - // Argument-taking builtins use the same gesture path: a tag sweep is the - // complete command line, and Theme consumes its tail without a PTY write. - if (pane.tag.own) |own| p.gpa.free(own); - pane.tag.own = try p.gpa.dupe(u8, " Theme dark"); - p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = tag_x + 1, .row = tag_y } }); - p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .drag, .col = tag_x + 10, .row = tag_y } }); - p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = tag_x + 10, .row = tag_y } }); - try std.testing.expectEqualStrings("dark", p.theme().name); - while (p.nextEffect()) |effect| switch (effect) { - .write => return error.ArgumentBuiltinFellThroughToPty, - else => {}, - }; - - // Fixed-name builtins remain exact: a tail does not turn New or Exit into - // a match (especially important for the destructive one). - try std.testing.expect(!p.executeBuiltinLine(0, "New argument")); - try std.testing.expect(!p.executeBuiltinLine(0, "Exit trailing-garbage")); - try std.testing.expect(!p.quit); - - // A word absent from the builtin vocabulary takes the fallback, including - // the terminating carriage return expected by the shell prompt. - if (pane.tag.own) |own| p.gpa.free(own); - pane.tag.own = try p.gpa.dupe(u8, " DefinitelyNotABuiltin"); - p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = tag_x + 1, .row = tag_y } }); - p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = tag_x + 1, .row = tag_y } }); - var sent: [256]u8 = undefined; - var sent_len: usize = 0; - while (p.nextEffect()) |effect| switch (effect) { - .write => |w| { - try std.testing.expectEqual(@as(u8, 0), w.pane); - try std.testing.expect(w.bytes.slice().len <= sent.len - sent_len); - @memcpy(sent[sent_len..][0..w.bytes.slice().len], w.bytes.slice()); - sent_len += w.bytes.slice().len; - }, - else => {}, - }; - try std.testing.expectEqualStrings("DefinitelyNotABuiltin\r", sent[0..sent_len]); -} - -test "LocationsConfig command reports partial updates and survives restore" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - _ = try p.setTestFile("source\n"); - try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig context:5 tscontext:on")); - try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig tslocations:off")); - const expected: locations.Config = .{ .context = 5, .tscontext = true, .tslocations = false }; - try std.testing.expectEqual(expected, p.locations_config); - try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig context:2 unknown:on")); - try std.testing.expectEqual(expected, p.locations_config); - // Setting it is silent; asking bare is what opens the window. - try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig")); - var reports: usize = 0; - for (p.panes) |slot| { - const pane = slot orelse continue; - const file = pane.file orelse continue; - const out = file.output orelse continue; - if (!std.meta.eql(out.from, panes.Output.Origin{ .cmd = .LocationsConfig })) continue; - reports += 1; - try std.testing.expectEqualStrings("LocationsConfig context:5 tscontext:on tslocations:off layout:stacked\n", file.content); - } - try std.testing.expectEqual(@as(usize, 1), reports); - try dump.dumpState(p); - const restored = try dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); - defer restored.deinit(); - try std.testing.expectEqual(expected, restored.locations_config); -} - -test "TreeContext tag style preserves message rows and its opt-out survives restore" { - if (comptime !syntax.enabled) return error.SkipZigTest; - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer p.deinit(); - const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*)))) ++ " }\n};\n"); - p.gpa.free(pane.file.?.path); - pane.file.?.path = try p.gpa.dupe(u8, "/test.zig"); - if (!panes.File.supportsContext(pane)) return error.SkipZigTest; - p.update(.{ .resize = .{ .cols = 60, .rows = 16, .row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 } } }); - pane.file.?.tree_context = true; - pane.file.?.scroll = 8; - pane.msg_len = 0; - p.sync(); - _ = try p.render(p.scratch.allocator()); - try std.testing.expect(p.settings.tree_context_tag_style); - const full_height = p.surface.body_layers[0].viewport.h; - try std.testing.expect(p.surface.body_layers[0].rows > full_height); - try std.testing.expectEqual(FontRole.tagline, p.surface.body_layers[0].cells[0].style.font_role); - pane.msg[0] = '!'; - pane.msg_len = 1; - p.sync(); - _ = try p.render(p.scratch.allocator()); - // An overlay takes nothing: the message is a chip OVER the body's first - // row, so the viewport keeps every row it had. - try std.testing.expectEqual(full_height, p.surface.body_layers[0].viewport.h); - const r = p.rects[0]; - const band = for (p.surface.tagLayers()) |*layer| { - if (layer.rows != 0 and layer.kind == .notice) break layer; - } else return error.NoNoticeBand; - try std.testing.expectEqual(p.bodyTop(pane, r), band.viewport.y); - try std.testing.expectEqual(p.surface.body_layers[0].viewport.y, band.viewport.y); - // Sized to its message, flush with the pane's right edge, and the text - // right aligned a cell short of that edge. - try std.testing.expectEqual(r.x + r.w, band.viewport.x + band.viewport.w); - try std.testing.expect(band.viewport.w < r.w - config.GUTTER); - try std.testing.expectEqualStrings("!", band.cells[layout.tagCapacity(p, band.viewport.w) - 2].grapheme()); - pane.msg_len = 0; - p.leader_on = true; - p.sync(); - _ = try p.render(p.scratch.allocator()); - try std.testing.expectEqual(full_height, p.surface.body_layers[0].viewport.h); - p.leader_on = false; - try std.testing.expect(p.executeBuiltinLine(0, "TreeContextTagStyle")); - p.sync(); - _ = try p.render(p.scratch.allocator()); - try std.testing.expectEqual(@as(u16, 0), p.surface.body_layers[0].rows); - try std.testing.expectEqual(@as(u16, 0), pane.body_rows); - try std.testing.expectEqual(FontRole.body, p.surface.at(r.x + config.GUTTER, p.bodyTop(pane, r)).style.font_role); - try dump.dumpState(p); - const restored = try dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); - defer restored.deinit(); - try std.testing.expect(!restored.settings.tree_context_tag_style); -} - -test "TreeContext command and custom tag survive a workspace round trip" { - if (comptime !syntax.enabled) return error.SkipZigTest; - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("pub fn main() void {}\n"); - try std.testing.expect(!panes.File.supportsContext(pane)); - try std.testing.expectEqualStrings(tagline.file_pane_tail, tagline.curTail(pane)); - const path = try p.gpa.dupe(u8, "/test.zig"); - p.gpa.free(pane.file.?.path); - pane.file.?.path = path; - if (!panes.File.supportsContext(pane)) return error.SkipZigTest; - try std.testing.expectEqualStrings(if (lsp.speaks("/test.zig")) tagline.lsp_context_pane_tail else tagline.context_pane_tail, tagline.curTail(pane)); - try std.testing.expect(!pane.file.?.tree_context); - try std.testing.expect(p.executeBuiltinLine(0, "TreeContext on")); - try std.testing.expect(pane.file.?.tree_context); - try std.testing.expect(p.executeBuiltinLine(0, "TreeContext off")); - try std.testing.expect(!pane.file.?.tree_context); - try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); - try std.testing.expect(pane.file.?.tree_context); - try std.testing.expect(p.executeBuiltinLine(0, "TreeContext invalid")); - try std.testing.expect(pane.file.?.tree_context); - if (pane.tag.own) |own| p.gpa.free(own); - pane.tag.own = try p.gpa.dupe(u8, " Save Keep Del"); - try dump.dumpState(p); - const restored = try dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); - defer restored.deinit(); - const saved = restored.panes[0].?; - try std.testing.expect(saved.file.?.tree_context); - try std.testing.expectEqualStrings(" Save Keep Del", tagline.curTail(saved)); -} - -test "Filter is ordered after Del and toggles only its terminal or +Pager pane" { - const testing = std.testing; - const del = std.meta.stringToEnum(Builtin, "Del") orelse return error.MissingDelBuiltin; - const filter = std.meta.stringToEnum(Builtin, "Filter") orelse return error.MissingFilterBuiltin; - try testing.expectEqual(@backingInt(del) + 1, @backingInt(filter)); - - const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const first = p.panes[0].?; - const palette_before = first.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; - - try testing.expect(first.tty_filter); - try testing.expect(p.executeBuiltinLine(0, "Filter")); - try testing.expect(!first.tty_filter); - try testing.expect(palette_before.eql(first.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); - - const second_id = p.freeSlot().?; - const second = try p.newShell(second_id, ""); - try testing.expect(second.tty_filter); - try testing.expect(p.executeBuiltinLine(second_id, "Filter")); - try testing.expect(!second.tty_filter); - try testing.expect(!first.tty_filter); - - const doc_id = p.freeSlot().?; - const doc = try panes.Image.create(p, doc_id, "/tmp/filter-inert.ppm", &.{}); - try testing.expect(!doc.tty_filter); - try testing.expect(p.executeBuiltinLine(doc_id, "Filter")); - try testing.expect(!doc.tty_filter); - try testing.expect(!first.tty_filter); - - try testing.expect(p.executeBuiltinLine(0, "Filter")); - try testing.expect(first.tty_filter); - try testing.expect(!second.tty_filter); - - // A +Pager opens filtered, with Filter on its tag and no line numbers; - // a second is a pane of its own. - const pager_id = try panes.Output.openPager(p, 0, "/tmp"); - const pager_pane = p.panes[pager_id].?; - try testing.expect(pager_pane.tty_filter); - try testing.expectEqualStrings(tagline.pager_pane_tail, tagline.curTail(pager_pane)); - try testing.expectEqual(@as(u16, 0), panes.File.gutterWidth(pager_pane)); - try testing.expect(p.executeBuiltinLine(pager_id, "Filter")); - try testing.expect(!pager_pane.tty_filter); - try testing.expect(try panes.Output.openPager(p, 0, "/tmp") != pager_id); -} - -test "compact tag commands stay beside their own prefix across layout changes" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} // initial shell spawn/geometry - - // A longer sibling never introduces invisible padding into this tag. - const below_id = p.freeSlot().?; - const below = try p.newShell(below_id, ""); - const f = layout.findPane(p, p.active).?; - layout.insert(p, f.col, f.idx + 1, below_id); - layout.splitBelow(p, p.active, below); - p.setCwd(below_id, "/a/deep/dir/whose/name/eats/the/right/pad/the/end/of/its/own/tagline"); - p.sync(); - while (p.nextEffect()) |_| {} - - const above = p.panes[0].?; - try std.testing.expectEqual(p.rects[0].x, p.rects[below_id].x); - const above_tag = try tagline.tagText(p, gpa, above); - defer gpa.free(above_tag); - const below_tag = try tagline.tagText(p, p.scratch.allocator(), below); - try std.testing.expect(below_tag.len > above_tag.len); - const tail = tagline.terminal_pane_tail; - try std.testing.expectEqualStrings(tail, above_tag[above_tag.len - tail.len ..]); - try std.testing.expectEqual(above.cwdSlice().len + tail.len, above_tag.len); - - p.update(.{ .resize = .{ .cols = 88, .rows = 30 } }); - while (p.nextEffect()) |_| {} - try std.testing.expectEqualStrings(above_tag, try tagline.tagText(p, p.scratch.allocator(), above)); - p.update(.{ .resize = .{ .cols = 87, .rows = 30 } }); - while (p.nextEffect()) |_| {} - try std.testing.expectEqualStrings(above_tag, try tagline.tagText(p, p.scratch.allocator(), above)); - p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); - while (p.nextEffect()) |_| {} - try std.testing.expectEqualStrings(tail, tagline.curTail(below)); - try below.appendTag(" lots and lots of typing out here"); - try std.testing.expectEqual(above_tag.len, (try tagline.tagText(p, p.scratch.allocator(), above)).len); - - p.update(.{ .resize = .{ .cols = 100, .rows = 2 } }); - while (p.nextEffect()) |_| {} - try std.testing.expectEqual(@as(u16, 0), p.rects[below_id].h); - try std.testing.expectEqualStrings(above_tag, try tagline.tagText(p, p.scratch.allocator(), above)); -} - -test "Term spawns a raw shell in the caller's directory" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - p.setCwd(0, "/tmp/newtty-dir"); - - try std.testing.expect(p.executeBuiltinLine(0, "Term")); - const free = p.active; - try std.testing.expect(free != 0); - const nt = p.panes[free] orelse return error.NoNewPane; - try std.testing.expect(nt.isTerminal()); - try std.testing.expect(nt.body.mode == .tty); - - var found = false; - while (p.nextEffect()) |effect| switch (effect) { - .spawn => |s| if (@as(usize, s.pane) == free) { - try std.testing.expectEqualStrings("/tmp/newtty-dir", s.cwd.slice()); - found = true; - }, - else => {}, - }; - try std.testing.expect(found); -} - -test "a terminal respawned into a closed pane's slot hangs the old shell up first" { - // Hosts keep a shell per slot: were the spawn first, the close would - // end the new shell and leave the old one running. - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 }); - defer p.deinit(); - try std.testing.expect(p.executeBuiltinLine(0, "Term")); - const slot = p.active; - while (p.nextEffect()) |_| {} - try p.removePane(slot, null); - try std.testing.expect(p.executeBuiltinLine(0, "Term")); - try std.testing.expectEqual(slot, p.active); - var closed = false; - var spawned = false; - while (p.nextEffect()) |effect| switch (effect) { - .close_pty => |c| if (c.pane == slot) { - try std.testing.expect(!spawned); - closed = true; - }, - .spawn => |s| if (s.pane == slot) { - spawned = true; - }, - else => {}, - }; - try std.testing.expect(closed and spawned); -} - -test "a frame no one watches is not drawn, and is drawn once someone does" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const Watch = struct { - var presents: usize = 0; - var seen = false; - const vtable: Host.VTable = .{ .present = present, .watched = watched }; - fn present(_: ?*anyopaque, _: *const Surface) void { - presents += 1; - } - fn watched(_: ?*anyopaque) bool { - return seen; - } - }; - Watch.presents = 0; - Watch.seen = false; - p.needs_frame = true; - try p.pump(.{ .vtable = &Watch.vtable }); - try std.testing.expectEqual(@as(usize, 0), Watch.presents); - try std.testing.expect(p.needs_frame); // still owed - Watch.seen = true; - try p.pump(.{ .vtable = &Watch.vtable }); - try std.testing.expectEqual(@as(usize, 1), Watch.presents); -} - -test "an empty column shows its theme's empty_col under its tag: acme's white, else the border" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 20 }); - defer p.deinit(); - layout.newColumn(p, 0); - tagline.exitHeader(p); - inline for (.{ "acme", "dark" }) |name| { - try std.testing.expect(p.executeBuiltinLine(0, "Theme " ++ name)); - p.sync(); - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - const s = try p.render(arena.allocator()); - const cell = s.at(p.col_x[1] + 3, p.screen_h - 2); - const want = p.chromeTheme().empty_col; - try std.testing.expectEqual(want, cell.style.bg.rgb); - if (std.mem.eql(u8, name, "acme")) try std.testing.expectEqual([3]u8{ 0xff, 0xff, 0xff }, want) else try std.testing.expectEqual(p.chromeTheme().border, want); - } -} - -test "unknown Exec from a document runs as a command pane in its directory, typed into no terminal" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{}); - defer p.deinit(); - while (p.nextEffect()) |_| {} - p.acknowledgeShell(0, "/bin/sh", false); - - // A terminal free at a prompt in the same directory is not borrowed. - p.setCwd(0, "/tmp/pardes-image-dir"); - const image_doc = try p.newDocPane(1); - image_doc.image = .{ .path = try gpa.dupe(u8, "/tmp/pardes-image-dir/pic.ppm") }; - try std.testing.expectEqualStrings("/tmp/pardes-image-dir", Pardes.paneDir(image_doc)); - const dst = exec.execute(p, 1, "echo image-fallback") orelse return error.ExecFoundNowhereToRun; - try std.testing.expect(dst != 0 and dst != 1); - try std.testing.expectEqualStrings("echo image-fallback", p.panes[dst].?.command.?); - - var spawned = false; - while (p.nextEffect()) |effect| switch (effect) { - .write => return error.TypedIntoATerminal, - .spawn => |sp| if (sp.pane == dst) { - try std.testing.expectEqualStrings("/tmp/pardes-image-dir", sp.cwd.slice()); - spawned = true; - }, - else => {}, - }; - try std.testing.expect(spawned); -} - -const FakeTtyQuery = struct { - taken: [MAX_PANES]bool = @splat(false), - asked: usize = 0, - - const vtable: Host.VTable = .{ .tty_taken = answer }; - - fn install(f: *FakeTtyQuery, p: *Pardes) void { - p.host = .{ .ctx = f, .vtable = &vtable }; - } - - fn answer(ctx: ?*anyopaque, pane: u8) bool { - const f: *FakeTtyQuery = @ptrCast(@alignCast(ctx.?)); - f.asked += 1; - return f.taken[pane]; - } -}; - -test "Exec in a terminal whose tty is taken runs as a command pane instead of typing at the program" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{}); - defer p.deinit(); - while (p.nextEffect()) |_| {} - - p.setCwd(0, "/tmp/pardes-taken"); - // vim, a pager, an agent: the host answers that this pane's tty is no - // longer the prompt pardes forked - var host: FakeTtyQuery = .{}; - host.install(p); - host.taken[0] = true; - const dst = exec.execute(p, 0, "echo taken-fallback") orelse return error.ExecFoundNowhereToRun; - // somewhere ELSE -- and still without moving focus, which is execute's - // contract and the whole difference between it and a look - try std.testing.expect(dst != 0); - try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqualStrings("echo taken-fallback", p.panes[dst].?.command.?); - var spawned = false; - while (p.nextEffect()) |effect| switch (effect) { - .write => return error.WroteACommandLineIntoATerminal, - .spawn => |sp| if (sp.pane == dst) { - // ...in the directory the command was about, the taken pane's own - try std.testing.expectEqualStrings("/tmp/pardes-taken", sp.cwd.slice()); - spawned = true; - }, - else => {}, - }; - try std.testing.expect(spawned); -} - -test "a command of several lines keeps its tag one row, and its echo does not staircase" { - 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 doc = try p.newDocPane(1); - doc.image = .{ .path = try gpa.dupe(u8, "/tmp/pic.ppm") }; - const two = "def greet(name):\n return name\n\nprint(greet(\"x\"))\n"; - const dst = exec.execute(p, 1, two) orelse return error.NoCommandPane; - while (p.nextEffect()) |_| {} - const pane = p.panes[dst].?; - const prefix = try tagline.tagPrefix(p, pane); - try std.testing.expect(std.mem.indexOfScalar(u8, prefix, '\n') == null); - try std.testing.expect(std.mem.indexOf(u8, prefix, "(def greet(name):...) running") != null); - // Rendered without a panic, however the tag wraps. - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - _ = try p.render(frame.allocator()); - p.update(.{ .exited = .{ .pane = @intCast(dst), .status = 0 } }); - _ = exec.execute(p, 1, two); - while (p.nextEffect()) |_| {} - _ = try p.render(frame.allocator()); - const body = try panes.terminal.screenTextAlloc(pane, gpa); - defer gpa.free(body); - try std.testing.expect(std.mem.indexOf(u8, body, "% def greet(name):\n return name") != null); -} - -test "a spawn is for the pane it was made for, not whatever took the slot since" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const Count = struct { - var spawns: usize = 0; - var command: [32]u8 = undefined; - var core: *Pardes = undefined; - const vtable: Host.VTable = .{ .spawn = spawn }; - fn spawn(_: ?*anyopaque, pane: u8, _: []const u8) void { - spawns += 1; - const line = core.panes[pane].?.command.?; - @memcpy(command[0..line.len], line); - } - }; - Count.core = p; - p.host = .{ .vtable = &Count.vtable }; - // A command pane closed and its slot taken, in one step, before the - // effects run: only the second's spawn is performed. - const slot = p.freeSlot().?; - _ = try panes.newCommand(p, slot, "", "first"); - try p.removePane(slot, null); - try std.testing.expectEqual(slot, p.freeSlot().?); - _ = try panes.newCommand(p, slot, "", "second"); - while (p.nextEffect()) |effect| p.perform(effect); - try std.testing.expectEqual(@as(usize, 1), Count.spawns); - try std.testing.expectEqualStrings("second", Count.command[0.."second".len]); -} - -test "a REPL bound for a language takes the exec made on a body in it; tags, Exec by name and command words still run" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .shells = 3, .cols = 100, .rows = 30 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const file = try p.setTestFile("print(1)\nls\n"); - gpa.free(file.file.?.path); - file.file.?.path = try gpa.dupe(u8, "/x.py"); - const Sent = struct { - var to: [MAX_PANES][128]u8 = undefined; - var len: [MAX_PANES]usize = @splat(0); - var spawned: bool = false; - fn drain(pp: *Pardes) void { - len = @splat(0); - spawned = false; - while (pp.nextEffect()) |effect| switch (effect) { - .write => |w| { - @memcpy(to[w.pane][len[w.pane]..][0..w.bytes.slice().len], w.bytes.slice()); - len[w.pane] += w.bytes.slice().len; - }, - .spawn => spawned = true, - else => {}, - }; - } - fn said(pane: usize) []const u8 { - return to[pane][0..len[pane]]; - } - }; - // The programs the REPLs run hold their terminals' ttys. - var host: FakeTtyQuery = .{}; - host.install(p); - host.taken[1] = true; - host.taken[2] = true; - // Only a terminal is a REPL; a language's name is the syntax table's. - try std.testing.expect(p.executeBuiltinLine(0, "Repl python")); - try std.testing.expect(file.repl == null); - try std.testing.expect(p.executeBuiltinLine(1, "Repl pithon")); - try std.testing.expect(p.panes[1].?.repl == null); - try std.testing.expect(std.mem.indexOf(u8, p.panes[1].?.msg[0..p.panes[1].?.msg_len], "python") != null); - try std.testing.expect(p.executeBuiltinLine(1, "Repl python")); - // again, as a code fence may name it: no change - try std.testing.expect(p.executeBuiltinLine(1, "Repl PY")); - var idbuf: [48]u8 = undefined; - try std.testing.expectEqualStrings("python-a", exec.replId(&idbuf, p.panes[1].?)); - try std.testing.expect(std.mem.endsWith(u8, try tagline.tagPrefix(p, p.panes[1].?), " python-a")); - Sent.drain(p); - - // A click on the file's body, a single word: typed into the REPL. - try std.testing.expectEqual(@as(?usize, 1), exec.executeFrom(p, 0, "ls", true)); - Sent.drain(p); - try std.testing.expectEqualStrings("ls\r", Sent.said(1)); - try std.testing.expect(!Sent.spawned); - try std.testing.expect(file.msg_sent); - try std.testing.expectEqualStrings("\u{2192} python-a", file.msg[0..file.msg_len]); - // A body's click written back to event is done as the click: sent. A - // line written to exec came back as F and runs as the command it was. - { - const th = @import("ninep/testing.zig"); - const event = ctlfs.Node.of(file.serial, .event); - const h = th.call(p, .{ .tag = 1, .op = .open, .node = event }).reply.handle; - defer _ = th.call(p, .{ .tag = 2, .op = .release, .node = event, .handle = h }); - // The 9P harness performs the effects: what it wrote is its answer's. - const sent = th.wr(p, event, "MX0 8\n"); - try std.testing.expectEqualStrings("print(1)\r", sent.pty_buf[0..sent.pty_len]); - const ran = th.wr(p, event, "FX0 0 2 2 ls\n"); - try std.testing.expect(ran.pty_len == 0 and ran.spawned); - // The pane's ctl line ends with the id it is bound as. - var line: [ctlfs.ctl.pane_text_cap]u8 = undefined; - try std.testing.expect(std.mem.indexOf(u8, ctlfs.ctl.paneText(p, p.panes[1].?, &line), " python-a ") != null); - } - // What is sent is plain text: CRLF is LF, no ESC or other control. - _ = exec.executeFrom(p, 0, "a = 1\r\nb = \x1b[201~2", true); - Sent.drain(p); - try std.testing.expectEqualStrings("a = 1\rb = [201~2\r", Sent.said(1)); - // Into a REPL that takes a bracketed paste (3.13's), the Enter waits - // for the REPL to answer the paste: read with it, it would be part of it. - p.update(.{ .output = .{ .pane = 1, .bytes = "\x1b[?2004h" } }); - Sent.drain(p); - _ = exec.executeFrom(p, 0, "print(1)", true); - Sent.drain(p); - try std.testing.expectEqualStrings("\x1b[200~print(1)\x1b[201~", Sent.said(1)); - p.update(.{ .output = .{ .pane = 1, .bytes = "print(1)" } }); - Sent.drain(p); - // Python's echo only restarts a short wait: the Enter goes once the - // echo of the whole paste has gone quiet. - try std.testing.expectEqualStrings("", Sent.said(1)); - p.now_ns = p.panes[1].?.repl_enter_due_ns; - p.update(.tick); - Sent.drain(p); - try std.testing.expectEqualStrings("\r", Sent.said(1)); - // A paste of more than one line gets the blank line a block gets. - _ = exec.executeFrom(p, 0, "print(11)\nprint(22)", true); - Sent.drain(p); - try std.testing.expectEqualStrings("\x1b[200~print(11)\nprint(22)\x1b[201~", Sent.said(1)); - p.now_ns = p.panes[1].?.repl_enter_due_ns; - p.update(.tick); - Sent.drain(p); - try std.testing.expectEqualStrings("\r\r", Sent.said(1)); - // Nothing answering, it goes when its wait is up. - _ = exec.executeFrom(p, 0, "print(2)", true); - p.update(.tick); // on the clock: not yet, however old core time is - Sent.drain(p); - try std.testing.expect(std.mem.endsWith(u8, Sent.said(1), "\x1b[200~print(2)\x1b[201~")); - p.now_ns = p.panes[1].?.repl_enter_due_ns; // the clock reaches its wait - p.update(.tick); - Sent.drain(p); - try std.testing.expectEqualStrings("\r", Sent.said(1)); - p.update(.{ .output = .{ .pane = 1, .bytes = "\x1b[?2004l" } }); - Sent.len[1] = 0; - // A block left open by its indented last line gets the blank line that - // ends it: a second Enter. - _ = exec.executeFrom(p, 0, "def f():\n return 1", true); - Sent.drain(p); - try std.testing.expectEqualStrings("def f():\r return 1\r\r", Sent.said(1)); - // Several selections executed at once: each is sent, not the first. - { - const text = try edit.flatSurface(p, &file.body); - file.body.setRanges(text, &.{ .{ .anchor = 0, .head = 8 }, .{ .anchor = 9, .head = 11 } }, &.{}, 0, true); - try std.testing.expect(exec.chordEachSel(p, file, .Exec)); - Sent.drain(p); - try std.testing.expectEqualStrings("print(1)\rls\r", Sent.said(1)); - } - // Its own body too. - try std.testing.expectEqual(@as(?usize, 1), exec.executeFrom(p, 1, "x = 1", true)); - Sent.drain(p); - try std.testing.expectEqualStrings("x = 1\r", Sent.said(1)); - - // Escapes: a tag's word, Exec by name, a command word. Each a command. - _ = exec.execute(p, 0, "ls"); - Sent.drain(p); - try std.testing.expect(Sent.spawned and Sent.len[1] == 0); - try std.testing.expect(p.executeBuiltinLine(0, "Exec ls")); - Sent.drain(p); - try std.testing.expect(Sent.spawned and Sent.len[1] == 0); - _ = exec.executeFrom(p, 0, "@`ls`", true); - Sent.drain(p); - try std.testing.expect(Sent.spawned and Sent.len[1] == 0); - - // Two bound: it asks, one key answers, Esc sends nowhere. - try std.testing.expect(p.executeBuiltinLine(2, "Repl python")); - try std.testing.expectEqualStrings("python-b", exec.replId(&idbuf, p.panes[2].?)); - Sent.drain(p); - try std.testing.expectEqual(@as(?usize, null), exec.executeFrom(p, 0, "print(2)", true)); - try std.testing.expectEqual(Pane.Prompt.repl_choice, file.prompt); - try std.testing.expect(std.mem.indexOf(u8, file.promptText().?, "a b") != null); - p.update(.{ .key = .{ .cp = 'b' } }); - Sent.drain(p); - try std.testing.expectEqualStrings("print(2)\r", Sent.said(2)); - try std.testing.expect(Sent.len[1] == 0 and file.prompt == .none); - // The question is in the log, and a script answers it on the ctl. - { - const th = @import("ninep/testing.zig"); - _ = exec.executeFrom(p, 0, "print(5)", true); - var want: [32]u8 = undefined; - try std.testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "ask {d} repl a b\n", .{file.serial}))); - // A choice not offered is refused, and the question stands. - const refused = th.wr(p, ctlfs.Node.of(file.serial, .ctl), "answer z\n"); - try std.testing.expectEqual(ctlfs.E.INVAL, refused.errno()); - try std.testing.expect(std.mem.endsWith(u8, refused.reply.ename, " \"z\"")); - try std.testing.expectEqual(Pane.Prompt.repl_choice, file.prompt); - const answered = th.wr(p, ctlfs.Node.of(file.serial, .ctl), "answer a\n"); - try std.testing.expectEqual(ctlfs.Status.ok, answered.reply.status); - try std.testing.expectEqualStrings("print(5)\r", answered.pty()); - try std.testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "answer {d} a\n", .{file.serial}))); - } - _ = exec.executeFrom(p, 0, "print(3)", true); - p.update(.{ .key = .{ .cp = Key.escape } }); - Sent.drain(p); - try std.testing.expect(Sent.len[1] == 0 and Sent.len[2] == 0); - // The pane a letter offered is the one it answers for: unbound while - // the question stood, it is sent nothing, and that is said. - _ = exec.executeFrom(p, 0, "print(4)", true); - try std.testing.expect(p.executeBuiltinLine(2, "Repl -")); - p.update(.{ .key = .{ .cp = 'b' } }); - Sent.drain(p); - try std.testing.expect(Sent.len[1] == 0 and Sent.len[2] == 0); - try std.testing.expectEqualStrings("Repl: the REPL chosen is gone; nothing sent", file.msg[0..file.msg_len]); - try std.testing.expect(p.executeBuiltinLine(2, "Repl python")); - try std.testing.expectEqualStrings("python-b", exec.replId(&idbuf, p.panes[2].?)); - - // A bound REPL whose program exited (Ctrl-D: the shell has the tty) is - // skipped: the one still running takes the text, no question asked; - // with none running, nothing runs and that is said. - host.taken[1] = false; - _ = exec.executeFrom(p, 0, "import os", true); - try std.testing.expectEqual(Pane.Prompt.none, file.prompt); - Sent.drain(p); - try std.testing.expectEqualStrings("import os\r", Sent.said(2)); - host.taken[2] = false; - _ = exec.executeFrom(p, 0, "import os", true); - try std.testing.expectEqual(Pane.Prompt.none, file.prompt); - Sent.drain(p); - try std.testing.expect(Sent.len[1] == 0 and Sent.len[2] == 0 and !Sent.spawned); - try std.testing.expect(std.mem.indexOf(u8, file.msg[0..file.msg_len], "no program running") != null); - host.taken[1] = true; - host.taken[2] = true; - - // Unbound, its letter is free again; bare, it says what it is. - try std.testing.expect(p.executeBuiltinLine(1, "Repl -")); - try std.testing.expect(p.panes[1].?.repl == null); - try std.testing.expect(p.executeBuiltinLine(1, "Repl python")); - try std.testing.expectEqualStrings("python-a", exec.replId(&idbuf, p.panes[1].?)); - try std.testing.expect(p.executeBuiltinLine(2, "Repl")); - try std.testing.expectEqualStrings("Repl: python-b", p.panes[2].?.msg[0..p.panes[2].?.msg_len]); - - // A command pane is a REPL while its command runs: done, it is none, - // and a done one cannot be bound. A document pane is no terminal. - const cmd = p.freeSlot().?; - _ = try panes.newCommand(p, cmd, "", "python3"); - try std.testing.expect(p.executeBuiltinLine(cmd, "Repl python")); - try std.testing.expect(p.panes[cmd].?.repl != null); - p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 0 } }); - try std.testing.expect(p.panes[cmd].?.repl == null); - try std.testing.expect(p.executeBuiltinLine(cmd, "Repl python")); - try std.testing.expect(p.panes[cmd].?.repl == null); - const doc_slot = p.freeSlot().?; - const doc = try p.newDocPane(doc_slot); - try std.testing.expect(p.executeBuiltinLine(doc_slot, "Repl python")); - try std.testing.expect(doc.repl == null); -} - -test "a restored terminal's tag names neither the REPL it was nor the shell it had" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - p.acknowledgeShell(0, "/usr/bin/fish", true); - var host: FakeTtyQuery = .{}; - host.install(p); - try std.testing.expect(p.executeBuiltinLine(0, "Repl python")); - try dump.dumpState(p); - const restored = try dump.restore(p, p.dump_out.?, "test"); - defer restored.deinit(); - const pane = restored.panes[0].?; - try std.testing.expect(pane.repl == null and pane.tag.own == null); - const shown = try tagline.tagText(restored, restored.scratch.allocator(), pane); - try std.testing.expect(std.mem.indexOf(u8, shown, "python-a") == null); - try std.testing.expect(std.mem.indexOf(u8, shown, "Term+fish") == null); -} - -test "a Term started by a shell's path keeps the path in its Term+ word" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - try std.testing.expect(p.executeBuiltinLine(0, "Term /bin/sh")); - try std.testing.expect(p.active != 0); - p.acknowledgeShell(p.active, "/bin/sh", false); - try std.testing.expect(std.mem.startsWith(u8, tagline.curTail(p.panes[p.active].?), " Term+/bin/sh ")); -} - -test "Tty, Term's old name in saved tags, runs as Term, bare and with its +shell" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - try std.testing.expect(p.executeBuiltinLine(0, "Tty+sh")); - try std.testing.expectEqualStrings("sh", p.panes[p.active].?.shell.?); - const first = p.active; - p.active = 0; - try std.testing.expect(p.executeBuiltinLine(0, "Tty")); - try std.testing.expect(p.active != 0 and p.active != first); -} - -test "Term+fish, one word a tag can hold, opens a terminal on that shell" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - // sh, the one shell every host has. - try std.testing.expect(p.executeBuiltinLine(0, "Term+sh")); - try std.testing.expect(p.active != 0); - try std.testing.expectEqualStrings("sh", p.panes[p.active].?.shell.?); - p.acknowledgeShell(p.active, "/bin/sh", false); - try std.testing.expect(std.mem.startsWith(u8, tagline.curTail(p.panes[p.active].?), " Term+sh ")); - p.active = 0; - // A shell that is not there is said, not quietly replaced, and the - // pane that asked gets no shell of its own. - const before = p.active; - const caller = p.panes[0].?; - try std.testing.expect(p.executeBuiltinLine(0, "Term /nonexistent")); - try std.testing.expect(p.active == before and caller.shell == null); - try std.testing.expect(std.mem.indexOf(u8, caller.msg[0..caller.msg_len], "shell \"/nonexistent\" not found") != null); - try std.testing.expect(p.executeBuiltinLine(0, "Term fsh-not-a-shell")); - try std.testing.expect(caller.shell == null); - // A directory passes access(X_OK); it is no shell either. - try std.testing.expect(p.executeBuiltinLine(0, "Term /etc")); - try std.testing.expect(p.active == before); - try std.testing.expect(std.mem.indexOf(u8, caller.msg[0..caller.msg_len], "Term: not a shell: /etc is a directory") != null); - // Only a word that says so splits at `+`: `Dump+x.zon` is no Dump. - try std.testing.expect(!p.executeBuiltinLine(0, "Dump+x.zon")); - try std.testing.expect(!p.executeBuiltinLine(0, "Msg+hello")); -} - -test "a command pane shows how its command ended, and the next command there runs below it" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{}); - defer p.deinit(); - while (p.nextEffect()) |_| {} - p.setCwd(0, "/tmp/pardes-cmd"); - const doc = try p.newDocPane(1); - doc.image = .{ .path = try gpa.dupe(u8, "/tmp/pardes-cmd/pic.ppm") }; - - const dst = exec.execute(p, 1, "make -j8") orelse return error.NoCommandPane; - while (p.nextEffect()) |_| {} - const pane = p.panes[dst].?; - // Its first command is echoed as every later one is. - { - const first = try panes.terminal.screenTextAlloc(pane, gpa); - defer gpa.free(first); - try std.testing.expect(std.mem.startsWith(u8, first, "% make -j8")); - } - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - try std.testing.expect(std.mem.endsWith(u8, try tagline.tagPrefix(p, pane), "(make -j8) running")); - // Running, a second command goes to a pane of its own. - const other = exec.execute(p, 1, "ls") orelse return error.NoCommandPane; - try std.testing.expect(other != dst); - while (p.nextEffect()) |_| {} - p.update(.{ .output = .{ .pane = @intCast(dst), .bytes = "compiled\r\n" } }); - // Its exit comes first, a job it left still printing: done, and not - // the next command's until its pty closes. - p.update(.{ .exited = .{ .pane = @intCast(dst), .status = 2 } }); - try std.testing.expect(pane.command_done and pane.command_pty); - const busy = exec.execute(p, 1, "true") orelse return error.NoCommandPane; - try std.testing.expect(busy != dst); - while (p.nextEffect()) |_| {} - // Its output ending: now it may be reused. - p.update(.{ .eof = .{ .pane = @intCast(dst) } }); - try std.testing.expect(p.panes[dst] == pane and !pane.command_pty); - try std.testing.expect(p.panes[dst] == pane); - try std.testing.expect(pane.command_done); - try std.testing.expect(std.mem.endsWith(u8, try tagline.tagPrefix(p, pane), "(make -j8) exit 2")); - // Kill leaves a finished one be. - try std.testing.expect(p.executeBuiltinLine(0, "Kill make")); - while (p.nextEffect()) |effect| if (effect == .signal_pty and effect.signal_pty.pane == dst) return error.SignalledAFinishedCommand; - // A program that crashed out of its full screen leaves the emulator - // in its modes; the next command starts clear of them. - p.update(.{ .output = .{ .pane = @intCast(dst), .bytes = "\x1b[?1049h\x1b[?2004h\x1b[?1000h" } }); - try std.testing.expect(panes.terminal.bracketedPaste(pane)); - // Done, the directory's next command runs there, below what it showed. - try std.testing.expectEqual(@as(?usize, dst), exec.execute(p, 1, "make test")); - try std.testing.expect(!panes.terminal.bracketedPaste(pane)); - var respawned = false; - while (p.nextEffect()) |effect| if (effect == .spawn and effect.spawn.pane == dst) { - respawned = true; - }; - try std.testing.expect(respawned); - const body = try panes.terminal.screenTextAlloc(pane, gpa); - defer gpa.free(body); - const said = std.mem.indexOf(u8, body, "compiled") orelse return error.OutputLost; - const ended = std.mem.indexOf(u8, body, "exit 2") orelse return error.ExitLost; - const next = std.mem.indexOf(u8, body, "% make test") orelse return error.NoSeparator; - try std.testing.expect(said < ended and ended < next); - try std.testing.expect(std.mem.endsWith(u8, try tagline.tagPrefix(p, pane), "(make test) running")); - // Kill stops a running one: its whole process group, SIGTERM. - try std.testing.expect(p.executeBuiltinLine(0, "Kill make")); - var signalled = false; - while (p.nextEffect()) |effect| if (effect == .signal_pty and effect.signal_pty.pane == dst) { - try std.testing.expectEqual(PtySignal.term, effect.signal_pty.sig); - signalled = true; - }; - try std.testing.expect(signalled); - // The log says what ran and how it ended. - const log = try ctlfs.events.freezeLog(p); - defer gpa.free(log.bytes); - var want: [64]u8 = undefined; - // The whole line, after the `new` of the pane it runs in. - const ran = std.mem.indexOf(u8, log.bytes, try std.fmt.bufPrint(&want, "run {d} make -j8\n", .{pane.serial})) orelse return error.NoRunRecord; - const made = std.mem.indexOf(u8, log.bytes, try std.fmt.bufPrint(&want, "new {d} ", .{pane.serial})) orelse return error.NoNewRecord; - try std.testing.expect(made < ran); - try std.testing.expect(std.mem.indexOf(u8, log.bytes, try std.fmt.bufPrint(&want, "exit {d} 2\n", .{pane.serial})) != null); - // A signal for a pane is not performed on whoever takes its slot. - const Count = struct { - var signals: usize = 0; - const vtable: Host.VTable = .{ .pty_signal = signal }; - fn signal(_: ?*anyopaque, _: u8, _: PtySignal) void { - signals += 1; - } - }; - const host_before = p.host; - p.host = .{ .vtable = &Count.vtable }; - try std.testing.expect(p.executeBuiltinLine(0, "Kill make")); - try p.removePane(dst, null); - _ = try panes.newCommand(p, dst, "", "other"); - while (p.nextEffect()) |effect| if (effect == .signal_pty) p.perform(effect); - try std.testing.expectEqual(@as(usize, 0), Count.signals); - p.host = host_before; - // A command line longer than a command pane takes is refused. - const long = &@as([exec.command_max + 1]u8, @splat('x')); - try std.testing.expectEqual(@as(?usize, null), exec.execute(p, 1, long)); -} - -test "image dump restores source bytes renderer choices and exact custom tail" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - try panes.deinitPane(p, p.panes[0].?); - p.panes[0] = null; - - const source = "\x00embedded image bytes\xff"; - const raw = try p.image_gpa.dupe(u8, source); - const pane = panes.Image.create(p, 0, "/missing/restored-image.ppm", raw) catch |err| { - p.image_gpa.free(raw); - return err; - }; - pane.image.?.glyph_art = true; - pane.image.?.pmode = .terminal; - pane.image.?.ascii = false; - if (pane.tag.own) |own| p.gpa.free(own); - pane.tag.own = try p.gpa.dupe(u8, " Keep Del"); - try dump.dumpState(p); - - const restored = try dump.initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?); - defer restored.deinit(); - const restored_pane = restored.panes[0].?; - try std.testing.expect(restored_pane.image.?.glyph_art); - try std.testing.expectEqual(image.PaletteMode.terminal, restored_pane.image.?.pmode); - try std.testing.expect(!restored_pane.image.?.ascii); - try std.testing.expect(restored_pane.tag.own != null); - try std.testing.expectEqualStrings(" Keep Del", tagline.curTail(restored_pane)); - try std.testing.expectEqualSlices(u8, source, restored_pane.image.?.raw); - - // And dumped again, its bytes still there. - try dump.dumpState(restored); - const again = try dump.load(gpa, .{ .tty_only = true }, restored.dump_out.?, null); - defer again.deinit(); - try std.testing.expectEqualSlices(u8, source, again.panes[0].?.image.?.raw); -} - -test "a terminal its program gave back takes command lines again" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{}); - defer p.deinit(); - while (p.nextEffect()) |_| {} - p.acknowledgeShell(0, "/bin/sh", false); - - p.setCwd(0, "/tmp/pardes-taken-flip"); - var host: FakeTtyQuery = .{}; - host.install(p); - host.taken[0] = true; - try std.testing.expect(exec.execute(p, 0, "echo while-taken") != 0); - while (p.nextEffect()) |_| {} - - // the program exited, so the host's answer changes — and the core asks - // again, because it never cached the old one - host.taken[0] = false; - try std.testing.expectEqual(@as(?usize, 0), exec.execute(p, 0, "echo after")); - var sent: [64]u8 = undefined; - var sent_len: usize = 0; - while (p.nextEffect()) |effect| switch (effect) { - .write => |w| { - try std.testing.expectEqual(@as(u8, 0), w.pane); - try std.testing.expect(w.bytes.slice().len <= sent.len - sent_len); - @memcpy(sent[sent_len..][0..w.bytes.slice().len], w.bytes.slice()); - sent_len += w.bytes.slice().len; - }, - .spawn => return error.SpawnedDespiteAPromptOfItsOwn, - else => {}, - }; - try std.testing.expectEqualStrings("echo after\r", sent[0..sent_len]); -} - -test "the host is asked about a tty only where a command line is about to go" { - const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - var frame = std.heap.ArenaAllocator.init(std.testing.allocator); - defer frame.deinit(); - - var host: FakeTtyQuery = .{}; - host.install(p); - p.setCwd(0, "/tmp/pardes-lazy-a"); - p.setCwd(1, "/tmp/pardes-lazy-b"); - p.setCwd(2, "/tmp/pardes-lazy-c"); - - _ = try p.render(frame.allocator()); - p.update(.{ .key = .{ .cp = 'x' } }); - p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = 4, .row = 4 } }); - p.update(.{ .resize = .{ .cols = 90, .rows = 28 } }); - while (p.nextEffect()) |_| {} - _ = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 0), host.asked); - - // The pane an Exec is typed into is one question, asked once... - _ = exec.execute(p, 0, "echo lazy"); - while (p.nextEffect()) |_| {} - try std.testing.expectEqual(@as(usize, 1), host.asked); - - // ...and a taken one is asked once too: the line then runs as a command - // pane, with no other terminal to ask about. - host.taken[0] = true; - host.asked = 0; - _ = exec.execute(p, 0, "echo lazy-again"); - while (p.nextEffect()) |_| {} - try std.testing.expectEqual(@as(usize, 1), host.asked); -} - -test "a host with no methods at all is a complete in-process pardes" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 10 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - - // A pump against the empty host renders a frame and blocks on nothing. - try p.pump(.{}); - try std.testing.expect(!p.quit); - - // the absent child is SILENT: the bytes are dropped, and nothing appears - // on the pane's screen to suggest a program answered - const before = p.panes[0].?.terminal.?.vt.screens.active.cursor.y; - p.perform(.{ .write = .{ .pane = 0, .bytes = .from("ls\r") } }); - try std.testing.expectEqual(before, p.panes[0].?.terminal.?.vt.screens.active.cursor.y); - - // the clipboard round-trips through the in-process one - p.registers.put(gpa, '+', "copied", 0, 1, true); - p.perform(.set_clipboard); - try std.testing.expectEqualStrings("copied", p.fallback.clipboard.items); - - // ...and a save with no filesystem lands in the virtual one - const doc = try p.setTestFile("body\n"); - var doc_id: u8 = 0; - for (p.panes, 0..) |slot, i| if (slot == doc) { - doc_id = @intCast(i); - }; - p.perform(.{ .save_file = .{ .pane = doc_id } }); - try std.testing.expectEqualStrings("body\n", p.fallback.files.get(doc.file.?.path).?); - - // a language backend nobody supplied answers nothing rather than hanging - p.perform(.{ .lsp = .{ .id = 7, .kind = .hover, .pane = doc_id, .offset = 0, .arg = .{} } }); - - p.perform(.quit); - try std.testing.expect(p.quit); -} - -test "Font keeps requested and acknowledged faces as separate plain state" { - if (comptime !font_picker) return; // there is no Font builtin on the tty - const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); - defer p.deinit(); - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - const installed = fonts.list(arena.allocator(), null); - if (installed.len == 0) return; // a machine with no monospace face at all - - var line: [512]u8 = undefined; - const cmd = try std.fmt.bufPrint(&line, "Font {s}", .{installed[0].name}); - try std.testing.expect(p.executeBuiltinLine(p.active, cmd)); - try std.testing.expect(p.settings.font.pending); - try std.testing.expectEqualStrings(installed[0].name, p.settings.font.requested_name.get()); - try std.testing.expectEqualStrings(installed[0].path, p.settings.font.requested_path.get()); - try std.testing.expectEqual(@as(u16, 0), p.settings.font.requested_size_hundredths); - try std.testing.expectEqualStrings("", p.settings.font.effective_name.get()); - - // Boot/zoom/display-scale reports describe the face already being drawn; - // they must neither answer nor reject the new request waiting beside it. - try std.testing.expect(p.observeFont("Embedded Mono", 1200, .pixels)); - try std.testing.expectEqualStrings("Embedded Mono", p.settings.font.effective_name.get()); - try std.testing.expect(p.settings.font.pending); - try std.testing.expect(!p.acknowledgeFont("Stray Ack", 1250, .pixels)); - p.rejectFont(); - try std.testing.expect(p.settings.font.pending); - - const request = p.takeFontRequest() orelse return error.MissingFontRequest; - try std.testing.expectEqualStrings(installed[0].path, request); - try std.testing.expect(p.settings.font.pending); - try std.testing.expect(p.takeFontRequest() == null); - try std.testing.expect(p.acknowledgeFont(installed[0].name, 1375, .pixels)); - try std.testing.expect(!p.settings.font.pending); - try std.testing.expectEqualStrings(installed[0].name, p.settings.font.effective_name.get()); - try std.testing.expectEqual(@as(u16, 1375), p.settings.font.effective_size_hundredths); - try std.testing.expectEqual(config.Runtime.FontSizeUnit.pixels, p.settings.font.effective_size_unit); - try std.testing.expect(!p.acknowledgeFont("Duplicate Ack", 1400, .pixels)); - - try std.testing.expect(p.executeBuiltinLine(p.active, cmd)); - _ = p.takeFontRequest() orelse return error.MissingRepeatedFontRequest; - try std.testing.expect(p.acknowledgeFont(installed[0].name, 1375, .pixels)); - - // A name nothing answers to changes neither request nor effective state. - try std.testing.expect(p.executeBuiltinLine(p.active, "Font zzz-no-such-face")); - try std.testing.expectEqualStrings(installed[0].name, p.settings.font.requested_name.get()); - try std.testing.expectEqualStrings(installed[0].name, p.settings.font.effective_name.get()); -} - -test "Font size suffix reaches native request and invalid input leaves it intact" { - if (comptime !font_picker) return; - const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); - defer p.deinit(); - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - const installed = fonts.list(arena.allocator(), null); - if (installed.len == 0) return; - var line: [512]u8 = undefined; - try std.testing.expect(p.executeBuiltinLine(p.active, try std.fmt.bufPrint(&line, "Font {s}:18.5", .{installed[0].name}))); - try std.testing.expectEqual(@as(u16, 1850), p.settings.font.requested_size_hundredths); - try std.testing.expectEqualStrings(installed[0].path, p.takeFontRequest().?); - try std.testing.expect(p.acknowledgeFont(installed[0].name, 1850, .pixels)); - try std.testing.expect(p.executeBuiltinLine(p.active, try std.fmt.bufPrint(&line, "Font {s}:nan", .{installed[0].name}))); - try std.testing.expectEqual(@as(u16, 1850), p.settings.font.requested_size_hundredths); - try std.testing.expect(p.takeFontRequest() == null); - try std.testing.expect(p.executeBuiltinLine(p.active, "Font zzz-no-such-face:20")); - try std.testing.expectEqual(@as(u16, 1850), p.settings.font.requested_size_hundredths); - try std.testing.expect(p.takeFontRequest() == null); - try std.testing.expect(p.executeBuiltinLine(p.active, try std.fmt.bufPrint(&line, "Font {s}", .{installed[0].name}))); - try std.testing.expectEqual(@as(u16, 0), p.settings.font.requested_size_hundredths); - try std.testing.expectEqual(@as(u16, 1850), p.settings.font.effective_size_hundredths); -} - -test "startup config overrides restored styling before initFromDump returns" { - const source = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme dark\n" }); - defer source.deinit(); - try std.testing.expectEqualStrings("dark", source.theme().name); - try dump.dumpState(source); - - const restored = try dump.initFromDump( - std.testing.allocator, - .{ .startup_config = "Theme acme\n" }, - source.dump_out.?, - ); - defer restored.deinit(); - try std.testing.expectEqualStrings("acme", restored.theme().name); - try std.testing.expect(!source.animationActive()); - try std.testing.expect(!restored.animationActive()); - try std.testing.expectEqual(ChromeTheme.fromTheme(source.theme()), source.chromeTheme().*); - try std.testing.expectEqual(ChromeTheme.fromTheme(restored.theme()), restored.chromeTheme().*); -} - -test "restored terminals keep monotonic nonzero pane identities" { - const gpa = std.testing.allocator; - const source = try Pardes.init(gpa, .{ .shells = 3 }); - defer source.deinit(); - // Filter is the pane's, and a dump keeps it: one toggled off comes back off. - source.panes[1].?.tty_filter = false; - try dump.dumpState(source); - - const restored = try dump.initFromDump(gpa, .{}, source.dump_out.?); - defer restored.deinit(); - - var ids: [MAX_PANES]usize = undefined; - var serials: [MAX_PANES]u32 = undefined; - var n: usize = 0; - for (restored.panes, 0..) |slot, id| { - const pane = slot orelse continue; - if (!pane.isTerminal()) continue; - try std.testing.expectEqual(id != 1, pane.tty_filter); - try std.testing.expect(pane.serial != 0); - for (serials[0..n]) |seen| try std.testing.expect(pane.serial != seen); - ids[n] = id; - serials[n] = pane.serial; - n += 1; - } - try std.testing.expectEqual(@as(usize, 3), n); - for (ids[0..n], serials[0..n]) |id, serial| - try std.testing.expectEqual(id, restored.paneBySerial(serial).?); - - const before = restored.next_serial; - const free = restored.freeSlot() orelse return error.NoFreePane; - const fresh = try restored.newShell(free, ""); - try std.testing.expect(fresh.tty_filter); - try std.testing.expectEqual(before + 1, fresh.serial); - try std.testing.expectEqual(fresh.serial, restored.next_serial); -} - fn chordName(comptime c: config.Chord) []const u8 { comptime { const mods = (if (c.ctrl) "C-" else "") ++ (if (c.alt) "A-" else "") ++ (if (c.shift) "S-" else ""); @@ -1655,2736 +439,13 @@ comptime { } } -test "Tab N draws every pane's tab N cells wide and clicks count past it; bare Tab says the width; the ctl read and a Dump keep it" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 }); - defer p.deinit(); - // The width is the process's: the next test starts from the default. - defer config.tab_now = config.tab_width; - const pane = try p.setTestFile("\tx = 1\n"); - try std.testing.expect(p.executeBuiltinLine(0, "Tab 8")); - try std.testing.expectEqual(@as(u16, 8), config.tab_now); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const surface = try p.render(frame.allocator()); - const rect = p.rects[0]; - const text_x = rect.x + config.GUTTER + config.PREFIX_W; - const body_y = rect.y + BOX_H; - try std.testing.expectEqualStrings("x", surface.at(text_x + 8, body_y).grapheme()); - // A click on the x is on its byte, past the tab. - p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = text_x + 8, .row = body_y } }); - p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = text_x + 8, .row = body_y } }); - try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); - // Bare, it says the width. - try std.testing.expect(p.executeBuiltinLine(0, "Tab")); - try std.testing.expectEqualStrings("Tab 8", pane.msg[0..pane.msg_len]); - // Out of range: refused, the width kept. - try std.testing.expect(p.executeBuiltinLine(0, "Tab 0")); - try std.testing.expectEqual(@as(u16, 8), config.tab_now); - // The ctl read's tab column, and a Dump's settings. - const ctl_text = @import("ninep/testing.zig").rd(p, ctlfs.Node.of(pane.serial, .ctl), 0, 4096).bytes; - try std.testing.expect(std.mem.indexOf(u8, ctl_text, " 8 ") != null); - try dump.dumpState(p); - const restored = try dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); - defer restored.deinit(); - try std.testing.expectEqual(@as(u16, 8), restored.settings.tab); - try std.testing.expectEqual(@as(u16, 8), config.tab_now); -} - -test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 }); - defer p.deinit(); - // Bold is an explicit preference; use it to expose the glyph boundaries. - try std.testing.expect(p.executeBuiltinLine(0, "SyntaxBold")); - const pane = try p.setTestFile("\treturn x\n"); - const f = &pane.file.?; - f.highlights = try p.tree_sitter_gpa.alloc(u8, f.content.len); - @memset(f.highlights, @backingInt(syntax.Syn.none)); - @memset(f.highlights[1..7], @backingInt(syntax.Syn.keyword)); - f.syntax_dirty = false; - pane.body.cur_row = 0; - pane.body.cur_col = 1; - - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const surface = try p.render(frame.allocator()); - const rect = p.rects[0]; - const text_x = rect.x + config.GUTTER + config.PREFIX_W; - const body_y = rect.y + BOX_H; - for (0..config.tab_width) |col| - try std.testing.expect(!surface.at(text_x + @as(u16, @intCast(col)), body_y).style.bold); - for (0.."return".len) |col| - try std.testing.expect(surface.at(text_x + config.tab_width + @as(u16, @intCast(col)), body_y).style.bold); - try std.testing.expectEqual(text_x + config.tab_width, surface.cursor.?.x); - - const click_x = text_x + config.tab_width + 2; - p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = click_x, .row = body_y } }); - p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = click_x, .row = body_y } }); - try std.testing.expectEqual(@as(i32, 3), pane.body.cur_col); - - const line = modal.lineSlice(f.content, 0); - const virtual: u16 = 3; - const blank_x = text_x + @as(u16, @intCast(panes.File.displayWidth(line))) + virtual; - p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = blank_x, .row = body_y } }); - p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = blank_x, .row = body_y } }); - try std.testing.expectEqual(@as(i32, @intCast(line.len)), pane.body.cur_col); - - _ = frame.reset(.retain_capacity); - const virtual_surface = try p.render(frame.allocator()); - try std.testing.expectEqual(blank_x - virtual, virtual_surface.cursor.?.x); - - const local_blank: i32 = @intCast(blank_x - rect.x - config.GUTTER); - try std.testing.expect(look.expandedSel(p, pane, .{ .state = .dragging, .c0 = local_blank, .c1 = local_blank, .r0 = BOX_H, .r1 = BOX_H }) == null); - - // The immediately-adjacent EOL cell and an in-line separator are blank - // too. Pointer expansion must not lean left into the preceding word. - const adjacent: i32 = @intCast(config.PREFIX_W + panes.File.displayWidth(line)); - try std.testing.expect(look.expandedSel(p, pane, .{ .state = .dragging, .c0 = adjacent, .c1 = adjacent, .r0 = BOX_H, .r1 = BOX_H }) == null); - const separator: i32 = @intCast(config.PREFIX_W + config.tab_width + "return".len); - try std.testing.expect(look.expandedSel(p, pane, .{ .state = .dragging, .c0 = separator, .c1 = separator, .r0 = BOX_H, .r1 = BOX_H }) == null); -} - -test "the workspace tag's Restore word names the last dump, the tag edited around it or not, across a Restore too" { - const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 20, .tty_only = true }); - defer p.deinit(); - p.setLastDump("/tmp/a.zon"); - // The tag edited: its own text holds the Restore word as it was then. - p.global_tag.own = try p.gpa.dupe(u8, try std.fmt.allocPrint(p.scratch.allocator(), "{s} Mine", .{tagline.headerDefault(p, .workspace)})); - p.setLastDump("/tmp/b.zon"); - try std.testing.expect(std.mem.indexOf(u8, p.global_tag.own.?, "Restore /tmp/b.zon Mine") != null); - try dump.dumpState(p); - const restored = try dump.restore(p, p.dump_out.?, "/tmp/c.zon"); - defer restored.deinit(); - try std.testing.expect(std.mem.indexOf(u8, restored.global_tag.own.?, "Restore /tmp/c.zon Mine") != null); - try std.testing.expectEqualStrings("/tmp/c.zon", restored.last_dump.?); -} - -test "editable workspace and column tags are typed into and persist" { - const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 20, .tty_only = true }); - defer p.deinit(); - _ = try p.setTestFile("untouched\n"); - p.presented(); - try std.testing.expectEqual(TOPBAR_H + COLBAR_H, p.rects[0].y); - // a sweep over a header is its selection, the caret where it ended - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = TAG_TEXT_INSET, .row = 0 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = TAG_TEXT_INSET + 6, .row = 0 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = TAG_TEXT_INSET + 6, .row = 0 } }); - try std.testing.expect(p.global_tag.vsel.active and p.global_tag.vsel.col == 0 and p.global_tag.cur_col == 6); - // A clicked header is in normal mode: `a` types after the sweep's - // last character, the blank it ended on. - p.update(.{ .key = .{ .cp = 'a', .text = "a" } }); - p.update(.{ .key = .{ .cp = 'H', .text = "Help " } }); - try std.testing.expect(std.mem.startsWith(u8, p.global_tag.own.?, "Newcol Help Joincol")); - p.update(.{ .key = .{ .cp = Key.escape } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); - p.update(.{ .key = .{ .cp = 'i', .text = "i" } }); - p.update(.{ .key = .{ .cp = 'é', .text = "é" } }); - try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, 0), "éNew")); - p.update(.{ .key = .{ .cp = Key.backspace } }); - try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, 0), "New")); - p.update(.{ .paste = "Grep " }); - try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, 0), "Grep New")); - try std.testing.expectEqualStrings("untouched\n", p.panes[0].?.file.?.content); - try dump.dumpState(p); - const restored = try dump.restore(p, p.dump_out.?, "test"); - defer restored.deinit(); - try std.testing.expectEqualStrings(p.global_tag.own.?, restored.global_tag.own.?); - try std.testing.expectEqualStrings(tagline.columnTag(p, 0), tagline.columnTag(restored, 0)); - p.gpa.free(p.col_tags[0].own.?); - p.col_tags[0].own = try p.gpa.dupe(u8, ""); - try dump.dumpState(p); - const empty = try dump.restore(p, p.dump_out.?, "test"); - defer empty.deinit(); - try std.testing.expectEqualStrings("", tagline.columnTag(empty, 0)); -} - -test "column tag first-cell execution keeps New local to the clicked column" { - const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 20, .tty_only = true }); - defer p.deinit(); - _ = try p.setTestFile("untouched\n"); - layout.newColumn(p, 0); - layout.newScratchIn(p, 0, layout.activeColumn(p).?); - p.sync(); - for (0..2) |column| { - p.active = p.col_panes[1 - column][0]; - p.presented(); - const before = p.col_n; - p.update(.{ .mouse = .{ .button = .middle, .kind = .press, .col = p.col_x[column] + TAG_TEXT_INSET, .row = TOPBAR_H } }); - p.update(.{ .mouse = .{ .button = .middle, .kind = .release, .col = p.col_x[column] + TAG_TEXT_INSET, .row = TOPBAR_H } }); - try std.testing.expectEqual(before[column] + 1, p.col_n[column]); - try std.testing.expectEqual(before[1 - column], p.col_n[1 - column]); - try std.testing.expectEqual(column, layout.findPane(p, p.active).?.col); - } - try std.testing.expectEqualStrings("untouched\n", p.panes[0].?.file.?.content); -} - -test "a screen too short for the column row releases a column tag's focus without losing its commands" { - const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12, .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("unchanged body\n"); - p.col_tags[0].own = try p.gpa.dupe(u8, "New Help"); - p.presented(); - const shown = p.rects[0]; - try std.testing.expectEqual(TOPBAR_H + COLBAR_H, shown.y); - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); - try std.testing.expect(p.header_focus and p.header_column != null); - - p.update(.{ .resize = .{ .cols = 60, .rows = 2 } }); - try std.testing.expectEqual(@as(u16, 0), layout.columnBarHeight(p)); - try std.testing.expectEqual(TOPBAR_H, p.rects[0].y); - try std.testing.expect(!p.header_focus and p.header_column == null); - p.update(.{ .resize = .{ .cols = 60, .rows = 12 } }); - try std.testing.expectEqual(shown, p.rects[0]); - try std.testing.expectEqualStrings("New Help", tagline.columnTag(p, 0)); - try std.testing.expectEqualStrings("unchanged body\n", pane.file.?.content); -} - /// Said at a focus-in when the Host's `newer_build` answers yes (upgrade.zig). pub const newer_build_words = "a newer pardes is installed: Upgrade (SPC s U) moves this session onto it"; -pub const PendingWrite = struct { bytes: []u8, off: usize = 0 }; - -test "screen resize keeps its previous storage until allocation succeeds" { - var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .cols = 80, .rows = 24, .tty_only = true }); - defer p.deinit(); - var frame: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer frame.deinit(); - const surface = try p.render(frame.allocator()); - const cells = surface.cells; - p.update(.{ .resize = .{ .cols = 81, .rows = 25 } }); - failing.fail_index = failing.alloc_index; - try std.testing.expectError(error.OutOfMemory, p.render(frame.allocator())); - try std.testing.expectEqual(cells.ptr, surface.cells.ptr); - try std.testing.expectEqual(cells.len, surface.cells.len); - try std.testing.expectEqual(@as(u16, 80), surface.cols); - try std.testing.expectEqual(@as(u16, 24), surface.rows); - failing.fail_index = std.math.maxInt(usize); - const resized = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(u16, 81), resized.cols); - try std.testing.expectEqual(@as(u16, 25), resized.rows); - try std.testing.expectEqual(@as(usize, 81 * 25), resized.cells.len); -} - pub const Rect = layout.Rect; -/// The session layouts `init` can put on screen. One name each, so choosing -/// between them reads as a choice instead of a chain of ifs over four options. -pub const Boot = enum { - /// the document named on the command line, or the pane explaining why not - document, - /// a Look that found nothing: reported, not opened - missing, - /// `pardes -`: stdin's text in a +Pager pane, as `vim -` shows it - stdin, - /// the bare tty startup: one shell in raw tty mode, with an empty text - /// pane under it so the editor half is there before you want it - tty, - /// that raw shell by itself, which is all a core booted for a test wants - tty_shell, - /// acme's boot: two columns, the left one split in two - classic, - /// one greeted shell - shell, - - pub fn of(opts: Options) Boot { - if (opts.boot) |named| return named; - if (opts.file != null) return .document; - if (opts.missing != null) return .missing; - if (opts.stdin_text != null) return .stdin; - if (opts.tty_only) return .tty_shell; - // ponytail: 1 and 3 are the only shell counts anyone asked for - return if (opts.shells >= 3) .classic else .shell; - } -}; - -pub const Options = struct { - tty_only: bool = false, - /// The first view's frontend is a window (`Pardes.windowed`), as a - /// window's build says: an option, taped with the rest, so that a - /// window's build replaying a terminal's session starts as it did. - windowed: bool = platform == .gui, - /// The layout to boot, when a host means one outright rather than leaving - /// it to be read off the options below. `--tty` names `.tty`; a core - /// booted for a test names nothing and gets `.tty_shell`. - boot: ?Boot = null, - /// initial shell panes: 1 (default) or 3 for the classic two-column boot. - /// A `file` outranks this — see there. - shells: u8 = 1, - file: ?[]const u8 = null, - file_line: usize = 0, - missing: ?struct { word: []const u8, dir: []const u8 } = null, - /// `pardes -`: stdin as it came, for a +Pager pane at boot (pager.zig - /// parses it). - stdin_text: ?[]const u8 = null, - tty_toggle: u21 = config.tty_toggle_default, - /// load a dump of another instance instead of spawning shells (acme -l) - load_path: ?[]const u8 = null, - /// `--geometry=WxH[+X+Y]`: a pixel shell's window size, and where it - /// goes when the display lets it say (a pane carried out of another - /// window opens one as big as that, Handover.zig). - geometry: ?[]const u8 = null, - nested: bool = false, - startup_config: ?[]const u8 = null, - ninep_name: []const u8 = "", - ninep_tcp: ?[]const u8 = null, - mounts: []const filesystem.Mount = &.{}, - config_dir: ?[]const u8 = null, - /// Where what outlives the session is kept (Db.zig): the user's state - /// file, set by a host that has one; none, Recent lasts as long as the - /// session; memory, the test host's. - state: Db.Kind = .off, - /// Where Recent's files were before the state file (0.24's `recent`, the - /// `store` before it): a state file that holds no Recent yet reads them - /// once (Db.zig). Set by a host that had them. - recent_import: ?[]const u8 = null, - startup_config_path: ?[]const u8 = null, - image_allocator: ?std.mem.Allocator = null, - pdf_allocator: ?std.mem.Allocator = null, - tree_sitter_allocator: ?std.mem.Allocator = null, - /// Where each frame's Surface text is built. Hosts pass a purpose-built - /// stack-fallback arena; null means the general allocator. - frame_allocator: ?std.mem.Allocator = null, - cols: u16 = 80, - rows: u16 = 24, -}; - -pub const Haptic = enum { none, exec, look }; - -/// Zero-sized off macOS, the way PdfSlot is off -Dmupdf: no other shell reads -/// the field, so no other shell carries it. -const HapticSlot = if (platform == .macos) Haptic else void; - -pub const RetiredPanes = struct { - current: [2 * MAX_PANES]?*Pane = @splat(null), - previous: [2 * MAX_PANES]?*Pane = @splat(null), - - pub fn retire(a: *RetiredPanes, pane: *Pane) void { - for (&a.current) |*slot| if (slot.* == null) { - slot.* = pane; - return; - }; - // One update runs one builtin, and the widest drop is a whole column; - // 2*MAX_PANES cannot fill in a single frame. - unreachable; - } -}; - -pub const Pardes = struct { - gpa: std.mem.Allocator, - image_gpa: std.mem.Allocator, - pdf_gpa: std.mem.Allocator, - tree_sitter_gpa: std.mem.Allocator, - opts: Options, - screen_w: u16, - screen_h: u16, - cell_pixels: CellPixels = .{}, - row_metrics: RowMetrics = .{}, - resize_count: usize = 0, - - panes: [MAX_PANES]?*Pane = @splat(null), - reserved_slots: [MAX_PANES]bool = @splat(false), - /// Deferred teardown of dropped panes (see RetiredPanes). - retired_panes: RetiredPanes = .{}, - // layout: columns own x by weight; panes own y by vweight within a column. - ncol: usize = 0, - col_weight: [MAX_COLS]u64 = @splat(column_weight_unit), - // Zeroed, not undefined: a digest takes the whole of it, a release - // build's heap leaves its unused slots whatever was there before, and - // two replicas must agree on them (src/replica.zig). - col_panes: [MAX_COLS][MAX_PANES]usize = @splat(@splat(0)), - col_n: [MAX_COLS]usize = @splat(0), - /// Each column's tag and the workspace's: Texts like a pane's tag, with - /// no prefix, showing a default until someone edits them. - col_tags: [MAX_COLS]Text = @splat(.{ .what = .column }), - col_serial: [MAX_COLS]u32 = @splat(0), - next_column_serial: u32 = 1, - /// The finder column, where query panes stack with SearchPlace column - /// (Finder.zig). - finder: Finder = .{}, - /// A pane or column on its way to another window (Handover.zig). - handover: Handover = .{}, - global_tag: Text = .{ .what = .workspace }, - // derived each sync - rects: [MAX_PANES]Rect = @splat(.{}), - col_x: [MAX_COLS]u16 = undefined, - col_w: [MAX_COLS]u16 = undefined, - - active: usize = 0, - /// The files opened lately, closed ones too (recent.zig): `Recent`, - /// /recent, and the jumplist's way back to a closed pane. - recent: recent_files.List = .{}, - /// The panes this session closed, which Panes brings back (Store.zig). - store: Store = .{}, - /// The user's state file, which every session shares: Recent's (Db.zig). - db: Db = .{}, - /// acme's Incl: the directories a look at a name that is nowhere else - /// (`stdio.h`, `<foo.h>`) is tried in, in order. The session's, seeded - /// with C's (/usr/include, /usr/local/include), kept in a dump. - incl: std.ArrayList([]u8) = .empty, - /// Zerox's groups of panes on one buffer (File.syncTwins), and the id - /// the next takes. - twin_groups: std.ArrayList(panes.File.TwinGroup) = .empty, - /// The buttons held as the 9P mousein file last said (Plan 9's bits: - /// 1 left, 2 middle, 4 right): its next line presses and releases - /// what changed. - mousein_buttons: u8 = 0, - next_twin: u32 = 1, - jumps: [MAX_JUMPS]Loc = undefined, - njumps: usize = 0, - jcur: usize = 0, - /// The next place tracked is an entry of its own however near the last - /// (a query answered: Ctrl-o goes back to where it was asked). - jump_force: bool = false, - look_src: [MAX_PANES]u32 = undefined, - n_look_src: usize = 0, - look_walk_owner: ?u32 = null, - /// hands out Pane.serial; monotonic, never reused - next_serial: u32 = 0, - /// The column whose tag the running command came from, while it runs: - /// the column acme's commands take from their Text's col. - exec_column: ?usize = null, - /// Panes made this step that found no room in their column - /// (exec.placeNew): closed at the step's end, once whatever made them - /// is done with them. - unplaced: std.StaticBitSet(MAX_PANES) = .empty, - /// A look's word search is running (look.lookUnresolved): from a - /// terminal its rows refill the directory's one +Search (Output). - word_look: bool = false, - /// The running word came from the workspace's or a column's tag, which - /// have no directory of their own: it runs in the session's - /// (`sessionDir`), as acme's row and column tags do. - exec_header: bool = false, - session_dir: [limits.host_path_cap]u8 = undefined, - /// A spawn's directory too long for the effect's inline buffer, by pane - /// slot: the effect then carries none, and perform gives the host this. - spawn_dirs: [MAX_PANES]?[]u8 = @splat(null), - session_dir_len: ?u16 = null, - /// acme's activecol (dat.c:37), by column serial, 0 for none: the - /// column last typed in (acme.c:487), clicked in with the select button - /// (acme.c:659), dropped into by a grip (acme.c:640), or given a new - /// pane (util.c:467). Where the acme placement puts new panes - /// (exec.placeNew). A Look click moves the keyboard but not this. - active_column: u32 = 0, - settings: config.Runtime = .{ .font = .{ .tagline_percent = config.gui_tagline_font_percent } }, - locations_config: locations.Config = .{}, - locations_cache: locations.Cache = .{}, - tty_filter_palette: panes.terminal.FilterPalette = .{}, - font_request_taken: bool = false, - custom_theme: ?Theme = null, - /// bodyChrome's: the theme it was worked out for, and it. - body_chrome: ?struct { theme: Theme, chrome: ChromeTheme } = null, - theme_file_path: config.Runtime.Text(limits.host_path_cap) = .{}, - /// The ThemeFile last loaded whole: what /ctl and DumpConfig name, and - /// what a failed ThemeFile goes back to (colors.revertThemeFile). - theme_file_loaded: config.Runtime.Text(limits.host_path_cap) = .{}, - theme_file_generation: u32 = 0, - theme_file_pane: u8 = 0, - chrome: colors.ChromeTheme = colors.initial_chrome, - /// Every drawn frame's timings (FrameStats: the Debug box, PARDES_FRAMES). - frames: FrameStats = .{}, - native_images: bool = false, - /// The shell can take a changed image a few rows at a time (a texture row - /// upload, a shared-memory hand-off), so a PDF selection is repainted as - /// it is dragged instead of once on release. - native_image_patches: bool = false, - quit: bool = false, - /// A detached session with no frontend attached: nothing renders, so - /// no input ever dismisses a message (Messages.expireUnattended). - unattended: bool = false, - haptic: HapticSlot = if (platform == .macos) .none else {}, - drag: mouse.Drag = .none, - /// A press a terminal's program took (mouse.programMouse): its drags - /// and release are the program's too, wherever the pointer goes. - mouse_grab: ?mouse.Grab = null, - /// Whether the host window has the keyboard (Event.focus), and the pane - /// whose program was last told it has it (reportFocus). - window_focused: bool = true, - focus_told: ?struct { id: usize, serial: u32 } = null, - hover_col: u16 = 0, - hover_row: u16 = 0, - pointer_raw_col: u16 = 0, - pointer_raw_row: u16 = 0, - pointer_body_hit: ?Mouse.BodyHit = null, - pointer_tag_hit: ?TagHit = null, - raw_hover_intent: bool = false, - pointer_inside: bool = false, - /// A pixel shell's window, which hears the pointer leave it: only then - /// does /status say whether the pointer is over it (a terminal's mouse - /// reports never say it left, so a tty would claim it for ever). - /// The live view's frontend is a window (Event.frontend): what it draws, - /// and the words it takes (builtins.zig `here`). It starts as - /// `Options.windowed` says. - windowed: bool = false, - /// The last plain B1 click, for acme's double-click (text.c:881, - /// textselect: a second click at the same point within 500 ms). - last_click: ?struct { id: usize, on_tag: bool, row: i32, col: i32, ms: i64 } = null, - /// The button an Alt- or Super-click of button 1 stands for, from its - /// press through its release (mouse.emulateButton). - click_as: ?Mouse.Button = null, - /// A B1 chord's edits share the undo point it took (mouse.zig). - chord_hold: bool = false, - /// The look just run found nothing (look.zig missed). - look_missed: bool = false, - /// The look being run opens a .diff or .patch as text, not its +Diff: - /// Diff going back from a +Diff, Edit's B (it edits the file). - look_text: bool = false, - look_hover_wait: ?look.LookHoverWait = null, - /// The place a look-hover last found nothing to open: the pointer - /// resting there does not ask again every frame (look.noteLookHover). - look_hover_refused: ?look.LookHoverWait = null, - look_hover_preview: ?look.LookHoverPreview = null, - pdf_hover_preview: if (pdf_enabled) ?look.PdfWordPreview else void = if (pdf_enabled) null else {}, - wheel_guard: u8 = 0, - ctrl_w_pending: bool = false, - /// While a key is replayed across the ranges (normal.replaySels): which - /// range this pass is, in document order, how many there are, and - /// whether this is the first pass; outside a replay, the one range and - /// its first pass. A register value belongs to its range by this index. - multi_first: bool = true, - multi_stop: bool = false, - multi_index: usize = 0, - multi_count: usize = 1, - /// The register the running normal command names (`"<reg>`); 0 for the - /// default one. - register: u21 = 0, - leader_on: bool = false, - /// Window mode's outlined pane (layout.windowKey); null outside it. - window_pick: ?usize = null, - leader_keys: [4]u8 = undefined, - leader_n: u8 = 0, - /// The keyboard is on a header: the column tag `header_column` names, or - /// the workspace's when that is null. - header_focus: bool = false, - header_column: ?usize = null, - /// A mouse sweep is extending the focused header's selection. - header_drag: bool = false, - /// A middle or right sweep held over a column's or the workspace's tag. - header_sweep: ?mouse.HeaderSweep = null, - header_scroll: usize = 0, - /// The focused header's first line on screen, which follows its caret - /// when it has more lines than rows. - header_top: usize = 0, - /// middle+left chord argument: a kept left selection captured by a left - /// press during an active middle select-drag; consumed on middle release - chord_arg: ?[]u8 = null, - /// how many `execute` calls are on the stack — see max_exec_depth - exec_depth: u8 = 0, - /// An exec waiting on the REPL question (`Pane.Prompt.repl_choice`): - /// the pane it came from, the language, and the text, owned. - /// `offered` holds, by letter, the serial of the pane each answer named - /// when asked: a letter answered later is that pane or nothing. - repl_ask: ?struct { from: u32, lang: u8, text: []u8, offered: [26]u32 = @splat(0) } = null, - /// A key press is being handled: someone is at the keyboard to answer, - /// so a builtin may ask rather than guess. Nothing else sets it -- not - /// a click, a 9P write, a startup line or a pane's shell exiting. - can_ask: bool = false, - - lsp_seq: u32 = 0, - /// The last query asked (Lspwhy explains it): its kind, argument, and - /// the pane and place it was asked at. - lsp_last: ?struct { kind: lsp.Kind, arg: Effect.Buf(128), serial: u32, offset: u32 } = null, - lsp_wait: ?struct { - id: u32, - kind: lsp.Kind, - pane: usize, - serial: u32, - revision: u32, - arg: Effect.Buf(128), - row: i32 = 0, - col: i32 = 0, - } = null, - - pipe: Pipe = .{}, - /// A query pane's Grep, and its Find's listing, on a worker (Stream.zig). - stream: Stream = .{}, - - fs: filesystem.Namespace = .{}, - boot: Boot = .shell, - /// Is there a frame worth drawing? Cleared once one is presented, set by - /// anything that can change what is on screen. The first frame always is. - needs_frame: bool = true, - /// Set by a shell whose present was skipped (no swapchain image): the - /// frame is still owed, and the next pump draws it again. - present_skipped: bool = false, - /// Core time. `now_ns` is the shell's monotonic clock as `advance` was - /// last given it; `stepped_ns` is how far its timings have been - /// stepped along it, in whole frames of `frame_ns`. Idle, the two are - /// the same instant. - now_ns: u64 = 0, - stepped_ns: u64 = 0, - clock_started: bool = false, - /// Builtins announce themselves on the message row. Off while startup - /// configuration is applied: those lines are nobody clicking, and should - /// not leave the row holding the name of the last one. - announce: bool = true, - - // Reject overflow: evicting an older effect would reorder a byte stream. - effects: [limits.effect_cap]Effect = undefined, - effects_head: usize = 0, - effects_len: usize = 0, - - // Each pty retains its own overflow tail until earlier effects drain. - pending_write: [MAX_PANES]?PendingWrite = @splat(null), - /// Total bytes parked above, so the drain path costs one comparison when - /// nothing is waiting — which is every frame that is not a large paste. - pending_write_bytes: usize = 0, - - /// WHO SERVES THIS CORE. Every method optional; a null one is answered by - /// `fallback` below, so a `Host{}` is a complete in-process pardes. - host: Host = .{}, - /// The in-program answers behind every unimplemented host method. Per - /// instance, so several cores behind one fan-out host stay independent. - fallback: host_io.Fallback, - /// The message-row log (see Messages.zig). - messages: Messages = .{}, - in_q: [64]Event = undefined, - in_head: usize = 0, - in_len: usize = 0, - - registers: Registers = .{}, - macro: Macro = .{}, - /// an edited text nothing kept (a tag's shown text): see edit.retireEditText - retired_edit: ?[]u8 = null, - clip_pending: ?edit.ClipRequest = null, - /// the last serialized dump (gpa-owned), read by the write_dump effect - dump_out: ?[]u8 = null, - /// Where the last Dump goes as a file of its own (`Dump export`; gpa- - /// owned), else the state file. - dump_export: ?[]u8 = null, - /// where the shell wrote the last dump (shell reports back after - /// write_dump); shown in the topbar as `Restore <path>` - last_dump: ?[]const u8 = null, - /// What a session word (Newcol, New, Exit) runs with when no pane is - /// there to run it: the window Delcol emptied. Never installed, made the - /// first time it is wanted. - stand_in: ?*Pane = null, - /// a Restore builtin wants this dump loaded into the live session; the - /// shell consumes it via takeRestore each frame (restore contents stay host-fed) - restore_req: ?[]const u8 = null, - restore_buf: [1024]u8 = @splat(0), - - surface: Surface = .{}, - /// A replica's predicted echo (src/echo.zig), drawn over its terminals: - /// presentation, its own, in no digest and no rollback copy. Null on a - /// session's own core. - echo: ?*echo.Echo = null, - /// The view the fields above are of: whose layout, focus, pointer and - /// panes' cursors and scroll (views.zig). `views_open` says which views - /// there are, one a window or terminal; each not live is in `parked`. - view: u8 = 0, - views_open: u8 = 1, - /// The open views kept for their clients' rejoin (views.away). - views_away: u8 = 0, - parked: [views.max]?*views.Parked = @splat(null), - /// The views no frontend here draws: a replica client's, which its own - /// process draws (src/replica.zig). A pump skips them. - undrawn: u8 = 0, - /// The Ctrl key into a terminal's tty mode and out (`--tty-toggle`): the - /// session's, taken from its options when it is made, so a dump carries - /// it to a replica, whose own options are its process's. - tty_toggle: u21 = config.tty_toggle_default, - /// per-update scratch (paneCursorLines, selection text); reset each update - scratch: std.heap.ArenaAllocator, - /// The arena each frame's Surface text is built in, reset by `pump`. Hosts - /// that still own their loop pass their own arena to `render` instead. - frame_arena: std.heap.ArenaAllocator, - /// the terminal motion surface, memoized against the pane it was built - /// for — see panes.terminal.RowsCache for the lifetime rule - shell_rows: panes.terminal.RowsCache = .{}, - /// Finished command panes' output, and whether it is a diff - /// (File.DiffOutput). - diff_output: panes.File.DiffOutput = .{}, - - /// What the replay digest leaves out (src/walk.zig): what drawing - /// keeps, what is recomputed, and what only the session that performs - /// effects has. - pub const replica = .{ - .local = .{ - // A frame, and the timings that make it. - "surface", "frames", "chrome", - "frame_arena", "scratch", - "needs_frame", "present_skipped", "native_image_patches", - "echo", - // Drained by every pump before its digest; a replica's queues - // are its own. - "effects", "effects_head", "effects_len", "in_q", "in_head", "in_len", - // The views not live: written whenever one goes out, so the - // live one's slot is stale (views.zig). - "parked", "undrawn", - // How this process was started, and the last dump it made for - // its host to write: a session loaded elsewhere has its own. - "opts", "dump_out", "dump_export", - }, - .derived = .{ "shell_rows", "diff_output", "locations_cache", "retired_panes", "tty_filter_palette", "body_chrome" }, - // The host's handles, the 9P server's fids and log, the state file - // every session of the user shares (and Recent read from it), this - // session's closed panes, and the files of a host with no file - // system of its own. - .authority = .{ "host", "fs", "store", "recent", "db", "fallback" }, - .len = .{ .{ "jumps", "njumps" }, .{ "look_src", "n_look_src" }, .{ "leader_keys", "leader_n" }, .{ "col_x", "ncol" }, .{ "col_w", "ncol" }, .{ "session_dir", "session_dir_len" } }, - }; - - /// The message row's entry points, called from everywhere as - /// `p.setMessage(...)`; they live with the rest of it in Messages.zig. - pub const setStatus = Messages.setStatus; - pub const setMessage = Messages.setMessage; - pub const reportError = Messages.reportError; - pub const reportFailure = Messages.reportFailure; - - /// Running a builtin line, called from everywhere as - /// `p.executeBuiltinLine(...)`; it lives with the rest of exec in exec.zig. - pub const executeBuiltinLine = exec.executeBuiltinLine; - - /// Geometry, called from everywhere as `p.bodyTop(pane, r)` and the rest - /// (setActiveColumn and tagTop by Store.zig and Handover.zig); it lives with the - /// columns in layout.zig. - pub const topBarHeight = layout.topBarHeight; - pub const bodyTop = layout.bodyTop; - pub const tagTop = layout.tagTop; - pub const setActiveColumn = layout.setActiveColumn; - - /// Pane slots, called from everywhere as `p.freeSlot()` and the rest - /// (emitSpawn and installPane by dump.zig); they live with the panes - /// in panes.zig. - pub const emitSpawn = panes.emitSpawn; - pub const installPane = panes.installPane; - pub const newShell = panes.newShell; - pub const newDocPane = panes.newDocPane; - pub const newScratchBelow = panes.newScratchBelow; - pub const freeSlot = panes.freeSlot; - pub const paneBySerial = panes.paneBySerial; - pub const setTestFile = panes.setTestFile; - pub const paneDir = panes.paneDir; - pub const removePane = panes.removePane; - - /// A language word's request, called from every word and test as - /// `p.lspRequest(...)`; it lives with its answer in lsp/Ask.zig. - pub const lspRequest = @import("lsp/Ask.zig").lspRequest; - - /// Performing an effect, called from every host and test as - /// `p.perform(e)`; it lives with the effects in Effect.zig. - pub const perform = @import("Effect.zig").perform; - - /// The one construction of a session, empty: its allocators, its column - /// and workspace tags, the 9P tree's clock and its mounts. `init` boots - /// a layout into it and a dump's restore (dump.initDump) its panes; a - /// second copy of this drifted once, leaving restored tags without an - /// allocator and every 9P mtime 0. - pub fn create(gpa: std.mem.Allocator, opts: Options) !*Pardes { - const p = try gpa.create(Pardes); - p.* = .{ - .gpa = gpa, - .image_gpa = opts.image_allocator orelse gpa, - .pdf_gpa = opts.pdf_allocator orelse gpa, - .tree_sitter_gpa = opts.tree_sitter_allocator orelse gpa, - .opts = opts, - .windowed = opts.windowed, - .tty_toggle = opts.tty_toggle, - .col_tags = @splat(.{ .what = .column, .gpa = gpa }), - .global_tag = .{ .what = .workspace, .gpa = gpa }, - .fs = .{}, - .screen_w = opts.cols, - .screen_h = opts.rows, - .scratch = .init(gpa), - .frame_arena = .init(opts.frame_allocator orelse gpa), - .fallback = .{ .gpa = gpa }, - .db = .{ .kind = opts.state }, - }; - errdefer p.deinit(); - p.fs.started = ctlfs.events.now(); - for (opts.mounts) |mount| try p.fs.mount(gpa, mount.name, mount.dial); - p.opts.mounts = &.{}; - return p; - } - - /// A new session, its tape written from here when PARDES_RECORD asks. - pub fn init(gpa: std.mem.Allocator, opts: Options) !*Pardes { - tape.startFromEnv(); - const taped = tape.enter(null, .{ .init = opts }); - const p = initSession(gpa, opts) catch |err| { - tape.leave(null, taped); - return err; - }; - tape.leave(p, taped); - return p; - } - - fn initSession(gpa: std.mem.Allocator, opts: Options) !*Pardes { - // A new session draws a tab at the default until `Tab` says otherwise. - config.tab_now = config.tab_width; - const p = try create(gpa, opts); - errdefer p.deinit(); - p.boot = Boot.of(opts); - // Asked once, at the start, whoever asks first after. - _ = p.sessionDir(); - switch (p.boot) { - .document => { - const path = opts.file.?; - const opened = initial_doc: { - if (comptime pdf_enabled) if (look.isPdfPath(path)) - break :initial_doc panes.Pdf.openPane(p, 0, path, opts.file_line, .last); - if (look.isImagePath(path)) - break :initial_doc panes.Image.create(p, 0, path, &.{}); - break :initial_doc panes.File.open(p, 0, path, opts.file_line); - }; - if (opened) |_| {} else |err| { - if (err == error.OutOfMemory) return err; - const why = switch (@as(anyerror, err)) { - error.PermissionDenied => "permission denied", - error.FileNotFound => "no file of that name", - error.IsDirectory => "that is a directory, and not one that could be read", - error.PathTooLong => "that path is too long", - error.FileTooLarge => "that file is too large to open", - error.NotAFile => "that is a pipe or a device, not a document", - else => @errorName(err), - }; - const content = try std.fmt.allocPrint(gpa, "cannot open\n\n\t{s}\n\n{s}\n", .{ path, why }); - errdefer gpa.free(content); - _ = try panes.Output.open(p, 0, std.fs.path.dirname(path) orelse "/", .errors, "", content); - } - p.oneColumn(); - }, - .missing => { - const missing = opts.missing.?; - const content = try std.fmt.allocPrint( - gpa, - "file or directory not found\n\n\t{s}\n", - .{missing.word}, - ); - errdefer gpa.free(content); - _ = try panes.Output.open(p, 0, missing.dir, .errors, "", content); - p.oneColumn(); - }, - .stdin => { - const page = try pager.parse(gpa, opts.stdin_text.?, p.settings.pager_color); - errdefer gpa.free(page.spans); - const content = page.text; - errdefer gpa.free(content); - const dir = p.sessionDir(); - const shown = try panes.Output.open(p, 0, dir, .{ .cmd = .New }, "", content); - // Named +Pager, as `pardes -` inside a session names its pane. - const named = try std.fs.path.join(gpa, &.{ dir, "+Pager" }); - gpa.free(shown.file.?.path); - shown.file.?.path = named; - shown.file.?.pager = true; - shown.tty_filter = true; - shown.file.?.pager_diff = panes.File.looksLikeDiff(content[0..@min(content.len, 64 * 1024)]); - shown.file.?.pager_spans = page.spans; - p.oneColumn(); - }, - .tty, .tty_shell => { - _ = try p.newShell(0, ""); - p.panes[0].?.body.mode = .tty; - p.oneColumn(); - // A bare tty is still an editor: it opens with somewhere to put - // text under the shell. The shell keeps the keyboard. A boot - // layout, like .classic's, not a placement. - if (p.boot == .tty) { - const np = try panes.newScratch(p, 0, 1, .scratch); - layout.insert(p, 0, 1, 1); - layout.splitBelow(p, 0, np); - } - }, - .classic => { - _ = try p.newShell(0, ""); - _ = try p.newShell(1, ""); - _ = try p.newShell(2, ""); - for (p.panes[0..3]) |slot| slot.?.greet = true; - p.ncol = 2; - p.col_n[0] = 2; - p.col_panes[0][0] = 0; - p.col_panes[0][1] = 1; - p.col_n[1] = 1; - p.col_panes[1][0] = 2; - }, - .shell => { - _ = try p.newShell(0, ""); - p.panes[0].?.greet = true; - p.oneColumn(); - }, - } - p.sync(); - for (config.default_incl) |dir| { - const copy = try gpa.dupe(u8, dir); - p.incl.append(gpa, copy) catch |err| { - gpa.free(copy); - return err; - }; - } - exec.applyStartupConfig(p); - // After the startup config, whose DumpDir says where the state file is. - p.loadRecent(); - colors.finishThemeInitialization(p); - p.sync(); - // A config init that opens a file with `Look …` armed the pulse before - // anyone touched anything. Nobody asked for that, so boot is silent. - _ = p.takeHaptic(); - // The ring is reserved whole now, so recording never allocates later. - try p.fs.log.buf.ensureTotalCapacityPrecise(p.gpa, p.fs.log.cap); - ctlfs.events.announce(p); // /log starts with the panes it booted with - return p; - } - - /// The layout every single-pane boot starts from. - fn oneColumn(p: *Pardes) void { - p.ncol = 1; - p.col_n[0] = 1; - p.col_panes[0][0] = 0; - } - - /// The recent list's own allocator: it is kept best effort (a file not - /// remembered for want of memory is no failure of what opened it), so - /// on a host it takes from the process heap, not the editor's, whose - /// every failure must be answered. - // ponytail: a host heap for a best-effort list. - pub fn recentGpa(_: *const Pardes) std.mem.Allocator { - return std.heap.smp_allocator; - } - - /// Recent read from the state file once at start: a new session's. - pub fn loadRecent(p: *Pardes) void { - // A replica's Recent is its own, in memory: the recording session's - // state file is every session's of its user (src/tape.zig). - if (tape.replaying()) p.db.kind = .off; - p.db.readRecent(p); - } - - /// What changed written out, at the end of a step and at the end. - pub fn saveRecent(p: *Pardes) void { - p.db.writeRecent(p, false); - } - - /// Whether `path` is one Recent keeps: a file on this host's disk, not - /// the served tree's (`/virtual/`) nor a name never saved. - pub fn recentKeeps(path: []const u8) bool { - const local = filesystem.localPath(path) orelse return false; - return exec.kindOf(local) == .file; - } - - /// A file, PDF or image pane closing: its place noted in Recent, when - /// Recent keeps it. - pub fn noteClosed(p: *Pardes, pane: *const Pane) void { - const d = recentPlace(pane) orelse return; - // The host asked first, always: what Recent holds is the - // authority's, and a step that asked only when it did not know the - // file would ask on one side and not the other. - if (!recentKeeps(d.path) and p.recent.get(d.path) == null) return; - p.recent.closed(p.recentGpa(), d.path, d.line, d.col, d.aline, d.acol); - } - - pub const RecentPlace = struct { path: []const u8, line: u32, col: u32, aline: u32 = 0, acol: u32 = 0 }; - - /// Where a pane is, as Recent keeps it: a file's dot, a PDF's page - /// (`:page:1`), an image's path alone (line 0). Null for any other. - pub fn recentPlace(pane: *const Pane) ?RecentPlace { - if (recentDot(pane)) |d| return .{ .path = d.path, .line = d.line, .col = d.col, .aline = d.aline, .acol = d.acol }; - if (pane.pdfPath()) |path| return .{ .path = path, .line = @intCast(pane.pdfPage().? + 1), .col = 1 }; - if (pane.image) |iv| return .{ .path = iv.path, .line = 0, .col = 0 }; - return null; - } - - /// A file pane's path and dot, for the recent list (0 when none). - pub fn recentDot(pane: *const Pane) ?struct { path: []const u8, line: u32, col: u32, aline: u32 = 0, acol: u32 = 0 } { - const f = pane.file orelse return null; - if (f.output != null) return null; - // The selection's anchor too, so a reopen restores both its ends. - const sel = pane.body.vsel.active; - return .{ - .path = f.path, - .line = @intCast(@max(0, pane.body.cur_row) + 1), - .col = @intCast(@max(0, pane.body.cur_col) + 1), - .aline = if (sel) @intCast(@max(0, pane.body.vsel.row) + 1) else 0, - .acol = if (sel) @intCast(@max(0, pane.body.vsel.col) + 1) else 0, - }; - } - - /// The session's configuration directory and startup file, as a step - /// reads them: its process's options, so the authority's - /// (`tape.authority`); a replica's are its own process's. - pub fn configDir(p: *Pardes) ?[]const u8 { - return tape.authority(optsConfigDir, .{p}); - } - - pub fn startupPath(p: *Pardes) ?[]const u8 { - return tape.authority(optsStartupPath, .{p}); - } - - fn optsConfigDir(p: *Pardes) ?[]const u8 { - return p.opts.config_dir; - } - - fn optsStartupPath(p: *Pardes) ?[]const u8 { - return p.opts.startup_config_path; - } - - /// The recent entry a closed jump names, by its path's hash, its path - /// in scratch. Recent is the authority's (every window of its user - /// writes it): a replica has its answer (`tape.authority`). - pub fn recentByHash(p: *Pardes, hash: u64) ?recent_files.Entry { - return tape.authority(recentFound, .{ p, hash }); - } - - fn recentFound(p: *Pardes, hash: u64) ?recent_files.Entry { - for (p.recent.entries.items) |e| if (std.hash.Wyhash.hash(0, e.path) == hash) { - var found = e; - found.path = p.scratch.allocator().dupe(u8, e.path) catch return null; - return found; - }; - return null; - } - - pub fn deinit(p: *Pardes) void { - const taped = tape.enter(p, .{ .deinit = tape.current(p) }); - tape.forget(p); - defer tape.leave(null, taped); - if (std.c.getenv("PARDES_FRAMES")) |path| p.frames.dump(std.mem.span(path)); - // Every file open now is closed with its dot, and the list kept. - for (p.panes) |slot| if (slot) |pane| p.noteClosed(pane); - p.db.writeRecent(p, true); - // The state file compacted once it is mostly what no moment holds. - p.db.compact(p); - p.db.deinit(); - p.store.deinit(p.recentGpa()); - p.recent.deinit(p.recentGpa()); - for (p.incl.items) |dir| p.gpa.free(dir); - p.incl.deinit(p.gpa); - for (p.twin_groups.items) |group| p.gpa.free(group.path); - p.twin_groups.deinit(p.gpa); - p.fs.batch.bytes.deinit(p.gpa); - if (p.stand_in) |pane| panes.teardownPane(p, pane); - look.cancelLookHover(p); - if (p.repl_ask) |ask| p.gpa.free(ask.text); - for (0..MAX_PANES) |id| p.dropPendingWrite(id); - // The panes, then those retired these last two frames. - inline for (.{ &p.panes, &p.retired_panes.previous, &p.retired_panes.current }) |slots| for (slots) |*slot| if (slot.*) |pane| { - panes.teardownPane(p, pane); - slot.* = null; - }; - const gpa = p.gpa; - views.deinit(p); - for (&p.col_tags) |*t| t.deinit(gpa); - p.global_tag.deinit(gpa); - p.registers.deinit(gpa); - p.macro.deinit(gpa); - if (p.retired_edit) |r| gpa.free(r); - if (p.dump_out) |d| gpa.free(d); - if (p.dump_export) |d| gpa.free(d); - p.fallback.deinit(); - if (p.last_dump) |d| gpa.free(d); - if (p.custom_theme) |theme_value| gpa.free(theme_value.name); - if (p.chord_arg) |a| gpa.free(a); - for (p.spawn_dirs) |d| if (d) |dir| gpa.free(dir); - p.pipe.deinit(gpa); - p.stream.deinit(gpa); - p.handover.deinit(gpa); - if (p.stream.ahead.len > 0) p.tree_sitter_gpa.free(p.stream.ahead); - p.locations_cache.deinit(p.tree_sitter_gpa); - p.fs.deinit(gpa); - p.shell_rows.reset(gpa); - p.diff_output.reset(gpa); - p.scratch.deinit(); - p.frame_arena.deinit(); - gpa.free(p.surface.cells); - for (&p.surface.body_layers) |*layer| gpa.free(layer.cells); - for (&p.surface.tag_layers) |*layer| gpa.free(layer.cells); - p.surface.images.deinit(gpa); - gpa.destroy(p); - } - - /// shell feedback after write_dump: remember where the dump landed (the - /// topbar grows a `Restore <path>` word pointing at it) - pub fn setLastDump(p: *Pardes, path: []const u8) void { - const taped = tape.enter(p, .{ .set_last_dump = path }); - defer tape.leave(p, taped); - p.pointRestoreAt(path); - ctlfs.events.notePath(p, "dump", path); - } - - /// The workspace tag's `Restore <path>` names `path` from now on: the - /// default's does by itself, and one the tag was edited around (its own - /// text) has the old path swapped, never left pointing at a dump that is - /// not the last. - pub fn pointRestoreAt(p: *Pardes, path: []const u8) void { - const copy = p.gpa.dupe(u8, path) catch return; - if (p.last_dump) |old| { - if (p.global_tag.own) |own| swap: { - const a = p.scratch.allocator(); - const was = std.fmt.allocPrint(a, "Restore {s}", .{old}) catch break :swap; - if (std.mem.indexOf(u8, own, was) == null) break :swap; - const now = std.fmt.allocPrint(a, "Restore {s}", .{path}) catch break :swap; - const swapped = std.mem.replaceOwned(u8, p.gpa, own, was, now) catch break :swap; - p.gpa.free(own); - p.global_tag.own = swapped; - } - p.gpa.free(old); - } - p.last_dump = copy; - } - - /// the shell polls this each frame: a pending Restore's dump path, or null - pub fn takeRestore(p: *Pardes) ?[]const u8 { - const taped = tape.enter(p, .take_restore); - defer tape.leave(p, taped); - const r = p.restore_req; - p.restore_req = null; - return r; - } - - /// DECSET 1004: a program that asked is told `CSI I` when its pane - /// takes the keyboard (the active pane, its body, the window focused) - /// and `CSI O` when it gives it up, to another pane, a tag or header, - /// or another window. - fn reportFocus(p: *Pardes) void { - const want: @FieldType(Pardes, "focus_told") = blk: { - if (!p.window_focused or p.header_focus) break :blk null; - const pane = p.panes[p.active] orelse break :blk null; - if (pane.focus != .body) break :blk null; - break :blk .{ .id = p.active, .serial = pane.serial }; - }; - if (std.meta.eql(want, p.focus_told)) return; - if (p.focus_told) |old| if (p.panes[old.id]) |pane| { - if (pane.serial == old.serial and panes.terminal.reportsFocus(pane)) p.emitWrite(old.id, "\x1b[O"); - }; - if (want) |new| if (panes.terminal.reportsFocus(p.panes[new.id].?)) p.emitWrite(new.id, "\x1b[I"); - p.focus_told = want; - } - - pub fn emitWrite(p: *Pardes, id: usize, bytes: []const u8) void { - var off: usize = 0; - // Anything already parked for this pane owns the stream's position, so - // new bytes queue BEHIND it — emitting them now would reorder the pty. - if (p.pending_write[id] == null) { - while (off < bytes.len and p.effects_len < p.effects.len) { - const n = @min(bytes.len - off, effect_write_cap); - p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(bytes[off .. off + n]) } }); - off += n; - } - } - if (off < bytes.len) p.parkPendingWrite(id, bytes[off..]); - } - - /// How many bytes `emitWrite` can take for pane `id` now without - /// dropping any: the effects left, then what the pending buffer holds. - pub fn writeRoom(p: *const Pardes, id: usize) usize { - const pending = limits.pending_write_cap -| p.pending_write_bytes; - if (p.pending_write[id] != null) return pending; - return (p.effects.len - p.effects_len) * effect_write_cap + pending; - } - - pub fn parkPendingWrite(p: *Pardes, id: usize, bytes: []const u8) void { - if (p.pending_write_bytes + bytes.len > limits.pending_write_cap) return; - if (p.pending_write[id]) |*pw| { - // Compact what the drain already sent before growing: a burst that - // arrives in pieces must not keep re-copying bytes nobody wants. - const keep = pw.bytes.len - pw.off; - const grown = p.gpa.alloc(u8, keep + bytes.len) catch return; - @memcpy(grown[0..keep], pw.bytes[pw.off..]); - @memcpy(grown[keep..], bytes); - p.gpa.free(pw.bytes); - pw.* = .{ .bytes = grown }; - } else { - p.pending_write[id] = .{ .bytes = p.gpa.dupe(u8, bytes) catch return }; - } - p.pending_write_bytes += bytes.len; - } - - /// The shell reports the spawned pane's working directory (and later cwd - /// changes it observes, e.g. via /proc/<pid>/cwd before each frame). - pub fn setCwd(p: *Pardes, id: usize, cwd: []const u8) void { - const taped = tape.enter(p, .{ .set_cwd = .{ .id = id, .cwd = cwd } }); - defer tape.leave(p, taped); - const pane = p.panes[id] orelse return; - // A command pane stays the directory's it was run for (newCommand). - if (pane.command != null) return; - const cur = switch (pane.cwd) { - .owned => |dir| dir, - else => "", - }; - if (std.mem.eql(u8, cur, cwd)) return; - // A shell started in a directory is asked where it is before it has - // said anything: its chdir may not have happened yet, and the answer - // is this process's directory, a rename to undo. That answer, then, - // is not taken. - if (pane.isTerminal() and !pane.shell_spoke and pane.cwd == .owned and std.mem.eql(u8, cwd, p.sessionDir())) return; - // One with no directory yet is named by the session's (nameOf): its - // shell saying it is there is no new name. - const same_name = cur.len == 0 and std.mem.eql(u8, cwd, p.sessionDir()); - pane.setOwnedCwd(cwd) catch |err| return p.reportError(id, "directory", err); - if (look.lookHoverPane(p) == id) look.cancelLookHover(p); - // A terminal is named by its directory, so /log hears it renamed; one - // not announced yet is announced under the new name. - if (pane.isTerminal() and !same_name) ctlfs.events.noteLog(p, .rename, pane); - } - - pub fn shellBin(p: *const Pardes) []const u8 { - const selected = p.settings.shell.requested.get(); - return if (selected.len == 0) config.defaultShell() else selected; - } - - /// A shell a dead session left, taken in (Adopt): a terminal pane made - /// for it as the Term word makes one, its greeting off (the shell is up - /// already), whose spawn the host answers with that shell's pty. Its id, - /// or null with no room. An input, as every host write into the core - /// is: a replica of the session makes the same pane. - pub fn adoptShell(p: *Pardes) ?u8 { - const taped = tape.enter(p, .adopt_shell); - defer tape.leave(p, taped); - var newest: u32 = 0; - for (p.panes) |slot| if (slot) |pn| { - newest = @max(newest, pn.serial); - }; - _ = p.executeBuiltinLine(p.active, "Term"); - for (p.panes, 0..) |slot, id| if (slot) |pn| if (pn.serial > newest and pn.isTerminal()) { - pn.greet = false; - return @intCast(id); - }; - return null; - } - - /// A terminal's reader failed (no end of file: the host closed its pty): - /// its pane takes keys again, and why is said. - pub fn readerFailed(p: *Pardes, id: u8, err: anyerror) void { - const taped = tape.enter(p, .{ .reader_failed = .{ .id = id, .err = err } }); - defer tape.leave(p, taped); - const pane = p.panes[id] orelse return; - pane.body.mode = .normal; - p.reportError(id, "terminal reader", err); - } - - pub fn acknowledgeShell(p: *Pardes, id: usize, executable: []const u8, prompt_marks: bool) void { - const taped = tape.enter(p, .{ .acknowledge_shell = .{ .id = id, .executable = executable, .prompt_marks = prompt_marks } }); - defer tape.leave(p, taped); - if (id < MAX_PANES) if (p.panes[id]) |pane| { - ctlfs.pty.shellGone(p, pane, true); // a respawn replaced whatever ran - pane.shell_failed = false; - pane.had_shell = true; - pane.fs.unmarked = !prompt_marks; - // The tag's Term word names the shell the host ran, and a click - // on it (`Term+fish`) opens another of the same. - if (pane.command == null) { - // A shell given as a path keeps it: its bare name would find - // nothing, or another program, on the usual paths. - const base = if (pane.shell) |given| (if (std.mem.indexOfScalar(u8, given, '/') != null) given else std.fs.path.basename(executable)) else std.fs.path.basename(executable); - const rest = tagline.terminal_pane_tail[" Term".len..]; - if (std.fmt.bufPrint(&pane.shell_tail, " Term+{s}{s}", .{ base, rest })) |tail| { - pane.shell_tail_len = @intCast(tail.len); - } else |_| {} - } - }; - if (id < MAX_PANES) panes.terminal.shellSpawned(p, id, prompt_marks); - if (p.settings.shell.effective.set(executable)) - p.settings.shell.pending = false; - } - - /// A window's font, asked and told (this and the three below): in every - /// build, not only a window's, as only a window's host calls - /// them and a terminal's replica of a window's session must step as - /// the window does. - pub fn takeFontRequest(p: *Pardes) ?[]const u8 { - const taped = tape.enter(p, .take_font_request); - defer tape.leave(p, taped); - if (!p.settings.font.pending or p.font_request_taken) return null; - const path = p.settings.font.requested_path.get(); - if (path.len == 0) return null; - p.font_request_taken = true; - return path; - } - - pub fn observeFont( - p: *Pardes, - effective_name: []const u8, - effective_size_hundredths: u16, - unit: config.Runtime.FontSizeUnit, - ) bool { - const taped = tape.enter(p, .{ .observe_font = .{ .name = effective_name, .size = effective_size_hundredths, .unit = unit } }); - defer tape.leave(p, taped); - if (!p.settings.font.effective_name.set(effective_name)) return false; - p.settings.font.effective_size_hundredths = effective_size_hundredths; - p.settings.font.effective_size_unit = unit; - return true; - } - - /// Resolve the request already handed to the GUI host. Requested and - /// effective tuples deliberately remain separate so DumpConfig can show both. - pub fn acknowledgeFont( - p: *Pardes, - effective_name: []const u8, - effective_size_hundredths: u16, - unit: config.Runtime.FontSizeUnit, - ) bool { - const taped = tape.enter(p, .{ .acknowledge_font = .{ .name = effective_name, .size = effective_size_hundredths, .unit = unit } }); - defer tape.leave(p, taped); - if (!p.settings.font.pending or !p.font_request_taken) return false; - const changed = !std.mem.eql( - u8, - p.settings.font.effective_name.get(), - effective_name, - ) or p.settings.font.effective_size_hundredths != effective_size_hundredths or - p.settings.font.effective_size_unit != unit; - if (!p.observeFont(effective_name, effective_size_hundredths, unit)) return false; - p.settings.font.pending = false; - p.font_request_taken = false; - if (changed) look.cancelLookHover(p); - return true; - } - - pub fn rejectFont(p: *Pardes) void { - const taped = tape.enter(p, .reject_font); - defer tape.leave(p, taped); - if (!p.settings.font.pending or !p.font_request_taken) return; - p.settings.font.pending = false; - p.font_request_taken = false; - } - - fn applyWatchedFileChanged(p: *Pardes, id: u8, bytes: []const u8) bool { - if (id >= MAX_PANES) return false; - const pane = p.panes[id] orelse return false; - if (comptime pdf_enabled) if (pane.pdf != null) { - panes.Pdf.reloadWatched(p, pane) catch |err| { - p.reportError(id, "PDF reload", err); - return false; - }; - return true; - }; - if (pane.file == null) return false; - panes.File.changed(p, id, bytes); - return if (p.panes[id]) |current| - if (current.file) |file| std.mem.eql(u8, file.content, bytes) else false - else - false; - } - - /// A view of its own for a new client (a second window, a terminal - /// `pardes --attach`ed), as the live one is laid out; null at - /// views.max. Not live until `toView`. - pub fn openView(p: *Pardes) ?u8 { - const taped = tape.enter(p, .open_view); - defer tape.leave(p, taped); - // Every view taken: one kept for a client that has not come back - // for it (views.away) goes first. ponytail: no timer lets one go; - // until its place is wanted it costs a parked slot, and a terminal - // it sized last keeps that size until another view types into it. - if (@popCount(p.views_open) == views.max and p.views_away != 0) { - views.close(p, @ctz(p.views_away)); - p.sync(); - } - // What was queued since the last pump (a leaving client's view - // closed, a 9P request's step) done first, as every client of the - // tape does it here: a join dumps the session next, and a core - // loaded from a dump has no queue (Replica.initDump). - p.settle(); - p.needs_frame = true; - return views.open(p); - } - - /// The client of view `k` gone: its view goes, the others stay. The - /// last one stays the session's own. - pub fn closeView(p: *Pardes, k: u8) void { - const taped = tape.enter(p, .{ .close_view = k }); - defer tape.leave(p, taped); - views.close(p, k); - p.sync(); - // What its sync queued (a terminal it sized, sized again) done here, - // in its own unit on every side: the session's next pump is another - // unit, and a replica takes a copy only of a core with nothing - // queued (rollback.Copy.take). - p.settle(); - } - - /// The last client of a session no one else watches gone: its view - /// goes, and the session's own is laid out as it was (views.closeKeeping), - /// which the client's rejoin copies. Settled as `closeView` is. - pub fn leaveView(p: *Pardes, k: u8) void { - const taped = tape.enter(p, .{ .leave_view = k }); - defer tape.leave(p, taped); - views.closeKeeping(p, k); - p.sync(); - p.settle(); - } - - /// The client of view `k` gone, to join again for it (an Upgrade's - /// rejoin, a divergence's): its view kept as it is (views.away). - pub fn awayView(p: *Pardes, k: u8) void { - const taped = tape.enter(p, .{ .away_view = k }); - defer tape.leave(p, taped); - views.away(p, k); - } - - /// A client back for view `k`, kept for it (`awayView`): its own again, - /// as it left it; false when it was let go meanwhile. Settled as - /// `openView` is, for the join's dump next. - pub fn rejoinView(p: *Pardes, k: u8) bool { - const taped = tape.enter(p, .{ .rejoin_view = k }); - defer tape.leave(p, taped); - if (!views.isAway(p, k)) return false; - p.views_away &= ~(@as(u8, 1) << @intCast(k)); - p.settle(); - p.needs_frame = true; - return true; - } - - /// Into view `k`, before the input its client sent. - pub fn toView(p: *Pardes, k: u8) void { - if (k == p.view) return; - const taped = tape.enter(p, .{ .to_view = k }); - defer tape.leave(p, taped); - views.to(p, k); - } - - /// Something changed the core without going through `update` -- a watched - /// file reloading under it, a theme file rewritten on disk. `pump` draws - /// only when it has a reason to, and this is the reason. - pub fn invalidate(p: *Pardes) void { - const taped = tape.enter(p, .invalidate); - defer tape.leave(p, taped); - p.needs_frame = true; - } - - pub fn reloadWatchedFile(p: *Pardes, id: u8, bytes: []const u8) bool { - const taped = tape.enter(p, .{ .reload_watched_file = .{ .id = id, .bytes = bytes } }); - defer tape.leave(p, taped); - p.invalidate(); - look.invalidateLookHover(p, id); - const applied = p.applyWatchedFileChanged(id, bytes); - _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); - p.sync(); - return applied; - } - - pub fn emit(p: *Pardes, e: Effect) void { - if (p.effects_len == p.effects.len) return; - const tail = (p.effects_head + p.effects_len) % p.effects.len; - p.effects[tail] = e; - p.effects_len += 1; - } - - pub fn nextEffect(p: *Pardes) ?Effect { - const taped = tape.enter(p, .next_effect); - defer tape.leave(p, taped); - p.refillPendingWrites(); - if (p.effects_len == 0) { - p.effects_head = 0; - return null; - } - const e = p.effects[p.effects_head]; - p.effects_head = (p.effects_head + 1) % p.effects.len; - p.effects_len -= 1; - return e; - } - - /// Move parked pty bytes into whatever room the ring now has, oldest pane - /// slot first. Costs one comparison when nothing is parked. - fn refillPendingWrites(p: *Pardes) void { - if (p.pending_write_bytes == 0) return; - for (&p.pending_write, 0..) |*slot, id| { - while (p.effects_len < p.effects.len) { - // `|*pw|` points INTO the slot: capturing by value would advance - // a copy's cursor and re-send the same chunk for ever. - const pw = if (slot.*) |*live| live else break; - const n = @min(pw.bytes.len - pw.off, effect_write_cap); - p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(pw.bytes[pw.off..][0..n]) } }); - pw.off += n; - p.pending_write_bytes -= n; - if (pw.off == pw.bytes.len) { - p.gpa.free(pw.bytes); - slot.* = null; - break; - } - } - if (p.effects_len == p.effects.len) return; - } - } - - /// Drop a pane's parked bytes: its pty is gone, and the slot it occupied - /// may be handed to a different pane next frame. - pub fn dropPendingWrite(p: *Pardes, id: usize) void { - const pw = p.pending_write[id] orelse return; - p.pending_write_bytes -= pw.bytes.len - pw.off; - p.gpa.free(pw.bytes); - p.pending_write[id] = null; - } - - pub fn postEvent(p: *Pardes, ev: Event) void { - switch (ev) { - .key => |k| std.debug.assert(k.text.len == 0), - .output, .paste, .lsp_resp, .pipe_resp, .search, .file_changed, .command => unreachable, - else => {}, - } - if (p.in_len == p.in_q.len) return; - p.in_q[(p.in_head + p.in_len) % p.in_q.len] = ev; - p.in_len += 1; - } - - fn nextQueued(p: *Pardes) ?Event { - if (p.in_len == 0) { - p.in_head = 0; - return null; - } - const ev = p.in_q[p.in_head]; - p.in_head = (p.in_head + 1) % p.in_q.len; - p.in_len -= 1; - return ev; - } - - pub fn hostForegroundName(p: *const Pardes, id: usize, buf: []u8) ?[]const u8 { - const f = p.host.vtable.fg_name orelse return null; - return f(p.host.ctx, @intCast(id), buf); - } - - pub fn hostTtyTaken(p: *const Pardes, id: usize) bool { - const f = p.host.vtable.tty_taken orelse return false; - return f(p.host.ctx, @intCast(id)); - } - - pub fn hostKillJob(p: *const Pardes, id: usize) bool { - const f = p.host.vtable.kill_job orelse return false; - return f(p.host.ctx, @intCast(id)); - } - - /// A terminal whose shell could not be started: said, and a run waiting - /// on it, or written to it from now on, hears `error shell gone` - /// rather than wait for a prompt that never comes. - pub fn shellFailed(p: *Pardes, id: u8, err: anyerror) void { - const taped = tape.enter(p, .{ .shell_failed = .{ .id = id, .err = err } }); - defer tape.leave(p, taped); - const pane = p.panes[id] orelse return; - pane.shell_failed = true; - ctlfs.pty.shellGone(p, pane, false); - p.sayShellFailure(id, err); - // A command that never started ended: `exit 127`, as a shell says of - // a command it could not run, so a follower waiting on its exit - // hears one, its tag stops saying it runs, and Kill finds nothing. - if (pane.command != null and !pane.command_done) { - pane.command_pty = false; - exec.commandDone(p, id, 127); - } else if (pane.command == null and !pane.had_shell) { - // A Term whose shell never ran: no dead pane left behind; the - // write that asked for it has failed with why. A terminal whose - // shell was started again (pty/ctl exec) keeps its pane. - p.unplaced.set(id); - } - } - - /// A shell started again in a terminal whose shell runs (pty/ctl's - /// exec) did not start: the host kept the running one, so only said. - pub fn restartFailed(p: *Pardes, id: u8, err: anyerror) void { - const taped = tape.enter(p, .{ .restart_failed = .{ .id = id, .err = err } }); - defer tape.leave(p, taped); - if (p.panes[id] == null) return; - p.sayShellFailure(id, err); - } - - fn sayShellFailure(p: *Pardes, id: u8, err: anyerror) void { - const pane = p.panes[id] orelse return; - if (err == error.FileNotFound or err == error.NotDir) { - p.reportFailure(id, "shell: directory missing (no such directory)"); - } else if (err == error.InterpreterNotFound) { - // The script is there; the program its `#!` names is not. - var said: [320]u8 = undefined; - var interp: [256]u8 = undefined; - const name = tape.value(.interpreter, missingInterpreter, .{ pane.shell orelse p.shellBin(), &interp }); - p.reportFailure(id, if (name) |n| std.fmt.bufPrint(&said, "shell: interpreter {s} not found", .{n}) catch "shell: interpreter not found" else "shell: interpreter not found"); - } else { - p.reportError(id, "shell", err); - } - // A 9P write that asked for the shell (pty/ctl's exec), waiting on - // it, fails with what was said, as a failed Save's does. - p.noteLateFailure(id); - } - - /// The program the shell's `#!` names that is not there, in `out`. - fn missingInterpreter(bin: []const u8, out: []u8) ?[]const u8 { - const Shell = @import("host_io.zig").Shell; - var buf: [std.fs.max_path_bytes]u8 = undefined; - return Shell.missingInterpreter(Shell.find(bin, &buf) orelse return null, out); - } - - /// The directory a write of `path` that failed with `err` went into: - /// what is there (a directory when it is no local path), whether it is - /// missing, and whether that is because one above refuses (EACCES). - fn parentTrouble(path: []const u8, err: anyerror) struct { dir: []const u8, kind: ?std.Io.File.Kind, missing: bool, denied: bool } { - const dir = std.fs.path.dirname(path) orelse "/"; - const local = filesystem.localPath(dir); - const kind: ?std.Io.File.Kind = if (local) |l| exec.kindOf(l) else .directory; - const missing = err == error.FileNotFound or err == error.NotDir or kind != .directory; - const denied = missing and (if (local) |l| tape.value(.denied, filesystem.deniedAbove, .{l}) else false); - return .{ .dir = dir, .kind = kind, .missing = missing, .denied = denied }; - } - - pub fn saveFailed(p: *Pardes, id: u8, path: []const u8, err: anyerror) void { - const taped = tape.enter(p, .{ .save_failed = .{ .id = id, .path = path, .err = err } }); - defer tape.leave(p, taped); - if (p.panes[id]) |pane| if (pane.file) |*f| { - // The `-%` spelling fs.zig already uses for "make this dirty". - f.saved_revision = f.revision -% 1; - }; - var what: [limits.host_path_cap + 32]u8 = undefined; - // A write into a directory that is not there: said so, in the words - // a mount reads as ENOENT; EACCES when one above refuses. - const parent = parentTrouble(path, err); - if (parent.denied) - p.reportFailure(id, std.fmt.bufPrint(&what, "Save {s}: permission denied", .{path}) catch "Save: permission denied") - else if (parent.missing) - p.reportFailure(id, std.fmt.bufPrint(&what, "Save {s}: no such directory", .{path}) catch "Save: no such directory") - else - p.reportError(id, std.fmt.bufPrint(&what, "Save {s}", .{path}) catch "Save", err); - p.noteLateFailure(id); - } - - /// A Dump the host could not write: said on the message row and in the - /// log, and the 9P write that asked for it fails with it, as a failed - /// Save's does. - pub fn dumpFailed(p: *Pardes, path: []const u8, err: anyerror) void { - const taped = tape.enter(p, .{ .dump_failed = .{ .path = path, .err = err } }); - defer tape.leave(p, taped); - var what: [limits.host_path_cap + 8]u8 = undefined; - const operation = std.fmt.bufPrint(&what, "Dump {s}", .{path}) catch "Dump"; - // Into a DumpDir that is not there: said so, ENOENT, as a Save is; - // one that is there but no directory (`/dev/null`) says that. - const parent = parentTrouble(path, err); - var said: [limits.host_path_cap + 48]u8 = undefined; - if (parent.denied and parent.kind == null) - p.reportFailure(p.active, std.fmt.bufPrint(&said, "{s}: permission denied", .{operation}) catch "Dump: permission denied") - else if (parent.kind != null and parent.kind != .directory) - p.reportFailure(p.active, std.fmt.bufPrint(&said, "{s}: {s} is not a directory", .{ operation, parent.dir }) catch "Dump: not a directory") - else if (parent.missing) - p.reportFailure(p.active, std.fmt.bufPrint(&said, "{s}: no such directory", .{operation}) catch "Dump: no such directory") - else - p.reportError(p.active, operation, err); - // In the words the message row has, so the write's err is the one - // record of it (its msg goes: 9p_io, dropMessage). - p.noteLateFailure(p.active); - } - - pub fn fsPayload(p: *const Pardes, r: ctlfs.Reply) []const u8 { - return switch (r.payload) { - .none => &.{}, - .staged => |n| p.fs.out.items[0..@min(n, p.fs.out.items.len)], - .region => |g| region: { - const pane = p.panes[g.pane] orelse break :region &.{}; - if (pane.serial != g.serial) break :region &.{}; - const text = if (pane.file) |*f| f.content else break :region &.{}; - const lo = @min(g.off, text.len); - break :region text[lo..@min(lo + g.len, text.len)]; - }, - }; - } - - pub fn pump(p: *Pardes, host: Host) !void { - p.host = host; - const taped = tape.enter(p, .pump); - defer tape.leave(p, taped); - // The host as the tape sees it, while it records. - const h = p.host; - const v = h.vtable; - if (v.wait_input) |f| { - // Asleep until input or until the core's next deadline - // (nextWake); 0 is no timeout at all. - // The clock read whether or not it is wanted: what a replica - // waits on is its own (a picture decoding wakes only a frame - // that draws it), and the tape has the same calls either way. - const now = if (v.now) |clock| clock(h.ctx) else p.now_ns; - const timeout: u32 = if (p.nextWake()) |due| wake: { - const ms = ((due -| now) + std.time.ns_per_ms - 1) / std.time.ns_per_ms; - break :wake @intCast(std.math.clamp(ms, 1, std.math.maxInt(u32))); - } else 0; - f(h.ctx, timeout); - } - // Detached, nobody's key dismisses a message: they go on the clock, - // here in the step, where the clock read is taped (the host's wait - // did it, untaped, and a replay kept a message its session had let - // go). - Messages.expireUnattended(p); - p.frames.mark_start = FrameStats.nowNs(); - if (v.now) |clock| p.advance(clock(h.ctx)); - p.settle(); - // A quitting frame has already freed what it would draw. - if (p.quit) return; - if (v.poll_frame) |f| f(h.ctx); - // Nothing to draw: do not spend a frame, and above all do not block on - // the display for one. This is what keeps the frame rate governing - // rendering and nothing else. - // A shell with a clock draws what `advance` stepped; one without - // steps its own `.tick`s and draws while a deadline is due. - if (!p.needs_frame and (v.now != null or !p.animationActive())) return p.frames.idle(); - // No one to see it: the frame stays owed (needs_frame), not drawn. - // A pty streaming into an unwatched session spent most of its time - // drawing what nobody looked at. - if (v.watched) |f| if (!f(h.ctx)) return; - // The other views first, each into its own window or terminal. - if (views.several(p)) try views.drawOthers(p, h); - // A replica client's view live (its input the last): its own - // process draws it. - if (p.undrawn & (@as(u8, 1) << @intCast(p.view)) == 0) { - _ = p.frame_arena.reset(.{ .retain_with_limit = memory.limits.frame_kept }); - p.frames.mark_update = FrameStats.nowNs(); - p.frames.view = if (p.panes[p.active]) |pane| pane.scroll() else 0; - const surface = try p.render(p.frame_arena.allocator()); - p.frames.mark_render = FrameStats.nowNs(); - if (v.present) |f| f(h.ctx, surface); - Stream.askAhead(p); - } - // Settled before post_present: a shell ticks there, and what that - // tick moves owes the next frame. - const skipped = p.present_skipped; - p.needs_frame = p.present_skipped; - p.present_skipped = false; - if (v.post_present) |f| f(h.ctx); - // Still moving: the next frame is owed a period from now. - const owed = if (p.nextWake()) |due| due <= p.stepped_ns + frame_ns else false; - p.frames.record(FrameStats.nowNs(), owed, skipped); - } - - /// What a pump does between its wait and its frame: the queued inputs - /// and the effects. Also the session at a step boundary, taken now (an - /// Upgrade's dump, upgrade.zig). - pub fn settle(p: *Pardes) void { - // What a 9P open wrote in a row goes in once the writes pause. - ctlfs.pane.flushPausedBatch(p); - // ...and what a /pager open was written before its close. - ctlfs.ctl.fillClosedPagers(p); - // ...and the last line of an open closed with no newline after it. - ctlfs.runClosedLines(p); - while (p.nextQueued()) |ev| p.update(ev); - while (p.nextEffect()) |e| p.perform(e); - turn.bump(&turn.epoch); - } - - /// A replica client's input settled on the authority (src/replica.zig): - /// a pump that waits on nothing, reads no clock and draws nothing, so - /// the client's own core can apply the same at once and expect the - /// authority's tape of it to read the same. The session's own pump - /// draws it after. - pub fn step(p: *Pardes) void { - const taped = tape.enter(p, .step); - defer tape.leave(p, taped); - p.settle(); - } - - /// One request of the control filesystem, from whichever thread has the - /// turn (`pardes.turn`). Not an event: it neither sweeps nor resets - /// anything the editor's own step may be in the middle of using, so it - /// can be answered while that step is out in a syscall. Only a request - /// that changes a pane costs a frame, which is why a round trip on a - /// local socket costs microseconds and not a vsync. - pub fn serveFs(p: *Pardes, req: ctlfs.Req) ctlfs.Reply { - const taped = tape.enter(p, .{ .serve_fs = req }); - defer tape.leave(p, taped); - // The held write of an Edit whose commands run, asked again by a - // retry of its park: still waiting, or its answer, never run twice. - if (p.fs.edit_hold) |*h| if (h.names(req)) { - if (!h.done) return .{ .tag = req.tag, .status = .again }; - return filesystem.EditHold.answer(&p.fs); - }; - defer panes.File.syncTwins(p); - if (!ctlfs.changesPane(p, req)) return ctlfs.handle(p, req); - // An address, a limit or the mark flag is nothing drawn: a script's - // addr write then its close costs no frame between them. - const drawn = if (ctlfs.Node.target(req.node)) |t| !(t == .pane and (t.pane.file == .addr or t.pane.file == .limit or t.pane.file == .mark)) else true; - if (drawn) p.needs_frame = true; - p.raw_hover_intent = false; - look.cancelLookHover(p); - p.fs.serving = true; - p.fs.lsp_answer_at = null; - p.fs.edit_started = false; - const reply = ctlfs.handle(p, req); - p.fs.serving = false; - // The one-failure rule is a write's: a refused open (its OTRUNC's - // truncation, a setattr, too), create or remove is its Rerror alone, - // no err, as is a write to pane/new, which is only ever read. - const ruled = req.op == .write and req.node != @backingInt(ctlfs.TopFile.new); - if (reply.status == .err and ruled) ctlfs.events.noteError(p, req, reply); - // The request was a whole step of its own, so it settles the way a - // step does: the cursor and scroll reconciled, the scripted panes - // told, and the panes it made announced to /log now rather than at - // the end of whatever the editor does next. - p.sync(); - p.fsReport(); - // A /focus write moves the keyboard as a click does: the programs - // that asked (DECSET 1004) hear it now, as after update(). - p.reportFocus(); - ctlfs.events.announce(p); - return reply; - } - - pub fn update(p: *Pardes, ev: Event) void { - const taped = tape.enter(p, .{ .update = ev }); - defer tape.leave(p, taped); - defer panes.File.syncTwins(p); - defer p.reportFocus(); - // A tick with no deadline due is the one event that cannot change - // the screen. - p.needs_frame = p.needs_frame or ev != .tick; - p.shell_rows.sweep(p.gpa); - Messages.expireUnattended(p); - // An announcement stands in only until its own step says more. - for (p.panes) |slot| if (slot) |pane| { - pane.msg_announcement = false; - }; - // A Look's hover outlives a tick, a batch of rows coming in (no - // gesture), a move with no button, and a change to another pane. - const hover_stays = switch (ev) { - .tick, .search => true, - .mouse => |m| m.button == .none and m.kind == .motion, - .output => |o| look.lookHoverPane(p) != o.pane, - .file_changed => |changed| look.lookHoverPane(p) != changed.pane, - .pdf_scroll => |scroll| look.lookHoverPane(p) != scroll.pane, - else => false, - }; - if (!hover_stays) { - p.raw_hover_intent = false; - look.cancelLookHover(p); - } - switch (ev) { - .key, .mouse => { - for (p.panes) |slot| { - if (slot) |pane| Messages.dismissMessage(p, pane); - } - p.clip_pending = null; - }, - .tick => { - Stream.step(p); - Messages.advanceMessages(p); - for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| f.tables.step(pane.gpa, f); - for (0..p.panes.len) |id| exec.flushReplEnter(p, id, false); - }, - else => {}, - } - if (p.fs.listeners != 0) p.fs.origin = switch (ev) { - .key => 'K', - .mouse => 'M', - else => p.fs.origin, - }; - switch (ev) { - .resize => |sz| { - if (sz.row_metrics) |metrics| p.row_metrics = metrics; - if (comptime pdf_enabled) { - var before: [MAX_PANES]?panes.Pdf.Viewport = @splat(null); - for (p.panes, 0..) |slot, id| { - const pane = slot orelse continue; - if (pane.pdf != null) before[id] = panes.Pdf.paneViewport(p, pane); - } - p.screen_w = sz.cols; - p.screen_h = sz.rows; - p.cell_pixels.w = @max(1, sz.cell_pixels.w); - p.cell_pixels.h = @max(1, sz.cell_pixels.h); - layout.compute(p); - for (p.panes, 0..) |slot, id| { - const pane = slot orelse continue; - if (pane.pdf) |pv| { - if (!std.meta.eql(before[id], panes.Pdf.paneViewport(p, pane))) { - panes.Pdf.captureLayoutAnchor(pv); - pv.layout_valid = false; - pv.search_reveal_pending = pv.search_query.len > 0; - } - } - } - } else { - p.screen_w = sz.cols; - p.screen_h = sz.rows; - } - p.resize_count += 1; - }, - .output => |o| { - const pane = p.panes[o.pane] orelse return; - pane.shell_spoke = true; - ctlfs.events.notePtyOutput(p, o.pane, o.bytes); - panes.terminal.feedOutput(p, pane, o.bytes); - ctlfs.pty.noteMarks(p, o.pane, pane); - exec.flushReplEnter(p, o.pane, true); - }, - .exited => |e| if (p.panes[e.pane]) |pane| { - if (pane.command == null) - ctlfs.pty.shellExited(p, pane, e.status) - else if (!pane.command_done) - exec.commandDone(p, e.pane, e.status); - }, - .eof => |e| if (p.panes[e.pane]) |pane| if (pane.command != null) { - // Output is over; the command is over when its child exits. - pane.command_pty = false; - } else p.removePane(e.pane, null) catch |err| { - pane.body.mode = .normal; - p.reportError(e.pane, "terminal exited; Del retries close", err); - }, - .lsp_resp => |r| @import("lsp/Ask.zig").lspResponse(p, r.id, r.rows), - .pipe_resp => |r| Pipe.pipeResponse(p, r.id, r.success, r.outputs, r.failure), - .search => |b| Stream.receive(p, &b), - .file_changed => |fc| _ = p.applyWatchedFileChanged(fc.pane, fc.bytes), - .key => |key| { - p.can_ask = true; - defer p.can_ask = false; - p.typedInto(); - @import("keys.zig").handleKey(p, key); - }, - .mouse => |m| mouse.handleMouse(p, m), - .pdf_scroll => |scroll| { - if (comptime pdf_enabled) { - if (scroll.pane < MAX_PANES) { - if (p.panes[scroll.pane]) |pane| { - if (pane.hasPdf() and p.native_images) - _ = panes.Pdf.scrollPane(p, pane, @floatCast(scroll.delta_pixels), scroll.glide); - } - } - } - }, - .paste => |bytes| { - p.typedInto(); - edit.applyPaste(p, bytes); - }, - .command => |line| _ = p.executeBuiltinLine(p.active, line), - .focus => |focused| { - p.window_focused = focused; - if (focused) if (p.host.vtable.newer_build) |f| if (f(p.host.ctx)) p.setMessage(p.active, newer_build_words); - }, - .handed => |h| p.handover.finish(p, h.seq, h.to, h.failure), - .frontend => |f| { - p.windowed = f.windowed; - p.native_images = f.native_images; - p.native_image_patches = f.native_image_patches; - }, - .pointer_leave => { - p.pointer_inside = false; - p.pointer_body_hit = null; - p.pointer_tag_hit = null; - }, - .tick => { - mouse.edgeScroll(p); - look.advanceLookHover(p); - }, - } - // Each pane's places find a frame's more on a tick, and on any other - // step the ones an edit or a scroll left unfound in the view. - for (p.panes) |slot| if (slot) |pane| pane.places.settle(p, pane, ev == .tick); - // Each live query pane's rows, made from what changed this step. - panes.Query.produceAll(p, ev == .tick, ev == .key); - _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); - p.sync(); - p.fsReport(); - ctlfs.events.announce(p); - } - - fn fsReport(p: *Pardes) void { - if (p.fs.listeners == 0) return; - for (p.panes, 0..) |slot, id| { - const pane = slot orelse continue; - if (pane.fs.readers == 0) continue; - const tag = tagline.tagText(p, p.scratch.allocator(), pane) catch continue; - const snap = &pane.fs.tag_snap; - if (std.mem.eql(u8, snap.items, tag)) continue; - if (snap.capacity != 0 or snap.items.len != 0) - ctlfs.events.noteReplace(p, id, true, snap.items, tag); - snap.clearRetainingCapacity(); - snap.appendSlice(p.gpa, tag) catch {}; - } - } - - /// Where pardes started: the directory of what runs from a header. - pub fn sessionDir(p: *Pardes) []const u8 { - if (p.session_dir_len) |n| return p.session_dir[0..n]; - // The directory the session that recorded was started in. - const dir = tape.value(.cwd, processDir, .{&p.session_dir}) orelse return "/"; - std.mem.copyForwards(u8, &p.session_dir, dir); - p.session_dir_len = @intCast(dir.len); - return p.session_dir[0..dir.len]; - } - - fn processDir(buf: *[limits.host_path_cap]u8) ?[]const u8 { - if (std.c.getcwd(buf, buf.len) == null) return null; - return buf[0 .. std.mem.indexOfScalar(u8, buf, 0) orelse return null]; - } - - /// The directory a word run from pane `id`'s text or tag runs in, or, - /// from a header, the session's. - pub fn execDir(p: *Pardes, id: usize) []const u8 { - if (p.exec_header) return p.sessionDir(); - return paneDir(p.panes[id] orelse return p.sessionDir()); - } - - pub const SavePath = Effect.Buf(effect_path_cap); - - /// What was said of a failure just now on pane `id` is also the waiting - /// 9P write's (9p_io, `fs.late_failure`). - pub fn noteLateFailure(p: *Pardes, id: usize) void { - const taped = tape.enter(p, .{ .note_late_failure = id }); - defer tape.leave(p, taped); - // Said by reportFailure just now: its words fitted whole, the - // reason kept; else what the message row has. - const said = if (p.fs.said_at == p.fs.failures and p.fs.said_len > 0) - p.fs.said[0..p.fs.said_len] - else if (p.panes[id]) |pane| pane.msg[0..pane.msg_len] else return; - const kept = @import("Messages.zig").clip(said, p.fs.late_failure.len); - @memcpy(p.fs.late_failure[0..kept.len], kept); - p.fs.late_failure_len = @intCast(kept.len); - } - - /// The frontend drew a frame: a pointer resting on it follows what is - /// under it now, a drag's moving end and a look-hover's word. - pub fn presented(p: *Pardes) void { - const taped = tape.enter(p, .presented); - defer tape.leave(p, taped); - if (p.pointer_inside and p.drag != .none) { - p.hover_col = p.pointer_raw_col; - p.hover_row = p.pointer_raw_row; - mouse.dragUpdate(p, p.pointer_raw_col, p.pointer_raw_row, p.pointer_body_hit); - } - look.refreshLookHoverFromRaw(p); - } - - /// The window's answer to a WindowOpacity: done, or `failure` says why - /// not, `applied` the opacity it keeps. - pub fn windowOpacityDone(p: *Pardes, applied: u8, failure: ?[]const u8) void { - const taped = tape.enter(p, .{ .window_opacity_done = .{ .applied = applied, .failure = failure } }); - defer tape.leave(p, taped); - p.settings.window_opacity_pending = false; - const reason = failure orelse return; - // Do not claim a value the compositor refused; an explicit retry of - // the same command will arm a new request. - p.settings.window_opacity = applied; - var buf: [256]u8 = undefined; - p.setMessage(p.active, std.fmt.bufPrint(&buf, "WindowOpacity: {s}", .{reason[0..@min(reason.len, 240)]}) catch "WindowOpacity: compositor rejected the request"); - } - - /// Recompute geometry, push grid-size changes to each emulator and pty, - /// fire deferred greetings. - pub fn sync(p: *Pardes) void { - while (p.unplaced.findFirstSet()) |id| { - p.unplaced.unset(id); - // Refused, it was never there. Its serial is not handed out - // again: one logged or answered names this pane for good. Its - // rows, if it had any, go where a closed pane's go; no other - // pane moves (a pane dragged short keeps its rows). - if (p.panes[id] != null) p.removePane(id, null) catch {}; - } - // A file opened or closed this step: the kept list follows. - p.saveRecent(); - tagline.flattenHeaders(p); - if (p.header_column != null and layout.columnBarHeight(p) == 0) { - tagline.exitHeader(p); - } - panes.reapPanes(p); - if (views.several(p)) views.show(p); - layout.compute(p); - Jump.trackJump(p); - for (&p.panes, 0..) |*slot, id| { - const pane = slot.* orelse continue; - // The keyboard is on one pane, or on a header: a tag it has left - // hands it back to its body, and a name drafted there is dropped. - if (id != p.active or p.header_focus) { - pane.focus = .body; - if (pane.prompt == .name and pane.prompt_view == p.view) pane.closePrompt(); - } - // A sweep over the tag is the tag's while it has the keyboard. - const swept = pane.sel[sel_slot]; - if (pane.focus == .body and swept.state == .done and @min(swept.r0, swept.r1) < pane.tag_rows) { - pane.clearPointerSelection(sel_slot); - pane.sel[sel_slot].state = .none; - } - // What the terminal answers its program (a cursor report, its - // attributes) goes as typed bytes go: behind whatever is still - // queued for its pty, never ahead of it nor dropped. - if (pane.terminal) |state| { - p.emitWrite(id, state.reply[0..state.reply_len]); - state.reply_len = 0; - } - const r = p.rects[id]; - // The session's part of the pane's view geometry (File.geometry), - // and its context declarations. - if (pane.file) |*f| panes.File.refreshContext(p, pane, f); - pane.view = .{ .wrap = p.settings.wrap, .layered = p.settings.tree_context_tag_style, .body_h = p.row_metrics.body_h, .tagline_h = p.row_metrics.tagline_h, .rect_h = r.h }; - // The tag takes a row per line, leaving the body one row if it - // had any; a folded pane shows its first line only. Its prefix - // is made once, on the stack: this runs on every event, and not - // every event may take from the scratch arena. - var wrap_room: [32 * 1024]u8 = undefined; - var wrap_fba = std.heap.FixedBufferAllocator.init(&wrap_room); - const wa = wrap_fba.allocator(); - const prefix: ?[]const u8 = tagline.prefixIn(p, wa, pane) catch null; - const lead = if (prefix) |made| made.len else pane.tag_lead; - if (lead != pane.tag_lead) { - const t = &pane.tag; - const old: i32 = @intCast(pane.tag_lead); - const new: i32 = @intCast(lead); - if (t.cur_row == 0 and t.cur_col >= old) t.cur_col += new - old; - if (t.vsel.row == 0 and t.vsel.col >= old) t.vsel.col += new - old; - for (t.sels[0..t.nsel]) |*sel| { - if (sel.row == 0 and sel.col >= old) sel.col += new - old; - if (sel.arow == 0 and sel.acol >= old) sel.acol += new - old; - } - pane.tag_lead = lead; - } - // A row per shown row: the tag's lines wrapped at its width. - var lines = std.mem.count(u8, tagline.curTail(pane), "\n") + 1; - var wanted = lines; - var caret_row: usize = @intCast(@max(0, pane.tag.cur_row)); - if (prefix) |made| wrap: { - const whole = std.mem.concat(wa, u8, &.{ made, tagline.curTail(pane) }) catch break :wrap; - const shown = tagline.wrapTag(wa, whole, tagline.tagWidth(p, id)) catch break :wrap; - lines = shown.rows(); - // Collapsed, one row, as acme's Tagup sets taglines to 1 - // (plan9port text.c:786). - wanted = if (pane.tag_expanded) lines else 1; - const cur = modal.offsetAt(whole, .{ .row = caret_row, .col = @intCast(@max(0, pane.tag.cur_col)) }); - caret_row = std.mem.count(u8, shown.text[0..@min(shown.fromReal(cur), shown.text.len)], "\n"); - } - if (!pane.tag_expanded) wanted = 1; - pane.tag_rows = @intCast(@min(wanted, MAX_TAG_ROWS, @max(BOX_H, r.h -| 1))); - if (pane.collapsed) pane.tag_rows = BOX_H; - if (pane.focus == .tag and pane.prompt != .name) { - const cur: usize = caret_row; - var top: usize = pane.tag_top; - if (cur < top) top = cur; - if (cur >= top + pane.tag_rows) top = cur + 1 - pane.tag_rows; - pane.tag_top = @intCast(@min(top, lines - pane.tag_rows)); - } else pane.tag_top = 0; - const cols = @max(1, r.w -| config.GUTTER); - // The tag steals the top rows. The pty is what the pane shows - // (layout keeps a terminal two body rows where the window has - // them): a taller pty would put its cursor below the pane. - const rows = @max(1, r.h -| pane.tag_rows); - // A terminal's pty follows its pane down to a row, whatever the - // resize; only a folded one keeps the size it had, and one not - // placed yet the grid it was made with. - if ((cols != pane.cols or rows != pane.rows) and (r.h > pane.tag_rows or (pane.isTerminal() and !pane.collapsed and r.h > 0)) and - (!pane.isTerminal() or p.sizes(pane))) - { - // doc panes have no pty/emulator grid to reflow; just record - // the size so bodyText renders the right number of rows - if (pane.isTerminal()) { - panes.terminal.resizeGrid(pane, cols, rows); - p.shell_rows.markStale(pane); // reflow moved every row - p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = cols, .rows = rows } }); - pane.fs.winsize = null; - } - pane.cols = cols; - pane.rows = rows; - if (pane.file) |*file| file.syntax_dirty = true; - } - pane.pan = panes.terminal.panFor(p, pane, r); - // A directory pane's entries follow its width, as acme's - // columns do (Dir.fit). - if (pane.file) |file| if (file.listing != null and r.h > pane.tag_rows) panes.Dir.fit(p, pane, pane.cols); - panes.terminal.releasePendingCommandIfReady(p, id, pane); - // Which bands a pane shows is the step's, as its geometry is: - // what is drawn under them, and where a click lands, read it. - Messages.collectNotices(p, pane, r, id); - // The greeting `ls` of a new terminal in a directory is typed at - // its shell's FIRST prompt, or never: typed later it would land - // in whatever runs then, or in the middle of a line someone - // typed (panes.terminal.greeting). - if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (tape.value(.prompt, panes.terminal.greeting, .{pane})) { - .wait => {}, - .never => pane.greet = false, - .now => { - p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = pane.cols, .rows = pane.rows } }); - p.emitWrite(id, "ls\r"); - pane.greet = false; - }, - }; - } - // A header's caret kept in its view, as a pane's is: the step's, not - // the frame's (paintHeaders draws what this leaves). - tagline.revealHeader(p); - } - - /// The view typing goes into is the one its terminal is sized for - /// (`sizes`). - fn typedInto(p: *Pardes) void { - if (p.panes[p.active]) |pane| pane.sized_by = p.view; - } - - /// Whether the live view sizes terminal `pane`: a terminal shown at two - /// sizes takes the size of the view that typed into it last, and any - /// view's once that one is gone. The others show it at that size, a - /// shorter one passed down to its cursor (`Pane.pan`, terminal.panFor). - // ponytail: a panned view's pointer reports to a terminal's program and - // its kitty images are placed as the unpanned rows are. - fn sizes(p: *Pardes, pane: *Pane) bool { - if (pane.sized_by == p.view) return true; - if (views.isOpen(p, pane.sized_by)) return false; - pane.sized_by = p.view; - return true; - } - - pub fn theme(p: *const Pardes) *const Theme { - if (p.custom_theme) |*custom| return custom; - return &themes[p.settings.theme]; - } - - /// The colours of the chrome: the theme's, set as it changes. - pub fn chromeTheme(p: *const Pardes) *const ChromeTheme { - return &p.chrome; - } - - /// The theme's own chrome, not a fade's (`theme()`'s, worked out once - /// per theme: its contrast searches take pow calls, too many for a - /// grapheme or a row). - pub fn bodyChrome(p: *Pardes) *const ChromeTheme { - const th = p.theme(); - if (p.body_chrome) |*cached| if (std.meta.eql(cached.theme, th.*)) return &cached.chrome; - p.body_chrome = .{ .theme = th.*, .chrome = ChromeTheme.fromTheme(th) }; - return &p.body_chrome.?.chrome; - } - - /// When the core next needs a frame, on the `stepped_ns` timeline: a - /// frame from now while work goes on (places to find, a picture - /// decoding, a PDF page on a lane), the end of the wait while something - /// only waits (a message lingering, a look-hover delay), null when - /// nothing is due. Every deadline the core owns is in this one list, - /// which is what lets every shell sleep exactly as long as nothing - /// changes; what moves on the screen is the frontends' own. - pub fn nextWake(p: *const Pardes) ?u64 { - const next = p.stepped_ns + frame_ns; - // Held 9P writes go in when they pause: wake for it, never before - // the next frame (writes served before the shell's clock was first - // seen are stamped 0, which `advance` would count back from). - if (p.fs.batch.bytes.items.len > 0) return @max(next, p.fs.batch.last_ns + ctlfs.pane.batch_pause_ns); - // Places still to find resume on the next frame; a picture being - // decoded is looked for. - for (p.panes) |slot| if (slot) |pane| if (pane.places.busy(pane)) return next; - for (p.panes) |slot| if (slot) |pane| if (pane.image) |iv| if (iv.decoder != null) return next; - // A PDF page being rendered on a lane lands on the frame after it is done. - if (comptime pdf_enabled) for (p.panes) |slot| if (slot) |pane| if (pane.pdf) |st| if (panes.Pdf.rendering(st)) return next; - // A markdown text's tables still being read from the top (Tables.zig). - for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.tables.busy()) return next; - if (panes.Query.busy(p)) return next; - // A typed Grep waiting out its pause. - const streaming = p.stream.wake(next); - if (streaming) |due| if (due <= next) return next; - var frames: ?u64 = null; - if (streaming) |due| frames = @max(1, (due -| p.stepped_ns + frame_ns - 1) / frame_ns); - if (p.look_hover_wait) |waiting| { - const delay = config.look_preview_delay_frames; - frames = @max(1, delay -| waiting.frames); - } - for (p.panes) |slot| if (slot) |pane| { - const wait = Messages.messageWake(p, pane) orelse continue; - frames = if (frames) |soonest| @min(soonest, wait) else wait; - }; - // Del's question goes up at the end of its delay: a frame then, and - // none after (stepped time has reached it). - for (p.panes) |slot| if (slot) |pane| if (pane.prompt == .del_side and pane.question_due_ns > p.stepped_ns) { - const wait = @max(1, (pane.question_due_ns - p.stepped_ns + frame_ns - 1) / frame_ns); - frames = if (frames) |soonest| @min(soonest, wait) else wait; - }; - // A paste's Enter waiting on its REPL goes at the end of its wait, - // a time on the clock: the frames from `stepped_ns` that reach it. - for (p.panes) |slot| if (slot) |pane| if (pane.repl_enter > 0) { - const wait = @max(1, (pane.repl_enter_due_ns -| p.stepped_ns + frame_ns - 1) / frame_ns); - frames = if (frames) |soonest| @min(soonest, wait) else wait; - }; - // A terminal's kitty animation, at its next frame. Only a time still - // ahead counts: a pane not drawn keeps the last one it was given, - // and a past one would wake every frame for nothing. - for (p.panes) |slot| if (slot) |pane| if (panes.terminal.animationDueMs(pane)) |due_ms| { - const due = due_ms *| std.time.ns_per_ms; - if (due > p.stepped_ns) { - const wait = @max(1, (due - p.stepped_ns + frame_ns - 1) / frame_ns); - frames = if (frames) |soonest| @min(soonest, wait) else wait; - } - }; - return if (frames) |n| p.stepped_ns + n * frame_ns else null; - } - - /// For shells that only need a yes or no: macOS, which keeps its own - /// frame bank. - pub fn animationActive(p: *const Pardes) bool { - return p.nextWake() != null; - } - - /// Bring core time up to `now_ns`, the shell's monotonic clock: one - /// `.tick` for every whole frame that has passed since it last stood - /// still, so a timing lasts as long on a 144 Hz display, over ssh or - /// after a slow frame as it does anywhere. A wait (a message lingering, - /// the look-hover delay) is jumped to its end in one step and drawn - /// once. Idle, time is not banked: the next wait starts from now. - pub fn advance(p: *Pardes, now_ns: u64) void { - const taped = tape.enter(p, .{ .advance = now_ns }); - defer tape.leave(p, taped); - // The first time a shell's clock is seen, core time starts there. - const started = p.clock_started; - p.clock_started = true; - p.now_ns = now_ns; - if (!started) p.stepped_ns = now_ns; - const frame = frame_ns; - var moving: u32 = 0; - // The session's ticks are the recording session's: a picture still - // decoding or a fade still moving asks for frames the way a message - // waiting to go does, and a replica that draws nothing has none. - while (tape.value(.wake, nextWake, .{p})) |due| { - if (due > now_ns) break; - // Only waiting until `due`: its counters move there at once. - const held = (due - p.stepped_ns) / frame; - if (held > 1) { - Messages.holdMessages(p, held - 1); - if (p.look_hover_wait) |*waiting| waiting.frames +|= @intCast(@min(held - 1, std.math.maxInt(u16))); - p.stepped_ns += (held - 1) * frame; - } - // Back from a stall, the moving frames it missed are not all - // run at once: the rest are stepped from now, at their pace. - if (moving == max_catch_up_frames) { - p.stepped_ns = now_ns; - return; - } - moving += 1; - p.stepped_ns += frame; - p.update(.tick); - // A stepped frame is a frame to draw. (A `.tick` does not ask - // for one itself: the last frame of a fade used never to be - // drawn.) - p.needs_frame = true; - } else { - p.stepped_ns = now_ns; - return; - } - // A 60 Hz display frame is 16.67 ms and ours 16: without this, every - // 24th display frame would take two steps, a hitch in every fade. - // An overshoot this small is let go; a larger one (144 Hz lands 4.8 - // ms past) is kept, so the average rate stays right. - if (moving > 0 and now_ns - p.stepped_ns < vsync_slack_ns) p.stepped_ns = now_ns; - } - - pub const vsync_slack_ns = 1500 * std.time.ns_per_us; - pub const max_catch_up_frames = 240; - - pub fn noteHaptic(p: *Pardes, pulse: Haptic) void { - if (comptime platform != .macos) return; - if (p.haptic == .look) return; - p.haptic = pulse; - } - - /// Take the armed pulse and disarm. The shell calls this once per pump, - /// after the tick that may have set it. - pub fn takeHaptic(p: *Pardes) Haptic { - if (comptime platform != .macos) return .none; - defer p.haptic = .none; - return p.haptic; - } - - pub const render = draw.render; - - pub fn appendImagePlace(p: *Pardes, place: ImagePlace) bool { - p.surface.images.append(p.gpa, place) catch return false; - return true; - } -}; - -test "a boot file that will not open boots an errors pane rather than failing the launch" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ - .cols = 80, - .rows = 24, - .file = "/definitely/not/here/notes.md", - }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); - - const pane = p.panes[0].?; - const f = pane.file.?; - try std.testing.expectEqual(panes.Output.Origin.errors, f.output.?.from); - // The reason IN WORDS, not an error name: `PermissionDenied` on a screen - // is jargon, and the whole point of this pane is that a human reads it. - try std.testing.expect(std.mem.indexOf(u8, f.content, "cannot open") != null); - try std.testing.expect(std.mem.indexOf(u8, f.content, "no file of that name") != null); - try std.testing.expect(std.mem.indexOf(u8, f.content, "/definitely/not/here/notes.md") != null); -} - -test "argv naming nothing boots an errors pane rather than failing the launch" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ - .cols = 80, - .rows = 24, - .missing = .{ .word = "notes/tdoo.md", .dir = "/home/pardes-test/work" }, - }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); - - // One pane, filling the window, and it is an OUTPUT pane rather than the - // shell a bare `pardes` boots: the answer is the whole screen. - try std.testing.expectEqual(@as(u8, 1), p.ncol); - try std.testing.expectEqual(@as(usize, 1), p.col_n[0]); - try std.testing.expectEqual(@as(usize, 0), p.col_panes[0][0]); - try std.testing.expectEqual(@as(usize, 0), p.active); - for (p.panes[1..]) |slot| try std.testing.expect(slot == null); - const pane = p.panes[0].?; - try std.testing.expect(!pane.isTerminal()); - const f = pane.file.?; - try std.testing.expectEqual(panes.Output.Origin.errors, f.output.?.from); - // ...and it says what happened AND what was asked for. The word as typed, - // which is the half a bare "not found" leaves out. - try std.testing.expect(std.mem.indexOf(u8, f.content, "not found") != null); - try std.testing.expect(std.mem.indexOf(u8, f.content, "notes/tdoo.md") != null); - - try std.testing.expectEqualStrings("/home/pardes-test/work/+Errors", f.path); -} - -test "raw terminal cursor obeys visibility without hiding modal and tag cursors" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.body.mode = .tty; - p.update(.{ .output = .{ .pane = 0, .bytes = "abc" } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const visible = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; - const rect = p.rects[0]; - const body_y = if (p.settings.tag_bottom) rect.y else rect.y + BOX_H; - try std.testing.expectEqual(rect.x + config.GUTTER + 3, visible.x); - try std.testing.expectEqual(body_y, visible.y); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?25l" } }); - try std.testing.expect((try p.render(frame.allocator())).cursor == null); - pane.body.mode = .normal; - pane.body.cur_pinned = true; - pane.body.cur_row = 0; - pane.body.cur_col = 1; - const modal_cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; - try std.testing.expectEqual(rect.x + config.GUTTER + 1, modal_cursor.x); - try std.testing.expectEqual(body_y, modal_cursor.y); - tagline.enterTag(p, pane); - const tag_cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; - try std.testing.expectEqual(if (p.settings.tag_bottom) rect.y + rect.h - BOX_H else rect.y, tag_cursor.y); - pane.focus = .body; - pane.body.mode = .tty; - try std.testing.expect((try p.render(frame.allocator())).cursor == null); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?25h\x1b[?1049h\x1b[2;5H" } }); - const alternate = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; - try std.testing.expectEqual(rect.x + config.GUTTER + 4, alternate.x); - try std.testing.expectEqual(body_y + 1, alternate.y); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?25l" } }); - try std.testing.expect((try p.render(frame.allocator())).cursor == null); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049l\x1b[?25h" } }); - const returned = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; - try std.testing.expectEqual(visible.x, returned.x); - try std.testing.expectEqual(visible.y, returned.y); -} - -test "raw terminal cursor follows its active row only while that row is visible" { - const gpa = std.testing.allocator; - for ([_]bool{ false, true }) |tag_bottom| { - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - p.settings.tag_bottom = tag_bottom; - const pane = p.panes[0].?; - pane.body.mode = .tty; - for (0..60) |_| p.update(.{ .output = .{ .pane = 0, .bytes = "row\r\n" } }); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3;4H" } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const live = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; - const rect = p.rects[0]; - const body_y = if (tag_bottom) rect.y else rect.y + BOX_H; - try std.testing.expectEqual(rect.x + config.GUTTER + 3, live.x); - try std.testing.expectEqual(body_y + 2, live.y); - - panes.terminal.scrollGrid(pane, -1); - const scrolled = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; - try std.testing.expectEqual(live.x, scrolled.x); - try std.testing.expectEqual(live.y + 1, scrolled.y); - panes.terminal.scrollGrid(pane, -@as(i32, pane.rows)); - try std.testing.expect((try p.render(frame.allocator())).cursor == null); - panes.terminal.followOutput(pane); - const returned = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; - try std.testing.expectEqual(live.x, returned.x); - try std.testing.expectEqual(live.y, returned.y); - } -} - -test "the bare tty startup opens a text pane under the shell, unfocused" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .boot = .tty }); - defer p.deinit(); - try std.testing.expectEqual(Boot.tty, p.boot); - - // One column, shell on top in raw mode, an empty text pane under it. - try std.testing.expectEqual(@as(usize, 1), p.ncol); - try std.testing.expectEqual(@as(usize, 2), p.col_n[0]); - const shell = p.panes[p.col_panes[0][0]].?; - const scratch = p.panes[p.col_panes[0][1]].?; - try std.testing.expect(shell.isTerminal()); - try std.testing.expectEqual(Text.Mode.tty, shell.body.mode); - try std.testing.expect(!scratch.isTerminal()); - try std.testing.expectEqualStrings("", scratch.file.?.content); - - // ...and the shell keeps the keyboard. - try std.testing.expectEqual(p.col_panes[0][0], p.active); - - // Unnamed, it is the bare shell every test asks for. - const plain = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer plain.deinit(); - try std.testing.expectEqual(Boot.tty_shell, plain.boot); - try std.testing.expectEqual(@as(usize, 1), plain.col_n[0]); -} - -test "tty output follows only from the bottom" { - const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); - p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell under the doc - const shell = p.active; - const sp = p.panes[shell].?; - p.update(.{ .key = .{ .cp = 'b', .ctrl = true } }); - try std.testing.expectEqual(Text.Mode.tty, sp.body.mode); - - for (0..60) |i| { - var buf: [32]u8 = undefined; - p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); - } - p.sync(); - const bottom = panes.terminal.scrollbar(sp).offset; - try std.testing.expect(bottom > 0); - - // Scrolled back, the reader stays put however much the shell prints. - sp.scrollBy(-10); - p.sync(); - const parked = panes.terminal.scrollbar(sp).offset; - try std.testing.expect(parked < bottom); - for (60..70) |i| { - var buf: [32]u8 = undefined; - p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); - } - p.sync(); - try std.testing.expectEqual(parked, panes.terminal.scrollbar(sp).offset); - - // Typing snaps back to live output, so nobody types blind. - p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); - p.sync(); - try std.testing.expect(panes.terminal.scrollbar(sp).offset > parked); - - // ...and from there output follows again. - const live = panes.terminal.scrollbar(sp).offset; - p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = "tail\r\n" } }); - p.sync(); - try std.testing.expect(panes.terminal.scrollbar(sp).offset > live); -} - -test "an unasked desktop paste reaches a tty pane's program, not its buffer" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); - var buf: [256]u8 = undefined; - _ = test_api.ptyBytes(p, null, &buf); - - const pane = p.panes[0].?; - panes.terminal.enterTty(p, 0); - // No request behind it: the window manager's own paste, or SDL answering a - // Ctrl-Shift-V the desktop handled. It still has to reach the shell. - p.update(.{ .paste = "ls -la" }); - try std.testing.expectEqualStrings("ls -la", test_api.ptyBytes(p, null, &buf)); - // and nothing was typed into an overlay the pty does not know about - try std.testing.expect(pane.ovl == null); -} - -test "a paste larger than the effect ring reaches the program whole and in order" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); - const buf = try gpa.alloc(u8, 2 << 20); - defer gpa.free(buf); - _ = test_api.ptyBytes(p, null, buf); - panes.terminal.enterTty(p, 0); - - const text = try gpa.alloc(u8, 1536 * 1024); - defer gpa.free(text); - for (text, 0..) |*c, i| c.* = 'a' + @as(u8, @intCast(i % 26)); - p.update(.{ .paste = text }); - try std.testing.expectEqualSlices(u8, text, test_api.ptyBytes(p, null, buf)); - // ...and the core is not still holding a copy afterwards - try std.testing.expectEqual(@as(usize, 0), p.pending_write_bytes); -} - -test "a bracketed paste larger than the ring still closes its bracket" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); - const buf = try gpa.alloc(u8, 2 << 20); - defer gpa.free(buf); - _ = test_api.ptyBytes(p, null, buf); - panes.terminal.enterTty(p, 0); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); - try std.testing.expect(panes.terminal.bracketedPaste(p.panes[0].?)); - const text = try gpa.alloc(u8, 1536 * 1024); - defer gpa.free(text); - @memset(text, 'z'); - p.update(.{ .paste = text }); - const got = test_api.ptyBytes(p, null, buf); - try std.testing.expect(std.mem.startsWith(u8, got, "\x1b[200~")); - try std.testing.expect(std.mem.endsWith(u8, got, "\x1b[201~")); - try std.testing.expectEqualSlices(u8, text, got["\x1b[200~".len .. got.len - "\x1b[201~".len]); -} - -test "a terminal's answer to its program waits behind the paste still queued for its pty" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); - const buf = try gpa.alloc(u8, 2 << 20); - defer gpa.free(buf); - _ = test_api.ptyBytes(p, null, buf); - panes.terminal.enterTty(p, 0); - - const text = try gpa.alloc(u8, 1536 * 1024); - defer gpa.free(text); - @memset(text, 'p'); - p.update(.{ .paste = text }); - // The ring is full and the rest of the paste waits for room in it. A - // host takes one write off, and the program asks where its cursor is. - const taken = p.nextEffect().?; - const off = if (taken == .write) taken.write.bytes.len else 0; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[6n" } }); - const got = test_api.ptyBytes(p, null, buf); - // The whole paste first, then the answer, `CSI row ; col R`, whole. - try std.testing.expectEqualSlices(u8, text[off..], got[0 .. text.len - off]); - const answer = got[text.len - off ..]; - try std.testing.expect(std.mem.startsWith(u8, answer, "\x1b[") and std.mem.endsWith(u8, answer, "R")); -} - -test "pasted bytes still queued at shutdown are freed, not leaked" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); - const buf = try gpa.alloc(u8, 2 << 20); - defer gpa.free(buf); - _ = test_api.ptyBytes(p, null, buf); - panes.terminal.enterTty(p, 0); - - const text = try gpa.alloc(u8, 1536 * 1024); - defer gpa.free(text); - @memset(text, 'q'); - p.update(.{ .paste = text }); - try std.testing.expect(p.pending_write_bytes > 0); -} - -test "leaving tty hides the prompt and keeps the command typed at it" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); - p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell under the doc - const shell = p.active; - const sp = p.panes[shell].?; - try std.testing.expect(sp.isTerminal()); - - // Exactly what an OSC 133 shell draws: prompt, then the marker that says - // the rest of this row is the user's, then what they typed. One grid row. - p.update(.{ .output = .{ - .pane = @intCast(shell), - .bytes = "\x1b]133;A\x1b\\user@box ~/src $ \x1b]133;B\x1b\\grep -rn TODO src/", - } }); - p.sync(); - - const rowOf = struct { - fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 { - const rows = panes.terminal.shellRows(pp, pane) catch return null; - for (rows) |r| if (std.mem.indexOf(u8, r, needle) != null) return r; - return null; - } - }.at; - const bodyRowOf = struct { - fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 { - const body = panes.terminal.bodyText(pp.scratch.allocator(), pane) catch return null; - var it = std.mem.splitScalar(u8, body, '\n'); - while (it.next()) |r| if (std.mem.indexOf(u8, r, needle) != null) return r; - return null; - } - }.at; - - // The BODY is what you look at, and it follows the mode: in tty the pane - // is the program's own screen, so the prompt is there. - sp.body.mode = .tty; - try std.testing.expectEqualStrings( - "user@box ~/src $ grep -rn TODO src/", - bodyRowOf(p, sp, "grep") orelse return error.MissingPromptRow, - ); - - sp.body.mode = .normal; - try std.testing.expectEqualStrings( - "grep -rn TODO src/", - bodyRowOf(p, sp, "grep") orelse return error.MissingPromptRow, - ); - - p.shell_rows.stale = true; - try std.testing.expectEqualStrings( - "grep -rn TODO src/", - rowOf(p, sp, "grep") orelse return error.MissingPromptRow, - ); - - // ...and a prompt with nothing typed at it yet is all chrome, so the whole - // row goes, which is what it has always done. - p.update(.{ .output = .{ - .pane = @intCast(shell), - .bytes = "\r\n\x1b]133;A\x1b\\user@box ~/src $ \x1b]133;B\x1b\\", - } }); - p.sync(); - p.shell_rows.stale = true; - try std.testing.expect(rowOf(p, sp, "user@box") == null); -} - -test "entering tty walks the shell cursor to the column clicked past the prompt" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); - p.update(.{ .key = .{ .cp = 'n', .alt = true } }); - const shell = p.active; - const sp = p.panes[shell].?; - p.update(.{ .output = .{ - .pane = @intCast(shell), - .bytes = "\x1b]133;A;cl=line\x1b\\prompt> \x1b]133;B\x1b\\0123456789", - } }); - p.sync(); - sp.body.mode = .normal; - p.shell_rows.stale = true; - - // The command shows LEFT-HUGGED, so its column 3 is the '3'... - const rows = try panes.terminal.shellRows(p, sp); - var row: i32 = 0; - const at = for (rows, 0..) |r, i| { - if (std.mem.indexOf(u8, r, "0123456789") != null) break i; - } else return error.MissingInputRow; - row = @intCast(at); - try std.testing.expectEqualStrings("0123456789", rows[at]); - - // ...but the shell's own cursor lives on the real grid, eight cells - // further right, behind the prompt this pane is not showing. - sp.body.cur_row = row; - sp.body.cur_col = 3; - sp.body.cur_pinned = true; - while (p.nextEffect()) |_| {} - panes.terminal.enterTty(p, shell); - - // The walk is arrow keys the shell understands. Seven lefts: readline's - // cursor sits past the '9' and the click was on the '3'. - var lefts: usize = 0; - var rights: usize = 0; - while (p.nextEffect()) |effect| switch (effect) { - .write => |wr| { - if (std.mem.eql(u8, wr.bytes.slice(), "\x1b[D")) lefts += 1; - if (std.mem.eql(u8, wr.bytes.slice(), "\x1b[C")) rights += 1; - }, - else => {}, - }; - try std.testing.expectEqual(@as(usize, 0), rights); - try std.testing.expectEqual(@as(usize, 7), lefts); -} - -fn bootAndTearDown(gpa: std.mem.Allocator) !void { - const p = try Pardes.init(gpa, .{ .cols = 56, .rows = 14, .tty_only = true, .frame_allocator = gpa, .image_allocator = gpa, .pdf_allocator = gpa, .tree_sitter_allocator = gpa }); - p.deinit(); -} - -test "every allocation failure during boot is a clean OutOfMemory" { - try std.testing.checkAllAllocationFailures(std.testing.allocator, bootAndTearDown, .{}); -} +pub const Pardes = @import("Core.zig"); +pub const Options = Pardes.Options; +pub const Boot = Pardes.Boot; +pub const Haptic = Pardes.Haptic; |
