diff --git a/README.md b/README.md index bf9bc21f..738e9cfd 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,19 @@ disktree ~/src # or any directory disktree --help # options: apparent size, follow links, skip hidden, … ``` +### Interface language + +Click **Language / 语言** in the top bar or source chooser, or press `F2`, +then choose **English** or **简体中文**. The window changes immediately; the +current scan, navigation and marked paths stay in place. The choice is saved +for the next launch in the user configuration directory, beside the Power +Efficiency setting. English is the default and fallback. + +The language setting covers the window and macOS application menus. Command +line help, exported prompts/scripts and technical filesystem/SSH diagnostics +retain their original wording. See [Adding a language](docs/translations.md) +to contribute another translation. + ### Servers over SSH (read-only) ```sh diff --git a/crates/disktree-app/src/app_menu.rs b/crates/disktree-app/src/app_menu.rs index faee4762..a11a83a2 100644 --- a/crates/disktree-app/src/app_menu.rs +++ b/crates/disktree-app/src/app_menu.rs @@ -5,6 +5,8 @@ //! draws no menu bar on Linux or Windows, so there the same actions get the //! shortcuts their users expect, with ctrl, and nothing else. +use crate::i18n::t; + use gpui_kit::{App, KeyBinding, Menu, MenuItem, SystemMenuType}; pub use menu_actions::*; @@ -39,6 +41,8 @@ mod menu_actions { GoBack, /// Forward again, after going back. GoForward, + /// Choose the interface language. + ChooseLanguage, ] ); } @@ -90,27 +94,39 @@ pub fn install(cx: &mut App) { KeyBinding::new("cmd-[", GoBack, None), KeyBinding::new("cmd-]", GoForward, None), ]); + update_language(cx); +} + +/// Rebuild localized menus without registering handlers or bindings twice. +pub fn update_language(cx: &App) { + if !cfg!(target_os = "macos") { + return; + } cx.set_menus([ Menu::new("disktree").items([ - MenuItem::os_submenu("Services", SystemMenuType::Services), + MenuItem::os_submenu(t!(cx, "Services"), SystemMenuType::Services), MenuItem::separator(), - MenuItem::action("Hide disktree", Hide), - MenuItem::action("Hide Others", HideOthers), - MenuItem::action("Show All", ShowAll), + MenuItem::action(t!(cx, "Hide disktree"), Hide), + MenuItem::action(t!(cx, "Hide Others"), HideOthers), + MenuItem::action(t!(cx, "Show All"), ShowAll), MenuItem::separator(), - MenuItem::action("Quit disktree", Quit), + MenuItem::action(t!(cx, "Quit disktree"), Quit), ]), - Menu::new("File").items([ - MenuItem::action("Open Folder\u{2026}", OpenFolder), - MenuItem::action("Show in Finder", ShowInFinder), + Menu::new(t!(cx, "File")).items([ + MenuItem::action(t!(cx, "Open Folder\u{2026}"), OpenFolder), + MenuItem::action(t!(cx, "Show in Finder"), ShowInFinder), MenuItem::separator(), - MenuItem::action("Rescan", Rescan), + MenuItem::action(t!(cx, "Rescan"), Rescan), MenuItem::separator(), - MenuItem::action("Close Window", CloseWindow), + MenuItem::action(t!(cx, "Close Window"), CloseWindow), ]), - Menu::new("Go").items([ - MenuItem::action("Back", GoBack), - MenuItem::action("Forward", GoForward), + Menu::new("Language / 语言").items([MenuItem::action( + t!(cx, "Choose interface language"), + ChooseLanguage, + )]), + Menu::new(t!(cx, "Go")).items([ + MenuItem::action(t!(cx, "Back"), GoBack), + MenuItem::action(t!(cx, "Forward"), GoForward), ]), ]); } diff --git a/crates/disktree-app/src/git.rs b/crates/disktree-app/src/git.rs index b4a69e31..643d5ff1 100644 --- a/crates/disktree-app/src/git.rs +++ b/crates/disktree-app/src/git.rs @@ -29,22 +29,31 @@ impl GitState { } /// One short line: `clean, no stash`, `3 changed, 1 stash, 2 unpushed`. - pub fn summary(&self) -> String { + pub fn summary(&self, language: crate::i18n::Language) -> String { let mut parts = Vec::new(); parts.push(match self.changed { - Some(0) => "clean".to_string(), - Some(count) => format!("{count} changed"), - None => "changes unknown".to_string(), + Some(0) => language.text("clean").to_string(), + Some(count) => crate::i18n::format( + language.text("{0} changed"), + &[count.to_string()], + ), + None => language.text("changes unknown").to_string(), }); parts.push(match self.stashes { - 0 => "no stash".to_string(), - 1 => "1 stash".to_string(), - count => format!("{count} stashes"), + 0 => language.text("no stash").to_string(), + 1 => language.text("1 stash").to_string(), + count => crate::i18n::format( + language.text("{0} stashes"), + &[count.to_string()], + ), }); match self.unpushed { Some(0) => {} - Some(count) => parts.push(format!("{count} unpushed")), - None => parts.push("no upstream".to_string()), + Some(count) => parts.push(crate::i18n::format( + language.text("{0} unpushed"), + &[count.to_string()], + )), + None => parts.push(language.text("no upstream").to_string()), } parts.join(", ") } @@ -218,25 +227,37 @@ mod tests { ..GitState::default() }; assert!(clean.is_clean()); - assert_eq!(clean.summary(), "clean, no stash"); + assert_eq!( + clean.summary(crate::i18n::Language::English), + "clean, no stash" + ); let busy = GitState { changed: Some(3), stashes: 1, unpushed: Some(2), }; assert!(!busy.is_clean()); - assert_eq!(busy.summary(), "3 changed, 1 stash, 2 unpushed"); + assert_eq!( + busy.summary(crate::i18n::Language::English), + "3 changed, 1 stash, 2 unpushed" + ); let local = GitState { changed: Some(0), ..GitState::default() }; - assert_eq!(local.summary(), "clean, no stash, no upstream"); + assert_eq!( + local.summary(crate::i18n::Language::English), + "clean, no stash, no upstream" + ); assert!(!local.is_clean(), "unpushed history could be lost"); let guarded = GitState { unpushed: Some(0), ..GitState::default() }; - assert_eq!(guarded.summary(), "changes unknown, no stash"); + assert_eq!( + guarded.summary(crate::i18n::Language::English), + "changes unknown, no stash" + ); assert!(!guarded.is_clean(), "unknown is not clean"); } diff --git a/crates/disktree-app/src/i18n.rs b/crates/disktree-app/src/i18n.rs new file mode 100644 index 00000000..3cd3c2d4 --- /dev/null +++ b/crates/disktree-app/src/i18n.rs @@ -0,0 +1,191 @@ +//! Window language and a small, dependency-free message catalog. + +use std::io::{self, Write as _}; +use std::path::{Path, PathBuf}; + +use gpui_kit::{App, Global}; + +#[path = "locales/zh_cn.rs"] +mod zh_cn; + +/// Languages offered by the window, using stable keys in the saved setting. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Language { + #[default] + English, + SimplifiedChinese, +} + +impl Global for Language {} + +impl Language { + /// Display order of the built-in languages. + pub const ALL: [Self; 2] = [Self::English, Self::SimplifiedChinese]; + + /// Stable locale identifier; independent of the translated display name. + pub const fn key(self) -> &'static str { + match self { + Self::English => "en", + Self::SimplifiedChinese => "zh-CN", + } + } + + /// Autonyms keep the language control usable after an accidental switch. + pub const fn name(self) -> &'static str { + match self { + Self::English => "English", + Self::SimplifiedChinese => "简体中文", + } + } + + /// Unknown or newer keys safely retain the original English interface. + pub fn parse(key: &str) -> Self { + Self::ALL + .into_iter() + .find(|lang| lang.key() == key) + .unwrap_or_default() + } + + /// English is also the fallback for a message not yet translated. + pub fn text(self, key: &str) -> &str { + if self == Self::SimplifiedChinese + && let Ok(index) = + zh_cn::MESSAGES.binary_search_by_key(&key, |&(en, _)| en) + { + return zh_cn::MESSAGES[index].1; + } + key + } +} + +/// Read the language from this GPUI app, keeping window tests isolated. +pub fn language(cx: &App) -> Language { + cx.try_global::().copied().unwrap_or_default() +} + +/// Translate presentation text; never use this for paths or protocol values. +pub fn text<'a>(cx: &App, key: &'a str) -> &'a str { + language(cx).text(key) +} + +/// Substitute numbered slots in one pass. Inserted paths are never parsed +/// again, even when they contain braces or look like another slot. +pub fn format(template: &str, values: &[String]) -> String { + let mut result = String::new(); + let mut rest = template; + while let Some(start) = rest.find('{') { + result.push_str(&rest[..start]); + rest = &rest[start..]; + if let Some(end) = rest.find('}') + && let Ok(index) = rest[1..end].parse::() + && let Some(value) = values.get(index) + { + result.push_str(value); + rest = &rest[end + 1..]; + } else { + result.push('{'); + rest = &rest[1..]; + } + } + result.push_str(rest); + result +} + +/// Save beside the existing per-user power preference, never in a scan root. +pub fn settings_path() -> Option { + crate::power::settings_path().map(|path| path.with_file_name("language")) +} + +/// Missing preferences use English; filesystem failures remain visible. +pub fn load(path: &Path) -> io::Result { + match std::fs::read_to_string(path) { + Ok(value) => Ok(Language::parse(value.trim())), + Err(error) if error.kind() == io::ErrorKind::NotFound => { + Ok(Language::default()) + } + Err(error) => Err(error), + } +} + +/// Atomic replacement preserves the previous setting after a failed write. +pub fn save(path: &Path, language: Language) -> io::Result<()> { + let parent = path.parent().ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "no settings directory") + })?; + std::fs::create_dir_all(parent)?; + let mut file = tempfile::NamedTempFile::new_in(parent)?; + writeln!(file, "{}", language.key())?; + file.persist(path).map_err(|error| error.error)?; + Ok(()) +} + +/// Static messages borrow the catalog; numbered messages format their values. +macro_rules! t { + ($cx:expr, $key:expr) => { crate::i18n::text($cx, $key) }; + ($cx:expr, $key:expr, $($value:expr),+ $(,)?) => { + crate::i18n::format(crate::i18n::text($cx, $key), &[$(format!("{}", $value)),+]) + }; +} +pub(crate) use t; + +#[cfg(test)] +mod tests { + use super::*; + + fn slots(template: &str) -> Vec { + let mut slots = template + .split('{') + .skip(1) + .map(|part| { + part.split_once('}') + .expect("closed slot") + .0 + .parse() + .expect("numbered slot") + }) + .collect::>(); + slots.sort_unstable(); + slots + } + + #[test] + fn catalog_is_sorted_complete_and_preserves_every_slot() { + let mut previous = ""; + for &(english, chinese) in zh_cn::MESSAGES { + assert!(english > previous, "duplicate or unsorted: {english}"); + assert!(!chinese.is_empty(), "missing: {english}"); + assert_eq!(slots(english), slots(chinese), "slots: {english}"); + assert_eq!(Language::English.text(english), english); + assert_eq!(Language::SimplifiedChinese.text(english), chinese); + previous = english; + } + assert_eq!( + Language::SimplifiedChinese.text("untranslated diagnostic"), + "untranslated diagnostic" + ); + } + + #[test] + fn numbered_slots_can_reorder_without_interpreting_inserted_paths() { + assert_eq!( + format("{1}: {0} / {1}", &["folder/{1}/中文".into(), "3".into()]), + "3: folder/{1}/中文 / 3" + ); + assert_eq!(format("{9} {bad} {", &[]), "{9} {bad} {"); + } + + #[test] + fn saved_language_survives_replacement_and_unknown_values_fall_back() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("config/language"); + assert_eq!(load(&path).expect("missing"), Language::English); + for language in Language::ALL { + save(&path, language).expect("save"); + assert_eq!(load(&path).expect("load"), language); + } + std::fs::write(&path, "future-language").expect("write"); + assert_eq!(load(&path).expect("fallback"), Language::English); + assert!(save(dir.path(), Language::English).is_err()); + assert!(load(dir.path()).is_err()); + } +} diff --git a/crates/disktree-app/src/locales/zh_cn.rs b/crates/disktree-app/src/locales/zh_cn.rs new file mode 100644 index 00000000..68fa04d3 --- /dev/null +++ b/crates/disktree-app/src/locales/zh_cn.rs @@ -0,0 +1,523 @@ +//! Simplified Chinese. Keep keys sorted and preserve every numbered slot. + +pub const MESSAGES: &[(&str, &str)] = &[ + (" · {0} · read-only", " · {0} · 只读"), + ("+{0} more", "另有 {0} 项"), + ( + "+{0} more on the review screen", + "清理检查界面中另有 {0} 项", + ), + ("+{0} smaller", "另有 {0} 个较小项目"), + ( + ", and a whole drive several times faster", + ",扫描整个驱动器也会快数倍", + ), + ("1 stash", "1 个贮藏"), + ("? or esc closes · {0} · {1}", "? 或 esc 关闭 · {0} · {1}"), + ( + "A permanent deletion always asks first", + "永久删除前始终要求确认", + ), + ("Acted on", "实际处理"), + ("Age", "时间"), + ("Agent scratch", "智能体临时文件"), + ("Aggressive", "高性能"), + ("Apparent size", "文件逻辑大小"), + ("Back", "返回"), + ( + "Back or forward, as do the mouse's side buttons", + "后退或前进,也可使用鼠标侧键", + ), + ("Balanced", "均衡"), + ("Building the treemap", "正在生成矩形树图"), + ("Cache", "缓存"), + ("Cancel", "取消"), + ("Cannot open that local directory.", "无法打开该本机目录。"), + ("Checking remote scanner", "正在检查远程扫描器"), + ( + "Choose a source. Then choose a root.", + "先选择来源,再选择根目录。", + ), + ("Choose another directory to scan", "选择其他目录进行扫描"), + ("Choose interface language", "选择界面语言"), + ("Choose interface language · F2", "选择界面语言 · F2"), + ("Choose local or SSH source · v", "选择本机或 SSH 来源 · v"), + ("Choose source…", "选择来源…"), + ("Choose what to scan", "选择扫描位置"), + ("Close Window", "关闭窗口"), + ("Code", "代码"), + ("Connect SSH", "连接 SSH"), + ( + "Connect SSH or choose This computer before scanning.", + "请先连接 SSH 或选择“本机”,再开始扫描。", + ), + ( + "Connect, then select a mount or directory. No new scan starts until you choose Scan.", + "连接后选择挂载点或目录。点击“扫描”才会开始新的扫描。", + ), + ("Connecting over SSH", "正在通过 SSH 连接"), + ("Copy as prompt", "复制为提示词"), + ("Copy delete script", "复制删除脚本"), + ("Custom", "自定义"), + ("Delete", "删除"), + ("Delete permanently", "永久删除"), + ("Delete {0} items permanently?", "永久删除 {0} 个项目?"), + ("Delete {0} {1}…", "删除 {0} {1}…"), + ("Delete “{0}” permanently?", "永久删除“{0}”?"), + ( + "Deleted at once, like rm -rf. Nothing is recoverable.", + "立即永久删除,类似 rm -rf。所有内容均无法恢复。", + ), + ("Depth {0}", "层级 {0}"), + ("Directories", "目录"), + ("Directory not reported yet", "尚未收到目录信息"), + ("Disk", "磁盘"), + ("Disk usage or apparent size", "磁盘占用或文件逻辑大小"), + ("Documents", "文档"), + ("Done", "完成"), + ("Drain My Battery", "全速运行"), + ( + "Draw fewer or more levels at once", + "减少或增加同时显示的层级", + ), + ("Elapsed", "已用时间"), + ( + "Enter an absolute directory path.", + "请输入目录的绝对路径。", + ), + ("File", "文件"), + ("Files", "文件"), + ("Filter by name", "按名称筛选"), + ( + "Filter by name: only matches keep their colour; enter shows only them", + "按名称筛选:仅匹配项保留颜色;enter 仅显示匹配项", + ), + ("Forward", "前进"), + ("Free space is not available here", "无法获取此处的可用空间"), + ("Go", "前往"), + ("Go up one directory", "返回上一级目录"), + ("Goes with {0}", "随 {0} 一同处理"), + ("Hidden", "隐藏"), + ("Hidden files", "隐藏文件"), + ("Hide Others", "隐藏其他应用"), + ("Hide disktree", "隐藏 disktree"), + ("Home directory", "主目录"), + ("Include or skip hidden entries", "包含或跳过隐藏项目"), + ("Indexing", "正在索引"), + ("Indexing remotely", "正在远程索引"), + ("Indexing stopped", "索引已停止"), + ("Indexing · incomplete", "正在索引 · 尚未完成"), + ("Inside a marked directory", "位于已标记的目录内"), + ("Inside marked {0}", "位于已标记的 {0} 内"), + ("Interface zoom", "界面缩放"), + ("Kept back", "已阻止"), + ("Keyboard and mouse", "键盘与鼠标"), + ("Kind", "类型"), + ("Language / 语言", "Language / 语言"), + ( + "Language changed for this session; no settings directory is available", + "本次会话的语言已切换;未找到可保存设置的目录", + ), + ( + "Language changed, but could not be saved: {0}", + "语言已切换,但无法保存:{0}", + ), + ("Language saved", "语言设置已保存"), + ("Last write", "最后修改"), + ("Levels drawn at once · [ and ]", "同时显示的层级 · [ 和 ]"), + ( + "Listing mounts, not scanning files…", + "正在列出挂载点,尚未扫描文件…", + ), + ( + "Live overview · incomplete · top-level contributions", + "实时概览 · 尚未完成 · 顶层目录已测量的占用", + ), + ( + "Local or SSH · one mount at a time · no background scan", + "本机或 SSH · 每次一个挂载点 · 无后台扫描", + ), + ("Magnify, shrink, or reset the view", "放大、缩小或重置视图"), + ("Mark for removal", "标记待清理"), + ( + "Mark or unmark the tile you point at", + "标记或取消标记指向的区块", + ), + ( + "Mark without moving the selection", + "标记区块并保持当前选择", + ), + ("Marked", "已标记"), + ("Marked for removal", "已标记待清理"), + ("Marked · {0}", "已标记 · {0}"), + ("Measured", "已测量"), + ("Media", "媒体"), + ("Miser", "极省电"), + ( + "More workers finish a scan sooner only up to a point. Past it they use more CPU for no gain, and can run the fans at full speed.", + "增加扫描线程只在一定范围内有效。超过该范围会增加 CPU 消耗,却无法加快扫描,还可能让风扇全速运行。", + ), + ("Mounted volume", "已挂载的卷"), + ("Move between tiles at this level", "在当前层级的区块间移动"), + ("Move to trash", "移至回收站"), + ("Move {0} {1} to trash", "将 {0} {1}移至回收站"), + ( + "Nested mounts and symlinks are not traversed. Space is measured only after selection.", + "不遍历嵌套挂载点和符号链接。选择位置后才会测量空间。", + ), + ("Nested, go with a parent", "随父目录一同处理"), + ("Next largest sibling", "选择下一个较大的同级项目"), + ( + "No mounts listed. Enter a directory below.", + "未找到挂载点。请在下方输入目录。", + ), + ("Not counted here", "未计入此卷"), + ( + "Nothing is marked. Go back and mark what should go.", + "尚未标记任何内容。请返回并标记需要清理的项目。", + ), + ("Nothing obviously disposable", "未发现明显可清理的内容"), + ("Of scan", "占扫描结果"), + ("Older", "更早"), + ("Open", "打开"), + ("Open Folder…", "打开文件夹…"), + ("Open Privacy Settings", "打开隐私设置"), + ("Open that directory, at any depth", "打开目录,不限层级"), + ("Other", "其他"), + ("Pan the magnified view", "平移放大后的视图"), + ("Partly unreadable", "部分无法读取"), + ( + "Point at a tile or select one with the arrows", + "指向一个区块,或用方向键选择", + ), + ("Power Efficiency: {0}", "能效模式:{0}"), + ( + "Power Efficiency: {0} · {1} of {2} CPUs\n{3}\nUsed from the next scan, and remembered.", + "能效模式:{0} · {1} / {2} 个 CPU\n{3}\n下次扫描生效,并记住此选择。", + ), + ("Preview only · provisional totals", "仅供预览 · 临时统计"), + ("Quit", "退出"), + ("Quit disktree", "退出 disktree"), + ("Read errors", "读取错误"), + ( + "Read-only SSH session. Export the selection; nothing is deleted here. Free space is sampled at scan time.", + "SSH 会话为只读。可导出所选项目,此处不会删除任何内容。可用空间为扫描时的快照。", + ), + ("Reading this computer", "正在读取本机"), + ("Recent directory", "最近读取的目录"), + ("Reclaimable", "可回收"), + ( + "Recoverable from the trash until it is emptied. Uses {0}.", + "清空回收站前可恢复。使用 {0}。", + ), + ( + "Remote identity changed; previous marks were cleared.", + "远程主机身份已改变,先前的标记已清除。", + ), + ("Removing", "正在清理"), + ("Rescan", "重新扫描"), + ("Restart as Administrator", "以管理员身份重启"), + ("Review", "检查清理列表"), + ("Review screen", "清理检查界面"), + ("Review the marked list", "检查已标记的列表"), + ( + "Review {0} marked · frees {1}…", + "检查 {0} 个标记项 · 可释放 {1}…", + ), + ( + "Run as administrator to read the whole drive from its file table: several times faster than this walk.", + "以管理员身份运行可从文件表读取整个驱动器:比逐目录扫描快数倍。", + ), + ("SSH alias or user@host", "SSH 别名或 user@host"), + ("Same as {0} with {1} CPUs", "在 {1} 个 CPU 上与{0}相同"), + ("Save delete script…", "保存删除脚本…"), + ("Save list…", "保存列表…"), + ("Scan", "扫描"), + ("Scan again", "重新扫描"), + ("Scan again from the same root", "重新扫描当前根目录"), + ("Scan another volume", "扫描其他卷"), + ("Scan directory", "扫描目录"), + ("Scan failed", "扫描失败"), + ( + "Scan from here · what is below is reused", + "从此处扫描 · 复用已扫描的下级目录", + ), + ("Scan selected root", "扫描所选根目录"), + ("Scan workers", "扫描线程"), + ("Selection", "选中项"), + ("Services", "服务"), + ("Show All", "显示全部"), + ("Show in Finder", "在访达中显示"), + ("Show it in File Explorer", "在文件资源管理器中显示"), + ("Show it in Finder", "在访达中显示"), + ("Show it in the file manager", "在文件管理器中显示"), + ("Show or hide the selection line", "显示或隐藏选中项面板"), + ("Siblings in {0}", "{0} 中的同级项目"), + ("Six months", "半年内"), + ("Size", "大小"), + ( + "Size, files or age: what areas and colours say", + "切换大小、文件数或时间模式", + ), + ("Source…", "来源…"), + ("Space freed", "释放空间"), + ("Space marks the tile you point at", "按空格标记指向的区块"), + ("Starting remote scanner", "正在启动远程扫描器"), + ("Stop", "停止"), + ("Stop a scan in progress", "停止正在进行的扫描"), + ("Stop indexing", "停止索引"), + ("Synced", "同步文件"), + ( + "The treemap is being re-scanned so the numbers on screen match the disk again.", + "正在重新扫描,以便界面数据与磁盘实际占用保持一致。", + ), + ( + "The whole disk; click any directory above to widen", + "扫描整个磁盘;点击上级目录可扩大扫描范围", + ), + ("This computer", "本机"), + ( + "This frees {0}. Deleted files can’t be recovered; move them to the trash if you might need them again.", + "这将释放 {0}。删除后无法恢复;如果以后可能还需要这些文件,请移至回收站。", + ), + ("This month", "本月"), + ("This week", "本周"), + ("This year", "一年内"), + ("Toolchains", "工具链"), + ("Totals", "汇总"), + ("Unmark", "取消标记"), + ("Unmark {0}", "取消标记 {0}"), + ( + "Up to about 8 workers a scan finishes sooner: a whole drive took a third less time with 8 than with Balanced. Past that it is no faster, but uses over twice the CPU and runs the fans at full speed.", + "扫描线程增加到约 8 个时会缩短耗时:相比均衡模式,8 个线程扫描整个驱动器的耗时减少约三分之一。再增加线程不会更快,但 CPU 消耗会超过两倍,并让风扇全速运行。", + ), + ("Uploading remote scanner", "正在上传远程扫描器"), + ("Volume", "卷"), + ( + "Waiting for the first indexed entries…", + "等待首批索引结果…", + ), + ("Waiting for the scan", "等待扫描"), + ("What happens", "执行方式"), + ( + "Windows kept {0} {1} unreadable. Run as administrator to read them{2}.", + "Windows 不允许读取 {0} {1}。请以管理员身份运行以读取这些项目{2}。", + ), + ("Worth a look", "值得查看"), + ("XDG trash", "XDG 回收站"), + ( + "Zoom toward a directory, then go into it", + "朝目录缩放,继续滚动即可进入", + ), + ( + "a user profile cannot be removed", + "无法删除用户配置文件目录", + ), + ("all keys", "所有快捷键"), + ("asking…", "正在查询…"), + ("back", "返回"), + ("build output", "构建产物"), + ("bytes claimed", "预计释放"), + ("changes unknown", "更改状态未知"), + ("clean", "干净"), + ("continue", "继续"), + ( + "copied a prompt for your agent: {0} {1}, {2}", + "已复制智能体提示词:{0} {1},{2}", + ), + ( + "copied delete script; previews by default, checks host before deletion", + "删除脚本已复制;默认仅预览,删除前会核对主机身份", + ), + ("copy as prompt", "复制为提示词"), + ("copy script", "复制脚本"), + ("could not save {0}: {1}", "无法保存 {0}:{1}"), + ("delete…", "删除…"), + ("depth", "层级"), + ("disktree · Choose a source", "disktree · 选择来源"), + ("enter commits · esc goes back", "enter 执行 · esc 返回"), + ("enter shows only these", "enter 仅显示匹配项"), + ("esc clears", "esc 清除"), + ("failed", "失败"), + ("files", "个文件"), + ("filter", "筛选"), + ( + "it became a mount point since it was marked", + "标记后该项目已变为挂载点", + ), + ("it contains the home directory", "其中包含主目录"), + ("item", "个项目"), + ("items", "个项目"), + ("just now", "刚刚"), + ( + "m trash · p permanent · ! unmark all · s save list · a copy as prompt", + "m 回收站 · p 永久删除 · ! 取消所有标记 · s 保存列表 · a 复制为提示词", + ), + ( + "macOS kept {0} {1} unreadable. Give disktree Full Disk Access, or your terminal if you started it there, then reopen it.", + "macOS 不允许读取 {0} {1}。请授予 disktree“完全磁盘访问权限”(若从终端启动,请授予终端该权限),然后重新打开。", + ), + ("mark", "标记"), + ( + "mark something first: space marks the selected tile", + "请先标记项目:按空格标记选中的区块", + ), + ("mode", "模式"), + ("move", "移动"), + ("move to trash", "移至回收站"), + ("no matches", "无匹配项"), + ("no stash", "无贮藏"), + ("no trash tool found", "未找到回收站工具"), + ("no upstream", "无上游分支"), + ("not counted here: {0}", "未计入此卷:{0}"), + ("not readable", "无法读取"), + ( + "not while restarting as administrator", + "以管理员身份重启时无法执行此操作", + ), + ("nothing here matches {0}", "此处没有与 {0} 匹配的项目"), + ("nothing is marked", "尚未标记任何内容"), + ("nothing to copy", "没有可复制的内容"), + ("nothing to save", "没有可保存的内容"), + ("open", "打开"), + ("outside the scanned root", "位于扫描根目录之外"), + ("package store", "软件包存储"), + ("path", "条路径"), + ("paths", "条路径"), + ("permanent", "永久删除"), + ("progress", "进度"), + ("re-scanning", "正在重新扫描"), + ( + "recoverable until the trash is emptied", + "清空回收站前可恢复", + ), + ("regenerable", "可重新生成"), + ("reinstallable", "可重新安装"), + ("removal finished", "清理已完成"), + ("removed", "已删除"), + ("rescan", "重新扫描"), + ("reset", "重置"), + ("review", "检查"), + ("rm -rf: unrecoverable", "rm -rf:无法恢复"), + ("sandbox layers", "沙箱镜像层"), + ("save list", "保存列表"), + ("save script", "保存脚本"), + ("saved {0} {1} to {2}", "已保存 {0} {1}到 {2}"), + ( + "scan cancelled · {0} entries · r scans again", + "扫描已取消 · {0} 个项目 · r 重新扫描", + ), + ("scan {0} entries{1}", "已扫描 {0} 个项目{1}"), + ("searching…", "正在搜索…"), + ("size", "大小"), + ("snapshots", "快照"), + ("space mark", "空格 标记"), + ("space mark · enter open", "空格 标记 · enter 打开"), + ("still not an administrator: {0}", "仍无管理员权限:{0}"), + ("stop after the current item", "处理完当前项目后停止"), + ("stopping after the current item", "处理完当前项目后停止"), + ("sync history", "同步历史"), + ("temporary", "临时文件"), + ("the Recycle Bin", "系统回收站"), + ("the Trash", "访达回收站"), + ( + "the filesystem root cannot be removed", + "无法删除文件系统根目录", + ), + ("the home directory cannot be removed", "无法删除主目录"), + ("the scanned root cannot be removed", "无法删除扫描根目录"), + ( + "the scanned root cannot be removed; open a directory first", + "无法删除扫描根目录;请先打开一个下级目录", + ), + ("trash", "回收站"), + ("type to filter", "输入名称筛选"), + ("unknown", "未知"), + ("unmark all", "取消所有标记"), + ("up", "上一级"), + ("volume freed", "卷上实际释放"), + ("volumes", "卷"), + ("what could not be removed", "无法删除的项目"), + ("worker", "个线程"), + ("workers", "个线程"), + ("{0} > {1} days", "{0} > {1} 天"), + ("{0} CPUs", "{0} 个 CPU"), + ("{0} Restarting drops the marks.", "{0} 重启将丢失标记。"), + ("{0} available", "{0} 可用"), + ("{0} changed", "{0} 项更改"), + ("{0} could not be placed", "{0} 无法确定所属卷"), + ("{0} day ago", "{0} 天前"), + ("{0} days ago", "{0} 天前"), + ("{0} experiment{1} untouched", "{0} 个未改动的实验目录{1}"), + ("{0} files", "{0} 个文件"), + ( + "{0} files · {1} dirs · {2} direct", + "{0} 个文件 · {1} 个目录 · {2} 个直属文件", + ), + ("{0} free", "{0} 可用"), + ("{0} free of {1}", "可用 {0} / 总计 {1}"), + ( + "{0} free · {1} after removing {2}", + "当前可用 {0} · 删除 {2} 后可用 {1}", + ), + ( + "{0} from the next scan, but it could not be saved: {1}", + "下次扫描使用 {0},但无法保存设置:{1}", + ), + ( + "{0} from the next scan; no settings directory to save it in", + "下次扫描使用 {0};未找到可保存设置的目录", + ), + ( + "{0} from the next scan; r rescans now", + "下次扫描使用 {0};按 r 立即重新扫描", + ), + ( + "{0} goes with the marked {1}; unmark that to keep it", + "{0} 随已标记的 {1} 一同处理;取消父目录标记即可保留", + ), + ("{0} hour ago", "{0} 小时前"), + ("{0} hours ago", "{0} 小时前"), + ("{0} is no longer on disk", "磁盘上已不存在 {0}"), + ("{0} items", "{0} 个项目"), + ("{0} marked · {1} to free", "{0} 个标记项 · 将释放 {1}"), + ("{0} match{1} · {2}", "{0} 个匹配项{1} · {2}"), + ("{0} measured", "已测量 {0}"), + ("{0} minute ago", "{0} 分钟前"), + ("{0} minutes ago", "{0} 分钟前"), + ("{0} month ago", "{0} 个月前"), + ("{0} months ago", "{0} 个月前"), + ( + "{0} more are marked and will be removed too. Unmark them in the treemap.", + "另有 {0} 个标记项也将被删除。可返回矩形树图取消标记。", + ), + ( + "{0} nested · {1} kept back", + "{0} 项随父目录处理 · {1} 项已阻止", + ), + ( + "{0} now covers {1} mark{2} inside it", + "{0} 现在包含其内部的 {1} 个标记项{2}", + ), + ("{0} of {1} done", "已完成 {0} / {1}"), + ("{0} on other volumes", "{0} 位于其他卷"), + ("{0} removed · {1} to free", "已删除 {0} 项 · 将释放 {1}"), + ("{0} stashes", "{0} 个贮藏"), + ("{0} total", "总计 {0}"), + ("{0} unpushed", "{0} 个未推送提交"), + ("{0} used", "已用 {0}"), + ( + "{0} worktree{1} · oldest {2} d", + "{0} 个工作树{1} · 最早修改于 {2} 天前", + ), + ("{0} year ago", "{0} 年前"), + ("{0} years ago", "{0} 年前"), + ("{0} · SSH · read-only", "{0} · SSH · 只读"), + ( + "{0} · read-only · space at scan", + "{0} · 只读 · 扫描时的空间", + ), + ("· {0} files · {1} dirs", "· {0} 个文件 · {1} 个目录"), + ("· {0} unreadable", "· {0} 项无法读取"), + ("→ {0} free", "→ {0} 可用"), +]; diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rs index 904a9319..ea5add2e 100644 --- a/crates/disktree-app/src/main.rs +++ b/crates/disktree-app/src/main.rs @@ -14,6 +14,7 @@ mod app_menu; mod appearance; mod git; +mod i18n; mod marks; mod palette; mod power; @@ -182,6 +183,18 @@ fn run() -> Result<()> { .with_assets(gpui_kit::assets::Assets) .run(move |cx| { gpui_omarchy::init(cx); + let language = i18n::settings_path() + .map_or_else( + || Ok(i18n::Language::default()), + |path| i18n::load(&path), + ) + .unwrap_or_else(|error| { + eprintln!( + "Cannot load interface language: {error}; using English" + ); + i18n::Language::default() + }); + cx.set_global(language); app_menu::install(cx); let home = std::env::home_dir(); let native_look = appearance::follows_system(home.as_deref()); diff --git a/crates/disktree-app/src/power.rs b/crates/disktree-app/src/power.rs index c4a05bd5..a1540cd7 100644 --- a/crates/disktree-app/src/power.rs +++ b/crates/disktree-app/src/power.rs @@ -54,8 +54,13 @@ impl PowerEfficiency { } } - pub fn label(self, cpus: usize) -> String { - format!("{} ({})", self.name(), workers(self.threads(cpus))) + /// The localized preset name and effective worker count. + pub fn label(self, cpus: usize, language: crate::i18n::Language) -> String { + format!( + "{} ({})", + language.text(self.name()), + workers(self.threads(cpus), language) + ) } /// A preset that would run no more workers than the one below it, on a @@ -89,9 +94,10 @@ impl PowerEfficiency { } } -pub fn workers(count: usize) -> String { +/// The worker count in the interface language. +pub fn workers(count: usize, language: crate::i18n::Language) -> String { let unit = if count == 1 { "worker" } else { "workers" }; - format!("{count} {unit}") + format!("{count} {}", language.text(unit)) } pub fn cpu_threads() -> usize { @@ -157,7 +163,8 @@ mod tests { } assert_eq!(PowerEfficiency::Balanced.threads(3), 3); assert_eq!( - PowerEfficiency::DrainMyBattery.label(18), + PowerEfficiency::DrainMyBattery + .label(18, crate::i18n::Language::English), "Drain My Battery (18 workers)" ); } diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index efb9730a..aaef5bbb 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -4,6 +4,8 @@ //! decisions — what is selected, what a mark means, what a key does, when to //! re-scan — live here so they can be reasoned about in one place. +use crate::i18n::t; + use std::cell::Cell; use std::path::{Path, PathBuf}; use std::rc::Rc; @@ -344,6 +346,12 @@ pub struct Disktree { /// The pointer is on the menu's button. A press there is the button's /// to toggle, not a press outside the menu that closes it first. pub power_hover: bool, + /// The language chooser overlays any screen without changing scan state. + pub language_open: bool, + /// Stable tab stops for both language choices and Cancel. + pub language_focus: [FocusHandle; crate::i18n::Language::ALL.len() + 1], + /// Separate from scan roots and the power setting. + pub language_settings_path: Option, pub cpu_threads: usize, pub tree: Option>, pub scan: Option, @@ -539,6 +547,9 @@ impl Disktree { power_settings_path: crate::power::settings_path(), power_menu: None, power_hover: false, + language_open: false, + language_focus: std::array::from_fn(|_| cx.focus_handle()), + language_settings_path: crate::i18n::settings_path(), cpu_threads: crate::power::cpu_threads(), tree: None, scan: None, @@ -867,7 +878,7 @@ impl Disktree { let value = self.volumes_source.clone().unwrap_or_default(); let host = cx.new(|cx| { InputState::new(window, cx) - .placeholder("SSH alias or user@host") + .placeholder(t!(cx, "SSH alias or user@host")) .default_value(value) }); cx.subscribe(&host, |this, _, event, cx| { @@ -891,6 +902,15 @@ impl Disktree { .detach(); self.picker_path = Some(path); } + let placeholder = t!(cx, "SSH alias or user@host"); + if let Some(host) = &self.picker_host + && host.read(cx).presentation().placeholder().as_ref() + != placeholder + { + host.update(cx, |host, cx| { + host.set_placeholder(placeholder, window, cx); + }); + } } pub fn picker_source_matches(&self, cx: &Context<'_, Self>) -> bool { @@ -1129,6 +1149,73 @@ impl Disktree { cx.notify(); } + /// Open a language chooser without changing the scan, marks or source. + pub fn open_language(&mut self, cx: &mut Context<'_, Self>) { + if self.confirm_open { + return; + } + self.language_open = true; + self.power_menu = None; + self.crumb_menu = None; + self.focus_request = Some(FocusTarget::Dialog); + cx.notify(); + } + + /// Return focus to the source chooser when it is still open underneath. + pub fn close_language(&mut self, cx: &mut Context<'_, Self>) { + self.language_open = false; + self.focus_request = Some(if self.volumes_open { + FocusTarget::Dialog + } else { + FocusTarget::Root + }); + cx.notify(); + } + + /// Keep Tab and Shift-Tab inside the chooser. + pub fn move_language_focus( + &self, + backwards: bool, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + let count = self.language_focus.len(); + let current = self + .language_focus + .iter() + .position(|focus| focus.is_focused(window)); + let next = current + .map_or(if backwards { count - 1 } else { 0 }, |current| { + (current + if backwards { count - 1 } else { 1 }) % count + }); + window.focus(&self.language_focus[next], cx); + cx.notify(); + } + + /// Apply immediately and save independently of the scan and power policy. + pub fn set_language( + &mut self, + language: crate::i18n::Language, + cx: &mut Context<'_, Self>, + ) { + cx.set_global(language); + crate::app_menu::update_language(cx); + self.notice = Some(match self.language_settings_path.as_deref() { + Some(path) => match crate::i18n::save(path, language) { + Ok(()) => (t!(cx, "Language saved").into(), Status::Success), + Err(error) => ( + t!(cx, "Language changed, but could not be saved: {0}", error), + Status::Warning, + ), + }, + None => ( + t!(cx, "Language changed for this session; no settings directory is available").into(), + Status::Warning, + ), + }); + self.close_language(cx); + } + /// Changing resource policy leaves the current scan and result intact; /// rescan, navigation to a new root and restart use the new fixed budget. pub fn set_power_efficiency( @@ -1145,25 +1232,28 @@ impl Disktree { } self.options.threads = preset.policy(self.cpu_threads); self.power_choice = Some(preset); - let label = preset.label(self.cpu_threads); + let label = preset.label(self.cpu_threads, crate::i18n::language(cx)); self.notice = Some(match self.power_settings_path.as_deref() { Some(path) => match crate::power::save(path, preset) { Ok(()) => ( - format!("{label} from the next scan; r rescans now"), + t!(cx, "{0} from the next scan; r rescans now", label), Status::Success, ), Err(error) => ( - format!( - "{label} from the next scan, but it could not be \ - saved: {error}" + t!( + cx, + "{0} from the next scan, but it could not be saved: {1}", + label, + error ), Status::Warning, ), }, None => ( - format!( - "{label} from the next scan; no settings directory to \ - save it in" + t!( + cx, + "{0} from the next scan; no settings directory to save it in", + label ), Status::Warning, ), @@ -1308,16 +1398,19 @@ impl Disktree { .detach(); } + /// Adopt the scan identity, clearing marks that belonged to another host. pub(crate) fn update_remote_identity( &mut self, identity: Option, + cx: &gpui_kit::App, ) { // A stable SSH alias can be repointed to a different machine. // Old marks must not acquire that machine's freshly captured guard. if self.remote_identity != identity && !self.marks.is_empty() { self.marks.clear(); self.notice = Some(( - "Remote identity changed; previous marks were cleared.".into(), + t!(cx, "Remote identity changed; previous marks were cleared.") + .into(), Status::Warning, )); } @@ -1354,7 +1447,7 @@ impl Disktree { self.disk_root = snapshot.header.disk_root; self.space = snapshot.header.space; self.remote_platform = snapshot.header.platform; - self.update_remote_identity(snapshot.header.identity); + self.update_remote_identity(snapshot.header.identity, cx); self.device = self.remote.as_ref().map(|host| { format!("{host} · read-only · space at scan") }); @@ -2088,8 +2181,11 @@ impl Disktree { }; if crumbs.is_empty() { self.notice = Some(( - "the scanned root cannot be removed; open a directory first" - .into(), + t!( + cx, + "the scanned root cannot be removed; open a directory first" + ) + .into(), Status::Warning, )); cx.notify(); @@ -2117,8 +2213,9 @@ impl Disktree { && let Some(ancestor) = self.marked_ancestor(&target.path) { self.notice = Some(( - format!( - "{} goes with the marked {}; unmark that to keep it", + t!( + cx, + "{0} goes with the marked {1}; unmark that to keep it", display_path(&target.path, self.home.as_deref()), display_path(&ancestor, self.home.as_deref()) ), @@ -2144,11 +2241,19 @@ impl Disktree { } if !inside.is_empty() { self.notice = Some(( - format!( - "{} now covers {} mark{} inside it", + t!( + cx, + "{0} now covers {1} mark{2} inside it", display_path(&path, self.home.as_deref()), inside.len(), - if inside.len() == 1 { "" } else { "s" } + if crate::i18n::language(cx) + == crate::i18n::Language::English + && inside.len() != 1 + { + "s" + } else { + "" + } ), Status::Neutral, )); @@ -2220,7 +2325,7 @@ impl Disktree { /// Runs once per render, before the paint callbacks: painting then only has /// to draw, and the marked/hidden/selected state of every tile is decided /// here, where the tree and the marks are both at hand. - pub fn prepare(&mut self) -> Mosaic { + pub fn prepare(&mut self, cx: &gpui_kit::App) -> Mosaic { let metric = self.options.metric; let view = self.view; let hovered = self.hovered.clone(); @@ -2317,7 +2422,7 @@ impl Disktree { }); } TileKind::Others { count, .. } => labels.push(Label { - text: format!("+{count} more"), + text: t!(cx, "+{0} more", count), rect: self.animated_rect(tile.rect), header: None, depth: tile.depth, @@ -2630,7 +2735,8 @@ impl Disktree { } let plan = self.plan(); if plan.is_empty() { - self.notice = Some(("nothing is marked".into(), Status::Warning)); + self.notice = + Some((t!(cx, "nothing is marked").into(), Status::Warning)); cx.notify(); return; } @@ -2638,7 +2744,7 @@ impl Disktree { // would stop a permanent delete halfway. if self.restarting { self.notice = Some(( - "not while restarting as administrator".into(), + t!(cx, "not while restarting as administrator").into(), Status::Warning, )); cx.notify(); @@ -2786,7 +2892,7 @@ impl Disktree { }; if matches.count == 0 { self.notice = Some(( - format!("nothing here matches {}", matches.needle), + t!(cx, "nothing here matches {0}", matches.needle), Status::Warning, )); cx.notify(); @@ -2855,7 +2961,7 @@ impl Disktree { files: false, directories: true, multiple: false, - prompt: Some("Scan".into()), + prompt: Some(t!(cx, "Scan").into()), }); cx.spawn(async move |this, cx| { let Ok(Ok(Some(paths))) = chosen.await else { @@ -2891,7 +2997,8 @@ impl Disktree { fn save_export(&mut self, script: bool, cx: &mut Context<'_, Self>) { let plan = self.plan(); if plan.is_empty() { - self.notice = Some(("nothing to save".into(), Status::Warning)); + self.notice = + Some((t!(cx, "nothing to save").into(), Status::Warning)); cx.notify(); return; } @@ -2913,21 +3020,33 @@ impl Disktree { let Ok(Ok(Some(path))) = chosen.await else { return; }; - let notice = match std::fs::write(&path, list) { - Ok(()) => ( - format!( - "saved {count} {} to {}", - if count == 1 { "path" } else { "paths" }, - path.display() - ), - Status::Success, - ), - Err(error) => ( - format!("could not save {}: {error}", path.display()), - Status::Error, - ), - }; + let outcome = std::fs::write(&path, list); let _ = this.update(cx, |this, cx| { + let notice = match outcome { + Ok(()) => ( + t!( + cx, + "saved {0} {1} to {2}", + count, + if count == 1 { + t!(cx, "path") + } else { + t!(cx, "paths") + }, + path.display() + ), + Status::Success, + ), + Err(error) => ( + t!( + cx, + "could not save {0}: {1}", + path.display(), + error + ), + Status::Error, + ), + }; this.notice = Some(notice); cx.notify(); }); @@ -2952,12 +3071,13 @@ impl Disktree { pub fn copy_delete_script(&mut self, cx: &mut Context<'_, Self>) { let plan = self.plan(); if plan.is_empty() { - self.notice = Some(("nothing to copy".into(), Status::Warning)); + self.notice = + Some((t!(cx, "nothing to copy").into(), Status::Warning)); } else { let script = self.delete_script(&plan.targets); cx.write_to_clipboard(gpui_kit::ClipboardItem::new_string(script)); self.notice = Some(( - "copied delete script; previews by default, checks host before deletion".into(), + t!(cx, "copied delete script; previews by default, checks host before deletion").into(), Status::Success, )); } @@ -2969,7 +3089,8 @@ impl Disktree { pub fn copy_agent_prompt(&mut self, cx: &mut Context<'_, Self>) { let plan = self.plan(); if plan.is_empty() { - self.notice = Some(("nothing to copy".into(), Status::Warning)); + self.notice = + Some((t!(cx, "nothing to copy").into(), Status::Warning)); cx.notify(); return; } @@ -3000,9 +3121,15 @@ impl Disktree { cx.write_to_clipboard(gpui_kit::ClipboardItem::new_string(prompt)); let count = plan.targets.len(); self.notice = Some(( - format!( - "copied a prompt for your agent: {count} {}, {}", - if count == 1 { "path" } else { "paths" }, + t!( + cx, + "copied a prompt for your agent: {0} {1}, {2}", + count, + if count == 1 { + t!(cx, "path") + } else { + t!(cx, "paths") + }, disktree_core::size::human_bytes(plan.bytes()) ), Status::Success, @@ -3023,8 +3150,9 @@ impl Disktree { // GPUI's reveal cannot report failure, so check what it can't. if std::fs::symlink_metadata(&path).is_err() { self.notice = Some(( - format!( - "{} is no longer on disk", + t!( + cx, + "{0} is no longer on disk", crate::marks::display_path(&path, self.home.as_deref()) ), Status::Warning, @@ -3053,6 +3181,18 @@ impl Disktree { return; } + if key == "f2" && !control && !alt { + self.open_language(cx); + return; + } + // The dialog owns its buttons and shortcuts, including over a picker. + if self.language_open { + if key == "escape" { + self.close_language(cx); + } + return; + } + // The volume picker owns its keys while open: arrows move, Enter // picks, Escape closes, and nothing behind it acts. if self.volumes_open { @@ -3135,7 +3275,7 @@ impl Disktree { { run.cancel(); self.notice = Some(( - "stopping after the current item".into(), + t!(cx, "stopping after the current item").into(), Status::Warning, )); cx.notify(); @@ -3212,7 +3352,7 @@ impl Disktree { "c" if !control => { if self.marks.is_empty() { self.notice = Some(( - "mark something first: space marks the selected tile" + t!(cx, "mark something first: space marks the selected tile") .into(), Status::Warning, )); @@ -3606,7 +3746,7 @@ impl Disktree { Err(error) => { this.restarting = false; this.notice = Some(( - format!("still not an administrator: {error}"), + t!(cx, "still not an administrator: {0}", error), Status::Warning, )); cx.notify(); @@ -3718,12 +3858,12 @@ impl Render for Disktree { // The titlebar names the directory on screen, however it got there: // a key, a click, a rescan or a folder chosen from the menu. let title = if self.awaiting_root { - "disktree · Choose a source".into() + t!(cx, "disktree · Choose a source").into() } else { format!( "disktree{} · {}", self.remote.as_ref().map_or_else(String::new, |host| { - format!(" · {host} · read-only") + t!(cx, " · {0} · read-only", host) }), crate::marks::display_path( &self.current_path(), diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs index 0520e4cb..e04dd39f 100644 --- a/crates/disktree-app/src/tests.rs +++ b/crates/disktree-app/src/tests.rs @@ -76,6 +76,118 @@ fn press(cx: &mut Window, keys: &str) { draw(cx); } +#[gpui_kit::test] +fn language_switch_saves_and_keeps_the_scan_and_marks(cx: &mut TestAppContext) { + use crate::i18n::{self, Language}; + cx.update(gpui_omarchy::init); + let temp = fixture(); + let config = tempfile::tempdir().expect("config"); + let path = config.path().join("language"); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(900.), px(600.))); + update(&view, cx, |app, cx| { + app.language_settings_path = Some(path.clone()); + let junk = app + .crumbs_for_path(&temp.path().join("junk")) + .expect("junk"); + app.toggle_mark(&junk, cx); + }); + let epoch = read(&view, cx, |app| app.scan_epoch); + let root = read(&view, cx, |app| app.root_path.clone()); + press(cx, "f2"); + press(cx, "tab"); + press(cx, "enter"); + assert!(!read(&view, cx, |app| app.language_open)); + assert_eq!(i18n::load(&path).expect("keyboard save"), Language::English); + press(cx, "f2"); + assert!(read(&view, cx, |app| app.language_open)); + let chinese = cx.debug_bounds("zh-CN").expect("Chinese choice"); + cx.simulate_click(chinese.center(), gpui_kit::Modifiers::none()); + draw(cx); + let language = cx.debug_bounds("language").expect("language control"); + assert!(language.left() >= px(0.) && language.right() <= px(900.)); + let power = cx.debug_bounds("power-efficiency").expect("power control"); + assert!(power.left() >= px(0.) && power.right() <= px(900.)); + assert_eq!( + i18n::load(&path).expect("saved"), + Language::SimplifiedChinese + ); + update(&view, cx, |app, cx| { + assert_eq!(i18n::text(cx, "Delete permanently"), "永久删除"); + assert_eq!(app.scan_epoch, epoch); + assert_eq!(app.root_path, root); + assert_eq!(app.marks.len(), 1); + assert!(app.tree.is_some()); + assert!(!app.language_open); + }); + press(cx, "f2"); + press(cx, "tab"); + press(cx, "tab"); + press(cx, "enter"); + assert!(!read(&view, cx, |app| app.language_open)); + assert_eq!( + i18n::load(&path).expect("keyboard Chinese"), + Language::SimplifiedChinese + ); + press(cx, "f2"); + press(cx, "shift-tab"); + press(cx, "enter"); + assert!(!read(&view, cx, |app| app.language_open)); + assert_eq!( + i18n::load(&path).expect("cancel keeps choice"), + Language::SimplifiedChinese + ); + // Draw the help, review and permanent-deletion dialog in Chinese. + press(cx, "?"); + press(cx, "escape"); + press(cx, "c"); + update(&view, cx, |app, _| { + app.removal_mode = RemovalMode::Permanent; + }); + press(cx, "enter"); + assert!(read(&view, cx, |app| app.confirm_open)); + press(cx, "f2"); + assert!(!read(&view, cx, |app| app.language_open)); + press(cx, "escape"); + press(cx, "f2"); + let english = cx.debug_bounds("en").expect("English choice"); + cx.simulate_click(english.center(), gpui_kit::Modifiers::none()); + draw(cx); + assert_eq!(i18n::load(&path).expect("saved"), Language::English); + assert!(temp.path().join("junk/blob.bin").exists()); +} + +#[gpui_kit::test] +fn language_dialog_returns_to_picker_and_reports_save_failures( + cx: &mut TestAppContext, +) { + use crate::i18n::Language; + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.open_volumes(cx); + app.language_settings_path = Some(temp.path().to_owned()); + }); + draw(cx); + press(cx, "f2"); + assert!(cx.debug_bounds("zh-CN").is_some()); + press(cx, "escape"); + assert!(!read(&view, cx, |app| app.language_open)); + assert!(read(&view, cx, |app| app.volumes_open)); + assert!(cx.debug_bounds("source-picker").is_some()); + update(&view, cx, |app, cx| { + app.set_language(Language::SimplifiedChinese, cx); + }); + assert!(read(&view, cx, |app| app.notice.as_ref().is_some_and( + |(message, status)| { + message.contains("无法保存") + && *status == gpui_omarchy::Status::Warning + } + ))); + draw(cx); +} + fn update( view: &Entity, cx: &mut Window, @@ -481,22 +593,23 @@ fn repointing_an_ssh_alias_never_reuses_old_machine_marks( machine_id: Some("machine-a".into()), }; app.remote = Some("stable-alias".into()); - app.update_remote_identity(Some(old.clone())); + app.update_remote_identity(Some(old.clone()), cx); let crumbs = app.crumbs_for_path(&temp.path().join("junk")).unwrap(); app.select(Some(crumbs), cx); app.toggle_mark_selected(cx); - app.update_remote_identity(Some(old.clone())); + app.update_remote_identity(Some(old.clone()), cx); assert!(!app.marks.is_empty(), "same machine keeps its marks"); - app.update_remote_identity(Some( - disktree_core::identity::HostIdentity { + app.update_remote_identity( + Some(disktree_core::identity::HostIdentity { hostname: old.hostname, machine_id: Some("machine-b".into()), - }, - )); + }), + cx, + ); assert!(app.marks.is_empty(), "same alias is not proof of identity"); app.toggle_mark_selected(cx); assert!(!app.marks.is_empty()); - app.update_remote_identity(None); + app.update_remote_identity(None, cx); assert!(app.marks.is_empty(), "lost identity also fails closed"); }); } @@ -750,7 +863,7 @@ fn a_parents_name_gets_its_own_band_above_its_children( draw(cx); let (band, lowest_child_top, bands_in_mosaic) = - update(&view, cx, |app, _| { + update(&view, cx, |app, cx| { let tiles = app.layout().map(<[Tile]>::to_vec).unwrap_or_default(); let parent = tiles .iter() @@ -766,7 +879,7 @@ fn a_parents_name_gets_its_own_band_above_its_children( }) .map(|tile| tile.rect.y) .fold(f32::INFINITY, f32::min); - let mosaic = app.prepare(); + let mosaic = app.prepare(cx); let bands_in_mosaic = mosaic .labels .iter() @@ -1554,14 +1667,14 @@ fn after_descending_every_tile_is_inside_the_directory_drawn( assert_eq!(read(&view, cx, |app| app.crumbs.clone()), junk); draw(cx); - let (paths, labels) = update(&view, cx, |app, _| { + let (paths, labels) = update(&view, cx, |app, cx| { let tiles = app.layout().map(<[Tile]>::to_vec).unwrap_or_default(); let paths: Vec<_> = tiles .iter() .filter_map(|tile| app.path_at(tile.crumbs())) .collect(); let labels: Vec = app - .prepare() + .prepare(cx) .labels .into_iter() .map(|label| label.text) @@ -1593,8 +1706,8 @@ fn after_descending_every_tile_is_inside_the_directory_drawn( assert_eq!(marked[0].bytes, 200_000); // And the mark is drawn on the right tile: its crumbs resolve here. - let hatched = update(&view, cx, |app, _| { - app.prepare() + let hatched = update(&view, cx, |app, cx| { + app.prepare(cx) .tiles .iter() .filter(|tile| tile.marked) @@ -1896,7 +2009,7 @@ fn marking_a_directory_marks_everything_inside_it(cx: &mut TestAppContext) { // Every tile inside it is drawn marked: the ones below the mark are // "covered", which paints the same fill and label. - let mosaic = update(&view, cx, |app, _| app.prepare()); + let mosaic = update(&view, cx, |app, cx| app.prepare(cx)); let (inside, covered) = update(&view, cx, |app, _| { let tiles = app.layout().map(<[Tile]>::to_vec).unwrap_or_default(); let inside: Vec = tiles diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index 32aedf5f..6c8d7c12 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -4,6 +4,8 @@ //! always exactly what the state says — there is no second copy of anything to //! keep in sync. +use crate::i18n::t; + use disktree_core::classify::Category; use disktree_core::insights::{Candidate, Finding, STALE_DAYS}; use disktree_core::removal::{Plan, RemovalMode, Target}; @@ -92,15 +94,23 @@ pub fn root( } }, )) + .on_action(cx.listener(|this, _: &crate::app_menu::ChooseLanguage, _, cx| { + this.open_language(cx); + })) .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| { if this.zoom_interface(event, window) { cx.notify(); return; } + if this.language_open && event.keystroke.key == "tab" { + this.move_language_focus(event.keystroke.modifiers.shift, window, cx); + cx.stop_propagation(); + return; + } if this.volumes_open { let editing = [&this.picker_host, &this.picker_path].into_iter() .flatten().any(|input| input.read(cx).focus_handle(cx).is_focused(window)); - if editing && event.keystroke.key != "escape" { return; } + if editing && !matches!(event.keystroke.key.as_str(), "escape" | "f2") { return; } } this.on_key_down(event, cx); this.apply_focus(window, cx); @@ -120,15 +130,111 @@ pub fn root( if app.show_help { root = root.child(help_overlay(app, cx)); } - if app.volumes_open { + if app.volumes_open && !app.language_open { root = root.child(volumes_dialog(app, window, cx)); } if app.confirm_open { root = root.child(delete_dialog(app, cx)); } + if app.language_open { + root = root.child(language_dialog(app, cx)); + } root } +/// A bilingual label remains recognizable in either supported language. +fn language_button(cx: &Context<'_, Disktree>) -> impl IntoElement { + with_tooltip( + button("language", "Language / 语言", ButtonVariant::Secondary, cx) + .debug_selector(|| "language".into()) + .on_click(cx.listener(|this, _, window, cx| { + this.open_language(cx); + this.apply_focus(window, cx); + })), + t!(cx, "Choose interface language · F2"), + ) +} + +/// Stable focus handles let the modal confirm the button reached with Tab. +fn language_dialog( + app: &Disktree, + cx: &mut Context<'_, Disktree>, +) -> impl IntoElement { + let mut choices = div().flex().flex_col().gap(space::SM); + for (index, language) in crate::i18n::Language::ALL.into_iter().enumerate() + { + choices = choices.child( + button( + language.key(), + language.name(), + ButtonVariant::Secondary, + cx, + ) + .track_focus(&app.language_focus[index]) + .debug_selector(move || language.key().into()) + .selected(crate::i18n::language(cx) == language) + .on_click(cx.listener(move |this, _, window, cx| { + this.set_language(language, cx); + this.apply_focus(window, cx); + })), + ); + } + let popup = dialog_popup(cx) + .child(dialog_title("Language / 语言", cx)) + .child(choices) + .child( + dialog_button( + "language-cancel", + t!(cx, "Cancel"), + ButtonVariant::Secondary, + cx, + ) + .track_focus(&app.language_focus[crate::i18n::Language::ALL.len()]) + .on_click(cx.listener(|this, _, window, cx| { + this.close_language(cx); + this.apply_focus(window, cx); + })), + ); + let entity = cx.entity().downgrade(); + let accept = entity.clone(); + let outside = entity.clone(); + let popup = centred_popup(popup, move |_, window, cx| { + let _ = outside.update(cx, |this, cx| { + this.close_language(cx); + this.apply_focus(window, cx); + }); + }); + alert_dialog(&app.confirm_focus, cx) + .open(true) + .on_ok(move |_, window, cx| { + let _ = accept.update(cx, |this, cx| { + if let Some(index) = this + .language_focus + .iter() + .position(|focus| focus.is_focused(window)) + { + if let Some(language) = + crate::i18n::Language::ALL.get(index) + { + this.set_language(*language, cx); + } else { + this.close_language(cx); + } + this.apply_focus(window, cx); + } + }); + false + }) + .on_cancel(move |_, window, cx| { + let _ = entity.update(cx, |this, cx| { + this.close_language(cx); + this.apply_focus(window, cx); + }); + false + }) + .popup(popup) +} + /// Discovery is lightweight; a separate, explicit action starts the walk. fn volumes_dialog( app: &Disktree, @@ -139,8 +245,8 @@ fn volumes_dialog( let cancel = cx.entity().downgrade(); let source_ready = app.picker_source_matches(cx); let source = app.volumes_source.as_ref().map_or_else( - || "This computer".to_owned(), - |host| format!("{host} · SSH · read-only"), + || t!(cx, "This computer").to_owned(), + |host| t!(cx, "{0} · SSH · read-only", host), ); let mut rows = div() .id("volume-rows") @@ -152,14 +258,14 @@ fn volumes_dialog( .overflow_y_scroll(); if app.volumes_loading { rows = rows.child(dialog_description( - "Listing mounts, not scanning files…", + t!(cx, "Listing mounts, not scanning files…"), cx, )); } else if let Some(error) = &app.volumes_error { rows = rows.child(div().text_color(theme.danger).child(error.clone())); } else if app.volumes.is_empty() { rows = rows.child(dialog_description( - "No mounts listed. Enter a directory below.", + t!(cx, "No mounts listed. Enter a directory below."), cx, )); } @@ -168,7 +274,10 @@ fn volumes_dialog( let label = format!( "{} · {}", volume.point.display(), - volume.device.as_deref().unwrap_or("Mounted volume") + volume + .device + .as_deref() + .unwrap_or_else(|| t!(cx, "Mounted volume")) ); rows = rows.child( div() @@ -201,34 +310,37 @@ fn volumes_dialog( .as_ref() .expect("picker prepared before rendering"); let popup = dialog_popup(cx).w_full() - .child(dialog_title("Choose what to scan", cx)) + .child(div().flex().items_center().justify_between() + .child(dialog_title(t!(cx, "Choose what to scan"), cx)) + .child(language_button(cx))) .child(dialog_description( - "Connect, then select a mount or directory. No new scan starts until you choose Scan.", + t!(cx, "Connect, then select a mount or directory. No new scan starts until you choose Scan."), cx)) .child(div().flex().flex_row().gap(space::SM) - .child(button("source-local", "This computer", ButtonVariant::Secondary, cx) + .child(button("source-local", t!(cx, "This computer"), ButtonVariant::Secondary, cx) .on_click(cx.listener(|this, _, window, cx| this.choose_local_source(window, cx)))) .child(gpui_omarchy::input("source-host", host, window, cx) .debug_selector(|| "source-host".into()).flex_1()) - .child(button("source-connect", "Connect SSH", ButtonVariant::Secondary, cx) + .child(button("source-connect", t!(cx, "Connect SSH"), ButtonVariant::Secondary, cx) .on_click(cx.listener(|this, _, _, cx| this.connect_picker(cx))))) .child(div().text_color(theme.bright).child(source)) + .children(notice_line(app, &theme, cx)) .child(rows) .child(dialog_description( - "Nested mounts and symlinks are not traversed. Space is measured only after selection.", cx)) + t!(cx, "Nested mounts and symlinks are not traversed. Space is measured only after selection."), cx)) .child(div().flex().flex_row().gap(space::SM) .child(gpui_omarchy::input("source-path", path, window, cx) .debug_selector(|| "source-path".into()).flex_1()) - .child(button("source-scan-path", "Scan directory", ButtonVariant::Secondary, cx) + .child(button("source-scan-path", t!(cx, "Scan directory"), ButtonVariant::Secondary, cx) .disabled(!source_ready || app.volumes_loading || app.volumes_error.is_some()) .on_click(cx.listener(|this, _, _, cx| this.choose_picker_path(cx))))) - .children(app.picker_error.as_ref().map(|error| div().text_color(theme.danger).child(error.clone()))) + .children(app.picker_error.as_ref().map(|error| div().text_color(theme.danger).child(t!(cx, error).to_owned()))) .child(div().flex().flex_row().justify_end().gap(space::SM) - .child(dialog_button("source-cancel", "Cancel", ButtonVariant::Secondary, cx) + .child(dialog_button("source-cancel", t!(cx, "Cancel"), ButtonVariant::Secondary, cx) .on_click(cx.listener(|this, _, window, cx| { this.close_volumes(cx); this.apply_focus(window, cx); }))) - .child(dialog_button("source-scan", "Scan selected root", ButtonVariant::Primary, cx) + .child(dialog_button("source-scan", t!(cx, "Scan selected root"), ButtonVariant::Primary, cx) .disabled(!source_ready || app.volumes_loading || app.volumes_error.is_some() || app.volumes.is_empty()) .on_click(cx.listener(|this, _, window, cx| { this.choose_volume(cx); this.apply_focus(window, cx); @@ -339,14 +451,12 @@ fn delete_dialog( ) -> impl IntoElement { let plan = app.plan(); let title = match plan.targets.as_slice() { - [only] => format!( - "Delete \u{201c}{}\u{201d} permanently?", - short_name(&only.path) - ), - targets => format!("Delete {} items permanently?", targets.len()), + [only] => t!(cx, "Delete “{0}” permanently?", short_name(&only.path)), + targets => t!(cx, "Delete {0} items permanently?", targets.len()), }; - let body = format!( - "This frees {}. Deleted files can\u{2019}t be recovered; move them to the trash if you might need them again.", + let body = t!( + cx, + "This frees {0}. Deleted files can’t be recovered; move them to the trash if you might need them again.", human_bytes(plan.bytes()) ); let confirm = cx.entity().downgrade(); @@ -359,7 +469,7 @@ fn delete_dialog( .child( dialog_button( "delete-cancel", - "Cancel", + t!(cx, "Cancel"), ButtonVariant::Secondary, cx, ) @@ -371,7 +481,7 @@ fn delete_dialog( .child( dialog_button( "delete-confirm", - "Delete", + t!(cx, "Delete"), ButtonVariant::Danger, cx, ) @@ -435,15 +545,16 @@ fn explore( .child( div() .text_size(text::HEADING) - .child("Choose a source. Then choose a root."), + .child(t!(cx, "Choose a source. Then choose a root.")), ) - .child(div().text_color(theme.secondary).child( - "Local or SSH · one mount at a time · no background scan", - )) + .child(div().text_color(theme.secondary).child(t!( + cx, + "Local or SSH · one mount at a time · no background scan" + ))) .child( button( "choose-source", - "Choose source…", + t!(cx, "Choose source…"), ButtonVariant::Primary, cx, ) @@ -453,9 +564,11 @@ fn explore( this.apply_focus(window, cx); }, )), - ); + ) + .child(language_button(cx)) + .children(notice_line(app, &theme, cx)); } - let mosaic: Mosaic = app.prepare(); + let mosaic: Mosaic = app.prepare(cx); let width_rems = window.viewport_size().width.as_f32() / app.rem; // The panel is where the selection, the marks and the disk live; it // only gives way when the mosaic would be too narrow to read. @@ -592,12 +705,13 @@ fn top_bar( this.open_volumes(cx); this.apply_focus(window, cx); })), - "Choose local or SSH source · v", + t!(cx, "Choose local or SSH source · v"), )) // Where you are is navigation, and it belongs to the whole window. .child(trail(app, theme, cx)) .child(div().flex_1()) .child(view_settings(app, window, cx)) + .child(language_button(cx)) } /// The trail, from `/`. Above the scanned root, a crumb widens the scan; @@ -652,7 +766,7 @@ fn trail(app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>) -> Div { .on_click(cx.listener(move |this, _, _, cx| { this.widen_to(path.clone(), cx); })), - "Scan from here · what is below is reused", + t!(cx, "Scan from here · what is below is reused"), ) .into_any_element() } @@ -802,7 +916,7 @@ fn sibling_menu( .py(space::XS) .text_size(text::CAPTION) .text_color(theme.secondary.opacity(0.8)) - .child(format!("Siblings in {parent_name}")), + .child(t!(cx, "Siblings in {0}", parent_name)), ); for (row_index, row) in rows.into_iter().enumerate() { let current = @@ -871,7 +985,7 @@ fn sibling_menu( .py(space::XS) .text_size(text::CAPTION) .text_color(theme.secondary.opacity(0.7)) - .child(format!("+{more} smaller")), + .child(t!(cx, "+{0} smaller", more)), ); } panel @@ -934,9 +1048,9 @@ fn view_settings( button_group( "mode", vec![ - ChoiceItem::new("size", "Size"), - ChoiceItem::new("files", "Files"), - ChoiceItem::new("age", "Age"), + ChoiceItem::new("size", t!(cx, "Size")), + ChoiceItem::new("files", t!(cx, "Files")), + ChoiceItem::new("age", t!(cx, "Age")), ], Some(app.mode_index()), move |index, window, cx| { @@ -964,7 +1078,7 @@ fn view_settings( let focus = focus.clone(); checkbox( "hidden", - "Hidden files", + t!(cx, "Hidden files"), check(app.options.include_hidden), cx, ) @@ -980,7 +1094,7 @@ fn view_settings( let apparent = { checkbox( "apparent", - "Apparent size", + t!(cx, "Apparent size"), check(app.options.apparent_size), cx, ) @@ -1099,11 +1213,11 @@ fn view_settings( .px(space::SM) .text_size(text::BODY) .text_color(theme.foreground) - .child(format!("Depth {depth}")), + .child(t!(cx, "Depth {0}", depth)), ) .child(stepper("depth-less", "\u{2212}", -1, cx)) .child(stepper("depth-more", "+", 1, cx)), - "Levels drawn at once \u{00b7} [ and ]", + t!(cx, "Levels drawn at once \u{00b7} [ and ]"), ); div() @@ -1144,7 +1258,7 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { let theme = cx.omarchy().clone(); let cpus = app.cpu_threads; let threads = app.options.threads.max_threads.min(cpus); - let name = app.power_choice.map_or("Custom", PowerEfficiency::name); + let name = t!(cx, app.power_choice.map_or("Custom", PowerEfficiency::name)); let open = app.power_menu.is_some(); let trigger = div() .id("power-efficiency") @@ -1160,7 +1274,7 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { })) .child( button("power-toggle", "", ButtonVariant::Secondary, cx) - .accessibility_label(format!("Power Efficiency: {name}")) + .accessibility_label(t!(cx, "Power Efficiency: {0}", name)) .selected(open) .tab_stop(false) .child(widgets::signal( @@ -1184,10 +1298,13 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { } else { with_tooltip( trigger, - format!( - "Power Efficiency: {name} \u{00b7} {} of {cpus} CPUs\n\ - {POWER_TRADEOFF}\nUsed from the next scan, and remembered.", - power::workers(threads) + t!( + cx, + "Power Efficiency: {0} · {1} of {2} CPUs\n{3}\nUsed from the next scan, and remembered.", + name, + power::workers(threads, crate::i18n::language(cx)), + cpus, + t!(cx, POWER_TRADEOFF) ), ) }; @@ -1223,8 +1340,8 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { .py(space::XS) .text_size(text::CAPTION) .text_color(theme.secondary.opacity(0.8)) - .child("Scan workers") - .child(format!("{cpus} CPUs")), + .child(t!(cx, "Scan workers")) + .child(t!(cx, "{0} CPUs", cpus)), ); for (index, preset) in PowerEfficiency::ALL.into_iter().enumerate() { let offered = preset.available(cpus); @@ -1261,7 +1378,7 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { .whitespace_nowrap() .overflow_hidden() .text_ellipsis() - .child(preset.name()), + .child(t!(cx, preset.name())), ) .child(div().flex_shrink_0().w(size::ROW_BAR).child(widgets::bar( count as f32 / cpus as f32, @@ -1276,7 +1393,7 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { .justify_end() .text_size(text::BODY) .text_color(theme.secondary) - .child(power::workers(count)), + .child(power::workers(count, crate::i18n::language(cx))), ); // A preset this machine cannot tell apart from the one below it is // shown, so the scale stays the same everywhere, but not offered. @@ -1294,10 +1411,10 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { window.focus(&this.focus, cx); })) } else { - let below = PowerEfficiency::ALL[index - 1].name(); + let below = t!(cx, PowerEfficiency::ALL[index - 1].name()); with_tooltip( row.opacity(0.45), - format!("Same as {below} with {cpus} CPUs"), + t!(cx, "Same as {0} with {1} CPUs", below, cpus), ) }; menu = menu.child(row); @@ -1335,21 +1452,24 @@ fn trail_and_legend( .gap(space::LG) .px(space::LG) .py(space::SM) - .child(scan_totals(app, theme)); + .child(scan_totals(app, theme, cx)); if app.find_open || !app.find.is_empty() { - row = row.child(find_field(app, theme)); + row = row.child(find_field(app, theme, cx)); } row.child(div().flex_1()).child(legend(app, theme, cx)) } /// What the whole scan found, as one quiet line; unreadable paths are /// flagged in the warning colour when there are any. -fn scan_totals(app: &Disktree, theme: &Theme) -> Div { +fn scan_totals(app: &Disktree, theme: &Theme, cx: &App) -> Div { if app.is_indexing() { return div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child("Live overview · incomplete · top-level contributions"); + .child(t!( + cx, + "Live overview · incomplete · top-level contributions" + )); } let tree = app.tree(); let bytes = tree.map_or(app.progress.bytes, |node| node.bytes); @@ -1365,14 +1485,16 @@ fn scan_totals(app: &Disktree, theme: &Theme) -> Div { .text_size(text::CAPTION) .text_color(theme.secondary) .child(div().text_color(theme.foreground).child(human_bytes(bytes))) - .child(format!( - "· {} files · {} dirs", + .child(t!( + cx, + "· {0} files · {1} dirs", widgets::human_count(files), widgets::human_count(dirs) )) .when(errors > 0, |this| { - this.child(div().text_color(theme.warning).child(format!( - "· {} unreadable", + this.child(div().text_color(theme.warning).child(t!( + cx, + "· {0} unreadable", widgets::human_count(errors) ))) }) @@ -1393,7 +1515,7 @@ fn legend(app: &Disktree, theme: &Theme, cx: &App) -> Div { div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child(label), + .child(t!(cx, label)), ) }; let mut lane = div() @@ -1427,7 +1549,10 @@ fn legend(app: &Disktree, theme: &Theme, cx: &App) -> Div { .gap(space::MD) .min_w_0() .overflow_hidden() - .child(item(widgets::hatch_swatch(hatch, ground), "Reclaimable")) + .child(item( + widgets::hatch_swatch(hatch, ground), + t!(cx, "Reclaimable"), + )) .child(lane) } @@ -1510,13 +1635,13 @@ fn selection_section( .flex() .flex_col() .gap(space::MD) - .child(widgets::eyebrow("Selection", cx)); + .child(widgets::eyebrow(t!(cx, "Selection"), cx)); let target = app.action_target().unwrap_or_else(|| app.crumbs.clone()); let Some(node) = app.node_at(&target) else { return section.child( div() .text_color(theme.secondary) - .child("Point at a tile or select one with the arrows"), + .child(t!(cx, "Point at a tile or select one with the arrows")), ); }; let path = app.path_at(&target); @@ -1570,7 +1695,9 @@ fn selection_section( let (number, unit) = match app.options.metric { Metric::Bytes => widgets::split_size(&human_bytes(node.bytes)), - Metric::Files => (widgets::human_count(node.files), "files".into()), + Metric::Files => { + (widgets::human_count(node.files), t!(cx, "files").into()) + } }; let share = node.bytes as f32 / root_value.max(1) as f32; let measure = div() @@ -1592,9 +1719,9 @@ fn selection_section( && crate::git::is_checkout(path) { let value = match app.git.get(path) { - Some(Some(state)) => state.summary(), - Some(None) => "not readable".to_string(), - None => "asking\u{2026}".to_string(), + Some(Some(state)) => state.summary(crate::i18n::language(cx)), + Some(None) => t!(cx, "not readable").to_string(), + None => t!(cx, "asking\u{2026}").to_string(), }; let clean = matches!(app.git.get(path), Some(Some(state)) if state.is_clean()); @@ -1606,12 +1733,16 @@ fn selection_section( ) } else { let kind = node.reclaim.map_or_else( - || node.category.label().to_string(), + || t!(cx, node.category.label()).to_string(), |reason| { - format!("{} \u{00b7} {}", node.category.label(), reason.label()) + format!( + "{} \u{00b7} {}", + t!(cx, node.category.label()), + t!(cx, reason.label()) + ) }, ); - widgets::figure("Kind", kind, theme.bright, cx) + widgets::figure(t!(cx, "Kind"), kind, theme.bright, cx) }; let grid = div() .flex() @@ -1622,13 +1753,13 @@ fn selection_section( .flex() .flex_row() .child(div().flex_1().min_w_0().child(widgets::figure( - "Of scan", + t!(cx, "Of scan"), widgets::percent(node.bytes, root_value), theme.bright, cx, ))) .child(div().flex_1().min_w_0().child(widgets::figure( - "Files", + t!(cx, "Files"), widgets::human_count(node.files), theme.bright, cx, @@ -1639,8 +1770,12 @@ fn selection_section( .flex() .flex_row() .child(div().flex_1().min_w_0().child(widgets::figure( - "Last write", - widgets::ago(crate::state::now_seconds(), node.modified), + t!(cx, "Last write"), + widgets::ago( + crate::state::now_seconds(), + node.modified, + crate::i18n::language(cx), + ), theme.bright, cx, ))) @@ -1650,17 +1785,21 @@ fn selection_section( // Only states that change the decision earn a badge. let mut chips = Vec::new(); if marked { - chips.push(widgets::chip("Marked", theme.danger, cx)); + chips.push(widgets::chip(t!(cx, "Marked"), theme.danger, cx)); } if let Some(ancestor) = &covered_by { chips.push(widgets::chip( - format!("Goes with {ancestor}"), + t!(cx, "Goes with {0}", ancestor), theme.danger, cx, )); } if node.read_error { - chips.push(widgets::chip("Partly unreadable", theme.warning, cx)); + chips.push(widgets::chip( + t!(cx, "Partly unreadable"), + theme.warning, + cx, + )); } let badges = (!chips.is_empty()).then(|| { div() @@ -1678,7 +1817,7 @@ fn selection_section( if node.is_dir() { let crumbs = target.clone(); actions = actions.child( - button("open", "Open", ButtonVariant::Outline, cx) + button("open", t!(cx, "Open"), ButtonVariant::Outline, cx) .tab_stop(false) .flex_1() .justify_center() @@ -1696,10 +1835,10 @@ fn selection_section( let crumbs = target; let label = match &ancestor { Some(ancestor) if !marked => { - format!("Unmark {}", short_name(ancestor)) + t!(cx, "Unmark {0}", short_name(ancestor)) } - _ if marked => "Unmark".to_string(), - _ => "Mark for removal".to_string(), + _ if marked => t!(cx, "Unmark").to_string(), + _ => t!(cx, "Mark for removal").to_string(), }; let mark = button("mark", label, ButtonVariant::Primary, cx) .tab_stop(false) @@ -1753,7 +1892,7 @@ fn worth_section( .items_center() .justify_between() .pb(space::XS) - .child(widgets::eyebrow("Worth a look", cx)) + .child(widgets::eyebrow(t!(cx, "Worth a look"), cx)) .when(total > 0, |this| { this.child( div() @@ -1769,9 +1908,9 @@ fn worth_section( .text_size(text::CAPTION) .text_color(theme.secondary) .child(if app.tree().is_some() { - "Nothing obviously disposable" + t!(cx, "Nothing obviously disposable") } else { - "Waiting for the scan" + t!(cx, "Waiting for the scan") }), ); } @@ -1780,7 +1919,7 @@ fn worth_section( let Some(node) = app.node_at(&candidate.crumbs) else { continue; }; - let (title, detail) = insight_text(app, candidate); + let (title, detail) = insight_text(app, candidate, cx); let accent = palette::category_accent(theme, node.category); let active = selected.as_deref() == Some(candidate.crumbs.as_slice()); let crumbs = candidate.crumbs.clone(); @@ -1852,7 +1991,11 @@ fn worth_section( /// A finding's title, as the last two parts of its path, and why it is on /// the list. -fn insight_text(app: &Disktree, candidate: &Candidate) -> (String, String) { +fn insight_text( + app: &Disktree, + candidate: &Candidate, + cx: &App, +) -> (String, String) { let tree = app.tree(); let chain = tree .map_or_else(Vec::new, |tree| tree.resolve_chain(&candidate.crumbs)); @@ -1860,19 +2003,38 @@ fn insight_text(app: &Disktree, candidate: &Candidate) -> (String, String) { chain.iter().skip(1).map(|node| &*node.name).collect(); let tail = names[names.len().saturating_sub(2)..].join("/"); match &candidate.finding { - Finding::Reclaimable(reason) => (tail, reason.label().to_string()), + Finding::Reclaimable(reason) => { + (tail, t!(cx, reason.label()).to_string()) + } Finding::Worktrees { count, oldest_days } => ( tail, - format!( - "{count} worktree{} \u{00b7} oldest {oldest_days} d", - if *count == 1 { "" } else { "s" } + t!( + cx, + "{0} worktree{1} · oldest {2} d", + count, + if crate::i18n::language(cx) == crate::i18n::Language::English + && *count != 1 + { + "s" + } else { + "" + }, + oldest_days ), ), Finding::StaleExperiments { count } => ( - format!("{tail} > {STALE_DAYS} days"), - format!( - "{count} experiment{} untouched", - if *count == 1 { "" } else { "s" } + t!(cx, "{0} > {1} days", tail, STALE_DAYS), + t!( + cx, + "{0} experiment{1} untouched", + count, + if crate::i18n::language(cx) == crate::i18n::Language::English + && *count != 1 + { + "s" + } else { + "" + } ), ), } @@ -1893,9 +2055,9 @@ fn marked_section( .justify_between() .child(widgets::eyebrow( if count == 0 { - "Marked".to_string() + t!(cx, "Marked").to_string() } else { - format!("Marked · {count}") + t!(cx, "Marked · {0}", count) }, cx, )) @@ -1913,7 +2075,7 @@ fn marked_section( div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child("Space marks the tile you point at"), + .child(t!(cx, "Space marks the tile you point at")), ); } for (index, item) in app.marks.items().iter().take(MARKED_ROWS).enumerate() @@ -1976,8 +2138,9 @@ fn marked_section( div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child(format!( - "+{} more on the review screen", + .child(t!( + cx, + "+{0} more on the review screen", count - MARKED_ROWS )), ); @@ -1987,8 +2150,9 @@ fn marked_section( div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child(format!( - "{} nested \u{00b7} {} kept back", + .child(t!( + cx, + "{0} nested · {1} kept back", plan.covered.len(), plan.blocked.len() )), @@ -2036,7 +2200,11 @@ fn privacy_line( } let color = theme.warning; let errors = app.progress.errors; - let noun = if errors == 1 { "item" } else { "items" }; + let noun = if errors == 1 { + t!(cx, "item") + } else { + t!(cx, "items") + }; Some( div() .flex() @@ -2047,16 +2215,11 @@ fn privacy_line( .border_1() .border_color(color.opacity(0.5)) .text_size(text::CAPTION) - .child(div().text_color(color).child(format!( - "macOS kept {} {noun} unreadable. Give disktree Full Disk \ - Access, or your terminal if you started it there, then \ - reopen it.", - widgets::human_count(errors) - ))) + .child(div().text_color(color).child(t!(cx, "macOS kept {0} {1} unreadable. Give disktree Full Disk Access, or your terminal if you started it there, then reopen it.", widgets::human_count(errors), noun))) .child( button( "privacy", - "Open Privacy Settings", + t!(cx, "Open Privacy Settings"), ButtonVariant::Outline, cx, ) @@ -2093,22 +2256,31 @@ fn administrator_line( } let errors = app.progress.errors; let message = if errors > 0 { - let noun = if errors == 1 { "item" } else { "items" }; + let noun = if errors == 1 { + t!(cx, "item") + } else { + t!(cx, "items") + }; // With `-l` the elevated copy walks too: only the reading is gained. let faster = if app.options.follow_links { "" } else { - ", and a whole drive several times faster" + t!(cx, ", and a whole drive several times faster") }; - format!( - "Windows kept {} {noun} unreadable. Run as administrator to read \ - them{faster}.", - widgets::human_count(errors) + t!( + cx, + "Windows kept {0} {1} unreadable. Run as administrator to read them{2}.", + widgets::human_count(errors), + noun, + faster ) } else if app.file_table && !app.options.follow_links { - "Run as administrator to read the whole drive from its file table: \ + t!( + cx, + "Run as administrator to read the whole drive from its file table: \ several times faster than this walk." - .to_owned() + ) + .to_owned() } else { return None; }; @@ -2116,7 +2288,7 @@ fn administrator_line( let message = if app.marks.is_empty() { message } else { - format!("{message} Restarting drops the marks.") + t!(cx, "{0} Restarting drops the marks.", message) }; let color = theme.warning; Some( @@ -2133,7 +2305,7 @@ fn administrator_line( .child( button( "administrator", - "Restart as Administrator", + t!(cx, "Restart as Administrator"), ButtonVariant::Outline, cx, ) @@ -2155,7 +2327,10 @@ fn disk_section( theme: &Theme, cx: &Context<'_, Disktree>, ) -> Div { - let device = app.device.clone().unwrap_or_default(); + let device = app.remote.as_ref().map_or_else( + || app.device.clone().unwrap_or_default(), + |host| t!(cx, "{0} · read-only · space at scan", host), + ); // The disk header doubles as the way to another volume: it opens the // picker, like `V` does. A plain label would hide that the scan can move. let header = div() @@ -2163,7 +2338,7 @@ fn disk_section( .flex_row() .items_center() .gap(space::SM) - .child(widgets::eyebrow("Disk", cx)) + .child(widgets::eyebrow(t!(cx, "Disk"), cx)) .child( div() .text_size(text::CAPTION) @@ -2172,7 +2347,7 @@ fn disk_section( ) .child(div().flex_1()) .child( - button("volumes", "Source…", ButtonVariant::Secondary, cx) + button("volumes", t!(cx, "Source…"), ButtonVariant::Secondary, cx) .tab_stop(false) .on_click(cx.listener(|this, _, window, cx| { this.open_volumes(cx); @@ -2185,7 +2360,7 @@ fn disk_section( div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child("Free space is not available here"), + .child(t!(cx, "Free space is not available here")), ); }; let plan = app.plan(); @@ -2208,7 +2383,7 @@ fn disk_section( .child(widgets::measure( number, text::FIGURE, - format!("{unit} free"), + t!(cx, "{0} free", unit), text::BODY, cx, )) @@ -2223,8 +2398,9 @@ fn disk_section( (text::FIGURE.0 - text::TITLE.0) * 0.2, )) .text_color(highlight) - .child(format!( - "→ {} free", + .child(t!( + cx, + "→ {0} free", human_bytes(after.available) )), ) @@ -2262,12 +2438,12 @@ fn disk_section( ), ), ); - if let Some(left_out) = not_counted(&plan) { + if let Some(left_out) = not_counted(&plan, cx) { section = section.child( div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child(format!("not counted here: {left_out}")), + .child(t!(cx, "not counted here: {0}", left_out)), ); } section @@ -2277,9 +2453,9 @@ fn disk_section( .flex_row() .text_size(text::CAPTION) .text_color(theme.secondary) - .child(format!("{} used", human_bytes(space_info.used()))) + .child(t!(cx, "{0} used", human_bytes(space_info.used()))) .child(div().flex_1()) - .child(format!("{} total", human_bytes(space_info.total))), + .child(t!(cx, "{0} total", human_bytes(space_info.total))), ) .children( (!app.marks.is_empty()) @@ -2291,14 +2467,15 @@ fn disk_section( /// bytes marked on another volume come back there, and bytes no volume can /// be found for are not claimed at all. `None` when every marked byte is /// this volume's, which is the usual case. -fn not_counted(plan: &Plan) -> Option { +fn not_counted(plan: &Plan, cx: &App) -> Option { let mut parts: Vec = Vec::new(); if plan.foreign() > 0 { - parts.push(format!("{} on other volumes", human_bytes(plan.foreign()))); + parts.push(t!(cx, "{0} on other volumes", human_bytes(plan.foreign()))); } if plan.unattributed() > 0 { - parts.push(format!( - "{} could not be placed", + parts.push(t!( + cx, + "{0} could not be placed", human_bytes(plan.unattributed()) )); } @@ -2345,8 +2522,10 @@ fn review_button( .whitespace_nowrap() .overflow_hidden() .text_ellipsis() - .child(format!( - "Review {count} marked · frees {}…", + .child(t!( + cx, + "Review {0} marked · frees {1}…", + count, human_bytes(reclaiming) )), ) @@ -2360,17 +2539,17 @@ fn review_button( fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div { // Most useful first, so a narrow window clips the least useful. let hints: [(&str, &str); 11] = [ - ("space", "mark"), - ("enter", "open"), - ("\u{232b}", "up"), - ("c", "review"), - ("hjkl", "move"), - ("/", "filter"), - ("[ ]", "depth"), - ("t", "mode"), - ("0", "reset"), - ("v", "volumes"), - ("r", "rescan"), + ("space", t!(cx, "mark")), + ("enter", t!(cx, "open")), + ("\u{232b}", t!(cx, "up")), + ("c", t!(cx, "review")), + ("hjkl", t!(cx, "move")), + ("/", t!(cx, "filter")), + ("[ ]", t!(cx, "depth")), + ("t", t!(cx, "mode")), + ("0", t!(cx, "reset")), + ("v", t!(cx, "volumes")), + ("r", t!(cx, "rescan")), ]; let mut lane = div() .flex() @@ -2404,22 +2583,25 @@ fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div { ); } let scan = if app.scan.is_some() || app.remote_scan.is_some() { - "Indexing · incomplete".to_string() + t!(cx, "Indexing · incomplete").to_string() } else if app.progress.cancelled { - format!( - "scan cancelled \u{00b7} {} entries \u{00b7} r scans again", + t!( + cx, + "scan cancelled · {0} entries · r scans again", widgets::human_count(app.progress.files) ) } else { let elapsed = app.scan_elapsed.map_or_else(String::new, |time| { format!(" \u{00b7} {:.1} s", time.as_secs_f32()) }); - format!( - "scan {} entries{elapsed}", - widgets::human_count(app.progress.files) + t!( + cx, + "scan {0} entries{1}", + widgets::human_count(app.progress.files), + elapsed ) }; - row.child(widgets::hint("?", "all keys", cx).flex_shrink_0()) + row.child(widgets::hint("?", t!(cx, "all keys"), cx).flex_shrink_0()) .child( div() .flex_shrink_0() @@ -2457,11 +2639,11 @@ fn scanning_panel( .text_size(text::BODY) .text_color(theme.secondary) .child(if error.is_some() { - "Scan failed" + t!(cx, "Scan failed") } else if app.progress.cancelled { - "Indexing stopped" + t!(cx, "Indexing stopped") } else { - "Waiting for the first indexed entries…" + t!(cx, "Waiting for the first indexed entries…") }) .children(error.map(|error| { div() @@ -2471,11 +2653,18 @@ fn scanning_panel( })) .when(!app.is_indexing(), |panel| { panel.child( - button("scan-again", "Scan again", ButtonVariant::Outline, cx) - .on_click(cx.listener(|this, _, window, cx| { + button( + "scan-again", + t!(cx, "Scan again"), + ButtonVariant::Outline, + cx, + ) + .on_click(cx.listener( + |this, _, window, cx| { this.start_scan(cx); window.focus(&this.focus, cx); - })), + }, + )), ) }) } @@ -2499,8 +2688,9 @@ fn indexing_compact( .min_w_0() .truncate() .font_family(theme.mono_font.clone()) - .child(format!( - "{} files", + .child(t!( + cx, + "{0} files", widgets::human_count(app.progress.files) )), ) @@ -2510,15 +2700,14 @@ fn indexing_compact( .min_w_0() .truncate() .font_family(theme.mono_font.clone()) - .child(format!("{} measured", human_bytes(app.progress.bytes))), + .child(t!(cx, "{0} measured", human_bytes(app.progress.bytes))), ) .child( - button("cancel-scan", "Stop", ButtonVariant::Outline, cx).on_click( - cx.listener(|this, _, window, cx| { + button("cancel-scan", t!(cx, "Stop"), ButtonVariant::Outline, cx) + .on_click(cx.listener(|this, _, window, cx| { this.cancel_scan(cx); window.focus(&this.focus, cx); - }), - ), + })), ) } @@ -2554,7 +2743,7 @@ fn indexing_progress( .and_then(|preview| preview.directory.as_ref()) }; let full_path = path.map_or_else( - || "Directory not reported yet".into(), + || t!(cx, "Directory not reported yet").into(), |path| path.display().to_string(), ); let mut parts = path @@ -2580,41 +2769,45 @@ fn indexing_progress( .gap(space::XS) .text_size(text::BODY) .text_color(theme.foreground) - .child(widgets::eyebrow("Indexing", cx)) + .child(widgets::eyebrow(t!(cx, "Indexing"), cx)) .child(div().h(size::PROGRESS_ROW).truncate().child( if app.remote.is_some() { - app.remote_progress.stage.label() + t!(cx, app.remote_progress.stage.label()) } else { - "Reading this computer" + t!(cx, "Reading this computer") }, )) .child(row( - "Files", + t!(cx, "Files"), widgets::human_count(app.progress.files), "indexing-files", )) .child(row( - "Directories", + t!(cx, "Directories"), widgets::human_count(app.progress.dirs), "indexing-dirs", )) .child(row( - "Measured", + t!(cx, "Measured"), human_bytes(app.progress.bytes), "indexing-bytes", )) .child(row( - "Read errors", + t!(cx, "Read errors"), widgets::human_count(app.progress.errors), "indexing-errors", )) - .child(row("Elapsed", format!("{elapsed} s"), "indexing-elapsed")) + .child(row( + t!(cx, "Elapsed"), + format!("{elapsed} s"), + "indexing-elapsed", + )) .child( div() .h(size::PROGRESS_ROW) .text_size(text::CAPTION) .text_color(theme.secondary) - .child("Recent directory"), + .child(t!(cx, "Recent directory")), ) .child(with_tooltip( div() @@ -2631,39 +2824,51 @@ fn indexing_progress( div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child("Preview only · provisional totals"), + .child(t!(cx, "Preview only · provisional totals")), ) .child( - button("cancel-scan", "Stop indexing", ButtonVariant::Outline, cx) - .on_click(cx.listener(|this, _, window, cx| { - this.cancel_scan(cx); - window.focus(&this.focus, cx); - })), + button( + "cancel-scan", + t!(cx, "Stop indexing"), + ButtonVariant::Outline, + cx, + ) + .on_click(cx.listener(|this, _, window, cx| { + this.cancel_scan(cx); + window.focus(&this.focus, cx); + })), ) } -fn find_field(app: &Disktree, theme: &Theme) -> Div { +fn find_field(app: &Disktree, theme: &Theme, cx: &App) -> Div { // What the text matches, said beside it as it is typed, and what Enter // and Escape will do with it. let (summary, hint) = match app.matches.as_deref() { _ if app.finding && app.matches.is_none() => { - ("searching…".to_string(), "") + (t!(cx, "searching…").to_string(), "") } - None => (String::new(), "type to filter"), + None => (String::new(), t!(cx, "type to filter")), Some(matches) if matches.count == 0 => { - ("no matches".to_string(), "esc clears") + (t!(cx, "no matches").to_string(), t!(cx, "esc clears")) } Some(matches) => ( - format!( - "{} match{} · {}", + t!( + cx, + "{0} match{1} · {2}", widgets::human_count(matches.count as u64), - if matches.count == 1 { "" } else { "es" }, + if crate::i18n::language(cx) == crate::i18n::Language::English + && matches.count != 1 + { + "es" + } else { + "" + }, human_bytes(matches.bytes) ), if app.filter_applied { - "esc clears" + t!(cx, "esc clears") } else { - "enter shows only these" + t!(cx, "enter shows only these") }, ), }; @@ -2698,7 +2903,7 @@ fn find_field(app: &Disktree, theme: &Theme) -> Div { .child(if app.find.is_empty() { div() .text_color(theme.secondary.opacity(0.7)) - .child("Filter by name") + .child(t!(cx, "Filter by name")) } else { div().text_color(theme.bright).child(app.find.clone()) }) @@ -2770,12 +2975,10 @@ fn review( .bg(theme.inset); if items.is_empty() { - list = list.child( - div() - .p(space::XXL) - .text_color(theme.secondary) - .child("Nothing is marked. Go back and mark what should go."), - ); + list = + list.child(div().p(space::XXL).text_color(theme.secondary).child( + t!(cx, "Nothing is marked. Go back and mark what should go."), + )); } for (index, item) in items.iter().take(LIST_LIMIT).enumerate() { @@ -2802,10 +3005,7 @@ fn review( .py(space::SM) .text_size(text::CAPTION) .text_color(theme.secondary) - .child(format!( - "{} more are marked and will be removed too. Unmark them in the treemap.", - items.len() - LIST_LIMIT - )), + .child(t!(cx, "{0} more are marked and will be removed too. Unmark them in the treemap.", items.len() - LIST_LIMIT)), ); } @@ -2816,9 +3016,10 @@ fn review( .flex_1() .min_h_0() .child(screen_header( - "Review", - &format!( - "{} marked \u{00b7} {} to free", + t!(cx, "Review"), + &t!( + cx, + "{0} marked · {1} to free", app.marks.len(), human_bytes(plan.bytes()) ), @@ -2897,11 +3098,15 @@ fn mark_row( ), ) .children(covered.then(|| { - widgets::chip("Inside a marked directory", theme.secondary, cx) + widgets::chip( + t!(cx, "Inside a marked directory"), + theme.secondary, + cx, + ) + })) + .children(blocked.map(|reason| { + widgets::chip(t!(cx, &reason).to_owned(), theme.warning, cx) })) - .children( - blocked.map(|reason| widgets::chip(reason, theme.warning, cx)), - ) .child(div().w(size::SHARE_LANE).flex_shrink_0().child( widgets::glyph_bar( item.bytes, @@ -2924,7 +3129,7 @@ fn mark_row( .child( button( ElementId::Name(SharedString::from(format!("unmark-{index}"))), - "Unmark", + t!(cx, "Unmark"), ButtonVariant::Outline, cx, ) @@ -2947,8 +3152,8 @@ fn review_summary( let reclaiming = plan.reclaim(); // The part of the saving that lands elsewhere, said rather than added to // this volume's projection, so the two numbers cannot be confused. - let left_out = not_counted(plan) - .map(|left_out| widgets::row("Not counted here", left_out, cx)); + let left_out = not_counted(plan, cx) + .map(|left_out| widgets::row(t!(cx, "Not counted here"), left_out, cx)); let trash = app.trash_backend.is_available(); // One silhouette for one either-or choice, reversible option first. @@ -2956,8 +3161,8 @@ fn review_summary( let mode = button_group( "removal-mode", vec![ - ChoiceItem::new("trash", "Move to trash").disabled(!trash), - ChoiceItem::new("permanent", "Delete permanently"), + ChoiceItem::new("trash", t!(cx, "Move to trash")).disabled(!trash), + ChoiceItem::new("permanent", t!(cx, "Delete permanently")), ], Some(usize::from(app.removal_mode == RemovalMode::Permanent)), move |index, _, cx| { @@ -2975,17 +3180,21 @@ fn review_summary( ); let explanation = if app.remote.is_some() { - "Read-only SSH session. Export the selection; nothing is \ + t!( + cx, + "Read-only SSH session. Export the selection; nothing is \ deleted here. Free space is sampled at scan time." - .to_string() + ) + .to_string() } else { match app.removal_mode { - RemovalMode::Trash => format!( - "Recoverable from the trash until it is emptied. Uses {}.", - app.trash_backend.label() + RemovalMode::Trash => t!( + cx, + "Recoverable from the trash until it is emptied. Uses {0}.", + t!(cx, app.trash_backend.label()) ), RemovalMode::Permanent => { - "Deleted at once, like rm -rf. Nothing is recoverable." + t!(cx, "Deleted at once, like rm -rf. Nothing is recoverable.") .to_string() } } @@ -3006,7 +3215,7 @@ fn review_summary( .flex() .flex_col() .gap(space::SM) - .child(widgets::section("What happens", cx)) + .child(widgets::section(t!(cx, "What happens"), cx)) .children(app.remote.is_none().then_some(mode)) .child( div() @@ -3020,29 +3229,29 @@ fn review_summary( .flex() .flex_col() .gap(space::SM) - .child(widgets::section("Totals", cx)) + .child(widgets::section(t!(cx, "Totals"), cx)) .child(widgets::row( - "Marked", + t!(cx, "Marked"), format!("{}", app.marks.len()), cx, )) .child(widgets::row( - "Acted on", + t!(cx, "Acted on"), format!("{}", plan.targets.len()), cx, )) .child(widgets::row( - "Nested, go with a parent", + t!(cx, "Nested, go with a parent"), format!("{}", plan.covered.len()), cx, )) .child(widgets::row( - "Kept back", + t!(cx, "Kept back"), format!("{}", plan.blocked.len()), cx, )) .child(widgets::row( - "Space freed", + t!(cx, "Space freed"), human_bytes(plan.bytes()), cx, )) @@ -3055,7 +3264,7 @@ fn review_summary( .flex() .flex_col() .gap(space::SM) - .child(widgets::section("Volume", cx)) + .child(widgets::section(t!(cx, "Volume"), cx)) .child(widgets::space_meter(volume, reclaiming, cx)), ); } @@ -3070,7 +3279,7 @@ fn review_summary( .child(format!( "{}: {}", short_name(&item.path), - item.reason + t!(cx, &item.reason) )), ); } @@ -3079,7 +3288,7 @@ fn review_summary( .flex() .flex_col() .gap(space::XS) - .child(widgets::section("Kept back", cx)) + .child(widgets::section(t!(cx, "Kept back"), cx)) .child(blocked), ); } @@ -3105,7 +3314,7 @@ fn export_controls( .child( button( "save-list", - "Save list\u{2026}", + t!(cx, "Save list\u{2026}"), ButtonVariant::Secondary, cx, ) @@ -3117,7 +3326,7 @@ fn export_controls( .child( button( "copy-prompt", - "Copy as prompt", + t!(cx, "Copy as prompt"), ButtonVariant::Secondary, cx, ) @@ -3129,7 +3338,7 @@ fn export_controls( .child( button( "save-script", - "Save delete script…", + t!(cx, "Save delete script…"), ButtonVariant::Secondary, cx, ) @@ -3141,7 +3350,7 @@ fn export_controls( .child( button( "copy-script", - "Copy delete script", + t!(cx, "Copy delete script"), ButtonVariant::Secondary, cx, ) @@ -3161,14 +3370,18 @@ fn commit_controls( cx: &Context<'_, Disktree>, ) -> Div { let count = plan.targets.len(); - let noun = if count == 1 { "item" } else { "items" }; + let noun = if count == 1 { + t!(cx, "item") + } else { + t!(cx, "items") + }; let (label, variant) = match app.removal_mode { RemovalMode::Trash => ( - format!("Move {count} {noun} to trash"), + t!(cx, "Move {0} {1} to trash", count, noun), ButtonVariant::Primary, ), RemovalMode::Permanent => ( - format!("Delete {count} {noun}\u{2026}"), + t!(cx, "Delete {0} {1}…", count, noun), ButtonVariant::Danger, ), }; @@ -3182,13 +3395,12 @@ fn commit_controls( .justify_end() .gap(space::SM) .child( - button("back", "Back", ButtonVariant::Secondary, cx).on_click( - cx.listener(|this, _, window, cx| { + button("back", t!(cx, "Back"), ButtonVariant::Secondary, cx) + .on_click(cx.listener(|this, _, window, cx| { this.screen = Screen::Explore; cx.notify(); window.focus(&this.focus, cx); - }), - ), + })), ) .child( button("commit", label, variant, cx) @@ -3202,8 +3414,8 @@ fn commit_controls( fn review_footer(app: &Disktree, theme: &Theme, cx: &App) -> Div { let commit = match app.removal_mode { - RemovalMode::Trash => "move to trash", - RemovalMode::Permanent => "delete\u{2026}", + RemovalMode::Trash => t!(cx, "move to trash"), + RemovalMode::Permanent => t!(cx, "delete\u{2026}"), }; div() .flex() @@ -3222,26 +3434,27 @@ fn review_footer(app: &Disktree, theme: &Theme, cx: &App) -> Div { .children( app.remote .is_none() - .then(|| widgets::hint("m", "trash", cx)), + .then(|| widgets::hint("m", t!(cx, "trash"), cx)), ) .children( app.remote .is_none() - .then(|| widgets::hint("p", "permanent", cx)), + .then(|| widgets::hint("p", t!(cx, "permanent"), cx)), ) - .child(widgets::hint("e", "save script", cx)) - .child(widgets::hint("y", "copy script", cx)) - .child(widgets::hint("!", "unmark all", cx)) - .child(widgets::hint("s", "save list", cx)) - .child(widgets::hint("a", "copy as prompt", cx)) - .child(widgets::hint("esc", "back", cx)) + .child(widgets::hint("e", t!(cx, "save script"), cx)) + .child(widgets::hint("y", t!(cx, "copy script"), cx)) + .child(widgets::hint("!", t!(cx, "unmark all"), cx)) + .child(widgets::hint("s", t!(cx, "save list"), cx)) + .child(widgets::hint("a", t!(cx, "copy as prompt"), cx)) + .child(widgets::hint("esc", t!(cx, "back"), cx)) .child(div().flex_1()) .child( div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child(format!( - "{} available", + .child(t!( + cx, + "{0} available", app.space.map_or_else( || "?".into(), |space| human_bytes(space.available) @@ -3322,8 +3535,8 @@ fn running(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div { .flex_1() .min_h_0() .child(screen_header( - "Removing", - &format!("{} of {} done", done, summary.total), + t!(cx, "Removing"), + &t!(cx, "{0} of {1} done", done, summary.total), &theme, cx, )) @@ -3336,9 +3549,10 @@ fn running(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div { .flex_1() .min_h_0() .child(widgets::meter_row( - "progress", - format!( - "{} removed · {} to free", + t!(cx, "progress"), + t!( + cx, + "{0} removed · {1} to free", summary.removed, human_bytes(summary.bytes) ), @@ -3365,7 +3579,11 @@ fn running(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div { .py(space::SM) .border_t_1() .border_color(theme.divider()) - .child(widgets::hint("esc", "stop after the current item", cx)), + .child(widgets::hint( + "esc", + t!(cx, "stop after the current item"), + cx, + )), ) } @@ -3417,14 +3635,14 @@ fn done(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div { .flex_row() .gap(space::XXL) .child(widgets::stat_colored( - "removed", - format!("{} items", summary.removed), + t!(cx, "removed"), + t!(cx, "{0} items", summary.removed), theme.success, cx, )) - .child(widgets::stat("bytes claimed", human_bytes(summary.bytes), cx)) + .child(widgets::stat(t!(cx, "bytes claimed"), human_bytes(summary.bytes), cx)) .child(widgets::stat_colored( - "failed", + t!(cx, "failed"), format!("{}", summary.failed), if summary.failed > 0 { theme.danger @@ -3435,7 +3653,7 @@ fn done(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div { )) .children(measured.map(|delta| { widgets::stat_colored( - "volume freed", + t!(cx, "volume freed"), if delta >= 0 { format!("+{}", human_bytes(delta.unsigned_abs())) } else { @@ -3450,7 +3668,7 @@ fn done(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div { div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child("The treemap is being re-scanned so the numbers on screen match the disk again."), + .child(t!(cx, "The treemap is being re-scanned so the numbers on screen match the disk again.")), ); if let Some(space) = app.space { @@ -3458,8 +3676,8 @@ fn done(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div { } if app.scan.is_some() { body = body.child(widgets::meter_row( - "re-scanning", - format!("{} files", widgets::human_count(app.progress.files)), + t!(cx, "re-scanning"), + t!(cx, "{0} files", widgets::human_count(app.progress.files)), 0.0, theme.accent, cx, @@ -3468,7 +3686,7 @@ fn done(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div { if summary.failed > 0 { body = body .child(separator(cx)) - .child(widgets::section("what could not be removed", cx)) + .child(widgets::section(t!(cx, "what could not be removed"), cx)) .child(failures); } @@ -3477,7 +3695,12 @@ fn done(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div { .flex_col() .flex_1() .min_h_0() - .child(screen_header("Done", "removal finished", &theme, cx)) + .child(screen_header( + t!(cx, "Done"), + t!(cx, "removal finished"), + &theme, + cx, + )) .child(body) .child( div() @@ -3491,14 +3714,21 @@ fn done(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div { .border_color(theme.divider()) .child( // An acknowledgement: the result is already on screen. - button("continue", "Done", ButtonVariant::Primary, cx) - .on_click(cx.listener(|this, _, window, cx| { + button( + "continue", + t!(cx, "Done"), + ButtonVariant::Primary, + cx, + ) + .on_click(cx.listener( + |this, _, window, cx| { this.screen = Screen::Explore; cx.notify(); window.focus(&this.focus, cx); - })), + }, + )), ) - .child(widgets::hint("enter", "continue", cx)), + .child(widgets::hint("enter", t!(cx, "continue"), cx)), ) } @@ -3609,9 +3839,9 @@ fn card_surface(cx: &gpui_kit::App) -> Div { /// at the pointer, over the button itself. fn history_card(app: &Disktree, back: bool, cx: &gpui_kit::App) -> Div { let (label, keys) = if back { - ("Back", "alt \u{2190} \u{00b7} side button") + (t!(cx, "Back"), "alt \u{2190} \u{00b7} side button") } else { - ("Forward", "alt \u{2192} \u{00b7} side button") + (t!(cx, "Forward"), "alt \u{2192} \u{00b7} side button") }; let card = app .history_target(back) @@ -3630,9 +3860,9 @@ pub fn hover_tooltip(app: &Disktree, cx: &gpui_kit::App) -> Option
{ let crumbs = app.hovered.as_deref()?; let is_dir = app.node_at(crumbs)?.is_dir(); let keys = if is_dir { - "space mark · enter open" + t!(cx, "space mark · enter open") } else { - "space mark" + t!(cx, "space mark") }; node_card(app, crumbs, keys, cx) } @@ -3720,8 +3950,9 @@ fn node_card( div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child(format!( - "{} files · {} dirs · {} direct", + .child(t!( + cx, + "{0} files · {1} dirs · {2} direct", widgets::human_count(node.files), widgets::human_count( u64::from(node.dirs) @@ -3733,15 +3964,19 @@ fn node_card( let mut badges = div().flex().flex_row().gap(space::XS).flex_wrap(); if hidden { - badges = badges.child(widgets::chip("Hidden", theme.secondary, cx)); + badges = + badges.child(widgets::chip(t!(cx, "Hidden"), theme.secondary, cx)); } if marked { - badges = - badges.child(widgets::chip("Marked for removal", theme.danger, cx)); + badges = badges.child(widgets::chip( + t!(cx, "Marked for removal"), + theme.danger, + cx, + )); } if let Some(ancestor) = covered { badges = badges.child(widgets::chip( - format!("Inside marked {ancestor}"), + t!(cx, "Inside marked {0}", ancestor), theme.secondary, cx, )); @@ -3780,56 +4015,69 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { // Sentence case, and the tile a key acts on is always the one under the // pointer if the pointer moved last, else the keyboard selection. let rows = [ - ("space / x", "Mark or unmark the tile you point at"), - (MODIFIER_CLICK, "Mark without moving the selection"), - ("enter", "Open that directory, at any depth"), - ("\u{232b} / esc", "Go up one directory"), + ("space / x", t!(cx, "Mark or unmark the tile you point at")), + (MODIFIER_CLICK, t!(cx, "Mark without moving the selection")), + ("enter", t!(cx, "Open that directory, at any depth")), + ("\u{232b} / esc", t!(cx, "Go up one directory")), ( "alt \u{2190} / \u{2192}", - "Back or forward, as do the mouse's side buttons", + t!(cx, "Back or forward, as do the mouse's side buttons"), ), ( "\u{2190} \u{2191} \u{2193} \u{2192}", - "Move between tiles at this level", + t!(cx, "Move between tiles at this level"), ), - ("tab", "Next largest sibling"), - ("scroll", "Zoom toward a directory, then go into it"), - ("shift-scroll", "Pan the magnified view"), - ("[ / ]", "Draw fewer or more levels at once"), - ("- / = / 0", "Magnify, shrink, or reset the view"), - (MODIFIER_ZOOM, "Interface zoom"), + ("tab", t!(cx, "Next largest sibling")), + ("scroll", t!(cx, "Zoom toward a directory, then go into it")), + ("shift-scroll", t!(cx, "Pan the magnified view")), + ("[ / ]", t!(cx, "Draw fewer or more levels at once")), + ("- / = / 0", t!(cx, "Magnify, shrink, or reset the view")), + (MODIFIER_ZOOM, t!(cx, "Interface zoom")), ( "/", - "Filter by name: only matches keep their colour; enter shows only them", + t!( + cx, + "Filter by name: only matches keep their colour; enter shows only them" + ), + ), + ("c", t!(cx, "Review the marked list")), + ( + "t", + t!(cx, "Size, files or age: what areas and colours say"), ), - ("c", "Review the marked list"), - ("t", "Size, files or age: what areas and colours say"), - ("r", "Scan again from the same root"), - ("esc", "Stop a scan in progress"), - ("v", "Scan another volume"), - (MODIFIER_OPEN, "Choose another directory to scan"), - ("g", "The whole disk; click any directory above to widen"), - ("d", "Disk usage or apparent size"), - ("i", "Include or skip hidden entries"), - ("p", "Show or hide the selection line"), + ("r", t!(cx, "Scan again from the same root")), + ("esc", t!(cx, "Stop a scan in progress")), + ("v", t!(cx, "Scan another volume")), + (MODIFIER_OPEN, t!(cx, "Choose another directory to scan")), + ( + "g", + t!(cx, "The whole disk; click any directory above to widen"), + ), + ("d", t!(cx, "Disk usage or apparent size")), + ("i", t!(cx, "Include or skip hidden entries")), + ("p", t!(cx, "Show or hide the selection line")), ( "o", if cfg!(target_os = "macos") { - "Show it in Finder" + t!(cx, "Show it in Finder") } else if cfg!(windows) { - "Show it in File Explorer" + t!(cx, "Show it in File Explorer") } else { - "Show it in the file manager" + t!(cx, "Show it in the file manager") }, ), - ("q", "Quit"), + ("f2", t!(cx, "Choose interface language")), + ("q", t!(cx, "Quit")), ("", ""), ( - "Review screen", - "m trash \u{00b7} p permanent \u{00b7} ! unmark all \u{00b7} s save list \u{00b7} a copy as prompt", + t!(cx, "Review screen"), + t!( + cx, + "m trash \u{00b7} p permanent \u{00b7} ! unmark all \u{00b7} s save list \u{00b7} a copy as prompt" + ), ), - ("", "enter commits \u{00b7} esc goes back"), - ("", "A permanent deletion always asks first"), + ("", t!(cx, "enter commits \u{00b7} esc goes back")), + ("", t!(cx, "A permanent deletion always asks first")), ]; let mut keys = div().flex().flex_col().gap(space::SM); @@ -3895,7 +4143,7 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { .text_size(text::TITLE) .font_weight(FontWeight::BOLD) .text_color(theme.bright) - .child("Keyboard and mouse"), + .child(t!(cx, "Keyboard and mouse")), ), ) .child(keys) @@ -3903,10 +4151,11 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child(format!( - "? or esc closes \u{00b7} {} \u{00b7} {}", + .child(t!( + cx, + "? or esc closes · {0} · {1}", app.root_path.display(), - app.options.metric.label() + t!(cx, app.options.metric.label()) )), ), ) diff --git a/crates/disktree-app/src/widgets.rs b/crates/disktree-app/src/widgets.rs index cc2927bf..02891a47 100644 --- a/crates/disktree-app/src/widgets.rs +++ b/crates/disktree-app/src/widgets.rs @@ -3,6 +3,8 @@ //! Everything is built from the active Omarchy theme's tokens, and every piece //! is a plain function over borrowed data so the screens stay readable. +use crate::i18n::t; + use disktree_core::size::{human_bytes, human_bytes_short, share, share_bar}; use disktree_core::space::SpaceInfo; use disktree_core::tree::{Metric, Node}; @@ -152,15 +154,17 @@ pub fn space_meter(space: SpaceInfo, reclaiming: u64, cx: &App) -> Div { let gained = gained.clamp(0.0, used_now); let label = if reclaiming > 0 { - format!( - "{} free · {} after removing {}", + t!( + cx, + "{0} free · {1} after removing {2}", human_bytes(space.available), human_bytes(projected.available), human_bytes(reclaiming) ) } else { - format!( - "{} free of {}", + t!( + cx, + "{0} free of {1}", human_bytes(space.available), human_bytes(space.total) ) @@ -375,26 +379,25 @@ pub fn split_size(text: &str) -> (String, String) { } /// How long ago a Unix time was, in the unit a person would use. -pub fn ago(now: i64, then: i64) -> String { +pub fn ago(now: i64, then: i64, language: crate::i18n::Language) -> String { if then <= 0 { - return "unknown".to_string(); + return language.text("unknown").to_string(); } let seconds = (now - then).max(0); - let plural = |count: i64, unit: &str| { - if count == 1 { - format!("1 {unit} ago") - } else { - format!("{count} {unit}s ago") + let (count, singular, plural) = match seconds { + 0..60 => return language.text("just now").to_string(), + 60..3_600 => (seconds / 60, "{0} minute ago", "{0} minutes ago"), + 3_600..86_400 => (seconds / 3_600, "{0} hour ago", "{0} hours ago"), + 86_400..5_184_000 => (seconds / 86_400, "{0} day ago", "{0} days ago"), + 5_184_000..63_072_000 => { + (seconds / 2_592_000, "{0} month ago", "{0} months ago") } + _ => (seconds / 31_536_000, "{0} year ago", "{0} years ago"), }; - match seconds { - 0..60 => "just now".to_string(), - 60..3_600 => plural(seconds / 60, "minute"), - 3_600..86_400 => plural(seconds / 3_600, "hour"), - 86_400..5_184_000 => plural(seconds / 86_400, "day"), - 5_184_000..63_072_000 => plural(seconds / 2_592_000, "month"), - _ => plural(seconds / 31_536_000, "year"), - } + crate::i18n::format( + language.text(if count == 1 { singular } else { plural }), + &[count.to_string()], + ) } /// A thin bar: `fraction` of a track, in `color`. @@ -516,14 +519,15 @@ mod tests { #[test] fn ages_read_in_the_unit_a_person_would_use() { + use crate::i18n::Language::English; let now = 1_800_000_000; - assert_eq!(ago(now, now - 5), "just now"); - assert_eq!(ago(now, now - 120), "2 minutes ago"); - assert_eq!(ago(now, now - 3_600), "1 hour ago"); - assert_eq!(ago(now, now - 19 * 86_400), "19 days ago"); - assert_eq!(ago(now, now - 90 * 86_400), "3 months ago"); - assert_eq!(ago(now, now - 800 * 86_400), "2 years ago"); - assert_eq!(ago(now, 0), "unknown"); + assert_eq!(ago(now, now - 5, English), "just now"); + assert_eq!(ago(now, now - 120, English), "2 minutes ago"); + assert_eq!(ago(now, now - 3_600, English), "1 hour ago"); + assert_eq!(ago(now, now - 19 * 86_400, English), "19 days ago"); + assert_eq!(ago(now, now - 90 * 86_400, English), "3 months ago"); + assert_eq!(ago(now, now - 800 * 86_400, English), "2 years ago"); + assert_eq!(ago(now, 0, English), "unknown"); } #[test] @@ -531,4 +535,18 @@ mod tests { assert_eq!(split_size("90.1 GiB"), ("90.1".into(), "GiB".into())); assert_eq!(split_size("0"), ("0".into(), String::new())); } + + #[test] + fn chinese_ages_use_complete_messages_without_english_suffixes() { + use crate::i18n::Language::SimplifiedChinese as Chinese; + let now = 1_800_000_000; + assert_eq!(ago(now, 0, Chinese), "未知"); + assert_eq!(ago(now, now + 1, Chinese), "刚刚"); + assert_eq!(ago(now, now - 60, Chinese), "1 分钟前"); + assert_eq!(ago(now, now - 120, Chinese), "2 分钟前"); + assert_eq!(ago(now, now - 3_600, Chinese), "1 小时前"); + assert_eq!(ago(now, now - 19 * 86_400, Chinese), "19 天前"); + assert_eq!(ago(now, now - 90 * 86_400, Chinese), "3 个月前"); + assert_eq!(ago(now, now - 800 * 86_400, Chinese), "2 年前"); + } } diff --git a/docs/translations.md b/docs/translations.md new file mode 100644 index 00000000..1d601ff2 --- /dev/null +++ b/docs/translations.md @@ -0,0 +1,36 @@ +# Adding a language + +The desktop window currently offers English and Simplified Chinese. Use +**Language / 语言** or `F2` to switch without restarting or rescanning. +Language names are written in their own language so users can switch back. +The preference is the separate `language` file in the same user directory as +`power-efficiency`; neither preference overwrites the other. + +The catalog lives in `crates/disktree-app/src/locales/zh_cn.rs`. English source +messages are stable lookup keys and the fallback for untranslated messages. +There is no new dependency, and the scanner and SSH protocol do not depend on +the window's language. + +To add a language: + +1. Copy the catalog into a new file in `locales/` and translate its values. + Keep the English keys sorted, unique and unchanged. +2. Add the language to `Language`, `ALL`, `key`, `name` and `text` in + `i18n.rs`. Use an autonym for `name` and a stable locale tag for `key`. +3. Preserve every numbered slot (`{0}`, `{1}`, …). Values may be reordered, + but never translated or removed. Inserted file paths are copied verbatim + and are not parsed again as formatting instructions. +4. Run `cargo xtask lint` and `cargo xtask test`. Extend the catalog checks to + the new language and draw the source chooser, help, review and permanent + deletion confirmation in the window harness. Check a small window and + larger interface zoom too. + +Translate complete messages rather than joining translated fragments. English +singular/plural variants of relative times have separate keys. Chinese does +not use the English plural suffixes in counts. + +Only presentation text is localized. Do not translate paths, file names, +internal control IDs, CLI flags, saved preset keys, SSH protocol fields or +generated shell commands. Raw operating-system and scanner error details, CLI +help, and agent handoff prompts remain in their original language. In +particular, do not infer an error code by parsing a translated error string.