diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/Core.zig | 11 | ||||
| -rw-r--r-- | src/daemon.zig | 43 | ||||
| -rw-r--r-- | src/gui/gui.zig | 227 | ||||
| -rw-r--r-- | src/main.zig | 19 | ||||
| -rw-r--r-- | src/replica.zig | 28 | ||||
| -rw-r--r-- | src/tui/tui.zig | 382 | ||||
| -rw-r--r-- | src/views.zig | 23 |
7 files changed, 205 insertions, 528 deletions
diff --git a/src/Core.zig b/src/Core.zig index 7fe4f2e4..4584e395 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -1417,11 +1417,12 @@ pub fn pump(p: *Pardes, host: Host) !void { // A pty streaming into an unwatched session spent most of its time // drawing what nobody looked at. if (v.watched) |f| if (!f(h.ctx)) return; - // The other views first, each into its own window or terminal. - if (Views.several(p)) try Views.drawOthers(p, h); - // A replica client's view live (its input the last): its own - // process draws it. - if (p.undrawn & (@as(u8, 1) << @intCast(p.live)) == 0) { + // The one view this process shows (a replica client's is its own + // process's to draw), drawn as it is if another's is live. + const shown = Views.shown(p); + if (shown != p.live) { + if (shown) |k| try Views.drawOne(p, k, .{ .ctx = h.ctx, .f = v.present }); + } else { _ = p.frame_arena.reset(.{ .retain_with_limit = memory.limits.frame_kept }); p.frames.mark_update = FrameStats.nowNs(); p.frames.view = if (p.panes[p.view().active]) |pane| pane.scroll() else 0; diff --git a/src/daemon.zig b/src/daemon.zig index 93cc8fa1..bc9e9773 100644 --- a/src/daemon.zig +++ b/src/daemon.zig @@ -328,6 +328,9 @@ pub fn register(fd: ?c_int, k: Kind, named: []const u8, detached: bool) bool { return true; } +/// A session's replica clients at once (replica.Peers): `--ps` lists them. +const max_clients = 4; + fn tell(words: []const u8, fds: []const c_int) void { if (link < 0) return; _ = send(link, words, fds); @@ -350,6 +353,16 @@ pub fn setState(detached: bool) void { tell(if (detached) "state detached" else "state attached", &.{}); } +/// This session's replica clients now, each its process's pid (0 when its +/// socket's peer is not known), for `--ps`. +pub fn clients(pids: []const libc.pid_t) void { + var buf: [64]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + w.writeAll("clients") catch return; + for (pids[0..@min(pids.len, max_clients)]) |pid| w.print(" {d}", .{pid}) catch return; + tell(w.buffered(), &.{}); +} + /// Asks for the masters of sessions that died holding them; they come back /// as an `adopted` note. pub fn adopt() void { @@ -684,6 +697,9 @@ const Conn = struct { killed: bool = false, name: [128]u8 = undefined, name_len: usize = 0, + /// Its replica clients' pids, as it says them (`clients`); 0 not known. + clients: [max_clients]libc.pid_t = undefined, + nclients: u8 = 0, fn named(c: *const Conn) []const u8 { return c.name[0..c.name_len]; @@ -768,6 +784,7 @@ const Daemon = struct { w.print("daemon {d}\n", .{libc.getpid()}) catch {}; for (&d.conns, 0..) |*s, k| if (s.fd >= 0 and s.kind != null) { w.print("session {d} {t} {s} {s}\n", .{ s.pid, s.kind.?, if (s.detached) "detached" else "attached", s.named() }) catch break; + for (s.clients[0..s.nclients]) |pid| w.print("client {d}\n", .{pid}) catch break; for (d.held) |h| if (h.fd >= 0 and h.owner == @as(u8, @intCast(k))) w.print("shell {d}\n", .{h.pid}) catch break; }; for (d.held) |h| if (h.fd >= 0 and h.owner == null) w.print("orphan {d}\n", .{h.pid}) catch break; @@ -802,6 +819,7 @@ const Daemon = struct { c.pid = pid; c.detached = std.mem.eql(u8, state, "detached"); c.semantics = semantics; + c.nclients = 0; c.name_len = @min(rest.len, c.name.len); @memcpy(c.name[0..c.name_len], rest[0..c.name_len]); return d.reply(i, "ok", &.{}); @@ -810,6 +828,14 @@ const Daemon = struct { c.detached = std.mem.eql(u8, words.next() orelse "", "detached"); return; } + if (std.mem.eql(u8, verb, "clients")) { + c.nclients = 0; + while (words.next()) |w| if (c.nclients < max_clients) { + c.clients[c.nclients] = std.fmt.parseInt(libc.pid_t, w, 10) catch 0; + c.nclients += 1; + }; + return; + } if (std.mem.eql(u8, verb, "pty")) { const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch return; if (got.nfds < 1) return; @@ -872,7 +898,9 @@ const Daemon = struct { /// The detached session of kind `k` called `wanted_name`, or the one /// there is when it is empty; else null, and why not in `why` - /// (0-terminated): "other <its name>" for one of the other kind. + /// (0-terminated): "other <its name>" for one to join as a replica + /// client (of the other kind, or attached already: a session shows one + /// frontend of its own). fn find(d: *Daemon, k: Kind, wanted_name: []const u8, why: *[512]u8) ?u8 { @memset(why, 0); const other: []const u8 = switch (k) { @@ -881,11 +909,10 @@ const Daemon = struct { }; if (wanted_name.len != 0) { for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.kind != null and std.mem.eql(u8, s.named(), wanted_name)) { - if (s.kind.? != k) { + if (s.kind.? != k or !s.detached) { _ = std.fmt.bufPrint(why, "other {s}", .{wanted_name}) catch {}; return null; } - // Attached already: the session takes another view. return @as(u8, @intCast(i)); }; _ = std.fmt.bufPrint(why, "no no session called '{s}'", .{wanted_name}) catch {}; @@ -904,13 +931,16 @@ const Daemon = struct { found = @intCast(i); }; if (count == 1) return found.?; - // None detached: the one session there is, as another view of it. + // None detached: the one session there is, joined as a client. if (count == 0) { for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.kind == k) { count += 1; found = @intCast(i); }; - if (count == 1) return found.?; + if (count == 1) { + _ = std.fmt.bufPrint(why, "other {s}", .{d.conns[found.?].named()}) catch {}; + return null; + } count = 0; // None of this kind at all: the one session there is, the other kind's. var only: ?*Conn = null; @@ -1061,7 +1091,8 @@ const Daemon = struct { ninep_io.setCloexec(fd); const c = &d.conns[i]; c.* = .{ .fd = fd, .kind = k, .pid = pid, .detached = detached, .semantics = semantics }; - c.name_len = @min(rest.len, c.name.len); + c.nclients = 0; + c.name_len = @min(rest.len, c.name.len); @memcpy(c.name[0..c.name_len], rest[0..c.name_len]); } else if (std.mem.eql(u8, what, "h")) { const fd = std.fmt.parseInt(c_int, words.next() orelse "", 10) catch continue; diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 85245b54..0d8c53ca 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1098,55 +1098,6 @@ const Gui = struct { deck: deck.Deck = .{}, }; -/// The Gui's fields that are each window's own, one a view (views.zig): -/// the window and its presenting, its scroll and glide, its pointer, its -/// blink, its images, its capture. The -/// device, the atlas, the font and the pipelines are every window's. The -/// Gui holds the live window's; the others wait in `Shell.windows`. -const window_fields = [_][:0]const u8{ - "window", "soft_renderer", "soft_texture", "soft_tex_w", "soft_tex_h", - "window_w", "window_h", "scroll_pane", "scroll_rect", "scroll_body_y", - "scroll_body_h", "scroll_held_px", "scroll_col", "scroll_row", "scroll_delta", - "scroll_lag", "scroll_edge", "scroll_edge_len", "scroll_notch", "program_wheel", - "glide", "pace_ns", "frame_arrival_ns", - "blink_due", "cursor_quad_alpha", "caret", "input_ns", "pointer_present", "pointer_shape", - "pointer_cell", "prepared_images", "touch", - "live_ctrl", "live_alt", "applied_window_opacity", "capture_tex", "capture_tex_w", - "capture_tex_h", "capture_xfer", "capture_xfer_size", "captured", "capture_dir", -}; - -const GuiWindow = blk: { - @setEvalBranchQuota(100_000); - const st = @typeInfo(Gui).@"struct"; - var types: [window_fields.len]type = undefined; - var attrs: [window_fields.len]std.lang.Type.Struct.FieldAttributes = undefined; - for (window_fields, 0..) |name, i| { - const at = for (st.field_names, 0..) |n, j| { - if (std.mem.eql(u8, n, name)) break j; - } else @compileError("gui: Gui has no field " ++ name); - types[i] = st.field_types[at]; - attrs[i] = .{ .default_value_ptr = st.field_attrs[at].default_value_ptr }; - } - break :blk @Struct(.auto, null, &window_fields, &types, &attrs); -}; - -fn copyWindow(dst: anytype, src: anytype) void { - inline for (window_fields) |name| @field(dst, name) = @field(src, name); -} - -/// The live window's share of `g` as a window starts, but its SDL window -/// (reopenWindow makes that). -fn freshWindow(g: *Gui) void { - @setEvalBranchQuota(100_000); - const st = @typeInfo(Gui).@"struct"; - inline for (window_fields) |name| { - const at = comptime for (st.field_names, 0..) |n, j| { - if (std.mem.eql(u8, n, name)) break j; - } else unreachable; - if (comptime st.field_attrs[at].defaultValue(st.field_types[at])) |d| @field(g, name) = d; - } -} - /// What a window held of its own let go (closeWindow lets the window go). fn releaseWindowParts(g: *Gui, gpa: std.mem.Allocator) void { if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(g.device, texture); @@ -1858,16 +1809,8 @@ fn localSession( if (fs) |f| try f.watch(&queue, wakeFs); _ = c.SDL_StartTextInput(g.window); - // An upgraded session's views, a window each again. - if (upgrade.resumed) |*rec| if (!rec.fresh and !headless) shell.resumeWindows(); - // PARDES_TEST_VIEWS=N: N more windows from the start, each a view of the - // session (views.zig), captured under view-<k>; view 0 live after. - if (test_mode and upgrade.resumed == null) if (std.c.getenv("PARDES_TEST_VIEWS")) |n| { - for (0..std.fmt.parseInt(u8, std.mem.span(n), 10) catch 0) |_| shell.openAnotherWindow(null); - core.toView(0); - shell.follow(); - }; - defer shell.closeOtherWindows(); + // An upgraded session's window, its view's again. + if (upgrade.resumed) |*rec| if (!rec.fresh and !headless) shell.resumeWindow(); if (test_mode) setStdinRaw() catch {}; shell.threads_ok = true; @@ -1897,10 +1840,8 @@ fn localSession( const nc = host_io.restoreCore(gpa, core, rp, &shell.peers, inotify_fd, &watches) orelse break :blk; pipe_tasks.cancelAll(io); queue.discardCompletions(); - // One view, the live window (host_io.restoreCore). - shell.closeOtherWindows(); + // One view, the window's (host_io.restoreCore). shell.gview = 0; - shell.windowed = 1; shell.stopPtys(); clearNativeImages(g); g.prepared_images.clearRetainingCapacity(); @@ -2269,8 +2210,6 @@ const StdinFeed = struct { var seq_start: usize = 0; while (seq_start < len) { // ESC]777;<event>;<fields>BEL, the driver's own: - // view;<k>: what follows is window k's (k from 1), as an event - // of that window's makes its view live (route). // mouse;<down|up|motion>;<SDL button, 0 for none>;<x>;<y>[;<mods>] // mouse;wheel;<amount>;<x>;<y>[;<mods>]: a mouse event at // window pixels, built as SDL would and run through dispatch, @@ -2291,13 +2230,7 @@ const StdinFeed = struct { const event = rest[osc.len..bel]; const semi = std.mem.indexOfScalar(u8, event, ';') orelse event.len; const fields = event[@min(semi + 1, event.len)..]; - if (std.mem.eql(u8, event[0..semi], "view")) { - const k = std.fmt.parseInt(u8, fields, 10) catch 0; - if (in.shell) |sh| if (k >= 1 and pardes.views.isOpen(sh.core, k - 1)) { - sh.core.toView(k - 1); - sh.follow(); - }; - } else if (std.mem.eql(u8, event[0..semi], "mouse")) { + if (std.mem.eql(u8, event[0..semi], "mouse")) { if (g) |gp| { var parts = std.mem.splitScalar(u8, fields, ';'); const kind = parts.next() orelse ""; @@ -2553,8 +2486,7 @@ test "the window's function and editing keys reach a terminal as its cursor keys const Input = struct { core: *pardes.Pardes, - /// The shell whose windows these are: a window closed while others - /// stay takes its view with it (views.zig). + /// The shell whose window this is (views.zig: its view is `gview`). shell: ?*Shell = null, /// A replica client's (`remote`): its inputs go to its link, never /// straight to the core, which only reads here. @@ -2578,8 +2510,7 @@ const Input = struct { return; } if (in.shell) |s| { - if (s.windowsOpen() > 1) return s.closeView(s.core.live); - // The last window, with replica clients: they keep the session, + // The window, with replica clients: they keep the session, // as a Detach would, the daemon holding it. if (s.peers.count() > 0 and daemon.kept()) return s.closeTheWindow(); } @@ -3190,19 +3121,16 @@ const Shell = struct { /// The tick a paced frame is sampled at (waitInput): the clock the /// core is advanced to while anything moves. paced_ns: ?u64 = null, - /// Each other view's window, while another's is in the Gui (views.zig), - /// and the view whose window the Gui holds (`follow`). - windows: [pardes.views.max]GuiWindow = undefined, + /// The view the window shows (views.zig); a second window on the + /// session is a replica client of it (`pardes-gui --attach`). gview: u8 = 0, /// Upgrade was asked from this pane, to be done between steps (`upgradeNow`). upgrade_asked: ?u8 = null, /// This window a replica client of a session elsewhere (`remote`). remote: ?*Client = null, /// The session's replica clients (src/replica.zig), on sockets: views - /// of their own with no window here (`windowed`). + /// of their own with no window here. peers: replica.Peers = .{}, - /// The views that are this process's windows (the rest are clients'). - windowed: u8 = 1, /// This wait took only a replica's post (its input, its join): the pump /// after it reads no new time, so it moves nothing the replicas' /// speculations stand on (tui.zig's `mail_only`). @@ -3261,8 +3189,6 @@ const Shell = struct { // A replica client's: its link ends. if (s.peers.detach(s.core.live)) return; if (s.gui == null) return s.core.reportFailure(s.core.view().active, "Detach: no window is open"); - // One of several: its window goes, and the session stays in the rest. - if (s.windowsOpen() > 1) return s.closeView(s.core.live); if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon keeps this session; closing its window ends it"); s.closeTheWindow(); } @@ -3273,67 +3199,6 @@ const Shell = struct { return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS(); } - /// The Gui holds the window of the core's live view. - fn follow(s: *Shell) void { - const g = s.gui orelse return; - const k = s.core.live; - if (s.gview == k) return; - // A replica client's view has no window here: the Gui keeps the one - // it holds (`windowView` puts that view back when it acts). - if (s.windowed & (@as(u8, 1) << @intCast(k)) == 0) return; - if (s.gview < s.windows.len) copyWindow(&s.windows[s.gview], g); - copyWindow(g, &s.windows[k]); - s.gview = k; - } - - /// An event of another view's window: that view goes live. - fn route(s: *Shell, sev: *const c.SDL_Event) void { - if (!pardes.views.several(s.core)) return; - const g = s.gui orelse return; - const w = c.SDL_GetWindowFromEvent(sev) orelse return; - // The Gui's window's, while a client's view is live: its own again. - if (w == g.window) { - _ = s.windowView(); - return; - } - for (s.windows, 0..) |win, k| if (k != s.gview and pardes.views.isOpen(s.core, @intCast(k)) and win.window == w) { - s.core.toView(@intCast(k)); - return s.follow(); - }; - } - - /// `pardes-gui --attach` while a window is open: another window, a view - /// of its own (views.zig), opened as the first was; or (`existing`) an - /// upgraded session's view's window again. - fn openAnotherWindow(s: *Shell, existing: ?u8) void { - const g = s.gui orelse return; - s.follow(); - const k = existing orelse s.core.openView() orelse return log.err("--attach: this session has as many windows as it takes", .{}); - const live = s.gview; - copyWindow(&s.windows[live], g); - freshWindow(g); - if (!reopenWindow(g)) { - log.err("--attach: no window: {s}", .{c.SDL_GetError()}); - copyWindow(g, &s.windows[live]); - return s.core.closeView(k); - } - if (s.test_mode) { - // Its own grid, its captures under view-<k> (PARDES_TEST_VIEWS). - // ponytail: the path is kept for the session, a few bytes. - const cols: u32 = if (std.c.getenv("PARDES_TEST_COLS")) |v| std.fmt.parseInt(u16, std.mem.span(v), 10) catch 80 else 80; - const rows: u32 = if (std.c.getenv("PARDES_TEST_ROWS")) |v| std.fmt.parseInt(u16, std.mem.span(v), 10) catch 24 else 24; - _ = c.SDL_SetWindowSize(g.window, @intCast(cols * g.cell_w + g.capture_pad), @intCast(rows * g.cell_h + g.capture_pad)); - _ = c.SDL_SyncWindow(g.window); - g.capture = true; - g.capture_dir = std.fmt.allocPrint(s.gpa, "{s}/view-{d}", .{ s.windows[live].capture_dir, k }) catch ""; - if (g.capture_dir.len > 0) std.Io.Dir.cwd().createDirPath(s.io, g.capture_dir) catch {}; - } - s.gview = k; - s.windowed |= @as(u8, 1) << @intCast(k); - s.core.toView(k); - s.core.needs_frame = true; - } - /// The Gui's window's view live, for what the window does to its own /// (its size, its scroll): a replica client's input may have been the /// last. True when it was not, and is now. @@ -3343,25 +3208,6 @@ const Shell = struct { return true; } - /// View `k`'s window closed while others stay: the view goes with it. - fn closeView(s: *Shell, k: u8) void { - const g = s.gui orelse return; - s.core.toView(k); - s.follow(); - closeWindow(g); - releaseWindowParts(g, s.gpa); - s.gview = std.math.maxInt(u8); - s.windowed &= ~(@as(u8, 1) << @intCast(k)); - s.core.closeView(k); - // Into another window's view, if a client's was the one left live. - for (0..pardes.views.max) |i| if (s.windowed & (@as(u8, 1) << @intCast(i)) != 0 and pardes.views.isOpen(s.core, @intCast(i))) { - if (s.core.live != i) s.core.toView(@intCast(i)); - break; - }; - s.follow(); - s.core.needs_frame = true; - } - /// With replica clients, a wait takes one person's input and its pump /// makes one unit of it (tui.zig `split`): whether `sev`, a second, is /// held for the next wait. Any event but a wake is no replica's post. @@ -3380,26 +3226,6 @@ const Shell = struct { return false; } - /// How many of the session's views are windows here. - fn windowsOpen(s: *const Shell) usize { - return @popCount(s.windowed & s.core.views_open); - } - - /// The session's end: every window but the live one closed. - fn closeOtherWindows(s: *Shell) void { - const g = s.gui orelse return; - for (0..s.windows.len) |i| { - const k: u8 = @intCast(i); - if (k == s.gview or !pardes.views.isOpen(s.core, k)) continue; - var live: GuiWindow = undefined; - copyWindow(&live, g); - copyWindow(g, &s.windows[k]); - closeWindow(g); - releaseWindowParts(g, s.gpa); - copyWindow(g, &live); - } - } - fn closeTheWindow(s: *Shell) void { const g = s.gui orelse return; closeWindow(g); @@ -3503,19 +3329,14 @@ const Shell = struct { } } - /// An upgraded session's views, a window each again: the Gui's is the - /// live view's, the others open as `--attach` opens one; a replica - /// client's, kept for its rejoin (views.away), none. - fn resumeWindows(s: *Shell) void { - const live = s.core.live; - s.gview = live; + /// An upgraded session's window, its view's again; every other view + /// but a replica client's, kept for its rejoin (views.away), closes. + fn resumeWindow(s: *Shell) void { + s.gview = s.core.live; for (0..pardes.views.max) |i| { const k: u8 = @intCast(i); - if (k != live and pardes.views.isOpen(s.core, k) and !pardes.views.isAway(s.core, k)) s.openAnotherWindow(k); + if (k != s.gview and pardes.views.isOpen(s.core, k) and !pardes.views.isAway(s.core, k)) s.core.closeView(k); } - s.windowed |= @as(u8, 1) << @intCast(live); - s.core.toView(live); - s.follow(); } const vtable: pardes.Host.VTable = .{ @@ -3636,7 +3457,7 @@ const Shell = struct { }, .files_changed => check_files = true, .fs_ready => {}, - .window => if (s.gui != null) s.openAnotherWindow(null) else s.openTheWindow(), + .window => if (s.gui == null) s.openTheWindow(), .adopted => |a| s.adoptions.adoptShell(s.core, a.pid, a.fd), }; if (check_files and file_watch.reloadChanged(s.core, s.io, s.gpa, s.watches)) @@ -3658,7 +3479,6 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { const s = shellOf(ctx); const core = s.core; var in: Input = .{ .core = core, .shell = s }; - s.follow(); s.mail_only = true; s.took_input = false; defer s.waited = true; @@ -3751,21 +3571,21 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { motion = sev; } else { if (motion) |*m| { - s.route(m); + _ = s.windowView(); dispatch(g, &in, m); } motion = null; if (sev.type == c.SDL_EVENT_MOUSE_MOTION) { motion = sev; } else { - s.route(&sev); + _ = s.windowView(); dispatch(g, &in, &sev); } } if (!c.SDL_PollEvent(&sev)) break; } if (motion) |*m| { - s.route(m); + _ = s.windowView(); dispatch(g, &in, m); } } @@ -3792,11 +3612,11 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { pardes.turn.wake(); if (more) { if (!s.split(&sev)) { - s.route(&sev); + _ = s.windowView(); dispatch(g, &in, &sev); while (c.SDL_PollEvent(&sev)) { if (s.split(&sev)) break; - s.route(&sev); + _ = s.windowView(); dispatch(g, &in, &sev); } } @@ -3842,7 +3662,6 @@ fn waitDetached(core: *pardes.Pardes, timeout_ms: u32) void { fn pollFrame(ctx: ?*anyopaque) void { const s = shellOf(ctx); - s.follow(); s.reconcilePtys(); const core = s.core; if (s.fs) |f| if (f.tick().pending) s.queue.push(.fs_ready); @@ -4110,7 +3929,6 @@ fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { const core = s.core; // A replica client draws outside the pump, which marks it there. if (s.remote != null) core.frames.mark_render = pardes.FrameStats.nowNs(); - s.follow(); const g = s.gui orelse return; frame_started_ns = monoNs(); const frame = surface; @@ -4129,7 +3947,6 @@ fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { fn postPresent(ctx: ?*anyopaque) void { const s = shellOf(ctx); - s.follow(); const g = s.gui orelse return; // No image (a minimized window): nothing was drawn to point at. if (!s.presented) return; @@ -7628,9 +7445,7 @@ fn rulePx(chrome: *const pardes.Chrome) f32 { /// by which every size given in logical pixels is drawn, as acme scales its /// Border, ButtonBorder and Scrollgap (scalesize). Cells, glyphs and what is /// measured in them are already the display's pixels and are not scaled. -/// ponytail: one per process: a session's windows (views.zig) on screens -/// of two densities draw at the density of the last one opened or moved; -/// a field of `window_fields` when that matters. +/// One per process, as its window is. var display_scale: f32 = 1; /// The window's display scale, or PARDES_TEST_SCALE (a harness forcing 2x); diff --git a/src/main.zig b/src/main.zig index 6f8a9923..623b6033 100644 --- a/src/main.zig +++ b/src/main.zig @@ -100,9 +100,9 @@ const help_text = \\ --attach show the one detached session here (with \\ none, the one session): in this terminal for \\ `pardes`, a window for `pardes-gui`. One - \\ attached already gets another view; one of the - \\ other kind (a window's session in a terminal, - \\ or the reverse) is joined as a client, as + \\ attached already, or of the other kind (a + \\ window's session in a terminal, or the + \\ reverse), is joined as a client, as \\ --attach=<sock>:<name>. Returns when the \\ session detaches or ends \\ --attach=<name> ...the session called <name> (its --9p or @@ -117,8 +117,8 @@ const help_text = \\ --attach=<sock>:<name> ...through that socket (a path, with a '/'), \\ one forwarded already, or this machine's \\ --ps what the pardes daemon keeps: each session (its - \\ pid, kind, whether attached) and its shells, then - \\ the shells no session holds + \\ pid, kind, whether attached), its clients and its + \\ shells, then the shells no session holds \\ --kill=<name> end session <name> and its shells (TERM, then \\ KILL 2 s later); unsaved changes are lost \\ --kill-all end every session and every shell the daemon keeps @@ -858,6 +858,8 @@ fn manage(io: std.Io, verb: []const u8, name: []const u8) noreturn { const kind = it.next() orelse ""; const state = it.next() orelse ""; w.print(" session {s} {s} ({s}, {s})\n", .{ std.mem.trim(u8, it.rest(), " "), pid, kind, state }) catch break; + } else if (std.mem.eql(u8, what, "client")) { + w.print(" client {s} {s}\n", .{ pid, comm }) catch break; } else if (std.mem.eql(u8, what, "shell")) { w.print(" shell {s} {s}\n", .{ pid, comm }) catch break; } else if (std.mem.eql(u8, what, "orphan")) { @@ -1023,8 +1025,8 @@ fn remoteAttach(init: std.process.Init, opts: pardes.Options, where: []const u8, /// the daemon) to the detached session of that name, or the only one, and /// this process its stub until the session leaves it. `pardes-gui /// --attach`: the session asked to open its window again, and done. A -/// session of the other kind is joined as a replica client, through this -/// machine's replica socket. +/// session attached already, or of the other kind, is joined as a replica +/// client, through this machine's replica socket. fn attachTo(init: std.process.Init, opts: pardes.Options, name: []const u8) noreturn { const io = init.io; var words: [600]u8 = undefined; @@ -1057,7 +1059,8 @@ fn attachTo(init: std.process.Init, opts: pardes.Options, name: []const u8) nore } } -/// A session of the other kind (`--attach`'s): a replica client of it here. +/// A session attached already or of the other kind (`--attach`'s): a +/// replica client of it here. fn crossAttach(init: std.process.Init, opts: pardes.Options, name: []const u8) noreturn { var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined; const sock = daemon.replicaSocket(&sock_buf) orelse die(init.io, "--attach: no runtime directory for the replica socket", .{}); diff --git a/src/replica.zig b/src/replica.zig index 40353d89..622537d7 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -1443,11 +1443,24 @@ pub const Framer = struct { } }; +/// The process at the other end of unix socket `fd` (Linux's SO_PEERCRED), +/// or 0: a client's through ssh is ssh's. +fn peerPid(fd: c_int) libc.pid_t { + if (comptime builtin.os.tag != .linux) return 0; + const Cred = extern struct { pid: libc.pid_t, uid: libc.uid_t, gid: libc.gid_t }; + var cred: Cred = undefined; + var len: libc.socklen_t = @sizeOf(Cred); + if (libc.getsockopt(fd, libc.SOL.SOCKET, libc.SO.PEERCRED, &cred, &len) != 0) return 0; + return cred.pid; +} + pub const Peer = struct { peers: *Peers, fd: c_int, id: u16, view: u8, + /// Its process (its socket's peer), for `--ps`; 0 not known. + pid: libc.pid_t = 0, /// Its bye said it joins again for its view (a divergence's rejoin): /// kept for it (views.away), not closed. Its reader's, read after its end. again: bool = false, @@ -2011,6 +2024,8 @@ pub const Peers = struct { return; } slot.* = peer; + peer.pid = peerPid(fd); + ps.tellClients(); // Its terminals afresh, after its dump and before any unit. if (ps.screens.addPeer()) |sid| { peer.sid = sid; @@ -2025,6 +2040,7 @@ pub const Peers = struct { slot.* = null; }; log.info("client {d} left '{s}'", .{ peer.id, ps.name }); + ps.tellClients(); ps.screens.dropPeer(peer.sid); core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view)); ps.closeViewOf(core, peer, peer.again); @@ -2120,6 +2136,17 @@ pub const Peers = struct { peer.dump = &.{}; } + /// The daemon told the clients there are now (`pardes --ps`). + fn tellClients(ps: *const Peers) void { + var pids: [pardes.views.max]libc.pid_t = undefined; + var n: usize = 0; + for (ps.list) |slot| if (slot) |peer| { + pids[n] = peer.pid; + n += 1; + }; + daemon.clients(pids[0..n]); + } + /// Detach typed in client view `k`'s: its link ends (its reader says /// it is gone, and the next boundary lets it go). pub fn detach(ps: *Peers, k: u8) bool { @@ -2155,6 +2182,7 @@ pub const Peers = struct { ps.screens.dropPeer(peer.sid); ps.letGo(peer); }; + ps.tellClients(); ps.stop(core); ps.lock.lockUncancelable(ps.io); for (ps.inbox.items) |note| switch (note) { diff --git a/src/tui/tui.zig b/src/tui/tui.zig index 860e96c8..0c74cbaa 100644 --- a/src/tui/tui.zig +++ b/src/tui/tui.zig @@ -23,11 +23,9 @@ extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); -/// What a terminal's input reader keeps, one a terminal (views.zig): its -/// graphemes, the frame it waits on the answer to, the shm probe, and the -/// view its input is. +/// What the terminal's input reader keeps: its graphemes, the frame it +/// waits on the answer to, and the shm probe. const Feed = struct { - view: u8 = 0, cache: vaxis.GraphemeCache = .{}, ack: FrameAck = .{}, /// The terminal answered the shared-memory probe (`kittyShmProbe`): it @@ -43,25 +41,6 @@ const Feed = struct { shm_probing: std.atomic.Value(bool) = .init(false), }; -/// A terminal's input onto the loop's queue, as its view's: a `from` goes -/// ahead of it whenever another terminal posted last. With one terminal -/// none ever does. -const Poster = struct { - loop: *Loop, - view: u8, - var lock: std.Io.Mutex = .init; - var last: u8 = 0; - - pub fn postEvent(p: Poster, ev: Msg) !void { - lock.lockUncancelable(p.loop.io); - defer lock.unlock(p.loop.io); - if (last != p.view) { - try p.loop.postEvent(.{ .from = p.view }); - last = p.view; - } - try p.loop.postEvent(ev); - } -}; const kitty_shm_probe_id = 0x7fff_fff1; var kitty_shm_serial: u32 = 0; /// Transmissions an unread shm segment outlives before it is removed. @@ -129,8 +108,6 @@ const Msg = union(enum) { adopted: struct { pid: posix.pid_t, fd: posix.fd_t }, /// A timed wait ran out: the core's next wake has come. wake, - /// The input after this is the terminal of this view's (Poster). - from: u8, /// A SIGWINCH: a terminal changed size (Shell.winched). winched, /// A SIGHUP: the session's own terminal hung up. @@ -187,12 +164,11 @@ fn inputReader(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) void { if (err == error.Canceled) return; std.log.err("terminal input: {s}", .{@errorName(err)}); }; - (Poster{ .loop = loop, .view = feed.view }).postEvent(.quit) catch {}; + loop.postEvent(.quit) catch {}; } fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void { - const post: Poster = .{ .loop = loop, .view = feed.view }; - try post.postEvent(.{ .winsize = try tty.getWinsize() }); + try loop.postEvent(.{ .winsize = try tty.getWinsize() }); var parser: vaxis.Parser = .{}; var buf: [1024]u8 = undefined; var carried: usize = 0; @@ -253,7 +229,7 @@ fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void { // chord, and a shell pane was typed its private-use code. if (result.event) |event| if (event == .key_press and event.key_press.isModifier()) continue; if (result.event) |event| - vaxis.loop.handleEventGeneric(post, vx, &feed.cache, Msg, event, vx.opts.system_clipboard_allocator) catch |err| { + vaxis.loop.handleEventGeneric(loop, vx, &feed.cache, Msg, event, vx.opts.system_clipboard_allocator) catch |err| { if (event == .paste) if (vx.opts.system_clipboard_allocator) |gpa| gpa.free(@constCast(event.paste)); return err; }; @@ -1163,7 +1139,7 @@ pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null); var tty_buf: [0x10000]u8 = undefined; - var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa), .primary = true }; + var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa) }; defer screen.kitty.deinit(); switch (term) { .open => try screen.enter(try vaxis.Tty.init(io, &tty_buf)), @@ -1269,7 +1245,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se posix.sigaction(.WINCH, &.{ .handler = .{ .handler = keepSignal }, .mask = posix.sigemptyset(), .flags = 0 }, null); posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null); var tty_buf: [0x10000]u8 = undefined; - var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa), .primary = true }; + var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa) }; defer screen.kitty.deinit(); try screen.enter(try vaxis.Tty.init(io, &tty_buf)); defer screen.leave(); @@ -1294,7 +1270,8 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se .frame = &frame_arena, .paste_buf = &paste_buf, .inotify_fd = -1, - .from = joined.view, + .own = joined.view, + .screen = &screen, .remote = &remote_link, }; @@ -1307,10 +1284,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se // session let it go to upgrade. The terminal stays as it is. while (true) { sh.core = r.core(); - sh.from = joined.view; - sh.terms = @splat(null); - sh.terms[joined.view] = &screen; - screen.feed.view = joined.view; + sh.own = joined.view; link.reset(r, &joined); var reader_done: std.atomic.Value(bool) = .init(false); const reader = try std.Thread.spawn(.{}, linkReader, .{ gpa, joined.fd, &joined.rest, &loop, &reader_done }); @@ -1396,9 +1370,8 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se /// A terminal a session draws on, while it has one: entered (raw, the /// alternate screen, mouse and paste reports) and left (all of it put back, /// the terminal closed) at the session's start and end, and at a detach and -/// a reattach in between (daemon.zig). One a view (views.zig): the session's -/// own (`primary`, its stub `daemon.stub`), and one more for each terminal -/// `pardes --attach`ed while it is attached, which keeps its own. +/// a reattach in between (daemon.zig), its stub `daemon.stub`. One a +/// process: a second terminal on a session is a replica client of it. const Screen = struct { io: std.Io, gpa: std.mem.Allocator, @@ -1407,11 +1380,6 @@ const Screen = struct { tty: vaxis.Tty = undefined, vx: vaxis.Vaxis = undefined, on: bool = false, - primary: bool = false, - /// The pipe to its stub, an attached one's (the primary's is daemon.stub). - stub: posix.fd_t = -1, - /// Its slot in Killed. - killed: ?usize = null, feed: Feed = .{}, thread: ?std.Io.Future(void) = null, /// The kitty images it holds, by placement key. @@ -1446,12 +1414,11 @@ const Screen = struct { try sc.vx.setMouseMode(sc.tty.writer(), true); try sc.vx.setBracketedPaste(sc.tty.writer(), true); if (comptime !builtin.is_test) { - sc.killed = Killed.arm(sc.tty.fd.handle, sc.tty.termios); + Killed.arm(sc.tty.fd.handle, sc.tty.termios); // What a panic puts back (vaxis.recover). - if (sc.primary) vaxis.tty.global_tty = sc.tty; + vaxis.tty.global_tty = sc.tty; } - const view = sc.feed.view; - sc.feed = .{ .view = view }; + sc.feed = .{}; sc.caps_pending = true; sc.size = null; sc.on = true; @@ -1460,28 +1427,17 @@ const Screen = struct { fn leave(sc: *Screen) void { if (!sc.on) return; sc.on = false; - if (sc.killed) |slot| Killed.disarm(slot); - sc.killed = null; + Killed.disarm(); clearNativeImages(&sc.kitty, &sc.vx, &sc.tty); sc.vx.exitAltScreen(sc.tty.writer()) catch {}; sc.vx.deinit(sc.gpa, sc.tty.writer()); - if (comptime !builtin.is_test) if (sc.primary) { - vaxis.tty.global_tty = null; - }; + if (comptime !builtin.is_test) vaxis.tty.global_tty = null; sc.tty.deinit(); // restore cooked termios LAST, after vx flushed its resets } - /// Its stub told the terminal is detached (it ends, and its shell has - /// the terminal back). - fn sayDetached(sc: *Screen) void { - if (sc.primary) return daemon.tellStubDetached(); - daemon.tellStub(sc.stub, "d{s}", .{daemon.name()}); - sc.stub = -1; - } - /// Its terminal hung up, or the stub that waits on it is gone. fn hungUp(sc: *const Screen) bool { - const stub = if (sc.primary) daemon.stub else sc.stub; + const stub = daemon.stub; const handle = if (@TypeOf(sc.tty.fd) == std.Io.File) sc.tty.fd.handle else sc.tty.fd; var fds = [_]posix.pollfd{ .{ .fd = handle, .events = 0, .revents = 0 }, @@ -1491,79 +1447,38 @@ const Screen = struct { const gone = posix.POLL.HUP | posix.POLL.ERR; return fds[0].revents & gone != 0 or (stub >= 0 and fds[1].revents & gone != 0); } - - fn setStub(sc: *Screen, fd: posix.fd_t) void { - if (sc.primary) daemon.stub = fd else sc.stub = fd; - } - - /// Another terminal's Screen, on the heap with a buffer of its own - /// (`destroy` lets both go); null with no room for either. - fn create(io: std.Io, gpa: std.mem.Allocator, env: *std.process.Environ.Map) ?*Screen { - const sc = gpa.create(Screen) catch return null; - const buf = gpa.alloc(u8, 0x10000) catch { - gpa.destroy(sc); - return null; - }; - sc.* = .{ .io = io, .gpa = gpa, .env = env, .buf = buf, .kitty = .init(gpa) }; - return sc; - } - - /// The terminal put back and its stub told; an attached one's Screen - /// freed (the session's own stays, a view of none). - fn drop(sc: *Screen, how: Shell.Leaving) void { - sc.leave(); - if (sc.primary) return sc.sayDetached(); - switch (how) { - .detach => sc.sayDetached(), - .exit => { - daemon.tellStub(sc.stub, "x{d}", .{0}); - sc.stub = -1; - }, - } - sc.destroy(); - } - - fn destroy(sc: *Screen) void { - sc.glide.deinit(sc.gpa); - sc.art.deinit(sc.gpa); - sc.kitty.deinit(); - sc.gpa.free(sc.buf); - sc.gpa.destroy(sc); - } }; -/// SIGTERM or SIGHUP: each terminal put back as a clean exit leaves it -- +/// SIGTERM or SIGHUP: the terminal put back as a clean exit leaves it -- /// the main screen, no mouse, paste or keyboard modes, the cursor shown, /// cooked termios -- and then the signal's own death. A nested editor /// killed in a pane must not leave that pane's terminal wedged. /// Async-signal-safe: write, tcsetattr, sigaction, raise. const Killed = struct { - var fds: [pardes.views.max]posix.fd_t = @splat(-1); - var cooked: [pardes.views.max]posix.termios = undefined; + var fd: posix.fd_t = -1; + var cooked: posix.termios = undefined; const reset = "\x1b[<u\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1004l\x1b[?2004l\x1b[0m\x1b[?25h\x1b[?1049l"; - fn arm(tty_fd: posix.fd_t, termios: posix.termios) ?usize { - const slot = std.mem.findScalar(posix.fd_t, &fds, -1) orelse return null; - cooked[slot] = termios; - fds[slot] = tty_fd; + fn arm(tty_fd: posix.fd_t, termios: posix.termios) void { + cooked = termios; + fd = tty_fd; const on: posix.Sigaction = .{ .handler = .{ .handler = handle }, .mask = posix.sigemptyset(), .flags = posix.SA.RESETHAND }; posix.sigaction(.TERM, &on, null); // A hangup a daemon keeps the session through is winchWatch's. if (daemon.link < 0) posix.sigaction(.HUP, &on, null); - return slot; } /// The terminal gone (put back, or detached): a TERM still takes the /// socket, the prompt files and the shells with it, and leaves the /// terminal alone. - fn disarm(slot: usize) void { - fds[slot] = -1; + fn disarm() void { + fd = -1; } fn handle(sig: posix.SIG) callconv(.c) void { - for (fds, &cooked) |fd, *termios| if (fd >= 0) { + if (fd >= 0) { _ = std.c.write(fd, reset, reset.len); - _ = std.c.tcsetattr(fd, .FLUSH, termios); - }; + _ = std.c.tcsetattr(fd, .FLUSH, &cooked); + } // The 9P socket and private prompt files go too: a killed editor // leaves none behind. Its shells too, the daemon's dups let go. ninep_io.unlinkOwnSocket(); @@ -1627,7 +1542,7 @@ fn localSession( .fs = fs, .test_clock = host_io.testClock(), }; - sh.terms[0] = screen; + sh.screen = screen; sh.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake_ctx = loop, .wake = wakeForReplica }; defer sh.peers.deinit(); // Before the core goes: each client sees its link end. @@ -1636,13 +1551,6 @@ fn localSession( host_io.setExitWake(loop, wakeForExit); defer screen.glide.deinit(gpa); defer screen.art.deinit(gpa); - // The terminals of the other views end with the session: each put back, - // its stub told. - defer for (&sh.terms) |*slot| if (slot.*) |sc| if (!sc.primary) { - stopInput(io, &sc.thread); - sc.drop(.exit); - slot.* = null; - }; defer { host_io.setExitWake(null, null); pardes.lsp.setStatusSink(null, null); @@ -1695,7 +1603,7 @@ fn localSession( core.host = host; // An upgraded session's terminals, its own again. - if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec, screen); + if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec); // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig). sh.setAttended(sh.attached()); while (core.nextEffect()) |effect| core.perform(effect); @@ -1714,18 +1622,6 @@ fn localSession( if (screen.on) try screen.vx.queryTerminalSend(screen.tty.writer()); // Detached from the start, nothing else may wake the first wait. if (!screen.on) daemon.watch(loop, deliverNote); - // PARDES_TEST_VIEWS: the terminals at these paths are views of the - // session too, from its start, as `pardes --attach`ed ones are (the - // snapshot harness's `start ... views=N`). - if (upgrade.resumed == null) if (init.environ_map.get("PARDES_TEST_VIEWS")) |paths| { - var it = std.mem.tokenizeScalar(u8, paths, ' '); - while (it.next()) |path| { - var path_buf: [256]u8 = undefined; - const z = std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0) catch continue; - const fd = libc.open(z, .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }, @as(libc.mode_t, 0)); - if (fd >= 0) sh.attachTerminal(fd, -1, null); - } - }; sh.threads_ok = true; for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| { @@ -1755,18 +1651,10 @@ fn localSession( sh.pipe_tasks.cancelAll(io); for (&sh.gens) |*generation| generation.* +%= 1; for (0..pardes.MAX_PANES) |pane| Shell.closePty(&sh, @intCast(pane)); - // One view, the live one's terminal (host_io.restoreCore). - const live = sh.term().?; - for (&sh.terms) |*slot| if (slot.*) |sc| if (sc != live) { - stopInput(io, &sc.thread); - sc.drop(.detach); - slot.* = null; - }; - sh.terms = @splat(null); - sh.terms[0] = live; + // One view, the terminal's (host_io.restoreCore). + const live = screen; stopInput(io, &live.thread); - live.feed.view = 0; - sh.from = 0; + sh.own = 0; if (live.on) startInput(loop, live) catch {}; if (live.on) clearNativeImages(&live.kitty, &live.vx, &live.tty); nc.view().frontend.native_images = live.on and live.vx.caps.kitty_graphics; @@ -1836,11 +1724,10 @@ const Shell = struct { core: *pardes.Pardes, prompt_rcs: *const host_io.Shell.PromptFiles, loop: *Loop, - /// Each view's terminal, by view (views.zig): the session's own first; - /// none in tests. - terms: [pardes.views.max]?*Screen = @splat(null), - /// The view the input taken now is from (`Msg.from`). - from: u8 = 0, + /// The terminal (none in tests), and the view it shows: a second + /// terminal on the session is a replica client (`pardes --attach`). + screen: ?*Screen = null, + own: u8 = 0, frame: *std.heap.ArenaAllocator, paste_buf: *std.Io.Writer.Allocating, inotify_fd: c_int, @@ -1857,8 +1744,6 @@ const Shell = struct { job_tasks: PipeTasks = .{}, threads_ok: bool = false, check_files: bool = false, - // ponytail: one bracketed paste at a time for every terminal: keys - // another terminal sends while one pastes join its paste. in_paste: bool = false, /// PARDES_TEST_CLOCK's virtual time (host_io.testClock), and where the /// running-out wait moves it: the core's next wake. @@ -1894,8 +1779,6 @@ const Shell = struct { /// its inputs go to the replica, never straight to the core. remote: ?*Remote = null, - const Leaving = enum { detach, exit }; - /// A terminal's input, to the core, or to a replica client's engine /// (applied at once there, and sent to the session). fn feed(s: *Shell, ev: pardes.Event) void { @@ -1906,8 +1789,7 @@ const Shell = struct { /// Whether a terminal of this process's shows the session, or /// nothing (a test) can. fn local(s: *const Shell) bool { - for (s.terms) |slot| if (slot != null) return true; - return false; + return s.screen != null; } /// Whether anyone looks at the session: a terminal here, or a replica @@ -1975,25 +1857,20 @@ const Shell = struct { return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); } - /// The live view's terminal (null in tests). + /// The terminal, while its view is live (null in tests, and while a + /// replica client's is: its input the last). fn term(s: *const Shell) ?*Screen { - return s.terms[s.core.live]; + return if (s.core.live == s.own) s.screen else null; } fn attached(s: *const Shell) bool { - const screen = s.term() orelse return true; + const screen = s.screen orelse return true; return screen.on; } - /// Drawn only while a terminal shows it: a replica client's view live - /// (its input the last), whichever terminal here shows another. + /// Drawn only while a terminal shows it. fn watched(ctx: ?*anyopaque) bool { - const s = of(ctx); - if (s.term() == null and s.local()) { - for (s.terms) |slot| if (slot) |sc| if (sc.on) return true; - return false; - } - return s.attached(); + return of(ctx).attached(); } /// Detach: the terminal put back and let go, the stub told (it ends, @@ -2003,24 +1880,12 @@ const Shell = struct { // A replica client's: its link ends. if (s.peers.detach(s.core.live)) return; if (!s.attached()) return s.core.reportFailure(s.core.view().active, "Detach: no terminal is attached"); - // One of several: its view goes, and the session stays on the rest. - if (pardes.views.count(s.core) > 1) return s.dropView(s.core.live, .detach); if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon keeps this session (it is its terminal's job)"); s.leaveTerminal(); } - /// View `k`'s terminal let go (detached, or gone) while others stay: the - /// view goes with it. - fn dropView(s: *Shell, k: u8, how: Leaving) void { - const sc = s.terms[k] orelse return; - stopInput(s.io, &sc.thread); - s.terms[k] = null; - s.core.closeView(k); - sc.drop(how); - } - fn leaveTerminal(s: *Shell) void { - const screen = s.term() orelse return; + const screen = s.screen orelse return; stopInput(s.io, &screen.thread); screen.leave(); s.core.view().frontend.native_images = false; @@ -2031,46 +1896,33 @@ const Shell = struct { for (0..3) |i| _ = libc.dup2(null_fd, @intCast(i)); if (null_fd > 2) _ = libc.close(null_fd); } - screen.sayDetached(); + daemon.tellStubDetached(); daemon.setState(true); } - /// `pardes --attach`'s terminal: for a detached session its own again, - /// entered as the first one was; for one attached already, a view of - /// its own (views.zig). Sized, asked what it can do, and drawn whole. + /// `pardes --attach`'s terminal, for a detached session: its own again, + /// entered as the first one was, sized, asked what it can do, and drawn + /// whole. One attached already takes no other (the daemon makes a second + /// a replica client). fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t, cooked: ?posix.termios) void { - // A replica client's view live (its input the last) has no terminal - // here: the session's own is the one a terminal takes, or joins. - const live = s.term() orelse for (s.terms) |slot| { - if (slot) |sc| if (sc.primary) break sc; - } else { + const screen = s.screen orelse { _ = libc.close(fd); return refuse(stub, "that session has no terminal of its own to attach to"); }; - const screen = if (!live.on) live else Screen.create(s.io, s.gpa, live.env) orelse { + if (screen.on) { _ = libc.close(fd); - return refuse(stub, "that session has no room for another terminal"); - }; - const extra = screen != live; + return refuse(stub, "that session has a terminal: join it as a client, `pardes --attach=<socket>:<name>`"); + } const tty = Screen.ttyOn(s.io, screen.buf, fd, cooked) catch { _ = libc.close(fd); - if (extra) screen.destroy() else daemon.setState(true); + daemon.setState(true); return refuse(stub, "that terminal would not go raw"); }; screen.enter(tty) catch { - if (extra) screen.destroy() else daemon.setState(true); + daemon.setState(true); return refuse(stub, "that terminal would not take the screen"); }; - if (extra) { - const k = s.core.openView() orelse { - screen.leave(); - screen.destroy(); - return refuse(stub, "that session has as many terminals as it takes"); - }; - screen.feed.view = k; - s.terms[k] = screen; - } - screen.setStub(stub); + daemon.stub = stub; s.setAttended(true); startInput(s.loop, screen) catch {}; screen.vx.queryTerminalSend(screen.tty.writer()) catch {}; @@ -2124,7 +1976,7 @@ const Shell = struct { s.upgrading = true; defer s.upgrading = false; for (&s.ptys) |*slot| if (slot.*) |*pt| pt.reader.cancel(s.io) catch {}; - for (s.terms) |slot| if (slot) |sc| stopInput(s.io, &sc.thread); + if (s.screen) |sc| stopInput(s.io, &sc.thread); while (s.loop.tryEvent() catch null) |ev| _ = s.apply(ev); core.settle(); // Its replica clients told, their views gone before the dump: each @@ -2132,11 +1984,11 @@ const Shell = struct { s.peers.refuseAll(core, "the session is upgrading to another build of pardes"); var rec: upgrade.Record = .{ .link = daemon.link, .stub = daemon.stub, .exe = path }; for (s.ptys, 0..) |slot, id| if (slot) |pt| rec.addPty(id, pt.pid, pt.file.handle); - for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on) rec.addTty(.{ - .view = @intCast(k), + if (s.screen) |sc| if (sc.on) rec.addTty(.{ + .view = s.own, .fd = sc.tty.fd.handle, - .stub = if (sc.primary) daemon.stub else sc.stub, - .primary = sc.primary, + .stub = daemon.stub, + .primary = true, .termios = sc.tty.termios, }); var popped = false; @@ -2144,7 +1996,7 @@ const Shell = struct { const failed: []const u8 = upgrade.dumpInto(core, &rec, &at_buf, &why) orelse failed: { // What this process put in its terminals that the next puts in // again: its images, and its keyboard mode, a stack. - for (s.terms) |slot| if (slot) |sc| if (sc.on) { + if (s.screen) |sc| if (sc.on) { clearNativeImages(&sc.kitty, &sc.vx, &sc.tty); if (sc.vx.state.kitty_keyboard) sc.tty.writer().writeAll("\x1b[<u") catch {}; sc.vx.state.kitty_keyboard = false; @@ -2158,7 +2010,7 @@ const Shell = struct { for (&s.ptys, 0..) |*slot, id| if (slot.*) |*pt| { pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, id, s.gens[id], s.loop }) catch pt.reader; }; - for (s.terms) |slot| if (slot) |sc| if (sc.on) { + if (s.screen) |sc| if (sc.on) { if (popped) sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {}; startInput(s.loop, sc) catch {}; }; @@ -2179,57 +2031,25 @@ const Shell = struct { } } - /// An upgraded session's terminals, each its view's again (`primary`, - /// run's, entered already); in a fresh session each but the primary a - /// view of its own, as `--attach` makes one. A view left with none - /// closes, but a replica client's, kept for its rejoin (views.away). - fn resumeTerminals(s: *Shell, rec: *const upgrade.Record, primary: *Screen) void { + /// An upgraded session's terminal, its view's again (`primary`, run's, + /// entered already); every other view but a replica client's, kept for + /// its rejoin (views.away), closes. A terminal another build kept for a + /// view of its own is let go, its stub told it is detached: one again + /// is a replica client. + fn resumeTerminals(s: *Shell, rec: *const upgrade.Record) void { if (comptime builtin.is_test) unreachable; const core = s.core; - if (rec.fresh) { - for (rec.ttys[0..rec.nttys]) |t| if (!t.primary) s.attachTerminal(t.fd, t.stub, t.termios); - return; - } - s.terms = @splat(null); - if (rec.nttys == 0) { - // The live view alone (never one kept for a rejoin) is the - // session's own. - for (0..pardes.views.max) |k| if (k != core.live and pardes.views.isOpen(core, @intCast(k)) and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k)); - s.terms[core.live] = primary; - primary.feed.view = core.live; - return; - } + s.own = core.live; for (rec.ttys[0..rec.nttys]) |t| { - if (!pardes.views.isOpen(core, t.view) or s.terms[t.view] != null) { - if (t.primary) continue; - _ = libc.close(t.fd); - if (t.stub >= 0) daemon.tellStub(t.stub, "d{s}", .{daemon.name()}); + if (t.primary) { + if (!rec.fresh and pardes.views.isOpen(core, t.view)) s.own = t.view; continue; } - const sc = if (t.primary) primary else extra: { - const sc = Screen.create(s.io, s.gpa, primary.env) orelse break :extra null; - const tty = Screen.ttyOn(s.io, sc.buf, t.fd, t.termios) catch { - sc.destroy(); - break :extra null; - }; - sc.enter(tty) catch { - sc.destroy(); - break :extra null; - }; - sc.setStub(t.stub); - startInput(s.loop, sc) catch {}; - sc.vx.queryTerminalSend(sc.tty.writer()) catch {}; - break :extra sc; - } orelse { - _ = libc.close(t.fd); - if (t.stub >= 0) daemon.tellStub(t.stub, "d{s}", .{daemon.name()}); - continue; - }; - sc.feed.view = t.view; - s.terms[t.view] = sc; + _ = libc.close(t.fd); + if (t.stub >= 0) daemon.tellStub(t.stub, "d{s}", .{daemon.name()}); } - for (0..pardes.views.max) |k| if (pardes.views.isOpen(core, @intCast(k)) and s.terms[k] == null and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k)); - if (s.terms[core.live] == null) s.terms[core.live] = primary; + if (rec.fresh) return; + for (0..pardes.views.max) |k| if (k != s.own and pardes.views.isOpen(core, @intCast(k)) and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k)); } fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { @@ -2394,27 +2214,20 @@ const Shell = struct { } if (s.input_seen) s.input_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); if (event != .replica_mail) s.mail_only = false; - // A terminal's input goes into its view; a closed one's last is - // dropped. + // The terminal's input goes into its view. switch (event) { .key_press, .mouse, .paste, .paste_start, .paste_end, .winsize, .focus_in, .focus_out, .quit => { - if (s.terms[s.from] == null and s.local()) { - if (event == .paste) s.gpa.free(@constCast(event.paste)); - return false; - } - if (s.local() and s.remote == null) core.toView(s.from); + if (s.local() and s.remote == null) core.toView(s.own); }, else => {}, } switch (event) { .nop => {}, - .from => |k| s.from = k, .winched => s.winched(), - // A terminal hung up (its stub passes the hangup on) or its stub - // died (a forked session's death signal): that one's input has - // ended. A HUP says not whose: each is asked. - .hangup => for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on and sc.hungUp()) { - s.from = @intCast(k); + // The terminal hung up (its stub passes the hangup on) or its + // stub died (a forked session's death signal): its input has + // ended. + .hangup => if (s.screen) |sc| if (sc.on and sc.hungUp()) { if (s.apply(.quit)) return true; }, .wake => if (s.test_clock) |*virtual| { @@ -2425,11 +2238,6 @@ const Shell = struct { c.link.quit = true; return true; } - // One of several: its view goes with it. - if (pardes.views.count(core) > 1) { - s.dropView(core.live, .detach); - return true; - } // The terminal went: a session the daemon keeps carries on // without it, to be attached again. Gone before the first // frame, the reader that takes the daemon's `ok` (kept @@ -2466,7 +2274,7 @@ const Shell = struct { s.feed(.pointer_leave); s.feed(.{ .focus = false }); }, - .winsize => |ws| if (s.attached()) s.resized(s.terms[s.from], ws), + .winsize => |ws| if (s.attached()) s.resized(s.screen, ws), .pty_read => |pr| { tookRead(s.io, pr.id); s.output_seen = true; @@ -2567,7 +2375,7 @@ const Shell = struct { return false; } - /// Terminal `screen` (the live view's) is `ws` big. + /// Terminal `screen` (its view live) is `ws` big. fn resized(s: *Shell, screen: ?*Screen, ws: vaxis.Winsize) void { if (screen) |sc| { sc.size = ws; @@ -2576,17 +2384,15 @@ const Shell = struct { s.feed(.{ .resize = if (comptime pardes.pdf_enabled) terminalSize(ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) else .{ .cols = ws.cols, .rows = ws.rows } }); } - /// A SIGWINCH: each terminal whose size it changed is resized, in its - /// view (a terminal reporting in band says so as input). + /// A SIGWINCH: the terminal, if it changed size, resized in its view + /// (one reporting in band says so as input). fn winched(s: *Shell) void { - for (s.terms, 0..) |slot, k| { - const sc = slot orelse continue; - if (!sc.on or sc.vx.state.in_band_resize) continue; - const ws = sc.tty.getWinsize() catch continue; - if (sc.size) |was| if (std.meta.eql(was, ws)) continue; - if (s.remote == null) s.core.toView(@intCast(k)); - s.resized(sc, ws); - } + const sc = s.screen orelse return; + if (!sc.on or sc.vx.state.in_band_resize) return; + const ws = sc.tty.getWinsize() catch return; + if (sc.size) |was| if (std.meta.eql(was, ws)) return; + if (s.remote == null) s.core.toView(s.own); + s.resized(sc, ws); } fn reloadWatched(s: *Shell) void { diff --git a/src/views.zig b/src/views.zig index 0c96c792..354ae0d0 100644 --- a/src/views.zig +++ b/src/views.zig @@ -474,18 +474,11 @@ pub fn deinit(p: *Pardes) void { pub const Present = struct { ctx: ?*anyopaque, f: ?*const fn (?*anyopaque, *const pardes.Surface) void }; -/// Each view but the live one drawn and presented, the live one put back -/// after exactly as it was (`drawOne`). Before the live one's frame: the -/// surface after the pump is its. -pub fn drawOthers(p: *Pardes, h: pardes.Host) !void { - for (0..max) |i| { - const k: u8 = @intCast(i); - if (k == p.live or !isOpen(p, k) or (p.undrawn | p.views_away) & bit(k) != 0) continue; - // No post_present: what a shell acknowledges there moves the - // session's pointer and hover, which are the live view's to move; - // a view's panels are acknowledged when it is live and drawn. - try drawOne(p, k, .{ .ctx = h.ctx, .f = h.vtable.present }); - } +/// The view this process's frontend shows: the one open view that is no +/// replica client's (`undrawn`) and kept for none (`away`), if there is one. +pub fn shown(p: *const Pardes) ?u8 { + for (0..max) |i| if (isOpen(p, @intCast(i)) and (p.undrawn | p.views_away) & bit(i) == 0) return @intCast(i); + return null; } fn drawLive(present: Present, p: *Pardes) anyerror!void { @@ -782,7 +775,7 @@ test "a client's view kept for its rejoin: through an Upgrade's dump, each clien try testing.expect(!isAway(p, ks[0]) and isAway(p, ks[1])); } -test "drawing the other views leaves the live one as it was, to the digest" { +test "drawing another view leaves the live one as it was, to the digest" { const gpa = testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -796,7 +789,7 @@ test "drawing the other views leaves the live one as it was, to the digest" { p.toView(0); cursorTo(p, pane, 95); const before = pardes.walk.digest(Pardes, p); - try drawOthers(p, .{}); + try drawOne(p, k, .{ .ctx = null, .f = null }); try testing.expectEqual(@as(u8, 0), p.live); try testing.expectEqual(before, pardes.walk.digest(Pardes, p)); p.toView(k); @@ -814,7 +807,7 @@ test "a view drawn while another is live keeps its own cursors" { try testing.expectEqual(@as(u16, 1), pane.body.nsel); p.toView(0); const before = pardes.walk.digest(Pardes, p); - try drawOthers(p, .{}); + try drawOne(p, k, .{ .ctx = null, .f = null }); try testing.expectEqual(before, pardes.walk.digest(Pardes, p)); p.toView(k); try testing.expectEqual(@as(u16, 1), pane.body.nsel); |
