AnyBot/src/platform.rs

186 lines
8.2 KiB
Rust
Raw Normal View History

// The system AnyBot runs on. Most words in the app were written for the Mac ("這台 Mac",
// "this Mac"); on Linux (and later Windows) the same sentences say "這台電腦" / "this computer".
// `localize` is applied to every translated label (i18n::t) and to what the bot is told (its
// instructions and tool descriptions), so the wording follows the system in one place.
修正卡死: ⌘ 一按視窗就鎖死、圖表縮小凍結、打字每鍵寫檔;複製中文亂碼;頭像不再擋住思考動畫 卡住當機 - ⌘1–⌘9(Win/Linux 為 Ctrl)在 ctx.input 裡又呼叫 ctx.input,egui 的 Context 被鎖兩次, 按住 ⌘(⌘C、⌘V、⌘Tab)視窗就永遠不動;改為只讀一次(bot_jump_key),加回歸測試 - 圖表 x 軸格線固定每 1 一條,縮小後一幀要畫上百萬條(凍結、記憶體爆);改為最多約 40 條, 滾輪不再被圖表吃掉(⌘/Ctrl+滾輪或雙指縮放) - 草稿每打一個字就同步重寫整個 state.json(含 fsync);改為停手 1.5 秒後才存,結尾空白也 不再造成每幀存檔 複製(三個系統) - Mac:pbcopy 從 Finder/Dock 開時沒有 UTF-8 語系,中文變亂碼;指定 UTF-8 - ⌘C 攔截只拿 CopyText,不再丟掉開連結、複製圖片、Linux 中鍵選取等指令(且只在 Mac 攔) - Windows:改用 Win32 剪貼簿(arboard,獨立執行緒),不再走 clip.exe(缺 BOM、多一個 NUL) - Linux:依 WAYLAND_DISPLAY/DISPLAY 選 wl-copy 或 xclip/xsel,都沒有時退回視窗剪貼簿 其他 - 頁面目錄點了不跳(標題位置從未記錄);目錄搜尋框按 Esc 會關掉整頁 - 圖表:單一系列欄名被 String::max 換成「數值」;同尺寸無標題的圖共用縮放;inf/NaN 不入圖 - KPI 卡片寬度未扣內距而超出欄寬 - 「還原上一個答案」在送出新訊息後會插錯位置;重試錯誤回覆不再存可還原的版本 - 手機:長輪詢回來時已切到別的聊天,不再把上一個聊天的訊息畫進來 - 輸入框上方頭像:思考時頭稍微縮小,三顆小球繞著頭轉(後面的從頭後經過、前面的壓在頭上並描邊), 不再被頭像蓋住 - 刪除未使用的 src/app/ui_kit.rs 驗證:macOS cargo test 374 通過(relay 18 通過);Windows/Linux cargo check 通過 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 06:19:59 +00:00
use eframe::egui;
const PAIRS: &[(&str, &str)] = &[
("使用者的這台 Mac", "使用者的這台電腦"),
("這台 Mac", "這台電腦"),
("你的 Mac", "你的電腦"),
("使用者的 Mac", "使用者的電腦"),
("我的 Mac", "我的電腦"),
("macOS 鑰匙圈", "系統鑰匙圈"),
("在 Finder 中顯示", "打開所在資料夾"),
("Finder", "檔案管理員"),
("この Mac", "このコンピューター"),
("the person's Mac", "the person's computer"),
("person's Mac", "person's computer"),
("this Mac", "this computer"),
("This Mac", "This computer"),
("your Mac", "your computer"),
("my Mac", "my computer"),
("the Mac", "the computer"),
("macOS Keychain", "system keyring"),
];
/// Mac wording → this system's wording (unchanged on macOS).
pub fn localize(s: &str) -> String {
// "macOS Keychain" and "macOS 鑰匙圈" contain no "Mac" (lowercase m), so the quick
// guard has to test "macOS" as well — those pairs used to never apply.
if cfg!(target_os = "macos") || !s.contains("Mac") && !s.contains("macOS") && !s.contains("Finder") {
return s.to_string();
}
let mut out = s.to_string();
for (a, b) in PAIRS {
out = out.replace(a, b);
}
out
}
/// Every string inside a JSON value (tool descriptions).
#[cfg_attr(target_os = "macos", allow(dead_code))]
pub fn localize_value(v: &mut serde_json::Value) {
if cfg!(target_os = "macos") {
return;
}
match v {
serde_json::Value::String(s) => *s = localize(s),
serde_json::Value::Array(a) => a.iter_mut().for_each(localize_value),
serde_json::Value::Object(o) => o.values_mut().for_each(localize_value),
_ => {}
}
}
// ---------- file dialogs on Linux: zenity (GNOME and most desktops) or kdialog (KDE) ----------
fn dialog(zenity: &[&str], kdialog: &[&str]) -> Option<String> {
for (cmd, args) in [("zenity", zenity), ("kdialog", kdialog)] {
match std::process::Command::new(cmd).args(args).stderr(std::process::Stdio::null()).output() {
// Exit code 1 = the person pressed Cancel: don't try the other one.
Ok(o) if o.status.success() => return Some(String::from_utf8_lossy(&o.stdout).trim_end_matches('\n').to_string()),
Ok(o) if o.status.code() == Some(1) => return None,
// Missing binary (Err) or a tool error (zenity 5, kdialog 2): fall through to
// the other tool — the old code returned None on any spawn, so a broken zenity
// hid the working kdialog.
_ => continue,
}
}
None
}
/// Pick files to open (several at once).
pub fn pick_files_linux(title: &str) -> Vec<std::path::PathBuf> {
dialog(&["--file-selection", "--multiple", "--separator=\n", &format!("--title={title}")], &["--getopenfilename", ".", "--multiple", "--separate-output", "--title", title])
.map(|s| s.lines().map(str::trim).filter(|l| !l.is_empty()).map(std::path::PathBuf::from).collect())
.unwrap_or_default()
}
/// Pick where to save (starting in Downloads with the given name).
pub fn choose_save_linux(title: &str, default_name: &str) -> Option<std::path::PathBuf> {
let start = dirs::download_dir().or_else(dirs::home_dir).unwrap_or_default().join(default_name);
let start = start.display().to_string();
dialog(&["--file-selection", "--save", "--confirm-overwrite", &format!("--filename={start}"), &format!("--title={title}")], &["--getsavefilename", &start, "--title", title])
.filter(|p| !p.is_empty())
.map(std::path::PathBuf::from)
}
/// A picture on the clipboard as PNG bytes (wl-paste on Wayland, xclip on X11).
pub fn clipboard_png_linux() -> Option<Vec<u8>> {
let wayland = std::env::var("WAYLAND_DISPLAY").map(|v| !v.is_empty()).unwrap_or(false);
let (types, get): (Vec<&str>, Vec<&str>) = if wayland {
(vec!["wl-paste", "--list-types"], vec!["wl-paste", "--no-newline", "--type", "image/png"])
} else {
(vec!["xclip", "-selection", "clipboard", "-t", "TARGETS", "-o"], vec!["xclip", "-selection", "clipboard", "-t", "image/png", "-o"])
};
let list = std::process::Command::new(types[0]).args(&types[1..]).stderr(std::process::Stdio::null()).output().ok()?;
if !String::from_utf8_lossy(&list.stdout).lines().any(|l| l.trim() == "image/png") {
return None;
}
let o = std::process::Command::new(get[0]).args(&get[1..]).stderr(std::process::Stdio::null()).output().ok()?;
(o.status.success() && o.stdout.starts_with(b"\x89PNG")).then_some(o.stdout)
}
修正卡死: ⌘ 一按視窗就鎖死、圖表縮小凍結、打字每鍵寫檔;複製中文亂碼;頭像不再擋住思考動畫 卡住當機 - ⌘1–⌘9(Win/Linux 為 Ctrl)在 ctx.input 裡又呼叫 ctx.input,egui 的 Context 被鎖兩次, 按住 ⌘(⌘C、⌘V、⌘Tab)視窗就永遠不動;改為只讀一次(bot_jump_key),加回歸測試 - 圖表 x 軸格線固定每 1 一條,縮小後一幀要畫上百萬條(凍結、記憶體爆);改為最多約 40 條, 滾輪不再被圖表吃掉(⌘/Ctrl+滾輪或雙指縮放) - 草稿每打一個字就同步重寫整個 state.json(含 fsync);改為停手 1.5 秒後才存,結尾空白也 不再造成每幀存檔 複製(三個系統) - Mac:pbcopy 從 Finder/Dock 開時沒有 UTF-8 語系,中文變亂碼;指定 UTF-8 - ⌘C 攔截只拿 CopyText,不再丟掉開連結、複製圖片、Linux 中鍵選取等指令(且只在 Mac 攔) - Windows:改用 Win32 剪貼簿(arboard,獨立執行緒),不再走 clip.exe(缺 BOM、多一個 NUL) - Linux:依 WAYLAND_DISPLAY/DISPLAY 選 wl-copy 或 xclip/xsel,都沒有時退回視窗剪貼簿 其他 - 頁面目錄點了不跳(標題位置從未記錄);目錄搜尋框按 Esc 會關掉整頁 - 圖表:單一系列欄名被 String::max 換成「數值」;同尺寸無標題的圖共用縮放;inf/NaN 不入圖 - KPI 卡片寬度未扣內距而超出欄寬 - 「還原上一個答案」在送出新訊息後會插錯位置;重試錯誤回覆不再存可還原的版本 - 手機:長輪詢回來時已切到別的聊天,不再把上一個聊天的訊息畫進來 - 輸入框上方頭像:思考時頭稍微縮小,三顆小球繞著頭轉(後面的從頭後經過、前面的壓在頭上並描邊), 不再被頭像蓋住 - 刪除未使用的 src/app/ui_kit.rs 驗證:macOS cargo test 374 通過(relay 18 通過);Windows/Linux cargo check 通過 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 06:19:59 +00:00
/// Text to the clipboard, the way that cannot freeze the window on each system:
/// - Mac: through `pbcopy`, not in-process. Writing NSPasteboard from the app hangs the whole
/// window when macOS's text services are unwell (the person taps 複製 and the app freezes — a
/// frozen app, not a crash, so there is no crash report to find). A helper may hang; the app
/// never may. pbcopy reads its input in the locale's encoding, and an app opened from Finder or
/// the Dock has no locale set — so it is told UTF-8, or Chinese arrives as 「‰∏≠Êñá」.
/// - Windows: the Win32 clipboard, in-process on a thread of its own (Unicode as is; no console
/// window flashes, no code page to get wrong).
/// - Linux: `wl-copy` in a Wayland session, `xclip`/`xsel` under X11 — they keep serving the
/// words after the app has gone. Without them, the window's own clipboard.
///
/// When nothing else works, egui's own clipboard (what eframe does at the end of the frame).
pub fn copy_text(ctx: &egui::Context, text: &str) {
#[cfg(target_os = "macos")]
{
let utf8 = [("LANG", "en_US.UTF-8"), ("LC_ALL", "en_US.UTF-8"), ("LC_CTYPE", "UTF-8")];
if spawn_copy("/usr/bin/pbcopy", &[], &utf8, text.as_bytes().to_vec()) {
return;
}
}
#[cfg(target_os = "windows")]
{
let (ctx, text) = (ctx.clone(), text.to_string());
std::thread::spawn(move || {
let done = arboard::Clipboard::new().and_then(|mut c| c.set_text(text.clone()));
if done.is_err() {
ctx.copy_text(text);
ctx.request_repaint();
}
});
return;
}
#[cfg(target_os = "linux")]
{
let set = |k: &str| std::env::var(k).map(|v| !v.is_empty()).unwrap_or(false);
let bytes = text.as_bytes();
if set("WAYLAND_DISPLAY") && spawn_copy("wl-copy", &[], &[], bytes.to_vec()) {
return;
}
if set("DISPLAY") && (spawn_copy("xclip", &["-selection", "clipboard"], &[], bytes.to_vec()) || spawn_copy("xsel", &["--clipboard", "--input"], &[], bytes.to_vec())) {
return;
}
}
#[allow(unreachable_code)]
ctx.copy_text(text.to_string());
}
/// Feed bytes to a clipboard helper's standard input, on a thread of its own; false when the
/// tool is not there at all.
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn spawn_copy(bin: &str, args: &[&str], env: &[(&str, &str)], bytes: Vec<u8>) -> bool {
use std::io::Write;
let mut c = std::process::Command::new(bin);
c.args(args).envs(env.iter().copied()).stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
let Ok(mut child) = c.spawn() else { return false };
let Some(mut si) = child.stdin.take() else {
let _ = child.kill();
let _ = child.wait();
return false;
};
std::thread::spawn(move || {
let _ = si.write_all(&bytes);
let _ = si.flush();
drop(si);
let _ = child.wait();
});
true
}
#[cfg(test)]
mod tests {
#[test]
fn mac_words_follow_the_system() {
let s = super::localize("檔案在這台 Mac;on this Mac");
if cfg!(target_os = "macos") {
assert_eq!(s, "檔案在這台 Mac;on this Mac");
} else {
assert_eq!(s, "檔案在這台電腦;on this computer");
}
}
}