diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-24 13:55:12 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-24 16:02:22 -0300 |
| commit | 4c635f357adb95235429d8905b8598a2643b4f3b (patch) | |
| tree | dd4f4f9b7e66b2bad71a0d30541c2b4ce2bb4cb9 /src | |
| parent | 95321ab082a750f4f1ef26d9bb21d1d3d01274f2 (diff) | |
| download | pardes-4c635f357adb95235429d8905b8598a2643b4f3b.tar.gz pardes-4c635f357adb95235429d8905b8598a2643b4f3b.zip | |
drag 2/3: a pane's or column's grip let go past the window's edge opens it in a new window (Handover.zig)
Diffstat (limited to 'src')
| -rw-r--r-- | src/Handover.zig | 307 | ||||
| -rw-r--r-- | src/detached/server.zig | 3 | ||||
| -rw-r--r-- | src/detached/wire.zig | 6 | ||||
| -rw-r--r-- | src/dump.zig | 27 | ||||
| -rw-r--r-- | src/gui/gui.zig | 75 | ||||
| -rw-r--r-- | src/host_io.zig | 14 | ||||
| -rw-r--r-- | src/macos.zig | 3 | ||||
| -rw-r--r-- | src/main.zig | 4 | ||||
| -rw-r--r-- | src/mouse.zig | 15 | ||||
| -rw-r--r-- | src/pardes.zig | 24 |
10 files changed, 467 insertions, 11 deletions
diff --git a/src/Handover.zig b/src/Handover.zig new file mode 100644 index 00000000..fdbe509b --- /dev/null +++ b/src/Handover.zig @@ -0,0 +1,307 @@ +//! Panes between windows, as a browser's tabs go between its windows. A +//! pane's grip, or a column's, released past the window's edge carries it +//! out: dumped alone (dump.dumpBytes, `carried`), it opens in a new window +//! of its own, `pardes-gui -l` of that dump. The pane closes here only once +//! the new window answers on its 9P socket, so its text is never in no +//! window at all; a failed handover leaves it where it was, and a pane +//! edited while it was on its way stays here too (both then have it). +//! +//! The core only dumps, and closes or keeps when told (`finish`); the host +//! writes the dump, and its worker (`carry`, on a thread of its own) spawns +//! the window and waits for it, posting how it went into host_io.Inbox. +const Handover = @This(); + +const std = @import("std"); +const builtin = @import("builtin"); +const pardes = @import("pardes.zig"); +const layout = @import("layout.zig"); +const dump = @import("dump.zig"); +const ninep_io = @import("9p_io.zig"); +const Pardes = pardes.Pardes; +const MAX_PANES = pardes.MAX_PANES; +const libc = std.c; + +/// The handover in flight, one at a time: its number, what it carries, +/// and each carried pane's serial and revision as it was dumped. +seq: u32 = 0, +flying: bool = false, +carried: dump.Carried = .pane, +column_serial: u32 = 0, +count: usize = 0, +serials: [MAX_PANES]u32 = @splat(0), +revisions: [MAX_PANES]u32 = @splat(0), +/// The dump the host sends, gpa-owned while the handover flies. +bytes: ?[]u8 = null, + +pub fn deinit(h: *Handover, gpa: std.mem.Allocator) void { + if (h.bytes) |b| gpa.free(b); + h.bytes = null; +} + +/// Pane slot `at` (with what is attached to it, or alone when it is itself +/// an attachment), or column `at`, released past the window's edge: dumped, +/// and the host asked to carry it. Only text panes travel: a terminal's +/// shell is this process's child and would die with the pane here. +pub fn begin(h: *Handover, p: *Pardes, carried: dump.Carried, at: usize) void { + var keep: [MAX_PANES]bool = @splat(false); + var ids: [MAX_PANES]usize = undefined; + var n: usize = 0; + switch (carried) { + .pane => { + const f = layout.findPane(p, at) orelse return; + const end = if (layout.ownerOf(p, at) == null) layout.groupEnd(p, f.col, f.idx) else f.idx + 1; + for (p.col_panes[f.col][f.idx..end]) |id| { + ids[n] = id; + n += 1; + } + }, + .column => { + if (at >= p.ncol or p.col_n[at] == 0) return; + for (p.col_panes[at][0..p.col_n[at]]) |id| { + ids[n] = id; + n += 1; + } + }, + } + const said = if (carried == .pane) at else ids[0]; + if (h.flying) return p.setMessage(said, "a pane is already on its way to another window"); + for (ids[0..n]) |id| { + const pane = p.panes[id] orelse return; + if (pane.file == null) return p.setMessage(said, if (pane.isTerminal()) + "a terminal stays in its window: its shell is this window's child" + else + "only text panes go to another window, for now"); + } + for (ids[0..n]) |id| keep[id] = true; + const bytes = dump.dumpBytes(p, &keep, carried) catch |err| return p.reportError(said, "handover", err); + h.deinit(p.gpa); + h.bytes = bytes; + h.seq +%= 1; + h.flying = true; + h.carried = carried; + h.column_serial = if (carried == .column) layout.columnSerial(p, at) else 0; + h.count = n; + for (ids[0..n], 0..) |id, i| { + const pane = p.panes[id].?; + h.serials[i] = pane.serial; + h.revisions[i] = pane.file.?.revision; + } + p.setMessage(said, if (carried == .pane) "to a new window…" else "the column, to a new window…"); + p.emit(.{ .hand_over = .{ .seq = h.seq } }); +} + +/// How the host's handover `seq` went: taken by `to` (failure null), or +/// not. Taken, its panes close here, unless one was edited since it was +/// dumped: that one stays, so neither window loses the edit. +pub fn finish(h: *Handover, p: *Pardes, seq: u32, to: []const u8, failure: ?[]const u8) void { + if (!h.flying or seq != h.seq) return; + h.flying = false; + h.deinit(p.gpa); + var buf: [320]u8 = undefined; + if (failure) |why| { + const at = p.paneBySerial(h.serials[0]) orelse p.active; + return p.reportFailure(at, std.fmt.bufPrint(&buf, "handover: {s}; the pane stays here", .{why}) catch "handover failed; the pane stays here"); + } + var kept: usize = 0; + for (h.serials[0..h.count], h.revisions[0..h.count]) |serial, revision| { + const id = p.paneBySerial(serial) orelse continue; // closed with its owner + const pane = p.panes[id].?; + if (pane.file == null or pane.file.?.revision != revision) { + // Out of its group, or the owner's close would take it along. + pane.attached_to = null; + kept += 1; + continue; + } + p.removePane(id, null) catch |err| { + kept += 1; + p.reportError(id, "handover", err); + }; + } + if (h.carried == .column) if (layout.columnBySerial(p, h.column_serial)) |c| { + if (p.col_n[c] == 0 and p.ncol > 1) layout.dropColumn(p, c); + }; + layout.compute(p); + p.setMessage(p.active, if (kept == 0) + std.fmt.bufPrint(&buf, "moved to {s}", .{to}) catch "moved" + else + std.fmt.bufPrint(&buf, "copied to {s}; edited on the way, kept here too", .{to}) catch "copied"); +} + +// ---- the host's half: a worker that carries the dump ---- + +/// A handover for a worker: the dump's file, and the window's geometry for +/// a new one. The worker owns it and frees it with `gpa`. +pub const Job = struct { + gpa: std.mem.Allocator, + seq: u32, + path: [:0]u8, + /// `--geometry=` for a new window: `WxH`, `+X+Y` when the host can place it. + geometry: [64]u8 = undefined, + geometry_len: usize = 0, + /// Where it says how it went: (seq, true, where) or (seq, false, why); + /// the words are borrowed for the call. + post: *const fn (ctx: ?*anyopaque, seq: u32, ok: bool, words: []const u8) void, + post_ctx: ?*anyopaque, +}; + +/// The file a handover's dump goes in: the runtime directory, the user's +/// alone, else the dump directory. Null-terminated, `gpa`'s. +pub fn dumpPath(gpa: std.mem.Allocator, seq: u32) ![:0]u8 { + var dir_buf: [1024]u8 = undefined; + const dir: []const u8 = if (libc.getenv("XDG_RUNTIME_DIR")) |x| std.mem.span(x) else dump.defaultDirectory(&dir_buf) orelse return error.NoDirectory; + return std.fmt.allocPrintSentinel(gpa, "{s}/pardes-handover-{d}-{d}.zon", .{ dir, libc.getpid(), seq }, 0); +} + +/// Runs the handover on its own thread, detached; it removes the dump's +/// file once someone has it, or nobody will. +pub fn start(job: *Job) !void { + const thread = try std.Thread.spawn(.{}, carry, .{job}); + thread.detach(); +} + +fn carry(job: *Job) void { + defer { + _ = libc.unlink(job.path); + job.gpa.free(job.path); + job.gpa.destroy(job); + } + var words: [256]u8 = undefined; + const pid = spawnWindow(job) catch |err| return job.post(job.post_ctx, job.seq, false, std.fmt.bufPrint(&words, "no new window: {s}", .{@errorName(err)}) catch "no new window"); + // Up when its registry entry answers: it read the dump before it + // listened (gui.localSession), so the file is no longer needed. + var entry_buf: [512]u8 = undefined; + const run = libc.getenv("XDG_RUNTIME_DIR") orelse ""; + const entry = std.fmt.bufPrint(&entry_buf, "{s}/9p/pardes/{d}", .{ std.mem.span(run), pid }) catch ""; + var waited: u32 = 0; + while (waited < 15_000) : (waited += 50) { + if (libc.kill(pid, @enumFromInt(0)) != 0) + return job.post(job.post_ctx, job.seq, false, "the new window ended before it was up"); + if (ninep_io.Client.readLimit(job.gpa, entry, "status", "status", 256)) |status| { + job.gpa.free(status); + return job.post(job.post_ctx, job.seq, true, std.fmt.bufPrint(&words, "a new window (pardes/{d})", .{pid}) catch "a new window"); + } else |_| {} + sleepMs(50); + } + _ = libc.kill(pid, libc.SIG.TERM); + job.post(job.post_ctx, job.seq, false, "the new window did not come up in 15 s"); +} + +fn sleepMs(ms: u32) void { + var ts: libc.timespec = .{ .sec = 0, .nsec = @as(isize, ms) * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); +} + +/// This program again, `-l` the dump: a new window, in a session of its own +/// (setsid) and not this one's child (forked twice), so it outlives this +/// window and leaves no zombie. Answers its pid. +fn spawnWindow(job: *Job) !libc.pid_t { + if (comptime builtin.os.tag != .linux) return error.Unsupported; + var exe_buf: [4096:0]u8 = undefined; + const n = libc.readlink("/proc/self/exe", &exe_buf, exe_buf.len - 1); + if (n <= 0) return error.NoExecutable; + exe_buf[@intCast(n)] = 0; + var geometry_z: [80:0]u8 = undefined; + const geometry = try std.fmt.bufPrintSentinel(&geometry_z, "--geometry={s}", .{job.geometry[0..job.geometry_len]}, 0); + const argv = [_:null]?[*:0]const u8{ &exe_buf, "-l", job.path, if (job.geometry_len > 0) geometry else null, null }; + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return error.NoPipe; + defer _ = libc.close(fds[0]); + const first = libc.fork(); + if (first < 0) { + _ = libc.close(fds[1]); + return error.NoFork; + } + if (first == 0) { + // Only async-signal-safe calls between fork and exec. + _ = libc.setsid(); + const second = libc.fork(); + if (second == 0) { + _ = libc.close(fds[1]); + _ = libc.execve(&exe_buf, &argv, @ptrCast(libc.environ)); + libc._exit(127); + } + _ = libc.write(fds[1], std.mem.asBytes(&second), @sizeOf(libc.pid_t)); + libc._exit(0); + } + _ = libc.close(fds[1]); + _ = libc.waitpid(first, null, 0); + var pid: libc.pid_t = 0; + if (libc.read(fds[0], std.mem.asBytes(&pid), @sizeOf(libc.pid_t)) != @sizeOf(libc.pid_t) or pid <= 0) return error.NoFork; + return pid; +} + +// ---- tests ---- + +/// Two text panes in one column, the lower one `/test.txt`'s twin made by +/// New, and the grip of pane `id` let go past the window's edge. +fn twoPanes(gpa: std.mem.Allocator) !*Pardes { + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 30 }); + errdefer p.deinit(); + _ = try p.setTestFile("alpha\nbeta\n"); + try std.testing.expect(p.executeBuiltinLine(p.active, "New")); + p.sync(); + return p; +} + +fn releaseOutside(p: *Pardes, id: usize) void { + const r = p.rects[id]; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = r.x, .row = p.tagTop(p.panes[id].?, r) } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = p.screen_w - 1, .row = r.y + 1 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = p.screen_w - 1, .row = r.y + 1, .outside = true } }); +} + +test "a grip let go past the window's edge dumps its pane alone, and closes it only once another window has it" { + const p = try twoPanes(std.testing.allocator); + defer p.deinit(); + const f = layout.findPane(p, 0).?; + try std.testing.expect(p.col_n[f.col] == 2); + const other = p.col_panes[f.col][1 - f.idx]; + const before = p.rects[other]; + releaseOutside(p, 0); + // Dumped and asked for; nothing moved yet. + try std.testing.expect(p.handover.flying); + try std.testing.expect(p.drag == .none); + try std.testing.expect(p.panes[0] != null); + try std.testing.expectEqual(before, p.rects[other]); + var parsed = try dump.readZon(std.testing.allocator, p.handover.bytes.?, "test"); + defer parsed.deinit(); + try std.testing.expectEqual(@as(?dump.Carried, .pane), parsed.value.carried); + try std.testing.expectEqual(@as(usize, 1), parsed.value.panes.len); + try std.testing.expectEqual(@as(usize, 1), parsed.value.columns.len); + try std.testing.expectEqualStrings("/test.txt", parsed.value.panes[0].file.?.path); + // A second one waits for the first. + releaseOutside(p, other); + try std.testing.expect(p.panes[other] != null); + // Refused (no window took it): it stays. + p.update(.{ .handed = .{ .seq = p.handover.seq, .failure = "no window" } }); + try std.testing.expect(!p.handover.flying); + try std.testing.expect(p.panes[0] != null); + // Taken: it closes, and the pane beside it takes its rows (Del's rule). + releaseOutside(p, 0); + const serial = p.panes[0].?.serial; + p.update(.{ .handed = .{ .seq = p.handover.seq, .to = "pardes/1" } }); + try std.testing.expect(p.paneBySerial(serial) == null); + p.sync(); + try std.testing.expectEqual(@as(usize, 1), p.col_n[layout.findPane(p, other).?.col]); +} + +test "a pane edited while it is on its way to another window stays here too" { + const p = try twoPanes(std.testing.allocator); + defer p.deinit(); + releaseOutside(p, 0); + const pane = p.panes[0].?; + pane.file.?.revision += 1; // an edit after the dump + p.update(.{ .handed = .{ .seq = p.handover.seq, .to = "pardes/1" } }); + try std.testing.expect(p.panes[0] == pane); +} + +test "a terminal's grip let go past the edge stays: its shell is this window's" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30, .shells = 3 }); + defer p.deinit(); + p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); + const id = p.col_panes[1][0]; + try std.testing.expect(p.panes[id].?.isTerminal()); + releaseOutside(p, id); + try std.testing.expect(!p.handover.flying); + try std.testing.expect(p.panes[id] != null); +} diff --git a/src/detached/server.zig b/src/detached/server.zig index eefce93e..d7dda6ba 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -201,7 +201,8 @@ pub const Session = struct { }, .search => |b| s.core.update(.{ .search = b }), // Ptys are read in the loop's own poll, not through the inbox. - .output, .eof, .files_changed, .fs_ready => {}, + // No hand_over host entry here (a session with no window): none comes. + .output, .eof, .files_changed, .fs_ready, .handed => {}, } } return batch.len != 0; diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 82614b4f..9890dc1a 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -856,7 +856,7 @@ fn clientTag(msg: ClientMsg) ClientTag { return switch (msg) { .event => |ev| switch (ev) { // Machine-local reports and 9P requests belong to the session owner. - .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .tick => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, inline else => |_, t| @field(ClientTag, @tagName(t)), }, inline else => |_, t| @field(ClientTag, @tagName(t)), @@ -986,7 +986,7 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { .pointer_leave => {}, .focus => |focused| try w.writeByte(@intFromBool(focused)), // See `clientTag`: no tag, so nothing to encode. - .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .tick => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, }, } try finishMessage(&w, at); @@ -1137,7 +1137,7 @@ pub fn clientBound(msg: ClientMsg) usize { .paste => |b| b.len, .command => |line| line.len, // See `clientTag`: not on this wire in this direction. - .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .tick => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, }, }; } diff --git a/src/dump.zig b/src/dump.zig index 140bc476..0da2513f 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -283,6 +283,10 @@ pub const Column = struct { pub const Mount = struct { name: []const u8, dial: []const u8 }; +/// What a grip carried out of its window (Handover.zig): one pane with the +/// panes attached to it, or a whole column. A session's own dump is none. +pub const Carried = enum { pane, column }; + pub const State = struct { magic: []const u8 = magic, version: u32 = version, @@ -303,6 +307,8 @@ pub const State = struct { settings: []const []const u8 = &.{}, /// Incl's directories, in order; null in older dumps (the defaults). incl: ?[]const []const u8 = null, + /// A dump a grip carried to another window; null for a session's own. + carried: ?Carried = null, }; /// A header is a text like any other: it may hold newlines, but not a @@ -710,12 +716,24 @@ test "validation bounds pane restore state" { // ---- a whole editor to and from a dump (acme keeps this in rows.c) ---- pub fn dumpState(p: *Pardes) !void { + const bytes = try dumpBytes(p, null, null); + if (p.dump_out) |d| p.gpa.free(d); + p.dump_out = bytes; + p.emit(.write_dump); +} + +/// The dump of the panes `keep` marks (every pane for null), gpa-owned: a +/// whole session's, or what a grip carries to another window (Handover.zig), +/// `carried` saying which. Only the columns holding a kept pane are in it, +/// and a carried pane's column tag is its old column's no longer. +pub fn dumpBytes(p: *Pardes, keep: ?*const [MAX_PANES]bool, carried: ?Carried) ![]u8 { const arena = p.scratch.allocator(); var slot_to_pane: [MAX_PANES]?usize = @splat(null); var dump_panes: [MAX_PANES]Pane = undefined; var panes_len: usize = 0; for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; + if (keep) |k| if (!k[id]) continue; slot_to_pane[id] = panes_len; dump_panes[panes_len] = try dumpPane(p, arena, pane); panes_len += 1; @@ -725,6 +743,7 @@ pub fn dumpState(p: *Pardes) !void { for (0..p.panes.len) |id| { const i = slot_to_pane[id] orelse continue; const owner = layout.ownerOf(p, id) orelse continue; + // An attachment carried without its owner stands on its own. dump_panes[i].attached_to = slot_to_pane[owner]; } // Zerox's twins: the text once, in the first; each other names it. @@ -753,9 +772,10 @@ pub fn dumpState(p: *Pardes) !void { column_ids[c][ids_len] = compact; ids_len += 1; }; + if (keep != null and ids_len == 0) continue; columns[columns_len] = .{ .serial = layout.columnSerial(p, c), - .tag = p.col_tags[c].own, + .tag = if (carried == .pane) null else p.col_tags[c].own, .weight = @as(f32, @floatFromInt(p.col_weight[c])) / @as(f32, @floatFromInt(column_weight_unit)), .panes = column_ids[c][0..ids_len], }; @@ -777,14 +797,13 @@ pub fn dumpState(p: *Pardes) !void { .mounts = mounts[0..p.fs.mounts.items.len], .settings = try changedSettings(p, arena), .incl = p.incl.items, + .carried = carried, }; try validate(state); var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer); - if (p.dump_out) |d| p.gpa.free(d); - p.dump_out = try out.toOwnedSlice(); - p.emit(.write_dump); + return out.toOwnedSlice(); } /// One pane as a dump keeps it, its strings in `arena`: a Restore's, and a diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 86d751f5..39eedf89 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1938,11 +1938,27 @@ 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 window = c.SDL_CreateWindow("pardes", 1120, 720, win_flags) orelse { + // `--geometry=WxH[+X+Y]`, as X11 programs take it. + var want_w: c_int = 1120; + var want_h: c_int = 720; + var want_at: ?[2]c_int = null; + if (opts_in.geometry) |spec| geometry: { + const x_at = std.mem.indexOfScalar(u8, spec, 'x') orelse break :geometry; + const plus = std.mem.indexOfAnyPos(u8, spec, x_at, "+-") orelse spec.len; + want_w = std.math.clamp(std.fmt.parseInt(c_int, spec[0..x_at], 10) catch break :geometry, 200, 16384); + want_h = std.math.clamp(std.fmt.parseInt(c_int, spec[x_at + 1 .. plus], 10) catch break :geometry, 120, 16384); + if (plus == spec.len) break :geometry; + const second = std.mem.indexOfAnyPos(u8, spec, plus + 1, "+-") orelse break :geometry; + const gx = std.fmt.parseInt(c_int, spec[plus + @intFromBool(spec[plus] == '+') .. second], 10) catch break :geometry; + const gy = std.fmt.parseInt(c_int, spec[second + @intFromBool(spec[second] == '+') ..], 10) catch break :geometry; + want_at = .{ gx, gy }; + } + const window = c.SDL_CreateWindow("pardes", want_w, want_h, win_flags) orelse { log.err("SDL_CreateWindow: {s}", .{c.SDL_GetError()}); return error.SdlInit; }; defer c.SDL_DestroyWindow(window); + 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", .{}); // On Linux the desktop's own cursor theme draws them (the compositor's @@ -3198,7 +3214,12 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { }; g.pointer_mapped = true; g.pointer_cell = mc; - in.post(.{ .mouse = pointerMouse(button, if (b.down) .press else .release, mc, pointerMods()) }); + var ev = pointerMouse(button, if (b.down) .press else .release, mc, pointerMods()); + // Let go past the window's edge (SDL follows a held button out + // of the window: Wayland's implicit grab, X11's capture). + const win = windowGeometry(g.window); + ev.outside = !b.down and (b.x < 0 or b.y < 0 or b.x >= win.window_w or b.y >= win.window_h); + in.post(.{ .mouse = ev }); }, c.SDL_EVENT_MOUSE_MOTION => { const m = sev.motion; @@ -3886,6 +3907,7 @@ const Shell = struct { .lsp = lsp, .pipe = pipe, .search = search, + .hand_over = handOver, }; const grid_vtable: pardes.Host.VTable = vt: { @@ -3984,6 +4006,11 @@ const Shell = struct { b.deinit(s.gpa); s.saw_event = true; }, + .handed => |h| { + s.core.update(.{ .handed = .{ .seq = h.seq, .to = if (h.ok) h.words else "", .failure = if (h.ok) null else h.words } }); + s.gpa.free(h.words); + s.saw_event = true; + }, .files_changed => check_files = true, .fs_ready => {}, }; @@ -4555,6 +4582,50 @@ fn search(ctx: ?*anyopaque, gen: u32) void { pardes.Stream.runHere(s.core, gen); } +/// Handover `seq`'s dump to its file, and a worker to carry it to another +/// window (Handover.start). A new window is as big as this one, and where +/// the pointer let go of it when the display lets a window say where it +/// goes (X11; on Wayland the compositor places it). +fn handOver(ctx: ?*anyopaque, seq: u32, bytes: []const u8) void { + const s = shellOf(ctx); + const Handover = pardes.Handover; + const path = Handover.dumpPath(s.gpa, seq) catch |err| return s.core.update(.{ .handed = .{ .seq = seq, .failure = @errorName(err) } }); + const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .CLOEXEC = true }, @as(libc.mode_t, 0o600)); + const written = fd >= 0 and host_io.writeFd(fd, bytes); + if (fd >= 0) _ = libc.close(fd); + if (!written) { + _ = libc.unlink(path); + s.gpa.free(path); + return s.core.update(.{ .handed = .{ .seq = seq, .failure = "cannot write its dump" } }); + } + const job = s.gpa.create(Handover.Job) catch { + _ = libc.unlink(path); + s.gpa.free(path); + return s.core.update(.{ .handed = .{ .seq = seq, .failure = "out of memory" } }); + }; + job.* = .{ .gpa = s.gpa, .seq = seq, .path = path, .post = Queue.pushHanded, .post_ctx = s.queue }; + if (s.gui) |g| { + var w: c_int = 0; + var h: c_int = 0; + _ = c.SDL_GetWindowSize(g.window, &w, &h); + var gx: f32 = 0; + var gy: f32 = 0; + _ = c.SDL_GetGlobalMouseState(&gx, &gy); + const placed = !std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); + const geometry = (if (placed) + std.fmt.bufPrint(&job.geometry, "{d}x{d}+{d}+{d}", .{ w, h, @as(i32, @intFromFloat(gx)) - 40, @as(i32, @intFromFloat(gy)) - 10 }) + else + std.fmt.bufPrint(&job.geometry, "{d}x{d}", .{ w, h })) catch ""; + job.geometry_len = geometry.len; + } + Handover.start(job) catch |err| { + _ = libc.unlink(path); + s.gpa.free(path); + s.gpa.destroy(job); + return s.core.update(.{ .handed = .{ .seq = seq, .failure = @errorName(err) } }); + }; +} + fn pollCwds(core: *pardes.Pardes, ptys: *[pardes.MAX_PANES]?Pty) void { for (ptys, 0..) |slot, id| if (slot) |pt| { if (pt.fd < 0) continue; diff --git a/src/host_io.zig b/src/host_io.zig index f5d6f375..af284e84 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -51,6 +51,9 @@ pub const Host = struct { /// Start the streaming search of this generation on a worker /// (pardes.Stream.start); absent, it runs on the loop. search: ?*const fn (ctx: ?*anyopaque, gen: u32) void = null, + /// Carry the dump of handover `seq` to another window on a worker + /// (Handover.start), which answers through the inbox's `handed`. + hand_over: ?*const fn (ctx: ?*anyopaque, seq: u32, bytes: []const u8) void = null, }; }; @@ -135,6 +138,9 @@ pub const Inbox = struct { /// A streaming search's rows (pardes.Stream), of whatever generation: /// the core drops a stale one. search: pardes.Stream.Batch, + /// How a handover went (Handover.zig): `words` is where it went, or + /// why it did not; gpa-owned. + handed: struct { seq: u32, ok: bool, words: []u8 }, files_changed, fs_ready, @@ -148,6 +154,7 @@ pub const Inbox = struct { response.deinit(gpa); }, .search => |b| b.deinit(gpa), + .handed => |h| gpa.free(h.words), .eof, .files_changed, .fs_ready => {}, } } @@ -432,6 +439,13 @@ pub const Inbox = struct { q.push(.{ .pipe = response }); } + /// A handover's end (Handover.Job.post). + pub fn pushHanded(ctx: ?*anyopaque, seq: u32, ok: bool, words: []const u8) void { + const q: *Inbox = @ptrCast(@alignCast(ctx.?)); + const copy = q.gpa.dupe(u8, words) catch return; + q.push(.{ .handed = .{ .seq = seq, .ok = ok, .words = copy } }); + } + /// A streaming search's batch (pardes.Stream.start's sink). Never /// dropped for want of room, as output is not: the worker waits for /// room, a wait its cancel ends (false: it stops). diff --git a/src/macos.zig b/src/macos.zig index 7599a02d..8d372432 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -1104,7 +1104,8 @@ fn drainInbox(st: *State) bool { // 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. - .files_changed, .fs_ready => {}, + // ponytail: no hand_over host entry on macOS yet, so none comes. + .files_changed, .fs_ready, .handed => {}, } } for (0..pardes.MAX_PANES) |pane| { diff --git a/src/main.zig b/src/main.zig index 26431324..4e6b49bb 100644 --- a/src/main.zig +++ b/src/main.zig @@ -100,6 +100,8 @@ const help_text = \\ see the same screen \\ --attach=<name> ...of the session called <name>, which is what to \\ use when more than one is running + \\ --geometry=WxH[+X+Y] the window's size in points, and where it goes + \\ where the display lets a window say (X11) \\ -h, --help show this help and exit \\ --version print the version and exit \\ @@ -418,6 +420,8 @@ fn nativeMain(std_init: std.process.Init) !void { if (mounts_len == mounts.len) badArgs(init.io, "too many mounts (maximum {d})", .{mounts.len}); mounts[mounts_len] = .{ .name = name, .dial = dial }; mounts_len += 1; + } else if (std.mem.startsWith(u8, a, "--geometry=")) { + opts.geometry = a["--geometry=".len..]; } else if (std.mem.eql(u8, a, "--nested")) { opts.nested = true; } else if (std.mem.eql(u8, a, "-w") or std.mem.eql(u8, a, "--wait")) { diff --git a/src/mouse.zig b/src/mouse.zig index 3400afbe..d8f19059 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -477,6 +477,21 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { if (m.kind == .press) p.jumpBy(if (m.button == .back) -1 else 1); return; } + // A grip let go past the window's edge, as a browser's tab dragged out + // of its window: the pane or column goes to another window. Inside, the + // grip's drag is the layout move below, as it always was. + if (m.kind == .release and m.outside and m.button == config.select_button) switch (p.drag) { + .move => |d| { + p.drag = .none; + return p.handover.begin(p, .pane, d.id); + }, + .column_move => |d| { + p.drag = .none; + const column = layout.columnBySerial(p, d.serial) orelse return; + return p.handover.begin(p, .column, column); + }, + else => {}, + }; const raw_col = @min(m.col, p.screen_w -| 1); const raw_row = @min(m.row, p.screen_h -| 1); p.pointer_raw_col = raw_col; diff --git a/src/pardes.zig b/src/pardes.zig index 79a2e5a5..99231a57 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -28,6 +28,7 @@ pub const Macro = @import("Macro.zig"); pub const Pipe = @import("Pipe.zig"); pub const Stream = @import("Stream.zig"); pub const Finder = @import("Finder.zig"); +pub const Handover = @import("Handover.zig"); pub const colors = @import("colors.zig"); pub const Theme = colors.Theme; pub const themes = colors.themes; @@ -495,6 +496,7 @@ test { _ = @import("Stream.zig"); _ = @import("Finder.zig"); _ = @import("Tables.zig"); + _ = @import("Handover.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -3600,6 +3602,10 @@ pub const Mouse = struct { /// them there. A row of text never is one; a terminal, with no rule, /// resizes by the grip. rule_above: bool = false, + /// A release past the window's edge: a grip let go there carries its + /// pane or column out of the window (Handover.zig). col and row are + /// still the last cell inside. + outside: bool = false, }; pub const Key = struct { @@ -3690,6 +3696,9 @@ pub const Event = union(enum) { pointer_leave, /// The window gained (true) or lost the host's keyboard focus. focus: bool, + /// How the host's handover `seq` went (Handover.finish): taken by `to`, + /// or `failure` says why not. Borrowed for the step. + handed: struct { seq: u32, to: []const u8 = "", failure: ?[]const u8 = null }, tick, }; @@ -3737,6 +3746,9 @@ pub const Effect = union(enum) { /// Start the disk search of this generation (Stream.start) on a worker /// posting into the shell's inbox. search: struct { gen: u32 }, + /// Carry `handover.bytes`, the dump of handover `seq`, to another + /// window, answering with `handed` (Handover.zig). + hand_over: struct { seq: u32 }, /// Write what an Edit's `w` took (`Pipe.writes`), in order. edit_write, watch: struct { pane: u8, on: bool, mode: WatchMode = .reconcile }, @@ -4319,6 +4331,10 @@ pub const Options = struct { tty_toggle: u21 = config.tty_toggle_default, /// load a dump of another instance instead of spawning shells (acme -l) load_path: ?[]const u8 = null, + /// `--geometry=WxH[+X+Y]`: a pixel shell's window size, and where it + /// goes when the display lets it say (a pane carried out of another + /// window opens one as big as that, Handover.zig). + geometry: ?[]const u8 = null, nested: bool = false, /// The core of a `--detach` session (detached/server.zig): it has no /// terminal of its own, so Attach there is refused with why. @@ -4394,6 +4410,8 @@ pub const Pardes = struct { /// The finder column, where query panes stack with SearchPlace column /// (Finder.zig). finder: Finder = .{}, + /// A pane or column on its way to another window (Handover.zig). + handover: Handover = .{}, global_tag: Text = .{ .what = .workspace }, // derived each sync rects: [MAX_PANES]Rect = @splat(.{}), @@ -4955,6 +4973,7 @@ pub const Pardes = struct { for (p.spawn_dirs) |d| if (d) |dir| gpa.free(dir); p.pipe.deinit(gpa); p.stream.deinit(gpa); + p.handover.deinit(gpa); p.locations_cache.deinit(p.tree_sitter_gpa); p.fs.deinit(gpa); p.shell_rows.reset(gpa); @@ -5858,6 +5877,10 @@ pub const Pardes = struct { p.update(.{ .pipe_resp = .{ .id = q.id, .success = false, .outputs = &.{} } }), // No workers here (a test, a board): it runs on the loop. .search => |q| if (v.search) |f| f(p.host.ctx, q.gen) else Stream.runHere(p, q.gen), + // No windows here (a test, the tty): it stays. + .hand_over => |h| if (v.hand_over) |f| { + if (p.handover.bytes) |bytes| f(p.host.ctx, h.seq, bytes); + } else p.update(.{ .handed = .{ .seq = h.seq, .failure = "no other windows here" } }), .edit_write => { // Each write takes the bytes `w` took when it ran: the text // as it was before the Edit's changes. @@ -6133,6 +6156,7 @@ pub const Pardes = struct { .pinch => |scale| p.ov_pinch_scale = scale, .touch_scroll => |delta| p.ov_touch_scroll_delta = delta, .focus => |focused| p.window_focused = focused, + .handed => |h| p.handover.finish(p, h.seq, h.to, h.failure), .pointer_leave => { p.pointer_inside = false; p.pointer_body_hit = null; |
