diff options
Diffstat (limited to 'src/macos.zig')
| -rw-r--r-- | src/macos.zig | 955 |
1 files changed, 424 insertions, 531 deletions
diff --git a/src/macos.zig b/src/macos.zig index d263cfc6..8d372432 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -6,15 +6,19 @@ const builtin = @import("builtin"); const posix = std.posix; const libc = std.c; const pardes = @import("pardes.zig"); +const dump = @import("dump.zig"); +const mouse = @import("mouse.zig"); +const colors = @import("colors.zig"); const look = @import("look.zig"); -const message = pardes.Pardes.Message; +const message = pardes.Messages.Message; const layout = @import("layout.zig"); +const animation = @import("animation.zig"); const file_watch = @import("file_watch.zig"); const image = if (pardes.pdf_enabled) @import("image.zig") else struct {}; const host_io = @import("host_io.zig"); const fonts = @import("fonts.zig"); // the shared fallback preference order const tracy = @import("tracy.zig"); // no-op unless -Dtracy names a checkout -const selection_pipe = @import("selection_pipe.zig"); // Job, runJob and Tasks +const selection_pipe = @import("selection_pipe.zig"); // start, Response and Tasks const crash = @import("crash.zig"); pub const panic = std.debug.FullPanic(struct { @@ -40,7 +44,11 @@ fn hostWatchFile(pane: u8, generation: u32, path: ?[*]const u8, path_len: usize) const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); -pub const std_options: std.Options = .{ .logFn = logFn }; +// Every thread's alternate signal stack is a threadlocal that libc zeroes as +// the thread starts, so std's 256 KiB made each 9P connection's thread cost +// that much resident. A stack-overflow segfault on a thread still printed its +// whole symbolized trace from 32 KiB up (16 KiB double-faulted): 64 KiB. +pub const std_options: std.Options = .{ .logFn = logFn, .signal_stack_size = 64 * 1024 }; fn logFn( comptime level: std.log.Level, @@ -69,8 +77,8 @@ pub const Scene = extern struct { frame: u32 = 0, }; -pub const PanelBox = layout.Box; -pub const PanelTrack = layout.Track; +pub const PanelBox = animation.Box; +pub const PanelTrack = animation.Track; pub const Image = extern struct { serial: u32, @@ -108,13 +116,11 @@ const cell_flag_default: u8 = 1; const cell_flag_tagline: u8 = 2; const cell_flag_hover: u8 = 4; const scene_flag_crt: u32 = 1 << 0; -const scene_flag_ripple: u32 = 1 << 1; -const scene_flag_glitch: u32 = 1 << 2; const scene_frame_hz: u32 = 60; const scene_wrap_ns: u64 = 4096 * std.time.ns_per_s; -const max_tick_catch_up_ns: u64 = 4 * pardes.layout.Animation.frame_ns; +const max_tick_catch_up_ns: u64 = 4 * pardes.animation.frame_ns; const theme_watch_pane: u8 = @intCast(pardes.MAX_PANES); const watch_slot_count = pardes.MAX_PANES + 1; @@ -122,9 +128,31 @@ const Pty = struct { file: std.Io.File, pid: posix.pid_t, gen: u32, - reader: std.Io.Future(anyerror!void), + reader: std.Io.Future(void), + /// A command pane's child, watched to its exit (host_io.watchExit); + /// the pty stays open until both its end of file and its exit. + cmd: host_io.CommandWatch = .{}, }; +/// A watched child exited: wake the host, which takes it (`takeExits`). +/// Called on a watcher thread holding host_io's exit lock, which +/// pardes_deinit takes to clear the wake: safe only because the runtime's +/// wakeup never waits for the main thread (AppDelegate's is a +/// DispatchQueue.main.async); one that did would deadlock the quit. +fn wakeForExit(ctx: ?*anyopaque) void { + const st: *State = @ptrCast(@alignCast(ctx orelse return)); + wake(st); +} + +/// The command panes' exits, told once their output is in (host_io). +fn takeExits(st: *State) void { + host_io.takeExits(st.core, &st.ptys, st, closeWatched); +} + +fn closeWatched(st: *State, id: usize) void { + reap(st, @intCast(id)); +} + const WatchedFile = struct { path: []u8, serial: u32, @@ -281,22 +309,26 @@ test "mac queued results never cancel a newer LSP request" { .runtime = .{}, .config_arena = .init(gpa), .prompt_rcs = .{}, + .inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = std.testing.io }, }; defer st.config_arena.deinit(); - defer st.inbox.close(gpa, std.testing.io); + defer st.inbox.close(); core.lspRequest(0, .status, ""); const old_id = core.lsp_wait.?.id; core.lspRequest(0, .status, ""); const current_id = core.lsp_wait.?.id; - st.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } }; - st.inbox.push(gpa, std.testing.io, .{ .lsp_done = .{ .id = old_id, .rows = try gpa.dupe(u8, "stale result\n") } }); - try std.testing.expect(drainInbox(&st)); - try std.testing.expect(st.lsp_task != null); - try std.testing.expectEqual(current_id, st.lsp_task.?.id); + st.inbox.lsp_id = current_id; + st.inbox.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } }; + // The inbox turns the superseded answer away. + st.inbox.push(.{ .lsp = .{ .id = old_id, .rows = try gpa.dupe(u8, "stale result\n") } }); + try std.testing.expectEqual(@as(usize, 0), st.inbox.completion_len); + _ = drainInbox(&st); + try std.testing.expect(st.inbox.lsp_task != null); + try std.testing.expectEqual(current_id, st.inbox.lsp_task.?.id); try std.testing.expectEqual(current_id, core.lsp_wait.?.id); - st.inbox.push(gpa, std.testing.io, .{ .lsp_done = .{ .id = current_id, .rows = try gpa.dupe(u8, "") } }); + st.inbox.push(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "") } }); try std.testing.expect(drainInbox(&st)); - try std.testing.expect(st.lsp_task == null); + try std.testing.expect(st.inbox.lsp_task == null); try std.testing.expect(core.lsp_wait == null); } @@ -320,9 +352,10 @@ test "mac worker setup failures finish matching LSP and pipe requests" { .runtime = .{}, .config_arena = .init(gpa), .prompt_rcs = .{}, + .inbox = .{ .gpa = failing.allocator(), .lsp_allocator = failing.allocator(), .io = failing_io }, }; defer st.config_arena.deinit(); - defer st.inbox.close(gpa, std.testing.io); + defer st.inbox.close(); core.lspRequest(core.active, .status, ""); const req: host_io.Lsp.Request = .{ .id = core.lsp_wait.?.id, @@ -335,16 +368,16 @@ test "mac worker setup failures finish matching LSP and pipe requests" { try std.testing.expect(core.lsp_wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; core.update(.{ .key = .{ .cp = '|' } }); core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); core.update(.{ .key = .{ .cp = pardes.Key.enter } }); - const pipe_id = core.pipe_wait.?.id; + const pipe_id = core.pipe.wait.?.id; pipeRequest(&st, pipe_id); - try std.testing.expect(core.pipe_wait == null); + try std.testing.expect(core.pipe.wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expect(st.lsp_task == null); + try std.testing.expect(st.inbox.lsp_task == null); try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); } } @@ -372,264 +405,8 @@ test "mac host watcher covers file and directory vnode events, debounce, and gen ) != null); } -const Msg = union(enum) { - output: struct { pane: u8, gen: u32, bytes: []u8 }, - eof: struct { pane: u8, gen: u32 }, - lsp_done: struct { id: u32, rows: ?[]u8 }, - lsp_status: []u8, - pipe: selection_pipe.Response, - - fn free(m: Msg, gpa: std.mem.Allocator) void { - switch (m) { - .output => |o| gpa.free(o.bytes), - .eof => {}, - .lsp_done => |d| if (d.rows) |rows| gpa.free(rows), - .lsp_status => |t| gpa.free(t), - .pipe => |r| { - var response = r; - response.deinit(gpa); - }, - } - } -}; - -const inbox_capacity = 512; -const inbox_output_limit = inbox_capacity - pardes.MAX_PANES - selection_pipe.Tasks.capacity - 2; - -const MessageBatch = struct { - items: [inbox_capacity]Msg = undefined, - len: usize = 0, - - fn slice(batch: *MessageBatch) []Msg { - return batch.items[0..batch.len]; - } -}; - -const Inbox = struct { - mutex: std.Io.Mutex = .init, - space: std.Io.Condition = .init, - items: [inbox_capacity]Msg = undefined, - len: usize = 0, - closed: bool = false, - wake_pending: std.atomic.Value(bool) = .init(false), - - fn removeAt(q: *Inbox, offset: usize) Msg { - const removed = q.items[offset]; - std.mem.copyForwards(Msg, q.items[offset .. q.len - 1], q.items[offset + 1 .. q.len]); - q.len -= 1; - return removed; - } - - fn pushOutput(q: *Inbox, gpa: std.mem.Allocator, io: std.Io, output: @FieldType(Msg, "output")) std.Io.Cancelable!void { - errdefer gpa.free(output.bytes); - q.mutex.lockUncancelable(io); - defer q.mutex.unlock(io); - while (q.len >= inbox_output_limit and !q.closed) try q.space.wait(io, &q.mutex); - if (q.closed) return error.Canceled; - q.items[q.len] = .{ .output = output }; - q.len += 1; - } - - fn push(q: *Inbox, gpa: std.mem.Allocator, io: std.Io, m: Msg) void { - std.debug.assert(m != .output); - q.mutex.lockUncancelable(io); - defer q.mutex.unlock(io); - if (q.closed) { - m.free(gpa); - return; - } - if (m != .pipe) { - var offset: usize = 0; - while (offset < q.len) : (offset += 1) { - const old = q.items[offset]; - const replaced = switch (m) { - .eof => |end| old == .eof and old.eof.pane == end.pane, - .lsp_done => old == .lsp_done, - .lsp_status => old == .lsp_status, - .output, .pipe => unreachable, - }; - if (replaced) { - q.removeAt(offset).free(gpa); - break; - } - } - } - std.debug.assert(q.len < q.items.len); - q.items[q.len] = m; - q.len += 1; - } - - fn take(q: *Inbox, io: std.Io) MessageBatch { - q.mutex.lockUncancelable(io); - defer q.mutex.unlock(io); - var batch: MessageBatch = .{ .len = q.len }; - @memcpy(batch.items[0..q.len], q.items[0..q.len]); - q.len = 0; - q.space.broadcast(io); - return batch; - } - - fn close(q: *Inbox, gpa: std.mem.Allocator, io: std.Io) void { - q.mutex.lockUncancelable(io); - defer q.mutex.unlock(io); - q.closed = true; - for (q.items[0..q.len]) |msg| msg.free(gpa); - q.len = 0; - q.space.broadcast(io); - } -}; - -test "mac inbox coalesces completions at the tail without reordering terminal output" { - const gpa = std.testing.allocator; - var inbox: Inbox = .{}; - defer inbox.close(gpa, std.testing.io); - inbox.push(gpa, std.testing.io, .{ .lsp_done = .{ .id = std.math.maxInt(u32), .rows = try gpa.dupe(u8, "old result") } }); - inbox.push(gpa, std.testing.io, .{ .lsp_status = try gpa.dupe(u8, "old status") }); - try inbox.pushOutput(gpa, std.testing.io, .{ .pane = 0, .gen = std.math.maxInt(u32), .bytes = try gpa.dupe(u8, "old output") }); - inbox.push(gpa, std.testing.io, .{ .eof = .{ .pane = 0, .gen = std.math.maxInt(u32) } }); - try inbox.pushOutput(gpa, std.testing.io, .{ .pane = 0, .gen = 0, .bytes = try gpa.dupe(u8, "new output") }); - inbox.push(gpa, std.testing.io, .{ .eof = .{ .pane = 0, .gen = 0 } }); - inbox.push(gpa, std.testing.io, .{ .lsp_done = .{ .id = 0, .rows = try gpa.dupe(u8, "new result") } }); - inbox.push(gpa, std.testing.io, .{ .lsp_status = try gpa.dupe(u8, "new status") }); - var batch = inbox.take(std.testing.io); - defer for (batch.slice()) |msg| msg.free(gpa); - try std.testing.expectEqual(@as(usize, 5), batch.len); - try std.testing.expectEqualStrings("old output", batch.items[0].output.bytes); - try std.testing.expectEqualStrings("new output", batch.items[1].output.bytes); - try std.testing.expectEqual(@as(u32, 0), batch.items[2].eof.gen); - try std.testing.expectEqual(@as(u32, 0), batch.items[3].lsp_done.id); - try std.testing.expectEqualStrings("new result", batch.items[3].lsp_done.rows.?); - try std.testing.expectEqualStrings("new status", batch.items[4].lsp_status); - inbox.close(gpa, std.testing.io); - inbox.push(gpa, std.testing.io, .{ .lsp_done = .{ .id = 1, .rows = try gpa.dupe(u8, "closed") } }); - try std.testing.expectEqual(@as(usize, 0), inbox.len); -} - -test "mac inbox admits every retained task completion when output fills the queue" { - const gpa = std.testing.allocator; - var inbox: Inbox = .{}; - defer inbox.close(gpa, std.testing.io); - var tasks: selection_pipe.Tasks = .{}; - defer tasks.cancelAll(std.testing.io); - for (0..inbox_output_limit) |_| try inbox.pushOutput(gpa, std.testing.io, .{ - .pane = 0, - .gen = 1, - .bytes = try gpa.dupe(u8, "output"), - }); - for (0..pardes.MAX_PANES) |pane| inbox.push(gpa, std.testing.io, .{ .eof = .{ .pane = @intCast(pane), .gen = 1 } }); - inbox.push(gpa, std.testing.io, .{ .lsp_done = .{ .id = 1, .rows = try gpa.dupe(u8, "result") } }); - for (0..selection_pipe.Tasks.capacity) |index| { - const id: u32 = @intCast(index); - try std.testing.expect(tasks.add(.{ .id = id, .future = .{ .any_future = null, .result = {} } })); - if (index == 0) { - const output = try gpa.dupe(u8, "filtered"); - const outputs = gpa.dupe([]u8, &.{output}) catch |err| { - gpa.free(output); - return err; - }; - inbox.push(gpa, std.testing.io, .{ .pipe = .{ .id = id, .success = true, .outputs = outputs } }); - } else inbox.push(gpa, std.testing.io, .{ .pipe = .{ - .id = id, - .success = false, - .outputs = &.{}, - .failure = .{ .kind = .exit, .code = 1, .stderr = try gpa.dupe(u8, "no match") }, - } }); - } - inbox.push(gpa, std.testing.io, .{ .lsp_status = try gpa.dupe(u8, "current status") }); - try std.testing.expectEqual(inbox_capacity, inbox.len); - var batch = inbox.take(std.testing.io); - defer for (batch.slice()) |msg| msg.free(gpa); - var eof_count: usize = 0; - var lsp_count: usize = 0; - var pipe_count: usize = 0; - var output_count: usize = 0; - for (batch.slice()) |msg| switch (msg) { - .eof => eof_count += 1, - .lsp_done => lsp_count += 1, - .pipe => |result| { - pipe_count += 1; - tasks.finish(std.testing.io, result.id); - }, - .output => |output| { - output_count += 1; - try std.testing.expectEqualStrings("output", output.bytes); - }, - .lsp_status => |status| try std.testing.expectEqualStrings("current status", status), - }; - try std.testing.expectEqual(pardes.MAX_PANES, eof_count); - try std.testing.expectEqual(@as(usize, 1), lsp_count); - try std.testing.expectEqual(selection_pipe.Tasks.capacity, pipe_count); - try std.testing.expectEqual(inbox_output_limit, output_count); - try std.testing.expectEqual(@as(usize, 0), tasks.len); -} - -test "mac inbox preserves output under backpressure and wakes on take cancel and close" { - const gpa = std.testing.allocator; - const io = std.testing.io; - const Producer = struct { - fn run(q: *Inbox, done: *std.Io.Event) !void { - defer done.set(std.testing.io); - defer q.push(std.testing.allocator, std.testing.io, .{ .eof = .{ .pane = 0, .gen = 1 } }); - try q.pushOutput(std.testing.allocator, std.testing.io, .{ - .pane = 0, - .gen = 1, - .bytes = try std.testing.allocator.dupe(u8, "tail\x1b[0m"), - }); - try q.pushOutput(std.testing.allocator, std.testing.io, .{ - .pane = 0, - .gen = 1, - .bytes = try std.testing.allocator.dupe(u8, "é😀"), - }); - } - }; - for ([_]enum { take, cancel, close }{ .take, .cancel, .close }) |action| { - var inbox: Inbox = .{}; - defer inbox.close(gpa, io); - for (0..inbox_output_limit) |_| try inbox.pushOutput(gpa, io, .{ - .pane = 0, - .gen = 1, - .bytes = try gpa.dupe(u8, "before"), - }); - var done: std.Io.Event = .unset; - var future = try io.concurrent(Producer.run, .{ &inbox, &done }); - defer future.cancel(io) catch {}; - for (0..1000) |_| { - if (inbox.space.state.load(.acquire).waiters != 0) break; - try io.sleep(.fromMilliseconds(1), .awake); - } - try std.testing.expectEqual(@as(u16, 1), inbox.space.state.load(.acquire).waiters); - switch (action) { - .take => { - var before = inbox.take(io); - defer for (before.slice()) |msg| msg.free(gpa); - try std.testing.expectEqual(inbox_output_limit, before.len); - for (before.slice()) |msg| try std.testing.expectEqualStrings("before", msg.output.bytes); - try done.waitTimeout(io, .{ .duration = .{ .raw = .fromSeconds(2), .clock = .awake } }); - try future.await(io); - var after = inbox.take(io); - defer for (after.slice()) |msg| msg.free(gpa); - try std.testing.expectEqual(@as(usize, 3), after.len); - try std.testing.expectEqualStrings("tail\x1b[0m", after.items[0].output.bytes); - try std.testing.expectEqualStrings("é😀", after.items[1].output.bytes); - try std.testing.expect(after.items[2] == .eof); - }, - .cancel => { - try std.testing.expectError(error.Canceled, future.cancel(io)); - var batch = inbox.take(io); - defer for (batch.slice()) |msg| msg.free(gpa); - try std.testing.expectEqual(inbox_output_limit + 1, batch.len); - for (batch.slice()[0..inbox_output_limit]) |msg| try std.testing.expectEqualStrings("before", msg.output.bytes); - try std.testing.expect(batch.items[inbox_output_limit] == .eof); - }, - .close => { - inbox.close(gpa, io); - try done.waitTimeout(io, .{ .duration = .{ .raw = .fromSeconds(2), .clock = .awake } }); - try std.testing.expectError(error.Canceled, future.await(io)); - try std.testing.expectEqual(@as(usize, 0), inbox.len); - }, - } - } -} +const Inbox = host_io.Inbox; +const Msg = Inbox.Msg; const State = struct { ninep: ?*ninep_io.Listener = null, @@ -653,8 +430,9 @@ const State = struct { panel_tracks: [pardes.MAX_PANES * 2]PanelTrack = undefined, panel_tracks_len: usize = 0, ptys: [pardes.MAX_PANES]?Pty = @splat(null), - inbox: Inbox = .{}, - lsp_task: ?host_io.Lsp.Task = null, + inbox: Inbox = undefined, + /// A wakeup is on its way to the runtime: the next ones are not sent. + wake_pending: std.atomic.Value(bool) = .init(false), pipe_tasks: selection_pipe.Tasks = .{}, file_watches: FileWatches = .{}, gens: [pardes.MAX_PANES]u32 = @splat(0), @@ -692,8 +470,15 @@ export fn pardes_init(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) c_ return 0; } +/// The shell's gpa in a Debug build, as std.start's is for the others. +var debug_gpa: std.heap.DebugAllocator(.{}) = .init; + fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { - const gpa = std.heap.smp_allocator; + // The allocator every other shell gets from std.start: a DebugAllocator + // in Debug, libc's malloc otherwise. libc's measured at least as fast as + // std.heap.smp_allocator everywhere and faster on MuPDF's page-sized + // rasters, so this shell no longer differs. + const gpa = if (builtin.mode == .debug) debug_gpa.allocator() else std.heap.c_allocator; const allocs = pardes.memory.init(gpa); errdefer pardes.memory.deinit(); @@ -709,6 +494,10 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { var opts: pardes.Options = .{ .tty_only = true, + // The app is a real bare-tty startup, like the terminal and SDL + // shells, so it names the same layout rather than the bare shell a + // core booted for a test gets. + .boot = .tty, .frame_allocator = allocs.frame, .image_allocator = allocs.image, .pdf_allocator = allocs.pdf, @@ -756,6 +545,7 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { .runtime = if (runtime) |r| r.* else .{}, }; const st = &state.?; + st.inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = io, .wake_fn = wakeHost, .wake_ctx = st }; st.ninep = ninep_io.start(io, gpa, core); core.host = hostFor(st); @@ -768,7 +558,12 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { if (st.ninep) |listener| listener.watch(st, wakeNinep) catch |err| core.reportError(0, "9p wake", err); for (&st.ptys, 0..) |*slot, id| if (slot.*) |*pt| startReader(st, pt, @intCast(id)); - pardes.lsp.setStatusSink(st, lspStatusSink); + pardes.lsp.setStatusSink(&st.inbox, Inbox.lspStatus); + host_io.setExitWake(st, wakeForExit); + // From here the core is touched only inside the entry points above, + // each of which takes the turn for its own duration; between them the + // 9P connections have it. + pardes.turn.rest(); } fn wakeNinep(ctx: ?*anyopaque) void { @@ -777,15 +572,17 @@ fn wakeNinep(ctx: ?*anyopaque) void { } export fn pardes_deinit() void { + pardes.turn.wake(); const st = &(state orelse return); if (st.ninep) |listener| { listener.deinit(st.gpa); st.ninep = null; } pardes.lsp.setStatusSink(null, null); - if (st.lsp_task) |*t| { - t.future.cancel(st.io) catch {}; - st.lsp_task = null; + host_io.setExitWake(null, null); + if (st.inbox.lsp_task) |*t| { + t.future.cancel(st.io); + st.inbox.lsp_task = null; } st.pipe_tasks.cancelAll(st.io); for (0..pardes.MAX_PANES) |pane| if (st.file_watches.entries[pane] != null) { @@ -798,7 +595,7 @@ export fn pardes_deinit() void { hostWatchFile(theme_watch_pane, generation, null, 0); } for (0..pardes.MAX_PANES) |pane| reap(st, @intCast(pane)); - st.inbox.close(st.gpa, st.io); + st.inbox.close(); st.file_watches.deinit(st.gpa); if (st.cells.len > 0) st.gpa.free(st.cells); for (st.layer_cells) |cells| st.gpa.free(cells); @@ -815,24 +612,31 @@ export fn pardes_deinit() void { st.threaded.deinit(); st.gpa.destroy(st.threaded); pardes.memory.deinit(); + // Leaks are logged and do not fail, as std.start treats the others'. + if (builtin.mode == .debug) { + _ = debug_gpa.deinit(); + debug_gpa = .init; + } state = null; } export fn pardes_should_quit() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return true); return st.core.quit; } -fn encodeSceneEffects(effects: layout.SceneEffect) u32 { +// The Metal shell keeps its own CRT kernel: the GUI's bundled post pass, as +// a flag. +fn encodeSceneEffects(post: *const pardes.config.Runtime.Post) u32 { var flags: u32 = 0; - if (effects.crt) flags |= scene_flag_crt; - if (effects.ripple) flags |= scene_flag_ripple; - if (effects.glitch) flags |= scene_flag_glitch; + if (post.has(.crt)) flags |= scene_flag_crt; return flags; } fn currentSceneFlags(st: *const State) u32 { - return encodeSceneEffects(st.core.settings.scene_effects); + return encodeSceneEffects(&st.core.settings.post); } fn advanceSceneClock(st: *State, elapsed_ns: u64) void { @@ -843,18 +647,18 @@ const TickSpend = struct { elapsed_ns: u64, steps: u32, bank_ns: u64 }; fn spendTickTime(previous_ns: u64, now_ns: u64, bank_ns: u64) TickSpend { const measured = if (previous_ns == 0 or now_ns <= previous_ns) - pardes.layout.Animation.frame_ns + pardes.animation.frame_ns else now_ns - previous_ns; const elapsed = @min(measured, max_tick_catch_up_ns); var bank = bank_ns +| elapsed; var steps: u32 = 0; - while (bank >= pardes.layout.Animation.frame_ns) : (steps += 1) bank -= pardes.layout.Animation.frame_ns; + while (bank >= pardes.animation.frame_ns) : (steps += 1) bank -= pardes.animation.frame_ns; return .{ .elapsed_ns = elapsed, .steps = steps, .bank_ns = bank }; } test "the animation clock spends real time, not callbacks" { - const frame = pardes.layout.Animation.frame_ns; + const frame = pardes.animation.frame_ns; const expectEqual = std.testing.expectEqual; const first = spendTickTime(0, 999 * std.time.ns_per_s, 0); @@ -886,11 +690,15 @@ test "the animation clock spends real time, not callbacks" { } export fn pardes_animating() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); return st.core.animationActive() or st.rotate_coasting or st.scroll_coasting; } export fn pardes_theme_bg() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const th = if (state) |*st| st.core.theme() else &pardes.themes[0]; const bg = th.bg orelse return color_default; return @as(u32, bg[0]) << 16 | @as(u32, bg[1]) << 8 | bg[2]; @@ -909,6 +717,8 @@ export fn pardes_theme_bg() u32 { /// own (pardes_theme_bg == PARDES_COLOR_DEFAULT) drops the ground entirely, /// whatever percentage is set here. export fn pardes_window_opacity() u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 100); st.core.settings.window_opacity_pending = false; return st.core.settings.window_opacity; @@ -916,6 +726,8 @@ export fn pardes_window_opacity() u8 { /// Public AppKit backdrop strength, independent of background paint opacity. export fn pardes_window_blur() u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); return if (state) |st| st.core.settings.window_blur else 0; } @@ -924,11 +736,15 @@ fn taglineFontPercent(core: ?*const pardes.Pardes) u8 { } export fn pardes_gui_tagline_font_percent() u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); return taglineFontPercent(if (state) |*st| st.core else null); } export fn pardes_tagline_band_offset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { - return pardes.taglineBandOffset(row, canvas_h, cell_h, tagline_h, if (state) |*st| st.core.settings.workspace_tag else true); + pardes.turn.wake(); + defer pardes.turn.rest(); + return pardes.taglineBandOffset(row, canvas_h, cell_h, tagline_h); } export fn pardes_topbar_pane_border_px(cell_h: u32, tagline_h: u32) u32 { @@ -936,16 +752,22 @@ export fn pardes_topbar_pane_border_px(cell_h: u32, tagline_h: u32) u32 { } export fn pardes_tagline_origin_col(col: u16, row: u16) f32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return @floatFromInt(col)); return pardes.taglineOriginColForFrame(st.core, col, row); } export fn pardes_grid_col_at(x: f32, row: u16, body_w: f32, tagline_w: f32) u16 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return pardes.gridColAt(null, x, row, body_w, tagline_w)); return pardes.gridColAt(st.core, x, row, body_w, tagline_w); } export fn pardes_topbar_pane_border_rgb() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const rgb = pardes.config.gui_topbar_pane_border_rgb orelse fromTheme: { const st = state orelse return color_default; break :fromTheme st.core.chromeTheme().border; @@ -954,11 +776,15 @@ export fn pardes_topbar_pane_border_rgb() u32 { } export fn pardes_tag_active_bg() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = state orelse return color_default; const rgb = st.core.chromeTheme().tag_active_bg; return @as(u32, rgb[0]) << 16 | @as(u32, rgb[1]) << 8 | rgb[2]; } export fn pardes_tagline_bg() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = state orelse return color_default; const rgb = st.core.chromeTheme().tag_bg; return @as(u32, rgb[0]) << 16 | @as(u32, rgb[1]) << 8 | rgb[2]; @@ -1004,6 +830,8 @@ test "the fallback preference order crosses the ABI intact and ends at the bound } export fn pardes_scene() Scene { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return .{}); const seconds = @as(f64, @floatFromInt(st.scene_ns)) / @as(f64, std.time.ns_per_s); return .{ @@ -1014,6 +842,8 @@ export fn pardes_scene() Scene { } export fn pardes_postprocessor_unavailable() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.core.disableSceneEffects(); st.core.settings.panel_transition = .off; @@ -1022,6 +852,8 @@ export fn pardes_postprocessor_unavailable() void { } export fn pardes_panel_animation_failed() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.core.abandonPanelAnimations(); } @@ -1033,7 +865,7 @@ fn refreshCwds(ctx: ?*anyopaque) void { stale.* = false; const pt = st.ptys[id] orelse continue; var buf: [1024]u8 = undefined; - if (host_io.shellCwd(pt.pid, &buf)) |wd| st.core.setCwd(id, wd); + if (host_io.ttyCwd(pt.pid, pt.file.handle, st.core.settings.shell.effective.get(), &buf)) |wd| st.core.setCwd(id, wd); } } @@ -1082,13 +914,13 @@ fn setThemeFileWatch(st: *State, request_generation: u32, on: bool, animate: boo const stopped = st.file_watches.stop(st.gpa, theme_watch_pane); hostWatchFile(theme_watch_pane, stopped, null, 0); if (!on) return; - const request = st.core.themeFileRequest(request_generation) orelse return; + const request = colors.themeFileRequest(st.core, request_generation) orelse return; const bytes = filesystem.readFile(st.gpa, request.path) catch |err| { - st.core.failThemeFile(request_generation, err); + colors.failThemeFile(st.core, request_generation, err); return; }; defer st.gpa.free(bytes); - if (!st.core.loadThemeFile(request_generation, bytes, animate)) return; + if (!colors.loadThemeFile(st.core, request_generation, bytes, animate)) return; const callback_generation = st.file_watches.replace( st.gpa, theme_watch_pane, @@ -1103,10 +935,10 @@ fn setThemeFileWatch(st: *State, request_generation: u32, on: bool, animate: boo fn reloadWatchedTheme(st: *State, announce: bool) bool { const watched = if (st.file_watches.entries[theme_watch_pane]) |*entry| entry else return false; - const request = st.core.themeFileRequest(watched.serial) orelse return false; + const request = colors.themeFileRequest(st.core, watched.serial) orelse return false; if (!std.mem.eql(u8, watched.path, request.path)) return false; const bytes = filesystem.readFile(st.gpa, watched.path) catch |err| { - st.core.failThemeFile(watched.serial, err); + colors.failThemeFile(st.core, watched.serial, err); return false; }; defer st.gpa.free(bytes); @@ -1115,7 +947,7 @@ fn reloadWatchedTheme(st: *State, announce: bool) bool { .text => |accepted| if (accepted == hash) return false, .pdf => unreachable, } - if (!st.core.loadThemeFile(watched.serial, bytes, true)) return false; + if (!colors.loadThemeFile(st.core, watched.serial, bytes, true)) return false; const live = if (st.file_watches.entries[theme_watch_pane]) |*entry| entry else return false; if (live.serial != watched.serial) return false; live.generation_on_disk = .{ .text = hash }; @@ -1206,16 +1038,20 @@ fn reloadWatchedFile(st: *State, pane: u8, announce: bool) bool { } export fn pardes_watch_changed(pane: u8, generation: u32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); if (pane >= watch_slot_count) return; if (st.file_watches.notify(pane, generation)) wake(st); } fn drainInbox(st: *State) bool { - var batch = st.inbox.take(st.io); + var batch = st.inbox.take(); + // After this batch's output, which an exit is told behind. + defer takeExits(st); var did = batch.len > 0; for (batch.slice()) |msg| { - defer msg.free(st.gpa); + defer msg.deinit(st.gpa, st.gpa); switch (msg) { .output => |o| { if (st.gens[o.pane] != o.gen) continue; @@ -1224,14 +1060,32 @@ fn drainInbox(st: *State) bool { }, .eof => |e| { if (st.gens[e.pane] != e.gen) continue; + if (st.ptys[e.pane]) |*pt| { + // A command's pty stays open until its child has exited: + // closing it would hang up one that runs on without it. + // Its exit, if it came first, is told now its output is in. + if (pt.cmd.watched) { + host_io.commandEof(st.core, &st.ptys, e.pane, st, closeWatched); + continue; + } + // Unwatched, a command's exit is read here, as its end, + // and a shell's, for a run waiting on it and the log. + const command = if (st.core.panes[e.pane]) |pane| pane.command != null else false; + const status = host_io.exitStatus(pt.pid, 100); + if (status != null) pt.pid = 0; // reaped: no shell to retire + reap(st, e.pane); + if (command or status != null) st.core.update(.{ .exited = .{ .pane = e.pane, .status = status } }); + st.core.update(.{ .eof = .{ .pane = e.pane } }); + continue; + } reap(st, e.pane); st.core.update(.{ .eof = .{ .pane = e.pane } }); }, - .lsp_done => |d| { + .lsp => |d| { st.core.update(.{ .lsp_resp = .{ .id = d.id, .rows = d.rows } }); - if (st.lsp_task) |*t| if (t.id == d.id) { - t.future.await(st.io) catch {}; - st.lsp_task = null; + if (st.inbox.lsp_task) |*t| if (t.id == d.id) { + t.future.await(st.io); + st.inbox.lsp_task = null; }; }, .lsp_status => |text| { @@ -1247,6 +1101,11 @@ fn drainInbox(st: *State) bool { } }); st.pipe_tasks.finish(st.io, value.id); }, + // ponytail: no `search` host entry here, so Stream runs on the loop. + .search => |b| st.core.update(.{ .search = b }), + // The SDL shell's: this one's file watches and 9P are its own. + // ponytail: no hand_over host entry on macOS yet, so none comes. + .files_changed, .fs_ready, .handed => {}, } } for (0..pardes.MAX_PANES) |pane| { @@ -1261,11 +1120,13 @@ fn drainInbox(st: *State) bool { } export fn pardes_tick() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); - st.inbox.wake_pending.store(false, .release); + st.wake_pending.store(false, .release); var did = drainInbox(st); if (st.ninep) |listener| { - const drained = listener.tick(st.core); + const drained = listener.tick(); did = did or drained.count != 0; if (drained.pending) wake(st); } @@ -1273,39 +1134,41 @@ export fn pardes_tick() bool { did = true; st.core.perform(effect); } + pardes.turn.bump(&pardes.turn.epoch); if (restoreCore(st)) did = true; + pardes.turn.bump(&pardes.turn.restores); return did; } fn restoreCore(st: *State) bool { if (st.core.quit) return false; const path = st.core.takeRestore() orelse return false; - const bytes = filesystem.readRestore(st.gpa, path) catch |err| { + const bytes = filesystem.readRestore(st.gpa, path, st.core.settings.dump_dir.get()) catch |err| { st.core.reportError(st.core.active, "Restore", err); return false; }; defer st.gpa.free(bytes); - const replacement = st.core.restore(bytes) catch |err| { + const replacement = dump.restore(st.core, bytes, path) catch |err| { st.core.reportError(st.core.active, "Restore", err); return false; }; - if (st.lsp_task) |*task| { - task.future.cancel(st.io) catch {}; - st.lsp_task = null; + if (st.inbox.lsp_task) |*task| { + task.future.cancel(st.io); + st.inbox.lsp_task = null; } st.pipe_tasks.cancelAll(st.io); for (0..pardes.MAX_PANES) |pane| { reap(st, @intCast(pane)); st.gens[pane] +%= 1; } - var stale = st.inbox.take(st.io); - for (stale.slice()) |msg| msg.free(st.gpa); + var stale = st.inbox.take(); + for (stale.slice()) |msg| msg.deinit(st.gpa, st.gpa); for (0..watch_slot_count) |pane| if (st.file_watches.entries[pane] != null) { const id: u8 = @intCast(pane); const generation = st.file_watches.stop(st.gpa, id); hostWatchFile(id, generation, null, 0); }; - if (st.ninep) |listener| listener.reset(st.core); + if (st.ninep) |listener| listener.reset(replacement); replacement.host = hostFor(st); st.core.deinit(); st.core = replacement; @@ -1340,19 +1203,20 @@ test "mac Restore keeps host state and rejects callbacks from the old core" { .runtime = .{}, .config_arena = .init(gpa), .prompt_rcs = .{}, + .inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = std.testing.io }, .frame_len = 7, .rotate_coasting = true, }; defer st.core.deinit(); defer st.config_arena.deinit(); defer st.file_watches.deinit(gpa); - defer st.inbox.close(gpa, std.testing.io); + defer st.inbox.close(); const marker = try st.config_arena.allocator().dupe(u8, "host configuration"); _ = try core.setTestFile("saved body\n"); const old_serial = core.panes[0].?.serial; st.gens[0] = 23; const old_watch = try st.file_watches.replace(gpa, 0, "/test.txt", old_serial, .{ .text = 0 }); - try core.dumpState(); + try dump.dumpState(core); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "restore.zon", .data = core.dump_out.? }); while (core.nextEffect()) |_| {} @@ -1365,19 +1229,21 @@ test "mac Restore keeps host state and rejects callbacks from the old core" { core.lspRequest(0, .status, ""); const old_request = core.lsp_wait.?.id; - st.lsp_task = .{ .id = old_request, .future = .{ .any_future = null, .result = {} } }; - st.inbox.push(gpa, std.testing.io, .{ .lsp_done = .{ .id = old_request, .rows = try gpa.dupe(u8, "old result") } }); + st.inbox.lsp_id = old_request; + st.inbox.lsp_task = .{ .id = old_request, .future = .{ .any_future = null, .result = {} } }; + st.inbox.push(.{ .lsp = .{ .id = old_request, .rows = try gpa.dupe(u8, "old result") } }); for (0..selection_pipe.Tasks.capacity) |index| { const id: u32 = @intCast(index); try std.testing.expect(st.pipe_tasks.add(.{ .id = id, .future = .{ .any_future = null, .result = {} } })); - st.inbox.push(gpa, std.testing.io, .{ .pipe = .{ + st.inbox.push(.{ .pipe = .{ .id = id, .success = false, .outputs = &.{}, .failure = .{ .kind = .exit, .code = 1, .stderr = try gpa.dupe(u8, "old filter failure") }, } }); } - try st.inbox.pushOutput(gpa, std.testing.io, .{ .pane = 0, .gen = 23, .bytes = try gpa.dupe(u8, "old PTY output") }); + st.inbox.acceptReader(0, 23); + _ = st.inbox.pushOutput(0, 23, try gpa.dupe(u8, "old PTY output")); core.update(.{ .command = try std.fmt.bufPrint(&command, "Restore .zig-cache/tmp/{s}/restore.zon", .{tmp.sub_path}) }); try std.testing.expect(restoreCore(&st)); try std.testing.expect(st.core != core); @@ -1391,35 +1257,36 @@ test "mac Restore keeps host state and rejects callbacks from the old core" { try std.testing.expect(st.file_watches.generations[0] > old_watch); try std.testing.expectEqual(@as(usize, 0), st.inbox.len); try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); - try std.testing.expect(st.lsp_task == null); + try std.testing.expect(st.inbox.lsp_task == null); try std.testing.expect(!drainInbox(&st)); try std.testing.expect(!st.cwd_stale[0]); st.core.lspRequest(0, .status, ""); const new_request = st.core.lsp_wait.?.id; try std.testing.expect(new_request > old_request); - st.lsp_task = .{ .id = new_request, .future = .{ .any_future = null, .result = {} } }; - st.inbox.push(gpa, std.testing.io, .{ .lsp_done = .{ .id = new_request, .rows = &.{} } }); + st.inbox.lsp_id = new_request; + st.inbox.lsp_task = .{ .id = new_request, .future = .{ .any_future = null, .result = {} } }; + st.inbox.push(.{ .lsp = .{ .id = new_request, .rows = &.{} } }); try std.testing.expect(drainInbox(&st)); - try std.testing.expect(st.lsp_task == null); + try std.testing.expect(st.inbox.lsp_task == null); try std.testing.expect(st.core.lsp_wait == null); const pane = st.core.panes[0].?; - pane.cur_col = 4; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_col = 4; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; st.core.update(.{ .key = .{ .cp = '|' } }); st.core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); st.core.update(.{ .key = .{ .cp = pardes.Key.enter } }); - const pipe_id = st.core.pipe_wait.?.id; + const pipe_id = st.core.pipe.wait.?.id; try std.testing.expect(st.pipe_tasks.add(.{ .id = pipe_id, .future = .{ .any_future = null, .result = {} } })); const output = try gpa.dupe(u8, "FRESH"); const outputs = gpa.dupe([]u8, &.{output}) catch |err| { gpa.free(output); return err; }; - st.inbox.push(gpa, std.testing.io, .{ .pipe = .{ .id = pipe_id, .success = true, .outputs = outputs } }); + st.inbox.push(.{ .pipe = .{ .id = pipe_id, .success = true, .outputs = outputs } }); try std.testing.expect(drainInbox(&st)); - try std.testing.expect(st.core.pipe_wait == null); + try std.testing.expect(st.core.pipe.wait == null); try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); try std.testing.expectEqualStrings("FRESH body\n", pane.file.?.content); } @@ -1437,19 +1304,17 @@ test "mac Restore cancels a PTY reader waiting for output capacity" { .runtime = .{}, .config_arena = .init(gpa), .prompt_rcs = .{}, + .inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = io }, }; defer st.core.deinit(); defer st.config_arena.deinit(); defer st.file_watches.deinit(gpa); - defer st.inbox.close(gpa, io); - try st.core.dumpState(); + defer st.inbox.close(); + try dump.dumpState(st.core); try tmp.dir.writeFile(io, .{ .sub_path = "restore.zon", .data = st.core.dump_out.? }); while (st.core.nextEffect()) |_| {} - for (0..inbox_output_limit) |_| try st.inbox.pushOutput(gpa, io, .{ - .pane = 0, - .gen = 1, - .bytes = try gpa.dupe(u8, "retained output"), - }); + st.inbox.acceptReader(1, 1); + for (0..Inbox.output_capacity) |_| _ = st.inbox.pushOutput(1, 1, try gpa.dupe(u8, "retained output")); const child = try host_io.forkShell(null, 0, &st.prompt_rcs, "/bin/sh", "", 12, 40, null); st.gens[0] = 1; st.ptys[0] = .{ .file = child.file, .pid = child.pid, .gen = 1, .reader = .{ .any_future = null, .result = {} } }; @@ -1473,17 +1338,20 @@ test "mac Restore cancels a PTY reader waiting for output capacity" { try std.testing.expect(st.ptys[0] == null); try std.testing.expectEqual(@as(usize, 0), st.inbox.len); try std.testing.expectEqual(@as(u16, 0), st.inbox.space.state.load(.acquire).waiters); - try st.inbox.pushOutput(gpa, io, .{ .pane = 0, .gen = st.gens[0], .bytes = try gpa.dupe(u8, "fresh output") }); - var batch = st.inbox.take(io); - defer for (batch.slice()) |msg| msg.free(gpa); + st.inbox.acceptReader(0, st.gens[0]); + _ = st.inbox.pushOutput(0, st.gens[0], try gpa.dupe(u8, "fresh output")); + var batch = st.inbox.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); try std.testing.expectEqual(@as(usize, 1), batch.len); try std.testing.expectEqualStrings("fresh output", batch.items[0].output.bytes); } export fn pardes_animation_tick() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); - const now: u64 = @intCast(@max(0, monotonicNs())); + const now: u64 = @intCast(std.Io.Clock.awake.now(st.io).nanoseconds); const spend = spendTickTime(st.last_tick_ns, now, st.tick_bank_ns); st.last_tick_ns = now; st.tick_bank_ns = spend.bank_ns; @@ -1542,6 +1410,8 @@ export fn pardes_animation_tick() bool { } export fn pardes_key(cp_arg: u32, text_ptr: ?[*]const u8, len: usize, mods: u32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); if (cp_arg > std.math.maxInt(u21)) return; const text: []const u8 = if (text_ptr) |p| p[0..len] else ""; @@ -1555,28 +1425,34 @@ export fn pardes_key(cp_arg: u32, text_ptr: ?[*]const u8, len: usize, mods: u32) } export fn pardes_paste(text_ptr: ?[*]const u8, len: usize) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); const text: []const u8 = if (text_ptr) |p| p[0..len] else ""; st.core.update(.{ .paste = text }); } export fn pardes_mouse(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); mouseWithHit(button_arg, kind_arg, col, row, mods, null, null); } export fn pardes_mouse_pixel(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u32, x: f32, y: f32, bw: f32, bh: f32, tw: f32, th: f32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); const source = st.core.presentation.pointerFractional(st.core.screen_w, st.core.screen_h, x / @max(1, bw), y / @max(1, bh)); var hit: ?pardes.Mouse.BodyHit = null; for (&st.core.surface.body_layers) |*layer| { const point = source orelse break; - hit = layer.hitAt(point.x * bw, point.y * bh, bw, bh, tw, th); + hit = layer.bodyHit(point.x * bw, point.y * bh, bw, bh, tw, th); if (hit != null) break; } var tag_hit: ?pardes.TagHit = null; for (&st.core.surface.tag_layers) |*layer| { const point = source orelse break; - tag_hit = layer.hitAt(point.x * bw, point.y * bh, bw, bh, tw, th); + tag_hit = layer.tagHit(point.x * bw, point.y * bh, bw, bh, tw, th); if (tag_hit != null) break; } mouseWithHit(button_arg, kind_arg, col, row, mods, hit, tag_hit); @@ -1604,23 +1480,32 @@ fn mouseWithHit(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u3 3 => .drag, else => return, }; - st.core.update(.{ .mouse = .{ - .body_hit = hit, - .tag_hit = tag_hit, - .button = button, - .kind = kind, - .col = col, - .row = row, - .ctrl = mods & 1 != 0, - } }); + st.core.update(.{ + .mouse = .{ + .body_hit = hit, + .tag_hit = tag_hit, + .button = button, + .kind = kind, + .col = col, + .row = row, + .ctrl = mods & 1 != 0, + // Option-click is B2 and Cmd-click B3 (mouse.emulateButton). + .alt = mods & 2 != 0, + .super = mods & 8 != 0, + }, + }); } export fn pardes_pointer_leave() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.core.update(.pointer_leave); } export fn pardes_scroll(delta_rows: f32, delta_cols: f32, col: u16, row: u16) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.scroll_col = col; st.scroll_row = row; @@ -1632,13 +1517,15 @@ export fn pardes_scroll(delta_rows: f32, delta_cols: f32, col: u16, row: u16) vo /// spinning dial. Also drops whatever the last gesture left banked, so the /// first millimetre of a new swipe cannot inherit a nearly-complete row. export fn pardes_scroll_begin() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.scroll_lag = 0; st.scroll_lag_x = 0; st.scroll_velocity = 0; st.scroll_velocity_x = 0; st.scroll_coasting = false; - st.scroll_last_ns = monotonicNs(); + st.scroll_last_ns = std.Io.Clock.awake.now(st.io).nanoseconds; } /// Fingers lifted. A swipe that was still moving when it ended becomes a @@ -1651,12 +1538,14 @@ export fn pardes_scroll_begin() void { /// momentum simply takes the gesture over, and the tail of that momentum is /// below the fling floor, so its end arms nothing. export fn pardes_scroll_end() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); const last = st.scroll_last_ns; st.scroll_last_ns = 0; st.scroll_coasting = false; // A hand that came to rest before lifting is not throwing anything. - if (last == 0 or monotonicNs() - last > 90 * std.time.ns_per_ms) { + if (last == 0 or std.Io.Clock.awake.now(st.io).nanoseconds - last > 90 * std.time.ns_per_ms) { st.scroll_velocity = 0; st.scroll_velocity_x = 0; return; @@ -1667,12 +1556,14 @@ export fn pardes_scroll_end() void { } export fn pardes_rotate(degrees: f32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); if (degrees == 0) { st.rotate_lag = 0; st.rotate_velocity = 0; st.rotate_coasting = false; - st.rotate_last_ns = monotonicNs(); + st.rotate_last_ns = std.Io.Clock.awake.now(st.io).nanoseconds; return; } noteRotationVelocity(st, degrees); @@ -1680,11 +1571,13 @@ export fn pardes_rotate(degrees: f32) void { } export fn pardes_rotate_end() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); const last = st.rotate_last_ns; st.rotate_last_ns = 0; st.rotate_coasting = false; - if (last == 0 or monotonicNs() - last > 90 * std.time.ns_per_ms) { + if (last == 0 or std.Io.Clock.awake.now(st.io).nanoseconds - last > 90 * std.time.ns_per_ms) { st.rotate_velocity = 0; return; } @@ -1692,14 +1585,8 @@ export fn pardes_rotate_end() void { st.rotate_coasting = st.rotate_velocity != 0; } -fn monotonicNs() i128 { - var ts: libc.timespec = undefined; - if (libc.clock_gettime(.MONOTONIC, &ts) != 0) return 0; - return @as(i128, ts.sec) * std.time.ns_per_s + ts.nsec; -} - fn noteRotationVelocity(st: *State, degrees: f32) void { - const now = monotonicNs(); + const now = std.Io.Clock.awake.now(st.io).nanoseconds; const last = st.rotate_last_ns; st.rotate_last_ns = now; st.rotate_coasting = false; @@ -1722,6 +1609,8 @@ fn spendRotation(st: *State, degrees: f32) void { } export fn pardes_command(text_ptr: ?[*]const u8, len: usize) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); const text: []const u8 = if (text_ptr) |p| p[0..len] else ""; if (text.len == 0) return; @@ -1729,6 +1618,8 @@ export fn pardes_command(text_ptr: ?[*]const u8, len: usize) void { } export fn pardes_resize(cols_arg: u16, rows_arg: u16, cell_w: u16, cell_h: u16) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); const cols = @max(1, cols_arg); const rows = @max(1, rows_arg); @@ -1743,6 +1634,8 @@ export fn pardes_resize(cols_arg: u16, rows_arg: u16, cell_w: u16, cell_h: u16) } export fn pardes_frame() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); const tz = tracy.zone(@src(), "pardes_frame"); defer tz.end(); @@ -1772,25 +1665,22 @@ fn clearFrame(st: *State) void { st.panel_diff_len = 0; } -fn blankTagCells(cells: []Cell, cols: u16, rows: u16, source: []const pardes.Cell, layers: []const pardes.TagLayer) void { +fn blankTagCells(cells: []Cell, cols: u16, rows: u16, source: []const pardes.Cell, layers: []const pardes.Layer) void { for (layers) |layer| { - if (layer.cols == 0 or layer.viewport.y >= rows or layer.viewport.x >= cols) continue; + if (layer.rows == 0 or layer.viewport.y >= rows or layer.viewport.x >= cols) continue; const start = @as(usize, layer.viewport.y) * cols + layer.viewport.x; const count = @min(layer.viewport.w, cols - layer.viewport.x); - for (cells[start..][0..count], source[start..][0..count]) |*cell, was| { - // The tag text is the layer's to draw, but a look-hover on a tag - // word is a canonical fact: carry the hover bit through so the - // glass overlay still finds the affordance rect. - cell.* = encodeCell(.{}); - cell.flags |= @as(u8, @intFromBool(was.hover)) * cell_flag_hover; - } + // The tag text is the layer's to draw. (The look-hover's glass + // rect went with the core's hover bit, stage 8's follow-up.) + _ = source; + for (cells[start..][0..count]) |*cell| cell.* = encodeCell(.{}); } } fn tagCursorCovered(core: *const pardes.Pardes) bool { const cursor = core.surface.cursor orelse return false; for (core.surface.tag_layers) |layer| { - if (layer.cols != 0 and cursor.y == layer.viewport.y and cursor.x >= layer.viewport.x and + if (layer.rows != 0 and cursor.y == layer.viewport.y and cursor.x >= layer.viewport.x and cursor.x - layer.viewport.x < layer.viewport.w) return true; } return false; @@ -1917,26 +1807,36 @@ fn collectImages(st: *State, surface: *const pardes.Surface) void { } export fn pardes_frame_images() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); return @intCast(st.images_len); } export fn pardes_frame_image_list() ?[*]const Image { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); return if (st.images_len == 0) null else st.images.ptr; } export fn pardes_frame_panel_tracks() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); return @intCast(st.panel_tracks_len); } export fn pardes_frame_panel_track_list() ?[*]const PanelTrack { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); return if (st.panel_tracks_len == 0) null else st.panel_tracks[0..].ptr; } export fn pardes_frame_presented(animated_panels: bool) bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); const was_animating = st.core.animationActive(); if (animated_panels) @@ -1947,11 +1847,15 @@ export fn pardes_frame_presented(animated_panels: bool) bool { } export fn pardes_frame_cells() ?[*]const Cell { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); return if (st.frame_len == 0) null else st.cells.ptr; } export fn pardes_frame_previous_cells() ?[*]const Cell { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); return if (st.panel_diff_len != st.frame_len or st.panel_diff_len == 0) null @@ -1960,6 +1864,8 @@ export fn pardes_frame_previous_cells() ?[*]const Cell { } export fn pardes_frame_changed_cells() ?[*]const u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); return if (st.panel_diff_len != st.frame_len or st.panel_diff_len == 0) null @@ -1968,16 +1874,22 @@ export fn pardes_frame_changed_cells() ?[*]const u8 { } export fn pardes_frame_cols() u16 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); return st.frame_cols; } export fn pardes_frame_rows() u16 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); return st.frame_rows; } export fn pardes_cursor_x() i32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return -1); if (tagCursorCovered(st.core)) return -1; return if (st.core.surface.cursor) |c| c.x else -1; @@ -1996,19 +1908,21 @@ export fn pardes_tag_layer_limit() u32 { } export fn pardes_tag_layer_value(index: u32, field: u32) u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); if (index >= pardes.MAX_TAG_LAYERS) return 0; const layer = &st.core.surface.tag_layers[index]; return switch (field) { 0 => layer.cols, - 1 => @intFromEnum(layer.kind), + 1 => @backingInt(layer.kind), 2 => layer.id, 3 => layer.serial, 4 => layer.viewport.x, 5 => layer.viewport.y, 6 => layer.viewport.w, 7 => layer.viewport.h, - 8 => if (layer.cursor) |c| c.col else 65535, + 8 => if (layer.cursor) |c| c.x else 65535, 9 => if (layer.cursor) |c| @intFromBool(c.bar) else 0, 10 => @as(u32, layer.bg[0]) << 16 | @as(u32, layer.bg[1]) << 8 | layer.bg[2], 11 => @intFromBool(layer.kind == .pane and st.core.settings.tag_bottom), @@ -2021,10 +1935,12 @@ export fn pardes_tag_layer_value(index: u32, field: u32) u32 { } export fn pardes_tag_layer_cells(index: u32) ?[*]const Cell { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); if (index >= pardes.MAX_TAG_LAYERS) return null; const layer = &st.core.surface.tag_layers[index]; - if (layer.cols == 0) return null; + if (layer.rows == 0) return null; const cells = &st.tag_cells[index]; if (cells.len != layer.cells.len) cells.* = st.gpa.realloc(cells.*, layer.cells.len) catch return null; for (layer.cells, cells.*) |source, *out| out.* = encodeCell(source); @@ -2032,6 +1948,8 @@ export fn pardes_tag_layer_cells(index: u32) ?[*]const Cell { } export fn pardes_body_layer_value(index: u32, field: u32) u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); if (index >= pardes.MAX_PANES) return 0; const layer = &st.core.surface.body_layers[index]; @@ -2052,6 +1970,8 @@ export fn pardes_body_layer_value(index: u32, field: u32) u32 { } export fn pardes_body_layer_cells(index: u32) ?[*]const Cell { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); if (index >= pardes.MAX_PANES) return null; const layer = &st.core.surface.body_layers[index]; @@ -2067,27 +1987,37 @@ export fn pardes_body_layer_limit() u32 { } export fn pardes_row_metrics(body_w: u16, body_h: u16, tagline_w: u16, tagline_h: u16) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.core.update(.{ .resize = .{ .cols = st.core.screen_w, .rows = st.core.screen_h, .cell_pixels = st.core.cell_pixels, .row_metrics = .{ .body_w = @max(1, body_w), .body_h = @max(1, body_h), .tagline_w = @max(1, tagline_w), .tagline_h = @max(1, tagline_h) } } }); } export fn pardes_pointer_shape() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); - return @intFromEnum(st.core.surface.pointer_shape); + return @backingInt(st.core.surface.pointer_shape); } export fn pardes_cursor_y() i32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return -1); if (tagCursorCovered(st.core)) return -1; return if (st.core.surface.cursor) |c| c.y else -1; } export fn pardes_cursor_bar() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); return if (st.core.surface.cursor) |c| c.bar else false; } export fn pardes_take_haptic() c_int { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); return switch (st.core.takeHaptic()) { .none => 0, @@ -2099,6 +2029,8 @@ export fn pardes_take_haptic() c_int { var font_path_z: [4096:0]u8 = undefined; export fn pardes_font_take(size_hundredths: *u16) ?[*:0]const u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); if (comptime !pardes.font_picker) return null; const want = st.core.takeFontRequest() orelse return null; @@ -2114,6 +2046,8 @@ export fn pardes_font_observe( len: usize, point_hundredths: u16, ) bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); const ptr = effective_name orelse return false; if (len == 0 or len > 255 or point_hundredths == 0) return false; @@ -2125,6 +2059,8 @@ export fn pardes_font_ack( len: usize, point_hundredths: u16, ) bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); const ptr = effective_name orelse return false; if (len == 0 or len > 255 or point_hundredths == 0) return false; @@ -2132,6 +2068,8 @@ export fn pardes_font_ack( } export fn pardes_font_reject() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.core.rejectFont(); } @@ -2139,6 +2077,8 @@ export fn pardes_font_reject() void { var active_path_z: [4096:0]u8 = undefined; export fn pardes_active_path() ?[*:0]const u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); const path = activeFilePath(st) orelse return null; if (path.len == 0 or path.len >= active_path_z.len) return null; @@ -2148,6 +2088,8 @@ export fn pardes_active_path() ?[*:0]const u8 { } export fn pardes_active_dirty() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); const pane = st.core.panes[st.core.active] orelse return false; const f = if (pane.file) |*x| x else return false; @@ -2170,7 +2112,9 @@ const vtable: pardes.Host.VTable = .{ .pty_write = ptyWrite, .pty_resize = ptyResize, .pty_signal = ptySignal, + .close_pty = closePty, .tty_taken = ttyTaken, + .kill_job = killJob, .write_file = writeFile, .write_dump = writeDump, .watch_file = watchFile, @@ -2189,63 +2133,12 @@ fn hostFor(st: *State) pardes.Host { fn lspRequest(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { const st = hostState(ctx); - const job = host_io.Lsp.snapshot(st.gpa, st.core, req) catch |err| { - st.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); - return st.core.reportError(req.pane, "lsp", err); - }; - if (st.lsp_task) |*old| { - old.future.cancel(st.io) catch {}; - st.lsp_task = null; - } - const future = st.io.concurrent(lspWorker, .{ st, job }) catch |err| { - job.free(st.gpa); - st.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); - return st.core.reportError(req.pane, "lsp", err); - }; - st.lsp_task = .{ .id = req.id, .future = future }; + st.inbox.startLsp(st.core, req); } fn pipeRequest(ctx: ?*anyopaque, id: u32) void { const st = hostState(ctx); - if (st.pipe_tasks.full()) { - st.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); - return; - } - const view = st.core.pipeRequest(id) orelse return; - const job = selection_pipe.Job.copy(st.gpa, view) catch |err| { - st.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); - return st.core.reportError(st.core.active, "pipe", err); - }; - const future = st.io.concurrent(pipeWorker, .{ st, job }) catch |err| { - job.deinit(st.gpa); - st.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); - return st.core.reportError(st.core.active, "pipe", err); - }; - std.debug.assert(st.pipe_tasks.add(.{ .id = id, .future = future })); -} - -fn pipeWorker(st: *State, job: *selection_pipe.Job) anyerror!void { - defer job.deinit(st.gpa); - const response = selection_pipe.runJob(st.gpa, st.io, job); - st.inbox.push(st.gpa, st.io, .{ .pipe = response }); - wake(st); -} - -fn lspWorker(st: *State, job: *host_io.Lsp.Job) anyerror!void { - host_io.Lsp.work(st.gpa, job, st, deliverLspRows); -} - -fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { - const st: *State = @ptrCast(@alignCast(ctx orelse return)); - st.inbox.push(st.gpa, st.io, .{ .lsp_done = .{ .id = id, .rows = rows } }); - wake(st); -} - -fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void { - const st: *State = @ptrCast(@alignCast(ctx orelse return)); - const copy = st.gpa.dupe(u8, text) catch return; - st.inbox.push(st.gpa, st.io, .{ .lsp_status = copy }); - wake(st); + selection_pipe.start(st.io, st.gpa, st.core, &st.pipe_tasks, id, &st.inbox, Inbox.pushPipe); } fn hostState(ctx: ?*anyopaque) *State { @@ -2255,19 +2148,29 @@ fn hostState(ctx: ?*anyopaque) *State { fn spawnShell(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { const st = hostState(ctx); const core = st.core; + // The new shell starts before a running one goes: one that cannot + // start leaves the running one be (pty/ctl's exec). + const running = st.ptys[pane] != null; + const child = host_io.forkShell(core, pane, &st.prompt_rcs, core.shellBin(), cwd, core.screen_h, core.screen_w, st.ninep) catch |err| { + if (running) return core.restartFailed(pane, err); + return core.shellFailed(pane, err); + }; reap(st, pane); st.gens[pane] +%= 1; const gen = st.gens[pane]; - const child = host_io.forkShell(core, pane, &st.prompt_rcs, core.shellBin(), cwd, core.screen_h, core.screen_w, st.ninep) catch |err| return core.reportError(pane, "shell", err); st.ptys[pane] = .{ .file = child.file, .pid = child.pid, .gen = gen, .reader = .{ .any_future = null, .result = {} }, + .cmd = .{ .watched = (if (core.panes[pane]) |pn| pn.command != null else false) and host_io.watchExit(child.pid), .fd = child.file.handle }, }; var lbuf: [1024]u8 = undefined; - if (host_io.shellCwd(child.pid, &lbuf)) |wd| core.setCwd(pane, wd); + // Only a shell given no directory is asked where it is: one given a + // directory is named by it already (newShell), and asked now, before + // its chdir, it would answer this process's, a rename to undo. + if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| core.setCwd(pane, wd); if (st.started) if (st.ptys[pane]) |*pt| startReader(st, pt, pane); } @@ -2285,7 +2188,8 @@ fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void { fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void { const st = hostState(ctx); - if (st.ptys[pane]) |pt| host_io.signalTty(pt.pid, pt.file.handle, sig); + // A command whose exit is recorded is reaped: its group may be another's. + if (st.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.file.handle, sig, pt.cmd.watched); } fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool { @@ -2294,10 +2198,16 @@ fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool { return host_io.ttyTaken(pt.pid, pt.file.handle); } +fn killJob(ctx: ?*anyopaque, pane: u8) bool { + const st = hostState(ctx); + const pt = st.ptys[pane] orelse return false; + return host_io.killJob(pt.pid, pt.file.handle); +} + fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { const st = hostState(ctx); filesystem.write(st.core, path, bytes) catch |err| - return st.core.saveFailed(pane, "save", err); + return st.core.saveFailed(pane, path, err); st.file_watches.restampText(pane, path, std.hash.Wyhash.hash(0, bytes)); var mbuf: [256]u8 = undefined; st.core.setMessage(pane, message.stamp(&mbuf, "saved", path)); @@ -2306,8 +2216,8 @@ fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) vo fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { const st = hostState(ctx); var pbuf: [1024:0]u8 = undefined; - const path = pardes.dump.outPath(&pbuf) orelse return; - filesystem.write(st.core, path, bytes) catch |err| return st.core.reportError(0, "dump", err); + const path = pardes.dump.outPath(&pbuf, st.core.settings.dump_dir.get()) orelse return st.core.dumpFailed(st.core.settings.dump_dir.get(), error.NoDumpDirectory); + filesystem.write(st.core, path, bytes) catch |err| return st.core.dumpFailed(path, err); st.core.setLastDump(path); } @@ -2355,39 +2265,37 @@ fn openLink(_: ?*anyopaque, url: []const u8) void { } fn startReader(st: *State, pt: *Pty, id: u8) void { - pt.reader = st.io.concurrent(readPty, .{ st, st.io, pt.file, id, pt.gen }) catch |err| { + pt.reader = st.inbox.startReader(pt.file, id, pt.gen) catch |err| { log.err("pane {d} has no reader ({t}); it will not show output", .{ id, err }); return; }; } +/// The pane is gone: its shell goes with it. +fn closePty(ctx: ?*anyopaque, pane: u8) void { + const st = hostState(ctx); + if (st.ptys[pane] == null) return; + reap(st, pane); + st.gens[pane] +%= 1; +} + fn reap(st: *State, pane: u8) void { var pt = st.ptys[pane] orelse return; st.ptys[pane] = null; - pt.reader.cancel(st.io) catch {}; + // The inbox first: a reader waiting for space there wakes and returns. + st.inbox.cancelReader(pane, pt.gen); + pt.reader.cancel(st.io); _ = libc.close(pt.file.handle); - _ = libc.waitpid(pt.pid, null, posix.W.NOHANG); + host_io.retireShell(pt.pid); } -fn readPty(st: *State, io: std.Io, pty: std.Io.File, id: u8, gen: u32) anyerror!void { - var read_buf: [0x10000]u8 = undefined; - var reader = pty.readerStreaming(io, &read_buf); - while (true) { - var buf: [0x10000]u8 = undefined; - var vec = [_][]u8{&buf}; - const n = reader.interface.readVec(&vec) catch break; - if (n == 0) break; - const bytes = st.gpa.dupe(u8, buf[0..n]) catch break; - st.inbox.pushOutput(st.gpa, io, .{ .pane = id, .gen = gen, .bytes = bytes }) catch break; - wake(st); - } - st.inbox.push(st.gpa, st.io, .{ .eof = .{ .pane = id, .gen = gen } }); - wake(st); +fn wakeHost(ctx: ?*anyopaque) void { + wake(@ptrCast(@alignCast(ctx.?))); } fn wake(st: *State) void { const cb = st.runtime.wakeup orelse return; - if (st.inbox.wake_pending.swap(true, .acq_rel)) return; + if (st.wake_pending.swap(true, .acq_rel)) return; cb(st.runtime.userdata); } @@ -2417,7 +2325,7 @@ fn encodeCell(cell: pardes.Cell) Cell { .fg = encodeColor(cell.style.fg), .bg = encodeColor(cell.style.bg), .attrs = encodeAttrs(cell.style), - .flags = encodeCellFlags(cell.default, cell.style.font_role, cell.hover), + .flags = encodeCellFlags(cell.default, cell.style.font_role, false), .len = if (cell.default) 1 else cell.len, }; if (cell.default) @@ -2436,7 +2344,7 @@ fn encodeAttrs(style: pardes.CellStyle) u16 { attrs |= @as(u16, @intFromBool(style.reverse)) << 4; attrs |= @as(u16, @intFromBool(style.invisible)) << 5; attrs |= @as(u16, @intFromBool(style.strikethrough)) << 6; - attrs |= @as(u16, @intFromEnum(style.ul)) << 8; + attrs |= @as(u16, @backingInt(style.ul)) << 8; return attrs; } @@ -2447,7 +2355,7 @@ fn encodeCellFlags(default: bool, role: pardes.FontRole, hover: bool) u8 { } fn noteScrollVelocity(st: *State, delta_rows: f32, delta_cols: f32) void { - const now = monotonicNs(); + const now = std.Io.Clock.awake.now(st.io).nanoseconds; const last = st.scroll_last_ns; st.scroll_last_ns = now; // Any real travel ends a coast: that is what lets a host with momentum of @@ -2485,7 +2393,7 @@ const Spent = struct { }; fn spendScroll(st: *State, delta_rows: f32, delta_cols: f32, col: u16, row: u16) Spent { - const pane = if (st.core.paneAt(col, row)) |id| st.core.panes[id] else null; + const pane = if (mouse.paneAt(st.core, col, row)) |id| st.core.panes[id] else null; var out: Spent = .{}; var down_left = takeScrollTicks(&st.scroll_lag, delta_rows); while (down_left != 0) { @@ -2573,9 +2481,9 @@ fn takeRotationNotches(lag: *f32, degrees: f32) i32 { fn expectSameAbi(comptime C: type, comptime Z: type) !void { const c_fn = @typeInfo(C).@"fn"; const z_fn = @typeInfo(Z).@"fn"; - try std.testing.expectEqual(c_fn.params.len, z_fn.params.len); - inline for (c_fn.params, z_fn.params) |cp, zp| - try std.testing.expectEqual(@sizeOf(cp.type.?), @sizeOf(zp.type.?)); + try std.testing.expectEqual(c_fn.param_types.len, z_fn.param_types.len); + inline for (c_fn.param_types, z_fn.param_types) |cp, zp| + try std.testing.expectEqual(@sizeOf(cp.?), @sizeOf(zp.?)); try std.testing.expectEqual(@sizeOf(c_fn.return_type.?), @sizeOf(z_fn.return_type.?)); } @@ -2590,6 +2498,7 @@ test "pardes.h declares every export the way it is defined" { try expectSameAbi(@TypeOf(c.pardes_gui_tagline_font_percent), @TypeOf(pardes_gui_tagline_font_percent)); try expectSameAbi(@TypeOf(c.pardes_tagline_band_offset), @TypeOf(pardes_tagline_band_offset)); try expectSameAbi(@TypeOf(c.pardes_topbar_pane_border_rgb), @TypeOf(pardes_topbar_pane_border_rgb)); + try expectSameAbi(@TypeOf(c.pardes_topbar_pane_border_px), @TypeOf(pardes_topbar_pane_border_px)); try expectSameAbi(@TypeOf(c.pardes_tag_active_bg), @TypeOf(pardes_tag_active_bg)); try expectSameAbi(@TypeOf(c.pardes_tagline_origin_col), @TypeOf(pardes_tagline_origin_col)); try expectSameAbi(@TypeOf(c.pardes_grid_col_at), @TypeOf(pardes_grid_col_at)); @@ -2660,22 +2569,17 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@offsetOf(c.pardes_cell_s, "len"), @offsetOf(Cell, "len")); try expectEqual(@offsetOf(c.pardes_cell_s, "flags"), @offsetOf(Cell, "flags")); try expectEqual(@sizeOf(c.pardes_scene_s), @sizeOf(Scene)); - inline for (@typeInfo(Scene).@"struct".fields) |field| - try expectEqual(@offsetOf(c.pardes_scene_s, field.name), @offsetOf(Scene, field.name)); + inline for (@typeInfo(Scene).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_scene_s, name), @offsetOf(Scene, name)); try expectEqual(@sizeOf(c.pardes_panel_box_s), @sizeOf(PanelBox)); - inline for (@typeInfo(PanelBox).@"struct".fields) |field| - try expectEqual(@offsetOf(c.pardes_panel_box_s, field.name), @offsetOf(PanelBox, field.name)); + inline for (@typeInfo(PanelBox).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_panel_box_s, name), @offsetOf(PanelBox, name)); try expectEqual(@sizeOf(c.pardes_panel_track_s), @sizeOf(PanelTrack)); - inline for (@typeInfo(PanelTrack).@"struct".fields) |field| { - const c_name = comptime if (std.mem.eql(u8, field.name, "_padding")) - "reserved0" - else - field.name; - try expectEqual(@offsetOf(c.pardes_panel_track_s, c_name), @offsetOf(PanelTrack, field.name)); - } + inline for (@typeInfo(PanelTrack).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_panel_track_s, name), @offsetOf(PanelTrack, name)); try expectEqual(@sizeOf(c.pardes_image_s), @sizeOf(Image)); - inline for (@typeInfo(Image).@"struct".fields) |field| - try expectEqual(@offsetOf(c.pardes_image_s, field.name), @offsetOf(Image, field.name)); + inline for (@typeInfo(Image).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_image_s, name), @offsetOf(Image, name)); try expectEqual(@sizeOf(c.pardes_runtime_s), @sizeOf(Runtime)); try expectEqual(@as(u32, c.PARDES_COLOR_DEFAULT), color_default); @@ -2685,23 +2589,21 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@as(u8, c.PARDES_CELL_HOVER), cell_flag_hover); try expectEqual(@as(u16, c.PARDES_TOPBAR_H), pardes.TOPBAR_H); try expectEqual(@as(u32, c.PARDES_SCENE_CRT), scene_flag_crt); - try expectEqual(@as(u32, c.PARDES_SCENE_RIPPLE), scene_flag_ripple); - try expectEqual(@as(u32, c.PARDES_SCENE_GLITCH), scene_flag_glitch); - try expectEqual(@as(u8, c.PARDES_PANEL_OPENING), @intFromEnum(layout.Phase.opening)); - try expectEqual(@as(u8, c.PARDES_PANEL_MOVING), @intFromEnum(layout.Phase.moving)); - try expectEqual(@as(u8, c.PARDES_PANEL_CLOSING), @intFromEnum(layout.Phase.closing)); - try expectEqual(@as(u8, c.PARDES_PANEL_OFF), @intFromEnum(layout.Transition.off)); - try expectEqual(@as(u8, c.PARDES_PANEL_SLIDE), @intFromEnum(layout.Transition.slide)); - try expectEqual(@as(u8, c.PARDES_PANEL_ZOOM), @intFromEnum(layout.Transition.zoom)); - try expectEqual(@as(u8, c.PARDES_PANEL_DISSOLVE), @intFromEnum(layout.Transition.dissolve)); - try expectEqual(@as(u8, c.PARDES_PANEL_ASCII), @intFromEnum(layout.Transition.ascii)); - try expectEqual(@as(u8, c.PARDES_PANEL_VERTICAL), @intFromEnum(layout.Transition.vertical)); - try expectEqual(@as(u8, c.PARDES_PANEL_EDGES), @intFromEnum(layout.Transition.edges)); - try expectEqual(@as(u8, c.PARDES_PANEL_FALL), @intFromEnum(layout.Transition.fall)); - try expectEqual(@as(u8, c.PARDES_PANEL_WAVE), @intFromEnum(layout.Transition.wave)); - try expectEqual(@as(u8, c.PARDES_PANEL_CURTAIN), @intFromEnum(layout.Transition.curtain)); - try expectEqual(@as(u8, c.PARDES_PANEL_SCRAMBLE), @intFromEnum(layout.Transition.scramble)); - try expectEqual(@as(u8, c.PARDES_PANEL_TYPEWRITER), @intFromEnum(layout.Transition.typewriter)); + try expectEqual(@as(u8, c.PARDES_PANEL_OPENING), @backingInt(animation.Phase.opening)); + try expectEqual(@as(u8, c.PARDES_PANEL_MOVING), @backingInt(animation.Phase.moving)); + try expectEqual(@as(u8, c.PARDES_PANEL_CLOSING), @backingInt(animation.Phase.closing)); + try expectEqual(@as(u8, c.PARDES_PANEL_OFF), @backingInt(animation.Transition.off)); + try expectEqual(@as(u8, c.PARDES_PANEL_SLIDE), @backingInt(animation.Transition.slide)); + try expectEqual(@as(u8, c.PARDES_PANEL_ZOOM), @backingInt(animation.Transition.zoom)); + try expectEqual(@as(u8, c.PARDES_PANEL_DISSOLVE), @backingInt(animation.Transition.dissolve)); + try expectEqual(@as(u8, c.PARDES_PANEL_ASCII), @backingInt(animation.Transition.ascii)); + try expectEqual(@as(u8, c.PARDES_PANEL_VERTICAL), @backingInt(animation.Transition.vertical)); + try expectEqual(@as(u8, c.PARDES_PANEL_EDGES), @backingInt(animation.Transition.edges)); + try expectEqual(@as(u8, c.PARDES_PANEL_FALL), @backingInt(animation.Transition.fall)); + try expectEqual(@as(u8, c.PARDES_PANEL_WAVE), @backingInt(animation.Transition.wave)); + try expectEqual(@as(u8, c.PARDES_PANEL_CURTAIN), @backingInt(animation.Transition.curtain)); + try expectEqual(@as(u8, c.PARDES_PANEL_SCRAMBLE), @backingInt(animation.Transition.scramble)); + try expectEqual(@as(u8, c.PARDES_PANEL_TYPEWRITER), @backingInt(animation.Transition.typewriter)); try expectEqual(@as(u21, c.PARDES_KEY_ENTER), pardes.Key.enter); try expectEqual(@as(u21, c.PARDES_KEY_ESCAPE), pardes.Key.escape); @@ -2717,24 +2619,24 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@as(u21, c.PARDES_KEY_PAGE_DOWN), pardes.Key.page_down); try expectEqual(@as(u21, c.PARDES_KEY_DELETE), pardes.Key.delete); - try expectEqual(c.PARDES_MOUSE_LEFT, @intFromEnum(pardes.Mouse.Button.left)); - try expectEqual(c.PARDES_MOUSE_MIDDLE, @intFromEnum(pardes.Mouse.Button.middle)); - try expectEqual(c.PARDES_MOUSE_RIGHT, @intFromEnum(pardes.Mouse.Button.right)); - try expectEqual(c.PARDES_MOUSE_WHEEL_UP, @intFromEnum(pardes.Mouse.Button.wheel_up)); - try expectEqual(c.PARDES_MOUSE_WHEEL_DOWN, @intFromEnum(pardes.Mouse.Button.wheel_down)); - try expectEqual(c.PARDES_MOUSE_WHEEL_LEFT, @intFromEnum(pardes.Mouse.Button.wheel_left)); - try expectEqual(c.PARDES_MOUSE_WHEEL_RIGHT, @intFromEnum(pardes.Mouse.Button.wheel_right)); - try expectEqual(c.PARDES_MOUSE_NONE, @intFromEnum(pardes.Mouse.Button.none)); - try expectEqual(c.PARDES_MOUSE_BACK, @intFromEnum(pardes.Mouse.Button.back)); - try expectEqual(c.PARDES_MOUSE_FORWARD, @intFromEnum(pardes.Mouse.Button.forward)); - try expectEqual(c.PARDES_MOUSE_PRESS, @intFromEnum(pardes.Mouse.Kind.press)); - try expectEqual(c.PARDES_MOUSE_RELEASE, @intFromEnum(pardes.Mouse.Kind.release)); - try expectEqual(c.PARDES_MOUSE_MOTION, @intFromEnum(pardes.Mouse.Kind.motion)); - try expectEqual(c.PARDES_MOUSE_DRAG, @intFromEnum(pardes.Mouse.Kind.drag)); + try expectEqual(c.PARDES_MOUSE_LEFT, @backingInt(pardes.Mouse.Button.left)); + try expectEqual(c.PARDES_MOUSE_MIDDLE, @backingInt(pardes.Mouse.Button.middle)); + try expectEqual(c.PARDES_MOUSE_RIGHT, @backingInt(pardes.Mouse.Button.right)); + try expectEqual(c.PARDES_MOUSE_WHEEL_UP, @backingInt(pardes.Mouse.Button.wheel_up)); + try expectEqual(c.PARDES_MOUSE_WHEEL_DOWN, @backingInt(pardes.Mouse.Button.wheel_down)); + try expectEqual(c.PARDES_MOUSE_WHEEL_LEFT, @backingInt(pardes.Mouse.Button.wheel_left)); + try expectEqual(c.PARDES_MOUSE_WHEEL_RIGHT, @backingInt(pardes.Mouse.Button.wheel_right)); + try expectEqual(c.PARDES_MOUSE_NONE, @backingInt(pardes.Mouse.Button.none)); + try expectEqual(c.PARDES_MOUSE_BACK, @backingInt(pardes.Mouse.Button.back)); + try expectEqual(c.PARDES_MOUSE_FORWARD, @backingInt(pardes.Mouse.Button.forward)); + try expectEqual(c.PARDES_MOUSE_PRESS, @backingInt(pardes.Mouse.Kind.press)); + try expectEqual(c.PARDES_MOUSE_RELEASE, @backingInt(pardes.Mouse.Kind.release)); + try expectEqual(c.PARDES_MOUSE_MOTION, @backingInt(pardes.Mouse.Kind.motion)); + try expectEqual(c.PARDES_MOUSE_DRAG, @backingInt(pardes.Mouse.Kind.drag)); - try expectEqual(c.PARDES_HAPTIC_NONE, @intFromEnum(pardes.Haptic.none)); - try expectEqual(c.PARDES_HAPTIC_EXEC, @intFromEnum(pardes.Haptic.exec)); - try expectEqual(c.PARDES_HAPTIC_LOOK, @intFromEnum(pardes.Haptic.look)); + try expectEqual(c.PARDES_HAPTIC_NONE, @backingInt(pardes.Haptic.none)); + try expectEqual(c.PARDES_HAPTIC_EXEC, @backingInt(pardes.Haptic.exec)); + try expectEqual(c.PARDES_HAPTIC_LOOK, @backingInt(pardes.Haptic.look)); try expectEqual(@as(u16, c.PARDES_ATTR_BOLD), encodeAttrs(.{ .bold = true })); try expectEqual(@as(u16, c.PARDES_ATTR_DIM), encodeAttrs(.{ .dim = true })); @@ -2757,14 +2659,10 @@ test "pardes.h matches the Zig boundary" { test "scene effect flags and display clock are compact and independent" { const expectEqual = std.testing.expectEqual; - try expectEqual(@as(u32, 0), encodeSceneEffects(.{})); - try expectEqual(scene_flag_crt, encodeSceneEffects(.{ .crt = true })); - try expectEqual(scene_flag_ripple, encodeSceneEffects(.{ .ripple = true })); - try expectEqual(scene_flag_glitch, encodeSceneEffects(.{ .glitch = true })); - try expectEqual( - scene_flag_crt | scene_flag_ripple | scene_flag_glitch, - encodeSceneEffects(.{ .crt = true, .ripple = true, .glitch = true }), - ); + var post: pardes.config.Runtime.Post = .{}; + try expectEqual(@as(u32, 0), encodeSceneEffects(&post)); + _ = post.set(.crt, "", true); + try expectEqual(scene_flag_crt, encodeSceneEffects(&post)); var st: State = undefined; st.scene_ns = scene_wrap_ns - (std.time.ns_per_ms * 5); @@ -2802,12 +2700,12 @@ test "mac panel mask is a literal normalized grayscale texture" { test "mac panel ABI has the documented compact byte layout" { try std.testing.expectEqual(@as(usize, 16), @sizeOf(PanelBox)); - try std.testing.expectEqual(@as(usize, 44), @sizeOf(PanelTrack)); + try std.testing.expectEqual(@as(usize, 48), @sizeOf(PanelTrack)); try std.testing.expectEqual(@as(usize, 0), @offsetOf(PanelTrack, "serial")); try std.testing.expectEqual(@as(usize, 4), @offsetOf(PanelTrack, "pane")); try std.testing.expectEqual(@as(usize, 5), @offsetOf(PanelTrack, "phase")); try std.testing.expectEqual(@as(usize, 6), @offsetOf(PanelTrack, "effect")); - try std.testing.expectEqual(@as(usize, 7), @offsetOf(PanelTrack, "_padding")); + try std.testing.expectEqual(@as(usize, 7), @offsetOf(PanelTrack, "motion")); try std.testing.expectEqual(@as(usize, 8), @offsetOf(PanelTrack, "frame")); try std.testing.expectEqual(@as(usize, 10), @offsetOf(PanelTrack, "frame_count")); try std.testing.expectEqual(@as(usize, 12), @offsetOf(PanelTrack, "from")); @@ -2952,7 +2850,7 @@ test "mac tag layer ABI preserves logical capacity and physical grip" { logical[11].text[0] = 'Z'; logical[11].len = 1; logical[11].default = false; - core.surface.tag_layers[0] = .{ .kind = .pane, .id = 1, .serial = 42, .viewport = .{ .x = 2, .y = 1, .w = 6, .h = 1 }, .cols = 12, .cells = &logical, .bg = .{ 0x12, 0x34, 0x56 }, .cursor = .{ .col = 11, .bar = true } }; + core.surface.tag_layers[0] = .{ .kind = .pane, .id = 1, .serial = 42, .viewport = .{ .x = 2, .y = 1, .w = 6, .h = 1 }, .cols = 12, .rows = 1, .cells = &logical, .bg = .{ 0x12, 0x34, 0x56 }, .cursor = .{ .x = 11, .y = 0, .bar = true } }; defer core.surface.tag_layers[0] = .{}; try std.testing.expectEqual(@as(u32, 12), pardes_tag_layer_value(0, 0)); try std.testing.expectEqual(@as(u32, 0x123456), pardes_tag_layer_value(0, 10)); @@ -2972,17 +2870,12 @@ test "mac tag layer ABI preserves logical capacity and physical grip" { }); try std.testing.expectEqual(@as(u32, 11), pardes_tag_layer_value(0, 8)); try std.testing.expectEqual(@as(u8, 'Z'), pardes_tag_layer_cells(0).?[11].text[0]); - var canonical: [24]Cell = @splat(encodeCell(.{ .text = .{'G'} ++ .{0} ** 6, .len = 1, .default = false })); - // A look-hover under the layer is a canonical fact and survives the blank; - // the glyph it marks does not, because the layer redraws that text itself. + var canonical: [24]Cell = @splat(encodeCell(.{ .text = .{ 'G', 0, 0, 0, 0, 0, 0 }, .len = 1, .default = false })); var source: [24]pardes.Cell = @splat(.{}); - source[11].hover = true; blankTagCells(&canonical, 8, 3, &source, &core.surface.tag_layers); try std.testing.expectEqual(@as(u8, 'G'), canonical[9].text[0]); try std.testing.expectEqual(@as(u8, 'G'), canonical[18].text[0]); try std.testing.expectEqual(encodeCell(.{}).len, canonical[10].len); - try std.testing.expectEqual(@as(u8, 0), canonical[10].flags & cell_flag_hover); - try std.testing.expectEqual(cell_flag_hover, canonical[11].flags & cell_flag_hover); } test "mac window blur builtin reaches the ABI without changing opacity" { |
