diff options
Diffstat (limited to 'src/term')
| -rw-r--r-- | src/term/terminal.zig | 196 |
1 files changed, 71 insertions, 125 deletions
diff --git a/src/term/terminal.zig b/src/term/terminal.zig index 50fca2d0..02ae4b3c 100644 --- a/src/term/terminal.zig +++ b/src/term/terminal.zig @@ -322,8 +322,8 @@ pub const State = struct { defer decoded.deinit(gpa); out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined }; } - if (comptime images_enabled) inline for (.{ .primary, .alternate }) |key| { - if (out.vt.screens.get(key)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir()); + if (comptime images_enabled) inline for (.{ .primary, .alternate }) |which| { + if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir()); }; out.wire(); const reply = parts.reply[0..@min(parts.reply.len, out.reply.len)]; @@ -404,13 +404,13 @@ const LivePalette = struct { for (&base, synthesized) |*dst, src| dst.* = asGhostRgb(src); } - const key: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; - if (self.key) |old| if (std.meta.eql(old, key)) return &self.colors; + const wanted: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; + if (self.key) |old| if (std.meta.eql(old, wanted)) return &self.colors; var seed = GColor.default; for (base, 0..) |rgb, i| seed[i] = rgb; self.colors = GColor.generate256Color(seed, .empty, bg, fg, false); - self.key = key; + self.key = wanted; return &self.colors; } }; @@ -620,16 +620,21 @@ pub fn replies(state: *State) []const u8 { return state.reply[0..state.reply_len]; } -/// DECSET 2004: the program wants its pastes bracketed. -pub fn bracketedPaste(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - return state.vt.modes.get(.bracketed_paste); -} - -/// The program tracks the mouse itself, so a click in its body is its event. -pub fn reportsMouse(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - return state.vt.flags.mouse_event != .none; +/// The modes its program set that the core decides by (`Term.Modes`). +pub fn modes(state: ?*const State) Term.Modes { + const s = state orelse return .{}; + const alternate = s.vt.screens.active_key == .alternate; + const mouse_event = s.vt.flags.mouse_event != .none; + return .{ + .mouse = mouse_event, + .all_motion = s.vt.flags.mouse_event == .any, + // On the alternate screen, which has no scrollback, alternate + // scroll (DECSET 1007, on unless turned off) asks for arrow keys. + .wheel = mouse_event or (alternate and s.vt.modes.get(.mouse_alternate_scroll)), + .focus = s.vt.modes.get(.focus_event), + .bracketed_paste = s.vt.modes.get(.bracketed_paste), + .alternate = alternate, + }; } /// A paste as xterm makes one (ghostty's encoder): the control bytes a @@ -637,35 +642,10 @@ pub fn reportsMouse(pane: *const Pane) bool { /// 2004's brackets early, NUL, ^C and the rest of xterm's list) become /// spaces, then the text goes inside the brackets when the program set /// 2004, else with its newlines as Returns. `text` is rewritten in place. -pub fn encodePaste(pane: *const Pane, text: []u8) [3][]const u8 { - return ghostty_vt.input.encodePaste(text, .{ .bracketed = bracketedPaste(pane) }); +pub fn paste(state: ?*const State, text: []u8) [3][]const u8 { + return ghostty_vt.input.encodePaste(text, .{ .bracketed = modes(state).bracketed_paste }); } -/// DECSET 1004: the program wants to hear when it gains and loses focus. -pub fn reportsFocus(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - return state.vt.modes.get(.focus_event); -} - -/// ...every move of it, a button down or not (1003). -pub fn tracksAllMotion(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - return state.vt.flags.mouse_event == .any; -} - -/// A wheel over the program is the program's: it tracks the mouse, or it is -/// on the alternate screen, which has no scrollback, with alternate scroll -/// (DECSET 1007, on unless turned off) asking for arrow keys instead. -pub fn ownsWheel(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - return reportsMouse(pane) or - (state.vt.screens.active_key == .alternate and state.vt.modes.get(.mouse_alternate_scroll)); -} - -pub const MouseMods = struct { shift: bool = false, alt: bool = false, ctrl: bool = false }; -pub const MouseButton = enum { left, middle, right, wheel_up, wheel_down, wheel_left, wheel_right }; -pub const MouseAction = enum { press, release, motion }; - /// One mouse event for the program, as xterm reports it (ctlseqs; ghostty's /// encoder): the tracking mode it set (1000 clicks, 1002 drags, 1003 all /// motion) decides whether it hears of it, the format it set (1006 SGR, @@ -673,8 +653,7 @@ pub const MouseAction = enum { press, release, motion }; /// ctrl+16. `col`,`row` are the 0-based grid cell; a drag that left the /// grid is reported clamped to its edge, motion only when the cell /// changed. Empty when the program does not hear of it. -pub fn mouseBytes(pane: *Pane, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { - const state = pane.terminal orelse return &.{}; +pub fn mouse(state: *State, buf: *[64]u8, action: Term.MouseAction, button: ?Term.MouseButton, mods: Term.MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { const input = ghostty_vt.input; var writer = std.Io.Writer.fixed(buf); var opts: input.MouseEncodeOptions = .{ @@ -714,17 +693,17 @@ pub fn mouseBytes(pane: *Pane, buf: *[64]u8, action: MouseAction, button: ?Mouse /// The bytes a wheel turn at grid cell `col`,`row` (0-based) sends the /// program: its mouse report while it tracks the mouse, else, on the /// alternate screen, an arrow key in the cursor keys' mode (none for a -/// sideways turn). Null when the wheel is not the program's (`ownsWheel`). -pub fn wheelBytes(pane: *Pane, buf: *[64]u8, wheel: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8 { - const state = pane.terminal orelse return null; - if (!ownsWheel(pane)) return null; +/// sideways turn). Null when the wheel is not the program's (`Modes.wheel`). +pub fn wheel(state: *State, buf: *[64]u8, turn: Term.MouseButton, col: u16, row: u16, mods: Term.MouseMods) ?[]const u8 { + const now = modes(state); + if (!now.wheel) return null; const m = &state.vt.modes; - if (!reportsMouse(pane)) return switch (wheel) { + if (!now.mouse) return switch (turn) { .wheel_up => if (m.get(.cursor_keys)) "\x1bOA" else "\x1b[A", .wheel_down => if (m.get(.cursor_keys)) "\x1bOB" else "\x1b[B", else => null, }; - return mouseBytes(pane, buf, .press, wheel, mods, col, row, false); + return mouse(state, buf, .press, turn, mods, col, row, false); } /// The whole scrollback as plain text, `gpa`-owned: what a terminal's body @@ -891,8 +870,8 @@ pub fn feed(state: *State, bytes: []const u8, track: []const i32, rows: []i32, e return .{ .rows = rows[0..0], .erased = erased[0..0], .cleared = false, .alive = true, .failed = false }; } const screens = &state.vt.screens; - const key = screens.active_key; - const generation = screens.generation(key); + const active = screens.active_key; + const generation = screens.generation(active); const pages = &screens.active.pages; var failed = false; var room: [512]RowPin = undefined; @@ -910,7 +889,7 @@ pub fn feed(state: *State, bytes: []const u8, track: []const i32, rows: []i32, e ingest(state, bytes); const cleared = state.vt.flags.dirty.clear; // RIS can destroy the alternate screen and every pin it owned. - const alive: ?*ghostty_vt.PageList = if (screens.generation(key) == generation) pages else null; + const alive: ?*ghostty_vt.PageList = if (screens.generation(active) == generation) pages else null; for (pins, rows[0..track.len], erased[0..track.len]) |pin, *row, *gone| { row.* = pinnedRow(alive, pin); gone.* = alive != null and pin.pin != null and pin.pin.?.garbage; @@ -919,12 +898,6 @@ pub fn feed(state: *State, bytes: []const u8, track: []const i32, rows: []i32, e return .{ .rows = rows[0..track.len], .erased = erased[0..track.len], .cleared = cleared, .alive = alive != null, .failed = failed }; } -/// A full-screen program has the emulator on its alternate screen. -pub fn onAlternateScreen(pane: *const Pane) bool { - const state = pane.terminal orelse return false; - return state.vt.screens.active_key == .alternate; -} - /// Whether a new terminal's greeting may be typed now: only at the shell's /// first prompt (pardes's own marks: no command started; a prompt drawn /// again for a resize is the same first prompt), with nothing @@ -1022,18 +995,16 @@ pub fn promptInputEmpty(pane: *const Pane) bool { return true; } -/// Encode one key for the program that owns a raw terminal and queue its pty -/// write, respecting the application's keyboard protocol and terminal modes. -pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { - const pane = p.panes[id] orelse return; - const state = pane.terminal orelse return; +/// One key for its program, as the program's keyboard protocol and modes +/// ask for it, written to `out`. +pub fn key(state: *State, k: Key, out: *std.Io.Writer) !void { const input = ghostty_vt.input; const function_keys = comptime keys: { var keys: [Key.f25 - Key.f1 + 1]input.Key = undefined; - for (&keys, 1..) |*k, n| k.* = @field(input.Key, std.fmt.comptimePrint("f{d}", .{n})); + for (&keys, 1..) |*slot, n| slot.* = @field(input.Key, std.fmt.comptimePrint("f{d}", .{n})); break :keys keys; }; - const physical: input.Key = switch (key.cp) { + const physical: input.Key = switch (k.cp) { Key.enter => .enter, Key.backspace => .backspace, Key.tab => .tab, @@ -1052,32 +1023,25 @@ pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { Key.scroll_lock => .scroll_lock, Key.pause => .pause, Key.menu => .context_menu, - Key.f1...Key.f25 => function_keys[key.cp - Key.f1], - else => if (key.cp < 128) input.Key.fromASCII(@intCast(key.cp)) orelse .unidentified else .unidentified, + Key.f1...Key.f25 => function_keys[k.cp - Key.f1], + else => if (k.cp < 128) input.Key.fromASCII(@intCast(k.cp)) orelse .unidentified else .unidentified, }; var utf8: [4]u8 = undefined; - const text_cp = if (key.shift and key.cp >= 'a' and key.cp <= 'z') key.cp - 'a' + 'A' else key.cp; + const text_cp = if (k.shift and k.cp >= 'a' and k.cp <= 'z') k.cp - 'a' + 'A' else k.cp; // A key with no text of its own types its code point only when that // is a character: the kitty keyboard protocol numbers function and // modifier keys in the private use area (F3 is U+E016), and a shell // was typed those as junk. - const text = if (key.text.len > 0) key.text else if (key.cp >= 32 and key.cp < Key.up and key.cp != Key.backspace and !(key.cp >= 0xE000 and key.cp <= 0xF8FF)) + const text = if (k.text.len > 0) k.text else if (k.cp >= 32 and k.cp < Key.up and k.cp != Key.backspace and !(k.cp >= 0xE000 and k.cp <= 0xF8FF)) utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return] else ""; - // A key's text has no bound of its own (an input method's commit, a - // paste as one key): past the stack's room the encoding grows on the - // heap, and emitWrite cuts it into writes. - var room: [256]u8 = undefined; - var first: std.heap.BufferFirstAllocator = .init(&room, p.gpa); - var out: std.Io.Writer.Allocating = .init(first.allocator()); - defer out.deinit(); - input.encodeKey(&out.writer, .{ + try input.encodeKey(out, .{ .key = physical, - .mods = .{ .ctrl = key.ctrl, .alt = key.alt, .shift = key.shift }, - .consumed_mods = .{ .shift = key.text.len > 0 and key.shift }, + .mods = .{ .ctrl = k.ctrl, .alt = k.alt, .shift = k.shift }, + .consumed_mods = .{ .shift = k.text.len > 0 and k.shift }, .utf8 = text, - .unshifted_codepoint = if (key.cp >= 'A' and key.cp <= 'Z') key.cp - 'A' + 'a' else if (key.cp < Key.up) key.cp else 0, + .unshifted_codepoint = if (k.cp >= 'A' and k.cp <= 'Z') k.cp - 'A' + 'a' else if (k.cp < Key.up) k.cp else 0, }, options: { var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); // fromTerminal cannot know this one and says so, defaulting to @@ -1091,49 +1055,32 @@ pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { // the floor and forwards Alt-n to the child as a bare `n`. opts.macos_option_as_alt = .true; break :options opts; - }) catch |err| return p.reportError(id, "key", err); - if (out.written().len > 0) p.emitWrite(id, out.written()); + }); } -pub fn enterTty(p: *Pardes, id: usize) void { - const pane = p.panes[id] orelse return; - const selected = pane.rawPointerText(pane.sel[@backingInt(config.select_button)]) != null; - if (!selected and pane.terminal != null and pane.body.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { - const screen = pane.terminal.?.vt.screens.active; - const goff: i32 = @intCast(screen.pages.scrollbar().offset); - const vp_row = pane.gridRow(pane.body.cur_row) - goff; - if (vp_row < 0) break :handoff; - - var grid_col: i32 = @max(0, pane.body.cur_col); - if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(vp_row) } })) |row_pin| { - if (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) { - .cut => |cols| grid_col += @intCast(cols), - .keep, .blank => {}, - }; - } - const click_pin = screen.pages.pin(.{ - .viewport = .{ .x = @intCast(grid_col), .y = @intCast(vp_row) }, - }) orelse break :handoff; - const cursor_pin = screen.cursor.page_pin.*; - var prompts = cursor_pin.promptIterator(.left_up, null); - const prompt_pin = prompts.next() orelse break :handoff; - if (click_pin.before(prompt_pin)) break :handoff; - const moves = screen.promptClickMove(click_pin); - for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); - for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); +/// How many cells left or right of the cursor a click on viewport row +/// `row`, column `col` of the text shown (the prompt cut off) is, at the +/// prompt the cursor is at: what moves the shell's cursor there. Null +/// when the cursor is at no prompt, or the click is before the prompt. +pub fn promptMoves(state: *State, row: i32, col: i32) ?Term.Moves { + if (!state.vt.cursorIsAtPrompt() or row < 0) return null; + const screen = state.vt.screens.active; + var grid_col: i32 = @max(0, col); + if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(row) } })) |row_pin| { + if (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) { + .cut => |cols| grid_col += @intCast(cols), + .keep, .blank => {}, + }; } - - pane.body.mode = .tty; - pane.followOutput(); // entering raw mode is a request for the live shell - pane.body.vsel.active = false; - pane.body.nsel = 0; - // The raw renderer follows the live cursor. A captured mouse selection - // keeps its modal endpoint for the next return to editor mode. - pane.body.cur_pinned = selected; - pane.body.select = false; - pane.body.restore_cursor = false; - pane.body.sticky_col = -1; - pane.body.normal.clear(); + const click_pin = screen.pages.pin(.{ + .viewport = .{ .x = @intCast(grid_col), .y = @intCast(row) }, + }) orelse return null; + const cursor_pin = screen.cursor.page_pin.*; + var prompts = cursor_pin.promptIterator(.left_up, null); + const prompt_pin = prompts.next() orelse return null; + if (click_pin.before(prompt_pin)) return null; + const moves = screen.promptClickMove(click_pin); + return .{ .left = moves.left, .right = moves.right }; } // Returned slices remain valid until the next cache rebuild or reset. @@ -2254,8 +2201,7 @@ test "document construction allocates only the pane and has inert terminal defau try std.testing.expect(!failing.has_induced_failure); try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes); try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); - try std.testing.expect(!bracketedPaste(pane)); - try std.testing.expect(!reportsMouse(pane)); + try std.testing.expectEqual(Term.Modes{}, modes(pane.terminal)); try std.testing.expect(!promptInputReady(pane)); pane.scrollBy(100); pane.followOutput(); @@ -2724,7 +2670,7 @@ test "terminal Filter holds every projected foreground off the page" { p.settings.theme = @intCast(t); var fc = FilteredColors.init(p, &pane.terminal.?.vt); var refused: usize = 0; - for (fc.target, 0..) |projected, key| { + for (fc.target, 0..) |projected, slot| { const ink = fc.legible(projected); try testing.expect(ink.contrast(fc.default_bg) >= config.tty_filter_min_contrast); if (!ink.eql(projected)) { @@ -2735,7 +2681,7 @@ test "terminal Filter holds every projected foreground off the page" { } // The key a background asks for is handed back untouched, including // the one whose value is the page itself. - try testing.expect(fc.keyedRgb(GColor.default[key]).eql(fc.target[fc.nearestKey(GColor.default[key])])); + try testing.expect(fc.keyedRgb(GColor.default[slot]).eql(fc.target[fc.nearestKey(GColor.default[slot])])); } // Every curated theme owns at least one collapsing key — that is why // the floor exists — and the floor must not be flattening the palette. |
