The command line pays for its chrome at the same counter

Three rounds were spent on a TUI that drew several frames over each other on
a cp936 console, and the fix worked: the interface asks the console what it
charges, per character, and draws ASCII where the console charges more than
the layout paid. Meanwhile `squid status`, printed in the same window on the
same machine, still produced a Storage table whose rows were each a screen
and a half long. Nothing in `main.rs` had ever asked what a `█` costs. It
repeats that character twenty-eight times for a gauge and lets the console
do the arithmetic, and the console's arithmetic is different.

`priced` is where a line stops being text and starts being cells, and `row!`
is the one door the body of every report prints through: the eleven places
that draw this program's chrome — the status key/value rows, the volume
gauges, the process table, the tree, the history rows, the whitelist
bullets, the rule headings and their `●`, the doctor's table — all of them
now go through it. It is a macro rather than a helper so the format
arguments stay where they were written, and one door rather than twelve
`println!`s of which eleven remember the console, because the twelfth is the
bug this whole thing is about.

Two refusals are the interesting part.

Nobody is stopped from seeing what a report actually says. Point the output
at a file or a pipe and the text comes back exactly as it was, because a
file is not a console: whatever glass reads the archive tomorrow may well
afford the `█`, and an archive of `#` is a worse record for the sake of a
screen that was never looking. The gate is the same tty question the live
progress line already asked — may this line overwrite a line — so
`live_stream_is_tty` is now `human_stream_is_tty`, since the two questions
have the same answer and deserve one function that says what it is asked.
And `--json` prints data, never through this: rewriting a person's report to
flatter their terminal is a different bug with the same fingerprint.

The price is not measured, even though measuring is what the interface does,
for the reason in `console::prices_unasked`: measurement spends characters,
and a command line is a guest on the screen it is printed to, sitting in a
pipeline or in front of a shell waiting for its next prompt. So it takes the
pessimistic answer the code page implies, which costs it a plainer gauge on
a console whose code page overcharges characters its font could have
carried. `█` becomes `#` there. A table that fits is worth more than a
prettier one that does not.

`no_line_of_chrome_escapes_the_counter` reads the file, with strings,
character literals and comments blanked, and demands that every `print!`,
`println!` and `eprintln!` either go through `priced` or print JSON or print
nothing. The scan exists because this mistake cannot be seen from the
machine it was made on: `println!(" {}", plan)` standing among eleven `row!`
calls is correct on every terminal that charges one cell for everything,
including the one it was typed on, and arrives folded over in front of
somebody else. It reads character literals as literals only when they close
again promptly, because `'static` is not the start of a character literal
and blanking from a lifetime to the next quote hides half a file from an
audit whose entire job is to look at all of it.

On the box, same pseudo-console, same 100x30 window, three reports per
capture and every one of them complete to `MARK_QUIT 0`. On cp936 — the code
page the user's own window is on — the decoded stream contains no `█`, no
`░`, no `─`, no `·`, no `…`, no arrow: the gauge reads
`[#######################.....]` and the headings are underlined with `-`.
On 65001 the same report keeps 104 `█`, 120 `░`, 236 `─`, 32 `·` and both
arrows. Same bytes of intent, two currencies, and the receipt is now in
both.

`win-tui-capture.sh` takes `TUI_ARGS=` so this evidence is repeatable rather
than hand-built: the default still captures the interface and judges it
frame by frame, and `TUI_ARGS="status"` captures a report, where the judge
is simply how many `█` survived.

The architecture document tells the story as one paragraph now, because it
is one story: `console::prices` measures and hands the answers to the
interface, `console::prices_unasked` guesses from the code page and hands
them to the command line, and each side has a test that keeps the characters
it draws and the characters it priced the same list.

178 tests here, two of them this commit's, clean under clippy for the host
and for `x86_64-pc-windows-msvc`, `cargo doc -D warnings` quiet over the
platform and the command line.
main
mula.liu 2026-10-16 10:32:05 +08:00
parent cc678dee21
commit bf04f2c105
4 changed files with 334 additions and 30 deletions

View File

@ -16,11 +16,12 @@ use squid_core::{
use squid_engine::analyze;
use squid_engine::delete::{self, DeleteJob};
use squid_engine::{clean, purge, uninstall, Engine};
use squid_platform::currency::Exchange;
use squid_platform::TrashTarget;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
// ------------------------------------------------------------------------ CLI
@ -196,12 +197,68 @@ static QUIET: AtomicBool = AtomicBool::new(false);
/// stderr so `squid clean --json | jq` never sees a progress message.
static DIAG_STDERR: AtomicBool = AtomicBool::new(false);
/// What to print when this console cannot afford the characters a report is
/// drawn out of.
///
/// The interface walks a finished frame; a command line has no frame, so its
/// frame is one line, and this is where a line stops being text and starts
/// being cells. It is the same exchange the interface spends, reached from the
/// other side — a gauge here repeats `█` twenty-eight times, and on the console
/// that turns the interface into a pile of half-frames it prints a Storage
/// table whose rows are each a screen and a half long.
///
/// The price is not measured here, even though measuring is what the interface
/// does. Measuring spends characters on whatever the console is showing at the
/// time, and a command line is a guest on that screen: it is in a pipeline, or
/// somebody's shell is still sitting there waiting for its next prompt, and a
/// row of sixty test characters written and erased in front of them is somebody
/// else's work interrupted. So the command line takes the pessimistic price the
/// code page implies and buys nothing, which costs it a plainer gauge on a
/// console that a measurement might have cleared. A table that fits is worth
/// more than a prettier one that does not.
///
/// See [`squid_platform::console::prices_unasked`] for that reasoning at the
/// counter, and `squid_tui::glyphs` for the half that walks a frame.
fn change() -> &'static Exchange {
static CHANGE: OnceLock<Exchange> = OnceLock::new();
CHANGE.get_or_init(|| Exchange::new(squid_platform::console::prices_unasked()))
}
/// One line a person is shown, in the characters their console can pay for.
///
/// Nobody is stopped from seeing what a report actually says. Point the output
/// at a file or a pipe and the text comes back as it was, because a file is not
/// a console: whatever glass reads it tomorrow may well be able to afford the
/// `█`, and an archive of `#` is a worse record for the sake of a screen that
/// was never looking. Only a screen is offered the exchange.
fn priced(text: &str) -> String {
if !human_stream_is_tty() {
return text.to_string();
}
change().afford(text)
}
/// Print one row of a report.
///
/// [`diag`] and [`say`] own the lines that carry a colour code, obey `--quiet`
/// or dodge `--json`; what is left is the body of the tables, which is printed
/// straight out because a report's rows belong to the report whoever asked for
/// it. That leftover is also where every gauge, bullet and rule in this
/// program's output is drawn, which is why there is one macro for it rather
/// than thirteen `println!`s of which twelve remember the console and one does
/// not. `no_line_of_chrome_escapes_the_counter` is what keeps it that way.
macro_rules! row {
($($arg:tt)*) => {
println!("{}", $crate::priced(&format!($($arg)*)))
};
}
/// One human-readable diagnostic line.
fn diag(code: &str, text: &str) {
if DIAG_STDERR.load(Ordering::Relaxed) {
eprintln!("{}", paint(code, text));
eprintln!("{}", priced(&paint(code, text)));
} else {
println!("{}", paint(code, text));
println!("{}", priced(&paint(code, text)));
}
}
@ -216,16 +273,22 @@ fn say(text: &str) {
}
if DIAG_STDERR.load(Ordering::Relaxed) {
if !text.is_empty() {
eprintln!("{text}");
eprintln!("{}", priced(text));
}
} else {
println!("{text}");
println!("{}", priced(text));
}
}
/// The stream the live progress line may overwrite: stdout while it is still
/// free, stderr once `--json` has claimed it for JSON alone.
fn live_stream_is_tty() -> bool {
/// The stream a human line lands on: stdout while it is still free, stderr
/// once `--json` has claimed it for JSON alone.
///
/// Two questions get asked of it, and they have the same answer. A progress
/// line may only overwrite a line when something can watch it being
/// overwritten. Chrome may only be exchanged for ASCII when somebody is looking
/// at the console that cannot afford it — because that is the only place the
/// exchange is an improvement rather than a loss.
fn human_stream_is_tty() -> bool {
if DIAG_STDERR.load(Ordering::Relaxed) {
std::io::stderr().is_tty()
} else {
@ -236,7 +299,7 @@ fn live_stream_is_tty() -> bool {
/// Rewrite the live progress line, or clear it when `text` is `None`.
fn live(text: Option<&str>) {
let line = match text {
Some(text) => format!("\r\x1b[K{text}"),
Some(text) => format!("\r\x1b[K{}", priced(text)),
None => "\r\x1b[K".to_string(),
};
if DIAG_STDERR.load(Ordering::Relaxed) {
@ -257,14 +320,20 @@ fn main() {
Err(error) => {
if let Some(inner) = error.downcast_ref::<squid_core::SquidError>() {
if matches!(inner, squid_core::SquidError::Cancelled) {
eprintln!("{}", paint("90", "cancelled — nothing was changed"));
eprintln!(
"{}",
priced(&paint("90", "cancelled — nothing was changed"))
);
std::process::exit(130);
}
}
eprintln!("{} {}", paint("31", "squid:"), error);
eprintln!(
"{}",
priced(&format!("{} {}", paint("31", "squid:"), error))
);
let mut source = error.source();
while let Some(cause) = source.take() {
eprintln!("{}", paint("90", &format!(" caused by: {cause}")));
eprintln!("{}", priced(&paint("90", &format!(" caused by: {cause}"))));
source = cause.source();
}
std::process::exit(1);
@ -451,7 +520,7 @@ fn ask(question: &str) -> bool {
);
return false;
}
print!("{} ", paint("1;33", &format!("{question} [y/N]")));
print!("{} ", priced(&paint("1;33", &format!("{question} [y/N]"))));
let _ = std::io::stdout().flush();
let mut answer = String::new();
if std::io::stdin().read_line(&mut answer).is_err() {
@ -488,7 +557,7 @@ fn with_progress<T>(
total,
subject,
} => {
if live_stream_is_tty() {
if human_stream_is_tty() {
let glyph = frames
.next()
.unwrap_or_else(|| label.chars().next().unwrap_or('#'));
@ -529,7 +598,7 @@ fn with_progress<T>(
}
}
if stop_now {
if live_stream_is_tty() {
if human_stream_is_tty() {
live(None);
}
break;
@ -647,7 +716,10 @@ fn delete_items(
with_progress("delete", move |engine, progress, cancel| {
if !COLOR.load(Ordering::Relaxed) {
// keep the count alive for the summary line
eprintln!("{}", paint("90", &format!(" removing {count} items")));
eprintln!(
"{}",
priced(&paint("90", &format!(" removing {count} items")))
);
}
delete::execute(engine, &job, progress, cancel)
})
@ -1084,7 +1156,7 @@ fn cmd_status(args: StatusArgs, json: bool) -> Result<i32> {
snapshot.host.hostname, snapshot.host.hardware
));
let kv = |label: &str, value: String| {
println!(" {:<10} {}", paint("90", label), value);
row!(" {:<10} {}", paint("90", label), value);
};
kv(
"system",
@ -1166,7 +1238,7 @@ fn cmd_status(args: StatusArgs, json: bool) -> Result<i32> {
paint("36", &"█".repeat(filled)),
paint("90", &"░".repeat(width - filled))
);
println!(
row!(
" {} [{}] {} / {} {}",
paint("1", &fit(&volume.name, 14)),
bar,
@ -1177,7 +1249,7 @@ fn cmd_status(args: StatusArgs, json: bool) -> Result<i32> {
}
heading(&format!("Top processes · {}", args.processes));
for process in snapshot.top_processes.iter().take(args.processes) {
println!(
row!(
" {:>6} {} {:>9} {}",
paint("36", &format!("{:.1}%", process.cpu)),
paint("1", &fit(&process.name, 30)),
@ -1261,7 +1333,7 @@ fn print_tree(node: &analyze::Node, depth: usize, total: &Bytes) {
paint("35", &"█".repeat(filled)),
paint("90", &"░".repeat(bar_w.saturating_sub(filled)))
);
println!(
row!(
" {}{} [{}] {} {:>4.1}%",
" ".repeat(depth),
paint("1", &fit(&child.name(), width)),
@ -1336,7 +1408,7 @@ fn cmd_history(args: HistoryArgs, json: bool) -> Result<i32> {
} else {
String::new()
};
println!(
row!(
" {} {} {} {} {} {}",
paint(
"90",
@ -1504,7 +1576,7 @@ fn cmd_whitelist(args: WhitelistArgs) -> Result<i32> {
shout("90", " empty — every matching path is offered for review");
}
for pattern in &settings.whitelist {
println!(" {} {}", paint("32", "●"), pattern);
row!(" {} {}", paint("32", "●"), pattern);
}
println!();
shout("90", &format!(" {}", paths::pretty(&Settings::path())));
@ -1545,7 +1617,7 @@ fn cmd_rules(json: bool) -> Result<i32> {
for category in rules.categories() {
let list = rules.by_category(category);
println!();
println!(
row!(
"{}",
paint(
"1;36",
@ -1570,7 +1642,7 @@ fn cmd_rules(json: bool) -> Result<i32> {
if !rule.select_by_default {
flags.push(paint("90", "opt-in"));
}
println!(
row!(
" {} {:<28} {}",
if enabled {
paint("32", "●")
@ -1581,7 +1653,7 @@ fn cmd_rules(json: bool) -> Result<i32> {
paint("90", rule.display_title())
);
if !flags.is_empty() {
println!(" {}", flags.join(" "));
row!(" {}", flags.join(" "));
}
}
}
@ -1603,7 +1675,7 @@ fn cmd_doctor() -> Result<i32> {
let engine = Engine::new();
let platform = engine.platform();
heading("squid doctor");
let kv = |label: &str, value: String| println!(" {:<12} {}", paint("90", label), value);
let kv = |label: &str, value: String| row!(" {:<12} {}", paint("90", label), value);
kv("version", squid_core::VERSION.to_string());
kv("platform", platform.display_name());
kv("os", platform.os_version());
@ -1700,7 +1772,7 @@ fn cmd_doctor() -> Result<i32> {
let volumes = platform.volumes().unwrap_or_default();
kv("volumes", format!("{}", volumes.len()));
for volume in &volumes {
println!(
row!(
" {} {}",
paint("1", &fit(&volume.name, 16)),
paint(
@ -1744,3 +1816,180 @@ fn cmd_doctor() -> Result<i32> {
);
Ok(0)
}
#[cfg(test)]
mod chrome {
use squid_platform::console::Prices;
use squid_platform::currency::{self, Exchange};
use unicode_width::UnicodeWidthStr;
/// The source with its strings, character literals and comments blanked, so
/// that a scan of the program is not a scan of its prose — which matters
/// more here than in most programs, because half of this file is sentences
/// about what it prints, and they quote the characters they describe.
fn only_code(source: &str) -> String {
let chars: Vec<char> = source.chars().collect();
let mut code = String::with_capacity(source.len());
let mut index = 0;
while index < chars.len() {
match chars[index] {
'/' if chars.get(index + 1) == Some(&'/') => {
while index < chars.len() && chars[index] != '\n' {
code.push(' ');
index += 1;
}
}
// A double quote always opens a string. A single quote only
// opens a character literal, and closes again almost immediately
// when it does; otherwise it is a lifetime, and blanking from a
// lifetime to the next quote is how a print site vanishes from
// an audit whose entire job is to find print sites.
quote @ ('"' | '\'') if quote == '"' || closes_char_literal(&chars, index) => {
code.push(' ');
index += 1;
while index < chars.len() {
if chars[index] == '\\' {
code.push(' ');
index += 2;
continue;
}
code.push(' ');
index += 1;
if chars[index - 1] == quote {
break;
}
}
}
ch => {
code.push(ch);
index += 1;
}
}
}
code
}
/// Whether the single quote at `open` opens a character literal.
///
/// `'q'`, `'\n'` and `'\u{1F600}'` all close inside a few characters, which
/// is what this asks; `'static`, `'a mut` and the apostrophe of a prose word
/// that escaped the comment blanker do not, so they stay where they are.
fn closes_char_literal(chars: &[char], open: usize) -> bool {
let mut index = open + 1;
while index < chars.len() && index - open <= 12 {
if chars[index] == '\\' {
index += 2;
continue;
}
if chars[index] == '\'' {
return true;
}
index += 1;
}
false
}
/// The index just past the parenthesis that closes the one at `open`.
fn closed(code: &str, open: usize) -> Option<usize> {
let mut depth = 0;
for (offset, ch) in code[open..].char_indices() {
match ch {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
return Some(open + offset);
}
}
_ => {}
}
}
None
}
/// Every line a person is shown pays for its chrome, and the only lines that
/// do not are JSON and blank ones.
///
/// The rule is about the printing rather than the characters: a `█` is
/// nothing to be ashamed of, and this program is full of them. It is
/// `println!` that owes the console an answer, because that is the moment a
/// measured row becomes a row of cells. So every print of this file either
/// goes through [`priced`] — directly, or as a [`row!`], which is the same
/// thing with the format arguments left where they were written — or prints
/// JSON, which is data: rewriting a person's report to flatter their
/// terminal is a different bug with the same fingerprint.
///
/// The scan reads the source because the mistake it looks for cannot be seen
/// from the machine it was made on. `println!(" {}", plan)` standing among
/// twelve `row!` calls is invisible on every terminal that charges one cell
/// for everything, including the one it was typed on, and arrives as a
/// report folded over on itself in front of somebody else.
#[test]
fn no_line_of_chrome_escapes_the_counter() {
let code = only_code(include_str!("main.rs"));
let mut offenders = Vec::new();
for call in ["println!(", "eprintln!(", "print!("] {
let mut from = 0;
while let Some(found) = code[from..].find(call) {
let at = from + found;
from = at + call.len();
let Some(end) = closed(&code, at + call.len() - 1) else {
continue;
};
let group = code[at + call.len()..end].trim();
if group.is_empty() || group.contains("serde_json") || group.contains("priced") {
continue;
}
offenders.push(group.to_string());
}
}
assert!(
offenders.is_empty(),
"{} print site(s) print a line nobody priced: {offenders:?}",
offenders.len()
);
}
/// What a console that reprices things charges for a line, which is not what
/// `format!` billed for it: the layout counts a `█` as the one column it
/// measured, and the glass charges two.
fn charged(text: &str) -> usize {
text.chars()
.map(|ch| 1 + currency::disputed(ch) as usize)
.sum()
}
#[test]
fn a_report_row_is_as_long_as_the_row_was_billed_for() {
// The disk row from `squid status`, built the way the command builds it.
// The row is the whole complaint: nobody called the gauge too ugly, they
// called the table unreadable, and the table is unreadable because this
// row is a screen and a half long on the glass it is printed on.
let row = format!(
" {:<14} [{}{}] 212.4 GB / 460 GB 247.6 GB free",
"Macintosh HD",
"█".repeat(20),
"░".repeat(8)
);
// Every character is one column to the layout, so the row is as many
// columns as it is characters — and twenty-eight of those characters are
// the gauge, which is what the console doubles.
assert_eq!(row.width(), row.chars().count());
assert_eq!(
charged(&row),
row.width() + 28,
"the row has to be overcharged before the exchange is worth testing"
);
let paid = Exchange::new(Prices::implied(936)).afford(&row);
assert_eq!(
charged(&paid),
paid.width(),
"a console may not charge for a cell the row did not pay for"
);
assert!(
paid.contains("Macintosh HD") && paid.contains("212.4 GB"),
"the row still says what it said: {paid}"
);
}
}

View File

@ -417,6 +417,44 @@ pub fn prices(witnesses: &[char]) -> Prices {
}
}
/// What a screen costs that this program does not own.
///
/// [`prices`] buys its answers by spending characters: it writes one into a
/// corner of the buffer, reads how far the cursor took itself, and paints the
/// cell back out again. On a screen the interface has taken over, that is
/// invisible. On a screen still showing a shell it is somebody else's row for
/// the length of a measurement — sixty characters, written and erased, in the
/// one place a person is looking.
///
/// A command-line program is a guest on that screen, often a pipe nobody is
/// watching at all, so it does not buy the answer. It takes the one the code
/// page hands over for free, which is the pessimistic one: a Far-Eastern code
/// page charges two cells for every rule, gauge and arrow, and a command line
/// that believes it prints `#` where a measured console would have printed
/// `█`. Being wrong that way costs a plainer table. Being wrong the other way
/// costs a table whose rows are each a screen and a half long, which is the
/// complaint this whole exchange exists to answer.
///
/// A person who can see the screen this program cannot — over ssh, in a
/// terminal that reprices things behind its back — still has the last word
/// through `SQUID_SYMBOL_CELLS`, obeyed here exactly as it is by [`prices`].
pub fn prices_unasked() -> Prices {
if let Some(asked) = asked_for() {
note(&format!("symbols={} asked", word(asked)));
return Prices::flat(asked);
}
#[cfg(windows)]
{
let code_page = windows::output_code_page();
note(&format!("symbols implied by cp={code_page}"));
Prices::implied(code_page)
}
#[cfg(not(windows))]
{
Prices::flat(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
@ -683,6 +721,14 @@ mod windows {
}
}
/// The code page the console writes in, without touching the screen.
///
/// See [`super::prices_unasked`] for why a program that only prints is
/// content with this one number instead of measuring.
pub(super) fn output_code_page() -> u32 {
unsafe { GetConsoleOutputCP() }
}
pub fn report() -> String {
let code_page = unsafe { GetConsoleOutputCP() };
let mut mode = 0u32;

View File

@ -78,7 +78,7 @@ fn running_executables(&self) -> Vec<String>; // 供 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 每一拍重新量一次尺寸(缓冲区被滚走、窗口被人拖大都算变化,只有真的变了才擦屏重画)。字形的价格归 `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` 把控制台自己的几个数字写进文件留证。
`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;`console::prices_unasked` 只取码页隐含的悲观答案给命令行,因为测量要往控制台上正显示的东西写一个字符再擦掉,而命令行是那台屏幕上的客人,它不该买这个答案,代价是在单格终端被码页误伤的机器上少一个 `█`、多一个 `#`。两边各有一条测试钉住「画的字符」与「问过的字符」是同一份:界面是 `every_glyph_this_interface_draws_has_a_price` 和 `the_probe_asks_the_price_of_everything_that_ends_up_on_the_screen`,命令行是 `no_line_of_chrome_escapes_the_counter`,它扫描 `main.rs`,要求除 JSON 和空行之外每个 print 都过 `priced`。`SQUID_SYMBOL_CELLS` 供人强制指定,`SQUID_CONSOLE_TRACE` 把控制台自己的几个数字写进文件留证。
### squid-rules

View File

@ -8,6 +8,7 @@
# TUI_CELLS=2 ./scripts/win-tui-capture.sh # 强制按"一列字符收两格"画(ASCII 边框)
# TUI_CP=936 ./scripts/win-tui-capture.sh # 用用户窗口的代码页跑(复现方块双格)
# TUI_REUSE=1 TUI_OUT=/tmp/x.bin ./scripts/win-tui-capture.sh # 只重算旧帧,不连真机
# TUI_ARGS="status" ./scripts/win-tui-capture.sh # 抓命令行的输出而不是界面(判据见下)
#
# 为什么不能用 scripts/tui_smoke.py:那个脚本自己 forkpty(),是 POSIX 专属。
# 真机上没有 pty 可以 fork,只能反过来:让 sshd 用 CreatePseudoConsole 分配一个
@ -36,6 +37,10 @@ DELAY="${TUI_DELAY:-8}"
# 那一版只能靠 SQUID_SYMBOL_CELLS 强制 —— 伪控制台量不到两格,不等于用户那个带
# 中文字体的窗口也量不到,这条路径正是为后者准备的。
CELLS="${TUI_CELLS:-}"
# 默认抓 state 界面。TUI_ARGS 换成命令行子命令就能抓 `squid status` 这类纯文本:
# 那种输出没有帧可判(帧判据会说"屏上没画框"),它的判据是剥掉 ANSI 之后还剩几
# 个 █ —— cp936 下应当一个不剩(换成 # 和 .),65001 下一个不少(控制台付得起)。
TUI_ARGS="${TUI_ARGS:-state}"
# TUI_CP=936 让远端控制台待在用户真正使用的那个代码页上。
# 为什么要这个:代码页决定"没被问到"的字符按几格算(936 按两格),而用户自己的
# 窗口就跑在 936 上;要让他那台机器上的问价过程在这里重现一遍,就得让控制台真的
@ -61,10 +66,14 @@ TUI_HOLD="${TUI_HOLD:-6}"
{ sleep "$DELAY"; for key in $TUI_KEYS; do printf '%s' "$key"; sleep "$TUI_HOLD"; done; sleep 2; } |
ssh -tt -i "$WIN_KEY" -o BatchMode=yes "$WIN_HOST" \
"${SETUP}powershell" -NoProfile -ExecutionPolicy Bypass -File "$RUNNER" \
"$COLS" "$ROWS" "$BIN" state "$@" \
"$COLS" "$ROWS" "$BIN" $TUI_ARGS "$@" \
> "$OUT" 2>&1
rc=$?
printf '\033[1;36m==>\033[0m 原始 ANSI 已存 %s (%s 字节, ssh rc=%s)\n' "$OUT" "$(wc -c < "$OUT" | tr -d ' ')" "$rc"
fi
python3 scripts/tui-frame-check.py "$OUT"
if [ "$TUI_ARGS" = state ]; then
python3 scripts/tui-frame-check.py "$OUT"
else
printf '\033[1;36m==>\033[0m 命令行输出按字符判,不按帧判(TUI_ARGS=%s)\n' "$TUI_ARGS"
fi