From 310c219386426691adea9228633113addd6252e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9B=B7=E7=94=B5=E8=8A=BD=E8=A1=A3?= Date: Sat, 17 Oct 2026 00:03:34 -0400 Subject: [PATCH] T35: review round 1: the tap holds an OSC that may be a mark until it ends and reads it as the session does, so 133;AB makes no prompt; each prompt's link carries the prompt's number, so a blank row within a prompt keeps one start; a program's own link keeps its cells and a prompt's link takes up again after it; controls vte runs in an escape go on before the link --- AGENTS.md | 2 +- src/term/prompts.rs | 317 +++++++++++++++++++++++++------------- src/term/prompts/tests.rs | 231 +++++++++++++++++---------- src/term/tap.rs | 16 +- tasks/acceptance.md | 2 +- 5 files changed, 368 insertions(+), 200 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 42332a0..06d7615 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -97,4 +97,4 @@ ELYTerminal. A terminal on GPUI and Ely components. `PRD.md` says what it does; - 2026-10-16: the main window opens at the size it was left at, which the owner asked for on macOS, Windows and Linux: `window_width` and `window_height` in the settings hold the size gpui's `window_bounds` gives 0.5 s after the bounds settle, saved through `SettingsStore::update`, which writes only a change, so a drag saves once and a move saves nothing. A maximized, full-screen or hidden window keeps the size from before; its state and size are read once they settle, since X11 marks a window maximized after its new size, gpui's X11 window then gives a maximized window's own size, and it calls a maximized window unmaximized while minimized. A window that shows again, uncovered, restored or back on its screen, is read again, so a size it took just before it hid is kept; a size it takes in the half second before it closes, or before it hides until the app quits, is lost. The window is no smaller than 100 by 100, the least the settings keep, or a smaller size the platform allows could not be kept. The window opens centered at whole points, since macOS grows a window by a point on a side whose edge falls on a half point; its place is not kept, and a kept side past the primary display's visible area shrinks to it, logged. A size outside 100 to 16384 stops the start, as any value out of range does. - 2026-10-16: the sessions and right columns resize by a drag on their border toward the terminal, which the owner asked for on macOS, Windows and Linux. Ely's `ShellColumn::resizable`, added to Ely for this, puts Ely's `resize_handle` on the border toward the filling column, the sessions column's right and the right column's left: the handle draws that border, a filled hairline, since gpui paints a border no wider than half its box, and the line it drew at first showed half a pixel on macOS and none on X11; it occludes the header under it, so a press there drags the border, not the window, on Windows too, where an unoccluded drag region takes the press as the caption. A drag sets off from the wider of the width drawn and the one kept: a header's parts may hold a column wider, and a window too narrow for both widths squeezes them, where a drag from the squeezed width jumped back against the pointer; a drag that has not moved sideways changes nothing, and one that comes back where it set off gives the width it had. A set width in Ely became a flex basis, so a column holds its header's own parts: at a set width under them, Windows' caption buttons ran out of the window. The widths, 160 to 960 pixels, show at once and are saved in `sessions_width` and `panel_width` through `SettingsStore::update` 0.5 s after a drag rests, as the window's size is; a drag in the half second before the window closes is lost, and a save the store refuses puts the columns back. A window too narrow for both yields the terminal its header's width, as Ely's set widths give way. - 2026-10-16: prompts and commands carry OSC 133 marks, which the owner asked for, read as Ghostty reads them: A or N starts a prompt, B or I ends it, C starts a command's output, and D ends the command with its status, D's first option, none when that is no number. The tap reads any program's marks before the parser, so it never sees the cursor: A's fresh line and L, which need it, are not done, and P adds nothing to A. Each session keeps the status its last command ended with. The integration marks what the shell leaves unmarked, and the user's prompt still sees the command's status. zsh: precmd reads `$?` and sends D after a command ran, preexec sends C, and a last precmd hook wraps PS1 in A and B under `prompt_percent`, which the first prompt says while it is off; it moves to the end of `precmd_functions` at each prompt, since a theme that sets PS1 in a hook of its own loads after it, and at the first prompt `sched +0` wraps it once more, since zsh runs due events after every precmd hook; that call returns the command's status, which the prompt shows, but it would reset `$pipestatus`, so it serves the first prompt alone. bash: PROMPT_COMMAND's first entry reads `$?`, which each entry resets, and its last wraps PS1. From bash 4.4 PS0 sends C and its subscript notes that a command ran, since bash prints no PS0 for an empty line, and the first entry sends D for it; both need `promptvars`, on by default. macOS's bash 3.2 has no PS0 and nothing else between reading a line and running it: its DEBUG trap runs for a key binding's command (`bind -x`) as for a typed one, with nothing to tell the two apart, runs for no line that is only a subshell, and under `extdebug` its status decides whether a command runs. So bash 3.2 sends no C, and Ghostty's automatic integration skips bash 3.2. Its D comes from PS1 once `\#`, the command number, has moved, which neither a key binding nor an empty line does; readline sends a prompt's escapes again at each redraw, so that D goes again with it, the same status. Every mark of a command rides an expansion, which `promptvars` turns on, so while it is off at start the script says so rather than mark nothing without a word. fish 4.3 marks its own prompts and commands, fish 4.0 all but B, older ones none: the script adds what the running fish lacks, around the prompt shown, and wraps it again when the user's changes. PowerShell: the prompt reads `$?` first and sets it back for the user's prompt through `Write-Error '' -ErrorAction Ignore`, which adds nothing to `$Error`. A failure ends with `$LASTEXITCODE` when a program set it during the line, since each run stores a new object, equal or not, which `[object]::ReferenceEquals` tells apart, unless the line surely ends in PowerShell: its syntax tree, read as PSReadLine hands the line over, ends in a cmdlet, as `Get-Command` resolves the name, aliases through, in a name not found, or in no command; such a line ends with 1, a cmdlet's failure under `-ErrorAction Ignore` too. A line that ends in a block, a function, a script or a call through a variable takes the code of a program it ran: only a hook on every command lookup would name the last command run, and it slowed a loop of commands by half. `$LASTEXITCODE` is read through `Get-Variable`, since strict mode refuses an unset variable and a prompt that fails falls back to `PS>`. C goes out when PSReadLine hands over a line that is not blank; without PSReadLine the script says it marks no command. herdr passes no OSC 133 on, so a session running herdr keeps the status from before it. -- 2026-10-16: the view jumps between prompts, which the owner asked for, as Ghostty jumps: Cmd-Up and Cmd-Down, with Shift or without, on macOS, Ctrl-Shift-Up and Ctrl-Shift-Down elsewhere, scroll to the prompt that starts before or after the view's top; a prompt on the screen's last page means the bottom, which the view cannot pass, and with none there nothing moves. alacritty's rows hold no marks, and the tap, which reads before the parser, never sees the cursor, so the tap rewrites each mark in place, at its own length, into an OSC 8 link of the terminal's own, which the parser handles in step with the text: `ESC ] 133;A`, or N, opens a link to `\x7f`, a target no program names, B, I, C and D close it, and the options after the letter become NULs, which vte skips inside an OSC. A mark's first bytes wait for the next read until its letter shows, 64 at most, and show nothing meanwhile, since an OSC shows nothing. The parser stamps each cell a prompt prints with the link, SGR 0 keeps it, and each open gets an id of alacritty's own, so the link rides the cells through scroll, reflow and history, and a prompt starts on the first row that shows its link. Links, Cmd-press among them, pass over it. The tap's OSC scanner ends a body as vte does, at BEL, ESC, CAN or SUB, and skips the controls vte skips, so a mark and its link agree. A prompt that opens an OSC 8 link of its own first loses the mark on those cells. +- 2026-10-16: the view jumps between prompts, which the owner asked for, as Ghostty jumps: Cmd-Up and Cmd-Down, with Shift or without, on macOS, Ctrl-Shift-Up and Ctrl-Shift-Down elsewhere, scroll to the prompt that starts before or after the view's top; a prompt on the screen's last page means the bottom, which the view cannot pass, and with none there nothing moves. alacritty's rows hold no marks, and the tap, which reads before the parser, never sees the cursor, so the tap rewrites what goes to the parser: an OSC that may be a mark is held whole until it ends and read as `marks` reads it, and a prompt's start becomes an OSC 8 link of the terminal's own, its target `\x7f`, which no program names, its id the prompt's number; the prompt's end closes it. The parser stamps each cell the prompt prints with the link, SGR 0 keeps it, and it rides the cells through scroll, reflow and history; a prompt starts on the first row that shows its number, blank rows within it passed. A program's own link keeps its cells: a prompt that starts inside one leaves it open, and its end inside a prompt opens the prompt's link again; a cursor restore that brings back a link passes the rewrite by. An OSC held, a body of 4096 bytes at most as the scanner keeps it and twice that with the controls vte skips, shows nothing until it ends; controls vte runs inside an escape go on first. A rewrite adds at most 14 bytes to a sequence of 6 or more, so the tap reads a quarter of the buffer's room. Links, Cmd-press among them, pass over the prompt's link. The tap's OSC scanner ends a body as vte does, at BEL, ESC, CAN or SUB, and skips the controls vte skips, so a mark and its link agree. diff --git a/src/term/prompts.rs b/src/term/prompts.rs index 2fee022..09d2ccc 100644 --- a/src/term/prompts.rs +++ b/src/term/prompts.rs @@ -1,159 +1,264 @@ use alacritty_terminal::{ - grid::{Dimensions, Scroll}, + grid::{Dimensions, Row, Scroll}, index::Line, - term::{ - Term, - cell::{Cell, Hyperlink}, - }, + term::{Term, cell::Cell}, }; use gpui::Context; -use super::view::TerminalView; +use super::{tap::MOST, view::TerminalView}; -/// The target of the OSC 8 link each prompt mark becomes; no program names a link so. +/// The target of the OSC 8 links prompts become, each named by its prompt's number; no program names a link so. pub(crate) const LINK: &str = "\u{7f}"; -/// The most bytes a mark's start may span, ignored controls in it too. -const MOST: usize = 64; +/// What ends a prompt's link. +const CLOSE: &[u8] = b"\x1b]8;;\x07"; const ESC: u8 = 0x1b; +/// Controls vte skips inside an OSC. +fn ignored(byte: u8) -> bool { + matches!(byte, 0x00..=0x06 | 0x08..=0x17 | 0x19 | 0x1c..=0x1f) +} + #[derive(Clone, Copy, Debug, Default, PartialEq)] enum State { #[default] Ground, - /// An ESC at this index, which may start a mark. - Escape(usize), - /// Inside `ESC ]` from this index, with this much of `133;` matched. - Body(usize, usize), - /// Past a rewritten mark's letter, its options blanked to the end. - Options, + /// After an ESC, held until the next byte says whether an OSC starts. + Escape, + /// An OSC held whole, since it may be a mark or a link to rewrite. + Held, + /// An OSC passed on as it comes. + Passing, } -/// Turns each OSC 133 mark into an OSC 8 link as it passes to the parser, so the parser marks the cells each prompt prints. +/// Rewrites what goes to the parser so it stamps each prompt's cells with a link of its own, numbered per prompt. #[derive(Default)] pub(crate) struct Prompts { state: State, - /// A mark's start, held from the parser until its letter shows. + /// The escape or OSC held, from its ESC. held: Vec, -} - -/// Controls vte skips inside a sequence. -fn ignored(byte: u8) -> bool { - matches!(byte, 0x00..=0x06 | 0x08..=0x17 | 0x19 | 0x1c..=0x1f) + /// The OSC's body as vte reads it, the controls it skips left out. + body: Vec, + /// The body passed the scanner's bound, so it counts for nothing. + overflow: bool, + /// The prompt open now, from its start mark to its end. + prompt: Option, + /// A program's own link is open. + user: bool, + /// The last prompt's number. + count: u32, + /// What goes to the parser from the last read. + out: Vec, } impl Prompts { - /// The bytes held from the last read, which go before the next. + /// The bytes held from earlier reads. pub fn held(&self) -> usize { self.held.len() } - /// Rewrites the marks in `buf[..held + read]`, the held bytes put first; returns how many bytes go on. - pub fn pass(&mut self, buf: &mut [u8], read: usize) -> usize { - let from = self.held.len(); - buf[..from].copy_from_slice(&self.held); - self.held.clear(); - let end = from + read; - for at in from..end { - let byte = buf[at]; - self.state = match self.state { - State::Ground if byte == ESC => State::Escape(at), - State::Ground => State::Ground, - State::Escape(start) => match byte { - b']' => State::Body(start, 0), - ESC => State::Escape(at), - // vte runs these and stays in the escape. - byte if byte == 0x07 || ignored(byte) => State::Escape(start), - _ => State::Ground, - }, - State::Body(start, seen) => match byte { - ESC => State::Escape(at), - 0x07 | 0x18 | 0x1a => State::Ground, - byte if ignored(byte) => State::Body(start, seen), - byte if seen < 4 && byte == b"133;"[seen] => State::Body(start, seen + 1), - byte if seen == 4 => match byte { - b'A' | b'N' => link(&mut buf[start..=at], true), - b'B' | b'I' | b'C' | b'D' => link(&mut buf[start..=at], false), - _ => State::Ground, - }, - _ => State::Ground, - }, - State::Options => match byte { - ESC => State::Escape(at), - 0x07 | 0x18 | 0x1a => State::Ground, - byte if ignored(byte) => State::Options, - _ => { - buf[at] = 0; - State::Options - } - }, - }; + /// What goes to the parser for `read`: marks become links, and a held start waits for its end. + pub fn pass(&mut self, read: &[u8]) -> &[u8] { + self.out.clear(); + for &byte in read { + self.step(byte); } - match self.state { - State::Escape(start) | State::Body(start, _) if end - start <= MOST => { - self.held.extend_from_slice(&buf[start..end]); - self.state = match self.state { - State::Body(_, seen) => State::Body(0, seen), - _ => State::Escape(0), - }; - start + &self.out + } + + fn step(&mut self, byte: u8) { + self.state = match (self.state, byte) { + (State::Ground, ESC) => { + self.held.push(ESC); + State::Escape } - State::Escape(_) | State::Body(..) => { - log::warn!("pty: a mark's start over {MOST} bytes passes as it came"); - self.state = State::Ground; - end + (State::Ground, _) => { + self.out.push(byte); + State::Ground } - State::Ground | State::Options => end, + (State::Escape, b']') => { + // Controls vte ran inside the escape go on first, as it ran them. + self.out.extend(self.held.drain(1..)); + self.held.push(byte); + self.body.clear(); + self.overflow = false; + State::Held + } + (State::Escape, ESC) => { + self.release(); + self.held.push(ESC); + State::Escape + } + // vte runs these and stays in the escape. + (State::Escape, _) if byte == 0x07 || ignored(byte) => { + self.held.push(byte); + State::Escape + } + (State::Escape, _) => { + // A full reset clears the link the parser writes with. + if byte == b'c' { + (self.prompt, self.user) = (None, false); + } + self.held.push(byte); + self.release(); + State::Ground + } + (State::Held | State::Passing, 0x07 | 0x18 | 0x1a) => { + self.end(Some(byte)); + State::Ground + } + (State::Held | State::Passing, ESC) => { + self.end(None); + self.held.push(ESC); + State::Escape + } + (State::Held, _) => { + self.held.push(byte); + self.read(byte); + if self.wanted() { + State::Held + } else { + self.release(); + State::Passing + } + } + (State::Passing, _) => { + self.out.push(byte); + self.read(byte); + State::Passing + } + }; + } + + /// Adds `byte` to the body as the tap's scanner does; skipped controls bound the bytes held too. + fn read(&mut self, byte: u8) { + if self.held.len() > 2 * MOST { + self.overflow = true; + } + if ignored(byte) { + return; + } + if self.body.len() < MOST { + self.body.push(byte); + } else { + self.overflow = true; + } + } + + /// Whether the OSC held may be a mark, or a link that ends inside a prompt, within the scanner's bounds. + fn wanted(&self) -> bool { + let fits = |prefix: &[u8]| { + let length = self.body.len().min(prefix.len()); + self.body[..length] == prefix[..length] + }; + !self.overflow && (fits(b"133;") || (self.prompt.is_some() && fits(b"8;"))) + } + + fn release(&mut self) { + self.out.append(&mut self.held); + } + + /// The OSC ends at `end`, BEL, CAN or SUB, or at an ESC when none. + fn end(&mut self, end: Option) { + let rewrite = if self.overflow { + None + } else if let Some(opens) = self.body.strip_prefix(b"133;").and_then(mark) { + if opens { + self.count = self.count.wrapping_add(1); + self.prompt = Some(self.count); + (!self.user).then(|| link(self.count)) + } else { + let closes = self.prompt.take().is_some() && !self.user; + closes.then(|| CLOSE.to_vec()) + } + } else if let Some(opens) = user(&self.body) { + self.user = opens; + // The program's link ends inside a prompt: the prompt's link takes up again. + self.prompt.filter(|_| !opens).map(link) + } else { + None + }; + match (rewrite, self.state) { + (Some(bytes), State::Held) => { + self.held.clear(); + self.out.extend_from_slice(&bytes); + // CAN and SUB end the OSC and run as well. + self.out.extend(end.filter(|&byte| byte != 0x07)); + } + (_, State::Held) => { + self.held.extend(end); + self.release(); + } + _ => self.out.extend(end), } } } -/// Makes `ESC ] 133;X` an OSC 8 link of the terminal's own: opened at a prompt's start, else closed. -fn link(span: &mut [u8], open: bool) -> State { - let bytes = [b'8', b';', b';', if open { 0x7f } else { 0 }, 0]; - let body = span - .iter() - .position(|&byte| byte == b']') - .expect("a mark holds its ]") - + 1; - let mut next = bytes.into_iter(); - for byte in span[body..].iter_mut().filter(|byte| !ignored(**byte)) { - *byte = next.next().expect("a mark's five bytes"); +/// Whether a mark's body opens a prompt or ends one, as `marks::read` reads its letter; none for neither. +fn mark(body: &[u8]) -> Option { + let (&letter, rest) = body.split_first()?; + if !rest.is_empty() && rest[0] != b';' { + return None; + } + match letter { + b'A' | b'N' => Some(true), + b'B' | b'I' | b'C' | b'D' => Some(false), + _ => None, } - State::Options } -/// The prompt link a cell carries. -fn prompt_link(cell: &Cell) -> Option { - cell.hyperlink().filter(|link| link.uri() == LINK) +/// Whether an OSC 8 body opens a program's link, as alacritty reads its target; none for no link at all. +fn user(body: &[u8]) -> Option { + let rest = body.strip_prefix(b"8;")?; + let target = &rest[rest.iter().position(|&byte| byte == b';')? + 1..]; + // alacritty joins the target's parts with `;`, each one empty when it is not UTF-8. + Some( + target.contains(&b';') + || std::str::from_utf8(target).is_ok_and(|target| !target.is_empty()), + ) } -/// The prompt `line` shows. -fn prompt(term: &Term, line: Line) -> Option { - term.grid()[line].into_iter().find_map(prompt_link) +/// The OSC 8 link that marks prompt `number`'s cells. +fn link(number: u32) -> Vec { + format!("\x1b]8;id={number};{LINK}\x07").into_bytes() } -/// Whether `line` starts a prompt: it shows one the line above does not. -fn starts(term: &Term, line: Line) -> bool { - prompt(term, line).is_some_and(|link| { - line == term.topmost_line() || prompt(term, line - 1).as_ref() != Some(&link) +/// The number of the prompt `row` shows, as its link names it. +fn prompt(row: &Row) -> Option { + row.into_iter().find_map(|cell| { + let link = cell.hyperlink().filter(|link| link.uri() == LINK)?; + link.id().parse().ok() }) } /// The display offset that puts the prompt before or after the view's top at the top, as Ghostty jumps. pub fn jump(term: &Term, up: bool) -> Option { - let top = Line(-(term.grid().display_offset() as i32)); - // ponytail: a scan of every row on the way; index prompt rows if long histories lag. + let top = -(term.grid().display_offset() as i32); + let (first, last) = (term.topmost_line().0, term.bottommost_line().0); + let number = |line: i32| prompt(&term.grid()[Line(line)]); + // ponytail: a scan of the rows on the way; index prompt rows if long histories lag. let found = if up { - let mut lines = (term.topmost_line().0..top.0).rev().map(Line); - lines.find(|&line| starts(term, line)) + // The nearest prompt above the view's top, then its first row, blank rows within it passed. + let (line, own) = (first..top) + .rev() + .find_map(|line| number(line).map(|own| (line, own)))?; + let mut start = line; + for above in (first..line).rev() { + match number(above) { + Some(other) if other != own => break, + Some(_) => start = above, + None => {} + } + } + start } else { - let mut lines = (top.0 + 1..=term.bottommost_line().0).map(Line); - lines.find(|&line| starts(term, line)) - }?; + // The prompt at or above the view's top may go on below it; the next one starts. + let here = (first..=top).rev().find_map(number); + (top + 1..=last).find(|&line| number(line).is_some_and(|other| Some(other) != here))? + }; // A prompt on the screen means the bottom, which the view cannot pass. - Some((-found.0).max(0) as usize) + Some((-found).max(0) as usize) } impl TerminalView { diff --git a/src/term/prompts/tests.rs b/src/term/prompts/tests.rs index 5d05d96..5313bde 100644 --- a/src/term/prompts/tests.rs +++ b/src/term/prompts/tests.rs @@ -6,37 +6,72 @@ use alacritty_terminal::{ }; use super::*; +use crate::term::marks::{self, Mark}; /// What the parser gets from `chunks`, each one read. fn passed(chunks: &[&[u8]]) -> Vec { let mut prompts = Prompts::default(); let mut out = Vec::new(); for chunk in chunks { - let held = prompts.held(); - let mut buf = vec![0; held + chunk.len()]; - buf[held..].copy_from_slice(chunk); - let count = prompts.pass(&mut buf, chunk.len()); - out.extend_from_slice(&buf[..count]); + out.extend_from_slice(prompts.pass(chunk)); } out } -#[test] -fn a_mark_becomes_a_link_of_the_same_length() { - assert_eq!(passed(&[b"\x1b]133;A\x07"]), b"\x1b]8;;\x7f\0\x07"); - assert_eq!(passed(&[b"\x1b]133;N\x07"]), b"\x1b]8;;\x7f\0\x07"); - assert_eq!(passed(&[b"\x1b]133;B\x1b\\"]), b"\x1b]8;;\0\0\x1b\\"); - assert_eq!(passed(&[b"\x1b]133;D;1\x07"]), b"\x1b]8;;\0\0\0\0\x07"); - assert_eq!( - passed(&[b"\x1b]133;A;k=i\x07x"]), - b"\x1b]8;;\x7f\0\0\0\0\0\x07x" +/// A terminal `columns` wide and `lines` high after `bytes` passed through the rewrite. +fn parsed(bytes: &[u8], columns: usize, lines: usize) -> Term { + let mut term = Term::new( + Config::default(), + &TermSize::new(columns, lines), + VoidListener, ); - assert_eq!(passed(&[b"\x1b]1\x0033;C\x07"]), b"\x1b]8\x00;;\0\0\x07"); + let mut parser: Processor = Processor::new(); + parser.advance(&mut term, &passed(&[bytes])); + term +} + +/// The target of the link at a cell. +fn target(term: &Term, line: i32, column: usize) -> Option { + let cell = &term.grid()[Line(line)][Column(column)]; + cell.hyperlink().map(|link| link.uri().to_string()) } #[test] -fn a_mark_split_across_reads_waits_for_its_letter() { - let whole: &[u8] = b"a\x1b]133;A;k=i\x07$ \x1b]133;B\x1b\\b"; +fn a_mark_becomes_its_prompt_s_numbered_link() { + assert_eq!( + passed(&[b"\x1b]133;A\x07$ \x1b]133;B\x1b\\x"]), + b"\x1b]8;id=1;\x7f\x07$ \x1b]8;;\x07\x1b\\x" + ); + assert_eq!( + passed(&[b"\x1b]133;A;k=i\x07\x1b]133;D;1\x18"]), + b"\x1b]8;id=1;\x7f\x07\x1b]8;;\x07\x18" + ); + assert_eq!( + passed(&[b"\x1b]133;N\x07\x1b]133;C\x07\x1b]133;A\x07"]), + b"\x1b]8;id=1;\x7f\x07\x1b]8;;\x07\x1b]8;id=2;\x7f\x07" + ); + assert_eq!( + passed(&[b"\x1b]133;D;0\x07"]), + b"\x1b]133;D;0\x07", + "an end with no prompt open passes" + ); +} + +#[test] +fn the_rewrite_reads_a_mark_as_the_session_hears_it() { + let bodies = [ + "A", "A;k=i", "N", "B", "I", "C;x", "D;1", "D;abc", "D", "", "AB", "L", "P;k=i", "Q", "a", + ]; + for body in bodies { + let heard = marks::read(body.as_bytes()).map(|mark| mark == Mark::Prompt); + assert_eq!(mark(body.as_bytes()), heard, "{body}"); + } +} + +#[test] +fn a_mark_split_across_reads_comes_out_whole() { + let whole: &[u8] = + b"a\x1b]133;A;k=i\x07\x1b]8;;file:///w\x1b\\w\x1b]8;;\x1b\\$ \x1b]133;B\x1b\\b"; let once = passed(&[whole]); for cut in 0..=whole.len() { let (first, second) = whole.split_at(cut); @@ -49,67 +84,76 @@ fn a_mark_split_across_reads_waits_for_its_letter() { #[test] fn other_sequences_pass_as_they_came() { for bytes in [ - &b"\x1b]1337;A\x07"[..], - b"\x1b]13;A\x07", - b"\x1b]133;P;k=i\x07", - b"\x1b]133;L\x07", - b"\x1b]133;\x07", - b"\x1b]133\x18;A\x07", - b"\x1b]0;133;A\x07", - b"\x1b[31m\x1bc", - b"text", + "\x1b]133;AB\x07x", + "\x1b]1337;A\x07", + "\x1b]133;P;k=i\x07", + "\x1b]133;\x07", + "\x1b]0;133;A\x07", + "\x1b[31m\x1bc", + "\x1b]8;;file:///x\x07x\x1b]8;;\x07", + "text", ] { - assert_eq!( - passed(&[bytes]), - bytes, - "{}", - String::from_utf8_lossy(bytes) - ); + assert_eq!(passed(&[bytes.as_bytes()]), bytes.as_bytes(), "{bytes:?}"); } -} - -#[test] -fn a_mark_s_start_waits_no_longer_than_its_cap() { - let mut long = b"\x1b]".to_vec(); - long.extend([0u8; MOST]); - assert_eq!(passed(&[&long]), long); -} - -/// A terminal `columns` wide and two lines high after `bytes` passed through the rewrite. -fn parsed(bytes: &[u8], columns: usize) -> Term { - let mut term = Term::new(Config::default(), &TermSize::new(columns, 2), VoidListener); - let mut parser: Processor = Processor::new(); - parser.advance(&mut term, &passed(&[bytes])); - term -} - -#[test] -fn a_prompt_s_cells_carry_its_link_and_its_input_none() { - let term = parsed(b"x\r\n\x1b]133;A\x07\x1b[31m$\x1b[0m \x1b]133;B\x07ls", 8); - let cell = |line, column| prompt_link(&term.grid()[Line(line)][Column(column)]); - assert!(cell(0, 0).is_none()); - assert!( - cell(1, 0).is_some(), - "a prompt keeps its link through SGR 0" + let mut long = b"\x1b]133;A;".to_vec(); + long.extend([b'x'; MOST]); + long.push(0x07); + assert_eq!(passed(&[&long]), long, "past the scanner's bound"); + let mut skipped = b"\x1b]133;A".to_vec(); + skipped.extend([0; 3 * MOST]); + skipped.push(0x07); + assert_eq!( + passed(&[&skipped]), + skipped, + "skipped controls bound the bytes held" ); - assert_eq!(cell(1, 0), cell(1, 1)); - assert!(cell(1, 2).is_none(), "input"); - assert!(starts(&term, Line(1))); - assert!(!starts(&term, Line(0))); } #[test] -fn a_prompt_over_two_rows_starts_at_its_first() { - let term = parsed(b"\x1b]133;A\x07~/dir\r\n> \x1b]133;B\x07", 8); - assert!(starts(&term, Line(0))); - assert!(!starts(&term, Line(1)), "the same prompt goes on"); - let next = parsed(b"\x1b]133;A\x07$ \x1b]133;B\x07\r\n\x1b]133;A\x07$ ", 8); - assert!( - starts(&next, Line(1)), - "an empty line's next prompt is its own" +fn controls_vte_runs_inside_an_escape_go_on_before_the_link() { + assert_eq!( + passed(&[b"\x1b\n\x07]133;A\x07$"]), + b"\n\x07\x1b]8;id=1;\x7f\x07$" ); } +#[test] +fn a_prompt_s_cells_carry_its_link_through_sgr_0_and_its_input_none() { + let term = parsed( + b"x\r\n\x1b]133;A\x07\x1b[31m$\x1b[0m \x1b]133;B\x07ls", + 8, + 2, + ); + assert_eq!(prompt(&term.grid()[Line(0)]), None); + assert_eq!(prompt(&term.grid()[Line(1)]), Some(1)); + assert_eq!(target(&term, 1, 1).as_deref(), Some(LINK)); + assert_eq!(target(&term, 1, 2), None, "input"); +} + +#[test] +fn a_program_s_own_link_and_the_prompt_s_keep_each_other() { + let term = parsed( + b"\x1b]133;A\x07\x1b]8;;file:///work\x1b\\/work\x1b]8;;\x1b\\ $ \x1b]133;B\x07", + 12, + 2, + ); + assert_eq!(target(&term, 0, 0).as_deref(), Some("file:///work")); + assert_eq!(target(&term, 0, 6).as_deref(), Some(LINK)); + assert_eq!(prompt(&term.grid()[Line(0)]), Some(1)); + let term = parsed( + b"\x1b]8;;file:///x\x1b\\x\x1b]133;A\x07y\x1b]8;;\x1b\\z\x1b]133;B\x07", + 12, + 2, + ); + assert_eq!(target(&term, 0, 0).as_deref(), Some("file:///x")); + assert_eq!( + target(&term, 0, 1).as_deref(), + Some("file:///x"), + "a prompt inside a link keeps it" + ); + assert_eq!(target(&term, 0, 2).as_deref(), Some(LINK)); +} + /// Prompts on lines 0, 3 and 6 of a history four lines high, the last on the screen. fn history() -> Term { let mut bytes = Vec::new(); @@ -119,17 +163,14 @@ fn history() -> Term { ); } bytes.extend_from_slice(b"\x1b]133;A\x07$ \x1b]133;B\x07"); - let mut term = Term::new(Config::default(), &TermSize::new(8, 4), VoidListener); - let mut parser: Processor = Processor::new(); - parser.advance(&mut term, &passed(&[&bytes])); - term + parsed(&bytes, 8, 4) } #[test] fn up_and_down_go_to_the_prompts_beside_the_view_s_top() { let mut term = history(); assert_eq!(term.grid().history_size(), 6); - // From the bottom: the prompt at the view's top (line 0) is passed, the one before it found. + // From the bottom: the prompt at the view's top is passed, the one before it found. assert_eq!(jump(&term, true), Some(3)); term.scroll_display(Scroll::Delta(3)); assert_eq!(jump(&term, true), Some(6)); @@ -145,16 +186,36 @@ fn up_and_down_go_to_the_prompts_beside_the_view_s_top() { } #[test] +fn a_prompt_over_rows_starts_at_its_first_blank_rows_within_it_too() { + let bytes = b"\x1b]133;A\x07FIRST\r\n\r\nLAST $ \x1b]133;B\x07\r\nout1\r\nout2\r\nout3\r\nout4"; + let mut term = parsed(bytes, 8, 3); + assert_eq!(term.grid().history_size(), 4); + assert_eq!(jump(&term, true), Some(4), "FIRST, not LAST"); + term.scroll_display(Scroll::Delta(4)); + assert_eq!(jump(&term, false), None, "LAST is the same prompt"); + let next = parsed(b"\x1b]133;A\x07$ \x1b]133;B\x07\r\n\x1b]133;A\x07$ ", 8, 2); + assert_eq!( + (prompt(&next.grid()[Line(0)]), prompt(&next.grid()[Line(1)])), + (Some(1), Some(2)), + "an empty line's next prompt is its own" + ); +} + +#[test] fn a_prompt_keeps_its_start_through_a_resize() { - let bytes = b"\x1b]133;A\x07~/folder $ \x1b]133;B\x07ls\r\nout\r\n\x1b]133;A\x07$ "; - let mut term = Term::new(Config::default(), &TermSize::new(12, 4), VoidListener); - let mut parser: Processor = Processor::new(); - parser.advance(&mut term, &passed(&[bytes])); - term.resize(TermSize::new(6, 4)); - let lines = term.topmost_line().0..=term.bottommost_line().0; - let starts: Vec = lines.filter(|&line| starts(&term, Line(line))).collect(); - // The first prompt wraps over two rows and starts at its first; the last starts two below. - let first = starts.first().copied().expect("a prompt"); - assert_eq!(starts.len(), 2, "{starts:?}"); - assert!(!starts.contains(&(first + 1)), "{starts:?}"); + let bytes = + b"\x1b]133;A\x07~/folder $ \x1b]133;B\x07ls\r\nout\r\nout\r\nout\r\n\x1b]133;A\x07$ "; + let mut term = parsed(bytes, 12, 3); + term.resize(TermSize::new(6, 3)); + let rows = term.topmost_line().0..=term.bottommost_line().0; + let numbers: Vec> = rows.map(|line| prompt(&term.grid()[Line(line)])).collect(); + let first = numbers.iter().position(|number| *number == Some(1)); + // The first prompt wraps over two rows; the view jumps to the first of them. + assert_eq!( + numbers.iter().filter(|number| **number == Some(1)).count(), + 2 + ); + let offset = jump(&term, true).expect("a prompt above"); + let top = term.topmost_line().0 + first.expect("prompt 1") as i32; + assert_eq!(offset as i32, -top); } diff --git a/src/term/tap.rs b/src/term/tap.rs index 150a3c2..819fd52 100644 --- a/src/term/tap.rs +++ b/src/term/tap.rs @@ -10,7 +10,7 @@ use polling::{Event, PollMode, Poller}; use super::{marks, mouse::MouseMode, prompts::Prompts, pty::PtyEvent}; /// The longest OSC body kept; longer ones are dropped whole. -const MOST: usize = 4096; +pub(super) const MOST: usize = 4096; /// A pty whose reader shows each byte to its scanners before the parser. pub(crate) struct Tapped

{ @@ -39,13 +39,13 @@ impl

Tapped

{ impl io::Read for Tapped

{ fn read(&mut self, buf: &mut [u8]) -> io::Result { - let held = self.prompts.held(); - // A buffer with no room past the held bytes waits for the parser to empty it. - if buf.len() <= held { + // A rewrite adds 14 bytes at most to a sequence of 6 or more, so a quarter of the room is read. + let take = buf.len().saturating_sub(self.prompts.held() + 64) / 4; + if take == 0 { return Ok(0); } - let count = self.inner.reader().read(&mut buf[held..])?; - let read = &buf[held..held + count]; + let count = self.inner.reader().read(&mut buf[..take])?; + let read = &buf[..count]; let (events, pid, last) = (&self.events, self.pid, &mut self.last); self.scanner.feed(read, &mut |body| { if let Some(mark) = body.strip_prefix(b"133;").and_then(marks::read) { @@ -74,7 +74,9 @@ impl io::Read for Tapped

{ log::debug!("pty {pid}: a mouse mode after its session closed"); } } - Ok(self.prompts.pass(buf, count)) + let out = self.prompts.pass(&buf[..count]); + buf[..out.len()].copy_from_slice(out); + Ok(out.len()) } } diff --git a/tasks/acceptance.md b/tasks/acceptance.md index 59e1a8e..76a36fa 100644 --- a/tasks/acceptance.md +++ b/tasks/acceptance.md @@ -52,7 +52,7 @@ What no check reached: no real KWin drew the blur; of Wayland desktops, only Hyp | PTY through alacritty's event loop; OSC 7 and OSC 133 scanned on the reader | T04, T34 | `term::pty`, `term::tap` tests; round 3 failed at the cap, its fix stands on a red-green test | Pass | | Shell integration for zsh, bash, fish, PowerShell; a shell without it reports nothing and the panels say so | T05 | `term::shell` tests on macOS and Linux | Pass | | Prompt marks, OSC 133, from the shell integration and any program; each session keeps its last command's status | T34 | `term::marks` tests: each letter and option as Ghostty reads them; `term::tap` and `term::pty` tests: marks split across reads reach the session in order; `term::shell` tests: zsh, bash, fish and PowerShell send C, D;1, A and B around a failing command, and the user's prompt still shows the failure, a zsh theme's that sets PS1 in its own hook too, whose first prompt is marked before any command, and `$pipestatus` stays; bash's lone subshell ends with D;7, `$_` stays, a command runs under `extdebug` after a failure, a key binding marks nothing, the user's DEBUG trap runs, bash 3.2 sends no C, and bash says at start why it marks nothing while `promptvars` is off; PowerShell reads 1 for a cmdlet's failure under `-ErrorAction Ignore` after a success, a native code twice, a native failure's code under `$PSNativeCommandUseErrorActionPreference`, on a line that mixes a program and a cmdlet the cmdlet's 1, and through a call by variable the program's code; on macOS fish 4.9 marks itself and bash 3.2 marks no C, in the Linux container fish 4.0 gets B and bash 5.2 marks C through PS0, CI's Ubuntu runs fish 3.7, which the script marks whole; by hand in a pty, PowerShell under strict mode, and a cmdlet's failure after a native one's reads 1 | Pass | -| Jump to the prompt before or after the view's top, as Ghostty jumps | T35 | `term::prompts` tests: a mark becomes a link of its own length, split across reads at every byte, and other sequences pass as they came; a prompt's cells carry its link through SGR 0 and a resize, its input none; a prompt over two rows starts at its first; up and down land as Ghostty's `scrollPrompt`; `term::links`: a prompt's link is no target; `term::pty`: through the event loop the prompt's cell alone carries it; in the app on macOS, Cmd-Up once and twice put PROMPT-3 and PROMPT-2 at the top, and Cmd-Shift-Down and Cmd-Down came back to the screen's bottom. The keys off macOS are bound, not run | Pass | +| Jump to the prompt before or after the view's top, as Ghostty jumps | T35 | `term::prompts` tests: a mark becomes its prompt's numbered link, read as the session reads marks, whole when split across reads at every byte, and other sequences, `133;AB` among them, pass as they came; a prompt's cells carry its link through SGR 0 and a resize, its input none; a program's own link and the prompt's keep each other; a prompt over rows starts at its first, blank rows within it too; up and down land as Ghostty's `scrollPrompt`; `term::links`: a prompt's link is no target; `term::pty`: through the event loop the prompt's cell alone carries it; in the app on macOS, Cmd-Up once and twice put PROMPT-3 and PROMPT-2 at the top, and Cmd-Shift-Down and Cmd-Down came back to the screen's bottom; the review's fixtures of a prompt that starts with a link and of a prompt with a blank row jumped to PROMPT-3-FIRST, and its fixture of `133;AB` marks found no prompt. The keys off macOS are bound, not run | Pass | | Inside herdr, the folder of herdr's focused pane, read from its socket, on macOS, Linux and Windows | T29, T32 | `term::herdr` tests: the socket found as herdr 0.9 finds it, only the terminal client followed and a remote one refused, the snapshot read, a socket round trip, a process's path, arguments and variables; `the_foreground_is_the_program_s_own_group`; on X11 with herdr 0.9.5 run in the session: its start showed the focused pane's folder, a cd in the pane moved the panel, the focus moved to a pane in `/etc` and back moved it each time, and the client's end gave the panel back to bash's report, then `exec herdr` from that bash, with `HERDR_SOCKET_PATH` relative to its folder, was followed through the socket there; on macOS under `shot`, herdr 0.9.5 as the program and again by `exec` from `sh` with a relative socket, its pane's cd moved the panel; on Windows, `term::herdr` tests on the CI runner: the folder under `APPDATA` and `USERPROFILE`, the `herdr.exe` nearest under the shell, this test's name, arguments and variables read through the live process list and `sysinfo`, a round trip over a named pipe; no real herdr has run on Windows yet | Partial | | Colors, styles, five underlines, wide characters, combining marks | T06 | `term::frame`, `term::ink`, `term::paint` tests | Pass | | Box drawing, blocks and powerline shapes as geometry | T07 | `term::boxes` tests | Pass |