diff options
Diffstat (limited to 'src/gui')
| -rw-r--r-- | src/gui/gui.zig | 487 |
1 files changed, 242 insertions, 245 deletions
diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 01272b41..a1590b48 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -22,7 +22,7 @@ const c_heap = @import("c_heap"); const ninep_io = @import("../9p_io.zig"); -const detached_client = @import("../detached/client.zig"); +const daemon = @import("../daemon.zig"); const tracy = @import("../tracy.zig"); pub const c = @import("gui_c"); // SDL3 and font.h, translated by build.zig @@ -1434,8 +1434,6 @@ const Gui = struct { tagline_percent: u8, tagline_width: u32, tagline_height: u32, - attached_layers: ?*const [pardes.MAX_PANES]pardes.Layer = null, - attached_tag_layers: ?*const [pardes.MAX_TAG_LAYERS]pardes.Layer = null, cell_w: u32, cell_h: u32, ascent: i32, @@ -1533,6 +1531,14 @@ const Gui = struct { applied_window_opacity: u8 = 100, soft_renderer: ?*c.SDL_Renderer = null, soft_texture: ?*c.SDL_Texture = null, + /// What a window is opened again with (reopenWindow): the flags (not + /// hidden), the present mode, its size when it was closed. + win_flags: c.SDL_WindowFlags = 0, + present_mode: c.SDL_GPUPresentMode = c.SDL_GPU_PRESENTMODE_VSYNC, + window_w: c_int = 1120, + window_h: c_int = 720, + /// The window runNative destroys at the end: the one open then, if any. + window_slot: ?*?*c.SDL_Window = null, soft_tex_w: u32 = 0, soft_tex_h: u32 = 0, @@ -1895,16 +1901,10 @@ fn setTransitionFields( pub const run = runNative; -fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u8) !void { +fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool) !void { const gpa = init.gpa; const env = init.environ_map; - if (env.get("PARDES_TEST_GRID") != null) { - if (attach != null) { - log.err("--attach needs a window; PARDES_TEST_GRID is headless", .{}); - return error.AttachNeedsWindow; - } - return runGrid(init, opts_in); - } + if (env.get("PARDES_TEST_GRID") != null) return runGrid(init, opts_in); const test_mode = env.get("PARDES_TEST") != null; const capture_dir = env.get("PARDES_TEST_CAPTURE_DIR"); @@ -1950,6 +1950,9 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u // opacity would dim the text as well. SDL requires this flag at creation. const surface_opacity = native_wayland; if (surface_opacity) win_flags |= c.SDL_WINDOW_TRANSPARENT; + const reopen_flags = win_flags; + // `--detach`: a window never shown, closed once the session is up. + if (headless) win_flags |= c.SDL_WINDOW_HIDDEN; // `--geometry=WxH[+X+Y]`, as X11 programs take it. var want_w: c_int = 1120; var want_h: c_int = 720; @@ -1969,7 +1972,8 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u log.err("SDL_CreateWindow: {s}", .{c.SDL_GetError()}); return error.SdlInit; }; - defer c.SDL_DestroyWindow(window); + var window_slot: ?*c.SDL_Window = window; + defer if (window_slot) |open| c.SDL_DestroyWindow(open); if (want_at) |at| _ = c.SDL_SetWindowPosition(window, at[0], at[1]); updateDisplayScale(window); if (native_wayland) log.info("Wayland opacity: background-only transparent surface", .{}); @@ -2173,6 +2177,11 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u .demo_next = if (env.get("PARDES_FRAMES_DEMO")) |name| (if (pardes.FrameStats.named(name) != null) @as(?usize, 0) else null) else null, .surface_opacity = surface_opacity, .soft_renderer = soft_renderer, + .win_flags = reopen_flags, + .present_mode = present_mode, + .window_w = want_w, + .window_h = want_h, + .window_slot = &window_slot, }; // The pipelines, textures and buffers the Gui holds, whatever they were // regrown to; the image ones are released below. @@ -2221,10 +2230,48 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u // compositor moves it, as it does a title bar. if (!test_mode and !c.SDL_SetWindowHitTest(window, hitTest, &g)) log.warn("SDL_SetWindowHitTest: {s}", .{c.SDL_GetError()}); - if (attach) |requested| return attachRequested(gpa, &g, requested); - var attached: ?detached_client.Client = null; - try localSession(init, &g, opts_in, test_mode, &attached); - if (attached) |*client| return attachedLoop(gpa, &g, client); + try localSession(init, &g, opts_in, test_mode, headless); +} + +/// Detach: the window closed (and with it its swapchain or renderer); the +/// device, the atlas and the pipelines stay for the next one. +fn closeWindow(g: *Gui) void { + _ = c.SDL_GetWindowSize(g.window, &g.window_w, &g.window_h); + _ = c.SDL_StopTextInput(g.window); + if (g.soft_renderer) |renderer| { + if (g.soft_texture) |texture| c.SDL_DestroyTexture(texture); + g.soft_texture = null; + g.soft_tex_w = 0; + g.soft_tex_h = 0; + c.SDL_DestroyRenderer(renderer); + g.soft_renderer = null; + } else c.SDL_ReleaseWindowFromGPUDevice(g.device, g.window); + c.SDL_DestroyWindow(g.window); + if (g.window_slot) |slot| slot.* = null; +} + +/// `pardes-gui --attach`: a window again, as the first was made, at the +/// size the last one had. False when the display will not give one. +fn reopenWindow(g: *Gui) bool { + const window = c.SDL_CreateWindow("pardes", g.window_w, g.window_h, g.win_flags) orelse return false; + if (g.soft_present) { + g.soft_renderer = c.SDL_CreateRenderer(window, null) orelse { + c.SDL_DestroyWindow(window); + return false; + }; + } else { + if (!c.SDL_ClaimWindowForGPUDevice(g.device, window)) { + c.SDL_DestroyWindow(window); + return false; + } + _ = c.SDL_SetGPUSwapchainParameters(g.device, window, c.SDL_GPU_SWAPCHAINCOMPOSITION_SDR, g.present_mode); + } + g.window = window; + if (g.window_slot) |slot| slot.* = window; + updateDisplayScale(window); + if (!g.capture) _ = c.SDL_SetWindowHitTest(window, hitTest, g); + _ = c.SDL_StartTextInput(window); + return true; } fn localSession( @@ -2232,7 +2279,7 @@ fn localSession( g: *Gui, opts_in: pardes.Options, test_mode: bool, - attached: *?detached_client.Client, + headless: bool, ) !void { const io = init.io; const gpa = init.gpa; @@ -2359,25 +2406,19 @@ fn localSession( defer pardes.lsp.setStatusSink(null, null); host_io.setExitWake(&queue, Queue.wakeForExit); defer host_io.setExitWake(null, null); + if (headless) { + shell.closeTheWindow(); + // Nothing else may wake the first wait. + daemon.watch(&queue, deliverNote); + } while (!core.quit) { pardes.turn.bump(&pardes.turn.restores); try core.pump(host); + // A window asked for again, or an adopted shell, from the daemon's + // thread through the queue; started after the first frame. + daemon.watch(&queue, deliverNote); if (core.quit) break; // a session that ended does not restore into one - if (core.takeAttach()) |req| { - const geom = windowCells(g); - const outcome = detached_client.attempt(gpa, req.name, geom.cols, geom.rows); - switch (outcome) { - .greeted => |client| { - attached.* = client; - break; - }, - else => { - var mbuf: [256]u8 = undefined; - core.setMessage(req.pane, attachFailure(&mbuf, outcome, req.name)); - }, - } - } if (core.takeRestore()) |rp| blk: { const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { core.reportError(core.active, "Restore", err); @@ -2426,198 +2467,6 @@ fn localSession( } } -fn attachFailure(buf: []u8, outcome: detached_client.Attempt, requested: []const u8) []const u8 { - return switch (outcome) { - .greeted => unreachable, - .no_session => if (requested.len != 0) - std.fmt.bufPrint(buf, "Attach: no detached session called '{s}'", .{requested}) catch - "Attach: no detached session under that name" - else - "Attach: nothing is detached (start one with `pardes --detach`)", - .ambiguous => |n| std.fmt.bufPrint(buf, "Attach: {d} detached sessions; say which one", .{n}) catch - "Attach: several detached sessions; say which one", - .refused => |why| switch (why) { - .version => "Attach: that session speaks a different wire version — it is another build of pardes", - .full => "Attach: that session already has every frontend slot taken", - .quitting => "Attach: that session is ending", - }, - .silent => "Attach: that session took the connection and never greeted us", - .lost => |err| std.fmt.bufPrint(buf, "Attach: lost the connection ({t})", .{err}) catch - "Attach: lost the connection", - }; -} - -fn attachRequested(gpa: std.mem.Allocator, g: *Gui, requested: []const u8) !void { - const geom = windowCells(g); - const outcome = detached_client.attempt(gpa, requested, geom.cols, geom.rows); - switch (outcome) { - .greeted => |greeted| { - var client = greeted; - return attachedLoop(gpa, g, &client); - }, - else => { - var mbuf: [256]u8 = undefined; - log.err("{s}", .{attachFailure(&mbuf, outcome, requested)}); - return switch (outcome) { - .no_session => error.NoSession, - .ambiguous => error.AmbiguousSession, - .refused => error.Refused, - .silent => error.NoGreeting, - .lost => |err| err, - .greeted => unreachable, - }; - }, - } -} - -fn attachedResize(client: *detached_client.Client, g: *const Gui, cols: u16, rows: u16) !void { - try client.send(.{ .event = .{ .resize = .{ .cols = cols, .rows = rows, .row_metrics = .{ - .body_w = @intCast(g.cell_w), - .body_h = @intCast(g.cell_h), - .tagline_w = @intCast(g.tagline_width), - .tagline_h = @intCast(g.tagline_height), - } } } }); -} - -fn attachedLoop(gpa: std.mem.Allocator, g: *Gui, client: *detached_client.Client) !void { - defer client.detach(); - _ = c.SDL_StartTextInput(g.window); - - var in: Input = .{ .client = client }; - g.attached_layers = &client.body_layers; - g.attached_tag_layers = &client.tag_layers; - var dirty = false; - var geom = windowCells(g); - try attachedResize(client, g, geom.cols, geom.rows); - while (true) { - const link = client.wait(detached_client.poll_ms); - while (true) { - const msg = (try client.next()) orelse break; - switch (msg) { - .welcome => {}, - .refuse => |why| { - log.err("session refused an already-greeted frontend: {t}", .{why}); - return error.Refused; - }, - .frame => dirty = true, - .quit => return, - .detach => return, - .set_clipboard => |text| putClipboard(gpa, text), - .read_clipboard => if (takeClipboard()) |text| { - defer c.SDL_free(text.ptr); - in.post(.{ .paste = text }); - }, - .open_link => |url| look.openLink(url), - .post => dirty = true, - } - } - try link; - - var sev = std.mem.zeroes(c.SDL_Event); - while (c.SDL_PollEvent(&sev)) dispatch(g, &in, &sev); - pollGamepad(g, &in); - if (in.lost) |err| return err; - if (in.quit) return; - - const now = windowCells(g); - if (now.cols != geom.cols or now.rows != geom.rows) { - geom = now; - try attachedResize(client, g, now.cols, now.rows); - } - // The session's chain, its files compiled there. - g.post.sync(gpa, g.device, g.swapchain_format, client.post.list(), client.post_key, null); - if (!dirty) { - // As a local window does: a chain that moves on its own redraws - // alone, once a refresh. - if (g.post.animating(client.post.animation) and g.scene_tex != null and - c.SDL_GetTicksNS() -| g.post.last_ns + std.time.ns_per_ms >= refreshNs(g)) redrawPost(g, gpa); - continue; - } - dirty = false; - paintAttached(g, gpa, client); - } -} - -fn paintAttached(g: *Gui, gpa: std.mem.Allocator, client: *detached_client.Client) void { - var surface = attachedSurface(client); - _ = renderFrame( - g, - gpa, - null, - &surface, - false, - ) catch |err| blk: { - log.err("render: {t}", .{err}); - break :blk false; - }; -} - -/// The session's frame as a surface: its cells, layers, regions and palette, -/// so its chrome is drawn from them as a local one's is. -fn attachedSurface(client: *const detached_client.Client) pardes.Surface { - var surface: pardes.Surface = .{ - .cols = client.cols, - .rows = client.rows, - .cells = client.grid.items, - .cursor = if (client.cursor) |cu| .{ .x = cu.x, .y = cu.y, .bar = cu.bar } else null, - .pointer_shape = client.pointer_shape, - .body_layers = client.body_layers, - .tag_layers = client.tag_layers, - .chrome = client.chrome, - }; - const placed = client.regions.items[0..@min(client.regions.items.len, surface.regions.len)]; - @memcpy(surface.regions[0..placed.len], placed); - surface.nregions = @intCast(placed.len); - return surface; -} - -test "an attached frontend draws the session's chrome from its frame alone" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - // A gui-shaped core, whose tags and notices are layers. - core.update(.{ .resize = .{ .cols = 80, .rows = 24, .row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 } } }); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - core.settings.focus_tint = true; - try std.testing.expect(core.executeBuiltinLine(0, "Msg a notice with a rule under it")); - core.sync(); - // Past its slide into place, where its rule shows. - for (0..30) |_| core.update(.tick); - const s = try core.render(core.scratch.allocator()); - - const wire = @import("../detached/wire.zig"); - var client: detached_client.Client = .{ .gpa = gpa }; - defer client.deinit(); - var welcome: [64]u8 = undefined; - try client.in.appendSlice(gpa, try wire.encodeServer(&welcome, .{ .welcome = .{ .slot = 0, .cols = s.cols, .rows = s.rows } })); - const out = try gpa.alloc(u8, wire.frameBound(s.cols, s.rows) + wire.layersBound(&s.body_layers, &s.tag_layers, s.regionList())); - defer gpa.free(out); - try client.in.appendSlice(gpa, try wire.encodeFrameLayers(out, s.cols, s.rows, null, s.pointer_shape, s.cells, &.{}, &s.body_layers, &s.tag_layers, s.regionList(), s.chrome)); - _ = try client.next(); - _ = try client.next(); - const attached = attachedSurface(&client); - - var g: Gui = undefined; - g.cell_w = 10; - g.cell_h = 20; - g.tagline_width = 6; - g.tagline_height = 12; - g.decor = .empty; - g.glide = .{}; - g.scroll_pane = null; - g.scroll_lag = 0; - defer g.decor.deinit(gpa); - var groups = makeGroups(&.{}, false); - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); - const local = try gpa.dupe(CellInstance, g.decor.items); - defer gpa.free(local); - try std.testing.expect(local.len > 8); - try std.testing.expect(groups.items[groups.notices].decor_count != 0); - try buildDecor(&g, gpa, &attached, &groups, fixedCellLayout(&g), 800, 480, true); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(local), std.mem.sliceAsBytes(g.decor.items)); -} - fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void { const io = init.io; const gpa = init.gpa; @@ -2691,6 +2540,7 @@ fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void { .inotify_fd = -1, .watches = &watches, .fs = fs, + .grid = true, }; defer shell.shutdownPtys(); const host = shell.host(); @@ -3125,18 +2975,10 @@ test "the window's function and editing keys reach a terminal as its cursor keys const Input = struct { core: ?*pardes.Pardes = null, - client: ?*detached_client.Client = null, quit: bool = false, - lost: ?anyerror = null, fn post(in: *Input, ev: pardes.Event) void { if (in.core) |core| return core.update(ev); - const client = in.client orelse return; - if (in.lost != null) return; - client.send(.{ .event = ev }) catch |err| switch (err) { - error.Overlong, error.WriteFailed => {}, - else => in.lost = err, - }; } fn close(in: *Input) void { @@ -3526,18 +3368,6 @@ fn gridCellAtPixels(g: *const Gui, core: ?*const pardes.Pardes, x: f32, y: f32) break; } }; - if (core == null) if (g.attached_layers) |layers| for (layers) |*layer| { - if (layer.bodyHit(x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width), @floatFromInt(g.tagline_height))) |body_hit| { - point.body_hit = body_hit; - break; - } - }; - if (core == null) if (g.attached_tag_layers) |layers| for (layers) |*layer| { - if (layer.tagHit(x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width), @floatFromInt(g.tagline_height))) |hit| { - point.tag_hit = hit; - break; - } - }; return point; } @@ -3805,7 +3635,17 @@ fn pollGamepad(g: *Gui, in: *Input) void { const Shell = struct { core: *pardes.Pardes, + /// The window's, while one is open; null while detached (`parked` has + /// it) and in the headless test grid. gui: ?*Gui = null, + parked: ?*Gui = null, + /// The headless test grid (runGrid): its own loop, no window ever. + grid: bool = false, + /// Shells a dead session left (Adopt), each waiting for the spawn of + /// the terminal pane made for it. + adoptions: [pardes.MAX_PANES]Adoption = undefined, + adoptions_len: usize = 0, + adopted: usize = 0, io: std.Io, gpa: std.mem.Allocator, fs: ?*ninep_io.Listener = null, @@ -3863,6 +3703,7 @@ const Shell = struct { } _ = libc.close(pt.fd); pt.fd = -1; + daemon.closed(pt.pid); const now = std.Io.Clock.awake.now(s.queue.io).toMilliseconds(); host_io.reapRetired(&pt.pid, &pt.kill_at, now); if (pt.pid == 0) { @@ -3917,7 +3758,83 @@ const Shell = struct { } fn host(s: *Shell) pardes.Host { - return .{ .ctx = s, .vtable = if (s.gui == null) &grid_vtable else &vtable }; + return .{ .ctx = s, .vtable = if (s.grid) &grid_vtable else &vtable }; + } + + /// Detach: the window closed, the session left running with no + /// window, for `pardes-gui --attach` to open one again. + fn detachWindow(ctx: ?*anyopaque) void { + const s = shellOf(ctx); + if (s.gui == null) return s.core.reportFailure(s.core.active, "Detach: no window is open"); + if (!daemon.kept()) return s.core.reportFailure(s.core.active, "Detach: no pardes daemon keeps this session; closing its window ends it"); + s.closeTheWindow(); + } + + fn closeTheWindow(s: *Shell) void { + const g = s.gui orelse return; + closeWindow(g); + s.parked = g; + s.gui = null; + s.presented = false; + s.surface = null; + s.core.unattended = true; + daemon.setState(true); + } + + fn openTheWindow(s: *Shell) void { + const g = s.parked orelse return; + if (!reopenWindow(g)) { + log.err("--attach: no window: {s}", .{c.SDL_GetError()}); + return daemon.setState(true); + } + s.gui = g; + s.parked = null; + s.core.unattended = false; + s.core.needs_frame = true; + resetScroll(g); + daemon.setState(false); + } + + fn watched(ctx: ?*anyopaque) bool { + return shellOf(ctx).gui != null; + } + + fn adopt(ctx: ?*anyopaque, pane: u8) void { + const s = shellOf(ctx); + if (!daemon.kept()) return s.core.reportFailure(pane, "Adopt: no pardes daemon is keeping shells for this session"); + s.adopted = 0; + daemon.adopt(); + } + + /// One shell of a dead session (`pid` 0: the last of them was told): + /// a terminal pane made for it, as the Tty word makes one, whose spawn + /// takes this pty (spawnPane). + fn adoptShell(s: *Shell, pid: libc.pid_t, fd: c_int) void { + const core = s.core; + if (pid == 0) { + var buf: [96]u8 = undefined; + return core.setMessage(core.active, if (s.adopted == 0) "Adopt: no shell of a session that died is waiting" else std.fmt.bufPrint(&buf, "Adopt: {d} shell{s} taken in; what they showed is gone", .{ s.adopted, if (s.adopted == 1) "" else "s" }) catch "Adopt: shells taken in"); + } + var newest: u32 = 0; + for (core.panes) |slot| if (slot) |pn| { + newest = @max(newest, pn.serial); + }; + if (s.adoptions_len < s.adoptions.len) { + s.adoptions[s.adoptions_len] = .{ .pid = pid, .fd = fd, .pane = null }; + s.adoptions_len += 1; + _ = core.executeBuiltinLine(core.active, "Tty"); + for (core.panes, 0..) |slot, id| if (slot) |pn| if (pn.serial > newest and pn.isTerminal()) { + // Its shell is up already: nothing to greet with `ls`. + pn.greet = false; + s.adoptions[s.adoptions_len - 1].pane = @intCast(id); + s.adopted += 1; + return; + }; + s.adoptions_len -= 1; + } + _ = libc.close(fd); + var buf: [96]u8 = undefined; + core.setMessage(core.active, std.fmt.bufPrint(&buf, "Adopt: no room for shell {d}; it ends with this session", .{pid}) catch "Adopt: no room for a shell"); } const vtable: pardes.Host.VTable = .{ @@ -3926,6 +3843,9 @@ const Shell = struct { .present = present, .post_present = postPresent, .poll_frame = pollFrame, + .watched = watched, + .detach = detachWindow, + .adopt = adopt, .spawn = spawnPane, .pty_write = ptyWrite, .pty_resize = ptyResize, @@ -3957,6 +3877,9 @@ const Shell = struct { v.post_present = gridPostPresent; v.set_clipboard = null; v.read_clipboard = null; + v.watched = null; + v.detach = null; + v.adopt = null; break :vt v; }; @@ -4051,6 +3974,14 @@ const Shell = struct { }, .files_changed => check_files = true, .fs_ready => {}, + .window => { + s.openTheWindow(); + s.saw_event = true; + }, + .adopted => |a| { + s.adoptShell(a.pid, a.fd); + s.saw_event = true; + }, }; if (check_files) s.shaders.recheck(); if (check_files and file_watch.reloadChanged(s.core, s.io, s.gpa, s.watches)) @@ -4214,7 +4145,7 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { } s.paced_ns = if (paced) tick else null; if (paced) g.pace_ns = tick; - } + } else waitDetached(core, timeout_ms); if (s.test_mode) { const r = s.feed.pump(s.gpa, &in, s.gui) catch { core.quit = true; @@ -4229,6 +4160,26 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { if (s.gui) |g| pollGamepad(g, &in); } +/// Detached: no window, asleep until the queue's wake (an SDL user event: +/// a pty's output, the daemon's window request), the core's next wake, or a +/// quit (SDL makes SIGTERM and SIGINT one). With nobody to dismiss them, +/// messages go on the clock. +fn waitDetached(core: *pardes.Pardes, timeout_ms: u32) void { + pardes.Messages.expireUnattended(core); + var ms: c_int = if (timeout_ms != 0) @intCast(@min(timeout_ms, std.math.maxInt(c_int))) else -1; + for (core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) { + ms = if (ms < 0) 100 else @min(ms, 100); + break; + }; + var sev = std.mem.zeroes(c.SDL_Event); + pardes.turn.rest(); + var got = c.SDL_WaitEventTimeout(&sev, ms); + pardes.turn.wake(); + while (got) : (got = c.SDL_PollEvent(&sev)) { + if (sev.type == c.SDL_EVENT_QUIT) core.quit = true; + } +} + fn pollFrame(ctx: ?*anyopaque) void { const s = shellOf(ctx); s.reconcilePtys(); @@ -4545,6 +4496,11 @@ fn gridPostPresent(ctx: ?*anyopaque) void { fn spawnPane(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { const s = shellOf(ctx); s.reap(); + for (s.adoptions[0..s.adoptions_len], 0..) |a, i| if (a.pane == pane) { + std.mem.copyForwards(Adoption, s.adoptions[i .. s.adoptions_len - 1], s.adoptions[i + 1 .. s.adoptions_len]); + s.adoptions_len -= 1; + return takeShell(s, pane, a); + }; // The new shell starts before a running one goes: one that cannot // start leaves the running one be (pty/ctl's exec). const running = s.ptys[pane] != null; @@ -4571,6 +4527,46 @@ fn spawnPane(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { }; } +const Adoption = struct { pid: libc.pid_t, fd: c_int, pane: ?u8 }; + +/// An adopted shell, running already, as pane `pane`'s: told the size twice +/// (one it never had, then the pane's), which makes it redraw. +fn takeShell(s: *Shell, pane: u8, a: Adoption) void { + s.closePty(pane); + s.gens[pane] +%= 1; + s.ptys[pane] = .{ .fd = a.fd, .pid = a.pid, .serial = s.core.panes[pane].?.serial, .cmd = .{} }; + var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); + const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; + _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); + if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1)); + if (!s.threads_ok) return; + s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = a.fd, .flags = .{ .nonblocking = false } }, pane, s.gens[pane]) catch |err| { + s.closePty(pane); + return s.core.reportError(pane, "terminal reader", err); + }; +} + +/// The daemon's thread: what it says, onto the queue (drainQueue). +fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { + const q: *Queue = @ptrCast(@alignCast(ctx)); + switch (note) { + .attach => |a| { + // A terminal for a window session: the daemon refuses that kind + // before it is sent, so only an old one's would be here. + if (a.tty >= 0) _ = libc.close(a.tty); + if (a.stub >= 0) daemon.refuseStub(a.stub, "a window session takes no terminal"); + if (a.tty < 0) q.push(.window); + }, + .adopted => |a| { + for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| q.push(.{ .adopted = .{ .pid = pid, .fd = fd } }); + q.push(.{ .adopted = .{ .pid = 0, .fd = -1 } }); + }, + } +} + fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { const s = shellOf(ctx); if (s.ptys[pane]) |pt| if (pt.fd >= 0) { @@ -4704,6 +4700,7 @@ test "the headless grid host round-trips a yank back as a paste" { .pipe_tasks = &pipe_tasks, .inotify_fd = -1, .watches = &watches, + .grid = true, }; core.host = shell.host(); try std.testing.expect(core.host.vtable == &Shell.grid_vtable); |
