diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-18 22:03:14 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-18 22:23:51 -0300 |
| commit | 99f5b10eccd95aa0066ea6fe6bb75f367ab56a47 (patch) | |
| tree | 813596ea84318a7bae4fd7416ba463de8e3b7107 /core/mouse.zig | |
| parent | 92d553123673376adf6126ab90d49a22c5b833d2 (diff) | |
| download | pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.tar.gz pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.zip | |
core: src/ becomes core/, pardes.zig its root.zig (the reorganisation's tree, step 2d), and every mention of a src/ path follows: the build's paths, the core's imports of its root, the tests that read the repository's files by path (lspbench's, look.zig's spans over core/look.zig), the comments that cite files, the documents and the manual (the typst corpus reads core/tutor.txt and core/plumbing); left as they were: the /src tree's served names (src/pardes.zig and the rest are the 9P tree's, not the repository's), the CHANGELOG's history, fixtures that are only strings; fs-unit-test runs from the core's root (a module of the core rooted at fs.zig had the runtime's and the devices' `core` be fs.zig); nothing else changes: the ledger (pardes.test.* now root.test.*), frames byte-identical, replicas and process-test the base's
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core/mouse.zig')
| -rw-r--r-- | core/mouse.zig | 1809 |
1 files changed, 1809 insertions, 0 deletions
diff --git a/core/mouse.zig b/core/mouse.zig new file mode 100644 index 00000000..073f09c3 --- /dev/null +++ b/core/mouse.zig @@ -0,0 +1,1809 @@ +//! The mouse: what a pointer is over, the three buttons' presses, drags and +//! releases (acme's chords, grip and seam drags, gestures). +const pardes = @import("root.zig"); +const tagline = @import("tagline.zig"); +const exec = @import("exec.zig"); +const look = @import("look.zig"); +const std = @import("std"); +const layout = @import("layout.zig"); +const modal = @import("modal.zig"); +const ctlfs = @import("ninep/tree.zig"); +const panes = @import("panes.zig"); +const edit = @import("edit.zig"); +const body_layer = @import("body_layer.zig"); +const builtins = @import("builtins.zig"); +const config = @import("config.zig"); +const platform = pardes.platform; +const Pane = panes.Pane; +const MAX_PANES = pardes.MAX_PANES; +const Layer = @import("Layer.zig"); +const Jump = @import("Jump.zig"); +const BOX_H = pardes.BOX_H; +const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; +const Builtin = pardes.Builtin; +const Mouse = pardes.Mouse; +const sel_slot = pardes.sel_slot; +const Pardes = pardes.Pardes; + +pub const Drag = union(enum) { + none, + border_h: struct { col: usize, top_idx: usize, cur_y: u16 }, + move: struct { id: usize, cur_x: u16, cur_y: u16 }, + /// `grab`: how far into the grip it was pressed, so the column's left + /// edge lands at `cur_x - grab`. A release still on the grip moves nothing. + column_move: struct { serial: u32, cur_x: u16, grab: u16 = 0 }, + /// chorded: a 1-2/1-3 cut/paste chord fired during this left drag — + /// the drag's own release is then inert + select: struct { + id: usize, + button: Mouse.Button, + chorded: bool = false, + ctrl: bool = false, + /// A B1 body sweep held past the pane's top (-1) or bottom (1): the + /// body scrolls a line a tick, as acme's frselect scrolls + /// (libframe frselect.c, the `scroll` callback while the button is + /// held outside the frame). + edge: i2 = 0, + /// Where the sweep began in the text, once it has scrolled: its + /// press row may be off the screen. + anchor: ?modal.Cursor = null, + /// Where its body was in the frontend's frame at its last hit there: + /// a sweep that leaves it is clamped back onto it (`bodyHitForPane`). + body: ?Layer.Place = null, + }, + + fn button(drag: Drag) ?Mouse.Button { + return switch (drag) { + .none => null, + .border_h, .move, .column_move => config.select_button, + .select => |selection| selection.button, + }; + } +}; + +/// A middle or right sweep over a column's tag or the workspace's, held as +/// a pane tag's is: painted in its button's tint while the button is down, +/// and run (or looked for) in that tag's context when it comes up. `anchor` +/// and `cur` are byte offsets into the header's text. +pub const HeaderSweep = struct { + /// The column's serial; null for the workspace's tag. + serial: ?u32, + button: Mouse.Button, + anchor: usize, + cur: usize, + + /// The column index the sweep is over, or null for the workspace's + /// tag; `error.Gone` once its column has been closed. + pub fn column(s: HeaderSweep, p: *const Pardes) error{Gone}!?usize { + const serial = s.serial orelse return null; + return layout.columnBySerial(p, serial) orelse error.Gone; + } + + /// The swept bytes, empty for a click that has not moved. + pub fn span(s: HeaderSweep, len: usize) struct { lo: usize, hi: usize } { + return .{ .lo = @min(s.anchor, s.cur, len), .hi = @min(@max(s.anchor, s.cur), len) }; + } +}; + +/// A header sweep's button came up: a click runs the word under it, or the +/// header's selection when it is on that; a sweep runs what it swept. +fn headerSweepRun(p: *Pardes, sweep: HeaderSweep) void { + const v = p.view(); + const column = sweep.column(p) catch return; // error.Gone: its column closed under the sweep + const t = if (column) |c| &v.col_tags[c] else &p.global_tag; + const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(v.active, "edit", err); + const swept = sweep.span(text.len); + const selected = if (swept.lo < swept.hi) text[swept.lo..swept.hi] else click: { + const line = std.mem.count(u8, text[0..swept.lo], "\n"); + const start = modal.lineStartOffset(text, line); + const bar = modal.lineSlice(text, line); + const at = swept.lo - start; + const focused = v.header != null and p.headerColumn() == column; + const on = if (focused) tagline.headerSelection(t, text, line) else null; + const under = if (tagline.wordBoundsAtCol(bar, at)) |b| bar[b.lo..b.hi] else ""; + break :click if (on) |sp| (if (at >= sp.lo and at < sp.hi) bar[sp.lo..sp.hi] else under) else under; + }; + const word = p.scratch.allocator().dupe(u8, selected) catch |err| return p.reportError(v.active, "edit", err); + tagline.exitHeader(p); + // A column tag's command acts on that column, empty or not. + p.exec_column = column; + defer p.exec_column = null; + p.exec_header = true; + defer p.exec_header = false; + if (word.len == 0) return; + if (sweep.button == config.exec_button) { + const named = std.meta.stringToEnum(Builtin, word); + const held = if (named) |b| (if (builtins.registry.takesArg(b)) exec.heldSelection(p, v.active) else null) else exec.heldSelection(p, v.active); + _ = exec.execute(p, v.active, exec.withArg(p, word, held)); + } else exec.runBuiltin(p, config.look_cmd, v.active, "", word); +} + +fn seamRowOf(p: *const Pardes, c: usize, k: usize) u16 { + const r = p.view().rects[p.view().cols[c].panes[k]]; + return r.y + r.h -| 1; +} + +pub fn paneAt(p: *const Pardes, col: u16, row: u16) ?usize { + for (p.panes, 0..) |slot, id| { + if (slot == null) continue; + const r = p.view().rects[id]; + if (col >= r.x and col < r.x + r.w and row >= r.y and row < r.y + r.h) return id; + } + return null; +} + +pub fn bodyHitForPane(p: *const Pardes, id: usize, supplied: Mouse.BodyHit, clamp: bool) ?Mouse.BodyHit { + const pane = p.panes[id] orelse return null; + if (pane.file == null or (!clamp and supplied.serial != pane.serial)) return null; + if (!std.math.isFinite(supplied.pixel_x) or !std.math.isFinite(supplied.pixel_y) or + supplied.metrics.body_w == 0 or supplied.metrics.body_h == 0 or + supplied.metrics.tagline_w == 0 or supplied.metrics.tagline_h == 0) return null; + var mapped_hit = supplied; + if (clamp) { + // Onto the body the sweep is in: the place of its last hit there + // (the drag's `body`), the hit's own while it is over it. + if (supplied.serial != pane.serial) mapped_hit.place = (if (p.view().drag == .select) p.view().drag.select.body else null) orelse return null; + mapped_hit.serial = pane.serial; + if (mapped_hit.place.rows == 0) return null; + const v = mapped_hit.place.viewport; + const bw: f32 = @floatFromInt(mapped_hit.metrics.body_w); + const bh: f32 = @floatFromInt(mapped_hit.metrics.body_h); + const x0 = @as(f32, @floatFromInt(v.x)) * bw; + const y0 = @as(f32, @floatFromInt(v.y)) * bh; + const x1 = x0 + @as(f32, @floatFromInt(v.w)) * bw; + const y1 = y0 + @as(f32, @floatFromInt(v.h)) * bh; + mapped_hit.pixel_x = std.math.clamp(mapped_hit.pixel_x, x0, @max(x0, x1 - 0.001)); + mapped_hit.pixel_y = std.math.clamp(mapped_hit.pixel_y, y0, @max(y0, y1 - 0.001)); + } + return Layer.bodyAgain(mapped_hit); +} + +pub fn sameBodyCell(a: ?Mouse.BodyHit, b: ?Mouse.BodyHit) bool { + const first = a orelse return b == null; + const second = b orelse return false; + return first.serial == second.serial and first.row == second.row and first.col == second.col; +} + +/// A wheel over a terminal whose program owns it (`Term.Modes.wheel`: +/// codex, htop, less) goes to the program as the program asked, one turn +/// per line, instead of scrolling a scrollback the alternate screen does +/// not have. Shift keeps it pardes's, as xterm's Shift does. False when +/// pardes scrolls. +fn programWheel(p: *Pardes, id: usize, m: Mouse, col: u16, row: u16) bool { + if (m.shift) return false; + const pane = p.panes[id] orelse return false; + if (!pane.isTerminal() or !panes.Term.modes(pane.terminal).wheel) return false; + const r = p.view().rects[id]; + const body_y = p.bodyTop(pane, r); + const gcol = std.math.clamp(col -| (r.x + config.GUTTER), 0, pane.cols -| 1); + const grow = std.math.clamp(row -| body_y, 0, pane.rows -| 1); + var buf: [64]u8 = undefined; + const wheel: panes.Term.MouseButton = switch (m.button) { + .wheel_up => .wheel_up, + .wheel_down => .wheel_down, + .wheel_left => .wheel_left, + else => .wheel_right, + }; + const bytes = panes.Term.wheel(pane.terminal.?, &buf, wheel, gcol, grow, .{ .alt = m.alt, .ctrl = m.ctrl }) orelse return true; + for (0..@intCast(config.wheel_rows)) |_| p.emitWrite(id, bytes); + return true; +} + +pub const Grab = struct { + id: usize, + serial: u32, + held: u3 = 0, + /// Taken by Shift-B2 or Shift-B3: the Shift chose the program, so its + /// reports leave it out. + unshift: bool = false, +}; + +/// The 0-based cell of a terminal program's grid under screen cell +/// `col`,`row`, or null over chrome (tag, gutter, scrollbar, anything past +/// the grid). +fn programCell(p: *const Pardes, id: usize, col: u16, row: u16) ?struct { col: i32, row: i32 } { + const pane = p.panes[id] orelse return null; + const r = p.view().rects[id]; + const x0 = r.x + config.GUTTER; + const y0 = p.bodyTop(pane, r); + const h = @min(r.h -| pane.tag_rows, pane.rows); + if (col < x0 or col >= r.x + r.w or col - x0 >= pane.cols or row < y0 or row - y0 >= h) return null; + return .{ .col = col - x0, .row = row - y0 }; +} + +/// A pane whose program tracks the mouse (1000, 1002, 1003, or X10's 9) +/// and has the keyboard's raw input: its clicks are the program's. +fn tracksMouse(pane: *const Pane) bool { + return pane.isTerminal() and pane.body.mode == .tty and panes.Term.modes(pane.terminal).mouse; +} + +/// A program that tracks the mouse gets it over its grid, as xterm gives +/// it: presses, releases, drags with a button down (1002) and, under 1003, +/// every move, once per cell. A press it took keeps its drag and release +/// wherever the pointer goes. Tags, gutters and the rest of pardes's +/// chrome are never its. B1 is the program's and Shift-B1 pardes's select; +/// B2 and B3 are pardes's execute and look, and Shift-B2 and Shift-B3 the +/// program's, reported without the Shift that chose it. True when the +/// event was the program's. +/// The pointer over the body of a pane whose kind takes the mouse: the +/// kind's, a press focusing the pane first, its drag and release the +/// kind's wherever they go (clamped to its body); a pointer leaving the +/// body is told as a motion at 0xffff. +fn kindMouse(p: *Pardes, m: Mouse) bool { + const v = p.view(); + if (v.drag != .none or v.header_drag or v.header_sweep != null) return false; + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const k = pane.addon orelse continue; + if (!pardes.Kind.takesMouse(p, k) or pane.collapsed) continue; + const r = v.rects[id]; + const top = p.bodyTop(pane, r) + pane.notices.span(); + const x0 = r.x + config.GUTTER; + const inside = m.col >= x0 and m.col < r.x + r.w and m.row >= top and m.row < r.y + r.h; + const grabbed = v.kind_grab != null and v.kind_grab.? == id and (m.kind == .drag or m.kind == .release); + if (!inside and !grabbed) continue; + if (v.kind_hover != null and v.kind_hover.? != id) kindLeave(p); + v.kind_hover = @intCast(id); + if (m.kind == .press) v.active = id; + if (m.kind == .press and m.button != .wheel_up and m.button != .wheel_down and m.button != .wheel_left and m.button != .wheel_right) v.kind_grab = @intCast(id); + if (m.kind == .release) v.kind_grab = null; + const col = std.math.clamp(m.col, x0, r.x + r.w -| 1) - x0; + const row = std.math.clamp(m.row, top, r.y + r.h -| 1) - top; + return pardes.Kind.mouse(p, id, m, col, row); + } + kindLeave(p); + return false; +} + +/// The pointer has left the kind's pane it was over: told so, once. +pub fn kindLeave(p: *Pardes) void { + const v = p.view(); + const id = v.kind_hover orelse return; + v.kind_hover = null; + _ = pardes.Kind.mouse(p, id, .{ .button = .none, .kind = .motion, .col = 0, .row = 0 }, 0xffff, 0xffff); +} + +fn programMouse(p: *Pardes, m: Mouse) bool { + const v = p.view(); + const button: ?panes.Term.MouseButton = switch (m.button) { + .left => .left, + .middle => .middle, + .right => .right, + .none => null, + else => return false, + }; + const bit: u3 = if (button) |b| @as(u3, 1) << @intCast(@backingInt(b)) else 0; + const at: struct { col: u16, row: u16 } = .{ .col = @min(m.col, v.screen_w -| 1), .row = @min(m.row, v.screen_h -| 1) }; + var mods: panes.Term.MouseMods = .{ .shift = m.shift, .alt = m.alt, .ctrl = m.ctrl }; + var buf: [64]u8 = undefined; + if (v.mouse_grab) |*grab| { + if (grab.unshift) mods.shift = false; + const pane = p.panes[grab.id] orelse { + v.mouse_grab = null; + return false; + }; + if (pane.serial != grab.serial or !pane.isTerminal()) { + v.mouse_grab = null; + return false; + } + // Off the grid the cell runs on past its edge, and the encoder + // clamps it there. + const r = v.rects[grab.id]; + const col: i32 = @as(i32, at.col) - @as(i32, r.x + config.GUTTER); + const row: i32 = @as(i32, at.row) - @as(i32, p.bodyTop(pane, r)); + const action: panes.Term.MouseAction = switch (m.kind) { + .press => .press, + .release => .release, + .drag, .motion => .motion, + }; + if (m.kind == .press) grab.held |= bit; + if (m.kind == .release) grab.held &= ~bit; + const bytes = panes.Term.mouse(pane.terminal.?, &buf, action, button, mods, col, row, grab.held != 0); + if (bytes.len > 0) p.emitWrite(grab.id, bytes); + if (grab.held == 0) v.mouse_grab = null; + return true; + } + if (v.drag != .none or v.header_drag or v.header_sweep != null) return false; + const shifted_to_program = m.button == .middle or m.button == .right; + if (m.shift != shifted_to_program) return false; + if (shifted_to_program) mods.shift = false; + const mapped = at; + const id = paneAt(p, mapped.col, mapped.row) orelse return false; + const pane = p.panes[id].?; + if (!tracksMouse(pane)) return false; + const cell = programCell(p, id, mapped.col, mapped.row) orelse return false; + switch (m.kind) { + .press => { + if (id != v.active) if (p.panes[v.active]) |previous| { + previous.focus = .body; + previous.closePrompt(); + }; + v.active = id; + pane.focus = .body; + pane.closePrompt(); + v.mouse_grab = .{ .id = id, .serial = pane.serial, .held = bit, .unshift = shifted_to_program }; + const bytes = panes.Term.mouse(pane.terminal.?, &buf, .press, button, mods, cell.col, cell.row, true); + if (bytes.len > 0) p.emitWrite(id, bytes); + return true; + }, + // A release or drag of a press pardes never passed on stays + // pardes's. + .release, .drag => return false, + .motion => { + const bytes = panes.Term.mouse(pane.terminal.?, &buf, .motion, null, mods, cell.col, cell.row, false); + if (bytes.len > 0) p.emitWrite(id, bytes); + // Under 1003 the move is the program's; below that pardes + // hovers as ever. + return panes.Term.modes(pane.terminal).all_motion; + }, + } +} + +/// plan9port's convention for a mouse or trackpad with one button: +/// Alt-click is B2 and Super-click (Cmd) is B3, sweeps included, decided at +/// the press and kept through its release, whatever keys are let go +/// meanwhile. Ctrl-click keeps its own meaning (a definition). Run after +/// programMouse: a program that takes the click gets it as it was. +fn emulateButton(p: *Pardes, m: *Mouse) void { + const v = p.view(); + if (m.button != .left) return; + if (m.kind == .press) v.click_as = if (m.ctrl) null else if (m.super) .right else if (m.alt) .middle else null; + const as = v.click_as orelse return; + m.button = as; + m.alt = false; + m.super = false; + if (m.kind == .release) v.click_as = null; +} + +/// What a pointer at (mcol, mrow) is over in a column's tag, or the +/// workspace's for null: the header's text, the line, and the byte offset +/// in that text. `clamp` holds a held sweep to the header's rows and text, +/// as a pane tag's sweep stays on its tag. +fn headerPoint(p: *Pardes, column: ?usize, mcol: u16, mrow: u16, clamp: bool) ?struct { t: *panes.Text, text: []const u8, line: u16, at: usize } { + const v = p.view(); + const t = if (column) |c| &v.col_tags[c] else &p.global_tag; + const x = if (column) |c| v.col_x[c] + TAG_TEXT_INSET else TAG_TEXT_INSET; + const focused = v.header != null and p.headerColumn() == column; + const text = edit.flatSurface(p.editor(), t) catch return null; + const base = if (column != null) p.topBarHeight() else 0; + const rows = if (column != null) layout.columnBarHeight(p) else p.topBarHeight(); + const row: u16 = if (clamp) @min(mrow -| base, rows -| 1) else mrow -| base; + const top: usize = if (focused) v.header_top else 0; + const lines = modal.lineCount(text); + const line: u16 = if (clamp) @intCast(@min(row + top, lines -| 1)) else @intCast(row + top); + if (line > 0 and line >= lines) return null; + const bar = modal.lineSlice(text, line); + const scroll = if (focused) v.header_scroll else 0; + const kind: Layer.Kind = if (column != null) .column else .workspace; + const at = @min(bar.len, panes.File.rawAtDisplay(bar, (Layer.columnAt(p, kind, column orelse 0, v.pointer_tag_hit, clamp, row) orelse (mcol -| x)) + scroll)); + return .{ .t = t, .text = text, .line = line, .at = modal.lineStartOffset(text, line) + at }; +} + +fn bodyPlace(hit: ?Mouse.BodyHit, pane: *const Pane) ?Layer.Place { + const h = hit orelse return null; + return if (h.serial == pane.serial) h.place else null; +} + +fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { + const s = &p.view().drag.select; + const pane = p.panes[s.id] orelse return; + if (@min(pane.sel[sel_slot].r0, pane.sel[sel_slot].r1) < pane.tag_rows) { + // A sweep over the tag cuts from and pastes into the tag's own text; + // the part of it over the prefix is not the tag's to cut, so the + // sweep starts after it. + const t = &pane.tag; + if (!s.chorded) { + s.chorded = true; + const sl = pane.sel[sel_slot]; + pane.sel[sel_slot].state = .none; + const forward = sl.r0 < sl.r1 or (sl.r0 == sl.r1 and sl.c0 <= sl.c1); + const start = if (forward) .{ sl.r0, sl.c0 } else .{ sl.r1, sl.c1 }; + const end = if (forward) .{ sl.r1, sl.c1 } else .{ sl.r0, sl.c0 }; + const lead = pane.tag_lead; + const origin: modal.Cursor = .{ .row = 0, .col = lead }; + var from = tagline.tagOffsetAt(p, pane, @intCast(@max(0, start[0])), @intCast(@max(0, start[1]))) orelse origin; + var to = tagline.tagOffsetAt(p, pane, @intCast(@max(0, end[0])), @intCast(@max(0, end[1]))) orelse origin; + if (from.row == 0) from.col = @max(from.col, lead); + if (to.row == 0) to.col = @max(to.col, lead); + t.cur_row = @intCast(to.row); + t.cur_col = @intCast(to.col); + t.cur_pinned = true; + t.vsel = .{ .active = from.row != to.row or from.col != to.col, .row = @intCast(from.row), .col = @intCast(from.col), .explicit = false }; + t.nsel = 0; + } + if (cut) { + if (t.vsel.active) try edit.normalDelete(p.editor(), t, true); + } else if (t.vsel.active) { + try edit.chordReplace(p.editor(), t); + } else try edit.pasteText(p.editor(), t, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); + return; + } + if (pane.body.mode == .tty) { + if (!s.chorded) { + s.chorded = true; + pane.sel[sel_slot].state = .none; // drop the sweep highlight + } + if (cut) return; + const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return; + if (y.len == 0) return; + if (panes.Term.modes(pane.terminal).mouse) { + // A click where the text goes, so the program's cursor is there. + const col = @max(0, pane.sel[sel_slot].c1); + const row = @max(0, pane.sel[sel_slot].r1 - @as(i32, pane.tag_rows)); + var mb: [64]u8 = undefined; + for ([_]panes.Term.MouseAction{ .press, .release }) |action| { + const bytes = panes.Term.mouse(pane.terminal.?, &mb, action, .left, .{}, col, row, action == .press); + if (bytes.len > 0) p.emitWrite(s.id, bytes); + } + } + edit.typeToTty(p, s.id, pane, y); + return; + } + if (!s.chorded) { + s.chorded = true; + // Everything done while B1 stays down is one undo step, as acme + // marks the file once per B1 hold (text.c:881 textselect, `state` + // and its one filemark): B1-B2 then B1-B3 is a copy. + try edit.pushUndo(p.editor(), &pane.body); + p.view().chord_hold = true; + const sl = pane.sel[sel_slot]; + pane.sel[sel_slot].state = .none; + const pfx: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; + // both ends of the sweep through the same last-frame map, so a + // chord over wrapped rows cuts the text that was under it + const w0 = pane.wrapAt(@max(0, sl.r0 - @as(i32, pane.tag_rows))); + const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, pane.tag_rows))); + const row0 = w0.line; + const row1 = w1.line; + const col0 = edit.paneByteAtDisplay(p.editor(), &pane.body, w0.line, w0.at, sl.c0 - pfx - w0.pad); + const col1 = edit.paneByteAtDisplay(p.editor(), &pane.body, w1.line, w1.at, sl.c1 - pfx - w1.pad); + pane.body.cur_row = row1; + pane.body.cur_col = col1; + pane.body.cur_pinned = true; + pane.body.normal.clear(); + if (!pane.isTerminal()) pane.body.mode = .normal; + pane.body.vsel = .{ .active = row0 != row1 or col0 != col1, .row = row0, .col = col0, .explicit = false }; + pane.body.nsel = 0; + } + if (cut) { + if (pane.body.vsel.active) try edit.normalDelete(p.editor(), &pane.body, true); + } else if (pane.body.vsel.active) { + try edit.chordReplace(p.editor(), &pane.body); + } else if (pane.file) |*f| { + // bare cursor: splice the register in literally (no linewise + // magic) so a paste right after a cut restores the text exactly + const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return; + if (y.len == 0) return; + const at = modal.Cursor{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)) }; + try edit.pushUndo(p.editor(), &pane.body); + const new = try modal.insertAt(p.gpa, f.content, at, y); + panes.File.setContent(p, f, new); + pane.body.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @intCast(at.row), .col = @intCast(at.col), .explicit = false }; + const end = modal.advanceBy(at, y); + if (end.col > 0) { + pane.body.cur_row = @intCast(end.row); + pane.body.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(f.content, end.row), end.col)); + } else { + // the register ended in '\n': the cursor lands ON that newline + pane.body.cur_row = @intCast(end.row -| 1); + pane.body.cur_col = @intCast(modal.lineSlice(f.content, end.row -| 1).len); + } + pane.body.cur_pinned = true; + pane.body.sticky_col = -1; + pane.ensureCursorVisible(); + } else try edit.pasteText(p.editor(), &pane.body, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); +} + +pub fn handleMouse(p: *Pardes, event: Mouse) void { + const v = p.view(); + var m = event; + // A click goes somewhere else: the question it leaves unanswered is + // taken back, and the pane stays. A wheel only looks around. + if (m.kind == .press) v.window_pick = null; + if (m.kind == .press and switch (m.button) { + .left, .middle, .right => true, + else => false, + }) for (p.panes) |slot| { + const pane = slot orelse continue; + if (pane.prompt == .del_side or pane.prompt == .repl_choice) pane.prompt = .none; + }; + if (m.button == .back or m.button == .forward) { + if (m.kind == .press) Jump.jumpBy(p, if (m.button == .back) -1 else 1); + return; + } + // A grip let go past the window's edge, as a browser's tab dragged out + // of its window: the pane or column goes to another window. Inside, the + // grip's drag is the layout move below, as it always was. + if (m.kind == .release and m.outside and m.button == config.select_button) switch (v.drag) { + .move => |d| { + v.drag = .none; + return p.handover.begin(p, .pane, d.id); + }, + .column_move => |d| { + v.drag = .none; + const column = layout.columnBySerial(p, d.serial) orelse return; + return p.handover.begin(p, .column, column); + }, + else => {}, + }; + const raw_col = @min(m.col, v.screen_w -| 1); + const raw_row = @min(m.row, v.screen_h -| 1); + v.pointer_raw_col = raw_col; + v.pointer_raw_row = raw_row; + const previous_hit = v.pointer_body_hit; + v.pointer_body_hit = m.body_hit; + const previous_tag_hit = v.pointer_tag_hit; + v.pointer_tag_hit = if (m.tag_hit) |point| layout.reprojectTagHit(p, point) else null; + if (m.tag_hit != null and v.pointer_tag_hit == null and m.kind == .press) return; + if (m.tag_hit == null and (m.kind == .drag or m.kind == .release) and (v.drag == .select or v.header_drag or v.header_sweep != null)) { + if (previous_tag_hit) |previous| { + var continued = previous; + continued.pixel_x = (@as(f32, @floatFromInt(raw_col)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_w)); + continued.pixel_y = (@as(f32, @floatFromInt(raw_row)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_h)); + v.pointer_tag_hit = continued; + } + } + if ((m.kind == .drag or m.kind == .release) and (v.drag == .select or v.header_drag or v.header_sweep != null)) { + if (previous_tag_hit) |previous| if (v.pointer_tag_hit) |*current| { + current.kind = previous.kind; + current.id = previous.id; + current.serial = previous.serial; + // ...and its place, which a clamp brings the pointer back onto. + current.place = previous.place; + }; + } + // A drag can leave the compact text viewport. Preserve its metrics so + // the endpoint still clamps to that body's last visible logical row. + if (m.body_hit == null and (m.kind == .drag or m.kind == .release) and v.drag == .select) { + if (previous_hit) |previous| { + var continued = previous; + continued.pixel_x = (@as(f32, @floatFromInt(raw_col)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_w)); + continued.pixel_y = (@as(f32, @floatFromInt(raw_row)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_h)); + v.pointer_body_hit = continued; + } + } + v.pointer_inside = true; + if (kindMouse(p, m)) return; + if (programMouse(p, m)) return; + emulateButton(p, &m); + if (m.button == .none and m.kind == .motion) { + v.raw_hover_intent = true; + look.refreshLookHoverFromRaw(p); + return; + } + v.raw_hover_intent = false; + const mapped: struct { col: u16, row: u16 } = .{ .col = raw_col, .row = raw_row }; + const mcol = mapped.col; + const mrow = mapped.row; + v.hover_col = mcol; + v.hover_row = mrow; + + const hovered = paneAt(p, mcol, mrow); + + // any press that is NOT the execute+select chord abandons a pending + // chord argument + if (m.kind == .press and + !(m.button == config.select_button and v.drag == .select and v.drag.select.button == config.exec_button)) + { + if (v.chord_arg) |a| { + p.gpa.free(a); + v.chord_arg = null; + } + } + if (v.header_sweep) |*sweep| { + if (m.kind == .press and switch (m.button) { + .left, .middle, .right => true, + else => false, + }) { + // acme 2-3 / 3-2: the other of execute and look cancels the + // sweep. The select button is inert: a header's command already + // takes the held selection as its argument, which is what a 2-1 + // chord would give it. + if (m.button != config.select_button) v.header_sweep = null; + return; + } + if (m.button == sweep.button and (m.kind == .drag or m.kind == .release)) { + const column = sweep.column(p) catch { + v.header_sweep = null; + return; + }; + if (headerPoint(p, column, mcol, mrow, true)) |point| sweep.cur = point.at; + if (m.kind == .release) { + const done = sweep.*; + v.header_sweep = null; + headerSweepRun(p, done); + } + return; + } + } + if (mrow >= p.topBarHeight() and mrow < p.topBarHeight() + layout.columnBarHeight(p) and m.kind == .press) { + for (0..p.view().ncol) |column| { + if (mcol < v.col_x[column] or mcol >= v.col_x[column] + @min(config.GUTTER, v.col_w[column])) continue; + if (m.button == config.select_button) { + v.header_drag = false; + v.drag = .{ .column_move = .{ .serial = v.cols[column].serial, .cur_x = mcol, .grab = mcol - v.col_x[column] } }; + } + return; + } + } + if (v.header_drag and m.button == config.select_button and (m.kind == .drag or m.kind == .release)) { + if (tagline.focusedHeader(p) == null) { + v.header_drag = false; + return; + } + // Held to the focused header's rows and text; the anchor stays + // where the press put it. + const point = headerPoint(p, p.headerColumn(), mcol, mrow, true) orelse return; + const t = point.t; + t.cur_row = point.line; + t.cur_col = @intCast(point.at - modal.lineStartOffset(point.text, point.line)); + t.vsel.active = t.vsel.row != t.cur_row or t.vsel.col != t.cur_col; + if (m.kind == .release) v.header_drag = false; + return; + } + if (mrow < p.topBarHeight() + layout.columnBarHeight(p) and m.kind == .press and + (m.button == config.select_button or m.button == config.exec_button or m.button == config.look_button)) + { + if (m.button == config.select_button) if (p.panes[v.active]) |pane| { + pane.focus = .body; + pane.closePrompt(); + }; + var column: ?usize = null; + var x: u16 = TAG_TEXT_INSET; + if (mcol < x) return; + if (mrow >= p.topBarHeight()) { + for (0..p.view().ncol) |c| if (mcol >= v.col_x[c] and mcol < v.col_x[c] + v.col_w[c]) { + column = c; + x = v.col_x[c] + TAG_TEXT_INSET; + if (layout.findPane(p, v.active)) |active_col| { + if (active_col.col != c and v.cols[c].n > 0) v.active = v.cols[c].panes[0]; + } + break; + }; + if (column == null or mcol < x) return; + } + const point = headerPoint(p, column, mcol, mrow, false) orelse return; + if (m.button == config.select_button) { + const t = point.t; + const at = point.at - modal.lineStartOffset(point.text, point.line); + // A clicked header starts in normal mode, as a clicked tag does. + if (!(v.header != null and p.headerColumn() == column)) tagline.enterHeader(p, column); + t.mode = .normal; + t.cur_row = point.line; + t.cur_col = @intCast(at); + t.vsel = .{ .active = false, .row = point.line, .col = @intCast(at) }; + v.header_drag = true; + } else { + // Held, as a pane tag's sweep is: it runs when the button + // comes up (headerSweepRun). + v.header_sweep = .{ + .serial = if (column) |c| v.cols[c].serial else null, + .button = m.button, + .anchor = point.at, + .cur = point.at, + }; + } + return; + } + if (m.kind == .press) { + tagline.exitHeader(p); + } + + switch (m.button) { + .none, .back, .forward => {}, // hover and navigation handled above + .wheel_up, .wheel_down => { + if (m.kind != .press) return; + // re-arms the drift guard below; vertical always scrolls, so + // the answer is never in doubt here + _ = config.wheelTick(&v.wheel_guard, true); + const id = hovered orelse return; + const pane = p.panes[id].?; + if (!programWheel(p, id, m, mcol, mrow)) + pane.scrollBy(if (m.button == .wheel_up) -config.wheel_rows else config.wheel_rows); + }, + .wheel_left, .wheel_right => { + if (m.kind != .press) return; + if (!config.wheelTick(&v.wheel_guard, false)) return; + const id = hovered orelse return; + const pane = p.panes[id].?; + if (programWheel(p, id, m, mcol, mrow)) { + // the program's + } else if (pane.file != null and !p.settings.wrap) { + // wrapped there is nothing off to the right to reach + const line = panes.File.sourceLine(pane, pane.body.cur_row); + const visual = panes.File.rawDisplayCol(line, @intCast(@max(0, pane.hscroll))); + const next: usize = if (m.button == .wheel_right) + visual +| @as(usize, @intCast(config.wheel_cols)) + else + visual -| @as(usize, @intCast(config.wheel_cols)); + pane.hscroll = @intCast(panes.File.rawAtDisplay(line, next)); + } + }, + config.select_button => switch (m.kind) { + .press => { + if (v.drag == .select and v.drag.select.button == config.exec_button) { + if (exec.heldSelection(p, v.drag.select.id)) |tx| { + if (v.chord_arg) |old| p.gpa.free(old); + v.chord_arg = p.gpa.dupe(u8, tx) catch null; + } + return; + } + // acme 3-1: a select tap during a LOOK drag cancels the + // look; the rest of the gesture is inert + if (v.drag == .select and v.drag.select.button == config.look_button) { + if (p.panes[v.drag.select.id]) |t| { + t.sel[@backingInt(config.look_button)].state = .none; + } + v.drag = .none; + return; + } + if (hovered) |mid| { + const mr = v.rects[mid]; + const mpane = p.panes[mid].?; + const mtag = p.tagTop(mpane, mr); + if (mcol < mr.x + config.GUTTER and mrow >= mtag and mrow < mtag + mpane.tag_rows) { + v.drag = .{ .move = .{ .id = mid, .cur_x = mcol, .cur_y = mrow } }; + return; + } + } + // Two panes are resized on the rule between them, never on a + // row of text; with no rule, by the grip, as acme moves a + // window by its button. + if (m.rule_above and mrow > 0) for (0..p.view().ncol) |cc| { + if (mcol < v.col_x[cc] or mcol >= v.col_x[cc] + v.col_w[cc]) continue; + const seam = mrow - 1; + if (seamIdxAt(p, cc, seam)) |k| { + v.drag = .{ .border_h = .{ .col = cc, .top_idx = k, .cur_y = seam } }; + return; + } + }; + const id = hovered orelse return; + const r = v.rects[id]; + const pane = p.panes[id] orelse return; + if (id != v.active) if (p.panes[v.active]) |previous| { + previous.focus = .body; + previous.closePrompt(); + }; + const tag_y = p.tagTop(pane, r); + const body_y = p.bodyTop(pane, r); + if (mcol < r.x + config.GUTTER) { + v.active = id; + // A tick of the pane's places: that place, selected and in view. + // The rail is chrome, and only the tick's cell does this. + const rail_h = r.h -| pane.tag_rows; + if (mrow >= body_y and mrow < body_y + rail_h) if (pane.places.tickHit(p, pane, mrow - body_y, rail_h)) |i| { + pane.focus = .body; + return pane.places.goTo(pane, i, false); + }; + // gutter scrollbar: a left click scrolls UP to that row + pane.scrollBy(-(@as(i32, mrow) - @as(i32, body_y))); + } else { + const on_tag = mrow >= tag_y and mrow < tag_y + pane.tag_rows; + if (on_tag and mcol < r.x + TAG_TEXT_INSET) return; + v.active = id; + layout.noteTyped(p); // acme's button 1 sets activecol (acme.c:659) + pane.closePrompt(); + const pointed = edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, v.pointer_tag_hit) orelse return; + pane.clearPointerSelection(sel_slot); + pane.sel[sel_slot] = pointed.sel; + // A clicked tag starts in normal mode, its cursor where it + // was clicked: `i` or `a` types there. + pane.focus = if (on_tag) .tag else .body; + if (on_tag) { + // a count typed before the click was meant for the body + pane.body.normal.clear(); + pane.tag.mode = .normal; + pane.tag.normal.clear(); + pane.tag.vsel.active = false; + pane.tag.nsel = 0; + pane.tag.cur_pinned = true; + const at = tagline.tagOffsetAt(p, pane, @intCast(@max(0, pointed.sel.r0)), @intCast(@max(0, pointed.sel.c0))) orelse modal.Cursor{ .row = 0, .col = 0 }; + pane.tag.cur_row = @intCast(at.row); + pane.tag.cur_col = @intCast(at.col); + } + v.drag = .{ .select = .{ + .id = id, + .button = config.select_button, + .ctrl = m.ctrl, + .body = bodyPlace(m.body_hit, pane), + } }; + } + }, + .drag => dragUpdate(p, mcol, mrow, v.pointer_body_hit), + .release => { + if ((v.pointer_body_hit != null or v.pointer_tag_hit != null or v.drag == .column_move) and v.drag.button() == m.button) dragUpdate(p, mcol, mrow, v.pointer_body_hit); + dragRelease(p, config.select_button); + }, + .motion => {}, + }, + config.exec_button, config.look_button => switch (m.kind) { + .press => { + // acme 1-2 / 1-3: the execute (Cut) or look (Paste) button + // tapped while the select button holds a selection drag + if (v.drag == .select and v.drag.select.button == config.select_button) { + chordCutPaste(p, m.button == config.exec_button) catch |err| p.reportError(v.active, "edit", err); + return; + } + // acme 2-3 / 3-2: tapping the OTHER of execute/look during + // an execute or look drag cancels it (textselect23's mask) + if (v.drag == .select) { + if (p.panes[v.drag.select.id]) |t| { + t.sel[@backingInt(v.drag.select.button)].state = .none; + } + v.drag = .none; + return; + } + const id = hovered orelse return; + const r = v.rects[id]; + const pane = p.panes[id] orelse return; + // the tag row and the body's first, exactly as the select + // arm above derives them + const tag_y = p.tagTop(pane, r); + const body_y = p.bodyTop(pane, r); + const on_tag = mrow >= tag_y and mrow < tag_y + pane.tag_rows; + if (mcol < r.x + config.GUTTER and !on_tag) { + const local = @as(i32, mrow) - @as(i32, body_y); + if (m.button == config.look_button) v.active = id; + pane.scrollBy(if (m.button == config.look_button) local else -local); + } else if (edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, v.pointer_tag_hit)) |pointed| { + if (m.button == config.look_button) v.active = id; + pane.clearPointerSelection(@backingInt(m.button)); + pane.sel[@backingInt(m.button)] = pointed.sel; + v.drag = .{ + .select = .{ + .id = id, + .button = m.button, + .body = bodyPlace(m.body_hit, pane), + }, + }; + } + }, + .drag => dragUpdate(p, mcol, mrow, v.pointer_body_hit), + .release => { + if ((v.pointer_body_hit != null or v.pointer_tag_hit != null or v.drag == .column_move) and v.drag.button() == m.button) dragUpdate(p, mcol, mrow, v.pointer_body_hit); + dragRelease(p, m.button); + }, + .motion => {}, + }, + } +} + +/// Index of the pane pair in column `c` whose seam (see seamRowOf) is screen +/// row `mrow`. Out-of-range columns simply have no seam. +fn seamIdxAt(p: *const Pardes, c: usize, mrow: u16) ?usize { + if (c >= p.view().ncol) return null; + for (0..p.view().cols[c].n -| 1) |k| if (mrow == seamRowOf(p, c, k)) return k; + return null; +} + +fn clampBorderRow(ay: u16, ah: u16, bh: u16, mrow: u16) u16 { + const lo = ay + BOX_H - 1; + const hi = ay +| ah +| bh -| (BOX_H + 1); + return if (lo <= hi) std.math.clamp(mrow, lo, hi) else mrow; +} + +pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) void { + const v = p.view(); + switch (v.drag) { + .border_h => |*d| { + const cc = d.col; + const k = d.top_idx; + if (k + 1 < v.cols[cc].n) { + const a = v.rects[v.cols[cc].panes[k]]; + const b = v.rects[v.cols[cc].panes[k + 1]]; + // Held by the rule over the lower pane: the seam is the row above. + d.cur_y = clampBorderRow(a.y, a.h, b.h, mrow -| 1); + } else d.cur_y = mrow; + }, + .column_move => |*d| d.cur_x = mcol, + .move => |*d| { + d.cur_x = mcol; + d.cur_y = mrow; + }, + .select => |*s| { + if (p.panes[s.id]) |pane| { + const r = v.rects[s.id]; + const b = @backingInt(s.button); + const tag_rows: i32 = pane.tag_rows; + panes.File.geometry(pane); + if (pane.body_rows > 0 and pane.sel[b].r0 >= tag_rows) if (body_hit) |supplied| { + if (supplied.serial == pane.serial) s.body = supplied.place; + const mapped_hit = bodyHitForPane(p, s.id, supplied, true) orelse return; + pane.sel[b].c1 = @as(i32, mapped_hit.col) - config.GUTTER; + pane.sel[b].r1 = @as(i32, mapped_hit.row) + tag_rows; + return; + }; + // A sweep that began on the tag stays on it, on the tag line + // nearest the pointer. + const tag_y = p.tagTop(pane, r); + const tag_line: u16 = @intCast(std.math.clamp(@as(i32, mrow) - @as(i32, tag_y), 0, tag_rows - 1)); + if (pane.sel[b].r0 < tag_rows) if (Layer.columnAt(p, .pane, s.id, v.pointer_tag_hit, true, tag_line)) |value| { + pane.sel[b].c1 = @as(i32, value) + pane.tag_scroll; + pane.sel[b].r1 = tag_line; + return; + }; + pane.sel[b].c1 = @as(i32, mcol) - @as(i32, r.x + config.GUTTER); + // Sel row tag_rows is the body's FIRST row, the same thing + // pointerTextSelection means by it -- so the drag has to + // measure from the body's top, notice bands included, or a + // selection made while a message is up lands rows away + // from the pointer. + const body_y = p.bodyTop(pane, r); + const body_h = r.h -| pane.tag_rows; + s.edge = if (s.button != config.select_button or pane.sel[b].r0 < tag_rows or pane.file == null or body_h == 0) + 0 + else if (mrow < body_y) + -1 + else if (mrow >= body_y + body_h or + // The pointer cannot leave the screen: at a bottom pane, + // its last row is the edge. + (body_y + body_h >= v.screen_h and mrow + 1 >= body_y + body_h)) + 1 + else + 0; + pane.sel[b].r1 = if (pane.sel[b].r0 < tag_rows) + tag_line + else if (body_h == 0) + 0 + else + @as(i32, @min(@max(mrow, body_y), body_y + body_h - 1)) - @as(i32, body_y) + tag_rows; + if (pane.sel[b].r1 < tag_rows) pane.sel[b].c1 += @as(i32, pane.tag_scroll); + } + }, + .none => {}, + } +} + +/// Whether a script reads pane `id`'s events, and so takes its looks and +/// execs: the 9P server's, the authority's alone (a replica has its +/// answer, `tape.authority`). +fn readsEvents(p: *Pardes, id: usize) bool { + const pane = p.panes[id] orelse return false; + return pane.fs.readers != 0; +} + +/// An event reader told of a look or an exec of `text` at `range` of the +/// tag or body, by a click or a key alike: false when the pane has none. +pub fn reportRange( + p: *Pardes, + id: usize, + cmd: Builtin, + text: []const u8, + on_tag: bool, + range: ctlfs.pane.State.Range, + chord_arg: ?[]const u8, +) bool { + const scripted = p.panes[id] orelse return false; + if (!pardes.tape.authority(readsEvents, .{ p, id })) return false; + const is_look = cmd == config.look_cmd; + const action: ctlfs.events.Action = if (is_look) + (if (on_tag) .tag_look else .body_look) + else + (if (on_tag) .tag_exec else .body_exec); + const named = exec.namesBuiltin(text); + // No flag 2: the record already carries the word a click took, its + // range and text, and in acme flag 2 promises a second record with them + // (editors/acme/exec.c:154-183, look.c:42-68), which none follows here. + var flag: u32 = if (named) ctlfs.events.flag_builtin else 0; + if (is_look) { + if (!named and std.mem.indexOfAny(u8, text, "/.:") != null) flag |= ctlfs.events.flag_filename; + } else if (chord_arg != null) flag |= ctlfs.events.flag_chorded; + // Taken whether or not this process's server has the reader: the + // session's said it has (a replica's has none). + ctlfs.events.noteAction(p, id, action, range.q0, range.q1, flag, text); + // A chorded exec's argument follows as two records, its text and where + // it came from (`file:#q0,#q1`, empty when that is not known), as acme + // sends them (exec.c:182-188); the pane keeps it for the write-back. + if (chord_arg) |a| { + ctlfs.events.noteAction(p, id, action, 0, 0, 0, a); + var where: [512]u8 = undefined; + ctlfs.events.noteAction(p, id, action, 0, 0, 0, exec.heldSelectionPlace(p, id, &where) orelse ""); + const pf = &scripted.fs; + if (pf.chord_arg) |old| p.gpa.free(old); + pf.chord_arg = p.gpa.dupe(u8, a) catch null; + pf.chord_at = range; + } + return true; +} + +fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: exec.PointerOperand) ctlfs.pane.State.Range { + const pane = p.panes[id] orelse return .{}; + if (on_tag) { + const tag = tagline.tagText(p, p.scratch.allocator(), pane) catch return .{}; + const shown = tagline.shownTag(p, p.scratch.allocator(), pane) catch return .{}; + const sel = operand.expanded orelse operand.preview orelse return .{}; + const lead = if (sel.r0 < sel.r1 or (sel.r0 == sel.r1 and sel.c0 <= sel.c1)) sel else Pane.Sel{ .r0 = sel.r1, .c0 = sel.c1 }; + const row: usize = @as(usize, @intCast(@max(0, lead.r0))) + pane.tag_top; + const start = modal.lineStartOffset(shown.text, row); + const at = shown.toReal(start + panes.File.rawAtDisplay(modal.lineSlice(shown.text, row), @intCast(@max(0, lead.c0)))); + const q0: u32 = @intCast(@min(at, tag.len)); + return .{ .q0 = q0, .q1 = @intCast(@min(q0 + text.len, tag.len)) }; + } + const f = if (pane.file) |*file| file else return .{}; + if (operand.preview) |selection| if (pane.pointerSelection(selection)) |rows| { + if (rows.len == 0) return .{}; + const first = rows[0]; + const last = rows[rows.len - 1]; + const q0 = panes.File.lineStart(p.gpa, f, @intCast(@max(0, first.row))) + + @min(first.lo, panes.File.sourceLine(pane, first.row).len); + const q1 = panes.File.lineStart(p.gpa, f, @intCast(@max(0, last.row))) + + @min(last.hi, panes.File.sourceLine(pane, last.row).len); + // A rectangle may contain disjoint pieces. Such an operand uses + // the event's expansion text instead of inventing a source range. + if (q1 < q0 or !std.mem.eql(u8, f.content[q0..q1], text)) return .{}; + return .{ .q0 = @intCast(q0), .q1 = @intCast(q1) }; + }; + const start: ?modal.Cursor = if (operand.file_word) |w| + .{ .row = @intCast(@max(0, w.row)), .col = @intCast(@max(0, w.lo)) } + else if (operand.expanded orelse operand.preview) |sel| lead: { + // A selection's start in reading order, converted the way + // `operandAt` converts the click itself. + const lead = edit.sweepEnds(sel)[0]; + const top = lead[0] - @as(i32, pane.tag_rows); + if (top < 0) break :lead null; + const w = pane.wrapAt(top); + const col = edit.paneByteAtDisplay(p.editor(), &pane.body, w.line, w.at, lead[1] - panes.File.gutterWidth(pane) - w.pad); + break :lead .{ + .row = @intCast(@max(0, w.line)), + .col = @intCast(@max(0, col)), + }; + } else null; + const cursor = start orelse return .{}; + const q0: u32 = @intCast(@min(modal.offsetAt(f.content, cursor), f.content.len)); + return .{ .q0 = q0, .q1 = @intCast(@min(q0 + text.len, f.content.len)) }; +} + +/// A look or exec of what an operand took (exec.operandAt), from a +/// click or a key: an event reader is told, else it runs. +pub fn dispatchPointerBuiltin( + p: *Pardes, + id: usize, + cmd: Builtin, + text: ?[]const u8, + gesture: ?struct { on_tag: bool, operand: exec.PointerOperand }, +) void { + const arg = p.view().chord_arg; + p.view().chord_arg = null; + defer if (arg) |a| p.gpa.free(a); + // A click that takes no text does nothing, and tells an event reader + // nothing, as acme's look3 and execute return on an empty expansion. + const operand = text orelse return; + if (gesture) |g| if (reportRange(p, id, cmd, operand, g.on_tag, gestureRange(p, id, operand, g.on_tag, g.operand), arg)) return; + // B2 anywhere on a query pane's line 1 is the line: run again, whatever + // word of it was clicked (Query.zig). + if (gesture) |g| if (!g.on_tag and g.operand.row == 0 and cmd == config.exec_cmd) if (p.panes[id]) |pane| if (pane.query) |q| { + p.gpa.free(q.asked); + q.asked = &.{}; + q.frozen = false; + panes.Query.produceAll(p, false, false); + return; + }; + // A middle click on a body is the exec a bound REPL may take. + exec.runBuiltinFrom(p, cmd, id, "", exec.withArg(p, operand, arg), gesture != null and !gesture.?.on_tag); +} + +fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { + const gesture = pane.sel[sel_slot]; + const rows = pane.pointerSelection(gesture) orelse return; + const text = pane.rawPointerText(gesture) orelse return; + if (rows.len == 0) return; + const forward = gesture.r1 > gesture.r0 or (gesture.r1 == gesture.r0 and gesture.c1 >= gesture.c0); + const endpoint = rows[if (forward) rows.len - 1 else 0]; + const body = body_layer.bodyText(p.scratch.allocator(), pane) catch |err| return p.reportError(p.view().active, "select", err); + const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - @as(i32, @intCast(panes.Term.grid(pane.terminal).offset))))); + const byte = if (forward) modal.prevGrapheme(line, @min(endpoint.hi, line.len)) else endpoint.lo; + pane.body.cur_row = pane.surfRow(endpoint.row); + var shown = std.mem.trimEnd(u8, line[@min(endpoint.prompt_bytes, line.len)..], " \t"); + if (pane.ovl) |overlay| { + const relative = pane.body.cur_row - overlay.row; + if (relative >= 0 and relative < modal.lineCount(overlay.text)) + shown = modal.lineSlice(overlay.text, @intCast(relative)); + } + pane.body.cur_col = @intCast(modal.graphemeStart(shown, @min(shown.len, byte -| endpoint.prompt_bytes))); + pane.body.cur_pinned = true; + pane.body.vsel.active = false; + pane.body.nsel = 0; + pane.body.select = false; + pane.body.restore_cursor = false; + pane.body.sticky_col = -1; + pane.body.normal.clear(); + edit.setYank(p.editor(), text) catch |err| p.reportError(p.view().active, "yank", err); +} + +/// acme's double-click (text.c:881 textselect, plan9port text.c:1407 +/// textdoubleclick): a second plain B1 click at the same cell within half a +/// second selects what edit.doubleClickRange says, from the caret the click +/// left. A plain click still puts the caret on its cell. +fn doubleClick(p: *Pardes, id: usize, t: *panes.Text, on_tag: bool, row: i32, col: i32) void { + const v = p.view(); + // The host's clock, which every host keeps and a test's virtual one + // replaces. + const now: i64 = @intCast(p.clock.now_ns / std.time.ns_per_ms); + const prev = v.last_click; + v.last_click = .{ .id = id, .on_tag = on_tag, .row = row, .col = col, .ms = now }; + const c = prev orelse return; + if (c.id != id or c.on_tag != on_tag or c.row != row or c.col != col or now - c.ms > 500) return; + v.last_click = null; + const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(v.active, "edit", err); + const q = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); + const r = edit.doubleClickRange(text, q); + if (r[1] <= r[0]) return; + const a = modal.positionAt(text, r[0]); + const h = modal.positionAt(text, modal.prevGrapheme(text, r[1])); + t.vsel = .{ .active = true, .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; + t.cur_row = @intCast(h.row); + t.cur_col = @intCast(h.col); + t.cur_pinned = true; +} + +/// On each tick while a B1 body sweep is held past an edge: the body +/// scrolls a line toward it, the sweep's end stays under the pointer and +/// its start stays on its text (Drag.select.anchor). +pub fn edgeScroll(p: *Pardes) void { + if (p.view().drag != .select) return; + const s = &p.view().drag.select; + if (s.edge == 0) return; + const pane = p.panes[s.id] orelse return; + const sl = &pane.sel[sel_slot]; + if (s.anchor == null) s.anchor = sweepPoint(p, pane, sl.r0, sl.c0) orelse return; + const before = pane.scroll(); + pane.scrollBy(s.edge); + // The start's row follows its text while it is on the screen, and + // stays on the body's edge row once it is off (the anchor keeps it). + const top: i32 = pane.tag_rows; + sl.r0 = std.math.clamp(sl.r0 - (pane.scroll() - before), top, top + @as(i32, pane.rows) - 1); +} + +/// The text position under a body cell of the sweep's space. +fn sweepPoint(p: *Pardes, pane: *panes.Pane, r: i32, c: i32) ?modal.Cursor { + const visible = r - @as(i32, pane.tag_rows); + if (visible < 0) return null; + const w = pane.wrapAt(visible); + if (w.line < 0) return null; + const col = edit.paneByteAtDisplay(p.editor(), &pane.body, w.line, w.at, c - w.pad - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0)); + return .{ .row = @intCast(w.line), .col = @intCast(@max(0, col)) }; +} + +fn dragRelease(p: *Pardes, button: Mouse.Button) void { + const v = p.view(); + // A different button's release belongs to a chord or another host + // stream; only the button which began this gesture may end it. + if (v.drag.button() != button) return; + defer v.drag = .none; + defer v.chord_hold = false; + switch (v.drag) { + .border_h => |d| if (d.cur_y != seamRowOf(p, d.col, d.top_idx)) + layout.applyRowSplit(p, d.col, d.top_idx, d.cur_y), + .column_move => |d| if (layout.columnBySerial(p, d.serial)) |column| switch (layout.columnDrop(p, column, d.cur_x, d.grab)) { + .stay => {}, + .reorder => |target| { + layout.reorderColumn(p, column, target); + p.setActiveColumn(target); // a grip drag sets activecol (acme.c:640) + }, + .edge => |x| layout.setColumnPairWidth(p, column - 1, x - v.col_x[column - 1]), + }, + .move => |d| { + layout.movePane(p, d.id, d.cur_x, d.cur_y); + if (layout.findPane(p, d.id)) |f| p.setActiveColumn(f.col); + }, + .select => |s| { + const pane = p.panes[s.id] orelse return; + if (s.chorded) { + // a cut/paste chord consumed this drag; the release is inert + pane.sel[@backingInt(s.button)].state = .none; + return; + } + const b = @backingInt(s.button); + pane.sel[b].state = .done; + if (s.button == config.select_button) { + const sl = pane.sel[sel_slot]; + const dragged = sl.c0 != sl.c1 or sl.r0 != sl.r1; + if (!dragged) pane.sel[sel_slot].state = .none; + if (sl.r0 < pane.tag_rows) { + // On the tag the caret goes where the button came up. A + // click on the path, if it can be renamed, drafts a name. + const row: usize = @intCast(@max(0, sl.r1)); + const col: usize = @intCast(@max(0, sl.c1)); + if (!dragged and tagline.onName(pane, row, col)) { + tagline.draftName(p, pane, col); + } else if (tagline.tagOffsetAt(p, pane, row, col)) |cursor| { + pane.tag.cur_row = @intCast(cursor.row); + pane.tag.cur_col = @intCast(cursor.col); + if (!dragged) doubleClick(p, s.id, &pane.tag, true, sl.r1, sl.c1); + } + return; + } + if (dragged and s.anchor == null) edit.capturePointerSelection(p, pane, sel_slot) catch |err| p.reportError(s.id, "select", err); + if (dragged and pane.body.mode == .tty) mirrorTtySelection(p, pane); + const body_vis = sl.r1 - @as(i32, pane.tag_rows); + if (body_vis >= 0 and pane.body.mode != .tty) { + const w = pane.wrapAt(body_vis); + pane.body.cur_row = w.line; + pane.body.cur_col = edit.paneByteAtDisplay( + p.editor(), + &pane.body, + w.line, + w.at, + sl.c1 - w.pad - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), + ); + pane.body.cur_pinned = true; + if (edit.clampFileCursor(&pane.body)) pane.ensureCursorVisible(); + pane.body.normal.clear(); + pane.body.vsel.active = false; + pane.body.nsel = 0; // a click says WHERE the one cursor is + pane.body.select = false; + pane.body.restore_cursor = false; + pane.body.sticky_col = -1; + // A ctrl-click is a definition jump, not half a double-click. + if (!dragged and !s.ctrl) doubleClick(p, s.id, &pane.body, false, sl.r1, sl.c1); + if (s.ctrl) v.last_click = null; + // A sweep that scrolled has its start off the screen: it + // is kept as the text's own selection, start to end. + if (dragged) if (s.anchor) |a| { + pane.sel[sel_slot].state = .none; + pane.body.vsel = .{ .active = true, .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; + }; + if (s.ctrl) exec.runBuiltin(p, .Def, s.id, "", null); + } + } else { + const clk = pane.sel[b]; + // A right-click on a line NUMBER looks at that line of + // this file -- a sticky context header's number included, + // since the row map holds each header's own source line. + if (s.button == config.look_button and clk.r0 >= pane.tag_rows and clk.r0 == clk.r1 and + clk.c0 == clk.c1 and clk.c0 >= 0 and pane.body.mode != .tty) + if (pane.file) |f| if (f.output == null and clk.c0 < panes.File.gutterWidth(pane)) { + const line = pane.wrapAt(clk.r0 - pane.tag_rows).line; + if (line >= 0) { + pane.sel[b].state = .none; + var buf: [48]u8 = undefined; + const target = std.fmt.bufPrint(&buf, "@p{d}:{d}", .{ pane.serial, @as(usize, @intCast(line)) + 1 }) catch unreachable; // a u32 and a usize fit 48 + exec.runBuiltin(p, config.look_cmd, s.id, "", target); + return; + } + }; + var operand = exec.operandAt(p, pane, clk, true, s.button == config.look_button); + if (operand.expanded) |expanded| + pane.sel[b] = expanded + else if (operand.text == null) + pane.sel[b].state = .none; + if (s.button == config.look_button and clk.r0 >= pane.tag_rows and pane.body.mode != .tty and operand.expanded != null) { + // This click chose a new word. An old keyboard anchor + // must not stretch to it; borrowed selections retain + // their original cursor and extent. + pane.body.vsel.active = false; + pane.body.nsel = 0; + pane.body.select = false; + pane.body.cur_row = operand.row; + pane.body.cur_col = operand.col; + if (edit.clampFileCursor(&pane.body)) pane.ensureCursorVisible(); + } + const txt = operand.text; + const cmd = if (s.button == config.look_button) config.look_cmd else config.exec_cmd; + if (clk.r0 == 0 and s.button == config.exec_button and pane.prompt == .name) { + const prefix_width = panes.File.displayWidth(tagline.tagPrefix(p, pane) catch return); + const on_name = @as(usize, @intCast(@max(0, clk.c0))) < prefix_width; + if (!tagline.commitTagName(p, pane)) return; + // Executing a staged filename commits it; executing its + // command tail uses the new identity (especially Save). + if (on_name) return; + const new_width = panes.File.displayWidth(tagline.tagPrefix(p, pane) catch return); + const shift = @as(i32, @intCast(new_width)) - @as(i32, @intCast(prefix_width)); + if (operand.expanded) |*sel| { + sel.c0 += shift; + sel.c1 += shift; + } + if (operand.preview) |*sel| { + sel.c0 += shift; + sel.c1 += shift; + } + pane.sel[b].c0 += shift; + pane.sel[b].c1 += shift; + } + dispatchPointerBuiltin(p, s.id, cmd, txt, .{ + .on_tag = clk.r0 < pane.tag_rows, + .operand = operand, + }); + } + }, + .none => {}, + } +} + +const test_metrics: pardes.RowMetrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 }; + +fn twoColumns(gpa: std.mem.Allocator) !*Pardes { + const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30, .shells = 3 }); + p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); + p.view().active = p.view().cols[1].panes[0]; + p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell below it, same column + p.sync(); + return p; +} + +fn nudgeRightSeam(p: *Pardes, delta: i32) u16 { + const from = seamRowOf(p, 1, 0); + const inside = p.view().col_x[1] + p.view().col_w[1] / 2; + const to: u16 = @intCast(@as(i32, from) + delta); + // On the rule a pixel frontend draws over the lower pane's first row. + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = inside, .row = from + 1, .rule_above = true } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = inside, .row = to + 1 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = inside, .row = to + 1 } }); + p.sync(); + return seamRowOf(p, 1, 0); +} + +/// A session and a replica joined to it from its dump: digest for digest +/// the same, and only the session has drawn a frame (its surface is its +/// own, `.local`). What a step does with one input must not depend on that. +fn sessionAndReplica(gpa: std.mem.Allocator, opts: pardes.Options) !struct { a: *Pardes, b: *Pardes } { + const a = try Pardes.init(gpa, opts); + errdefer a.deinit(); + a.update(.{ .resize = .{ .cols = opts.cols, .rows = opts.rows, .row_metrics = test_metrics } }); + a.sync(); + const bytes = try pardes.dump.dumpBytes(a); + defer gpa.free(bytes); + const b = try pardes.dump.load(gpa, a.opts, bytes, null); + errdefer b.deinit(); + var frame: std.heap.ArenaAllocator = .init(gpa); + defer frame.deinit(); + _ = try a.render(frame.allocator()); + try expectSame(a, b, "before the press"); + return .{ .a = a, .b = b }; +} + +/// The two cores' digests equal, else the fields (and pane fields) that differ. +fn expectSame(a: *const Pardes, b: *const Pardes, when: []const u8) !void { + if (pardes.walk.digest(Pardes, a) == pardes.walk.digest(Pardes, b)) return; + const names = comptime pardes.walk.fieldNames(Pardes); + var da: [names.len]u64 = undefined; + var db: [names.len]u64 = undefined; + _ = pardes.walk.fieldDigests(Pardes, a, &da); + _ = pardes.walk.fieldDigests(Pardes, b, &db); + for (names, da, db) |name, x, y| if (x != y) std.debug.print("{s}: {s} differs\n", .{ when, name }); + const pane_names = comptime pardes.walk.fieldNames(pardes.Pane); + for (a.panes, b.panes, 0..) |pa, pb, id| { + const x = pa orelse continue; + const y = pb orelse continue; + var pda: [pane_names.len]u64 = undefined; + var pdb: [pane_names.len]u64 = undefined; + _ = pardes.walk.fieldDigests(pardes.Pane, x, &pda); + _ = pardes.walk.fieldDigests(pardes.Pane, y, &pdb); + for (pane_names, pda, pdb) |name, u, v| if (u != v) std.debug.print("{s}: pane {d}.{s} differs\n", .{ when, id, name }); + } + return error.DigestsDiffer; +} + +fn layerCenter(layer: *const Layer, col: u16, comptime tag: bool) [2]f32 { + const w: f32 = if (tag) test_metrics.tagline_w else test_metrics.body_w; + const h: f32 = if (tag) test_metrics.tagline_h else test_metrics.body_h; + return .{ + @as(f32, @floatFromInt(layer.viewport.x)) * test_metrics.body_w + (@as(f32, @floatFromInt(col)) + 0.5) * w, + @as(f32, @floatFromInt(layer.viewport.y)) * test_metrics.body_h + 0.5 * h, + }; +} + +test "a pane's last row of text is no resize handle; the rule over the next pane is" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells + const p = try twoColumns(std.testing.allocator); + defer p.deinit(); + const seam = seamRowOf(p, 1, 0); + const inside = p.view().col_x[1] + p.view().col_w[1] / 2; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = inside, .row = seam } }); + try std.testing.expect(p.view().drag != .border_h); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = inside, .row = seam } }); + try std.testing.expect(nudgeRightSeam(p, 2) == seam + 2); +} + +test "the line between two columns is no resize handle: a press there is a sweep in the pane" { + const p = try twoColumns(std.testing.allocator); + defer p.deinit(); + const line = p.view().col_x[0] + p.view().col_w[0] - 1; + const row = p.view().rects[p.view().cols[0].panes[0]].y + BOX_H + 1; + const weight = p.view().cols[0].weight; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = line, .row = row } }); + try std.testing.expect(p.view().drag == .select); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = line + 8, .row = row } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = line + 8, .row = row } }); + p.sync(); + try std.testing.expectEqual(weight, p.view().cols[0].weight); +} + +test "a pane's grip dragged up or down its own column moves its top, down to the floor of the pane above" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const p = try twoColumns(std.testing.allocator); + defer p.deinit(); + const upper = p.view().cols[1].panes[0]; + const lower = p.view().cols[1].panes[1]; + const grip_x = p.view().rects[lower].x; + // Up, past the pane above's first row: a text pane keeps its tag, a + // terminal its tag and two rows (layout.floorRows). + const top = p.view().rects[upper].y; + const above = p.panes[upper].?; + const floor: u16 = if (above.isTerminal()) above.tag_rows + layout.min_body_rows else 1; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = grip_x, .row = p.view().rects[lower].y } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = grip_x, .row = top } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = grip_x, .row = top } }); + p.sync(); + try std.testing.expectEqual(floor, p.view().rects[upper].h); + try std.testing.expectEqual(lower, p.view().cols[1].panes[1]); + // Down, inside itself: its top follows, the pane above taking the rows. + const to = p.view().rects[lower].y + 6; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = grip_x, .row = p.view().rects[lower].y } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = grip_x, .row = to } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = grip_x, .row = to } }); + p.sync(); + try std.testing.expectEqual(to, p.view().rects[lower].y); +} + +test "plain left click clears explicit modal selection" { + const gpa = std.testing.allocator; + // Wide enough for the tag on one row: the body starts under it. + const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 10 }); + defer p.deinit(); + const pane = try p.setTestFile("abcdef\n"); + pane.body.cur_row = 0; + pane.body.cur_col = 5; + pane.body.vsel = .{ .active = true, .row = 0, .col = 1, .explicit = true }; + + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const rect = p.view().rects[0]; + const click_x = rect.x + config.GUTTER + config.PREFIX_W + 3; + const body_y = rect.y + BOX_H; + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = click_x, .row = body_y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = click_x, .row = body_y } }); + + try std.testing.expectEqual(@as(i32, 3), pane.body.cur_col); + try std.testing.expect(!pane.body.vsel.active); + try std.testing.expectEqual(.none, pane.sel[@backingInt(config.select_button)].state); +} + +test "a selection drag and its release leave the selection done" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 50, .rows = 10, .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("alpha beta\n"); + const rect = p.view().rects[0]; + const x = rect.x + config.GUTTER + config.PREFIX_W + 1; + const y = rect.y + BOX_H; + + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = x, .row = y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .drag, .col = x + 2, .row = y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = x + 2, .row = y } }); + try std.testing.expect(p.view().drag == .none); + try std.testing.expectEqual(.done, pane.sel[sel_slot].state); +} + +test "mouse thumb buttons navigate once and clear selection gestures" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha beta\ngamma delta\nepsilon zeta\n"); + pane.body.setRange(pane.file.?.content, 0, .{ .anchor = 1, .head = 5 }, true); + p.view().jumps.n = 3; + p.view().jumps.cur = 2; + for (0..3) |i| p.view().jumps.list[i] = .{ .pane = 0, .serial = pane.serial, .line = @intCast(i + 1), .col = 1 }; + p.view().drag = .{ .select = .{ .id = 0, .button = config.select_button } }; + p.update(.{ .mouse = .{ .button = .back, .kind = .press, .col = 0, .row = 0 } }); + try std.testing.expectEqual(@as(usize, 1), p.view().jumps.cur); + for ([_]Mouse.Kind{ .drag, .release, .motion }) |kind| + p.update(.{ .mouse = .{ .button = .back, .kind = kind, .col = 0, .row = 0 } }); + try std.testing.expectEqual(@as(usize, 1), p.view().jumps.cur); + p.update(.{ .mouse = .{ .button = .forward, .kind = .press, .col = 0, .row = 0 } }); + p.update(.{ .mouse = .{ .button = .forward, .kind = .release, .col = 0, .row = 0 } }); + try std.testing.expectEqual(@as(usize, 2), p.view().jumps.cur); + try std.testing.expect(!pane.body.vsel.active); + try std.testing.expectEqual(.none, p.view().drag); +} + +test "a chorded exec an event reader holds is told with its argument, and written back runs with it" { + const th = @import("ninep/testing.zig"); + const p = try th.withFile(std.testing.allocator, "Msg said\narg-text\n"); + defer p.deinit(); + const serial = p.panes[0].?.serial; + const event = ctlfs.Node.of(serial, .event); + const h = th.call(p, .{ .tag = 1, .op = .open, .node = event, .omode = 2 }).reply.handle; + // The argument: a selection held in the pane (its second line). + ctlfs.pane.setDot(p.panes[0].?, .{ .q0 = 9, .q1 = 17 }); + p.view().chord_arg = try p.gpa.dupe(u8, "arg-text"); + dispatchPointerBuiltin(p, 0, config.exec_cmd, "Msg", .{ .on_tag = false, .operand = .{ .row = 0, .col = 1, .text = "Msg" } }); + var records: [3][]const u8 = undefined; + var got: [3][64]u8 = undefined; + for (&records, &got) |*r, *g| { + const bytes = th.call(p, .{ .tag = 2, .op = .read, .node = event, .handle = h, .size = 64 }).bytes; + @memcpy(g[0..bytes.len], bytes); + r.* = g[0..bytes.len]; + } + try std.testing.expect(std.mem.endsWith(u8, records[0], " 9 3 Msg\n")); // builtin|chorded, no expansion record + try std.testing.expectEqualStrings("X0 0 0 8 arg-text\n", records[1][1..]); + try std.testing.expect(std.mem.endsWith(u8, records[2], "test.txt:#9,#17\n")); + // Written back whole, it runs with its argument. + var back: [64]u8 = undefined; + const line = try std.fmt.bufPrint(&back, "M{s}", .{records[0][1..]}); + try std.testing.expectEqual(ctlfs.Status.ok, th.call(p, .{ .tag = 3, .op = .write, .node = event, .handle = h, .data = line }).reply.status); + const pane = p.panes[0].?; + try std.testing.expectEqualStrings("arg-text", pane.msg[0..pane.msg_len]); + // All three records written back as read, in one write or in three: + // the two after the first are its argument and where it came from, + // never commands of their own. + for ([_]bool{ true, false }) |together| { + pane.msg_len = 0; + var all: [256]u8 = undefined; + var w = std.Io.Writer.fixed(&all); + for (records) |r| try w.print("M{s}", .{r[1..]}); + if (together) { + _ = th.call(p, .{ .tag = 5, .op = .write, .node = event, .handle = h, .data = w.buffered() }); + } else for (records) |r| { + var one: [80]u8 = undefined; + _ = th.call(p, .{ .tag = 6, .op = .write, .node = event, .handle = h, .data = try std.fmt.bufPrint(&one, "M{s}", .{r[1..]}) }); + } + try std.testing.expectEqualStrings("arg-text", pane.msg[0..pane.msg_len]); + try std.testing.expect(!th.logHas(p, "run ")); + } + _ = th.call(p, .{ .tag = 4, .op = .release, .node = event, .handle = h }); +} + +test "a wheel over a program that owns it is the program's, in the form it asked for; a shell's scrolls" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + var out: [4096]u8 = undefined; + _ = pardes.test_api.ptyBytes(p, 0, &out); + const pane = p.panes[0].?; + const r = p.view().rects[0]; + // Grid cell 6,4 (1-based), as a program counts. + const col = r.x + config.GUTTER + 5; + const row = p.bodyTop(pane, r) + 3; + const Case = struct { modes: []const u8, button: Mouse.Button, ctrl: bool = false, alt: bool = false, shift: bool = false, sent: []const u8 }; + const cases = [_]Case{ + // codex's chat (0.158+): the alternate screen, any-event tracking, SGR. + .{ .modes = "\x1b[?2004h\x1b[>7u\x1b[?1004h\x1b[?1049h\x1b[?1007l\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h", .button = .wheel_up, .sent = "\x1b[<64;6;4M" }, + .{ .modes = "", .button = .wheel_down, .ctrl = true, .sent = "\x1b[<81;6;4M" }, + // Meta is 8, both 24; Shift keeps the wheel pardes's, which has + // nothing to scroll on the alternate screen. + .{ .modes = "", .button = .wheel_up, .alt = true, .sent = "\x1b[<72;6;4M" }, + .{ .modes = "", .button = .wheel_up, .alt = true, .ctrl = true, .sent = "\x1b[<88;6;4M" }, + .{ .modes = "", .button = .wheel_up, .shift = true, .sent = "" }, + // htop's legacy bytes (1000 alone), and 1015's. + .{ .modes = "\x1b[?1006l", .button = .wheel_down, .sent = "\x1b[M\x61\x26\x24" }, + .{ .modes = "\x1b[?1015h", .button = .wheel_up, .sent = "\x1b[96;6;4M" }, + // codex's sign-in, less: the alternate screen asking for arrow keys + // (1007), in the cursor keys' mode. + .{ .modes = "\x1b[?1015l\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1007h", .button = .wheel_down, .sent = "\x1b[B" }, + .{ .modes = "\x1b[?1h", .button = .wheel_up, .sent = "\x1bOA" }, + .{ .modes = "", .button = .wheel_right, .sent = "" }, + // With alternate scroll off the alternate screen keeps the wheel. + .{ .modes = "\x1b[?1007l", .button = .wheel_up, .sent = "" }, + }; + for (cases) |case| { + p.update(.{ .output = .{ .pane = 0, .bytes = case.modes } }); + _ = pardes.test_api.ptyBytes(p, 0, &out); + p.update(.{ .mouse = .{ .button = case.button, .kind = .press, .col = col, .row = row, .ctrl = case.ctrl, .alt = case.alt, .shift = case.shift } }); + try std.testing.expectEqualStrings(case.sent, pardes.test_api.ptyBytes(p, 0, &out)); + } + // A shell on the main screen: the wheel scrolls its scrollback, and + // the shell hears nothing. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1l\x1b[?1049l" } }); + for (0..40) |i| { + var line: [16]u8 = undefined; + p.update(.{ .output = .{ .pane = 0, .bytes = try std.fmt.bufPrint(&line, "{d}\r\n", .{i}) } }); + } + _ = try p.render(frame.allocator()); + _ = pardes.test_api.ptyBytes(p, 0, &out); + const was = pane.scroll(); + p.update(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = col, .row = row } }); + try std.testing.expectEqualStrings("", pardes.test_api.ptyBytes(p, 0, &out)); + try std.testing.expect(pane.scroll() != was); + // A program tracking the mouse on the main screen: Shift and the + // wheel scroll the scrollback, the program hears nothing. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1000h\x1b[?1006h" } }); + _ = pardes.test_api.ptyBytes(p, 0, &out); + const tracked = pane.scroll(); + p.update(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = col, .row = row, .shift = true } }); + try std.testing.expectEqualStrings("", pardes.test_api.ptyBytes(p, 0, &out)); + try std.testing.expect(pane.scroll() != tracked); + p.update(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = col, .row = row } }); + try std.testing.expectEqualStrings("\x1b[<64;6;4M", pardes.test_api.ptyBytes(p, 0, &out)); +} + +test "Alt-click is B2 and Super-click B3, kept from the press through the release; Ctrl-click stays B1" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const file = try p.setTestFile("Newcol here\n"); + p.presented(); + const r = p.view().rects[0]; + const col = r.x + config.GUTTER + panes.File.gutterWidth(file) + 1; + const row = p.bodyTop(file, r); + // A Super-press sweeps with B3's selection, not B1's. + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = col, .row = row, .super = true } }); + try std.testing.expect(p.view().drag == .select and file.sel[2].state != .none and file.sel[0].state == .none); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = col, .row = row } }); + try std.testing.expect(p.view().drag == .none); + try std.testing.expectEqual(@as(?Mouse.Button, null), p.view().click_as); + // Ctrl with Alt is Ctrl's: a B1 click (a definition), never B2. + const cols = p.view().ncol; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = col, .row = row, .ctrl = true, .alt = true } }); + try std.testing.expectEqual(@as(?Mouse.Button, null), p.view().click_as); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = col, .row = row, .ctrl = true } }); + try std.testing.expectEqual(cols, p.view().ncol); + // Alt-click on Newcol runs it, as B2 does, though Alt is let go + // before the button. + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = col, .row = row, .alt = true } }); + try std.testing.expectEqual(@as(?Mouse.Button, .middle), p.view().click_as); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = col, .row = row } }); + try std.testing.expectEqual(cols + 1, p.view().ncol); + try std.testing.expectEqual(@as(?Mouse.Button, null), p.view().click_as); +} + +test "a program tracking the mouse gets its clicks, drags and moves over its grid as xterm reports them; Shift and chrome stay pardes's" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + var out: [4096]u8 = undefined; + _ = pardes.test_api.ptyBytes(p, 0, &out); + const pane = p.panes[0].?; + try std.testing.expectEqual(.tty, pane.body.mode); + const r = p.view().rects[0]; + const col = r.x + config.GUTTER + 5; + const row = p.bodyTop(pane, r) + 3; + const Ev = struct { button: Mouse.Button, kind: Mouse.Kind, dx: i32 = 0, dy: i32 = 0, shift: bool = false, alt: bool = false, ctrl: bool = false, super: bool = false }; + const send = struct { + fn f(pp: *Pardes, o: []u8, c: u16, rw: u16, e: Ev) ![]const u8 { + pp.update(.{ .mouse = .{ + .button = e.button, + .kind = e.kind, + .col = @intCast(@as(i32, c) + e.dx), + .row = @intCast(@as(i32, rw) + e.dy), + .shift = e.shift, + .alt = e.alt, + .ctrl = e.ctrl, + .super = e.super, + } }); + return pardes.test_api.ptyBytes(pp, 0, o); + } + }.f; + // htop's modes: clicks in SGR, a release its own `m`. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049h\x1b[?1h\x1b[?1006;1000h" } }); + _ = pardes.test_api.ptyBytes(p, 0, &out); + try std.testing.expectEqualStrings("\x1b[<0;6;4M", try send(p, &out, col, row, .{ .button = .left, .kind = .press })); + try std.testing.expect(p.view().drag == .none); + // 1000 has no drags; the release is reported where it lands. + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .left, .kind = .drag, .dx = 1 })); + try std.testing.expectEqualStrings("\x1b[<0;7;4m", try send(p, &out, col, row, .{ .button = .left, .kind = .release, .dx = 1 })); + // An Alt- or Super-click (B2, B3 elsewhere) is still the program's + // button 1, Alt its meta and Super no bit at all. + try std.testing.expectEqualStrings("\x1b[<8;6;4M", try send(p, &out, col, row, .{ .button = .left, .kind = .press, .alt = true })); + try std.testing.expectEqualStrings("\x1b[<0;6;4m", try send(p, &out, col, row, .{ .button = .left, .kind = .release })); + try std.testing.expectEqualStrings("\x1b[<0;6;4M", try send(p, &out, col, row, .{ .button = .left, .kind = .press, .super = true })); + try std.testing.expectEqualStrings("\x1b[<0;6;4m", try send(p, &out, col, row, .{ .button = .left, .kind = .release, .super = true })); + try std.testing.expect(p.view().drag == .none); + // B2 and B3 are pardes's execute and look, as in any pane. + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .right, .kind = .press })); + try std.testing.expect(p.view().drag == .select); + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .right, .kind = .release })); + try std.testing.expect(p.view().drag == .none); + // Shift-B3 is the program's, the Shift that chose it left out: meta + // and ctrl, 2 + 8 + 16. + try std.testing.expectEqualStrings("\x1b[<26;6;4M", try send(p, &out, col, row, .{ .button = .right, .kind = .press, .shift = true, .alt = true, .ctrl = true })); + try std.testing.expectEqualStrings("\x1b[<2;6;4m", try send(p, &out, col, row, .{ .button = .right, .kind = .release, .shift = true })); + try std.testing.expectEqualStrings("\x1b[<1;6;4M", try send(p, &out, col, row, .{ .button = .middle, .kind = .press, .shift = true })); + try std.testing.expectEqualStrings("\x1b[<1;6;4m", try send(p, &out, col, row, .{ .button = .middle, .kind = .release })); + // Moves are no 1000 program's business: pardes hovers. + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .none, .kind = .motion })); + // Shift: pardes's own sweep, the program hears nothing of it. + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .left, .kind = .press, .shift = true })); + try std.testing.expect(p.view().drag == .select); + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .left, .kind = .drag, .dx = 2 })); + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .left, .kind = .release, .dx = 2 })); + try std.testing.expect(p.view().drag == .none); + // Chrome is never the program's: the tag, and the gutter. + const tag_row = p.tagTop(pane, r); + try std.testing.expectEqualStrings("", try send(p, &out, col, tag_row, .{ .button = .right, .kind = .press })); + try std.testing.expectEqualStrings("", try send(p, &out, col, tag_row, .{ .button = .right, .kind = .release })); + try std.testing.expectEqualStrings("", try send(p, &out, r.x, row, .{ .button = .left, .kind = .press })); + try std.testing.expectEqualStrings("", try send(p, &out, r.x, row, .{ .button = .left, .kind = .release })); + + // codex's any-event tracking: a drag once per cell, carried past the + // grid's edge and clamped there, and bare moves. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1003h" } }); + _ = pardes.test_api.ptyBytes(p, 0, &out); + try std.testing.expectEqualStrings("\x1b[<35;9;4M", try send(p, &out, col, row, .{ .button = .none, .kind = .motion, .dx = 3 })); + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .none, .kind = .motion, .dx = 3 })); + try std.testing.expectEqualStrings("\x1b[<0;6;4M", try send(p, &out, col, row, .{ .button = .left, .kind = .press })); + try std.testing.expectEqualStrings("\x1b[<32;7;4M", try send(p, &out, col, row, .{ .button = .left, .kind = .drag, .dx = 1 })); + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .left, .kind = .drag, .dx = 1 })); + // Up over the tag: row 1, the grid's first. + try std.testing.expectEqualStrings("\x1b[<32;7;1M", try send(p, &out, col + 1, tag_row, .{ .button = .left, .kind = .drag })); + try std.testing.expectEqualStrings("\x1b[<0;7;1m", try send(p, &out, col + 1, tag_row, .{ .button = .left, .kind = .release })); + try std.testing.expect(p.view().mouse_grab == null); + // Over the tag a bare move is pardes's. + try std.testing.expectEqualStrings("", try send(p, &out, col, tag_row, .{ .button = .none, .kind = .motion })); + // B2 held for pardes: its sweep's moves are not the program's; held + // for the program with Shift, they are its button-2 drags. + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .middle, .kind = .press })); + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .middle, .kind = .drag, .dx = 1 })); + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .middle, .kind = .release, .dx = 1 })); + try std.testing.expectEqualStrings("\x1b[<1;6;4M", try send(p, &out, col, row, .{ .button = .middle, .kind = .press, .shift = true })); + try std.testing.expectEqualStrings("\x1b[<33;7;4M", try send(p, &out, col, row, .{ .button = .middle, .kind = .drag, .dx = 1, .shift = true })); + try std.testing.expectEqualStrings("\x1b[<1;7;4m", try send(p, &out, col, row, .{ .button = .middle, .kind = .release, .dx = 1, .shift = true })); + + // Legacy X10 bytes: a release is button 3. (Turning 1003 off turns + // tracking off, as xterm's one tracking mode goes.) + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1003l\x1b[?1006l\x1b[?1000h" } }); + _ = pardes.test_api.ptyBytes(p, 0, &out); + try std.testing.expectEqualStrings("\x1b[M &$", try send(p, &out, col, row, .{ .button = .left, .kind = .press })); + try std.testing.expectEqualStrings("\x1b[M#&$", try send(p, &out, col, row, .{ .button = .left, .kind = .release })); + + // A pane out of the program's raw input (Esc to normal mode) clicks as + // pardes clicks. + pane.body.mode = .normal; + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .left, .kind = .press })); + try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .left, .kind = .release })); +} + +// A frontend's pointer hit is its own frame's: a step resolves it on the +// place the hit carries (Layer.Place), never on this process's last frame +// (`surface`, `.local`), so a session and its replica take one input alike +// (the variant hunt's, 2026-10-30, after a window client's tag hover). +test "a tag press is the same state whichever frame this process drew last" { + const gpa = std.testing.allocator; + const two = try sessionAndReplica(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer two.a.deinit(); + defer two.b.deinit(); + const layer = for (two.a.surface.tagLayers()) |*l| { + if (l.rows != 0 and l.kind == .pane) break l; + } else return error.NoPaneTag; + const at = layerCenter(layer, 2, true); + const hit = layer.tagHit(at[0], at[1], test_metrics.body_w, test_metrics.body_h, test_metrics.tagline_w, test_metrics.tagline_h) orelse return error.NoHit; + const press: pardes.Event = .{ .mouse = .{ .button = .left, .kind = .press, .col = layer.viewport.x + 2, .row = layer.viewport.y, .tag_hit = hit } }; + two.a.update(press); + two.b.update(press); + try expectSame(two.a, two.b, "after the press"); +} + +// The same through a body hit (edit.pointerTextSelection, a sweep's drag), +// on a compact body layer (TreeContext), which a pixel shell inverts. +test "a body press, drag and release are the same state whichever frame this process drew last" { + if (comptime !pardes.syntax.enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const a = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); + defer a.deinit(); + const pane = try a.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*)))) ++ " }\n};\n"); + a.gpa.free(pane.file.?.path); + pane.file.?.path = try a.gpa.dupe(u8, "/test.zig"); + if (!pardes.panes.File.supportsContext(pane)) return error.SkipZigTest; + a.update(.{ .resize = .{ .cols = 60, .rows = 16, .row_metrics = test_metrics } }); + pane.file.?.tree_context = true; + pane.file.?.scroll = 8; + a.sync(); + const bytes = try pardes.dump.dumpBytes(a); + defer gpa.free(bytes); + const b = try pardes.dump.load(gpa, a.opts, bytes, null); + defer b.deinit(); + var frame: std.heap.ArenaAllocator = .init(gpa); + defer frame.deinit(); + _ = try a.render(frame.allocator()); + // The join agrees, the frame drawn and all. + try expectSame(a, b, "before the press"); + const layer = for (&a.surface.body_layers) |*l| { + if (l.rows > 0 and l.serial == pane.serial) break l; + } else return error.NoBodyLayer; + const at = layerCenter(layer, 8, false); + const hit = layer.bodyHit(at[0], at[1], test_metrics.body_w, test_metrics.body_h, test_metrics.tagline_w, test_metrics.tagline_h) orelse return error.NoHit; + const col: u16 = @intFromFloat(at[0] / test_metrics.body_w); + const row: u16 = @intFromFloat(at[1] / test_metrics.body_h); + for ([_]pardes.Mouse.Kind{ .press, .drag, .release }) |kind| { + const ev: pardes.Event = .{ .mouse = .{ .button = .left, .kind = kind, .col = col, .row = row, .body_hit = hit } }; + a.update(ev); + b.update(ev); + } + try expectSame(a, b, "after the press"); +} |
