summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--build/patches.zig15
-rw-r--r--core/Addon.zig18
-rw-r--r--core/Core.zig1
-rw-r--r--core/Effect.zig7
-rw-r--r--core/File.zig15
-rw-r--r--core/Kind.zig2
-rw-r--r--core/Stream.zig2
-rw-r--r--core/body_layer.zig2
-rw-r--r--core/builtins.zig6
-rw-r--r--core/config.zig3
-rw-r--r--core/draw.zig2
-rw-r--r--core/exec.zig3
-rw-r--r--core/jj.zig537
-rw-r--r--core/regexp.zig45
-rw-r--r--core/replica.zig27
-rw-r--r--core/root.zig5
-rw-r--r--core/surface.zig6
-rw-r--r--core/tape.zig3
-rw-r--r--dev/fonts.zig6
-rw-r--r--dev/gui/gui.zig44
-rw-r--r--dev/tui/tui.zig63
-rw-r--r--docs/mvzr-empty-group.md132
-rw-r--r--docs/typ/builtins-gui.json3
-rw-r--r--docs/typ/builtins-tui.json3
-rw-r--r--docs/typ/cheatsheet.typ3
-rw-r--r--docs/typ/guide.typ69
-rw-r--r--runtime/main.zig38
-rw-r--r--runtime/session.zig12
-rw-r--r--test/daemon.py177
-rw-r--r--test/panes.zig55
-rw-r--r--test/process/flags.zig2
31 files changed, 1108 insertions, 198 deletions
diff --git a/build/patches.zig b/build/patches.zig
index 7d87b9f1..410d27ab 100644
--- a/build/patches.zig
+++ b/build/patches.zig
@@ -356,6 +356,15 @@ pub fn ghosttyKitty(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Bui
/// could compile one typed pattern differently. Unreported upstream as
/// of 3efcfe33 (its trunk on 2026-11-19); docs/mvzr-bounds.md is the
/// report for it.
+/// - Three kinds of pattern the matcher indexed an empty slice on (a panic
+/// in a safe build, at a key typed into `s` or `/`): an empty group with
+/// more after it (`()a`, `a()b`: whether the group may match nothing was
+/// asked of its inside's first operation, which it has not got); a
+/// repeat right after `|` or `^` (`a|*`, `|??`, `^*`: it took the `|` or
+/// the `^` for what it repeats; at the pattern's start it was already
+/// refused); and a count that ends in neither `,` nor `}` (`({1))`: the
+/// character after it was skipped and a hole left in the program, which
+/// ends it there). docs/mvzr-empty-group.md is the report for upstream.
const mvzr_edits = [_]Edit{
.{
.old = "fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {\n",
@@ -419,6 +428,12 @@ const mvzr_edits = [_]Edit{
.{ .old = "fn valueFor(in: []const u8) ?u8 {\n", .new = "fn valueFor(in: []const u8) ?u8 {\n if (in.len == 0) return null;\n" },
.{ .old = " return parseHex(in[1..4]) catch return null;\n", .new = " return parseHex(in[1..3]) catch return null;\n" },
.{ .old = " if (i == in.len or in[i] != ']') {\n return BadString;\n", .new = " if (i >= in.len or in[i] != ']') {\n return BadString;\n" },
+ // What compiles is a program the matcher can walk: an empty pattern
+ // accepts the empty string; a repeat repeats an operation; a count is
+ // closed.
+ .{ .old = "fn patternAcceptsEmpty(patt: []const RegOp) bool {\n", .new = "fn patternAcceptsEmpty(patt: []const RegOp) bool {\n if (patt.len == 0) return true;\n" },
+ .{ .old = " if (j == 0 or patt[j] == .begin) return BadString;\n", .new = " if (j == 0 or patt[j - 1] == .begin or patt[j - 1] == .alt) return BadString;\n" },
+ .{ .old = " } else if (in[i] == '}') {\n // {M}\n", .new = " } else if (in[i] != '}') {\n bad_string = true;\n break :dispatch;\n } else {\n // {M}\n" },
.{ .old = "for (c1..c2 + 1) |c_range|", .new = "for (c1..@as(usize, c2) + 1) |c_range|" },
.{ .old = "[1]RegOp{.{ .unused = {} }} ** ops", .new = "@splat(.{ .unused = {} })" },
.{ .old = "[1]CharSet{.{ .low = 0, .hi = 0 }} ** char_sets", .new = "@splat(.{ .low = 0, .hi = 0 })" },
diff --git a/core/Addon.zig b/core/Addon.zig
index c60f2430..aa3195f9 100644
--- a/core/Addon.zig
+++ b/core/Addon.zig
@@ -567,9 +567,11 @@ pub fn loadedOf(ops: *const Kind.Ops, path: []const u8, hash: [32]u8, words: *[6
/// This process's code for a kind a session's core lists, which a client
/// runs itself: PA_PLAIN, of the same name, version, ABI and functions (a
-/// compiled-in addon's library hash is 0: never by the hash), and not
-/// caught breaking its promise here (`distrusted`, the client's). Null: its
-/// panes say so.
+/// compiled-in addon's library hash is 0: never by the hash), or else the
+/// library at the session's path when its bytes are the session's (P51: a
+/// client on its machine; never bytes the session sent), and not caught
+/// breaking its promise here (`distrusted`, the client's). Null: its panes
+/// say so.
pub fn plainOps(e: *const Kind.Entry, distrusted: ?*const Distrusted) ?*const Kind.Ops {
if (!e.caps.plain or e.refused) return null;
// A client scans for its addons only when its session has a plain kind.
@@ -582,6 +584,16 @@ pub fn plainOps(e: *const Kind.Entry, distrusted: ?*const Distrusted) ?*const Ki
if (l.ops == 0) l.ops = loadListed(i, &why) orelse return null;
return @ptrFromInt(l.ops);
};
+ var words: [64]LoadedWord = undefined;
+ var why: Why = .{};
+ var data_buf: [4096]u8 = undefined;
+ const l = read(dataDir(&data_buf), e.path.slice(), &words, &why);
+ if (l.why.len > 0) return null;
+ const ops: *const Kind.Ops = @ptrFromInt(l.ops);
+ if (std.mem.eql(u8, &l.hash, &e.hash)) return ops;
+ const lib = libOf(ops).?;
+ lib.refs -= 1;
+ closeIdle(lib);
return null;
}
diff --git a/core/Core.zig b/core/Core.zig
index 2d832f48..a35cea8e 100644
--- a/core/Core.zig
+++ b/core/Core.zig
@@ -883,6 +883,7 @@ pub fn deinit(p: *Pardes) void {
for (&p.surface.tag_layers) |*layer| gpa.free(layer.cells);
p.surface.placements.deinit(gpa);
p.surface.lanes.deinit(gpa);
+ p.surface.heat.deinit(gpa);
gpa.destroy(p);
}
diff --git a/core/Effect.zig b/core/Effect.zig
index abfe4711..bdf41e66 100644
--- a/core/Effect.zig
+++ b/core/Effect.zig
@@ -256,9 +256,10 @@ fn performInner(p: *Pardes, e: Effect) void {
.dump_themes => |d| _ = p.tape.host(p, .dump_themes, .{d.pane}),
.detach => |d| p.tape.host(p, .detach, .{}) orelse p.reportError(d.pane, "detach", error.NotAttached),
// dlopen is the same on every host, so none has a method of its
- // own; a replica's core holds no library (what it brought comes in
- // the event this taped).
- .addon => |a| if (!p.tape.replaying()) @import("Addon.zig").perform(p, a.op, a.pane.index(), a.arg.slice()),
+ // own; a replica's core holds no library: what it brought is the
+ // event inside this call, recorded there and applied by a replay
+ // (its code a client's own, Addon.plainOps); a speculation waits.
+ .addon => |a| if (!p.tape.authorityOnly("an addon's load")) p.tape.value(.landing, @import("Addon.zig").perform, .{ p, a.op, a.pane.index(), a.arg.slice() }),
.job => |j| p.tape.host(p, .job, .{ j.pane, j.serial, j.token }) orelse if (!p.tape.replaying()) host_io.KindJob.runHere(p, j.pane.index(), j.serial, j.token),
// the loop's own condition; a host tears down after its own loop
.quit => p.endSession(),
diff --git a/core/File.zig b/core/File.zig
index 347f4809..c4fc8a38 100644
--- a/core/File.zig
+++ b/core/File.zig
@@ -373,7 +373,7 @@ pub fn gutterWidth(pane: *const Pane) u16 {
var lines = if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content);
var digits: u16 = 1;
while (lines >= 10) : (lines /= 10) digits += 1;
- return @max(config.PREFIX_W, digits + 1) + laneCells(pane);
+ return @max(config.PREFIX_W, digits + 1) + laneCells(pane) + pane.layers.heat;
}
/// The cells the changes' lanes take after the line number in this view
@@ -758,7 +758,7 @@ fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, who
};
reportEdit(p, f, off, len, bytes);
// A pinned change's per-line values ride with the lines (jj.zig).
- if (p.changes.answers.items.len > 0) jj.edited(p, f, off, len, bytes);
+ if (p.changes.answers.items.len | p.changes.heats.items.len > 0) jj.edited(p, f, off, len, bytes);
if (f.mini) |*mini| mini.deinit(p.gpa);
f.mini = null;
if (f.line_starts.len > 0) shiftIndex(p.gpa, f, off, len, bytes);
@@ -1779,7 +1779,7 @@ fn geometryKey(pane: *const Pane, f: *const State) u64 {
if (f.output) |o| pardes.walk.digest(Output.Origin, &o.from) else 0, std.hash.Wyhash.hash(0, f.path), f.tree_context, f.context.revision orelse 0,
f.context.declarations.len, f.line_starts.len, t.revision orelse 0, t.list.items.len,
pane.view.wrap, pane.view.layered, pane.view.body_h, pane.view.tagline_h,
- pane.view.rect_h, laneCells(pane),
+ pane.view.rect_h, laneCells(pane) + @as(u16, pane.layers.heat),
};
// One hash of them laid out as words: every reader of the map asks for
// this key, a hundred times a frame.
@@ -1797,8 +1797,8 @@ fn geometryKey(pane: *const Pane, f: *const State) u64 {
fn fillBody(comptime ghosted: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) usize {
if (record_wrap) pane.wrap_n = 0;
const prefix_width = gutterWidth(pane);
- // Where a number ends: a blank, then the lanes (laneCells), after it.
- const number_end = prefix_width -| laneCells(pane) -| 1;
+ // Where a number ends: a blank, then the heat lane and the lanes after it.
+ const number_end = prefix_width -| laneCells(pane) -| pane.layers.heat -| 1;
const total = nlines(pane.gpa, f);
// The slot after the text's last newline, found once: every numbered
// row below asks whether it is that one.
@@ -1949,9 +1949,12 @@ pub const Layers = struct {
/// frontend, in a window two, which its strips of pixels fill one and
/// a half of (Surface.Lane), in a terminal three, a glyph each.
lanes: u8 = 0,
+ /// Whether this view shows the pane's churn (`Churn`, jj.Heat), as the
+ /// cells its lane takes: one after the number, before the lanes.
+ heat: u8 = 0,
pub fn digest(l: *const Layers, h: *pardes.walk.Hasher) void {
- h.update(&.{ @intFromBool(l.ink), l.lanes });
+ h.update(&.{ @intFromBool(l.ink), l.lanes, l.heat });
}
};
diff --git a/core/Kind.zig b/core/Kind.zig
index 81997afb..49076f78 100644
--- a/core/Kind.zig
+++ b/core/Kind.zig
@@ -424,7 +424,7 @@ pub fn draw(p: *Pardes, s: *surface.Surface, arena: std.mem.Allocator, pane: *Pa
if (slot.ops == null and slot.live) {
// A client: a plain kind runs where it is shown, and this one lacks
// it; any other runs in its session alone.
- const why = if (caps(p, slot).plain) "it is not in its addons, or it broke its promise here" else "its state is not plain (PA_PLAIN), so it runs in the session alone";
+ const why = if (caps(p, slot).plain) "it is not in its addons nor the session's library at its path here, or it broke its promise here" else "its state is not plain (PA_PLAIN), so it runs in the session alone";
var line: [200]u8 = undefined;
_ = s.print(x, y, cols, std.fmt.bufPrint(&line, "addon {s} {d} does not run in this client: {s}", .{ slot.nameOf(), slot.version, why }) catch &line, .{ .fg = fg, .bg = bg });
return;
diff --git a/core/Stream.zig b/core/Stream.zig
index 1d061b52..7956e4f2 100644
--- a/core/Stream.zig
+++ b/core/Stream.zig
@@ -735,6 +735,8 @@ fn receiveParse(p: *Pardes, b: *const Batch, serial: u32, revision: u32) void {
} else |_| {}
};
p.needs_frame = true;
+ // A `Churn` waiting on these declarations (jj.zig).
+ @import("jj.zig").parsed(p, serial);
if (s.parse_next) |next| {
s.parse_next = null;
if (p.paneBySerial(next.serial)) |id| parseFor(p, id);
diff --git a/core/body_layer.zig b/core/body_layer.zig
index cb518af4..95fb2700 100644
--- a/core/body_layer.zig
+++ b/core/body_layer.zig
@@ -341,7 +341,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane
drawGutter(p, s, pane, r, tx, tw, body_h, active);
// Never inlined: in renderBody's own frame it cost every body a
// frame (a terminal's output about 33,000 instructions a pump).
- if (pane.layers.lanes > 0) @call(.never_inline, @import("jj.zig").paint, .{ p, s, pane, r, tx, tw, body_h });
+ if (pane.layers.lanes | pane.layers.heat > 0) @call(.never_inline, @import("jj.zig").paint, .{ p, s, pane, r, tx, tw, body_h });
panes.Query.paintMark(p, s, pane, r, body_h);
if (pane.colorAlgo() != .none)
panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h);
diff --git a/core/builtins.zig b/core/builtins.zig
index 7485af81..e6d22c17 100644
--- a/core/builtins.zig
+++ b/core/builtins.zig
@@ -1086,6 +1086,12 @@ pub const Changes = struct {
pub const run = @import("jj.zig").changesWord;
};
+/// Count, for each declaration of a file's pane, the changes in `window` (jj) that touched it, and show it in this view: a heat lane after the line number and a strip by the scroll thumb, the line numbers' grey to the theme's red on a log scale; `window` a revset or a span of time (`3d`, `2w`, `6m`, `1y`); bare, shown here or not (none counted yet: the file's whole history).
+pub const Churn = struct {
+ pub const takes_arg = true;
+ pub const run = @import("jj.zig").churnWord;
+};
+
/// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. `Diff <file>` stacks that diff's, `Diff <revision>` git show's.
/// The diff viewer's one registration: its word and traits here, all else
/// its own (hunks.zig).
diff --git a/core/config.zig b/core/config.zig
index 1f5819c9..aae832f4 100644
--- a/core/config.zig
+++ b/core/config.zig
@@ -77,7 +77,8 @@ pub const leader_path = paths: {
.Filter = null,
.Diff = null,
.At = null,
- .Changes = null,
+ .Changes = "tc",
+ .Churn = "tu",
.Mode = null,
.Togglettymode = null,
.Collapse = null,
diff --git a/core/draw.zig b/core/draw.zig
index 3d2a1452..8198e2ff 100644
--- a/core/draw.zig
+++ b/core/draw.zig
@@ -86,6 +86,7 @@ pub fn place(p: *Pardes, s: *Surface) void {
s.nregions = 0;
s.nrail_ticks = 0;
s.lanes.clearRetainingCapacity();
+ s.heat.clearRetainingCapacity();
// The facts filled in the walk the frame's places take anyway.
viewFacts(p, &p.facts);
s.facts = &p.facts;
@@ -510,6 +511,7 @@ fn renderPane(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r:
}
try body_layer.joinBody(p, s, arena, pane, r, id, active, rail.*);
+ if (pane.layers.heat > 0) @import("jj.zig").railHeat(p, s, pane, id, rail.rect);
// A terminal panned to its cursor in a view shorter than it: an arrow
// in the gutter's first body row says rows are above (views.zig).
if (pane.pan > 0) s.set(r.x, p.bodyTop(pane, r), "↑", .{ .fg = .{ .rgb = chrome.box } });
diff --git a/core/exec.zig b/core/exec.zig
index ae9111f8..d1e1830f 100644
--- a/core/exec.zig
+++ b/core/exec.zig
@@ -20,7 +20,6 @@ const python_lang = blk: {
@setEvalBranchQuota(20_000);
break :blk @import("grammar_manifest.zig").byName("python").?;
};
-const font_picker = pardes.font_picker;
const fonts = pardes.fonts;
const Pane = panes.Pane;
const MAX_COLS = pardes.MAX_COLS;
@@ -1013,7 +1012,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Settings.Setting, arg: ?[
return p.reportFailure(v.active, text.print("Theme: no theme \"{s}\"; like it: {s}; Themes lists all", .{ shown, colors.themesNear(near[0..@min(room, near.len)], want) }));
},
.font => {
- if (comptime !font_picker) return;
+ if (comptime !pardes.builtins.capabilities.font_picker) return;
const spec = config.Settings.FontSpec.parse(arg orelse return) orelse return;
// The session's machine's fonts, a question to its disk: a
// client's replay takes the session's answer, never its own.
diff --git a/core/jj.zig b/core/jj.zig
index 6a7d7da4..a0dfec10 100644
--- a/core/jj.zig
+++ b/core/jj.zig
@@ -17,6 +17,7 @@ const Output = pardes.panes.Output;
const look = @import("look.zig");
const layout = @import("layout.zig");
const diff = @import("diff.zig");
+const syntax = @import("syntax.zig");
/// What jj answered: why not, in its own words (its first line, without
/// `Error: `), or the file's bytes. The caller's, in the allocator the site
@@ -253,15 +254,60 @@ pub fn answered(p: *Pardes, serial: u32) ?*Changes {
return null;
}
+/// What jj answered for pane `serial`'s `Churn` (`Pardes.changes`), counted.
+pub fn churned(p: *Pardes, serial: u32) ?*Heat {
+ for (p.changes.heats.items) |*h| if (h.serial == serial) return h;
+ return null;
+}
+
/// Pane `serial`'s answers let go (the pane's end).
pub fn forget(p: *Pardes, serial: u32) void {
for (p.changes.answers.items, 0..) |*c, i| if (c.serial == serial) {
c.deinit(p.gpa);
_ = p.changes.answers.swapRemove(i);
+ break;
+ };
+ forgetHeat(p, serial);
+}
+
+fn forgetHeat(p: *Pardes, serial: u32) void {
+ for (p.changes.heats.items, 0..) |*h, i| if (h.serial == serial) {
+ h.deinit(p.gpa);
+ _ = p.changes.heats.swapRemove(i);
return;
};
}
+/// A pane's `Churn [window]` (PARDES.md "Changes on the source view":
+/// churn per declaration): for each line, how many of the window's changes
+/// touched the declaration it is in (tree-sitter's innermost, as
+/// TreeContext finds them; 0 outside any), counted in every process from
+/// jj's raw answer (`heatOf`), replicated state as `Changes` is, riding
+/// with the lines through edits.
+pub const Heat = struct {
+ pub const replica = .{ .len = .{.{ "revset", "revset_len" }} };
+ serial: u32,
+ /// The window as jj was asked it.
+ revset: [Changes.revset_max]u8 = undefined,
+ revset_len: u8 = 0,
+ lines: []u16 = &.{},
+ /// The file's hottest declaration's count, the gradient's top.
+ hottest: u16 = 0,
+ /// jj's raw answer until it is counted (`parsed`): its log, then its
+ /// text of the revision from `pending_was` on.
+ pending: []u8 = &.{},
+ pending_was: u32 = 0,
+
+ pub fn deinit(h: *Heat, gpa: std.mem.Allocator) void {
+ gpa.free(h.lines);
+ gpa.free(h.pending);
+ }
+
+ pub fn window(h: *const Heat) []const u8 {
+ return h.revset[0..h.revset_len];
+ }
+};
+
/// A pinned change, as `jj log` says it.
pub const Pin = struct {
pub const replica = .{ .len = .{ .{ "author", "author_len" }, .{ "title", "title_len" } } };
@@ -378,7 +424,57 @@ pub fn changesWord(c: pardes.builtins.Ctx) void {
else
return p.reportFailure(c.id, "Changes: only a file's pane takes it");
pane.layers.lanes = cells;
- ask(p, c.id, pane.serial, shown.path, shown.rev, revset);
+ ask(p, .changes, c.id, pane.serial, shown.path, shown.rev, revset);
+}
+
+/// The `Churn` word (builtins.zig registers it): in a file's pane (or a
+/// revision's), how many changes in `window` touched each declaration,
+/// shown in this view as a heat lane after the line number and a strip by
+/// the scroll thumb. The window: a revset, or a span of time back from now
+/// (`3d`, `2w`, `6m`, `1y`: what the file's history has in it); bare, shown
+/// here or not, and with none counted yet the file's whole history (`::`
+/// the revision shown).
+pub fn churnWord(c: pardes.builtins.Ctx) void {
+ const p = c.p;
+ const pane = c.pane;
+ const f = if (pane.file) |*file| file else return p.reportFailure(c.id, "Churn: only a file's pane takes it");
+ const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
+ if (arg.len == 0 and pane.layers.heat > 0) {
+ pane.layers.heat = 0;
+ return;
+ }
+ if (arg.len == 0 and churned(p, pane.serial) != null) {
+ pane.layers.heat = 1;
+ return;
+ }
+ const shown: struct { path: []const u8, rev: []const u8 } = if (of(f)) |r|
+ .{ .path = r.path, .rev = r.rev }
+ else if (f.output == null and pardes.filesystem.localPath(f.path) != null)
+ .{ .path = f.path, .rev = "@" }
+ else
+ return p.reportFailure(c.id, "Churn: only a file's pane takes it");
+ var buf: [Changes.revset_max]u8 = undefined;
+ const window = spanOf(&buf, shown.rev, arg) orelse arg;
+ if (window.len > Changes.revset_max) return p.reportFailure(c.id, "Churn: a window that long");
+ pane.layers.heat = 1;
+ ask(p, .churn, c.id, pane.serial, shown.path, shown.rev, window);
+}
+
+/// `arg` as a revset: bare, every change of the revision's history; a span
+/// of time (a count and `h`, `d`, `w`, `m` or `y`), its changes since then
+/// (jj's `author_date`); null for a revset.
+fn spanOf(buf: []u8, rev: []const u8, arg: []const u8) ?[]const u8 {
+ if (arg.len == 0) return std.fmt.bufPrint(buf, "::({s})", .{rev}) catch null;
+ const n = std.fmt.parseInt(u16, arg[0 .. arg.len - 1], 10) catch return null;
+ const unit: []const u8 = switch (arg[arg.len - 1]) {
+ 'h' => "hours",
+ 'd' => "days",
+ 'w' => "weeks",
+ 'm' => "months",
+ 'y' => "years",
+ else => return null,
+ };
+ return std.fmt.bufPrint(buf, "::({s}) & author_date(after:\"{d} {s} ago\")", .{ rev, n, unit }) catch null;
}
// ---- jj off the loop (Stream.zig's model) ----
@@ -392,6 +488,7 @@ pub fn changesWord(c: pardes.builtins.Ctx) void {
/// run a site of the step's tape.
pub const Ask = struct {
gpa: std.mem.Allocator,
+ kind: Kind = .changes,
/// What its answer is made with: the shell's, which frees a batch.
out: std.mem.Allocator,
gen: u32,
@@ -400,11 +497,15 @@ pub const Ask = struct {
rev: []u8,
revset: []u8,
- fn make(gpa: std.mem.Allocator, gen: u32, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) error{OutOfMemory}!*Ask {
+ /// `Changes`' (with who wrote each line), or `Churn`'s (with jj's text
+ /// of the revision, which the counts are lined up with).
+ pub const Kind = enum(u8) { changes, churn };
+
+ fn make(gpa: std.mem.Allocator, kind: Kind, gen: u32, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) error{OutOfMemory}!*Ask {
const a = try gpa.create(Ask);
errdefer gpa.destroy(a);
const owned = try std.mem.concat(gpa, u8, &.{ path, rev, revset });
- a.* = .{ .gpa = gpa, .out = gpa, .gen = gen, .serial = serial, .path = owned[0..path.len], .rev = owned[path.len..][0..rev.len], .revset = owned[path.len + rev.len ..] };
+ a.* = .{ .gpa = gpa, .kind = kind, .out = gpa, .gen = gen, .serial = serial, .path = owned[0..path.len], .rev = owned[path.len..][0..rev.len], .revset = owned[path.len + rev.len ..] };
return a;
}
@@ -421,6 +522,7 @@ pub const Ask = struct {
/// `Changes` is asked, then one update while nothing is asked of jj.
pub const Session = struct {
answers: std.ArrayList(Changes) = .empty,
+ heats: std.ArrayList(Heat) = .empty,
task: ?Task = null,
next: ?*Ask = null,
count: u32 = 0,
@@ -430,6 +532,7 @@ pub const Session = struct {
const bits: u64 = c.count | @as(u64, @intFromBool(c.task != null)) << 32 | @as(u64, @intFromBool(c.next != null)) << 33;
h.update(std.mem.asBytes(&bits));
pardes.walk.hash(std.ArrayList(Changes), &c.answers, h);
+ pardes.walk.hash(std.ArrayList(Heat), &c.heats, h);
if (c.task) |*t| pardes.walk.hash(Task, t, h);
if (c.next) |n| pardes.walk.hash(Ask, n, h);
}
@@ -448,6 +551,8 @@ pub const Session = struct {
}
for (c.answers.items) |*a| a.deinit(gpa);
c.answers.deinit(gpa);
+ for (c.heats.items) |*h| h.deinit(gpa);
+ c.heats.deinit(gpa);
}
};
@@ -470,10 +575,10 @@ fn liveGen(c: *const Session) u32 {
/// Ask jj of `revset` for pane `serial` (said at pane `id` while it runs):
/// what the pane shows stays until the answer lands.
-fn ask(p: *Pardes, id: usize, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) void {
+fn ask(p: *Pardes, kind: Ask.Kind, id: usize, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) void {
p.changes.count +%= 1;
- const a = Ask.make(p.gpa, liveGen(&p.changes), serial, path, rev, revset) catch return p.reportFailure(id, "Changes: out of memory");
- p.setStatus(.at(id), "Changes: jj\u{2026}");
+ const a = Ask.make(p.gpa, kind, liveGen(&p.changes), serial, path, rev, revset) catch return p.reportFailure(id, "Changes: out of memory");
+ p.setStatus(.at(id), if (kind == .churn) "Churn: jj\u{2026}" else "Changes: jj\u{2026}");
if (p.changes.task != null) {
if (p.changes.next) |old| old.deinit();
p.changes.next = a;
@@ -550,6 +655,14 @@ fn answer(p: ?*Pardes, gpa: std.mem.Allocator, a: *const Ask) pardes.Stream.Batc
if (if (entryOf(l)) |e| e.pinned else false) break true;
} else false;
if (!any) return .{ .gen = a.gen, .rows = logged, .end = .done };
+ // Churn: jj's text of the revision, to line the counts up with the pane's.
+ if (a.kind == .churn) return switch (runJj(p, gpa, dirOf(a.path), &.{ "file", "show", "-r", a.rev, "--", set })) {
+ .refused => |why| {
+ gpa.free(logged);
+ return failed(gpa, a, why);
+ },
+ .bytes => |shown| .{ .gen = a.gen, .rows = logged, .styles = shown, .end = .done },
+ };
// Who wrote each line: a path, not a fileset (annotate takes one file
// as it is named).
const annotate_args = [_][]const u8{ "file", "annotate", "-r", a.rev, "-T", "commit.change_id().short(8) ++ \"\\t\" ++ content", "--", std.Io.Dir.path.basename(a.path) };
@@ -575,17 +688,19 @@ fn runJj(p: ?*Pardes, gpa: std.mem.Allocator, dir: []const u8, args: []const []c
}
/// A `Changes` answer (`Event.search` with a `Changes` generation),
-/// borrowed: the last asked's is parsed and pinned on its pane (the ask
-/// names it); an earlier one's, or a gone pane's, dropped. Then the one
-/// asked meanwhile goes.
+/// borrowed: the last asked of its kind is parsed and pinned (or counted,
+/// a `Churn`'s) on its pane (the ask names it); an earlier one's, or a gone
+/// pane's, dropped. Then the one asked meanwhile goes.
pub fn receive(p: *Pardes, b: *const pardes.Stream.Batch) void {
var revset: [Changes.revset_max]u8 = undefined;
var revset_len: usize = 0;
var serial: u32 = 0;
+ var kind: Ask.Kind = .changes;
if (p.changes.task) |t| if (t.ask.gen == b.gen) {
p.changes.task = null;
if (t.future) |f| pardes.Stream.join(f, t.io.?, .wait);
serial = t.ask.serial;
+ kind = t.ask.kind;
revset_len = t.ask.revset.len;
@memcpy(revset[0..revset_len], t.ask.revset);
t.ask.deinit();
@@ -594,9 +709,14 @@ pub fn receive(p: *Pardes, b: *const pardes.Stream.Batch) void {
p.changes.next = null;
go(p, next);
};
- if (b.gen != liveGen(&p.changes) or revset_len == 0) return;
+ if (revset_len == 0) return;
+ // A later one of its kind asked meanwhile: only that one is shown.
+ if (p.changes.next) |n| if (n.kind == kind) return;
const id = p.paneBySerial(serial) orelse return;
- pinAnswer(p, id, b, revset[0..revset_len]);
+ switch (kind) {
+ .changes => pinAnswer(p, id, b, revset[0..revset_len]),
+ .churn => heatAnswer(p, id, b, revset[0..revset_len]),
+ }
}
/// A splice of `f`'s text, before its bytes go in (File.edit, the one
@@ -619,6 +739,18 @@ pub fn edited(p: *Pardes, f: *const File.State, off: usize, len: usize, bytes: [
showGhosts(p, p.panes[id].?);
};
}
+ i = p.changes.heats.items.len;
+ while (i > 0) {
+ i -= 1;
+ const h = &p.changes.heats.items[i];
+ const id = p.paneBySerial(h.serial) orelse continue;
+ const shown = if (p.panes[id].?.file) |*shown| shown else continue;
+ if (shown.content.ptr != f.content.ptr) continue;
+ _ = spliceValues(u16, p.gpa, &h.lines, 0, f.content, off, len, bytes) catch {
+ h.deinit(p.gpa);
+ _ = p.changes.heats.swapRemove(i);
+ };
+ }
}
/// `c`'s values spliced as `text`'s lines are by the splice of `len` bytes
@@ -628,20 +760,10 @@ pub fn edited(p: *Pardes, f: *const File.State, off: usize, len: usize, bytes: [
/// before it. Else the line it starts in keeps its value, and the lines
/// taken and put come after it.
fn splice(gpa: std.mem.Allocator, c: *Changes, text: []const u8, off: usize, len: usize, bytes: []const u8) error{OutOfMemory}!void {
- const taken = std.mem.count(u8, text[off..][0..len], "\n");
- const put = std.mem.count(u8, bytes, "\n");
- if (taken == 0 and put == 0) return;
- const line_start = if (std.mem.lastIndexOfScalar(u8, text[0..off], '\n')) |nl| nl + 1 else 0;
- const in_lead = std.mem.trimStart(u8, text[line_start..off], " \t").len == 0;
- const from = std.mem.count(u8, text[0..line_start], "\n") + @intFromBool(!in_lead);
- if (from > c.lines.len) return;
- const take = @min(taken, c.lines.len - from);
- const next = try gpa.alloc(Line, c.lines.len - take + put);
- @memcpy(next[0..from], c.lines[0..from]);
- @memset(next[from..][0..put], .{ .pin = .none });
- @memcpy(next[from + put ..], c.lines[from + take ..]);
- gpa.free(c.lines);
- c.lines = next;
+ const cut = try spliceValues(Line, gpa, &c.lines, .{ .pin = .none }, text, off, len, bytes) orelse return;
+ const from = cut.from;
+ const take = cut.take;
+ const put = cut.put;
// A ghost row stands before the line it stood before; one before a
// line taken out, before the line after what took its place.
for (c.ghosts) |*g| {
@@ -650,6 +772,26 @@ fn splice(gpa: std.mem.Allocator, c: *Changes, text: []const u8, off: usize, len
}
}
+/// A value a line, `values`, spliced as `splice` says, a line put in
+/// `none`; null when no line is taken or put.
+fn spliceValues(comptime T: type, gpa: std.mem.Allocator, values: *[]T, none: T, text: []const u8, off: usize, len: usize, bytes: []const u8) error{OutOfMemory}!?struct { from: usize, take: usize, put: usize } {
+ const taken = std.mem.count(u8, text[off..][0..len], "\n");
+ const put = std.mem.count(u8, bytes, "\n");
+ if (taken == 0 and put == 0) return null;
+ const line_start = if (std.mem.lastIndexOfScalar(u8, text[0..off], '\n')) |nl| nl + 1 else 0;
+ const in_lead = std.mem.trimStart(u8, text[line_start..off], " \t").len == 0;
+ const from = std.mem.count(u8, text[0..line_start], "\n") + @intFromBool(!in_lead);
+ if (from > values.len) return null;
+ const take = @min(taken, values.len - from);
+ const next = try gpa.alloc(T, values.len - take + put);
+ @memcpy(next[0..from], values.*[0..from]);
+ @memset(next[from..][0..put], none);
+ @memcpy(next[from + put ..], values.*[from + take ..]);
+ gpa.free(values.*);
+ values.* = next;
+ return .{ .from = from, .take = take, .put = put };
+}
+
/// jj's answer `b` for `revset` parsed and pinned on pane `id`, or its
/// refusal said there.
fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []const u8) void {
@@ -689,6 +831,118 @@ fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []con
}
}
+/// jj's answer `b` for a `Churn` of `window` on pane `id`, kept raw
+/// until the text's declarations are there (a worker's parse,
+/// Stream.parseFor: a big file's parse is seconds in a Debug build, never
+/// the loop's), then counted (`count`); or its refusal said there.
+fn heatAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, window: []const u8) void {
+ const pane = p.panes[id].?;
+ var line: pardes.Kind.Buf(512) = .{};
+ if (pane.file == null) return;
+ if (b.end == .failed) {
+ if (churned(p, pane.serial) == null) pane.layers.heat = 0;
+ return p.reportFailure(id, line.print("Churn: {s}", .{b.rows[0..@min(b.rows.len, 480)]}));
+ }
+ var heat: Heat = .{ .serial = pane.serial, .revset_len = @intCast(window.len) };
+ @memcpy(heat.revset[0..window.len], window);
+ heat.pending = std.mem.concat(p.gpa, u8, &.{ b.rows, b.styles }) catch return p.reportFailure(id, "Churn: out of memory");
+ heat.pending_was = @intCast(b.rows.len);
+ if (churned(p, pane.serial)) |kept| {
+ kept.deinit(p.gpa);
+ kept.* = heat;
+ } else p.changes.heats.append(p.gpa, heat) catch {
+ heat.deinit(p.gpa);
+ pane.layers.heat = 0;
+ return p.reportFailure(id, "Churn: out of memory");
+ };
+ parsed(p, pane.serial);
+}
+
+/// A parse of pane `serial`'s text landed (Stream.receiveParse), or jj's
+/// answer did: a `Churn` waiting on it counted when the declarations are of
+/// the text as it is, else a parse of it asked.
+pub fn parsed(p: *Pardes, serial: u32) void {
+ const h = churned(p, serial) orelse return;
+ if (h.pending.len == 0) return;
+ const id = p.paneBySerial(serial) orelse return;
+ const pane = p.panes[id].?;
+ const f = if (pane.file) |*file| file else return;
+ var line: pardes.Kind.Buf(512) = .{};
+ if (!syntax.supportsPath(f.path)) {
+ // No grammar for it (a revision's pane too: its name ends `@rev`).
+ p.reportFailure(id, line.print("Churn: no declarations to count in {s}", .{std.Io.Dir.path.basename(f.path)}));
+ pane.layers.heat = 0;
+ return forgetHeat(p, serial);
+ }
+ if (f.context.revision != f.revision) return pardes.Stream.parseFor(p, id);
+ const lines = heatOf(p.gpa, p.scratch.allocator(), h.pending[0..h.pending_was], h.pending[h.pending_was..], f.content, f.context.declarations, &h.hottest) catch |err| return p.reportFailure(id, line.print("Churn: {s}", .{@errorName(err)}));
+ p.gpa.free(h.pending);
+ h.pending = &.{};
+ h.lines = lines;
+ if (h.hottest > 0) return p.setStatus(.at(id), "");
+ p.reportFailure(id, line.print("Churn: no change of `{s}` touches a declaration of {s}", .{ h.window(), std.Io.Dir.path.basename(File.langPath(f)) }));
+ pane.layers.heat = 0;
+ forgetHeat(p, serial);
+}
+
+/// For each line of `text` (`decls` its declarations), how many of the window's
+/// changes in `logged` (jj's log, `p` the window's, `c` a later change
+/// that only carries places) touched the declaration it is in: tree-
+/// sitter's innermost, a line in none 0. A change's hunk touches the lines
+/// it wrote, carried into the revision jj showed (`was`) through the later
+/// changes' hunks, then into `text` (`Moved`); a hunk that only took lines
+/// away, the line above where they stood. Each change counts once a
+/// declaration. `hottest`: the largest count.
+fn heatOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, was: []const u8, text: []const u8, decls: []const syntax.ContextDeclaration, hottest: *u16) error{OutOfMemory}![]u16 {
+ var hunks: std.ArrayList(Hunk) = .empty;
+ var removed: std.ArrayList(u8) = .empty;
+ var windowed: std.ArrayList(bool) = .empty;
+ var starts: std.ArrayList(usize) = .empty;
+ var it = std.mem.splitScalar(u8, logged, '\n');
+ while (it.next()) |l| if (entryOf(l)) |e| {
+ if (windowed.items.len == Hunk.carrier) break;
+ try windowed.append(arena, e.pinned);
+ try starts.append(arena, it.index orelse logged.len);
+ };
+ try starts.append(arena, logged.len);
+ for (starts.items[0 .. starts.items.len - 1], starts.items[1..], 0..) |from, to, i|
+ try hunksOf(arena, arena, Hunk.carrier, @intCast(i), logged[from..to], text, &.{}, &hunks, &removed, undefined, undefined);
+ const n = lineCount(text);
+ const moved: Moved = .of(was, text);
+ // Each line's innermost declaration (outermost first, so an inner one
+ // writes over its container's lines).
+ const none = std.math.maxInt(u32);
+ const inner = try arena.alloc(u32, n);
+ @memset(inner, none);
+ for (decls, 0..) |d, k| {
+ if (d.start_line >= n) continue;
+ @memset(inner[d.start_line..@min(n, d.end_line + 1)], @intCast(k));
+ }
+ const counts = try arena.alloc(u16, decls.len);
+ @memset(counts, 0);
+ // The last change each declaration was counted for.
+ const seen = try arena.alloc(u32, decls.len);
+ @memset(seen, none);
+ for (hunks.items) |h| {
+ if (!windowed.items[h.step] or n == 0) continue;
+ const a = carried(hunks.items, h.step, h.new_start -| 1 + @intFromBool(h.new_len == 0), moved) orelse continue;
+ const b = carried(hunks.items, h.step, h.new_start -| 1 + h.new_len, moved) orelse continue;
+ const lo = @min(if (h.new_len == 0) a -| 1 else a, n - 1);
+ for (inner[lo..@max(lo + 1, @min(b, n))]) |k| {
+ if (k == none or seen[k] == h.step) continue;
+ seen[k] = h.step;
+ counts[k] +|= 1;
+ }
+ }
+ const out = try gpa.alloc(u16, n);
+ hottest.* = 0;
+ for (out, inner) |*o, k| {
+ o.* = if (k == none) 0 else counts[k];
+ hottest.* = @max(hottest.*, o.*);
+ }
+ return out;
+}
+
/// The pane's ghost rows as its geometry reads them (`Pane.ghosts`): the
/// session's answers' (one set a pane), its geometry made again when they
/// change (each step while a view shows them, and as an answer lands).
@@ -808,21 +1062,10 @@ pub fn provenance(gpa: std.mem.Allocator, arena: std.mem.Allocator, annotated: [
if (!std.mem.endsWith(u8, annotated, "\n") and was.items.len > 0) was.items.len -= 1;
const out = try gpa.alloc(Line, lineCount(text));
@memset(out, .{ .pin = .none });
- const was_n: u32 = @intCast(owners.items.len);
- if (std.mem.eql(u8, was.items, text)) {
- for (out[0..@min(out.len, owners.items.len)], owners.items[0..@min(out.len, owners.items.len)]) |*l, pin| l.pin = pin;
- moved.* = .{ .head = was_n, .tail = 0, .was = was_n, .now = was_n };
- return out;
- }
- const span = File.spanOf(was.items, text);
- const head = @min(std.mem.count(u8, was.items[0..span.head], "\n"), out.len, owners.items.len);
- for (out[0..head], owners.items[0..head]) |*l, pin| l.pin = pin;
- var tail = @min(tailLines(was.items, span.tail), out.len - head, owners.items.len - head);
- // The line the two ends meet inside (an insertion before it shares its
- // indent with the line above) is the same line when its bytes are.
- if (head + tail < @min(out.len, owners.items.len) and std.mem.eql(u8, lineFromEnd(was.items, tail), lineFromEnd(text, tail))) tail += 1;
+ moved.* = .of(was.items, text);
+ for (out[0..@min(moved.head, owners.items.len)], owners.items[0..@min(moved.head, owners.items.len)]) |*l, pin| l.pin = pin;
+ const tail = @min(moved.tail, owners.items.len);
for (out[out.len - tail ..], owners.items[owners.items.len - tail ..]) |*l, pin| l.pin = pin;
- moved.* = .{ .head = @intCast(head), .tail = @intCast(tail), .was = was_n, .now = @intCast(out.len) };
return out;
}
@@ -837,6 +1080,21 @@ pub const Moved = struct {
was: u32,
now: u32,
+ /// `was` (jj's text) lined up with `text` by what they agree on at
+ /// either end (`File.spanOf`, the editor's differ).
+ pub fn of(was: []const u8, text: []const u8) Moved {
+ const was_n: u32 = @intCast(lineCount(was));
+ const now: u32 = @intCast(lineCount(text));
+ if (std.mem.eql(u8, was, text)) return .{ .head = was_n, .tail = 0, .was = was_n, .now = was_n };
+ const span = File.spanOf(was, text);
+ const head = @min(std.mem.count(u8, was[0..span.head], "\n"), now, was_n);
+ var tail = @min(tailLines(was, span.tail), now - head, was_n - head);
+ // The line the two ends meet inside (an insertion before it shares its
+ // indent with the line above) is the same line when its bytes are.
+ if (head + tail < @min(now, was_n) and std.mem.eql(u8, lineFromEnd(was, tail), lineFromEnd(text, tail))) tail += 1;
+ return .{ .head = @intCast(head), .tail = @intCast(tail), .was = was_n, .now = now };
+ }
+
/// The text's place of jj's place `at` (before its line `at`), or null
/// inside lines rewritten since: no place there tells the truth.
fn place(m: Moved, at: u32) ?u32 {
@@ -914,7 +1172,6 @@ fn hunksOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, k: u16, step: u16,
else => return,
};
};
- const syntax = @import("syntax.zig");
var said = std.mem.splitScalar(u8, patch.text, '\n');
var run_from = taken.items.len;
var plus_from = added.items.len;
@@ -1017,13 +1274,13 @@ fn ghostsOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, pins: []const Pin,
ti += h.old_len;
// A changed line's old text right above the line; a line taken
// away whole above the next changed one's, or after the run.
- var at = carried(hunks, h.pin, if (h.new_len > 0) h.new_start - 1 + h.new_len else h.new_start, moved);
+ var at = carried(hunks, h.step, if (h.new_len > 0) h.new_start - 1 + h.new_len else h.new_start, moved);
var ats: [max_run]?u32 = undefined;
if (run.len > max_run) continue;
var k = run.len;
while (k > 0) {
k -= 1;
- if (run[k].paired) at = run[k].shown orelse carried(hunks, h.pin, run[k].new -| 1, moved);
+ if (run[k].paired) at = run[k].shown orelse carried(hunks, h.step, run[k].new -| 1, moved);
ats[k] = at;
}
var from: usize = h.removed;
@@ -1055,11 +1312,13 @@ fn ghostsOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, pins: []const Pin,
}
var first: u32 = 0;
var end: u32 = 0;
+ var step: u16 = 0;
for (hunks) |h| if (h.pin == k) {
if (first == 0) first = h.new_start;
end = if (h.new_len > 0) h.new_start - 1 + h.new_len else h.new_start;
+ step = h.step;
};
- const place = at orelse carried(hunks, @intCast(k), end, moved) orelse continue;
+ const place = at orelse carried(hunks, step, end, moved) orelse continue;
// After its own ghost rows at its place.
for (made.items) |m| if (m.g.pin == k and m.g.at == place) {
rank = m.rank | 1;
@@ -1081,15 +1340,12 @@ fn ghostsOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, pins: []const Pin,
return out;
}
-/// Where the place after line `after` of pin `k`'s revision is in the
-/// text: moved by each later change's hunks before it (a pin's, or one
+/// Where the place after line `after` of step `from`'s revision (its
+/// change's place in jj's answer, `Hunk.step`) is in the text: moved by each later change's hunks before it (a pin's, or one
/// between the pins the revset does not pin), or, inside a run of lines a
/// later one took away, after what it wrote there; then from jj's lines
/// to the text's (`moved`).
-fn carried(hunks: []const Hunk, k: u16, after: u32, moved: Moved) ?u32 {
- const from = for (hunks) |h| {
- if (h.pin == k) break h.step;
- } else 0;
+fn carried(hunks: []const Hunk, from: u16, after: u32, moved: Moved) ?u32 {
var pos: i64 = after;
var i: usize = 0;
while (i < hunks.len) {
@@ -1290,7 +1546,7 @@ fn nest(lines: []Line, npins: usize) void {
/// orange go). Distinct colours, never one between two.
pub fn laneColours(th: *const pardes.Theme, buf: *[8][3]u8) []const [3]u8 {
const pal = th.palette;
- const grounds = [2][3]u8{ if (pal) |c| c[1] else .{ 0xcf, 0x22, 0x2e }, if (pal) |c| c[2] else .{ 0x2e, 0xa0, 0x43 } };
+ const grounds = [2][3]u8{ themeRed(th), if (pal) |c| c[2] else .{ 0x2e, 0xa0, 0x43 } };
const accents: [6][3]u8 = if (pal) |c| .{ c[3], c[4], c[5], c[6], th.num, th.kw } else .{ th.kw, th.num, th.str, th.box, th.column_box orelse th.box, th.comment };
var sorted: [6][3]u8 = undefined;
var n: usize = 0;
@@ -1347,6 +1603,64 @@ fn hueApart(a: [3]u8, b: [3]u8) f32 {
/// (`Ghost`) its lanes and its cells (`inkGhost`). Not yet: a changed
/// line's words.
pub fn paint(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void {
+ if (pane.layers.heat > 0) paintHeat(p, s, pane, r, tx, body_h);
+ if (pane.layers.lanes > 0) paintLanes(p, s, pane, r, tx, tw, body_h);
+}
+
+/// The theme's red: what a change took away; churn's top.
+pub fn themeRed(th: *const pardes.Theme) [3]u8 {
+ return if (th.palette) |c| c[1] else .{ 0xcf, 0x22, 0x2e };
+}
+
+/// A count's colour on churn's gradient: smooth from the line numbers'
+/// grey to the theme's red, on a log scale of the count against the
+/// hottest; null for none.
+fn heatColour(th: *const pardes.Theme, count: u16, hottest: u16) ?[3]u8 {
+ if (count == 0 or hottest == 0) return null;
+ const t = @log(@as(f32, @floatFromInt(count)) + 1) / @log(@as(f32, @floatFromInt(hottest)) + 1);
+ return pardes.colors.mixOklab(th.lineno, themeRed(th), t);
+}
+
+/// The heat lane: a cell after the line number (before the changes'
+/// lanes, which stay next to the text they mark), a half block in its
+/// line's colour; none on a ghost row or a line in no declaration.
+fn paintHeat(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, body_h: u16) void {
+ const heat = churned(p, pane.serial) orelse return;
+ const x = tx + File.gutterWidth(pane) - File.laneCells(pane) - 1;
+ const body_y = p.bodyTop(pane, r);
+ const scroll = pane.scroll();
+ var vr: u16 = pane.context_rows;
+ while (vr < body_h) : (vr += 1) {
+ const row: i32 = if (pane.wrap_n == 0) scroll + @as(i32, vr) else if (vr < pane.wrap_n) pane.wrap_line[vr] else break;
+ if (vr < pane.wrap_n and pane.wrap_col[vr] < 0) continue;
+ if (row < 0 or row >= heat.lines.len) continue;
+ const rgb = heatColour(p.theme(), heat.lines[@intCast(row)], heat.hottest) orelse continue;
+ var style = s.at(x, body_y + vr).style;
+ style.fg = .{ .rgb = rgb };
+ s.set(x, body_y + vr, "\u{258c}", style);
+ }
+}
+
+/// Churn's strip by the scroll thumb (draw.zig, while a view shows it): a
+/// rail row each, the hottest line of the lines that row stands for; in a
+/// terminal the rail's second cell's ground, for a pixel shell a list
+/// (Surface.heat).
+pub fn railHeat(p: *Pardes, s: *pardes.Surface, pane: *Pane, id: usize, rail: pardes.Rect) void {
+ const heat = churned(p, pane.serial) orelse return;
+ const total = heat.lines.len;
+ if (rail.h == 0 or total == 0) return;
+ for (0..rail.h) |row| {
+ const lo = row * total / rail.h;
+ const hi = @max(lo + 1, (row + 1) * total / rail.h);
+ const rgb = heatColour(p.theme(), std.mem.max(u16, heat.lines[lo..@min(hi, total)]), heat.hottest) orelse continue;
+ if (p.view().frontend.windowed)
+ s.heat.append(p.gpa, .{ .owner = @intCast(id), .row = @intCast(row), .rgb = rgb }) catch {}
+ else
+ s.fill(rail.x + 1, rail.y + @as(u16, @intCast(row)), 1, 1, .{ .bg = .{ .rgb = rgb } });
+ }
+}
+
+fn paintLanes(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void {
const ch = answered(p, pane.serial) orelse return;
if (ch.lines.len == 0) return;
var buf: [8][3]u8 = undefined;
@@ -1702,7 +2016,7 @@ const WorkerJj = struct {
/// answer the session's input, as its loop hands it, and the client's.
fn land(w: *WorkerJj) !void {
var waited: u32 = 0;
- while (w.a.core.changes.task != null or w.a.core.changes.next != null) : (waited += 1) {
+ while (w.a.core.changes.task != null or w.a.core.changes.next != null or w.a.core.stream.parse != null) : (waited += 1) {
if (waited == 5000) return error.Timeout;
var batch: Inbox.Batch = .{};
w.shell.q.takeInto(&batch);
@@ -2238,6 +2552,127 @@ test "the lanes ride with the text: a line typed in a nested block is nobody's,
try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
}
+/// Two functions four changes wrote: `fn` both, `f2` and `f3` rewrote
+/// f's line, `g2` g's: f three changes, g two.
+const Churned = struct {
+ const fn_text = "fn f() void {\n a();\n}\n\nfn g() void {\n b();\n}\n";
+ const f2_text = "fn f() void {\n a2();\n}\n\nfn g() void {\n b();\n}\n";
+ const f3_text = "fn f() void {\n a3();\n}\n\nfn g() void {\n b();\n}\n";
+ const g2_text = "fn f() void {\n a3();\n}\n\nfn g() void {\n b2();\n}\n";
+
+ fn repo() !?Repo {
+ return Repo.with(testing.allocator, &.{ .{ fn_text, "fn" }, .{ f2_text, "f2" }, .{ f3_text, "f3" }, .{ g2_text, "g2" } }, null);
+ }
+};
+
+test "Churn counts the changes that touched each declaration and draws them after the line number and by the scroll thumb, grey to red on a log scale; bare again, off" {
+ const gpa = testing.allocator;
+ var repo = try Churned.repo() orelse return error.SkipZigTest;
+ defer repo.deinit(gpa);
+ for ([_]bool{ false, true }) |windowed| {
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .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].?;
+ const before = File.gutterWidth(pane);
+ p.update(.{ .command = "Churn" });
+ const heat = churned(p, pane.serial).?;
+ try testing.expectEqualSlices(u16, &.{ 3, 3, 3, 0, 2, 2, 2 }, heat.lines);
+ try testing.expectEqual(@as(u16, 3), heat.hottest);
+ try testing.expectEqual(before + 1, File.gutterWidth(pane));
+ // Drawn: a cell after the number, f's the theme's red, g's along
+ // the way from the numbers' grey at ln 3 / ln 4, none between.
+ 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;
+ const x = body.x + File.gutterWidth(pane) - 1;
+ const red = themeRed(p.theme());
+ const warm = pardes.colors.mixOklab(p.theme().lineno, red, @log(3.0) / @log(4.0));
+ for (0..7) |row| {
+ const cell = s.at(x, body.y + @as(u16, @intCast(row)));
+ if (row == 3) {
+ try testing.expectEqualStrings(" ", cell.grapheme());
+ continue;
+ }
+ try testing.expectEqualStrings("\u{258c}", cell.grapheme());
+ try testing.expectEqual(pardes.Color{ .rgb = if (row < 3) red else warm }, cell.style.fg);
+ }
+ // By the scroll thumb: the rail's first row holds f's lines.
+ const rail = s.region(.rail, id).?.rect;
+ if (windowed) {
+ const strip = for (s.heat.items) |h| {
+ if (h.owner == id and h.row == 0) break h;
+ } else return error.TestExpectedEqual;
+ try testing.expectEqual(red, strip.rgb);
+ } else try testing.expectEqual(pardes.Color{ .rgb = red }, s.at(rail.x + 1, rail.y).style.bg);
+ // Bare again: hidden, the gutter as it was; again: shown, jj not asked.
+ p.update(.{ .command = "Churn" });
+ try testing.expectEqual(before, File.gutterWidth(pane));
+ p.update(.{ .command = "Churn" });
+ try testing.expectEqual(before + 1, File.gutterWidth(pane));
+ try testing.expectEqual(heat, churned(p, pane.serial).?);
+ }
+}
+
+test "Churn's window: a revset, or a span of time back from now; jj's refusal said" {
+ const gpa = testing.allocator;
+ var repo = try Churned.repo() orelse return error.SkipZigTest;
+ defer repo.deinit(gpa);
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = false });
+ 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].?;
+ // f3 and g2 alone: one each.
+ p.update(.{ .command = "Churn @--::@" });
+ try testing.expectEqualSlices(u16, &.{ 1, 1, 1, 0, 1, 1, 1 }, churned(p, pane.serial).?.lines);
+ // The last week: all four, just made.
+ p.update(.{ .command = "Churn 1w" });
+ try testing.expectEqualSlices(u16, &.{ 3, 3, 3, 0, 2, 2, 2 }, churned(p, pane.serial).?.lines);
+ try testing.expectEqualStrings("::(@) & author_date(after:\"1 weeks ago\")", churned(p, pane.serial).?.window());
+ p.update(.{ .command = "Churn nosuch" });
+ try testing.expect(std.mem.indexOf(u8, told(p, id), "Churn: Revision `nosuch` doesn't exist") != null);
+}
+
+test "Churn on a worker: jj's answer kept raw, counted when the worker's parse of the text lands; the client equal" {
+ var repo = try Churned.repo() orelse return error.SkipZigTest;
+ defer repo.deinit(testing.allocator);
+ var w = try WorkerJj.init(&repo, "");
+ defer w.deinit();
+ try w.word("Churn");
+ try w.land();
+ try testing.expectEqualSlices(u16, &.{ 3, 3, 3, 0, 2, 2, 2 }, churned(w.a.core, w.serial).?.lines);
+ try testing.expectEqualSlices(u16, churned(w.a.core, w.serial).?.lines, churned(w.r.core(), w.serial).?.lines);
+}
+
+test "Churn's counts ride with the text, and a client replays them equal" {
+ var repo = try Churned.repo() orelse return error.SkipZigTest;
+ defer repo.deinit(testing.allocator);
+ const R = pardes.replica;
+ const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{});
+ defer a.deinit();
+ const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0));
+ defer r.deinit();
+ var line: [4200]u8 = undefined;
+ r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }));
+ r.confirm(try a.local(.{ .command = "Churn" }));
+ r.settle();
+ const serial = a.core.panes[a.core.view().active].?.serial;
+ // `a3();` deleted: its value goes with it.
+ r.confirm(try a.local(.{ .command = "Look a.zig:2" }));
+ for (";xd") |k| r.confirm(try a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }));
+ r.settle();
+ try testing.expectEqualSlices(u16, &.{ 3, 3, 0, 2, 2, 2 }, churned(a.core, serial).?.lines);
+ try testing.expect(r.diverged == null);
+ try testing.expectEqualSlices(u16, churned(a.core, serial).?.lines, churned(r.core(), serial).?.lines);
+ try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
+}
+
test "a B3 click on path@rev:line in running text opens the file at that revision there" {
const gpa = testing.allocator;
var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
diff --git a/core/regexp.zig b/core/regexp.zig
index 2936b491..4a51d0ce 100644
--- a/core/regexp.zig
+++ b/core/regexp.zig
@@ -681,3 +681,48 @@ test "a pattern that stops inside a count or an escape is refused, not read past
}
}
}
+
+test "what mvzr compiles it can walk: an empty group matches the empty string; a repeat of `|` or `^`, and a count without its `}`, are refused" {
+ std.testing.log_level = .err; // mvzr warns of each bad string
+ // An empty group with more after it, searched to a line's end, where
+ // mvzr asks whether the group may match nothing (build/patches.zig).
+ const Case = struct { pat: []const u8, text: []const u8, hit: ?[2]usize };
+ for ([_]Case{
+ .{ .pat = "()a", .text = "b", .hit = null },
+ .{ .pat = "()a", .text = "ba", .hit = .{ 1, 2 } },
+ .{ .pat = "a()b", .text = "a", .hit = null },
+ .{ .pat = "a()b", .text = "xab", .hit = .{ 1, 3 } },
+ }) |c| {
+ var rx = try Regex.compile(c.pat);
+ const m = try rx.find(c.text, 0, c.text.len, c.text.len);
+ try std.testing.expectEqual(c.hit, if (m) |h| [2]usize{ h.start, h.end } else null);
+ }
+ // A repeat right after `|` or `^` took it for what it repeats, and a
+ // count ending in neither `,` nor `}` left a hole in the program: each
+ // walked off an empty slice in the matcher.
+ for ([_][]const u8{ "a|*", "|+", "(|?)", "|??", "^*", "^+?", "a|{2}", "({1))", "a{1b" }) |pat|
+ try std.testing.expectError(error.Bad, Regex.compile(pat));
+ // Every pattern up to five characters over the first alphabet and four
+ // over the second, searched from every offset of a text with an empty
+ // line: refused, or searched to an answer inside the budget.
+ const text = "aa\n\na";
+ var pat: [5]u8 = undefined;
+ for ([_][]const u8{ "()|*+?a", "()|*+?a^{1}" }, [_]usize{ 5, 4 }) |alphabet, longest| {
+ for (1..longest + 1) |len| {
+ var n: usize = 1;
+ for (0..len) |_| n *= alphabet.len;
+ for (0..n) |k| {
+ var rest = k;
+ for (pat[0..len]) |*c| {
+ c.* = alphabet[rest % alphabet.len];
+ rest /= alphabet.len;
+ }
+ var rx = Regex.compile(pat[0..len]) catch continue;
+ for (0..text.len + 1) |from| {
+ const m = try rx.find(text, from, text.len, text.len) orelse continue;
+ try std.testing.expect(from <= m.start and m.start <= m.end and m.end <= text.len);
+ }
+ }
+ }
+ }
+}
diff --git a/core/replica.zig b/core/replica.zig
index 6072eea4..f4a3284c 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -1348,6 +1348,12 @@ pub const Peer = struct {
again: bool = false,
/// ...or that its window was closed (Peers.closed).
close: bool = false,
+ /// It said a bye: none, and the session let it go with no word of its
+ /// own (`closing`, `cut`), is a client that died (killed: P48).
+ bye: bool = false,
+ /// A pair's first client (`Joining.own`): the terminal its session
+ /// keeps is its (`Peers.pair_left`).
+ pair: bool = false,
/// Inputs read (each one's seq, as the client numbered them).
seq: u32 = 0,
/// The `stamp` frame its next input came with (its reader's).
@@ -1630,6 +1636,7 @@ pub const Peer = struct {
const b = (wire.decodeClient(tag, payload) catch return false).bye;
peer.again = b.again;
peer.close = b.close;
+ peer.bye = true;
return false;
},
.ping => {
@@ -1762,6 +1769,14 @@ pub const Peers = struct {
/// hung up) and the session is a pair's not kept (daemon.sessionState): it
/// ends there (runtime/session.zig).
closed: bool = false,
+ /// Its pair's first client left (P48): with no word at all (killed),
+ /// true; its session's frontend puts the user's terminal back then,
+ /// and lets it go either way (tui.zig `Own.sent`), and clears this.
+ pair_left: ?bool = null,
+ /// Its pair's first client's terminal or window found again (a focus
+ /// in): the session asks whether a newer build is installed, as its own
+ /// frontend asks at its own (runtime/session.zig), and clears this.
+ pair_focused: bool = false,
/// An Upgrade told its clients so (`refuseAll`): a connection handed
/// over before its exec is told the same, never closed by the exec
/// unanswered. Its exec failed: the next boundary takes joins again.
@@ -1883,6 +1898,7 @@ pub const Peers = struct {
const t0 = nowNs();
defer if (ps.samples) ps.input_ns.append(ps.gpa, nowNs() - t0) catch {};
core.toView(peer.view);
+ if (peer.pair and in.event == .focus and in.event.focus) ps.pair_focused = true;
ps.t.stamp = stampOf(in);
core.update(in.event);
core.step();
@@ -1987,7 +2003,7 @@ pub const Peers = struct {
core.gpa.free(bytes);
return daemon.refuseReplica(fd, "out of memory");
};
- peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = .at(k), .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa };
+ peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = .at(k), .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa, .pair = joining.own };
ps.next_id +%= 1;
if (ps.next_id == 0) ps.next_id = 1;
// The session's digest as dumped, for the joiner to check its load by
@@ -2062,6 +2078,7 @@ pub const Peers = struct {
ps.closeViewOf(core, peer, peer.again or peer.cut);
if (ps.count() == 0) core.unattended = ps.detached;
if (ps.count() == 0 and peer.close and daemon.sessionState() == .pair) ps.closed = true;
+ if (peer.pair) ps.pair_left = !peer.bye and !peer.closing and !peer.cut;
ps.seq += 1;
ps.unit(0, ps.seq);
ps.letGo(peer);
@@ -6327,12 +6344,10 @@ const may_wait = [_]Wait{
.{ .what = "*", .on = .addon, .stop = "a kind's close", .why = "a kind's pane closed: its state let go on the session" },
.{ .what = "*", .on = .addon, .stop = "a kind's word", .why = "a word to a kind (a key it takes as one): its own state" },
.{ .what = "*", .on = .addon, .stop = "a kind's open", .why = "a kind's pane opened (`Life`): its state made on the session" },
-} ++ (if (pardes.font_picker) [_]Wait{
- // A window's view (the font words are a window's).
+} ++ (if (pardes.builtins.capabilities.font_picker) [_]Wait{
+ // A window's view's words, which a terminal's build has too: a window
+ // client of its session runs them.
.{ .what = "Font *", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" },
-} else [_]Wait{}) ++ (if (pardes.builtins.capabilities.font_picker) [_]Wait{
- // ...and Fonts a terminal's build has too, which a window client of its
- // session runs (exec.zig's Font, a window build's alone, does not).
.{ .what = "Fonts", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" },
} else [_]Wait{});
diff --git a/core/root.zig b/core/root.zig
index 99fb4845..3bca5e03 100644
--- a/core/root.zig
+++ b/core/root.zig
@@ -55,6 +55,7 @@ pub const Facts = @import("surface.zig").Facts;
pub const Region = @import("surface.zig").Region;
pub const Chrome = @import("surface.zig").Chrome;
pub const RailTick = @import("surface.zig").RailTick;
+pub const RailHeat = @import("surface.zig").Heat;
pub const Lane = @import("surface.zig").Lane;
pub const MAX_REGIONS = @import("surface.zig").MAX_REGIONS;
/// What comes in (Event.zig).
@@ -117,7 +118,9 @@ const Loc = Jump.Loc;
pub const can_attach = platform == .tui or platform == .gui;
-pub const fonts = if (font_picker) @import("dev").fonts else struct {};
+/// The machine's fonts: every desktop build's, which steps a window's Font
+/// as the window does (builtins.capabilities), and the Mac's.
+pub const fonts = if (builtins.capabilities.font_picker) @import("dev").fonts else struct {};
pub const Pane = panes.Pane;
const Text = panes.Text;
diff --git a/core/surface.zig b/core/surface.zig
index 653abd82..3ab9a933 100644
--- a/core/surface.zig
+++ b/core/surface.zig
@@ -151,6 +151,9 @@ pub const max_rail_ticks = 4096;
/// it as a strip in gutter cell `x`, at its `level`'s place (sample A of
/// the ruled design: each a third of a cell wide, half that of air between).
pub const Lane = struct { x: u16, y: u16, level: u8, rgb: [3]u8 };
+/// Churn's strip on a rail (jj.railHeat): a pixel shell draws its row of
+/// pane `owner`'s rail, beside the track, in `rgb`.
+pub const Heat = struct { owner: u8, row: u16, rgb: [3]u8 };
pub const rail_tick_scale = 1024;
pub const Chrome = struct {
@@ -266,6 +269,9 @@ pub const Surface = struct {
/// makes many a temporary Surface, and a safe build fills an array's
/// `undefined` in each).
lanes: std.ArrayList(Lane) = .empty,
+ /// Churn's strips by the scroll thumbs, for a pixel shell (in a
+ /// terminal the rail's cells), as `lanes`.
+ heat: std.ArrayList(Heat) = .empty,
chrome: Chrome = .{},
cells: []Cell = &.{},
/// bar: draw an insert-style thin cursor instead of the block
diff --git a/core/tape.zig b/core/tape.zig
index 1cbf8aed..dc53a7c9 100644
--- a/core/tape.zig
+++ b/core/tape.zig
@@ -140,6 +140,9 @@ pub const Site = enum(u16) {
/// A kitty image's medium as a terminal's emulator read it (a file, a
/// temporary file, shared memory: Term.media), its bytes or its failure.
medium,
+ /// An addon's library loaded or let go (Addon.perform): what it brought
+ /// is the `addon` event inside it, which a replica applies from here.
+ landing,
};
/// What the sites return. wire.semantics hashes their shape with the
diff --git a/dev/fonts.zig b/dev/fonts.zig
index 540e3a60..3d69c8a1 100644
--- a/dev/fonts.zig
+++ b/dev/fonts.zig
@@ -4,9 +4,9 @@
//! because the core has no font and the shells have no builtin dispatch.
//!
//! It lives at src/ rather than under gui/ because two shells draw their own
-//! text. It is compiled only behind `pardes.font_picker` (gui or macos), so
-//! the tui binary never opens a font directory, and the browser has none to
-//! open.
+//! text. It is compiled behind `builtins.capabilities.font_picker` (a
+//! desktop build, whose terminal steps a window's Fonts and Font as the
+//! window does, or the Mac's): the browser has none to open.
//!
//! No fontconfig and no CoreText. Enumerating fonts is a walk over a handful
//! of well-known directories, and the one thing the picker must know about
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index d9d38f06..3193d966 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -1132,6 +1132,9 @@ const Client = struct {
titled: bool = false,
moving: bool = false,
blink: ?Blink = null,
+ /// The session's WindowOpacity this window last took (P47: each
+ /// window applies it to the view it draws; none answers the core).
+ opacity: ?u8 = null,
fn deinit(cl: *Client) void {
cl.pending.deinit(cl.gpa);
@@ -1173,6 +1176,7 @@ const Client = struct {
const g = cl.g;
const core = l.link.r.core();
g.session_font_request = null;
+ cl.opacity = null;
cl.shell.core = core;
cl.shell.gview = cl.joins.joined.view;
cl.shell.surface = null;
@@ -1206,6 +1210,14 @@ const Client = struct {
const link = &l.link;
l.frames.period_ns = refreshNs(g);
if (syncReplicaFont(g, &cl.in.core.settings.font, gpa)) link.dirty = true;
+ const opacity = cl.in.core.settings.window_opacity;
+ if (cl.opacity != opacity) {
+ cl.opacity = opacity;
+ if (applyWindowOpacity(g, opacity) catch return false) |why| {
+ log.warn("WindowOpacity: {s}", .{why});
+ } else g.applied_window_opacity = opacity;
+ link.dirty = true;
+ }
if (scrollRows(g, &cl.in, gpa)) link.dirty = true;
if (fitTaglineFont(g, g.facts.tagline_percent)) link.dirty = true;
const geom = windowCells(g);
@@ -3025,12 +3037,24 @@ fn finishWindowOpacity(core: *pardes.Pardes, applied: *u8, failure: ?[]const u8)
fn syncWindowOpacity(g: *Gui, core: *pardes.Pardes) void {
if (!core.settings.window_opacity_pending) return;
+ const failure = applyWindowOpacity(g, core.settings.window_opacity) catch blk: {
+ core.quit = true;
+ break :blk null;
+ };
+ finishWindowOpacity(core, &g.applied_window_opacity, failure);
+}
+
+/// What the window does at a WindowOpacity, the own window's and a
+/// client's (P47: a window's facts are the process's that draws it): why
+/// it cannot, or null; error.NoWindow when it was made again and could
+/// not be.
+fn applyWindowOpacity(g: *Gui, opacity: u8) error{NoWindow}!?[]const u8 {
// The first opacity under 100 on Wayland: the window made again,
// transparent, presenting through SDL_Renderer from then on (the
// capture's format, the swapchain's, is one it uploads). At a start's
// own WindowOpacity this is before its first frame, so unseen.
const unorm = g.present.swapchain_format == c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM or g.present.swapchain_format == c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;
- if (g.wayland and !g.present.surface_opacity and core.settings.window_opacity < 100 and unorm) {
+ if (g.wayland and !g.present.surface_opacity and opacity < 100 and unorm) {
// A `--detach` session's window stays hidden.
const hidden = c.SDL_GetWindowFlags(g.window) & c.SDL_WINDOW_HIDDEN;
const mode = g.present.present_mode;
@@ -3046,16 +3070,16 @@ fn syncWindowOpacity(g: *Gui, core: *pardes.Pardes) void {
g.present.surface_opacity = false;
g.present.present_mode = mode;
g.win_flags &= ~@as(c.SDL_WindowFlags, c.SDL_WINDOW_TRANSPARENT);
- if (!reopenWindow(g)) core.quit = true;
+ if (!reopenWindow(g)) return error.NoWindow;
}
g.win_flags &= ~hidden;
}
// Offscreen captures also support per-pixel alpha. Never approximate this
// with SDL_SetWindowOpacity: that would make foreground text translucent.
- finishWindowOpacity(core, &g.applied_window_opacity, if (g.present.surface_opacity or g.present.capture or core.settings.window_opacity == 100)
+ return if (g.present.surface_opacity or g.present.capture or opacity == 100)
null
else
- "background transparency requires a native Wayland or alpha-capable SDL window");
+ "background transparency requires a native Wayland or alpha-capable SDL window";
}
fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) bool {
@@ -4891,7 +4915,7 @@ fn buildDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, g
else => {},
} else false;
if (grid_bottom < win_h and tag_last) try addDecor(g, gpa, 0, grid_bottom, win_w, win_h, chrome.tag_bg, 1, win_w, win_h);
- try paneDecor(g, gpa, regions, surface.rail_ticks[0..surface.nrail_ticks], chrome, layout, surface.cols, surface.rows, win_w, win_h);
+ try paneDecor(g, gpa, regions, surface.rail_ticks[0..surface.nrail_ticks], surface.heat.items, chrome, layout, surface.cols, surface.rows, win_w, win_h);
// The changes' lanes (jj.paint): a strip a level in the gutter's
// lane cells, each a third of a cell wide with half that of air
// before it, so three take one and a half cells (the ruled
@@ -4934,7 +4958,7 @@ fn buildDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, g
/// Each pane's rule between its tag and body, and its scroll rail: a page
/// coloured gutter with a thin track and its thumb, running down through the
/// pixels past the last whole row.
-fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ticks: []const pardes.RailTick, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32) !void {
+fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ticks: []const pardes.RailTick, heat: []const pardes.RailHeat, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32) !void {
const page = chrome.page orelse bg_default;
for (regions) |rail| {
if (rail.kind != .rail or rail.rect.h == 0) continue;
@@ -5013,6 +5037,14 @@ fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ti
const ty = y0 + std.math.clamp(at * track_px, 0, track_px - h);
try addDecor(g, gpa, column[0], ty, column[1], ty + h, if (tick.current) chrome.match_current else chrome.match_tick, 1, win_w, win_h);
};
+ // Churn's strip (jj.railHeat): beside the track, at the rail's
+ // right edge, a rail row each.
+ const strip_x1 = x0 + @as(f32, @floatFromInt(config.GUTTER)) * layout.w - dp(1);
+ const strip_x0 = @max(column[1], strip_x1 - dp(2));
+ for (heat) |h| if (h.owner == rail.owner and h.row < rail.rect.h) {
+ const hy = y0 + @as(f32, @floatFromInt(h.row)) * layout.h;
+ try addDecor(g, gpa, strip_x0, hy, strip_x1, hy + layout.h, h.rgb, 1, win_w, win_h);
+ };
}
}
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index 2f731e68..5d75722f 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -559,8 +559,12 @@ fn surfaceHasKittyKey(surface: *const pardes.Surface, key: u64) bool {
/// opens it; one open already (a session forked off its stub,
/// daemon.forkSession); or none, detached from the start (`--detach`).
/// The terminal a session starts on: /dev/tty, one its stub opened (an
-/// upgraded session's is raw already, `termios` the cooked one), or none.
-pub const Term = union(enum) { open, fd: struct { fd: posix.fd_t, termios: ?posix.termios = null }, detached };
+/// upgraded session's is raw already, `termios` the cooked one), or none:
+/// a pair's (main.zig `pair`) draws on none, and keeps its client's, with
+/// its modes before the client took it, to put back if that client dies
+/// with no word (P48: `Own.sent`).
+pub const Term = union(enum) { open, fd: struct { fd: posix.fd_t, termios: ?posix.termios = null }, detached, pair: Kept };
+pub const Kept = struct { fd: posix.fd_t, termios: posix.termios };
pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void {
const io = init.io;
@@ -583,7 +587,7 @@ pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void {
switch (term) {
.open => try screen.enter(try vaxis.Tty.init(io, &tty_buf)),
.fd => |t| try screen.enter(try Screen.ttyOn(io, &tty_buf, t.fd, t.termios)),
- .detached => {},
+ .detached, .pair => {},
}
defer screen.leave();
@@ -591,7 +595,7 @@ pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void {
defer paste_buf.deinit();
var loop: Loop = .init(io, &screen.tty, &screen.vx);
- var own: Own = .{ .screen = &screen, .loop = &loop, .paste_buf = &paste_buf };
+ var own: Own = .{ .screen = &screen, .loop = &loop, .paste_buf = &paste_buf, .kept = if (term == .pair) term.pair else null };
try session_loop.Loop(Own).run(init, opts, &own);
}
@@ -897,12 +901,14 @@ const Screen = struct {
fn leave(sc: *Screen) void {
if (!sc.on) return;
sc.on = false;
- Killed.disarm();
clearNativeImages(&sc.kitty, &sc.vx, &sc.tty);
sc.vx.exitAltScreen(sc.tty.writer()) catch {};
sc.vx.deinit(sc.gpa, sc.tty.writer());
if (comptime !builtin.is_test) vaxis.tty.global_tty = null;
- sc.tty.deinit(); // restore cooked termios LAST, after vx flushed its resets
+ // The cooked modes back LAST, after vx flushed its resets, and Killed
+ // armed until they are.
+ Killed.disarm();
+ sc.tty.deinit();
}
/// Its terminal hung up, or the stub that waits on it is gone.
@@ -929,7 +935,9 @@ const Screen = struct {
const Killed = struct {
var fd: posix.fd_t = -1;
var cooked: posix.termios = undefined;
- const reset = "\x1b[<u\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1004l\x1b[?2004l\x1b[0m\x1b[?25h\x1b[?1049l";
+ /// Every mode it may have turned on off (the in-band resize its
+ /// terminal query asks for, vaxis's `in_band_resize_set`, too).
+ const reset = "\x1b[<u\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1004l\x1b[?2004l\x1b[?2048l\x1b[0m\x1b[?25h\x1b[?1049l";
fn arm(tty_fd: posix.fd_t, termios: posix.termios) void {
cooked = termios;
fd = tty_fd;
@@ -939,18 +947,24 @@ const Killed = struct {
if (daemon.link < 0) posix.sigaction(.HUP, &on, null);
}
- /// The terminal gone (put back, or detached): a TERM still takes the
- /// socket, the prompt files and the shells with it, and leaves the
- /// terminal alone.
+ fn putBack(tty: posix.fd_t, termios: *const posix.termios) void {
+ _ = std.c.write(tty, reset, reset.len);
+ _ = std.c.tcsetattr(tty, .FLUSH, termios);
+ }
+
+ /// The terminal let go (Screen.leave): its cooked modes put back first,
+ /// so that a TERM anywhere in a leave finds them back or puts them back
+ /// itself (let go first, a TERM before vaxis put them back died leaving
+ /// the terminal raw for good); then a TERM still takes the socket,
+ /// the prompt files and the shells with it, and leaves the terminal
+ /// alone.
fn disarm() void {
+ if (fd >= 0) _ = std.c.tcsetattr(fd, .FLUSH, &cooked);
fd = -1;
}
fn handle(sig: posix.SIG) callconv(.c) void {
- if (fd >= 0) {
- _ = std.c.write(fd, reset, reset.len);
- _ = std.c.tcsetattr(fd, .FLUSH, &cooked);
- }
+ if (fd >= 0) putBack(fd, &cooked);
// The 9P socket and private prompt files go too: a killed editor
// leaves none behind. Its shells too, the daemon's dups let go.
ninep_io.unlinkOwnSocket();
@@ -971,6 +985,9 @@ const Own = struct {
paste_buf: *std.Io.Writer.Allocating,
frame_arena: std.heap.ArenaAllocator = undefined,
sh: Shell = undefined,
+ /// A pair's: its client's terminal (Term.pair), until that client
+ /// leaves.
+ kept: ?Kept = null,
const Session = session_loop.Loop(Own);
@@ -1007,6 +1024,12 @@ const Own = struct {
if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec);
// Nobody to see it, and nobody to size it: `size` sets it (ctl.zig).
sh.setAttended(!sh.detached());
+ // An upgraded pair's client joins again at once: what the session
+ // says meanwhile ("Upgrade: now") waits for it, as at a Restore
+ // (session.zig `restore`), not 800 ms on an unattended clock.
+ if (comptime !builtin.is_test) if (upgrade.resumed) |rec| if (rec.state == .pair) {
+ l.core.unattended = false;
+ };
return host;
}
@@ -1027,6 +1050,7 @@ const Own = struct {
o.screen.art.deinit(gpa);
o.screen.glide.deinit(gpa);
o.frame_arena.deinit();
+ if (o.kept) |k| _ = libc.close(k.fd);
}
pub fn start(o: *Own, l: *Session) !void {
@@ -1051,6 +1075,17 @@ const Own = struct {
pub fn sent(o: *Own) void {
const sh = &o.sh;
if (sh.peers.recording and sh.detached()) sh.drawn_ns = @intCast(std.Io.Clock.awake.now(sh.io).nanoseconds);
+ // A pair's client gone: dead with no word (a kill -9), its
+ // terminal put back as the own path's survivor puts it back (a
+ // forked session's when its stub is killed), from the alternate
+ // screen and raw; with a word, it did that itself. Let go either
+ // way: a terminal held open keeps an ssh, or its emulator, waiting.
+ const lost = sh.peers.pair_left orelse return;
+ sh.peers.pair_left = null;
+ const k = o.kept orelse return;
+ o.kept = null;
+ if (lost) Killed.putBack(k.fd, &k.termios);
+ _ = libc.close(k.fd);
}
pub fn upgradeAsked(o: *Own) void {
diff --git a/docs/mvzr-empty-group.md b/docs/mvzr-empty-group.md
new file mode 100644
index 00000000..a3028fc7
--- /dev/null
+++ b/docs/mvzr-empty-group.md
@@ -0,0 +1,132 @@
+# mvzr: three kinds of pattern compile into a program the matcher walks off an empty slice
+
+A report for upstream (https://github.com/mnemnion/mvzr), against trunk
+3efcfe3 (0.3.9; its trunk when last fetched here, 2026-11-19). pardes
+patches its fetched copy at build time (build/patches.zig) until it is
+fixed there.
+
+## What happens
+
+```zig
+const mvzr = @import("mvzr");
+// each of these panics in Debug and ReleaseSafe: index out of bounds,
+// or (`^*`) reached unreachable code
+_ = mvzr.compile("()a").?.match("b");
+_ = mvzr.compile("a()b").?.match("a");
+_ = mvzr.compile("a|*").?.match("a");
+_ = mvzr.compile("|*").?.match("b");
+_ = mvzr.compile("|??").?.match("");
+_ = mvzr.compile("^*").?.match("a");
+_ = mvzr.compile("({1))").?.match("a");
+// and these compile to something else: `a{1b` to `a` (it matches "a"),
+// `a|{2}` to a program that matches "" at the start of "a"
+```
+
+A program that searches with what a person types, at each key (an
+editor's incremental search), reaches the first as soon as the person has
+typed `()` and one character more, wherever a line ends before a match.
+
+Searched from every offset of three short texts (each line its own
+haystack), every pattern up to seven characters over `()|*+?a` (960,799):
+18,746 panic; up to six over `()|*+?a^$.{}1` (5,229,042): 68,627; up to
+five over `()[]{},*+?|\^$.-a1xnbf` (5,399,042): 40,135.
+
+## Why
+
+**An empty group with more after it.** At the end of the haystack
+`matchPattern` asks `groupAcceptsEmpty` whether a group may match nothing.
+`hasAlt` answers true at the group's own `)` when more pattern follows it
+(docs/mvzr-group-backtrack.md, the same quirk), so a group with no `|`
+takes the alternatives branch, whose last line is
+`return (patternAcceptsEmpty(inner_patt));`, and `patternAcceptsEmpty`
+switches on `patt[0]` of the empty inside. (The branch without
+alternatives checks `inner.len == 0` first; this one does not.)
+
+**A repeat right after `|` or `^`.** `prefixModifier` refuses a repeat with
+nothing before it by `if (j == 0 or patt[j] == .begin)`, but `patt[j]` is
+the slot about to be written and is never `.begin`. So `^*` compiles to
+`star, begin`, and the matcher meets `.begin` where it is `unreachable`;
+and a repeat after `|` takes the `.alt` for what it repeats: `|*` compiles
+to `star, alt`. Split at the `|`, the first alternative is a lone `star`,
+and `thisPattern` (from `matchStar`) or `nextPattern` (`|??`) reads
+`patt[0]` of the empty slice after it.
+
+**A count that ends in neither `,` nor `}`.** After `{` and a number,
+`compileRegex` handles `,` and `}`; any other character writes no
+operation, and the dispatch loop's step moves past it, so the program has
+an `.unused` slot there, which `findPatternEnd` takes for its end. `a{1b`
+runs as `a`; `({1))` (its first `)` skipped, its second closing the `(`)
+runs as a lone `.left`, and `sliceGroup` reads past it.
+
+## The fix
+
+An empty pattern accepts the empty string; a repeat after `^` or `|` is a
+bad string, as one at the start of the pattern is (`patt[j - 1]`, as the
+`.begin` test seems to have meant); a count followed by anything but `,`
+or `}` is a bad string, as the other unfinished counts are. With it the
+same patterns make no panic (0 of 11,588,883), and mvzr's own tests pass
+with the one below (32 of 32; the copy tested had its four uses of `**`
+replaced, which Zig 0.17 needs: PR #16; without the fix the new test
+aborts at `patternAcceptsEmpty`).
+
+```diff
+diff --git a/src/mvzr.zig b/src/mvzr.zig
+index d4ea747..791664e 100644
+--- a/src/mvzr.zig
++++ b/src/mvzr.zig
+@@ -983,6 +983,7 @@ fn thisGroup(patt: []const RegOp) []const RegOp {
+ }
+
+ fn patternAcceptsEmpty(patt: []const RegOp) bool {
++ if (patt.len == 0) return true;
+ switch (patt[0]) {
+ .optional,
+ .star,
+@@ -1190,7 +1191,7 @@ pub fn resourcesNeeded(comptime in: []const u8) struct { comptime_int, comptime_
+
+ /// Move modifiers to prefix position.
+ fn prefixModifier(patt: []RegOp, j: usize, op: RegOp) !usize {
+- if (j == 0 or patt[j] == .begin) return BadString;
++ if (j == 0 or patt[j - 1] == .begin or patt[j - 1] == .alt) return BadString;
+ var find_j = j - 1;
+ // travel back before last group
+ switch (patt[find_j]) {
+@@ -1518,7 +1519,10 @@ fn compileRegex(RegexT: type, in: []const u8) ?RegexT {
+ bad_string = true;
+ break :dispatch;
+ };
+- } else if (in[i] == '}') {
++ } else if (in[i] != '}') {
++ bad_string = true;
++ break :dispatch;
++ } else {
+ // {M}
+ j += prefixModifier(patt, j, RegOp{ .some = c1 }) catch {
+ bad_string = true;
+@@ -2552,3 +2556,15 @@ test "iterator with empty alternation terminates" {
+ while (r_iter.next()) |_| {}
+ try expectEqual(null, r_iter.next());
+ }
++
++test "an empty group, a repeat after | or ^, a count without its }: no walk off an empty slice" {
++ // An empty group with more after it may match nothing.
++ try expect(compile("()a").?.match("b") == null);
++ try expect(compile("a()b").?.match("a") == null);
++ try expectEqual(1, compile("()a").?.match("ba").?.start);
++ try expectEqual(3, compile("a()b").?.match("xab").?.end);
++ // A repeat needs something to repeat; a count needs its `}`.
++ for ([_][]const u8{ "a|*", "|+", "(|?)", "|??", "^*", "^+?", "a|{2}", "({1))", "a{1b" }) |patt| {
++ try expect(compile(patt) == null);
++ }
++}
+```
+
+## Left as they are
+
+- `patternAcceptsEmpty` judges a pattern by its first operation: `x(a*b)`
+ matches `x` (the group is taken to accept the empty string because `a*`
+ does), and `(()a)` now matches the empty string at the end of `b` where
+ it panicked. Asking it of every piece of the sequence is the full fix.
+- A repeat right after `(` takes the `(` for what it repeats: `(*a)`
+ compiles as `(a)*` and matches `aa`. Testing `.left` in the same line
+ refuses it; nothing panics on it, so pardes leaves it.
diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json
index ad1f98df..aeaf6953 100644
--- a/docs/typ/builtins-gui.json
+++ b/docs/typ/builtins-gui.json
@@ -10,7 +10,8 @@
{"name": "Callstack", "leader": "SPC l b", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show outermost callers first, with signatures and call sites (gc)."},
{"name": "CallstackDepth", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit."},
{"name": "Changelog", "leader": "SPC h c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "This build's version and what changed to reach it, printed into an output buffer the same way Config prints the live settings."},
- {"name": "Changes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pin the changes `revset` names (jj) on a file's pane and show them in this view: a lane each after the line number, a line one added whole green, what the file no longer has drawn where it stood (ghost rows: a line taken away whole red, each change's description after its last line); bare, shown here or not (none pinned yet: `@`)."},
+ {"name": "Changes", "leader": "SPC t c", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pin the changes `revset` names (jj) on a file's pane and show them in this view: a lane each after the line number, a line one added whole green, what the file no longer has drawn where it stood (ghost rows: a line taken away whole red, each change's description after its last line); bare, shown here or not (none pinned yet: `@`)."},
+ {"name": "Churn", "leader": "SPC t u", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Count, for each declaration of a file's pane, the changes in `window` (jj) that touched it, and show it in this view: a heat lane after the line number and a strip by the scroll thumb, the line numbers' grey to the theme's red on a log scale; `window` a revset or a span of time (`3d`, `2w`, `6m`, `1y`); bare, shown here or not (none counted yet: the file's whole history)."},
{"name": "ClipPaste", "leader": "SPC p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard after the selection."},
{"name": "ClipPasteBefore", "leader": "SPC P", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard before the selection."},
{"name": "ClipReplace", "leader": "SPC R", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Replace the selection with the system clipboard."},
diff --git a/docs/typ/builtins-tui.json b/docs/typ/builtins-tui.json
index 3ec4ea07..2263df44 100644
--- a/docs/typ/builtins-tui.json
+++ b/docs/typ/builtins-tui.json
@@ -10,7 +10,8 @@
{"name": "Callstack", "leader": "SPC l b", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show outermost callers first, with signatures and call sites (gc)."},
{"name": "CallstackDepth", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit."},
{"name": "Changelog", "leader": "SPC h c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "This build's version and what changed to reach it, printed into an output buffer the same way Config prints the live settings."},
- {"name": "Changes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pin the changes `revset` names (jj) on a file's pane and show them in this view: a lane each after the line number, a line one added whole green, what the file no longer has drawn where it stood (ghost rows: a line taken away whole red, each change's description after its last line); bare, shown here or not (none pinned yet: `@`)."},
+ {"name": "Changes", "leader": "SPC t c", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pin the changes `revset` names (jj) on a file's pane and show them in this view: a lane each after the line number, a line one added whole green, what the file no longer has drawn where it stood (ghost rows: a line taken away whole red, each change's description after its last line); bare, shown here or not (none pinned yet: `@`)."},
+ {"name": "Churn", "leader": "SPC t u", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Count, for each declaration of a file's pane, the changes in `window` (jj) that touched it, and show it in this view: a heat lane after the line number and a strip by the scroll thumb, the line numbers' grey to the theme's red on a log scale; `window` a revset or a span of time (`3d`, `2w`, `6m`, `1y`); bare, shown here or not (none counted yet: the file's whole history)."},
{"name": "ClipPaste", "leader": "SPC p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard after the selection."},
{"name": "ClipPasteBefore", "leader": "SPC P", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard before the selection."},
{"name": "ClipReplace", "leader": "SPC R", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Replace the selection with the system clipboard."},
diff --git a/docs/typ/cheatsheet.typ b/docs/typ/cheatsheet.typ
index 2df92b00..d65ca6d9 100644
--- a/docs/typ/cheatsheet.typ
+++ b/docs/typ/cheatsheet.typ
@@ -101,6 +101,8 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla
key("SPC t t"), word("Themes"),
key("SPC t n"), word("NextColor"),
key("SPC t w"), word("Wrap"),
+ key("SPC t c"), word("Changes"),
+ key("SPC t u"), word("Churn"),
key("SPC c n"), word("Newcol"),
key("SPC s d"), word("Dump"),
key("SPC s r"), word("Restore"),
@@ -117,6 +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")
== 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 0d55c6a6..e73eabaf 100644
--- a/docs/typ/guide.typ
+++ b/docs/typ/guide.typ
@@ -295,24 +295,57 @@ the revision has not) is said in jj's words. jj reads the working copy as
it last saw it (`@`): pardes never snapshots it.
#word("Syntax") (#key("SPC t h")) turns a text's syntax colours off in
this view, and on again.
-#word("Changes") with a revset pins its changes on a file's pane (or a
-revision's) and shows them in this view (one set a pane: another view's
-revset replaces it there too); bare, they are hidden in this view or shown
-again, and with none pinned yet it is `@`, the change against its parent. Each change that touched the file gets a lane after the
-line number, from its first line to its last, in the theme's accents in
-hue order, 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. What the file no longer has is drawn where it stood, a
-ghost row with no number: a line a change took away whole, red across;
-each change's description (`id title author age`) after its last line, in
-its lane's colour. The cursor steps over ghost rows, search and selection
-do not see them, and a Look on one opens its line in the revision it came
-from. `]g` and `[g` go to the next and the previous change. jj answers
-once, when the word is run: the lanes and the ghost rows ride with the
-lines through edits made since. A line a change changed is not green across: its
-old text stands right above it as a ghost row, the words that went red,
-and on the line the words that came are green (the patch view's
-alignment says which lines are one line changed).
+
+= Changes on the source view <changes>
+
+jj's changes drawn on a file's own pane, as layers each view wears or
+not: the text stays the text (the patch view, `+Diff`, is unchanged).
+Nothing is shown, and nothing asked of jj, until a word is run.
+
+#pairs(
+ [#word("Changes") `revset` (#key("SPC t c"))], [pins the revset's changes that touched the file on its pane (or a revision's) and shows them in this view; one set a pane (another view's revset replaces it there too). Bare: hidden in this view or shown again; with none pinned yet, `@`, the change against its parent],
+ [#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],
+)
+
+*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.
+
+*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;
+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
+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
+lines shows none of them.
+
+*Churn.* A cell after the line number, from the line numbers' grey to the
+theme's red on a log scale of the count against the file's hottest
+declaration, the declaration a line is in being the innermost
+tree-sitter finds (a line in none has none); beside the scroll thumb a
+strip, each of its rows the hottest of the lines it stands for. With
+#word("Changes") on too, the churn's cell comes first and the lanes stay
+next to the text they mark. A file's history is followed by its name:
+what it had under another name before a move is not counted.
+
+jj answers once, when the word is run, on a worker (the editor goes on);
+its answer is lined up with the pane's text as it is then (lines typed
+before jj's last snapshot or while it ran), and the lanes, ghost rows and
+counts ride with the lines through the edits made since. A place inside
+lines rewritten since jj's snapshot has no ghost row. A change between
+two pinned ones that the revset does not pin still moves the older ones'
+ghost rows to where they stand.
= Call hierarchy <callstack>
diff --git a/runtime/main.zig b/runtime/main.zig
index aa35e687..5cdf5ee0 100644
--- a/runtime/main.zig
+++ b/runtime/main.zig
@@ -1583,17 +1583,17 @@ fn nativeMain(std_init: std.process.Init) !void {
daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, rec.state orelse if (detached) .detached else .attached);
} else if (paired) |fd| {
// A window's pair's session: its first client on `fd`, the daemon
- // its own to dial (and to start, when none runs).
+ // its own to dial (and to start, when none runs), listed as the
+ // window's (P49: only a window's pair execs one with `--paired`).
opts.pair = fd;
term = .detached;
detached = true;
- if (daemon.wanted()) _ = daemon.register(null, kind, opts.ninep_name, .pair);
+ if (daemon.wanted()) _ = daemon.register(null, .gui, opts.ninep_name, .pair);
} else if (detach == null and std.c.getenv("PARDES_PAIR") != null) {
// The last step's way, behind its variable until it is the default:
// this terminal or window a client of a session forked off for it
// (`pair`).
- pair(init, &opts, args);
- term = .detached;
+ term = if (pair(init, &opts, args)) |kept| .{ .pair = kept } else .detached;
} else if (daemon.wanted()) {
if (detach != null or pardes.platform == .gui) {
// A session started detached is kept from birth: a pair's word.
@@ -1756,9 +1756,11 @@ fn pardesBeside(buf: *[4104]u8) ?[:0]const u8 {
/// effects (runtime/session.zig). A window's child execs the `pardes`
/// beside it (`--paired=FD` first, its arguments after), which dials the
/// daemon itself: a window's session loop is woken through SDL (gui.zig
-/// `sdlWake`), a terminal's needs none. Returns in a terminal's session;
-/// the client exits. No fork to be had: returns, and this process is the
-/// session, with no terminal: said by the caller's run. A window with no
+/// `sdlWake`), a terminal's needs none. Returns in a terminal's session,
+/// with the terminal its client draws on, cooked as it is now (P48: put
+/// back if that client dies with no word); the client exits. No fork to
+/// be had: returns, and this process is the session, with no terminal:
+/// said by the caller's run. A window with no
/// `pardes` beside it returns at once, its own session as before.
/// A terminal's launch with no terminal to draw on (a detached pty, a
/// daemon): said, not an error trace, and exit 1.
@@ -1767,23 +1769,22 @@ fn noTerminal(io: std.Io) noreturn {
std.process.exit(1);
}
-fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u8) void {
+fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u8) ?@import("dev").tui.Kept {
var path_buf: [4104]u8 = undefined;
var fd_buf: [32]u8 = undefined;
var argv: [64:null]?[*:0]const u8 = @splat(null);
if (pardes.platform == .gui) {
- const path = pardesBeside(&path_buf) orelse return;
- if (args.len >= argv.len - 1 or std.c.access(path, std.c.X_OK) != 0) return;
+ const path = pardesBeside(&path_buf) orelse return null;
+ if (args.len >= argv.len - 1 or std.c.access(path, std.c.X_OK) != 0) return null;
argv[0] = path.ptr;
for (args[1..], 2..) |a, k| argv[k] = a.ptr;
}
// Its client draws on /dev/tty: none to be had, said as the own path
- // says it, before a session is forked for nobody.
- if (pardes.platform == .tui) {
- const tty = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(std.c.mode_t, 0));
- if (tty < 0) noTerminal(init.io);
- _ = std.c.close(tty);
- }
+ // says it, before a session is forked for nobody. The session keeps it,
+ // cooked as it is now. std.posix's termios: glibc's is a bigger struct.
+ const tty: c_int = if (pardes.platform == .tui) std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(std.c.mode_t, 0)) else -1;
+ if (pardes.platform == .tui and tty < 0) noTerminal(init.io);
+ const cooked = if (tty >= 0) std.posix.tcgetattr(tty) catch null else null;
const conn: ?c_int = if (pardes.platform == .tui and daemon.wanted()) daemon.connect(true) else null;
var fds: [2]c_int = undefined;
if (std.c.socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0)
@@ -1815,8 +1816,11 @@ fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u
// The daemon is the client's to start; the hello is this one's.
daemon.startPending(false);
if (conn) |c| _ = daemon.register(c, .tty, opts.ninep_name, .pair);
- return;
+ if (cooked) |t| return .{ .fd = tty, .termios = t };
+ if (tty >= 0) _ = std.c.close(tty);
+ return null;
}
+ if (tty >= 0) _ = std.c.close(tty);
_ = std.c.close(fds[0]);
if (conn) |c| _ = std.c.close(c);
daemon.startPending(true);
diff --git a/runtime/session.zig b/runtime/session.zig
index 75e8efcc..50497560 100644
--- a/runtime/session.zig
+++ b/runtime/session.zig
@@ -23,7 +23,8 @@
//! - `start(l)`: after the first effects, the ptys and the watches
//! read: its input, its readers, the listener's wake, a detached
//! session's first wait (`l.watch`).
-//! - `sent()`: after each step's unit went to the clients.
+//! - `sent()`: after each step's unit went to the clients (a pair's
+//! client gone with it: before its session ends).
//! - `upgradeAsked()`: an Upgrade asked in the step, done (it execs).
//! - `restoring(nc)`, `restored(l)`: a Restore's new core, before it
//! replaces the old one (its devices let go, what it is told of the
@@ -130,11 +131,18 @@ pub fn Loop(comptime Frontend: type) type {
try l.core.pump(l.host);
// Its unit to each replica client, and theirs taken in.
l.peers.boundary(l.core);
+ // Before a pair's end: its client's terminal put back (P48).
+ fe.sent();
+ // A pair's client stands for the frontend it was started
+ // for: at its focus in, a newer build said (upgrade.zig).
+ if (l.peers.pair_focused) {
+ l.peers.pair_focused = false;
+ upgrade.noticeNewer(l.core);
+ }
// A pair's session with no daemon ends with its last link:
// nothing could attach to it again; with one, when its last
// client left with a close (not a loss) and it is not kept.
if (l.peers.count() == 0 and (l.peers.closed or (o.pair != null and daemon.link < 0))) break;
- fe.sent();
upgrade.locate();
// Asked in the step (the word), done between steps: the
// session whole.
diff --git a/test/daemon.py b/test/daemon.py
index c91e6dde..9c0252e5 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -29,6 +29,8 @@ private HOME and runtime directory:
`pardes new --detach` returns once its session runs
python3 -B test/daemon.py --pair <pardes>
PARDES_PAIR: a terminal's session and its first client
+ python3 -B test/daemon.py --with-pair <mode> ...
+ any mode with PARDES_PAIR set in every process it starts
python3 -B test/daemon.py --attach-upgrading <pardes>
an attach started as its session upgrades, and two clients' views
across an Upgrade (in plain and --pair too)
@@ -69,6 +71,29 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from ninep import Client # noqa: E402
+# `--with-pair` before a mode: that mode as a user who exported PARDES_PAIR.
+WITH_PAIR = False
+
+
+def base_env():
+ """This process's environment without the caller's PARDES_* (a session
+ of the user's) or a pager; under `--with-pair`, PARDES_PAIR set in it, as
+ for a user who exported it: every mode run with the variable."""
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ if WITH_PAIR:
+ env['PARDES_PAIR'] = '1'
+ return env
+
+
+def listed_as(word, kind='tty'):
+ """How `--ps` lists a session `detached` (started so, or Detached in its
+ own frontend) or that `has a frontend`: under the variable the first is
+ kept (from birth, or at the Detach) and the second a pair (P36)."""
+ if WITH_PAIR:
+ return f'({kind}, kept)' if word == 'detached' else f'({kind})'
+ return f'({kind}, {word})'
+
+
def wait_for(what, check, timeout=10):
deadline = time.monotonic() + timeout
while True:
@@ -454,7 +479,7 @@ def clients(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rc-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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)
@@ -596,7 +621,7 @@ def launch(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rl-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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)
@@ -623,12 +648,12 @@ def launch(binary):
assert (root / 'pardes-9p-work.sock').exists(), list(root.iterdir())
pid = status_pid('work')
listed = cli('ps').stdout.decode()
- assert f'session work {pid} (tty, detached)' in listed, listed
+ assert f'session work {pid} {listed_as('detached')}' in listed, listed
assert alive(pid) and os.getsid(pid) == pid, (pid, os.getsid(pid))
out = cli('new', '--detach')
assert out.returncode == 0 and out.stdout.strip().isdigit(), out
unnamed = int(out.stdout)
- assert status_pid(str(unnamed)) == unnamed and f'session {unnamed} {unnamed} (tty, detached)' in cli('ps').stdout.decode()
+ assert status_pid(str(unnamed)) == unnamed and f'session {unnamed} {unnamed} {listed_as('detached')}' in cli('ps').stdout.decode()
taken = cli('new', '--detach=work')
assert taken.returncode == 1 and taken.stderr == b'pardes: a session named work is already running\n', taken
# The flag alone runs the session in this process, as a supervisor
@@ -664,7 +689,7 @@ def pair(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rp-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -738,7 +763,7 @@ def pair_rows(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -928,7 +953,7 @@ def attach_upgrading(binary, rounds=6, dump=True):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='ru-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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)
@@ -1019,7 +1044,7 @@ def kept_views(binary):
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 = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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)
@@ -1091,7 +1116,7 @@ def pair_upgrade_views(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rv-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -1197,7 +1222,7 @@ def pair_exec_reaps(old, new):
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))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -1261,7 +1286,7 @@ def far_exec(old, new):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rfx-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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)
@@ -1327,7 +1352,7 @@ def pair_window_geometry(gui_binary, new_gui):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rgg-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_DAEMON='on', TERM='xterm-256color', PARDES_PAIR='1',
SDL_VIDEO_DRIVER='offscreen')
@@ -1399,7 +1424,7 @@ def manage(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rm-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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)
@@ -1435,14 +1460,14 @@ def manage(binary):
listed = out.stdout.decode()
assert f'pardes daemon {daemon}' in listed, listed
for name in ('one', 'two'):
- assert f'session {name} {sessions[name]} (tty, detached)' in listed, listed
+ assert f'session {name} {sessions[name]} {listed_as('detached')}' in listed, listed
assert f'shell {shells[name]}' in listed, listed
# The same, a record a line, in each session's /sessions.
with Client(root / 'pardes-9p-one.sock') as c:
records = c.read('/sessions').decode().splitlines()
assert records[0] == f'daemon {daemon}', records
for name in ('one', 'two'):
- at = records.index(f'session {sessions[name]} tty detached {name}')
+ at = records.index(f'session {sessions[name]} tty {"kept" if WITH_PAIR else "detached"} {name}')
assert records[at + 1] == f'shell {shells[name]}', records
print('manage: /sessions read over 9P listed the daemon, both sessions and their shells')
os.kill(sessions['two'], signal.SIGKILL)
@@ -1503,7 +1528,7 @@ def relink(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rr-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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)
@@ -1545,7 +1570,7 @@ def relink(binary):
own_shell = terminals(own)[0]
own_shell_pid = int(run(own, own_shell, b'echo $$\n').split(b'\n')[1])
started.append(own_shell_pid)
- expected = [f'session work {session} (tty, detached)', f'session own {own_pid} (tty, has a frontend)',
+ 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}']
assert all(row in listed() for row in expected), listed()
daemon = daemons()[0]
@@ -1609,7 +1634,7 @@ def answer_late(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='ra-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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)
@@ -1727,7 +1752,7 @@ def pdf_window(binary, gui_binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='pdfw-', dir=os.environ.get('TMPDIR') or scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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')
env.pop('XDG_DATA_HOME', None)
@@ -1793,7 +1818,7 @@ def window_clients(binary, gui_binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='wc-', dir=os.environ.get('TMPDIR') or scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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)
@@ -1845,7 +1870,7 @@ def window_clients(binary, gui_binary):
if not rtt:
# Its clients are no sessions of the daemon's.
listed = sessions_listed(binary, env, root)
- assert [(n, k) for n, _, k in listed] == [('files', '(tty, detached)')], listed
+ assert [(n, k) for n, _, k in listed] == [('files', listed_as('detached'))], listed
# Moved and scrolled, its own view only: agreed again.
n = len(checks(check))
w.keys(b'jjjjjkkk\x06\x06\x02')
@@ -1951,15 +1976,19 @@ def window_clients(binary, gui_binary):
wait_for('the terminal client agrees with the window', lambda: agreed(root / 'b.check', nb), timeout=30)
wait_for('the window client agrees with the window', lambda: agreed(root / 'g.check', ng), timeout=30)
listed = sessions_listed(binary, env, root)
- assert [(n, k) for n, _, k in listed] == [('win', '(gui, has a frontend)')], listed
+ assert [(n, k) for n, _, k in listed] == [('win', listed_as('has a frontend', 'gui'))], listed
assert wg.close() == 0, wg.said()[-800:]
os.write(tb.master, b' sD')
wait_for('the terminal client let go', lambda: b.poll() is not None, timeout=10)
assert win.p.poll() is None
print(f'daemon: a window\'s session served a terminal\'s client and a window\'s, digests agreed '
- f'{len(checks(root / "b.check"))} and {len(checks(root / "g.check"))} times; --ps listed it alone, (gui, has a frontend)')
+ f'{len(checks(root / "b.check"))} and {len(checks(root / "g.check"))} times; --ps listed it alone, {listed_as("has a frontend", "gui")}')
win.close()
nine.socket.close()
+ # Under the variable the window is its session's client, and the
+ # terminal client's Detach kept that session (P36): ended by name.
+ if WITH_PAIR:
+ subprocess.run([binary, '--kill=win'], env=dict(env, PARDES_DAEMON='on'), cwd=root, capture_output=True, timeout=30)
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=15)
print('daemon: window clients\' sessions ended, nothing left behind')
finally:
@@ -2015,7 +2044,7 @@ def far(binary):
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rf-', dir=scratch))
cache = root / 'cache'
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
XDG_CACHE_HOME=str(cache), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash',
PARDES_NOTIME='1', PARDES_REPLICA_FAR='1')
@@ -2185,7 +2214,7 @@ def far_flood(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='fl-', dir=os.environ.get('TMPDIR') or scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
XDG_CACHE_HOME=str(root / 'cache'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash',
PARDES_NOTIME='1')
@@ -2284,7 +2313,7 @@ def by_hash(binary):
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rh-', dir=scratch))
cache = root / 'cache'
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
XDG_CACHE_HOME=str(cache), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -2370,7 +2399,7 @@ def games(binary, libs, secs=10):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rg-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -2481,7 +2510,7 @@ def far_find(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_REPLICA_FAR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -2541,14 +2570,16 @@ def far_find(binary):
def restore_client(binary):
- """A Restore while a client is attached: the client is let go (its link
- ends), the replacement core is the session's (its tape adopts it, its
- options keep none), and a client attached after agrees with it, its
- keys reaching it."""
+ """A Restore while a client is attached: the client is told and joins
+ the restored session again by itself (P44, as at an Upgrade), saying
+ nothing on its screen; its keys reach the replacement core (the
+ session's: its tape adopts it, its options keep none) and it agrees with
+ it, as does a client attached after. A 9P connection is the old core's:
+ cut, dialled again."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rr-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'),
TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -2573,23 +2604,36 @@ def restore_client(binary):
wait_for(f'client {name}\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30)
time.sleep(.3)
return t, c
- t, c = client('a')
+ ta, ca = client('a')
nine.write(f'/pane/{text}/exec', b'Dump\n')
nine.write(f'/pane/{text}/exec', b'Restore\n')
- wait_for('client a let go at the Restore', lambda: c.poll() is not None, timeout=30)
- # The 9P link was the old core's.
+
+ def cut():
+ try:
+ nine.read('/index')
+ return False
+ except (OSError, EOFError):
+ return True
+ wait_for('the 9P connection cut at the Restore', cut, timeout=30)
nine.socket.close()
nine = reconnect(root / 'pardes-9p-back.sock')
text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
- t, c = client('r')
- os.write(t.master, b'Oafter the restore\x1b')
texts = lambda: b''.join(nine.read(f'/pane/{row.split()[0].decode()}/body') for row in nine.read('/index').splitlines()
if row.split()[1] == b'text')
- wait_for('the client\'s keys in the restored session', lambda: b'after the restore' in texts(), timeout=30)
+ # Client a, joined again by itself: its keys in the restored core.
+ os.write(ta.master, b'Oa after the restore\x1b')
+ wait_for('client a\'s keys in the restored session', lambda: b'a after the restore' in texts(), timeout=30)
+ assert ca.poll() is None, 'client a ended at the Restore'
+ seen = len(checks(root / 'a.check'))
+ wait_for('client a agrees once quiet', lambda: agreed(root / 'a.check', seen), timeout=60)
+ assert b'joined again' not in ta.text(), ('a notice left on client a\'s screen', ta.text())
+ tr, cr = client('r')
+ os.write(tr.master, b'Or after the restore\x1b')
+ wait_for('client r\'s keys in the restored session', lambda: b'r after the restore' in texts(), timeout=30)
seen = len(checks(root / 'r.check'))
- wait_for('the client agrees once quiet', lambda: agreed(root / 'r.check', seen), timeout=60)
- assert c.poll() is None, 'the client ended'
- print(f'daemon: a Restore with a client attached: it was let go, and one attached after agreed ({len(checks(root / "r.check"))} checks), its keys in the restored session')
+ wait_for('client r agrees once quiet', lambda: agreed(root / 'r.check', seen), timeout=60)
+ assert ca.poll() is None and cr.poll() is None, 'a client ended'
+ print(f'daemon: a Restore with a client attached: it joined again by itself, saying nothing, its keys in the restored session and agreeing ({len(checks(root / "a.check"))} checks); the 9P connection cut; one attached after agreed ({len(checks(root / "r.check"))} checks)')
exit_session(nine, text)
sess.wait(timeout=60)
nine.socket.close()
@@ -2682,7 +2726,7 @@ def kitty_image(binary, secs=5):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='ri-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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)
@@ -2743,7 +2787,7 @@ def main(binary, cycles):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rt-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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)
@@ -2804,7 +2848,7 @@ def main(binary, cycles):
wait_for('the client\'s first frame', lambda: b'\x1b[?1049h' in term.text())
listed = wait_for('the client in --ps', lambda: (lambda out: f'client {c.pid} ' in out and out)(
subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()))
- assert f'session work {session} (tty, detached)' in listed, listed
+ assert f'session work {session} {listed_as("detached")}' in listed, listed
os.write(term.master, f'echo {typed}\r'.encode())
wait_for('its keys in the shell', lambda: typed.encode() in client.read(f'/pane/{shell}/body'))
return c
@@ -2934,7 +2978,9 @@ def main(binary, cycles):
wait_for('the client\'s first frame', lambda: b'\x1b[?1049h' in term.text())
listed = wait_for('the client in --ps', lambda: (lambda out: f'client {stub.pid} ' in out and out)(
subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()))
- assert f'session fresh {session} (tty, detached)' in listed, listed
+ # (Under the variable the killed stub was the pair's client: a loss,
+ # the session still a pair's, P36.)
+ assert f'session fresh {session} {"(tty)" if WITH_PAIR else listed_as("detached")}' in listed, listed
print('daemon: a session whose stub was killed outright detached, and was attached again, as a client')
# The end: the session quits, its shells hang up, its client and
@@ -2977,7 +3023,7 @@ def gui(binary, cycles):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rtg-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
(root / 'caps').mkdir()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root / 'caps'),
@@ -2997,6 +3043,9 @@ def gui(binary, cycles):
wait_for('the window session', sock.exists, timeout=20)
client = Client(sock)
shell = terminals(client)[0]
+ # The window's own process, or under the variable its child (a
+ # pair: the window a client of it).
+ session = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])
assert not sized(client), 'a window owns the size'
# With its window: another window is a client of the session (its
# own process, its captures its own), listed by --ps; closed, it
@@ -3005,22 +3054,23 @@ def gui(binary, cycles):
wait_for('the second window drawn', lambda: (root / 'second' / 'latest.ppm').exists(), timeout=20)
assert f'client {second.pid} ' in listed(), listed()
second.close()
- wait_for('the client gone from --ps', lambda: 'client ' not in listed())
+ # (a pair's own window is a client too: the second's pid is what goes)
+ wait_for('the client gone from --ps', lambda: f'client {second.pid} ' not in listed())
assert not sized(client), 'the first window stays'
- assert proc.poll() is None
+ assert alive(session)
print('daemon: a second window on a window session a client of it (in --ps), closed alone')
# Detached: the window closed, the process on; every attach after it
# a window client, the session detached still.
client.write(f'/pane/{shell}/exec', b'Detach\n')
wait_for('the window closed', lambda: sized(client))
- assert proc.poll() is None, 'the process carries on with no window'
- assert f'session win {proc.pid} (gui, detached)' in listed(), listed()
+ assert alive(session), 'the session carries on with no window'
+ assert f'session win {session} {listed_as("detached", "gui")}' in listed(), listed()
baseline = None
for cycle in range(cycles):
w = Window(root, f'w{cycle}', [binary, 'attach'] if cycle % 2 else [binary, '--attach=win'], env)
wait_for('the client window drawn', lambda: (root / f'w{cycle}' / 'latest.ppm').exists(), timeout=20)
wait_for('the client in --ps', lambda: f'client {w.pid} ' in listed())
- assert f'session win {proc.pid} (gui, detached)' in listed(), listed()
+ assert f'session win {session} {listed_as("detached", "gui")}' in listed(), listed()
now = (fds(proc.pid), len(processes(root)))
baseline = baseline or now
assert now == baseline, (cycle, now, baseline)
@@ -3037,14 +3087,14 @@ def gui(binary, cycles):
tty_attach.terminate()
tty_attach.wait(timeout=10)
term.close()
- assert proc.poll() is None
+ assert alive(session)
print('daemon: a terminal attached to a window session by name, as a client')
nobody = subprocess.run([binary, '--attach=nobody'], env=env, cwd=root, timeout=10,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
assert nobody.returncode == 1 and b"no session called 'nobody'" in nobody.stderr, nobody.stderr
# Detached and told to end: it ends.
client.write(f'/pane/{shell}/exec', b'Exit\n')
- proc.wait(timeout=10)
+ wait_for('the session ended', lambda: not alive(session))
client.socket.close()
wait_for('the daemon gone once idle', lambda: not [p for p in processes(root) if alive(p)], timeout=5)
print('daemon: window session ended, nothing left behind')
@@ -3072,7 +3122,7 @@ def gui_pair(gui_binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rgp-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_DAEMON='on', TERM='xterm-256color', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -3100,7 +3150,7 @@ def gui_pair(gui_binary):
try:
w, nine, session, pane = started('gp', env)
- wait_for('the window listed its client', lambda: f'session gp {session} (tty)' in listed()
+ wait_for('the window listed its client', lambda: f'session gp {session} (gui)' in listed()
and f'client {w.pid} ' in listed())
w.keys(b'Ofrom-the-window\x1b')
wait_for('its keys in the session\'s text', lambda: b'from-the-window' in nine.read(f'/pane/{pane}/body'))
@@ -3118,7 +3168,7 @@ def gui_pair(gui_binary):
os.kill(w.pid, signal.SIGKILL)
w.p.wait(timeout=10)
wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed())
- assert alive(session) and f'session gl {session} (tty)' in listed(), listed()
+ assert alive(session) and f'session gl {session} (gui)' in listed(), listed()
nine.socket.close()
assert subprocess.run([binary, 'kill', 'gl'], env=env, capture_output=True, timeout=30).returncode == 0
wait_for('the session ended', lambda: not alive(session), timeout=30)
@@ -3243,7 +3293,7 @@ def upgrades(old, new):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rtu-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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)
@@ -3344,6 +3394,10 @@ def upgrades(old, new):
# (A client of a build that execs at an Upgrade comes back: its
# connection is the session's again.)
gone = 2 if b'detached from' in term2.text() else 0 if knows_exec(old) and stub2.poll() is None else 1
+ # (Under the variable a pair's session of a build that keeps its
+ # client's terminal, P48, lets it go: close-on-exec, not carried;
+ # such a build's put-back turns the in-band resize off.)
+ gone += 1 if WITH_PAIR and b'\x1b[?2048l\x1b[0m' in Path(old).read_bytes() else 0
return fds_before[0] - 2 - gone + min(state_fds(session), 1) - state_before, fds_before[1]
try:
wait_for('the fds level', lambda: (fds(session), fds(daemon)) == level(), timeout=5)
@@ -3553,7 +3607,7 @@ def upgrade_clients(old, new):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='ruc-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ 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)
@@ -3655,7 +3709,7 @@ def gui_upgrades(old, new):
another build."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
root = Path(tempfile.mkdtemp(prefix='rtgu-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
display = Path(os.environ.get('WAYLAND_DISPLAY', 'wayland-0'))
if not display.is_absolute():
display = Path(os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}')) / display
@@ -3746,6 +3800,9 @@ def gui_upgrades(old, new):
if __name__ == '__main__':
+ WITH_PAIR = sys.argv[1:2] == ['--with-pair']
+ if WITH_PAIR:
+ del sys.argv[1]
# A session's state file is its HOME's, never the user's: the dumps a
# test makes there would push the user's out.
os.environ.pop('XDG_DATA_HOME', None)
diff --git a/test/panes.zig b/test/panes.zig
index 0a0bd3f9..88209693 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -4316,6 +4316,61 @@ const PdfAddon = struct {
try std.testing.expect(a.core.panes[c.id] == null and win.core().panes[c.id] == null);
try std.testing.expect(win.diverged == null);
}
+
+ test "Addon load <path> typed in a session lands on its client too, which runs the kind from that path while its bytes are the session's and shows its line once they are not" {
+ const R = pardes.replica;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable });
+ defer a.deinit();
+ const r = try R.Replica.init(gpa, 1, try a.unit(0, 0));
+ defer r.deinit();
+ const Land = struct {
+ a: *R.Authority,
+ r: *R.Replica,
+ fn step(l: @This(), ev: pardes.Event) !void {
+ l.r.confirm(try l.a.local(ev));
+ }
+ };
+ const land: Land = .{ .a = a, .r = r };
+ // The image addon at a path of its own, in no addons directory.
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const lib = try std.Io.Dir.cwd().readFileAlloc(io, addons.image, gpa, .limited(256 << 20));
+ defer gpa.free(lib);
+ try tmp.dir.writeFile(io, .{ .sub_path = "libpic.so", .data = lib });
+ try tmp.dir.writeFile(io, .{ .sub_path = "dot.ppm", .data = "P6\n1 1\n255\n\x01\x02\x03" });
+ var buf: [4096]u8 = undefined;
+ const dir = buf[0..try tmp.dir.realPath(io, &buf)];
+ var line: [4200]u8 = undefined;
+ try land.step(.{ .command = try std.fmt.bufPrint(&line, "Addon load {s}/libpic.so", .{dir}) });
+ try std.testing.expect(r.diverged == null);
+ try std.testing.expect(a.core.kinds.byName("image") != null and r.core().kinds.byName("image") != null);
+ // A picture: the client runs the kind from the session's path.
+ try land.step(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/dot.ppm", .{dir}) });
+ try jobs(a.core, land);
+ const id = for (a.core.panes, 0..) |slot, i| {
+ if (slot) |pane| if (pane.addon != null) break i;
+ } else return error.NoPicture;
+ try std.testing.expect(r.core().panes[id].?.addon.?.ops != null);
+ r.settle();
+ try std.testing.expect(r.diverged == null);
+ // The file written over since (one byte more): a client joining
+ // now finds other bytes there and shows the kind's line.
+ const longer = try std.mem.concat(gpa, u8, &.{ lib, "\x00" });
+ defer gpa.free(longer);
+ try tmp.dir.writeFile(io, .{ .sub_path = "libpic.so", .data = longer });
+ const was = pardes.tape.on;
+ pardes.tape.on = &a.t;
+ const bytes = try pardes.dump.byteDump(a.core);
+ pardes.tape.resync(&a.t);
+ pardes.tape.on = was;
+ defer a.core.gpa.free(bytes);
+ const late = try R.Replica.initDump(gpa, 2, 0, bytes, .{ .cols = 80, .rows = 24 });
+ defer late.deinit();
+ try std.testing.expect(late.loaded(pardes.tape.digestOf(a.core)));
+ try std.testing.expect(late.core().panes[id].?.addon.?.ops == null);
+ }
};
test {
diff --git a/test/process/flags.zig b/test/process/flags.zig
index cfdb1faf..3c54a7ad 100644
--- a/test/process/flags.zig
+++ b/test/process/flags.zig
@@ -746,7 +746,7 @@ fn killedTty(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
const seen = try d.get(a, std.fs.path.basename(log));
const tail = seen[std.mem.lastIndexOf(u8, seen, "\x1b[?1049h").?..];
try check(has(tail, "\x1b[?1049l"), "the main screen not put back", .{});
- try check(try process.canonical(killed.slave), "the terminal left raw", .{});
+ try check(try process.canonical(killed.slave), "{t}: the terminal left raw", .{sig});
daemonGone(&d);
}
}