summaryrefslogtreecommitdiff
path: root/src/gui
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-31 06:28:48 -0300
committerGabriel Schneider <[email protected]>2026-10-31 06:28:48 -0300
commita479792a1ab2b593642d7f648194bfa23ce01dba (patch)
tree96ddee7d879a9084daa07db43b0b7910b072a785 /src/gui
parente179cc44fe5060c76a5b00c41e53f11209f5acd9 (diff)
parent4c761893e5b3fdae422622cfa02104ab36633045 (diff)
downloadpardes-a479792a1ab2b593642d7f648194bfa23ce01dba.tar.gz
pardes-a479792a1ab2b593642d7f648194bfa23ce01dba.zip
Merge the upstream daemon and replicated client/server refactor
Diffstat (limited to 'src/gui')
-rw-r--r--src/gui/gui.zig1352
1 files changed, 1078 insertions, 274 deletions
diff --git a/src/gui/gui.zig b/src/gui/gui.zig
index 01272b41..d3acf454 100644
--- a/src/gui/gui.zig
+++ b/src/gui/gui.zig
@@ -22,7 +22,10 @@ const c_heap = @import("c_heap");
const ninep_io = @import("../9p_io.zig");
-const detached_client = @import("../detached/client.zig");
+const daemon = @import("../daemon.zig");
+const upgrade = @import("../upgrade.zig");
+const replica = @import("../replica.zig");
+const wire = @import("../detached/wire.zig");
const tracy = @import("../tracy.zig");
pub const c = @import("gui_c"); // SDL3 and font.h, translated by build.zig
@@ -670,24 +673,29 @@ test "closing tombstone overlays but never owns canonical cells" {
}
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, cols, rows, cell_w, cell_h, tag_w, tag_h) orelse return false);
+ return true;
+}
+
+/// The resize a window of `cols` by `rows` cells of these sizes is to the
+/// live view, or null when it is that already.
+fn resizeOf(core: 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, core.row_metrics);
if (comptime pardes.pdf_enabled) {
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 == core.screen_w and rows == core.screen_h and
- cell_px_w == core.cell_pixels.w and cell_px_h == core.cell_pixels.h and same_metrics) return false;
- core.update(.{ .resize = .{
+ cell_px_w == core.cell_pixels.w and cell_px_h == core.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,
- } });
- } else {
- if (cols == core.screen_w and rows == core.screen_h and same_metrics) return false;
- core.update(.{ .resize = .{ .cols = cols, .rows = rows, .row_metrics = metrics } });
+ } };
}
- return true;
+ if (cols == core.screen_w and rows == core.screen_h and same_metrics) return null;
+ return .{ .resize = .{ .cols = cols, .rows = rows, .row_metrics = metrics } };
}
const TouchSample = struct { x: f32 = 0, y: f32 = 0, pressure: f32 = 1 };
@@ -1109,7 +1117,8 @@ test "GUI PTY Restore joins a real reader waiting for queue space" {
core.deinit();
core = replacement;
shell.core = replacement;
- try std.testing.expect(core.panes[0].?.serial != old_serial);
+ // The dump's pane, its serial too; its old shell stopped all the same.
+ try std.testing.expectEqual(old_serial, core.panes[0].?.serial);
try std.testing.expectEqual(@as(usize, 0), queue.waiting);
try std.testing.expect(queue.readers[0] == null);
try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD));
@@ -1434,8 +1443,6 @@ const Gui = struct {
tagline_percent: u8,
tagline_width: u32,
tagline_height: u32,
- attached_layers: ?*const [pardes.MAX_PANES]pardes.Layer = null,
- attached_tag_layers: ?*const [pardes.MAX_TAG_LAYERS]pardes.Layer = null,
cell_w: u32,
cell_h: u32,
ascent: i32,
@@ -1533,6 +1540,14 @@ const Gui = struct {
applied_window_opacity: u8 = 100,
soft_renderer: ?*c.SDL_Renderer = null,
soft_texture: ?*c.SDL_Texture = null,
+ /// What a window is opened again with (reopenWindow): the flags (not
+ /// hidden), the present mode, its size when it was closed.
+ win_flags: c.SDL_WindowFlags = 0,
+ present_mode: c.SDL_GPUPresentMode = c.SDL_GPU_PRESENTMODE_VSYNC,
+ window_w: c_int = 1120,
+ window_h: c_int = 720,
+ /// The window runNative destroys at the end: the one open then, if any.
+ window_slot: ?*?*c.SDL_Window = null,
soft_tex_w: u32 = 0,
soft_tex_h: u32 = 0,
@@ -1544,6 +1559,68 @@ const Gui = struct {
deck: deck.Deck = .{},
};
+/// The Gui's fields that are each window's own, one a view (views.zig):
+/// the window and its presenting, its scroll and glide, its scene and post
+/// chain, its pointer, its blink, its images as presented, its capture. The
+/// device, the atlas, the font and the pipelines are every window's. The
+/// Gui holds the live window's; the others wait in `Shell.windows`.
+const window_fields = [_][:0]const u8{
+ "window", "soft_renderer", "soft_texture", "soft_tex_w", "soft_tex_h",
+ "window_w", "window_h", "scroll_pane", "scroll_rect", "scroll_body_y",
+ "scroll_body_h", "scroll_held_px", "scroll_col", "scroll_row", "scroll_delta",
+ "scroll_lag", "scroll_edge", "scroll_edge_len", "scroll_notch", "program_wheel",
+ "glide", "pace_ns", "sel_glow", "hover_glow", "frame_arrival_ns",
+ "blink_due", "cursor_quad_alpha", "scene_tex", "scene_tex_w", "scene_tex_h",
+ "scene_failures", "scene_target_failed", "post", "pointer_present", "pointer_shape",
+ "pointer_mapped", "pointer_cell", "presented_images", "prepared_images", "touch",
+ "live_ctrl", "live_alt", "applied_window_opacity", "capture_tex", "capture_tex_w",
+ "capture_tex_h", "capture_xfer", "capture_xfer_size", "captured", "capture_dir",
+};
+
+const GuiWindow = blk: {
+ @setEvalBranchQuota(100_000);
+ const st = @typeInfo(Gui).@"struct";
+ var types: [window_fields.len]type = undefined;
+ var attrs: [window_fields.len]std.lang.Type.Struct.FieldAttributes = undefined;
+ for (window_fields, 0..) |name, i| {
+ const at = for (st.field_names, 0..) |n, j| {
+ if (std.mem.eql(u8, n, name)) break j;
+ } else @compileError("gui: Gui has no field " ++ name);
+ types[i] = st.field_types[at];
+ attrs[i] = .{ .default_value_ptr = st.field_attrs[at].default_value_ptr };
+ }
+ break :blk @Struct(.auto, null, &window_fields, &types, &attrs);
+};
+
+fn copyWindow(dst: anytype, src: anytype) void {
+ inline for (window_fields) |name| @field(dst, name) = @field(src, name);
+}
+
+/// The live window's share of `g` as a window starts, but its SDL window
+/// (reopenWindow makes that).
+fn freshWindow(g: *Gui) void {
+ @setEvalBranchQuota(100_000);
+ const st = @typeInfo(Gui).@"struct";
+ inline for (window_fields) |name| {
+ const at = comptime for (st.field_names, 0..) |n, j| {
+ if (std.mem.eql(u8, n, name)) break j;
+ } else unreachable;
+ if (comptime st.field_attrs[at].defaultValue(st.field_types[at])) |d| @field(g, name) = d;
+ }
+}
+
+/// What a window held of its own let go (closeWindow lets the window go).
+fn releaseWindowParts(g: *Gui, gpa: std.mem.Allocator) void {
+ if (g.scene_tex) |texture| c.SDL_ReleaseGPUTexture(g.device, texture);
+ if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(g.device, texture);
+ if (g.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(g.device, transfer);
+ g.post.deinit(gpa, g.device);
+ g.glide.deinit(gpa);
+ gpa.free(g.scroll_edge);
+ g.presented_images.deinit(gpa);
+ g.prepared_images.deinit(gpa);
+}
+
fn setGuiFontName(g: *Gui, fallback: []const u8) void {
const name = if (c.ui_font_name(g.font)) |name_z| std.mem.span(name_z) else fallback;
const len = @min(name.len, g.font_name.len);
@@ -1893,18 +1970,23 @@ fn setTransitionFields(
}
}
-pub const run = runNative;
+pub fn run(init: std.process.Init, opts: pardes.Options, headless: bool) !void {
+ return runNative(init, opts, headless, null);
+}
+
+/// `pardes-gui --attach=<socket>:<session>` (and `<host>:<session>`,
+/// through ssh, main.zig): this window a replica client of a session
+/// elsewhere, as the tty's `remote` is a terminal's (`remoteSession`).
+pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, session: []const u8, far: bool) !void {
+ return runNative(init, opts, false, .{ .path = path, .session = session, .far = far });
+}
-fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u8) !void {
+const Dial = struct { path: []const u8, session: []const u8, far: bool };
+
+fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, dial: ?Dial) !void {
const gpa = init.gpa;
const env = init.environ_map;
- if (env.get("PARDES_TEST_GRID") != null) {
- if (attach != null) {
- log.err("--attach needs a window; PARDES_TEST_GRID is headless", .{});
- return error.AttachNeedsWindow;
- }
- return runGrid(init, opts_in);
- }
+ if (dial == null and env.get("PARDES_TEST_GRID") != null) return runGrid(init, opts_in);
const test_mode = env.get("PARDES_TEST") != null;
const capture_dir = env.get("PARDES_TEST_CAPTURE_DIR");
@@ -1950,6 +2032,9 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u
// opacity would dim the text as well. SDL requires this flag at creation.
const surface_opacity = native_wayland;
if (surface_opacity) win_flags |= c.SDL_WINDOW_TRANSPARENT;
+ const reopen_flags = win_flags;
+ // `--detach`: a window never shown, closed once the session is up.
+ if (headless) win_flags |= c.SDL_WINDOW_HIDDEN;
// `--geometry=WxH[+X+Y]`, as X11 programs take it.
var want_w: c_int = 1120;
var want_h: c_int = 720;
@@ -1969,7 +2054,8 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u
log.err("SDL_CreateWindow: {s}", .{c.SDL_GetError()});
return error.SdlInit;
};
- defer c.SDL_DestroyWindow(window);
+ var window_slot: ?*c.SDL_Window = window;
+ defer if (window_slot) |open| c.SDL_DestroyWindow(open);
if (want_at) |at| _ = c.SDL_SetWindowPosition(window, at[0], at[1]);
updateDisplayScale(window);
if (native_wayland) log.info("Wayland opacity: background-only transparent surface", .{});
@@ -2173,6 +2259,11 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u
.demo_next = if (env.get("PARDES_FRAMES_DEMO")) |name| (if (pardes.FrameStats.named(name) != null) @as(?usize, 0) else null) else null,
.surface_opacity = surface_opacity,
.soft_renderer = soft_renderer,
+ .win_flags = reopen_flags,
+ .present_mode = present_mode,
+ .window_w = want_w,
+ .window_h = want_h,
+ .window_slot = &window_slot,
};
// The pipelines, textures and buffers the Gui holds, whatever they were
// regrown to; the image ones are released below.
@@ -2221,10 +2312,54 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u
// compositor moves it, as it does a title bar.
if (!test_mode and !c.SDL_SetWindowHitTest(window, hitTest, &g))
log.warn("SDL_SetWindowHitTest: {s}", .{c.SDL_GetError()});
- if (attach) |requested| return attachRequested(gpa, &g, requested);
- var attached: ?detached_client.Client = null;
- try localSession(init, &g, opts_in, test_mode, &attached);
- if (attached) |*client| return attachedLoop(gpa, &g, client);
+ if (dial) |to| return remoteSession(init, &g, opts_in, test_mode, to);
+ try localSession(init, &g, opts_in, test_mode, headless);
+}
+
+/// Detach: the window closed (and with it its swapchain or renderer); the
+/// device, the atlas and the pipelines stay for the next one.
+fn closeWindow(g: *Gui) void {
+ _ = c.SDL_GetWindowSize(g.window, &g.window_w, &g.window_h);
+ _ = c.SDL_StopTextInput(g.window);
+ if (g.soft_renderer) |renderer| {
+ if (g.soft_texture) |texture| c.SDL_DestroyTexture(texture);
+ g.soft_texture = null;
+ g.soft_tex_w = 0;
+ g.soft_tex_h = 0;
+ c.SDL_DestroyRenderer(renderer);
+ g.soft_renderer = null;
+ } else c.SDL_ReleaseWindowFromGPUDevice(g.device, g.window);
+ c.SDL_DestroyWindow(g.window);
+ if (g.window_slot) |slot| if (slot.* == g.window) {
+ slot.* = null;
+ };
+}
+
+/// `pardes-gui --attach`: a window again, as the first was made, at the
+/// size the last one had. False when the display will not give one.
+fn reopenWindow(g: *Gui) bool {
+ const window = c.SDL_CreateWindow("pardes", g.window_w, g.window_h, g.win_flags) orelse return false;
+ if (g.soft_present) {
+ g.soft_renderer = c.SDL_CreateRenderer(window, null) orelse {
+ c.SDL_DestroyWindow(window);
+ return false;
+ };
+ } else {
+ if (!c.SDL_ClaimWindowForGPUDevice(g.device, window)) {
+ c.SDL_DestroyWindow(window);
+ return false;
+ }
+ _ = c.SDL_SetGPUSwapchainParameters(g.device, window, c.SDL_GPU_SWAPCHAINCOMPOSITION_SDR, g.present_mode);
+ }
+ g.window = window;
+ if (g.window_slot) |slot| slot.* = window;
+ updateDisplayScale(window);
+ // ponytail: another view's window asks the hit test of whichever
+ // window's share the Gui holds then (the workspace tag sits in the same
+ // place in every view); a test per window if one moves it.
+ if (!g.capture) _ = c.SDL_SetWindowHitTest(window, hitTest, g);
+ _ = c.SDL_StartTextInput(window);
+ return true;
}
fn localSession(
@@ -2232,7 +2367,7 @@ fn localSession(
g: *Gui,
opts_in: pardes.Options,
test_mode: bool,
- attached: *?detached_client.Client,
+ headless: bool,
) !void {
const io = init.io;
const gpa = init.gpa;
@@ -2261,7 +2396,9 @@ fn localSession(
opts.cols = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(pw, 1))), g.cell_w)));
opts.rows = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(ph, 1))), g.cell_h)));
}
- var core = if (opts.load_path) |lp| blk: {
+ var core = if (upgrade.resumed) |*rec|
+ try upgrade.load(gpa, allocs.pardes, opts, rec)
+ else if (opts.load_path) |lp| blk: {
const bytes = try @import("../fs.zig").readFile(gpa, lp);
defer gpa.free(bytes);
break :blk try pardes.dump.initFromDump(allocs.pardes, opts, bytes);
@@ -2340,8 +2477,18 @@ fn localSession(
frame_capture_dir = if (std.c.getenv("PARDES_FRAMES_CAPTURE")) |dir| std.mem.span(dir) else null;
const host = shell.host();
core.host = host;
+ shell.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake = sdlWake, .alone_unattended = headless };
+ defer shell.peers.deinit();
+ // Before the core goes: each client sees its link end.
+ defer shell.peers.dropAll(shell.core);
while (core.nextEffect()) |e| core.perform(e);
+ // An upgraded session's shells, once a fresh session's own has a
+ // directory to adopt them in.
+ if (upgrade.resumed) |*rec| {
+ shell.resumePtys(rec);
+ while (core.nextEffect()) |e| core.perform(e);
+ }
for (&ptys, 0..) |*slot, id| if (slot.*) |*pt| {
pt.reader = try queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, @intCast(id), gens[id]);
};
@@ -2352,6 +2499,16 @@ fn localSession(
if (fs) |f| try f.watch(&queue, wakeFs);
_ = c.SDL_StartTextInput(g.window);
+ // An upgraded session's views, a window each again.
+ if (upgrade.resumed) |*rec| if (!rec.fresh and !headless) shell.resumeWindows();
+ // PARDES_TEST_VIEWS=N: N more windows from the start, each a view of the
+ // session (views.zig), captured under view-<k>; view 0 live after.
+ if (test_mode and upgrade.resumed == null) if (std.c.getenv("PARDES_TEST_VIEWS")) |n| {
+ for (0..std.fmt.parseInt(u8, std.mem.span(n), 10) catch 0) |_| shell.openAnotherWindow(null);
+ core.toView(0);
+ shell.follow();
+ };
+ defer shell.closeOtherWindows();
if (test_mode) setStdinRaw() catch {};
shell.threads_ok = true;
@@ -2359,26 +2516,28 @@ fn localSession(
defer pardes.lsp.setStatusSink(null, null);
host_io.setExitWake(&queue, Queue.wakeForExit);
defer host_io.setExitWake(null, null);
+ if (headless) {
+ shell.closeTheWindow();
+ // Nothing else may wake the first wait.
+ daemon.watch(&shell, deliverNote);
+ }
while (!core.quit) {
pardes.turn.bump(&pardes.turn.restores);
try core.pump(host);
+ // Its unit to each replica client, and theirs taken in.
+ shell.peers.boundary(core);
+ upgrade.locate();
+ // Asked in the step (the word), done between steps: the session whole.
+ if (shell.upgrade_asked) |pane| shell.upgradeNow(pane);
+ // A window asked for again, or an adopted shell, from the daemon's
+ // thread through the queue; started after the first frame.
+ daemon.watch(&shell, deliverNote);
if (core.quit) break; // a session that ended does not restore into one
- if (core.takeAttach()) |req| {
- const geom = windowCells(g);
- const outcome = detached_client.attempt(gpa, req.name, geom.cols, geom.rows);
- switch (outcome) {
- .greeted => |client| {
- attached.* = client;
- break;
- },
- else => {
- var mbuf: [256]u8 = undefined;
- core.setMessage(req.pane, attachFailure(&mbuf, outcome, req.name));
- },
- }
- }
if (core.takeRestore()) |rp| blk: {
+ // ponytail: a Restore replaces the core its clients replicate;
+ // they are let go, and attach again (as the tty's).
+ shell.peers.dropAll(core);
const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| {
core.reportError(core.active, "Restore", err);
break :blk;
@@ -2390,6 +2549,11 @@ fn localSession(
};
pipe_tasks.cancelAll(io);
queue.discardCompletions();
+ // ponytail: a restored session is one view, the live window's:
+ // the others close.
+ shell.closeOtherWindows();
+ shell.gview = 0;
+ shell.windowed = 1;
shell.stopPtys();
for (0..pardes.MAX_PANES) |wid| file_watch.watchPane(
inotify_fd,
@@ -2426,198 +2590,327 @@ fn localSession(
}
}
-fn attachFailure(buf: []u8, outcome: detached_client.Attempt, requested: []const u8) []const u8 {
- return switch (outcome) {
- .greeted => unreachable,
- .no_session => if (requested.len != 0)
- std.fmt.bufPrint(buf, "Attach: no detached session called '{s}'", .{requested}) catch
- "Attach: no detached session under that name"
- else
- "Attach: nothing is detached (start one with `pardes --detach`)",
- .ambiguous => |n| std.fmt.bufPrint(buf, "Attach: {d} detached sessions; say which one", .{n}) catch
- "Attach: several detached sessions; say which one",
- .refused => |why| switch (why) {
- .version => "Attach: that session speaks a different wire version — it is another build of pardes",
- .full => "Attach: that session already has every frontend slot taken",
- .quitting => "Attach: that session is ending",
- },
- .silent => "Attach: that session took the connection and never greeted us",
- .lost => |err| std.fmt.bufPrint(buf, "Attach: lost the connection ({t})", .{err}) catch
- "Attach: lost the connection",
- };
-}
+/// A window's link to a session elsewhere (`remoteSession`): what the
+/// window's input made, fed to the replica once its own view is put back,
+/// and what the link's reader took off the stream.
+const Client = struct {
+ link: replica.Link,
+ io: std.Io,
+ gpa: std.mem.Allocator,
+ /// The window's inputs since the last feed, their texts in `texts`:
+ /// read over its own view (`Replica.within`), applied after it.
+ pending: std.ArrayListUnmanaged(pardes.Event) = .empty,
+ texts: std.heap.ArenaAllocator,
+ /// The reader's, under `lock`: what it took, and whether the link ended.
+ lock: std.Io.Mutex = .init,
+ inbox: std.ArrayListUnmanaged(replica.Said) = .empty,
+ taken: std.ArrayListUnmanaged(replica.Said) = .empty,
+ ended: bool = false,
-fn attachRequested(gpa: std.mem.Allocator, g: *Gui, requested: []const u8) !void {
- const geom = windowCells(g);
- const outcome = detached_client.attempt(gpa, requested, geom.cols, geom.rows);
- switch (outcome) {
- .greeted => |greeted| {
- var client = greeted;
- return attachedLoop(gpa, g, &client);
- },
- else => {
- var mbuf: [256]u8 = undefined;
- log.err("{s}", .{attachFailure(&mbuf, outcome, requested)});
- return switch (outcome) {
- .no_session => error.NoSession,
- .ambiguous => error.AmbiguousSession,
- .refused => error.Refused,
- .silent => error.NoGreeting,
- .lost => |err| err,
- .greeted => unreachable,
- };
- },
+ fn deinit(cl: *Client) void {
+ cl.pending.deinit(cl.gpa);
+ cl.texts.deinit();
+ cl.inbox.deinit(cl.gpa);
+ cl.taken.deinit(cl.gpa);
}
-}
-fn attachedResize(client: *detached_client.Client, g: *const Gui, cols: u16, rows: u16) !void {
- try client.send(.{ .event = .{ .resize = .{ .cols = cols, .rows = rows, .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),
- } } } });
-}
-
-fn attachedLoop(gpa: std.mem.Allocator, g: *Gui, client: *detached_client.Client) !void {
- defer client.detach();
- _ = c.SDL_StartTextInput(g.window);
+ fn post(cl: *Client, ev: pardes.Event) void {
+ var e = ev;
+ const a = cl.texts.allocator();
+ switch (e) {
+ .key => |*k| k.text = a.dupe(u8, k.text) catch "",
+ .paste, .command => |*b| b.* = a.dupe(u8, b.*) catch return,
+ else => {},
+ }
+ cl.pending.append(cl.gpa, e) catch {};
+ }
- var in: Input = .{ .client = client };
- g.attached_layers = &client.body_layers;
- g.attached_tag_layers = &client.tag_layers;
- var dirty = false;
- var geom = windowCells(g);
- try attachedResize(client, g, geom.cols, geom.rows);
- while (true) {
- const link = client.wait(detached_client.poll_ms);
- while (true) {
- const msg = (try client.next()) orelse break;
- switch (msg) {
- .welcome => {},
- .refuse => |why| {
- log.err("session refused an already-greeted frontend: {t}", .{why});
- return error.Refused;
- },
- .frame => dirty = true,
- .quit => return,
- .detach => return,
- .set_clipboard => |text| putClipboard(gpa, text),
- .read_clipboard => if (takeClipboard()) |text| {
- defer c.SDL_free(text.ptr);
- in.post(.{ .paste = text });
- },
- .open_link => |url| look.openLink(url),
- .post => dirty = true,
- }
+ /// What the window's input made, applied at once and sent.
+ fn feed(cl: *Client) void {
+ for (cl.pending.items) |ev| {
+ const r = cl.link.r;
+ const predicted = r.echo.stats.predicted;
+ cl.link.input(ev);
+ // PARDES_TEST_LATENCY: the input, and whether it shows at once
+ // (applied, or its echo predicted), for the frame that shows it.
+ latencyNote("I {d} {d} {d}\n", .{ r.next_seq - 1, monoNs(), @intFromBool(r.applied == r.pending.items.len or r.echo.stats.predicted > predicted) });
}
- try link;
+ cl.pending.clearRetainingCapacity();
+ _ = cl.texts.reset(.retain_capacity);
+ }
- var sev = std.mem.zeroes(c.SDL_Event);
- while (c.SDL_PollEvent(&sev)) dispatch(g, &in, &sev);
- pollGamepad(g, &in);
- if (in.lost) |err| return err;
- if (in.quit) return;
+ /// The reader's: a message of the stream, for the loop, which it wakes.
+ fn said(cl: *Client, msg: replica.Said) bool {
+ cl.lock.lockUncancelable(cl.io);
+ defer cl.lock.unlock(cl.io);
+ cl.inbox.append(cl.gpa, msg) catch return false;
+ sdlWake(null);
+ return true;
+ }
- const now = windowCells(g);
- if (now.cols != geom.cols or now.rows != geom.rows) {
- geom = now;
- try attachedResize(client, g, now.cols, now.rows);
+ /// What the reader took, in its order, and the link's end after it.
+ fn takeSaid(cl: *Client) void {
+ cl.lock.lockUncancelable(cl.io);
+ std.mem.swap(std.ArrayListUnmanaged(replica.Said), &cl.inbox, &cl.taken);
+ const ended = cl.ended;
+ cl.lock.unlock(cl.io);
+ for (cl.taken.items) |msg| {
+ // PARDES_TEST_LATENCY: when a terminal's delta came (an echo's).
+ if (msg == .screen) latencyNote("S {d}\n", .{monoNs()});
+ cl.link.take(msg);
+ // And after a unit, the first of its own inputs not confirmed.
+ if (msg == .unit) {
+ const r = cl.link.r;
+ latencyNote("U {d} {d}\n", .{ monoNs(), if (r.pending.items.len > 0) r.pending.items[0].seq else r.next_seq });
+ }
}
- // The session's chain, its files compiled there.
- g.post.sync(gpa, g.device, g.swapchain_format, client.post.list(), client.post_key, null);
- if (!dirty) {
- // As a local window does: a chain that moves on its own redraws
- // alone, once a refresh.
- if (g.post.animating(client.post.animation) and g.scene_tex != null and
- c.SDL_GetTicksNS() -| g.post.last_ns + std.time.ns_per_ms >= refreshNs(g)) redrawPost(g, gpa);
- continue;
+ cl.taken.clearRetainingCapacity();
+ if (ended) {
+ cl.link.quit = true;
+ cl.link.gone = true;
}
- dirty = false;
- paintAttached(g, gpa, client);
}
-}
-fn paintAttached(g: *Gui, gpa: std.mem.Allocator, client: *detached_client.Client) void {
- var surface = attachedSurface(client);
- _ = renderFrame(
- g,
- gpa,
- null,
- &surface,
- false,
- ) catch |err| blk: {
- log.err("render: {t}", .{err});
- break :blk false;
- };
+ /// Its own view drawn in the window, outside any step, as the tty's
+ /// client draws its terminal (tty.zig `Remote.draw`): what presenting
+ /// writes in the core (a frame skipped, one owed) is put back.
+ fn draw(cl: *Client, s: *Shell) void {
+ const r = cl.link.r;
+ const core = r.core();
+ const skipped = core.present_skipped;
+ const needs = core.needs_frame;
+ core.frames.mark_start = pardes.FrameStats.nowNs();
+ core.frames.mark_update = core.frames.mark_start;
+ // Its render's end is marked as it presents (`present`).
+ core.frames.mark_render = core.frames.mark_update;
+ r.draw(.{ .ctx = s, .f = present });
+ cl.link.owed = core.present_skipped;
+ core.frames.record(pardes.FrameStats.nowNs(), false, cl.link.owed);
+ core.present_skipped = skipped;
+ core.needs_frame = needs;
+ cl.link.drawn(s.presented);
+ }
+};
+
+/// The session's stream, onto the client's inbox: its units, and its end.
+fn clientReader(cl: *Client, fd: c_int, rest: *replica.Framer) void {
+ replica.readLink(cl.gpa, fd, rest, cl, Client.said);
+ cl.lock.lockUncancelable(cl.io);
+ cl.ended = true;
+ cl.lock.unlock(cl.io);
+ sdlWake(null);
}
-/// The session's frame as a surface: its cells, layers, regions and palette,
-/// so its chrome is drawn from them as a local one's is.
-fn attachedSurface(client: *const detached_client.Client) pardes.Surface {
- var surface: pardes.Surface = .{
- .cols = client.cols,
- .rows = client.rows,
- .cells = client.grid.items,
- .cursor = if (client.cursor) |cu| .{ .x = cu.x, .y = cu.y, .bar = cu.bar } else null,
- .pointer_shape = client.pointer_shape,
- .body_layers = client.body_layers,
- .tag_layers = client.tag_layers,
- .chrome = client.chrome,
+/// What the window does over its own view (`Replica.within`), its inputs
+/// posted to the client (`Input.remote`): an SDL event dispatched, its size
+/// (the tagline's face too), the pointer under a frame that moved, the
+/// timedemo's and the test feed's steps.
+const OwnView = struct {
+ g: *Gui,
+ in: *Input,
+ s: *Shell,
+ sev: ?*const c.SDL_Event = null,
+ pointer: bool = false,
+ eof: bool = false,
+
+ fn run(v: *OwnView, core: *pardes.Pardes) anyerror!void {
+ if (v.sev) |sev| return dispatch(v.g, v.in, sev);
+ const g = v.g;
+ if (fitTaglineFont(g, core.settings.font.tagline_percent)) v.s.remote.?.link.dirty = true;
+ const geom = windowCells(g);
+ if (resizeOf(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) |ev| v.in.post(ev);
+ if (v.pointer) refreshPresentedPointer(g, v.in);
+ runDemo(g, v.in, core);
+ if (v.s.test_mode) {
+ const r = v.s.feed.pump(v.s.gpa, v.in, g) catch return error.TestFeed;
+ if (r.eof) v.eof = true;
+ }
+ }
+};
+
+/// `pardes-gui --attach=<where>:<session>`: the window, made as a session's
+/// is, a replica client of that session (docs/next-daemon.md, "Phase 6: GUI
+/// replica notes"). Its own core, loaded from the session's dump, applies
+/// its input at once (src/replica.zig) and draws its own view; the
+/// session's units are the truth it rolls back to. The tty's `remote`, with
+/// a window for a terminal.
+fn remoteSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_mode: bool, to: Dial) !void {
+ const io = init.io;
+ const gpa = init.gpa;
+ const Said = struct {
+ fn no(o: std.Io, comptime fmt: []const u8, args: anytype) noreturn {
+ var buf: [800]u8 = undefined;
+ std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&buf, "pardes-gui: --attach: " ++ fmt ++ "\n", args) catch "pardes-gui: --attach failed\n") catch {};
+ std.process.exit(1);
+ }
};
- const placed = client.regions.items[0..@min(client.regions.items.len, surface.regions.len)];
- @memcpy(surface.regions[0..placed.len], placed);
- surface.nregions = @intCast(placed.len);
- return surface;
-}
+ var why: [600]u8 = @splat(0);
+ // Far (through ssh, or PARDES_REPLICA_FAR=1): its join's blobs by hash
+ // and its stream in zstd, as the tty's client (replica.zig `Have`).
+ const far = if (init.environ_map.get("PARDES_REPLICA_FAR")) |v| std.mem.eql(u8, v, "1") else to.far;
+ var have_store: replica.Have = if (far) .init(io) else .{ .io = io };
+ defer have_store.deinit();
+ const have: ?*replica.Have = if (far) &have_store else null;
+ var dial_t0 = std.Io.Clock.awake.now(io).nanoseconds;
+ var joined = replica.dial(gpa, to.path, to.session, &why, have, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)});
+ if (joined.semantics != wire.semantics) Said.no(io, "{s}", .{replica.Link.upgrade_words});
-test "an attached frontend draws the session's chrome from its frame alone" {
- const gpa = std.testing.allocator;
- const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 });
- defer core.deinit();
- // A gui-shaped core, whose tags and notices are layers.
- core.update(.{ .resize = .{ .cols = 80, .rows = 24, .row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 } } });
- _ = try core.newShell(1, "");
- try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false));
- core.settings.focus_tint = true;
- try std.testing.expect(core.executeBuiltinLine(0, "Msg a notice with a rule under it"));
- core.sync();
- // Past its slide into place, where its rule shows.
- for (0..30) |_| core.update(.tick);
- const s = try core.render(core.scratch.allocator());
+ const allocs = pardes.memory.init(gpa);
+ defer pardes.memory.deinit();
+ pardes.image.start(io, allocs.image);
+ if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf);
+ pardes.syntax.start(allocs.tree_sitter);
+ defer {
+ pardes.image.stop();
+ if (comptime pardes.pdf_enabled) pardes.pdf.stop();
+ pardes.syntax.stop();
+ }
+ var o = opts_in;
+ o.image_allocator = allocs.image;
+ o.pdf_allocator = allocs.pdf;
+ var r = replica.Link.load(gpa, &joined, o, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)});
+ var dial_ms: u64 = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms));
- const wire = @import("../detached/wire.zig");
- var client: detached_client.Client = .{ .gpa = gpa };
+ var client: Client = .{ .link = .{ .r = r, .fd = joined.fd }, .io = io, .gpa = gpa, .texts = .init(gpa) };
defer client.deinit();
- var welcome: [64]u8 = undefined;
- try client.in.appendSlice(gpa, try wire.encodeServer(&welcome, .{ .welcome = .{ .slot = 0, .cols = s.cols, .rows = s.rows } }));
- const out = try gpa.alloc(u8, wire.frameBound(s.cols, s.rows) + wire.layersBound(&s.body_layers, &s.tag_layers, s.regionList()));
- defer gpa.free(out);
- try client.in.appendSlice(gpa, try wire.encodeFrameLayers(out, s.cols, s.rows, null, s.pointer_shape, s.cells, &.{}, &s.body_layers, &s.tag_layers, s.regionList(), s.chrome));
- _ = try client.next();
- _ = try client.next();
- const attached = attachedSurface(&client);
-
- var g: Gui = undefined;
- g.cell_w = 10;
- g.cell_h = 20;
- g.tagline_width = 6;
- g.tagline_height = 12;
- g.decor = .empty;
- g.glide = .{};
- g.scroll_pane = null;
- g.scroll_lag = 0;
- defer g.decor.deinit(gpa);
- var groups = makeGroups(&.{}, false);
- try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true);
- const local = try gpa.dupe(CellInstance, g.decor.items);
- defer gpa.free(local);
- try std.testing.expect(local.len > 8);
- try std.testing.expect(groups.items[groups.notices].decor_count != 0);
- try buildDecor(&g, gpa, &attached, &groups, fixedCellLayout(&g), 800, 480, true);
- try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(local), std.mem.sliceAsBytes(g.decor.items));
+ const link = &client.link;
+ try link.fromEnv(gpa, init.environ_map);
+ defer link.deinit(gpa);
+ // A client spawns, watches and serves nothing: the Shell's tables are
+ // empty ones, there for what draws.
+ var ptys: [pardes.MAX_PANES]?Pty = @splat(null);
+ var gens: [pardes.MAX_PANES]u32 = @splat(0);
+ var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = allocs.lsp };
+ defer queue.deinit();
+ var pipe_tasks: PipeTasks = .{};
+ var watches: file_watch.Table = @splat(null);
+ const prompt_rcs: host_io.Shell.PromptFiles = .{};
+ var shell: Shell = .{
+ .core = r.core(),
+ .gui = g,
+ .io = io,
+ .gpa = gpa,
+ .lsp_allocator = allocs.lsp,
+ .prompt_rcs = &prompt_rcs,
+ .ptys = &ptys,
+ .gens = &gens,
+ .queue = &queue,
+ .pipe_tasks = &pipe_tasks,
+ .inotify_fd = -1,
+ .watches = &watches,
+ .test_mode = test_mode,
+ .remote = &client,
+ };
+ defer shell.shaders.deinit(gpa, -1, &watches);
+ g.no_blink = test_mode;
+ defer g.hit_core = null;
+ _ = c.SDL_StartTextInput(g.window);
+ if (test_mode) setStdinRaw() catch {};
+ // A join a pass: the first, and one after the replica diverged or the
+ // session let it go to upgrade. The window stays as it is.
+ while (true) {
+ r.gmtoff = joined.gmtoff;
+ const core = r.core();
+ shell.core = core;
+ shell.gview = joined.view;
+ shell.surface = null;
+ g.hit_core = core;
+ frame_probe = &core.frames;
+ link.reset(r, joined.fd);
+ link.joinedAs(&joined, dial_ms);
+ client.ended = false;
+ // ponytail: why it joined again is the window's title (and its
+ // log) until a key, where a terminal's client draws it over its
+ // frame: a window's frame is the core's cells, which it cannot write.
+ var titled = link.notice_len > 0;
+ if (titled) {
+ var title: [260]u8 = undefined;
+ _ = c.SDL_SetWindowTitle(g.window, std.fmt.bufPrintSentinel(&title, "pardes: {s}", .{link.notice()}, 0) catch "pardes");
+ log.warn("{s}", .{link.notice()});
+ }
+ const reader = try std.Thread.spawn(.{}, clientReader, .{ &client, joined.fd, &joined.rest });
+ var in: Input = .{ .core = core, .shell = &shell, .remote = &client };
+ // What it is, then its size, are its view's first inputs.
+ link.input(.{ .frontend = .{ .windowed = true, .native_images = true, .native_image_patches = true } });
+ var drew = false;
+ while (!link.quit) {
+ core.frames.period_ns = refreshNs(g);
+ syncLigatures(g, core);
+ {
+ var passes: [Post.max]ShaderBuild.Pass = undefined;
+ g.post.sync(gpa, g.device, g.swapchain_format, shell.shaders.view(&core.settings.post, &passes), shell.shaders.revision, core);
+ }
+ var own: OwnView = .{ .g = g, .in = &in, .s = &shell, .pointer = drew };
+ r.within(&own, OwnView.run);
+ client.feed();
+ if (own.eof) break;
+ // Its predicted echo judged and caught up, once a frame.
+ if (r.echoFrame()) link.dirty = true;
+ drew = false;
+ if (link.dirty) {
+ client.draw(&shell);
+ drew = shell.presented;
+ }
+ const predicting = r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0;
+ var ms: c_int = if (test_mode) 16 else -1;
+ if (demoDue(g)) |due| ms = if (ms < 0) due else @min(ms, due);
+ if (predicting or link.owed) ms = if (ms < 0) frame_ms else @min(ms, frame_ms);
+ if (link.quietCheck()) |wait| ms = if (ms < 0) @intCast(wait) else @min(ms, @as(c_int, @intCast(wait)));
+ // Idle, its frame drawn: the next input needs no copy taken.
+ if (ms != 0) r.ready();
+ var sev = std.mem.zeroes(c.SDL_Event);
+ g.input_seen = false;
+ var got = c.SDL_WaitEventTimeout(&sev, ms);
+ while (got) : (got = c.SDL_PollEvent(&sev)) {
+ if (sev.type == c.SDL_EVENT_USER) continue;
+ var one: OwnView = .{ .g = g, .in = &in, .s = &shell, .sev = &sev };
+ r.within(&one, OwnView.run);
+ client.feed();
+ if (link.quit) break;
+ }
+ client.takeSaid();
+ r.settle();
+ if (titled and link.notice_len == 0) {
+ titled = false;
+ _ = c.SDL_SetWindowTitle(g.window, "pardes");
+ }
+ if (link.owed or r.echo.changed) link.dirty = true;
+ if (r.diverged != null) link.quit = true;
+ }
+ if (init.environ_map.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file);
+ if (!link.gone) replica.bye(joined.fd, r.diverged != null);
+ // The reader ends with the link: what it took meanwhile is let go.
+ _ = libc.shutdown(joined.fd, 2);
+ reader.join();
+ client.lock.lockUncancelable(io);
+ for (client.inbox.items) |msg| switch (msg) {
+ .unit, .screen, .refused => |b| std.heap.c_allocator.free(b),
+ .checked => {},
+ };
+ client.inbox.clearRetainingCapacity();
+ client.lock.unlock(io);
+ _ = libc.close(joined.fd);
+ joined.rest.deinit(gpa);
+ if (!link.rejoins()) {
+ // What it made since it joined, kept for its next start.
+ if (have) |h| h.keep(r.core());
+ r.deinit();
+ if (link.gone) Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{to.session});
+ return;
+ }
+ // The session again, the core it leaves held meanwhile.
+ if (have) |h| h.leaving(r.core());
+ dial_t0 = std.Io.Clock.awake.now(io).nanoseconds;
+ joined = replica.Link.redial(gpa, to.path, to.session, &why, have, r.diverged == null, joined.view) orelse Said.no(io, "could not join again: {s}", .{std.mem.sliceTo(&why, 0)});
+ if (have) |h| h.left();
+ r.deinit();
+ r = replica.Link.load(gpa, &joined, o, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)});
+ dial_ms = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms));
+ }
}
+const frame_ms: c_int = @intCast(pardes.animation.frame_ns / std.time.ns_per_ms);
+
fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void {
const io = init.io;
const gpa = init.gpa;
@@ -2691,6 +2984,7 @@ fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void {
.inotify_fd = -1,
.watches = &watches,
.fs = fs,
+ .grid = true,
};
defer shell.shutdownPtys();
const host = shell.host();
@@ -2785,6 +3079,24 @@ const StdinFeed = struct {
// A mouse event at 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.
+ // ESC]777;view;<k>BEL: what follows is window k's (k from 1),
+ // as an event of that window's makes its view live (route).
+ const view_prefix = "\x1b]777;view;";
+ if (std.mem.startsWith(u8, f.buf[seq_start..len], view_prefix)) {
+ const body = f.buf[seq_start + view_prefix.len .. len];
+ const end = std.mem.indexOfScalar(u8, body, 0x07) orelse {
+ std.mem.copyForwards(u8, f.buf[0 .. len - seq_start], f.buf[seq_start..len]);
+ f.fill = len - seq_start;
+ break;
+ };
+ const k = std.fmt.parseInt(u8, body[0..end], 10) catch 0;
+ if (in.shell) |sh| if (k >= 1 and pardes.views.isOpen(sh.core, k - 1)) {
+ sh.core.toView(k - 1);
+ sh.follow();
+ };
+ seq_start += view_prefix.len + end + 1;
+ continue;
+ }
const mouse_prefix = "\x1b]777;mouse;";
if (std.mem.startsWith(u8, f.buf[seq_start..len], mouse_prefix)) {
const body = f.buf[seq_start + mouse_prefix.len .. len];
@@ -3125,21 +3437,36 @@ test "the window's function and editing keys reach a terminal as its cursor keys
const Input = struct {
core: ?*pardes.Pardes = null,
- client: ?*detached_client.Client = null,
+ /// The shell whose windows these are: a window closed while others
+ /// stay takes its view with it (views.zig).
+ shell: ?*Shell = null,
+ /// A replica client's (`remote`): its inputs go to its link, never
+ /// straight to the core, which only reads here.
+ remote: ?*Client = null,
quit: bool = false,
- lost: ?anyerror = null,
fn post(in: *Input, ev: pardes.Event) void {
- if (in.core) |core| return core.update(ev);
- const client = in.client orelse return;
- if (in.lost != null) return;
- client.send(.{ .event = ev }) catch |err| switch (err) {
- error.Overlong, error.WriteFailed => {},
- else => in.lost = err,
+ if (in.remote) |r| return r.post(ev);
+ // The window's input is its own view's, a replica client's input
+ // the session's last or not.
+ if (in.shell) |s| if (s.core.view != s.gview) {
+ _ = s.windowView();
};
+ if (in.core) |core| return core.update(ev);
}
fn close(in: *Input) void {
+ if (in.remote) |r| {
+ r.link.quit = true;
+ in.quit = true;
+ return;
+ }
+ if (in.shell) |s| {
+ if (s.windowsOpen() > 1) return s.closeView(s.core.view);
+ // The last window, with replica clients: they keep the session,
+ // as a Detach would, the daemon holding it.
+ if (s.peers.count() > 0 and daemon.kept()) return s.closeTheWindow();
+ }
if (in.core) |core| core.quit = true;
in.quit = true;
}
@@ -3169,15 +3496,24 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void {
updateDisplayScale(g.window);
// Underlines are drawn into the glyphs a logical pixel thick.
resetGlyphAtlas(g);
- if (in.core) |core| core.needs_frame = true;
+ if (in.remote) |r| {
+ r.link.dirty = true;
+ } else if (in.core) |core| core.needs_frame = true;
},
c.SDL_EVENT_WINDOW_FOCUS_GAINED => g.post.focus(true),
c.SDL_EVENT_WINDOW_FOCUS_LOST => g.post.focus(false),
else => {},
}
switch (sev.type) {
- c.SDL_EVENT_QUIT, c.SDL_EVENT_WINDOW_CLOSE_REQUESTED => in.close(),
- c.SDL_EVENT_WINDOW_FOCUS_GAINED => in.post(.{ .focus = true }),
+ c.SDL_EVENT_QUIT => {
+ in.shell = null;
+ in.close();
+ },
+ c.SDL_EVENT_WINDOW_CLOSE_REQUESTED => in.close(),
+ c.SDL_EVENT_WINDOW_FOCUS_GAINED => {
+ in.post(.{ .focus = true });
+ if (in.remote == null) if (in.core) |core| upgrade.noticeNewer(core);
+ },
c.SDL_EVENT_WINDOW_FOCUS_LOST => in.post(.{ .focus = false }),
c.SDL_EVENT_WINDOW_MOUSE_LEAVE => {
g.pointer_present = false;
@@ -3196,8 +3532,14 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void {
const want = std.math.clamp(g.px + step, font_px_min, font_px_max);
if (want != g.px) {
g.px = want;
- refitFont(g, in.core);
- if (in.core) |core| observeGuiFont(g, core);
+ // A client's view is sized by its next loop, as its input.
+ if (in.remote) |r| {
+ refitFont(g, null);
+ r.link.dirty = true;
+ } else {
+ refitFont(g, in.core);
+ if (in.core) |core| observeGuiFont(g, core);
+ }
}
return;
}
@@ -3526,18 +3868,6 @@ fn gridCellAtPixels(g: *const Gui, core: ?*const pardes.Pardes, x: f32, y: f32)
break;
}
};
- if (core == null) if (g.attached_layers) |layers| for (layers) |*layer| {
- if (layer.bodyHit(x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width), @floatFromInt(g.tagline_height))) |body_hit| {
- point.body_hit = body_hit;
- break;
- }
- };
- if (core == null) if (g.attached_tag_layers) |layers| for (layers) |*layer| {
- if (layer.tagHit(x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width), @floatFromInt(g.tagline_height))) |hit| {
- point.tag_hit = hit;
- break;
- }
- };
return point;
}
@@ -3637,6 +3967,18 @@ fn wheelAt(g: *Gui, in: *Input, w: WheelTurn, mc: MouseCell) void {
in.post(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt } });
while (g.program_wheel <= -1) : (g.program_wheel += 1)
in.post(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt } });
+ } else if (in.remote != null) {
+ // ponytail: a replica client's wheel moves the view a
+ // whole row a turn, with no glide and no touchpad's
+ // fraction: its core's clock is the session's, which
+ // moves only as its units come.
+ if (notchOf(w.y, w.integer_y)) |lines| {
+ g.program_wheel = @floatFromInt(lines);
+ } else g.program_wheel = accumulateWheelDelta(g.program_wheel, w.y);
+ while (g.program_wheel >= 1) : (g.program_wheel -= 1)
+ in.post(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = mc.col, .row = mc.row, .shift = true } });
+ while (g.program_wheel <= -1) : (g.program_wheel += 1)
+ in.post(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .shift = true } });
} else {
g.scroll_pane = id;
g.scroll_col = mc.col;
@@ -3727,10 +4069,11 @@ fn heldPointerButton(g: *const Gui) ?pardes.Mouse.Button {
return null;
}
-fn refreshPresentedPointer(g: *Gui, core: *pardes.Pardes) void {
+fn refreshPresentedPointer(g: *Gui, in: *Input) void {
if (!g.pointer_present) return;
+ const core = in.core orelse return;
const mc = mouseCell(g, core, g.pad_x, g.pad_y) orelse {
- if (g.pointer_mapped) core.update(.pointer_leave);
+ if (g.pointer_mapped) in.post(.pointer_leave);
g.pointer_mapped = false;
return;
};
@@ -3740,7 +4083,7 @@ fn refreshPresentedPointer(g: *Gui, core: *pardes.Pardes) void {
g.pointer_cell = mc;
if (!moved) return;
const held = heldPointerButton(g);
- core.update(.{ .mouse = .{
+ in.post(.{ .mouse = .{
.button = held orelse .none,
.kind = if (held != null) .drag else .motion,
.col = mc.col,
@@ -3805,7 +4148,17 @@ fn pollGamepad(g: *Gui, in: *Input) void {
const Shell = struct {
core: *pardes.Pardes,
+ /// The window's, while one is open; null while detached (`parked` has
+ /// it) and in the headless test grid.
gui: ?*Gui = null,
+ parked: ?*Gui = null,
+ /// The headless test grid (runGrid): its own loop, no window ever.
+ grid: bool = false,
+ /// Shells a dead session left (Adopt), each waiting for the spawn of
+ /// the terminal pane made for it.
+ adoptions: [pardes.MAX_PANES]Adoption = undefined,
+ adoptions_len: usize = 0,
+ adopted: usize = 0,
io: std.Io,
gpa: std.mem.Allocator,
fs: ?*ninep_io.Listener = null,
@@ -3837,6 +4190,28 @@ const Shell = struct {
/// The tick a paced frame is sampled at (waitInput): the clock the
/// core is advanced to while anything moves.
paced_ns: ?u64 = null,
+ /// Each other view's window, while another's is in the Gui (views.zig),
+ /// and the view whose window the Gui holds (`follow`).
+ windows: [pardes.views.max]GuiWindow = undefined,
+ gview: u8 = 0,
+ /// Upgrade was asked from this pane, to be done between steps (`upgradeNow`).
+ upgrade_asked: ?u8 = null,
+ /// This window a replica client of a session elsewhere (`remote`).
+ remote: ?*Client = null,
+ /// The session's replica clients (src/replica.zig), on sockets: views
+ /// of their own with no window here (`windowed`).
+ peers: replica.Peers = .{},
+ /// The views that are this process's windows (the rest are clients').
+ windowed: u8 = 1,
+ /// 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 (tty.zig's `mail_only`).
+ mail_only: bool = false,
+ waited: bool = false,
+ /// With replica clients, a wait takes one person's input (tty.zig
+ /// `split`): the next is held for the next wait.
+ took_input: bool = false,
+ held: ?c.SDL_Event = null,
fn reap(s: *Shell) void {
const now = std.Io.Clock.awake.now(s.queue.io).toMilliseconds();
@@ -3863,6 +4238,7 @@ const Shell = struct {
}
_ = libc.close(pt.fd);
pt.fd = -1;
+ daemon.closed(pt.pid);
const now = std.Io.Clock.awake.now(s.queue.io).toMilliseconds();
host_io.reapRetired(&pt.pid, &pt.kill_at, now);
if (pt.pid == 0) {
@@ -3917,7 +4293,302 @@ const Shell = struct {
}
fn host(s: *Shell) pardes.Host {
- return .{ .ctx = s, .vtable = if (s.gui == null) &grid_vtable else &vtable };
+ return .{ .ctx = s, .vtable = if (s.grid) &grid_vtable else &vtable };
+ }
+
+ /// Detach: the window closed, the session left running with no
+ /// window, for `pardes-gui --attach` to open one again.
+ fn detachWindow(ctx: ?*anyopaque) void {
+ const s = shellOf(ctx);
+ // A replica client's: its link ends.
+ if (s.peers.detach(s.core.view)) return;
+ if (s.gui == null) return s.core.reportFailure(s.core.active, "Detach: no window is open");
+ // One of several: its window goes, and the session stays in the rest.
+ if (s.windowsOpen() > 1) return s.closeView(s.core.view);
+ if (!daemon.kept()) return s.core.reportFailure(s.core.active, "Detach: no pardes daemon keeps this session; closing its window ends it");
+ s.closeTheWindow();
+ }
+
+ /// The Gui holds the window of the core's live view.
+ fn follow(s: *Shell) void {
+ const g = s.gui orelse return;
+ const k = s.core.view;
+ if (s.gview == k) return;
+ // A replica client's view has no window here: the Gui keeps the one
+ // it holds (`windowView` puts that view back when it acts).
+ if (s.windowed & (@as(u8, 1) << @intCast(k)) == 0) return;
+ if (s.gview < s.windows.len) copyWindow(&s.windows[s.gview], g);
+ copyWindow(g, &s.windows[k]);
+ s.gview = k;
+ }
+
+ /// An event of another view's window: that view goes live.
+ fn route(s: *Shell, sev: *const c.SDL_Event) void {
+ if (!pardes.views.several(s.core)) return;
+ const g = s.gui orelse return;
+ const w = c.SDL_GetWindowFromEvent(sev) orelse return;
+ // The Gui's window's, while a client's view is live: its own again.
+ if (w == g.window) {
+ _ = s.windowView();
+ return;
+ }
+ for (s.windows, 0..) |win, k| if (k != s.gview and pardes.views.isOpen(s.core, @intCast(k)) and win.window == w) {
+ s.core.toView(@intCast(k));
+ return s.follow();
+ };
+ }
+
+ /// `pardes-gui --attach` while a window is open: another window, a view
+ /// of its own (views.zig), opened as the first was; or (`existing`) an
+ /// upgraded session's view's window again.
+ fn openAnotherWindow(s: *Shell, existing: ?u8) void {
+ const g = s.gui orelse return;
+ s.follow();
+ const k = existing orelse s.core.openView() orelse return log.err("--attach: this session has as many windows as it takes", .{});
+ const live = s.gview;
+ copyWindow(&s.windows[live], g);
+ freshWindow(g);
+ if (!reopenWindow(g)) {
+ log.err("--attach: no window: {s}", .{c.SDL_GetError()});
+ copyWindow(g, &s.windows[live]);
+ return s.core.closeView(k);
+ }
+ if (s.test_mode) {
+ // Its own grid, its captures under view-<k> (PARDES_TEST_VIEWS).
+ // ponytail: the path is kept for the session, a few bytes.
+ const cols: u32 = if (std.c.getenv("PARDES_TEST_COLS")) |v| std.fmt.parseInt(u16, std.mem.span(v), 10) catch 80 else 80;
+ const rows: u32 = if (std.c.getenv("PARDES_TEST_ROWS")) |v| std.fmt.parseInt(u16, std.mem.span(v), 10) catch 24 else 24;
+ _ = c.SDL_SetWindowSize(g.window, @intCast(cols * g.cell_w + g.capture_pad), @intCast(rows * g.cell_h + g.capture_pad));
+ _ = c.SDL_SyncWindow(g.window);
+ g.capture = true;
+ g.capture_dir = std.fmt.allocPrint(s.gpa, "{s}/view-{d}", .{ s.windows[live].capture_dir, k }) catch "";
+ if (g.capture_dir.len > 0) std.Io.Dir.cwd().createDirPath(s.io, g.capture_dir) catch {};
+ }
+ s.gview = k;
+ s.windowed |= @as(u8, 1) << @intCast(k);
+ s.core.toView(k);
+ s.core.needs_frame = true;
+ }
+
+ /// The Gui's window's view live, for what the window does to its own
+ /// (its size, its scroll): a replica client's input may have been the
+ /// last. True when it was not, and is now.
+ fn windowView(s: *Shell) bool {
+ if (s.core.view == s.gview or !pardes.views.isOpen(s.core, s.gview)) return false;
+ s.core.toView(s.gview);
+ return true;
+ }
+
+ /// View `k`'s window closed while others stay: the view goes with it.
+ fn closeView(s: *Shell, k: u8) void {
+ const g = s.gui orelse return;
+ s.core.toView(k);
+ s.follow();
+ closeWindow(g);
+ releaseWindowParts(g, s.gpa);
+ s.gview = std.math.maxInt(u8);
+ s.windowed &= ~(@as(u8, 1) << @intCast(k));
+ s.core.closeView(k);
+ // Into another window's view, if a client's was the one left live.
+ for (0..pardes.views.max) |i| if (s.windowed & (@as(u8, 1) << @intCast(i)) != 0 and pardes.views.isOpen(s.core, @intCast(i))) {
+ if (s.core.view != i) s.core.toView(@intCast(i));
+ break;
+ };
+ s.follow();
+ s.core.needs_frame = true;
+ }
+
+ /// With replica clients, a wait takes one person's input and its pump
+ /// makes one unit of it (tty.zig `split`): whether `sev`, a second, is
+ /// held for the next wait. Any event but a wake is no replica's post.
+ fn split(s: *Shell, sev: *const c.SDL_Event) bool {
+ if (sev.type != c.SDL_EVENT_USER) s.mail_only = false;
+ if (!s.peers.recording) return false;
+ switch (sev.type) {
+ 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, c.SDL_EVENT_PINCH_BEGIN, c.SDL_EVENT_PINCH_UPDATE => {},
+ else => return false,
+ }
+ if (s.took_input) {
+ s.held = sev.*;
+ return true;
+ }
+ s.took_input = true;
+ return false;
+ }
+
+ /// How many of the session's views are windows here.
+ fn windowsOpen(s: *const Shell) usize {
+ return @popCount(s.windowed & s.core.views_open);
+ }
+
+ /// The session's end: every window but the live one closed.
+ fn closeOtherWindows(s: *Shell) void {
+ const g = s.gui orelse return;
+ for (0..s.windows.len) |i| {
+ const k: u8 = @intCast(i);
+ if (k == s.gview or !pardes.views.isOpen(s.core, k)) continue;
+ var live: GuiWindow = undefined;
+ copyWindow(&live, g);
+ copyWindow(g, &s.windows[k]);
+ closeWindow(g);
+ releaseWindowParts(g, s.gpa);
+ copyWindow(g, &live);
+ }
+ }
+
+ fn closeTheWindow(s: *Shell) void {
+ const g = s.gui orelse return;
+ closeWindow(g);
+ s.parked = g;
+ s.gui = null;
+ s.presented = false;
+ s.surface = null;
+ // Its clients look at it still (Peers keeps it attended).
+ s.peers.alone_unattended = true;
+ s.core.unattended = s.peers.count() == 0;
+ daemon.setState(true);
+ }
+
+ fn openTheWindow(s: *Shell) void {
+ const g = s.parked orelse return;
+ if (!reopenWindow(g)) {
+ log.err("--attach: no window: {s}", .{c.SDL_GetError()});
+ return daemon.setState(true);
+ }
+ s.gui = g;
+ s.parked = null;
+ s.peers.alone_unattended = false;
+ s.core.unattended = false;
+ s.core.needs_frame = true;
+ resetScroll(g);
+ daemon.setState(false);
+ }
+
+ fn watched(ctx: ?*anyopaque) bool {
+ return shellOf(ctx).gui != null;
+ }
+
+ fn adopt(ctx: ?*anyopaque, pane: u8) void {
+ const s = shellOf(ctx);
+ if (!daemon.kept()) return s.core.reportFailure(pane, "Adopt: no pardes daemon is keeping shells for this session");
+ s.adopted = 0;
+ daemon.adopt();
+ }
+
+ fn upgradeAsked(ctx: ?*anyopaque, pane: u8) void {
+ const s = shellOf(ctx);
+ if (comptime !upgrade.supported) return s.core.reportFailure(pane, "Upgrade: this system cannot move a session to another build in place");
+ s.upgrade_asked = pane;
+ }
+
+ /// Upgrade, between steps: this process exec'd as the pardes now at the
+ /// path it was started from, the session in its dump and its ptys and
+ /// daemon link kept open across (upgrade.zig); the new process opens
+ /// its windows again. Returns only when it could not be, as it was.
+ fn upgradeNow(s: *Shell, pane: u8) void {
+ s.upgrade_asked = null;
+ const core = s.core;
+ var why: [800]u8 = undefined;
+ const path = upgrade.exe() orelse return core.reportFailure(pane, "Upgrade: this process does not know the path it was started from");
+ // 9P is served while the new binary is asked, and not after.
+ pardes.turn.rest();
+ const checked = upgrade.check(path, &why);
+ pardes.turn.wake();
+ switch (checked) {
+ .no => |w| return core.reportFailure(pane, w),
+ .ok => {},
+ }
+ // Nothing more read from a pty, and what was read goes in: drained,
+ // the readers stopped (a reader waiting for room has it then), and
+ // what they pushed meanwhile drained.
+ s.drainQueue();
+ for (s.ptys) |*slot| if (slot.*) |*pt| if (pt.reader) |*r| {
+ r.cancel(s.queue.io);
+ pt.reader = null;
+ };
+ s.drainQueue();
+ core.settle();
+ // Its replica clients told, their views gone before the dump: each
+ // dials the session again once it is back.
+ s.peers.refuseAll(core, "the session is upgrading to another build of pardes");
+ var rec: upgrade.Record = .{ .link = daemon.link, .window = s.gui != null, .exe = path };
+ for (s.ptys, 0..) |slot, id| if (slot) |pt| if (pt.fd >= 0) rec.addPty(id, pt.pid, pt.fd);
+ var at_buf: [1024:0]u8 = undefined;
+ const failed: []const u8 = failed: {
+ const at = pardes.dump.upgradePath(&at_buf, core.settings.dump_dir.get()) orelse break :failed "Upgrade: no directory for the session's dump; this session stays as it is";
+ const bytes = pardes.dump.dumpBytes(core) catch |err| {
+ var words: [128]u8 = undefined;
+ break :failed std.fmt.bufPrint(&why, "Upgrade: the session would not dump: {s}; it stays as it is", .{pardes.Messages.errorWords(err, &words)}) catch "Upgrade: the session would not dump";
+ };
+ defer s.gpa.free(bytes);
+ if (!upgrade.writeDump(at, bytes)) break :failed std.fmt.bufPrint(&why, "Upgrade: the session's dump could not be written to {s}; it stays as it is", .{at[0..@min(at.len, 600)]}) catch "Upgrade: its dump could not be written";
+ rec.dump = at;
+ rec.old = upgrade.openSelf();
+ daemon.upgraded();
+ if (s.fs) |f| f.flushOut();
+ const err_words = upgrade.exec(s.gpa, path, -1, &rec);
+ // Still here: the exec failed.
+ _ = libc.unlink(at);
+ if (rec.old >= 0) _ = libc.close(rec.old);
+ break :failed std.fmt.bufPrint(&why, "Upgrade: {s} would not start: {s}; this session stays as it is", .{ path[0..@min(path.len, 600)], err_words }) catch "Upgrade: the new pardes would not start";
+ };
+ // As it was: its ptys read on.
+ for (s.ptys, 0..) |*slot, id| if (slot.*) |*pt| if (pt.fd >= 0 and pt.reader == null) {
+ pt.reader = s.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, @intCast(id), s.gens[id]) catch null;
+ };
+ core.reportFailure(pane, failed);
+ }
+
+ /// An upgraded session's shells, running on: each its pane's pty again,
+ /// or, when its dump would not load (`fresh`), adopted as new panes.
+ fn resumePtys(s: *Shell, rec: *const upgrade.Record) void {
+ for (rec.ptys[0..rec.nptys]) |k| {
+ const pane = if (rec.fresh) null else s.core.panes[k.pane];
+ if (pane == null or !pane.?.isTerminal()) {
+ s.adoptShell(k.pid, k.fd);
+ continue;
+ }
+ s.ptys[k.pane] = .{ .fd = k.fd, .pid = k.pid, .serial = pane.?.serial, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } };
+ }
+ }
+
+ /// An upgraded session's views, a window each again: the Gui's is the
+ /// live view's, the others open as `--attach` opens one; a replica
+ /// client's, kept for its rejoin (views.away), none.
+ fn resumeWindows(s: *Shell) void {
+ const live = s.core.view;
+ s.gview = live;
+ for (0..pardes.views.max) |i| {
+ const k: u8 = @intCast(i);
+ if (k != live and pardes.views.isOpen(s.core, k) and !pardes.views.isAway(s.core, k)) s.openAnotherWindow(k);
+ s.windowed |= @as(u8, 1) << @intCast(live);
+ }
+ s.core.toView(live);
+ s.follow();
+ }
+
+ /// One shell of a dead session (`pid` 0: the last of them was told):
+ /// a terminal pane made for it, as the Tty word makes one, whose spawn
+ /// takes this pty (spawnPane).
+ fn adoptShell(s: *Shell, pid: libc.pid_t, fd: c_int) void {
+ const core = s.core;
+ if (pid == 0) {
+ var buf: [96]u8 = undefined;
+ return core.setMessage(core.active, if (s.adopted == 0) "Adopt: no shell of a session that died is waiting" else std.fmt.bufPrint(&buf, "Adopt: {d} shell{s} taken in; what they showed is gone", .{ s.adopted, if (s.adopted == 1) "" else "s" }) catch "Adopt: shells taken in");
+ }
+ if (s.adoptions_len < s.adoptions.len) {
+ s.adoptions[s.adoptions_len] = .{ .pid = pid, .fd = fd, .pane = null };
+ s.adoptions_len += 1;
+ if (core.adoptShell()) |id| {
+ s.adoptions[s.adoptions_len - 1].pane = id;
+ s.adopted += 1;
+ return;
+ }
+ s.adoptions_len -= 1;
+ }
+ _ = libc.close(fd);
+ var buf: [96]u8 = undefined;
+ core.setMessage(core.active, std.fmt.bufPrint(&buf, "Adopt: no room for shell {d}; it ends with this session", .{pid}) catch "Adopt: no room for a shell");
}
const vtable: pardes.Host.VTable = .{
@@ -3926,6 +4597,10 @@ const Shell = struct {
.present = present,
.post_present = postPresent,
.poll_frame = pollFrame,
+ .watched = watched,
+ .detach = detachWindow,
+ .adopt = adopt,
+ .upgrade = upgradeAsked,
.spawn = spawnPane,
.pty_write = ptyWrite,
.pty_resize = ptyResize,
@@ -3957,6 +4632,10 @@ const Shell = struct {
v.post_present = gridPostPresent;
v.set_clipboard = null;
v.read_clipboard = null;
+ v.watched = null;
+ v.detach = null;
+ v.adopt = null;
+ v.upgrade = null;
break :vt v;
};
@@ -3976,6 +4655,7 @@ const Shell = struct {
defer s.takeExits();
s.queue.takeInto(&s.batch);
const msgs = &s.batch;
+ if (msgs.len > 0) s.mail_only = false;
var check_files = false;
for (msgs.slice()) |m| switch (m) {
.output => |o| {
@@ -3988,10 +4668,7 @@ const Shell = struct {
if (s.gens[e.pane] == e.gen) eof: {
if (e.failure) |err| {
s.closePty(e.pane);
- if (s.core.panes[e.pane]) |pane| {
- pane.body.mode = .normal;
- s.core.reportError(e.pane, "terminal reader", err);
- }
+ s.core.readerFailed(e.pane, err);
break :eof;
}
const pt = if (s.ptys[e.pane]) |*pt| pt else {
@@ -4051,6 +4728,14 @@ const Shell = struct {
},
.files_changed => check_files = true,
.fs_ready => {},
+ .window => {
+ if (s.gui != null) s.openAnotherWindow(null) else s.openTheWindow();
+ s.saw_event = true;
+ },
+ .adopted => |a| {
+ s.adoptShell(a.pid, a.fd);
+ s.saw_event = true;
+ },
};
if (check_files) s.shaders.recheck();
if (check_files and file_watch.reloadChanged(s.core, s.io, s.gpa, s.watches))
@@ -4077,7 +4762,11 @@ fn shellOf(ctx: ?*anyopaque) *Shell {
fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void {
const s = shellOf(ctx);
const core = s.core;
- var in: Input = .{ .core = core };
+ var in: Input = .{ .core = core, .shell = s };
+ s.follow();
+ s.mail_only = true;
+ s.took_input = false;
+ defer s.waited = true;
if (s.gui) |g| {
var sev = std.mem.zeroes(c.SDL_Event);
// Idle is asleep until an event: SDL's own, and the user events the
@@ -4139,9 +4828,13 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void {
ms = 0;
}
g.input_seen = false;
+ // An input held from the last wait (`split`) is this one's, at once.
+ const held = s.held;
+ s.held = null;
+ if (held) |h| sev = h;
// The wait is the 9P connections' turn with the core.
pardes.turn.rest();
- const got = c.SDL_WaitEventTimeout(&sev, ms);
+ const got = held != null or c.SDL_WaitEventTimeout(&sev, ms);
pardes.turn.wake();
// A virtual clock: while a render-time animation moves, each loop
// is a presented frame and moves it by one display frame
@@ -4169,16 +4862,28 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void {
// each would repeat hover and selection work the next undoes.
var motion: ?c.SDL_Event = null;
while (true) {
- if (sev.type == c.SDL_EVENT_MOUSE_MOTION) {
+ 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| dispatch(g, &in, m);
+ if (motion) |*m| {
+ s.route(m);
+ dispatch(g, &in, m);
+ }
motion = null;
- dispatch(g, &in, &sev);
+ if (sev.type == c.SDL_EVENT_MOUSE_MOTION) {
+ motion = sev;
+ } else {
+ s.route(&sev);
+ dispatch(g, &in, &sev);
+ }
}
if (!c.SDL_PollEvent(&sev)) break;
}
- if (motion) |*m| dispatch(g, &in, m);
+ if (motion) |*m| {
+ s.route(m);
+ dispatch(g, &in, m);
+ }
}
runDemo(g, &in, core);
// Paced: what came before the tick is in; wait out the rest of it,
@@ -4196,14 +4901,21 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void {
// 1.9 ms spinning against 7-8 ms asleep (docs/next-anim.md).
// ponytail: a core while something moves (~250 ms a scroll); a
// sleep to a millisecond short of the tick if the power matters more.
- while (paced and !g.input_seen) {
+ while (paced and !g.input_seen and s.held == null) {
if (tick -| c.SDL_GetTicksNS() < 50 * std.time.ns_per_us) break;
pardes.turn.rest();
const more = c.SDL_PollEvent(&sev);
pardes.turn.wake();
if (more) {
- dispatch(g, &in, &sev);
- while (c.SDL_PollEvent(&sev)) dispatch(g, &in, &sev);
+ if (!s.split(&sev)) {
+ s.route(&sev);
+ dispatch(g, &in, &sev);
+ while (c.SDL_PollEvent(&sev)) {
+ if (s.split(&sev)) break;
+ s.route(&sev);
+ dispatch(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;
@@ -4214,7 +4926,7 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void {
}
s.paced_ns = if (paced) tick else null;
if (paced) g.pace_ns = tick;
- }
+ } else waitDetached(core, timeout_ms);
if (s.test_mode) {
const r = s.feed.pump(s.gpa, &in, s.gui) catch {
core.quit = true;
@@ -4229,8 +4941,28 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void {
if (s.gui) |g| pollGamepad(g, &in);
}
+/// Detached: no window, asleep until the queue's wake (an SDL user event:
+/// a pty's output, the daemon's window request), the core's next wake, or a
+/// quit (SDL makes SIGTERM and SIGINT one). With nobody to dismiss them,
+/// messages go on the clock (the pump's, after this wait), which wakes it.
+fn waitDetached(core: *pardes.Pardes, timeout_ms: u32) void {
+ var ms: c_int = if (timeout_ms != 0) @intCast(@min(timeout_ms, std.math.maxInt(c_int))) else -1;
+ for (core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) {
+ ms = if (ms < 0) 100 else @min(ms, 100);
+ break;
+ };
+ var sev = std.mem.zeroes(c.SDL_Event);
+ pardes.turn.rest();
+ var got = c.SDL_WaitEventTimeout(&sev, ms);
+ pardes.turn.wake();
+ while (got) : (got = c.SDL_PollEvent(&sev)) {
+ if (sev.type == c.SDL_EVENT_QUIT) core.quit = true;
+ }
+}
+
fn pollFrame(ctx: ?*anyopaque) void {
const s = shellOf(ctx);
+ s.follow();
s.reconcilePtys();
const core = s.core;
if (s.fs) |f| if (f.tick().pending) s.queue.push(.fs_ready);
@@ -4241,6 +4973,16 @@ 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).
+ if (core.view != s.gview) {
+ const geom = windowCells(g);
+ const own = if (core.parked[s.gview]) |slot| &slot.view else null;
+ 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
+ (own != null and resizeOf(own.?, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height) != null);
+ if (due) _ = s.windowView();
+ }
syncWindowOpacity(g, core);
core.frames.period_ns = refreshNs(g);
syncTaglineFont(g, core);
@@ -4411,16 +5153,8 @@ fn refreshNs(g: *const Gui) u64 {
}
fn finishWindowOpacity(core: *pardes.Pardes, applied: *u8, failure: ?[]const u8) void {
- core.settings.window_opacity_pending = false;
- if (failure) |reason| {
- // Do not claim a value the compositor refused; an explicit retry of
- // the same command will arm a new request.
- core.settings.window_opacity = applied.*;
- var buf: [256]u8 = undefined;
- core.setMessage(core.active, std.fmt.bufPrint(&buf, "WindowOpacity: {s}", .{reason[0..@min(reason.len, 240)]}) catch "WindowOpacity: compositor rejected the request");
- } else {
- applied.* = core.settings.window_opacity;
- }
+ core.windowOpacityDone(applied.*, failure);
+ applied.* = core.settings.window_opacity;
}
fn syncWindowOpacity(g: *Gui, core: *pardes.Pardes) void {
@@ -4463,6 +5197,9 @@ test "background opacity acknowledges success and rolls back unsupported surface
fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void {
const s = shellOf(ctx);
const core = s.core;
+ // A replica client draws outside the pump, which marks it there.
+ if (s.remote != null) core.frames.mark_render = pardes.FrameStats.nowNs();
+ s.follow();
const g = s.gui orelse return;
frame_started_ns = monoNs();
const frame = @constCast(surface);
@@ -4488,7 +5225,9 @@ fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void {
g.scene_failures +|= 1;
log.err("scene target unavailable (attempt {d}/3)", .{g.scene_failures});
if (g.scene_failures >= 3) {
- core.disableSceneEffects();
+ // ponytail: a client's window keeps asking (its core is the
+ // session's to change).
+ if (s.remote == null) core.disableSceneEffects();
g.scene_failures = 0;
}
} else if (scene_requested and s.presented) g.scene_failures = 0;
@@ -4496,17 +5235,26 @@ fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void {
fn postPresent(ctx: ?*anyopaque) void {
const s = shellOf(ctx);
+ s.follow();
const g = s.gui orelse return;
// No image (a minimized window) shows no tracks; time still passes and
// the pump advances it all the same.
if (!s.presented) return;
const frame = s.surface orelse return;
- refreshPresentedPointer(g, s.core);
+ // A client's view live: the window's frame is acknowledged when its
+ // own view is live and drawn.
+ if (s.core.view != s.gview) return;
+ var in: Input = .{ .core = s.core };
+ refreshPresentedPointer(g, &in);
s.core.acknowledgePanelPresentation(frame.panelTracks());
}
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.now_ns;
+ }
return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS();
}
@@ -4545,6 +5293,11 @@ fn gridPostPresent(ctx: ?*anyopaque) void {
fn spawnPane(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void {
const s = shellOf(ctx);
s.reap();
+ for (s.adoptions[0..s.adoptions_len], 0..) |a, i| if (a.pane == pane) {
+ std.mem.copyForwards(Adoption, s.adoptions[i .. s.adoptions_len - 1], s.adoptions[i + 1 .. s.adoptions_len]);
+ s.adoptions_len -= 1;
+ return takeShell(s, pane, a);
+ };
// The new shell starts before a running one goes: one that cannot
// start leaves the running one be (pty/ctl's exec).
const running = s.ptys[pane] != null;
@@ -4571,6 +5324,49 @@ fn spawnPane(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void {
};
}
+const Adoption = struct { pid: libc.pid_t, fd: c_int, pane: ?u8 };
+
+/// An adopted shell, running already, as pane `pane`'s: told the size twice
+/// (one it never had, then the pane's), which makes it redraw.
+fn takeShell(s: *Shell, pane: u8, a: Adoption) void {
+ s.closePty(pane);
+ s.gens[pane] +%= 1;
+ s.ptys[pane] = .{ .fd = a.fd, .pid = a.pid, .serial = s.core.panes[pane].?.serial, .cmd = .{} };
+ var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
+ s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid));
+ var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
+ if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd);
+ const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 };
+ _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny));
+ if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1));
+ if (!s.threads_ok) return;
+ s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = a.fd, .flags = .{ .nonblocking = false } }, pane, s.gens[pane]) catch |err| {
+ s.closePty(pane);
+ return s.core.reportError(pane, "terminal reader", err);
+ };
+}
+
+/// The daemon's thread: what it says, onto the queue (drainQueue).
+fn deliverNote(ctx: *anyopaque, note: daemon.Note) void {
+ const s: *Shell = @ptrCast(@alignCast(ctx));
+ const q = s.queue;
+ switch (note) {
+ .attach => |a| {
+ // A terminal for a window session: the daemon refuses that kind
+ // before it is sent, so only an old one's would be here.
+ if (a.tty >= 0) _ = libc.close(a.tty);
+ if (a.stub >= 0) daemon.refuseStub(a.stub, "a window session takes no terminal");
+ if (a.tty < 0) q.push(.window);
+ },
+ .adopted => |a| {
+ for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| q.push(.{ .adopted = .{ .pid = pid, .fd = fd } });
+ q.push(.{ .adopted = .{ .pid = 0, .fd = -1 } });
+ },
+ // Joined at the next step boundary (Peers, any thread).
+ .replica => |j| s.peers.handed(j.fd, j.view),
+ }
+}
+
fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void {
const s = shellOf(ctx);
if (s.ptys[pane]) |pt| if (pt.fd >= 0) {
@@ -4704,6 +5500,7 @@ test "the headless grid host round-trips a yank back as a paste" {
.pipe_tasks = &pipe_tasks,
.inotify_fd = -1,
.watches = &watches,
+ .grid = true,
};
core.host = shell.host();
try std.testing.expect(core.host.vtable == &Shell.grid_vtable);
@@ -7654,8 +8451,14 @@ fn syncLigatures(g: *Gui, core: *pardes.Pardes) void {
}
fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void {
- const percent = core.settings.font.tagline_percent;
- if (percent == g.tagline_percent) return;
+ 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;
g.tagline_percent = percent;
const tagline = taglineRaster(g.font, g.px, g.cell_w, g.cell_h, percent);
g.tagline_px = tagline.px;
@@ -7663,8 +8466,7 @@ fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void {
g.tagline_baseline = tagline.baseline;
g.tagline_height = tagline.height;
resetGlyphAtlas(g);
- const geom = windowCells(g);
- _ = updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height);
+ return true;
}
/// What text draws, so a frame does not work it out again. `cells` is the
@@ -9400,7 +10202,9 @@ fn rulePx(chrome: *const pardes.Chrome) f32 {
/// by which every size given in logical pixels is drawn, as acme scales its
/// Border, ButtonBorder and Scrollgap (scalesize). Cells, glyphs and what is
/// measured in them are already the display's pixels and are not scaled.
-/// ponytail: one window per process, so one global; per window if ever two.
+/// ponytail: one per process: a session's windows (views.zig) on screens
+/// of two densities draw at the density of the last one opened or moved;
+/// a field of `window_fields` when that matters.
var display_scale: f32 = 1;
/// The window's display scale, or PARDES_TEST_SCALE (a harness forcing 2x);