Skip to content

armgit / Wake

Public Imported from GitHub
0

All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.

Rust

feat(i18n): localize the UI, ship Simplified Chinese

Corey Chiub2fb99db371a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0d75d81..ab9f8ec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,11 @@
## Unreleased
+## [0.5.2] — 2026-09-10
+
+- New: Wake speaks your language — Simplified Chinese included, and the UI follows your system language on first launch; pick a fixed language under Settings → General
+- New: adding a language takes one JSON file — drop it in Wake's config folder to use it right away, or send it as a pull request; anything left untranslated stays English (see crates/wake/locales/README.md)
+
## [0.5.1] — 2026-09-08
- Update: the MCP tools now tell agents when to use Wake — earlier conversations, decisions, where work stopped, "have we seen this error" — so a fresh session reaches for session history instead of answering from git log
diff --git a/Cargo.lock b/Cargo.lock
index e0c035c..5552f1a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7740,7 +7740,7 @@ dependencies = [
[[package]]
name = "wake"
-version = "0.5.1"
+version = "0.5.2"
dependencies = [
"anyhow",
"chrono",
@@ -7753,6 +7753,7 @@ dependencies = [
"semver",
"serde",
"serde_json",
+ "sys-locale",
"tempfile",
"unicode-segmentation",
"unicode-width",
@@ -7763,7 +7764,7 @@ dependencies = [
[[package]]
name = "wake-core"
-version = "0.5.1"
+version = "0.5.2"
dependencies = [
"anyhow",
"base64",
diff --git a/Cargo.toml b/Cargo.toml
index 44ec345..d70d9b7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/wake-core", "crates/wake"]
[workspace.package]
-version = "0.5.1"
+version = "0.5.2"
edition = "2021"
license = "MIT"
diff --git a/README.md b/README.md
index 34aac66..4b2088f 100644
--- a/README.md
+++ b/README.md
@@ -100,6 +100,17 @@ A few things worth knowing:
The full reference — every parameter, output formats, key and reference formats, error semantics, troubleshooting — is in [docs/mcp.md](docs/mcp.md).
+## Language
+
+Wake's interface follows your system language on first launch and falls back to
+English. Simplified Chinese ships with the app; pick a fixed language under
+**Settings → General → Language**.
+
+Adding a language is one flat JSON file mapping the English text to your
+translation — drop it in Wake's config folder to use it immediately, or send it
+as a pull request. Untranslated strings simply stay English, so a partial pack is
+welcome. See [crates/wake/locales/README.md](crates/wake/locales/README.md).
+
## Privacy stance
- Agent data directories are opened **read-only**; Wake never writes to another tool's files or databases
diff --git a/crates/wake/Cargo.toml b/crates/wake/Cargo.toml
index 80295f1..e4ec006 100644
--- a/crates/wake/Cargo.toml
+++ b/crates/wake/Cargo.toml
@@ -24,6 +24,9 @@ semver.workspace = true
reqwest.workspace = true
image.workspace = true
unicode-width = "0.2"
+# 系统语言探测(i18n 的 System 档):macOS 走 CFLocale、Windows 走
+# GetUserDefaultLocaleName、Linux 读 LC_ALL/LANG,三平台一份接口
+sys-locale = "0.3"
unicode-segmentation = "1.13"
[dev-dependencies]
diff --git a/crates/wake/locales/README.md b/crates/wake/locales/README.md
new file mode 100644
index 0000000..fa88169
--- /dev/null
+++ b/crates/wake/locales/README.md
@@ -0,0 +1,63 @@
+# Language packs
+
+Wake's UI text is English by default. A language pack is one flat JSON file that
+maps **the English string itself** to its translation:
+
+```json
+{
+ "$name": "简体中文",
+ "All Sessions": "全部会话",
+ "{} min ago": "{} 分钟前"
+}
+```
+
+- The key is the exact English text as it appears in the app. Anything the pack
+ doesn't cover falls back to English, so a partial translation is fine and
+ shipping one never breaks the UI.
+- `$name` is the language's own name for itself; it's what the picker in
+ **Settings → General → Language** shows.
+- The file name is the BCP 47 tag: `zh-Hans.json`, `ja.json`, `de.json`,
+ `pt-BR.json`. Wake matches the system language against it (exact tag, then
+ tag prefix, then the primary language code — with the script subtag honoured
+ for Chinese, so `zh-TW` never falls into a Simplified pack).
+- English is a pack too (`en.json`, which carries only `$name` because the keys
+ are already English). There is no special case for it: dropping your own
+ `en.json` into the config directory rewrites the English wording.
+
+## Adding a language
+
+**Without rebuilding** — drop the file into Wake's config directory and restart:
+
+| Platform | Path |
+| --- | --- |
+| macOS | `~/Library/Application Support/wake/locales/<tag>.json` |
+| Linux | `~/.config/wake/locales/<tag>.json` |
+| Windows | `%APPDATA%\wake\locales\<tag>.json` |
+
+A file there also overrides a bundled pack with the same tag, so you can correct
+a translation on your own machine without touching the app.
+
+**As a pull request** — put the file in this directory and add one row to the
+`BUNDLED` table at the top of `crates/wake/src/i18n.rs` (tag, the language's own
+name, and the `include_str!`). That's the only code change needed; everything
+else is data.
+
+## Placeholders
+
+`{}` slots are filled left to right with the values the English string carries.
+When the translation needs a different word order, use explicit indices:
+
+```json
+{ "{} to {}": "把 {1} 存到了 {0}" }
+```
+
+`{0}` is the first value, `{1}` the second. Referring to an index the English
+string doesn't provide leaves the literal `{2}` visible in the UI — a unit test
+(`translations_never_reference_missing_arguments`) fails the build on that, so
+run `cargo test -p wake` after editing a pack.
+
+Strings starting with `%` are [chrono] date formats rather than prose — translate
+them into the date order your language reads in (`"%b %-d"` → `"%-m月%-d日"`),
+keeping the `%` directives intact.
+
+[chrono]: https://docs.rs/chrono/latest/chrono/format/strftime/index.html
diff --git a/crates/wake/locales/en.json b/crates/wake/locales/en.json
new file mode 100644
index 0000000..f0f3058
--- /dev/null
+++ b/crates/wake/locales/en.json
@@ -0,0 +1,3 @@
+{
+ "$name": "English"
+}
diff --git a/crates/wake/locales/zh-Hans.json b/crates/wake/locales/zh-Hans.json
new file mode 100644
index 0000000..b94e105
--- /dev/null
+++ b/crates/wake/locales/zh-Hans.json
@@ -0,0 +1,310 @@
+{
+ " Copy Session ID": " 拷贝会话 ID",
+ " Export as Markdown": " 导出为 Markdown",
+ "$name": "简体中文",
+ "%-I:%M %p": "%H:%M",
+ "%B": "%-m月",
+ "%B %Y": "%Y年%-m月",
+ "%b": "%-m月",
+ "%b %-d": "%-m月%-d日",
+ "%b %-d, %Y": "%Y年%-m月%-d日",
+ "%b %Y": "%Y年%-m月",
+ "12 AM": "凌晨 12 点",
+ "12 PM": "中午 12 点",
+ "About": "关于",
+ "About Wake": "关于 Wake",
+ "Active days": "活跃天数",
+ "Activity": "活动",
+ "Add": "添加",
+ "Add a local session location to get started.": "先添加一个本地会话位置。",
+ "Add a location": "添加位置",
+ "Add host": "添加主机",
+ "Add location": "添加位置",
+ "Add remote host": "添加远程主机",
+ "Agent": "Agent",
+ "Agents": "Agent",
+ "Agents get four read-only tools: search, recent sessions, transcripts, projects.": "Agent 会获得四个只读工具:搜索、最近会话、转录、项目。",
+ "All Sessions": "全部会话",
+ "All your AI agent sessions, in one place.": "所有 AI agent 会话,集中在一处。",
+ "Appearance": "外观",
+ "Ascending": "升序",
+ "Building your library": "正在建立会话库",
+ "Built with ❤️ by ": "❤️ 由 ",
+ "Busiest {} ({})": "最忙 {}({})",
+ "By hour": "按小时",
+ "By month": "按月份",
+ "By weekday": "按星期",
+ "Cancel": "取消",
+ "Check Again": "再次检查",
+ "Check GitHub Releases for a newer version.": "到 GitHub Releases 查看是否有新版本。",
+ "Check for Updates": "检查更新",
+ "Check for Updates…": "检查更新…",
+ "Checking GitHub Releases…": "正在检查 GitHub Releases…",
+ "Checking…": "正在检查…",
+ "Choose": "选择",
+ "Choose a folder": "选择文件夹",
+ "Choose where Wake looks for local agent sessions.": "选择 Wake 查找本地 agent 会话的位置。",
+ "Close": "关闭",
+ "Close Window": "关闭窗口",
+ "Compared with the 7 days before": "与之前 7 天相比",
+ "Connect": "连接",
+ "Context compacted": "上下文已压缩",
+ "Copied": "已拷贝",
+ "Copy": "拷贝",
+ "Copy SSH command": "拷贝 SSH 命令",
+ "Copy code": "拷贝代码",
+ "Copy full {}": "拷贝完整{}",
+ "Copy image": "拷贝图片",
+ "Copy path": "拷贝路径",
+ "Copy the SSH command that resumes this session on its host": "拷贝可在其主机上恢复此会话的 SSH 命令",
+ "Couldn't add remote host: {}": "无法添加远程主机:{}",
+ "Couldn't check for updates. Check your connection and try again.": "检查更新失败。请检查网络后重试。",
+ "Couldn't load this session": "无法载入此会话",
+ "Couldn't remove remote host: {}": "无法移除远程主机:{}",
+ "Couldn't save appearance: {}": "无法保存外观设置:{}",
+ "Couldn't save language: {}": "无法保存语言设置:{}",
+ "Couldn't save the image": "无法存储图片",
+ "Couldn't update location: {}": "无法更新位置:{}",
+ "Couldn't update remote host": "无法更新远程主机",
+ "Created {}": "创建于 {}",
+ "Customize how Wake looks and reads.": "自定义 Wake 的外观与语言。",
+ "Cut": "剪切",
+ "Dark": "深色",
+ "Data": "数据",
+ "Date created": "创建时间",
+ "Date updated": "更新时间",
+ "Delete failed: {}": "删除失败:{}",
+ "Delete this session tree?": "删除此会话树?",
+ "Delete this session?": "删除此会话?",
+ "Descending": "降序",
+ "Disable host": "停用主机",
+ "Disable location": "停用位置",
+ "Earlier this week": "本周早些时候",
+ "Edit": "编辑",
+ "Edit location": "编辑位置",
+ "Edit…": "编辑…",
+ "Enable host": "启用主机",
+ "Enable location": "启用位置",
+ "Enter an absolute folder path": "请输入绝对路径",
+ "Export failed": "导出失败",
+ "Exported": "已导出",
+ "Failed to parse {} session data: {}": "解析 {} 会话数据失败:{}",
+ "File": "文件",
+ "First {} characters": "前 {} 个字符",
+ "Folder": "文件夹",
+ "Folder not found": "找不到文件夹",
+ "Follow the system language, or pick one.": "跟随系统语言,或自行选择。",
+ "Follow the system or keep Wake light or dark.": "跟随系统,或固定浅色/深色。",
+ "Fri": "周五",
+ "Fridays": "周五",
+ "General": "通用",
+ "Hide": "隐藏",
+ "Hide Others": "隐藏其他",
+ "Hide Wake": "隐藏 Wake",
+ "Host": "主机",
+ "Host must be an SSH alias or user@host (letters, digits, . _ - @)": "主机必须是 SSH 别名或 user@host(字母、数字、. _ - @)",
+ "Image copied": "图片已拷贝",
+ "Image omitted": "图片已省略",
+ "Input": "输入",
+ "Input preview": "输入预览",
+ "Insights": "统计",
+ "Just now": "刚刚",
+ "Keep Wake up to date.": "保持 Wake 为最新版本。",
+ "Language": "语言",
+ "Last 7 days": "最近 7 天",
+ "Less": "少",
+ "Let your coding agents look up your past sessions from Wake.": "让你的 coding agent 从 Wake 查阅过往会话。",
+ "Light": "浅色",
+ "Live updates off": "实时更新已关闭",
+ "Loading session…": "正在载入会话…",
+ "Location added": "位置已添加",
+ "Location disabled": "位置已停用",
+ "Location enabled": "位置已启用",
+ "Location removed": "位置已移除",
+ "Location updated": "位置已更新",
+ "Locations": "位置",
+ "Locations restored to defaults": "位置已恢复默认",
+ "Longest {} days": "最长 {} 天",
+ "Looking for local agent sessions…": "正在查找本地 agent 会话…",
+ "MCP server": "MCP 服务器",
+ "Main Window": "主窗口",
+ "Matches natural language and code, like \"useEffect(\".": "自然语言与代码都能匹配,例如 \"useEffect(\"。",
+ "Message count": "消息数",
+ "Minimize": "最小化",
+ "Models": "模型",
+ "Mon": "周一",
+ "Mondays": "周一",
+ "More": "多",
+ "Most active around {}": "最常在 {}",
+ "Most active in {}": "最常在 {}",
+ "Most active on {}": "最常在{}",
+ "Move to Recycle Bin": "移到回收站",
+ "Move to Trash": "移到废纸篓",
+ "New this week": "本周新增",
+ "Next view": "下一个视图",
+ "No activity": "没有活动",
+ "No activity yet": "还没有活动记录",
+ "No matching sessions": "没有匹配的会话",
+ "No newer release is available (latest: {}).": "没有更新的版本(最新:{})。",
+ "No prompts": "没有提问",
+ "No remote hosts yet. Add one to mirror its sessions into Wake.": "还没有远程主机。添加一台即可把它的会话镜像进 Wake。",
+ "No results for \"{}\"": "没有找到 \"{}\"",
+ "No session selected": "未选择会话",
+ "No terminal application found on PATH": "PATH 中没有找到终端应用",
+ "No tool calls": "无工具调用",
+ "No {} adapter is available for this session path.": "此会话路径没有可用的 {} 适配器。",
+ "Not detected": "未检测到",
+ "Not found next to the Wake app — reinstall Wake, or build it with `cargo build -p wake-core --bin wake-mcp`": "未在 Wake 应用旁找到 —— 请重新安装 Wake,或用 `cargo build -p wake-core --bin wake-mcp` 自行构建",
+ "Only the local file is removed — Codex's own records stay intact.": "只会删除本地文件 —— Codex 自己的记录不受影响。",
+ "Open this session": "打开此会话",
+ "Open this session in {}": "在 {} 中打开此会话",
+ "Open this session in…": "打开此会话于…",
+ "Opened in terminal: {}": "已在终端中打开:{}",
+ "Other": "其他",
+ "Output": "输出",
+ "Over time": "随时间变化",
+ "Paste": "粘贴",
+ "Pick one from the list, or press {} to search.": "从列表里选一个,或按 {} 搜索。",
+ "Pin": "置顶",
+ "Pinned": "已置顶",
+ "Preview unavailable": "无法预览",
+ "Previous view": "上一个视图",
+ "Projects": "项目",
+ "Prompts": "提问",
+ "Prompts per week by agent": "各 agent 每周提问数",
+ "Prompts per week by agent · {} leads this week": "各 agent 每周提问数 · 本周 {} 领先",
+ "Prompts you sent, day by day": "你逐日发出的提问",
+ "Quit Wake": "退出 Wake",
+ "Recycle Bin": "回收站",
+ "Redo": "重做",
+ "Refresh Sessions": "刷新会话",
+ "Refresh failed: {}": "刷新失败:{}",
+ "Refresh sessions": "刷新会话",
+ "Refresh sessions to see your activity here.": "刷新会话后这里会显示你的活动。",
+ "Refreshing {}/{}": "正在刷新 {}/{}",
+ "Refreshing…": "正在刷新…",
+ "Remote host disabled": "远程主机已停用",
+ "Remote host enabled": "远程主机已启用",
+ "Remote host removed": "远程主机已移除",
+ "Remote hosts": "远程主机",
+ "Remote sessions are read-only — files stay on the remote host": "远程会话只读 —— 文件仍留在远程主机上",
+ "Remove": "移除",
+ "Remove failed": "移除失败",
+ "Remove {}?": "移除 {}?",
+ "Restore defaults": "恢复默认",
+ "Restore failed": "恢复失败",
+ "Resume failed": "恢复失败",
+ "Reveal in File Explorer": "在文件资源管理器中显示",
+ "Reveal in File Manager": "在文件管理器中显示",
+ "Reveal in Finder": "在访达中显示",
+ "SSH command copied: {}": "已拷贝 SSH 命令:{}",
+ "Same as last week": "与上周持平",
+ "Sat": "周六",
+ "Saturdays": "周六",
+ "Save": "存储",
+ "Save failed: {}": "保存失败:{}",
+ "Save image": "存储图片",
+ "Save original image": "存储原图",
+ "Saved": "已存储",
+ "Scope: all sessions": "范围:全部会话",
+ "Search everything — prose or code": "搜索全部内容 —— 文字或代码",
+ "Search full conversation text": "搜索完整对话文本",
+ "Search sessions": "搜索会话",
+ "See where Wake stores local data. Sessions refresh automatically.": "查看 Wake 的本地数据位置。会话会自动刷新。",
+ "Select All": "全选",
+ "Session locations": "会话位置",
+ "Session moved to Recycle Bin": "会话已移到回收站",
+ "Session moved to Trash": "会话已移到废纸篓",
+ "Sessions": "会话",
+ "Sessions refreshed": "会话已刷新",
+ "Settings": "设置",
+ "Settings…": "设置…",
+ "Setup guide": "配置指南",
+ "Short query — using fallback search. Longer keywords are faster.": "关键词太短,已改用回退搜索。词长一些会更快。",
+ "Show": "显示",
+ "Show All": "全部显示",
+ "Show in File Explorer": "在文件资源管理器中显示",
+ "Show in File Manager": "在文件管理器中显示",
+ "Show in Finder": "在访达中显示",
+ "Since {}": "自 {} 起",
+ "Sort by {} · {}": "排序:{} · {}",
+ "Star": "收藏",
+ "Starred": "已收藏",
+ "Storage": "存储",
+ "Sun": "周日",
+ "Sundays": "周日",
+ "Sync failed: {}": "同步失败:{}",
+ "Sync now": "立即同步",
+ "Syncing sessions from {}…": "正在从 {} 同步会话…",
+ "Syncing {} remote hosts…": "正在同步 {} 台远程主机…",
+ "Syncing {}…": "正在同步 {}…",
+ "Syncing…": "正在同步…",
+ "System": "跟随系统",
+ "The session file will be moved to Trash. You can restore it anytime:": "会话文件将被移到废纸篓,随时可以还原:",
+ "The session file will be moved to the Recycle Bin. You can restore it anytime:": "会话文件将被移到回收站,随时可以还原:",
+ "Thinking": "思考",
+ "This folder is already in Wake's session locations": "该文件夹已在 Wake 的会话位置中",
+ "This session and {} nested session will be moved to {}. You can restore them anytime:": "此会话及其 {0} 个子会话将被移到{1},随时可以还原:",
+ "This session and {} nested sessions will be moved to {}. You can restore them anytime:": "此会话及其 {0} 个子会话将被移到{1},随时可以还原:",
+ "Thu": "周四",
+ "Thursdays": "周四",
+ "Today": "今天",
+ "Toggle Full Screen": "切换全屏",
+ "Tokens": "Token",
+ "Transcript limit reached": "已达转录上限",
+ "Trash": "废纸篓",
+ "Try Again": "重试",
+ "Try a different agent, project, or filter.": "换个 agent、项目或筛选条件试试。",
+ "Try a different or shorter query.": "换个词或用更短的关键词试试。",
+ "Tue": "周二",
+ "Tuesdays": "周二",
+ "Undated": "无日期",
+ "Undo": "撤销",
+ "Unknown project": "未知项目",
+ "Unpin": "取消置顶",
+ "Unstar": "取消收藏",
+ "Updated {}": "更新于 {}",
+ "Updates": "更新",
+ "Version {}": "版本 {}",
+ "View Update": "查看更新",
+ "Wake Settings": "Wake 设置",
+ "Wake couldn't open or rebuild its index at {}. {}": "Wake 无法在 {} 打开或重建索引。{}",
+ "Wake couldn't {} its window: {}": "Wake 无法{}窗口:{}",
+ "Wake data": "Wake 数据",
+ "Wake {} is available. Open the release page to download it.": "Wake {} 已发布。打开发布页即可下载。",
+ "Wed": "周三",
+ "Wednesdays": "周三",
+ "Week of {} · {}": "{} 当周 · {}",
+ "When you talk to your agents": "你与 agent 交流的时段",
+ "Yesterday": "昨天",
+ "Your coding agent activity": "你的 coding agent 活动",
+ "Your library is empty": "会话库还是空的",
+ "Zoom": "缩放",
+ "alias from ~/.ssh/config, or user@host": "~/.ssh/config 里的别名,或 user@host",
+ "esc close": "esc 关闭",
+ "open": "打开",
+ "reopen": "重新打开",
+ "the Recycle Bin": "回收站",
+ "{} AM": "上午 {} 点",
+ "{} PM": "下午 {} 点",
+ "{} failed": "{} 个失败",
+ "{} messages": "{} 条消息",
+ "{} min ago": "{} 分钟前",
+ "{} nested session": "{0} 个子会话",
+ "{} nested sessions": "{0} 个子会话",
+ "{} prompt": "{} 次提问",
+ "{} prompts": "{} 次提问",
+ "{} session": "{} 个会话",
+ "{} sessions": "{} 个会话",
+ "{} sessions moved to Recycle Bin": "{} 个会话已移到回收站",
+ "{} sessions moved to Trash": "{} 个会话已移到废纸篓",
+ "{} to {}": "{} 到 {}",
+ "{} tokens": "{} Token",
+ "{} tool calls": "{} 次工具调用",
+ "{} · never synced": "{} · 从未同步",
+ "{} · synced {}": "{} · {}同步",
+ "{}% vs last week": "较上周 {}%",
+ "{}-day streak": "连续 {} 天",
+ "↑↓ navigate": "↑↓ 切换",
+ "↩ open": "↩ 打开"
+}
diff --git a/crates/wake/src/format.rs b/crates/wake/src/format.rs
index 61177de..8248885 100644
--- a/crates/wake/src/format.rs
+++ b/crates/wake/src/format.rs
@@ -1,3 +1,4 @@
+use crate::i18n::t;
use chrono::{DateTime, Datelike, Duration, Local, TimeZone};
use unicode_segmentation::UnicodeSegmentation as _;
use unicode_width::UnicodeWidthStr as _;
@@ -48,17 +49,17 @@ fn smart_time_from(ts: i64, now: &DateTime<Local>) -> String {
let diff = now.timestamp_millis() - ts;
const MIN: i64 = 60_000;
if (0..MIN).contains(&diff) {
- "Just now".to_string()
+ t("Just now").to_string()
} else if (MIN..60 * MIN).contains(&diff) {
- format!("{} min ago", diff / MIN)
+ crate::tf!("{} min ago", diff / MIN)
} else if dt.date_naive() == now.date_naive() {
- dt.format("%-I:%M %p").to_string()
+ dt.format(t("%-I:%M %p")).to_string()
} else if dt.date_naive() == now.date_naive() - Duration::days(1) {
- "Yesterday".to_string()
+ t("Yesterday").to_string()
} else if dt.year() == now.year() {
- dt.format("%b %-d").to_string()
+ dt.format(t("%b %-d")).to_string()
} else {
- dt.format("%b %-d, %Y").to_string()
+ dt.format(t("%b %-d, %Y")).to_string()
}
}
@@ -83,7 +84,7 @@ pub fn month_year(ts: i64) -> String {
Local
.timestamp_millis_opt(ts)
.single()
- .map(|dt| dt.format("%b %Y").to_string())
+ .map(|dt| dt.format(t("%b %Y")).to_string())
.unwrap_or_default()
}
diff --git a/crates/wake/src/i18n.rs b/crates/wake/src/i18n.rs
new file mode 100644
index 0000000..ad87f41
--- /dev/null
+++ b/crates/wake/src/i18n.rs
@@ -0,0 +1,627 @@
+//! Wake 的多语言层。
+//!
+//! **key 就是英文原文**:漏翻译天然回退英文(查不到即返回 key 自身),改文案
+//! 不必同步改 key,代码里读到的还是那句话。代价是同一英文在两处需要不同译文时
+//! 会撞——真撞上再给其中一处加消歧后缀,别提前发明符号 key 体系。
+//!
+//! `t()` 返回 `&'static str` 而非 String/SharedString:调用点是 `.child("Settings")`
+//! → `.child(t("Settings"))` 的**原地替换**,所有既有签名(`label: &'static str`
+//! 这类)一字不改。代价是译文串要 leak——语言表整表 leak,切一次语言泄漏一份
+//! (几十 KB),而切语言是罕见操作(`set_language` 另有同档位早退)。
+//!
+//! ## 加一门语言
+//!
+//! 两条路,都不需要动这个文件之外的逻辑:
+//! - **提 PR**:`crates/wake/locales/<BCP47>.json`,再在下面 `BUNDLED` 加一行。
+//! - **不重编译**:把同样的 JSON 丢进 `<config dir>/wake/locales/<BCP47>.json`,
+//! 重启即出现在 Settings 的语言列表里;同 tag 的外部文件整体顶掉内嵌那份。
+//!
+//! JSON 是平铺的 `{"英文原文": "译文"}`,另有一个 `"$name"` 给这门语言的自称。
+//! **英文自己也是一个语言包**(`locales/en.json`,只有 `$name`)——这样"一门语言
+//! 就是一个 JSON 文件"没有例外,`available()` 不必给英文开后门,用户也能靠
+//! `<config dir>/wake/locales/en.json` 改写英文原文。
+
+use std::collections::HashMap;
+use std::fmt::Write as _;
+use std::sync::RwLock;
+
+use gpui::App;
+
+/// 内嵌语言包:(BCP 47 tag, 这门语言的自称, JSON 正文)。社区加语言在这里
+/// 登记一行,文件放 `crates/wake/locales/`。
+///
+/// 自称写在这里而不是只放在 JSON 里,是为了让**发现**不必解析:启动时
+/// `available()` 要列出每门语言的名字,若从 JSON 里取就得把每个包都完整
+/// parse 一遍再全部丢掉(只为一个字段),随社区包增多线性变慢。JSON 里的
+/// `$name` 仍然保留且必须一致(测试卡住),外部包就靠它。
+const BUNDLED: &[(&str, &str, &str)] = &[
+ ("en", "English", include_str!("../locales/en.json")),
+ ("zh-Hans", "简体中文", include_str!("../locales/zh-Hans.json")),
+];
+
+/// 语言包里 native name 的保留 key(`$` 前缀不会与任何 UI 文案撞)
+const NAME_KEY: &str = "$name";
+
+/// prefs 文件名。内容是 tag,或 `system` = 跟随系统
+const PREF: &str = "language";
+
+/// 一门可选语言:tag 是 BCP 47(`zh-Hans`),name 是它的自称(`简体中文`)
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub struct Locale {
+ pub tag: &'static str,
+ pub name: &'static str,
+}
+
+type Table = HashMap<&'static str, &'static str>;
+
+/// 当前生效的语言:tag 与它的译文表恒同生同死,所以是一个 static 而不是两个。
+/// None = 英文原文——**空表也归到这里**(英文包本身、以及坏掉的包),于是
+/// `t()` 在英文下连哈希都不查
+static ACTIVE: RwLock<Option<(&'static str, &'static Table)>> = RwLock::new(None);
+
+/// 装表的次数。UI 里凡是**缓存过译文**的地方(列表的日期分组标签、输入框
+/// 的 placeholder)都要记下取用时的代次,变了就重算——`refresh_windows()`
+/// 只触发重绘,不会让已经存进 entity 的字符串跟着变
+static GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// 当前语言代次,见 `GENERATION`
+pub fn generation() -> u64 {
+ GENERATION.load(std::sync::atomic::Ordering::Relaxed)
+}
+
+/// 翻译一句 UI 文案。查不到就是英文原文——**永远不会显示 key 名**
+pub fn t(key: &'static str) -> &'static str {
+ match *ACTIVE.read().expect("i18n table") {
+ Some((_, table)) => table.get(key).copied().unwrap_or(key),
+ None => key,
+ }
+}
+
+/// 带参数的文案。占位符 `{}` 按顺序取参、`{0}`/`{1}` 按下标取参
+/// ——译文语序与英文不同时用下标形式重排,不必迁就英文的参数顺序。
+/// 认不出的花括号内容(`{foo}`)原样输出。
+pub fn tf(key: &'static str, args: &[&dyn std::fmt::Display]) -> String {
+ let template = t(key);
+ let mut out = String::with_capacity(template.len() + args.len() * 8);
+ let mut next = 0usize;
+ let mut rest = template;
+ while let Some(open) = rest.find('{') {
+ out.push_str(&rest[..open]);
+ let after = &rest[open + 1..];
+ let Some(close) = after.find('}') else {
+ // 没有闭合花括号:剩下的全是普通文本
+ out.push_str(&rest[open..]);
+ return out;
+ };
+ let slot = &after[..close];
+ let picked = if slot.is_empty() {
+ let ix = next;
+ next += 1;
+ args.get(ix)
+ } else if let Ok(ix) = slot.parse::<usize>() {
+ args.get(ix)
+ } else {
+ None
+ };
+ match picked {
+ // 直接写进 out:`arg.to_string()` 会为每个参数多分配一个临时 String
+ Some(arg) => {
+ let _ = write!(out, "{arg}");
+ }
+ // 越界或非占位:原样保留,别把 UI 变成空白
+ None => {
+ out.push('{');
+ out.push_str(slot);
+ out.push('}');
+ }
+ }
+ rest = &after[close + 1..];
+ }
+ out.push_str(rest);
+ out
+}
+
+/// 英语的单复数:`n == 1` 取 one 支,否则取 other 支。两支都是完整句子
+/// (`"{} session"` / `"{} sessions"`),中文两条译成同一句即可
+pub fn tp(one: &'static str, other: &'static str, n: i64, args: &[&dyn std::fmt::Display]) -> String {
+ tf(if n == 1 { one } else { other }, args)
+}
+
+/// `tf` 的调用糖:`tf!("{} messages", n)`
+#[macro_export]
+macro_rules! tf {
+ ($key:literal $(, $arg:expr)* $(,)?) => {
+ $crate::i18n::tf($key, &[$(&$arg),*])
+ };
+}
+
+/// `tp` 的调用糖:`tp!("{} session", "{} sessions", n)`。
+/// **计数即第一个参数**——它总要出现在句子里,分开写就是把同一个值传两遍。
+/// 译文要把它挪到别处用 `{0}`(见 `tf` 的下标占位)
+#[macro_export]
+macro_rules! tp {
+ ($one:literal, $other:literal, $n:expr $(, $arg:expr)* $(,)?) => {{
+ let n = $n;
+ $crate::i18n::tp($one, $other, n as i64, &[&n $(, &$arg)*])
+ }};
+}
+
+// ---------------- 语言包发现与加载 ----------------
+
+/// 用户语言包目录 `<config dir>/wake/locales/`
+fn user_dir() -> Option<std::path::PathBuf> {
+ crate::prefs::dir().map(|dir| dir.join("locales"))
+}
+
+/// 一门语言的原始 JSON 文本:用户目录优先(同 tag 整体顶掉内嵌那份,
+/// 允许用户在本机覆盖官方翻译),否则用内嵌的
+fn source_for(tag: &str) -> Option<String> {
+ if let Some(dir) = user_dir() {
+ if let Ok(text) = std::fs::read_to_string(dir.join(format!("{tag}.json"))) {
+ return Some(text);
+ }
+ }
+ BUNDLED
+ .iter()
+ .find(|(bundled, ..)| *bundled == tag)
+ .map(|(.., text)| (*text).to_string())
+}
+
+/// 解析一个语言包。**坏包给空表而不是消失**:JSON 语法错、顶层不是对象、
+/// 值不是字符串——这些都退化成"这门语言的这些句子还是英文",而不是让整门
+/// 语言从选择器里蒸发(那种失败是静默的,用户只会看见语言列表少了一项)
+fn parse(text: &str) -> HashMap<String, String> {
+ let Ok(serde_json::Value::Object(object)) = serde_json::from_str(text) else {
+ return HashMap::new();
+ };
+ object
+ .into_iter()
+ .filter_map(|(k, v)| Some((k, v.as_str()?.to_string())))
+ .collect()
+}
+
+/// 语言列表要活到进程结束,tag 与 native name 都 leak 成 'static
+fn leak(text: String) -> &'static str {
+ Box::leak(text.into_boxed_str())
+}
+
+/// 可选语言 = 内嵌 ∪ 用户目录里的 `*.json`(同 tag 由用户目录顶掉),按 tag
+/// 字典序。
+///
+/// **只扫一次**:tag 与 native name 都要 leak 成 'static,而语言选择器在
+/// Settings 的 render 路径上(每帧调),不缓存就是每帧漏几十字节。代价是
+/// 运行中往 locales/ 丢的新语言包要重启才出现——README 就是这么写的
+pub fn available() -> &'static [Locale] {
+ static CACHE: std::sync::OnceLock<Vec<Locale>> = std::sync::OnceLock::new();
+ CACHE.get_or_init(scan_available)
+}
+
+fn scan_available() -> Vec<Locale> {
+ let mut out: Vec<Locale> = BUNDLED
+ .iter()
+ .map(|(tag, name, _)| Locale { tag, name })
+ .collect();
+ // 用户目录:同 tag 覆盖内嵌那份的自称,新 tag 追加。只有这一支要解析
+ // JSON,而且只为取 `$name`(内嵌包的自称在 BUNDLED 里,零解析)
+ let entries = user_dir()
+ .and_then(|dir| std::fs::read_dir(dir).ok())
+ .into_iter()
+ .flatten()
+ .flatten();
+ for entry in entries {
+ let path = entry.path();
+ if path.extension().is_none_or(|ext| ext != "json") {
+ continue;
+ }
+ let (Some(stem), Ok(text)) = (
+ path.file_stem().and_then(|s| s.to_str()),
+ std::fs::read_to_string(&path),
+ ) else {
+ continue;
+ };
+ let name = parse(&text)
+ .remove(NAME_KEY)
+ .map_or_else(|| leak(stem.to_string()), leak);
+ match out.iter_mut().find(|locale| locale.tag == stem) {
+ Some(existing) => existing.name = name,
+ None => out.push(Locale {
+ tag: leak(stem.to_string()),
+ name,
+ }),
+ }
+ }
+ out.sort_by_key(|locale| locale.tag);
+ out
+}
+
+// ---------------- 系统语言匹配 ----------------
+
+/// `zh-CN` 这类只带地区的 tag 推断书写系统——中文用户的系统 locale 绝大多数是
+/// `zh-Hans-CN`/`zh-CN`/`zh-TW`,不补这一步就会把 zh-TW 匹配给简体包。
+/// **入参必须已是小写**(调用方都已 lowercase,别在这里再转一次)。
+///
+/// 只认中文是有意的:安全属性是"zh-TW 绝不落进简体包",而更一般的规则
+/// (带 script 子标签的包不参与主码回退)会连 `zh-CN` → 简体一起打掉,
+/// 那是最常见的中文系统。地区→书写系统本就是 CLDR 数据,推不出来。
+/// 第二门有简繁之分的语言(`sr-Cyrl`/`sr-Latn`)出现时,把这份知识挪进语言包
+/// (`"$match": ["zh-Hans", "zh-CN", "zh-SG"]`),`match_system` 就不必认识任何语言了
+fn script_hint(lower: &str) -> Option<&'static str> {
+ let (lang, region) = lower.split_once('-')?;
+ if lang != "zh" {
+ return None;
+ }
+ match region.split('-').next_back().unwrap_or(region) {
+ "cn" | "sg" | "my" | "hans" => Some("hans"),
+ "tw" | "hk" | "mo" | "hant" => Some("hant"),
+ _ => None,
+ }
+}
+
+fn primary(tag: &str) -> &str {
+ tag.split('-').next().unwrap_or(tag)
+}
+
+/// 把系统 locale 匹配到一门已装语言。没有匹配 = 英文
+fn match_system(locale: &str, choices: &[Locale]) -> Option<&'static str> {
+ let want = locale.to_ascii_lowercase();
+ let lower = |choice: &Locale| choice.tag.to_ascii_lowercase();
+ // ① 完全相等。**必须自成一轮**:choices 按 tag 排序,`en` 排在 `en-GB`
+ // 前面,和前缀判据混在同一轮里就会让装了 en-GB 的人永远匹配到 en
+ // (pt / pt-BR 同理)
+ if let Some(choice) = choices.iter().find(|choice| lower(choice) == want) {
+ return Some(choice.tag);
+ }
+ // ② 语言包 tag 是系统 locale 的前缀(zh-Hans ⊂ zh-Hans-CN);多个都匹配
+ // 时取最长的,即最具体的那个
+ if let Some(choice) = choices
+ .iter()
+ .filter(|choice| want.starts_with(&format!("{}-", lower(choice))))
+ .max_by_key(|choice| choice.tag.len())
+ {
+ return Some(choice.tag);
+ }
+ // ③ 主语言码相同;中文另按书写系统裁一刀,免得 zh-TW 落进简体包
+ let hint = script_hint(&want);
+ let mut fallback = None;
+ for choice in choices {
+ let tag = lower(choice);
+ if primary(&tag) != primary(&want) {
+ continue;
+ }
+ match hint {
+ Some(script) if tag.contains(script) => return Some(choice.tag),
+ Some(_) => continue,
+ None => fallback = fallback.or(Some(choice.tag)),
+ }
+ }
+ fallback
+}
+
+/// gpui-component 自带组件(日期选择器、颜色选择器等)的语言。它的 tag 体系
+/// 与我们的语言包不同名(en / zh-CN / zh-HK / zh-TW / it),按主语言码加书写
+/// 系统映射;没有对应的就退英文——组件文案是英文、Wake 自己的文案仍是译文,
+/// 比整个界面回退英文强
+fn component_locale(tag: Option<&str>) -> &'static str {
+ let Some(tag) = tag else { return "en" };
+ let lower = tag.to_ascii_lowercase();
+ match primary(&lower) {
+ "zh" if script_hint(&lower) == Some("hant") => "zh-TW",
+ "zh" => "zh-CN",
+ "it" => "it",
+ _ => "en",
+ }
+}
+
+// ---------------- 偏好读写与应用 ----------------
+
+/// 用户选定的语言;None = 跟随系统。**显式选的英文是 `Some(en)`**,与跟随
+/// 系统区别开:系统语言是中文时两者结果不同。落盘的 `system` 不等于任何
+/// tag,所以不必单独判
+pub fn preference() -> Option<Locale> {
+ let saved = crate::prefs::read(PREF)?;
+ available().iter().copied().find(|l| l.tag == saved)
+}
+
+/// 当前实际生效的 tag(None = 英文原文)
+fn active() -> Option<&'static str> {
+ ACTIVE.read().expect("i18n active").map(|(tag, _)| tag)
+}
+
+/// `%` 开头的 key 是 chrono 模板不是散文。译文写坏了不是"显示得难看"——
+/// `dt.format(坏模板).to_string()` 会 panic(实测 `%Q`:Display 返回 Err,
+/// `to_string` 直接炸),而外部语言包是用户随手丢进 locales/ 的文件,没有
+/// 任何一步会先看它一眼。丢掉这一条即回退英文模板
+fn usable(key: &str, value: &str) -> bool {
+ use chrono::format::{Item, StrftimeItems};
+ !key.starts_with('%') || !StrftimeItems::new(value).any(|item| item == Item::Error)
+}
+
+/// 偏好 → 实际该装哪门语言。**跟随系统(None)不等于"没有语言"**,而是
+/// "由 sys_locale 现算"——把这一步只放在 `init()` 里,运行时从 English 切回
+/// 跟随系统就会掉成英文原文,得重启才回得到系统语言
+fn resolve(preference: Option<&'static str>) -> Option<&'static str> {
+ match preference {
+ Some(tag) => Some(tag),
+ None => sys_locale::get_locale()
+ .as_deref()
+ .and_then(|locale| match_system(locale, available())),
+ }
+}
+
+/// 装载一门语言的译文表;None 卸回英文
+fn load(tag: Option<&'static str>) {
+ let loaded = tag.and_then(|tag| {
+ let table: Table = parse(&source_for(tag)?)
+ .into_iter()
+ .filter(|(k, v)| k != NAME_KEY && usable(k, v))
+ .map(|(k, v)| (leak(k), leak(v)))
+ .collect();
+ // 空表(英文包本身,或坏掉的包)当没装:`t()` 少一次哈希查询
+ (!table.is_empty()).then(|| (tag, &*Box::leak(Box::new(table))))
+ });
+ *ACTIVE.write().expect("i18n table") = loaded;
+ GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+}
+
+/// 启动时调用一次。**必须在建任何窗口/菜单之前**——菜单栏文案是 `set_menus`
+/// 时求值的,晚一步就是一栏英文菜单配中文界面
+pub fn init() {
+ // 存过的偏好指向一门已经不在的语言包时,`preference()` 给 None,于是
+ // 跟着系统走——与选择器那时显示的 "System" 一致
+ load(resolve(preference().map(|locale| locale.tag)));
+ gpui_component::set_locale(component_locale(active()));
+}
+
+/// 切语言:落盘 + 重装译文表 + 重设组件语言 + **重建菜单栏** + 全窗重绘。
+/// 五步缺一不可(菜单栏文案是 `set_menus` 那一刻求值的静态串,不重建就留着
+/// 上一门语言),所以这是唯一出口——装表那步不单独对外开放
+pub fn set_language(tag: Option<&'static str>, cx: &mut App) -> std::io::Result<()> {
+ if tag == preference().map(|locale| locale.tag) {
+ // 点的就是当前档位:别再落一次盘(UI 线程上的真实磁盘 I/O),
+ // 也别再 leak 一张几十 KB 的表
+ return Ok(());
+ }
+ crate::prefs::write(PREF, tag.unwrap_or("system").as_bytes())?;
+ load(resolve(tag));
+ gpui_component::set_locale(component_locale(active()));
+ cx.set_menus(crate::app_menus());
+ cx.refresh_windows();
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn locales() -> Vec<Locale> {
+ vec![
+ Locale { tag: "zh-Hans", name: "简体中文" },
+ Locale { tag: "zh-Hant", name: "繁體中文" },
+ Locale { tag: "ja", name: "日本語" },
+ ]
+ }
+
+ #[test]
+ fn system_locale_matches_by_prefix_and_script() {
+ let all = locales();
+ assert_eq!(match_system("zh-Hans-CN", &all), Some("zh-Hans"));
+ assert_eq!(match_system("zh-CN", &all), Some("zh-Hans"));
+ assert_eq!(match_system("zh-TW", &all), Some("zh-Hant"));
+ assert_eq!(match_system("ja-JP", &all), Some("ja"));
+ assert_eq!(match_system("en-US", &all), None);
+ // 只装了简体时,繁体系统宁可回落英文也不给简体
+ let hans = vec![all[0]];
+ assert_eq!(match_system("zh-TW", &hans), None);
+ assert_eq!(match_system("zh-CN", &hans), Some("zh-Hans"));
+ }
+
+ #[test]
+ fn component_locale_maps_our_tags_onto_gpui_components() {
+ // gpui-component 的 locales/ui.yml 只有这五个
+ assert_eq!(component_locale(Some("zh-Hans")), "zh-CN");
+ assert_eq!(component_locale(Some("zh-Hant")), "zh-TW");
+ assert_eq!(component_locale(Some("zh-TW")), "zh-TW");
+ assert_eq!(component_locale(Some("it")), "it");
+ assert_eq!(component_locale(Some("ja")), "en");
+ assert_eq!(component_locale(None), "en");
+ }
+
+ /// 通用包与地区包并存时,精确匹配必须赢。`available()` 按 tag 排序,
+ /// `en` 恒排在 `en-GB` 前面——两条判据混在一轮里就是 en-GB 永不中选
+ #[test]
+ fn exact_tag_wins_over_a_shorter_prefix() {
+ let all = vec![
+ Locale { tag: "en", name: "English" },
+ Locale { tag: "en-GB", name: "English (UK)" },
+ Locale { tag: "pt", name: "Português" },
+ Locale { tag: "pt-BR", name: "Português (Brasil)" },
+ ];
+ assert_eq!(match_system("en-GB", &all), Some("en-GB"));
+ assert_eq!(match_system("en-US", &all), Some("en"));
+ assert_eq!(match_system("pt-BR", &all), Some("pt-BR"));
+ // 前缀匹配到多个时取最具体的:en-GB-oxendict 属于 en-GB 而不是 en
+ assert_eq!(match_system("en-GB-oxendict", &all), Some("en-GB"));
+ }
+
+ /// 坏日期模板会让 `dt.format(..).to_string()` panic(Display 返回 Err),
+ /// 而外部语言包没有任何一步会先看它一眼——必须在装表时就拦掉
+ #[test]
+ fn broken_date_patterns_never_reach_the_table() {
+ assert!(usable("%b %-d", "%-m月%-d日"));
+ assert!(!usable("%b %-d", "%Q"));
+ // 散文里的 % 不是日期模板,别误伤
+ assert!(usable("{}% vs last week", "较上周 {}%"));
+ }
+
+ #[test]
+ fn missing_key_falls_back_to_english() {
+ assert_eq!(t("Never Translated"), "Never Translated");
+ }
+
+ #[test]
+ fn placeholders_fill_in_order_and_by_index() {
+ assert_eq!(tf("{} of {}", &[&3, &7]), "3 of 7");
+ assert_eq!(tf("{1} / {0}", &[&"a", &"b"]), "b / a");
+ // 参数不够/不是占位:原样保留,不把界面吃成空白
+ assert_eq!(tf("{} and {}", &[&1]), "1 and {}");
+ assert_eq!(tf("{name} stays", &[]), "{name} stays");
+ assert_eq!(tf("unclosed {", &[]), "unclosed {");
+ }
+
+ #[test]
+ fn plural_picks_branch_by_count() {
+ assert_eq!(tp("{} session", "{} sessions", 1, &[&1]), "1 session");
+ assert_eq!(tp("{} session", "{} sessions", 4, &[&4]), "4 sessions");
+ }
+
+ #[test]
+ fn broken_pack_keeps_the_language_listed() {
+ // 坏 JSON 只该让句子退回英文,不该让这门语言从选择器里消失
+ assert!(parse("{ not json").is_empty());
+ assert!(parse(r#"["array"]"#).is_empty());
+ // 非字符串值单独跳过,同一个包里的其余条目照常生效
+ let map = parse(r#"{"a": "译", "b": 3}"#);
+ assert_eq!(map.get("a").map(String::as_str), Some("译"));
+ assert!(!map.contains_key("b"));
+ }
+
+ #[test]
+ fn bundled_packs_agree_with_their_json() {
+ for (tag, name, text) in BUNDLED {
+ let map = parse(text);
+ assert!(!map.is_empty(), "{tag} is not a flat JSON object");
+ // BUNDLED 的自称是为了免解析发现而抄的一份,漂了就是选择器
+ // 显示一个名字、用户目录里同一个包显示另一个
+ assert_eq!(
+ map.get(NAME_KEY).map(String::as_str),
+ Some(*name),
+ "{tag}: BUNDLED 的自称与 {NAME_KEY} 对不上"
+ );
+ }
+ }
+
+ /// 模板引用到的最高参数下标(顺序 `{}` 也计入),None = 不带参数
+ fn max_slot(template: &str) -> Option<usize> {
+ let mut next = 0usize;
+ let mut max = None;
+ let mut rest = template;
+ while let Some(open) = rest.find('{') {
+ let after = &rest[open + 1..];
+ let Some(close) = after.find('}') else { break };
+ let slot = &after[..close];
+ let ix = if slot.is_empty() {
+ let ix = next;
+ next += 1;
+ Some(ix)
+ } else {
+ slot.parse::<usize>().ok()
+ };
+ if let Some(ix) = ix {
+ max = Some(max.map_or(ix, |m: usize| m.max(ix)));
+ }
+ rest = &after[close + 1..];
+ }
+ max
+ }
+
+ /// 译文引用的参数不能比英文原文提供的多——多出来的那个 `{2}` 不会报错,
+ /// 只会原样出现在界面上(校对时最容易漏掉的一类错)
+ #[test]
+ fn translations_never_reference_missing_arguments() {
+ for (tag, _, text) in BUNDLED {
+ for (key, value) in parse(text) {
+ if key == NAME_KEY {
+ continue;
+ }
+ let provided = max_slot(&key).map_or(0, |m| m + 1);
+ if let Some(used) = max_slot(&value) {
+ assert!(
+ used < provided,
+ "{tag}: 译文 {value:?} 用了第 {used} 个参数,但 {key:?} 只提供 {provided} 个"
+ );
+ }
+ // 认不出的花括号会原样显示,`tf` 跑一遍就能同时卡住它和落单的 `{`
+ let filled = tf_with(&value, provided);
+ assert!(
+ !filled.contains('{'),
+ "{tag}: 译文 {value:?} 里有不是占位符的花括号"
+ );
+ }
+ }
+ }
+
+ /// 拿 `provided` 个哑参数把模板填满,用于检查有没有填不掉的花括号
+ fn tf_with(template: &str, provided: usize) -> String {
+ let args: Vec<&dyn std::fmt::Display> = (0..provided).map(|_| &"x" as &dyn std::fmt::Display).collect();
+ // tf 走 t() 查表,这里要的是模板本身,故复制那几行的效果:
+ // 未装表时 t(key) == key,测试进程从不 load,恒等成立
+ tf(Box::leak(template.to_string().into_boxed_str()), &args)
+ }
+
+ /// `%` 开头的 key 是 chrono 模板不是散文,译者改的是日期顺序与时制。
+ /// `{}` 那套占位符有测试盯着,`%` 指令没有——写错只会渲染出静默的乱码
+ #[test]
+ fn date_patterns_stay_valid_chrono_formats() {
+ use chrono::format::{Item, StrftimeItems};
+ for (tag, _, text) in BUNDLED {
+ for (key, value) in parse(text) {
+ if !key.starts_with('%') {
+ continue;
+ }
+ for (which, pattern) in [("key", key.as_str()), ("译文", value.as_str())] {
+ assert!(
+ !StrftimeItems::new(pattern).any(|item| item == Item::Error),
+ "{tag}: {which} {pattern:?} 不是合法的 chrono 格式串"
+ );
+ }
+ }
+ }
+ }
+
+ /// 语言包里的死 key(英文原文改过、包里那条没跟着改)是静默的:界面
+ /// 悄悄回退英文,没人报错。扫一遍源码里的 `t("…")` / `tf!("…"` / `tp!("…"`
+ /// 把它们揪出来
+ #[test]
+ fn packs_have_no_keys_without_a_call_site() {
+ const SOURCES: &[&str] = &[
+ include_str!("workbench.rs"),
+ include_str!("settings.rs"),
+ include_str!("main.rs"),
+ include_str!("format.rs"),
+ ];
+ for (tag, _, text) in BUNDLED {
+ for key in parse(text).into_keys() {
+ if key == NAME_KEY || assembled_elsewhere(&key) {
+ continue;
+ }
+ // 源码里是字面量形式,反斜杠与引号都带着转义
+ let literal = format!("\"{}\"", key.replace('\\', r"\\").replace('"', "\\\""));
+ assert!(
+ SOURCES.iter().any(|src| src.contains(&literal)),
+ "{tag}: {key:?} 在源码里没有调用点了(英文原文改过?)"
+ );
+ }
+ }
+ }
+
+ /// 文本扫描找不到的 key:ui.rs 由 `concat!` 拼出整句(平台名词只写一次),
+ /// 开窗动词由 `t(what)` 间接传入
+ fn assembled_elsewhere(key: &str) -> bool {
+ const PREFIXES: &[&str] = &[
+ "Move to ",
+ "Session moved to ",
+ "{} sessions moved to ",
+ "The session file will be moved to ",
+ "Show in ",
+ "Reveal in ",
+ ];
+ PREFIXES.iter().any(|p| key.starts_with(p))
+ || matches!(
+ key,
+ // trash_copy! 的两个宏实参:名词本身与它在正文里的带冠形式
+ "Trash" | "Recycle Bin" | "the Recycle Bin"
+ // 开窗失败提示里的动词,由 t(what) 间接传入
+ | "open" | "reopen"
+ )
+ }
+}
diff --git a/crates/wake/src/main.rs b/crates/wake/src/main.rs
index d455f54..cdf4832 100644
--- a/crates/wake/src/main.rs
+++ b/crates/wake/src/main.rs
@@ -8,6 +8,7 @@
mod assets;
mod format;
+mod i18n;
mod main_window;
mod prefs;
mod settings;
@@ -19,6 +20,7 @@ mod workbench;
use assets::Assets;
use gpui::*;
use gpui_component::Root;
+use i18n::t;
use main_window::MainWindow;
use workbench::{
OpenAbout, OpenSettings, OpenUpdates, PaletteDown, PaletteUp, RefreshSessions, ToggleSearch,
@@ -109,12 +111,14 @@ fn open_main_window(cx: &mut App) -> anyhow::Result<WindowHandle<Root>> {
/// 可去,用户看到的就是任务栏闪一下然后什么都没有(GPU/驱动起不来、RDP 会话
/// 等都会走到这)。show_fatal_alert 会弹系统对话框,并始终先往 stderr 落一份
///(2026-08-25 review)。`what` 是 "open"/"reopen",拼进提示语
-fn open_main_window_or_exit(cx: &mut App, what: &str) -> WindowHandle<Root> {
+fn open_main_window_or_exit(cx: &mut App, what: &'static str) -> WindowHandle<Root> {
match open_main_window(cx) {
Ok(handle) => handle,
Err(e) => {
- wake_core::services::terminal::show_fatal_alert(&format!(
- "Wake couldn't {what} its window: {e}"
+ wake_core::services::terminal::show_fatal_alert(&crate::tf!(
+ "Wake couldn't {} its window: {}",
+ t(what),
+ e
));
std::process::exit(1);
}
@@ -219,59 +223,63 @@ fn key_bindings() -> Vec<KeyBinding> {
/// 菜单栏。gpui 只按这里给的生成,不补任何标准项——Edit/Window/Hide 一族在
/// macOS 上必须自己给,否则对应快捷键全是死键
-fn app_menus() -> Vec<Menu> {
+pub(crate) fn app_menus() -> Vec<Menu> {
let mac = cfg!(target_os = "macos");
let wake: Vec<MenuItem> = [
- Some(MenuItem::action("About Wake", OpenAbout)),
- mac.then(|| MenuItem::action("Check for Updates…", OpenUpdates)),
+ Some(MenuItem::action(t("About Wake"), OpenAbout)),
+ mac.then(|| MenuItem::action(t("Check for Updates…"), OpenUpdates)),
Some(MenuItem::separator()),
- Some(MenuItem::action("Settings…", OpenSettings)),
+ Some(MenuItem::action(t("Settings…"), OpenSettings)),
Some(MenuItem::separator()),
- mac.then(|| MenuItem::action("Hide Wake", Hide)),
- mac.then(|| MenuItem::action("Hide Others", HideOthers)),
- mac.then(|| MenuItem::action("Show All", ShowAll)),
+ mac.then(|| MenuItem::action(t("Hide Wake"), Hide)),
+ mac.then(|| MenuItem::action(t("Hide Others"), HideOthers)),
+ mac.then(|| MenuItem::action(t("Show All"), ShowAll)),
mac.then(MenuItem::separator),
- Some(MenuItem::action("Quit Wake", Quit)),
+ Some(MenuItem::action(t("Quit Wake"), Quit)),
]
.into_iter()
.flatten()
.collect();
let file = vec![
- MenuItem::action("Refresh Sessions", RefreshSessions),
+ MenuItem::action(t("Refresh Sessions"), RefreshSessions),
MenuItem::separator(),
- MenuItem::action("Close Window", CloseWindow),
+ MenuItem::action(t("Close Window"), CloseWindow),
];
// os_action:菜单项挂原生 cut:/copy:/paste:/selectAll: 选择器。gpui 窗口
// 在前时由 gpui 接住、派发成右侧的 action(输入框消费);系统面板(目录
// 选择器)在前时走原生响应链——没有这组菜单项,面板里的 ⌘C/⌘V 无人应答
let edit = mac.then(|| Menu {
- name: "Edit".into(),
+ name: t("Edit").into(),
items: vec![
- MenuItem::os_action("Undo", gpui_component::input::Undo, OsAction::Undo),
- MenuItem::os_action("Redo", gpui_component::input::Redo, OsAction::Redo),
+ MenuItem::os_action(t("Undo"), gpui_component::input::Undo, OsAction::Undo),
+ MenuItem::os_action(t("Redo"), gpui_component::input::Redo, OsAction::Redo),
MenuItem::separator(),
- MenuItem::os_action("Cut", gpui_component::input::Cut, OsAction::Cut),
- MenuItem::os_action("Copy", gpui_component::input::Copy, OsAction::Copy),
- MenuItem::os_action("Paste", gpui_component::input::Paste, OsAction::Paste),
+ MenuItem::os_action(t("Cut"), gpui_component::input::Cut, OsAction::Cut),
+ MenuItem::os_action(t("Copy"), gpui_component::input::Copy, OsAction::Copy),
+ MenuItem::os_action(t("Paste"), gpui_component::input::Paste, OsAction::Paste),
MenuItem::os_action(
- "Select All",
+ t("Select All"),
gpui_component::input::SelectAll,
OsAction::SelectAll,
),
],
disabled: false,
});
- // 名字必须是 "Window":gpui 据此把它登记为系统 windows menu,窗口列表由
- // AppKit 自动追加在后面。只剩 Settings 时 Dock 点击不会触发 on_reopen
- //(系统认为还有可见窗口),Main Window 是拉回主窗的唯一入口
+ // 名字必须**逐字**是 "Window",不能翻译:gpui_macos 的 create_menu_bar
+ // 里是 `if menu_config.name == "Window"` 才调 `setWindowsMenu_`,译成
+ // 「窗口」后 AppKit 就不再把它当系统窗口菜单,自动维护的已打开窗口列表
+ // 随之消失。gpui 没有「菜单标识 + 显示标题」分开的 API,所以中文界面里
+ // 这一个菜单名保持英文是当前依赖下的唯一选择(2026-09-10 Codex review;
+ // 上游给出标识位之前别动它)。只剩 Settings 时 Dock 点击不会触发
+ // on_reopen(系统认为还有可见窗口),Main Window 是拉回主窗的唯一入口
let window = mac.then(|| Menu {
name: "Window".into(),
items: vec![
- MenuItem::action("Minimize", Minimize),
- MenuItem::action("Zoom", Zoom),
- MenuItem::action("Toggle Full Screen", ToggleFullScreen),
+ MenuItem::action(t("Minimize"), Minimize),
+ MenuItem::action(t("Zoom"), Zoom),
+ MenuItem::action(t("Toggle Full Screen"), ToggleFullScreen),
MenuItem::separator(),
- MenuItem::action("Main Window", ShowMainWindow),
+ MenuItem::action(t("Main Window"), ShowMainWindow),
],
disabled: false,
});
@@ -282,7 +290,7 @@ fn app_menus() -> Vec<Menu> {
disabled: false,
}),
Some(Menu {
- name: "File".into(),
+ name: t("File").into(),
items: file,
disabled: false,
}),
@@ -302,7 +310,8 @@ fn main() {
app.on_reopen(|cx| show_main_window(cx, |_, _| {}));
app.run(move |cx: &mut App| {
gpui_component::init(cx);
- gpui_component::set_locale("en");
+ // 必须在 set_menus 与开任何窗之前:两者的文案都在构造那一刻求值
+ i18n::init();
theme::sync_appearance(None, cx);
cx.on_action(|_: &Quit, cx| cx.quit());
diff --git a/crates/wake/src/prefs.rs b/crates/wake/src/prefs.rs
index ed0acca..1d804eb 100644
--- a/crates/wake/src/prefs.rs
+++ b/crates/wake/src/prefs.rs
@@ -2,13 +2,16 @@
//! Store)建立之前就要用,都等不了库。统一目录、统一原子写法
use std::path::PathBuf;
-/// `<config dir>/wake/<name>`
-fn path(name: &str) -> PathBuf {
+/// `<config dir>/wake/`——语言包目录等也挂在它下面
+pub fn dir() -> Option<PathBuf> {
dirs::config_dir()
.or_else(dirs::data_dir)
- .unwrap_or_else(|| PathBuf::from("."))
- .join("wake")
- .join(name)
+ .map(|dir| dir.join("wake"))
+}
+
+/// `<config dir>/wake/<name>`
+fn path(name: &str) -> PathBuf {
+ dir().unwrap_or_else(|| PathBuf::from(".")).join(name)
}
/// 读整个文件并去掉首尾空白;不存在、读不到或为空 = None
diff --git a/crates/wake/src/settings.rs b/crates/wake/src/settings.rs
index 7fe6311..47b0b40 100644
--- a/crates/wake/src/settings.rs
+++ b/crates/wake/src/settings.rs
@@ -1,3 +1,4 @@
+use crate::i18n::t;
use gpui::prelude::FluentBuilder as _;
use gpui::*;
use gpui_component::button::{Button, ButtonCustomVariant, ButtonVariants as _};
@@ -13,7 +14,7 @@ use wake_core::models::AgentId;
use crate::format::tilde_path;
use crate::ui::{
overlay_layers, BUTTON_SM_H, FONT_BODY, FONT_CAPTION, FONT_DISPLAY, FONT_HEADING, FONT_LABEL,
- FONT_TITLE, RADIUS_BUTTON, SHOW_IN_FM, SPACE_LG, SPACE_MD, SPACE_SM, SPACE_XL, SPACE_XS,
+ FONT_TITLE, RADIUS_BUTTON, show_in_fm, SPACE_LG, SPACE_MD, SPACE_SM, SPACE_XL, SPACE_XS,
SPACE_XXL,
};
use crate::update::{self, UpdateStatus};
@@ -124,6 +125,7 @@ fn settings_info_card(
primary: &'static str,
details: Vec<AnyElement>,
trailing: AnyElement,
+ min_h: Pixels,
cx: &App,
) -> Div {
let theme = cx.theme();
@@ -139,7 +141,7 @@ fn settings_info_card(
.bg(theme.popover)
.child(
h_flex()
- .min_h(px(84.))
+ .min_h(min_h)
.px(SPACE_LG)
.gap(SPACE_LG)
.items_center()
@@ -286,7 +288,7 @@ impl SettingsView {
.text_size(FONT_HEADING)
.font_semibold()
.text_color(theme.sidebar_foreground)
- .child("Settings"),
+ .child(t("Settings")),
)
.child(
v_flex()
@@ -295,35 +297,35 @@ impl SettingsView {
.gap(px(2.))
.child(self.render_nav_item(
"settings-general-nav",
- "General",
+ t("General"),
"icons/settings.svg",
SettingsPage::General,
cx,
))
.child(self.render_nav_item(
"settings-locations-nav",
- "Locations",
+ t("Locations"),
"icons/hard-drive.svg",
SettingsPage::Locations,
cx,
))
.child(self.render_nav_item(
"settings-remotes-nav",
- "Remote hosts",
+ t("Remote hosts"),
"icons/server.svg",
SettingsPage::Remotes,
cx,
))
.child(self.render_nav_item(
"settings-connect-nav",
- "Connect",
+ t("Connect"),
"icons/plug.svg",
SettingsPage::Connect,
cx,
))
.child(self.render_nav_item(
"settings-data-nav",
- "Data",
+ t("Data"),
"icons/database.svg",
SettingsPage::Data,
cx,
@@ -336,14 +338,14 @@ impl SettingsView {
.gap(px(2.))
.child(self.render_nav_item(
"settings-updates-nav",
- "Updates",
+ t("Updates"),
"icons/download.svg",
SettingsPage::Updates,
cx,
))
.child(self.render_nav_item(
"settings-about-nav",
- "About",
+ t("About"),
"icons/info.svg",
SettingsPage::About,
cx,
@@ -352,6 +354,76 @@ impl SettingsView {
.into_any_element()
}
+ /// General 页的设置行:与 Data/Connect 的信息卡同一张卡,只是矮一档
+ /// (72 是 Appearance 行的用户定稿值),副行是 caption 级说明
+ fn setting_row(
+ title: &'static str,
+ subtitle: &'static str,
+ control: impl IntoElement,
+ cx: &Context<Self>,
+ ) -> AnyElement {
+ let caption = div()
+ .text_size(FONT_CAPTION)
+ .text_color(cx.theme().muted_foreground)
+ .child(subtitle)
+ .into_any_element();
+ settings_info_card(
+ title,
+ vec![caption],
+ control.into_any_element(),
+ px(72.),
+ cx,
+ )
+ .into_any_element()
+ }
+
+ /// 语言选择:System + English + 装好的语言包。选项数量随语言包增减,
+ /// 所以是下拉而不是 Appearance 那样的分段控件
+ fn language_control(&self) -> AnyElement {
+ // 直接读全局:镜像成字段就要在每个切换点写回,而 `apply_language`
+ // 改的是全局(appearance 那个字段正是这么漂的)
+ let current = crate::i18n::preference().map(|locale| locale.tag);
+ Button::new("settings-language")
+ .outline()
+ .small()
+ .rounded(RADIUS_BUTTON)
+ .label(current.map_or(t("System"), |tag| {
+ crate::i18n::available()
+ .iter()
+ .find(|locale| locale.tag == tag)
+ .map_or(t("System"), |locale| locale.name)
+ }))
+ .icon(icon("icons/chevron-down.svg").with_size(px(14.)))
+ .dropdown_menu(move |mut menu, _, _| {
+ // 选项只在菜单打开时才需要,`available()` 又是 'static 切片
+ // ——留在闭包里就不必每帧建一个 Vec 再 clone 一份进来
+ menu = menu.min_w(px(160.));
+ let options = std::iter::once((None, t("System"))).chain(
+ crate::i18n::available()
+ .iter()
+ .map(|locale| (Some(locale.tag), locale.name)),
+ );
+ for (tag, name) in options {
+ menu = menu.item(
+ PopupMenuItem::new(name)
+ .checked(tag == current)
+ .on_click(move |_, window, cx| {
+ if let Err(error) = crate::i18n::set_language(tag, cx) {
+ window.push_notification(
+ gpui_component::notification::Notification::error(
+ crate::tf!("Couldn't save language: {}", error),
+ ),
+ cx,
+ );
+ }
+ }),
+ );
+ }
+ menu
+ })
+ .into_any_element()
+ }
+
fn appearance_button(
&self,
id: &'static str,
@@ -386,9 +458,7 @@ impl SettingsView {
cx.notify();
}
Err(error) => window.push_notification(
- gpui_component::notification::Notification::error(format!(
- "Couldn't save appearance: {error}"
- )),
+ gpui_component::notification::Notification::error(crate::tf!("Couldn't save appearance: {}", error)),
cx,
),
}
@@ -414,73 +484,55 @@ impl SettingsView {
.text_size(FONT_TITLE)
.font_semibold()
.text_color(theme.foreground)
- .child("General"),
+ .child(t("General")),
)
.child(
div()
.text_size(FONT_CAPTION)
.text_color(theme.muted_foreground)
- .child("Customize how Wake looks."),
+ .child(t("Customize how Wake looks and reads.")),
),
)
.child(
- v_flex().px(SPACE_XXL).child(
- h_flex()
- .min_h(px(72.))
- .w_full()
- .px(SPACE_LG)
- .gap(SPACE_LG)
- .items_center()
- .rounded(theme.radius_lg)
- .border_1()
- .border_color(theme.border)
- .bg(theme.popover)
- .child(
- v_flex()
- .flex_1()
- .min_w_0()
- .gap(px(3.))
- .child(
- div()
- .text_size(FONT_BODY)
- .text_color(theme.foreground)
- .child("Appearance"),
- )
- .child(
- div()
- .text_size(FONT_CAPTION)
- .text_color(theme.muted_foreground)
- .child("Follow the system or keep Wake light or dark."),
- ),
- )
- .child(
- h_flex()
- .h(BUTTON_SM_H + px(4.))
- .p(px(2.))
- .rounded(theme.radius)
- .border_1()
- .border_color(theme.border)
- .bg(theme.secondary)
- .child(self.appearance_button(
- "appearance-system",
- "System",
- AppearancePreference::System,
- cx,
- ))
- .child(self.appearance_button(
- "appearance-light",
- "Light",
- AppearancePreference::Light,
- cx,
- ))
- .child(self.appearance_button(
- "appearance-dark",
- "Dark",
- AppearancePreference::Dark,
- cx,
- )),
- ),
- ),
+ v_flex()
+ .px(SPACE_XXL)
+ .gap(SPACE_MD)
+ .child(Self::setting_row(
+ t("Appearance"),
+ t("Follow the system or keep Wake light or dark."),
+ h_flex()
+ .h(BUTTON_SM_H + px(4.))
+ .p(px(2.))
+ .rounded(theme.radius)
+ .border_1()
+ .border_color(theme.border)
+ .bg(theme.secondary)
+ .child(self.appearance_button(
+ "appearance-system",
+ t("System"),
+ AppearancePreference::System,
+ cx,
+ ))
+ .child(self.appearance_button(
+ "appearance-light",
+ t("Light"),
+ AppearancePreference::Light,
+ cx,
+ ))
+ .child(self.appearance_button(
+ "appearance-dark",
+ t("Dark"),
+ AppearancePreference::Dark,
+ cx,
+ )),
+ cx,
+ ))
+ .child(Self::setting_row(
+ t("Language"),
+ t("Follow the system language, or pick one."),
+ self.language_control(),
+ cx,
+ )),
)
.into_any_element()
}
@@ -488,10 +540,11 @@ impl SettingsView {
fn render_data(&mut self, cx: &mut Context<Self>) -> AnyElement {
let theme = cx.theme();
let snapshot = self.workbench.read(cx).data_settings_snapshot();
+ // 会话计数的措辞单点在 workbench 的 session_tally(Locations 与
+ // Remote hosts 也用它);这里只补分隔符,不再复制一遍句子
let summary: SharedString = format!(
- "{} session{} · {}",
- snapshot.session_count,
- wake_core::text::plural(snapshot.session_count),
+ "{} · {}",
+ crate::workbench::session_tally(snapshot.session_count),
format_storage_size(snapshot.size_bytes)
)
.into();
@@ -499,7 +552,7 @@ impl SettingsView {
let show_in_finder = settings_button(
Button::new("settings-show-data")
.icon(icon("icons/folder.svg").with_size(px(13.)))
- .label(SHOW_IN_FM),
+ .label(show_in_fm()),
cx,
)
.on_click(move |_, _, _| {
@@ -526,8 +579,8 @@ impl SettingsView {
.h_full()
.bg(theme.background)
.child(settings_page_header(
- "Data",
- "See where Wake stores local data. Sessions refresh automatically.",
+ t("Data"),
+ t("See where Wake stores local data. Sessions refresh automatically."),
cx,
))
.child(
@@ -539,12 +592,13 @@ impl SettingsView {
.text_size(FONT_CAPTION)
.font_semibold()
.text_color(theme.foreground)
- .child("Storage"),
+ .child(t("Storage")),
)
.child(settings_info_card(
- "Wake data",
+ t("Wake data"),
details,
show_in_finder.into_any_element(),
+ px(84.),
cx,
)),
)
@@ -571,7 +625,7 @@ impl SettingsView {
})
.with_size(px(13.)),
)
- .label(if copied { "Copied" } else { label }),
+ .label(if copied { t("Copied") } else { label }),
cx,
)
.on_click(cx.listener(move |this, _, _, cx| {
@@ -643,7 +697,7 @@ impl SettingsView {
})
.with_size(px(13.)),
)
- .label(if shown { "Hide" } else { "Show" })
+ .label(if shown { t("Hide") } else { t("Show") })
.on_click(cx.listener(move |this, _, _, cx| {
if !this.connect_shown.remove(&ix) {
this.connect_shown.insert(ix);
@@ -713,7 +767,7 @@ impl SettingsView {
let copy_path = self.copy_button(
"connect-copy-path".into(),
- "Copy path",
+ t("Copy path"),
info.bin_path.clone(),
cx,
);
@@ -730,7 +784,7 @@ impl SettingsView {
div()
.text_size(FONT_CAPTION)
.text_color(theme.danger)
- .child("Not found next to the Wake app — reinstall Wake, or build it with `cargo build -p wake-core --bin wake-mcp`")
+ .child(t("Not found next to the Wake app — reinstall Wake, or build it with `cargo build -p wake-core --bin wake-mcp`"))
.into_any_element(),
);
}
@@ -750,7 +804,7 @@ impl SettingsView {
.text_size(FONT_CAPTION)
.text_color(theme.primary)
.on_click(|_, _, cx| cx.open_url(CONNECT_GUIDE_URL))
- .child("Setup guide");
+ .child(t("Setup guide"));
v_flex()
.flex_1()
@@ -758,8 +812,8 @@ impl SettingsView {
.h_full()
.bg(theme.background)
.child(settings_page_header(
- "Connect",
- "Let your coding agents look up your past sessions from Wake.",
+ t("Connect"),
+ t("Let your coding agents look up your past sessions from Wake."),
cx,
))
.child(
@@ -771,14 +825,15 @@ impl SettingsView {
.px(SPACE_XXL)
.pb(SPACE_XXL)
.gap(SPACE_SM)
- .child(section("MCP server"))
+ .child(section(t("MCP server")))
.child(settings_info_card(
"wake-mcp",
details,
copy_path.into_any_element(),
+ px(84.),
cx,
))
- .child(section("Agents").pt(SPACE_LG))
+ .child(section(t("Agents")).pt(SPACE_LG))
.child(
v_flex()
.w_full()
@@ -802,7 +857,7 @@ impl SettingsView {
.min_w_0()
.text_size(FONT_CAPTION)
.text_color(theme.muted_foreground)
- .child("Agents get four read-only tools: search, recent sessions, transcripts, projects."),
+ .child(t("Agents get four read-only tools: search, recent sessions, transcripts, projects.")),
)
.child(guide),
),
@@ -835,7 +890,7 @@ impl SettingsView {
fn render_about(&mut self, cx: &mut Context<Self>) -> AnyElement {
let theme = cx.theme();
let faint = theme.muted_foreground.opacity(0.72);
- let version: SharedString = format!("Version {}", env!("CARGO_PKG_VERSION")).into();
+ let version: SharedString = crate::tf!("Version {}", env!("CARGO_PKG_VERSION")).into();
v_flex()
.flex_1()
@@ -874,7 +929,7 @@ impl SettingsView {
.mt(SPACE_MD)
.text_size(FONT_CAPTION)
.text_color(theme.muted_foreground)
- .child("All your AI agent sessions, in one place."),
+ .child(t("All your AI agent sessions, in one place.")),
)
.child(div().mt(px(14.)).child(self.about_link(
"about-github",
@@ -888,7 +943,7 @@ impl SettingsView {
.text_size(FONT_LABEL)
.font_family(theme.mono_font_family.clone())
.text_color(faint)
- .child("© 2026 Corey Chiu · MIT License"),
+ .child(t("© 2026 Corey Chiu · MIT License")),
)
.child(
h_flex()
@@ -896,7 +951,7 @@ impl SettingsView {
.text_size(FONT_LABEL)
.font_family(theme.mono_font_family.clone())
.text_color(faint)
- .child("Built with ❤️ by ")
+ .child(t("Built with ❤️ by "))
.child(self.about_link(
"about-author",
"Corey Chiu",
@@ -914,24 +969,24 @@ impl SettingsView {
let checking = matches!(status, UpdateStatus::Checking);
let update_available = matches!(status, UpdateStatus::Available { .. });
let status_message: SharedString = match &status {
- UpdateStatus::Idle => "Check GitHub Releases for a newer version.".into(),
- UpdateStatus::Checking => "Checking GitHub Releases…".into(),
+ UpdateStatus::Idle => t("Check GitHub Releases for a newer version.").into(),
+ UpdateStatus::Checking => t("Checking GitHub Releases…").into(),
UpdateStatus::UpToDate { latest } => {
- format!("No newer release is available (latest: {latest}).").into()
+ crate::tf!("No newer release is available (latest: {}).", latest).into()
}
UpdateStatus::Available { latest } => {
- format!("Wake {latest} is available. Open the release page to download it.").into()
+ crate::tf!("Wake {} is available. Open the release page to download it.", latest).into()
}
UpdateStatus::Failed => {
- "Couldn't check for updates. Check your connection and try again.".into()
+ t("Couldn't check for updates. Check your connection and try again.").into()
}
};
let button_label = match status {
- UpdateStatus::Idle => "Check for Updates",
- UpdateStatus::Checking => "Checking…",
- UpdateStatus::UpToDate { .. } => "Check Again",
- UpdateStatus::Available { .. } => "View Update",
- UpdateStatus::Failed => "Try Again",
+ UpdateStatus::Idle => t("Check for Updates"),
+ UpdateStatus::Checking => t("Checking…"),
+ UpdateStatus::UpToDate { .. } => t("Check Again"),
+ UpdateStatus::Available { .. } => t("View Update"),
+ UpdateStatus::Failed => t("Try Again"),
};
let button = Button::new("settings-check-updates")
.label(button_label)
@@ -967,13 +1022,13 @@ impl SettingsView {
.text_size(FONT_TITLE)
.font_semibold()
.text_color(theme.foreground)
- .child("Updates"),
+ .child(t("Updates")),
)
.child(
div()
.text_size(FONT_CAPTION)
.text_color(theme.muted_foreground)
- .child("Keep Wake up to date."),
+ .child(t("Keep Wake up to date.")),
),
)
.child(
@@ -1037,20 +1092,20 @@ impl SettingsView {
let edit_row = edit_row.clone();
let mut menu = menu
.min_w(px(180.))
- .item(PopupMenuItem::new("Edit…").on_click(move |_, window, cx| {
+ .item(PopupMenuItem::new(t("Edit…")).on_click(move |_, window, cx| {
let row = edit_row.clone();
workbench
.update(cx, |this, cx| this.open_edit_location_form(row, window, cx));
}));
if exists {
let path = reveal_path.clone();
- menu = menu.item(PopupMenuItem::new(SHOW_IN_FM).on_click(move |_, _, _| {
+ menu = menu.item(PopupMenuItem::new(show_in_fm()).on_click(move |_, _, _| {
wake_core::services::terminal::open_in_file_manager(path.as_ref())
}));
}
if let Some(stored) = remove_target.clone() {
let workbench = edit_workbench.clone();
- menu = menu.separator().item(PopupMenuItem::new("Remove").on_click(
+ menu = menu.separator().item(PopupMenuItem::new(t("Remove")).on_click(
move |_, window, cx| {
let stored = stored.clone();
workbench.update(cx, |this, cx| {
@@ -1106,9 +1161,9 @@ impl SettingsView {
.checked(enabled)
.small()
.tooltip(if enabled {
- "Disable location"
+ t("Disable location")
} else {
- "Enable location"
+ t("Enable location")
})
.on_click(move |enabled, window, cx| {
let path = toggle_path.clone();
@@ -1226,20 +1281,20 @@ impl SettingsView {
.text_size(FONT_TITLE)
.font_semibold()
.text_color(theme.foreground)
- .child("Session locations"),
+ .child(t("Session locations")),
)
.child(
div()
.text_size(FONT_CAPTION)
.text_color(theme.muted_foreground)
- .child("Choose where Wake looks for local agent sessions."),
+ .child(t("Choose where Wake looks for local agent sessions.")),
),
)
.child(
settings_button(
Button::new("settings-add-location")
.icon(icon("icons/plus.svg").with_size(px(13.)))
- .label("Add location"),
+ .label(t("Add location")),
cx,
)
.on_click(move |_, window, cx| {
@@ -1256,7 +1311,7 @@ impl SettingsView {
.dropdown_menu(move |menu, _, _| {
let workbench = restore_workbench.clone();
menu.min_w(px(180.)).item(
- PopupMenuItem::new("Restore defaults")
+ PopupMenuItem::new(t("Restore defaults"))
.disabled(!diverged)
.on_click(move |_, window, cx| {
workbench.update(cx, |this, cx| {
@@ -1318,7 +1373,7 @@ impl SettingsView {
.flex_1()
.text_size(FONT_CAPTION)
.font_medium()
- .child("Not detected"),
+ .child(t("Not detected")),
)
.child(
div()
@@ -1366,7 +1421,7 @@ impl SettingsView {
let remove_name = menu_name.clone();
menu.min_w(px(180.))
.item(
- PopupMenuItem::new("Sync now")
+ PopupMenuItem::new(t("Sync now"))
.disabled(syncing || !enabled)
.on_click(move |_, _, cx| {
let name = sync_name.to_string();
@@ -1376,7 +1431,7 @@ impl SettingsView {
}),
)
.separator()
- .item(PopupMenuItem::new("Remove").on_click(move |_, window, cx| {
+ .item(PopupMenuItem::new(t("Remove")).on_click(move |_, window, cx| {
let name = remove_name.clone();
remove_workbench.update(cx, |this, cx| {
this.confirm_remove_remote_host(name, window, cx)
@@ -1430,9 +1485,9 @@ impl SettingsView {
.checked(enabled)
.small()
.tooltip(if enabled {
- "Disable host"
+ t("Disable host")
} else {
- "Enable host"
+ t("Enable host")
})
.on_click(move |checked, window, cx| {
let enabled = *checked;
@@ -1474,7 +1529,7 @@ impl SettingsView {
.text_size(FONT_TITLE)
.font_semibold()
.text_color(theme.foreground)
- .child("Remote hosts"),
+ .child(t("Remote hosts")),
)
.child(
div()
@@ -1491,7 +1546,7 @@ impl SettingsView {
settings_button(
Button::new("settings-sync-remotes")
.icon(icon("icons/refresh-cw.svg").with_size(px(13.)))
- .label(if syncing { "Syncing…" } else { "Sync now" }),
+ .label(if syncing { t("Syncing…") } else { t("Sync now") }),
cx,
)
.disabled(syncing)
@@ -1505,7 +1560,7 @@ impl SettingsView {
settings_button(
Button::new("settings-add-remote-host")
.icon(icon("icons/plus.svg").with_size(px(13.)))
- .label("Add host"),
+ .label(t("Add host")),
cx,
)
.on_click(move |_, window, cx| {
@@ -1543,7 +1598,7 @@ impl SettingsView {
div()
.text_size(FONT_CAPTION)
.text_color(theme.muted_foreground)
- .child("No remote hosts yet. Add one to mirror its sessions into Wake."),
+ .child(t("No remote hosts yet. Add one to mirror its sessions into Wake.")),
)
}),
)
diff --git a/crates/wake/src/ui.rs b/crates/wake/src/ui.rs
index f1ecf17..f7c761f 100644
--- a/crates/wake/src/ui.rs
+++ b/crates/wake/src/ui.rs
@@ -34,44 +34,72 @@ pub const FONT_MSG_THINKING: Pixels = px(11.5);
// ---------------- 平台文案 ----------------
// 同一处 UI 在不同平台叫不同名字/键(Finder vs File Explorer vs 文件管理器、
-// ⌘ vs Ctrl),文案引用这里的常量,别在 render 里散落字面量。cfg! 表达式让
-// 各支在任一平台都过类型检查(名词与 wake-core terminal 的平台实现对应:
-// macos=Finder,windows=资源管理器官方英文名 File Explorer)。
-
-pub const SHOW_IN_FM: &str = if cfg!(target_os = "macos") {
- "Show in Finder"
-} else if cfg!(target_os = "windows") {
- "Show in File Explorer"
-} else {
- "Show in File Manager"
-};
-pub const REVEAL_IN_FM: &str = if cfg!(target_os = "macos") {
- "Reveal in Finder"
-} else if cfg!(target_os = "windows") {
- "Reveal in File Explorer"
-} else {
- "Reveal in File Manager"
-};
+// ⌘ vs Ctrl),文案走这里的函数,别在 render 里散落字面量。名词与 wake-core
+// terminal 的平台实现对应:macos=Finder,windows=资源管理器官方英文名
+// File Explorer。这里用 `#[cfg]` 而非别处惯用的 `cfg!` 表达式:展开物只是
+// `concat!` 出的字面量与同形函数体,没有会在另一平台上失配的类型。
+//
+// 两个宏的形状相同:给一个平台名词 → `concat!` 派生若干**整句** key(整句
+// 即英文文案本身),并直接 emit 取用函数。中间不留 const:那层只是把字面量
+// 从宏内递到宏外,而 `t()` 要到运行时才知道译文,常量存不下它。
+//
+// 整句而非「动词 + {名词}」是有意的——zh-Hans 包里三条 "Show in …" 各自带着
+// 平台正确的中文产品名(访达 / 文件资源管理器 / 文件管理器),名词替换式的
+// 设计产不出这个。
+
+/// 文件管理器的平台名(macos=Finder,windows=官方英文名 File Explorer)
+macro_rules! file_manager_copy {
+ ($app:literal) => {
+ /// 详情页 / 设置页的「在文件管理器中显示」
+ pub fn show_in_fm() -> &'static str {
+ crate::i18n::t(concat!("Show in ", $app))
+ }
+ /// 更多菜单里的同一动作(措辞不同,是两条 key)
+ pub fn reveal_in_fm() -> &'static str {
+ crate::i18n::t(concat!("Reveal in ", $app))
+ }
+ };
+}
+#[cfg(target_os = "macos")]
+file_manager_copy!("Finder");
+#[cfg(target_os = "windows")]
+file_manager_copy!("File Explorer");
+#[cfg(not(any(target_os = "macos", target_os = "windows")))]
+file_manager_copy!("File Manager");
// 系统回收站的平台名词(macOS 与 freedesktop 都叫 Trash,Windows 是
-// Recycle Bin)与由它派生的三句删除文案。名词只写一次、整句由 concat!
-// 拼出:三处分别手写 cfg! 链的话,没有任何东西能拦住它们说不同的词
+// Recycle Bin)与由它派生的五句删除文案。名词只写一次、整句由 concat!
+// 拼出:五处分别手写 cfg! 链的话,没有任何东西能拦住它们说不同的词
// ——与 wake-core 各平台 trash_existing 的失败文案也得是同一个词。
//
-// 全部是 &'static str 而非调用点 format!:确认框内容活在 **dialog builder
-// 闭包**里,对话框开着时每帧重跑,留 format! 在里面就是每帧堆分配。
+// 确认框内容活在 **dialog builder 闭包**里、对话框开着时每帧重跑,`t()` 是
+// 一次哈希查表,和从前读常量一样不分配。
macro_rules! trash_copy {
($noun:literal, $body:literal) => {
/// 删除确认框主按钮 / 更多菜单项
- pub const MOVE_TO_TRASH: &str = concat!("Move to ", $noun);
- /// 删除成功通知
- pub const SESSION_TRASHED: &str = concat!("Session moved to ", $noun);
- /// 删除确认框正文首句(冠词随名词变,故整句单列)
- pub const TRASH_CONFIRM_BODY: &str = concat!(
- "The session file will be moved to ",
- $body,
- ". You can restore it anytime:"
- );
+ pub fn move_to_trash() -> &'static str {
+ crate::i18n::t(concat!("Move to ", $noun))
+ }
+ // 删除成功的通知。单/复数两支都返回 **key** 而非译文:调用点用
+ // `i18n::tp` 按条数选支,选支这一步必须发生在查表之前
+ pub fn session_trashed_key() -> &'static str {
+ concat!("Session moved to ", $noun)
+ }
+ pub fn sessions_trashed_key() -> &'static str {
+ concat!("{} sessions moved to ", $noun)
+ }
+ /// 确认框正文里嵌的名词(冠词随名词变,故与 $noun 分开)
+ pub fn trash_body() -> &'static str {
+ crate::i18n::t($body)
+ }
+ /// 删除确认框正文首句
+ pub fn trash_confirm_body() -> &'static str {
+ crate::i18n::t(concat!(
+ "The session file will be moved to ",
+ $body,
+ ". You can restore it anytime:"
+ ))
+ }
};
}
#[cfg(target_os = "windows")]
diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rs
index ddea05d..3d7ce2e 100644
--- a/crates/wake/src/workbench.rs
+++ b/crates/wake/src/workbench.rs
@@ -14,6 +14,7 @@
// FINISH: unreviewed and undocumented is unfinished; this build ends with the
// finish review, the verdict, and DESIGN.md
// ============================================================================
+use crate::i18n::t;
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::ops::Range;
@@ -199,25 +200,25 @@ fn session_group_label(ts: i64, today: NaiveDate) -> SharedString {
.single()
.map(|dt| dt.date_naive())
else {
- return "Undated".into();
+ return t("Undated").into();
};
if date >= today {
- return "Today".into();
+ return t("Today").into();
}
if date == today.pred_opt().unwrap_or(today) {
- return "Yesterday".into();
+ return t("Yesterday").into();
}
let week_start =
today - chrono::Duration::days(i64::from(today.weekday().num_days_from_monday()));
if date >= week_start {
- return "Earlier this week".into();
+ return t("Earlier this week").into();
}
if date.year() == today.year() {
- return date.format("%B").to_string().into();
+ return date.format(t("%B")).to_string().into();
}
- date.format("%B %Y").to_string().into()
+ date.format(t("%B %Y")).to_string().into()
}
#[derive(Debug, Clone)]
@@ -249,7 +250,7 @@ fn build_row_groups_at(
let pinned_count = rows.iter().take_while(|row| row.group_pinned).count();
if pinned_count > 0 {
groups.push(SessionGroup {
- label: "Pinned".into(),
+ label: t("Pinned").into(),
range: 0..pinned_count,
});
}
@@ -311,6 +312,8 @@ pub struct SessionsDelegate {
expanded: HashSet<String>,
groups: Vec<SessionGroup>,
grouped_on: NaiveDate,
+ /// 取 `groups` 里那些标签时的语言代次(标签是译好的文本,不是 key)
+ grouped_lang: u64,
sort: SortKey,
ascending: bool,
pagination: Option<SessionPagination>,
@@ -335,6 +338,7 @@ impl SessionsDelegate {
expanded: HashSet::new(),
groups: Vec::new(),
grouped_on,
+ grouped_lang: crate::i18n::generation(),
sort,
ascending,
pagination: None,
@@ -418,9 +422,11 @@ impl SessionsDelegate {
}
fn rebuild_groups_at(&mut self, today: NaiveDate) -> bool {
- if self.grouped_on == today {
+ let lang = crate::i18n::generation();
+ if self.grouped_on == today && self.grouped_lang == lang {
return false;
}
+ self.grouped_lang = lang;
let groups = build_row_groups_at(&self.rows, self.sort, self.ascending, today);
let changed = groups != self.groups;
self.groups = groups;
@@ -767,10 +773,7 @@ impl ListDelegate for SessionsDelegate {
.flex_shrink_0()
.child(format!("{child_count}"))
.tooltip(move |window, cx| {
- gpui_component::tooltip::Tooltip::new(format!(
- "{child_count} nested session{}",
- if child_count == 1 { "" } else { "s" }
- ))
+ gpui_component::tooltip::Tooltip::new(crate::tp!("{} nested session", "{} nested sessions", child_count))
.build(window, cx)
}),
)
@@ -1395,8 +1398,8 @@ impl ListDelegate for SearchDelegate {
"icons/search.svg",
px(48.),
px(22.),
- "Search full conversation text",
- "Matches natural language and code, like \"useEffect(\".",
+ t("Search full conversation text"),
+ t("Matches natural language and code, like \"useEffect(\"."),
cx,
));
}
@@ -1412,12 +1415,12 @@ impl ListDelegate for SearchDelegate {
div()
.text_size(FONT_BODY)
.font_medium()
- .child(format!("No results for \"{}\"", self.last_query)),
+ .child(crate::tf!("No results for \"{}\"", self.last_query)),
)
.child(
div()
.text_size(FONT_CAPTION)
- .child("Try a different or shorter query."),
+ .child(t("Try a different or shorter query.")),
)
}
@@ -1436,7 +1439,7 @@ impl ListDelegate for SearchDelegate {
.pb(SPACE_XS)
.text_size(FONT_LABEL)
.text_color(cx.theme().muted_foreground)
- .child("Short query — using fallback search. Longer keywords are faster."),
+ .child(t("Short query — using fallback search. Longer keywords are faster.")),
)
}
}
@@ -1460,17 +1463,11 @@ fn load_visible_transcript(
// adapter_for 按文件路径挑实例:自定义 location 的会话必须由拥有其根的
// 实例解析;完全找不到对应 agent 时保留可读错误,不再静默变成空详情。
let adapter = adapter_for(adapters, meta.agent, &meta.file_path).ok_or_else(|| {
- format!(
- "No {} adapter is available for this session path.",
- meta.agent.display_name()
- )
+ crate::tf!("No {} adapter is available for this session path.", meta.agent.display_name())
})?;
let session_ref = SessionFileRef::from_meta(meta);
let transcript = adapter.parse_transcript(&session_ref).map_err(|error| {
- format!(
- "Failed to parse {} session data: {error:#}",
- meta.agent.display_name()
- )
+ crate::tf!("Failed to parse {} session data: {}", meta.agent.display_name(), format!("{error:#}"))
})?;
Ok(transcript
@@ -1980,6 +1977,8 @@ pub struct Workbench {
palette_list: Entity<ListState<SearchDelegate>>,
/// ⌘K 搜索输入框(自管,不用 List 内置 searchable:清除钮可控)
palette_input: Entity<InputState>,
+ /// 上次刷新界面缓存译文时的语言代次(见 `sync_language`)
+ lang_generation: u64,
/// 进行中的搜索任务;新输入覆盖旧值即取消过期搜索
_palette_search_task: Option<Task<()>>,
/// 搜索命中不在首批会话时,按页补齐到命中项;新搜索覆盖旧任务。
@@ -2036,9 +2035,9 @@ enum InsightsRange {
impl InsightsRange {
fn title(self) -> &'static str {
match self {
- Self::Hour => "By hour",
- Self::Weekday => "By weekday",
- Self::Month => "By month",
+ Self::Hour => t("By hour"),
+ Self::Weekday => t("By weekday"),
+ Self::Month => t("By month"),
}
}
@@ -2072,9 +2071,9 @@ enum InsightsMetric {
impl InsightsMetric {
fn caption(self) -> &'static str {
match self {
- Self::Sessions => "Sessions",
- Self::Prompts => "Prompts",
- Self::Tokens => "Tokens",
+ Self::Sessions => t("Sessions"),
+ Self::Prompts => t("Prompts"),
+ Self::Tokens => t("Tokens"),
}
}
@@ -2106,9 +2105,9 @@ enum UsageBoard {
impl UsageBoard {
fn title(self) -> &'static str {
match self {
- Self::Agents => "Agents",
- Self::Projects => "Projects",
- Self::Models => "Models",
+ Self::Agents => t("Agents"),
+ Self::Projects => t("Projects"),
+ Self::Models => t("Models"),
}
}
@@ -2205,10 +2204,7 @@ impl Workbench {
let (store, db_note) = match wake_core::db::open_or_rebuild(&db_path) {
Ok(v) => v,
Err(e) => {
- terminal::show_fatal_alert(&format!(
- "Wake couldn't open or rebuild its index at {}. {e}",
- db_path.display()
- ));
+ terminal::show_fatal_alert(&crate::tf!("Wake couldn't open or rebuild its index at {}. {}", db_path.display(), e));
std::process::exit(1);
}
};
@@ -2237,7 +2233,7 @@ impl Workbench {
.searchable(false)
});
let palette_input = cx.new(|cx| {
- InputState::new(window, cx).placeholder("Search everything \u{2014} prose or code")
+ InputState::new(window, cx).placeholder(t("Search everything — prose or code"))
});
// 后台:全量扫描线程 + 文件监听 + 远程同步(彼此独立并行)
@@ -2310,6 +2306,7 @@ impl Workbench {
list_state,
palette_list,
palette_input,
+ lang_generation: crate::i18n::generation(),
_palette_search_task: None,
_list_seek_task: None,
pending_list_selection: None,
@@ -2446,6 +2443,21 @@ impl Workbench {
cx.notify();
}
+ /// 切语言后把**缓存住的译文**补上。`refresh_windows()` 只让每帧重跑
+ /// render,凡是早先存进 entity 的字符串(输入框 placeholder、列表分组
+ /// 标签)都不会自己变——分组那半由 `rebuild_groups_at` 比对代次处理,
+ /// 这里管 placeholder。每帧一次整数比较
+ fn sync_language(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let lang = crate::i18n::generation();
+ if self.lang_generation == lang {
+ return;
+ }
+ self.lang_generation = lang;
+ self.palette_input.update(cx, |state, cx| {
+ state.set_placeholder(t("Search everything — prose or code"), window, cx);
+ });
+ }
+
fn refresh_session_group_date(&mut self, cx: &mut Context<Self>) {
let today = Local::now().date_naive();
let selected_key = self
@@ -2578,7 +2590,7 @@ impl Workbench {
tally: if exists {
session_tally(count).into()
} else {
- "Folder not found".into()
+ t("Folder not found").into()
},
exists,
custom: custom_owner(&customs, location.agent, &raw).cloned(),
@@ -2709,7 +2721,7 @@ impl Workbench {
}
} else {
TitlebarOptions {
- title: Some("Wake Settings".into()),
+ title: Some(t("Wake Settings").into()),
appears_transparent: false,
traffic_light_position: None,
}
@@ -2791,7 +2803,7 @@ impl Workbench {
cx: &mut Context<Self>,
) {
let host_input = cx.new(|cx| {
- InputState::new(window, cx).placeholder("alias from ~/.ssh/config, or user@host")
+ InputState::new(window, cx).placeholder(t("alias from ~/.ssh/config, or user@host"))
});
cx.subscribe_in(&host_input, window, |this, input, event, window, cx| {
if matches!(event, gpui_component::input::InputEvent::PressEnter { .. }) {
@@ -2821,10 +2833,10 @@ impl Workbench {
.pl(field_inset)
.text_size(FONT_HEADING)
.font_semibold()
- .child("Add remote host"),
+ .child(t("Add remote host")),
)
.w(px(500.))
- .button_props(gpui_component::dialog::DialogButtonProps::default().ok_text("Add"))
+ .button_props(gpui_component::dialog::DialogButtonProps::default().ok_text(t("Add")))
.child(
v_flex()
.gap(SPACE_MD)
@@ -2839,7 +2851,7 @@ impl Workbench {
.flex_shrink_0()
.text_size(FONT_CAPTION)
.text_color(theme.muted_foreground)
- .child("Host"),
+ .child(t("Host")),
)
.child(div().flex_1().min_w_0().child(Input::new(&host_input))),
)
@@ -2870,11 +2882,11 @@ impl Workbench {
.px(field_inset)
.child(
gpui_component::dialog::DialogClose::new()
- .child(Button::new("remote-host-cancel").label("Cancel").outline()),
+ .child(Button::new("remote-host-cancel").label(t("Cancel")).outline()),
)
.child(
gpui_component::dialog::DialogAction::new()
- .child(Button::new("remote-host-add").label("Add").primary()),
+ .child(Button::new("remote-host-add").label(t("Add")).primary()),
),
)
} else {
@@ -2898,7 +2910,7 @@ impl Workbench {
if !wake_core::remote::valid_host_name(name) {
window.push_notification(
Notification::error(
- "Host must be an SSH alias or user@host (letters, digits, . _ - @)",
+ t("Host must be an SSH alias or user@host (letters, digits, . _ - @)"),
),
cx,
);
@@ -2952,8 +2964,8 @@ impl Workbench {
AgentId,
SharedString,
) = match &target {
- FormTarget::Add => ("Add location", "Add", AgentId::ClaudeCode, "".into()),
- FormTarget::Edit { agent, path, .. } => ("Edit location", "Save", *agent, path.clone()),
+ FormTarget::Add => (t("Add location"), t("Add"), AgentId::ClaudeCode, "".into()),
+ FormTarget::Edit { agent, path, .. } => (t("Edit location"), t("Save"), *agent, path.clone()),
};
// 占位符须与校验规则(Path::is_absolute)同形:Windows 上没有盘符
// 的 `/absolute/...` 并不算绝对路径,照着占位符敲会被拒
@@ -3032,7 +3044,7 @@ impl Workbench {
.flex_shrink_0()
.text_size(FONT_CAPTION)
.text_color(theme.muted_foreground)
- .child("Agent"),
+ .child(t("Agent")),
)
.child(
// Button 走 ParentElement 自组内容:品牌图标是
@@ -3101,7 +3113,7 @@ impl Workbench {
.flex_shrink_0()
.text_size(FONT_CAPTION)
.text_color(theme.muted_foreground)
- .child("Folder"),
+ .child(t("Folder")),
)
.child(div().flex_1().min_w_0().child(Input::new(&browse_input)))
.child(
@@ -3109,7 +3121,7 @@ impl Workbench {
.outline()
.rounded(RADIUS_BUTTON)
.icon(icon("icons/folder.svg").with_size(px(13.)))
- .tooltip("Choose a folder")
+ .tooltip(t("Choose a folder"))
.on_click({
let entity = browse_entity.clone();
let input = browse_input.clone();
@@ -3182,7 +3194,7 @@ impl Workbench {
.with_size(px(13.))
.flex_shrink_0(),
)
- .child("Remove"),
+ .child(t("Remove")),
)
})
.when(exists, |el| {
@@ -3208,7 +3220,7 @@ impl Workbench {
.flex_shrink_0()
.text_color(theme.muted_foreground),
)
- .child(SHOW_IN_FM),
+ .child(show_in_fm()),
)
}),
)
@@ -3229,7 +3241,7 @@ impl Workbench {
.px(field_inset)
.child(
gpui_component::dialog::DialogClose::new()
- .child(Button::new("location-cancel").label("Cancel").outline()),
+ .child(Button::new("location-cancel").label(t("Cancel")).outline()),
)
.child(
gpui_component::dialog::DialogAction::new().child(
@@ -3256,7 +3268,7 @@ impl Workbench {
files: false,
directories: true,
multiple: false,
- prompt: Some("Choose".into()),
+ prompt: Some(t("Choose").into()),
});
cx.spawn_in(window, async move |this, cx| {
let dir = match rx.await {
@@ -3298,7 +3310,7 @@ impl Workbench {
// **必须判在剪尾之前**:`//` 剪完是空串,若拿剪后的结果去判就会退回
// 未剪形态放行,而旧版是拒的(2026-08-25 review)
if !std::path::Path::new(&expanded).is_absolute() {
- window.push_notification(Notification::warning("Enter an absolute folder path"), cx);
+ window.push_notification(Notification::warning(t("Enter an absolute folder path")), cx);
return false;
}
// 尾分隔符归一(展示与重叠判定都吃这份);裸根("/"、"C:\")剪完会
@@ -3376,7 +3388,7 @@ impl Workbench {
});
if covered {
window.push_notification(
- Notification::info("This folder is already in Wake's session locations"),
+ Notification::info(t("This folder is already in Wake's session locations")),
cx,
);
return false;
@@ -3401,15 +3413,15 @@ impl Workbench {
),
};
if let Err(e) = res {
- window.push_notification(Notification::error(format!("Save failed: {e}")), cx);
+ window.push_notification(Notification::error(crate::tf!("Save failed: {}", e)), cx);
return false;
}
// Settings 页本身是动态快照,只需收起表单;Workbench notify 会让
// SettingsView 观察者刷新列表。
window.close_all_dialogs(cx);
let note = match &target {
- FormTarget::Add => "Location added",
- FormTarget::Edit { .. } => "Location updated",
+ FormTarget::Add => t("Location added"),
+ FormTarget::Edit { .. } => t("Location updated"),
};
self.apply_roster_change(Ok(()), "", Notification::success(note), window, cx);
false
@@ -3429,8 +3441,8 @@ impl Workbench {
.remove_custom_root(agent.as_str(), stored.as_ref());
self.apply_roster_change(
res,
- "Remove failed",
- Notification::info("Location removed"),
+ t("Remove failed"),
+ Notification::info(t("Location removed")),
window,
cx,
);
@@ -3446,8 +3458,8 @@ impl Workbench {
let res = self.store.clear_location_overrides();
self.apply_roster_change(
res,
- "Restore failed",
- Notification::info("Locations restored to defaults"),
+ t("Restore failed"),
+ Notification::info(t("Locations restored to defaults")),
window,
cx,
);
@@ -3467,7 +3479,7 @@ impl Workbench {
.set_location_enabled(agent.as_str(), path.as_ref(), enabled)
{
Err(e) => window.push_notification(
- Notification::error(format!("Couldn't update location: {e}")),
+ Notification::error(crate::tf!("Couldn't update location: {}", e)),
cx,
),
Ok(()) => {
@@ -3475,9 +3487,9 @@ impl Workbench {
self.kick_incremental_scan(cx);
window.push_notification(
Notification::info(if enabled {
- "Location enabled"
+ t("Location enabled")
} else {
- "Location disabled"
+ t("Location disabled")
}),
cx,
);
@@ -3500,7 +3512,7 @@ impl Workbench {
) {
match res {
Err(e) => {
- window.push_notification(Notification::error(format!("{err_prefix}: {e}")), cx);
+ window.push_notification(Notification::error(crate::tf!("{}: {}", err_prefix, e)), cx);
}
Ok(()) => {
self.rebuild_roster(cx);
@@ -3526,9 +3538,9 @@ impl Workbench {
.map(|host| {
let tally = session_tally(counts.get(&host.name).copied().unwrap_or(0));
let (status, failed) = match (&host.last_sync_error, host.last_sync_at) {
- (Some(err), _) => (format!("Sync failed: {err}"), true),
- (None, Some(ts)) => (format!("{tally} · synced {}", smart_time(ts)), false),
- (None, None) => (format!("{tally} · never synced"), false),
+ (Some(err), _) => (crate::tf!("Sync failed: {}", err), true),
+ (None, Some(ts)) => (crate::tf!("{} · synced {}", tally, smart_time(ts)), false),
+ (None, None) => (crate::tf!("{} · never synced", tally), false),
};
RemoteHostRow {
name: host.name.into(),
@@ -3549,7 +3561,7 @@ impl Workbench {
if !wake_core::remote::valid_host_name(name) {
window.push_notification(
Notification::error(
- "Host must be an SSH alias or user@host (letters, digits, . _ - @)",
+ t("Host must be an SSH alias or user@host (letters, digits, . _ - @)"),
),
cx,
);
@@ -3557,7 +3569,7 @@ impl Workbench {
}
match self.store.add_remote_host(name) {
Err(e) => window.push_notification(
- Notification::error(format!("Couldn't add remote host: {e}")),
+ Notification::error(crate::tf!("Couldn't add remote host: {}", e)),
cx,
),
Ok(()) => {
@@ -3567,7 +3579,7 @@ impl Workbench {
// 就能给出"密钥不在 agent 里"这类反馈
self.spawn_remote_sync(vec![name.to_string()], cx);
window.push_notification(
- Notification::info(format!("Syncing sessions from {name}…")),
+ Notification::info(crate::tf!("Syncing sessions from {}…", name)),
cx,
);
}
@@ -3585,11 +3597,11 @@ impl Workbench {
// 的行按"磁盘已删"出清;缓存保留,重新启用即收编回来
let res = self.store.set_remote_host_enabled(name, enabled);
let note = Notification::info(if enabled {
- "Remote host enabled"
+ t("Remote host enabled")
} else {
- "Remote host disabled"
+ t("Remote host disabled")
});
- self.apply_roster_change(res, "Couldn't update remote host", note, window, cx);
+ self.apply_roster_change(res, t("Couldn't update remote host"), note, window, cx);
}
/// Remove 按确认流程走:索引行与本地缓存一并清掉,远端文件不动。
@@ -3609,13 +3621,13 @@ impl Workbench {
div()
.text_size(FONT_HEADING)
.font_semibold()
- .child(format!("Remove {name}?")),
+ .child(crate::tf!("Remove {}?", name)),
)
.width(px(440.))
.confirm()
.button_props(
gpui_component::dialog::DialogButtonProps::default()
- .ok_text("Remove")
+ .ok_text(t("Remove"))
.ok_variant(gpui_component::button::ButtonVariant::Danger),
)
.child(
@@ -3639,7 +3651,7 @@ impl Workbench {
fn remove_remote_host(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) {
if let Err(e) = self.store.remove_remote_host(name) {
window.push_notification(
- Notification::error(format!("Couldn't remove remote host: {e}")),
+ Notification::error(crate::tf!("Couldn't remove remote host: {}", e)),
cx,
);
return;
@@ -3658,7 +3670,7 @@ impl Workbench {
});
}
self.kick_incremental_scan(cx);
- window.push_notification(Notification::info("Remote host removed"), cx);
+ window.push_notification(Notification::info(t("Remote host removed")), cx);
}
/// 起远程同步(add host / Sync now / ⌘R 共用)。rsync 在独立线程,
@@ -3712,8 +3724,8 @@ impl Workbench {
let note = if !p.scanning && self.refreshing {
self.refreshing = false;
Some(match &p.error {
- None => Notification::success("Sessions refreshed"),
- Some(err) => Notification::error(format!("Refresh failed: {err}")),
+ None => Notification::success(t("Sessions refreshed")),
+ Some(err) => Notification::error(crate::tf!("Refresh failed: {}", err)),
})
} else {
None
@@ -3936,13 +3948,13 @@ impl Workbench {
.justify_between()
.text_size(FONT_LABEL)
.text_color(theme.muted_foreground)
- .child("Scope: all sessions")
+ .child(t("Scope: all sessions"))
.child(
h_flex()
.gap(SPACE_MD)
- .child("\u{2191}\u{2193} navigate")
- .child("\u{21a9} open")
- .child("esc close"),
+ .child(t("↑↓ navigate"))
+ .child(t("↩ open"))
+ .child(t("esc close")),
),
),
)
@@ -4458,14 +4470,14 @@ impl Workbench {
if outcome.ok {
Notification::success(match target {
terminal::ResumeTarget::App(_) => {
- format!("Opened in terminal: {}", outcome.command)
+ crate::tf!("Opened in terminal: {}", outcome.command)
}
terminal::ResumeTarget::CopySshCommand => {
- format!("SSH command copied: {}", outcome.command)
+ crate::tf!("SSH command copied: {}", outcome.command)
}
})
} else {
- Notification::error(outcome.error.unwrap_or_else(|| "Resume failed".into()))
+ Notification::error(outcome.error.unwrap_or_else(|| t("Resume failed").into()))
}
});
}
@@ -4504,8 +4516,8 @@ impl Workbench {
cx,
self.store.clone(),
name,
- "Exported",
- "Export failed",
+ t("Exported"),
+ t("Export failed"),
move |path| {
let adapter = adapter_for(&adapters, meta.agent, &meta.file_path)
.ok_or_else(|| anyhow::anyhow!("no adapter for this session"))?;
@@ -4545,22 +4557,18 @@ impl Workbench {
{
this.detail = None;
}
- let message = if count == 1 {
- SESSION_TRASHED.to_string()
- } else {
- format!(
- "{count} sessions {}",
- SESSION_TRASHED
- .strip_prefix("Session ")
- .unwrap_or(SESSION_TRASHED)
- )
- };
+ let message = crate::i18n::tp(
+ crate::ui::session_trashed_key(),
+ crate::ui::sessions_trashed_key(),
+ count as i64,
+ &[&count],
+ );
window.push_notification(Notification::success(message), cx);
// 立刻把它从列表摘掉,不等 watcher 那 800ms 去抖
this.refresh(cx);
}
Err(e) => {
- window.push_notification(Notification::error(format!("Delete failed: {e}")), cx)
+ window.push_notification(Notification::error(crate::tf!("Delete failed: {}", e)), cx)
}
})
.ok();
@@ -4574,7 +4582,7 @@ impl Workbench {
// 缓存副本,trash 它下次同步就复活;动远端文件是阶段 3 的产品决定
if !detail.meta.host.is_empty() {
window.push_notification(
- Notification::info("Remote sessions are read-only — files stay on the remote host"),
+ Notification::info(t("Remote sessions are read-only — files stay on the remote host")),
cx,
);
return;
@@ -4611,9 +4619,9 @@ impl Workbench {
.text_size(FONT_HEADING)
.font_semibold()
.child(if nested_count > 0 {
- "Delete this session tree?"
+ t("Delete this session tree?")
} else {
- "Delete this session?"
+ t("Delete this session?")
}),
)
.width(px(440.))
@@ -4623,7 +4631,7 @@ impl Workbench {
.confirm()
.button_props(
gpui_component::dialog::DialogButtonProps::default()
- .ok_text(MOVE_TO_TRASH)
+ .ok_text(move_to_trash())
.ok_variant(gpui_component::button::ButtonVariant::Danger),
)
.child(
@@ -4631,13 +4639,14 @@ impl Workbench {
.gap(SPACE_SM)
.text_size(FONT_BODY)
.child(if nested_count > 0 {
- format!(
- "This session and {nested_count} nested session{} will be moved to {}. You can restore them anytime:",
- if nested_count == 1 { "" } else { "s" },
- if cfg!(target_os = "windows") { "the Recycle Bin" } else { "Trash" },
+ crate::tp!(
+ "This session and {} nested session will be moved to {}. You can restore them anytime:",
+ "This session and {} nested sessions will be moved to {}. You can restore them anytime:",
+ nested_count,
+ crate::ui::trash_body()
)
} else {
- TRASH_CONFIRM_BODY.to_string()
+ trash_confirm_body().to_string()
})
.child(
div()
@@ -4657,7 +4666,7 @@ impl Workbench {
div()
.text_size(FONT_CAPTION)
.text_color(theme.muted_foreground)
- .child("Only the local file is removed — Codex's own records stay intact."),
+ .child(t("Only the local file is removed — Codex's own records stay intact.")),
)
}),
)
@@ -4672,7 +4681,7 @@ impl Workbench {
fn context_title(&self) -> String {
if self.favorite_only {
- return "Starred".to_string();
+ return t("Starred").to_string();
}
if let Some(p) = &self.selected_project {
// 项目显示名以侧栏列表(store 的 ProjectInfo)为准,不再重推
@@ -4681,10 +4690,10 @@ impl Workbench {
.iter()
.find(|info| info.path == *p)
.map(|info| info.name.clone())
- .unwrap_or_else(|| "Projects".to_string());
+ .unwrap_or_else(|| t("Projects").to_string());
}
match self.selected_agent {
- None => "All Sessions".to_string(),
+ None => t("All Sessions").to_string(),
Some(one) => one.display_name().to_string(),
}
}
@@ -4701,22 +4710,19 @@ impl Workbench {
// 文案在此按 scan 现算,不另存字段——存下来就会有第二个写入点要维护
let note = if self.scan.scanning {
Some(match self.scan.total {
- 0 => "Refreshing…".to_string(),
- total => format!("Refreshing {}/{}", self.scan.done, total),
+ 0 => t("Refreshing…").to_string(),
+ total => crate::tf!("Refreshing {}/{}", self.scan.done, total),
})
} else if let [only] = self.syncing_hosts.as_slice() {
// rsync 与扫描并行;扫描先收工时这里接着展示同步状态
- Some(format!("Syncing {only}…"))
+ Some(crate::tf!("Syncing {}…", only))
} else if !self.syncing_hosts.is_empty() {
- Some(format!(
- "Syncing {} remote hosts…",
- self.syncing_hosts.len()
- ))
+ Some(crate::tf!("Syncing {} remote hosts…", self.syncing_hosts.len()))
} else {
self.scan
.error
.as_ref()
- .map(|e| format!("Refresh failed: {e}"))
+ .map(|e| crate::tf!("Refresh failed: {}", e))
};
let status: Option<AnyElement> = if let Some(note) = note {
Some(
@@ -4745,7 +4751,7 @@ impl Workbench {
.flex_shrink_0()
.bg(theme.warning),
)
- .child(div().min_w_0().truncate().child("Live updates off"))
+ .child(div().min_w_0().truncate().child(t("Live updates off")))
.into_any_element(),
)
} else {
@@ -4817,7 +4823,7 @@ impl Workbench {
.child(icon("icons/search.svg").with_size(px(13.)).flex_shrink_0())
// flex_1 + min_w_0 + truncate:空间不足时压这里,
// 绝不把右侧刷新按钮挤出侧栏
- .child(div().flex_1().min_w_0().truncate().child("Search sessions"))
+ .child(div().flex_1().min_w_0().truncate().child(t("Search sessions")))
.child(
div()
.flex_shrink_0()
@@ -4836,7 +4842,7 @@ impl Workbench {
.child(sidebar_row(
"all",
RowLead::Icon(icon("icons/layers.svg")),
- "All Sessions",
+ t("All Sessions"),
Some(self.session_total()),
all_active,
RowLevel::Primary,
@@ -4848,7 +4854,7 @@ impl Workbench {
.child(sidebar_row(
"fav",
RowLead::Icon(icon("icons/star.svg")),
- "Starred",
+ t("Starred"),
if self.starred_count > 0 {
Some(self.starred_count)
} else {
@@ -4877,7 +4883,7 @@ impl Workbench {
.gap(SPACE_XS)
.child(group_header(
"agents-header",
- "Agents",
+ t("Agents"),
self.agents_collapsed,
cx.listener(|this, _, _window, cx| {
this.agents_collapsed = !this.agents_collapsed;
@@ -4909,7 +4915,7 @@ impl Workbench {
})
.child(group_header(
"projects-header",
- "Projects",
+ t("Projects"),
self.projects_collapsed,
cx.listener(|this, _, _window, cx| {
this.projects_collapsed = !this.projects_collapsed;
@@ -4968,7 +4974,7 @@ impl Workbench {
.gap(SPACE_XS)
.child(sidebar_tool_btn(
"insights",
- "Insights",
+ t("Insights"),
true,
// 页面打开时图标点亮 primary(显式设色后不被
// hover 的容器 text_color 覆盖)
@@ -4984,7 +4990,7 @@ impl Workbench {
))
.child(sidebar_tool_btn(
"settings",
- "Settings",
+ t("Settings"),
true,
icon("icons/settings.svg")
.with_size(px(14.))
@@ -4994,7 +5000,7 @@ impl Workbench {
))
.child(sidebar_tool_btn(
"refresh",
- "Refresh sessions",
+ t("Refresh sessions"),
!self.scan.scanning,
if self.scan.scanning {
Spinner::new().small().into_any_element()
@@ -5031,19 +5037,15 @@ impl Workbench {
let sort_ascending = self.sort_ascending;
let sort_entity = cx.entity();
let sort_label = match sort_key {
- SortKey::Updated => "Date updated",
- SortKey::Created => "Date created",
- SortKey::Messages => "Message count",
+ SortKey::Updated => t("Date updated"),
+ SortKey::Created => t("Date created"),
+ SortKey::Messages => t("Message count"),
};
- let sort_tooltip = format!(
- "Sort by {} · {}",
- sort_label,
- if sort_ascending {
- "Ascending"
+ let sort_tooltip = crate::tf!("Sort by {} · {}", sort_label, if sort_ascending {
+ t("Ascending")
} else {
- "Descending"
- }
- );
+ t("Descending")
+ });
// 与详情工具栏统一:icon-only ghost,常态透明、hover 才出现背景。
let sort_menu = Button::new("sort-sessions")
.ghost()
@@ -5084,12 +5086,12 @@ impl Workbench {
})
};
menu.min_w(px(180.))
- .item(mk_key("Date updated", SortKey::Updated))
- .item(mk_key("Date created", SortKey::Created))
- .item(mk_key("Message count", SortKey::Messages))
+ .item(mk_key(t("Date updated"), SortKey::Updated))
+ .item(mk_key(t("Date created"), SortKey::Created))
+ .item(mk_key(t("Message count"), SortKey::Messages))
.separator()
- .item(mk_dir("Descending", false))
- .item(mk_dir("Ascending", true))
+ .item(mk_dir(t("Descending"), false))
+ .item(mk_dir(t("Ascending"), true))
})
.anchor(Anchor::TopRight);
v_flex()
@@ -5147,12 +5149,12 @@ impl Workbench {
.text_size(FONT_BODY)
.font_medium()
.text_color(theme.foreground)
- .child("Building your library"),
+ .child(t("Building your library")),
)
.child(
div()
.text_size(FONT_CAPTION)
- .child("Looking for local agent sessions…"),
+ .child(t("Looking for local agent sessions…")),
)
.into_any_element()
} else if library_empty {
@@ -5166,8 +5168,8 @@ impl Workbench {
"icons/layers.svg",
px(48.),
px(22.),
- "Your library is empty",
- "Add a local session location to get started.",
+ t("Your library is empty"),
+ t("Add a local session location to get started."),
cx,
))
.child(
@@ -5175,7 +5177,7 @@ impl Workbench {
.primary()
.small()
.rounded(RADIUS_BUTTON)
- .label("Add a location")
+ .label(t("Add a location"))
.on_click(cx.listener(|this, _, _window, cx| {
this.settings_page = SettingsPage::Locations;
this.open_settings(cx);
@@ -5191,8 +5193,8 @@ impl Workbench {
"icons/inbox.svg",
px(48.),
px(22.),
- "No matching sessions",
- "Try a different agent, project, or filter.",
+ t("No matching sessions"),
+ t("Try a different agent, project, or filter."),
cx,
))
.into_any_element()
@@ -5304,7 +5306,7 @@ impl Workbench {
cx.stop_propagation();
cx.write_to_clipboard(ClipboardItem::new_image(&copy_image));
this.show_image_action_success(target, ImageAction::Copy, cx);
- window.push_notification(Notification::success("Image copied"), cx);
+ window.push_notification(Notification::success(t("Image copied")), cx);
});
let save_action = cx.listener(move |this, _, window, cx| {
cx.stop_propagation();
@@ -5320,8 +5322,8 @@ impl Workbench {
cx,
this.store.clone(),
name,
- "Saved",
- "Couldn't save the image",
+ t("Saved"),
+ t("Couldn't save the image"),
move |path| Ok(std::fs::write(path, &image.bytes)?),
);
cx.spawn_in(window, async move |this, cx| {
@@ -5399,9 +5401,9 @@ impl Workbench {
})
.tooltip(move |window, cx| {
gpui_component::tooltip::Tooltip::new(if copy_succeeded {
- "Copied"
+ t("Copied")
} else {
- "Copy image"
+ t("Copy image")
})
.build(window, cx)
})
@@ -5440,9 +5442,9 @@ impl Workbench {
})
.tooltip(move |window, cx| {
gpui_component::tooltip::Tooltip::new(if save_succeeded {
- "Saved"
+ t("Saved")
} else {
- "Save image"
+ t("Save image")
})
.build(window, cx)
})
@@ -5479,7 +5481,7 @@ impl Workbench {
.hover(|style| style.bg(gpui::white().opacity(0.2)))
.cursor_pointer()
.tooltip(|window, cx| {
- gpui_component::tooltip::Tooltip::new("Close").build(window, cx)
+ gpui_component::tooltip::Tooltip::new(t("Close")).build(window, cx)
})
.on_click(close_button)
.child(
@@ -5544,7 +5546,7 @@ impl Workbench {
let is_jump_target = jump_seq == Some(m.seq);
let inner: AnyElement = if m.kind == MessageKind::CompactSummary {
- centered_pill("Context compacted", cx).into_any_element()
+ centered_pill(t("Context compacted"), cx).into_any_element()
} else {
match m.role {
MessageRole::User => {
@@ -5689,10 +5691,10 @@ impl Workbench {
// 副标题只说 "Since {首会话月份}"(用户定稿);拿不到时间时回落默认句
let subtitle: SharedString = match &self.insights {
Some(d) if d.sessions > 0 => match month_year(d.first_ts) {
- my if my.is_empty() => "Your coding agent activity".into(),
- my => format!("Since {my}").into(),
+ my if my.is_empty() => t("Your coding agent activity").into(),
+ my => crate::tf!("Since {}", my).into(),
},
- _ => "Your coding agent activity".into(),
+ _ => t("Your coding agent activity").into(),
};
let body: AnyElement = match &self.insights {
@@ -5712,8 +5714,8 @@ impl Workbench {
"icons/chart-column.svg",
px(58.),
px(24.),
- "No activity yet",
- "Refresh sessions to see your activity here.",
+ t("No activity yet"),
+ t("Refresh sessions to see your activity here."),
cx,
))
.into_any_element(),
@@ -5740,7 +5742,7 @@ impl Workbench {
div()
.text_size(FONT_TITLE)
.font_semibold()
- .child("Insights"),
+ .child(t("Insights")),
)
.child(
div()
@@ -5764,14 +5766,14 @@ impl Workbench {
|value: String, label: &'static str| stat_cell(value, label, FONT_TITLE, None, cx);
let overview = h_flex()
.gap(px(40.))
- .child(stat(thousands(d.sessions), "Sessions"))
+ .child(stat(thousands(d.sessions), t("Sessions")))
.when(d.tokens > 0, |row| {
- row.child(stat(fmt_tokens(Some(d.tokens)), "Tokens"))
+ row.child(stat(fmt_tokens(Some(d.tokens)), t("Tokens")))
})
- .child(stat(thousands(d.prompts), "Prompts"))
- .child(stat(thousands(d.agents.len() as i64), "Agents"))
- .child(stat(thousands(d.project_count), "Projects"))
- .child(stat(thousands(d.active_days()), "Active days"));
+ .child(stat(thousands(d.prompts), t("Prompts")))
+ .child(stat(thousands(d.agents.len() as i64), t("Agents")))
+ .child(stat(thousands(d.project_count), t("Projects")))
+ .child(stat(thousands(d.active_days()), t("Active days")));
// ---- 三个榜单的行首/名称(闭包只捕获 Copy 的色值) ----
let dark = theme.mode.is_dark();
@@ -5815,8 +5817,8 @@ impl Workbench {
v_flex()
.gap(SPACE_MD)
.child(switch_section_head(
- "Activity",
- Some("Prompts you sent, day by day".into()),
+ t("Activity"),
+ Some(t("Prompts you sent, day by day").into()),
None,
cx,
))
@@ -5898,7 +5900,7 @@ impl Workbench {
v_flex()
.gap(SPACE_MD)
.child(switch_section_head(
- "Over time",
+ t("Over time"),
Some(trend_caption(&layers).into()),
None,
cx,
@@ -6025,11 +6027,8 @@ impl Workbench {
"icons/message-square.svg",
px(58.),
px(26.),
- "No session selected",
- format!(
- "Pick one from the list, or press {} to search.",
- search_key_hint()
- ),
+ t("No session selected"),
+ crate::tf!("Pick one from the list, or press {} to search.", search_key_hint()),
cx,
))
.into_any_element();
@@ -6053,7 +6052,7 @@ impl Workbench {
let delete_entity = delete_entity.clone();
menu.min_w(px(210.))
.item(
- PopupMenuItem::new(" Export as Markdown")
+ PopupMenuItem::new(t(" Export as Markdown"))
.icon(icon("icons/download.svg").with_size(px(15.)))
.on_click(move |_, window, cx| {
export_entity.update(cx, |this, cx| {
@@ -6062,7 +6061,7 @@ impl Workbench {
}),
)
.item(
- PopupMenuItem::new(format!(" {REVEAL_IN_FM}"))
+ PopupMenuItem::new(format!(" {}", reveal_in_fm()))
.icon(icon("icons/folder.svg").with_size(px(15.)))
.on_click(move |_, _, cx| {
reveal_entity.update(cx, |this, _| {
@@ -6073,7 +6072,7 @@ impl Workbench {
}),
)
.item(
- PopupMenuItem::new(" Copy Session ID")
+ PopupMenuItem::new(t(" Copy Session ID"))
.icon(icon("icons/copy.svg").with_size(px(15.)))
.on_click({
let id = session_id.clone();
@@ -6085,7 +6084,7 @@ impl Workbench {
.when(!menu_is_remote, |menu| {
menu.separator().item(
PopupMenuItem::element(|_, cx| {
- div().text_color(cx.theme().danger).child(MOVE_TO_TRASH)
+ div().text_color(cx.theme().danger).child(move_to_trash())
})
.icon(
icon("icons/trash-2.svg")
@@ -6103,30 +6102,30 @@ impl Workbench {
.anchor(Anchor::TopRight);
let detail_path: SharedString = if meta.project_path.is_empty() {
- "Unknown project".to_string()
+ t("Unknown project").to_string()
} else {
meta.project_path.clone()
}
.into();
let mut detail_facts: Vec<String> = Vec::new();
if meta.message_count > 0 {
- detail_facts.push(format!("{} messages", meta.message_count));
+ detail_facts.push(crate::tf!("{} messages", meta.message_count));
}
if let Some(tokens) = meta.tokens_used {
- detail_facts.push(format!("{} tokens", fmt_tokens(Some(tokens))));
+ detail_facts.push(crate::tf!("{} tokens", fmt_tokens(Some(tokens))));
}
let has_detail_facts = !detail_facts.is_empty();
let detail_fact_line: SharedString = detail_facts.join(" · ").into();
let created_time: Option<(SharedString, SharedString)> = (meta.created_at > 0).then(|| {
(
- format!("Created {}", smart_time(meta.created_at)).into(),
- format!("Created {}", abs_date(meta.created_at)).into(),
+ crate::tf!("Created {}", smart_time(meta.created_at)).into(),
+ crate::tf!("Created {}", abs_date(meta.created_at)).into(),
)
});
let updated_time: Option<(SharedString, SharedString)> = (meta.updated_at > 0).then(|| {
(
- format!("Updated {}", smart_time(meta.updated_at)).into(),
- format!("Updated {}", abs_date(meta.updated_at)).into(),
+ crate::tf!("Updated {}", smart_time(meta.updated_at)).into(),
+ crate::tf!("Updated {}", abs_date(meta.updated_at)).into(),
)
});
let branch: Option<SharedString> =
@@ -6145,7 +6144,7 @@ impl Workbench {
.id("detail-project")
.cursor_pointer()
.tooltip(|window, cx| {
- gpui_component::tooltip::Tooltip::new(SHOW_IN_FM).build(window, cx)
+ gpui_component::tooltip::Tooltip::new(show_in_fm()).build(window, cx)
})
.on_click(move |_, _, _| terminal::open_in_file_manager(&project_path))
.child(badge)
@@ -6216,9 +6215,9 @@ impl Workbench {
)
.h(px(28.))
.icon(icon("icons/terminal.svg").with_size(px(13.)))
- .label("Copy SSH command")
+ .label(t("Copy SSH command"))
.tooltip(
- "Copy the SSH command that resumes this session on its host",
+ t("Copy the SSH command that resumes this session on its host"),
)
.on_click(cx.listener(|this, _, window, cx| {
this.do_resume(
@@ -6281,8 +6280,8 @@ impl Workbench {
))
.tooltip({
let label: SharedString = match current {
- Some(t) => format!("Open this session in {}", t.display_name()).into(),
- None => "Open this session".into(),
+ Some(t) => crate::tf!("Open this session in {}", t.display_name()).into(),
+ None => t("Open this session").into(),
};
move |window, cx| {
gpui_component::tooltip::Tooltip::new(label.clone()).build(window, cx)
@@ -6302,7 +6301,7 @@ impl Workbench {
// ——静默无操作是死按钮,至少说一声为什么
window.push_notification(
Notification::warning(
- "No terminal application found on PATH",
+ t("No terminal application found on PATH"),
),
cx,
);
@@ -6331,7 +6330,7 @@ impl Workbench {
icon("icons/chevron-down.svg")
.with_size(px(12.)),
)
- .tooltip("Open this session in…")
+ .tooltip(t("Open this session in…"))
.dropdown_menu(move |menu, _, _| {
let mut menu = menu.min_w(px(170.));
for (term, icon_path) in term_items.clone() {
@@ -6373,9 +6372,9 @@ impl Workbench {
"icons/star-filled.svg",
rgb(crate::theme::STAR_YELLOW).into(),
if meta.favorite {
- "Unstar"
+ t("Unstar")
} else {
- "Star"
+ t("Star")
},
meta.favorite,
cx.listener(|this, _, window, cx| {
@@ -6388,9 +6387,9 @@ impl Workbench {
"icons/pin-filled.svg",
theme.primary,
if meta.pinned {
- "Unpin"
+ t("Unpin")
} else {
- "Pin"
+ t("Pin")
},
meta.pinned,
cx.listener(|this, _, window, cx| {
@@ -6564,7 +6563,7 @@ impl Workbench {
.gap(SPACE_SM)
.text_color(theme.muted_foreground)
.child(Spinner::new().small())
- .child(div().text_size(FONT_BODY).child("Loading session…"))
+ .child(div().text_size(FONT_BODY).child(t("Loading session…")))
.into_any_element()
} else if let Some(error) = detail.error.clone() {
let reveal_path = meta.file_path.clone();
@@ -6590,7 +6589,7 @@ impl Workbench {
.text_size(FONT_HEADING)
.font_semibold()
.text_color(theme.foreground)
- .child("Couldn't load this session"),
+ .child(t("Couldn't load this session")),
)
.child(
div()
@@ -6607,7 +6606,7 @@ impl Workbench {
.small()
.rounded(RADIUS_BUTTON)
.icon(icon("icons/folder.svg").with_size(px(13.)))
- .label(REVEAL_IN_FM)
+ .label(reveal_in_fm())
.on_click(move |_, _, _| {
terminal::reveal_in_file_manager(&reveal_path)
}),
@@ -6714,7 +6713,7 @@ fn insight_arrows(
.ghost()
.rounded(RADIUS_BUTTON)
.icon(icon("icons/chevron-left.svg").with_size(px(14.)))
- .tooltip("Previous view")
+ .tooltip(t("Previous view"))
.on_click(on_prev),
)
.when_some(label, |row, label| {
@@ -6734,7 +6733,7 @@ fn insight_arrows(
.ghost()
.rounded(RADIUS_BUTTON)
.icon(icon("icons/chevron-right.svg").with_size(px(14.)))
- .tooltip("Next view")
+ .tooltip(t("Next view"))
.on_click(on_next),
)
}
@@ -6846,60 +6845,70 @@ fn usage_bar_row(
fn prompts_label(n: i64) -> String {
match n {
- 0 => "No prompts".into(),
- 1 => "1 prompt".into(),
- n => format!("{} prompts", thousands(n)),
+ 0 => t("No prompts").into(),
+ // 千分位要按 n 自己格式化,故不走 tp! 的「计数即首参」约定
+ n => crate::i18n::tp("{} prompt", "{} prompts", n, &[&thousands(n)]),
}
}
/// 0–23 时 → "12 AM" / "2 PM" 形制(与 smart_time 的 12 小时制一致)
fn hour_label(h: usize) -> String {
match h % 24 {
- 0 => "12 AM".into(),
- 12 => "12 PM".into(),
- h if h < 12 => format!("{h} AM"),
- h => format!("{} PM", h - 12),
+ 0 => t("12 AM").into(),
+ 12 => t("12 PM").into(),
+ h if h < 12 => crate::tf!("{} AM", h),
+ h => crate::tf!("{} PM", h - 12),
}
}
-const DOW_SHORT: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
-const DOW_PLURAL: [&str; 7] = [
- "Mondays",
- "Tuesdays",
- "Wednesdays",
- "Thursdays",
- "Fridays",
- "Saturdays",
- "Sundays",
-];
-const MONTH_SHORT: [&str; 12] = [
- "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
-];
-const MONTH_FULL: [&str; 12] = [
- "January",
- "February",
- "March",
- "April",
- "May",
- "June",
- "July",
- "August",
- "September",
- "October",
- "November",
- "December",
-];
+// 译文表要到运行时才知道,四张名表因此是函数而非 const;调用点每次取一份
+// 数组(7/12 个 &'static str 的拷贝,栈上,比查一次表还便宜)
+fn dow_short() -> [&'static str; 7] {
+ [
+ t("Mon"), t("Tue"), t("Wed"), t("Thu"), t("Fri"), t("Sat"), t("Sun"),
+ ]
+}
+fn dow_plural() -> [&'static str; 7] {
+ [
+ t("Mondays"),
+ t("Tuesdays"),
+ t("Wednesdays"),
+ t("Thursdays"),
+ t("Fridays"),
+ t("Saturdays"),
+ t("Sundays"),
+ ]
+}
+/// 月份名从 chrono 派生。`%b`/`%B` 的译文本来就在给 smart_time 与 Insights
+/// 副标题用(format.rs、`session_group_label`),再单列 Jan…December 24 条就是
+/// 同一批词的第二份真相——写这版时 zh 包已经漂成「4月」与「4 月」两种写法。
+/// **调用点务必提到循环外**:每次调用是 12 次查表加 12 次日期格式化
+fn month_names(pattern: &'static str) -> [SharedString; 12] {
+ std::array::from_fn(|m| {
+ chrono::NaiveDate::from_ymd_opt(2000, m as u32 + 1, 1)
+ .expect("1..=12 是合法月份")
+ .format(t(pattern))
+ .to_string()
+ .into()
+ })
+}
+fn month_short() -> [SharedString; 12] {
+ month_names("%b")
+}
+fn month_full() -> [SharedString; 12] {
+ month_names("%B")
+}
/// peak 由 render_distribution_section 算一次传入——caption 点名的与
/// 图里高亮的必须是同一根柱
fn dist_caption(range: InsightsRange, peak: usize, peak_n: i64) -> String {
if peak_n == 0 {
- return "When you talk to your agents".into();
+ return t("When you talk to your agents").into();
}
match range {
- InsightsRange::Hour => format!("Most active around {}", hour_label(peak)),
- InsightsRange::Weekday => format!("Most active on {}", DOW_PLURAL[peak]),
- InsightsRange::Month => format!("Most active in {}", MONTH_FULL[peak]),
+ InsightsRange::Hour => crate::tf!("Most active around {}", hour_label(peak)),
+ InsightsRange::Weekday => crate::tf!("Most active on {}", dow_plural()[peak]),
+ InsightsRange::Month => crate::tf!("Most active in {}", month_full()[peak]),
}
}
@@ -6915,6 +6924,18 @@ fn render_distribution(range: InsightsRange, values: &[i64], peak: usize, cx: &A
InsightsRange::Month => px(6.),
};
const CHART_H: f32 = 72.;
+ // 两张名表在逐柱闭包**之外**取一次:闭包体每根柱跑一遍,放进去就是
+ // 12 根柱 × 12 次查表(hour 档不用名表,空着)
+ let long_names: Vec<SharedString> = match range {
+ InsightsRange::Hour => Vec::new(),
+ InsightsRange::Weekday => dow_plural().map(SharedString::from).into(),
+ InsightsRange::Month => month_full().into(),
+ };
+ let tick_names: Vec<SharedString> = match range {
+ InsightsRange::Hour => Vec::new(),
+ InsightsRange::Weekday => dow_short().map(SharedString::from).into(),
+ InsightsRange::Month => month_short().into(),
+ };
v_flex()
.gap(px(6.))
.child(
@@ -6944,12 +6965,7 @@ fn render_distribution(range: InsightsRange, values: &[i64], peak: usize, cx: &A
hour_label(i),
hour_label(i + 1)
),
- InsightsRange::Weekday => {
- format!("{} · {}", prompts_label(n), DOW_PLURAL[i])
- }
- InsightsRange::Month => {
- format!("{} · {}", prompts_label(n), MONTH_FULL[i])
- }
+ _ => format!("{} · {}", prompts_label(n), long_names[i]),
}
.into();
div()
@@ -6971,14 +6987,10 @@ fn render_distribution(range: InsightsRange, values: &[i64], peak: usize, cx: &A
.text_size(FONT_LABEL)
.text_color(theme.muted_foreground)
.children((0..values.len()).map(|i| {
- let tick: Option<&'static str> = match range {
- InsightsRange::Hour => None,
- InsightsRange::Weekday => Some(DOW_SHORT[i]),
- InsightsRange::Month => Some(MONTH_SHORT[i]),
- };
+ let tick = tick_names.get(i).cloned();
div().flex_1().whitespace_nowrap().map(|slot| match tick {
// 每柱都有标签时与柱居中;hour 的稀疏锚点靠左
- Some(t) => slot.flex().justify_center().child(t),
+ Some(name) => slot.flex().justify_center().child(name),
None if i % 6 == 0 => slot.child(hour_label(i)),
None => slot,
})
@@ -7006,6 +7018,7 @@ fn month_ticks(start: chrono::NaiveDate, cx: &App) -> Div {
.h(px(14.))
.text_size(FONT_LABEL)
.text_color(theme.muted_foreground);
+ let names = month_short();
for c in 0..TREND_WEEKS as u64 {
let monday = start + chrono::Days::new(c * 7);
if monday.month() != (monday - chrono::Days::new(7)).month() {
@@ -7014,7 +7027,7 @@ fn month_ticks(start: chrono::NaiveDate, cx: &App) -> Div {
.absolute()
.top_0()
.left(px(DOW_W + WEEK_GAP + c as f32 * WEEK_STEP))
- .child(MONTH_SHORT[monday.month0() as usize]),
+ .child(names[monday.month0() as usize].clone()),
);
}
}
@@ -7098,7 +7111,7 @@ fn trend_layers(series: &[TrendSeries], cx: &App) -> Rc<Vec<TrendLayer>> {
}
}
layers.push(TrendLayer {
- name: "Other".into(),
+ name: t("Other").into(),
color: theme.muted_foreground.opacity(0.35),
weekly: other,
other: true,
@@ -7119,8 +7132,8 @@ fn trend_caption(layers: &[TrendLayer]) -> String {
.map(|l| l.name.clone())
});
match leader {
- Some(name) => format!("Prompts per week by agent · {name} leads this week"),
- None => "Prompts per week by agent".to_string(),
+ Some(name) => crate::tf!("Prompts per week by agent · {} leads this week", name),
+ None => t("Prompts per week by agent").to_string(),
}
}
@@ -7132,16 +7145,15 @@ fn render_week_section(d: &InsightsData, cx: &App) -> AnyElement {
let (cur, prev) = d.last_week_pair();
let note = |now: i64, before: i64| -> (SharedString, Hsla) {
match (now, before) {
- (0, 0) => ("No activity".into(), theme.muted_foreground),
- (_, 0) => ("New this week".into(), theme.primary),
+ (0, 0) => (t("No activity").into(), theme.muted_foreground),
+ (_, 0) => (t("New this week").into(), theme.primary),
_ => {
let pct = ((now - before) as f64 * 100. / before as f64).round() as i64;
match pct {
- 0 => ("Same as last week".into(), theme.muted_foreground),
- p if p > 0 => (format!("{p:+}% vs last week").into(), theme.primary),
+ 0 => (t("Same as last week").into(), theme.muted_foreground),
p => (
- format!("{p:+}% vs last week").into(),
- theme.muted_foreground,
+ crate::tf!("{}% vs last week", format!("{p:+}")).into(),
+ if p > 0 { theme.primary } else { theme.muted_foreground },
),
}
}
@@ -7153,8 +7165,8 @@ fn render_week_section(d: &InsightsData, cx: &App) -> AnyElement {
v_flex()
.gap(SPACE_MD)
.child(switch_section_head(
- "Last 7 days",
- Some("Compared with the 7 days before".into()),
+ t("Last 7 days"),
+ Some(t("Compared with the 7 days before").into()),
None,
cx,
))
@@ -7162,10 +7174,10 @@ fn render_week_section(d: &InsightsData, cx: &App) -> AnyElement {
h_flex()
.gap(px(40.))
.items_start()
- .child(stat("Sessions", cur.sessions, prev.sessions, &thousands))
- .child(stat("Prompts", cur.prompts, prev.prompts, &thousands))
+ .child(stat(t("Sessions"), cur.sessions, prev.sessions, &thousands))
+ .child(stat(t("Prompts"), cur.prompts, prev.prompts, &thousands))
.child(stat(
- "Active days",
+ t("Active days"),
cur.active_days,
prev.active_days,
&thousands,
@@ -7218,11 +7230,7 @@ fn render_trend(start: chrono::NaiveDate, layers: Rc<Vec<TrendLayer>>, cx: &App)
columns = columns.child(column.id(("trend", w)).flex_shrink_0().tooltip(
move |window, cx| {
let monday = start + chrono::Days::new(w as u64 * 7);
- let mut label = format!(
- "Week of {} · {}",
- monday.format("%b %-d"),
- prompts_label(total)
- );
+ let mut label = crate::tf!("Week of {} · {}", monday.format(t("%b %-d")), prompts_label(total));
let breakdown: Vec<String> = layers
.iter()
.filter(|l| l.weekly[w] > 0)
@@ -7310,13 +7318,16 @@ fn render_heatmap(d: &InsightsData, cx: &App) -> AnyElement {
.flex_shrink_0()
.text_size(FONT_LABEL)
.text_color(theme.muted_foreground)
- .children([0usize, 2, 4].map(|r| {
- div()
- .absolute()
- .top(px(r as f32 * STEP - 2.))
- .left_0()
- .child(DOW_SHORT[r])
- }));
+ .children({
+ let names = dow_short();
+ [0usize, 2, 4].map(|r| {
+ div()
+ .absolute()
+ .top(px(r as f32 * STEP - 2.))
+ .left_0()
+ .child(names[r])
+ })
+ });
let mut grid = h_flex().gap(px(GAP)).items_start().child(dow_col);
for c in 0..TREND_WEEKS {
@@ -7337,7 +7348,7 @@ fn render_heatmap(d: &InsightsData, cx: &App) -> AnyElement {
// 只捕获 Copy 的 (start, ix, n),hover 到的那格才格式化
.tooltip(move |window, cx| {
let day = start + chrono::Days::new(ix as u64);
- let label = format!("{} · {}", prompts_label(n), day.format("%b %-d, %Y"));
+ let label = format!("{} · {}", prompts_label(n), day.format(t("%b %-d, %Y")));
gpui_component::tooltip::Tooltip::new(SharedString::from(label))
.build(window, cx)
}),
@@ -7349,17 +7360,13 @@ fn render_heatmap(d: &InsightsData, cx: &App) -> AnyElement {
// 底注:streak/最忙一天(左) + Less…More 图例(右)
let mut notes: Vec<String> = Vec::new();
if d.current_streak > 0 {
- notes.push(format!("{}-day streak", d.current_streak));
+ notes.push(crate::tf!("{}-day streak", d.current_streak));
}
if d.longest_streak > 0 {
- notes.push(format!("Longest {} days", d.longest_streak));
+ notes.push(crate::tf!("Longest {} days", d.longest_streak));
}
if let Some((day, n)) = d.busiest_day() {
- notes.push(format!(
- "Busiest {} ({})",
- day.format("%b %-d"),
- prompts_label(n)
- ));
+ notes.push(crate::tf!("Busiest {} ({})", day.format(t("%b %-d")), prompts_label(n)));
}
let legend = h_flex()
.justify_between()
@@ -7372,7 +7379,7 @@ fn render_heatmap(d: &InsightsData, cx: &App) -> AnyElement {
.gap(px(GAP))
.items_center()
.flex_shrink_0()
- .child("Less")
+ .child(t("Less"))
.children(std::iter::once(0.).chain(HEAT).map(|a: f32| {
div().size(px(CELL)).rounded(RADIUS_CELL).bg(if a == 0. {
theme.muted
@@ -7380,7 +7387,7 @@ fn render_heatmap(d: &InsightsData, cx: &App) -> AnyElement {
theme.primary.opacity(a)
})
}))
- .child("More"),
+ .child(t("More")),
);
v_flex()
@@ -7595,9 +7602,9 @@ fn save_as(
if let Some(dir) = path.parent() {
let _ = store.pref_set("export_dir", &dir.to_string_lossy());
}
- Notification::success(format!("{done} to {}", path.display()))
+ Notification::success(crate::tf!("{} to {}", done, path.display()))
}
- Err(e) => Notification::error(format!("{failed}: {e}")),
+ Err(e) => Notification::error(crate::tf!("{}: {}", failed, e)),
};
window.push_notification(note, cx);
})
@@ -7795,7 +7802,7 @@ fn image_strip(
.text_color(muted)
.cursor_pointer()
.tooltip(|window, cx| {
- gpui_component::tooltip::Tooltip::new("Save original image")
+ gpui_component::tooltip::Tooltip::new(t("Save original image"))
.build(window, cx)
})
.on_click(move |_, window, cx| {
@@ -7811,13 +7818,13 @@ fn image_strip(
cx,
store,
name,
- "Saved",
- "Couldn't save the image",
+ t("Saved"),
+ t("Couldn't save the image"),
move |path| Ok(std::fs::write(path, &*bytes)?),
)
.detach();
})
- .child("Preview unavailable")
+ .child(t("Preview unavailable"))
.child(div().max_w_full().truncate().child(media_type.clone()))
.child(icon("icons/download.svg").with_size(px(14.)))
.into_any_element()
@@ -7837,8 +7844,8 @@ fn image_strip(
.bg(panel)
.text_size(FONT_LABEL)
.text_color(muted)
- .child("Image omitted")
- .child("Transcript limit reached")
+ .child(t("Image omitted"))
+ .child(t("Transcript limit reached"))
.into_any_element(),
});
}
@@ -7931,7 +7938,7 @@ fn markdown_body(
.cursor_pointer()
.hover(|style| style.bg(theme.secondary_hover))
.tooltip(|window, cx| {
- gpui_component::tooltip::Tooltip::new("Copy code").build(window, cx)
+ gpui_component::tooltip::Tooltip::new(t("Copy code")).build(window, cx)
})
.on_click(move |_, _, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(code.to_string()));
@@ -7980,7 +7987,7 @@ fn thinking_panel(
icon.rotate(gpui::Radians(std::f32::consts::FRAC_PI_2))
}),
)
- .child(div().flex_shrink_0().font_medium().child("Thinking"))
+ .child(div().flex_shrink_0().font_medium().child(t("Thinking")))
.when(!expanded, |header| {
header.child(
div()
@@ -8020,7 +8027,7 @@ fn tool_cluster_heading(
arg_cells: usize,
) -> (SharedString, Option<SharedString>) {
match calls {
- [] => ("No tool calls".into(), None),
+ [] => (t("No tool calls").into(), None),
[only] => {
let arg = (!only.input_preview.trim().is_empty())
.then(|| clip_display(&only.input_preview, arg_cells).into());
@@ -8033,7 +8040,7 @@ fn tool_cluster_heading(
.collect::<Vec<_>>()
.join(" · ");
(
- format!("{} tool calls", many.len()).into(),
+ crate::tf!("{} tool calls", many.len()).into(),
Some(clip_display(&names, arg_cells).into()),
)
}
@@ -8122,7 +8129,7 @@ fn tool_cluster(
.text_size(FONT_LABEL)
.text_color(theme.danger)
.bg(theme.danger.opacity(0.12))
- .child(format!("{failed} failed")),
+ .child(crate::tf!("{} failed", failed)),
)
})
.on_click(on_toggle),
@@ -8180,7 +8187,7 @@ fn tool_cluster(
if let Some(input) = input {
item = item.child(tool_section(
format!("tool-copy-{ix}-{call_ix}-input").into(),
- "Input",
+ t("Input"),
input,
false,
mono.clone(),
@@ -8189,7 +8196,7 @@ fn tool_cluster(
} else if let Some(input_preview) = non_blank_tool_text(&call.input_preview) {
item = item.child(tool_section(
format!("tool-copy-{ix}-{call_ix}-input-preview").into(),
- "Input preview",
+ t("Input preview"),
input_preview,
false,
mono.clone(),
@@ -8200,7 +8207,7 @@ fn tool_cluster(
if let Some(output) = call.output.as_deref().and_then(non_blank_tool_text) {
item = item.child(tool_section(
format!("tool-copy-{ix}-{call_ix}-output").into(),
- "Output",
+ t("Output"),
output,
call.is_error,
mono.clone(),
@@ -8231,7 +8238,7 @@ fn tool_section(
let theme = cx.theme();
let (shown, truncated) = clip_tool_text(body, TOOL_TEXT_PREVIEW_LIMIT);
let full = body.to_string();
- let copy_tooltip: SharedString = format!("Copy full {}", label.to_lowercase()).into();
+ let copy_tooltip: SharedString = crate::tf!("Copy full {}", label.to_lowercase()).into();
v_flex()
.w_full()
@@ -8253,7 +8260,7 @@ fn tool_section(
header.child(
div()
.text_color(theme.muted_foreground)
- .child(format!("First {TOOL_TEXT_PREVIEW_LIMIT} characters")),
+ .child(crate::tf!("First {} characters", TOOL_TEXT_PREVIEW_LIMIT)),
)
})
.child(div().flex_1())
@@ -8318,13 +8325,10 @@ fn custom_owner<'a>(
.map(|(_, p)| p)
}
-/// "1 session / N sessions" 单复数文案(Locations 与 Remote hosts 两个
-/// 设置页共用,别让两处各自漂移)
-fn session_tally(n: i64) -> String {
- match n {
- 1 => "1 session".to_string(),
- n => format!("{n} sessions"),
- }
+/// "1 session / N sessions" 单复数文案(Locations、Remote hosts、Data 三个
+/// 设置页共用,别让几处各自漂移)
+pub(crate) fn session_tally(n: i64) -> String {
+ crate::tp!("{} session", "{} sessions", n)
}
fn badge(name: impl Into<SharedString>, bg: Hsla, fg: Hsla) -> impl IntoElement {
@@ -8541,6 +8545,7 @@ impl Focusable for Workbench {
impl Render for Workbench {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ self.sync_language(window, cx);
self.refresh_session_group_date(cx);
self.restore_pending_list_selection(window, cx);
let theme = cx.theme();