diff options
| -rw-r--r-- | abi/addon.zig | 24 | ||||
| -rw-r--r-- | abi/term.zig | 4 | ||||
| -rw-r--r-- | addons/pdf/pdf.zig | 57 | ||||
| -rw-r--r-- | build/addons.zig | 9 | ||||
| -rw-r--r-- | build/core.zig | 15 | ||||
| -rw-r--r-- | build/tests.zig | 1 | ||||
| -rw-r--r-- | core/Addon.zig | 2 | ||||
| -rw-r--r-- | core/Core.zig | 2 | ||||
| -rw-r--r-- | core/Kind.zig | 17 | ||||
| -rw-r--r-- | core/hunks.zig | 49 | ||||
| -rw-r--r-- | core/jj.zig | 333 | ||||
| -rw-r--r-- | core/mouse.zig | 6 | ||||
| -rw-r--r-- | core/ninep/pty.zig | 81 | ||||
| -rw-r--r-- | core/panes.zig | 4 | ||||
| -rw-r--r-- | core/plumbing | 9 | ||||
| -rw-r--r-- | core/surface.zig | 3 | ||||
| -rw-r--r-- | core/term/terminal.zig | 12 | ||||
| -rw-r--r-- | dev/gui/gui.zig | 35 | ||||
| -rw-r--r-- | docs/typ/cheatsheet.typ | 2 | ||||
| -rw-r--r-- | docs/typ/guide.typ | 23 | ||||
| -rw-r--r-- | docs/typ/reference.typ | 3 | ||||
| -rw-r--r-- | runtime/daemon.zig | 16 | ||||
| -rw-r--r-- | runtime/upgrade.zig | 26 | ||||
| -rw-r--r-- | test/behaviour/addons_pdf.zig | 16 | ||||
| -rw-r--r-- | test/daemon.py | 162 | ||||
| -rw-r--r-- | test/process/look_and_exec.zig | 14 | ||||
| -rw-r--r-- | test/process/terminals.zig | 17 |
27 files changed, 744 insertions, 198 deletions
diff --git a/abi/addon.zig b/abi/addon.zig index 1fa2279a..059e016d 100644 --- a/abi/addon.zig +++ b/abi/addon.zig @@ -248,8 +248,14 @@ pub fn loadBytes(s: anytype, bytes: []const u8, version: u32) bool { pub const body_max = 4096; var body_cut = false; -fn span(p: [*c]const u8, n: u64) []const u8 { - return if (p == null) "" else p[0..n]; +/// A C pointer and its count as a slice; NULL is none, whatever the count: +/// C says none with a NULL (a page's search without a hit, a selection +/// over no text, an outline of no entries), and a NULL C pointer sliced +/// is a safety panic even at length 0 (a release build's abort). Every +/// pointer a C struct or a C caller hands with its count is read through +/// it: pdf.zig's test holds the bridge's to it. +pub fn cSlice(ptr: anytype, n: usize) []const std.meta.Child(@TypeOf(ptr)) { + return if (ptr == null) &.{} else ptr[0..n]; } /// `pardes_addon` exported, when built as a library alone: the kind is its @@ -282,7 +288,7 @@ pub fn ops(comptime T: type) c.pa_ops { fn open(path: [*c]const u8, bytes: [*c]const u8, len: u64) callconv(.c) ?*anyopaque { const s = arena.create(T) catch return null; s.* = std.mem.zeroInit(T, .{}); - if (@hasDecl(T, "open")) T.open(s, if (path == null) null else std.mem.span(path), if (bytes == null) null else bytes[0..len]); + if (@hasDecl(T, "open")) T.open(s, if (path == null) null else std.mem.span(path), if (bytes == null) null else cSlice(bytes, len)); return s; } fn close(st: ?*anyopaque) callconv(.c) void { @@ -329,7 +335,7 @@ pub fn ops(comptime T: type) c.pa_ops { return @intCast(from.len); } fn address(st: ?*anyopaque, t: [*c]const u8, n: u32) callconv(.c) c_int { - return @intFromBool(T.address(self(st) orelse return 0, span(t, n))); + return @intFromBool(T.address(self(st) orelse return 0, cSlice(t, n))); } fn where(st: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 { return write(T.where, self(st) orelse return 0, buf, n); @@ -337,26 +343,26 @@ pub fn ops(comptime T: type) c.pa_ops { fn ctl(st: ?*anyopaque, line: [*c]const u8, n: u32, reply: [*c]u8, cap: u32) callconv(.c) c_int { var w: std.Io.Writer = .fixed(reply[0..cap -| 1]); defer reply[w.end] = 0; - return if (T.ctl(self(st) orelse return 1, span(line, n), &w)) c.PA_OK else 1; + return if (T.ctl(self(st) orelse return 1, cSlice(line, n), &w)) c.PA_OK else 1; } fn ctl_read(st: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 { return write(T.ctlRead, self(st) orelse return 0, buf, n); } fn job_run(in: [*c]const u8, n: u32, out: [*c]c.pa_out) callconv(.c) u32 { const gpa: Allocator = .{ .ptr = out, .vtable = &.{ .alloc = jobAlloc, .resize = Allocator.noResize, .remap = Allocator.noRemap, .free = Allocator.noFree } }; - return @intCast((T.jobRun(span(in, n), gpa) orelse return 0).len); + return @intCast((T.jobRun(cSlice(in, n), gpa) orelse return 0).len); } fn job_done(st: ?*anyopaque, token: u32, out: [*c]const u8, n: u32) callconv(.c) void { - T.jobDone(self(st) orelse return, token, span(out, n)); + T.jobDone(self(st) orelse return, token, cSlice(out, n)); } fn dump(st: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 { return @intCast(T.dump(self(st) orelse return 0, buf[0..n])); } fn load(st: ?*anyopaque, buf: [*c]const u8, n: u32, version: u32) callconv(.c) c_int { - return @intFromBool(!T.load(self(st) orelse return 1, span(buf, n), version)); + return @intFromBool(!T.load(self(st) orelse return 1, cSlice(buf, n), version)); } fn search(st: ?*anyopaque, pat: [*c]const u8, n: u32) callconv(.c) void { - T.search(self(st) orelse return, span(pat, n)); + T.search(self(st) orelse return, cSlice(pat, n)); } }; if (T.head.name.len > 15) @compileError(@typeName(T) ++ "'s name " ++ T.head.name ++ " is over 15 bytes"); diff --git a/abi/term.zig b/abi/term.zig index 31f155e8..e84d6998 100644 --- a/abi/term.zig +++ b/abi/term.zig @@ -78,7 +78,9 @@ pub const Prompt = struct { finished: ?Finished = null, /// The cursor is at a prompt's input, on either screen. input_ready: bool = false, - /// ...and nothing is typed on its line up to the cursor. + /// ...and nothing is typed on its line up to the cursor, nor on the + /// line above when a newline in the input began this one (a line taken + /// whose command has not started yet). input_empty: bool = false, /// The cursor is on a prompt's row or at its input, on the primary /// screen. diff --git a/addons/pdf/pdf.zig b/addons/pdf/pdf.zig index 8f314bbe..79d79219 100644 --- a/addons/pdf/pdf.zig +++ b/addons/pdf/pdf.zig @@ -759,7 +759,7 @@ pub const Pdf = extern struct { const found = in.n > 0 and m.pardes_pdf_search_page(ld, @intCast(in.page), &q, &r) == ok; defer if (found) m.pardes_pdf_drop_search_result(ld, r.handle); res.ok, res.n, res.hits = .{ 1, @intCast(t.len), if (found) @intCast(r.hit_count) else 0 }; - return answer(gpa, res, std.mem.concat(gpa, u8, &.{ t.data[0..t.len], if (found) std.mem.sliceAsBytes(r.quads[0..r.quad_count]) else "" }) catch return null); + return answer(gpa, res, std.mem.concat(gpa, u8, &.{ addon.cSlice(t.data, t.len), if (found) std.mem.sliceAsBytes(addon.cSlice(r.quads, r.quad_count)) else "" }) catch return null); } // each page's count of hits, then the rows var shown = @min(in.n, 200); @@ -1011,7 +1011,7 @@ fn pageText(o: *Own, page: u32) []const u8 { var t: m.pardes_pdf_text = undefined; if (m.pardes_pdf_page_text(d.base, @intCast(page), &t) != ok) return ""; defer m.pardes_pdf_drop_text(d.base, t.handle); - o.read.bytes = heap.dupe(u8, t.data[0..t.len]) catch &.{}; + o.read.bytes = heap.dupe(u8, addon.cSlice(t.data, t.len)) catch &.{}; return o.read.bytes; } @@ -1030,7 +1030,7 @@ fn hitsOf(st: *const Pdf, o: *Own) []const m.pardes_pdf_search_quad { var r: m.pardes_pdf_search_result = undefined; if (m.pardes_pdf_search_page(d.base, @intCast(f.hits_page), &q, &r) != ok) return &.{}; defer m.pardes_pdf_drop_search_result(d.base, r.handle); - o.hits = heap.dupe(m.pardes_pdf_search_quad, r.quads[0..r.quad_count]) catch &.{}; + o.hits = heap.dupe(m.pardes_pdf_search_quad, addon.cSlice(r.quads, r.quad_count)) catch &.{}; return o.hits; } @@ -1073,8 +1073,8 @@ fn selectHere(o: *Own, page: u32, from: Point, to: Point) ?usize { var t: m.pardes_pdf_owned_text = undefined; if (m.pardes_pdf_copy_selection(base, @intCast(page), sel.start, sel.end, &t) != ok) return null; defer m.pardes_pdf_drop_owned_text(base, t.handle); - o.sel_quads = heap.dupe(Quad, sel.quads[0..sel.quad_count]) catch &.{}; - o.sel_text = heap.dupe(u8, t.data[0..t.len]) catch &.{}; + o.sel_quads = heap.dupe(Quad, addon.cSlice(sel.quads, sel.quad_count)) catch &.{}; + o.sel_text = heap.dupe(u8, addon.cSlice(t.data, t.len)) catch &.{}; return sel.quad_count; } @@ -1691,11 +1691,11 @@ fn probeAt(st: *Pdf, id: u8, col: u16, row: u16) ?struct { page: u32, quad: Quad const uri = struct { var buf: [1024]u8 = undefined; }; - @memcpy(uri.buf[0..link.uri_len], link.uri[0..link.uri_len]); + @memcpy(uri.buf[0..link.uri_len], addon.cSlice(link.uri, link.uri_len)); link.uri = &uri.buf; var text: []u8 = &.{}; if (m.pardes_pdf_copy_rectangle(base, @intCast(at.page), link.quad, &t) == ok) { - text = heap.dupe(u8, t.data[0..t.len]) catch &.{}; + text = heap.dupe(u8, addon.cSlice(t.data, t.len)) catch &.{}; m.pardes_pdf_drop_owned_text(base, t.handle); } return .{ .page = at.page, .quad = link.quad, .text = text, .link = link }; @@ -1706,7 +1706,7 @@ fn probeAt(st: *Pdf, id: u8, col: u16, row: u16) ?struct { page: u32, quad: Quad if (sel.quad_count == 0 or m.pardes_pdf_copy_selection(base, @intCast(at.page), sel.start, sel.end, &t) != ok) return null; defer m.pardes_pdf_drop_owned_text(base, t.handle); if (t.len == 0) return null; - return .{ .page = at.page, .quad = sel.quads[0], .text = heap.dupe(u8, t.data[0..t.len]) catch return null, .link = null }; + return .{ .page = at.page, .quad = addon.cSlice(sel.quads, sel.quad_count)[0], .text = heap.dupe(u8, addon.cSlice(t.data, t.len)) catch return null, .link = null }; } /// A link followed: a place in the document scrolled to, else looked at @@ -1714,7 +1714,7 @@ fn probeAt(st: *Pdf, id: u8, col: u16, row: u16) ?struct { page: u32, quad: Quad /// both, a +Links. fn follow(st: *Pdf, link: m.pardes_pdf_link, text: []const u8) void { if (link.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) return goToXY(st, @intCast(link.page), link.has_x != 0, link.x, link.has_y != 0, link.y); - const uri = link.uri[0..link.uri_len]; + const uri = addon.cSlice(link.uri, link.uri_len); var shown: [512]u8 = undefined; var k: usize = 0; for (text) |ch| if (ch > ' ' and k < shown.len) { @@ -1749,10 +1749,10 @@ fn goToXY(st: *Pdf, page: u32, has_x: bool, x: f32, has_y: bool, y: f32) void { /// from 1), indented by depth; an entry with nowhere to go takes its first /// child's that has, and an http(s) one is its URI. fn usable(o: *const m.pardes_pdf_outline_result, i: usize) bool { - const it = o.items[i]; + const it = addon.cSlice(o.items, o.item_count)[i]; if (it.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) return true; if (it.destination_kind != m.PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL or it.uri_len == 0 or it.uri_len > 256) return false; - const u = o.bytes[it.uri_offset..][0..it.uri_len]; + const u = addon.cSlice(o.bytes, o.bytes_len)[it.uri_offset..][0..it.uri_len]; return (std.mem.startsWith(u8, u, "http://") or std.mem.startsWith(u8, u, "https://")) and for (u) |ch| { if (ch <= 0x20 or ch == 0x7f) break false; } else true; @@ -1760,9 +1760,10 @@ fn usable(o: *const m.pardes_pdf_outline_result, i: usize) bool { /// Entry `i`'s place: its own, else the first usable one below it. fn resolve(o: *const m.pardes_pdf_outline_result, i: usize) ?usize { - if (o.items[i].destination_kind != m.PARDES_PDF_OUTLINE_DESTINATION_NONE) return if (usable(o, i)) i else null; + const items = addon.cSlice(o.items, o.item_count); + if (items[i].destination_kind != m.PARDES_PDF_OUTLINE_DESTINATION_NONE) return if (usable(o, i)) i else null; var k = i + 1; - while (k < o.item_count and o.items[k].depth > o.items[i].depth) : (k += 1) if (usable(o, k)) return k; + while (k < items.len and items[k].depth > items[i].depth) : (k += 1) if (usable(o, k)) return k; return null; } @@ -1774,13 +1775,15 @@ fn sections(st: *Pdf) void { const rows = heap.alloc(u8, o.item_count * 300 + 1) catch return; defer heap.free(rows); var w: std.Io.Writer = .fixed(rows); - for (o.items[0..o.item_count], 0..) |it, i| { - const to = o.items[resolve(&o, i) orelse continue]; - if (to.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) w.print("{s}:{d}:{d} ", .{ ownOf(st).name, to.page + 1, i + 1 }) catch {} else w.print("{s} ", .{o.bytes[to.uri_offset..][0..to.uri_len]}) catch {}; + const items = addon.cSlice(o.items, o.item_count); + const bytes = addon.cSlice(o.bytes, o.bytes_len); + for (items, 0..) |it, i| { + const to = items[resolve(&o, i) orelse continue]; + if (to.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) w.print("{s}:{d}:{d} ", .{ ownOf(st).name, to.page + 1, i + 1 }) catch {} else w.print("{s} ", .{bytes[to.uri_offset..][0..to.uri_len]}) catch {}; w.splatByteAll(' ', 2 * it.depth) catch {}; // the title on one line: control and invalid characters a space // between words, none at either end - const t = o.bytes[it.title_offset..][0..it.title_len]; + const t = bytes[it.title_offset..][0..it.title_len]; const start = w.end; var gap = false; var i_: usize = 0; @@ -1811,9 +1814,9 @@ fn section(st: *Pdf, page: u32, ord: u32) bool { defer if (o.handle != null) m.pardes_pdf_drop_outline_result(base, o.handle); var said: [200]u8 = undefined; const r = if (m.pardes_pdf_load_outline(base, &o) == ok and ord > 0 and ord <= o.item_count) resolve(&o, ord - 1) else null; - const to = o.items[r orelse return miss(std.fmt.bufPrint(&said, "PdfSections: {s} has no section {d}", .{ ownOf(st).name, ord }))]; + const to = addon.cSlice(o.items, o.item_count)[r orelse return miss(std.fmt.bufPrint(&said, "PdfSections: {s} has no section {d}", .{ ownOf(st).name, ord }))]; if (to.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL) { - addon.look(o.bytes[to.uri_offset..][0..@min(to.uri_len, 256)]); + addon.look(addon.cSlice(o.bytes, o.bytes_len)[to.uri_offset..][0..@min(to.uri_len, 256)]); return true; } if (to.page + 1 != page) return miss(std.fmt.bufPrint(&said, "PdfSections: section {d} of {s} is on page {d}, not {d}", .{ ord, ownOf(st).name, to.page + 1, page })); @@ -1831,3 +1834,19 @@ fn miss(said: anyerror![]const u8) bool { fn noText() bool { return miss("has no text to address; its address is a page, :N"); } + +test "every pointer the bridge's structs hand back is read through addon.cSlice: none of them sliced or indexed bare (a NULL for none sliced at 0 was a release build's abort)" { + var src: []const u8 = @embedFile("pdf.zig"); // (searched at run time: at comptime it is over the branch quota) + _ = &src; + @setEvalBranchQuota(1_000_000); // (the translated header's every declaration) + inline for (@typeInfo(m).@"struct".decl_names) |name| { + if (comptime !std.mem.startsWith(u8, name, "pardes_pdf_") or @TypeOf(@field(m, name)) != type or @typeInfo(@field(m, name)) != .@"struct") continue; + const S = @typeInfo(@field(m, name)).@"struct"; + inline for (S.field_names, S.field_types) |field, F| if (comptime @typeInfo(F) == .pointer and @typeInfo(F).pointer.size == .c) { + if (std.mem.indexOf(u8, src, "." ++ field ++ "[")) |at| { + std.debug.print("pdf.zig:{d}: {s}.{s} read bare: addon.cSlice(ptr, count)\n", .{ std.mem.count(u8, src[0..at], "\n") + 1, name, field }); + return error.BareCPointer; + } + }; + } +} diff --git a/build/addons.zig b/build/addons.zig index 38b02dff..a1bdb43b 100644 --- a/build/addons.zig +++ b/build/addons.zig @@ -52,6 +52,9 @@ pub const Pdf = struct { /// `pardes_addon` alone. pub fn pdf(b: *std.Build, c: struct { addon_mod: *std.Build.Module, + /// pdf.zig's and the bridge's (core.zig's `addon_optimize`); MuPDF's + /// and the rest of the C's `c_optimize`. + addon_optimize: std.lang.Optimize, c_optimize: std.lang.Optimize, enable_jpx: bool, freetype: ?*std.Build.Step.Compile, @@ -83,7 +86,7 @@ pub fn pdf(b: *std.Build, c: struct { // The bridge's header translated here for pdf.zig (Zig 0.17 has no // @cImport), as the kinds' header is for the core. const bridge_mod = b.addTranslateC(.{ .root_source_file = b.path("addons/pdf/pdf_bridge.h"), .target = c.target, .optimize = c.c_optimize }).createModule(); - const pdf_mod = b.createModule(.{ .root_source_file = b.path("addons/pdf/pdf.zig"), .target = c.target, .optimize = c.c_optimize, .link_libc = true, .imports = &.{ .{ .name = "addon", .module = c.addon_mod }, .{ .name = "pdf_bridge", .module = bridge_mod } } }); + const pdf_mod = b.createModule(.{ .root_source_file = b.path("addons/pdf/pdf.zig"), .target = c.target, .optimize = c.addon_optimize, .link_libc = true, .imports = &.{ .{ .name = "addon", .module = c.addon_mod }, .{ .name = "pdf_bridge", .module = bridge_mod } } }); mupdf.linkTo(pdf_mod); pdf_mod.addIncludePath(b.path("addons/pdf")); pdf_mod.addCSourceFile(.{ .file = b.path("addons/pdf/pdf_bridge.c"), .flags = &.{"-std=gnu11"} }); @@ -105,8 +108,8 @@ pub fn pdf(b: *std.Build, c: struct { /// The image addon (addons/image/image.zig over stb_image, stb.c), /// installed by its step and handed by path to every test that opens a /// picture. -pub fn image(b: *std.Build, target: std.Build.ResolvedTarget, c_optimize: std.lang.Optimize, addon_mod: *std.Build.Module, zstbi_dep: *std.Build.Dependency) *std.Build.Step.Compile { - const image_mod = b.createModule(.{ .root_source_file = b.path("addons/image/image.zig"), .target = target, .optimize = c_optimize, .link_libc = true, .imports = &.{.{ .name = "addon", .module = addon_mod }} }); +pub fn image(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, addon_mod: *std.Build.Module, zstbi_dep: *std.Build.Dependency) *std.Build.Step.Compile { + const image_mod = b.createModule(.{ .root_source_file = b.path("addons/image/image.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "addon", .module = addon_mod }} }); image_mod.addIncludePath(zstbi_dep.path("libs/stbi")); image_mod.addCSourceFile(.{ .file = b.path("addons/image/stb.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } }); const image_addon = b.addLibrary(.{ .name = "image", .linkage = .dynamic, .root_module = image_mod }); diff --git a/build/core.zig b/build/core.zig index e8150843..f9cb450f 100644 --- a/build/core.zig +++ b/build/core.zig @@ -310,8 +310,10 @@ pub const Parts = struct { pdf: ?*std.Build.Module, term: *std.Build.Module, plain: *std.Build.Module, - /// The kinds' C ABI (abi/pardes_addon.h), translated. + /// The kinds' C ABI (abi/pardes_addon.h), translated, and what an addon + /// in Zig imports over it (abi/addon.zig: the core's `cSlice` too). kind: *std.Build.Module, + addon: *std.Build.Module, themes: *std.Build.Module, ts: TreeSitter, mvzr: *std.Build.Module, @@ -401,6 +403,7 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { if (c.terminal) x.addImport("term", p.term); x.addImport("plain", p.plain); x.addImport("pardes_addon", p.kind); + x.addImport("addon", p.addon); x.addImport("generated_themes", p.themes); x.addImport("tree-sitter", p.ts.mod); x.addImport("ts_queries", ts_queries); @@ -514,8 +517,15 @@ pub fn assemble(b: *std.Build, c: struct { const kind_mod = b.addTranslateC(.{ .root_source_file = b.path("abi/pardes_addon.h"), .target = target, .optimize = optimize }).createModule(); // ...and what an addon in Zig imports over it (abi/addon.zig). const addon_mod = b.createModule(.{ .root_source_file = b.path("abi/addon.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "pardes_addon", .module = kind_mod }} }); + // The C-backed addons' own Zig and bridge at the C's speed, with the + // checks a release keeps: ReleaseSafe in a Debug build, as in the + // user's (a page's search without a hit sliced a NULL: only a release + // build aborted, Debug's addons ran ReleaseFast); MuPDF and stb stay + // at c_optimize. + const addon_optimize: std.lang.Optimize = if (optimize == .debug) .safe else c_optimize; const pdf_built = addons.pdf(b, .{ .addon_mod = addon_mod, + .addon_optimize = addon_optimize, .c_optimize = c_optimize, .enable_jpx = c.enable_jpx, .freetype = freetype, @@ -602,7 +612,7 @@ pub fn assemble(b: *std.Build, c: struct { // library and no allocator hook of its own (it takes Zig allocators). const xitdb_mod = b.dependency("xitdb", .{ .target = target, .optimize = optimize }).module("xitdb"); - const image_addon = addons.image(b, target, c_optimize, addon_mod, zstbi_dep); + const image_addon = addons.image(b, target, addon_optimize, addon_mod, zstbi_dep); // The records the core and the terminal both name (abi/plain.zig). const plain_mod = b.createModule(.{ .root_source_file = b.path("abi/plain.zig"), .target = target, .optimize = optimize }); // The terminal, a module of its own (core/term/term.zig): the emulator and @@ -625,6 +635,7 @@ pub fn assemble(b: *std.Build, c: struct { .term = term_mod, .plain = plain_mod, .kind = kind_mod, + .addon = addon_mod, .themes = themes_mod, .ts = ts, .mvzr = mvzr_mod, diff --git a/build/tests.zig b/build/tests.zig index e0b33911..5e913501 100644 --- a/build/tests.zig +++ b/build/tests.zig @@ -162,6 +162,7 @@ pub fn add(b: *std.Build, c: struct { run_replicas.has_side_effects = true; b.step("replicas", "one authority and several replicas in process, each client typing over a delayed link: digests at quiescence, rollback rate and costs per RTT (-- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207])").dependOn(&run_replicas.step); for ([_]*std.Build.Module{ snake_mod, life_mod, liar_mod, c.parts.image }) |m| addon_test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); + if (c.pdf_addon) |lib| addon_test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lib.root_module })).step); // ...and the pdf addon's, which mupdf-check runs too (its script // opens docs/design.pdf, from the build root). const libs = [_]struct { ?*std.Build.Step.Compile, []const u8 }{ .{ fake_addon_lib.?, "addons/fake/fake" }, .{ snake_lib, "addons/snake/snake" }, .{ c.snake_shader_lib, "addons/snake_shader/snake_shader" }, .{ life_lib, "addons/life/life" }, .{ c.pdf_addon, "addons/pdf/pdf" } }; diff --git a/core/Addon.zig b/core/Addon.zig index aa3195f9..e93a43dc 100644 --- a/core/Addon.zig +++ b/core/Addon.zig @@ -532,7 +532,7 @@ pub const LoadedWord = struct { name: []const u8, leader: []const u8 = "", arg: /// `ops`'s head as a `Loaded` (its words borrowed from it, in `words`). pub fn loadedOf(ops: *const Kind.Ops, path: []const u8, hash: [32]u8, words: *[64]LoadedWord) Loaded { const h = &ops.head; - const head_words = if (h.nwords == 0 or h.words == null) &.{} else h.words[0..@min(h.nwords, words.len)]; + const head_words = @import("addon").cSlice(h.words, @min(h.nwords, words.len)); for (head_words, words[0..head_words.len]) |*w, *out| out.* = .{ .name = if (w.name == null) "" else std.mem.span(w.name), .leader = if (w.leader == null) "" else std.mem.span(w.leader), diff --git a/core/Core.zig b/core/Core.zig index 2c6567ed..f5ed28bd 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -1070,6 +1070,7 @@ fn acknowledgeShellInner(p: *Pardes, id: Pane.Id, executable: []const u8, prompt if (id.index() < MAX_PANES) if (p.panes[id.index()]) |pane| { ctlfs.pty.shellGone(p, pane, true); // a respawn replaced whatever ran pane.shell_failed = false; + pane.greeted = false; pane.had_shell = true; pane.fs.unmarked = !prompt_marks; // The tag's Term word names the shell the host ran, and a click @@ -2010,6 +2011,7 @@ pub fn sync(p: *Pardes) void { p.emit(.{ .resize_pty = .{ .pane = .at(id), .cols = pane.cols, .rows = pane.rows } }); p.emitWrite(id, "ls\r"); pane.greet = false; + pane.greeted = true; }, }; } diff --git a/core/Kind.zig b/core/Kind.zig index 49076f78..5d2dcdb0 100644 --- a/core/Kind.zig +++ b/core/Kind.zig @@ -17,6 +17,7 @@ const std = @import("std"); const builtin = @import("builtin"); pub const c = @import("pardes_addon"); +const cSlice = @import("addon").cSlice; const pardes = @import("root.zig"); const walk = @import("walk.zig"); const surface = @import("surface.zig"); @@ -1130,7 +1131,7 @@ pub const api: c.pa_api = .{ .look = struct { fn f(text: [*c]const u8, n: u32) callconv(.c) void { const cl = current orelse return; - if (!cl.quiet and text != null) cl.look.set(text[0..n]); + if (!cl.quiet and text != null) cl.look.set(cSlice(text, n)); } }.f, .say = struct { @@ -1138,8 +1139,8 @@ pub const api: c.pa_api = .{ const cl = current orelse return; if (cl.quiet or text == null) return; // Refusing its open: the opener says why. - if (err != 0 and cl.opening) return cl.refused.set(text[0..n]); - cl.said.set(text[0..n]); + if (err != 0 and cl.opening) return cl.refused.set(cSlice(text, n)); + cl.said.set(cSlice(text, n)); cl.err = err != 0; } }.f, @@ -1149,8 +1150,8 @@ pub const api: c.pa_api = .{ const cl = current orelse return 0; const p = cl.p orelse return 0; if (cl.quiet or name == null or cl.pane_name.len > 0) return 0; - cl.pane_name.set(name[0..name_len]); - cl.pane_text = p.scratch.allocator().dupe(u8, if (bytes == null) "" else bytes[0..n]) catch ""; + cl.pane_name.set(cSlice(name, name_len)); + cl.pane_text = p.scratch.allocator().dupe(u8, cSlice(bytes, n)) catch ""; return p.next_serial + 1; } }.f, @@ -1181,7 +1182,7 @@ pub const api: c.pa_api = .{ .exec = struct { fn f(text: [*c]const u8, n: u32) callconv(.c) void { const cl = current orelse return; - if (!cl.quiet and text != null) cl.exec.set(text[0..n]); + if (!cl.quiet and text != null) cl.exec.set(cSlice(text, n)); } }.f, .select = struct { @@ -1189,7 +1190,7 @@ pub const api: c.pa_api = .{ const cl = current orelse return; if (cl.quiet) return; const p = cl.p orelse return; - cl.selected = p.scratch.allocator().dupe(u8, if (text == null) "" else text[0..n]) catch return; + cl.selected = p.scratch.allocator().dupe(u8, cSlice(text, n)) catch return; } }.f, .cancel = struct { @@ -1234,7 +1235,7 @@ pub const api: c.pa_api = .{ const cl = current orelse return; const p = cl.p orelse return; if (cl.quiet or rows == null) return; - cl.rows = std.mem.concat(p.scratch.allocator(), u8, &.{ cl.rows, rows[0..n] }) catch return; + cl.rows = std.mem.concat(p.scratch.allocator(), u8, &.{ cl.rows, cSlice(rows, n) }) catch return; } }.f, }; diff --git a/core/hunks.zig b/core/hunks.zig index bee06cc2..e109b788 100644 --- a/core/hunks.zig +++ b/core/hunks.zig @@ -701,7 +701,9 @@ fn trimmedWidth(ctx: *const Ctx, section: []const u8) usize { /// (a .diff, a .patch: relative to the pane's directory), its hunks /// stacked so; with a revision (7 to 40 lowercase hex digits, a letter and /// a digit among them), `git show` of it, paged into a +Pager that stacks -/// its hunks (ctl.fillPager), run in the pane's git work tree. A plumbing +/// its hunks (ctl.fillPager), run in the pane's git work tree; with a jj +/// change (`Diff wrnnmymq [path[:line]]`: jj.diffChange), its patch, header +/// and all, the cursor at that place in it. A plumbing /// rule's Diff that cannot (no hunk, no work tree) declines, saying /// nothing (Pardes.plumb_declined), and the look looks itself. pub fn word(c: pardes.builtins.Ctx) void { @@ -731,6 +733,9 @@ pub fn word(c: pardes.builtins.Ctx) void { if (p.panes[dst]) |cp| cp.command_pages = true; return; } + // A jj change (its letters k to z), with a place in its patch to stand at. + if (@import("jj.zig").diffChange(p, c.id, arg)) return; + if (@import("jj.zig").isChangeId(arg[0 .. std.mem.indexOfAny(u8, arg, " \t") orelse arg.len])) return declined(p, c.id, "Diff: no such change"); var buf: [4096]u8 = undefined; const path = if (arg[0] == '/') arg else std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, Pardes.paneDir(c.pane), "/"), arg }) catch arg; const bytes = pardes.filesystem.read(p, path) catch |err| { @@ -1072,6 +1077,48 @@ test "a mailed patch keeps its headers, message and diffstat above its hunks" { try testing.expectEqualStrings("From 0123 Mon Sep 17 00:00:00 2001\nSubject: [PATCH] change x\n\nWhy it changed.\n---\n x.txt | 2 +-\n\nx.txt:1\n-a\n+b\n", result.content); } +test "a log of several changes keeps each one's header and whole message above its own hunks: git log -p, jj show's header" { + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); + const log = + \\commit 1111111111111111111111111111111111111111 + \\Author: A <a@a> + \\Date: Mon Nov 23 10:00:00 2026 -0300 + \\ + \\ second + \\ + \\ its body, a line + \\ + \\diff --git a/x.txt b/x.txt + \\index 1..2 100644 + \\--- a/x.txt + \\+++ b/x.txt + \\@@ -1 +1 @@ + \\-b + \\+c + \\ + \\commit 2222222222222222222222222222222222222222 + \\Author: A <a@a> + \\Date: Mon Nov 23 09:00:00 2026 -0300 + \\ + \\ first + \\ + \\diff --git a/x.txt b/x.txt + \\index 0..1 100644 + \\--- a/x.txt + \\+++ b/x.txt + \\@@ -1 +1 @@ + \\-a + \\+b + \\ + ; + const result = try paneResult(testing.allocator, try format(&t.ctx, "/pardes-surely-missing-dir", log)); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); + try testing.expectEqualStrings("commit 1111111111111111111111111111111111111111\nAuthor: A <a@a>\nDate: Mon Nov 23 10:00:00 2026 -0300\n\n second\n\n its body, a line\n\nx.txt:1\n-b\n+c\n\ncommit 2222222222222222222222222222222222222222\nAuthor: A <a@a>\nDate: Mon Nov 23 09:00:00 2026 -0300\n\n first\n\nx.txt:1\n-a\n+b\n", result.content); +} + test "a .patch looked at opens its +Diff, and Diff goes to the text and back" { const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); defer p.deinit(); diff --git a/core/jj.zig b/core/jj.zig index 59e0e21d..1ec1a0dc 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -369,9 +369,10 @@ pub const Hunk = struct { /// A row a view shows that is not a line of the text (PARDES.md "Changes on /// the source view": a ghost row): a line a pin took away whole, drawn where /// it stood, red across; or a pin's description (`id title author age`), -/// after its last line, in its lane's colour. No number, the cursor steps -/// over it, search and selection do not see it; a Look on it goes to its -/// line in the revision it came from (`lookGhost`). A line a pin CHANGED +/// after its last line, its lane an arrow to it. No number, the cursor +/// steps over it, search and selection do not see it; a Look on it looks at +/// its word as anywhere, on a description's id its change's patch +/// (`lookGhost`). A line a pin CHANGED /// is a ghost row too: its old text right above the line, the words that /// went in red, the line with the words that came in green. pub const Ghost = struct { @@ -1425,10 +1426,12 @@ fn ghostLanes(ch: *const Changes, ghosts: []const Ghost, gi: usize) [levels]PinI } /// A ghost row's cells: a line taken away whole red across, its text in -/// the line numbers' grey (dimmer than the text's ink); a description in -/// its lane's colour, its author and age grey; `said`, the row's text as -/// the body shows it (a description `fitted`). -fn inkGhost(p: *Pardes, s: *pardes.Surface, g: Ghost, said: []const u8, marks: []const [2]u32, colours: []const [3]u8, x: u16, y: u16, w: u16) void { +/// the line numbers' grey (dimmer than the text's ink); a description's id +/// and title in its lane's colour `lane`, or with one change pinned (no one +/// colour a lane) its id in the theme's keyword ink; its author and age +/// grey; `said`, the row's text as the body shows it (a description +/// `fitted`). +fn inkGhost(p: *Pardes, s: *pardes.Surface, g: Ghost, said: []const u8, marks: []const [2]u32, lane: ?[3]u8, x: u16, y: u16, w: u16) void { const th = p.theme(); switch (g.kind) { .deleted => s.tint(x, y, w, pardes.colors.Grounds.of(th).del.row, th.lineno), @@ -1445,9 +1448,13 @@ fn inkGhost(p: *Pardes, s: *pardes.Surface, g: Ghost, said: []const u8, marks: [ // `id title author age`: the last two words grey. var grey = said.len; for (0..2) |_| grey = std.mem.lastIndexOfScalar(u8, said[0..grey], ' ') orelse 0; - const lane_cells = File.displayWidth(p.settings.tab, said[0..grey]); + const id_cells = if (lane != null) File.displayWidth(p.settings.tab, said) else std.mem.indexOfScalar(u8, said, ' ') orelse said.len; + const title_cells = File.displayWidth(p.settings.tab, said[0..grey]); const cells = @min(w, File.displayWidth(p.settings.tab, said)); - for (0..cells) |c| s.at(x + @as(u16, @intCast(c)), y).style.fg = .{ .rgb = if (c < lane_cells) colours[g.pin % colours.len] else th.lineno }; + for (0..cells) |c| { + if (c >= id_cells and c < title_cells) continue; + s.at(x + @as(u16, @intCast(c)), y).style.fg = .{ .rgb = if (c >= title_cells) th.lineno else lane orelse th.kw }; + } }, } } @@ -1491,21 +1498,104 @@ pub fn nextChange(p: *Pardes, pane: *const Pane, from: usize, forward: bool) ?us return best; } -/// A Look on body row `vr` of pane `id` when it is a ghost row (mouse.zig, -/// a B3 click): the line it shows in the revision it came from, as the -/// address `path@rev:line` opens it (a line taken away: its pin's parent's; -/// a description: its pin's first line). False on any other row. -pub fn lookGhost(p: *Pardes, id: usize, vr: i32) bool { +/// A Look (B3) at column `col` of body row `vr` of pane `id` when it is a +/// ghost row (mouse.zig): a regular Look of the word there, as the same +/// text anywhere is looked at; on a description's id, its change's patch at +/// the row for the last line of its this file has (`Diff <id> <path>:<line>`, +/// what a user could type). False on any other row. +pub fn lookGhost(p: *Pardes, id: usize, vr: i32, col: i32) bool { const pane = p.panes[id].?; if (pane.layers.lanes == 0 or !pane.wrapAt(p.settings.tab, vr).ghost) return false; const ch = answered(p, pane.serial) orelse return false; const gi: usize = @intCast(-1 - pane.wrap_col[@intCast(vr)]); if (gi >= pane.ghosts.len) return false; const g = pane.ghosts[gi]; - const f = &pane.file.?; - const path = if (of(f)) |r| r.path else f.path; - const rev: [9]u8 = ch.pins[g.pin].id ++ "-".*; - _ = open(p, id, path, rev[0 .. if (g.kind == .description) 8 else 9], .{ .line = g.line }, false); + const said = pane.ghost_text[g.text..][0..g.len]; + const at = File.rawAtDisplay(p.settings.tab, said, @intCast(@max(0, col - @as(i32, File.gutterWidth(pane))))); + const what = wordAt(said, at) orelse return true; + const id_end = std.mem.indexOfScalar(u8, said, ' ') orelse said.len; + if (g.kind == .description and what.ptr == said.ptr and what.len == id_end) { + const f = &pane.file.?; + const path = if (of(f)) |r| r.path else f.path; + var last: u32 = g.line; + for (ch.hunks) |h| if (h.pin == g.pin) { + last = @max(last, h.new_start + h.new_len -| 1); + }; + var line: [4200]u8 = undefined; + const arg = std.fmt.bufPrint(&line, "{s} {s}:{d}", .{ ch.pins[g.pin].id, path, last }) catch return true; + pardes.exec.runBuiltin(p, .Diff, id, "Diff", arg); + return true; + } + pardes.look.lookAt(p, id, what); + return true; +} + +/// The word of a ghost row's text at byte `at`: a run of what a path, a +/// name, an address or an id is made of. +fn wordAt(text: []const u8, at: usize) ?[]const u8 { + const part = struct { + fn of(c: u8) bool { + return std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "_./:@-+~", c) != null or c >= 0x80; + } + }.of; + if (at >= text.len or !part(text[at])) return null; + var lo = at; + while (lo > 0 and part(text[lo - 1])) lo -= 1; + var hi = at; + while (hi < text.len and part(text[hi])) hi += 1; + return std.mem.trimEnd(u8, text[lo..hi], ".:"); +} + +/// A jj change id as jj writes one: its letters, k to z. +pub fn isChangeId(text: []const u8) bool { + if (text.len < 4 or text.len > 32) return false; + for (text) |c| if (c < 'k' or c > 'z') return false; + return true; +} + +/// `Diff <change> [path[:line]]` (hunks.zig): change `change` of the +/// repository pane `id`'s directory is in, its patch as `jj show --git` +/// prints it (its ids, author, dates and whole message above its hunks), +/// stacked in its +Diff (one a change: a second goes to it); the cursor on +/// the patch's row for `path`'s line `line` (that file's first row +/// without one; none of it: the top). False when it names no change. +pub fn diffChange(p: *Pardes, id: usize, arg: []const u8) bool { + var words = std.mem.tokenizeAny(u8, arg, " \t"); + const change = words.next() orelse return false; + if (!isChangeId(change)) return false; + const dir = pardes.filesystem.localPath(Pardes.paneDir(p.panes[id].?)) orelse return false; + var buf: [64]u8 = undefined; + const revset = std.fmt.bufPrint(&buf, "change_id({s})", .{change}) catch return false; + const shown = p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, dir, @as([]const []const u8, &.{ "show", "--git", "-r", revset }) }); + const bytes = switch (shown) { + .refused => |why| { + p.gpa.free(why); + return false; + }, + .bytes => |b| b, + }; + defer p.gpa.free(bytes); + var name: [4200]u8 = undefined; + const hid = @import("hunks.zig").openDiff(p, id, std.fmt.bufPrint(&name, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), change }) catch return false, bytes) catch return false; + p.view().active = hid; + const place = look.parsePathLine(words.next() orelse return true); + const pane = p.panes[hid].?; + const rows = pane.file.?.location_rows; + const want = std.Io.Dir.path.resolvePosix(p.scratch.allocator(), &.{ dir, place.path }) catch return true; + var best: ?usize = null; + for (rows, 0..) |row, i| { + if (!std.mem.endsWith(u8, want, row.path) or row.path.len == 0) continue; + if (best == null) best = i; + if (row.at.line == place.at.line) { + best = i; + break; + } + } + if (best) |i| { + pane.body.cur_row = @intCast(i); + pane.body.cur_col = 0; + pane.ensureCursorVisible(p.settings.tab); + } return true; } @@ -1539,6 +1629,26 @@ fn nest(lines: []Line, npins: usize) void { } } +/// A diff's two inks (one change pinned, `paintLanes`): its lane's colour +/// says the kind of the row it stands beside (the user's rulings of +/// 2026-11-23), `added` beside a row it wrote (a line added whole, a changed +/// line's new text), `taken` beside a row it took away (a line taken away, a +/// changed line's old text). +pub const Inks = struct { added: [3]u8, taken: [3]u8 }; + +/// The diff's own two colours: the theme's green and its red (the grounds' +/// and the changed words' hues), each pushed toward the ink until it reads +/// 3:1 on the page (or nearly as the ink does, where the ink reads less). +pub fn laneInks(th: *const pardes.Theme) Inks { + var inks: [2][3]u8 = .{ if (th.palette) |c| c[2] else .{ 0x2e, 0xa0, 0x43 }, themeRed(th) }; + const page = th.bg orelse th.tag_bg; + for (&inks) |*ink| { + var step: usize = 0; + while (step < 8 and pardes.colors.contrast(ink.*, page) < 3) : (step += 1) ink.* = pardes.colors.mixOklab(ink.*, th.fg orelse th.tag_fg, 0.4); + } + return .{ .added = inks[0], .taken = inks[1] }; +} + /// The lanes' colours, a pin's the `pin % len`th, oldest first: the /// theme's accents but the two that mean written and taken away (its green /// and red), in hue order from the top, each a hue `hue_apart` or more from @@ -1666,6 +1776,9 @@ fn paintLanes(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u var buf: [8][3]u8 = undefined; const colours = laneColours(p.theme(), &buf); if (colours.len == 0) return; + // One change pinned is a diff: its lane in the diff's own two colours, + // by the row's kind; several, a colour a change, to tell them apart. + const one: ?Inks = if (ch.pins.len == 1) laneInks(p.theme()) else null; const gutter = File.gutterWidth(pane); const cells = File.laneCells(pane); if (gutter >= tw or cells == 0) return; @@ -1677,13 +1790,18 @@ fn paintLanes(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u var vr: u16 = pane.context_rows; while (vr < body_h) : (vr += 1) { const y = body_y + vr; + var taken = false; + // On a description row, its change's lane: an arrow to it. + var points: PinIndex = .none; const lanes: [levels]PinIndex = if (vr < pane.wrap_n and pane.wrap_col[vr] < 0) ghost: { const gi: usize = @intCast(-1 - pane.wrap_col[vr]); if (gi >= pane.ghosts.len) continue; const g = pane.ghosts[gi]; const said = pane.ghost_text[g.text..][0..g.len]; var fit: [row_max]u8 = undefined; - inkGhost(p, s, g, if (g.kind == .description) fitted(p.settings.tab, said, File.bodyWidth(pane), &fit) else said, ch.marks, colours, tx + gutter, y, tw - gutter); + inkGhost(p, s, g, if (g.kind == .description) fitted(p.settings.tab, said, File.bodyWidth(pane), &fit) else said, ch.marks, if (one == null) colours[g.pin % colours.len] else null, tx + gutter, y, tw - gutter); + if (g.kind == .description) points = @enumFromInt(g.pin); + taken = g.kind != .description or takenAbove(pane.ghosts, gi); break :ghost ghostLanes(ch, pane.ghosts, gi); } else line: { const row: i32 = if (pane.wrap_n == 0) scroll + @as(i32, vr) else if (vr < pane.wrap_n) pane.wrap_line[vr] else break; @@ -1695,20 +1813,38 @@ fn paintLanes(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u }; for (lanes, 0..) |lane, level| { if (lane == .none) break; - const rgb = colours[@intFromEnum(lane) % colours.len]; + const arrow = lane == points; + const rgb = if (one) |d| (if (taken) d.taken else d.added) else colours[@intFromEnum(lane) % colours.len]; if (windowed) { // A body a pixel shell draws as a layer is painted on a // temporary surface first: its lanes are not drawn yet. - if (s == &p.surface) s.lanes.append(p.gpa, .{ .x = first, .y = y, .level = @intCast(level), .rgb = rgb }) catch {}; + if (s == &p.surface) s.lanes.append(p.gpa, .{ .x = first, .y = y, .level = @intCast(level), .rgb = rgb, .arrow = if (arrow) @intCast(cells) else 0 }) catch {}; } else if (level < cells) { var style = s.at(first + @as(u16, @intCast(level)), y).style; style.fg = .{ .rgb = rgb }; - s.set(first + @as(u16, @intCast(level)), y, "\u{258e}", style); + // An arrow: the lane bent into a shaft and a head at the text + // (`╰─→`, the user's choice of 2026-11-23 over `▎─→`); from + // the last level, where there is one cell, a bent arrow. + const at: u16 = @intCast(level); + s.set(first + at, y, if (!arrow) "\u{258e}" else if (at + 1 == cells) "\u{21b3}" else "\u{2570}", style); + if (arrow) for (at + 1..cells) |c| s.set(first + @as(u16, @intCast(c)), y, if (c + 1 == cells) "\u{2192}" else "\u{2500}", style); } } } } +/// Whether the row above description `ghosts[gi]` is one its lanes stand +/// beside as taken away: a ghost row of a line at its place, not a line. +fn takenAbove(ghosts: []const Ghost, gi: usize) bool { + var j = gi; + while (j > 0) { + j -= 1; + if (ghosts[j].at != ghosts[gi].at) return false; + if (ghosts[j].kind != .description) return true; + } + return false; +} + // ---- tests ---- const testing = std.testing; @@ -2143,6 +2279,19 @@ test "Changes draws a lane a pinned change after the line number, nested ones a } } +test "a diff's two lane inks in every theme: its green and its red, never one colour, each read on the page" { + for (&pardes.colors.themes) |*th| { + const inks = laneInks(th); + errdefer std.debug.print("{s}: added {any} taken {any}\n", .{ th.name, inks.added, inks.taken }); + try testing.expect(!std.meta.eql(inks.added, inks.taken)); + const page = th.bg orelse th.tag_bg; + // 3:1, or as near the theme's own ink's as it reads (hex_poison's). + const floor = @min(3, pardes.colors.contrast(th.fg orelse th.tag_fg, page)) - 0.1; + try testing.expect(pardes.colors.contrast(inks.added, page) >= floor); + try testing.expect(pardes.colors.contrast(inks.taken, page) >= floor); + } +} + /// A function `fn` wrote, two of its lines `cut` took away whole, and one /// `mid` rewrote as two (one changed, one added whole). const Ghosts = struct { @@ -2183,7 +2332,7 @@ fn saidOf(arena: std.mem.Allocator, ch: *const Changes) ![3][]const u8 { return said; } -test "Changes draws what the text has not where it stood, as ghost rows: a line a change took away whole red across, each change's description after its last line in its lane's colour; no number, their lanes, the rows below moved down in this view alone" { +test "Changes draws what the text has not where it stood, as ghost rows: a line a change took away whole red across, each change's description after its last line in its lane's colour, its lane an arrow to it; no number, their lanes; one change pinned, its lane green beside what it wrote and red beside what it took away; the rows below moved down in this view alone" { const gpa = testing.allocator; var repo = try Ghosts.repo() orelse return error.SkipZigTest; defer repo.deinit(gpa); @@ -2220,19 +2369,27 @@ test "Changes draws what the text has not where it stood, as ghost rows: a line const lanes = [_][]const u8{ "0", "0", "02", "02", "02", "02", "01", "01", "01", "0", "0", "0" }; const Ground = enum { none, add, del }; const ground = [_]Ground{ .add, .add, .none, .none, .add, .none, .del, .del, .none, .add, .add, .none }; - for (lanes, ground, 0..) |pins, gr, row| { + // On a description row the level its change's arrow leaves from. + const arrows = [_]?usize{ null, null, null, null, null, 1, null, null, 1, null, null, 0 }; + for (lanes, ground, arrows, 0..) |pins, gr, arrow, row| { const y = body.y + @as(u16, @intCast(row)); if (windowed) { var n: usize = 0; for (s.lanes.items) |lane| if (lane.y == y) { + try testing.expect(lane.level < pins.len); try testing.expectEqual(colours[pins[lane.level] - '0'], lane.rgb); + try testing.expectEqual(@as(u8, if (arrow == lane.level) @intCast(File.laneCells(pane)) else 0), lane.arrow); n += 1; }; try testing.expectEqual(pins.len, n); - } else for (pins, 0..) |pin, level| { + } else for (0..levels) |level| { + // `▎` a lane; an arrow: its lane bent, a shaft, a head (`╰─→`). const cell = s.at(first + @as(u16, @intCast(level)), y); - try testing.expectEqualStrings("\u{258e}", cell.grapheme()); - try testing.expectEqual(pardes.Color{ .rgb = colours[pin - '0'] }, cell.style.fg); + const bent = arrow != null and arrow.? == level; + const glyph = if (level < pins.len) (if (!bent) "\u{258e}" else if (level + 1 == levels) "\u{21b3}" else "\u{2570}") else if (arrow == null) " " else if (level + 1 == levels) "\u{2192}" else "\u{2500}"; + try testing.expectEqualStrings(glyph, cell.grapheme()); + const pin = if (level < pins.len) pins[level] - '0' else pins[arrow orelse 0] - '0'; + if (!std.mem.eql(u8, glyph, " ")) try testing.expectEqual(pardes.Color{ .rgb = colours[pin] }, cell.style.fg); } const cell = s.at(body.x + File.gutterWidth(pane) + 1, y); const bg: ?[3]u8 = switch (gr) { @@ -2247,8 +2404,10 @@ test "Changes draws what the text has not where it stood, as ghost rows: a line } // A description's id and title in its lane's colour; a line taken // away in the numbers' grey. - for ([_]u16{ 5, 8, 11 }, [_]usize{ 2, 1, 0 }) |row, pin| + for ([_]u16{ 5, 8, 11 }, [_]usize{ 2, 1, 0 }) |row, pin| { try testing.expectEqual(pardes.Color{ .rgb = colours[pin] }, s.at(body.x + File.gutterWidth(pane), body.y + row).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = colours[pin] }, s.at(body.x + File.gutterWidth(pane) + 5, body.y + row).style.fg); + } try testing.expectEqual(pardes.Color{ .rgb = p.theme().lineno }, s.at(body.x + File.gutterWidth(pane) + 4, body.y + 6).style.fg); // The changed line: on its old text the word that went (`b`) red, // on it the word that came (`b2`) green; the rest of each neither. @@ -2262,10 +2421,35 @@ test "Changes draws what the text has not where it stood, as ghost rows: a line for (plain[0..6]) |row| try testing.expectEqualStrings(lines.next().?, Ghosts.text(pane, row)); p.toView(.at(0)); try testing.expectEqualStrings(said[2], Ghosts.text(pane, (try Ghosts.rows(p, pane, arena.allocator(), &buf))[5])); + // One change pinned, mid: a diff. Its rows `b();` (its old text), + // `b2();`, `x();`, its description: the lane red beside the first, + // green beside the lines, green into its arrow; its id the + // keyword's ink, its title the text's. + var one: [64]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&one, "Changes {s}", .{ch.pins[2].id}) }); + p.sync(); + const s1 = try p.render(arena.allocator()); + const top = s1.region(.body, id).?.rect.y; + const at = body.x + File.gutterWidth(pane) - File.laneCells(pane); + const inks = laneInks(p.theme()); + try testing.expect(!std.meta.eql(inks.added, inks.taken)); + for ([_]u16{ 2, 3, 4, 5 }, [_]bool{ true, false, false, false }) |row, red| { + const ink = if (red) inks.taken else inks.added; + if (windowed) { + var n: usize = 0; + for (s1.lanes.items) |lane| if (lane.y == top + row) { + try testing.expectEqual(ink, lane.rgb); + n += 1; + }; + try testing.expectEqual(@as(usize, 1), n); + } else try testing.expectEqual(pardes.Color{ .rgb = ink }, s1.at(at, top + row).style.fg); + } + try testing.expectEqual(pardes.Color{ .rgb = p.theme().kw }, s1.at(text_x, top + 5).style.fg); + try testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.theme().kw }, s1.at(text_x + 5, top + 5).style.fg)); } } -test "the cursor steps over ghost rows and selection does not see them; ]g and [g go from change to change; a Look on one opens its line in the revision it came from" { +test "the cursor steps over ghost rows and selection does not see them; ]g and [g go from change to change; a Look on one looks at its word as anywhere" { const gpa = testing.allocator; var repo = try Ghosts.repo() orelse return error.SkipZigTest; defer repo.deinit(gpa); @@ -2309,18 +2493,84 @@ test "the cursor steps over ghost rows and selection does not see them; ]g and [ key(p, "[g"); try testing.expectEqual(want, pane.body.cur_row); } - // A Look (B3) on `c();`'s ghost row: fn's revision (cut's parent) at its line 4. + // A Look (B3) on `c();`'s ghost row is a Look of `c`, as `Look c` + // typed in the pane: no file at a revision opens. + p.update(.{ .command = "Look a.zig:1" }); p.sync(); s = try p.render(arena.allocator()); body = s.region(.body, id).?.rect; - p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = x, .row = body.y + 6 } }); - p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = x, .row = body.y + 6 } }); - const shown = p.view().active; - try testing.expect(shown != id); - const f = &p.panes[shown].?.file.?; - try testing.expect(of(f) != null); - try testing.expectEqualStrings(Ghosts.fn_text, f.content); - try testing.expectEqual(@as(i32, 3), p.panes[shown].?.body.cur_row); + p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = body.x + File.gutterWidth(pane) + 4, .row = body.y + 6 } }); + p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = body.x + File.gutterWidth(pane) + 4, .row = body.y + 6 } }); + try testing.expectEqual(id, p.view().active); + for (p.panes) |slot| if (slot) |q| if (q.file) |*f| try testing.expect(of(f) == null); + const clicked: [2]i32 = .{ pane.body.cur_row, pane.body.cur_col }; + p.update(.{ .command = "Look a.zig:1" }); + look.lookAt(p, id, "c"); + try testing.expectEqual(clicked, [2]i32{ pane.body.cur_row, pane.body.cur_col }); +} + +test "a Look on a change's id opens its patch, its header and whole message at the top: on a description row, at the row of that change's last line in this file; in any text, at the top; a word that names no change is looked as any word" { + const gpa = testing.allocator; + var repo = try Ghosts.repo() orelse return error.SkipZigTest; + defer repo.deinit(gpa); + for ([_]bool{ false, true }) |windowed| { + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 30, .windowed = windowed }); + defer p.deinit(); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + const id = p.view().active; + const pane = p.panes[id].?; + p.update(.{ .command = "Changes ::@" }); + const ch = answered(p, pane.serial).?; + const mid = ch.pins[2].id; + p.sync(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const s = try p.render(arena.allocator()); + const body = s.region(.body, id).?.rect; + // mid's description (row 5): a B3 on its id. + const x = body.x + File.gutterWidth(pane) + 1; + p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = x, .row = body.y + 5 } }); + p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = x, .row = body.y + 5 } }); + const hid = p.view().active; + try testing.expect(hid != id); + const patch = p.panes[hid].?; + const f = &patch.file.?; + try testing.expectStringStartsWith(f.path, try std.fmt.allocPrint(arena.allocator(), "{s}/+Diff-", .{repo.dir})); + // jj show's header, the whole message, above the hunks. + var rows = std.mem.splitScalar(u8, f.content, '\n'); + try testing.expectStringStartsWith(rows.next().?, "Commit ID: "); + try testing.expectStringStartsWith(rows.next().?, try std.fmt.allocPrint(arena.allocator(), "Change ID: {s}", .{mid})); + try testing.expectStringStartsWith(rows.next().?, "Author : t <t@t>"); + try testing.expect(std.mem.indexOf(u8, f.content, "\n mid\n") != null); + // The cursor on mid's last line in a.zig, `x();` (its line 4). + try testing.expectEqualStrings("a.zig:4", try std.fmt.allocPrint(arena.allocator(), "{s}:{d}", .{ std.Io.Dir.path.basename(f.location_rows[@intCast(patch.body.cur_row)].path), f.location_rows[@intCast(patch.body.cur_row)].at.line })); + // The same, typed: one pane a change, the cursor moved there. + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + p.update(.{ .command = try std.fmt.bufPrint(&line, "Diff {s} a.zig:2", .{mid}) }); + try testing.expectEqual(hid, p.view().active); + try testing.expectEqual(@as(usize, 2), f.location_rows[@intCast(patch.body.cur_row)].at.line); + // In running text: the patch at its top. + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{ch.pins[1].id}) }); + const cut = p.panes[p.view().active].?; + try testing.expectStringStartsWith(cut.file.?.content, "Commit ID: "); + try testing.expect(std.mem.indexOf(u8, cut.file.?.content, "\n cut\n") != null); + try testing.expectEqual(@as(i32, 0), cut.body.cur_row); + // A word of k to z that names no change: no patch. + const patches = struct { + fn count(q: *Pardes) usize { + var n: usize = 0; + for (q.panes) |slot| if (slot) |o| if (o.file) |*of_| { + n += @intFromBool(std.mem.indexOf(u8, of_.path, "+Diff-") != null); + }; + return n; + } + }.count; + const before = patches(p); + p.update(.{ .command = "Look zzzzzzzz" }); + try testing.expectEqual(before, patches(p)); + } } test "ghost rows ride with the text: a line deleted above moves them up, a line they stood before deleted puts them before the next; a client replays it equal" { @@ -2385,14 +2635,13 @@ test "a description's ghost row keeps its author and age: in a pane narrower tha try testing.expect(File.displayWidth(p.settings.tab, row) <= room); try testing.expectStringStartsWith(row, try std.fmt.allocPrint(arena.allocator(), "{s} a title long", .{ch.pins[0].id[0..4]})); try testing.expectStringEndsWith(row, "\u{2026} t now"); - // Drawn: the id and the title in its lane's colour, the author and - // the age grey, at the row's end. + // Drawn: the id in the keyword's ink, the author and the age grey, + // at the row's end. p.sync(); const s = try p.render(arena.allocator()); const body = s.region(.body, id).?.rect; const x = body.x + File.gutterWidth(pane); - var cbuf: [8][3]u8 = undefined; - try testing.expectEqual(pardes.Color{ .rgb = laneColours(p.theme(), &cbuf)[0] }, s.at(x, body.y + 3).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = p.theme().kw }, s.at(x, body.y + 3).style.fg); const age_x = x + @as(u16, @intCast(File.displayWidth(p.settings.tab, row))) - 1; try testing.expectEqualStrings("w", s.at(age_x, body.y + 3).grapheme()); try testing.expectEqual(pardes.Color{ .rgb = p.theme().lineno }, s.at(age_x, body.y + 3).style.fg); diff --git a/core/mouse.zig b/core/mouse.zig index 91d2932c..7c9007a1 100644 --- a/core/mouse.zig +++ b/core/mouse.zig @@ -1250,10 +1250,10 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { } } else { const clk = pane.sel[b]; - // A right-click on a ghost row (jj.zig) looks at its line - // in the revision it came from. + // A right-click on a ghost row (jj.zig) looks at the word + // there, as anywhere. if (s.button == config.look_button and clk.r0 >= pane.tag_rows and clk.r0 == clk.r1 and clk.c0 == clk.c1 and - pane.layers.lanes > 0 and @import("jj.zig").lookGhost(p, s.id, clk.r0 - pane.tag_rows)) + pane.layers.lanes > 0 and @import("jj.zig").lookGhost(p, s.id, clk.r0 - pane.tag_rows, clk.c0)) { pane.sel[b].state = .none; return; diff --git a/core/ninep/pty.zig b/core/ninep/pty.zig index 43973491..2dd7f7f3 100644 --- a/core/ninep/pty.zig +++ b/core/ninep/pty.zig @@ -135,11 +135,12 @@ pub const status_len: u64 = 36; pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // Busy is what a run written now would be told: a command is running - // or a line is typed at the prompt. Before the shell's first prompt a - // run waits for it rather than answer busy, so that is not busy. + // or a line is typed at the prompt. Before the shell's first prompt, or + // the one after its greeting, a run waits for it rather than answer + // busy, so that is not busy. const marks = pardes.Term.prompt(pane.terminal); const busy = p.hostTtyTaken(id) or (!pane.fs.unmarked and (waitingRun(p, pane) != null or - (marks.prompts > 0 and (marks.phase != .input or !marks.input_empty)))); + (marks.prompts > 0 and !greeting(pane, marks) and (marks.phase != .input or !marks.input_empty)))); const out = p.fs.stage(p.gpa); const size = winsize(pane); out.print(p.gpa, "{d:>11} {d:>11} {d:>11}\n", .{ size[0], size[1], @intFromBool(busy) }) catch return Reply.fail(req.tag, E.NOMEM); @@ -230,8 +231,8 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { answer(p, slot, "error {s}", .{if (pane.command_done) "command done; not a shell" else "a command runs here, not a shell"}); } else if (pf.unmarked) { answer(p, slot, "error no prompt marks", .{}); - } else if (waitingRun(p, pane) != null or (marks.prompts > 0 and (marks.phase != .input or - !marks.input_empty or p.hostTtyTaken(id)))) + } else if (waitingRun(p, pane) != null or (marks.prompts > 0 and !greeting(pane, marks) and + (marks.phase != .input or !marks.input_empty or p.hostTtyTaken(id)))) { // Something is running or someone has typed at the prompt: sending // now would type into the middle of it. The phase is pardes's own @@ -248,7 +249,8 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { answer(p, slot, "busy", .{}); } else { // Sent now if the shell is at its prompt, or at its first prompt - // when it has not drawn one yet (noteMarks). + // when it has not drawn one yet, or the one after its greeting + // (noteMarks). slot.line = p.gpa.dupe(u8, line) catch return Reply.fail(req.tag, E.NOMEM); slot.phase = .waiting; pf.run = req.handle; @@ -296,7 +298,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { pf.run = null; return; } - if (marks.phase != .input or !marks.input_empty or p.hostTtyTaken(id)) return; + if (greeting(pane, marks) or marks.phase != .input or !marks.input_empty or p.hostTtyTaken(id)) return; slot.want = marks.started +% 1; slot.prompts = marks.prompts; slot.declined = marks.declined; @@ -361,6 +363,15 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { finish(p, slot, pane, done.status); } +/// The greeting typed at a new terminal's first prompt (Pane.greeted) is +/// its shell's first command until the prompt after it: its echo not back +/// yet, the prompt looks empty, and a line sent then would be typed behind +/// the `ls`, its start taken for the run's (the run answered with what ls +/// printed). `ls` always starts, so the wait ends. +fn greeting(pane: *const Pane, marks: pardes.Term.Prompt) bool { + return pane.greeted and (marks.started == 0 or (marks.started == 1 and marks.phase != .input)); +} + /// The shell's marks as the session's emulator has them (taped), as a /// run's step reads them: a screen-state replica's emulator is the last /// delta's, which comes at a frame and can be a unit behind the one it @@ -785,6 +796,62 @@ test "a run waiting for a new terminal's first prompt is the only line typed the try testing.expectEqualStrings("true\r", sent[0..len]); } +test "a prompt redrawn under a run's line, the line taken, is the line run: never `error not run`" { + const gpa = testing.allocator; + const p = try withTerm(gpa); + defer p.deinit(); + const node = Node.of(serialOf(p), .pty_run); + const out = struct { + fn put(pp: *Pardes, bytes: []const u8) void { + pp.update(.{ .output = .{ .pane = .at(0), .bytes = bytes } }); + while (pp.nextEffect()) |_| {} + } + }; + const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; + // A window's first terminal: bash's first prompt, then the window's + // first size (its rows a row shorter), which readline answers by + // drawing its prompt again: with the run's line on it when it had read + // it, its Enter not yet. Then the line taken: its newline, and in the + // next read PS0's C (bash writes them apart): bytes as pty/data read + // them off a ReleaseSafe window session's start. + out.put(p, "\x1b]133;D;0;aid=pardes\x07" ++ prompt); + const h = call(p, .{ .tag = 1, .op = .open, .node = node }).reply.handle; + try testing.expectEqualStrings("echo $$\r", call(p, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "echo $$\n" }).pty()); + out.put(p, "\r\x1b[K\r" ++ prompt ++ "echo $$"); + out.put(p, "\r\n\x1b[?2004l\r"); + try testing.expectEqual(Status.again, call(p, .{ .tag = 3, .op = .read, .node = node, .handle = h, .size = 64 }).reply.status); + out.put(p, "\x1b]133;C;aid=pardes\x074242\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt); + try testing.expectEqualStrings("exit 0\n4242\n", call(p, .{ .tag = 4, .op = .read, .node = node, .handle = h, .size = 64 }).bytes); +} + +test "a run written just after a new terminal's greeting is typed is not answered with the greeting's output" { + const gpa = testing.allocator; + const p = try withTerm(gpa); + defer p.deinit(); + p.panes[0].?.greet = true; // a Term's, in a window (resized) + p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); + while (p.nextEffect()) |_| {} + const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; + // The first prompt: the greeting typed at it, its echo not back yet. + p.update(.{ .output = .{ .pane = .at(0), .bytes = prompt } }); + var greeted: [16]u8 = undefined; + var len: usize = 0; + while (p.nextEffect()) |e| if (e == .write) { + const b = e.write.bytes.slice(); + @memcpy(greeted[len..][0..b.len], b); + len += b.len; + }; + try testing.expectEqualStrings("ls\r", greeted[0..len]); + const node = Node.of(serialOf(p), .pty_run); + const h = call(p, .{ .tag = 1, .op = .open, .node = node }).reply.handle; + _ = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "true\n" }); + for ([_][]const u8{ "ls\r\n\x1b]133;C;aid=pardes\x07notes.txt\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ prompt }) |bytes| { + p.update(.{ .output = .{ .pane = .at(0), .bytes = bytes } }); + while (p.nextEffect()) |_| {} + } + try testing.expectEqualStrings("exit 0\n", call(p, .{ .tag = 3, .op = .read, .node = node, .handle = h, .size = 64 }).bytes); +} + test "run answers how its command ended once the shell is back at a prompt" { const gpa = testing.allocator; const p = try withTerm(gpa); diff --git a/core/panes.zig b/core/panes.zig index 5bf6992a..4116c3e8 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -160,6 +160,10 @@ pub const Pane = struct { cols: u16, rows: u16, greet: bool = false, + /// Its greeting was typed (Pardes.layout): that `ls` is its shell's + /// first command, and a run written until the prompt after it waits for + /// that prompt (ninep/pty.zig `greeting`), as for the first. + greeted: bool = false, /// Its shell could not be started (Pardes.shellFailed): a run hears /// `error shell gone` at once. shell_failed: bool = false, diff --git a/core/plumbing b/core/plumbing index 4e8cd702..7292577f 100644 --- a/core/plumbing +++ b/core/plumbing @@ -43,6 +43,15 @@ data matches '[0-9a-f]*[0-9][0-9a-f]*' data matches '[0-9a-f]*[a-f][0-9a-f]*' plumb start Diff $0 +# a jj change id looked at in the editor (eight or more of its letters, +# k to z, as jj log shows them), in a jj repository: jj show, its header +# and its hunks, stacked in a +Diff (a word that names no change: Diff +# declines and the word is searched for) +type is text +src is pardes +data matches '[k-z]{8,32}' +plumb start Diff $0 + # a diff paged (git show, git log -p) is shown stacked in a +Diff in # its +Pager's place type is text/x-diff diff --git a/core/surface.zig b/core/surface.zig index 3452bc77..5b381958 100644 --- a/core/surface.zig +++ b/core/surface.zig @@ -155,6 +155,9 @@ pub const Lane = struct { y: u16, level: u8, rgb: [3]u8, + /// On its change's description row, the lane's end: an arrow to the + /// text, which stands this many cells from `x` (0: a strip). + arrow: u8 = 0, /// The levels a row shows at most: the ruled gutter fits three. pub const levels = 3; diff --git a/core/term/terminal.zig b/core/term/terminal.zig index 45c01841..88eb1443 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -927,9 +927,19 @@ pub fn prompt(state: ?*State) Term.Prompt { // Nothing further right counts: that is where fish draws a right // prompt, and fish suggests nothing on an empty line. const empty = ready and empty: { + var prompted = false; const row = cursor.page_pin.cells(.all); - for (row[0..@min(cursor.x + 1, row.len)]) |cell| + for (row[0..@min(cursor.x + 1, row.len)]) |cell| { if (cell.semantic_content == .input and !cell.isEmpty()) break :empty false; + prompted = prompted or cell.semantic_content == .prompt; + } + // A row with no prompt on it, begun by a newline in the input: the + // line above was taken, its Enter echoed and the command's C still + // to come (bash writes them apart), so it is typed still. + if (!prompted and cursor.page_row.semantic_prompt == .prompt_continuation) if (cursor.page_pin.up(1)) |above| { + for (above.cells(.all)) |cell| + if (cell.semantic_content == .input and !cell.isEmpty()) break :empty false; + }; break :empty true; }; return .{ diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 88ba023b..76af0ec8 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -5028,17 +5028,36 @@ fn laneDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, la const LaneRide = struct { x0: u16, x1: u16, y0: u16, y1: u16, dy: f32, top: f32, bottom: f32 }; /// `lane`'s strip, `w` pixels wide, on grid row `row`, riding a scroll's -/// rows when given one. +/// rows when given one; on its description row an arrow to the text: the +/// strip down to the row's middle, a shaft along it, a head half a strip +/// short of the text. fn laneStrip(g: *Gui, gpa: std.mem.Allocator, lane: pardes.Lane, row: i32, ride: ?*const LaneRide, w: f32, layout: CellLayout, win_w: f32, win_h: f32) !void { const x0 = @round(@as(f32, @floatFromInt(lane.x)) * layout.w + w / 2 + @as(f32, @floatFromInt(lane.level)) * (w + w / 2)); - var y0 = @as(f32, @floatFromInt(row)) * layout.h; - var y1 = y0 + layout.h; - if (ride) |r| { - y0 = @max(y0 - r.dy, r.top); - y1 = @min(y1 - r.dy, r.bottom); - if (y1 <= y0) return; + const top = @as(f32, @floatFromInt(row)) * layout.h; + const Piece = struct { + fn add(gu: *Gui, alloc: std.mem.Allocator, rd: ?*const LaneRide, rgb: [3]u8, x_0: f32, y_0: f32, x_1: f32, y_1: f32, ww: f32, wh: f32) !void { + var a = y_0; + var b = y_1; + if (rd) |r| { + a = @max(a - r.dy, r.top); + b = @min(b - r.dy, r.bottom); + } + if (b > a and x_1 > x_0) try addDecor(gu, alloc, x_0, a, x_1, b, rgb, 1, ww, wh); + } + }; + if (lane.arrow == 0) return Piece.add(g, gpa, ride, lane.rgb, x0, top, x0 + w, top + layout.h, win_w, win_h); + const mid = @round(top + (layout.h - w) / 2); + const tip = @round(@as(f32, @floatFromInt(lane.x + lane.arrow)) * layout.w - w / 2); + const head = @round(w * 1.5); + try Piece.add(g, gpa, ride, lane.rgb, x0, top, x0 + w, mid + w, win_w, win_h); + try Piece.add(g, gpa, ride, lane.rgb, x0 + w, mid, tip - head, mid + w, win_w, win_h); + // The head: a pixel row each, narrowing to the tip. + var dy: f32 = -head; + while (dy < head) : (dy += 1) { + const y = mid + w / 2 + dy; + const len = @round(head * (1 - @abs(dy + 0.5) / head)); + try Piece.add(g, gpa, ride, lane.rgb, tip - head, @round(y), tip - head + len, @round(y) + 1, win_w, win_h); } - try addDecor(g, gpa, x0, y0, x0 + w, y1, lane.rgb, 1, win_w, win_h); } /// Each pane's rule between its tag and body, and its scroll rail: a page diff --git a/docs/typ/cheatsheet.typ b/docs/typ/cheatsheet.typ index d65ca6d9..a590e402 100644 --- a/docs/typ/cheatsheet.typ +++ b/docs/typ/cheatsheet.typ @@ -119,7 +119,7 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla == Reviewing diffs `git diff` output is a diff: #btn("B3") on a file line, an `@@` or a line's `+`/`-` jumps there. #doc("tags", section: "reviewing-diffs") -#word("Changes") `revset` on a file's pane: a lane a change, ghost rows for what it took away, #keys("] g", "[ g") from change to change; #word("Churn") `3m`: each declaration's changes, grey to red; `a.zig@main:12` is a file at a revision. #doc("guide", section: "changes") +#word("Changes") `revset` on a file's pane: a lane a change (one change: green beside what it wrote, red beside what it took away), an arrow to its description, ghost rows for what it took away, #keys("] g", "[ g") from change to change; #btn("B3") on a change id: its patch, header first; #word("Churn") `3m`: each declaration's changes, grey to red; `a.zig@main:12` is a file at a revision. #doc("guide", section: "changes") == Finding things - A query pane under the pane: line 1 the query, its first word the source: `/pat`, `Find name` (fuzzy), `Grep text` (literal), `Recent`, `Panes`, `Symbols`, `All`. #keys("Ctrl-n", "Ctrl-p") step, #key("Enter") lands and keeps the rows, #key("Esc") puts things back. #word("Help"), #word("Tutor"). diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index e73eabaf..985d324d 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -307,13 +307,18 @@ Nothing is shown, and nothing asked of jj, until a word is run. [#word("Churn") `window` (#key("SPC t u"))], [counts, for each declaration, the window's changes that touched it, and shows them in this view; the window a revset, or a span of time back from now (`3d`, `2w`, `6m`, `1y`). Bare: hidden or shown again; with none counted yet, the file's whole history], [#keys("] g", "[ g")], [the next and the previous change's first line], [`path@rev`, `path@rev:line`], [the file at a revision (#doc("guide", section: "revision")): a #word("Look") anywhere opens it], + [#word("Diff") `change` `path:line`], [a jj change's patch, its header (ids, author, dates, the whole message) above its hunks, in its own `+Diff`, the cursor on `path`'s line in it; a #word("Look") on a change id (eight of its letters, `k` to `z`, as `jj log` shows them) anywhere opens it at its top], ) *Lanes.* Each pinned change gets a lane after the line number, from its -first line to its last, in the theme's accents in hue order (a colour too -close to the one before it skipped), oldest first; a change that rewrote -lines inside another's steps a lane to the right on those rows. A line -one added whole is green across the line. +first line to its last; a change that rewrote lines inside another's +steps a lane to the right on those rows. With one change pinned (bare +`Changes`, a diff) its lane is the diff's own colours: green beside the +lines it wrote, red beside what it took away; with several, each its own +of the theme's accents in hue order (a colour too close to the one before +it skipped), oldest first, so they are told apart. At a change's +description its lane ends in an arrow to it. A line one added whole is +green across the line. *Ghost rows.* What the file no longer has is drawn where it stood, a row of its own with no number: a line a change took away whole, red across; @@ -321,10 +326,12 @@ a line a change changed, its old text right above it with the words that went red, and on the line the words that came green (the patch view's alignment says which lines are one line changed); each change's description, `id title author age` (`3w`, `4m`), after its last line, in -its lane's colour, at one place after that change's own ghost rows. A -ghost row is not text: the cursor steps over it, search, selection and -the line numbers do not see it, and a #btn("B3") on one opens its line in -the revision it came from (`path@id-:line`; a description, `path@id`). It +its lane's colour (one change pinned: its id in the theme's keyword +colour), at one place after that change's own +ghost rows. The cursor steps over a ghost row, and search, selection and +the line numbers do not see it; a #btn("B3") on one looks at the word +there as anywhere, and on a description's id opens that change's patch +at the row for its last line here (`Diff id path:line`). It moves the rows below down in this view alone. It is one row, cut where the pane ends (never wrapped); in a narrow pane a description's title is cut, its author and age kept. A hunk that took away more than 1,024 diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index ac61ca74..fac705c6 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -914,7 +914,8 @@ Terminal panes also have #file("pty/"): the clear onward). Or: `busy: <program> is running` (bare `busy` when text is typed at the prompt, `busy alternate screen` on the alternate screen with no prompt drawn), `exit ?` (no status reported, not a success), `error not run` (the shell refused the line, e.g. a fish syntax error), `error shell gone`, `error no prompt marks`, and on a command pane `error a command runs here, not a shell` (`error command done; not a shell` once it ended). A line written - before a fresh terminal's first prompt waits for it. One line per run; a + before a fresh terminal's first prompt waits for it, and for the prompt + after the `ls` a new terminal in a directory greets with. One line per run; a second line before the answer is refused. #file("pty/run") relies on the OSC 133 marks pardes injects into bash and diff --git a/runtime/daemon.zig b/runtime/daemon.zig index 595d5107..97941a12 100644 --- a/runtime/daemon.zig +++ b/runtime/daemon.zig @@ -241,9 +241,8 @@ extern "c" fn close_range(first: c_uint, last: c_uint, flags: c_int) c_int; /// twice), on the listener and the lock as fds 3 and 4. fn spawn(listener: c_int, lock: c_int) bool { var exe_buf: [4096:0]u8 = undefined; - const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), &exe_buf) catch return false; - exe_buf[n] = 0; - const argv = [_:null]?[*:0]const u8{ &exe_buf, "--daemon", null }; + const exe = upgrade.startPath(&exe_buf) orelse return false; + const argv = [_:null]?[*:0]const u8{ exe, "--daemon", null }; const first = libc.fork(); if (first < 0) return false; if (first == 0) { @@ -268,7 +267,7 @@ fn spawn(listener: c_int, lock: c_int) bool { }; if (null_fd > 4) _ = libc.close(null_fd); _ = libc.chdir("/"); - _ = libc.execve(&exe_buf, &argv, @ptrCast(libc.environ)); + _ = libc.execve(exe, &argv, @ptrCast(libc.environ)); libc._exit(127); } var status: c_int = 0; @@ -677,8 +676,13 @@ fn stubWait(session: libc.pid_t, pipe: c_int) noreturn { if (libc.W.IFEXITED(s)) libc._exit(@intCast(libc.W.EXITSTATUS(s))); if (libc.W.IFSIGNALED(s)) { const sig = libc.W.TERMSIG(s); - const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; - posix.sigaction(sig, &default, null); + // A KILL's action is its default already and cannot be set + // (EINVAL: posix.sigaction's unreachable, the stub aborting with a + // trace on the terminal); any other is put back to it first. + if (sig != .KILL) { + const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; + posix.sigaction(sig, &default, null); + } _ = libc.raise(sig); } libc._exit(1); diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig index f59117ee..510c50ea 100644 --- a/runtime/upgrade.zig +++ b/runtime/upgrade.zig @@ -58,18 +58,28 @@ pub fn remember(args: []const [:0]const u8) void { }; } -/// Its path asked of the system (a readlink) and the file there now (a +/// Its path asked of the system (a readlink) and the file it runs (a /// stat), once: after the first frame, off a startup's way (the hosts' -/// loops; nothing is reinstalled within a frame of a start). +/// loops). A build can be installed at that path before then (a pair's +/// session, whose first pass comes after its client's first frame; a +/// loaded machine): Linux then names the path "PATH (deleted)", and the +/// file at the path is not the one it started from, the one it runs is. pub fn locate() void { if (located) return; located = true; - if (exe_len == 0) { - const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), &exe_buf) catch 0; - exe_buf[n] = 0; - exe_len = n; - } - if (exe()) |path| started_inode = inodeOf(path); + if (exe_len == 0) exe_len = if (startPath(&exe_buf)) |path| path.len else 0; + started_inode = if (builtin.os.tag == .linux) inodeOf("/proc/self/exe") else if (exe()) |path| inodeOf(path) else null; +} + +/// The path this process was started from, as the system names it, less +/// the " (deleted)" Linux adds once the file there was replaced (a +/// reinstall): the path is the path (what an Upgrade execs, and a daemon +/// started from here: daemon.zig `spawn`). +pub fn startPath(buf: *[4096:0]u8) ?[:0]const u8 { + const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), buf) catch return null; + const len = if (std.mem.endsWith(u8, buf[0..n], " (deleted)")) n - " (deleted)".len else n; + buf[len] = 0; + return buf[0..len :0]; } fn inodeOf(path: [:0]const u8) ?u64 { diff --git a/test/behaviour/addons_pdf.zig b/test/behaviour/addons_pdf.zig index cf5c8009..18fa503c 100644 --- a/test/behaviour/addons_pdf.zig +++ b/test/behaviour/addons_pdf.zig @@ -132,6 +132,22 @@ test "addons: a PDF's / lists its hits as file.pdf:P:H rows in a +Search, n walk try std.testing.expect(try s.focused() != n); } +test "addons: a PDF's / of what its page has not, and f on a PDF with no outline, each say so and the session goes on (the bridge's none is a NULL with a count of 0: a safe build's abort before)" { + var s = try Session.initFile(std.testing.allocator, "x\n"); + defer s.deinit(); + const n = try s.lookFile("docs/design.pdf"); + // No page has it: page 1's hits of it asked, none; a hit of it a miss. + try s.keys("/zzqxv\r"); + try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]); + _ = try s.refused(s.at("/pane/{d}/look", .{n}), ":1:1\n"); + try std.testing.expect(has(try s.read("/log"), "design.pdf has no search hit 1 on page 1")); + // tall.pdf has no outline. + const t = try s.lookFile("test/pdf-fixtures/tall.pdf"); + try s.keys("f"); + try std.testing.expect(has(try s.read("/log"), "PdfSections: this PDF has no outline")); + try std.testing.expectEqual(t, try s.focused()); +} + test "addons: a PDF's f is its PdfSections, its outline as places a Look in it goes to (none once the PDF is gone), and a jump back over a far one is Ctrl-o's, Forward's on, two places on a page a window apart two" { var s = try Session.initFile(std.testing.allocator, "x\n"); defer s.deinit(); diff --git a/test/daemon.py b/test/daemon.py index caa1272b..f456837b 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -188,14 +188,16 @@ def run(client, serial, line): client.close(fid) -def adopted_pid(client, pane): - """An adopted shell's `echo $$`, once it answers: sized twice at its - adoption (dev/Ptys.zig `take`), it draws its prompt again, and a run - sent into a prompt redrawn under it reads as not run (core/ninep/pty.zig - `noteMarks`).""" - wait_for('the adopted shell answers', lambda: run(client, pane, b'true\n') == b'exit 0\n') +def pid_in(client, pane): + """The pid of terminal `pane`'s shell, its `echo $$` by pty/run, asked + at once: a run written before its first prompt (or before the prompt + after its greeting) waits for it, and one under a prompt drawn again + (a window's first size, an adoption's two) is still the line run + (core/ninep/pty.zig). Any other answer is said whole.""" said = run(client, pane, b'echo $$\n') - return said.split(b'\n')[1], said + pid = re.fullmatch(rb'exit 0\n([0-9]+)\n', said) + assert pid, f'pane {pane}: `echo $$` answered {said!r}' + return int(pid[1]) # FreeBSD has no /proc: ps and procstat answer instead. @@ -611,7 +613,8 @@ def clients(binary): c = tc.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'c.check'))) started.append(c.pid) wait_for('client C\'s first frame', lambda: b'$' in tc.text(), timeout=20) - run(nine, shell, b'echo from-the-session\n') + said = run(nine, shell, b'echo from-the-session\n') + assert said == b'exit 0\nfrom-the-session\n', said os.write(tc.master, b'echo from-C\r') wait_for('client C\'s keys in the shell', lambda: b'from-C' in nine.read(f'/pane/{shell}/body')) wait_for('client C agrees with a shell\'s output', lambda: agreed(root / 'c.check', 0)) @@ -1332,12 +1335,18 @@ def pair_upgrade_views(binary): shutil.rmtree(root, ignore_errors=True) -def pair_exec_reaps(old, new): +def pair_exec_reaps(old, new, early=False): """PARDES_PAIR across builds: a pair started from `root/bin` (old), its session upgraded to the build installed there since (new): its client, the session's parent, execs that build (the blink) and is still its parent; Exit typed then: the client returns once the session is gone, - reaped, its status the session's (0), as before the exec.""" + reaped, its status the session's (0), as before the exec. `early`: old + and new the same build, installed again at once, before the session's + first pass round its loop, where it first looks its start path up + (upgrade.zig `locate`), and as the client starts the daemon from its + own (daemon.zig `spawn`): the path is the path, not Linux's "PATH + (deleted)", so the daemon starts and the session execs it; the client, + its build the session's still, joins again in place (no exec).""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rpx-', dir=scratch)) @@ -1352,36 +1361,48 @@ def pair_exec_reaps(old, new): notes = root / 'notes.txt' notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30))) terms = [] + sock = root / 'pardes-9p-px.sock' + c = session = None try: t = Term(30, 100) terms.append(t) c = t.spawn([str(binary), '--9p=px', str(notes)], env) - sock = root / 'pardes-9p-px.sock' + if early: + install(new, binary) wait_for('the socket', sock.exists) nine = Client(sock) session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) assert ppid(session) == c.pid wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) - install(new, binary) + if not early: + install(new, binary) ino = sock.stat().st_ino # Before the Upgrade: the exec'd client can draw before its exec is seen. mark = len(t.text()) nine.write('/ctl', b'Upgrade\n') nine.socket.close() wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60) - wait_for('the client on the new build', lambda: exe_of(c.pid) == (str(binary), True), timeout=30) + if early: + wait_for('joined again in place', lambda: b'joined again' in t.text()[mark:], timeout=30) + else: + wait_for('the client on the new build', lambda: on_build(c, binary), timeout=30) nine = reconnect(sock) assert ppid(session) == c.pid # The blink: its screen left and entered again, the notes drawn there. - wait_for('drawn again', lambda: (lambda x: x.rfind(b'\x1b[?1049h') > x.rfind(b'\x1b[?1049l') > mark - and b'line 3 of the notes' in x[x.rfind(b'\x1b[?1049h'):])(t.text()), timeout=30) + if not early: + wait_for('drawn again', lambda: b'line 3 of the notes' in (entered_again(t.text(), mark) or b''), timeout=30) nine.write('/ctl', b'Exit\n') nine.socket.close() assert c.wait(timeout=30) == 0, c.returncode # Its parent's wait returned: the session reaped, not a zombie left # to whoever takes it in. assert not os.path.exists(f'/proc/{session}') if procfs else not alive(session), open(f'/proc/{session}/stat').read() - print('pair exec reaps: a pair\'s client exec\'d at its session\'s Upgrade still reaps it at Exit, status 0') + print('pair exec reaps: a pair\'s client exec\'d at its session\'s Upgrade still reaps it at Exit, status 0' + + (' (the same build installed again before the session looked its path up: joined again in place)' if early else '')) + except (TimeoutError, AssertionError, OSError, EOFError, subprocess.TimeoutExpired) as err: + kept = keep_evidence('pair-exec', root, env, binary, sock, [('session', session)] if session else [], + [('client', t, c, root / 'client.check', root / 'client.stats')] if c else []) + raise AssertionError(f'{type(err).__name__}: {err} (kept: {kept})') from None finally: for p in processes(root): try: @@ -1439,8 +1460,8 @@ def far_exec(old, new): nine.socket.close() wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60) nine = reconnect(sock) - wait_for('the far client on the new build', lambda: exe_of(c.pid) == (str(binary), True), timeout=30) - wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30) + wait_for('the far client on the new build', lambda: on_build(c, binary), timeout=30) + wait_for('the terminal entered again', lambda: entered_again(t.text(), mark), timeout=30) # Its environment read once the new image runs (it entered the # screen): an exec names the new file in /proc/PID/exe before it has # written where the environment is, and a read between gets nothing @@ -1518,7 +1539,7 @@ def pair_window_geometry(gui_binary, new_gui): nine.write('/ctl', b'Upgrade\n') nine.socket.close() wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60) - wait_for('the window on the new build', lambda: exe_of(p.pid) == (str(gui), True), timeout=30) + wait_for('the window on the new build', lambda: on_build(p, gui), timeout=30) nine = reconnect(sock) time.sleep(3) assert grid(nine) == sized, ('the exec\'d window the size it had', grid(nine), sized, plain) @@ -1573,8 +1594,7 @@ def manage(binary): c.write('/pane/1/exec', b'Term\n') wait_for(f'session {name}\'s shell', lambda: terminals(c)) shell = terminals(c)[0] - wait_for(f'session {name}\'s shell answers', lambda: run(c, shell, b'true\n') == b'exit 0\n') - shells[name] = int(run(c, shell, b'echo $$\n').split(b'\n')[1]) + shells[name] = pid_in(c, shell) started.append(shells[name]) daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0] started.append(daemon) @@ -1678,8 +1698,7 @@ def relink(binary): work.write('/pane/1/exec', b'Term\n') wait_for('its shell', lambda: terminals(work)) shell = terminals(work)[0] - wait_for('its shell answers', lambda: run(work, shell, b'true\n') == b'exit 0\n') - shell_pid = int(run(work, shell, b'echo $$\n').split(b'\n')[1]) + shell_pid = pid_in(work, shell) started.append(shell_pid) term = Term() terms.append(term) @@ -1691,7 +1710,7 @@ def relink(binary): started.append(own_pid) wait_for('its first frame', lambda: b'\x1b[?1049h' in term.text()) own_shell = terminals(own)[0] - own_shell_pid = int(run(own, own_shell, b'echo $$\n').split(b'\n')[1]) + own_shell_pid = pid_in(own, own_shell) started.append(own_shell_pid) expected = [f'session work {session} {listed_as("detached")}', f'session own {own_pid} {listed_as("has a frontend")}', f'shell {shell_pid}', f'shell {own_shell_pid}'] @@ -1723,8 +1742,7 @@ def relink(binary): before = set(terminals(own)) own.write(f'/pane/{min(before)}/exec', b'Adopt\n') pane = wait_for('the adopted pane', lambda: set(terminals(own)) - before).pop() - pid, said = adopted_pid(own, pane) - assert pid == str(shell_pid).encode(), (said, shell_pid) + assert (pid := pid_in(own, pane)) == shell_pid, (pid, shell_pid) print(f'relink: a client attached to the session through the new daemon; killed outright, its shell {shell_pid} was adopted') exit_session(own, pane) stub.wait(timeout=10) @@ -1774,7 +1792,7 @@ def answer_late(binary): one = Client(root / 'pardes-9p-one.sock') session = int(dict(line.split(maxsplit=1) for line in one.read('/status').decode().splitlines())['pid']) started.append(session) - shell_pid = int(run(one, terminals(one)[0], b'echo $$\n').split(b'\n')[1]) + shell_pid = pid_in(one, terminals(one)[0]) started.append(shell_pid) daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0] started.append(daemon) @@ -1798,8 +1816,7 @@ def answer_late(binary): two.write(f'/pane/{min(before)}/exec', b'Adopt\n') took = time.monotonic() - asked pane = wait_for('the adopted pane', lambda: set(terminals(two)) - before).pop() - pid, said = adopted_pid(two, pane) - assert pid == str(shell_pid).encode(), (said, shell_pid) + assert (pid := pid_in(two, pane)) == shell_pid, (pid, shell_pid) print(f'answer late: an Adopt asked while the daemon was stopped waited {took:.1f} s for its answer, ' f'and shell {shell_pid} was adopted') exit_session(two, pane) @@ -2852,6 +2869,46 @@ def cpu_ticks(pid): return int(stat[11]) + int(stat[12]) +def killed_session(binary): + """A terminal's session killed outright (KILL, as the OOM killer does): + the job its terminal waits on ends with it, and says nothing of its own + (no trace): the own path's stub dead of the same signal, as a job is + (daemon.zig `stubWait`, which aborted re-raising a KILL); a pair's + client let go of its session, 1.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rk-', dir=scratch)) + env = base_env() + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30))) + t = Term(30, 100) + try: + c = t.spawn([binary, '--9p=k', str(notes)], env) + sock = root / 'pardes-9p-k.sock' + wait_for('the socket', sock.exists) + with Client(sock) as nine: + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) + os.kill(session, signal.SIGKILL) + code = c.wait(timeout=30) + said = t.last() + assert b'panic' not in said and b'unreachable' not in said, said[-1500:] + assert code == (1 if WITH_PAIR else -signal.SIGKILL), (code, said[-600:]) + print(f'killed session: its terminal\'s job ended {code} with it, no trace') + finally: + for p in processes(root): + try: + os.kill(p, signal.SIGKILL) + except OSError: + pass + t.close() + shutil.rmtree(root, ignore_errors=True) + + def kitty_image(binary, secs=5): """A plain attach watching a terminal in which a program shows a kitty image (the corpus's scene 10's: 8x8 RGB, 10x4 cells): it @@ -2960,7 +3017,7 @@ def main(binary, cycles): answer_late(binary) kitty_image(binary) shell = terminals(client)[0] - shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) + shell_pid = pid_in(client, shell) started.append(shell_pid) # Detach in the terminal it was born with: the stub ends (exit 0, # its words), the terminal put back; the session runs on detached, @@ -3101,8 +3158,7 @@ def main(binary, cycles): client.write(f'/pane/{min(before)}/exec', b'Adopt\n') adopted = wait_for('the adopted pane', lambda: set(terminals(client)) - before) pane = adopted.pop() - pid, said = adopted_pid(client, pane) - assert pid == str(shell_pid).encode(), said + assert (pid := pid_in(client, pane)) == shell_pid, (pid, shell_pid) print(f'daemon: shell {shell_pid} outlived kill -9 of its session and was adopted') # Attached again: a client. (After the runs: a pty/run under a # client puts it off the session's state, and it joins again; one @@ -3392,7 +3448,10 @@ def exe_of(pid): if not procfs: rows = subprocess.run(['procstat', '-b', str(pid)], capture_output=True).stdout.decode().splitlines() return (rows[-1].split()[-1] if len(rows) > 1 else ''), None - link = os.readlink(f'/proc/{pid}/exe') + try: + link = os.readlink(f'/proc/{pid}/exe') + except OSError: # gone, or a zombie: it runs nothing + return '', False try: same = os.stat(f'/proc/{pid}/exe').st_ino == os.stat(link).st_ino except OSError: @@ -3400,6 +3459,22 @@ def exe_of(pid): return link, same +def entered_again(text, mark): + """The blink of a client exec'd at an Upgrade: its terminal's screen + left at or after `mark` (the text's length before the Upgrade: when the + reader had read all the old client wrote, the leave is its very next + byte) and entered again. What was drawn since that enter, or None.""" + enter, leave = text.rfind(b'\x1b[?1049h'), text.rfind(b'\x1b[?1049l') + return text[enter:] if enter > leave >= mark else None + + +def on_build(proc, binary): + """Whether the test's child `proc` runs `binary` now (exe_of); one that + ended says so with its status at once, not as a wait run out.""" + assert proc.poll() is None, f'pid {proc.pid} ended ({proc.returncode}) before it ran {binary}' + return exe_of(proc.pid) == (str(binary), True) + + def ppid(pid): if not procfs: return int(ps('-o', 'ppid=', '-p', str(pid))) @@ -3509,7 +3584,7 @@ def upgrades(old, new): daemon = wait_for('the daemon', lambda: [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']])[0] started.append(daemon) shell = terminals(client)[0] - shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) + shell_pid = pid_in(client, shell) started.append(shell_pid) client.write(f'/pane/{shell}/look', f'{notes}\n'.encode()) text = int(client.read('/look')) @@ -3699,7 +3774,7 @@ def upgrades(old, new): assert os.stat(f'/proc/{session}/exe').st_ino == running, 'back on the build that ran' assert alive(shell_pid) and ppid(shell_pid) == session and stub.poll() is None assert client.read(f'/pane/{text}/body') == b'one\ntwo\n' - assert run(client, shell, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode() + assert (pid := pid_in(client, shell)) == shell_pid, (pid, shell_pid) print('upgrade: a build that refused the dump fell back to the one running; the shell ran on') # One that refuses it everywhere: a fresh session, the shells adopted. @@ -3712,8 +3787,8 @@ def upgrades(old, new): kept = client.read('/dumps').decode() assert any(line.split()[0].startswith(f'upgrade-{session}') for line in kept.splitlines()), kept assert alive(shell_pid) and ppid(shell_pid) == session, ('the shell under the fresh session', shell_pid, alive(shell_pid) and ppid(shell_pid), session) - pids = {p: run(client, p, b'echo $$\n') for p in terminals(client)} - adopted = [p for p, out in pids.items() if out.split(b'\n')[1:2] == [str(shell_pid).encode()]] + pids = {p: pid_in(client, p) for p in terminals(client)} + adopted = [p for p, pid in pids.items() if pid == shell_pid] assert adopted, ('the shell is a pane of the fresh session', shell_pid, pids, client.read('/index')) print(f'upgrade: a build that refused it everywhere started afresh, shell {shell_pid} adopted, the dump kept') @@ -3750,8 +3825,7 @@ def upgrades(old, new): before = set(terminals(client)) client.write(f'/pane/{min(before)}/exec', b'Adopt\n') pane = wait_for('the adopted pane', lambda: set(terminals(client)) - before).pop() - pid, said = adopted_pid(client, pane) - assert pid == str(shell_pid).encode(), (said, shell_pid) + assert (pid := pid_in(client, pane)) == shell_pid, (pid, shell_pid) print(f'upgrade: the upgraded daemon kept shell {shell_pid} through kill -9 of its session, and it was adopted') exit_session(client, pane) stub.wait(timeout=10) @@ -3850,7 +3924,7 @@ def upgrade_clients(old, new): nine = Client(sock) session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) shell = terminals(nine)[0] - shell_pid = int(run(nine, shell, b'echo $$\n').split(b'\n')[1]) + shell_pid = pid_in(nine, shell) t = Term(30, 100) terms.append(t) tc = t.spawn([str(binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 't.check'))) @@ -3888,7 +3962,7 @@ def upgrade_clients(old, new): wait_for('the terminal client on the new build', lambda: exe_of(tc.pid) == (str(binary), True), timeout=30) wait_for('the window client on the new build', lambda: exe_of(w.pid) == (str(gui_binary), True), timeout=30) # The blink: its screen left, and entered again. - wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30) + wait_for('the terminal entered again', lambda: entered_again(t.text(), mark), timeout=30) assert tc.poll() is None and w.p.poll() is None for (key, check), pane, theirs in zip(owners, mine, reversed(mine)): if knows_exec(new): @@ -3955,7 +4029,7 @@ def gui_upgrades(old, new): daemon = wait_for('the daemon', lambda: [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']])[0] started.append(daemon) shell = terminals(client)[0] - shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) + shell_pid = pid_in(client, shell) started.append(shell_pid) client.write(f'/pane/{shell}/look', f'{notes}\n'.encode()) text = int(client.read('/look')) @@ -4035,6 +4109,9 @@ if __name__ == '__main__': far_exec(old, new) else: print('far exec: skipped: the old build\'s far client, cut at the Upgrade with no last word, takes it for its session\'s end (no PARDES_JOIN_SIZE)') + # A reinstall of the new build before the pair's first look: the + # new build's own, whatever the old one does. + pair_exec_reaps(new, new, early=True) # With a pardes-gui beside each: the clients carried too. if all(a.with_name('pardes-gui').exists() for a in (old, new)): upgrade_clients(old, new) @@ -4092,3 +4169,4 @@ if __name__ == '__main__': gui_pair(args[0]) else: main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50) + killed_session(sys.argv[1]) diff --git a/test/process/look_and_exec.zig b/test/process/look_and_exec.zig index 9829797b..8ba52534 100644 --- a/test/process/look_and_exec.zig +++ b/test/process/look_and_exec.zig @@ -118,18 +118,8 @@ fn canary(gpa: std.mem.Allocator, exe: [:0]const u8) !void { // A terminal: pty/run failing then passing. const term = try f.madeBy(1, "Term\n"); - { - const deadline = process.nowMs() + 10_000; - while (true) { - const answer = try f.run(term, "true\n"); - if (std.mem.eql(u8, answer, "exit 0\n")) break; - if (process.nowMs() > deadline) { - std.debug.print("pty/run answered {s}\n", .{answer}); - return error.Timeout; - } - process.nap(50); - } - } + // Asked at once: a run waits for its first prompt and its greeting. + try std.testing.expectEqualStrings("exit 0\n", try f.run(term, "true\n")); try std.testing.expectEqualStrings("exit 1\n", try f.run(term, "false\n")); try std.testing.expectEqualStrings("exit 0\npassed\n", try f.run(term, "echo passed\n")); // (A run's answer is its record: the log has no err for these.) diff --git a/test/process/terminals.zig b/test/process/terminals.zig index 151b221b..8d595120 100644 --- a/test/process/terminals.zig +++ b/test/process/terminals.zig @@ -111,15 +111,6 @@ fn sizeLines(a: std.mem.Allocator, c: *process.Conn, n: u32) ![]const []const u8 return out.items; } -/// A shell takes runs: its first prompt, or the one started again. -fn prompted(a: std.mem.Allocator, c: *process.Conn, term: u32) !void { - const deadline = eh.nowMs() + 10_000; - while (!std.mem.eql(u8, try run(a, c, term, "true\n"), "exit 0\n")) { - if (eh.nowMs() > deadline) return error.NoPrompt; - process.sleep(50); - } -} - fn sizedFork(gpa: std.mem.Allocator, exe: [:0]const u8) !void { var d = try process.Detached.start(gpa, exe, "sized", .{}); defer d.deinit(); @@ -135,7 +126,7 @@ fn sizedFork(gpa: std.mem.Allocator, exe: [:0]const u8) !void { // the screen's 160x50. try c.write("/exec", "Term\n"); const term = try c.newest(gpa); - try prompted(a, c, term); + // Asked at once: a run waits for its first prompt and its greeting. var got = try sttySize(a, c, term); try expect(!std.mem.eql(u8, got[1], "50 160")); try expectEqualStrings(got[1], got[0]); @@ -200,11 +191,7 @@ fn runFile(gpa: std.mem.Allocator, exe: [:0]const u8) !void { const serial = try std.fmt.parseInt(u32, w.next().?, 10); if (std.mem.eql(u8, w.next().?, "term")) term = @max(term, serial); } - const deadline = eh.nowMs() + 10_000; - while (std.mem.eql(u8, try run(a, c, term, "true\n"), "busy\n")) { // deadline its first prompt - if (eh.nowMs() > deadline) return error.NoPrompt; - process.sleep(50); - } + try expectEqualStrings("exit 0\n", try run(a, c, term, "true\n")); // asked at once: it waits for the first prompt, and the greeting's try expectEqualStrings("exit 1\n", try run(a, c, term, "false\n")); try expectEqualStrings("exit 0\none\ntwo\n", try run(a, c, term, "printf \"one\\ntwo\\n\"\n")); // then what it printed try expectEqualStrings("exit 7\n", try run(a, c, term, "sh -c \"exit 7\"\n")); |
