// 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. 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 { 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 { 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 { 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> { 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) } /// 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) -> 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"); } } }