Record what the Windows box proved, and keep the proof repeatable

`win-tui-capture.sh` drives the real binary over `ssh -tt`, which is the only
way to render the TUI the way a Windows console does: sshd allocates a
pseudoconsole, crossterm takes its Windows backend, and the bytes it emits are
decoded back into a frame locally. The existing smoke script cannot do this
because it forks its own pty, which is POSIX-only.

It now takes a key sequence, so the interesting case — a populated list, not an
empty panel — is the one that gets checked, and it keeps the fullest frame
rather than the last one, because quitting wipes the screen. It reports where a
replacement character appeared, since mid-stream means the console could not
draw the glyph and at the tail only means ssh truncated a frame on disconnect.

`win-hwcheck.ps1` measures the volume before and after a real deletion, counts
entries in the shell's Recycle Bin, and asserts the two agree; that is what
caught the missing undo flag. Its fixtures clean themselves up.

Windows moves from "cross-compile only" to verified on real hardware in the
roadmap. UAC elevation, the long-path manifest, and publishing stay pending.
main
mula.liu 2026-10-15 18:55:01 +08:00
parent 9f1cf348a4
commit 937d955937
5 changed files with 228 additions and 33 deletions

View File

@ -13,12 +13,13 @@ macOS 磁盘清理与系统监控工具:清理缓存与系统垃圾、卸载 A
| 深度清理 | `node_modules` 等项目构建产物、磁盘镜像、陈旧安装包与下载 | `squid purge` | | 深度清理 | `node_modules` 等项目构建产物、磁盘镜像、陈旧安装包与下载 | `squid purge` |
| 存储分析 | 体积树与最大文件,可逐层下钻 | `squid analyze`、`state` 存储面板 | | 存储分析 | 体积树与最大文件,可逐层下钻 | `squid analyze`、`state` 存储面板 |
| 系统监控 | CPU / 内存 / 网络 / 磁盘 / 电池 / 温度 / 进程 | `squid status`、`state` 系统面板 | | 系统监控 | CPU / 内存 / 网络 / 磁盘 / 电池 / 温度 / 进程 | `squid status`、`state` 系统面板 |
| 历史与撤销 | 每次真实删除写一条 JSON 账本,可将仍在废纸篓里的文件原样放回 | `squid history`、`squid undo` | | 历史与撤销 | 每次真实删除写一条 JSON 账本,可将仍在废纸篓 / 回收站里的文件原样放回 | `squid history`、`squid undo` |
- 语言:Rust 1.80+,workspace 由 7 个 crate 组成 - 语言:Rust 1.80+,workspace 由 7 个 crate 组成
- 界面:中英双语文案,跟随系统语言;真彩色 / 256 色 / 无色三档自动适配 - 界面:中英双语文案,跟随系统语言;真彩色 / 256 色 / 无色三档自动适配
- 结构:命令行与 TUI 共用同一套扫描与删除通道,行为、确认、账本完全一致 - 结构:命令行与 TUI 共用同一套扫描与删除通道,行为、确认、账本完全一致
- 平台:macOS 完整支持,Linux / Windows 见[路线图](#路线图) - 平台:macOS 完整支持;Windows 10 / 11 用同一个构建,已在 Windows 10 真机验证
(回收站删除与还原、中英文 TUI 在真实控制台下的渲染);UAC 提权与 Linux 见[路线图](#路线图)
--- ---
@ -301,7 +302,7 @@ Homebrew formula 的校验和。
| --- | --- | --- | | --- | --- | --- |
| macOS | 完整实现(规则、App 残留、卷、卸载钩子)| Developer ID 签名与公证流水线 | | macOS | 完整实现(规则、App 残留、卷、卸载钩子)| Developer ID 签名与公证流水线 |
| Linux | `squid-platform/src/linux.rs` 已实现 `.desktop` / Flatpak / Snap 应用清单与 XDG 残留目录 | `rules/linux.toml`、真机验证 | | Linux | `squid-platform/src/linux.rs` 已实现 `.desktop` / Flatpak / Snap 应用清单与 XDG 残留目录 | `rules/linux.toml`、真机验证 |
| Windows | 平台层已实现:注册表卸载表(HKLM 64/32 位 + HKCU)、AppData 残留目录、卷枚举、回收站(`IFileOperation`);安全层按 Windows 语义比较路径(大小写不敏感、盘符根/`$Recycle.Bin` 等硬封禁);内置 30 条清理规则(临时文件、WER 崩溃报告、浏览器/Shell/开发缓存、Windows.old 等);CI 每次提交做 MSVC 目标交叉编译检查 | 真机验证、UAC 提权、长路径 manifest、winget 发布 | | Windows | 平台层已实现:注册表卸载表(HKLM 64/32 位 + HKCU)、AppData 残留目录、卷枚举、回收站(`IFileOperation`);安全层按 Windows 语义比较路径(大小写不敏感、盘符根/`$Recycle.Bin` 等硬封禁);内置 30 条清理规则(临时文件、WER 崩溃报告、浏览器/Shell/开发缓存、Windows.old 等);CI 每次提交做 MSVC 目标交叉编译检查;已在局域网内的真机验证通过:回收站真实删除(按卷核算字节数、可在资源管理器里还原)、`undo` 的措辞与行为、`--json` 输出只含一份 JSON、TUI 在 OpenSSH 分配的 ConPTY 下中英文都排版正确 | UAC 提权、长路径 manifest、winget 发布 |
其他:规则贡献流程与规则覆盖度基准、TUI 主题自定义、Linux/Windows 冒烟测试。 其他:规则贡献流程与规则覆盖度基准、TUI 主题自定义、Linux/Windows 冒烟测试。

View File

@ -1,4 +1,4 @@
# Build and test squid on a real Windows machine (runner or dev box). # Build and test squid on a real Windows machine (runner or dev box).
# Usage: pwsh -File scripts/ci-windows.ps1 [-Static] # Usage: pwsh -File scripts/ci-windows.ps1 [-Static]
param( param(
# Statically link the CRT so the exe needs no VC++ redistributable. # Statically link the CRT so the exe needs no VC++ redistributable.

View File

@ -1,4 +1,4 @@
# 在 Windows 真机上跑一整套校验:fmt 之外的 test / clippy / release build。 # 在 Windows 真机上跑一整套校验:fmt 之外的 test / clippy / release build。
# 由 scripts/win-sync.sh 上传并调用;也可以单独在 PowerShell 里直接跑。 # 由 scripts/win-sync.sh 上传并调用;也可以单独在 PowerShell 里直接跑。
$ErrorActionPreference = 'Continue' $ErrorActionPreference = 'Continue'
# 中文输出必须 UTF-8,否则 SSH 那头看到的全是乱码。 # 中文输出必须 UTF-8,否则 SSH 那头看到的全是乱码。

View File

@ -1,13 +1,18 @@
# 真机验收脚本:只读检查 + 一个自建的回收站往返实验,不碰用户真实数据。 # 真机验收脚本:只读检查 + 一个自建的回收站往返实验,不碰用户真实数据。
# 注意:含中文的 .ps1 必须带 UTF-8 BOM,否则 Windows PowerShell 5.1 会按系统
# ANSI 代码页(中文机器上是 GBK)解码,注释里的字节会吞掉相邻的引号,整份脚本
# 报"字符串缺少终止符"。chcp 65001 只影响控制台,不影响脚本文件的解码。
# 由 scripts/win-sync.sh 同步后单独执行: # 由 scripts/win-sync.sh 同步后单独执行:
# ssh KANGWJ@host powershell -NoProfile -ExecutionPolicy Bypass -File C:\Users\kangwj\win-hwcheck.ps1 # ssh KANGWJ@host cmd /c "chcp 65001 >nul & powershell -NoProfile -ExecutionPolicy Bypass -File C:\Users\kangwj\win-hwcheck.ps1"
$ErrorActionPreference = 'Continue' $ErrorActionPreference = 'Continue'
$null = & cmd /c 'chcp 65001 >nul' $null = & cmd /c 'chcp 65001 >nul'
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$env:Path = "$env:USERPROFILE\.cargo\bin;$env:Path" $env:Path = "$env:USERPROFILE\.cargo\bin;$env:Path"
$env:CARGO_TARGET_DIR = 'C:\dev\target' $env:CARGO_TARGET_DIR = 'C:\dev\target'
$squid = 'C:\dev\target\release\squid.exe' $squid = 'C:\dev\target\release\squid.exe'
$scratch = Join-Path $env:USERPROFILE 'squid-rb-test' # 每轮换一个名字:回收站里可能有上一轮的同名条目,用名字判断"这一轮真的进去了"才成立。
$run = 'squid-rb-{0}' -f (Get-Date -Format 'HHmmss')
$scratch = Join-Path $env:USERPROFILE $run
$fails = @() $fails = @()
function Step($name) { Write-Output "`n=== $name ===" } function Step($name) { Write-Output "`n=== $name ===" }
function Fail($m) { $script:fails += $m; Write-Output "!!! FAIL: $m" } function Fail($m) { $script:fails += $m; Write-Output "!!! FAIL: $m" }
@ -16,13 +21,28 @@ function Ok($m) { Write-Output "ok : $m" }
if (-not (Test-Path $squid)) { Write-Output "missing $squid"; exit 1 } if (-not (Test-Path $squid)) { Write-Output "missing $squid"; exit 1 }
Step 'doctor' Step 'doctor'
& $squid doctor --lang en $doctor = & $squid doctor --lang en 2>&1 | Out-String
Write-Output $doctor
# doctor 不能谎报回收站:Windows 上没有 ~/.Trash,但回收站是可用的。
if ($doctor -match 'fall back to permanent') {
Fail 'doctor 说没有回收站(Windows 上应该是 Recycle Bin)'
} elseif ($doctor -match 'Recycle Bin') {
Ok 'doctor 认出了 Recycle Bin'
} else {
Write-Output 'note: doctor 的 trash 行既不是 Recycle Bin 也不是 fallback,人工确认'
}
Step 'status (json)' Step 'status (json)'
$status = & $squid status --json | ConvertFrom-Json $status = & $squid status --json | ConvertFrom-Json
Ok ("os={0} host={1} disks={2}" -f $status.os, $status.hostname, $status.disks.Count) Ok ("os={0} host={1} volumes={2} arch={3}" -f $status.host.os_version, $status.host.hostname,
@($status.volumes).Count, $status.host.arch)
if (-not $status.host.os_version) { Fail 'status --json 没有报告操作系统' }
if (@($status.volumes).Count -lt 1) { Fail 'status --json 没有报告任何卷' }
Step 'installed apps vs registry' Step 'installed apps vs registry'
$apps = & $squid uninstall --list --json | ConvertFrom-Json # 2>$null 不能省:进度走 stderr,PowerShell 会把它们变成 ErrorRecord 混进输出流,
# 下面的 Count 就数成了 1。
$apps = @(& $squid uninstall --list --json 2>$null | ConvertFrom-Json)
$reg = @() $reg = @()
foreach ($hive in 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', foreach ($hive in 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall', 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall',
@ -33,40 +53,125 @@ foreach ($hive in 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
} }
} }
$regNames = $reg | Sort-Object -Unique $regNames = $reg | Sort-Object -Unique
Ok ("squid={0} registry={1}" -f $apps.Count, $regNames.Count) Ok ("squid={0} registry={1}" -f $apps.Count, @($regNames).Count)
$missing = $regNames | Where-Object { $apps.name -notcontains $_ } $missing = @($regNames | Where-Object { $apps.name -notcontains $_ })
if ($missing) { Write-Output ("missing in squid: " + ($missing -join ' | ')) } if ($missing.Count) { Write-Output (" missing in squid: " + (($missing | Select-Object -First 12) -join ' | ')) }
Step 'clean --dry-run (safety invariant)' Step 'clean --dry-run (safety invariant)'
$report = & $squid clean --dry-run --json | ConvertFrom-Json $report = & $squid clean --dry-run --json | ConvertFrom-Json
Ok ("items={0} freed={1} unreadable={2}" -f $report.items.Count, $report.freed_on_disk.human, $report.unreadable) $items = @($report.items)
$report.items | Group-Object category | Sort-Object Count -Descending | ForEach-Object { # 汇总由条目累加:JSON 里没有现成的 freed 总计字段。
$freed = 0
if ($items.Count) { $freed = [double](($items | Measure-Object -Property allocated -Sum).Sum) }
Ok ("items={0} freed={1:N0} B unreadable={2}" -f $items.Count, $freed, $report.unreadable)
# 每条清理建议都必须落在锚点之内,且 allocated 不能是 0(否则 freed 数是假的)。
$noanchor = @($items | Where-Object { -not $_.anchors -or @($_.anchors).Count -eq 0 })
if ($noanchor.Count) { Fail ("{0} 个清理项没有 anchor" -f $noanchor.Count) } else { Ok '每个清理项都有 anchor' }
$zero = @($items | Where-Object { $_.size -gt 0 -and $_.allocated -eq 0 })
if ($zero.Count) { Fail ("{0} 个清理项 size>0 但 allocated=0" -f $zero.Count) } else { Ok 'size>0 的清理项都量到了 allocated' }
$items | Group-Object category | Sort-Object Count -Descending | ForEach-Object {
Write-Output (" {0,-14} {1}" -f $_.Name, $_.Count) Write-Output (" {0,-14} {1}" -f $_.Name, $_.Count)
} }
# 核心安全不变量:清理项绝不能落在系统目录里。 # 核心安全不变量:系统目录里的条目可以"被看见",但绝不能"被选中"。
$forbidden = @('C:\Windows', 'C:\Program Files', 'C:\Program Files (x86)', '$Recycle.Bin') # C:\Windows\SoftwareDistribution\Download 和 Prefetch 是正当的清理目标
$bad = $report.items | Where-Object { # (磁盘清理工具也清它们),所以禁止的不是路径本身,而是"未提权时被预选"。
$p = $_.path.ToLower() # 真机上这一条救回了误判:280 条 SoftwareDistribution 全部 selected=false
foreach ($f in $forbidden) { if ($p.StartsWith($f.ToLower())) { return $true } } # 且 lock=protected,note 里写明了要提权 —— 行为是对的。
$forbidden = @('c:\windows', 'c:\program files', 'c:\program files (x86)', '\$recycle.bin')
function In-SystemDir($path) {
$p = ("$path").ToLower()
foreach ($f in $forbidden) { if ($p.StartsWith($f)) { return $true } }
return $false return $false
} }
if ($bad) { Fail ("clean offered {0} system-dir item(s): " -f $bad.Count + (($bad | Select-Object -First 3).path -join ' | ')) } $armed = @($items | Where-Object { In-SystemDir $_.path })
else { Ok 'no clean item inside system directories' } $live = @($armed | Where-Object { $_.selected -or -not $_.lock })
Write-Output (" 系统目录条目: {0} 条,其中可选中的 {1} 条" -f $armed.Count, $live.Count)
if ($live.Count) {
Fail ("clean 把 {0} 个系统目录条目设成了可删: {1}" -f $live.Count, (($live | Select-Object -First 3).path -join ' | '))
} else { Ok '系统目录条目一律 protected + 未选中' }
Step 'recycle-bin round trip' Step 'recycle-bin round trip'
Remove-Item $scratch -Recurse -Force -ErrorAction SilentlyContinue # 观察回收站有两种办法,任一有效即可断定 IFileOperation 成功:
# 1) Shell.Application 枚举(在非交互 SSH 会话里能不能用,本身就是待验证项);
# 2) squid 自己的账本 —— 只有 IFileOperation 返回成功才会记下这次会话。
# 注意函数里绝不能 Write-Output 诊断文本:它会混进返回值,$before/$after 就废了。
$script:bin_err = $null
function Bin-Items {
$script:bin_err = $null
try {
$shell = New-Object -ComObject Shell.Application
return ,@($shell.Namespace(0xA).Items() | ForEach-Object { $_.Name })
} catch {
$script:bin_err = $_.Exception.Message
return $null
}
}
$pkg = Join-Path $scratch 'node_modules\pkg' $pkg = Join-Path $scratch 'node_modules\pkg'
New-Item -ItemType Directory -Force -Path $pkg | Out-Null New-Item -ItemType Directory -Force -Path $pkg | Out-Null
[IO.File]::WriteAllBytes((Join-Path $pkg 'blob.bin'), (New-Object byte[] 2MB)) [IO.File]::WriteAllBytes((Join-Path $pkg 'blob.bin'), (New-Object byte[] 2MB))
Ok ("fixture created: $scratch (2 MB)") $artefact = Join-Path $scratch 'node_modules'
$before = (New-Object -ComObject Shell.Application).Namespace(0xA).Items().Count Ok ("fixture created: $artefact (2 MB)")
& $squid purge $scratch --yes --trash --json
$after = (New-Object -ComObject Shell.Application).Namespace(0xA).Items().Count # 回收站的落地判据:量 C:\$Recycle.Bin 的字节数,别信 COM 枚举。
if (Test-Path $scratch) { Fail 'scratch folder still on disk after trash' } else { Ok 'scratch folder left the disk' } # 就是这条量出了真 bug —— IFileOperation 少了 FOF_ALLOWUNDO 时,
if ($after -le $before) { Fail "recycle bin did not grow ($before -> $after)" } else { Ok "recycle bin grew $before -> $after" } # 文件从磁盘消失、账本写 mode=trash、回收站一字节没多。
$names = (New-Object -ComObject Shell.Application).Namespace(0xA).Items() | ForEach-Object { $_.Name } function Bin-Bytes {
if ($names -match 'squid-rb-test') { Ok 'original name recoverable from recycle bin' } else { Fail 'fixture not found in recycle bin by name' } $t = 0
& $squid undo 2>&1 | Select-Object -First 4 foreach ($d in Get-ChildItem 'C:\$Recycle.Bin' -Force -Directory -ErrorAction SilentlyContinue) {
# 用 .NET 枚举:Get-ChildItem -Recurse 撞到别人 SID 的 ACL 会直接报错刷屏。
try {
foreach ($f in [IO.Directory]::EnumerateFiles($d.FullName, '*', 'AllDirectories')) {
try { $t += (New-Object IO.FileInfo $f).Length } catch {}
}
} catch {}
}
return $t
}
$bytesBefore = Bin-Bytes
Write-Output (" bin bytes before = {0:N0}" -f $bytesBefore)
$before = Bin-Items
if ($null -eq $before) { Write-Output (" Shell.Application 不可用: " + $script:bin_err) }
# --min-age 0 是必须的:purge 默认只碰 7 天没动的文件,刚建的 fixture 会被跳过。
# 进度走 stderr、结果走 stdout:把 2>&1 并起来会被 PowerShell 变成 ErrorRecord,
# JSON 就没了,所以这里分开收。
$purge = & $squid purge $scratch --yes --min-age 0 --json 2>$null | Out-String
if (-not $purge) { Fail 'purge --json 没有给出任何 stdout' }
$verdict = $null
try { $verdict = $purge | ConvertFrom-Json } catch { Fail "purge --json 解析失败: $_" }
if ($verdict) {
Write-Output (" removed={0} failed={1} mode={2} freed={3:N0} B" -f
$verdict.removed, $verdict.failed, $verdict.mode, $verdict.freed_allocated)
if ($verdict.mode -ne 'trash') { Fail ("mode={0},fixture 应为 trash 模式" -f $verdict.mode) }
if ($verdict.failed -gt 0) { Fail ("purge 报告 {0} 条失败" -f $verdict.failed) }
}
# 断言 artefact 自身被移走:purge 只删 node_modules,它的父目录本来就该留着。
if (Test-Path $artefact) { Fail 'trash 之后 node_modules 仍在磁盘上' } else { Ok 'node_modules 已离开磁盘' }
$bytesAfter = Bin-Bytes
$delta = $bytesAfter - $bytesBefore
Write-Output (" bin bytes after = {0:N0} (delta {1:N0})" -f $bytesAfter, $delta)
if ($delta -lt 1MB) {
Fail ("回收站只多了 {0:N0} 字节 —— 删除绕过了回收站,mode=trash 是假的" -f $delta)
} else { Ok ("回收站真的收到了 {0:N0} 字节" -f $delta) }
$after = Bin-Items
if ($null -eq $before -or $null -eq $after) {
Write-Output 'note: 无法从当前会话枚举回收站,改由账本判定'
} elseif (@($after).Count -le @($before).Count) {
Fail ("回收站条目数没有增加 ({0} -> {1})" -f @($before).Count, @($after).Count)
} else {
Ok ("回收站增加 {0} -> {1}" -f @($before).Count, @($after).Count)
}
if ($after -and (@($after) -match [regex]::Escape($run))) { Ok "回收站里能看到原名 $run" }
elseif ($after) { Write-Output ("note: 回收站里按原名找不到 {0},内容: {1}" -f $run, ((@($after) | Select-Object -First 8) -join ' | ')) }
Step 'undo'
# Windows 上回收站不记录落地路径,undo 应给出"去回收站里还原"的指引而不是假装恢复。
$undo = & $squid undo 2>&1 | Out-String
if ($undo) { Write-Output (($undo.Trim() -split "`n" | Select-Object -First 8) -join "`n") }
if ($undo -match 'no trashed session') { Fail 'purge 之后账本里没有这次回收会话' } else { Ok 'undo 认出了刚才的会话' }
Step 'result' Step 'result'
if ($fails.Count) { Write-Output ("FAILURES: " + $fails.Count); $fails | ForEach-Object { Write-Output " - $_" }; exit 1 } if ($fails.Count) { Write-Output ("FAILURES: " + $fails.Count); $fails | ForEach-Object { Write-Output " - $_" }; exit 1 }

View File

@ -0,0 +1,89 @@
#!/usr/bin/env bash
# 在 Windows 真机上把 TUI 抓成一帧纯文本,验证 ConPTY 上的绘制结果。
#
# ./scripts/win-tui-capture.sh # 抓 state 界面
# ./scripts/win-tui-capture.sh --lang zh # 中文界面(验证 CJK 宽度)
# TUI_KEYS="s q" ./scripts/win-tui-capture.sh # 先扫描再退出(验证有数据的排版)
#
# 为什么不能用 scripts/tui_smoke.py:那个脚本自己 forkpty(),是 POSIX 专属。
# 真机上没有 pty 可以 fork,只能反过来:让 sshd 用 CreatePseudoConsole 分配一个
# ConPTY(Windows OpenSSH 在 1809+ 上对 -tt 就是这么做的),crossterm 因此走真正的
# Windows 控制台后端,而不是退化到没验证过的 ANSI 假设。原始 ANSI 落盘后拿回本地,
# 用 pyte 这个终端仿真器解码成文本 —— 看到的才是用户会看到的那一帧。
set -uo pipefail
cd "$(dirname "$0")/.."
WIN_HOST="${WIN_HOST:-KANGWJ@192.168.2.92}"
WIN_KEY="${WIN_KEY:-$HOME/.ssh/id_ed25519_windows}"
BIN="${WIN_BIN:-C:\dev\target\release\squid.exe}"
OUT="${TUI_OUT:-/tmp/squid-win-tui.bin}"
COLS="${TUI_COLS:-100}"
ROWS="${TUI_ROWS:-30}"
DELAY="${TUI_DELAY:-8}"
# 尺寸:ConPTY 的窗口大小由 pty 请求决定,ssh 会把它自己的 winsize 传过去,
# 所以这里用 stty 定一个已知的尺寸,pyte 才能按同样的宽度重排。
printf '\033[1;36m==>\033[0m 抓取 %s (%sx%s, %ss)\n' "$BIN" "$COLS" "$ROWS" "$DELAY"
# 按键序列:默认只按 q 退出。想验证"有数据时"的排版,用 TUI_KEYS="s q"
# 先触发扫描再退出 —— 空面板和有数据的面板排的是两种版。
TUI_KEYS="${TUI_KEYS:-q}"
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" \
"chcp 65001 >nul & mode con cols=$COLS lines=$ROWS >nul 2>&1& $BIN state $* 2>&1" \
> "$OUT" 2>&1
rc=$?
printf '\033[1;36m==>\033[0m 原始 ANSI 已存 %s (%s 字节, ssh rc=%s)\n' "$OUT" "$(wc -c < "$OUT" | tr -d ' ')" "$rc"
python3 - "$OUT" "$COLS" "$ROWS" <<'PYEOF'
import sys, unicodedata
raw = open(sys.argv[1], 'rb').read().decode('utf-8', 'replace')
cols, rows = int(sys.argv[2]), int(sys.argv[3])
try:
import pyte
except ImportError:
sys.exit("需要 pyte: pip3 install pyte")
# 退出时 TUI 会擦掉整屏(crossterm 的 Clear + LeaveAlternateScreen),所以
# "最后一帧"必然是空的。逐块喂给仿真器,留下内容最多的那一帧 —— 那才是用户
# 按 q 之前看到的界面。
def render(data):
screen = pyte.Screen(cols, rows)
pyte.Stream(screen).feed(data)
try:
lines = [l.rstrip() for l in screen.display]
except IndexError:
# 这一帧正好喂到被截断的半个字符上,pyte 量宽度时会越界。跳过它。
return []
while lines and not lines[-1]:
lines.pop()
return lines
best = []
step = 64
for cut in range(step, len(raw) + step, step):
lines = render(raw[:cut])
filled = sum(1 for l in lines if l.strip())
if filled >= sum(1 for l in best if l.strip()):
best = lines
print("\n".join(best))
print()
# 制表符没解码出来 = 字体/代码页问题;U+FFFD = 编码链路某一环把字节弄丢了。
bad = [ch for ch in raw if ch == '\ufffd']
if bad:
at = raw.index('\ufffd')
where = '流中间 = 控制台画不出这个字形' if at < len(raw) - 24 else '流末尾 = ssh 断开切掉半帧'
print(f"[decode] 第一个 U+FFFD 在偏移 {at}/{len(raw)}:{where}")
frame = "".join(best)
fbad = frame.count('\ufffd')
print(f"[decode] {len(raw)} 字符 · 原始流 U+FFFD {len(bad)} 个 · 屏上 U+FFFD {fbad} 个 · 制表符 {'出现' if any(c in frame for c in '─│┌┐└┘') else '未出现'}")
if fbad:
for n, l in enumerate(best, 1):
if '\ufffd' in l:
print(f"[decode] !!! 第 {n} 行有画不出来的字形: {l!r}")
cjk = [ch for ch in raw if 'CJK' in unicodedata.name(ch, '')]
print(f"[decode] CJK 字符 {len(cjk)} 个")
if 'panicked' in raw.lower():
print("[decode] !!! 输出里有 panic 字样")
PYEOF