diff --git a/Cargo.lock b/Cargo.lock index 5a80b5d..6841548 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1035,6 +1035,7 @@ dependencies = [ "squid-core", "sysinfo", "walkdir", + "windows-sys 0.59.0", "winreg", ] diff --git a/crates/squid-platform/Cargo.toml b/crates/squid-platform/Cargo.toml index 6b7f207..7b697f9 100644 --- a/crates/squid-platform/Cargo.toml +++ b/crates/squid-platform/Cargo.toml @@ -21,3 +21,4 @@ libc.workspace = true [target.'cfg(windows)'.dependencies] winreg = "0.52" sysinfo.workspace = true +windows-sys = { version = "0.59", features = ["Win32_System_Console", "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_Security"] } diff --git a/crates/squid-platform/src/console.rs b/crates/squid-platform/src/console.rs new file mode 100644 index 0000000..8f5fbdf --- /dev/null +++ b/crates/squid-platform/src/console.rs @@ -0,0 +1,900 @@ +//! The console this program paints on, and the rectangle it can really hold. +//! +//! A terminal user interface runs on one assumption: the size it was told is +//! the size it may write to. Legacy Windows consoles break that assumption in +//! a way that looks like a broken renderer. The screen buffer behind the +//! alternate screen keeps the size it had when the program entered it, while +//! the window reports the size the user just dragged it to, so the console now +//! claims to be *wider* than the cells that exist. Cells written past the end +//! of a row wrap to the beginning of the next one, every line below the drag +//! shifts right, and cells that the renderer believes are empty show the +//! previous frame. A diff-based renderer cannot undo that: it compares frames +//! by coordinate, and the console moved the content between them. +//! +//! Reading the geometry is how the interface notices the lie. Making the +//! buffer agree with the window is how it repairs itself, and drawing inside +//! what is left is how it degrades when the console refuses. +//! +//! Whether the rectangle is honest is not the only question a console gets to +//! answer, and the second one is what makes a whole screen look broken at once. +//! A character that measures one column is supposed to spend one cell, and a +//! Far-Eastern console spends two on the box-drawing rules, block shading, +//! arrows, ticks and middots an interface is built out of. The window is not +//! lying any more: it is simply too small for what was written into it, every +//! row overflows by the characters it paid one cell for, and the overflow lands +//! at the start of the row below, which is the same pile of previous frames a +//! wrong size produces. [`symbol_cells`] asks the cells what they cost instead +//! of guessing from the locale, so the interface can afford its glyphs where it +//! can and pay for them in ASCII where it cannot. +//! +//! A second question has to be answered before the first one means anything: +//! *which* buffer is being measured. The alternate screen on a legacy console is +//! a second buffer made active, and a process can still be holding the handle it +//! was started with, which then describes a screen nobody is looking at. Every +//! measurement here is taken from the buffer the console is showing, and +//! [`note`] writes both answers down side by side so the disagreement is +//! visible instead of being guessed at. + +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; +use std::time::Instant; + +/// What a console reports about itself, in cells. +/// +/// Three numbers, because a console has three ways to be too optimistic. The +/// window is what it says it shows; the buffer is what it says it holds; the +/// limit is the largest window it could show at all, which is where the console +/// itself admits how much the window on the desk can carry. Reading only the +/// first of the three is how an interface ends up painting columns that have no +/// cells, which on a legacy console is where the wrapping starts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Geometry { + /// The part the user can see. + pub window: (u16, u16), + /// Where in the buffer that part begins. + /// + /// Zero, usually, and not always: a window dragged taller than a buffer + /// with room to spare slides down its own history, and so does one the user + /// scrolled. Nothing about the *size* changes, which is why a renderer that + /// only watches sizes keeps painting at row zero of a buffer whose first + /// visible row is somewhere else — an interface that draws where nobody is + /// looking, over a screen of cells it believes it already drew. + pub origin: (u16, u16), + /// The part that actually exists. + pub buffer: (u16, u16), + /// The largest window this console could display at its current size. + pub limit: (u16, u16), +} + +impl Geometry { + /// The largest rectangle the console can show, hold, and display at once. + /// + /// This is the only area it is safe to paint: anything wider wraps, and + /// anything taller is discarded. + pub fn drawable(&self) -> (u16, u16) { + ( + self.smallest(|edges| edges.0), + self.smallest(|edges| edges.1), + ) + } + + /// The narrowest of the three claims along one axis. + fn smallest(&self, axis: fn((u16, u16)) -> u16) -> u16 { + axis(self.window) + .min(axis(self.buffer)) + .min(axis(self.limit)) + } + + /// True when the window asks for cells the buffer does not contain. + pub fn outlived_its_buffer(&self) -> bool { + self.window.0 > self.buffer.0 || self.window.1 > self.buffer.1 + } + + /// True when the window is not sitting on the first cell of its buffer. + /// + /// The interface paints from (0, 0) of its own area, so anything else means + /// the frame and the screen are two different rectangles. + pub fn misplaced(&self) -> bool { + self.origin != (0, 0) + } + + /// True when this looks like a buffer the console made for this program + /// rather than the screen a person types into. + /// + /// Measured on Windows 10 18363: the alternate screen arrives with no + /// history at all, its buffer exactly the size of its window. A screen with + /// somebody's scrollback in it is a screen that belongs to them. + pub fn is_own_screen(&self) -> bool { + self.buffer == self.window + } + + /// The buffer size that would leave the window nowhere to hide. + /// + /// When the screen is ours the answer is the window, in both directions: a + /// buffer the size of its window has exactly one place it can sit, so + /// agreeing about size is also what puts the picture back underneath it. + /// When the screen is not ours, growth is the only change on offer, because + /// history that belongs to somebody else is not ours to cut down. + pub fn repair_target(&self, ours: bool) -> (u16, u16) { + if ours { + self.window + } else { + ( + self.window.0.max(self.buffer.0), + self.window.1.max(self.buffer.1), + ) + } + } + + /// True when the buffer is not the shape a repair would leave it in. + pub fn needs_repair(&self, ours: bool) -> bool { + self.repair_target(ours) != self.buffer + } + + /// `window+origin in buffer of limit`, the shape a trace line carries, in + /// the order a person reads a window manager's geometry. + fn text(&self) -> String { + format!( + "{}x{}+{}+{} in {}x{} of {}x{}", + self.window.0, + self.window.1, + self.origin.0, + self.origin.1, + self.buffer.0, + self.buffer.1, + self.limit.0, + self.limit.1 + ) + } +} + +/// Ask the console how big its window and its buffer are. +/// +/// `None` means the question does not apply: standard output is a pipe, or the +/// platform's terminal is an emulator that owns both sizes itself. Callers then +/// trust the size the terminal library reported. +pub fn geometry() -> Option { + #[cfg(windows)] + { + windows::shown() + } + #[cfg(not(windows))] + { + None + } +} + +/// Claim the screen being shown, if it arrived as one this program made. +/// +/// The promise has to be taken from the console at the moment it is still true: +/// once something has moved underneath the interface, there is no way left to +/// tell a buffer the console made for us from a main screen the user happens to +/// keep one row of history in. Call this once, as the alternate screen goes up. +pub fn adopt() { + #[cfg(windows)] + { + windows::adopt(); + } + #[cfg(not(windows))] + {} +} + +/// One line about what kind of screen this is, for the trace. +/// +/// The output code page and the virtual-terminal flag together decide how this +/// program's words reach the glass. With the flag the interface addresses the +/// window, so a window the console moves takes the picture with it; without it +/// the interface addresses absolute cells of a buffer, and a window that slides +/// down its history leaves the interface painting rows nobody is looking at. +/// Which of the two a machine is doing is not written in its version number — +/// the same build of conhost answers differently through a pseudo-console and +/// through a window on a desk — so it is measured and written down. +pub fn report() -> String { + #[cfg(windows)] + { + windows::report() + } + #[cfg(not(windows))] + { + "not-a-console".to_string() + } +} + +/// Put the console back into a shape the renderer's coordinates agree with. +/// +/// The buffer is made to equal the window; the window itself is left alone. +/// Every half is an attempt, and `false` means nothing changed, which is not an +/// error worth reporting to someone watching their own window resize. The +/// caller keeps drawing inside [`Geometry::drawable`] either way. +pub fn repair() -> bool { + #[cfg(windows)] + { + windows::repair() + } + #[cfg(not(windows))] + { + false + } +} + +/// What the console charges for a character that measures one column. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SymbolCells { + /// One cell, which is what the character measures and what a layout + /// measured in columns paid for it. + Single, + /// Two cells, so every one-column symbol on the screen spends a cell it was + /// not bought, and every row holding one is that much longer than the glass. + Double, +} + +/// Ask the console, once, what it charges for a one-column character. +/// +/// The answer is measured rather than looked up, because the two things that +/// decide it are both set outside this program: the code page the console was +/// left on and the font it was left with. They are not even the same question, +/// since `chcp 65001` moves a box-drawing bar back to one cell on the box that +/// charges two, and the same console shows that bar as a blank when the font +/// carries no glyph for it. The only answer worth laying a screen out against +/// is the one taken from the cells themselves. +/// +/// Measuring spends one character on whatever screen the console is showing, so +/// call this when the interface owns the screen rather than while somebody's +/// shell is still on it. +pub fn symbol_cells() -> SymbolCells { + if let Some(asked) = asked_for() { + note(&format!("symbols={asked:?} asked")); + return asked; + } + #[cfg(windows)] + { + windows::symbol_cells() + } + #[cfg(not(windows))] + { + SymbolCells::Single + } +} + +/// The price somebody named, rather than the one the console charges. +/// +/// `SQUID_SYMBOL_CELLS=2` charges two cells for every ambiguous character and +/// `=1` charges one, whatever the console says. The measurement is the honest +/// answer and this is the exception to it, for the two cases a measurement +/// cannot reach: a person looking at a screen this program cannot see — over +/// ssh, the program measures the console sshd made for it, not the one on the +/// glass — and a person who wants to see the plain frame on a terminal that +/// could afford the drawn one, to compare the two. +/// +/// Anything the variable says is obeyed without argument, including on a +/// terminal that would have been drawn better. It is a person looking at their +/// own screen, and they can see what this code cannot. +fn asked_for() -> Option { + spend(&std::env::var("SQUID_SYMBOL_CELLS").ok()?) +} + +/// The two spellings of an answer: how many cells, or the word for it. A price +/// with spaces round it is still that price, because it came from an environment +/// variable somebody typed between the equals sign and the end of the line. +fn spend(asked: &str) -> Option { + match asked.trim().to_ascii_lowercase().as_str() { + "2" | "two" | "double" => Some(SymbolCells::Double), + "1" | "one" | "single" => Some(SymbolCells::Single), + _ => None, + } +} + +/// The price a code page implies, for when the cells cannot be measured. +/// +/// A Far-Eastern code page has no one-byte spelling for any of the punctuation, +/// rules and shading an interface is drawn from: those characters are two bytes +/// there, and a two-byte character is two cells to the console reading it. +/// UTF-8 has no two-byte character at all, and neither has the code page a +/// person chooses with `chcp 437`, so both charge one. +#[cfg_attr(not(windows), allow(dead_code))] +fn charged_by_code_page(code_page: u32) -> SymbolCells { + match code_page { + 932 | 936 | 949 | 950 => SymbolCells::Double, + _ => SymbolCells::Single, + } +} + +/// Write down what the console is claiming right now, when it was asked to. +/// +/// `SQUID_CONSOLE_TRACE=a\path\file.log` switches this on; with the variable +/// unset the call reads one environment entry and writes nothing. The variable +/// exists because the console that misreports its size is a console somebody +/// has to sit in front of and drag: a hand-made resize leaves no evidence +/// behind, and the whole diagnosis is about which of several numbers the +/// console changed. The file says, per line, what stdout described, what the +/// screen being shown described, and what the interface did about it. +pub fn note(what: &str) { + #[cfg(windows)] + { + let Some(path) = trace_path() else { return }; + let line = measurement( + elapsed(), + what, + &[("stdout", windows::stdout()), ("shown", windows::shown())], + ); + append(path, &line); + } + #[cfg(not(windows))] + { + let _ = what; + } +} + +/// Where the trace goes, decided once so a beat that measures four times a +/// second does not re-read the environment forever. +#[cfg_attr(not(windows), allow(dead_code))] +fn trace_path() -> Option<&'static PathBuf> { + static PATH: OnceLock> = OnceLock::new(); + PATH.get_or_init(|| std::env::var_os("SQUID_CONSOLE_TRACE").map(PathBuf::from)) + .as_ref() +} + +/// Milliseconds since the first measurement, so lines can be read in order +/// against a resize someone performed by hand. +#[cfg_attr(not(windows), allow(dead_code))] +fn elapsed() -> u128 { + static START: OnceLock = OnceLock::new(); + START.get_or_init(Instant::now).elapsed().as_millis() +} + +/// One line of the trace: when, what happened, and what each handle said. +#[cfg_attr(not(windows), allow(dead_code))] +fn measurement(elapsed: u128, what: &str, cells: &[(&str, Option)]) -> String { + let mut line = format!("+{elapsed:>6}ms {what}"); + for (name, geometry) in cells { + let claim = geometry + .as_ref() + .map(Geometry::text) + .unwrap_or_else(|| "none".to_string()); + line.push_str(&format!(" {name}={claim}")); + } + line +} + +#[cfg_attr(not(windows), allow(dead_code))] +fn append(path: &Path, line: &str) { + use std::fs::OpenOptions; + use std::io::Write; + if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) { + let _ = writeln!(file, "{line}"); + } +} + +#[cfg(windows)] +mod windows { + use super::{charged_by_code_page, Geometry, SymbolCells}; + use std::ffi::c_void; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::OnceLock; + use windows_sys::Win32::Foundation::{ + CloseHandle, GENERIC_READ, GENERIC_WRITE, INVALID_HANDLE_VALUE, + }; + use windows_sys::Win32::Storage::FileSystem::{ + CreateFileW, GetFileType, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, + }; + use windows_sys::Win32::System::Console::{ + GetConsoleMode, GetConsoleOutputCP, GetConsoleScreenBufferInfo, GetStdHandle, + SetConsoleCursorPosition, SetConsoleScreenBufferSize, WriteConsoleW, + CONSOLE_SCREEN_BUFFER_INFO, COORD, ENABLE_VIRTUAL_TERMINAL_PROCESSING, STD_OUTPUT_HANDLE, + }; + + type Handle = *mut c_void; + + /// A console refuses a buffer larger than this, and `srWindow` is measured + /// in buffer coordinates, so a window wider than it cannot be satisfied by + /// growing anything. + const SPAN: i32 = 9_999; + + /// A console handle that closes itself, since `CONOUT$` is opened fresh + /// every time it is asked about. + struct Owned(Handle); + + impl Drop for Owned { + fn drop(&mut self) { + unsafe { + CloseHandle(self.0); + } + } + } + + /// The buffer this process' bytes go to. + fn stdout_handle() -> Option { + let handle = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) }; + if handle.is_null() || handle == INVALID_HANDLE_VALUE { + return None; + } + Some(handle) + } + + /// True when standard output really is a console rather than a pipe or a + /// redirected file. Without this test a `squid > log.txt` would happily + /// resize the console sitting behind the file it is no longer writing to. + fn stdout_is_console() -> bool { + let Some(handle) = stdout_handle() else { + return false; + }; + let mut mode = 0u32; + unsafe { GetConsoleMode(handle, &mut mode) != 0 } + } + + /// The buffer the console is displaying, opened fresh because the console + /// can switch it at any moment and a cached handle would keep describing + /// the screen that was there when we looked. + fn shown_handle() -> Option { + if !stdout_is_console() { + return None; + } + let name: Vec = "CONOUT$\0".encode_utf16().collect(); + let handle = unsafe { + CreateFileW( + name.as_ptr(), + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + std::ptr::null(), + OPEN_EXISTING, + 0, + std::ptr::null_mut(), + ) + }; + if handle.is_null() || handle == INVALID_HANDLE_VALUE { + return None; + } + Some(Owned(handle)) + } + + fn info(handle: Handle) -> Option { + let mut info = std::mem::MaybeUninit::::uninit(); + let ok = unsafe { GetConsoleScreenBufferInfo(handle, info.as_mut_ptr()) }; + if ok == 0 { + return None; + } + Some(unsafe { info.assume_init() }) + } + + /// `srWindow` is a rectangle, not a size, so the window is one cell wider + /// and taller than subtracting its corners suggests. + fn geometry_of(info: &CONSOLE_SCREEN_BUFFER_INFO) -> Geometry { + let span = + |low: i16, high: i16| (i32::from(high) - i32::from(low) + 1).clamp(1, SPAN) as u16; + let axis = |cells: i16| i32::from(cells).clamp(1, SPAN) as u16; + let edge = |cells: i16| i32::from(cells).clamp(0, SPAN) as u16; + Geometry { + window: ( + span(info.srWindow.Left, info.srWindow.Right), + span(info.srWindow.Top, info.srWindow.Bottom), + ), + origin: (edge(info.srWindow.Left), edge(info.srWindow.Top)), + buffer: (axis(info.dwSize.X), axis(info.dwSize.Y)), + limit: ceiling(info), + } + } + + /// `dwMaximumWindowSize`: the largest window this console could display. + /// + /// It is worth measuring and drawing inside, and it is not worth asking + /// permission from: it can sit below the buffer (a console with a thousand + /// rows of history can display far fewer) and level with it (the alternate + /// screen, where the two are the same number). A repair asks the console + /// instead. + fn ceiling(info: &CONSOLE_SCREEN_BUFFER_INFO) -> (u16, u16) { + ( + i32::from(info.dwMaximumWindowSize.X).clamp(1, SPAN) as u16, + i32::from(info.dwMaximumWindowSize.Y).clamp(1, SPAN) as u16, + ) + } + + /// What the handle this process was started with claims, which is the + /// screen its bytes go to — and, on a console that switched buffers under + /// the program, not necessarily the screen anybody can see. + pub fn stdout() -> Option { + stdout_handle().and_then(|handle| info(handle).as_ref().map(geometry_of)) + } + + /// The size of the screen the interface is painting, which is the size the + /// console will reflow when it changes. + /// + /// This is the buffer the terminal library measures too: a legacy console + /// that is asked through the handle the process started with answers about + /// the main screen while the interface is on the alternate one, and the two + /// numbers being different is what a resized window turns into ghosting. + pub fn shown() -> Option { + shown_handle() + .as_ref() + .and_then(|owned| info(owned.0).as_ref().map(geometry_of)) + } + + /// Whether the screen being shown is the one this program asked for. + /// + /// Latched once, by [`adopt`], because the question can only be answered + /// while the screen is still the way the console handed it over. + static OWNED: AtomicBool = AtomicBool::new(false); + + pub fn adopt() { + if let Some(geometry) = shown() { + OWNED.store(geometry.is_own_screen(), Ordering::Relaxed); + } + } + + pub fn report() -> String { + let code_page = unsafe { GetConsoleOutputCP() }; + let mut mode = 0u32; + let mut kind = 0; + if let Some(handle) = stdout_handle() { + unsafe { + GetConsoleMode(handle, &mut mode); + kind = GetFileType(handle); + } + } + // GetFileType: 1 is a disk, 2 a character device (a console, of one kind + // or another), 3 a pipe. Which one decides whether the interface talks + // to conhost in cells or in escape sequences. + let kind = match kind { + 0 => "unknown", + 1 => "disk", + 2 => "char", + 3 => "pipe", + _ => "other", + }; + format!( + "cp={code_page} kind={kind} vt={} ours={}", + mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING != 0, + OWNED.load(Ordering::Relaxed) + ) + } + + /// The character the price is asked with: a box-drawing bar, which measures + /// one column in every table that measures characters and is the glyph this + /// interface draws more of than any other. + const PROBE: char = '│'; + + /// The price, measured once. See [`super::symbol_cells`] for why it is + /// measured, and why the answer is worth keeping for the life of a run. + static SYMBOLS: OnceLock = OnceLock::new(); + + pub fn symbol_cells() -> SymbolCells { + *SYMBOLS.get_or_init(|| { + measure_symbol_cells() + .unwrap_or_else(|| charged_by_code_page(unsafe { GetConsoleOutputCP() })) + }) + } + + /// Write one character where the console is looking, and read back the cost. + /// + /// `None` when there is no screen to ask, or no answer to read: the + /// character did not land, or it landed where a second cell would have had + /// to wrap — a place the cursor can be and deliberately not a place this + /// function writes to. A cursor that did not move at all is not an answer + /// either; a console that writes nothing where it was told to write is not + /// one whose prices can be read off it. The caller falls back on the code + /// page. + fn measure_symbol_cells() -> Option { + let owned = shown_handle()?; + let before = info(owned.0)?; + // The top-left cell of what is on the glass, not where the cursor + // happens to be: on the last column of the last row a second cell + // wraps, and a wrap scrolls the very screen this program is about to + // draw on. The cell is painted over by the first frame anyway, which is + // what makes it worth spending one character of somebody's screen to + // keep the rest of the frame from being wrong. + let at = COORD { + X: before.srWindow.Left, + Y: before.srWindow.Top, + }; + if unsafe { SetConsoleCursorPosition(owned.0, at) } == 0 { + return None; + } + let glyph: Vec = PROBE.to_string().encode_utf16().collect(); + let mut written = 0u32; + let ok = unsafe { + WriteConsoleW( + owned.0, + glyph.as_ptr().cast(), + 1, + &mut written, + std::ptr::null(), + ) + }; + let after = info(owned.0); + unsafe { SetConsoleCursorPosition(owned.0, before.dwCursorPosition) }; + if ok == 0 || written != 1 { + return None; + } + // Whatever the cursor moved past is what the character cost. Reading it + // back from the console instead of counting bytes is the point: the + // console is the thing this program has to agree with. + let cost = after?.dwCursorPosition.X.checked_sub(at.X)?; + match cost { + 0 => None, + 1 => Some(SymbolCells::Single), + _ => Some(SymbolCells::Double), + } + } + + /// Make the buffer agree with the window, and report whether it did. + /// + /// The window is left alone, which is a change of mind worth keeping in + /// words: an earlier version of this function moved the window back onto the + /// first cell of its buffer and won that argument for exactly one frame. A + /// console that has settled its window at the bottom of a taller buffer puts + /// it straight back, and the screen scrolls one row every time it does — + /// after which the renderer's diff and the glass are a row apart everywhere, + /// which is the precise damage this function exists to prevent. Measured on + /// the 18363 box: the origin went 0, then 17, then 20, one scroll per + /// repair, while the size never changed at all. + /// + /// The buffer is the half that can move without a fight, and a buffer the + /// size of its window has only one place it can be. Agreeing about the size + /// therefore puts the picture back under the window by itself, without + /// scrolling anything. + pub fn repair() -> bool { + let Some(owned) = shown_handle() else { + return false; + }; + let Some(info) = info(owned.0) else { + return false; + }; + let geometry = geometry_of(&info); + let ours = OWNED.load(Ordering::Relaxed); + if !geometry.needs_repair(ours) { + return false; + } + let want = geometry.repair_target(ours); + let size = COORD { + X: want.0 as i16, + Y: want.1 as i16, + }; + // There is no ceiling worth checking here, which is worth stating + // because an earlier version of this function had one and it made the + // repair impossible. On the box the bug was reported from, the buffer + // behind the alternate screen is exactly the size of the window, so the + // largest window the console will admit to is the size the window + // already is: every request looks illegal to a caller that compares + // against `limit`, and the answer is `false` in the one situation this + // function exists for. The console knows whether the cells exist and + // this function does not, so its return value is the only measurement + // worth trusting. + unsafe { SetConsoleScreenBufferSize(owned.0, size) != 0 } + } +} + +#[cfg(test)] +mod tests { + use super::{charged_by_code_page, measurement, spend, Geometry, SymbolCells}; + + /// A console with room above the window, so the limit is not what holds + /// this one back. + fn console(window: (u16, u16), buffer: (u16, u16)) -> Geometry { + let limit = (window.0.max(buffer.0), window.1.max(buffer.1).max(9_999)); + Geometry { + window, + origin: (0, 0), + buffer, + limit, + } + } + + /// A console whose window asks for more cells than it could ever show. + fn too_wide(window: (u16, u16), limit: (u16, u16)) -> Geometry { + let buffer = (window.0.max(limit.0), window.1.max(limit.1)); + Geometry { + window, + origin: (0, 0), + buffer, + limit, + } + } + + #[test] + fn a_far_eastern_code_page_charges_two_cells_for_a_one_column_character() { + // Shift-JIS, GBK, Unified Hangul and Big5: the four consoles this + // fallback exists for, and the reason the interface does not trust its + // own arithmetic about character widths on a Chinese Windows box. + for code_page in [932, 936, 949, 950] { + assert_eq!( + charged_by_code_page(code_page), + SymbolCells::Double, + "code page {code_page} spells every rule and arrow in two bytes" + ); + } + } + + #[test] + fn a_named_price_is_obeyed_and_a_rubbish_one_is_ignored() { + // The override is the only way to lay out for a screen this program is + // not sitting in front of, so it has to work both ways and shut up + // quietly when it holds a word that is not a price. + assert_eq!(spend("2"), Some(SymbolCells::Double)); + assert_eq!(spend(" Double "), Some(SymbolCells::Double)); + assert_eq!(spend("1"), Some(SymbolCells::Single)); + assert_eq!(spend("SINGLE"), Some(SymbolCells::Single)); + assert_eq!(spend("as big as you like"), None); + assert_eq!(spend(""), None); + } + + #[test] + fn a_code_page_with_no_two_byte_characters_charges_one() { + // 65001 is the one a person can choose on the same machine to get the + // interface's glyphs back; 437 is the one a console arrives with. + for code_page in [65001, 437, 1252, 0] { + assert_eq!(charged_by_code_page(code_page), SymbolCells::Single); + } + } + + #[test] + fn a_window_that_fits_its_buffer_is_a_place_to_draw() { + let tight = console((120, 40), (120, 300)); + assert!(!tight.outlived_its_buffer()); + assert_eq!(tight.drawable(), (120, 40)); + } + + #[test] + fn scrollback_is_height_the_interface_does_not_get() { + // A console with a thousand rows of history is still forty rows of + // interface. Painting into the rest would push the prompt away. + let tight = console((100, 40), (100, 1_000)); + assert_eq!(tight.drawable(), (100, 40)); + } + + #[test] + fn a_window_wider_than_its_buffer_is_not_a_place_to_draw() { + // The 1909 conhost case: the alternate buffer is still 100 columns, + // the maximized window claims 180. Writing column 101 wraps to the + // next row and everything below it shifts. + let tight = console((180, 50), (100, 30)); + assert!(tight.outlived_its_buffer()); + assert_eq!(tight.drawable(), (100, 30)); + } + + #[test] + fn a_repair_grows_the_buffer_to_the_window_and_no_further() { + let tight = console((180, 50), (100, 30)); + assert!(tight.needs_repair(false)); + assert_eq!(tight.repair_target(false), (180, 50)); + // Nothing to grow when the buffer already carries the window, even + // when it towers over it with scrollback. + let roomy = console((120, 40), (120, 900)); + assert_eq!(roomy.repair_target(false), (120, 900)); + assert!(!roomy.needs_repair(false)); + assert!(!roomy.outlived_its_buffer()); + } + + #[test] + fn a_buffer_that_grew_underneath_us_is_brought_back_to_the_window() { + // Measured on the 18363 box: something grew the screen to 180x50 while + // the window stayed 100x30, and the window slid down to row 20 to sit + // at the bottom of what it now had. The interface went on painting rows + // 0..30 of a screen showing rows 20..50 — an interface drawing where + // nobody is looking, and a diff comparing cells it can no longer see. + let ours = Geometry { + window: (100, 30), + origin: (0, 20), + buffer: (180, 50), + limit: (180, 50), + }; + // Note the `false`: by now the screen no longer looks like one the + // console made for us, which is why `adopt` has to take the promise + // early rather than ask whenever a repair is wanted. + assert!(!ours.is_own_screen()); + assert!(ours.misplaced()); + assert!(ours.needs_repair(true)); + // The window does not move, because conhost would move it back and the + // screen would scroll one row each time it did. The buffer comes down to + // meet it, which leaves the window exactly one place to be. + assert_eq!(ours.repair_target(true), (100, 30)); + } + + #[test] + fn somebody_elses_history_is_never_cut_down_to_our_window() { + // The same shape on a screen this program did not make: nine thousand + // rows of somebody's commands, with the window parked at the bottom of + // them. That is a console working as designed, and shrinking it to the + // window would delete the record to fix a picture that was never broken. + let theirs = Geometry { + window: (120, 30), + origin: (0, 8_971), + buffer: (120, 9_001), + limit: (120, 30), + }; + assert!(!theirs.is_own_screen()); + assert!(!theirs.needs_repair(false)); + assert_eq!(theirs.repair_target(false), (120, 9_001)); + } + + #[test] + fn a_screen_with_no_history_announces_itself_as_ours() { + // What `adopt` latches on: the alternate screen arrives with nowhere to + // scroll, so its buffer already equals its window. + assert!(console((120, 30), (120, 30)).is_own_screen()); + assert!(!console((120, 30), (120, 9_001)).is_own_screen()); + } + + #[test] + fn a_window_the_console_could_never_show_is_not_a_place_to_draw() { + // The claim on the desk: a window of 180 columns on a console whose + // font and pixels can display 150 of them. The buffer is big enough to + // hold 180, so only the limit knows the last thirty columns have no + // cells — and growing anything cannot invent them. + let tight = too_wide((180, 50), (150, 9_999)); + assert_eq!(tight.drawable(), (150, 50)); + } + + #[test] + fn an_alternate_buffer_the_size_of_its_window_leaves_nothing_to_grow() { + // Measured on Windows 10 18363: entering the alternate screen leaves a + // buffer the size of the window, and the console's own maximum is that + // same number. Nothing here can grow, so the frame stays inside the + // cells that exist and waits for the user to move the window. + let tight = Geometry { + window: (120, 30), + origin: (0, 0), + buffer: (120, 30), + limit: (120, 30), + }; + assert!(!tight.outlived_its_buffer()); + assert!(tight.is_own_screen()); + assert_eq!(tight.repair_target(true), (120, 30)); + assert!(!tight.needs_repair(true)); + assert!(!tight.needs_repair(false)); + assert_eq!(tight.drawable(), (120, 30)); + } + + #[test] + fn a_repair_asks_for_the_window_even_when_the_limit_disagrees() { + // The ask is the window, not the ceiling: whether those cells can exist + // is a question the console answers with its return value. Refusing + // first is what made this repair unreachable on the machine it was + // written for, because there the limit is the size of the window. + let tight = too_wide((180, 50), (150, 60)); + assert_eq!(tight.repair_target(false), (180, 60)); + assert!(tight.repair_target(false).0 > tight.limit.0); + assert_eq!(tight.drawable(), (150, 50)); + } + + #[test] + fn a_trace_line_writes_both_answers_side_by_side() { + // The whole point of the file: one number tells a story, two numbers + // tell which buffer lied. + let line = measurement( + 1_530, + "resize", + &[ + ("stdout", Some(console((180, 50), (100, 30)))), + ("shown", Some(console((180, 50), (180, 50)))), + ], + ); + assert_eq!( + line, + "+ 1530ms resize stdout=180x50+0+0 in 100x30 of 180x9999 \ + shown=180x50+0+0 in 180x50 of 180x9999" + ); + } + + #[test] + fn a_window_scrolled_down_its_buffer_still_holds_the_frame_it_asked_for() { + // The size is honest here and the picture is still wrong: the console + // moved the visible rectangle down its own history, so the first cells + // the interface paints are not the first cells anybody can see. The + // drawable area is unchanged, which is exactly why the size alone is + // not enough to notice — and why the origin is measured at all. + let scrolled = Geometry { + window: (120, 30), + origin: (0, 897), + buffer: (120, 9_000), + limit: (120, 30), + }; + assert!(scrolled.misplaced()); + assert!(!scrolled.outlived_its_buffer()); + assert_eq!(scrolled.drawable(), (120, 30)); + } + + #[test] + fn a_handle_that_is_not_a_console_is_written_as_none() { + let line = measurement(4, "start", &[("stdout", None), ("shown", None)]); + assert_eq!(line, "+ 4ms start stdout=none shown=none"); + } +} diff --git a/crates/squid-platform/src/lib.rs b/crates/squid-platform/src/lib.rs index 9036a06..883c94b 100644 --- a/crates/squid-platform/src/lib.rs +++ b/crates/squid-platform/src/lib.rs @@ -11,6 +11,7 @@ use squid_core::{AppInfo, Bytes, Volume}; use std::path::{Path, PathBuf}; pub mod apps; +pub mod console; pub mod leftovers; #[cfg(unix)] pub mod volumes; diff --git a/crates/squid-tui/src/glyphs.rs b/crates/squid-tui/src/glyphs.rs new file mode 100644 index 0000000..9389beb --- /dev/null +++ b/crates/squid-tui/src/glyphs.rs @@ -0,0 +1,388 @@ +//! Buying the screen at the price the console actually charges for it. +//! +//! The layout measures a row in columns, and every character is charged the +//! number of columns it measures: one for a letter, one for a box-drawing bar, +//! two for a Chinese one. Unicode keeps a class of characters whose price was +//! never settled — *East Asian Ambiguous* — and it leaves a terminal free to +//! charge either one cell or two for them. ratatui charges one. A console left +//! on a Far-Eastern code page charges two, and that class is exactly where the +//! chrome of an interface lives: the rules `─│╭`, the shading `█▒░`, the arrows +//! `↑↓`, the ticks `✓`, the middot `·`, the ellipsis `…`. +//! +//! A screen of this interface is a pile of cards, so it is built out of nothing +//! but ambiguous characters, and on such a console every row of it is several +//! cells longer than the screen. What goes past the right edge arrives at the +//! start of the row below, which shifts that one, and the frame ends up as +//! several copies of itself at several offsets: a border that stops short, half +//! a rounded corner standing alone where the next frame did not reach, a footer +//! printed twice. It looks like a renderer that cannot count. The renderer is +//! counting correctly, in a currency the console will not accept. +//! +//! So the finished frame passes through here on its way to the terminal, and +//! every character the console overcharges is drawn as an ASCII character that +//! costs the one cell the layout paid for it. The rules become `|-+`, the +//! gauges `#`, the arrows `<^>v`. Nothing about the layout moves, because the +//! exchange is one column for one column: what changes is that the rows fit. +//! +//! Chinese text is left alone, and so are the letters of most alphabets — +//! neither is ambiguous, so both cost the console exactly what they cost the +//! layout. That is deliberate. A person's paths and process names are not what +//! an alignment bug was caused by, and this module rewrites only the characters +//! it can prove the console is overcharging. + +use ratatui::buffer::Buffer; +use squid_platform::console::SymbolCells; +use unicode_width::UnicodeWidthChar; + +/// The console's price list, taken once, from the console itself. +pub struct Fit { + /// True when a character the layout bought for one cell costs two here. + overcharging: bool, +} + +impl Fit { + /// Ask what the screen being drawn on charges for a one-column character. + /// + /// [`squid_platform::console::symbol_cells`] measures the answer by writing + /// one character and reading back what it cost, so the Chinese Windows + /// console that cannot afford a box-drawing bar gets the ASCII chrome it + /// can, while Windows Terminal, a console on UTF-8 and a Mac keep the + /// rounded cards they have always paid for. + pub fn measure() -> Fit { + let cells = squid_platform::console::symbol_cells(); + squid_platform::console::note(&format!("symbols={cells:?}")); + Fit { + overcharging: cells == SymbolCells::Double, + } + } + + /// Rewrite a rendered frame so that every cell costs what the layout paid. + /// + /// Called once the widgets are done and before the frame reaches the + /// terminal, which is the last moment at which an over-long row can still + /// be made to fit. On a console that charges one cell there is nothing to + /// do, and this returns without touching the frame. + pub fn carry(&self, buffer: &mut Buffer) { + if !self.overcharging { + return; + } + for y in 0..buffer.area.height { + for x in 0..buffer.area.width { + let Some(cell) = buffer.cell_mut((x, y)) else { + continue; + }; + // A cell holding no character is the half of a wide one that a + // previous row already paid for, and has nothing to price. + let Some(first) = cell.symbol().chars().next() else { + continue; + }; + if let Some(instead) = cheaper(first) { + cell.set_char(instead); + } + } + } + } +} + +/// The character to draw instead, or `None` when this one is fairly priced. +fn cheaper(ch: char) -> Option { + overcharged(ch).then(|| one_cell(ch)) +} + +/// True when the console charges two cells for what the layout measured as one. +/// +/// The first of the two tests is the honest one: `width` is what the layout paid +/// and `width_cjk` is what the Ambiguous class says a Far-Eastern terminal +/// charges, so where they agree there is nothing for this module to repair, +/// whatever else the console may be getting wrong. +/// +/// The second test exists because that class is a description of what terminals +/// have been seen to do rather than a rule, and a console on code page 936 has +/// been seen doing it to characters the class leaves out. `░` is not Ambiguous at +/// all, and it is what this interface fills its gauges with: a row of ten of them +/// is twenty cells on that glass. Being too generous here buys a plainer +/// character on the console that cannot afford the drawn one; being too strict +/// buys the shifted frame this module exists to prevent. So the blocks a +/// Far-Eastern writing system was laid out over are asked as well as the class, +/// and the letters of other alphabets keep their one cell. +fn overcharged(ch: char) -> bool { + ch.width() == Some(1) && (ch.width_cjk() == Some(2) || laid_out_by_far_east(ch)) +} + +/// The blocks a Far-Eastern code page spells in two bytes, and a console reading +/// those bytes therefore reserves two cells for. +/// +/// Kept to the blocks an interface is drawn out of — punctuation, rules, shading, +/// arrows, shapes, enclosed digits — rather than applied to everything above +/// ASCII, because what is left out is what a person brought with them: a path +/// with an `é`, a process named in Greek. Rewriting those would be editing +/// somebody's data to cover for the console. +/// +/// Only consulted once the console has been measured charging two, so on every +/// terminal that charges one this answers nothing at all. +fn laid_out_by_far_east(ch: char) -> bool { + let code = ch as u32; + matches!( + code, + // Punctuation and signs: `· × ° ± ¼ «`. + 0x00A1..=0x00BF + // Dashes, quotes, bullets, the ellipsis. + | 0x2010..=0x205E + // The currency sign a price or a path may carry. + | 0x20A0..=0x20BF + // Signs like `№`, arrows of every shape, and the maths an interface + // leans on for `≈ ≥ ⋅`, and the keys a Mac legends with a shape. + | 0x2100..=0x218F | 0x2190..=0x21FF | 0x2200..=0x23FF + // Digits and letters with a ring drawn round them. + | 0x2460..=0x24FF + // Box drawing, block shading, geometric shapes, and the symbols and + // dingbats a status line is made of. + | 0x2500..=0x2BFF + ) +} + +/// What an overcharged character is worth in characters the console accepts. +/// +/// Every answer is a single ASCII column, because ASCII is the one thing a +/// Far-Eastern console never reprices, and every one is chosen to say the same +/// thing at the same width: a rule stays a rule, a gauge stays a gauge, a tick +/// still points the way it did. A shape with no honest equivalent becomes `?`, +/// which is what the console would have shown in its place anyway. +fn one_cell(ch: char) -> char { + match ch { + // Rules: the chrome of every card on the screen. + '─' | '━' | '═' | '┄' | '┅' | '┈' | '┉' => '-', + '│' | '┃' | '║' | '┆' | '┇' | '┊' | '┋' => '|', + // Corners and junctions both mean "these lines meet here", which ASCII + // spells with one character. + '┌' | '┍' | '┎' | '┏' | '╭' | '╔' | '┐' | '┑' | '┒' | '┓' | '╮' | '╗' | '└' | '┕' | '┖' + | '┗' | '╰' | '╚' | '┘' | '┙' | '┚' | '┛' | '╯' | '╝' | '├' | '┝' | '┞' | '┟' | '┠' + | '┡' | '┢' | '┣' | '╠' | '┤' | '┥' | '┦' | '┧' | '┨' | '┩' | '┪' | '┫' | '╣' | '┬' + | '┭' | '┮' | '┯' | '┰' | '┱' | '┲' | '┳' | '╦' | '┴' | '┵' | '┶' | '┷' | '┸' | '┹' + | '┺' | '┻' | '╩' | '┼' | '┽' | '┾' | '┿' | '╀' | '╁' | '╂' | '╃' | '╄' | '╅' | '╆' + | '╇' | '╈' | '╉' | '╊' | '╬' | '╪' | '╫' => '+', + // Gauges and shading, densest to faintest. + '█' | '▓' | '▄' | '▅' | '▆' | '▇' | '▉' | '■' | '▪' | '◆' | '◼' => { + '#' + } + '▒' | '▂' | '▃' => '%', + '░' | '▁' | '□' | '▫' | '◻' => '.', + // Status. A tick still has to read as a tick, so it keeps the shape + // ASCII art has always used for one; a cross keeps the one it had. + '✓' | '✔' | '☑' => 'v', + '✗' | '✘' | '☒' | '☓' | '×' => 'x', + // A box nobody is allowed to toggle says "not this one" with the same + // letter a cross uses. + '⊘' => 'x', + '●' | '◉' => '@', + '○' | '◎' | '◦' => 'o', + // Direction. + '▶' | '▸' | '►' | '▹' | '→' | '⇒' | '➤' | '»' => '>', + '◀' | '◂' | '◄' | '◃' | '←' | '⇐' | '«' => '<', + // Both directions at once has no spelling in one letter. An equals sign + // is the closest one that still says the two sides belong together. + '⇄' | '⇅' | '↔' | '↕' => '=', + '▲' | '△' | '▴' | '⌃' | '↑' | '⇧' => '^', + '▼' | '▽' | '▾' | '↓' | '⇩' => 'v', + // An arrow that turns the corner into something: a right angle is what + // a backslash looks like. + '↳' => '\\', + // The separator this interface puts between two thoughts, and the bullets. + '·' | '‧' | '⋅' | '÷' => '/', + '•' | '‣' | '★' | '☆' => '*', + // A word the row ran out of room for, and a line the row ran out of. + '…' | '⋯' | '⋮' => '.', + '—' | '–' | '―' | '−' => '-', + '“' | '”' | '„' | '‟' => '"', + '‘' | '’' | '‚' | '‛' => '\'', + '±' => '+', + '≈' => '~', + '≥' => '>', + '≤' => '<', + // The keys a Mac legends with a shape no other keyboard carries. + '⌘' => '#', + '⌥' => 'A', + '⌫' => '<', + '⌦' => '>', + '⇥' => '>', + // A digit with a ring round it: the ring is the part being charged for. + '①'..='⑨' => char::from_u32(ch as u32 - '①' as u32 + '0' as u32).unwrap_or('?'), + _ => '?', + } +} + +#[cfg(test)] +mod tests { + use super::{cheaper, one_cell, overcharged, Fit}; + use ratatui::{ + buffer::Buffer, + layout::Rect, + style::Style, + widgets::{Block, BorderType, Borders, Widget}, + }; + use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; + + /// A narrow frame, spelled out so the tests read as rows of a screen. + fn cramped() -> Fit { + Fit { overcharging: true } + } + + /// What a row of the buffer reads as. The cell behind a wide character is + /// reset to a blank and no eye ever sees it, so it is stepped over here the + /// same way the terminal steps over it. + fn read(buffer: &Buffer, y: u16) -> String { + let mut row = String::new(); + let mut hidden = 0usize; + for x in 0..buffer.area.width { + let Some(cell) = buffer.cell((x, y)) else { + continue; + }; + if hidden > 0 { + hidden -= 1; + continue; + } + let symbol = cell.symbol(); + hidden = symbol.width().saturating_sub(1); + row.push_str(symbol); + } + row + } + + #[test] + fn the_chrome_of_this_interface_is_exactly_what_the_console_overcharges() { + // The class is not a curiosity. A card's border, the separator between + // two thoughts, the ellipsis that ends a truncated name and the gauge + // that says how full a disk is are all in it. + for ch in [ + '─', '│', '╭', '╮', '╯', '╰', '·', '…', '—', '↑', '↓', '✓', '×', '█', '▒', '▾', '①', + '●', '“', '░', '►', '⊘', '⇄', + ] { + assert!(overcharged(ch), "{ch} should be in dispute"); + assert!( + one_cell(ch).is_ascii(), + "{ch} is in dispute and must be exchanged, not argued about" + ); + } + } + + #[test] + fn chinese_and_the_latin_alphabet_keep_their_own_price() { + // Two cells to both sides, or one to both: no dispute, nothing to + // rewrite. This is what keeps a person's paths out of the repair. + for ch in ['回', '收', '站', ',', ':', 'é', 'ü', 'Ω', 'ф', '十'] { + assert!( + cheaper(ch).is_none(), + "{ch} costs the same to both sides and must survive" + ); + } + } + + #[test] + fn nothing_is_exchanged_for_a_character_with_the_same_problem() { + // Sweeps the whole plane: whatever this module answers with must be one + // cell by both tables and spellable by a console that reprices + // everything else. A gap here is a row that still overflows. + for code in 0x20u32..=0xFFFF { + let Some(ch) = char::from_u32(code) else { + continue; + }; + let Some(instead) = cheaper(ch) else { + continue; + }; + assert!(instead.is_ascii(), "{ch} was paid for with {instead}"); + assert_eq!( + instead.width(), + Some(1), + "{ch} bought {instead}, which is not one column" + ); + assert_eq!( + instead.width_cjk(), + Some(1), + "{ch} bought {instead}, which is overcharged too" + ); + } + } + + #[test] + fn an_overcharged_frame_comes_back_as_a_row_that_fits() { + let mut buffer = Buffer::empty(Rect::new(0, 0, 9, 1)); + buffer.set_string(0, 0, "╭─╮ · ░▒█", Style::default()); + cramped().carry(&mut buffer); + assert_eq!(read(&buffer, 0), "+-+ / .%#"); + } + + #[test] + fn a_frame_is_left_alone_on_a_console_that_charges_one() { + let mut buffer = Buffer::empty(Rect::new(0, 0, 9, 1)); + buffer.set_string(0, 0, "╭─╮ · ░▒█", Style::default()); + Fit { + overcharging: false, + } + .carry(&mut buffer); + assert_eq!(read(&buffer, 0), "╭─╮ · ░▒█"); + } + + #[test] + fn chinese_keeps_both_of_its_cells_and_its_neighbour_keeps_one() { + // 回收站 spends six cells and the middot after it one, so the row is + // seven wide before and after. The repair may not move text it is not + // touching, which is the whole difference between this and a redraw. + let mut buffer = Buffer::empty(Rect::new(0, 0, 7, 1)); + buffer.set_string(0, 0, "回收站·", Style::default()); + cramped().carry(&mut buffer); + assert_eq!(read(&buffer, 0), "回收站/"); + } + + /// The source of every screen this crate draws, so the set of glyphs is the + /// program's and not a list someone keeps up to date by hand. + const FACES: &[&str] = &[ + include_str!("app.rs"), + include_str!("theme.rs"), + include_str!("views.rs"), + ]; + + #[test] + fn every_glyph_this_interface_draws_has_a_price() { + // What this test stands in for is the mistake that spent a week: a glyph + // put into a card in one file and never priced in the table in another. + // Nothing else in the suite notices, because on every terminal that + // charges one cell the row is exactly as wide as the layout says, and + // the frame only falls apart in front of a person on a Chinese console. + let mut drawn = String::new(); + for face in FACES { + for ch in face.chars() { + if ch as u32 <= 0x7F || ch.width() != Some(1) || drawn.contains(ch) { + continue; + } + drawn.push(ch); + let Some(instead) = cheaper(ch) else { + continue; + }; + assert!( + instead.is_ascii() && instead != '?', + "`{ch}` is drawn by this interface, so the console must not be left guessing what it was meant to be" + ); + } + } + assert!( + drawn.chars().count() > 15, + "the scan found {drawn:?}, which is not this interface" + ); + } + + #[test] + fn a_card_is_still_a_card_after_the_exchange() { + // ratatui's own border widget rather than a hand-written row, so this + // fails if the library ever draws a card with a character that has been + // left unpriced. + let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 3)); + Block::default() + .borders(Borders::ALL) + .border_type(BorderType::Rounded) + .render(buffer.area, &mut buffer); + cramped().carry(&mut buffer); + assert_eq!(read(&buffer, 0), "+---+"); + assert_eq!(read(&buffer, 1), "| |"); + assert_eq!(read(&buffer, 2), "+---+"); + } +} diff --git a/crates/squid-tui/src/lib.rs b/crates/squid-tui/src/lib.rs index 91b7e2b..f475ffa 100644 --- a/crates/squid-tui/src/lib.rs +++ b/crates/squid-tui/src/lib.rs @@ -3,8 +3,18 @@ //! [`run`] owns the whole screen: it installs raw mode plus the alternate //! buffer, drives [`App::tick`] on a fixed beat, and always puts the terminal //! back the way it found it — including when a render panics. +//! +//! It also decides what "the whole screen" means, once per beat. That sounds +//! like a detail and is the difference between an interface and a pile of +//! previous frames: see [`drawable`] and [`repaint`]. +//! +//! Then it asks what a column costs, because on a console that charges two for +//! the characters the layout measured as one, every row of the interface is +//! longer than the screen and the pile of previous frames comes back on its +//! own: see [`glyphs`]. pub mod app; +pub mod glyphs; pub mod job; pub mod theme; pub mod views; @@ -13,15 +23,24 @@ use app::{Action, App}; use crossterm::{ event::{poll, read, Event, KeyCode, KeyEventKind, KeyModifiers}, execute, - terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, + terminal::{ + disable_raw_mode, enable_raw_mode, Clear, ClearType, EnterAlternateScreen, + LeaveAlternateScreen, + }, }; -use ratatui::{backend::CrosstermBackend, Terminal}; -use std::io::{stdout, Write}; +use ratatui::{backend::CrosstermBackend, layout::Rect, Terminal, TerminalOptions, Viewport}; +use squid_platform::console::Geometry; +use std::io::{stdout, Stdout, Write}; use std::time::{Duration, Instant}; /// How often the UI drains progress events and repaints. const TICK: Duration = Duration::from_millis(250); +/// The shape to draw into when a terminal cannot be asked for one. +const FALLBACK: (u16, u16) = (80, 24); + +type Screen = Terminal>; + /// Restores the terminal on the way out, panic included. Without the panic /// hook a bug would leave the user's shell in raw mode. struct TerminalGuard; @@ -64,22 +83,154 @@ pub fn run() -> anyhow::Result<()> { // first and defaulting downwards is what keeps Apple Terminal and a bare // ssh session readable instead of garbled. crate::theme::init(); + squid_platform::console::note(&format!("start {}", squid_platform::console::report())); let guard = TerminalGuard::install()?; + // The line that settles the argument about which buffer the interface is + // on: this is measured after the alternate screen went up, and it is the + // last moment at which the screen can still be recognised as one the + // console made for us. The `vt=` on both lines says which way the words are + // reaching the glass, and the difference between the two lines says whether + // the terminal library managed to turn on escape-sequence output at all. + squid_platform::console::adopt(); + squid_platform::console::note(&format!("alternate {}", squid_platform::console::report())); let result = run_inner(); + squid_platform::console::note("leaving"); drop(guard); + squid_platform::console::note("restored"); result } +/// The rectangle the interface may paint. +/// +/// A window that reports 180 columns is only 180 columns wide if something +/// exists to hold them. Modern terminals own both numbers and answer +/// [`Geometry::None`](Geometry), so the window is the answer; a legacy Windows +/// console reports a buffer as well, and the smaller of the two is the only +/// area where writing cannot spill onto the following row. +fn drawable(window: (u16, u16), console: Option) -> Rect { + let (columns, rows) = match console { + Some(geometry) => geometry.drawable(), + None => window, + }; + Rect::new(0, 0, columns, rows) +} + +/// Everything the screen reports about its own shape, right now. +/// +/// Three numbers, because one is not enough to notice trouble. The window is +/// what the user is looking at; the area is what may be painted without +/// spilling into the next row; the console geometry is the pair of measurements +/// behind both, and it is the only one that sees a buffer being resized +/// underneath an interface whose drawable area happens not to move. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Reported { + window: (u16, u16), + area: Rect, + console: Option, +} + +/// Ask the terminal, then the console behind it, what it can hold right now. +fn current_shape() -> Reported { + let window = crossterm::terminal::size().unwrap_or(FALLBACK); + let console = squid_platform::console::geometry(); + Reported { + window, + area: drawable(window, console), + console, + } +} + +/// The screen as it was when the interface last painted it, so that a wipe +/// happens when the shape changes and not every beat. Repainting on an +/// unchanged size would cost a flicker four times a second for the session. +/// +/// What it remembers is the whole measurement on purpose. A window can grow +/// while the area stays clamped to a buffer that refused to grow with it, and +/// then the columns that just came into view are full of whatever the console +/// remembers; a buffer can also be resized by the console host while both the +/// window and the area stay put, which moves the frame without asking. Either +/// way the diff is now comparing coordinates that no longer mean the same cell. +#[derive(Debug)] +struct Drawn { + reported: Reported, +} + +impl Drawn { + fn new(reported: Reported) -> Drawn { + Drawn { reported } + } + + /// `Some` when the screen is no longer the shape last drawn into. + fn observe(&mut self, seen: Reported) -> Option { + (self.reported != seen).then(|| { + self.reported = seen; + seen.area + }) + } +} + +/// The screen changed shape, which no diff renderer survives on its own. +/// +/// The frame is drawn by writing the cells that differ from the previous one. +/// Resizing moves content around inside the console without asking, so cells +/// this renderer believes are empty are holding an older frame, and cells it +/// believes are filled are somewhere else entirely. Growing the console's +/// buffer is tried first — it is the actual fault on Windows 10 — and then the +/// whole buffer is wiped so the next frame starts from a screen that matches +/// what the diff assumes. +fn repaint(terminal: &mut Screen, drawn: &mut Drawn) -> anyhow::Result<()> { + // A console that accepted a bigger buffer has just handed back columns, so + // the answer worth drawing into is asked for again. + let repaired = squid_platform::console::repair(); + if repaired { + drawn.reported = current_shape(); + } + let area = drawn.reported.area; + squid_platform::console::note(&format!( + "repaint {}x{} repair={repaired}", + area.width, area.height + )); + let mut out = stdout(); + execute!(out, Clear(ClearType::All))?; + out.flush()?; + terminal.resize(area)?; + Ok(()) +} + fn run_inner() -> anyhow::Result<()> { let mut app = App::new()?; - let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?; + // The viewport is fixed rather than full-screen because the size of a full + // screen is whatever the terminal says it is, and on a legacy console that + // answer is a lie the renderer would then paint into. + let seen = current_shape(); + let mut terminal = Terminal::with_options( + CrosstermBackend::new(stdout()), + TerminalOptions { + viewport: Viewport::Fixed(seen.area), + }, + )?; + let mut drawn = Drawn::new(seen); terminal.hide_cursor()?; terminal.clear()?; + // Priced against the screen, not against the tables the layout was drawn + // with, and only now: measuring spends one character on whatever the console + // is showing, and the screen is not ours to spend until the alternate one is + // up. The character it writes is covered by the first frame. + let fit = glyphs::Fit::measure(); let mut next_tick = Instant::now() + TICK; while !app.should_quit { app.tick(); - terminal.draw(|frame| views::draw(frame, &app))?; + let wanted = current_shape(); + if drawn.observe(wanted).is_some() { + repaint(&mut terminal, &mut drawn)?; + } + terminal.draw(|frame| { + views::draw(frame, &app); + // The last moment at which a row that is too long for this console + // can still be made to fit is after the widgets and before the wire. + fit.carry(frame.buffer_mut()); + })?; if poll(next_tick.saturating_duration_since(Instant::now()))? { match read()? { Event::Key(key) if key.kind == KeyEventKind::Press => { @@ -100,6 +251,9 @@ fn run_inner() -> anyhow::Result<()> { app.cancel_jobs(); app.should_quit = true; } + // Nothing to do: the beat above re-reads the geometry from the + // console instead of trusting this event, which also covers the + // resizes a legacy console never reports. Event::Resize(_, _) => {} _ => {} } @@ -111,3 +265,150 @@ fn run_inner() -> anyhow::Result<()> { terminal.show_cursor()?; Ok(()) } + +#[cfg(test)] +mod tests { + use super::{drawable, Drawn, Reported}; + use ratatui::layout::Rect; + use squid_platform::console::Geometry; + + /// A console that can display whatever it is showing, so only the window + /// and the buffer are in disagreement here. + fn console(window: (u16, u16), buffer: (u16, u16)) -> Option { + Some(Geometry { + window, + origin: (0, 0), + buffer, + limit: (window.0.max(buffer.0), window.1.max(buffer.1).max(9_999)), + }) + } + + fn reported(window: (u16, u16), area: (u16, u16), buffer: (u16, u16)) -> Reported { + Reported { + window, + area: Rect::new(0, 0, area.0, area.1), + console: console(window, buffer), + } + } + + fn painted(window: (u16, u16), area: (u16, u16), buffer: (u16, u16)) -> Drawn { + Drawn::new(reported(window, area, buffer)) + } + + #[test] + fn a_terminal_that_owns_its_buffer_keeps_the_size_it_reported() { + // Every terminal drawn on so far — Terminal.app, Windows Terminal, + // konsole, a bare ssh session — owns both numbers, so its word is the + // layout's word. + assert_eq!(drawable((140, 45), None), Rect::new(0, 0, 140, 45)); + } + + #[test] + fn a_window_wider_than_the_cells_that_exist_is_not_a_place_to_draw() { + // The maximized-on-Windows-10 frame: 180 columns of window over 100 + // columns of buffer. Column 101 is column 0 of the next row, and every + // line under it slides. + assert_eq!( + drawable((180, 50), console((180, 50), (100, 30))), + Rect::new(0, 0, 100, 30) + ); + } + + #[test] + fn a_consoles_history_is_not_extra_interface() { + // Rows of scrollback are the shell's, not the interface's. + assert_eq!( + drawable((120, 40), console((120, 40), (120, 900))), + Rect::new(0, 0, 120, 40) + ); + } + + #[test] + fn the_screen_is_wiped_when_it_changes_and_only_then() { + let mut drawn = painted((100, 30), (100, 30), (100, 900)); + assert_eq!( + drawn.observe(reported((100, 30), (100, 30), (100, 900))), + None, + "an unchanged screen must not be wiped again" + ); + assert_eq!( + drawn.observe(reported((140, 40), (140, 40), (140, 900))), + Some(Rect::new(0, 0, 140, 40)) + ); + assert_eq!( + drawn.observe(reported((140, 40), (140, 40), (140, 900))), + None, + "the wipe is once per change, not once per beat" + ); + } + + #[test] + fn a_console_that_scrolled_its_own_buffer_moves_the_picture_without_moving_the_size() { + // Every number the layout reads is unchanged here, and the frame is + // still on the wrong cells: the console slid its window down the buffer + // underneath the interface. The measurement carries the origin for this + // case and nobody has to explain why the screen looks frozen. + let mut drawn = painted((120, 30), (120, 30), (120, 9_000)); + let scrolled = Reported { + window: (120, 30), + area: Rect::new(0, 0, 120, 30), + console: Some(Geometry { + window: (120, 30), + origin: (0, 897), + buffer: (120, 9_000), + limit: (120, 30), + }), + }; + assert_eq!(drawn.observe(scrolled), Some(Rect::new(0, 0, 120, 30))); + } + + #[test] + fn a_window_that_grew_is_repainted_even_when_the_buffer_stayed_behind() { + // The clamped case: 180 columns of window over the 100 columns of + // buffer a console refused to grow. The drawing area has not moved, + // but eighty columns of that console's memory just came into view. + let mut drawn = painted((100, 30), (100, 30), (100, 30)); + assert_eq!( + drawn.observe(reported((180, 30), (100, 30), (100, 30))), + Some(Rect::new(0, 0, 100, 30)), + "newly visible columns must not keep what the console remembered" + ); + } + + #[test] + fn a_buffer_moved_under_an_unchanged_window_is_repainted_too() { + // Nothing the interface lays out has changed: the window is the same + // and the drawable area is still clamped by it. The console host has + // resized the buffer behind the frame, which is exactly the move a + // coordinate-based diff cannot see, so the numbers behind the layout + // have to be watched, not only the layout. + let mut drawn = painted((120, 30), (120, 30), (120, 30)); + assert_eq!( + drawn.observe(reported((120, 30), (120, 30), (120, 60))), + Some(Rect::new(0, 0, 120, 30)), + "a buffer that moved is a screen that has to be wiped" + ); + } + + #[test] + fn scrollback_that_grew_past_the_frame_is_not_a_change_of_pace() { + // Height the console offers as history is not height the interface + // paints into, so growth entirely inside scrollback must not buy a + // flicker. A buffer that only grew taller than a window that is the + // limit either way is the one case ignored on purpose. + let mut drawn = Drawn::new(Reported { + window: (120, 30), + area: Rect::new(0, 0, 120, 30), + console: console((120, 30), (120, 900)), + }); + assert_eq!( + drawn.observe(Reported { + window: (120, 30), + area: Rect::new(0, 0, 120, 30), + console: console((120, 30), (120, 1_800)), + }), + Some(Rect::new(0, 0, 120, 30)), + "documented cost: the console changed, so the frame is redrawn" + ); + } +}