From 542e6677e23e277ce39edb3e96d729e9adca99d0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 5 Nov 2026 19:29:06 -0300 Subject: split pardes.zig by noun, keys: the keyboard leaves the session for src/keys.zig, free functions on it as mouse.zig is the mouse: handleKey, leaderKey, replayKeys, cycleMode, toggleTty, questionChoices and answerQuestion; their callers name keys (builtins.zig, ninep/ctl.zig, normal.zig, whose own `keys` are the replayed keys, so it imports the file as keyboard; update calls keys.handleKey); comments citing Pardes.handleKey and Pardes.answerQuestion cite keys; tests moved with them, by name: Esc back into a tty leaves its view at the prompt; Del from a key asks which neighbour takes the rows; nothing else asks; raw tty Esc backs out and Shift-Esc is the program's Esc; with ProgramEsc raw tty Escape only leaves at a shell prompt; the Del question shows only once its delay is up: a quick SPC d j never sees it; raw tty Ctrl-B switches to editor mode without sending child input; raw tty forwards Ctrl letters and former global shortcuts to the child; s in a header selects in the header's own text; a pure move, no field touched, a dump and the wire as they were; gates on tui: core-test 960/960, behaviour-test 238/238 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge --- src/keys.zig | 805 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 805 insertions(+) create mode 100644 src/keys.zig (limited to 'src/keys.zig') diff --git a/src/keys.zig b/src/keys.zig new file mode 100644 index 00000000..5673c0ba --- /dev/null +++ b/src/keys.zig @@ -0,0 +1,805 @@ +//! The keyboard: a key's way through the session (handleKey), the leader's +//! chords, the window and tty prefixes, a question's answer, the modes' +//! cycle and the tty toggle, as mouse.zig is the mouse. +const std = @import("std"); +const pardes = @import("pardes.zig"); +const config = @import("config.zig"); +const panes = @import("panes.zig"); +const modal = @import("modal.zig"); +const normal = @import("normal.zig"); +const edit = @import("edit.zig"); +const exec = @import("exec.zig"); +const look = @import("look.zig"); +const layout = @import("layout.zig"); +const tagline = @import("tagline.zig"); +const mouse = @import("mouse.zig"); +const builtins = @import("builtins.zig"); +const image = @import("image.zig"); +const ctlfs = @import("ninep/tree.zig"); +const Macro = @import("Macro.zig"); +const Pipe = @import("Pipe.zig"); +const Registers = @import("Registers.zig"); +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const Text = panes.Text; +const Key = pardes.Key; +const hit = pardes.hit; +const MAX_COLS = pardes.MAX_COLS; +const BOX_H = pardes.BOX_H; +const builtin_rows = pardes.builtin_rows; +const test_api = pardes.test_api; +const frame_ns = pardes.frame_ns; + +/// Cycle only the body modes supported by this pane. +pub fn cycleMode(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + if (pane.file == null and !pane.isTerminal()) return; + const previous = pane.body.mode; + p.active = id; + tagline.exitHeader(p); + pane.focus = .body; + pane.closePrompt(); + switch (previous) { + .tty => { + pane.body.mode = .normal; + pane.body.normal.clear(); + }, + .normal => edit.enterInsert(p, &pane.body, .at, 1), + .insert => { + edit.exitInsert(p, &pane.body); + if (pane.isTerminal()) panes.terminal.enterTty(p, id); + }, + } +} + +/// One mode transition for the terminal tag command and the Ctrl-B chord. +pub fn toggleTty(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + if (!pane.isTerminal()) return; + p.active = id; + tagline.exitHeader(p); + pane.focus = .body; + pane.closePrompt(); + if (pane.body.mode == .tty) { + pane.body.mode = .normal; + pane.body.normal.clear(); + } else panes.terminal.enterTty(p, id); +} + +/// Type `keys` again (a macro, `.`): through the modal handling as +/// typed, except that no key leaves the text for pardes's own acts -- +/// Esc does not hop panes, and Enter and Tab neither look nor execute. +pub fn replayKeys(p: *Pardes, keys: []const Macro.Stored) void { + if (p.macro.replaying >= 8) return; // a macro typing itself + p.macro.replaying += 1; + defer p.macro.replaying -= 1; + for (keys) |stored| { + var buf: [4]u8 = undefined; + handleKey(p, stored.typed(&buf)); + } +} + +/// The choices the question pane `id` asks offers, space-separated +/// (`k j`, `a b`), or null when it asks none. +pub fn questionChoices(p: *const Pardes, id: usize, buf: []u8) ?[]const u8 { + const asked = p.panes[id] orelse return null; + switch (asked.prompt) { + .del_side => return "k j", + // Any path; `-` takes it back. + .save => return "", + .repl_choice => { + const ask = p.repl_ask orelse return null; + var w = std.Io.Writer.fixed(buf); + for (ask.offered, 0..) |serial, i| if (serial != 0) { + if (w.buffered().len > 0) w.writeByte(' ') catch {}; + w.writeByte(@intCast('a' + i)) catch {}; + }; + return w.buffered(); + }, + else => return null, + } +} + +/// Answers the question pane `id` asks on its notice band (logged as +/// `ask `): Del's side (`k` above, `j` below) +/// or the REPL to send to (its letter). A choice it offers answers it; +/// null, or one it does not offer, takes it back. A key answers it, or +/// `answer` on the pane's ctl, and the log says which, as `answer +/// `; false when the pane asks nothing. +pub fn answerQuestion(p: *Pardes, id: usize, choice: ?u8) bool { + const asked = p.panes[id] orelse return false; + var offered: [64]u8 = undefined; + if (questionChoices(p, id, &offered)) |choices| { + const chosen: ?u8 = if (choice) |c| (if (std.mem.indexOfScalar(u8, choices, c) != null and c != ' ') c else null) else null; + var rec: [32]u8 = undefined; + ctlfs.events.notePath(p, "answer", std.fmt.bufPrint(&rec, "{d} {c}", .{ asked.serial, chosen orelse '-' }) catch ""); + } + switch (asked.prompt) { + .repl_choice => { + asked.prompt = .none; + const ask = p.repl_ask orelse return true; + p.repl_ask = null; + defer p.gpa.free(ask.text); + const letter = choice orelse return true; + if (letter < 'a' or letter > 'z') return true; + const serial = ask.offered[letter - 'a']; + if (serial == 0) return true; + // The pane offered, still that REPL and still running: it + // may have closed or been rebound while the question stood. + if (p.paneBySerial(serial)) |to| if (p.panes[to].?.repl) |r| + if (r.lang == ask.lang and r.letter == letter) { + // Offered with no program running: said so, not sent. + if (!exec.replLive(p, to)) { + _ = exec.replGone(p, id, p.panes[to].?); + return true; + } + exec.sendToRepl(p, id, to, ask.text); + return true; + }; + p.setMessage(id, "Repl: the REPL chosen is gone; nothing sent"); + }, + .del_side => { + asked.prompt = .none; + if (choice == 'k') exec.runBuiltin(p, .Del, id, "", "k"); + if (choice == 'j') exec.runBuiltin(p, .Del, id, "", "j"); + // Asked from window mode (`d`): the outline goes with the rows. + if (p.window_pick == id and p.panes[id] == null) p.window_pick = if (p.header_focus) null else p.active; + }, + else => return false, + } + return true; +} + +pub fn handleKey(p: *Pardes, key: Key) void { + // A double-click is two clicks with nothing between them. + p.last_click = null; + if (p.macro.recording != 0 and p.macro.replaying == 0) Macro.append(&p.macro.recorded, p.gpa, key); + // A question waiting on a pane takes the next key, whatever mode the + // pane or a header edit is in: that key is its answer. + for (p.panes, 0..) |slot, id| { + const asked = slot orelse continue; + switch (asked.prompt) { + // Its letter sends it there; anything else takes it back. + .repl_choice => _ = answerQuestion(p, id, if (key.ctrl or key.alt or key.cp > 'z' or key.cp < 'a') null else @intCast(key.cp)), + .del_side => _ = answerQuestion(p, id, if (hit(key, config.del_above)) 'k' else if (hit(key, config.del_below)) 'j' else null), + else => continue, + } + return; + } + if (p.window_pick != null) return layout.windowKey(p, key); + const pane = p.panes[p.active] orelse return; + p.noteTyped(); + // In a raw terminal the two Escs swap unless ProgramEsc is on: Esc + // backs out, and Shift-Esc is the program's, sent as a plain Esc. + const raw_esc = key.cp == Key.escape and !key.ctrl and !key.alt and !p.settings.program_esc and + pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none and + tagline.focusedHeader(p) == null; + if (raw_esc and key.shift) { + p.leader_on = false; + p.ctrl_w_pending = false; + panes.terminal.followOutput(pane); + var plain = key; + plain.shift = false; + return panes.terminal.forwardKey(p, p.active, plain); + } + // Shift-Esc backs out of whatever the pane is in -- a prompt, insert + // mode, a pending count, a raw program -- to the previous pane, as + // Esc does from normal mode. Nothing under it sees the key. + if (raw_esc or hit(key, config.back_out)) { + p.leader_on = false; + p.ctrl_w_pending = false; + if (pane.prompt != .none) { + pane.closePrompt(); + pane.focus = .body; + } + for ([_]*Text{ &pane.body, &pane.tag }) |t| { + if (t.mode == .insert) edit.exitInsert(p, t); + t.normal.clear(); + t.select = false; + } + tagline.exitHeader(p); + return exec.runBuiltin(p, .Last, p.active, "", null); + } + // Alt-Down and Alt-Up in a pane's tag expand and collapse it, in + // either mode: acme's Tagdown and Tagup (plan9port text.c:776). + if (pane.focus == .tag and key.alt and !key.ctrl and (key.cp == Key.down or key.cp == Key.up) and tagline.focusedHeader(p) == null) { + pane.tag_expanded = key.cp == Key.down; + return; + } + // An open prompt takes the keys even when it answers for a header. + const header = if (pane.prompt != .none) null else tagline.focusedHeader(p); + if (header == null and pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none) { + p.leader_on = false; + p.ctrl_w_pending = false; + if (key.ctrl and !key.alt and key.cp == p.tty_toggle) + return toggleTty(p, p.active); + // With ProgramEsc on, bare Escape leaves only at a shell prompt + // (Shift-Esc, above, always). + if (key.cp == Key.escape and !key.ctrl and !key.alt and !key.shift and exec.takesCommandLine(p, p.active)) + return exec.runBuiltin(p, .Last, p.active, "", null); + panes.terminal.followOutput(pane); // typing snaps back to live output + // Paste stays the window's, the one exception to forwarding a raw + // tty's keys: Ctrl-V types the register at the program and + // Ctrl-Shift-V asks the desktop for its clipboard first. Forwarded, + // they reach an application that reads the clipboard on its own + // account instead — a coding agent goes there hunting for an image. + // A host that folds Shift into the letter says the same thing. + if (key.ctrl and !key.alt and (key.cp == 'v' or key.cp == 'V')) { + if (key.shift or key.cp == 'V') return edit.clipRequest(p, p.active, .after); + // With something in the register this is a paste. With nothing + // in it the chord is the program's -- vim's visual block, + // readline's quoted-insert -- and swallowing it would make + // Ctrl-V a black hole in every full-screen application. + if (p.registers.text(p.gpa, Registers.default)) |text| return edit.typeToTty(p, p.active, pane, text); + } + return panes.terminal.forwardKey(p, p.active, key); + } + if (p.leader_on) return leaderKey(p, key); + if (p.ctrl_w_pending) { + p.ctrl_w_pending = false; + for (config.window_keys) |wk| { + if (hit(key, &.{ wk.letter, wk.arrow })) return exec.runBuiltin(p, wk.cmd, p.active, "", null); + } + return; + } + // insert mode owns Ctrl-w (delete word backward, helix); outside raw + // tty mode it enters window mode, or on a header prefixes a move + // between the headers + const t = header orelse if (pane.focus == .tag) &pane.tag else &pane.body; + if (hit(key, config.window_prefix) and t.mode != .insert and (header != null or pane.prompt == .none)) { + if (header != null) { + p.ctrl_w_pending = true; + return; + } + return exec.runBuiltin(p, .Window, p.active, "", null); + } + // global window ops (any mode): Alt-n new terminal below, Alt-c move + // the active terminal into a fresh column + if (hit(key, config.new_shell_below)) { + const free = p.freeSlot() orelse return p.reportError(p.active, "Term", error.NoPaneSlots); + const nt = p.newShell(free, "") catch return; + nt.greet = true; + // From a tag, as a 9P new is: acme's t->w == nil. + exec.placeNew(p, p.active, if (p.header_focus) null else p.active, free, .shell); + return; + } + for (config.jump_keys) |jk| { + if (!hit(key, &.{jk.chord})) continue; + tagline.exitHeader(p); + return exec.runBuiltin(p, jk.cmd, p.active, "", null); + } + if (hit(key, config.pane_to_new_column)) { + tagline.exitHeader(p); + const f = layout.findPane(p, p.active).?; + if (p.ncol < MAX_COLS and p.col_n[f.col] > 1) { + _ = layout.splitColumn(p, p.active, p.active, false); + } + return; + } + const tty_toggle = key.ctrl and key.cp == p.tty_toggle; + if (pane.isTerminal() and tty_toggle) { + return toggleTty(p, p.active); + } + if (header == null and pane.prompt == .name) { + // Enter or the execute key commits the draft and the keyboard + // goes back to the body. Esc while typing keeps the draft, + // pending, as Esc keeps any edit: Enter then renames, and a + // second Esc drops it. Pending, no other key changes it. + if (hit(key, config.look_key) or hit(key, config.exec_key)) { + if (tagline.commitTagName(p, pane)) pane.focus = .body; + return; + } + const pending = pane.input.mode != .insert; + if (hit(key, config.escape) and pending) { + pane.closePrompt(); + pane.focus = .body; + return; + } + if (hit(key, config.escape) or pending) { + pane.input.mode = .normal; + p.setMessage(p.active, "name drafted: Enter renames the buffer, Esc drops the draft"); + return; + } + edit.handleInsert(p, &pane.input, key); + return; + } + if (header == null and pane.prompt != .none) { + if (hit(key, config.search_submit) or hit(key, config.escape)) { + const submit = hit(key, config.search_submit); + const target = p.promptTarget(pane); + switch (pane.prompt) { + .pipe => if (submit) Pipe.submitPipe(p, p.active), + .save => if (submit) exec.submitSave(p, p.active), + .search => if (submit) + look.submitSearch(p, p.active) + else if (normal.selRegexArmed(pane)) |_| if (target) |answered| + normal.applySelRegex(p, pane, answered, "", .select), + .none, .del_side, .repl_choice, .name => unreachable, + } + pane.closePrompt(); + if (target) |answered| { + answered.mode = .normal; + answered.normal.clear(); + } + return; + } + edit.handleInsert(p, &pane.input, key); + if (normal.selRegexArmed(pane)) |a| if (p.promptTarget(pane)) |answered| normal.applySelRegex(p, pane, answered, a.pat, a.mode); + return; + } + if (t == &pane.body and pane.jump.items.len > 0) return normal.jumpKey(p, pane, t, key); + // A query pane's line 1 answers Enter, Esc and the stepping keys + // itself (Query.zig). + if (t == &pane.body and header == null and pane.query != null and panes.Query.key(p, p.active, key)) return; + if (t.mode == .normal and p.macro.replaying == 0 and (hit(key, config.look_key) or hit(key, config.exec_key))) { + // A header's words are the workspace's and column's commands, so + // Enter runs them there, as the execute key does. + const header_word = t.what == .column or t.what == .workspace; + const cmd = if (hit(key, config.look_key) and !header_word) config.look_cmd else config.exec_cmd; + if (t.what != .body) { + // An explicit selection, else the word under the cursor in the + // text as it is shown: a tag's prefix is part of what a word is. + const shown = p.scratch.allocator().dupe(u8, edit.flatSurface(p, t) catch return) catch return; + const range = t.primaryRange(shown, 0); + const lo = @min(range.anchor, range.head); + const hi = @max(range.anchor, range.head); + const span: [2]usize = if (t.vsel.active and t.vsel.explicit) + .{ lo, hi } + else word: { + const b = config.wordBounds(shown, modal.selectionCursor(shown, range)); + break :word .{ b.lo, b.hi }; + }; + const txt = shown[span[0]..span[1]]; + // A column tag's command acts on that column, empty or not. + p.exec_column = if (header != null) p.header_column else null; + defer p.exec_column = null; + p.exec_header = header != null; + defer p.exec_header = false; + // Out of the tag or header FIRST: Del frees the pane, Kill + // and Restore the whole session. + if (header != null) tagline.exitHeader(p) else pane.focus = .body; + if (txt.len == 0) return; + // A pane's tag word: an event reader hears it as a click on + // it, at its place in the tag (flatSurface is the tag's text). + if (header == null and t.what == .tag and + mouse.reportRange(p, p.active, cmd, txt, true, .{ .q0 = @intCast(span[0]), .q1 = @intCast(span[1]) }, null)) return; + exec.runBuiltin(p, cmd, p.active, "", txt); + return; + } + edit.pinPaneCursor(p, &pane.body); + const explicit = (p.native_images and pane.hasPdfSelection()) or + (pane.body.vsel.active and pane.body.vsel.explicit); + if (explicit) { + if (exec.chordEachSel(p, pane, cmd)) return; + if (edit.currentSelText(p, pane)) |txt| { + pane.body.vsel.active = false; + pane.body.select = false; + // The execute key on a body: text a bound REPL may take. + exec.runBuiltinFrom(p, cmd, p.active, "", txt, true); + return; + } + } + // The cursor's word as a click there takes it: one expansion + // (exec.operandAt), a diff line's address and all, and an + // event reader told as a click tells it. + const operand = exec.operandAt(p, pane, look.cursorWordSel(p, pane), false, cmd == config.look_cmd); + mouse.dispatchPointerBuiltin(p, p.active, cmd, operand.text, .{ .on_tag = false, .operand = operand }); + return; + } + if (t.mode == .normal and t.what == .body and pane.hasPdf()) return normal.handlePdfNormal(p, pane, key); + if (t.what == .tag and t.mode == .insert and tagline.typedIntoName(p, pane, key)) return; + // A tag's prefix is read-only: a key whose edit reached into it + // changes nothing, not even where the cursor is. + const kept = .{ t.cur_row, t.cur_col, t.vsel }; + var kept_sels: [Text.max_selections - 1]Text.SelRange = undefined; + const kept_n = t.nsel; + @memcpy(kept_sels[0..kept_n], t.sels[0..kept_n]); + t.refused = false; + defer if (t.refused) { + t.cur_row, t.cur_col, t.vsel = kept; + t.restoreSels(kept_sels[0..kept_n]); + }; + const was = t.mode; + switch (t.mode) { + .normal => normal.handleNormal(p, t, key), + .insert => if (hit(key, config.escape) and !t.reg_wait) + edit.exitInsert(p, t) + else + edit.handleInsert(p, t, key), + .tty => panes.terminal.forwardKey(p, p.active, key), + } + // `.`'s log: the keys of the normal command that entered insert + // mode, then everything typed until it is left + if (p.macro.repeating) return; + const m = &p.macro; + switch (was) { + .normal => { + Macro.append(&m.command, p.gpa, key); + if (t.mode == .insert) { + m.last_insert.clearRetainingCapacity(); + m.last_insert.appendSlice(p.gpa, m.command.items) catch {}; + m.typed_from = m.last_insert.items.len; + m.inserting = true; + m.command.clearRetainingCapacity(); + } else if (std.meta.eql(t.normal, modal.Normal.State{})) m.command.clearRetainingCapacity(); + }, + .insert => if (m.inserting) { + Macro.append(&m.last_insert, p.gpa, key); + if (t.mode != .insert) m.inserting = false; + }, + .tty => {}, + } +} + +fn leaderKey(p: *Pardes, key: Key) void { + p.leader_on = false; // only "still a prefix" below re-arms it + if (key.ctrl or key.alt or key.cp < 0x20 or key.cp > 0x7e) return; + const c: u8 = @intCast(key.cp); + if (c == config.leader_help) { + panes.Output.openHelp(p, p.active, p.leader_keys[0..p.leader_n]) catch |err| + p.reportError(p.active, "help", err); + return; + } + if (p.leader_n >= p.leader_keys.len) return; + p.leader_keys[p.leader_n] = c; + p.leader_n += 1; + const pfx = p.leader_keys[0..p.leader_n]; + // A path that runs a builtin with its argument (the query pane's + // sources with no word of their own). + for (config.leader_args) |la| if (std.mem.eql(u8, la.path, pfx)) return exec.runBuiltin(p, la.cmd, p.active, "", la.arg); + for (config.leader_args) |la| if (std.mem.startsWith(u8, la.path, pfx)) { + p.leader_on = true; + }; + // a path-less builtin is a row here too (it is the same index Help + // reads), and SPC cannot reach one — so both scans skip it; and a + // window's own word is no path in a terminal's view + for (builtin_rows) |row| { + if (!builtins.registry.here(p, row.cmd)) continue; + if (std.mem.eql(u8, row.path orelse continue, pfx)) return exec.runBuiltin(p, row.cmd, p.active, "", null); + } + for (builtin_rows) |row| { + if (!builtins.registry.here(p, row.cmd)) continue; + if (std.mem.startsWith(u8, row.path orelse continue, pfx)) { + p.leader_on = true; + return; + } + } +} + +test "Esc back into a tty leaves its view at the prompt" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); + defer p.deinit(); + p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); + p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell under the doc + const shell = p.active; + const sp = p.panes[shell].?; + try std.testing.expect(sp.isTerminal()); + + // A click pins the modal cursor — one of the several ordinary ways to get a + // pin, and the pin is what a shell's rows then scroll out from under. + const r = p.rects[shell]; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = r.x + config.GUTTER + 1, .row = r.y + BOX_H } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = r.x + config.GUTTER + 1, .row = r.y + BOX_H } }); + try std.testing.expectEqual(shell, p.active); + + p.update(.{ .key = .{ .cp = 'b', .ctrl = true } }); + try std.testing.expectEqual(Text.Mode.tty, sp.body.mode); + + // tty mode follows output to the bottom, so a screenful and a half of it + // rides the view down and leaves that pin far up in the scrollback. + for (0..60) |i| { + var buf: [32]u8 = undefined; + p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); + } + p.sync(); + const live = sp.terminal.?.vt.screens.active.pages.scrollbar().offset; + try std.testing.expect(live > 0); + + p.update(.{ .key = .{ .cp = Key.escape } }); // shell-prompt heuristic: out to the doc + try std.testing.expect(p.active != shell); + p.update(.{ .key = .{ .cp = Key.escape } }); // ...and back in + p.sync(); + try std.testing.expectEqual(shell, p.active); + + try std.testing.expectEqual(live, sp.terminal.?.vt.screens.active.pages.scrollbar().offset); +} + +test "Del from a key asks which neighbour takes the rows; nothing else asks" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 40 }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const top = p.active; + p.newScratchBelow(top); + const mid = p.active; + p.newScratchBelow(mid); + const low = p.active; + p.sync(); + var h = [_]u16{ p.rects[top].h, p.rects[mid].h, p.rects[low].h }; + + // SPC d on the middle pane asks on its notice band, and closes nothing yet. + p.active = mid; + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'd' } }); + try std.testing.expect(p.panes[mid] != null); + try std.testing.expectEqual(Pane.Prompt.del_side, p.panes[mid].?.prompt); + p.now_ns = p.panes[mid].?.question_due_ns; // shown once its delay is up + _ = try p.render(frame.allocator()); + try std.testing.expectEqual(Pane.Notices.Kind.prompt, p.panes[mid].?.notices.kinds[p.panes[mid].?.notices.len - 1]); + try std.testing.expectEqualStrings(config.del_question, p.panes[mid].?.promptText().?); + // j: the pane below takes every row, the one above keeps its own. + p.update(.{ .key = .{ .cp = 'j' } }); + try std.testing.expect(p.panes[mid] == null); + try std.testing.expectEqual(h[0], p.rects[top].h); + try std.testing.expectEqual(h[1] + h[2], p.rects[low].h); + try std.testing.expectEqual(low, p.active); // focus follows the rows + + // Esc takes the question back and the pane stays; so does any other key, + // and so does a click. A New goes to the column's foot, under low, which + // is between two again. + p.newScratchBelow(low); + const foot = p.active; + const again = low; + p.active = again; + p.sync(); + h = .{ p.rects[top].h, p.rects[again].h, p.rects[foot].h }; + try std.testing.expect(p.executeBuiltinLine(again, "Msg keep")); + for ([_]Key{ .{ .cp = Key.escape }, .{ .cp = 'x' } }) |answer| { + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'd' } }); + try std.testing.expectEqual(Pane.Prompt.del_side, p.panes[again].?.prompt); + p.update(.{ .key = answer }); + try std.testing.expect(p.panes[again] != null); + try std.testing.expectEqual(Pane.Prompt.none, p.panes[again].?.prompt); + } + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'd' } }); + const r = p.rects[again]; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = r.x + 5, .row = r.y + 3 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = r.x + 5, .row = r.y + 3 } }); + try std.testing.expect(p.panes[again] != null); + try std.testing.expectEqual(Pane.Prompt.none, p.panes[again].?.prompt); + try std.testing.expectEqual(h[1], p.rects[again].h); + + // A word that is not a side closes nothing. + try std.testing.expect(p.executeBuiltinLine(again, "Del x")); + try std.testing.expectEqualStrings("Del: takes k, j or nothing", p.panes[again].?.msg[0..p.panes[again].?.msg_len]); + try std.testing.expect(p.panes[again] != null); + // DelAbove is Del k, and a line that is not a key never asks. + try std.testing.expect(p.executeBuiltinLine(again, "DelAbove")); + p.sync(); + try std.testing.expect(p.panes[again] == null); + try std.testing.expectEqual(h[0] + h[1], p.rects[top].h); + try std.testing.expectEqual(top, p.active); + try std.testing.expectEqual(h[2], p.rects[foot].h); + + // A script answers the question on the pane's ctl, as the log's `ask` + // names it: `answer -` takes it back, a side closes the pane toward it. + p.newScratchBelow(foot); + const tail = p.active; + { + const th = @import("ninep/testing.zig"); + const asked = foot; + p.active = asked; + p.sync(); + const serial = p.panes[asked].?.serial; + const ctl = ctlfs.Node.of(serial, .ctl); + try std.testing.expectEqual(ctlfs.E.INVAL, th.wr(p, ctl, "answer k\n").errno()); + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'd' } }); + var want: [32]u8 = undefined; + try std.testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "ask {d} del k j\n", .{serial}))); + try std.testing.expectEqual(ctlfs.E.INVAL, th.wr(p, ctl, "answer x\n").errno()); + try std.testing.expectEqual(Pane.Prompt.del_side, p.panes[asked].?.prompt); + try std.testing.expectEqual(ctlfs.Status.ok, th.wr(p, ctl, "answer -\n").reply.status); + try std.testing.expect(p.panes[asked] != null and p.panes[asked].?.prompt == .none); + try std.testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "answer {d} -\n", .{serial}))); + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'd' } }); + try std.testing.expectEqual(ctlfs.Status.ok, th.wr(p, ctl, "answer k\n").reply.status); + try std.testing.expect(p.paneBySerial(serial) == null); + try std.testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "answer {d} k\n", .{serial}))); + } + + // Bare Del from anything but a key closes at once and gives the rows up, + // as it always has. + p.newScratchBelow(tail); + const last = p.active; + const third = tail; + p.sync(); + h = .{ p.rects[top].h, p.rects[third].h, p.rects[last].h }; + try std.testing.expect(p.executeBuiltinLine(third, "Del")); + p.sync(); + try std.testing.expect(p.panes[third] == null); + try std.testing.expectEqual(h[0] + h[1], p.rects[top].h); + + // With nothing open below, there is nothing to ask: SPC d closes at once. + p.active = last; + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'd' } }); + try std.testing.expect(p.panes[last] == null); +} + +test "raw tty Esc backs out and Shift-Esc is the program's Esc" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); + defer p.deinit(); + _ = exec.spawnTty(p, 0); + const shell = p.active; + const pane = p.panes[shell].?; + var buf: [256]u8 = undefined; + _ = test_api.ptyBytes(p, null, &buf); + + p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); + _ = test_api.ptyBytes(p, null, &buf); + p.update(.{ .key = .{ .cp = Key.escape } }); // past typed text too + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqualStrings("", test_api.ptyBytes(p, null, &buf)); + try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); + + p.update(.{ .key = .{ .cp = Key.escape } }); // back into the shell + try std.testing.expectEqual(shell, p.active); + _ = test_api.ptyBytes(p, null, &buf); + p.update(.{ .key = .{ .cp = Key.escape, .shift = true } }); + try std.testing.expectEqual(shell, p.active); + try std.testing.expectEqualStrings("\x1b", test_api.ptyBytes(p, null, &buf)); +} + +test "with ProgramEsc raw tty Escape only leaves at a shell prompt" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); + defer p.deinit(); + p.settings.program_esc = true; + _ = exec.spawnTty(p, 0); + const shell = p.active; + const pane = p.panes[shell].?; + var buf: [256]u8 = undefined; + _ = test_api.ptyBytes(p, null, &buf); + + // Ordinary keys reach the child; Shift-Escape is the one unconditional way + // out and sends it nothing. + p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); + try std.testing.expectEqual(shell, p.active); + try std.testing.expect(test_api.ptyBytes(p, null, &buf).len > 0); + + p.update(.{ .key = .{ .cp = Key.escape, .shift = true } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqualStrings("", test_api.ptyBytes(p, null, &buf)); + try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); + + p.update(.{ .key = .{ .cp = Key.escape } }); // back into the shell + try std.testing.expectEqual(shell, p.active); + _ = test_api.ptyBytes(p, null, &buf); + + p.update(.{ .key = .{ .cp = Key.escape } }); // bare Escape leaves at a prompt + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqualStrings("", test_api.ptyBytes(p, null, &buf)); + try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); +} + +test "the Del question shows only once its delay is up: a quick SPC d j never sees it" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 40 }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const top = p.active; + p.newScratchBelow(top); + const mid = p.active; + p.newScratchBelow(mid); + p.sync(); + p.active = mid; + p.now_ns = 5 * std.time.ns_per_s; + p.stepped_ns = p.now_ns; + const asked_at = p.now_ns; + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'd' } }); + const pane = p.panes[mid].?; + try std.testing.expectEqual(Pane.Prompt.del_side, pane.prompt); + try std.testing.expectEqual(asked_at + config.del_question_delay_ns, pane.question_due_ns); + // Asked, and nothing on the band yet. + _ = try p.render(frame.allocator()); + for (pane.notices.kinds[0..pane.notices.len]) |kind| try std.testing.expect(kind != .prompt); + // The loop wakes for it, at the end of the delay and not before. + const wake = p.nextWake().?; + try std.testing.expect(wake >= pane.question_due_ns and wake < pane.question_due_ns + frame_ns); + p.now_ns = pane.question_due_ns - 1; + _ = try p.render(frame.allocator()); + for (pane.notices.kinds[0..pane.notices.len]) |kind| try std.testing.expect(kind != .prompt); + // Its time come, it is the band's last line; stepped past it, nothing + // more to wake for. + p.now_ns = wake; + p.stepped_ns = wake; + _ = try p.render(frame.allocator()); + try std.testing.expectEqual(Pane.Notices.Kind.prompt, pane.notices.kinds[pane.notices.len - 1]); + try std.testing.expect(p.nextWake() == null); + // A key answers it either way, shown or not: Esc keeps the pane. + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(Pane.Prompt.none, pane.prompt); + try std.testing.expect(p.nextWake() == null); + // A fast SPC d j: closed before the band ever showed the question. + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'd' } }); + _ = try p.render(frame.allocator()); + for (pane.notices.kinds[0..pane.notices.len]) |kind| try std.testing.expect(kind != .prompt); + p.update(.{ .key = .{ .cp = 'j' } }); + try std.testing.expect(p.panes[mid] == null); +} + +test "raw tty Ctrl-B switches to editor mode without sending child input" { + const p = try Pardes.init(std.testing.allocator, .{ .file = "mise.toml" }); + defer p.deinit(); + _ = exec.spawnTty(p, 0); + const shell = p.active; + p.sync(); + var buf: [256]u8 = undefined; + _ = test_api.ptyBytes(p, null, &buf); + p.update(.{ .key = .{ .cp = 'b', .ctrl = true } }); + try std.testing.expectEqual(shell, p.active); + try std.testing.expectEqual(Text.Mode.normal, p.panes[shell].?.body.mode); + try std.testing.expectEqualStrings("", test_api.ptyBytes(p, null, &buf)); +} + +test "raw tty forwards Ctrl letters and former global shortcuts to the child" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var buf: [256]u8 = undefined; + _ = test_api.ptyBytes(p, null, &buf); + edit.setYank(p, "register text"); + for ('a'..'z' + 1) |letter| { + if (letter == p.tty_toggle) continue; // editor/TTY mode shortcut + if (letter == 'v') continue; // the window's paste, asserted just below + p.update(.{ .key = .{ .cp = @intCast(letter), .ctrl = true } }); + const expected = [_]u8{@intCast(letter - 'a' + 1)}; + // The terminal encoder distinguishes Ctrl-I/M from Tab/Return. + const encoded: []const u8 = switch (letter) { + 'i' => "\x1b[105;5u", + 'm' => "\x1b[109;5u", + else => &expected, + }; + try std.testing.expectEqualStrings(encoded, test_api.ptyBytes(p, null, &buf)); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(Text.Mode.tty, p.panes[0].?.body.mode); + try std.testing.expect(!p.ctrl_w_pending and p.clip_pending == null); + } + // ...and the two paste chords are the exception: Ctrl-V types the register + // at the program, Ctrl-Shift-V asks the desktop first and types nothing yet. + p.update(.{ .key = .{ .cp = 'v', .ctrl = true } }); + try std.testing.expectEqualStrings("register text", test_api.ptyBytes(p, null, &buf)); + try std.testing.expect(p.clip_pending == null); + p.update(.{ .key = .{ .cp = 'v', .ctrl = true, .shift = true } }); + try std.testing.expectEqualStrings("", test_api.ptyBytes(p, null, &buf)); + try std.testing.expect(p.clip_pending != null); + const unopened = p.freeSlot(); // whatever the boot layout already used + for ([_]u8{ 'n', 'c' }) |letter| { + p.update(.{ .key = .{ .cp = letter, .alt = true } }); + const expected = [_]u8{ 0x1b, letter }; + try std.testing.expectEqualStrings(&expected, test_api.ptyBytes(p, null, &buf)); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(unopened, p.freeSlot()); + } + p.update(.{ .key = .{ .cp = Key.up } }); + try std.testing.expectEqualStrings("\x1b[A", test_api.ptyBytes(p, null, &buf)); + p.panes[0].?.terminal.?.vt.modes.set(.cursor_keys, true); + p.update(.{ .key = .{ .cp = Key.up } }); + try std.testing.expectEqualStrings("\x1bOA", test_api.ptyBytes(p, null, &buf)); + p.update(.{ .key = .{ .cp = Key.left, .ctrl = true } }); + try std.testing.expectEqualStrings("\x1b[1;5D", test_api.ptyBytes(p, null, &buf)); +} + +test "s in a header selects in the header's own text" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 12, .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("body col\n"); + tagline.enterHeader(p, null); + p.update(.{ .key = .{ .cp = 'x' } }); + p.update(.{ .key = .{ .cp = 's' } }); + try std.testing.expect(pane.prompt == .search and pane.prompt_for == .workspace); + // the prompt takes the keys while the header keeps the keyboard + p.update(.{ .key = .{ .cp = 'c', .text = "col" } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(p.header_focus and pane.prompt == .none); + var ranges: [Text.max_selections]modal.Selection = undefined; + const text = try edit.flatSurface(p, &p.global_tag); + const got = p.global_tag.ranges(text, 0, &ranges); + try std.testing.expectEqual(@as(usize, 2), got.n); // Newcol, Joincol + try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); +} -- cgit v1.3