diff --git a/Cargo.lock b/Cargo.lock index 6841548..96eb66d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1034,6 +1034,7 @@ dependencies = [ "serde", "squid-core", "sysinfo", + "unicode-width 0.2.0", "walkdir", "windows-sys 0.59.0", "winreg", diff --git a/crates/squid-platform/Cargo.toml b/crates/squid-platform/Cargo.toml index 7b697f9..af72749 100644 --- a/crates/squid-platform/Cargo.toml +++ b/crates/squid-platform/Cargo.toml @@ -14,6 +14,7 @@ dirs.workspace = true walkdir.workspace = true plist.workspace = true rayon.workspace = true +unicode-width.workspace = true [target.'cfg(unix)'.dependencies] libc.workspace = true diff --git a/crates/squid-platform/src/console.rs b/crates/squid-platform/src/console.rs index 03b3d39..028a13e 100644 --- a/crates/squid-platform/src/console.rs +++ b/crates/squid-platform/src/console.rs @@ -274,7 +274,8 @@ impl Prices { } /// The answer for a screen that cannot be asked, which is the one a code - /// page implies. See [`charged_by_code_page`] for what that answer is worth. + /// page implies. The function that guesses it, `charged_by_code_page`, says + /// for itself what that answer is worth. pub fn implied(code_page: u32) -> Prices { Prices { source: "implied", diff --git a/crates/squid-platform/src/currency.rs b/crates/squid-platform/src/currency.rs new file mode 100644 index 0000000..860562b --- /dev/null +++ b/crates/squid-platform/src/currency.rs @@ -0,0 +1,430 @@ +//! What a console charges for the characters an interface is drawn out of, and +//! what to draw when it charges more than the layout paid. +//! +//! A layout measures a row in columns and charges every character the number of +//! columns it measured: 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 leaves each terminal free to charge +//! either one cell or two for them. Where the two disagree is exactly where the +//! chrome of an interface lives: the rules `─│╭`, the shading `█▒░`, the arrows +//! `↑↓`, the ticks `✓`, the middot `·`, the ellipsis `…`. +//! +//! Two programs pay for that disagreement in two different ways, and both of +//! them are this module's business. An interface that is a pile of cards is built +//! out of nothing but ambiguous characters, so on a console that charges two +//! every row of it is several cells longer than the screen, and what goes past +//! the right edge arrives at the start of the row below: several copies of one +//! frame at several offsets, which looks like a renderer that cannot count. It is +//! counting correctly, in a currency the console will not accept. A command-line +//! program does not measure its rows at all — it repeats `█` twenty-eight times +//! for a gauge and lets the console do the arithmetic, and prints a table whose +//! rows are each a screen and a half long. Same price, same receipt. +//! +//! The price is asked, not looked up, and it is asked of every character +//! separately: [`crate::console::prices`] writes each one and reads back what it +//! cost, and [`Exchange`] turns those answers into what to draw instead. Nothing +//! promises that rules, shading and punctuation land on the same side of a code +//! page and a font, so one answer for the lot is one character deep — the console +//! this was chased through had room for the rounded cards and none for the `░` +//! inside them. On such a glass the card stays rounded and the gauge is paid for +//! in `.`, `%`, `#`. A character nobody asked about is charged the pessimistic +//! price, because a glyph that escaped the list is a glyph nobody checked. +//! +//! 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. +//! +//! This lives beside the console rather than inside the interface because the +//! command line and the interface buy the same screen at the same counter. The +//! half that cannot travel is the walking of a finished ratatui frame — a +//! different library's question, so it stays in [`squid_tui::glyphs`]. +//! +//! [`squid_tui::glyphs`]: ../../squid_tui/glyphs/index.html + +use crate::console::{note, Prices, SymbolCells}; +use unicode_width::UnicodeWidthChar; + +/// What to draw in place of every character this console cannot afford. +/// +/// Held as a table rather than as one verdict, for the reason in the module +/// documentation: the price is set per character, so the answer is per character +/// too. A frame is tens of thousands of cells and a beat is a quarter of a +/// second, so the answer is looked up rather than worked out — and the table +/// holds the replacement rather than a bit saying *this one is wrong*, because +/// the character is what the caller needs. +pub struct Exchange { + /// The answers this table was built from, kept so a log can say what the + /// glass charged and a test can ask what one glyph cost. + prices: Prices, + /// Indexed by code point, with `None` for every character this console can + /// afford. Empty when nothing is overcharged, which is what makes + /// [`Exchange::afford`] cheap on the terminals where there is nothing to do. + table: Vec>, +} + +impl Exchange { + /// Build the table from one console's answers, and write those answers into + /// the trace. + /// + /// The `note` belongs here rather than at each call site because it is the + /// only record of why a gauge came out as `#`: a person comparing the plain + /// frame with the drawn one needs to be told what the glass charged for `░`, + /// and both the interface and the command line owe them that line. + pub fn new(prices: Prices) -> Exchange { + let table = if prices.overcharged() { + (0..=PRICED_UPTO) + .map(|code| { + char::from_u32(code) + // Two questions have to be answered before a character is + // rewritten: is this one owned at all (not Chinese, not + // somebody's path), and does *this* console actually + // charge two cells for it. The first is a rule, the + // second is a measurement, and a glyph that fails either + // one keeps what it was drawn with. + .filter(|&ch| prices.price(ch) == SymbolCells::Double) + .and_then(cheaper) + }) + .collect() + } else { + Vec::new() + }; + note(&format!("symbols {}", prices.text())); + Exchange { prices, table } + } + + /// The answers this table was built from. + pub fn prices(&self) -> &Prices { + &self.prices + } + + /// Whether this console charges for anything a layout measured as one cell, + /// which is the one question worth asking before rewriting anything. + pub fn overcharged(&self) -> bool { + !self.table.is_empty() + } + + /// The character to draw in place of this one, or `None` when this console + /// can afford the character it was given. + pub fn change(&self, ch: char) -> Option { + self.table.get(ch as usize).copied().flatten() + } + + /// One run of text at the price this console charges. + /// + /// This is the door a command-line program prints through: it has no frame to + /// walk, only strings, and a gauge built by repeating `█` twenty-eight times + /// is twenty-eight cells wide as far as the console is concerned — the only + /// moment a row like that can still be made to fit is before the bytes leave. + pub fn afford(&self, text: &str) -> String { + if !self.overcharged() { + return text.to_string(); + } + text.chars() + .map(|ch| self.change(ch).unwrap_or(ch)) + .collect() + } +} + +/// Every character in these pieces of chrome whose price has to be asked rather +/// than looked up. +/// +/// The list is derived from the program rather than maintained by hand, which is +/// the whole lesson of the single-probe version: a glyph put into a screen in one +/// file and never mentioned in another produced a frame that was correct on every +/// terminal but one, and no test could see it. Hand each piece of chrome this +/// program draws out of — its own source, a widget library's symbols — and the +/// questions to ask come out of the answer. +pub fn witnesses(pieces: impl IntoIterator>) -> Vec { + let mut asked: Vec = Vec::new(); + for piece in pieces { + for ch in piece.as_ref().chars() { + if disputed(ch) && !asked.contains(&ch) { + asked.push(ch); + } + } + } + asked +} + +/// The highest code point the price of is worth a slot in the table, which is +/// one past the last range a Far-Eastern console was ever seen repricing. +pub const PRICED_UPTO: u32 = 0x2BFF; + +/// True when this is a character a console is free to charge two cells for. +/// +/// In dispute is not the same as overcharged: whether *this* console does it is +/// measured, per character, by [`Exchange`]. What this answers is which +/// characters are worth asking about, and which ones the frame is allowed to +/// rewrite once the console has said. +/// +/// 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 Chinese console charges it to +/// characters the class leaves out. `░` is not Ambiguous at all, and it is what +/// this interface fills its gauges with — and it is the character the single probe +/// never asked about, which is how a frame whose rules were measured fair still +/// overflowed. Anything this list declines to ask about is a character the console +/// prices without being asked, so it errs towards the questions. +/// 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. +pub fn disputed(ch: char) -> bool { + ch.width() == Some(1) && (ch.width_cjk() == Some(2) || laid_out_by_far_east(ch)) +} + +/// The character to draw instead, or `None` when this one is fairly priced. +pub fn cheaper(ch: char) -> Option { + disputed(ch).then(|| one_cell(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, disputed, one_cell, witnesses, Exchange, PRICED_UPTO}; + use crate::console::{Prices, SymbolCells}; + use unicode_width::UnicodeWidthChar; + + /// The worst answer a probe can bring back: two cells for everything the + /// layout measured as one. + fn cramped() -> Exchange { + Exchange::new(Prices::flat(SymbolCells::Double)) + } + + /// The answer every terminal not on a Far-Eastern code page gives. + fn fairly_priced() -> Exchange { + Exchange::new(Prices::flat(SymbolCells::Single)) + } + + /// The shape of the unlucky answer: the rules cost one cell, the shading + /// costs two. Whether a console really charges this way is measured, never + /// assumed — this is the case a single price can never express, so it is + /// built rather than waited for. + fn rules_affordable_gauges_not() -> Exchange { + let mut asked = Vec::new(); + for ch in "░▒▓█".chars() { + asked.push((ch, SymbolCells::Double)); + } + for ch in "│─╭·…↑✓".chars() { + asked.push((ch, SymbolCells::Single)); + } + Exchange::new(Prices::measured(asked, SymbolCells::Single)) + } + + #[test] + fn the_chrome_an_interface_is_drawn_from_is_what_a_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 [ + "─", "│", "╭", "╮", "╯", "╰", "·", "…", "—", "↑", "↓", "✓", "×", "█", "▒", "▾", "①", + "●", "“", "░", "►", "⊘", "⇄", + ] { + let ch = ch.chars().next().expect("one character"); + assert!(disputed(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 word in ["回", "收", "站", ",", ":", "é", "ü", "Ω", "ф", "十"] { + let ch = word.chars().next().expect("one character"); + 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 a_line_pays_for_itself_in_characters_the_console_accepts() { + // The command line's whole need in one assertion: what comes out is all + // one column wide, so a gauge of twenty-eight of them is twenty-eight + // columns and the row under it still holds its own text. + let paid = cramped().afford(" ✓ [░▒█] · ↑↓ …"); + assert_eq!(paid, " v [.%#] / ^v ."); + for ch in paid.chars() { + assert_eq!(ch.width_cjk(), Some(1), "{paid} still charges two"); + } + } + + #[test] + fn text_untouched_is_the_answer_on_a_console_that_charges_one() { + let line = " ✓ [░▒█] · 回收站"; + assert!(!fairly_priced().overcharged()); + assert_eq!(fairly_priced().afford(line), line); + } + + #[test] + fn only_the_overcharged_half_of_a_line_changes_hands() { + // The console this module was written for and still got wrong once: the + // rule was asked, found fair, and that one answer became the price of + // every glyph on the screen. + let exchange = rules_affordable_gauges_not(); + assert_eq!(exchange.afford("│ C: ░░ █"), "│ C: .. #"); + } + + #[test] + fn witnesses_are_the_chrome_they_are_handed() { + let asked = witnesses(["│░ clean", " ✓ 回"]); + assert!(asked.contains(&'│') && asked.contains(&'░') && asked.contains(&'✓')); + assert!(!asked.contains(&'c'), "ascii is never in dispute"); + assert!(!asked.contains(&'回'), "a person's text is not in dispute"); + assert_eq!(witnesses(["█"]), witnesses(["██"]), "asked once"); + } + + #[test] + fn the_table_reaches_every_character_a_console_is_seen_to_reprice() { + // A character above the table is one nothing reprices, so the last slot + // has to be past the last block a Far-Eastern writing system was laid out + // over — otherwise the exchange answers `?` where it should have had a plan. + assert!(char::from_u32(PRICED_UPTO).is_some()); + for ch in ["─", "█", "■", "→", "①"] { + let ch = ch.chars().next().expect("one character"); + assert!( + (ch as u32) <= PRICED_UPTO, + "{ch} is off the end of the table" + ); + } + } +} diff --git a/crates/squid-platform/src/lib.rs b/crates/squid-platform/src/lib.rs index 883c94b..0dd5ba6 100644 --- a/crates/squid-platform/src/lib.rs +++ b/crates/squid-platform/src/lib.rs @@ -12,6 +12,7 @@ use std::path::{Path, PathBuf}; pub mod apps; pub mod console; +pub mod currency; pub mod leftovers; #[cfg(unix)] pub mod volumes; diff --git a/crates/squid-tui/src/glyphs.rs b/crates/squid-tui/src/glyphs.rs index 0c0f198..8b9e835 100644 --- a/crates/squid-tui/src/glyphs.rs +++ b/crates/squid-tui/src/glyphs.rs @@ -1,139 +1,44 @@ -//! Buying the screen at the price the console actually charges for it. +//! Carrying a finished frame to the console it is about to be drawn on. //! -//! 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 `…`. +//! What a console charges for the characters an interface is drawn out of, and +//! what to draw when it charges more than the layout paid, is +//! [`squid_platform::currency`]: the command line buys the same screen at the +//! same counter, so the price list and the exchange live beside the console +//! rather than beside a renderer. What cannot travel is the walk over a finished +//! ratatui [`Buffer`] — a question about somebody else's data structure — so +//! that, and only that, is what this crate adds. //! -//! 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. +//! Two things live here because of it. [`witnesses`] is the list of glyphs this +//! interface is drawn out of, which only this crate can know: the source of the +//! files every screen is built from, plus the symbols ratatui's widgets draw on +//! its behalf. [`Carry`] is the walk that spends the answers on a frame. //! -//! 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. +//! The invariant worth defending is that those two are one list. A glyph drawn +//! but never priced is invisible on every terminal that charges one cell for +//! everything, and overflows a row on the one that does not, so the mistake is +//! undetectable from a screenshot and lands in front of exactly one person. The +//! last test here is what holds the two halves together. //! -//! The exchange is decided character by character, which is the part that took -//! the longest to get right. Rules, shading and punctuation are priced one at a -//! time by the code page and font a console was left on, nothing binds the three -//! to the same answer, and a layout that asks about one and pays for all three is -//! one character deep — the first Chinese window this was chased through had room -//! for the rounded cards and none for the `░` inside them. So the price of every -//! glyph this interface draws is asked of the console -//! — [`squid_platform::console::prices`] takes the whole list — and the -//! rounded card a Chinese console can afford stays rounded while only the -//! blocks that it cannot are paid for in ASCII. A character that was never -//! asked about is charged the pessimistic price, because a glyph that escaped -//! the list is a glyph nobody checked. -//! -//! 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 ratatui::symbols; -use squid_platform::console::{Prices, SymbolCells}; -use unicode_width::UnicodeWidthChar; +use squid_platform::currency::{self, Exchange}; -/// What the console charges for the characters this interface is drawn from. -pub struct Fit { - /// The price list, kept so a beat can say what the glass charged and so a - /// test can ask what one glyph cost. - prices: Prices, - /// What to draw in place of each character, indexed by code point, with - /// `None` for the ones this console can afford. A frame is tens of - /// thousands of cells and a beat is a quarter of a second, so the answer is - /// looked up rather than worked out — and the table holds the replacement - /// rather than a bit saying *this one is wrong*, because the character is - /// what a cell needs and asking the price of a glyph is the only way to - /// know that a rounded corner may stay rounded while a block of shading - /// may not. - exchange: Vec>, +/// Ask this console what it charges for everything this interface draws, and +/// work out what to draw instead. +/// +/// [`squid_platform::console::prices`] measures the answers by writing each +/// character and reading back what it cost, so the Chinese console that cannot +/// afford a block of shading draws its gauges in `#` while keeping the rounded +/// cards it can afford, and Windows Terminal, a console on UTF-8 and a Mac keep +/// everything they were drawn with. +/// +/// Measuring spends characters on whatever the console is showing, which is why +/// this is called once the alternate screen is up and not at startup. +pub fn measure() -> Exchange { + Exchange::new(squid_platform::console::prices(&witnesses())) } -impl Fit { - /// Ask the console what it charges for every character this interface draws. - /// - /// [`squid_platform::console::prices`] measures the answers by writing each - /// character and reading back what it cost, so the Chinese Windows console - /// that cannot afford a block of shading draws its gauges in `#` while - /// keeping the rounded cards it can afford, and Windows Terminal, a console - /// on UTF-8 and a Mac keep everything they were drawn with. - /// - /// Measuring spends characters on whatever the console is showing, which is - /// why this is called once the alternate screen is up and not at startup. - pub fn measure() -> Fit { - Fit::priced(squid_platform::console::prices(&witnesses())) - } - - /// A console whose answers are already known: the ones a person named in the - /// environment, and the ones a test wants to pretend. - fn priced(prices: Prices) -> Fit { - let exchange = (0..=PRICED_UPTO) - .map(|code| { - char::from_u32(code) - // Two questions have to be answered before a cell is - // rewritten: is this a character this module owns at all - // (not Chinese, not somebody's path), and does *this* - // console actually charge two cells for it. The first is a - // rule, the second is a measurement, and a glyph that fails - // either one keeps what it was drawn with. - .filter(|&ch| prices.price(ch) == SymbolCells::Double) - .and_then(cheaper) - }) - .collect(); - squid_platform::console::note(&format!("symbols {}", prices.text())); - Fit { prices, exchange } - } - - /// 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 for everything there - /// is nothing to do, and this returns without touching the frame. - pub fn carry(&self, buffer: &mut Buffer) { - if !self.prices.overcharged() { - 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; - }; - // A character above the table is one no console reprices: that - // is where Chinese lives, and both sides already agree that it - // costs two cells, so it has nothing here to buy back. - if let Some(instead) = self.exchange.get(first as usize).copied().flatten() { - cell.set_char(instead); - } - } - } - } -} - -/// The highest code point the price of is worth a slot in the table, which is -/// one past the last range a Far-Eastern console was ever seen repricing. -const PRICED_UPTO: u32 = 0x2BFF; - /// The three files every screen of this interface is drawn out of. const FACES: &[&str] = &[ include_str!("app.rs"), @@ -232,157 +137,58 @@ fn drawn_by_widgets() -> Vec { /// update a table, which is exactly the thing that went wrong and looked /// perfectly fine on every terminal but one. pub fn witnesses() -> Vec { - let mut asked: Vec = Vec::new(); - let widgets = drawn_by_widgets(); - let drawn = FACES.iter().map(|face| face.to_string()); - for face in drawn.chain(widgets) { - for ch in face.chars() { - if in_dispute(ch) && !asked.contains(&ch) { - asked.push(ch); - } - } - } - asked -} - -/// The character to draw instead, or `None` when this one is fairly priced. -fn cheaper(ch: char) -> Option { - in_dispute(ch).then(|| one_cell(ch)) -} - -/// True when this is a character a console is free to charge two cells for. -/// -/// In dispute is not the same as overcharged: whether *this* console does it is -/// measured, per character, by [`Fit::measure`]. What this answers is which -/// characters are worth asking about, and which ones the frame is allowed to -/// rewrite once the console has said. -/// -/// 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 Chinese console charges it to -/// characters the class leaves out. `░` is not Ambiguous at all, and it is what -/// this interface fills its gauges with — and it is the character the single probe -/// never asked about, which is how a frame whose rules were measured fair still -/// overflowed. Anything this list declines to ask about is a character the console -/// prices without being asked, so it errs towards the questions. -/// 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 in_dispute(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 + currency::witnesses( + FACES + .iter() + .map(|face| face.to_string()) + .chain(drawn_by_widgets()), ) } -/// What an overcharged character is worth in characters the console accepts. +/// Spend a console's answers on a frame that was drawn without asking for them. /// -/// 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. - '█' | '▓' | '▄' | '▅' | '▆' | '▇' | '▉' | '■' | '▪' | '◆' | '◼' => { - '#' +/// A trait rather than a method on [`Exchange`], because the exchange is shared +/// with the command line and a command line has no frame to walk. What travels +/// is the arithmetic; this is the part that knows what a cell is. +pub trait Carry { + /// 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 for everything there is + /// nothing to do, and this returns without touching the frame. + fn carry(&self, buffer: &mut Buffer); +} + +impl Carry for Exchange { + fn carry(&self, buffer: &mut Buffer) { + if !self.overcharged() { + 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; + }; + // A character above the table is one no console reprices: that + // is where Chinese lives, and both sides already agree that it + // costs two cells, so it has nothing here to buy back. + if let Some(instead) = self.change(first) { + cell.set_char(instead); + } + } } - '▒' | '▂' | '▃' => '%', - '░' | '▁' | '□' | '▫' | '◻' => '.', - // 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, in_dispute, one_cell, witnesses, Fit, FACES}; + use super::{witnesses, Carry, FACES}; use ratatui::{ buffer::Buffer, layout::Rect, @@ -390,36 +196,9 @@ mod tests { widgets::{Block, BorderType, Borders, Widget}, }; use squid_platform::console::{Prices, SymbolCells}; + use squid_platform::currency::{self, Exchange}; use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; - /// A console that charges two cells for everything the layout measured as - /// one, which is the worst answer the probe can bring back. - fn cramped() -> Fit { - Fit::priced(Prices::flat(SymbolCells::Double)) - } - - /// A console that charges one cell for everything, so nothing here has a - /// reason to touch the frame. - fn fairly_priced() -> Fit { - Fit::priced(Prices::flat(SymbolCells::Single)) - } - - /// The console this module was written for and still got wrong: the rules - /// cost one cell, the shading costs two. Whether a console really charges this - /// way is measured, never assumed — this is the *shape* of the unlucky answer, - /// so the exchange is tested against the two sets having different prices, - /// which is the one thing a single price can never express. - fn rules_affordable_gauges_not() -> Fit { - let mut asked = Vec::new(); - for ch in "░▒▓█".chars() { - asked.push((ch, SymbolCells::Double)); - } - for ch in "│─╭·…↑✓".chars() { - asked.push((ch, SymbolCells::Single)); - } - Fit::priced(Prices::measured(asked, SymbolCells::Single)) - } - /// 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. @@ -441,59 +220,32 @@ mod tests { 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!(in_dispute(ch), "{ch} should be in dispute"); - assert!( - one_cell(ch).is_ascii(), - "{ch} is in dispute and must be exchanged, not argued about" - ); - } + /// A console that charges two cells for everything the layout measured as + /// one, which is the worst answer the probe can bring back. + fn cramped() -> Exchange { + Exchange::new(Prices::flat(SymbolCells::Double)) } - #[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" - ); - } + /// A console that charges one cell for everything, so nothing here has a + /// reason to touch the frame. + fn fairly_priced() -> Exchange { + Exchange::new(Prices::flat(SymbolCells::Single)) } - #[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" - ); + /// The console this exchange was written for and still got wrong once: the + /// rules cost one cell, the shading costs two. Whether a console really + /// charges this way is measured, never assumed — this is the *shape* of the + /// unlucky answer, so the walk is tested against the two sets having + /// different prices, which is the one thing a single price cannot express. + fn rules_affordable_gauges_not() -> Exchange { + let mut asked = Vec::new(); + for ch in "░▒▓█".chars() { + asked.push((ch, SymbolCells::Double)); } + for ch in "│─╭·…↑✓".chars() { + asked.push((ch, SymbolCells::Single)); + } + Exchange::new(Prices::measured(asked, SymbolCells::Single)) } #[test] @@ -523,6 +275,26 @@ mod tests { assert_eq!(read(&buffer, 0), "回收站/"); } + #[test] + fn a_console_that_reprices_the_gauges_keeps_the_rules_it_priced_fairly() { + // The frame this module existed for two rounds and still got wrong. One + // probe asked the price of a box-drawing rule, was answered one cell, and + // that became the price of every glyph on the screen — so the rounded card + // stayed rounded, the gauge stayed made of `█`, and every row of the + // Storage and System panels ran further than the console had cells for. + // The overflow arrived at the beginning of the row below, which is where + // the menu is: a gauge overwriting the second entry of a list is what the + // screen looked like, and it is why a price is now asked of every + // character instead of of whichever one was easiest to write. + let exchange = rules_affordable_gauges_not(); + let mut buffer = Buffer::empty(Rect::new(0, 0, 14, 1)); + buffer.set_string(0, 0, "│ C: ░░░░░ ███", Style::default()); + exchange.carry(&mut buffer); + // The rule is exactly as it was drawn, because this console was measured + // charging one cell for it; only the blocks changed hands. + assert_eq!(read(&buffer, 0), "│ C: ..... ###"); + } + #[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 @@ -537,7 +309,7 @@ mod tests { continue; } drawn.push(ch); - let Some(instead) = cheaper(ch) else { + let Some(instead) = currency::cheaper(ch) else { continue; }; assert!( @@ -552,26 +324,6 @@ mod tests { ); } - #[test] - fn a_console_that_reprices_the_gauges_keeps_the_rules_it_priced_fairly() { - // The frame this module existed for two rounds and still got wrong. One - // probe asked the price of a box-drawing rule, was answered one cell, and - // that became the price of every glyph on the screen — so the rounded card - // stayed rounded, the gauge stayed made of `█`, and every row of the - // Storage and System panels ran further than the console had cells for. - // The overflow arrived at the beginning of the row below, which is where - // the menu is: a gauge overwriting the second entry of a list is what the - // screen looked like, and it is why a price is now asked of every - // character instead of of whichever one was easiest to write. - let fit = rules_affordable_gauges_not(); - let mut buffer = Buffer::empty(Rect::new(0, 0, 14, 1)); - buffer.set_string(0, 0, "│ C: ░░░░░ ███", Style::default()); - fit.carry(&mut buffer); - // The rule is exactly as it was drawn, because this console was measured - // charging one cell for it; only the blocks changed hands. - assert_eq!(read(&buffer, 0), "│ C: ..... ###"); - } - #[test] fn the_probe_asks_the_price_of_everything_that_ends_up_on_the_screen() { // The invariant that would have caught it: the list the console is asked @@ -582,7 +334,7 @@ mod tests { let asked = witnesses(); for face in FACES { for ch in face.chars() { - if in_dispute(ch) { + if currency::disputed(ch) { assert!(asked.contains(&ch), "`{ch}` is drawn but never priced"); } } diff --git a/crates/squid-tui/src/lib.rs b/crates/squid-tui/src/lib.rs index f475ffa..f6cd862 100644 --- a/crates/squid-tui/src/lib.rs +++ b/crates/squid-tui/src/lib.rs @@ -28,6 +28,7 @@ use crossterm::{ LeaveAlternateScreen, }, }; +use glyphs::Carry as _; use ratatui::{backend::CrosstermBackend, layout::Rect, Terminal, TerminalOptions, Viewport}; use squid_platform::console::Geometry; use std::io::{stdout, Stdout, Write}; @@ -216,7 +217,7 @@ fn run_inner() -> anyhow::Result<()> { // 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 exchange = glyphs::measure(); let mut next_tick = Instant::now() + TICK; while !app.should_quit { @@ -229,7 +230,7 @@ fn run_inner() -> anyhow::Result<()> { 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()); + exchange.carry(frame.buffer_mut()); })?; if poll(next_tick.saturating_duration_since(Instant::now()))? { match read()? { diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 004a96c..22b7dc2 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -78,7 +78,7 @@ fn running_executables(&self) -> Vec; // 供 skip_if_ - 匹配前大小写要归一化(`Xmind` vs `xmind`); - `KNOWN_SUFFIXES` 带点而文件名切分后不带点,两侧必须用同一种归一化形式比较(`has_known_suffix`)。另外 `.pdf/.png/.mp3` 这类文档后缀绝不能出现在「按名称匹配」的后缀表里,否则 `Xmind-notes.pdf` 会被当成残留删掉。 -`console` 不在 `Platform` trait 里,但它回答的是同一类问题——「这台机器上的现实是什么」:控制台自称的窗口尺寸、它背后那块屏幕缓冲区的尺寸、它最大允许多大的窗口,以及一个「按 Unicode 只有 1 列宽」的字符在这里到底占几格。legacy conhost 在这两件事上都会给出错答案:进备用屏换掉的只是「正在显示的那块缓冲区」,进程的 stdout 句柄仍指着没人看的那一块,于是窗口比真正存在的格子更宽,写出一行的格子就落到下一行开头;cp936 码页又把 `─│·…↑↓✓` 这批 East Asian Ambiguous 字符收两格,而 ratatui 按一格排版。两者最后都表现为同一种花屏——屏上同时留着好几帧。所以 TUI 每一拍重新量一次尺寸(缓冲区被滚走、窗口被人拖大都算变化,只有真的变了才擦屏重画),并在量到「两格」时把整屏退成 ASCII 边框;`SQUID_SYMBOL_CELLS` 供人强制指定,`SQUID_CONSOLE_TRACE` 把控制台自己的几个数字写进文件留证。 +`console` 不在 `Platform` trait 里,但它回答的是同一类问题——「这台机器上的现实是什么」:控制台自称的窗口尺寸、它背后那块屏幕缓冲区的尺寸、它最大允许多大的窗口,以及一个「按 Unicode 只有 1 列宽」的字符在这里到底占几格。legacy conhost 在这两件事上都会给出错答案:进备用屏换掉的只是「正在显示的那块缓冲区」,进程的 stdout 句柄仍指着没人看的那一块,于是窗口比真正存在的格子更宽,写出一行的格子就落到下一行开头;cp936 码页又把 `─│·…↑↓✓` 这批 East Asian Ambiguous 字符收两格,而 ratatui 按一格排版。两者最后都表现为同一种花屏——屏上同时留着好几帧。所以 TUI 每一拍重新量一次尺寸(缓冲区被滚走、窗口被人拖大都算变化,只有真的变了才擦屏重画)。字形的价格归 `currency`:`Exchange` 按码位存一张兑换表,只在控制台确实多收钱时建,`afford` 在单格终端上原样返回。价是谁问的要分开说——`console::prices` 逐字符把答案量回来给界面,`squid_tui::glyphs` 因此只剩 ratatui 那一半:`witnesses` 从界面源码和 widget 里收集本界面会画的所有歧义字符,`Carry` 走一遍成品帧把付不起的字符换成 ASCII。界面有两条测试钉住「画的字符」与「问过的字符」是同一份:`every_glyph_this_interface_draws_has_a_price` 和 `the_probe_asks_the_price_of_everything_that_ends_up_on_the_screen`。`SQUID_SYMBOL_CELLS` 供人强制指定,`SQUID_CONSOLE_TRACE` 把控制台自己的几个数字写进文件留证。 ### squid-rules