From 2cce341e2c94fb3150dc1f3e7911c26502a70487 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 29 Oct 2026 17:01:35 -0300 Subject: views: several clients on one session, each its own layout, focus, cursors and scroll over the panes they share; a second `pardes --attach` draws on its own terminal beside the first, and `pardes-gui --attach` opens another window The core still sees one view, the live one, in the fields it always had (src/views.zig): a view's share of the session (`views.fields`: its screen, columns, rects, focus, pointer and gestures, jumps, key prefixes, column tags, presentation and animations, windowed and native_images) and of each pane (`PaneView`: its place in the layout, which text has the keyboard, the body's cursor, selections and mode, its scroll, a document's size, what the step measured of it) is copied out when another view goes live and back when it is live again. One view never parks: the single client pays a test of one byte a step. `toView`, `openView` and `closeView` are taped inputs; the pump draws each other view by going into it and back, which leaves every digested field as it was, so the replica that draws nothing skips it. A parked view is in no digest (its slot is written whenever it goes out); what drawing it made of its own (animations, presentation) is kept, whatever its unpark brought inside a changed text is done again when it is next live. Shared: the panes' text, terminals, tags, prompts, messages, registers (yanked in one view, put in another), the workspace tag and settings. A terminal shown at two sizes takes the size of the view that typed into it last (`Pane.sized_by`), and any view's once that one is gone; the others show it at that size. A text edited in one view moves the other views' cursors and scroll with the splice, as a Zerox twin's (File.ParkedPlaces). A pane closed in one view leaves the others' layouts (by its slot's serial); a pane focused in a view that does not show it is placed in its active column (views.show). tty: each terminal is a Screen of its own (its vaxis, input reader, frame answer, kitty images and shm probe, glide, trail and flash); its input reaches the loop as its view's (a `from` ahead of it when another terminal posted last, so one terminal posts none). A SIGWINCH asks every terminal its size; a SIGHUP asks each whether it hung up or lost its stub. Detach, or a terminal's end, with other views left closes only that view, its stub told `d`; the session's end tells every stub. daemon.zig: an attach names an attached session too (or the only one there is when none is detached). gui: the Gui holds the live window's share of itself (window_fields: the SDL window and its presenting, scroll, glide, scene and post chain, pointer, blink, captures); the others wait in Shell.windows, swapped in (`follow`) as the core's live view changes, and each SDL event first takes its window's view live (`route`). Closing a window while others stay closes its view. Harnesses: `start views=N` in a snapshot script gives the app N-1 more terminals (PARDES_TEST_VIEWS, opened as attached ones), `view ` types into and captures terminal k, every wait reads them all; `pardes-monkey --views=N` switches among N; `zig build replay` runs its seeds at three views too. views.snap pins two terminals: an edit seen in both, a scroll in one, a line yanked in one and put in the other, Newcol in one, Detach in one. Unit tests: own cursor, scroll, mode, layout and focus; edits shared; registers shared; terminal size by last typist; closing views; drawing the others leaves the digest; a view keeps its place in a text another edits. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 51 ++++- src/daemon.zig | 39 +++- src/gui/gui.zig | 225 ++++++++++++++++++- src/panes.zig | 16 +- src/pardes.zig | 70 +++++- src/tape.zig | 6 + src/tty/tty.zig | 666 ++++++++++++++++++++++++++++++++++++-------------------- src/views.zig | 555 ++++++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 1366 insertions(+), 262 deletions(-) create mode 100644 src/views.zig (limited to 'src') diff --git a/src/File.zig b/src/File.zig index d795eaa1..dd6b2d34 100644 --- a/src/File.zig +++ b/src/File.zig @@ -1208,7 +1208,12 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { // the caller did not say, is what the line index wants anyway. var twins: [pardes.MAX_PANES]usize = undefined; const ntwins = twinsOf(p, f, &twins); - const span: ?Span = span_in orelse if (ntwins > 0) spanOf(f.content, new) else null; + // The views not live keep their place in it as twins do (views.zig). + const viewed = pardes.views.several(p); + const span: ?Span = span_in orelse if (ntwins > 0 or viewed) spanOf(f.content, new) else null; + var parked: ParkedPlaces = .{}; + if (viewed) parked.before(p, f, span.?, new.len); + defer if (viewed) parked.after(p); var moved: [pardes.MAX_PANES]struct { cursor: usize, scroll: usize } = undefined; for (twins[0..ntwins], 0..) |id, i| { const t = p.panes[id].?; @@ -1301,6 +1306,50 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { } } +/// Each other view's cursor and scroll on a text being changed, as offsets +/// moved by the splice (`spliced`), put back as places in the new text once +/// it is in: a view not live keeps its place, as a twin does. Its +/// selections go, as a twin's do. +const ParkedPlaces = struct { + const max = pardes.MAX_PANES * pardes.views.max; + at: [max]struct { pane: *Pane, view: u8, cursor: usize, scroll: usize } = undefined, + n: usize = 0, + + fn before(pp: *ParkedPlaces, p: *Pardes, f: *State, span: Span, new_len: usize) void { + for (p.panes) |slot| { + const pane = slot orelse continue; + const tf = if (pane.file) |*file| file else continue; + if (tf != f and (f.twin == 0 or tf.twin != f.twin)) continue; + for (0..pardes.views.max) |k| { + if (k == p.view or !pardes.views.isOpen(p, @intCast(k)) or pp.n == max) continue; + const v = &pane.pv[k]; + const at = lineStart(p.gpa, tf, @intCast(@max(0, v.body.cur_row))) + @as(usize, @intCast(@max(0, v.body.cur_col))); + pp.at[pp.n] = .{ + .pane = pane, + .view = @intCast(k), + .cursor = spliced(@min(at, f.content.len), f.content.len, new_len, span), + .scroll = spliced(@min(lineStart(p.gpa, tf, v.scroll), f.content.len), f.content.len, new_len, span), + }; + pp.n += 1; + } + } + } + + fn after(pp: *ParkedPlaces, p: *Pardes) void { + for (pp.at[0..pp.n]) |a| { + const tf = &(a.pane.file orelse continue); + const v = &a.pane.pv[a.view]; + const cursor = positionIn(p.gpa, tf, @min(a.cursor, tf.content.len)); + v.body.cur_row = @intCast(cursor.row); + v.body.cur_col = @intCast(cursor.col); + v.body.vsel.active = false; + v.body.msel.active = false; + v.body.nsel = 0; + v.scroll = positionIn(p.gpa, tf, @min(a.scroll, tf.content.len)).row; + } + } +}; + /// Where an offset into the old text is in the new, after the splice that /// kept `span` at either end: past it, moved by what it added; inside it, /// at its start, as acme moves a clone's q0 (textinsert, textdelete). diff --git a/src/daemon.zig b/src/daemon.zig index 0f770514..ac9e6eb4 100644 --- a/src/daemon.zig +++ b/src/daemon.zig @@ -530,21 +530,32 @@ fn hupOnStubDeath(on: bool) void { pub fn tellStubDetached() void { if (stub < 0) return; hupOnStubDeath(false); + tellDetached(stub); + stub = -1; +} + +/// The stub on `fd` told its terminal is detached (one of a session's +/// several, views.zig), and the pipe let go. +pub fn tellDetached(fd: c_int) void { + if (fd < 0) return; var buf: [160]u8 = undefined; const said = std.fmt.bufPrint(&buf, "d{s}", .{name()}) catch "d"; - _ = libc.write(stub, said.ptr, said.len); - _ = libc.close(stub); - stub = -1; + _ = libc.write(fd, said.ptr, said.len); + _ = libc.close(fd); } /// The session's end, `code` its exit status: the stub is told (and goes). pub fn tellStubExit(code: u8) void { - if (stub < 0) return; + tellExit(stub, code); + stub = -1; +} + +pub fn tellExit(fd: c_int, code: u8) void { + if (fd < 0) return; var buf: [8]u8 = undefined; const said = std.fmt.bufPrint(&buf, "x{d}", .{code}) catch "x1"; - _ = libc.write(stub, said.ptr, said.len); - _ = libc.close(stub); - stub = -1; + _ = libc.write(fd, said.ptr, said.len); + _ = libc.close(fd); } /// A terminal refused (an attach that came too late): its stub is told why. @@ -742,10 +753,7 @@ const Daemon = struct { _ = std.fmt.bufPrint(why, "no '{s}' is {s}={s}`", .{ wanted_name, other, wanted_name }) catch {}; return error.Said; } - if (!s.detached) { - _ = std.fmt.bufPrint(why, "no '{s}' is attached already, to another terminal or window", .{wanted_name}) catch {}; - return error.Said; - } + // Attached already: the session takes another view. return @intCast(i); }; _ = std.fmt.bufPrint(why, "no no session called '{s}'", .{wanted_name}) catch {}; @@ -764,6 +772,15 @@ const Daemon = struct { found = @intCast(i); }; if (count == 1) return found.?; + // None detached: the one session there is, as another view of it. + 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.?; + count = 0; + } if (count == 0 and others == 0) { w.writeAll("no no detached session is running") catch {}; return error.Said; diff --git a/src/gui/gui.zig b/src/gui/gui.zig index a1590b48..2d9124cc 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1550,6 +1550,68 @@ const Gui = struct { deck: deck.Deck = .{}, }; +/// The Gui's fields that are each window's own, one a view (views.zig): +/// the window and its presenting, its scroll and glide, its scene and post +/// chain, its pointer, its blink, its images as presented, its capture. The +/// device, the atlas, the font and the pipelines are every window's. The +/// Gui holds the live window's; the others wait in `Shell.windows`. +const window_fields = [_][:0]const u8{ + "window", "soft_renderer", "soft_texture", "soft_tex_w", "soft_tex_h", + "window_w", "window_h", "scroll_pane", "scroll_rect", "scroll_body_y", + "scroll_body_h", "scroll_held_px", "scroll_col", "scroll_row", "scroll_delta", + "scroll_lag", "scroll_edge", "scroll_edge_len", "scroll_notch", "program_wheel", + "glide", "pace_ns", "sel_glow", "hover_glow", "frame_arrival_ns", + "blink_due", "cursor_quad_alpha", "scene_tex", "scene_tex_w", "scene_tex_h", + "scene_failures", "scene_target_failed", "post", "pointer_present", "pointer_shape", + "pointer_mapped", "pointer_cell", "presented_images", "prepared_images", "touch", + "live_ctrl", "live_alt", "applied_window_opacity", "capture_tex", "capture_tex_w", + "capture_tex_h", "capture_xfer", "capture_xfer_size", "captured", "capture_dir", +}; + +const GuiWindow = blk: { + @setEvalBranchQuota(100_000); + const st = @typeInfo(Gui).@"struct"; + var types: [window_fields.len]type = undefined; + var attrs: [window_fields.len]std.lang.Type.Struct.FieldAttributes = undefined; + for (window_fields, 0..) |name, i| { + const at = for (st.field_names, 0..) |n, j| { + if (std.mem.eql(u8, n, name)) break j; + } else @compileError("gui: Gui has no field " ++ name); + types[i] = st.field_types[at]; + attrs[i] = .{ .default_value_ptr = st.field_attrs[at].default_value_ptr }; + } + break :blk @Struct(.auto, null, &window_fields, &types, &attrs); +}; + +fn copyWindow(dst: anytype, src: anytype) void { + inline for (window_fields) |name| @field(dst, name) = @field(src, name); +} + +/// The live window's share of `g` as a window starts, but its SDL window +/// (reopenWindow makes that). +fn freshWindow(g: *Gui) void { + @setEvalBranchQuota(100_000); + const st = @typeInfo(Gui).@"struct"; + inline for (window_fields) |name| { + const at = comptime for (st.field_names, 0..) |n, j| { + if (std.mem.eql(u8, n, name)) break j; + } else unreachable; + if (comptime st.field_attrs[at].defaultValue(st.field_types[at])) |d| @field(g, name) = d; + } +} + +/// What a window held of its own let go (closeWindow lets the window go). +fn releaseWindowParts(g: *Gui, gpa: std.mem.Allocator) void { + if (g.scene_tex) |texture| c.SDL_ReleaseGPUTexture(g.device, texture); + if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(g.device, texture); + if (g.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(g.device, transfer); + g.post.deinit(gpa, g.device); + g.glide.deinit(gpa); + gpa.free(g.scroll_edge); + g.presented_images.deinit(gpa); + g.prepared_images.deinit(gpa); +} + fn setGuiFontName(g: *Gui, fallback: []const u8) void { const name = if (c.ui_font_name(g.font)) |name_z| std.mem.span(name_z) else fallback; const len = @min(name.len, g.font_name.len); @@ -2247,7 +2309,9 @@ fn closeWindow(g: *Gui) void { g.soft_renderer = null; } else c.SDL_ReleaseWindowFromGPUDevice(g.device, g.window); c.SDL_DestroyWindow(g.window); - if (g.window_slot) |slot| slot.* = null; + if (g.window_slot) |slot| if (slot.* == g.window) { + slot.* = null; + }; } /// `pardes-gui --attach`: a window again, as the first was made, at the @@ -2399,6 +2463,14 @@ fn localSession( if (fs) |f| try f.watch(&queue, wakeFs); _ = c.SDL_StartTextInput(g.window); + // PARDES_TEST_VIEWS=N: N more windows from the start, each a view of the + // session (views.zig), captured under view-; view 0 live after. + if (test_mode) if (std.c.getenv("PARDES_TEST_VIEWS")) |n| { + for (0..std.fmt.parseInt(u8, std.mem.span(n), 10) catch 0) |_| shell.openAnotherWindow(); + core.toView(0); + shell.follow(); + }; + defer shell.closeOtherWindows(); if (test_mode) setStdinRaw() catch {}; shell.threads_ok = true; @@ -2431,6 +2503,10 @@ fn localSession( }; pipe_tasks.cancelAll(io); queue.discardCompletions(); + // ponytail: a restored session is one view, the live window's: + // the others close. + shell.closeOtherWindows(); + shell.gview = 0; shell.stopPtys(); for (0..pardes.MAX_PANES) |wid| file_watch.watchPane( inotify_fd, @@ -2635,6 +2711,24 @@ const StdinFeed = struct { // A mouse event at window pixels, built as SDL would and run // through dispatch, so a driver exercises the real pointer path // (pixel to cell, tag and body hits). SGR mouse carries only cells. + // ESC]777;view;BEL: what follows is window k's (k from 1), + // as an event of that window's makes its view live (route). + const view_prefix = "\x1b]777;view;"; + if (std.mem.startsWith(u8, f.buf[seq_start..len], view_prefix)) { + const body = f.buf[seq_start + view_prefix.len .. len]; + const end = std.mem.indexOfScalar(u8, body, 0x07) orelse { + std.mem.copyForwards(u8, f.buf[0 .. len - seq_start], f.buf[seq_start..len]); + f.fill = len - seq_start; + break; + }; + const k = std.fmt.parseInt(u8, body[0..end], 10) catch 0; + if (in.shell) |sh| if (k >= 1 and pardes.views.isOpen(sh.core, k - 1)) { + sh.core.toView(k - 1); + sh.follow(); + }; + seq_start += view_prefix.len + end + 1; + continue; + } const mouse_prefix = "\x1b]777;mouse;"; if (std.mem.startsWith(u8, f.buf[seq_start..len], mouse_prefix)) { const body = f.buf[seq_start + mouse_prefix.len .. len]; @@ -2975,6 +3069,9 @@ test "the window's function and editing keys reach a terminal as its cursor keys const Input = struct { core: ?*pardes.Pardes = null, + /// The shell whose windows these are: a window closed while others + /// stay takes its view with it (views.zig). + shell: ?*Shell = null, quit: bool = false, fn post(in: *Input, ev: pardes.Event) void { @@ -2982,6 +3079,7 @@ const Input = struct { } fn close(in: *Input) void { + if (in.shell) |s| if (pardes.views.count(s.core) > 1) return s.closeView(s.core.view); if (in.core) |core| core.quit = true; in.quit = true; } @@ -3018,7 +3116,11 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { else => {}, } switch (sev.type) { - c.SDL_EVENT_QUIT, c.SDL_EVENT_WINDOW_CLOSE_REQUESTED => in.close(), + c.SDL_EVENT_QUIT => { + in.shell = null; + in.close(); + }, + c.SDL_EVENT_WINDOW_CLOSE_REQUESTED => in.close(), c.SDL_EVENT_WINDOW_FOCUS_GAINED => in.post(.{ .focus = true }), c.SDL_EVENT_WINDOW_FOCUS_LOST => in.post(.{ .focus = false }), c.SDL_EVENT_WINDOW_MOUSE_LEAVE => { @@ -3677,6 +3779,10 @@ const Shell = struct { /// The tick a paced frame is sampled at (waitInput): the clock the /// core is advanced to while anything moves. paced_ns: ?u64 = null, + /// Each other view's window, while another's is in the Gui (views.zig), + /// and the view whose window the Gui holds (`follow`). + windows: [pardes.views.max]GuiWindow = undefined, + gview: u8 = 0, fn reap(s: *Shell) void { const now = std.Io.Clock.awake.now(s.queue.io).toMilliseconds(); @@ -3766,10 +3872,92 @@ const Shell = struct { 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"); + // One of several: its window goes, and the session stays in the rest. + if (pardes.views.count(s.core) > 1) return s.closeView(s.core.view); if (!daemon.kept()) return s.core.reportFailure(s.core.active, "Detach: no pardes daemon keeps this session; closing its window ends it"); s.closeTheWindow(); } + /// The Gui holds the window of the core's live view. + fn follow(s: *Shell) void { + const g = s.gui orelse return; + const k = s.core.view; + if (s.gview == k) return; + 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; + if (w == g.window) 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. + fn openAnotherWindow(s: *Shell) void { + const g = s.gui orelse return; + s.follow(); + const k = 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- (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.core.toView(k); + s.core.needs_frame = 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.core.closeView(k); + s.follow(); + s.core.needs_frame = true; + } + + /// 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); @@ -3975,7 +4163,7 @@ const Shell = struct { .files_changed => check_files = true, .fs_ready => {}, .window => { - s.openTheWindow(); + if (s.gui != null) s.openAnotherWindow() else s.openTheWindow(); s.saw_event = true; }, .adopted => |a| { @@ -4008,7 +4196,8 @@ fn shellOf(ctx: ?*anyopaque) *Shell { fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { const s = shellOf(ctx); const core = s.core; - var in: Input = .{ .core = core }; + var in: Input = .{ .core = core, .shell = s }; + s.follow(); if (s.gui) |g| { var sev = std.mem.zeroes(c.SDL_Event); // Idle is asleep until an event: SDL's own, and the user events the @@ -4100,16 +4289,27 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { // each would repeat hover and selection work the next undoes. var motion: ?c.SDL_Event = null; while (true) { - if (sev.type == c.SDL_EVENT_MOUSE_MOTION) { + if (sev.type == c.SDL_EVENT_MOUSE_MOTION and (motion == null or motion.?.motion.windowID == sev.motion.windowID)) { motion = sev; } else { - if (motion) |*m| dispatch(g, &in, m); + if (motion) |*m| { + s.route(m); + dispatch(g, &in, m); + } motion = null; - dispatch(g, &in, &sev); + if (sev.type == c.SDL_EVENT_MOUSE_MOTION) { + motion = sev; + } else { + s.route(&sev); + dispatch(g, &in, &sev); + } } if (!c.SDL_PollEvent(&sev)) break; } - if (motion) |*m| dispatch(g, &in, m); + if (motion) |*m| { + s.route(m); + dispatch(g, &in, m); + } } runDemo(g, &in, core); // Paced: what came before the tick is in; wait out the rest of it, @@ -4133,8 +4333,12 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { const more = c.SDL_PollEvent(&sev); pardes.turn.wake(); if (more) { + s.route(&sev); dispatch(g, &in, &sev); - while (c.SDL_PollEvent(&sev)) dispatch(g, &in, &sev); + while (c.SDL_PollEvent(&sev)) { + s.route(&sev); + dispatch(g, &in, &sev); + } } else { // The events asked for every 100 µs, the core busy between. const until = c.SDL_GetTicksNS() + 100 * std.time.ns_per_us; @@ -4182,6 +4386,7 @@ 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); @@ -4414,6 +4619,7 @@ test "background opacity acknowledges success and rolls back unsupported surface fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { const s = shellOf(ctx); const core = s.core; + s.follow(); const g = s.gui orelse return; frame_started_ns = monoNs(); const frame = @constCast(surface); @@ -4447,6 +4653,7 @@ fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { fn postPresent(ctx: ?*anyopaque) void { const s = shellOf(ctx); + s.follow(); const g = s.gui orelse return; // No image (a minimized window) shows no tracks; time still passes and // the pump advances it all the same. diff --git a/src/panes.zig b/src/panes.zig index a782e3e0..71a04464 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -1,6 +1,7 @@ const std = @import("std"); const vaxis = @import("vaxis"); const pardes = @import("pardes.zig"); +const views = @import("views.zig"); const layout = @import("layout.zig"); const config = @import("config.zig"); const Pardes = pardes.Pardes; @@ -26,8 +27,9 @@ pub const EditText = struct { text: []u8, row0: i32 }; pub const Pane = struct { /// What the replay digest leaves out (src/walk.zig): the view's geometry, /// made again from the rest (File.geometry); the 9P server's record of - /// the pane's opens and readers. + /// the pane's opens and readers; the other views' share of it (views.zig). pub const replica = .{ + .local = .{ "pv", "pv_known" }, .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "view", "notices" }, .authority = .{"fs"}, .len = .{ .{ "msg", "msg_len" }, .{ "msg_older", "msg_older_len" }, .{ "question", "question_len" }, .{ "shell_tail", "shell_tail_len" }, .{ "sel_snap", "nsel_snap" } }, @@ -95,6 +97,7 @@ pub const Pane = struct { pub const Cwd = union(enum) { none, inherited: *Pane, owned: []u8 }; pub const Focus = enum { body, tag }; + pub const SessionView = struct { wrap: bool = true, layered: bool = true, body_h: u32 = 0, tagline_h: u32 = 0, rect_h: u16 = 0 }; terminal: ?*terminal.State = null, gpa: std.mem.Allocator, serial: u32 = 0, @@ -263,7 +266,7 @@ pub const Pane = struct { geometry_key: u64 = 0, geometry_len: usize = 0, /// The session's part of the geometry, as of the last step (`sync`). - view: struct { wrap: bool = true, layered: bool = true, body_h: u32 = 0, tagline_h: u32 = 0, rect_h: u16 = 0 } = .{}, + view: SessionView = .{}, sel: [3]Sel = @splat(.{}), pointer_selections: [3]?PointerSelection = @splat(null), next_pointer_selection: u64 = 0, @@ -297,6 +300,15 @@ pub const Pane = struct { /// body layer reserves exactly `len` rows for them, the way it already /// reserves rows for sticky context headers. notices: Notices = .{}, + /// Each other view's share of this pane, while it is not live + /// (views.zig): its cursor, scroll and place in that view's layout. + pv: [views.max]views.PaneView = undefined, + /// The views `pv` holds a share for (a pane retired before a view came + /// has none of it). + pv_known: u8 = 0, + /// The view that last typed into it: a terminal shown at two sizes takes + /// that view's (Pardes.sync). + sized_by: u8 = 0, pub const MessagePhase = enum { entering, shown, lingering, leaving }; /// One message line's animation: falling in, shown, lingering after the diff --git a/src/pardes.zig b/src/pardes.zig index 228d97fa..88d75fd1 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -64,6 +64,7 @@ pub const memory = @import("memory.zig"); pub const tape = @import("tape.zig"); pub const walk = @import("walk.zig"); pub const screen_state = if (terminal_panes) @import("screen_state.zig") else struct {}; +pub const views = @import("views.zig"); pub const image = @import("image.zig"); pub const dump = @import("dump.zig"); pub const lsp = @import("lsp/lsp.zig"); @@ -511,6 +512,7 @@ test { _ = @import("Handover.zig"); _ = @import("walk.zig"); _ = screen_state; + _ = @import("views.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -4699,6 +4701,12 @@ pub const Pardes = struct { restore_buf: [1024]u8 = undefined, surface: Surface = .{}, + /// The view the fields above are of: whose layout, focus, pointer and + /// panes' cursors and scroll (views.zig). `views_open` says which views + /// there are, one a window or terminal; each not live is in `parked`. + view: u8 = 0, + views_open: u8 = 1, + parked: [views.max]?*views.Parked = @splat(null), /// per-update scratch (paneCursorLines, selection text); reset each update scratch: std.heap.ArenaAllocator, /// The arena each frame's Surface text is built in, reset by `pump`. Hosts @@ -4725,6 +4733,9 @@ pub const Pardes = struct { // Drained by every pump before its digest; a replica's queues // are its own. "effects", "in_q", + // The views not live: written whenever one goes out, so the + // live one's slot is stale (views.zig). + "parked", }, .derived = .{ "shell_rows", "diff_output", "locations_cache", "retired_panes", "tty_filter_palette", "body_chrome" }, // The host's handles, the 9P server's fids and log, the store file @@ -5020,6 +5031,7 @@ pub const Pardes = struct { slot.* = null; }; const gpa = p.gpa; + views.deinit(p); for (&p.col_tags) |*t| t.deinit(gpa); p.global_tag.deinit(gpa); p.registers.deinit(gpa); @@ -5167,6 +5179,7 @@ pub const Pardes = struct { if (comptime pdf_enabled) if (pane.pdf) |*pv| panes.Pdf.deinitPane(p, pane, pv); if (pane.file) |*file| panes.File.deinit(p, pane, file); if (pane.ovl) |o| p.gpa.free(o.text); + views.tornDown(p, pane); pane.body.deinit(p.gpa); pane.tag.deinit(p.gpa); pane.input.deinit(p.gpa); @@ -5201,6 +5214,7 @@ pub const Pardes = struct { pane.serial = p.next_serial; p.rects[id] = .{}; p.panes[id] = pane; + views.installed(p, pane); panes.terminal.adoptSettings(p, pane); // /log hears of it once the update that made it ends, when it has // its file, name and place (`ctlfs.events.announce`). @@ -5569,6 +5583,33 @@ pub const Pardes = struct { /// Something changed the core without going through `update` -- a watched /// file reloading under it, a theme file rewritten on disk. `pump` draws /// only when it has a reason to, and this is the reason. + /// A view of its own for a new client (a second window, a terminal + /// `pardes --attach`ed), as the live one is laid out; null at + /// views.max. Not live until `toView`. + pub fn openView(p: *Pardes) ?u8 { + const taped = tape.enter(p, .open_view); + defer tape.leave(p, taped); + p.needs_frame = true; + return views.open(p); + } + + /// The client of view `k` gone: its view goes, the others stay. The + /// last one stays the session's own. + pub fn closeView(p: *Pardes, k: u8) void { + const taped = tape.enter(p, .{ .close_view = k }); + defer tape.leave(p, taped); + views.close(p, k); + p.sync(); + } + + /// Into view `k`, before the input its client sent. + pub fn toView(p: *Pardes, k: u8) void { + if (k == p.view) return; + const taped = tape.enter(p, .{ .to_view = k }); + defer tape.leave(p, taped); + views.to(p, k); + } + pub fn invalidate(p: *Pardes) void { const taped = tape.enter(p, .invalidate); defer tape.leave(p, taped); @@ -6053,6 +6094,8 @@ pub const Pardes = struct { // 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); _ = p.frame_arena.reset(.{ .retain_with_limit = memory.limits.frame_kept }); p.frames.mark_update = FrameStats.nowNs(); p.frames.view = if (p.panes[p.active]) |pane| pane.scroll() else 0; @@ -6235,6 +6278,7 @@ pub const Pardes = struct { .key => |key| { p.can_ask = true; defer p.can_ask = false; + p.typedInto(); p.handleKey(key); }, .mouse => |m| { @@ -6254,7 +6298,10 @@ pub const Pardes = struct { } } }, - .paste => |bytes| edit.applyPaste(p, bytes), + .paste => |bytes| { + p.typedInto(); + edit.applyPaste(p, bytes); + }, .command => |line| _ = p.executeBuiltinLine(p.active, line), .pinch => |scale| p.ov_pinch_scale = scale, .touch_scroll => |delta| p.ov_touch_scroll_delta = delta, @@ -7672,6 +7719,7 @@ pub const Pardes = struct { tagline.exitHeader(p); } p.reapPanes(); + if (views.several(p)) views.show(p); layout.compute(p); p.presentation.sync(p); p.trackJump(); @@ -7759,7 +7807,9 @@ pub const Pardes = struct { // A terminal's pty follows its pane down to a row, whatever the // resize; only a folded one keeps the size it had, and one not // placed yet the grid it was made with. - if ((cols != pane.cols or rows != pane.rows) and (r.h > pane.tag_rows or (pane.isTerminal() and !pane.collapsed and r.h > 0))) { + if ((cols != pane.cols or rows != pane.rows) and (r.h > pane.tag_rows or (pane.isTerminal() and !pane.collapsed and r.h > 0)) and + (!pane.isTerminal() or p.sizes(pane))) + { // doc panes have no pty/emulator grid to reflow; just record // the size so bodyText renders the right number of rows if (pane.isTerminal()) { @@ -7798,6 +7848,22 @@ pub const Pardes = struct { tagline.revealHeader(p); } + /// The view typing goes into is the one its terminal is sized for + /// (`sizes`). + fn typedInto(p: *Pardes) void { + if (p.panes[p.active]) |pane| pane.sized_by = p.view; + } + + /// Whether the live view sizes terminal `pane`: a terminal shown at two + /// sizes takes the size of the view that typed into it last, and any + /// view's once that one is gone. The others show it at that size. + fn sizes(p: *Pardes, pane: *Pane) bool { + if (pane.sized_by == p.view) return true; + if (views.isOpen(p, pane.sized_by)) return false; + pane.sized_by = p.view; + return true; + } + pub fn theme(p: *const Pardes) *const Theme { if (p.custom_theme) |*custom| return custom; return &themes[p.settings.theme]; diff --git a/src/tape.zig b/src/tape.zig index eaf1a9fa..ec38deac 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -57,6 +57,9 @@ pub const Input = union(enum) { acknowledge_panel_presentation: []const pardes.animation.Track, run_closed_lines, file_deleted: u8, + open_view, + close_view: u8, + to_view: u8, }; /// The core's own syscalls (each `turn.yield()`s around itself), numbered @@ -442,6 +445,9 @@ pub const Tape = struct { .acknowledge_panel_presentation => |tracks| p.acknowledgePanelPresentation(tracks), .run_closed_lines => pardes.ctlfs.runClosedLines(p), .file_deleted => |id| pardes.panes.File.deleted(p, id), + .open_view => _ = p.openView(), + .close_view => |k| p.closeView(k), + .to_view => |k| p.toView(k), } t.finishInput(); } diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 760c0692..f949d571 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -21,15 +21,45 @@ 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)); -/// The terminal answered the shared-memory probe (`kittyShmProbe`): it can -/// read a raster from a POSIX shm object, so a page costs a name on the wire -/// instead of its whole base64 body. Set by the input reader, which sees the -/// reply before vaxis' parser swallows every graphics APC alike. -var kitty_shm = std.atomic.Value(bool).init(false); -/// Only a reply that arrives while the probe is out counts. The id is one -/// vaxis' own image numbering (1, 2, ...) never reaches, because a terminal -/// answers every transmission `i=;OK` and one of those must not pass. -var kitty_shm_probing = std.atomic.Value(bool).init(false); +/// 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. +const Feed = struct { + view: u8 = 0, + cache: vaxis.GraphemeCache = .{}, + ack: FrameAck = .{}, + /// The terminal answered the shared-memory probe (`kittyShmProbe`): it + /// can read a raster from a POSIX shm object, so a page costs a name on + /// the wire instead of its whole base64 body. Set by the input reader, + /// which sees the reply before vaxis' parser swallows every graphics APC + /// alike. + shm: std.atomic.Value(bool) = .init(false), + /// Only a reply that arrives while the probe is out counts. The id is + /// one vaxis' own image numbering (1, 2, ...) never reaches, because a + /// terminal answers every transmission `i=;OK` and one of those must + /// not pass. + 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: @TypeOf(Command.value)) !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. @@ -62,13 +92,13 @@ fn kittyShmWrite(name: [:0]const u8, bytes: []const u8) bool { /// Ask with a 1x1 RGB image in shm whether the terminal reads that medium. A /// remote terminal cannot see our shm and answers an error (or nothing). -fn kittyShmProbe(w: *std.Io.Writer) void { +fn kittyShmProbe(w: *std.Io.Writer, feed: *Feed) void { var buf: [64]u8 = undefined; const name = kittyShmName(&buf, 0) catch return; if (!kittyShmWrite(name, &.{ 0, 0, 0 })) return; var b64: [64]u8 = undefined; const enc = std.base64.standard.Encoder.encode(&b64, name); - kitty_shm_probing.store(true, .release); + feed.shm_probing.store(true, .release); w.print("\x1b_Gi={d},s=1,v=1,a=q,t=s,f=24;{s}\x1b\\", .{ kitty_shm_probe_id, enc }) catch return; w.flush() catch {}; } @@ -86,6 +116,12 @@ pub const Command = struct { 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. + hangup, key_press: vaxis.Key, pty_read: struct { id: usize, gen: u32, bytes: []u8 }, pty_eof: struct { id: usize, gen: u32 }, @@ -107,36 +143,36 @@ pub const Command = struct { }; const Loop = vaxis.Loop(@TypeOf(Command.value)); -fn startInput(loop: *Loop, cache: *vaxis.GraphemeCache) !void { +fn startInput(loop: *Loop, sc: *Screen) !void { if (comptime builtin.os.tag == .windows) return loop.start(); - if (loop.thread != null) return; - loop.thread = try loop.io.concurrent(inputThread, .{ loop, cache }); + if (sc.thread != null) return; + sc.thread = try loop.io.concurrent(inputThread, .{ loop, sc }); } -fn stopInput(loop: *Loop) void { - if (comptime builtin.os.tag == .windows) return loop.stop(); - if (loop.thread) |*thread| { - thread.cancel(loop.io); - loop.thread = null; +fn stopInput(io: std.Io, thread: *?std.Io.Future(void)) void { + if (thread.*) |*t| { + t.cancel(io); + thread.* = null; } } -fn inputThread(loop: *Loop, cache: *vaxis.GraphemeCache) void { +fn inputThread(loop: *Loop, sc: *Screen) void { // vaxis's test terminal reads nothing off Linux: it has no read at all. if (comptime !@hasDecl(vaxis.Tty, "read")) return; - inputReader(loop, loop.tty, cache); + inputReader(loop, &sc.tty, &sc.vx, &sc.feed); } -fn inputReader(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) void { - readInput(loop, tty, cache) catch |err| { +fn inputReader(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) void { + readInput(loop, tty, vx, feed) catch |err| { if (err == error.Canceled) return; std.log.err("terminal input: {s}", .{@errorName(err)}); }; - loop.postEvent(.quit) catch {}; + (Poster{ .loop = loop, .view = feed.view }).postEvent(.quit) catch {}; } -fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { - try loop.postEvent(.{ .winsize = try tty.getWinsize() }); +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() }); var parser: vaxis.Parser = .{}; var buf: [1024]u8 = undefined; var carried: usize = 0; @@ -147,14 +183,14 @@ fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { // The terminal's answers to frames (FrameAck) come out first, // wherever they sit: never events, and never glued to a key (an // Escape pressed just before one would read as Alt on it). - const end = FrameAck.take(buf[0 .. carried + received], loop); + const end = feed.ack.take(buf[0 .. carried + received], loop); if (end == 0) { carried = 0; continue; } - if (kitty_shm_probing.load(.acquire)) if (std.mem.indexOf(u8, buf[0..end], std.fmt.comptimePrint("\x1b_Gi={d};", .{kitty_shm_probe_id}))) |at| { - kitty_shm_probing.store(false, .release); - kitty_shm.store(std.mem.startsWith(u8, buf[at..end], std.fmt.comptimePrint("\x1b_Gi={d};OK", .{kitty_shm_probe_id})), .release); + if (feed.shm_probing.load(.acquire)) if (std.mem.indexOf(u8, buf[0..end], std.fmt.comptimePrint("\x1b_Gi={d};", .{kitty_shm_probe_id}))) |at| { + feed.shm_probing.store(false, .release); + feed.shm.store(std.mem.startsWith(u8, buf[at..end], std.fmt.comptimePrint("\x1b_Gi={d};OK", .{kitty_shm_probe_id})), .release); // Answered either way: a terminal that could not read it left it. var name_buf: [64]u8 = undefined; if (kittyShmName(&name_buf, 0)) |name| _ = libc.shm_unlink(name) else |_| {} @@ -187,9 +223,9 @@ fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { std.mem.startsWith(u8, FrameAck.answer, rest)) break; if (!waited and parse_end == end and rest[0] == 0x1b and (rest.len == 1 or (rest.len == 2 and rest[1] == 0x1b))) { waited = true; - if (try inputFollows(tty, loop.io, if (loop.vaxis.caps.kitty_keyboard) 1000 else 50)) break; + if (try inputFollows(tty, loop.io, if (vx.caps.kitty_keyboard) 1000 else 50)) break; } - const result = try parser.parse(buf[consumed..parse_end], loop.vaxis.opts.system_clipboard_allocator); + const result = try parser.parse(buf[consumed..parse_end], vx.opts.system_clipboard_allocator); if (result.n == 0) break; consumed += result.n; // A modifier pressed on its own, which the kitty keyboard @@ -197,8 +233,8 @@ fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !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(loop, loop.vaxis, cache, @TypeOf(Command.value), event, loop.vaxis.opts.system_clipboard_allocator) catch |err| { - if (event == .paste) if (loop.vaxis.opts.system_clipboard_allocator) |gpa| gpa.free(@constCast(event.paste)); + vaxis.loop.handleEventGeneric(post, vx, &feed.cache, @TypeOf(Command.value), 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; }; // The last answer to the startup queries is no event of its @@ -226,14 +262,14 @@ const FrameAck = struct { const request = "\x1b[5n"; const answer = "\x1b[0n"; const timeout_ns: u64 = std.time.ns_per_s; - var waiting = std.atomic.Value(bool).init(false); - var off = std.atomic.Value(bool).init(false); + waiting: std.atomic.Value(bool) = .init(false), + off: std.atomic.Value(bool) = .init(false), /// When the request went out (the loop's thread only). - var sent_ns: u64 = 0; + sent_ns: u64 = 0, /// Take every answer out of `bytes`, closing up the rest; the new /// length. The loop is woken for the frame that waited on one. - fn take(bytes: []u8, loop: *Loop) usize { + fn take(a: *FrameAck, bytes: []u8, loop: *Loop) usize { var len = bytes.len; var found = false; while (std.mem.indexOf(u8, bytes[0..len], answer)) |at| { @@ -241,18 +277,18 @@ const FrameAck = struct { len -= answer.len; found = true; } - if (found and waiting.swap(false, .acq_rel)) loop.postEvent(.nop) catch {}; + if (found and a.waiting.swap(false, .acq_rel)) loop.postEvent(.nop) catch {}; return len; } /// Whether a new frame must wait (and the loop has a wake at the /// timeout); past the timeout the terminal is taken to never answer. - fn holds(now_ns: u64, io: std.Io) bool { - if (off.load(.acquire) or !waiting.load(.acquire)) return false; - const waited_ns = now_ns -| sent_ns; + fn holds(a: *FrameAck, now_ns: u64, io: std.Io) bool { + if (a.off.load(.acquire) or !a.waiting.load(.acquire)) return false; + const waited_ns = now_ns -| a.sent_ns; if (waited_ns >= timeout_ns) { - off.store(true, .release); - waiting.store(false, .release); + a.off.store(true, .release); + a.waiting.store(false, .release); return false; } requestWake(io, @intCast((timeout_ns - waited_ns + std.time.ns_per_ms - 1) / std.time.ns_per_ms)); @@ -260,14 +296,14 @@ const FrameAck = struct { } /// After a frame that wrote something: ask for the answer. - fn ask(w: *std.Io.Writer, now_ns: u64) void { - if (off.load(.acquire)) return; + fn ask(a: *FrameAck, w: *std.Io.Writer, now_ns: u64) void { + if (a.off.load(.acquire)) return; // Waiting before the request goes: a local terminal can answer // before the write returns, and an answer nobody waited for is lost. - sent_ns = now_ns; - waiting.store(true, .release); - w.writeAll(request) catch return waiting.store(false, .release); - w.flush() catch return waiting.store(false, .release); + a.sent_ns = now_ns; + a.waiting.store(true, .release); + w.writeAll(request) catch return a.waiting.store(false, .release); + w.flush() catch return a.waiting.store(false, .release); } }; @@ -299,7 +335,7 @@ test "terminal input preserves fragmented keys queries paste and text after EOF" vx.queries_done.store(false, .unordered); var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; + var feed: Feed = .{}; const Reader = struct { parts: []const []const u8, next: usize = 0, @@ -321,7 +357,7 @@ test "terminal input preserves fragmented keys queries paste and text after EOF" "plain \x1b[?62;", "4c\x1b[", "A\x1b[200", "~caf\xc3", "\xa9 \xe7", "\x95", "\x8c \xf0\x9f", "\x98\x80", "\x1b[201", "~\x1b]52;c;Y2", "xpcA==\x07tail", "\x1b", } }; - try readInput(&loop, &reader, &cache); + try readInput(&loop, &reader, &vx, &feed); try std.testing.expect(vx.queries_done.load(.unordered)); var text: std.ArrayList(u8) = .empty; defer text.deinit(gpa); @@ -384,7 +420,7 @@ test "terminal replies and malformed sequences never become typed text" { vx.queries_done.store(false, .unordered); var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; + var feed: Feed = .{}; const Reader = struct { parts: []const []const u8, next: usize = 0, @@ -427,7 +463,7 @@ test "terminal replies and malformed sequences never become typed text" { "c", }, }; - try readInput(&loop, &reader, &cache); + try readInput(&loop, &reader, &vx, &feed); try std.testing.expect(vx.queries_done.load(.unordered)); try std.testing.expect(vx.caps.kitty_graphics); var text: std.ArrayList(u8) = .empty; @@ -466,7 +502,7 @@ test "terminal input split at every byte with a gap reads as it does whole" { defer vx.deinit(gpa, &output.writer); var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; + var feed: Feed = .{}; // Two reads with `gap_ms` between them, as an ssh link delivers a // sequence cut across two packets. const Reader = struct { @@ -531,7 +567,7 @@ test "terminal input split at every byte with a gap reads as it does whole" { const all = try std.mem.concat(gpa, u8, &.{ "x", case.bytes, "y" }); defer gpa.free(all); var one: Reader = .{ .parts = .{ all, "" }, .gap_ms = 0 }; - try readInput(&loop, &one, &cache); + try readInput(&loop, &one, &vx, &feed); try Reader.events(&loop, &whole); for (1..all.len) |cut| { // A cut just after an ESC is the one that has to wait, and a @@ -539,7 +575,7 @@ test "terminal input split at every byte with a gap reads as it does whole" { // anywhere else is carried however long the gap. const after_esc = all[cut - 1] == 0x1b; var two: Reader = .{ .parts = .{ all[0..cut], all[cut..] }, .gap_ms = if (after_esc and !case.kitty) 40 else 60 }; - try readInput(&loop, &two, &cache); + try readInput(&loop, &two, &vx, &feed); try Reader.events(&loop, &split); std.testing.expectEqualStrings(whole.items, split.items) catch |err| { std.debug.print("case {f} cut at {d}\n", .{ std.ascii.hexEscape(case.bytes, .lower), cut }); @@ -562,7 +598,7 @@ test "an ESC read by itself is the Escape key at once" { defer vx.deinit(gpa, &output.writer); var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; + var feed: Feed = .{}; // More always follows at once: a reader that waited on the ESC would // take `j` for the rest of its sequence (Alt-j). const Reader = struct { @@ -587,7 +623,7 @@ test "an ESC read by itself is the Escape key at once" { for ([_]bool{ false, true }) |kitty| { vx.caps.kitty_keyboard = kitty; var reader: Reader = .{ .parts = &.{ "\x1b", "j" } }; - try readInput(&loop, &reader, &cache); + try readInput(&loop, &reader, &vx, &feed); try std.testing.expect(!reader.asked); try std.testing.expectEqual(.winsize, std.meta.activeTag((try loop.tryEvent()).?)); const escape = (try loop.tryEvent()).?.key_press; @@ -613,7 +649,7 @@ test "a frame's answer is taken wherever the reads cut it, and never typed" { defer vx.deinit(gpa, &output.writer); var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; + var feed: Feed = .{}; const Reader = struct { parts: [2][]const u8, next: usize = 0, @@ -635,12 +671,12 @@ test "a frame's answer is taken wherever the reads cut it, and never typed" { } }; const all = "x" ++ FrameAck.answer ++ "y"; - defer FrameAck.waiting.store(false, .release); + defer feed.ack.waiting.store(false, .release); for (0..all.len) |cut| { - FrameAck.waiting.store(true, .release); + feed.ack.waiting.store(true, .release); var reader: Reader = .{ .parts = .{ all[0..cut], all[cut..] } }; - try readInput(&loop, &reader, &cache); - try std.testing.expect(!FrameAck.waiting.load(.acquire)); + try readInput(&loop, &reader, &vx, &feed); + try std.testing.expect(!feed.ack.waiting.load(.acquire)); var typed: std.ArrayList(u8) = .empty; defer typed.deinit(gpa); var woke = false; @@ -658,9 +694,9 @@ test "a frame's answer is taken wherever the reads cut it, and never typed" { } // An Escape pressed just before an answer, in the same read, is the // Escape key, not Alt on the answer. - FrameAck.waiting.store(true, .release); + feed.ack.waiting.store(true, .release); var glued: Reader = .{ .parts = .{ "\x1b" ++ FrameAck.answer, "j" } }; - try readInput(&loop, &glued, &cache); + try readInput(&loop, &glued, &vx, &feed); try std.testing.expectEqual(.winsize, std.meta.activeTag((try loop.tryEvent()).?)); try std.testing.expectEqual(.nop, std.meta.activeTag((try loop.tryEvent()).?)); const escape = (try loop.tryEvent()).?.key_press; @@ -672,25 +708,21 @@ test "a frame's answer is taken wherever the reads cut it, and never typed" { test "a terminal that never answers a frame stops being asked after one timeout" { const io = std.testing.io; - defer { - FrameAck.off.store(false, .release); - FrameAck.waiting.store(false, .release); - FrameAck.sent_ns = 0; - } + var ack: FrameAck = .{}; var out: std.Io.Writer.Allocating = .init(std.testing.allocator); defer out.deinit(); const t0: u64 = 5 * std.time.ns_per_s; - FrameAck.ask(&out.writer, t0); + ack.ask(&out.writer, t0); try std.testing.expectEqualStrings(FrameAck.request, out.written()); // Unanswered: the next frame waits, until the timeout. - try std.testing.expect(FrameAck.holds(t0 + 10 * std.time.ns_per_ms, io)); - try std.testing.expect(FrameAck.holds(t0 + 999 * std.time.ns_per_ms, io)); - try std.testing.expect(!FrameAck.holds(t0 + FrameAck.timeout_ns, io)); + try std.testing.expect(ack.holds(t0 + 10 * std.time.ns_per_ms, io)); + try std.testing.expect(ack.holds(t0 + 999 * std.time.ns_per_ms, io)); + try std.testing.expect(!ack.holds(t0 + FrameAck.timeout_ns, io)); // Then never again: no request, no wait. out.clearRetainingCapacity(); - FrameAck.ask(&out.writer, t0 + 2 * std.time.ns_per_s); + ack.ask(&out.writer, t0 + 2 * std.time.ns_per_s); try std.testing.expectEqual(@as(usize, 0), out.written().len); - try std.testing.expect(!FrameAck.holds(t0 + 2 * std.time.ns_per_s, io)); + try std.testing.expect(!ack.holds(t0 + 2 * std.time.ns_per_s, io)); } test "terminal input cancellation joins blocked reads and queued EOF" { @@ -724,8 +756,8 @@ test "terminal input cancellation joins blocked reads and queued EOF" { } return self.file.readStreaming(std.testing.io, &.{buf}); } - fn run(loop: *Loop, reader: *@This(), cache: *vaxis.GraphemeCache) void { - inputReader(loop, reader, cache); + fn run(loop: *Loop, reader: *@This(), vx_: *vaxis.Vaxis, feed: *Feed) void { + inputReader(loop, reader, vx_, feed); } }; const Case = enum { blocked_read, cancel_eof, deliver_eof }; @@ -738,9 +770,9 @@ test "terminal input cancellation joins blocked reads and queued EOF" { var reader: Reader = .{ .file = .{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .eof = eof }; var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; - loop.thread = try io.concurrent(Reader.run, .{ &loop, &reader, &cache }); - defer stopInput(&loop); + var feed: Feed = .{}; + var thread: ?std.Io.Future(void) = try io.concurrent(Reader.run, .{ &loop, &reader, &vx, &feed }); + defer stopInput(io, &thread); try std.testing.expectEqual(.winsize, std.meta.activeTag(try loop.nextEvent())); try reader.entered.wait(io); if (eof) { @@ -750,10 +782,10 @@ test "terminal input cancellation joins blocked reads and queued EOF" { } if (case == .deliver_eof) { try std.testing.expectEqual(.nop, std.meta.activeTag(try loop.nextEvent())); - loop.thread.?.await(io); + thread.?.await(io); } - stopInput(&loop); - try std.testing.expect(loop.thread == null); + stopInput(io, &thread); + try std.testing.expect(thread == null); var count: usize = 0; while (try loop.tryEvent()) |event| { const expected: std.meta.Tag(@TypeOf(Command.value)) = if (case == .deliver_eof and count == 511) .quit else .nop; @@ -1194,7 +1226,8 @@ 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 }; + var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa), .primary = true }; + defer screen.kitty.deinit(); switch (term) { .open => try screen.enter(try vaxis.Tty.init(io, &tty_buf)), .fd => |fd| try screen.enter(try Screen.ttyOn(io, &tty_buf, fd)), @@ -1202,27 +1235,19 @@ pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { } defer screen.leave(); - var kitty_handles = std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image).init(gpa); - defer { - if (screen.on) clearNativeImages(&kitty_handles, &screen.vx, &screen.tty); - kitty_handles.deinit(); - } var paste_buf: std.Io.Writer.Allocating = .init(gpa); defer paste_buf.deinit(); var loop: Loop = .init(io, &screen.tty, &screen.vx); - var input_cache: vaxis.GraphemeCache = .{}; - try localSession(init, opts, &screen, &loop, &input_cache, &kitty_handles, &paste_buf); + try localSession(init, opts, &screen, &loop, &paste_buf); } -/// Whether a terminal is there to ask its size (winchWatch): none while -/// detached, when the descriptor it had may be another's. -var terminal_on = std.atomic.Value(bool).init(false); - -/// The terminal a session draws on, while it has one: entered (raw, the +/// 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). +/// 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. const Screen = struct { io: std.Io, gpa: std.mem.Allocator, @@ -1231,6 +1256,24 @@ 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, + kitty: std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), + caps_pending: bool = true, + /// Its size as last taken (`Shell.resized`). + size: ?vaxis.Winsize = null, + tracks: []const pardes.animation.Track = &.{}, + /// T2: the cursor's jump trail (JumpTrail). + trail: JumpTrail = .{}, + /// The view's glide, the GUI's motion drawn at whole rows (anim 12). + glide: pardes.glide.Glide = .{}, + /// T7: when each pane's view last moved (ThumbFlash). + flash: ThumbFlash = .{}, /// `fd` made raw, as vaxis.Tty.init makes /dev/tty: the terminal of a /// forked session is no controlling terminal of its, which /dev/tty is. @@ -1250,56 +1293,88 @@ const Screen = struct { try sc.vx.setMouseMode(sc.tty.writer(), true); try sc.vx.setBracketedPaste(sc.tty.writer(), true); if (comptime !builtin.is_test) { - Killed.arm(sc.tty.fd.handle, sc.tty.termios); + sc.killed = Killed.arm(sc.tty.fd.handle, sc.tty.termios); // What a panic puts back (vaxis.recover). - vaxis.tty.global_tty = sc.tty; + if (sc.primary) vaxis.tty.global_tty = sc.tty; } + const view = sc.feed.view; + sc.feed = .{ .view = view }; + sc.caps_pending = true; + sc.size = null; sc.on = true; - terminal_on.store(true, .release); } fn leave(sc: *Screen) void { if (!sc.on) return; sc.on = false; - terminal_on.store(false, .release); - Killed.disarm(); + if (sc.killed) |slot| Killed.disarm(slot); + sc.killed = null; + 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) vaxis.tty.global_tty = null; + if (comptime !builtin.is_test) if (sc.primary) { + 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.tellDetached(sc.stub); + 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; + var fds = [_]posix.pollfd{ + .{ .fd = sc.tty.fd.handle, .events = 0, .revents = 0 }, + .{ .fd = stub, .events = 0, .revents = 0 }, + }; + _ = posix.poll(fds[0..if (stub >= 0) 2 else 1], 0) catch return false; + 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; + } }; -/// SIGTERM or SIGHUP: the terminal put back as a clean exit leaves it -- +/// SIGTERM or SIGHUP: each 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 fd: posix.fd_t = -1; - var cooked: posix.termios = undefined; + var fds: [pardes.views.max]posix.fd_t = @splat(-1); + var cooked: [pardes.views.max]posix.termios = undefined; const reset = "\x1b[= 0) { + for (fds, &cooked) |fd, *termios| if (fd >= 0) { _ = std.c.write(fd, reset, reset.len); - _ = std.c.tcsetattr(fd, .FLUSH, &cooked); - } + _ = std.c.tcsetattr(fd, .FLUSH, termios); + }; // 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(); @@ -1315,14 +1390,10 @@ fn localSession( opts: pardes.Options, screen: *Screen, loop: *Loop, - input_cache: *vaxis.GraphemeCache, - kitty_handles: *std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), paste_buf: *std.Io.Writer.Allocating, ) !void { const io = init.io; const gpa = init.gpa; - const vx = &screen.vx; - const tty = &screen.tty; const allocs = pardes.memory.init(gpa); defer pardes.memory.deinit(); @@ -1367,20 +1438,23 @@ fn localSession( .core = core, .prompt_rcs = &prompt_rcs, .loop = loop, - .vx = vx, - .tty = tty, - .screen = screen, - .input_cache = input_cache, - .kitty = kitty_handles, .frame = &frame_arena, .paste_buf = paste_buf, .inotify_fd = file_watch.init(false), .fs = fs, .test_clock = host_io.testClock(), }; + sh.terms[0] = screen; pardes.lsp.setStatusSink(&sh, lspStatusSink); host_io.setExitWake(loop, wakeForExit); - defer sh.glide.deinit(gpa); + defer screen.glide.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); + sh.dropScreen(sc, .exit); + slot.* = null; + }; defer { host_io.setExitWake(null, null); pardes.lsp.setStatusSink(null, null); @@ -1421,7 +1495,7 @@ fn localSession( .search_rows => |b| b.deinit(gpa), .attach => |a| { _ = libc.close(a.tty); - _ = libc.close(a.stub); + if (a.stub >= 0) _ = libc.close(a.stub); }, .adopted => |a| _ = libc.close(a.fd), else => {}, @@ -1434,14 +1508,26 @@ fn localSession( core.unattended = !screen.on; while (core.nextEffect()) |effect| core.perform(effect); - if (screen.on) try startInput(loop, input_cache); - defer stopInput(loop); - (try std.Thread.spawn(.{}, winchWatch, .{ loop, vx, tty })).detach(); + if (screen.on) try startInput(loop, screen); + defer stopInput(io, &screen.thread); + (try std.Thread.spawn(.{}, winchWatch, .{loop})).detach(); (try std.Thread.spawn(.{}, wakeWatch, .{ io, loop })).detach(); if (fs) |f| try f.watch(loop, wakeFs); - if (screen.on) try vx.queryTerminalSend(tty.writer()); + 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 (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); + } + } sh.threads_ok = true; for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| { @@ -1497,15 +1583,29 @@ fn localSession( .{ .text = 0 }, ); _ = file_watch.applyThemeEffect(core, gpa, sh.inotify_fd, &sh.watches, 0, false, false); - if (screen.on) clearNativeImages(kitty_handles, vx, tty); - nc.native_images = screen.on and vx.caps.kitty_graphics; - nc.unattended = !screen.on; + // ponytail: a restored session is one view, the live one's + // terminal: the others are let go, as a detach of each. + const live = sh.term().?; + for (&sh.terms) |*slot| if (slot.*) |sc| if (sc != live) { + stopInput(io, &sc.thread); + sh.dropScreen(sc, .detach); + slot.* = null; + }; + sh.terms = @splat(null); + sh.terms[0] = live; + stopInput(io, &live.thread); + live.feed.view = 0; + sh.from = 0; + if (live.on) startInput(loop, live) catch {}; + if (live.on) clearNativeImages(&live.kitty, &live.vx, &live.tty); + nc.native_images = live.on and live.vx.caps.kitty_graphics; + nc.unattended = !live.on; if (fs) |f| f.reset(nc); core.deinit(); core = nc; sh.core = nc; - if (comptime pardes.pdf_enabled) if (screen.on) { - updateCoreTerminalSize(core, vx.screen.width, vx.screen.height, vx.screen.width_pix, vx.screen.height_pix); + if (comptime pardes.pdf_enabled) if (live.on) { + updateCoreTerminalSize(core, live.vx.screen.width, live.vx.screen.height, live.vx.screen.width_pix, live.vx.screen.height_pix); }; } } @@ -1554,12 +1654,11 @@ const Shell = struct { core: *pardes.Pardes, prompt_rcs: *const host_io.Shell.PromptFiles, loop: *Loop, - vx: *vaxis.Vaxis, - tty: *vaxis.Tty, - /// The terminal, while there is one (Screen.on); null in tests. - screen: ?*Screen = null, - input_cache: ?*vaxis.GraphemeCache = null, - kitty: *std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), + /// 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 (`Command.value.from`). + from: u8 = 0, frame: *std.heap.ArenaAllocator, paste_buf: *std.Io.Writer.Allocating, inotify_fd: c_int, @@ -1576,16 +1675,8 @@ const Shell = struct { lsp_task: ?host_io.Lsp.Task = null, pipe_tasks: PipeTasks = .{}, threads_ok: bool = false, - caps_pending: bool = true, check_files: bool = false, in_paste: bool = false, - tracks: []const pardes.animation.Track = &.{}, - /// T2: the cursor's jump trail (JumpTrail). - trail: JumpTrail = .{}, - /// The view's glide, the GUI's motion drawn at whole rows (anim 12). - glide: pardes.glide.Glide = .{}, - /// T7: when each pane's view last moved (ThumbFlash). - flash: ThumbFlash = .{}, /// PARDES_TEST_CLOCK's virtual time (host_io.testClock), and where the /// running-out wait moves it: the core's next wake. test_clock: ?u64 = null, @@ -1602,6 +1693,8 @@ const Shell = struct { input_ns: u64 = 0, focused_ns: u64 = 0, + const Leaving = enum { detach, exit }; + fn of(ctx: ?*anyopaque) *Shell { return @ptrCast(@alignCast(ctx.?)); } @@ -1653,8 +1746,13 @@ 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). + fn term(s: *const Shell) ?*Screen { + return s.terms[s.core.view]; + } + fn attached(s: *const Shell) bool { - const screen = s.screen orelse return true; + const screen = s.term() orelse return true; return screen.on; } @@ -1668,14 +1766,46 @@ const Shell = struct { fn detach(ctx: ?*anyopaque) void { const s = of(ctx); if (!s.attached()) return s.core.reportFailure(s.core.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.view, .detach); if (!daemon.kept()) return s.core.reportFailure(s.core.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); + s.dropScreen(sc, how); + } + + /// A terminal put back and its stub told; an attached one's Screen freed + /// (the session's own stays, a view of none). + fn dropScreen(s: *Shell, sc: *Screen, how: Leaving) void { + if (sc.primary) { + sc.leave(); + return sc.sayDetached(); + } + sc.leave(); + switch (how) { + .detach => sc.sayDetached(), + .exit => { + daemon.tellExit(sc.stub, 0); + sc.stub = -1; + }, + } + sc.glide.deinit(s.gpa); + sc.kitty.deinit(); + s.gpa.free(sc.buf); + s.gpa.destroy(sc); + } + fn leaveTerminal(s: *Shell) void { - const screen = s.screen orelse return; - stopInput(s.loop); - clearNativeImages(s.kitty, s.vx, s.tty); + const screen = s.term() orelse return; + stopInput(s.io, &screen.thread); screen.leave(); s.core.native_images = false; s.core.unattended = true; @@ -1685,39 +1815,65 @@ const Shell = struct { for (0..3) |i| _ = libc.dup2(null_fd, @intCast(i)); if (null_fd > 2) _ = libc.close(null_fd); } - daemon.tellStubDetached(); + screen.sayDetached(); daemon.setState(true); } - /// `pardes --attach`'s terminal, for this detached session: entered as - /// the first one was, 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; for one attached already, a view of + /// its own (views.zig). Sized, asked what it can do, and drawn whole. fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t) void { - const screen = s.screen orelse return; - if (screen.on) { + const live = s.term() orelse return; + const screen = if (!live.on) live else extra: { + const sc = s.gpa.create(Screen) catch break :extra null; + const buf = s.gpa.alloc(u8, 0x10000) catch { + s.gpa.destroy(sc); + break :extra null; + }; + sc.* = .{ .io = s.io, .gpa = s.gpa, .env = live.env, .buf = buf, .kitty = .init(s.gpa) }; + break :extra sc; + } orelse { _ = libc.close(fd); - return daemon.refuseStub(stub, "that session has a terminal already"); - } + return refuse(stub, "that session has no room for another terminal"); + }; + const extra = screen != live; const tty = Screen.ttyOn(s.io, screen.buf, fd) catch { _ = libc.close(fd); - daemon.setState(true); - return daemon.refuseStub(stub, "that terminal would not go raw"); + if (extra) s.freeScreen(screen) else daemon.setState(true); + return refuse(stub, "that terminal would not go raw"); }; screen.enter(tty) catch { - daemon.setState(true); - return daemon.refuseStub(stub, "that terminal would not take the screen"); + if (extra) s.freeScreen(screen) else daemon.setState(true); + return refuse(stub, "that terminal would not take the screen"); }; - daemon.stub = stub; - FrameAck.waiting.store(false, .release); - FrameAck.off.store(false, .release); - kitty_shm.store(false, .release); - s.caps_pending = true; + if (extra) { + const k = s.core.openView() orelse { + screen.leave(); + s.freeScreen(screen); + return refuse(stub, "that session has as many terminals as it takes"); + }; + screen.feed.view = k; + s.terms[k] = screen; + } + screen.setStub(stub); s.core.unattended = false; - startInput(s.loop, s.input_cache.?) catch {}; - s.vx.queryTerminalSend(s.tty.writer()) catch {}; + startInput(s.loop, screen) catch {}; + screen.vx.queryTerminalSend(screen.tty.writer()) catch {}; s.core.needs_frame = true; daemon.setState(false); } + fn freeScreen(s: *Shell, sc: *Screen) void { + sc.kitty.deinit(); + s.gpa.free(sc.buf); + s.gpa.destroy(sc); + } + + /// A terminal refused: its stub told why (a test's has none). + fn refuse(stub: posix.fd_t, why: []const u8) void { + if (stub >= 0) daemon.refuseStub(stub, why); + } + /// Adopt: the daemon is asked for the shells of sessions that died /// holding them; each comes back (`adopted`) as a terminal pane here. fn adopt(ctx: ?*anyopaque, pane: u8) void { @@ -1880,12 +2036,38 @@ const Shell = struct { else => {}, } if (s.input_seen) s.input_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + // A terminal's input goes into its view; a closed one's last is + // dropped. + switch (event) { + .key_press, .mouse, .paste, .paste_start, .paste_end, .winsize, .focus_in, .focus_out, .quit => { + if (s.terms[s.from] == null and s.term() != null) { + if (event == .paste) s.gpa.free(@constCast(event.paste)); + return false; + } + if (s.term() != null) core.toView(s.from); + }, + 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); + if (s.apply(.quit)) return true; + }, .wake => if (s.test_clock) |*virtual| { virtual.* = @max(virtual.*, s.wake_to); }, .quit => { + // One of several: its view goes with it. + if (pardes.views.count(core) > 1) { + s.dropView(core.view, .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 @@ -1905,13 +2087,7 @@ const Shell = struct { core.update(.pointer_leave); core.update(.{ .focus = false }); }, - .winsize => |ws| if (s.attached()) { - s.vx.resize(s.gpa, s.tty.writer(), ws) catch {}; - if (comptime pardes.pdf_enabled) - updateCoreTerminalSize(core, ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) - else - core.update(.{ .resize = .{ .cols = ws.cols, .rows = ws.rows } }); - }, + .winsize => |ws| if (s.attached()) s.resized(ws), .pty_read => |pr| { tookRead(s.io, pr.id); s.output_seen = true; @@ -2008,6 +2184,32 @@ const Shell = struct { return false; } + /// The live view's terminal is `ws` big. + fn resized(s: *Shell, ws: vaxis.Winsize) void { + const core = s.core; + if (s.term()) |sc| { + sc.size = ws; + sc.vx.resize(s.gpa, sc.tty.writer(), ws) catch {}; + } + if (comptime pardes.pdf_enabled) + updateCoreTerminalSize(core, ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) + else + core.update(.{ .resize = .{ .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). + 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; + s.core.toView(@intCast(k)); + s.resized(ws); + } + } + fn reloadWatched(s: *Shell) void { if (!s.check_files) return; s.check_files = false; @@ -2020,13 +2222,12 @@ const Shell = struct { /// notches are); `wheeled` from the mouse event if it should glide. fn stepGlide(ctx: ?*anyopaque) void { const s = of(ctx); - s.glide.step(s.core, s.gpa, null, null); + if (s.term()) |sc| sc.glide.step(s.core, s.gpa, null, null); } fn pollFrame(ctx: ?*anyopaque) void { const s = of(ctx); stepGlide(ctx); - s.core.native_image_patches = kitty_shm.load(.acquire); if (s.fs) |f| if (f.tick().pending) { _ = s.loop.tryPostEvent(.fs_ready) catch {}; }; @@ -2035,23 +2236,26 @@ const Shell = struct { if (host_io.ttyCwd(pt.pid, pt.file.handle, s.core.settings.shell.effective.get(), &lbuf)) |cwd| s.core.setCwd(id, cwd); }; - if (s.caps_pending and s.attached() and s.vx.queries_done.load(.unordered)) { - s.caps_pending = false; - s.vx.enableDetectedFeatures(s.tty.writer()) catch {}; - s.core.native_images = s.vx.caps.kitty_graphics; - if (s.vx.caps.kitty_graphics) kittyShmProbe(s.tty.writer()); - s.vx.queueRefresh(); + const sc = s.term() orelse return; + s.core.native_image_patches = sc.feed.shm.load(.acquire); + if (sc.caps_pending and sc.on and sc.vx.queries_done.load(.unordered)) { + sc.caps_pending = false; + sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {}; + s.core.native_images = sc.vx.caps.kitty_graphics; + if (sc.vx.caps.kitty_graphics) kittyShmProbe(sc.tty.writer(), &sc.feed); + sc.vx.queueRefresh(); s.core.needs_frame = true; } } fn present(ctx: ?*anyopaque, canonical: *const pardes.Surface) void { const s = of(ctx); - const vx = s.vx; - s.tracks = canonical.panelTracks(); + const sc = s.term() orelse return; + const vx = &sc.vx; + sc.tracks = canonical.panelTracks(); // The last frame is not answered yet: this one stays owed, and the // answer's wake draws the state as it is then. - if (FrameAck.holds(@intCast(std.Io.Clock.awake.now(s.io).nanoseconds), s.io)) { + if (sc.feed.ack.holds(@intCast(std.Io.Clock.awake.now(s.io).nanoseconds), s.io)) { s.core.present_skipped = true; return; } @@ -2059,21 +2263,21 @@ const Shell = struct { const surface = panel_compositor.compose( s.frame.allocator(), @constCast(canonical), - s.tracks, + sc.tracks, s.core.theme().bg, ) catch return; const tz_cells = tracy.zone(@src(), "surface->vaxis"); const win = vx.window(); const truecolor = vx.caps.rgb or colortermTruecolor(); // Each of the shell's own motions below asks for frames while it runs. - if (s.glide.pending) s.glide.measure(s.gpa, canonical); - if (s.glide.moving()) s.glide.advance(s.core.now_ns, s.glide.motion); - s.core.shell_continuous = s.glide.moving(); - s.core.frames.scroll = @round(s.glide.follow.offset); - const glided = pardes.glide.shifted(&s.glide, s.frame.allocator(), surface) catch surface; + if (sc.glide.pending) sc.glide.measure(s.gpa, canonical); + if (sc.glide.moving()) sc.glide.advance(s.core.now_ns, sc.glide.motion); + s.core.shell_continuous = sc.glide.moving(); + s.core.frames.scroll = @round(sc.glide.follow.offset); + const glided = pardes.glide.shifted(&sc.glide, s.frame.allocator(), surface) catch surface; const shadowed = chipShadows(s.frame.allocator(), glided, s.core, truecolor) catch glided; - const flashed = s.flash.apply(s.frame.allocator(), shadowed, s.core, truecolor) catch shadowed; - const trailed = s.trail.apply(s.frame.allocator(), flashed, s.core, truecolor) catch flashed; + const flashed = sc.flash.apply(s.frame.allocator(), shadowed, s.core, truecolor) catch shadowed; + const trailed = sc.trail.apply(s.frame.allocator(), flashed, s.core, truecolor) catch flashed; paintCells(win, trailed.cells, trailed.cols, trailed.rows); tz_cells.end(); for (surface.images[0..surface.nimages]) |maybe| { @@ -2083,7 +2287,7 @@ const Shell = struct { if (!kittyImageRepresentable(place)) continue; } const key = place.cacheKey(); - if (!s.kitty.contains(key) and vx.caps.kitty_graphics and kitty_shm.load(.acquire)) shm: { + if (!sc.kitty.contains(key) and vx.caps.kitty_graphics and sc.feed.shm.load(.acquire)) shm: { var buf: [64]u8 = undefined; kitty_shm_serial +%= 1; // Bounded: a segment this many transmissions old was never @@ -2095,21 +2299,21 @@ const Shell = struct { } const name = kittyShmName(&buf, kitty_shm_serial) catch break :shm; if (!kittyShmWrite(name, place.rgba)) break :shm; - if (vx.transmitLocalImagePath(s.gpa, s.tty.writer(), name, @intCast(place.iw), @intCast(place.ih), .shared_mem, .rgba) catch null) |handle| - s.kitty.put(key, handle) catch vx.freeImage(s.tty.writer(), handle.id) + if (vx.transmitLocalImagePath(s.gpa, sc.tty.writer(), name, @intCast(place.iw), @intCast(place.ih), .shared_mem, .rgba) catch null) |handle| + sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id) else _ = libc.shm_unlink(name); } - if (!s.kitty.contains(key) and vx.caps.kitty_graphics) { + if (!sc.kitty.contains(key) and vx.caps.kitty_graphics) { const enc = std.base64.standard.Encoder; if (s.gpa.alloc(u8, enc.calcSize(place.rgba.len))) |b64| { defer s.gpa.free(b64); _ = enc.encode(b64, place.rgba); - if (vx.transmitPreEncodedImage(s.tty.writer(), b64, @intCast(place.iw), @intCast(place.ih), .rgba) catch null) |handle| - s.kitty.put(key, handle) catch vx.freeImage(s.tty.writer(), handle.id); + if (vx.transmitPreEncodedImage(sc.tty.writer(), b64, @intCast(place.iw), @intCast(place.ih), .rgba) catch null) |handle| + sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id); } else |_| {} } - if (s.kitty.get(key)) |cached| { + if (sc.kitty.get(key)) |cached| { if (comptime !pardes.pdf_enabled) { const child = win.child(.{ .x_off = place.x, .y_off = place.y, .width = place.w, .height = place.h }); cached.draw(child, .{ .scale = .contain }) catch {}; @@ -2150,32 +2354,32 @@ const Shell = struct { while (true) { var stale: [pardes.MAX_PANES]pardes.ImageCacheKey = undefined; var stale_len: usize = 0; - var image_iterator = s.kitty.iterator(); + var image_iterator = sc.kitty.iterator(); while (image_iterator.next()) |entry| { if (surfaceHasKittyKey(surface, entry.key_ptr.*)) continue; stale[stale_len] = entry.key_ptr.*; stale_len += 1; if (stale_len == stale.len) break; } - for (stale[0..stale_len]) |key| if (s.kitty.fetchRemove(key)) |removed| - vx.freeImage(s.tty.writer(), removed.value.id); + for (stale[0..stale_len]) |key| if (sc.kitty.fetchRemove(key)) |removed| + vx.freeImage(sc.tty.writer(), removed.value.id); if (stale_len < stale.len) break; } if (glided.cursor) |cur| paintCursor(win, cur.x, cur.y, cur.bar); const tz_render = tracy.zone(@src(), "vx.render"); - const before = s.tty.tty_writer.pos + s.tty.writer().end; - vx.render(s.tty.writer()) catch {}; + const before = sc.tty.tty_writer.pos + sc.tty.writer().end; + vx.render(sc.tty.writer()) catch {}; // The frame's cost to the terminal (FrameStats.Frame.bytes): what // vaxis's diff of the cells wrote. - s.core.frames.bytes +|= @intCast(@min(std.math.maxInt(u32), s.tty.tty_writer.pos + s.tty.writer().end -| before)); - if (s.tty.tty_writer.pos + s.tty.writer().end != before) FrameAck.ask(s.tty.writer(), @intCast(std.Io.Clock.awake.now(s.io).nanoseconds)); + s.core.frames.bytes +|= @intCast(@min(std.math.maxInt(u32), sc.tty.tty_writer.pos + sc.tty.writer().end -| before)); + if (sc.tty.tty_writer.pos + sc.tty.writer().end != before) sc.feed.ack.ask(sc.tty.writer(), @intCast(std.Io.Clock.awake.now(s.io).nanoseconds)); s.drawn_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); tz_render.end(); } fn postPresent(ctx: ?*anyopaque) void { const s = of(ctx); - s.core.acknowledgePanelPresentation(s.tracks); + if (s.term()) |sc| s.core.acknowledgePanelPresentation(sc.tracks); tracy.frameMark(); } @@ -2320,14 +2524,16 @@ const Shell = struct { fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { const s = of(ctx); // Detached, the session keeps it (a 9P read, a paste here). - if (!s.attached()) return s.core.fallback.setClipboard(text); - copyToClipboard(s.vx, s.tty, s.gpa, text); + const sc = s.term() orelse return s.core.fallback.setClipboard(text); + if (!sc.on) return s.core.fallback.setClipboard(text); + copyToClipboard(&sc.vx, &sc.tty, s.gpa, text); } fn readClipboard(ctx: ?*anyopaque) void { const s = of(ctx); - if (!s.attached()) return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); - requestClipboard(s.vx, s.tty); + const sc = s.term() orelse return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); + if (!sc.on) return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); + requestClipboard(&sc.vx, &sc.tty); } fn openLink(_: ?*anyopaque, url: []const u8) void { @@ -2391,9 +2597,6 @@ test "TTY queued results reject old PTY generations and LSP request IDs" { .core = core, .prompt_rcs = undefined, .loop = undefined, - .vx = undefined, - .tty = undefined, - .kitty = undefined, .frame = undefined, .paste_buf = undefined, .inotify_fd = -1, @@ -2439,9 +2642,6 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { .core = core, .prompt_rcs = undefined, .loop = undefined, - .vx = undefined, - .tty = undefined, - .kitty = undefined, .frame = undefined, .paste_buf = undefined, .inotify_fd = -1, @@ -2507,24 +2707,16 @@ fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void { fn keepSignal(_: posix.SIG) callconv(.c) void {} -fn winchWatch(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { +fn winchWatch(loop: *Loop) void { var set = posix.sigemptyset(); posix.sigaddset(&set, posix.SIG.WINCH); if (daemon.link >= 0) posix.sigaddset(&set, posix.SIG.HUP); while (true) { var sig: c_int = 0; if (libc.sigwait(&set, &sig) != 0) continue; - // The terminal hung up (its stub passes the hangup on): as its - // input's end. - if (sig == @backingInt(posix.SIG.HUP)) { - loop.postEvent(.quit) catch {}; - continue; - } - // Detached, the descriptor the terminal had may be another's now. - if (!terminal_on.load(.acquire)) continue; - if (vx.state.in_band_resize) continue; // terminal reports via CSI 48 - const ws = tty.getWinsize() catch continue; - loop.postEvent(.{ .winsize = ws }) catch {}; + // The terminals are the loop's: it asks each its size, and takes a + // hangup as the end of the one that hung up. + loop.postEvent(if (sig == @backingInt(posix.SIG.HUP)) .hangup else .winched) catch {}; } } @@ -2665,7 +2857,7 @@ test "a terminal pane gets function keys as their sequences and lone modifiers n vx.queries_done.store(false, .unordered); var tty: vaxis.Tty = undefined; var loop: Loop = .init(io, &tty, &vx); - var cache: vaxis.GraphemeCache = .{}; + var feed: Feed = .{}; const Reader = struct { parts: []const []const u8, next: usize = 0, @@ -2698,7 +2890,7 @@ test "a terminal pane gets function keys as their sequences and lone modifiers n "\x1b[104;;104u", }, }; - try readInput(&loop, &reader, &cache); + try readInput(&loop, &reader, &vx, &feed); const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); core.panes[0].?.body.mode = .tty; diff --git a/src/views.zig b/src/views.zig new file mode 100644 index 00000000..ae2b338d --- /dev/null +++ b/src/views.zig @@ -0,0 +1,555 @@ +//! Views: several clients on one session, kakoune's way (docs/next-daemon.md, +//! "Phase 4 notes"). Each view has its own layout, focus, selections and +//! scroll over the panes every view shares: their text, terminals, tags, +//! registers and messages. +//! +//! The core still sees one view, the live one, in the fields it always had: +//! a view's share of the session (`fields`) and of each pane (`PaneView`) is +//! copied out when another view goes live (`park`) and back when it is live +//! again (`unpark`). No line of the core reads a view through an +//! indirection, and one view never parks: today's single client runs +//! exactly as before. +//! +//! A parked view is in no digest (Pardes.replica's `parked`, Pane's `pv`): +//! a slot is written whenever its view goes out, so the live view's slot is +//! stale by design, and a parked view that diverged shows when it is live +//! again. The pump draws the other views by going into each and back +//! (`drawOthers`), which leaves every digested field as it was; a replica +//! that draws nothing skips it. +const std = @import("std"); +const pardes = @import("pardes.zig"); +const Pardes = pardes.Pardes; +const Pane = pardes.Pane; +const Text = pardes.panes.Text; +const File = pardes.panes.File; +const layout = pardes.layout; +const MAX_PANES = pardes.MAX_PANES; + +/// Views at once: a window or terminal each. +pub const max = 4; + +/// The session's fields that are each view's own: its screen and layout, +/// its focus, its pointer and gestures, its jumps, its key prefixes, and +/// what drawing it keeps (animations, the presentation of its panels). +pub const fields = [_][:0]const u8{ + "screen_w", "screen_h", "cell_pixels", "row_metrics", + "ncol", "col_weight", "col_panes", "col_n", + "col_tags", "col_serial", "finder", "rects", + "col_x", "col_w", "presentation", "active", + "jumps", "njumps", "jcur", "jump_force", + "active_column", "lifts", "lift_serials", "cursor_glide", + "cursor_view", "cursor_crossing", "cursor_held", "shell_continuous", + "input_ns", "native_images", "native_image_patches", "windowed", + "drag", "mouse_grab", "window_focused", "focus_told", + "hover_col", "hover_row", "pointer_raw_col", "pointer_raw_row", + "pointer_body_hit", "pointer_tag_hit", "raw_hover_intent", "pointer_inside", + "last_click", "click_as", "chord_hold", "wheel_guard", + "ctrl_w_pending", "register", "leader_on", "window_pick", + "leader_keys", "leader_n", "header_focus", "header_column", + "header_drag", "header_sweep", "header_scroll", "header_top", + "ov_pinch_scale", "ov_touch_scroll_delta", "chord_arg", "clip_pending", +}; + +/// A pane's fields that are each view's own: where it is in the view's +/// layout, which of its texts has the keyboard, how far it is scrolled, and +/// what the view's step measured of it (its tag's rows, its bands). +const pane_fields = [_][:0]const u8{ "focus", "vweight", "collapsed", "attached_to", "hscroll", "tag_scroll", "tag_top", "tag_rows", "view", "notices" }; + +/// The body's: its cursor, selections and mode. Its undo stays the pane's. +const body_fields = [_][:0]const u8{ "mode", "cur_pinned", "cur_row", "cur_col", "msel", "vsel", "sels", "nsel", "select", "sticky_col", "restore_cursor", "last_edit", "reg_wait", "normal", "find_op", "find_ch" }; + +pub const View = Part(Pardes, &fields); + +/// Named field by field, not taken from Pane's type: a pane holds its own. +pub const PaneView = struct { + focus: Pane.Focus = .body, + vweight: f32 = 1, + collapsed: bool = false, + attached_to: ?u32 = null, + hscroll: i32 = 0, + tag_scroll: u16 = 0, + tag_top: u16 = 0, + tag_rows: u16 = 1, + view: Pane.SessionView = .{}, + notices: Pane.Notices = .{}, + body: Part(Text, &body_fields) = .{}, + /// A document's scroll and size; a terminal's size is its pty's, which + /// every view shows (sized by its last typist, `Pardes.sync`). + scroll: usize = 0, + cols: u16 = 1, + rows: u16 = 1, +}; + +/// A view not live: its share of the session, and the serial of each pane +/// slot when it went out, by which the panes closed since leave its layout. +pub const Parked = struct { + view: View, + serials: [MAX_PANES]u32 = @splat(0), +}; + +/// The fields of `T` named, as a struct of their own, each of its type and +/// default. +fn Part(comptime T: type, comptime names: []const [:0]const u8) type { + @setEvalBranchQuota(100_000); + const s = @typeInfo(T).@"struct"; + var types: [names.len]type = undefined; + var attrs: [names.len]std.lang.Type.Struct.FieldAttributes = undefined; + for (names, 0..) |name, i| { + const at = for (s.field_names, 0..) |n, j| { + if (std.mem.eql(u8, n, name)) break j; + } else @compileError("views: " ++ @typeName(T) ++ " has no field " ++ name); + types[i] = s.field_types[at]; + attrs[i] = .{ .default_value_ptr = s.field_attrs[at].default_value_ptr }; + } + return @Struct(.auto, null, names, &types, &attrs); +} + +fn copy(comptime names: []const [:0]const u8, dst: anytype, src: anytype) void { + inline for (names) |name| @field(dst, name) = @field(src, name); +} + +pub fn isOpen(p: *const Pardes, k: u8) bool { + return k < max and p.views_open & (@as(u8, 1) << @intCast(k)) != 0; +} + +pub fn count(p: *const Pardes) usize { + return @popCount(p.views_open); +} + +/// More than one view: the one test the single client's path pays. +pub fn several(p: *const Pardes) bool { + return p.views_open & (p.views_open -% 1) != 0; +} + +/// Pane `pane`'s share of the live view. +fn extract(pane: *const Pane) PaneView { + var v: PaneView = .{ .cols = pane.cols, .rows = pane.rows }; + copy(&pane_fields, &v, pane); + copy(&body_fields, &v.body, &pane.body); + if (pane.file) |f| v.scroll = f.scroll; + return v; +} + +/// Its share of view `v` put back. +fn apply(pane: *Pane, v: *const PaneView) void { + copy(&pane_fields, pane, v); + copy(&body_fields, &pane.body, &v.body); + if (!pane.isTerminal()) { + pane.cols = v.cols; + pane.rows = v.rows; + } + const f = if (pane.file) |*file| file else return; + // The text may have changed while the view was out: what it held is + // brought back inside it. + const lines = File.nlines(pane.gpa, f); + f.scroll = @min(v.scroll, lines -| 1); + if (pane.body.cur_row >= lines) { + pane.body.vsel.active = false; + pane.body.msel.active = false; + pane.body.nsel = 0; + } + _ = pardes.edit.clampFileCursor(&pane.body); +} + +/// A copy of the live view's share for another view, owning nothing of the +/// live one's (its extra selections stay behind). +fn fresh(pane: *const Pane) PaneView { + var v = extract(pane); + v.body.sels = &.{}; + v.body.nsel = 0; + return v; +} + +/// A new pane is in each other view as it was made, there to be shown. +pub fn installed(p: *Pardes, pane: *Pane) void { + pane.sized_by = p.view; + if (!several(p)) return; + for (0..max) |k| if (k != p.view and isOpen(p, @intCast(k))) { + pane.pv[k] = fresh(pane); + }; + pane.pv_known = p.views_open; +} + +/// A pane going: the other views' selections of it go too. +pub fn tornDown(p: *Pardes, pane: *Pane) void { + for (0..max) |k| if (k != p.view and pane.pv_known & (@as(u8, 1) << @intCast(k)) != 0) { + const sels = pane.pv[k].body.sels; + if (sels.len > 0) p.gpa.free(sels); + pane.pv[k].body.sels = &.{}; + }; +} + +fn park(p: *Pardes) void { + const slot = p.parked[p.view].?; + copy(&fields, &slot.view, p); + for (p.panes, 0..) |s, id| { + const pane = s orelse { + slot.serials[id] = 0; + continue; + }; + slot.serials[id] = pane.serial; + pane.pv[p.view] = extract(pane); + } +} + +fn unpark(p: *Pardes, k: u8) void { + const slot = p.parked[k].?; + copy(&fields, p, &slot.view); + p.view = k; + for (p.panes) |s| if (s) |pane| apply(pane, &pane.pv[k]); + // The panes closed while it was out (a slot empty or another pane's + // now) leave its layout, and its keyboard leaves them. + for (0..p.ncol) |c| { + var n: usize = 0; + for (p.col_panes[c][0..p.col_n[c]]) |id| { + const pane = p.panes[id] orelse continue; + if (pane.serial != slot.serials[id]) continue; + p.col_panes[c][n] = id; + n += 1; + } + p.col_n[c] = n; + } + if (layout.findPane(p, p.active) == null) { + for (0..p.ncol) |c| if (p.col_n[c] > 0) { + p.active = p.col_panes[c][0]; + break; + }; + } + layout.compute(p); +} + +/// The pane with the keyboard is one the live view shows: focused where its +/// layout has it not (a Look at a file another view opened, a jump, a 9P +/// focus), it goes into the view's active column, as kakoune shows a buffer +/// in the window that asked for it. +pub fn show(p: *Pardes) void { + if (p.panes[p.active] == null or layout.findPane(p, p.active) != null) return; + const c = layout.firstColumn(p) orelse layout.columnBySerial(p, p.active_column) orelse p.ncol - 1; + layout.acmePlace(p, c, null, p.active); +} + +/// Into view `k`: the live one parked, `k`'s put in its place. +pub fn to(p: *Pardes, k: u8) void { + std.debug.assert(isOpen(p, k)); + if (k == p.view) return; + park(p); + unpark(p, k); +} + +/// A new view, as the live one is laid out and focused, with its panes +/// where they are scrolled and its cursors where they are; the rest of it +/// (column tags, gestures, animations) as a session starts. Null when there +/// are `max` already. +pub fn open(p: *Pardes) ?u8 { + const k: u8 = for (0..max) |i| { + if (!isOpen(p, @intCast(i))) break @intCast(i); + } else return null; + // Each live view parks too: its slot is made with the first other. + for ([_]u8{ p.view, k }) |i| if (p.parked[i] == null) { + const slot = p.gpa.create(Parked) catch return null; + slot.* = .{ .view = .{ .screen_w = p.screen_w, .screen_h = p.screen_h } }; + p.parked[i] = slot; + }; + const slot = p.parked[k].?; + slot.* = .{ .view = .{ .screen_w = p.screen_w, .screen_h = p.screen_h } }; + inline for (.{ "screen_w", "screen_h", "cell_pixels", "row_metrics", "ncol", "col_weight", "col_panes", "col_n", "col_serial", "finder", "active", "active_column", "jumps", "njumps", "jcur", "windowed", "native_images", "native_image_patches" }) |name| + @field(slot.view, name) = @field(p, name); + slot.view.col_tags = @splat(.{ .what = .column, .gpa = p.gpa }); + for (p.panes, 0..) |s, id| { + const pane = s orelse continue; + slot.serials[id] = pane.serial; + pane.pv[k] = fresh(pane); + pane.pv_known |= @as(u8, 1) << @intCast(k); + } + p.views_open |= @as(u8, 1) << @intCast(k); + return k; +} + +/// View `k` gone, and all it held; the live one moves to another first. +/// The last view stays: a session without a client keeps its own. +pub fn close(p: *Pardes, k: u8) void { + if (!isOpen(p, k) or count(p) == 1) return; + if (k == p.view) { + const other: u8 = for (0..max) |i| { + if (i != k and isOpen(p, @intCast(i))) break @intCast(i); + } else unreachable; + park(p); + unpark(p, other); + } + const v = &p.parked[k].?.view; + for (&v.col_tags) |*t| t.deinit(p.gpa); + if (v.chord_arg) |a| p.gpa.free(a); + v.presentation.deinit(p.gpa); + for (p.panes) |s| if (s) |pane| { + const sels = pane.pv[k].body.sels; + if (sels.len > 0) p.gpa.free(sels); + pane.pv[k].body.sels = &.{}; + pane.pv_known &= ~(@as(u8, 1) << @intCast(k)); + }; + p.views_open &= ~(@as(u8, 1) << @intCast(k)); +} + +/// The session's end: what each view not live holds. +pub fn deinit(p: *Pardes) void { + for (0..max) |i| { + const k: u8 = @intCast(i); + const slot = p.parked[k] orelse continue; + if (k != p.view and isOpen(p, k)) { + const v = &slot.view; + for (&v.col_tags) |*t| t.deinit(p.gpa); + if (v.chord_arg) |a| p.gpa.free(a); + v.presentation.deinit(p.gpa); + } + p.gpa.destroy(slot); + } +} + +/// What drawing a view keeps of its own (its animations, its panels as +/// presented), kept from a frame drawn while it was out. +const drawn_fields = [_][:0]const u8{ "presentation", "lifts", "lift_serials", "cursor_glide", "cursor_view", "cursor_crossing", "cursor_held", "shell_continuous" }; + +/// Each view but the live one drawn and presented, the live one put back +/// after exactly as it was: no digested field moves, so a replica that +/// draws nothing (and skips this) stays the same. A view drawn keeps only +/// what its drawing made (`drawn_fields`); whatever its unpark brought +/// inside a changed text is not kept, and is done again when it is next +/// live. Before the live one's frame: the surface after the pump is its. +pub fn drawOthers(p: *Pardes, h: pardes.Host) !void { + const live = p.view; + const v = h.vtable; + park(p); + defer { + copy(&fields, p, &p.parked[live].?.view); + p.view = live; + for (p.panes) |s| if (s) |pane| { + const pv = &pane.pv[live]; + copy(&pane_fields, pane, pv); + copy(&body_fields, &pane.body, &pv.body); + if (!pane.isTerminal()) { + pane.cols = pv.cols; + pane.rows = pv.rows; + } + if (pane.file) |*f| f.scroll = pv.scroll; + }; + } + for (0..max) |i| { + const k: u8 = @intCast(i); + if (k == live or !isOpen(p, k)) continue; + unpark(p, k); + _ = p.frame_arena.reset(.{ .retain_with_limit = pardes.memory.limits.frame_kept }); + const surface = try p.render(p.frame_arena.allocator()); + if (v.present) |f| f(h.ctx, surface); + if (v.post_present) |f| f(h.ctx); + copy(&drawn_fields, &p.parked[k].?.view, p); + } +} + +// ---- tests ---- + +const testing = std.testing; +const Key = pardes.Key; + +fn typeKeys(p: *Pardes, text: []const u8) void { + for (text) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); +} + +fn escape(p: *Pardes) void { + p.update(.{ .key = .{ .cp = Key.escape } }); +} + +fn numbered(gpa: std.mem.Allocator, n: usize) ![]u8 { + var out: std.ArrayList(u8) = .empty; + for (1..n + 1) |i| try out.print(gpa, "line {d}\n", .{i}); + return out.toOwnedSlice(gpa); +} + +/// The cursor put on `row`, as a jump puts it, and the step after. +fn cursorTo(p: *Pardes, pane: *Pane, row: i32) void { + pane.body.vsel.active = false; + pane.body.nsel = 0; + pane.body.cur_row = row; + pane.body.cur_col = 0; + pane.body.cur_pinned = true; + pane.ensureCursorVisible(); + p.sync(); +} + +test "each view has its own cursor and scroll, and an edit in one is in the other" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const text = try numbered(gpa, 200); + defer gpa.free(text); + const pane = try p.setTestFile(text); + try testing.expectEqual(@as(?u8, 1), p.openView()); + cursorTo(p, pane, 119); + const scrolled = pane.file.?.scroll; + try testing.expect(scrolled > 0); + // The other view is where the session was when it came. + p.toView(1); + try testing.expectEqual(@as(i32, 0), pane.body.cur_row); + try testing.expectEqual(@as(usize, 0), pane.file.?.scroll); + typeKeys(p, "ix"); + escape(p); + try testing.expectEqual(Text.Mode.normal, pane.body.mode); + p.toView(0); + try testing.expectEqual(@as(i32, 119), pane.body.cur_row); + try testing.expectEqual(scrolled, pane.file.?.scroll); + try testing.expect(std.mem.startsWith(u8, pane.file.?.content, "xline 1\n")); + // Its mode is its own: insert here leaves the other in normal. + typeKeys(p, "i"); + try testing.expectEqual(Text.Mode.insert, pane.body.mode); + p.toView(1); + try testing.expectEqual(Text.Mode.normal, pane.body.mode); +} + +test "each view has its own layout and focus over the same panes" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); + defer p.deinit(); + _ = try p.setTestFile("one\ntwo\n"); + const k = p.openView().?; + const ncol = p.ncol; + p.toView(k); + p.update(.{ .command = "Newcol" }); + p.update(.{ .command = "New" }); + const made = p.active; + try testing.expect(made != 0); + try testing.expectEqual(ncol + 1, p.ncol); + p.toView(0); + try testing.expectEqual(ncol, p.ncol); + try testing.expectEqual(@as(usize, 0), p.active); + try testing.expect(layout.findPane(p, made) == null); + try testing.expectEqual(pardes.Rect{}, p.rects[made]); + // The pane is the session's: focused here, this view shows it too. + p.active = made; + p.sync(); + try testing.expect(layout.findPane(p, made) != null); + try testing.expect(p.rects[made].h > 0); + // Closed here, it leaves the other view's layout, and its keyboard. + try p.removePane(made, null); + p.sync(); + p.toView(k); + try testing.expect(layout.findPane(p, made) == null); + try testing.expect(p.panes[p.active] != null); + try testing.expect(layout.findPane(p, p.active) != null); +} + +test "registers are the session's: yanked in one view, put in another" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha\nbeta\n"); + const k = p.openView().?; + typeKeys(p, "xy"); + p.toView(k); + cursorTo(p, pane, 1); + typeKeys(p, "p"); + try testing.expectEqualStrings("alpha\nbeta\nalpha\n", pane.file.?.content); +} + +test "a terminal shown at two sizes takes the size of the view that typed into it last" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const term = p.panes[p.active].?; + try testing.expect(term.isTerminal()); + const small = .{ term.cols, term.rows }; + const k = p.openView().?; + p.toView(k); + p.update(.{ .resize = .{ .cols = 120, .rows = 40 } }); + // Shown bigger here, it keeps the size of the view that typed last. + try testing.expect(p.rects[p.active].w > 80); + try testing.expectEqual(small, .{ term.cols, term.rows }); + p.update(.{ .key = .{ .cp = Key.right } }); + try testing.expect(term.cols > small[0] and term.rows > small[1]); + const big = .{ term.cols, term.rows }; + p.toView(0); + p.sync(); + try testing.expectEqual(big, .{ term.cols, term.rows }); + p.update(.{ .key = .{ .cp = Key.right } }); + try testing.expectEqual(small, .{ term.cols, term.rows }); + // That view gone, the one left sizes it. + p.toView(k); + p.closeView(0); + try testing.expectEqual(k, p.view); + try testing.expectEqual(big, .{ term.cols, term.rows }); +} + +test "a view closing leaves the others as they were" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); + defer p.deinit(); + const text = try numbered(gpa, 100); + defer gpa.free(text); + const pane = try p.setTestFile(text); + const a = p.openView().?; + const b = p.openView().?; + try testing.expectEqual(@as(usize, 3), count(p)); + p.toView(b); + p.update(.{ .command = "Newcol" }); + cursorTo(p, pane, 40); + typeKeys(p, "xy"); + p.toView(a); + cursorTo(p, pane, 70); + p.toView(0); + cursorTo(p, pane, 10); + const ncol = p.ncol; + // The live one closing: the session goes into another. + p.toView(b); + p.closeView(b); + try testing.expect(p.view != b); + try testing.expectEqual(@as(usize, 2), count(p)); + p.toView(a); + try testing.expectEqual(@as(i32, 70), pane.body.cur_row); + p.closeView(0); + try testing.expectEqual(a, p.view); + try testing.expectEqual(ncol, p.ncol); + // The last stays. + p.closeView(a); + try testing.expectEqual(@as(usize, 1), count(p)); + try testing.expectEqual(@as(i32, 70), pane.body.cur_row); +} + +test "drawing the other views 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(); + const text = try numbered(gpa, 100); + defer gpa.free(text); + const pane = try p.setTestFile(text); + const k = p.openView().?; + p.toView(k); + cursorTo(p, pane, 60); + typeKeys(p, "dd"); + p.toView(0); + cursorTo(p, pane, 95); + const before = pardes.walk.digest(Pardes, p); + try drawOthers(p, .{}); + try testing.expectEqual(@as(u8, 0), p.view); + try testing.expectEqual(before, pardes.walk.digest(Pardes, p)); + p.toView(k); + try testing.expectEqual(@as(i32, 60), pane.body.cur_row); +} + +test "a view not live keeps its place in a text another view edits" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const text = try numbered(gpa, 200); + defer gpa.free(text); + const pane = try p.setTestFile(text); + const k = p.openView().?; + p.toView(k); + cursorTo(p, pane, 100); + const scrolled = pane.file.?.scroll; + p.toView(0); + // Three lines put above it, one taken below it. + typeKeys(p, "xyppp"); + cursorTo(p, pane, 150); + typeKeys(p, "xd"); + p.toView(k); + try testing.expectEqual(@as(i32, 103), pane.body.cur_row); + try testing.expectEqual(scrolled + 3, pane.file.?.scroll); + try testing.expect(std.mem.startsWith(u8, pardes.panes.File.sourceLine(pane, 103), "line 101")); +} -- cgit v1.3