summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--core/replica.zig12
-rw-r--r--dev/gui/gui.zig295
-rw-r--r--dev/tui/tui.zig74
-rw-r--r--docs/loose-ends.md92
-rw-r--r--test/daemon.py394
-rw-r--r--test/panes.zig84
6 files changed, 803 insertions, 148 deletions
diff --git a/core/replica.zig b/core/replica.zig
index 48cb1838..2a66cc3d 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -1911,6 +1911,18 @@ pub const Peers = struct {
return n;
}
+ /// The time the session's pump reads after its wait, when that wait
+ /// took a client's post and nothing else (`only_mail`, the shell's word
+ /// for its wait): the core's clock as it stands, so the pump's unit
+ /// moves nothing a client's speculation stands on; null otherwise (the
+ /// shell's clock). Held only while a post waits (`mail`): a wait that
+ /// ran out took none, and the pump after it is the one its deadline
+ /// asked for (a window's wait that ran out was held, 2026-11-24: a
+ /// deadline never met, the session stepped a millisecond for ever).
+ pub fn heldNow(ps: *const Peers, core: *const Pardes, only_mail: bool) ?u64 {
+ return if (only_mail and ps.recording and ps.mail.load(.acquire) and core.clock.started) core.clock.now_ns else null;
+ }
+
pub fn post(ps: *Peers, note: Note) void {
ps.lock.lockUncancelable(ps.io);
if (note == .join and ps.upgrading.load(.monotonic)) {
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index 0f1fe0e6..bc831a69 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -192,27 +192,27 @@ const PreparedImage = struct {
texture: *c.SDL_GPUTexture,
};
-fn updateCoreResize(core: *pardes.Pardes, cols: u16, rows: u16, cell_w: u32, cell_h: u32, tag_w: u32, tag_h: u32) bool {
- core.update(resizeOf(core.view(), cols, rows, cell_w, cell_h, tag_w, tag_h) orelse return false);
- return true;
+/// The window's size as its view takes it (Event.resize): its whole
+/// cells, their pixels, its rows' metrics. Posted to its own view when it
+/// changes, compared with what the window last posted or that view is,
+/// never with a frame or the live view.
+const Size = @FieldType(pardes.Event, "resize");
+
+fn windowSize(g: *const Gui) Size {
+ var pw: c_int = 0;
+ var ph: c_int = 0;
+ _ = c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph);
+ return .{
+ .cols = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(pw, 1))), g.cell_w))),
+ .rows = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(ph, 1))), g.cell_h))),
+ .cell_pixels = .{ .w = @intCast(@min(@max(1, g.cell_w), std.math.maxInt(u16))), .h = @intCast(@min(@max(1, g.cell_h), std.math.maxInt(u16))) },
+ .row_metrics = .{ .body_w = @intCast(g.cell_w), .body_h = @intCast(g.cell_h), .tagline_w = @intCast(g.tagline_width), .tagline_h = @intCast(g.tagline_height) },
+ };
}
-/// The resize a window of `cols` by `rows` cells of these sizes is to the
-/// live view (a View, or the Facts a frame carries of it), or null when it
-/// is that already.
-fn resizeOf(v: anytype, cols: u16, rows: u16, cell_w: u32, cell_h: u32, tag_w: u32, tag_h: u32) ?pardes.Event {
- const metrics: pardes.RowMetrics = .{ .body_w = @intCast(cell_w), .body_h = @intCast(cell_h), .tagline_w = @intCast(tag_w), .tagline_h = @intCast(tag_h) };
- const same_metrics = std.meta.eql(metrics, v.row_metrics);
- const cell_px_w: u16 = @intCast(@min(@max(1, cell_w), std.math.maxInt(u16)));
- const cell_px_h: u16 = @intCast(@min(@max(1, cell_h), std.math.maxInt(u16)));
- if (cols == v.screen_w and rows == v.screen_h and
- cell_px_w == v.cell_pixels.w and cell_px_h == v.cell_pixels.h and same_metrics) return null;
- return .{ .resize = .{
- .cols = cols,
- .rows = rows,
- .cell_pixels = .{ .w = cell_px_w, .h = cell_px_h },
- .row_metrics = metrics,
- } };
+/// Whether view `v` is `size` already.
+fn sizedTo(v: *const pardes.Pardes.View, size: Size) bool {
+ return v.screen_w == size.cols and v.screen_h == size.rows and std.meta.eql(v.cell_pixels, size.cell_pixels) and std.meta.eql(v.row_metrics, size.row_metrics.?);
}
const TouchPoint = struct {
@@ -372,6 +372,22 @@ fn emitTouchClick(g: *const Gui, in: *Input, point: TouchNormPoint, button: pard
const Queue = host_io.Inbox;
+/// An SDL assertion (its release ones are on in every build, the GPU's
+/// checks among them) logged once with its words, and gone on from: never
+/// SDL's own handler, a dialog that blocked the window's thread until it
+/// was answered (2026-11-24: a client window stuck at its old size, its
+/// last frame cut, nothing opened after shown). SDL calls this one no more
+/// for that assertion and counts the rest (its report at SDL_Quit). Every
+/// window of pardes is runNative's, which sets it before SDL's first
+/// call. A test build fails at one.
+fn sdlAssertion(data: [*c]const c.SDL_AssertData, _: ?*anyopaque) callconv(.c) c.SDL_AssertState {
+ const d = data.*;
+ const words = .{ d.condition, d.filename, d.linenum, d.function };
+ if (builtin.is_test) std.debug.panic("SDL assertion: {s} at {s}:{d} ({s})", words);
+ log.err("SDL assertion: {s} at {s}:{d} ({s}); ignored, from now on", words);
+ return c.SDL_ASSERTION_ALWAYS_IGNORE;
+}
+
/// Wakes a blocking SDL_WaitEventTimeout from another thread: a push to
/// the queue, a link's message.
fn sdlWake(_: ?*anyopaque) void {
@@ -580,7 +596,7 @@ fn syncReplicaFont(g: *Gui, f: *const @FieldType(pardes.config.Settings, "font")
if (f.requested_size_hundredths != 0)
g.px = @as(f32, @floatFromInt(f.requested_size_hundredths)) / 100;
setGuiFontName(g, face.name);
- refitFont(g, null);
+ refitFont(g);
return true;
}
@@ -624,18 +640,6 @@ fn windowGeometry(window: *c.SDL_Window) WindowGeometry {
};
}
-const GridCells = struct { cols: u16, rows: u16 };
-
-fn windowCells(g: *const Gui) GridCells {
- var pw: c_int = 0;
- var ph: c_int = 0;
- _ = c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph);
- return .{
- .cols = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(pw, 1))), g.cell_w))),
- .rows = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(ph, 1))), g.cell_h))),
- };
-}
-
const Point = struct { x: f32, y: f32 };
fn windowPointToPixels(geometry: WindowGeometry, x: f32, y: f32) Point {
@@ -774,6 +778,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, detached: bool, di
log.err("SDL_SetMemoryFunctions: {s}", .{c.SDL_GetError()});
return error.SdlInit;
}
+ c.SDL_SetAssertionHandler(sdlAssertion, null);
_ = c.SDL_SetHint("SDL_JOYSTICK_HIDAPI", "1"); // SDL_HINT_JOYSTICK_HIDAPI
_ = c.SDL_SetHint("SDL_JOYSTICK_HIDAPI_STEAMDECK", "1"); // ..._STEAMDECK
if (comptime builtin.os.tag == .macos) _ = c.SDL_SetHint(c.SDL_HINT_MAC_SCROLL_MOMENTUM, "1");
@@ -1019,7 +1024,7 @@ const Own = struct {
core.view().frontend.native_images = true;
core.view().frontend.native_image_patches = true;
observeGuiFont(g, core);
- syncTaglineFont(g, core);
+ _ = fitTaglineFont(g, core.settings.font.tagline_percent);
l.inbox.wake_fn = sdlWake;
o.shell = .{
.core = core,
@@ -1093,7 +1098,7 @@ const Own = struct {
o.shell.core = l.core;
o.shell.surface = null;
observeGuiFont(o.g, l.core);
- syncTaglineFont(o.g, l.core);
+ _ = fitTaglineFont(o.g, l.core.settings.font.tagline_percent);
}
};
@@ -1118,10 +1123,11 @@ const Client = struct {
inbox: std.ArrayListUnmanaged(replica.Said) = .empty,
taken: std.ArrayListUnmanaged(replica.Said) = .empty,
link_ended: bool = false,
- /// The size the window last posted while its view is not that size
- /// yet (the session has not taken it, or speculation stopped at it):
- /// posted once, not again each pass while it waits.
- posted: ?@FieldType(pardes.Event, "resize") = null,
+ /// The size the window last posted (windowSize): posted again only
+ /// when the window's own size changes. Never by what a frame shows: a
+ /// frame is its view as the session had it then, and a rollback's drew
+ /// an older size (each was posted again, 2026-11-24).
+ posted: ?Size = null,
/// The window, the shell its frames are drawn through, the input it
/// routes (its core this join's), and the client's joins.
g: *Gui = undefined,
@@ -1159,9 +1165,11 @@ const Client = struct {
cl.pending.append(cl.gpa, e) catch {};
}
- /// What the window's input made, applied at once and sent; what the
- /// window reads beside its frame (Gui.facts) as its view is now.
+ /// What the window's input made, its last motion with it (Input.moved),
+ /// applied at once and sent; what the window reads beside its frame
+ /// (Gui.facts) as its view is now.
fn feed(cl: *Client, l: *ClientLoop) void {
+ cl.in.flush();
const r = l.link.r;
for (cl.pending.items) |ev| {
const predicted = r.echo.stats.predicted;
@@ -1225,11 +1233,11 @@ const Client = struct {
}
if (scrollRows(g, &cl.in, gpa)) link.dirty = true;
if (fitTaglineFont(g, g.facts.tagline_percent)) link.dirty = true;
- const geom = windowCells(g);
- if (resizeOf(&g.facts, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) |ev| {
- if (cl.posted == null or !std.meta.eql(cl.posted.?, ev.resize)) cl.in.post(ev);
- cl.posted = ev.resize;
- } else cl.posted = null;
+ const size = windowSize(g);
+ if (cl.posted == null or !std.meta.eql(cl.posted.?, size)) {
+ cl.in.post(.{ .resize = size });
+ cl.posted = size;
+ }
if (cl.drew) refreshPresentedPointer(g, &cl.in);
cl.drew = false;
runDemo(g, &cl.in, cl.in.core);
@@ -1287,8 +1295,9 @@ const Client = struct {
return ms;
}
- /// SDL's wait: each event dispatched and fed; then what the reader
- /// took, the window's own pictures' draws done.
+ /// SDL's wait: each event dispatched and fed (a run of motions one
+ /// input, Input.moved); then what the reader took, the window's own
+ /// pictures' draws done.
pub fn wait(cl: *Client, l: *ClientLoop, ms: u32) void {
const g = cl.g;
const link = &l.link;
@@ -1301,11 +1310,14 @@ const Client = struct {
while (got) : (got = c.SDL_PollEvent(&sev)) {
if (sev.type == c.SDL_EVENT_USER) continue;
dispatch(g, &cl.in, &sev);
- cl.feed(l);
+ // Fed as it comes, the next event's hits read in the frame it
+ // predicts; a motion goes with the next input, or the pass's.
+ if (cl.in.moved == null) cl.feed(l);
if (cl.in.redraw) link.dirty = true;
cl.in.redraw = false;
if (link.quit) break;
}
+ cl.feed(l);
cl.takeSaid(l);
// Its draws done (api.draw: this window's own pictures).
if (cl.shell.takeDraws()) link.dirty = true;
@@ -1530,6 +1542,9 @@ const StdinFeed = struct {
// window pixels, built as SDL would and run through dispatch,
// so a driver exercises the real pointer path (pixel to cell,
// tag and body hits). SGR mouse carries only cells.
+ // mouse;pointer;<SDL button, 0 for none>;<x>;<y>: a motion as
+ // `motion` builds it, pushed onto SDL's queue as a mouse's
+ // comes, for the window's wait to take with the rest.
// finger;<kind>;<id>;<x>;<y>;<pressure>
// close: the window's close button
// One the read cut short, or what may yet begin one, waits for
@@ -1558,7 +1573,7 @@ const StdinFeed = struct {
// counts them: shift 4, meta (alt) 8, ctrl 16.
const held = std.fmt.parseInt(u8, parts.next() orelse "0", 10) catch 0;
var sev = std.mem.zeroes(c.SDL_Event);
- const k = std.meta.stringToEnum(enum { wheel, focus, motion, down, up }, kind) orelse .up;
+ const k = std.meta.stringToEnum(enum { wheel, focus, motion, pointer, down, up }, kind) orelse .up;
switch (k) {
.wheel => {
// ESC]777;mouse;wheel;<y, SDL's sign: up positive>;<x>;<y>BEL:
@@ -1572,7 +1587,7 @@ const StdinFeed = struct {
},
// ESC]777;mouse;focus;<1 gained, 0 lost>;0;0BEL
.focus => sev.type = if (button != 0) c.SDL_EVENT_WINDOW_FOCUS_GAINED else c.SDL_EVENT_WINDOW_FOCUS_LOST,
- .motion => {
+ .motion, .pointer => {
sev.type = c.SDL_EVENT_MOUSE_MOTION;
sev.motion.x = x;
sev.motion.y = y;
@@ -1586,6 +1601,11 @@ const StdinFeed = struct {
sev.button.y = y;
},
}
+ if (k == .pointer) {
+ sev.motion.windowID = c.SDL_GetWindowID(gp.window);
+ _ = c.SDL_PushEvent(&sev);
+ continue;
+ }
const before = c.SDL_GetModState();
var mods: c.SDL_Keymod = 0;
if (held & 4 != 0) mods |= c.SDL_KMOD_LSHIFT;
@@ -1756,8 +1776,27 @@ const Input = struct {
/// Something the window draws of its own changed (a display's scale, a
/// touchpad's fraction): the runner draws again.
redraw: bool = false,
+ /// The pointer's last motion `dispatch` took, not posted yet: a run of
+ /// motions is one input, its last, posted before whatever input comes
+ /// next or at the pass's end (`flush`). The core reads only a motion's
+ /// cell and held button; posted each, every one was a step of the
+ /// session, and with clients a unit to each and a frame of each (1652
+ /// motions in 0.35 s were 1655 frames of the session, 2026-11-24).
+ moved: ?pardes.Mouse = null,
fn post(in: *Input, ev: pardes.Event) void {
+ in.flush();
+ in.send(ev);
+ }
+
+ /// The pass's last motion (`moved`) posted.
+ fn flush(in: *Input) void {
+ const m = in.moved orelse return;
+ in.moved = null;
+ in.send(.{ .mouse = m });
+ }
+
+ fn send(in: *Input, ev: pardes.Event) void {
// A replica client's: fed after the event (Client.feed).
if (in.client) |cl| return cl.post(ev);
const g = if (in.shell) |s| s.gui else null;
@@ -1908,7 +1947,7 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void {
else
physical_held;
const mc = pointAt(g, m.x, m.y);
- in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, pointerMods()) });
+ in.moved = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, pointerMods());
},
c.SDL_EVENT_MOUSE_WHEEL => {
const w = sev.wheel;
@@ -2210,13 +2249,8 @@ const WheelTurn = struct { x: f32 = 0, y: f32 = 0, integer_y: i32 = 0, precise:
fn setFontPx(g: *Gui, in: *Input, want: f32) void {
if (want == g.px) return;
g.px = want;
- if (in.client) |r| {
- refitFont(g, null);
- r.loop.link.dirty = true;
- } else {
- refitFont(g, in.core);
- observeGuiFont(g, in.core);
- }
+ refitFont(g);
+ if (in.client) |r| r.loop.link.dirty = true else observeGuiFont(g, in.core);
}
/// A Mac trackpad's gesture, decoded by macos_trackpad.m (Trackpad.zig's
@@ -2422,14 +2456,14 @@ const Shell = struct {
/// of their own with no window here; the session loop's
/// (runtime/session.zig), a client's none.
peers: *replica.Peers,
- /// This wait took only a replica's post (its input, its join): the pump
- /// after it reads no new time, so it moves nothing the replicas'
- /// speculations stand on (tui.zig's `mail_only`).
+ /// This wait took nothing but a replica's post, if one (its input, its
+ /// join): the pump after one reads no new time (Peers.heldNow).
mail_only: bool = false,
waited: bool = false,
/// With replica clients, a wait takes one person's input (tui.zig
- /// `split`): the next is held for the next wait.
- took_input: bool = false,
+ /// `split`), the type of its first event here: the next is held for
+ /// the next wait.
+ took: ?u32 = null,
held: ?c.SDL_Event = null,
fn host(s: *Shell) pardes.Host {
@@ -2462,6 +2496,17 @@ const Shell = struct {
return true;
}
+ /// The window's events from `sev` on, SDL's queue after it, made inputs
+ /// (`dispatch`: a run of motions one, Input.moved) until the queue is
+ /// empty or one is held for the next wait (`split`).
+ fn takeEvents(s: *Shell, g: *Gui, in: *Input, sev: *c.SDL_Event) void {
+ while (!s.split(sev)) {
+ _ = s.windowView();
+ dispatch(g, in, sev);
+ if (!c.SDL_PollEvent(sev)) break;
+ }
+ }
+
/// With replica clients, a wait takes one person's input and its pump
/// makes one unit of it (tui.zig `split`): whether `sev`, a second, is
/// held for the next wait. Any event but a wake is no replica's post.
@@ -2473,11 +2518,13 @@ const Shell = struct {
c.SDL_EVENT_KEY_DOWN, c.SDL_EVENT_TEXT_INPUT, c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_BUTTON_UP, c.SDL_EVENT_MOUSE_MOTION, c.SDL_EVENT_MOUSE_WHEEL, c.SDL_EVENT_WINDOW_FOCUS_GAINED, c.SDL_EVENT_WINDOW_FOCUS_LOST, c.SDL_EVENT_WINDOW_MOUSE_LEAVE, c.SDL_EVENT_FINGER_DOWN, c.SDL_EVENT_FINGER_MOTION, c.SDL_EVENT_FINGER_UP => {},
else => return false,
};
- if (s.took_input) {
+ if (s.took) |took| {
+ // A run of motions is one input, its last (Input.moved).
+ if (took == c.SDL_EVENT_MOUSE_MOTION and sev.type == took) return false;
s.held = sev.*;
return true;
}
- s.took_input = true;
+ s.took = sev.type;
return false;
}
@@ -2649,7 +2696,7 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void {
const core = s.core;
var in: Input = .{ .core = core, .shell = s };
s.mail_only = true;
- s.took_input = false;
+ s.took = null;
defer s.waited = true;
if (s.gui) |g| {
if (s.surface != null) startGamepads(g);
@@ -2730,35 +2777,9 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void {
virtual.* = @max(virtual.*, core.nextWake() orelse virtual.*);
}
}
- if (got) {
- // A run of queued motions is one move to its last position (the
- // handler reads only absolute x/y and held buttons): acting on
- // each would repeat hover and selection work the next undoes.
- var motion: ?c.SDL_Event = null;
- while (true) {
- if (s.split(&sev)) break;
- if (sev.type == c.SDL_EVENT_MOUSE_MOTION and (motion == null or motion.?.motion.windowID == sev.motion.windowID)) {
- motion = sev;
- } else {
- if (motion) |*m| {
- _ = s.windowView();
- dispatch(g, &in, m);
- }
- motion = null;
- if (sev.type == c.SDL_EVENT_MOUSE_MOTION) {
- motion = sev;
- } else {
- _ = s.windowView();
- dispatch(g, &in, &sev);
- }
- }
- if (!c.SDL_PollEvent(&sev)) break;
- }
- if (motion) |*m| {
- _ = s.windowView();
- dispatch(g, &in, m);
- }
- }
+ // A run of queued motions is one move to its last position
+ // (Input.moved), whoever's input it is.
+ if (got) s.takeEvents(g, &in, &sev);
runDemo(g, &in, core);
// Paced: what came before the tick is in; wait out the rest of it,
// unless an input came: its frame is drawn at once (the paced loop
@@ -2780,17 +2801,7 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void {
pardes.turn.rest();
const more = c.SDL_PollEvent(&sev);
pardes.turn.wake();
- if (more) {
- if (!s.split(&sev)) {
- _ = s.windowView();
- dispatch(g, &in, &sev);
- while (c.SDL_PollEvent(&sev)) {
- if (s.split(&sev)) break;
- _ = s.windowView();
- dispatch(g, &in, &sev);
- }
- }
- } else {
+ if (more) s.takeEvents(g, &in, &sev) else {
// The events asked for every 100 µs, the core busy between.
const until = c.SDL_GetTicksNS() + 100 * std.time.ns_per_us;
while (c.SDL_GetTicksNS() < @min(until, tick)) std.atomic.spinLoopHint();
@@ -2807,6 +2818,8 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void {
return;
}
}
+ // The pass's last motion, before what the ptys said (`split`).
+ in.flush();
s.drainQueue();
if (s.gui) |g| pollGamepad(g, &in);
if (in.redraw) core.needs_frame = true;
@@ -2845,17 +2858,15 @@ fn pollFrame(ctx: ?*anyopaque) void {
return;
};
// A replica client's view live: the window's own view back before what
- // the window does to it (its size, its scroll, its font).
+ // the window does to it (its scroll, its font).
if (core.live != s.gview) {
- const geom = windowCells(g);
const due = g.scroll_pane != null or g.scroll_notch != 0 or g.glide.moving() or
- core.settings.font.tagline_percent != g.tagline_percent or core.settings.font.pending or
- (if (core.views[s.gview]) |*own| resizeOf(own, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height) != null else false);
+ core.settings.font.tagline_percent != g.tagline_percent or core.settings.font.pending;
if (due) _ = s.windowView();
}
syncWindowOpacity(g, core);
frame_probe.?.period_ns = refreshNs(g);
- syncTaglineFont(g, core);
+ _ = fitTaglineFont(g, core.settings.font.tagline_percent);
if (core.takeFontRequest()) |path| blk: {
const bytes = filesystem.readFile(&pardes.tape.none, s.gpa, path) catch {
core.rejectFont();
@@ -2869,11 +2880,22 @@ fn pollFrame(ctx: ?*anyopaque) void {
if (core.settings.font.requested_size_hundredths != 0)
g.px = @as(f32, @floatFromInt(core.settings.font.requested_size_hundredths)) / 100;
setGuiFontName(g, core.settings.font.requested_name.get());
- refitFont(g, core);
+ refitFont(g);
acknowledgeGuiFont(g, core);
}
- const geom = windowCells(g);
- if (updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) resetScroll(g);
+ // The window's size is its own view's, compared with that view and
+ // posted to it as the window's input (Input.post makes it live): never
+ // compared with the live view, which a client's input leaves live
+ // (2026-11-24: sized to this window, that client posted its own size
+ // again and this window its own, a unit and a rollback each way, on
+ // and on after a drag ended, the client drawing its view at this
+ // window's size, cut). A font's new cells come here too.
+ const size = windowSize(g);
+ if (core.views[s.gview]) |*own| if (!sizedTo(own, size)) {
+ var in: Input = .{ .core = core, .shell = s };
+ in.post(.{ .resize = size });
+ resetScroll(g);
+ };
stepScroll(g, core, s.gpa);
if (s.test_mode) writeTestStatus(g, core, s.presented, core.needs_frame);
// A blink edge, or the window's own motion (its glide, its caret, a
@@ -3143,7 +3165,7 @@ fn guiNow(ctx: ?*anyopaque) u64 {
const s = shellOf(ctx);
if (s.waited) {
s.waited = false;
- if (s.mail_only and s.peers.count() > 0 and s.core.clock.started) return s.core.clock.now_ns;
+ if (s.peers.heldNow(s.core, s.mail_only)) |held| return held;
}
return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS();
}
@@ -3728,17 +3750,17 @@ fn holdContext(g: *Gui, surface: *const pardes.Surface, id: usize, held: u16, bh
return .{ .rows = rows, .lift = @as(f32, @floatFromInt(rows)) * (row_px - layout.h) };
}
-fn scrollScissor(g: *const Gui, layout: CellLayout, sw: u32, sh: u32) c.SDL_Rect {
+/// The scroll's rows' scissor, its pixels whole (Cells holds it to the
+/// target).
+fn scrollScissor(g: *const Gui, layout: CellLayout) c.SDL_Rect {
const r = g.scroll_rect;
const px = layout.x_off + @as(f32, @floatFromInt(r.x + config.GUTTER)) * layout.w;
const py = layout.y_off + @as(f32, @floatFromInt(g.scroll_body_y)) * layout.h + g.scroll_held_px;
const pw = @as(f32, @floatFromInt(r.w - config.GUTTER)) * layout.w;
const ph = @max(0, @as(f32, @floatFromInt(g.scroll_body_h)) * layout.h - g.scroll_held_px);
- const x0 = std.math.clamp(@as(i32, @intFromFloat(@floor(px))), 0, @as(i32, @intCast(sw)));
- const y0 = std.math.clamp(@as(i32, @intFromFloat(@floor(py))), 0, @as(i32, @intCast(sh)));
- const x1 = std.math.clamp(@as(i32, @intFromFloat(@ceil(px + pw))), x0, @as(i32, @intCast(sw)));
- const y1 = std.math.clamp(@as(i32, @intFromFloat(@ceil(py + ph))), y0, @as(i32, @intCast(sh)));
- return .{ .x = x0, .y = y0, .w = x1 - x0, .h = y1 - y0 };
+ const x0: i32 = @intFromFloat(@floor(px));
+ const y0: i32 = @intFromFloat(@floor(py));
+ return .{ .x = x0, .y = y0, .w = @as(i32, @intFromFloat(@ceil(px + pw))) - x0, .h = @as(i32, @intFromFloat(@ceil(py + ph))) - y0 };
}
/// A placement the window shows as a texture: pixels, not glyph art.
@@ -3880,6 +3902,8 @@ fn prepareNativeImages(
return true;
}
+/// A picture's scissor, its placement's cells (Cells holds it to the
+/// target: a frame may be larger than the window it is drawn into).
fn imageScissor(g: *const Gui, place: pardes.Placement) c.SDL_Rect {
return .{
.x = @intCast(@as(u32, place.dst.x) * g.cell_w),
@@ -4085,7 +4109,7 @@ fn renderFrame(
building = false;
if (frame_probe) |probe| probe.zone(.gui_build, probe_build);
// Drawn only over a scroll's shifted rows (scrollScissor asks a scroll).
- const scroll_clip = if (shifted != 0) scrollScissor(g, layout, sw, sh) else std.mem.zeroes(c.SDL_Rect);
+ const scroll_clip = if (shifted != 0) scrollScissor(g, layout) else std.mem.zeroes(c.SDL_Rect);
g.cells.record(cmd, target, sw, sh, clear, background_opacity, groups.items[0..groups.len], groups.ink, cell_total, shifted, scroll_clip, overlay_count);
command_consumed = true;
@@ -4514,7 +4538,7 @@ fn firstCp(s: []const u8) u32 {
return std.unicode.utf8Decode(s[0..n]) catch ' ';
}
-fn refitFont(g: *Gui, core: ?*pardes.Pardes) void {
+fn refitFont(g: *Gui) void {
var cw: c_int = 10;
var chh: c_int = 20;
var asc: c_int = 16;
@@ -4529,12 +4553,6 @@ fn refitFont(g: *Gui, core: ?*pardes.Pardes) void {
g.tagline_height = tagline.height;
resetGlyphAtlas(g);
-
- if (core) |p| {
- const geom = windowCells(g);
- _ = updateCoreResize(p, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height);
- }
-
resetScroll(g);
}
@@ -4544,12 +4562,6 @@ fn resetGlyphAtlas(g: *Gui) void {
g.words.clear();
}
-fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void {
- if (!fitTaglineFont(g, core.settings.font.tagline_percent)) return;
- const geom = windowCells(g);
- _ = updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height);
-}
-
/// The tagline's face at `percent` of the body's: whether it changed.
fn fitTaglineFont(g: *Gui, percent: u8) bool {
if (percent == g.tagline_percent) return false;
@@ -7021,6 +7033,13 @@ test "a held key moves the view at the stream's own rate, never a bounce a line,
for (70..90) |k| try std.testing.expectEqual(held.carets[70], held.carets[k]);
}
+test "a picture's scissor is its placement's cells, cut at its pane's edges" {
+ const g = testGui(10, 20, 6, 12);
+ var place: pardes.Placement = undefined;
+ place.dst = .{ .x = 2, .y = 3, .w = 4, .h = 5 };
+ try std.testing.expectEqual(c.SDL_Rect{ .x = 20, .y = 60, .w = 40, .h = 100 }, imageScissor(&g, place));
+}
+
test "a scroll's shifted rows start under the context rows, and its scissor below their band" {
var surface: pardes.Surface = .{};
var g = testGui(10, 20, 6, 12);
@@ -7032,7 +7051,7 @@ test "a scroll's shifted rows start under the context rows, and its scissor belo
const grid = holdContext(&g, &surface, 0, 3, 19, layout);
try std.testing.expectEqual(@as(u16, 3), grid.rows);
try std.testing.expectEqual(@as(f32, 0), grid.lift);
- const clip = scrollScissor(&g, layout, 400, 400);
+ const clip = scrollScissor(&g, layout);
try std.testing.expectEqual(@as(c_int, 20 + 3 * 20), clip.y);
try std.testing.expectEqual(@as(c_int, 16 * 20), clip.h);
// In a body layer they are tagline-high: the rows under them move up
@@ -7041,11 +7060,11 @@ test "a scroll's shifted rows start under the context rows, and its scissor belo
surface.body_layers[0].context_rows = 3;
const layered = holdContext(&g, &surface, 0, 3, 19, layout);
try std.testing.expectEqual(@as(f32, 3 * (12 - 20)), layered.lift);
- try std.testing.expectEqual(@as(c_int, 20 + 3 * 12), scrollScissor(&g, layout, 400, 400).y);
+ try std.testing.expectEqual(@as(c_int, 20 + 3 * 12), scrollScissor(&g, layout).y);
// None held: the whole body moves.
surface.body_layers[0].rows = 0;
try std.testing.expectEqual(@as(u16, 0), holdContext(&g, &surface, 0, 0, 19, layout).rows);
- try std.testing.expectEqual(@as(c_int, 20), scrollScissor(&g, layout, 400, 400).y);
+ try std.testing.expectEqual(@as(c_int, 20), scrollScissor(&g, layout).y);
}
test "concealed terminal text emits no ink on its ground" {
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index f0011273..44f931b6 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -442,6 +442,11 @@ fn terminalSize(cols: u16, rows: u16, pixel_w: u16, pixel_h: u16) @FieldType(par
.w = @intCast(terminalCellPixels(pixel_w, cols, 8)),
.h = @intCast(terminalCellPixels(pixel_h, rows, 16)),
},
+ // A terminal's tag and body are one cell: its own row metrics, said,
+ // never those of the view its client's was opened from (a window's
+ // tagline is narrower than its body: a tag wrapped at a fifth more
+ // than its row held, the middle of a long tag never shown).
+ .row_metrics = .{},
};
}
@@ -1240,9 +1245,8 @@ const Shell = struct {
/// The session's replica clients (core/replica.zig), on sockets: the
/// session loop's (runtime/session.zig); a client's, none.
peers: *replica.Peers,
- /// This wait took only a replica's post (its input, its join): the
- /// pump after it reads no new time, so it moves nothing the replicas'
- /// speculations stand on (a replica takes such a unit as is).
+ /// This wait took nothing but a replica's post, if one (its input, its
+ /// join): the pump after one reads no new time (Peers.heldNow).
mail_only: bool = false,
waited: bool = false,
/// This wait's steps so far, and the input held for the next (`split`).
@@ -1321,7 +1325,7 @@ const Shell = struct {
const s = of(ctx);
if (s.waited) {
s.waited = false;
- if (s.mail_only and s.peers.count() > 0 and s.core.clock.started) return s.core.clock.now_ns;
+ if (s.peers.heldNow(s.core, s.mail_only)) |held| return held;
}
return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
}
@@ -1572,11 +1576,9 @@ const Shell = struct {
var motion: ?Msg = null;
var ev = first;
while (true) {
- if (s.split(ev)) break;
+ if (s.split(ev, motion)) break;
if (ev == .mouse and (ev.mouse.type == .motion or ev.mouse.type == .drag)) {
- if (motion) |m| if (m.mouse.button != ev.mouse.button or m.mouse.type != ev.mouse.type or
- @as(u3, @bitCast(m.mouse.mods)) != @as(u3, @bitCast(ev.mouse.mods)))
- {
+ if (motion) |m| if (!movesOn(m, ev)) {
_ = s.apply(m);
};
motion = ev;
@@ -1605,14 +1607,16 @@ const Shell = struct {
/// a person's input, and none after a pty's output: a step reads the
/// terminals as the clients' deltas bring them, sent after each unit
/// (docs/next-daemon.md, part B terminal notes). One that must wait is
- /// held for the next. Whether `ev` is.
- fn split(s: *Shell, ev: Msg) bool {
+ /// held for the next. Whether `ev` is; a motion that goes on this
+ /// wait's run of them (`streak`) is that one input, its last.
+ fn split(s: *Shell, ev: Msg, streak: ?Msg) bool {
if (!s.peers.recording) return false;
switch (ev) {
.key_press => if (s.in_paste) return false,
.mouse, .paste, .paste_end, .reply_dropped, .winsize, .focus_in, .focus_out => {},
else => return false,
}
+ if (streak) |m| if (movesOn(m, ev)) return false;
if (s.took_output or s.took_input) {
s.held = ev;
s.input_seen = true;
@@ -1622,6 +1626,13 @@ const Shell = struct {
return false;
}
+ /// Whether `ev` goes on the motion `streak`: one move to its last cell
+ /// (the same button, kind and modifiers).
+ fn movesOn(streak: Msg, ev: Msg) bool {
+ return ev == .mouse and ev.mouse.type == streak.mouse.type and ev.mouse.button == streak.mouse.button and
+ @as(u3, @bitCast(ev.mouse.mods)) == @as(u3, @bitCast(streak.mouse.mods));
+ }
+
fn apply(s: *Shell, event: Msg) bool {
const core = s.core;
const tz_event = tracy.zone(@src(), "event");
@@ -3282,3 +3293,46 @@ test "the tty draws a glide at whole rows: once a flick or a spin slows, its ste
try std.testing.expectEqual(row, (shown.cursor orelse return error.NoCursor).y);
}
}
+test "a terminal client's view, opened from a window's, wraps a tag at its own width: a terminal's resize says a terminal's row metrics" {
+ const gpa = std.testing.allocator;
+ const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 140, .rows = 45 });
+ defer core.deinit();
+ // The session's window: its tag line's glyphs narrower than its body's,
+ // so a tag row holds more of them than it has cells.
+ core.update(.{ .resize = .{ .cols = 140, .rows = 45, .cell_pixels = .{ .w = 16, .h = 33 }, .row_metrics = .{ .body_w = 16, .body_h = 33, .tagline_w = 13, .tagline_h = 26 } } });
+ const pane = try core.setTestFile("text\n");
+ var words: [40][3]u8 = undefined;
+ var tag: std.ArrayList(u8) = .empty;
+ defer tag.deinit(gpa);
+ for (&words, 0..) |*w, i| {
+ w.* = .{ 'w', '0' + @as(u8, @intCast(i / 10)), '0' + @as(u8, @intCast(i % 10)) };
+ try tag.appendSlice(gpa, " ");
+ try tag.appendSlice(gpa, w);
+ }
+ if (pane.tag.own) |own| gpa.free(own);
+ pane.tag.own = try gpa.dupe(u8, tag.items);
+ // A terminal's client joins: its view opened from the window's, then
+ // sized by its terminal, as the client's first inputs do.
+ const k = core.openView().?;
+ core.toView(k);
+ core.update(.{ .resize = terminalSize(100, 30, 0, 0) });
+ core.sync();
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const s = try core.render(arena.allocator());
+ var shown: std.ArrayList(u8) = .empty;
+ defer shown.deinit(gpa);
+ for (s.regionList()) |region| {
+ if (region.kind != .tag) continue;
+ for (region.rect.y..region.rect.y + region.rect.h) |y| {
+ for (s.cells[y * s.cols ..][region.rect.x..][0..region.rect.w]) |cell| try shown.appendSlice(gpa, if (cell.len == 0) " " else cell.grapheme());
+ try shown.append(gpa, '\n');
+ }
+ }
+ // Each of its words shows: wrapped at its rows' width, none lost
+ // between a row cut short and the next.
+ for (&words) |*w| if (std.mem.indexOf(u8, shown.items, w) == null) {
+ std.debug.print("{s} is not shown in the tag:\n{s}\n", .{ w, shown.items });
+ return error.TestUnexpectedResult;
+ };
+}
diff --git a/docs/loose-ends.md b/docs/loose-ends.md
new file mode 100644
index 00000000..0fb2c984
--- /dev/null
+++ b/docs/loose-ends.md
@@ -0,0 +1,92 @@
+# Loose ends
+
+What is known to be wrong, unfinished or decided and not built, as of
+2026-11-24, written down so that none of it has to be found twice. Nothing
+here blocks daily use; each entry says where it was seen and what is known.
+An entry leaves this file in the change that settles it.
+
+## Faults known, not fixed
+
+- **Restore on a release build fails one process test.** `process-test`
+ on ReleaseSafe, the root-ctl case "Restore asks once about unsaved text,
+ is answered before it cuts every connection": the request is answered
+ `Refused`. A request on a connection the Restore is cutting gets an error
+ in the 200 ms cut window (runtime/9p_io.zig `onServe`). Debug passes,
+ which is why every gate missed it until the release row was added. A fix
+ is written on the client-connection line (a connection being cut is hung
+ up, never answered with a refusal) and lands with that line.
+- **A damaged session image can panic the database reader.** The dump
+ fuzz's image road reaches xitdb's own reader (`switch on corrupt value`
+ in `HashMap.init`, `readBytesObjectAlloc`, from core `Db.Read`) past its
+ fixed seeds. pardes's own decoders refuse a damaged dump naming the
+ field; this one is the dependency's. It wants an Edit in
+ build/patches.zig and a report beside the other dependency reports.
+- **A client that replays after it diverged can overflow an integer.**
+ `Core.advanceInner` (`due - p.clock.stepped_ns`): seen only by the
+ soak's witness replaying a client that had already parted. A client that
+ diverges is dropped and joins again, so a user does not reach it today.
+- **A detached session loses the words of an Upgrade that could not
+ load.** With no frontend of its own, "no build could load" is shown to
+ nobody; it should reach the log and the next client.
+- **After an Upgrade a window says the pointer is inside.** `/status`
+ read "pointer in" in two windows right after their exec with the pointer
+ in neither (2026-11-24); one went back to "out" by itself.
+- **A client left once across a build whose wire number differed.** Seen
+ once on the client-connection line, not reproduced.
+- **In a terminal client a column's border did not drag** by B1 on the
+ second column's tag gutter (measured while testing several clients).
+ Whether a terminal has another handle for it was not looked at.
+
+## Decided, not built
+
+- **An addon's panic closes only its pane** (ruled 2026-11-24). Today an
+ addon's panic is pardes's panic: a crash record is written, the terminal
+ is put back, and the session ends. The ruling: the pane of the addon
+ that panicked is closed with its words in the log, the session goes on.
+- **A client's send queue bounded by back-pressure.** The session writes
+ no more than a window W past what the client has read and queues the
+ rest; a client is cut to a fresh dump only when the queue also passes W.
+ Designed with a draft on the client-connection line; today a far client
+ under a flood is cut by the older lag rule, which works.
+- **The 200 ms flush before a link is dropped** becomes a wait that each
+ writer's end wakes, and every other time bound gets one line saying why
+ real time is right there. Designed, not built.
+- **More than four views a session.** A fifth view is refused (the
+ session's own and three clients, or four clients of a detached one).
+ What raising the limit costs (the per-view arrays, the digest, the dump,
+ the wire) is not measured.
+- **Help wraps mid-word.** It waits on wrapping at word boundaries, which
+ no pane has yet.
+- **A pane's rectangle inside its column, checked at a load.** A view's
+ rectangles off its screen are refused; this narrower check is not built
+ because a pane placed and not yet laid out has an empty rectangle inside
+ a step, and a dump is written inside a step.
+
+## Prices accepted (to turn if they are felt)
+
+- A view's scroll by rows: selecting deep into one 2 MB line costs about
+ 75% more a frame (it draws the rows the selection is on; the old view
+ did not show them). Every ordinary key, wheel, page and edit: no dearer.
+- One terminal cell of the performance table is 0.14% to 0.16% over its
+ old count since the change layers; the baseline was recorded again.
+
+## The structural queue
+
+Three pieces of organization meant to make whole kinds of fault
+impossible to write, each to start with a read-only survey and a plan:
+a client's lifecycle as one state with codes on the wire and every time
+bound named; what a field of the core costs (the digest, the dump and
+the copy declared together); the test harness (the Python daemon tests
+moved to the Zig runner, mode by mode). Three questions go with it: the
+terminal boundary enforced by type or by a counted list; the codes'
+names; whether the Python harness goes entirely.
+
+## Tests and gates
+
+- The gui `unit-test` step exits 1 with every test passing: its
+ performance check reports a baseline recorded by another harness. A
+ baseline recorded with the current one clears it.
+- `test/daemon.py --upgrade --gui` assumes `wayland-0` when
+ `WAYLAND_DISPLAY` is unset; it should find the compositor's socket.
+- `test/daemon.py --window-clients` skips its PDF case when the terminal
+ build's prefix holds no `pdf.so`.
diff --git a/test/daemon.py b/test/daemon.py
index adfbc52a..97b0de76 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -48,6 +48,18 @@ private HOME and runtime directory:
python3 -B test/daemon.py --window-clients <pardes> <pardes-gui>
window replica clients (hidden, offscreen) of a terminal's session,
at 0/30/80/207 ms, and a window's session serving replicas
+ python3 -B test/daemon.py --client-motion <pardes> <pardes-gui>
+ a run of pointer motions over a client window is a few inputs, not
+ one each (also run by --window-clients)
+ python3 -B test/daemon.py --client-resize-real <pardes> <pardes-gui>
+ a client window showing a PDF resized 30 times in a second by the
+ real compositor (driftwm), the caller's display: no SDL assertion,
+ the last size taken, an input a size at most
+ python3 -B test/daemon.py --client-idle <pardes> <pardes-gui>
+ a window's session (the test surface, and offscreen with no test
+ mode) and a terminal's, each with a PDF and a terminal client,
+ nobody typing: no more steps than the text alone (pdf.so in both
+ prefixes)
"""
import fcntl
import json
@@ -2145,6 +2157,381 @@ def window_clients(binary, gui_binary):
shutil.rmtree(root, ignore_errors=True)
+def client_motion(binary, gui_binary):
+ """A run of pointer motions is one move to its last position (gui.zig
+ Input.moved), over a client window and over the session's own window
+ with a client attached: not an input each, which the session steps one
+ by one and sends every client as a unit each, every one of them
+ replayed and drawn again (the user's "resizing feels very slow with
+ several clients", 2026-11-24: a 1000 Hz mouse is a thousand inputs a
+ second). 300 motions written at once, 30 bytes each: the window takes
+ them a read of its test feed (1024 bytes) a pass, so at most ten
+ passes, each one input; with the five a client makes anyway (what it
+ is, its size, its focus, two keys) at most 15, asserted at most 20.
+ Three roads: the feed's own dispatch (`motion`) and SDL's queue
+ (`pointer`: the same motion pushed as a mouse's comes) over a window
+ client of a terminal's session, the inputs it sent the session (its
+ PARDES_REPLICA_STATS); and SDL's queue over a window's session with a
+ terminal client watching, a drag, the frames the window drew (its
+ status: on main each motion was its own wait, `split`, a frame each)."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='cm-', dir=os.environ.get('TMPDIR') or scratch))
+ env = base_env()
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
+ started, terms, windows = [], [], []
+ try:
+ sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+ started.append(sess.pid)
+ sock = root / 'pardes-replica.sock'
+ wait_for('the replica socket', sock.exists)
+ wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists)
+ nine = Client(root / 'pardes-9p-files.sock')
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ tt = Term(24, 80)
+ terms.append(tt)
+ t = tt.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_STATS=str(root / 't.stats')))
+ started.append(t.pid)
+ wait_for('the terminal client\'s first frame', lambda: b'line 3 of the notes' in tt.text(), timeout=30)
+ motions = 300
+
+ def burst(win, kind, button=0):
+ win.p.stdin.write(b''.join(f'\x1b]777;mouse;{kind};{button};{200 + 3 * i};{300 + i % 40}\x07'.encode() for i in range(motions)))
+ win.p.stdin.flush()
+
+ def said(path, word):
+ line = checks(path)[-1].split()
+ return int(line[line.index(word) + 1])
+
+ sent = {}
+ for kind in ('motion', 'pointer'):
+ stats = root / f'w-{kind}.stats'
+ w = Window(root, f'w-{kind}', [gui_binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_STATS=str(stats)))
+ windows.append(w)
+ started.append(w.pid)
+ w.keys(b'jj')
+ wait_for('the window\'s keys in the session', lambda: b'line' in nine.read(f'/pane/{pane}/body'), timeout=30)
+ time.sleep(2)
+ burst(w, kind)
+ time.sleep(3)
+ assert w.close() == 0, w.said()[-800:]
+ sent[kind] = said(stats, 'inputs')
+ t.send_signal(signal.SIGHUP)
+ t.wait(timeout=10)
+ tt_units = said(root / 't.stats', 'units') if checks(root / 't.stats') else None
+ print(f'daemon: {motions} motions over a client window: it sent the session {sent["motion"]} inputs by the feed, '
+ f'{sent["pointer"]} by SDL\'s queue; the terminal client took {tt_units} units')
+ for kind, n in sent.items():
+ assert n <= 20, (f'{motions} pointer motions ({kind}) over a client window were {n} inputs to its session, '
+ 'each a unit for every client: not one a pass')
+ exit_session(nine, pane)
+ sess.wait(timeout=60)
+ nine.socket.close()
+ # The session's own window, a terminal client watching: SDL's queue.
+ win = Window(root, 'win', [gui_binary, '--9p=win', str(notes)], dict(env, PARDES_DAEMON='on'))
+ windows.append(win)
+ started.append(win.pid)
+ wait_for('the window session\'s 9P socket', (root / 'pardes-9p-win.sock').exists, timeout=30)
+ wait_for('the replica socket', sock.exists)
+ nine = Client(root / 'pardes-9p-win.sock')
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ tb = Term(24, 80)
+ terms.append(tb)
+ b = tb.spawn([binary, f'--attach={sock}:win'], dict(env, PARDES_REPLICA_STATS=str(root / 'b.stats')))
+ started.append(b.pid)
+ wait_for('the terminal client\'s first frame', lambda: b'line 3 of the notes' in tb.text(), timeout=30)
+ time.sleep(2)
+
+ def frames():
+ return int((root / 'win' / 'status').read_text().split()[1])
+
+ # A drag selecting: each motion moves what the window shows.
+ win.mouse('down', 1, 200, 300)
+ time.sleep(1)
+ before = frames()
+ burst(win, 'pointer', 1)
+ time.sleep(3)
+ drawn = frames() - before
+ win.mouse('up', 1, 1097, 339)
+ time.sleep(1)
+ b.send_signal(signal.SIGHUP)
+ b.wait(timeout=10)
+ print(f'daemon: {motions} motions of a drag over the session\'s own window, a terminal client watching: '
+ f'the window drew {drawn} frames; the client {said(root / "b.stats", "draws")} in all')
+ assert drawn <= 20, (f'{motions} pointer motions over the session\'s window were {drawn} frames of it with a client '
+ 'attached: each motion its own wait (split), a step and a unit each, not one a pass')
+ exit_session(nine, pane)
+ assert win.close() == 0, win.said()[-800:]
+ nine.socket.close()
+ finally:
+ for tm in terms:
+ tm.close()
+ for w in windows:
+ if w.p.poll() is None:
+ w.p.kill()
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def idle_session(binary, gui_binary, surface, pdf, secs):
+ """One session (`surface`: a window's on the test surface; a window's
+ offscreen with no test mode, `loop`: the loop a real window runs, asleep
+ until an event or its deadline; or a terminal's with its own terminal),
+ a text and, with `pdf`, a PDF, one terminal client attached, nobody
+ typing for `secs`: the session's boundaries and the units the client
+ took over its whole life, and the CPU each spent in the idle seconds
+ (ticks of 10 ms)."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ci-', dir=os.environ.get('TMPDIR') or scratch))
+ env = base_env()
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(60)))
+ stats = root / 'session.stats'
+ started, terms, windows = [], [], []
+ try:
+ if surface == 'window':
+ win = Window(root, 'win', [gui_binary, '--9p=idle', str(notes)], dict(env, PARDES_DAEMON='on', PARDES_REPLICA_STATS=str(stats)))
+ windows.append(win)
+ started.append(win.pid)
+ elif surface == 'loop':
+ started.append(subprocess.Popen([gui_binary, '--9p=idle', str(notes)], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL, start_new_session=True,
+ env=dict(env, PARDES_DAEMON='on', PARDES_REPLICA_STATS=str(stats), SDL_VIDEO_DRIVER='offscreen')).pid)
+ else:
+ ts = Term(30, 100)
+ terms.append(ts)
+ started.append(ts.spawn([binary, '--tty', '--9p=idle', str(notes)], dict(env, PARDES_REPLICA_STATS=str(stats))).pid)
+ wait_for('the session\'s 9P socket', (root / 'pardes-9p-idle.sock').exists, timeout=30)
+ nine = Client(root / 'pardes-9p-idle.sock')
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ started.append(session)
+ sock = root / 'pardes-replica.sock'
+ wait_for('the replica socket', sock.exists, timeout=30)
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ if pdf:
+ doc = root / 'design.pdf'
+ shutil.copy(Path(__file__).resolve().parent.parent / 'docs' / 'design.pdf', doc)
+ nine.write(f'/pane/{pane}/look', f'{doc}\n'.encode())
+ wait_for('the PDF shown', lambda: any(row.split()[1] == b'pdf' for row in nine.read('/index').splitlines()), timeout=30)
+ tc = Term(24, 80)
+ terms.append(tc)
+ c = tc.spawn([binary, f'--attach={sock}:idle'], dict(env, PARDES_REPLICA_STATS=str(root / 'c.stats')))
+ started.append(c.pid)
+ wait_for('the client\'s first frame', lambda: b'notes' in tc.text(), timeout=30)
+ # Its join and the frames after it over.
+ time.sleep(1.5)
+ cpu = (cpu_ticks(session), cpu_ticks(c.pid))
+ time.sleep(secs)
+ cpu = (cpu_ticks(session) - cpu[0], cpu_ticks(c.pid) - cpu[1])
+ c.send_signal(signal.SIGHUP)
+ c.wait(timeout=10)
+ line = checks(root / 'c.stats')[-1].split()
+ units = int(line[line.index('units') + 1])
+ exit_session(nine, pane)
+ wait_for('the session ended', lambda: not alive(session), timeout=60)
+ nine.socket.close()
+ return int(session_stats(stats)[0]['boundaries']), units, cpu
+ finally:
+ for t in terms:
+ t.close()
+ for w in windows:
+ if w.p.poll() is None:
+ w.p.kill()
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def client_idle(binary, gui_binary, secs=5):
+ """An idle session sends nothing (2026-11-24: a PDF in a window's session
+ with a client attached stepped the session ~700 times a second, nobody
+ typing, each step a unit every client replayed): a session showing a
+ text and a PDF, one terminal client, nobody typing for `secs`, takes at
+ most the steps the same session with the text alone takes, plus the
+ PDF's own opening (its page drawn, its views told: `opening`). On the
+ test surface the window's loop polls its feed every 16 ms, a step and a
+ unit each (the text alone's count is that rate); a window's own loop
+ (`loop`: offscreen, no test mode) and a terminal's session step for
+ nothing. The PDF's addon (`<prefix>/lib/pardes/addons/pdf.so`, `zig
+ build addons`) beside each binary."""
+ for b in (binary, gui_binary):
+ lib = Path(b).resolve().parent.parent / 'lib' / 'pardes' / 'addons' / 'pdf.so'
+ assert lib.exists(), f'no {lib}: the PDF is this test\'s subject (zig build install addons into that prefix)'
+ opening = 40
+ flooded = []
+ for surface in ('window', 'loop', 'tty'):
+ text = idle_session(binary, gui_binary, surface, False, secs)
+ shown = idle_session(binary, gui_binary, surface, True, secs)
+ print(f'daemon: a {surface}\'s session idle {secs} s, a terminal client attached: '
+ f'text alone {text[0]} boundaries, the client {text[1]} units, CPU {text[2][0] * 10}/{text[2][1] * 10} ms; '
+ f'with a PDF {shown[0]} boundaries, {shown[1]} units, CPU {shown[2][0] * 10}/{shown[2][1] * 10} ms (session/client)')
+ if shown[0] > text[0] + opening or shown[1] > text[1] + opening:
+ flooded.append(f'{surface}: {shown[0]} boundaries and {shown[1]} units against the text alone\'s {text[0]} and {text[1]}')
+ assert not flooded, (f'a session showing a PDF, a client attached, nobody typing for {secs} s, steps with nothing to do, '
+ f'a unit every client replays: {"; ".join(flooded)}')
+
+
+def client_resize_real(binary, gui_binary):
+ """A client window resized by a real compositor (driftwm's `msg resize`,
+ the configures a drag sends: 30 sizes in a second) while it shows a PDF:
+ no SDL assertion (on main every frame drawn larger than the target it
+ is drawn into placed the page's scissor past it: `SDL_SetGPUScissor`'s
+ release assertion, whose dialog blocks the window's thread: the window
+ frozen at its old size, cut, and nothing opened after shows in it), it
+ takes the last size, it posts a size a configure at most and is rolled
+ back as often at most (on main the session's own window sized the
+ client's view to its own size, the client posted its own again, on and
+ on: 425 to 1308 inputs, 228 rollbacks, its frames drawn at the session
+ window's size, cut). Real windows: the
+ caller's display and runtime directory reach the compositor; the
+ session's runtime directory is the test's own; skipped without driftwm."""
+ real_runtime = os.environ.get('XDG_RUNTIME_DIR', '')
+ wayland = os.environ.get('WAYLAND_DISPLAY') or 'wayland-1'
+ display = wayland if wayland.startswith('/') else os.path.join(real_runtime, wayland)
+ lib = Path(binary).resolve().parent.parent / 'lib' / 'pardes' / 'addons' / 'pdf.so'
+ if not shutil.which('driftwm') or not os.path.exists(display) or not lib.exists():
+ print('daemon: client resize on a real compositor: skipped (no driftwm, display or pdf.so)')
+ return
+ drift_env = dict(os.environ, XDG_RUNTIME_DIR=real_runtime, WAYLAND_DISPLAY=wayland)
+
+ def drift(*args):
+ out = subprocess.run(['driftwm', 'msg', '--json', *map(str, args)], env=drift_env, capture_output=True, text=True, timeout=10)
+ return json.loads(out.stdout) if out.stdout.strip() else {}
+
+ def window_of(pid):
+ state = drift('state')['Ok']['State']
+ return next((w for w in state['windows'] if w.get('pid') == pid), None)
+
+ def away(pid, x, y):
+ """The window moved far from the desktop user's view, and kept
+ there: driftwm places a window again when it maps, after a move made
+ before (it came back beside the user's view, 2026-11-24)."""
+ wid = window_of(pid)['id']
+ still = 0
+ for _ in range(300):
+ if window_of(pid)['position'] != [x, y]:
+ drift('move', '--id', wid, x, y)
+ still = 0
+ else:
+ still += 1
+ if still == 40:
+ return wid
+ time.sleep(0.05)
+ raise AssertionError(('a test window would not stay away from the desktop user\'s view', window_of(pid)))
+
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='cr-', dir=os.environ.get('TMPDIR') or scratch))
+ env = base_env()
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', SDL_AUDIODRIVER='dummy')
+ env.pop('XDG_DATA_HOME', None)
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
+ doc = root / 'design.pdf'
+ shutil.copy(Path(__file__).resolve().parent.parent / 'docs' / 'design.pdf', doc)
+ started = []
+ try:
+ state = drift('state')['Ok']['State']
+ focused = next((w['id'] for w in state['windows'] if w.get('is_focused')), None)
+ # The session a window of its own, as a desktop's is, its daemon on;
+ # a terminal with output in it beside the PDF.
+ sess = subprocess.Popen([gui_binary, '--9p=files', str(notes), '--geometry=1120x760'],
+ env=dict(env, PARDES_DAEMON='on', WAYLAND_DISPLAY=display, SDL_VIDEO_DRIVER='wayland', SDL_ASSERT='ignore'),
+ cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=open(root / 's.err', 'w'),
+ start_new_session=True)
+ started.append(sess.pid)
+ wait_for('the session\'s window', lambda: (window_of(sess.pid) or {}).get('id'), timeout=30)
+ away(sess.pid, 59400, -18000)
+ if focused is not None:
+ drift('focus', '--id', focused)
+ sock = root / 'pardes-replica.sock'
+ wait_for('the replica socket', sock.exists, timeout=30)
+ wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists, timeout=30)
+ nine = Client(root / 'pardes-9p-files.sock')
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ nine.write(f'/pane/{pane}/exec', b'Term\n')
+ shell = wait_for('a shell pane', lambda: next((int(row.split()[0]) for row in nine.read('/index').splitlines()
+ if row.split()[1] == b'term'), None))
+ wait_for('the shell\'s prompt', lambda: b'$' in nine.read(f'/pane/{shell}/body'))
+ nine.write(f'/pane/{shell}/pty/data', b'seq 1 400\r')
+ nine.write(f'/pane/{pane}/look', f'{doc}\n'.encode())
+ wait_for('the PDF pane', lambda: any(row.split()[1] == b'pdf' for row in nine.read('/index').splitlines()))
+ err = root / 'w.err'
+ stats = root / 'w.stats'
+ # SDL's assertion counted on stderr, never its dialog on the desktop.
+ w = subprocess.Popen([gui_binary, f'--attach={sock}:files', '--geometry=900x600'],
+ env=dict(env, WAYLAND_DISPLAY=display, SDL_VIDEO_DRIVER='wayland', SDL_ASSERT='ignore',
+ PARDES_REPLICA_STATS=str(stats), SDL_EVENT_LOGGING='2'),
+ cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=open(err, 'w'), start_new_session=True)
+ started.append(w.pid)
+ wait_for('the client\'s window', lambda: (window_of(w.pid) or {}).get('id'), timeout=30)
+ # Far from where the desktop's user looks, the focus given back.
+ wid = away(w.pid, 62000, -18000)
+ if focused is not None:
+ drift('focus', '--id', focused)
+ time.sleep(3)
+ steps = 30
+ t0 = time.monotonic()
+ for i in range(steps):
+ time.sleep(max(0, t0 + i / 30 - time.monotonic()))
+ last = (900 + 9 * (i + 1), 600 + 5 * (i + 1))
+ drift('resize', '--id', wid, *last)
+ time.sleep(3)
+ size = window_of(w.pid)['size']
+ said = err.read_text(errors='replace')
+ w.send_signal(signal.SIGTERM)
+ w.wait(timeout=15)
+ line = checks(stats)[-1].split() if checks(stats) else []
+ sent = int(line[line.index('inputs') + 1]) if 'inputs' in line else -1
+ # SDL's default handler's words, and pardes's own (gui.zig sdlAssertion).
+ asserted = said.count('Assertion failure') + said.count('SDL assertion: ')
+ # A pointer that crossed the window (one sliding under it as it was
+ # moved away) is motion's, --client-motion's: not counted here.
+ motions = said.count('SDL_EVENT_MOUSE_MOTION')
+ sent -= motions
+ # Its own inputs rolled back by the session's units between them.
+ rollbacks = int(line[line.index('foreign') + 1]) if 'foreign' in line else -1
+ print(f'daemon: a client window resized {steps} times in a second by the compositor: {asserted} SDL assertions, '
+ f'its size {size} (asked {list(last)}), {sent} inputs besides {motions} pointer motions, {rollbacks} rollbacks')
+ assert asserted == 0, ('a client window drew past its target while resized', said[-600:])
+ assert abs(size[0] - last[0]) <= 2 and abs(size[1] - last[1]) <= 40, ('the client window did not take the last size', size, last)
+ # A size a configure at most (the window's own, compared with what it
+ # posted last: none after the last).
+ assert sent <= steps, ('a client window resized posted its size again and again', sent)
+ assert 0 <= rollbacks <= steps + motions, ('a client window resized was rolled back again and again', rollbacks)
+ exit_session(nine, pane)
+ sess.wait(timeout=60)
+ nine.socket.close()
+ finally:
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
def joins(path):
"""A replica client's joins (PARDES_REPLICA_STATS, a line a link): how
many blobs each listed, how many it held already from the core it left
@@ -4212,6 +4599,13 @@ if __name__ == '__main__':
elif sys.argv[1:2] == ['--window-clients']:
window_clients(sys.argv[2], sys.argv[3])
pdf_window(sys.argv[2], sys.argv[3])
+ client_motion(sys.argv[2], sys.argv[3])
+ elif sys.argv[1:2] == ['--client-motion']:
+ client_motion(sys.argv[2], sys.argv[3])
+ elif sys.argv[1:2] == ['--client-resize-real']:
+ client_resize_real(sys.argv[2], sys.argv[3])
+ elif sys.argv[1:2] == ['--client-idle']:
+ client_idle(sys.argv[2], sys.argv[3])
elif sys.argv[1:2] == ['--ping']:
ping(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5]) if len(sys.argv) > 5 else 50)
elif sys.argv[1:2] == ['--pair-gui']:
diff --git a/test/panes.zig b/test/panes.zig
index eea4b36d..ba3466fb 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -4049,6 +4049,90 @@ const PdfAddon = struct {
}
}
+ /// A session's loop with nobody typing: each wait runs out at its
+ /// deadline, and the clock read after it is the shells' (Peers.heldNow,
+ /// as gui.zig `guiNow` and tui.zig `clockNow` read it: a wait that took
+ /// nothing else, `only_mail`).
+ const Idle = struct {
+ now: u64 = std.time.ns_per_s,
+ waited: bool = false,
+ core: ?*Pardes = null,
+ peers: pardes.replica.Peers = .{ .gpa = std.testing.allocator, .io = std.testing.io },
+
+ const vtable: pardes.Host.VTable = .{
+ .wait_input = wait,
+ .now = clock,
+ .watched = host_vtable.watched,
+ .job = host_vtable.job,
+ };
+
+ fn wait(ctx: ?*anyopaque, timeout_ms: u32) void {
+ const h: *Idle = @ptrCast(@alignCast(ctx.?));
+ h.now += @as(u64, timeout_ms) * std.time.ns_per_ms;
+ h.waited = true;
+ }
+
+ fn clock(ctx: ?*anyopaque) u64 {
+ const h: *Idle = @ptrCast(@alignCast(ctx.?));
+ if (!h.waited) return h.now;
+ h.waited = false;
+ return h.peers.heldNow(h.core orelse return h.now, true) orelse h.now;
+ }
+ };
+
+ test "a PDF shown and a client's view its kind was not told: the session's next pump, its wait run out with nobody typing, tells it, and nothing is owed after; a client's post waiting holds the clock" {
+ // 2026-11-24: a window's session showing a PDF, a client attached,
+ // stepped ~700 times a second with nobody typing: the client's view
+ // owed to the kind (Kind.wake: now), a wait of a millisecond that
+ // ran out, and the clock after it held as if a client had posted
+ // (gui.zig guiNow: its wait's `mail_only` is cleared by an event,
+ // and one that ran out had none), so no step met the deadline.
+ if (!addons.has_pdf) return error.SkipZigTest;
+ const R = pardes.replica;
+ var idle: Idle = .{};
+ defer idle.peers.deinit();
+ const a = try R.Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .ctx = &idle, .vtable = &Idle.vtable });
+ defer a.deinit();
+ idle.core = a.core;
+ const Land = struct {
+ a: *R.Authority,
+ fn step(l: @This(), ev: pardes.Event) !void {
+ _ = try l.a.local(ev);
+ }
+ };
+ const id = try opened(a, Land{ .a = a });
+ const slot = a.core.panes[id].?.addon.?;
+ // A client attached (units go to it), its view sized by its input:
+ // a client's step tells no kind (17.2), so its view is owed.
+ idle.peers.recording = true;
+ const k = (try a.openView(2)).view;
+ 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 win = try R.Replica.initDump(std.testing.allocator, 2, k, bytes, .{ .cols = 80, .rows = 24 });
+ defer win.deinit();
+ _ = try a.take(try win.input(.{ .resize = .{ .cols = 80, .rows = 24 } }));
+ try std.testing.expect(pardes.Kind.viewOwed(a.core, slot, id));
+ // ONE pump, nobody typing: its wait runs out at the wake, the step
+ // it asked for tells the view, and nothing is owed after.
+ a.pump();
+ try std.testing.expect(!pardes.Kind.viewOwed(a.core, slot, id));
+ try std.testing.expect((pardes.Kind.wake(a.core) orelse std.math.maxInt(u64)) > a.core.clock.now_ns);
+ // A client's post waiting (its input, its join): the pump before
+ // the boundary takes it reads the clock as it stands.
+ const at = a.core.clock.now_ns;
+ idle.now += std.time.ns_per_s;
+ idle.peers.mail.store(true, .release);
+ a.pump();
+ try std.testing.expectEqual(at, a.core.clock.now_ns);
+ idle.peers.mail.store(false, .release);
+ a.pump();
+ try std.testing.expectEqual(idle.now, a.core.clock.now_ns);
+ }
+
test "a PDF pane whose file changes on disk opens again from it at its page, its fit kept" {
if (!addons.has_pdf) return error.SkipZigTest;
const gpa = std.testing.allocator;