feat(i18n,plugin): implement end-to-end i18n & L10n v2 architecture and language pack protocol
- Build single-source-of-truth 7-domain locale catalog (`locales/{zh-CN,en-US}/*.json`, 1,100+ keys) and `cmd/i18ngen` generator emitting Go catalogs and eager/lazy-split TypeScript domain modules (`core`/`vm` eager; `wizard`/`settings`/`plugins` lazy)
- Add zero-dependency ICU MessageFormat subset (`{var}`, `{n, number}`, CLDR `plural`, `select`), 8-hop cycle-free regional fallback (`zh-HK/zh-MO -> zh-Hant -> zh-TW -> zh-CN`), `auto` OS display-language preference, and `en-XA` pseudo-localization across Go and TypeScript
- Introduce `CodedError` supportability with `[E_CODE]` badges, collapsible `[detail]` diagnostics, and automatic SMC OSK / SMBIOS serial / MAC / token redaction
- Add Host × Guest macOS dual-terminology annotation (`FormatGuestTerm`) across 6 official Apple guest UI locales and localize Win32 system tray, file pickers, and DPI-adaptive `installguide` overlays with CJK font fallback probing
- Upgrade L1–L4 plugin localization to dual-track v2: Track A full language packs (`files`, WOFF2 `fonts`, cross-plugin `pluginOverrides`), Track B plugin-scoped `l10n` bundles (`HasUIMessages` isolation), live `plugin/localeChanged` notifications, `< 2ms` static CLI pack loading, and `reims-go plugin locale init|check` translator toolchain with `zh-TW` and `ja-JP` reference packs
- Harden security, WCAG 2.1 AA token contrast, `< 768px` responsive drawer & form layouts, and RTL logical properties; add backend security/locale regression tests and frontend `node --test` static/runtime guard suite in CI
# Conflicts:
# frontend/src/i18n.ts
# internal/cli/cli.go
# internal/i18n/i18n.go
This commit is contained in:
1 parent
21eef18f7b
commit
ceeec602be
123 files changed
+14965
-2965
No files matched your search
@@ -39,10 +39,11 @@ jobs:
|
||||
& ./scripts/build-release-notes.ps1 -Tag $ver -OutFile $tmp
|
||||
Write-Host "PASS CHANGELOG.md contains valid release notes for $ver ($((Get-Item -LiteralPath $tmp).Length) bytes)"
|
||||
|
||||
- name: Frontend build
|
||||
- name: Frontend test & build
|
||||
shell: pwsh
|
||||
run: |
|
||||
pnpm --dir frontend install --frozen-lockfile
|
||||
pnpm --dir frontend test
|
||||
pnpm --dir frontend build
|
||||
|
||||
- name: Debug workspace hygiene check & self-test
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
// Command i18ngen compiles and validates the canonical JSON message catalogs
|
||||
// under locales/{zh-CN,en-US}/*.json, enforcing:
|
||||
// - 100% key parity between zh-CN and en-US in every domain
|
||||
// - valid lightweight ICU AST syntax across every entry
|
||||
// - identical {var} placeholder sets between zh-CN, en-US, and optional $params
|
||||
//
|
||||
// Outputs:
|
||||
// - internal/i18n/catalog_gen.go
|
||||
// - frontend/src/i18n/keys.gen.ts
|
||||
// - frontend/src/i18n/domains/{core,vm,wizard,settings,plugins}.gen.ts
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
var (
|
||||
allDomains = []string{"core", "vm", "wizard", "settings", "plugins", "native", "macos-glossary"}
|
||||
goDomains = []string{"native", "macos-glossary", "core"}
|
||||
feEagerDomains = []string{"core", "vm"}
|
||||
feLazyDomains = []string{"wizard", "settings", "plugins"}
|
||||
)
|
||||
|
||||
type parsedEntry struct {
|
||||
Message string
|
||||
Params []string
|
||||
Comment string
|
||||
MaxLength int
|
||||
}
|
||||
|
||||
func main() {
|
||||
root := "."
|
||||
if _, err := os.Stat("locales/zh-CN/core.json"); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "i18ngen: must be run from repository root: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
zhByDomain := make(map[string]map[string]parsedEntry)
|
||||
enByDomain := make(map[string]map[string]parsedEntry)
|
||||
keyOwnerDomain := make(map[string]string)
|
||||
|
||||
var validationErrors []string
|
||||
|
||||
for _, dom := range allDomains {
|
||||
zhPath := filepath.Join(root, "locales", "zh-CN", dom+".json")
|
||||
enPath := filepath.Join(root, "locales", "en-US", dom+".json")
|
||||
|
||||
zhMap, err := readCatalogFile(zhPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "i18ngen: read %s: %v\n", zhPath, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
enMap, err := readCatalogFile(enPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "i18ngen: read %s: %v\n", enPath, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
for k := range zhMap {
|
||||
if prevDom, exists := keyOwnerDomain[k]; exists {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("duplicate key %q across domains %q and %q", k, prevDom, dom))
|
||||
}
|
||||
keyOwnerDomain[k] = dom
|
||||
if _, ok := enMap[k]; !ok {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] key %q exists in zh-CN but missing in en-US", dom, k))
|
||||
}
|
||||
}
|
||||
for k := range enMap {
|
||||
if _, ok := zhMap[k]; !ok {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] key %q exists in en-US but missing in zh-CN", dom, k))
|
||||
}
|
||||
}
|
||||
|
||||
keys := sortedKeys(zhMap)
|
||||
for _, k := range keys {
|
||||
ze, ok := zhMap[k]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ee, ok := enMap[k]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
_, zhVars, zErr := i18n.ParseICU(ze.Message)
|
||||
if zErr != nil {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] zh-CN %q invalid ICU syntax: %v", dom, k, zErr))
|
||||
continue
|
||||
}
|
||||
_, enVars, eErr := i18n.ParseICU(ee.Message)
|
||||
if eErr != nil {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] en-US %q invalid ICU syntax: %v", dom, k, eErr))
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(zhVars, enVars) {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] placeholder mismatch for %q: zh-CN=%v vs en-US=%v", dom, k, zhVars, enVars))
|
||||
}
|
||||
if len(ze.Params) > 0 {
|
||||
decl := append([]string(nil), ze.Params...)
|
||||
sort.Strings(decl)
|
||||
if !reflect.DeepEqual(decl, zhVars) {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] zh-CN $params %v does not match template vars %v for %q", dom, ze.Params, zhVars, k))
|
||||
}
|
||||
}
|
||||
if len(ee.Params) > 0 {
|
||||
decl := append([]string(nil), ee.Params...)
|
||||
sort.Strings(decl)
|
||||
if !reflect.DeepEqual(decl, enVars) {
|
||||
validationErrors = append(validationErrors, fmt.Sprintf("[%s] en-US $params %v does not match template vars %v for %q", dom, ee.Params, enVars, k))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
zhByDomain[dom] = zhMap
|
||||
enByDomain[dom] = enMap
|
||||
}
|
||||
|
||||
if len(validationErrors) > 0 {
|
||||
for _, msg := range validationErrors {
|
||||
fmt.Fprintln(os.Stderr, "ERROR:", msg)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if err := writeGoCatalog(root, zhByDomain, enByDomain); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "i18ngen: write Go catalog: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := writeFrontendCatalogs(root, zhByDomain, enByDomain); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "i18ngen: write frontend catalogs: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println("i18ngen: OK")
|
||||
}
|
||||
|
||||
func readCatalogFile(path string) (map[string]parsedEntry, error) {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var rawMap map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &rawMap); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]parsedEntry, len(rawMap))
|
||||
for k, v := range rawMap {
|
||||
if strings.HasPrefix(k, "$") {
|
||||
continue
|
||||
}
|
||||
var plain string
|
||||
if err := json.Unmarshal(v, &plain); err == nil {
|
||||
out[k] = parsedEntry{Message: plain}
|
||||
continue
|
||||
}
|
||||
var meta struct {
|
||||
Message string `json:"message"`
|
||||
Params []string `json:"$params"`
|
||||
Comment string `json:"$comment"`
|
||||
MaxLength int `json:"$maxLength"`
|
||||
}
|
||||
if err := json.Unmarshal(v, &meta); err != nil {
|
||||
return nil, fmt.Errorf("key %q: %w", k, err)
|
||||
}
|
||||
out[k] = parsedEntry{
|
||||
Message: meta.Message,
|
||||
Params: meta.Params,
|
||||
Comment: meta.Comment,
|
||||
MaxLength: meta.MaxLength,
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func sortedKeys[V any](m map[string]V) []string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
func writeGoCatalog(root string, zhByDom, enByDom map[string]map[string]parsedEntry) error {
|
||||
zhMerged := make(map[string]string)
|
||||
enMerged := make(map[string]string)
|
||||
params := make(map[string][]string)
|
||||
|
||||
for _, dom := range goDomains {
|
||||
for k, e := range zhByDom[dom] {
|
||||
zhMerged[k] = e.Message
|
||||
if len(e.Params) > 0 {
|
||||
params[k] = e.Params
|
||||
} else if ee := enByDom[dom][k]; len(ee.Params) > 0 {
|
||||
params[k] = ee.Params
|
||||
} else {
|
||||
_, vars, _ := i18n.ParseICU(e.Message)
|
||||
if len(vars) > 0 {
|
||||
params[k] = vars
|
||||
}
|
||||
}
|
||||
}
|
||||
for k, e := range enByDom[dom] {
|
||||
enMerged[k] = e.Message
|
||||
}
|
||||
}
|
||||
|
||||
keys := sortedKeys(zhMerged)
|
||||
var b bytes.Buffer
|
||||
b.WriteString("// Code generated by cmd/i18ngen; DO NOT EDIT.\n\npackage i18n\n\n")
|
||||
b.WriteString("var catalog = map[Locale]map[string]string{\n")
|
||||
b.WriteString("\tZhCN: {\n")
|
||||
for _, k := range keys {
|
||||
fmt.Fprintf(&b, "\t\t%q: %q,\n", k, zhMerged[k])
|
||||
}
|
||||
b.WriteString("\t},\n\tEnUS: {\n")
|
||||
for _, k := range keys {
|
||||
fmt.Fprintf(&b, "\t\t%q: %q,\n", k, enMerged[k])
|
||||
}
|
||||
b.WriteString("\t},\n}\n\n")
|
||||
|
||||
paramKeys := sortedKeys(params)
|
||||
b.WriteString("var paramOrder = map[string][]string{\n")
|
||||
for _, k := range paramKeys {
|
||||
p := params[k]
|
||||
quoted := make([]string, len(p))
|
||||
for i, name := range p {
|
||||
quoted[i] = fmt.Sprintf("%q", name)
|
||||
}
|
||||
fmt.Fprintf(&b, "\t%q: {%s},\n", k, strings.Join(quoted, ", "))
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
|
||||
return os.WriteFile(filepath.Join(root, "internal/i18n/catalog_gen.go"), b.Bytes(), 0o644)
|
||||
}
|
||||
|
||||
func writeFrontendCatalogs(root string, zhByDom, enByDom map[string]map[string]parsedEntry) error {
|
||||
feDir := filepath.Join(root, "frontend/src/i18n")
|
||||
domDir := filepath.Join(feDir, "domains")
|
||||
if err := os.MkdirAll(domDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Merge macos-glossary into frontend core domain as well so UI components can use official glossary keys.
|
||||
feDomains := []string{"core", "vm", "wizard", "settings", "plugins"}
|
||||
var allFEKeys []string
|
||||
|
||||
for _, dom := range feDomains {
|
||||
zhMap := make(map[string]string)
|
||||
enMap := make(map[string]string)
|
||||
for k, v := range zhByDom[dom] {
|
||||
zhMap[k] = v.Message
|
||||
}
|
||||
for k, v := range enByDom[dom] {
|
||||
enMap[k] = v.Message
|
||||
}
|
||||
if dom == "core" {
|
||||
for k, v := range zhByDom["macos-glossary"] {
|
||||
zhMap[k] = v.Message
|
||||
}
|
||||
for k, v := range enByDom["macos-glossary"] {
|
||||
enMap[k] = v.Message
|
||||
}
|
||||
}
|
||||
|
||||
keys := sortedKeys(zhMap)
|
||||
allFEKeys = append(allFEKeys, keys...)
|
||||
|
||||
isLazy := false
|
||||
for _, ld := range feLazyDomains {
|
||||
if ld == dom {
|
||||
isLazy = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
var b bytes.Buffer
|
||||
b.WriteString("// Code generated by cmd/i18ngen; DO NOT EDIT.\n")
|
||||
if isLazy {
|
||||
b.WriteString("import { registerBuiltinDomain } from '../runtime'\n\n")
|
||||
} else {
|
||||
b.WriteString("\n")
|
||||
}
|
||||
fmt.Fprintf(&b, "export const %sZh: Record<string, string> = {\n", dom)
|
||||
for _, k := range keys {
|
||||
fmt.Fprintf(&b, " %s: %s,\n", tsQuoted(k), tsQuoted(zhMap[k]))
|
||||
}
|
||||
b.WriteString("}\n\n")
|
||||
fmt.Fprintf(&b, "export const %sEn: Record<string, string> = {\n", dom)
|
||||
for _, k := range keys {
|
||||
fmt.Fprintf(&b, " %s: %s,\n", tsQuoted(k), tsQuoted(enMap[k]))
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
if isLazy {
|
||||
fmt.Fprintf(&b, "\nregisterBuiltinDomain(%sZh, %sEn)\n", dom, dom)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(filepath.Join(domDir, dom+".gen.ts"), b.Bytes(), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
sort.Strings(allFEKeys)
|
||||
var kb bytes.Buffer
|
||||
kb.WriteString("// Code generated by cmd/i18ngen; DO NOT EDIT.\n\n")
|
||||
kb.WriteString("export type I18nKey =\n")
|
||||
for i, k := range allFEKeys {
|
||||
sep := ""
|
||||
if i == len(allFEKeys)-1 {
|
||||
sep = ";"
|
||||
}
|
||||
fmt.Fprintf(&kb, " | %s%s\n", tsQuoted(k), sep)
|
||||
}
|
||||
return os.WriteFile(filepath.Join(feDir, "keys.gen.ts"), kb.Bytes(), 0o644)
|
||||
}
|
||||
|
||||
func tsQuoted(s string) string {
|
||||
raw, _ := json.Marshal(s)
|
||||
return string(raw)
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
2. **包装而非重写引擎**:通过受控子进程调用上游 `reims-ctl`、`reims-util` 与 `qemu-img`,不手写易随上游演进失效的 QEMU 启动参数拼接逻辑。
|
||||
3. **GUI 与 CLI 单文件同源**:所有业务逻辑下沉在 `internal/`。无参数启动 Wails 桌面窗口,带子命令(`reims-go <subcommand>`)进入命令行模式,供终端、脚本与自动化工具调用。
|
||||
4. **数据目录隔离**:运行时、下载缓存、虚拟机磁盘、快照与临时文件全部落在用户选定的 `<DataRoot>` 下,不污染系统盘。
|
||||
5. **原生中英双语**:前后端内置 `zh-CN` / `en-US` 双语字典,自动跟随系统语言并支持运行时切换。
|
||||
5. **同构多语言与语言包扩展**:单一事实源分域 JSON 词表(`locales/`)在编译期同时生成 Go 与 TypeScript 类型安全字典,前后端共用轻量 ICU 消息语法与多跳区域回退链;主程序内置 `zh-CN` 与 `en-US`(默认 `auto` 跟随系统并支持热切换),其他语种通过 L1 声明式语言包插件按需扩展并覆盖桌面界面、Win32 原生浮层、系统托盘与命令行。
|
||||
6. **跨平台开发友好**:所有 Windows 原生 API(WHPX、注册表、处理器拓扑、进程亲和性、系统代理、托盘)严格隔离在 `*_windows.go`,提供 `*_other.go` 桩实现,确保非 Windows 环境也能执行 `go build` 与 `go test ./...`。
|
||||
|
||||
---
|
||||
@@ -66,7 +66,8 @@ flowchart TB
|
||||
| `internal/guesttools` | 本地回环鉴权 HTTP/WebDAV 服务:图文双向剪贴板、共享目录、Windows 盘符只读共享、防休眠开关与 `REIMSTOOLS` 辅助盘生成 |
|
||||
| `internal/opencore` | 改写 OpenCore 镜像中的 `prev-lang:kbd`,实现系统外预设 macOS 语言 |
|
||||
| `internal/netproxy` | 统一 HTTP Transport:优先环境变量代理,回退读取 Windows 系统代理配置 |
|
||||
| `internal/config`、`internal/i18n` | 应用配置持久化(`reims-go.json`)与 Go 端双语消息/结构化错误码 |
|
||||
| `locales/`、`cmd/i18ngen` | 单一事实源分域 JSON 词表(含译者上下文 `$comment` 与 Apple macOS 官方多语种词汇表)及编译期前后端字典代码生成器 |
|
||||
| `internal/config`、`internal/i18n` | 应用配置持久化(`reims-go.json`)、轻量 ICU 格式化引擎、多跳语言回退链与带稳定排障码的结构化错误(`CodedError`) |
|
||||
| `internal/thumb`、`internal/tray`、`internal/version` | 4K 截屏行级缩放预览、Windows 系统托盘常驻、版本信息与新版本检查 |
|
||||
| `frontend/src` | 桌面界面:`components/`(页面与对话框)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) |
|
||||
| `patches/` | 上游临时补丁队列与 PR 跟踪,见 [`patches/README.md`](../patches/README.md) |
|
||||
|
||||
@@ -82,7 +82,7 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台
|
||||
## 6. 视觉、图标与无障碍基线
|
||||
|
||||
- **样式令牌化**:所有颜色、字号、间距(4 px 网格)、圆角与阴影统一引用 [`frontend/src/styles/tokens.css`](../frontend/src/styles/tokens.css) 中的 CSS 变量,禁止在组件内联写死颜色或字号。
|
||||
- **字体**:内嵌开源 Inter Variable 作为拉丁字体,并针对 Windows DirectWrite 特性显式映射中文字体字重,避免正文过细或中英混排断层。
|
||||
- **字体与区域排印**:内嵌开源 Inter Variable 作为拉丁字体,并通过动态 `<html lang dir>` 与 `:lang()` 选择器按区域分离东亚字体栈(简体、繁体、日文、韩文各自优先匹配对应系统 UI 字体,避免 Han Unification 异体字混用);繁体与日文正文采用 `400` 字重与更舒展的行高防止高笔画糊字,开启中西文自动盘古间距;Win32 原生引导浮层按脚本分级探测 GDI 字体并支持卡片宽度自适应与长按钮纵向堆叠。语言包插件可附带沙箱校验的 `.woff2` 字体补齐缺字宿主。
|
||||
- **按钮层级**:每视图至多 1 个实底主按钮;常用操作用次按钮或图标按钮;破坏性操作仅用红字出现在菜单与确认框。
|
||||
- **纯图标按钮边界**:仅当图标含义通用(启动、停止、设置、更多、新建、复制、关闭、刷新、日志)且既非主操作也非破坏性操作时才允许纯图标;所有纯图标按钮必须具备悬停 Tooltip(含快捷键)、`aria-label` 与 ≥ 28×28 px 的点击热区。领域专有操作(如「弹出安装盘」「显示 VM 窗口」「重启以应用」)必须保留文字。
|
||||
- **键盘与缩放**:所有可交互项必须为原生 `<button>` 或带完整 ARIA 语义的 Radix 基件,提供 `:focus-visible` 焦点环;全局快捷键包括 `Ctrl+N`(新建)、`Ctrl+B`(折叠侧栏)、`Ctrl+,`(设置)、`Ctrl+L`(日志)。最小窗口尺寸 960×640,需在 100% / 125% / 150% DPI 下无文字截断。
|
||||
@@ -101,9 +101,9 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台
|
||||
| `x86-64 macOS guest (q35 and OpenCore, WHPX)` | 本地化简述(如「macOS · Intel · WHPX 加速」) | 技术信息 |
|
||||
| `user (MAC configured), ssh on 127.0.0.1:2222` | 「NAT · SSH 2222」 | 技术信息 |
|
||||
| 环境变量或底层参数名(如 `REIMS_VGPU_LOG`) | 用效果命名标题,不把变量名放进标题 | 描述或技术信息 |
|
||||
| 内部错误原始文本 | 本地化的一句话说明 + 下一步建议 | 详情折叠区 / 日志 |
|
||||
| 内部错误原始文本 | 本地化的一句话说明 + 稳定错误码徽标(如 `[E_VM_CLONE_RUNNING]`) | 详情折叠区保留原始英文技术输出并支持一键复制完整诊断信息 |
|
||||
|
||||
格式化逻辑统一集中在 [`frontend/src/lib/format.ts`](../frontend/src/lib/format.ts),不在组件中零散拼接。
|
||||
格式化逻辑统一集中在 [`frontend/src/lib/format.ts`](../frontend/src/lib/format.ts)(数字、列表与相对时间统一经原生 `Intl` API 按当前语种格式化),不在组件中零散拼接。跨宿主与客户机语言的安装引导提示(如宿主机中文操作英文 macOS 恢复环境)自动采用「宿主译名 (`Guest Term`)」双标,同语种则单标。开发模式下提供 `en-XA` 伪本地化语种用于排查硬编码与长词截断。
|
||||
|
||||
### 7.2 文案风格
|
||||
- **克制直接**:标题用名词;按钮用 2–5 字动词;描述控制在清晰的一句话;不使用「请」「您」「成功」和感叹号;按钮和短提示末尾不加句号。
|
||||
|
||||
@@ -128,7 +128,7 @@ flowchart TB
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `themes`(令牌、配色方案、字体、图标、背景、提示音、样式表、状态装饰) | Builtin · L1 | 按 id,同一时刻仅一个主题包生效 | 回退内置默认主题 |
|
||||
| `uiScripts`(交互主题脚本) | 主窗口受信任脚本 | 随所属主题包 | 单个功能出错只停用该功能;整体失败回退到无脚本的主题 |
|
||||
| `locales`(多语种语言包:`locale` / `label` / `fallback` / `file` / `backendFile` / `messages` / `backend`) | Builtin · L1(纯 JSON,免高危权限) | 按 BCP-47 语种合并,自动出现在设置语言下拉框 | 缺失词条回退 `fallback` / 内置英语;停用插件后自动回退内置语言 |
|
||||
| `locales`(声明式语言包:分域 `files`、可选包内 `.woff2` 字体、`pluginOverrides` 跨插件翻译覆盖) | Builtin · L1(纯 JSON + WOFF2,免高危权限) | 按 BCP-47 语种与信任等级合并,覆盖 GUI、Win32 浮层、托盘与 CLI | 缺失词条沿有界多跳 `fallback` 链回退至内置语种;单条坏模板自动回退不崩宿主 |
|
||||
| `inputFilters` | Builtin · L1(仅声明式规则) | 有序列表 | 规则非法即忽略;宿主输入服务异常时卸载钩子、放行原始输入 |
|
||||
| `vmTemplates` | Builtin · L1 | 列表 | 跳过非法项 |
|
||||
| `runtimeSources` | Builtin · L1 | 列表 | 跳过该源,回退其他源 |
|
||||
@@ -302,7 +302,8 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
| :--- | :--- |
|
||||
| `schema` | 清单格式版本 |
|
||||
| `id` / `version` | 反向域名 id;SemVer |
|
||||
| `name` / `description` | `zh-CN` / `en-US` 本地化文本,**无需执行插件代码即可读取** |
|
||||
| `name` / `description` | 多语种本地化文本(内置 `zh-CN` / `en-US` 及任意 BCP-47 扩展键),**无需执行插件代码即可读取** |
|
||||
| `l10n` | 可选的包内私有词表目录(如 `"locales"`),存放 `<locale>.json` 供插件自身 UI、iframe 面板与 Sidecar 使用;独立语言包可通过 `pluginOverrides` 在外部补充或覆盖任意第三方插件的清单字段与私有词条 |
|
||||
| `publisher` / `license` / `homepage` | 来源与许可,市场审核依据 |
|
||||
| `engines` | `reims-go` 版本范围与 `pluginApi` 范围,**下载前预检** |
|
||||
| `platforms` | 如 `windows-x64` |
|
||||
@@ -344,7 +345,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
|
||||
## 8. 进程监管与通信协议
|
||||
|
||||
- **协议**:stdin/stdout 双向 JSON-RPC 2.0,采用 `Content-Length` 分帧(LSP 风格);握手交换 `pluginApi` 版本与能力;stdout 只走协议帧,日志一律走 stderr 并由宿主采集。截图、磁盘镜像等大对象不进 JSON,经插件数据目录内的文件路径传递。
|
||||
- **协议**:stdin/stdout 双向 JSON-RPC 2.0,采用 `Content-Length` 分帧(LSP 风格);握手交换 `pluginApi` 版本、能力、当前生效语种(`locale` / `fallbackChain`)及合并后的插件私有词表(`l10nBundle`),运行期切换界面语言时向已运行 Sidecar 广播 `plugin/localeChanged` 通知(不唤醒休眠进程);stdout 只走协议帧,日志一律走 stderr 并由宿主采集。截图、磁盘镜像等大对象不进 JSON,经插件数据目录内的文件路径传递。
|
||||
- **进程模型**:每个 L3 插件独立进程;全部放入设置 `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` 的 Job Object,宿主退出或崩溃时进程树一并回收;L2 脚本宿主额外设置进程内存与 CPU 时间上限。
|
||||
- **健壮性**:单写协程 + 有界队列提供背压;所有请求可取消;回收依据进程句柄而非管道 EOF;子进程不继承协议管道,工作目录固定为 `data/<id>/`;崩溃后指数退避重启,连续失败熔断为 `failed`;升级与配置变更采用「先起新进程、旧进程处理完在途请求再退出」。
|
||||
- **惰性与回收**:按 `activation` 惰性拉起;空闲超时回收;托盘常驻模式下只保留有活动 VM 或后台服务的 Sidecar。
|
||||
@@ -389,7 +390,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
|
||||
| 入口 | 内容 |
|
||||
| :--- | :--- |
|
||||
| CLI | `reims-go plugin list / install / link <dir> / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor / run <id> <command>`;`vm create --driver <id>` |
|
||||
| CLI | `reims-go plugin list / install / link <dir> / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor / locale <init\|check> / run <id> <command>`;`vm create --driver <id>` |
|
||||
| 应用设置 → 插件 | 分组展示内置插件与第三方插件:核心置顶、显示「始终启用」且无开关;其余显示来源与信任标签、权限摘要、启用开关、故障状态与日志入口;本地包导入 |
|
||||
| 插件设置页 | 由 `settings` Schema 渲染,复用现有设置控件,标注生效时机 |
|
||||
| VM 页面 | 按能力位显隐操作;`vm.toolbar` 菜单项支持 `when` 条件;`vm.card` 展示驱动或插件提供的键值信息 |
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<html dir="ltr">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"test": "node --test scripts/test-i18n.mjs",
|
||||
"build": "tsc --noEmit && vite build && node scripts/check-ui-contract.mjs",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { createRequire } from 'node:module'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
const rootDir = path.resolve(__dirname, '..')
|
||||
const srcDir = path.join(rootDir, 'src')
|
||||
const localesDir = path.resolve(rootDir, '..', 'locales', 'en-US')
|
||||
|
||||
// Resolve esbuild from Vite's dependency tree (zero extra npm dependencies per §8.1).
|
||||
const requireFromRoot = createRequire(path.join(rootDir, 'package.json'))
|
||||
const vitePkgPath = requireFromRoot.resolve('vite/package.json')
|
||||
const requireFromVite = createRequire(vitePkgPath)
|
||||
const esbuild = requireFromVite('esbuild')
|
||||
|
||||
async function loadBundledTS(entrySource) {
|
||||
const result = await esbuild.build({
|
||||
stdin: {
|
||||
contents: entrySource,
|
||||
resolveDir: srcDir,
|
||||
sourcefile: 'test-entry.ts',
|
||||
loader: 'ts',
|
||||
},
|
||||
bundle: true,
|
||||
write: false,
|
||||
format: 'esm',
|
||||
platform: 'browser',
|
||||
target: 'es2022',
|
||||
})
|
||||
const code = result.outputFiles[0].text
|
||||
const dataUrl = `data:text/javascript;base64,${Buffer.from(code, 'utf8').toString('base64')}`
|
||||
return import(dataUrl)
|
||||
}
|
||||
|
||||
function walkFiles(dir, exts) {
|
||||
const out = []
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) out.push(...walkFiles(full, exts))
|
||||
else if (exts.some((ext) => entry.name.endsWith(ext))) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
test('Static Guard (CRITICAL-1): lazy i18n domain keys are always backed by domain .gen imports', () => {
|
||||
const lazyDomains = ['wizard', 'settings', 'plugins']
|
||||
const keyToDomain = new Map()
|
||||
for (const dom of ['core', 'vm', ...lazyDomains]) {
|
||||
const raw = JSON.parse(fs.readFileSync(path.join(localesDir, `${dom}.json`), 'utf8'))
|
||||
for (const k of Object.keys(raw)) {
|
||||
if (!k.startsWith('$')) keyToDomain.set(k, dom)
|
||||
}
|
||||
}
|
||||
|
||||
// Known lazy-loaded chunk entry trees (loaded via React.lazy or dynamic import in App.tsx)
|
||||
const lazyEntryBasenames = new Set([
|
||||
'CreateWizard.tsx',
|
||||
'SettingsModal.tsx',
|
||||
'AffinityDialog.tsx',
|
||||
'Setup.tsx',
|
||||
'RuntimeOnline.tsx',
|
||||
'HostView.tsx',
|
||||
'InstallersPage.tsx',
|
||||
'PluginsPage.tsx',
|
||||
'AppSettingsPage.tsx',
|
||||
'AboutPage.tsx',
|
||||
'PluginPanelFrame.tsx',
|
||||
'SchemaForm.tsx',
|
||||
'optimizations.ts',
|
||||
])
|
||||
|
||||
for (const file of walkFiles(srcDir, ['.ts', '.tsx'])) {
|
||||
const rel = path.relative(srcDir, file).replace(/\\/g, '/')
|
||||
if (rel.startsWith('i18n/')) continue
|
||||
const base = path.basename(file)
|
||||
const src = fs.readFileSync(file, 'utf8')
|
||||
|
||||
// Match string literals passed to t(..., 'key'), tr('key'), labelKey: 'key', detailKey: 'key', titleKey: 'key', descKey: 'key'
|
||||
const referencedLazyDomains = new Set()
|
||||
const callMatches = [
|
||||
...src.matchAll(/\b(?:tr|t)\(\s*(?:[a-zA-Z0-9_$.]+\s*,\s*)?'([a-zA-Z0-9_.]+)'/g),
|
||||
...src.matchAll(/\b(?:labelKey|detailKey|titleKey|descKey)\s*:\s*'([a-zA-Z0-9_.]+)'/g),
|
||||
]
|
||||
for (const m of callMatches) {
|
||||
const dom = keyToDomain.get(m[1])
|
||||
if (dom && lazyDomains.includes(dom)) {
|
||||
referencedLazyDomains.add(`${dom}:${m[1]}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (referencedLazyDomains.size === 0) continue
|
||||
|
||||
assert.ok(
|
||||
lazyEntryBasenames.has(base),
|
||||
`Eager module ${rel} references lazy domain keys (${[...referencedLazyDomains].join(', ')})! Either move keys to core/vm or lazy-load the module.`,
|
||||
)
|
||||
|
||||
for (const item of referencedLazyDomains) {
|
||||
const [dom, key] = item.split(':')
|
||||
// Sub-dialogs rendered exclusively inside lazy parent chunks inherit their parent's domain registration
|
||||
if (base === 'AffinityDialog.tsx' && dom === 'settings') continue
|
||||
if (base === 'RuntimeOnline.tsx' && (dom === 'wizard' || dom === 'settings')) continue
|
||||
assert.match(
|
||||
src,
|
||||
new RegExp(`i18n/domains/${dom}\\.gen`),
|
||||
`Module ${rel} uses ${dom} key "${key}" without importing i18n/domains/${dom}.gen`,
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('Static Guard (CRITICAL-2): every stack-*, notice-*, error-boundary*, and toast-* class in TSX exists in CSS', () => {
|
||||
const css =
|
||||
fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8') +
|
||||
'\n' +
|
||||
fs.readFileSync(path.join(srcDir, 'styles', 'tokens.css'), 'utf8')
|
||||
|
||||
const prefixes = ['stack-', 'notice-', 'error-boundary', 'toast-']
|
||||
const used = new Set()
|
||||
for (const file of walkFiles(srcDir, ['.tsx'])) {
|
||||
const src = fs.readFileSync(file, 'utf8')
|
||||
for (const m of src.matchAll(/className\s*=\s*(?:"([^"]+)"|'([^']+)'|\{`([^`]+)`\})/g)) {
|
||||
const raw = (m[1] || m[2] || m[3] || '').replace(/\$\{[^}]+\}/g, ' ')
|
||||
for (const tok of raw.split(/\s+/)) {
|
||||
if (prefixes.some((p) => tok.startsWith(p))) used.add(tok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const cls of used) {
|
||||
const escaped = cls.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
assert.match(css, new RegExp(`\\.${escaped}(?![a-zA-Z0-9_-])`), `Missing CSS rule for .${cls}`)
|
||||
}
|
||||
})
|
||||
|
||||
test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppError (HIGH-2), RTL (L-2), and en-XA', async () => {
|
||||
const mod = await loadBundledTS(`
|
||||
import './i18n/domains/wizard.gen'
|
||||
import './i18n/domains/settings.gen'
|
||||
import './i18n/domains/plugins.gen'
|
||||
export * from './i18n'
|
||||
export * from './lib/format'
|
||||
export * from './lib/themeEngine'
|
||||
`)
|
||||
|
||||
// 1. Built-in bilingual + ICU plural + decimal formatting
|
||||
assert.equal(mod.formatMemory('16G', 'en-US'), '16 GB')
|
||||
assert.equal(mod.formatMemory('1536M', 'de-DE'), '1,5 GB')
|
||||
|
||||
// 2. H-3 & HIGH-9: Functional plugin L10n (has_ui_messages: false) must NOT pollute host UI locales,
|
||||
// while full language pack (has_ui_messages: true) activates properly.
|
||||
mod.setPluginLocales([
|
||||
{
|
||||
locale: 'de-DE',
|
||||
label: 'Deutsch',
|
||||
fallback: 'en-US',
|
||||
has_ui_messages: false,
|
||||
messages: {},
|
||||
plugin_messages: {
|
||||
'acme.de': { 'btn.run': 'Ausführen ({n})' },
|
||||
},
|
||||
},
|
||||
{
|
||||
locale: 'ja-JP',
|
||||
label: '日本語',
|
||||
fallback: 'en-US',
|
||||
has_ui_messages: true,
|
||||
messages: { sidebarSettings: '設定' },
|
||||
plugin_messages: {
|
||||
'acme.de': { 'btn.run': '実行 ({n})' },
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
const opts = mod.getLocaleOptions().map((o) => o.value)
|
||||
assert.ok(opts.includes('ja-JP'), 'ja-JP language pack should appear in UI options')
|
||||
assert.ok(!opts.includes('de-DE'), 'de-DE functional plugin L10n must NOT appear as ghost UI locale')
|
||||
assert.equal(mod.resolveActiveLocale('de-DE'), 'en-US')
|
||||
assert.equal(mod.resolveActiveLocale('ja-JP'), 'ja-JP')
|
||||
assert.equal(mod.t('ja-JP', 'sidebarSettings'), '設定')
|
||||
assert.equal(mod.tPlugin('acme.de', 'de-DE', 'btn.run', { n: 3 }), 'Ausführen (3)')
|
||||
assert.equal(mod.getPluginMessageBundle('acme.de', 'ja-JP')['btn.run'], '実行 ({n})')
|
||||
|
||||
// 3. Pseudo-locale en-XA wraps host & plugin strings in ⟦...⟧ and preserves placeholders
|
||||
const pseudoHost = mod.t('en-XA', 'cores', { n: 8 })
|
||||
assert.ok(pseudoHost.startsWith('⟦') && pseudoHost.endsWith('⟧') && pseudoHost.includes('8'), `bad pseudoHost: ${pseudoHost}`)
|
||||
const pseudoPlugin = mod.tPlugin('acme.de', 'en-XA', 'btn.run', { n: 5 }, 'Run ({n})')
|
||||
assert.ok(pseudoPlugin.startsWith('⟦') && pseudoPlugin.includes('5'), `bad pseudoPlugin: ${pseudoPlugin}`)
|
||||
|
||||
// Reset plugin locales
|
||||
mod.setPluginLocales([])
|
||||
|
||||
// 4. HIGH-2: parseAppError handles suffix & prefix [E_CODE], multi-line summaries, codeless [detail], and Error objects
|
||||
const codedSuffix = mod.parseAppError('First summary line\nSecond summary line [E_VM_BUSY]\n[detail] raw trace line 1\nline 2')
|
||||
assert.equal(codedSuffix.code, 'E_VM_BUSY')
|
||||
assert.equal(codedSuffix.summary, 'First summary line\nSecond summary line')
|
||||
assert.equal(codedSuffix.rawDetail, 'raw trace line 1\nline 2')
|
||||
|
||||
const codedPrefix = mod.parseAppError('[E_VM_BUSY] First summary line\nSecond summary line\n[detail] raw trace line 1\nline 2')
|
||||
assert.equal(codedPrefix.code, 'E_VM_BUSY')
|
||||
assert.equal(codedPrefix.summary, 'First summary line\nSecond summary line')
|
||||
assert.equal(codedPrefix.rawDetail, 'raw trace line 1\nline 2')
|
||||
|
||||
const codelessDetail = mod.parseAppError('Human summary without code\n[detail] exit status 1')
|
||||
assert.equal(codelessDetail.code, undefined)
|
||||
assert.equal(codelessDetail.summary, 'Human summary without code')
|
||||
assert.equal(codelessDetail.rawDetail, 'exit status 1')
|
||||
|
||||
const objErr = mod.parseAppError({ message: 'Timeout [E_NET]' })
|
||||
assert.equal(objErr.code, 'E_NET')
|
||||
assert.equal(objErr.summary, 'Timeout')
|
||||
|
||||
// 5. L-2: 8-subtag RTL parity with Go backend
|
||||
for (const rtl of ['ar-SA', 'he-IL', 'iw-IL', 'fa-IR', 'ur-PK', 'ps-AF', 'dv-MV', 'yi']) {
|
||||
assert.equal(mod.isRTLLocale(rtl), true, `expected RTL for ${rtl}`)
|
||||
}
|
||||
assert.equal(mod.isRTLLocale('en-US'), false)
|
||||
assert.equal(mod.isRTLLocale('zh-TW'), false)
|
||||
|
||||
// 6. LOW-5: resolveGuestLang structured preset lookup without punctuation splitting
|
||||
const zhGuest = mod.resolveGuestLang('zh-CN', 'zh-Hans:0')
|
||||
assert.ok(zhGuest.label.length > 0 && zhGuest.detail && zhGuest.detail.length > 0)
|
||||
|
||||
// 7. HIGH-1: Theme seed token derivation enforces WCAG contrast on bright vs dark accents
|
||||
const brightYellow = mod.deriveTokensFromSeeds({ accent: '#ffd60a' }, undefined, 'light')
|
||||
assert.equal(brightYellow['--accent-text'], '#1d1d1f')
|
||||
assert.ok(brightYellow['--accent-soft-text'], 'expected --accent-soft-text to be derived')
|
||||
|
||||
const appleBlue = mod.deriveTokensFromSeeds({ accent: '#0071e3' }, undefined, 'dark')
|
||||
assert.equal(appleBlue['--accent-text'], '#ffffff')
|
||||
assert.ok(appleBlue['--accent-soft-text'], 'expected --accent-soft-text to be derived')
|
||||
})
|
||||
+59
-16
@@ -11,12 +11,12 @@ import { TitleMenus } from './components/TitleMenus'
|
||||
import { UpdateCapsule, UpdatePhase } from './components/UpdateCapsule'
|
||||
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
|
||||
import { VMAction, VMPage } from './components/VMPage'
|
||||
import { I18nKey, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
|
||||
import { LogLine, appendLog } from './lib/logs'
|
||||
import { macOSMajor } from './lib/macosRelease'
|
||||
import { currentTask, finishedTaskTTL, pruneFinishedTasks, upsertTask } from './lib/tasks'
|
||||
import { applyActiveTheme, type UIStateSnapshot } from './lib/themeEngine'
|
||||
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine'
|
||||
import { latestVMStats } from './lib/vmStats'
|
||||
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types'
|
||||
import { Button, Tip, TooltipProvider } from './ui/controls'
|
||||
@@ -37,7 +37,7 @@ const PluginsPage = lazy(() => import('./components/PluginsPage').then((m) => ({
|
||||
const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
|
||||
const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ default: m.AboutPage })))
|
||||
|
||||
const errText = (e: unknown) => String(e).replace(/^Error:\s*/, '')
|
||||
const errText = (e: unknown) => parseAppError(e).summary
|
||||
|
||||
const failKey: Record<VMAction, I18nKey> = {
|
||||
start: 'failStart',
|
||||
@@ -200,7 +200,17 @@ export const App: React.FC = () => {
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
refresh()
|
||||
Promise.all([
|
||||
api.GetPluginUIContributions().catch(() => null),
|
||||
refresh(),
|
||||
]).then(([pui]) => {
|
||||
if (pui) {
|
||||
setPluginLocales(pui.locales)
|
||||
setPluginUI(pui)
|
||||
} else {
|
||||
setPluginUI({} as PluginUIContributions)
|
||||
}
|
||||
})
|
||||
events.emitUIPong()
|
||||
const offPing = events.onUIPing(() => { events.emitUIPong() })
|
||||
const offState = events.onStateChanged(() => {
|
||||
@@ -216,7 +226,6 @@ export const App: React.FC = () => {
|
||||
}
|
||||
setLogLines((prev) => appendLog(prev, entry))
|
||||
})
|
||||
api.GetPluginUIContributions().then(setPluginUI).catch(() => {})
|
||||
api.GetActiveTheme().then(setActiveThemePayload).catch(() => {})
|
||||
// Tasks: seed from the backend, then follow events.
|
||||
api.GetTasks().then((list) => {
|
||||
@@ -295,10 +304,21 @@ export const App: React.FC = () => {
|
||||
// (VMPage), so a 3-second tick no longer re-renders the whole App.
|
||||
|
||||
setPluginLocales(pluginUI?.locales)
|
||||
const locale: Locale = resolveActiveLocale(state?.config.locale, pluginUI?.locales)
|
||||
const locale: Locale = resolveActiveLocale(state?.config.locale, pluginUI?.locales, state?.detected_locale)
|
||||
const dir = localeDir(locale)
|
||||
useEffect(() => {
|
||||
document.documentElement.lang = locale
|
||||
}, [locale])
|
||||
const html = document.documentElement
|
||||
html.lang = locale === 'en-XA' ? 'en' : locale
|
||||
html.dir = dir
|
||||
html.dataset.locale = locale
|
||||
const chain = buildFallbackChain(locale, pluginUI?.locales)
|
||||
const fontPack = chain
|
||||
.map((step) => pluginUI?.locales?.find((p) => p.locale === step))
|
||||
.find((p) => p?.fonts && p.fonts.length > 0)
|
||||
applyActiveLocaleFonts(fontPack?.fonts)
|
||||
}, [locale, dir, pluginUI?.locales])
|
||||
|
||||
useEffect(() => () => { disposeActiveThemeAndLocaleFonts() }, [])
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const effectiveState = selectedVM ? (state?.transitions[selectedVM.name] ?? selectedVM.state) : ''
|
||||
const pending = selectedVM ? (state?.pending_changes[selectedVM.name] ?? []) : []
|
||||
@@ -378,13 +398,13 @@ export const App: React.FC = () => {
|
||||
// One toast after an update restart: the version changed since the last run.
|
||||
useEffect(() => {
|
||||
const v = state?.app_version
|
||||
if (!v) return
|
||||
if (!v || pluginUI === null) return
|
||||
try {
|
||||
const last = localStorage.getItem('reims-go-last-version')
|
||||
if (last && last !== v) toasts.push({ kind: 'ok', title: tr('updateDoneToast', { v }) })
|
||||
localStorage.setItem('reims-go-last-version', v)
|
||||
} catch {}
|
||||
}, [state?.app_version])
|
||||
}, [state?.app_version, pluginUI !== null])
|
||||
const importRuntime = async () => {
|
||||
try {
|
||||
const file = await api.PickFile(tr('importRuntime'), '*.tar.zst;*.zip')
|
||||
@@ -409,6 +429,8 @@ export const App: React.FC = () => {
|
||||
const uiStateRef = useRef<UIStateSnapshot>({
|
||||
appearance: theme,
|
||||
motion: reducedMotion ? 'reduced' : 'full',
|
||||
locale,
|
||||
dir,
|
||||
view: currentView,
|
||||
vmName: selectedVM?.name ?? '',
|
||||
vmState: effectiveState,
|
||||
@@ -421,6 +443,8 @@ export const App: React.FC = () => {
|
||||
uiStateRef.current = {
|
||||
appearance: theme,
|
||||
motion: reducedMotion ? 'reduced' : 'full',
|
||||
locale,
|
||||
dir,
|
||||
view: currentView,
|
||||
vmName: selectedVM?.name ?? '',
|
||||
vmState: effectiveState,
|
||||
@@ -438,7 +462,8 @@ export const App: React.FC = () => {
|
||||
el.dataset.hasError = String(hasAnyError)
|
||||
el.dataset.sidebarCollapsed = String(!sidebarOpen)
|
||||
el.dataset.safeMode = String(!!state?.safe_mode)
|
||||
}, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode])
|
||||
notifyInteractiveThemeState(uiStateRef.current)
|
||||
}, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme])
|
||||
|
||||
// Apply active theme pack (zero extra CSS for builtin default theme, §5.1 & §8.1).
|
||||
useEffect(() => {
|
||||
@@ -486,8 +511,19 @@ export const App: React.FC = () => {
|
||||
const loadSerial = (name?: string) => loadVMLog(true, name)
|
||||
const loadQemu = (name?: string) => loadVMLog(false, name)
|
||||
|
||||
const fail = (title: string, e: unknown) =>
|
||||
toasts.push({ kind: 'error', title, description: errText(e), action: { label: tr('viewLogs'), onClick: () => openLogs('app') } })
|
||||
const fail = (title: string, e: unknown) => {
|
||||
const parsed = parseAppError(e)
|
||||
toasts.push({
|
||||
kind: 'error',
|
||||
title,
|
||||
description: parsed.summary,
|
||||
errorCode: parsed.code,
|
||||
rawDetail: parsed.rawDetail,
|
||||
detailsLabel: tr('errRawDetailsToggle'),
|
||||
copyDetailsLabel: tr('errCopyDetails'),
|
||||
action: { label: tr('viewLogs'), onClick: () => openLogs('app') },
|
||||
})
|
||||
}
|
||||
|
||||
const runVMAction = async (name: string, action: VMAction, fn: () => Promise<void>, okTitle?: string) => {
|
||||
setBusy((b) => ({ ...b, [name]: action }))
|
||||
@@ -707,10 +743,15 @@ export const App: React.FC = () => {
|
||||
})
|
||||
.catch((e) => {
|
||||
void refresh()
|
||||
const parsed = parseAppError(e)
|
||||
toasts.push({
|
||||
kind: 'error',
|
||||
title: tr('failCreate', { name }),
|
||||
description: errText(e),
|
||||
description: parsed.summary,
|
||||
errorCode: parsed.code,
|
||||
rawDetail: parsed.rawDetail,
|
||||
detailsLabel: tr('errRawDetailsToggle'),
|
||||
copyDetailsLabel: tr('errCopyDetails'),
|
||||
action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } },
|
||||
})
|
||||
})
|
||||
@@ -734,7 +775,8 @@ export const App: React.FC = () => {
|
||||
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
|
||||
shortcutRef.current = (e: KeyboardEvent) => {
|
||||
if (!e.ctrlKey || e.altKey || e.metaKey) return
|
||||
if (showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget) return
|
||||
if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return
|
||||
if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return
|
||||
const k = e.key.toLowerCase()
|
||||
if (k === 'n') { e.preventDefault(); openWizard() }
|
||||
else if (k === ',' && detail) { e.preventDefault(); setShowSettings(true) }
|
||||
@@ -879,6 +921,7 @@ export const App: React.FC = () => {
|
||||
</Suspense>
|
||||
) : (
|
||||
<div className={`workspace rg-p-workspace${sidebarOpen ? '' : ' sidebar-hidden'}`}>
|
||||
{sidebarOpen && <div className="sidebar-backdrop" aria-hidden="true" onClick={toggleSidebar} />}
|
||||
<Sidebar
|
||||
locale={locale}
|
||||
vms={vms}
|
||||
@@ -1176,7 +1219,7 @@ export const App: React.FC = () => {
|
||||
/>
|
||||
)}
|
||||
|
||||
<Toaster items={toasts.items} onRemove={toasts.remove} closeLabel={tr('close')} />
|
||||
<Toaster items={toasts.items} onRemove={toasts.remove} closeLabel={tr('close')} dir={dir} />
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Copy, Download, ExternalLink, RotateCw } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
import { AppUpdateInfo, Locale, Task } from '../types'
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { AlertTriangle, Check, Cpu } from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, parseAppError, t } from '../i18n'
|
||||
import { HostReport, Locale, LogicalCPUInfo, VMAffinityMode, VMAffinityStatus } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
@@ -110,7 +111,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
setDisableEcoQoS(st.disable_eco_qos)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (live) setErr(String(e).replace(/^Error:\s*/, ''))
|
||||
if (live) setErr(parseAppError(e).summary)
|
||||
})
|
||||
.finally(() => {
|
||||
if (live) setLoading(false)
|
||||
@@ -211,7 +212,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
})
|
||||
onApplied(updated)
|
||||
} catch (e) {
|
||||
setErr(String(e).replace(/^Error:\s*/, ''))
|
||||
setErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { getLocaleOptions, I18nKey, t } from '../i18n'
|
||||
import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations'
|
||||
import { AppState, Locale, ResolvedLocalePack } from '../types'
|
||||
@@ -28,6 +29,7 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
const { host, config, optimizations } = state
|
||||
|
||||
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
|
||||
const missingFontScript = state.missing_font_hint || ''
|
||||
|
||||
const guard = (fn: () => Promise<unknown>) => async () => {
|
||||
try {
|
||||
@@ -125,13 +127,16 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('language')}</div>
|
||||
<div className="row-sub">{tr('languageSub')}</div>
|
||||
{missingFontScript && (
|
||||
<div className="row-sub warn-text">{tr('fontMissingFoDHint', { script: missingFontScript })}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<PopupSelect
|
||||
label={tr('language')}
|
||||
value={locale}
|
||||
value={config.locale || 'auto'}
|
||||
onChange={onSetLocale}
|
||||
options={getLocaleOptions(locales)}
|
||||
options={getLocaleOptions(locales, locale, state.detected_locale)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
|
||||
import React, { Suspense, lazy, useEffect, useState } from 'react'
|
||||
import { I18nKey, locText, t } from '../i18n'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, locText, parseAppError, t } from '../i18n'
|
||||
import {
|
||||
GUEST_LANG_PRESETS,
|
||||
guestLangOptions,
|
||||
MEMORY_MARKS,
|
||||
controllerLabel,
|
||||
defaultGuestLang,
|
||||
@@ -180,7 +183,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
setCmdPreview(cmd)
|
||||
setErr('')
|
||||
})
|
||||
.catch((e) => { if (live) setErr(String(e).replace(/^Error:\s*/, '')) })
|
||||
.catch((e) => { if (live) setErr(parseAppError(e).summary) })
|
||||
.finally(() => { if (live) setChecking(false) })
|
||||
}, 200)
|
||||
return () => { live = false; clearTimeout(timer) }
|
||||
@@ -365,7 +368,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
label={tr('guestLangShort')}
|
||||
value={opts.guest_lang || defaultGuestLang(locale)}
|
||||
onChange={(guest_lang) => set({ guest_lang })}
|
||||
options={GUEST_LANG_PRESETS.map((p) => splitLangLabel(p.value, locale === 'zh-CN' ? p.zh : p.en))}
|
||||
options={guestLangOptions(locale)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
@@ -645,7 +648,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
|
||||
})
|
||||
onClose()
|
||||
} catch (e) {
|
||||
setErr(String(e).replace(/^Error:\s*/, ''))
|
||||
setErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
setDriverCreating(false)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React from 'react'
|
||||
import { resolveActiveLocale, t } from '../i18n'
|
||||
import { events } from '../wails'
|
||||
|
||||
interface State {
|
||||
@@ -28,65 +29,25 @@ export class ErrorBoundary extends React.Component<{ children: React.ReactNode }
|
||||
const { error, stack } = this.state
|
||||
if (!error) return this.props.children
|
||||
|
||||
const isZh = (document.documentElement.lang || '').toLowerCase().startsWith('zh')
|
||||
const docLocale = typeof document !== 'undefined' ? document.documentElement.dataset.locale : undefined
|
||||
const loc = resolveActiveLocale(docLocale || undefined)
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
height: '100%',
|
||||
padding: 24,
|
||||
background: 'var(--surface-canvas, #1c1c1e)',
|
||||
color: 'var(--text, #f5f5f7)',
|
||||
fontFamily: 'var(--font-sans, system-ui, sans-serif)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
maxWidth: 560,
|
||||
width: '100%',
|
||||
padding: 20,
|
||||
borderRadius: 12,
|
||||
border: '1px solid var(--border, rgba(128,128,128,0.25))',
|
||||
background: 'var(--surface-1, rgba(128,128,128,0.08))',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 12,
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: 0, fontSize: 16 }}>
|
||||
{isZh ? '界面发生异常' : 'Interface encountered an error'}
|
||||
<div className="error-boundary">
|
||||
<div className="error-boundary-card" role="alert">
|
||||
<h2 className="error-boundary-title">
|
||||
{t(loc, 'errorBoundaryTitle')}
|
||||
</h2>
|
||||
<p style={{ margin: 0, fontSize: 13, opacity: 0.85 }}>
|
||||
{isZh
|
||||
? '渲染过程出现未捕获异常,虚拟机和后台服务不受影响。你可以重新加载界面。'
|
||||
: 'An unexpected UI error occurred. Running VMs and background services are unaffected.'}
|
||||
</p>
|
||||
<pre
|
||||
style={{
|
||||
margin: 0,
|
||||
padding: 10,
|
||||
borderRadius: 8,
|
||||
fontSize: 12,
|
||||
maxHeight: 180,
|
||||
overflow: 'auto',
|
||||
background: 'var(--surface-0, rgba(0,0,0,0.2))',
|
||||
border: '1px solid var(--border, rgba(128,128,128,0.2))',
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-word',
|
||||
}}
|
||||
>
|
||||
<pre className="error-boundary-pre selectable">
|
||||
{error.message || String(error)}
|
||||
{stack ? `\n\n${stack}` : ''}
|
||||
</pre>
|
||||
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
|
||||
<div className="error-boundary-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={() => window.location.reload()}
|
||||
>
|
||||
{isZh ? '重新加载界面' : 'Reload UI'}
|
||||
{t(loc, 'errorBoundaryReload')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Cpu, HardDrive, MemoryStick, Plus, RefreshCw, ShieldCheck, Trash } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format'
|
||||
import { AppState, Locale, StorageBreakdown, Task } from '../types'
|
||||
@@ -154,7 +156,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
<div className="card-title">
|
||||
<span>{tr('storageBreakdownTitle')}</span>
|
||||
<span className="spacer" />
|
||||
<span className="muted tnum" style={{ fontSize: 12, fontWeight: 500 }}>{formatBytes(storage.total_bytes)}</span>
|
||||
<span className="muted tnum" style={{ fontSize: 'var(--fs-12)', fontWeight: 'var(--fw-medium)' }}>{formatBytes(storage.total_bytes, locale)}</span>
|
||||
</div>
|
||||
<div className="storage-bar" aria-hidden="true">
|
||||
{vmsPct > 0 && <div className="storage-seg-vms" style={{ width: `${vmsPct}%` }} />}
|
||||
@@ -164,15 +166,15 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
<div className="storage-legend">
|
||||
<span className="storage-legend-item">
|
||||
<span className="storage-dot storage-seg-vms" aria-hidden="true" />
|
||||
{tr('storageVMs')} · {formatBytes(storage.vms_bytes)}
|
||||
{tr('storageVMs')} · {formatBytes(storage.vms_bytes, locale)}
|
||||
</span>
|
||||
<span className="storage-legend-item">
|
||||
<span className="storage-dot storage-seg-inst" aria-hidden="true" />
|
||||
{tr('storageInstallers')} · {formatBytes(storage.installers_bytes)}
|
||||
{tr('storageInstallers')} · {formatBytes(storage.installers_bytes, locale)}
|
||||
</span>
|
||||
<span className="storage-legend-item">
|
||||
<span className="storage-dot storage-seg-rt" aria-hidden="true" />
|
||||
{tr('storageRuntimes')} · {formatBytes(storage.runtimes_bytes)}
|
||||
{tr('storageRuntimes')} · {formatBytes(storage.runtimes_bytes, locale)}
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { AlertTriangle, Check, ChevronDown, Download, LoaderCircle, Pause, Plus, RefreshCw, Trash } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { macOSMajor } from '../lib/macosRelease'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
|
||||
@@ -158,13 +158,25 @@ export const LogPanel: React.FC<Props> = ({
|
||||
<div
|
||||
className="log-resize-handle"
|
||||
role="separator"
|
||||
tabIndex={0}
|
||||
aria-orientation="horizontal"
|
||||
aria-label={tr('resizeLogPanel')}
|
||||
aria-valuemin={MIN_LOG_HEIGHT}
|
||||
aria-valuemax={MAX_LOG_HEIGHT}
|
||||
aria-valuenow={height}
|
||||
data-dragging={dragging}
|
||||
onPointerDown={onResizeDown}
|
||||
onPointerMove={onResizeMove}
|
||||
onPointerUp={onResizeUp}
|
||||
onPointerCancel={onResizeUp}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return
|
||||
e.preventDefault()
|
||||
const delta = e.key === 'ArrowUp' ? 24 : -24
|
||||
const next = Math.min(MAX_LOG_HEIGHT, Math.max(MIN_LOG_HEIGHT, height + delta))
|
||||
setHeight(next)
|
||||
try { localStorage.setItem(LOG_HEIGHT_KEY, String(next)) } catch {}
|
||||
}}
|
||||
onDoubleClick={() => {
|
||||
setHeight(DEFAULT_LOG_HEIGHT)
|
||||
try { localStorage.setItem(LOG_HEIGHT_KEY, String(DEFAULT_LOG_HEIGHT)) } catch {}
|
||||
@@ -265,16 +277,31 @@ export const LogPanel: React.FC<Props> = ({
|
||||
{tr('logErrorsOnly')}
|
||||
</button>
|
||||
)}
|
||||
<div className="tabs" role="tablist">
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'app'} onClick={() => onTab('app')}>
|
||||
<div
|
||||
className="tabs"
|
||||
role="tablist"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return
|
||||
e.preventDefault()
|
||||
const order: LogTab[] = showSerial ? ['app', 'serial', 'qemu'] : ['app']
|
||||
const cur = Math.max(0, order.indexOf(tab))
|
||||
const isRTL = getComputedStyle(e.currentTarget).direction === 'rtl'
|
||||
const delta = (e.key === 'ArrowRight') !== isRTL ? 1 : -1
|
||||
const next = order[(cur + delta + order.length) % order.length]
|
||||
onTab(next)
|
||||
const btns = e.currentTarget.querySelectorAll<HTMLButtonElement>('[role="tab"]')
|
||||
btns[order.indexOf(next)]?.focus()
|
||||
}}
|
||||
>
|
||||
<button type="button" role="tab" className="tab" tabIndex={tab === 'app' ? 0 : -1} aria-selected={tab === 'app'} onClick={() => onTab('app')}>
|
||||
{tr('logActivity')}
|
||||
</button>
|
||||
{showSerial && (
|
||||
<>
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
|
||||
<button type="button" role="tab" className="tab" tabIndex={tab === 'serial' ? 0 : -1} aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
|
||||
{tr('logSerial')}
|
||||
</button>
|
||||
<button type="button" role="tab" className="tab" aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
|
||||
<button type="button" role="tab" className="tab" tabIndex={tab === 'qemu' ? 0 : -1} aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
|
||||
{tr('logQemu')}
|
||||
</button>
|
||||
</>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { getPluginMessageBundle, localeDir, parseAppError, t } from '../i18n'
|
||||
import { Locale, PanelContribution } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
@@ -52,7 +52,10 @@ export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, a
|
||||
for (const k of ['--surface-0', '--surface-1', '--text', '--text-2', '--border', '--accent', '--font-sans']) {
|
||||
tokens[k] = cs.getPropertyValue(k).trim()
|
||||
}
|
||||
win.postMessage({ type: 'reims:theme', appearance, locale, tokens }, '*')
|
||||
const dir = localeDir(locale)
|
||||
const messages = getPluginMessageBundle(panel.pluginId ?? '', locale)
|
||||
win.postMessage({ type: 'reims:theme', appearance, locale, dir, tokens, messages }, '*')
|
||||
win.postMessage({ type: 'reims:i18n', locale, dir, messages }, '*')
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -76,12 +79,21 @@ export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, a
|
||||
? (rawParams as Record<string, unknown>)
|
||||
: {}
|
||||
try {
|
||||
if (msg.method === 'i18n.getBundle') {
|
||||
const bundle = {
|
||||
locale,
|
||||
dir: localeDir(locale),
|
||||
messages: getPluginMessageBundle(panel.pluginId ?? '', locale),
|
||||
}
|
||||
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: true, result: bundle }, '*')
|
||||
return
|
||||
}
|
||||
const result = await api.PanelBridgeCall(panel.pluginId ?? '', msg.method, params)
|
||||
if (cancelled || iframeRef.current?.contentWindow !== win) return
|
||||
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: true, result }, '*')
|
||||
} catch (err) {
|
||||
if (cancelled || iframeRef.current?.contentWindow !== win) return
|
||||
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: false, error: String(err) }, '*')
|
||||
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: false, error: parseAppError(err).summary || 'RPC failed' }, '*')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,7 +102,7 @@ export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, a
|
||||
cancelled = true
|
||||
window.removeEventListener('message', onMessage)
|
||||
}
|
||||
}, [panel.pluginId, nonce, src])
|
||||
}, [panel.pluginId, nonce, src, locale])
|
||||
|
||||
if (failed || !src) {
|
||||
return (
|
||||
|
||||
@@ -4,6 +4,8 @@ import {
|
||||
Settings2, Shield, ShieldAlert, ShieldCheck, Sparkles, Terminal, Trash2,
|
||||
} from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import {
|
||||
ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions,
|
||||
@@ -583,8 +585,10 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
<div className="stack-3" style={{ padding: 'var(--sp-4)' }}>
|
||||
{(approveTarget.tier === 'L3' || (approveTarget.permissions ?? []).some((p) => p.name === 'ui:script')) && (
|
||||
<div className="notice notice-warn">
|
||||
<ShieldAlert size={15} aria-hidden="true" style={{ marginRight: 6, verticalAlign: '-2px' }} />
|
||||
{tr('pluginApproveL3Warn')}
|
||||
<span className="notice-main">
|
||||
<ShieldAlert size={15} className="notice-icon" aria-hidden="true" />
|
||||
<span>{tr('pluginApproveL3Warn')}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="list">
|
||||
@@ -698,7 +702,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setLogTarget(null)}
|
||||
>
|
||||
<pre className="mono selectable" style={{ padding: 'var(--sp-4)', maxHeight: 360, overflow: 'auto', margin: 0 }}>
|
||||
<pre className="mono selectable" style={{ padding: 'var(--sp-4)', maxHeight: 360, overflow: 'auto', margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
|
||||
{logTarget.text}
|
||||
</pre>
|
||||
</Modal>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Download, LoaderCircle, Pause, RefreshCw } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
import { InstalledRuntime, Locale, RemoteRuntime, Task } from '../types'
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import React from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { locText, t } from '../i18n'
|
||||
import { Locale, SettingProperty, SettingsSchema } from '../types'
|
||||
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { CircleAlert, Copy, Cpu, HardDrive, Info, Keyboard, LucideIcon, Monitor, Wrench } from 'lucide-react'
|
||||
import React, { Suspense, lazy, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, parseAppError, t } from '../i18n'
|
||||
import {
|
||||
GUEST_LANG_PRESETS,
|
||||
splitLangLabel,
|
||||
guestLangOptions,
|
||||
MEMORY_MARKS,
|
||||
findGPU,
|
||||
formatBytes,
|
||||
@@ -175,7 +176,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
|
||||
const updateVMPluginSetting = (pluginID: string, next: Record<string, unknown>) => {
|
||||
setVmPluginVals((prev) => ({ ...prev, [pluginID]: next }))
|
||||
void api.SetPluginSettings(pluginID, detail.name, next).catch((e) => setErr(String(e)))
|
||||
void api.SetPluginSettings(pluginID, detail.name, next).catch((e) => setErr(parseAppError(e).summary))
|
||||
}
|
||||
|
||||
const renderVMPluginGroup = (group: string) => {
|
||||
@@ -258,7 +259,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
setDriveErr('')
|
||||
api.GetVMDriveShareSettings(detail.name)
|
||||
.then((settings) => { if (active) setDriveSettings(settings) })
|
||||
.catch((e) => { if (active) setDriveErr(String(e).replace(/^Error:\s*/, '')) })
|
||||
.catch((e) => { if (active) setDriveErr(parseAppError(e).summary) })
|
||||
return () => { active = false }
|
||||
}, [detail.name])
|
||||
|
||||
@@ -280,7 +281,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
const next = await api.SetVMDriveShareSettings(vmName, enabled, selected)
|
||||
if (activeVMNameRef.current === vmName) setDriveSettings(next)
|
||||
} catch (e) {
|
||||
if (activeVMNameRef.current === vmName) setDriveErr(String(e).replace(/^Error:\s*/, ''))
|
||||
if (activeVMNameRef.current === vmName) setDriveErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
driveBusyRef.current = false
|
||||
setDriveBusy(false)
|
||||
@@ -298,7 +299,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
await api.OpenProcessorScheduling()
|
||||
onHostChanged?.()
|
||||
} catch (e) {
|
||||
setErr(String(e).replace(/^Error:\s*/, ''))
|
||||
setErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
setOpeningSched(false)
|
||||
}
|
||||
@@ -322,7 +323,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
await api.ApplyVMSettings(diff)
|
||||
onSaved()
|
||||
} catch (e) {
|
||||
setErr(String(e).replace(/^Error:\s*/, ''))
|
||||
setErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
@@ -366,7 +367,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
value={form.guest_lang || 'en-US:0'}
|
||||
onChange={(guest_lang) => set({ guest_lang })}
|
||||
options={[
|
||||
...GUEST_LANG_PRESETS.map((p) => splitLangLabel(p.value, locale === 'zh-CN' ? p.zh : p.en)),
|
||||
...guestLangOptions(locale),
|
||||
...(form.guest_lang && !GUEST_LANG_PRESETS.some((p) => p.value === form.guest_lang)
|
||||
? [{ value: form.guest_lang, label: form.guest_lang }]
|
||||
: []),
|
||||
@@ -641,7 +642,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
setResizeResult(res)
|
||||
onDiskChanged?.()
|
||||
} catch (e) {
|
||||
setErr(String(e).replace(/^Error:\s*/, ''))
|
||||
setErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
setDiskOpBusy('')
|
||||
}
|
||||
@@ -656,7 +657,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
setCompactResult(res)
|
||||
onDiskChanged?.()
|
||||
} catch (e) {
|
||||
setErr(String(e).replace(/^Error:\s*/, ''))
|
||||
setErr(parseAppError(e).summary)
|
||||
} finally {
|
||||
setDiskOpBusy('')
|
||||
}
|
||||
@@ -679,9 +680,8 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
<SetValue
|
||||
title={tr('factDisk')}
|
||||
value={tr('diskUsageSummary', {
|
||||
actual: formatBytes(stats.disk_actual_bytes),
|
||||
virtual: formatBytes(stats.disk_virtual_bytes),
|
||||
format: (stats.disk_format || 'qcow2').toUpperCase(),
|
||||
actual: formatBytes(stats.disk_actual_bytes, locale),
|
||||
virtual: formatBytes(stats.disk_virtual_bytes, locale),
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
@@ -749,7 +749,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
</div>
|
||||
{resizeResult && (
|
||||
<div className="notice">
|
||||
<div>{tr('diskResizeDone', { size: formatBytes(resizeResult.new_virtual_bytes) })}</div>
|
||||
<div>{tr('diskResizeDone', { size: formatBytes(resizeResult.new_virtual_bytes, locale) })}</div>
|
||||
<div className="cmd-line cmd-line-spaced">
|
||||
<code>{resizeResult.guest_expand_cmd}</code>
|
||||
{onCopy && (
|
||||
@@ -766,14 +766,11 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
desc={compactResult
|
||||
? compactResult.reclaimed_bytes > 0
|
||||
? tr('diskCompactDone', {
|
||||
before: formatBytes(compactResult.before_bytes),
|
||||
after: formatBytes(compactResult.after_bytes),
|
||||
reclaimed: formatBytes(compactResult.reclaimed_bytes),
|
||||
})
|
||||
: tr('diskCompactNoGain', {
|
||||
before: formatBytes(compactResult.before_bytes),
|
||||
after: formatBytes(compactResult.after_bytes),
|
||||
before: formatBytes(compactResult.before_bytes, locale),
|
||||
after: formatBytes(compactResult.after_bytes, locale),
|
||||
reclaimed: formatBytes(compactResult.reclaimed_bytes, locale),
|
||||
})
|
||||
: tr('diskCompactNoGain')
|
||||
: tr('diskCompactDesc')}
|
||||
disabled={running || !isQcow2}
|
||||
reason={running ? tr('stopBeforeDiskOp') : tr('diskCompactQcow2Only')}
|
||||
@@ -1003,7 +1000,6 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
|
||||
key={c.id}
|
||||
type="button"
|
||||
className="nav-item"
|
||||
aria-selected={cat === c.id}
|
||||
aria-current={cat === c.id ? 'page' : undefined}
|
||||
onClick={() => setCat(c.id)}
|
||||
>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { FolderOpen, HardDrive } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { getLocaleOptions, I18nKey, joinNotices, t } from '../i18n'
|
||||
import { AppState, DataRootCheck, DataRootChoice, Locale, ResolvedLocalePack, Task } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
@@ -40,7 +42,7 @@ export const Setup: React.FC<Props> = (p) => {
|
||||
|
||||
type StepProps = Props & { tr: (k: I18nKey, v?: Record<string, string | number>) => string }
|
||||
|
||||
const FolderStep: React.FC<StepProps> = ({ locale, locales, tr, onLocale, onFolderDone, onError }) => {
|
||||
const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale, onFolderDone, onError }) => {
|
||||
const [choices, setChoices] = useState<DataRootChoice[]>([])
|
||||
const [custom, setCustom] = useState('')
|
||||
const [customMode, setCustomMode] = useState(false)
|
||||
@@ -144,9 +146,9 @@ const FolderStep: React.FC<StepProps> = ({ locale, locales, tr, onLocale, onFold
|
||||
<div className="setup-foot">
|
||||
<PopupSelect
|
||||
label={tr('language')}
|
||||
value={locale}
|
||||
value={state.config.locale || 'auto'}
|
||||
onChange={onLocale}
|
||||
options={getLocaleOptions(locales)}
|
||||
options={getLocaleOptions(locales, locale, state.detected_locale)}
|
||||
/>
|
||||
<Button variant="primary" busy={busy} disabled={!selected || !!check?.error} onClick={next}>{tr('setupContinue')}</Button>
|
||||
</div>
|
||||
|
||||
@@ -62,6 +62,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
listRef.current?.querySelector<HTMLElement>(`[data-id="${CSS.escape(ids[next])}"]`)?.focus()
|
||||
}
|
||||
|
||||
const hasSelectedInList = ids.includes(selected)
|
||||
const navBtn = (
|
||||
id: string,
|
||||
label: string,
|
||||
@@ -80,7 +81,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
className="nav-item"
|
||||
aria-selected={selected === id}
|
||||
aria-label={stateLabel ? t(locale, 'sidebarItemAria', { label, state: stateLabel }) : label}
|
||||
tabIndex={selected === id ? 0 : -1}
|
||||
tabIndex={selected === id || (!hasSelectedInList && id === ids[0]) ? 0 : -1}
|
||||
onClick={() => onSelect(id)}
|
||||
onDoubleClick={onDoubleClick}
|
||||
>
|
||||
|
||||
@@ -41,8 +41,8 @@ import {
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, locText, t } from '../i18n'
|
||||
import {
|
||||
controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel, guestLangLabel,
|
||||
parseMemoryGB, pendingChangeText, splitLangLabel, sshCommand,
|
||||
controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel,
|
||||
parseMemoryGB, pendingChangeText, resolveGuestLang, sshCommand,
|
||||
} from '../lib/format'
|
||||
import { useVMStats } from '../lib/vmStats'
|
||||
import { DiskSnapshot, HostReport, Locale, PendingChange, PluginUIContributions, VMDetail, VMThumbnail } from '../types'
|
||||
@@ -296,7 +296,8 @@ export const VMPage: React.FC<Props> = ({
|
||||
const formatSnapTime = (sec: number) => {
|
||||
if (!sec) return ''
|
||||
try {
|
||||
return new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(sec * 1000))
|
||||
const loc = locale === 'en-XA' ? 'en-US' : locale
|
||||
return new Intl.DateTimeFormat(loc, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(sec * 1000))
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
@@ -448,7 +449,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
const memPct = memGB > 0 && rss > 0 ? clampPct((rss / (memGB * 1024 ** 3)) * 100) : 0
|
||||
const diskKnown = !!stats && stats.disk_virtual_bytes > 0 && stats.disk_actual_bytes > 0
|
||||
const diskPct = diskKnown ? clampPct((stats!.disk_actual_bytes / stats!.disk_virtual_bytes) * 100) : 0
|
||||
const mem = formatMemory(detail.memory)
|
||||
const mem = formatMemory(detail.memory, locale)
|
||||
|
||||
specs.push(
|
||||
{
|
||||
@@ -458,14 +459,14 @@ export const VMPage: React.FC<Props> = ({
|
||||
},
|
||||
{
|
||||
key: 'mem', label: tr('factMemory'), icon: <MemoryStick size={15} aria-hidden="true" />, value: mem,
|
||||
tip: live && rss > 0 ? tr('specMemLiveTip', { mem, used: formatBytes(rss) }) : tr('specMemTip', { mem }),
|
||||
tip: live && rss > 0 ? tr('specMemLiveTip', { mem, used: formatBytes(rss, locale) }) : tr('specMemTip', { mem }),
|
||||
meter: { pct: memPct, tone: '', idle: !live },
|
||||
},
|
||||
{
|
||||
key: 'disk', label: tr('factDisk'), icon: <HardDrive size={15} aria-hidden="true" />,
|
||||
value: diskKnown ? formatDiskUsage(stats!.disk_actual_bytes, stats!.disk_virtual_bytes) : controllerLabel(detail.disk_controller),
|
||||
value: diskKnown ? formatDiskUsage(stats!.disk_actual_bytes, stats!.disk_virtual_bytes, locale) : controllerLabel(detail.disk_controller),
|
||||
tip: diskKnown
|
||||
? tr('specDiskUsage', { ctl: controllerLabel(detail.disk_controller), used: formatBytes(stats!.disk_actual_bytes), max: formatBytes(stats!.disk_virtual_bytes) })
|
||||
? tr('specDiskUsage', { ctl: controllerLabel(detail.disk_controller), used: formatBytes(stats!.disk_actual_bytes, locale), max: formatBytes(stats!.disk_virtual_bytes, locale) })
|
||||
: tr('specDiskTip', { ctl: controllerLabel(detail.disk_controller) }),
|
||||
meter: { pct: diskPct, tone: meterTone(diskPct, 85, 95), idle: !diskKnown },
|
||||
},
|
||||
@@ -481,7 +482,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
},
|
||||
)
|
||||
if (detail.guest_lang) {
|
||||
const lang = splitLangLabel('', guestLangLabel(locale, detail.guest_lang))
|
||||
const lang = resolveGuestLang(locale, detail.guest_lang)
|
||||
specs.push({
|
||||
key: 'lang', label: tr('specLang'), icon: <Globe size={15} aria-hidden="true" />, value: lang.label,
|
||||
tip: lang.detail
|
||||
@@ -588,7 +589,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
<div className={`vm-spec-card rg-p-vm-summary${running ? ' is-live' : ''}`} role="list" data-rg-slot="vm.card">
|
||||
{specs.map((s) => (
|
||||
<Tip key={s.key} label={s.tip}>
|
||||
<div className="vm-spec-cell" role="listitem" tabIndex={-1}>
|
||||
<div className="vm-spec-cell" role="listitem" tabIndex={0}>
|
||||
<span className="vm-spec-icon">{s.icon}</span>
|
||||
<span className="vm-spec-label">{s.label}</span>
|
||||
<span className="vm-spec-val">{s.value}</span>
|
||||
|
||||
+345
-1644
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,351 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
|
||||
export const coreZh: Record<string, string> = {
|
||||
"affinityMenu": "处理器相关性…",
|
||||
"appearance": "外观",
|
||||
"backToEdit": "返回修改",
|
||||
"borderless": "无边框全屏",
|
||||
"cancel": "取消",
|
||||
"clear": "清空",
|
||||
"close": "关闭",
|
||||
"closeWindow": "关闭",
|
||||
"collapseLogs": "收起日志",
|
||||
"copy": "复制",
|
||||
"copyTechInfo": "复制技术信息",
|
||||
"delete": "删除…",
|
||||
"deleteEllipsis": "删除…",
|
||||
"displays": "显示器数量",
|
||||
"eject": "弹出安装盘",
|
||||
"emptyVMs": "还没有虚拟机",
|
||||
"errCopyDetails": "复制排障信息",
|
||||
"errRawDetailsToggle": "技术详情",
|
||||
"errorBoundaryReload": "重新加载界面",
|
||||
"errorBoundaryTitle": "界面遇到意外错误",
|
||||
"expandLogs": "展开日志",
|
||||
"failCreate": "{name} 创建失败",
|
||||
"failDownload": "下载失败",
|
||||
"failGeneric": "操作失败",
|
||||
"failRuntime": "运行时安装失败",
|
||||
"failSSH": "SSH 操作失败",
|
||||
"fontMissingFoDHint": "当前 Windows 缺少 {script} 可选字体包,部分原生弹窗字形可能回退;可在「Windows 设置 › 应用 › 可选功能」添加对应补充字体。",
|
||||
"footerDiskLabel": "磁盘",
|
||||
"footerDiskTip": "虚拟机数据目录:{dir}",
|
||||
"footerDiskValue": "可用 {gb} GB",
|
||||
"footerHostIssue": "虚拟化未就绪",
|
||||
"footerHostIssueTip": "打开「内核」页查看需要处理的项",
|
||||
"footerMemLabel": "内存",
|
||||
"footerMemTip": "系统内存:已用 {used} GB / 共 {total} GB(可用 {avail} GB)",
|
||||
"footerMemValue": "{used} / {total} GB",
|
||||
"footerRunningVMs": "{n, plural, other {# 台运行中}}",
|
||||
"forceStop": "强制关机",
|
||||
"gpuErrMissingExt": "缺少必需 Vulkan 扩展({ext}),请更新显卡驱动或改用 VMware SVGA",
|
||||
"gpuErrVulkanCpu": "软件 Vulkan 实现不满足 vGPU 加速要求,请改用 VMware SVGA",
|
||||
"gpuErrVulkanTooOld": "Vulkan {ver} 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA",
|
||||
"gpuWarnAmdLegacy": "AMD Vega/Polaris 在 Windows 闭源驱动下存在上游已知黑屏/设备丢失问题({ref});若有其他独显请改选独显,否则建议暂用 VMware SVGA",
|
||||
"gpuWarnAmdRdna2": "该 AMD 显卡在 Windows 下存在上游已知设备丢失风险({ref});若卡死黑屏请升级驱动或暂用 VMware SVGA",
|
||||
"guestKbdPinyin": "拼音键盘",
|
||||
"guestKbdUS": "美式键盘",
|
||||
"guestKbdUSRecommended": "美式键盘,推荐",
|
||||
"guestLang": "macOS 系统语言",
|
||||
"guestLangEnUS": "English (US)",
|
||||
"guestLangJaJP": "日本語",
|
||||
"guestLangKoKR": "한국어",
|
||||
"guestLangZhHansUS": "简体中文",
|
||||
"guestLangZhHantUS": "繁體中文",
|
||||
"helpAbout": "关于 Reims-Go",
|
||||
"helpCheckUpdate": "检查更新…",
|
||||
"helpProjectPage": "项目主页",
|
||||
"helpReportIssue": "报告问题",
|
||||
"hideSidebar": "隐藏侧边栏",
|
||||
"hidpiTipFullscreen": "窗口里的 macOS 只能 1x,文字会发虚;改用全屏可得到 HiDPI",
|
||||
"hidpiTipScale": "这块屏幕上 macOS 只能 1x,文字会发虚;把 Windows 缩放调到 150% 或以上可得到 HiDPI",
|
||||
"hidpiTipUnavailable": "这块屏幕像素不够,macOS 只能以 1x 显示",
|
||||
"hostDisplayHint": "主屏 {w}×{h},{scale}% 缩放",
|
||||
"hostNeedsAction": "需要处理",
|
||||
"hostReady": "就绪",
|
||||
"importRuntime": "导入运行时包",
|
||||
"installersRetry": "重试",
|
||||
"jumpLatest": "跳到最新",
|
||||
"localeAuto": "跟随系统",
|
||||
"localeAutoDetail": "当前:{tag}",
|
||||
"logActivity": "活动",
|
||||
"logButton": "日志",
|
||||
"logCopy": "复制日志",
|
||||
"logErrorsOnly": "仅错误/警告",
|
||||
"logQemu": "QEMU",
|
||||
"logSearchPlaceholder": "筛选日志…",
|
||||
"logSerial": "串口",
|
||||
"logsEmpty": "暂无日志",
|
||||
"macos.appsUtilitiesTerminal": "应用程序 › 实用工具 › 终端",
|
||||
"macos.diskUtility": "磁盘工具",
|
||||
"macos.erase": "抹掉",
|
||||
"macos.finder": "访达",
|
||||
"macos.guidPartitionMap": "GUID 分区图",
|
||||
"macos.otherSignInSetUpLater": "其他登录选项 › 稍后设置",
|
||||
"macos.recovery": "恢复",
|
||||
"macos.reinstallMacOS": "重新安装 macOS",
|
||||
"macos.setupAssistant": "设置助理",
|
||||
"macos.showAllDevices": "显示 › 显示所有设备",
|
||||
"macos.utilitiesTerminal": "实用工具 › 终端",
|
||||
"macos.volume": "宗卷",
|
||||
"maximize": "最大化",
|
||||
"menuBar": "菜单栏",
|
||||
"menuHelp": "帮助",
|
||||
"menuVM": "虚拟机",
|
||||
"menuView": "视图",
|
||||
"minimize": "最小化",
|
||||
"more": "更多",
|
||||
"newVM": "新建虚拟机",
|
||||
"newVMEllipsis": "新建虚拟机…",
|
||||
"noRuntimeAlert": "先在「内核」导入运行时包",
|
||||
"off": "关闭",
|
||||
"on": "开启",
|
||||
"openFolder": "打开所在文件夹",
|
||||
"panelLoadFailed": "面板加载失败",
|
||||
"pauseDownload": "暂停下载",
|
||||
"pluginSafeModeShort": "安全模式",
|
||||
"refresh": "刷新",
|
||||
"resLooksLike": "看起来像 {w} × {h}",
|
||||
"resizeLogPanel": "拖动调整日志高度",
|
||||
"resolution": "分辨率",
|
||||
"restart": "重启",
|
||||
"safeModeBanner": "安全模式已启用:已跳过全部第三方插件并回退至内置默认主题",
|
||||
"safeModeManagePlugins": "管理插件",
|
||||
"save": "保存",
|
||||
"settings": "设置",
|
||||
"settingsAbout": "关于",
|
||||
"settingsEllipsis": "设置…",
|
||||
"shortcutBarFullscreen": "切换全屏",
|
||||
"shortcutBarRelease": "释放键盘和鼠标",
|
||||
"showSidebar": "显示侧边栏",
|
||||
"sidebarHost": "内核",
|
||||
"sidebarInstallers": "安装包",
|
||||
"sidebarItemAria": "{label},{state}",
|
||||
"sidebarLabel": "侧边栏",
|
||||
"sidebarPlugins": "插件",
|
||||
"sidebarSettings": "设置",
|
||||
"sidebarSystem": "系统",
|
||||
"sidebarVMs": "虚拟机",
|
||||
"start": "启动",
|
||||
"starting": "启动中",
|
||||
"stop": "关机",
|
||||
"taskAppUpdate": "下载 Reims-Go {v}",
|
||||
"taskCreate": "创建 {name}",
|
||||
"taskDownload": "下载 macOS {v}",
|
||||
"taskRecoveryDownload": "正在为 {name} 拉取并挂载在线恢复镜像",
|
||||
"taskRuntime": "安装运行时 {v}",
|
||||
"tasksRunning": "{n, plural, other {# 个任务进行中}}",
|
||||
"themeDark": "深色",
|
||||
"themeLight": "浅色",
|
||||
"themeSwitchDark": "切换深色外观",
|
||||
"themeSwitchLight": "切换浅色外观",
|
||||
"themeSystem": "跟随系统",
|
||||
"toastAffinityApplied": "处理器相关性已应用({count} 个逻辑处理器 · {mask})",
|
||||
"toastAffinitySaved": "处理器相关性已保存,下次启动时生效",
|
||||
"toastBorderlessNextStart": "已保存全屏启动偏好,重启虚拟机后生效",
|
||||
"toastBorderlessUpdated": "已保存全屏启动偏好",
|
||||
"toastCopied": "已复制",
|
||||
"toastCreated": "{name} 已创建",
|
||||
"toastDownloadPaused": "已暂停,再次下载会从中断处继续",
|
||||
"toastInstallerReady": "macOS {v} 安装包已就绪",
|
||||
"toastRuntimeReady": "运行时 {v} 已安装",
|
||||
"toastSSHConfigWritten": "已写入 Host {alias}",
|
||||
"toastSSHUserSaved": "已保存 SSH 用户名",
|
||||
"toastSaved": "已保存",
|
||||
"toastSavedNextStart": "已保存,下次启动生效",
|
||||
"updateCancel": "取消下载",
|
||||
"updateCapsuleAvailable": "{v} 可用",
|
||||
"updateCapsuleDownloading": "正在下载更新",
|
||||
"updateCapsuleDownloadingPct": "正在下载 {p}%",
|
||||
"updateCapsuleFailed": "更新下载失败",
|
||||
"updateCapsuleOpen": "查看更新详情",
|
||||
"updateCapsuleReady": "{v} 已就绪",
|
||||
"updateConfirmBody": "{n, plural, other {有 # 台虚拟机正在运行。它们不会被关闭,但 Reims-Go 重启的几秒内,剪贴板、共享文件夹和输入法桥接会暂停,之后自动恢复。}}",
|
||||
"updateConfirmTitle": "重启并安装 {v}",
|
||||
"updateConfirmWin10": "这台 Windows 10 宿主依赖冷重启补偿:这些虚拟机里的 macOS 下次重启后不会自动开机,需要手动启动一次。",
|
||||
"updateDoneToast": "已更新到 {v}",
|
||||
"updateDownload": "下载",
|
||||
"updateFailed": "更新失败",
|
||||
"updateLater": "以后再提醒我",
|
||||
"updateRestart": "重启并安装",
|
||||
"updateRetry": "重试",
|
||||
"uptimeHoursMinutes": "{h} 小时 {m} 分",
|
||||
"uptimeMinutesSeconds": "{m} 分 {s} 秒",
|
||||
"uptimeSeconds": "{s} 秒",
|
||||
"viewLogs": "查看日志",
|
||||
}
|
||||
|
||||
export const coreEn: Record<string, string> = {
|
||||
"affinityMenu": "Processor Affinity…",
|
||||
"appearance": "Appearance",
|
||||
"backToEdit": "Edit and retry",
|
||||
"borderless": "Borderless full screen",
|
||||
"cancel": "Cancel",
|
||||
"clear": "Clear",
|
||||
"close": "Close",
|
||||
"closeWindow": "Close",
|
||||
"collapseLogs": "Hide logs",
|
||||
"copy": "Copy",
|
||||
"copyTechInfo": "Copy technical details",
|
||||
"delete": "Delete…",
|
||||
"deleteEllipsis": "Delete…",
|
||||
"displays": "Displays",
|
||||
"eject": "Eject installer",
|
||||
"emptyVMs": "No virtual machines",
|
||||
"errCopyDetails": "Copy diagnostic details",
|
||||
"errRawDetailsToggle": "Technical details",
|
||||
"errorBoundaryReload": "Reload window",
|
||||
"errorBoundaryTitle": "Something went wrong in the window",
|
||||
"expandLogs": "Show logs",
|
||||
"failCreate": "Couldn’t create {name}",
|
||||
"failDownload": "Download failed",
|
||||
"failGeneric": "Something went wrong",
|
||||
"failRuntime": "Runtime install failed",
|
||||
"failSSH": "SSH action failed",
|
||||
"fontMissingFoDHint": "Windows optional {script} fonts are not installed; native overlay text may use fallback glyphs. Install them under Windows Settings › Apps › Optional features.",
|
||||
"footerDiskLabel": "Disk",
|
||||
"footerDiskTip": "VM data folder: {dir}",
|
||||
"footerDiskValue": "{gb} GB free",
|
||||
"footerHostIssue": "Virtualization not ready",
|
||||
"footerHostIssueTip": "Open the Engine page to see what needs attention",
|
||||
"footerMemLabel": "Memory",
|
||||
"footerMemTip": "System memory: {used} GB used / {total} GB total ({avail} GB free)",
|
||||
"footerMemValue": "{used} / {total} GB",
|
||||
"footerRunningVMs": "{n, plural, one {# running} other {# running}}",
|
||||
"forceStop": "Force shut down",
|
||||
"gpuErrMissingExt": "Missing required Vulkan extensions ({ext}); update GPU drivers or use VMware SVGA",
|
||||
"gpuErrVulkanCpu": "Software Vulkan implementation cannot accelerate vGPU; use VMware SVGA",
|
||||
"gpuErrVulkanTooOld": "Vulkan {ver} is below the required 1.3 floor; update GPU drivers or use VMware SVGA",
|
||||
"gpuWarnAmdLegacy": "AMD Vega/Polaris on Windows hits known upstream black-screen/device-loss issues ({ref}); prefer another discrete GPU or use VMware SVGA for now",
|
||||
"gpuWarnAmdRdna2": "This AMD GPU hits known Windows device-loss issues upstream ({ref}); update drivers or use VMware SVGA if it freezes",
|
||||
"guestKbdPinyin": "Pinyin",
|
||||
"guestKbdUS": "US Keyboard",
|
||||
"guestKbdUSRecommended": "US Keyboard, recommended",
|
||||
"guestLang": "macOS system language",
|
||||
"guestLangEnUS": "English (US)",
|
||||
"guestLangJaJP": "Japanese",
|
||||
"guestLangKoKR": "Korean",
|
||||
"guestLangZhHansUS": "Simplified Chinese",
|
||||
"guestLangZhHantUS": "Traditional Chinese",
|
||||
"helpAbout": "About Reims-Go",
|
||||
"helpCheckUpdate": "Check for Updates…",
|
||||
"helpProjectPage": "Project Page",
|
||||
"helpReportIssue": "Report an Issue",
|
||||
"hideSidebar": "Hide sidebar",
|
||||
"hidpiTipFullscreen": "In a window macOS runs at 1x with rough text; full screen gives HiDPI",
|
||||
"hidpiTipScale": "macOS runs at 1x on this screen, with rough text; Windows scaling at 150% or more gives HiDPI",
|
||||
"hidpiTipUnavailable": "This screen has too few pixels; macOS runs at 1x",
|
||||
"hostDisplayHint": "Main display {w}×{h} at {scale}%",
|
||||
"hostNeedsAction": "Needs attention",
|
||||
"hostReady": "Ready",
|
||||
"importRuntime": "Import runtime",
|
||||
"installersRetry": "Retry",
|
||||
"jumpLatest": "Jump to latest",
|
||||
"localeAuto": "System Default",
|
||||
"localeAutoDetail": "Current: {tag}",
|
||||
"logActivity": "Activity",
|
||||
"logButton": "Logs",
|
||||
"logCopy": "Copy logs",
|
||||
"logErrorsOnly": "Errors \u0026 warnings",
|
||||
"logQemu": "QEMU",
|
||||
"logSearchPlaceholder": "Filter logs…",
|
||||
"logSerial": "Serial",
|
||||
"logsEmpty": "No logs yet",
|
||||
"macos.appsUtilitiesTerminal": "Applications › Utilities › Terminal",
|
||||
"macos.diskUtility": "Disk Utility",
|
||||
"macos.erase": "Erase",
|
||||
"macos.finder": "Finder",
|
||||
"macos.guidPartitionMap": "GUID Partition Map",
|
||||
"macos.otherSignInSetUpLater": "Other Sign-In Options › Set Up Later",
|
||||
"macos.recovery": "Recovery",
|
||||
"macos.reinstallMacOS": "Reinstall macOS",
|
||||
"macos.setupAssistant": "Setup Assistant",
|
||||
"macos.showAllDevices": "View › Show All Devices",
|
||||
"macos.utilitiesTerminal": "Utilities › Terminal",
|
||||
"macos.volume": "Volume",
|
||||
"maximize": "Maximize",
|
||||
"menuBar": "Menu bar",
|
||||
"menuHelp": "Help",
|
||||
"menuVM": "VM",
|
||||
"menuView": "View",
|
||||
"minimize": "Minimize",
|
||||
"more": "More",
|
||||
"newVM": "New virtual machine",
|
||||
"newVMEllipsis": "New Virtual Machine…",
|
||||
"noRuntimeAlert": "Import a runtime under Engine first",
|
||||
"off": "Off",
|
||||
"on": "On",
|
||||
"openFolder": "Show in folder",
|
||||
"panelLoadFailed": "Panel failed to load",
|
||||
"pauseDownload": "Pause download",
|
||||
"pluginSafeModeShort": "Safe mode",
|
||||
"refresh": "Refresh",
|
||||
"resLooksLike": "Looks like {w} × {h}",
|
||||
"resizeLogPanel": "Drag to resize log panel",
|
||||
"resolution": "Resolution",
|
||||
"restart": "Restart",
|
||||
"safeModeBanner": "Safe mode is active: all third-party plugins are disabled and the built-in theme is restored",
|
||||
"safeModeManagePlugins": "Manage plugins",
|
||||
"save": "Save",
|
||||
"settings": "Settings",
|
||||
"settingsAbout": "About",
|
||||
"settingsEllipsis": "Settings…",
|
||||
"shortcutBarFullscreen": "Toggle full screen",
|
||||
"shortcutBarRelease": "Release keyboard and mouse",
|
||||
"showSidebar": "Show sidebar",
|
||||
"sidebarHost": "Engine",
|
||||
"sidebarInstallers": "Installers",
|
||||
"sidebarItemAria": "{label}, {state}",
|
||||
"sidebarLabel": "Sidebar",
|
||||
"sidebarPlugins": "Plugins",
|
||||
"sidebarSettings": "Settings",
|
||||
"sidebarSystem": "System",
|
||||
"sidebarVMs": "Virtual machines",
|
||||
"start": "Start",
|
||||
"starting": "Starting",
|
||||
"stop": "Shut down",
|
||||
"taskAppUpdate": "Downloading Reims-Go {v}",
|
||||
"taskCreate": "Creating {name}",
|
||||
"taskDownload": "Downloading macOS {v}",
|
||||
"taskRecoveryDownload": "Downloading online recovery for {name}",
|
||||
"taskRuntime": "Installing runtime {v}",
|
||||
"tasksRunning": "{n, plural, one {# task running} other {# tasks running}}",
|
||||
"themeDark": "Dark",
|
||||
"themeLight": "Light",
|
||||
"themeSwitchDark": "Switch to dark appearance",
|
||||
"themeSwitchLight": "Switch to light appearance",
|
||||
"themeSystem": "System",
|
||||
"toastAffinityApplied": "Processor affinity applied ({count} logical CPUs · {mask})",
|
||||
"toastAffinitySaved": "Processor affinity saved for next start",
|
||||
"toastBorderlessNextStart": "Fullscreen launch saved — applies on next restart",
|
||||
"toastBorderlessUpdated": "Fullscreen launch preference saved",
|
||||
"toastCopied": "Copied",
|
||||
"toastCreated": "{name} created",
|
||||
"toastDownloadPaused": "Paused — downloading again continues where it stopped",
|
||||
"toastInstallerReady": "macOS {v} installer ready",
|
||||
"toastRuntimeReady": "Runtime {v} installed",
|
||||
"toastSSHConfigWritten": "Wrote Host {alias}",
|
||||
"toastSSHUserSaved": "Saved SSH username",
|
||||
"toastSaved": "Saved",
|
||||
"toastSavedNextStart": "Saved — applies on next start",
|
||||
"updateCancel": "Cancel download",
|
||||
"updateCapsuleAvailable": "{v} available",
|
||||
"updateCapsuleDownloading": "Downloading update",
|
||||
"updateCapsuleDownloadingPct": "Downloading {p}%",
|
||||
"updateCapsuleFailed": "Update download failed",
|
||||
"updateCapsuleOpen": "Update details",
|
||||
"updateCapsuleReady": "{v} ready",
|
||||
"updateConfirmBody": "{n, plural, one {# VM is running. It will keep running, while clipboard, shared folders and the input bridge pause for a few seconds until Reims-Go is back.} other {# VMs are running. They will keep running, while clipboard, shared folders and the input bridge pause for a few seconds until Reims-Go is back.}}",
|
||||
"updateConfirmTitle": "Restart to install {v}",
|
||||
"updateConfirmWin10": "This Windows 10 host relies on the cold-reboot workaround: the next time macOS in these VMs restarts, start the VM again by hand.",
|
||||
"updateDoneToast": "Updated to {v}",
|
||||
"updateDownload": "Download",
|
||||
"updateFailed": "Update failed",
|
||||
"updateLater": "Remind me later",
|
||||
"updateRestart": "Restart to install",
|
||||
"updateRetry": "Retry",
|
||||
"uptimeHoursMinutes": "{h}h {m}m",
|
||||
"uptimeMinutesSeconds": "{m}m {s}s",
|
||||
"uptimeSeconds": "{s}s",
|
||||
"viewLogs": "View logs",
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
import { registerBuiltinDomain } from '../runtime'
|
||||
|
||||
export const pluginsZh: Record<string, string> = {
|
||||
"pluginAccentSeed": "强调种子色",
|
||||
"pluginActiveCount": "已启用 {active} / {total}",
|
||||
"pluginActiveTheme": "当前主题包",
|
||||
"pluginAlwaysOn": "核心组件,始终启用",
|
||||
"pluginApproveCheckbox": "我已核对来源与权限,确认启用此插件",
|
||||
"pluginApproveConfirm": "确认启用",
|
||||
"pluginApproveL3Warn": "此插件为原生可执行程序(L3 Sidecar),能够以当前 Windows 账户身份执行任意操作",
|
||||
"pluginApproveTitle": "高危权限确认",
|
||||
"pluginBuiltinSection": "内置插件",
|
||||
"pluginColorSchemes": "配色方案",
|
||||
"pluginColorSchemesHint": "修改种子色派生整套界面色阶",
|
||||
"pluginDeleteScheme": "删除方案",
|
||||
"pluginDone": "完成",
|
||||
"pluginEntryPath": "入口路径",
|
||||
"pluginExternalSection": "已安装插件",
|
||||
"pluginFailDeleteScheme": "删除配色方案失败",
|
||||
"pluginFailEnable": "启用插件失败",
|
||||
"pluginFailImport": "导入插件包失败",
|
||||
"pluginFailLinkDev": "链接开发插件失败",
|
||||
"pluginFailLoad": "加载插件列表失败",
|
||||
"pluginFailLoadSettings": "读取插件设置失败",
|
||||
"pluginFailReadLog": "读取插件日志失败",
|
||||
"pluginFailRemove": "卸载插件失败",
|
||||
"pluginFailSaveScheme": "保存配色方案失败",
|
||||
"pluginFailSaveSettings": "保存插件设置失败",
|
||||
"pluginFailSwitchTheme": "切换主题失败",
|
||||
"pluginFailToggle": "切换插件状态失败",
|
||||
"pluginGlobalSettings": "插件全局设置",
|
||||
"pluginHighRiskNotice": "包含高危权限,启用前需确认",
|
||||
"pluginImportBtn": "导入插件",
|
||||
"pluginImportTitle": "导入本地插件包 (.zip)",
|
||||
"pluginInUse": "使用中不可卸载",
|
||||
"pluginLinkDevBtn": "链接插件开发目录",
|
||||
"pluginLinkDevTitle": "链接本地开发插件目录",
|
||||
"pluginLogEmpty": "暂无日志记录",
|
||||
"pluginLogTitle": "{id} — 日志",
|
||||
"pluginNewScheme": "新建配色方案",
|
||||
"pluginPanelsSection": "插件面板",
|
||||
"pluginPermCount": "{count, plural, other {# 项权限}}",
|
||||
"pluginPermissionsLabel": "权限:{list}",
|
||||
"pluginPublisherLicense": "发布者 / 许可",
|
||||
"pluginRemove": "卸载",
|
||||
"pluginRequestedPerms": "请求权限",
|
||||
"pluginSchemeDefault": "默认",
|
||||
"pluginSchemeModalTitle": "新建配色方案",
|
||||
"pluginSchemeName": "方案名称",
|
||||
"pluginSchemePlaceholder": "如:柔蓝",
|
||||
"pluginSearchEmpty": "没有匹配的插件",
|
||||
"pluginSearchPlaceholder": "筛选插件",
|
||||
"pluginSettings": "插件设置",
|
||||
"pluginStateDegraded": "已降级",
|
||||
"pluginStateFailed": "故障",
|
||||
"pluginStatePending": "等待依赖",
|
||||
"pluginSurfaceSeed": "画布种子色(可选)",
|
||||
"pluginThemeEmptyHint": "导入本地主题包(.zip)后可在此切换外观与配色方案",
|
||||
"pluginThemeHint": "同一时刻仅启用一个主题包,停用后自动回退默认主题",
|
||||
"pluginThemePackLabel": "主题包",
|
||||
"pluginThemeSafeModeHint": "安全模式下固定使用内置默认主题",
|
||||
"pluginThemeSection": "主题扩展",
|
||||
"pluginTrustCommunity": "社区",
|
||||
"pluginTrustDev": "开发",
|
||||
"pluginTrustOfficial": "官方",
|
||||
"pluginTrustVerified": "已审核",
|
||||
"pluginViewLog": "查看日志",
|
||||
}
|
||||
|
||||
export const pluginsEn: Record<string, string> = {
|
||||
"pluginAccentSeed": "Accent seed",
|
||||
"pluginActiveCount": "{active} / {total} active",
|
||||
"pluginActiveTheme": "Active theme pack",
|
||||
"pluginAlwaysOn": "Core component, always on",
|
||||
"pluginApproveCheckbox": "I have reviewed the source and permissions and confirm enabling this plugin",
|
||||
"pluginApproveConfirm": "Confirm enable",
|
||||
"pluginApproveL3Warn": "This plugin runs native code (L3 Sidecar) and can perform arbitrary actions as your Windows user",
|
||||
"pluginApproveTitle": "Approve high-risk permissions",
|
||||
"pluginBuiltinSection": "Built-in plugins",
|
||||
"pluginColorSchemes": "Color schemes",
|
||||
"pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp",
|
||||
"pluginDeleteScheme": "Delete scheme",
|
||||
"pluginDone": "Done",
|
||||
"pluginEntryPath": "Entry path",
|
||||
"pluginExternalSection": "Installed plugins",
|
||||
"pluginFailDeleteScheme": "Couldn’t delete color scheme",
|
||||
"pluginFailEnable": "Couldn’t enable plugin",
|
||||
"pluginFailImport": "Couldn’t import plugin package",
|
||||
"pluginFailLinkDev": "Couldn’t link dev plugin",
|
||||
"pluginFailLoad": "Couldn’t load plugins",
|
||||
"pluginFailLoadSettings": "Couldn’t load plugin settings",
|
||||
"pluginFailReadLog": "Couldn’t read plugin log",
|
||||
"pluginFailRemove": "Couldn’t remove plugin",
|
||||
"pluginFailSaveScheme": "Couldn’t save color scheme",
|
||||
"pluginFailSaveSettings": "Couldn’t save plugin settings",
|
||||
"pluginFailSwitchTheme": "Couldn’t switch theme",
|
||||
"pluginFailToggle": "Couldn’t toggle plugin",
|
||||
"pluginGlobalSettings": "Plugin settings",
|
||||
"pluginHighRiskNotice": "Contains high-risk permissions; approval required before enabling",
|
||||
"pluginImportBtn": "Import plugin",
|
||||
"pluginImportTitle": "Import plugin package (.zip)",
|
||||
"pluginInUse": "In use",
|
||||
"pluginLinkDevBtn": "Link plugin dev folder",
|
||||
"pluginLinkDevTitle": "Link local dev plugin folder",
|
||||
"pluginLogEmpty": "No log entries yet",
|
||||
"pluginLogTitle": "{id} — Log",
|
||||
"pluginNewScheme": "New scheme",
|
||||
"pluginPanelsSection": "Plugin panels",
|
||||
"pluginPermCount": "{count, plural, one {# permission} other {# permissions}}",
|
||||
"pluginPermissionsLabel": "Permissions: {list}",
|
||||
"pluginPublisherLicense": "Publisher / License",
|
||||
"pluginRemove": "Remove",
|
||||
"pluginRequestedPerms": "Requested permissions",
|
||||
"pluginSchemeDefault": "Default",
|
||||
"pluginSchemeModalTitle": "New color scheme",
|
||||
"pluginSchemeName": "Scheme name",
|
||||
"pluginSchemePlaceholder": "e.g. Soft Blue",
|
||||
"pluginSearchEmpty": "No matching plugins",
|
||||
"pluginSearchPlaceholder": "Filter plugins",
|
||||
"pluginSettings": "Plugin settings",
|
||||
"pluginStateDegraded": "Degraded",
|
||||
"pluginStateFailed": "Failed",
|
||||
"pluginStatePending": "Pending",
|
||||
"pluginSurfaceSeed": "Surface seed (optional)",
|
||||
"pluginThemeEmptyHint": "Import a local theme package (.zip) to switch visual themes and color schemes",
|
||||
"pluginThemeHint": "One active theme pack at a time; disabling falls back to the built-in default",
|
||||
"pluginThemePackLabel": "Theme pack",
|
||||
"pluginThemeSafeModeHint": "Built-in default theme is enforced in safe mode",
|
||||
"pluginThemeSection": "Theme extensions",
|
||||
"pluginTrustCommunity": "Community",
|
||||
"pluginTrustDev": "Dev",
|
||||
"pluginTrustOfficial": "Official",
|
||||
"pluginTrustVerified": "Verified",
|
||||
"pluginViewLog": "View log",
|
||||
}
|
||||
|
||||
registerBuiltinDomain(pluginsZh, pluginsEn)
|
||||
@@ -0,0 +1,596 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
import { registerBuiltinDomain } from '../runtime'
|
||||
|
||||
export const settingsZh: Record<string, string> = {
|
||||
"aboutCommunity": "社区与支持",
|
||||
"aboutCopyQQGroup": "复制群号",
|
||||
"aboutIssueSub": "遇到问题或有功能建议,在 GitHub 提交 Issue",
|
||||
"aboutJoinQQGroup": "加入群聊",
|
||||
"aboutProjectSub": "GitHub 上的源码、发布版本与使用文档",
|
||||
"aboutQQGroup": "QQ 交流群",
|
||||
"aboutQQGroupSub": "点击直接拉起 QQ 加群,交流使用与问题反馈",
|
||||
"aboutQQLaunchFailed": "未能拉起 QQ,可复制群号手动搜索加入",
|
||||
"aboutQQNotInstalled": "未安装 QQ",
|
||||
"aboutQQNotInstalledSub": "未检测到本地 QQ,可复制群号手动搜索加入",
|
||||
"aboutTagline": "在 Windows 上开一台带 GPU 加速的 macOS 虚拟机——免编译,开箱即用。",
|
||||
"activate": "使用",
|
||||
"affinityApplyNow": "立即应用",
|
||||
"affinityAvoidLPE": "避开 LP-E",
|
||||
"affinityConfigure": "配置…",
|
||||
"affinityEcoQoS": "禁用 Windows 效率模式节流 (EcoQoS)",
|
||||
"affinityEcoQoSDesc": "防止 Windows 11 在窗口失焦或后台运行时把 QEMU 线程压缩到 2 个低功耗核心",
|
||||
"affinityExcludeCPU0": "排除 CPU 0",
|
||||
"affinityLiveMask": "Windows 当前生效:{mask}({count} 线程)",
|
||||
"affinityModeAll": "所有处理器",
|
||||
"affinityModeAllHint": "允许 Windows 将 QEMU 调度到全部宿主机逻辑处理器。",
|
||||
"affinityModeAuto": "自动",
|
||||
"affinityModeAutoHint": "跟随全局策略,在混合大小核处理器上自动避开超售与低功耗核。",
|
||||
"affinityModeCustom": "自定义",
|
||||
"affinityModeCustomHint": "勾选允许运行 QEMU 的逻辑处理器,等价于 Windows 任务管理器的处理器相关性。",
|
||||
"affinityModeNonLPE": "P + E 核",
|
||||
"affinityModeNonLPEHint": "在性能核与能效核(P + E)上运行,仅排除慢速低功耗核(LP-E)。",
|
||||
"affinityModePCores": "仅 P 核",
|
||||
"affinityModePCoresHint": "仅在性能核(P-Core)上运行,减少大小核混调引起的抖动。",
|
||||
"affinityNeedOne": "请至少勾选 1 个逻辑处理器",
|
||||
"affinityOnlyPCores": "仅 P 核",
|
||||
"affinityOversubWarn": "当前只勾选了 {selected} 个逻辑处理器,少于虚拟机分配的 {vcpus} 个 vCPU,可能导致明显卡顿。",
|
||||
"affinityPhysicalOnly": "仅物理核",
|
||||
"affinityRowDesc": "指定虚拟机在哪些核心上运行,立即生效",
|
||||
"affinitySave": "保存",
|
||||
"affinitySelectAll": "所有处理器",
|
||||
"affinitySelectedSummary": "已选 {selected} / {total} 个逻辑处理器 · 掩码 {mask}",
|
||||
"affinitySubtitleRunning": "运行中(PID {pid})· {vcpus} vCPU · 修改后立即生效",
|
||||
"affinitySubtitleStopped": "已停止 · {vcpus} vCPU · 下次启动时自动生效",
|
||||
"affinitySummaryAll": "所有处理器({count} 线程)",
|
||||
"affinitySummaryAuto": "自动({eff} · {count} 线程)",
|
||||
"affinitySummaryCustom": "自定义({count} 线程 · {mask})",
|
||||
"affinitySummaryNonLPE": "P + E 核({count} 线程 · {mask})",
|
||||
"affinitySummaryPCores": "仅 P 核({count} 线程 · {mask})",
|
||||
"affinityTitle": "处理器核心",
|
||||
"appCheckUpdate": "检查更新",
|
||||
"appDownloadUpdate": "前往下载",
|
||||
"appUpToDate": "已是最新",
|
||||
"appUpdateAvailable": "发现新版本 {v}(稳定版)",
|
||||
"appUpdateLookupFailed": "暂时无法连接 GitHub 检查更新",
|
||||
"appVersionTitle": "客户端版本",
|
||||
"appliesNextStart": "下次启动生效",
|
||||
"audioBackendAuto": "自动",
|
||||
"audioBackendDesc": "「静音」保留 macOS 的声卡但不出声,适合排查音频问题",
|
||||
"audioBackendDsound": "DirectSound",
|
||||
"audioBackendNone": "静音",
|
||||
"audioBackendTitle": "声音输出",
|
||||
"audioDesc": "在 Windows 上播放 macOS 的声音",
|
||||
"audioDisabledReason": "请先开启音频",
|
||||
"audioTroubleshootNote": "有爆音时,把 Windows 声音格式设为 48000 Hz;麦克风没声音时,检查 Windows「隐私 › 麦克风」权限",
|
||||
"autoPinPCores": "启动后绑定到性能核",
|
||||
"back": "上一步",
|
||||
"captureInput": "点击窗口时捕获键鼠",
|
||||
"captureInputHint": "开启后 ⌘Tab 等快捷键交给 macOS;关闭时 Win 键和 Alt+Tab 留给 Windows",
|
||||
"catAdvanced": "高级",
|
||||
"catAudio": "音频",
|
||||
"catCompute": "处理器与内存",
|
||||
"catGeneral": "通用",
|
||||
"catGraphics": "图形与显示器",
|
||||
"catInput": "键盘与指针",
|
||||
"catInputAudio": "输入与音频",
|
||||
"catLogs": "日志",
|
||||
"catNetwork": "网络",
|
||||
"catStorage": "存储",
|
||||
"catStorageNet": "存储与网络",
|
||||
"choose": "浏览…",
|
||||
"configured": "已配置",
|
||||
"coresUnit": "核",
|
||||
"cpuOverHint": "留给 Windows 的线程不足 2 个,电脑可能变卡",
|
||||
"cpuRecHint": "推荐 {rec} 核 · 本机共 {n} 线程",
|
||||
"diskCompactAction": "立即回收",
|
||||
"diskCompactDesc": "把 macOS 里已删除文件占用的空间还给 Windows,过程中需要与当前占用差不多的空闲空间",
|
||||
"diskCompactDone": "已回收 {reclaimed}({before} → {after})",
|
||||
"diskCompactNoGain": "没有可回收的空间",
|
||||
"diskCompactQcow2Only": "这块磁盘不支持回收空间",
|
||||
"diskCompactTitle": "回收空间",
|
||||
"diskController": "磁盘接口",
|
||||
"diskControllerInstallHint": "装机时保持 SATA,装完弹出安装盘再改 NVMe",
|
||||
"diskControllerNvmeHint": "NVMe 读写更快",
|
||||
"diskControllerNvmeReadyHint": "NVMe 速度快,也兼容恢复模式,推荐",
|
||||
"diskControllerVirtioHint": "VirtIO 开销更低,仍属实验性;遇到问题请改回 NVMe",
|
||||
"diskControllerWarn": "切换前先弹出安装盘",
|
||||
"diskMode": "使用方式",
|
||||
"diskModeCopy": "复制一份,不改动原盘",
|
||||
"diskModeInPlace": "直接使用原盘",
|
||||
"diskResizeAction": "扩容",
|
||||
"diskResizeDesc": "只能增大。扩大后在 macOS 终端运行提示的命令,新空间才能使用",
|
||||
"diskResizeDone": "已扩大到 {size}。在 macOS 终端运行:",
|
||||
"diskResizeTitle": "扩大磁盘",
|
||||
"diskSize": "磁盘上限",
|
||||
"diskSizeHint": "按实际占用增长",
|
||||
"diskUsageSummary": "已占用 {actual},上限 {virtual}",
|
||||
"displayGroup": "显示器",
|
||||
"driveShareMaster": "共享 Windows 盘符",
|
||||
"driveShareMasterDesc": "在 macOS 访达中显示所选磁盘,立即生效",
|
||||
"driveShareNeedsTools": "需要 Guest Tools {version} 以上:重启虚拟机,再在 macOS 中重新运行安装命令",
|
||||
"driveShareNoDrives": "没有可共享的内部固定磁盘",
|
||||
"driveShareReadOnly": "只读:macOS 可以打开和复制,不能修改",
|
||||
"driveShareSystem": "系统盘,含个人文件和登录信息,请谨慎共享",
|
||||
"driveShareTitle": "Windows 盘符共享",
|
||||
"effectImmediate": "立即生效",
|
||||
"effectNextStart": "下次启动生效",
|
||||
"enableAudio": "音频",
|
||||
"enableLogs": "记录图形与串口日志",
|
||||
"enableNetwork": "网络(NAT)",
|
||||
"enableWHPX": "启用",
|
||||
"extraArgs": "额外 QEMU 参数",
|
||||
"extraArgsDesc": "原样追加到 QEMU 命令行",
|
||||
"failAffinity": "设置处理器相关性失败",
|
||||
"footerDisk": "磁盘可用 {gb} GB",
|
||||
"footerMem": "内存 {pct}%",
|
||||
"footerMemAvail": "可用 {avail} GB",
|
||||
"fullscreenLaunch": "无边框全屏启动",
|
||||
"fullscreenLaunchHint": "启动后直接进入无边框全屏",
|
||||
"gpuAutoOption": "自动(优先独显)",
|
||||
"gpuAutoSub": "将使用 {name}",
|
||||
"gpuAutoTitle": "自动",
|
||||
"gpuCompatUnsupported": "不支持加速",
|
||||
"gpuCompatWarn": "已知兼容风险",
|
||||
"gpuCustomIcd": "自定义 Vulkan ICD",
|
||||
"gpuDiscrete": "独显",
|
||||
"gpuIntegrated": "核显",
|
||||
"gpuKindDiscrete": "独立显卡",
|
||||
"gpuKindIntegrated": "集成显卡",
|
||||
"gpuRecommended": "推荐",
|
||||
"gpuSelect": "显卡",
|
||||
"gpuSvgaReason": "VMware SVGA 不使用宿主显卡",
|
||||
"gpuSwitchSvga": "改用 VMware SVGA",
|
||||
"gpuUnavailableHint": "没有找到能加速的显卡,可改用 VMware SVGA",
|
||||
"gpuUnknown": "未知",
|
||||
"gpuVirtual": "虚拟",
|
||||
"graphicsBackend": "虚拟显卡",
|
||||
"graphicsReimsDesc": "用宿主显卡加速 Metal,推荐",
|
||||
"graphicsReimsShort": "Reims vGPU",
|
||||
"graphicsRunningReason": "关机后才能切换",
|
||||
"graphicsSvgaDesc": "没有硬件加速,只用于排障",
|
||||
"graphicsSvgaShort": "VMware SVGA",
|
||||
"groupGraphics": "图形",
|
||||
"groupMacOS": "macOS",
|
||||
"groupPerformance": "性能",
|
||||
"groupQemu": "QEMU",
|
||||
"gtInstallCmd": "安装命令",
|
||||
"guestLangHint": "恢复模式、设置助理和登录界面使用的语言;选美式键盘,在终端输命令不易出错",
|
||||
"guestLangSettingsHint": "恢复模式、设置助理和登录界面使用的语言",
|
||||
"guestLangShort": "系统语言",
|
||||
"guestMemory": "分配内存",
|
||||
"guestToolsConnected": "已连接",
|
||||
"guestToolsPreventSleepSub": "闲置时让 macOS 保持唤醒,立即生效",
|
||||
"guestToolsReady": "已配置",
|
||||
"hidpiPresetBadge": "HiDPI",
|
||||
"hostAudioInput": "Windows 麦克风",
|
||||
"hostAudioMissingIn": "没有检测到麦克风,macOS 录不到声音",
|
||||
"hostAudioMissingOut": "没有检测到扬声器或耳机,虚拟机将没有声音",
|
||||
"hostAudioOutput": "Windows 播放设备",
|
||||
"hostCPU": "处理器",
|
||||
"hostCoresThreads": "{c} 核 · {t} 线程",
|
||||
"hostDataRoot": "数据目录",
|
||||
"hostDisk": "可用空间",
|
||||
"hostDisplayPrimary": "主屏",
|
||||
"hostDisplays": "物理显示器",
|
||||
"hostGPUs": "显卡",
|
||||
"hostRAM": "内存",
|
||||
"hostRAMAvail": "可用 {n} GB",
|
||||
"hostRAMTotal": "共 {n} GB",
|
||||
"hostRuntime": "运行时",
|
||||
"hostWHPX": "Windows 虚拟机监控程序平台",
|
||||
"installersAvailable": "Apple 提供的版本",
|
||||
"installersCreateVM": "新建虚拟机",
|
||||
"installersDelete": "删除",
|
||||
"installersDeleteConfirm": "确认删除",
|
||||
"installersDownload": "下载",
|
||||
"installersDownloaded": "已下载",
|
||||
"installersEmpty": "还没有下载任何安装包",
|
||||
"installersHint": "下载好的安装包可以重复用来新建虚拟机",
|
||||
"installersKindOffline": "离线完整包",
|
||||
"installersKindOnline": "在线恢复镜像",
|
||||
"installersLatest": "最新",
|
||||
"installersNoSpace": "空间不足:需要约 {need} GB,可用 {free} GB",
|
||||
"installersOlder": "{count, plural, other {# 个旧版本}}",
|
||||
"installersPartial": "未下载完",
|
||||
"installersResume": "继续下载",
|
||||
"installersTitle": "安装包",
|
||||
"kernelIrqchipAuto": "自动",
|
||||
"kernelIrqchipLabel": "中断加速",
|
||||
"kernelIrqchipOff": "关闭",
|
||||
"kernelIrqchipOn": "开启",
|
||||
"language": "语言",
|
||||
"languageSub": "内置简体中文与英语,可通过插件扩展更多语言",
|
||||
"logLevel": "日志级别",
|
||||
"logLevelCustom": "自定义",
|
||||
"logLevelDesc": "排查问题时再调高",
|
||||
"macosVersion": "macOS 版本",
|
||||
"memCommitHint": "Windows 还能分配 {avail} GB · 推荐 {rec} GB",
|
||||
"memOverHint": "超过推荐值,启动时可能分配失败",
|
||||
"memRecHint": "推荐 {rec} GB · 本机共 {n} GB",
|
||||
"minimizeToTray": "关闭窗口时最小化到系统托盘",
|
||||
"minimizeToTraySub": "关闭窗口后剪贴板和共享文件夹继续工作,可从托盘启停虚拟机",
|
||||
"multiDisplayHint": "{n, plural, other {检测到 # 块显示器,排列方式在 macOS「系统设置 › 显示器」里调整}}",
|
||||
"navHasIssue": "这一页有需要修改的项",
|
||||
"networkDesc": "通过 Windows 的网络连接上网",
|
||||
"networkOfflineHint": "离线安装默认关闭;看到「设置助理」后退出恢复模式并重启即可联网",
|
||||
"networkTitle": "网络",
|
||||
"next": "下一步",
|
||||
"noChanges": "没有更改",
|
||||
"offlineListFailed": "无法读取 Apple 的版本列表",
|
||||
"opencore": "OpenCore",
|
||||
"optAuto": "已自动开启",
|
||||
"optAvailable": "可用",
|
||||
"optExperimental": "实验性",
|
||||
"optKernelIrqchipExp": "实验性:开启可能更快,启动卡住就改回「自动」(Win10 上自动为关闭)",
|
||||
"optKernelIrqchipNestedErr": "当前 Windows 不支持({code}),「自动」会保持关闭",
|
||||
"optKernelIrqchipRec": "由 Windows 直接处理中断,磁盘和多核更流畅。「自动」即开启",
|
||||
"optKernelIrqchipUnavailable": "当前电脑不支持",
|
||||
"optKernelIrqchipWin10NoPatch": "Win10 上需要先更新运行时才能开启",
|
||||
"optPCoreSub": "仅调度到性能核({detail}),减少卡顿",
|
||||
"optPCoreUnavailable": "当前处理器无大小核架构,无需开启",
|
||||
"optRecommended": "推荐",
|
||||
"optSchedBackground": "后台服务",
|
||||
"optSchedNowBackground": "当前为「后台服务」,适合虚拟机在后台运行(影响整个 Windows)",
|
||||
"optSchedNowPrograms": "当前为「程序优先」,虚拟机在后台时可能变慢,建议改为「后台服务」(影响整个 Windows)",
|
||||
"optSchedOpen": "更改…",
|
||||
"optSchedPrograms": "程序优先",
|
||||
"optSchedSub": "选「后台服务」,虚拟机在后台时更稳定(影响整个 Windows)",
|
||||
"optSchedTitle": "Windows 处理器调度",
|
||||
"optUnavailable": "不可用",
|
||||
"pendingChanges": "{n, plural, other {# 项更改,下次启动生效}}",
|
||||
"platformReadonly": "机型、序列号等平台身份信息不在界面显示",
|
||||
"recommendedBadge": "推荐",
|
||||
"resCustom": "自定义",
|
||||
"resCustomSub": "宽 × 高",
|
||||
"resFullscreen": "全屏",
|
||||
"resInvalid": "格式为 宽x高,例如 2560x1600",
|
||||
"resetAll": "全部还原",
|
||||
"resetField": "还原为当前值",
|
||||
"runtimeDelete": "删除运行时",
|
||||
"runtimeDeleteConfirm": "确认删除",
|
||||
"runtimeDeleted": "已删除运行时 {commit}",
|
||||
"secondsUnit": "秒",
|
||||
"settingsAppearance": "外观与语言",
|
||||
"settingsGeneral": "常规",
|
||||
"settingsTitle": "{name}",
|
||||
"sourceDisk": "已有虚拟磁盘(.qcow2)",
|
||||
"sourceInstaller": "本地安装器镜像(.img / .dmg)",
|
||||
"sshForward": "SSH 端口转发",
|
||||
"sshNeedsNetwork": "需要先开启网络",
|
||||
"sshOffDesc": "从 Windows 用 SSH 登录 macOS",
|
||||
"sshPort": "SSH 转发端口",
|
||||
"startAfterCreate": "创建后立即启动",
|
||||
"statsCPU": "QEMU CPU",
|
||||
"statsDisk": "磁盘占用",
|
||||
"statsDiskSub": "实际 {actual} / 上限 {virtual}",
|
||||
"statsMemory": "宿主机内存",
|
||||
"statsUptime": "运行时长",
|
||||
"stopBeforeDiskOp": "关机后才能操作",
|
||||
"stopTimeout": "关机等待时间",
|
||||
"stopTimeoutHint": "0 表示一直等待",
|
||||
"storageBreakdownTitle": "空间分布",
|
||||
"storageInstallers": "安装包",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"storageVMs": "虚拟机文件",
|
||||
"themeLabel": "外观",
|
||||
"themePluginDarkDisabled": "默认主题插件已停用,深色与跟随系统外观不可用",
|
||||
"themePluginLightDisabled": "当前主题仅支持深色外观",
|
||||
"updateDownloadInstall": "下载并安装",
|
||||
"updateDownloadingSub": "正在下载 {v}",
|
||||
"updateFailedSub": "下载或校验失败,可以重试",
|
||||
"updateReadySub": "{v} 已下载并通过校验,重启 Reims-Go 即可完成更新",
|
||||
"updateReleaseNotes": "发行说明",
|
||||
"useDefault": "恢复默认",
|
||||
"vcpus": "虚拟处理器",
|
||||
"vmDir": "存放目录",
|
||||
"vmName": "名称",
|
||||
"welcomeCheckHost": "先完成内核环境配置 →",
|
||||
"welcomeSub": "选择系统来源、分配核数与显卡,几步完成配置",
|
||||
"welcomeTitle": "创建第一台 macOS 虚拟机",
|
||||
"whpxMissing": "启用后需要重启 Windows",
|
||||
"whpxMissingShort": "未启用",
|
||||
"whpxNoHv": "在 BIOS 中开启 Intel VT-x / AMD-V",
|
||||
"whpxNoHvShort": "未激活",
|
||||
"whpxReady": "就绪",
|
||||
"whpxTitle": "WHPX",
|
||||
"whpxUnsupported": "当前不是 Windows 宿主",
|
||||
"whpxUnsupportedShort": "不支持",
|
||||
}
|
||||
|
||||
export const settingsEn: Record<string, string> = {
|
||||
"aboutCommunity": "Community \u0026 support",
|
||||
"aboutCopyQQGroup": "Copy group ID",
|
||||
"aboutIssueSub": "Report a problem or suggest a feature on GitHub",
|
||||
"aboutJoinQQGroup": "Join group",
|
||||
"aboutProjectSub": "Source code, releases and docs on GitHub",
|
||||
"aboutQQGroup": "QQ Group",
|
||||
"aboutQQGroupSub": "Launch QQ directly to join for community support and feedback",
|
||||
"aboutQQLaunchFailed": "Couldn’t launch QQ — copy the group ID to join manually",
|
||||
"aboutQQNotInstalled": "QQ not installed",
|
||||
"aboutQQNotInstalledSub": "Local QQ wasn’t detected — copy the group ID to join manually",
|
||||
"aboutTagline": "Run a GPU-accelerated macOS virtual machine on Windows — prebuilt, ready out of the box.",
|
||||
"activate": "Use",
|
||||
"affinityApplyNow": "Apply Now",
|
||||
"affinityAvoidLPE": "Exclude LP-E",
|
||||
"affinityConfigure": "Configure…",
|
||||
"affinityEcoQoS": "Disable Windows EcoQoS power throttling",
|
||||
"affinityEcoQoSDesc": "Prevents Windows 11 from parking unfocused/background QEMU threads onto 2 low-power cores",
|
||||
"affinityExcludeCPU0": "Exclude CPU 0",
|
||||
"affinityLiveMask": "Active in Windows: {mask} ({count} threads)",
|
||||
"affinityModeAll": "All CPUs",
|
||||
"affinityModeAllHint": "Allows Windows to schedule QEMU across all host logical processors.",
|
||||
"affinityModeAuto": "Auto",
|
||||
"affinityModeAutoHint": "Follows global policy and avoids oversubscription and slow LP-E cores on hybrid CPUs.",
|
||||
"affinityModeCustom": "Custom",
|
||||
"affinityModeCustomHint": "Check the host logical CPUs allowed to run QEMU — identical to Windows Task Manager affinity.",
|
||||
"affinityModeNonLPE": "P + E",
|
||||
"affinityModeNonLPEHint": "Runs QEMU on P + E cores while excluding slow SoC LP-E cores.",
|
||||
"affinityModePCores": "P-Cores",
|
||||
"affinityModePCoresHint": "Restricts QEMU to performance cores (P-cores) to minimize scheduling jitter.",
|
||||
"affinityNeedOne": "Select at least 1 logical CPU",
|
||||
"affinityOnlyPCores": "P-cores only",
|
||||
"affinityOversubWarn": "Only {selected} logical CPUs selected for {vcpus} guest vCPUs; this may cause noticeable stalls.",
|
||||
"affinityPhysicalOnly": "Physical cores only",
|
||||
"affinityRowDesc": "Choose which cores the VM runs on. Applies immediately",
|
||||
"affinitySave": "Save",
|
||||
"affinitySelectAll": "All CPUs",
|
||||
"affinitySelectedSummary": "{selected} / {total} logical CPUs selected · Mask {mask}",
|
||||
"affinitySubtitleRunning": "Running (PID {pid}) · {vcpus} vCPU · Applies immediately",
|
||||
"affinitySubtitleStopped": "Stopped · {vcpus} vCPU · Applied on next start",
|
||||
"affinitySummaryAll": "All CPUs ({count}T)",
|
||||
"affinitySummaryAuto": "Auto ({eff} · {count}T)",
|
||||
"affinitySummaryCustom": "Custom ({count}T · {mask})",
|
||||
"affinitySummaryNonLPE": "P + E ({count}T · {mask})",
|
||||
"affinitySummaryPCores": "P-Cores ({count}T · {mask})",
|
||||
"affinityTitle": "CPU cores",
|
||||
"appCheckUpdate": "Check for updates",
|
||||
"appDownloadUpdate": "Download",
|
||||
"appUpToDate": "Up to date",
|
||||
"appUpdateAvailable": "New stable release {v} available",
|
||||
"appUpdateLookupFailed": "Couldn’t check GitHub for updates",
|
||||
"appVersionTitle": "App version",
|
||||
"appliesNextStart": "Applies on next start",
|
||||
"audioBackendAuto": "Auto",
|
||||
"audioBackendDesc": "Silent keeps the macOS sound card but plays nothing; useful for troubleshooting",
|
||||
"audioBackendDsound": "DirectSound",
|
||||
"audioBackendNone": "Silent",
|
||||
"audioBackendTitle": "Sound output",
|
||||
"audioDesc": "Plays macOS sound through Windows",
|
||||
"audioDisabledReason": "Enable audio first",
|
||||
"audioTroubleshootNote": "If audio crackles, set the Windows sound format to 48000 Hz. If the mic is silent, check Windows Privacy › Microphone",
|
||||
"autoPinPCores": "Pin to performance cores on start",
|
||||
"back": "Back",
|
||||
"captureInput": "Capture keyboard and mouse on click",
|
||||
"captureInputHint": "When on, shortcuts like ⌘Tab go to macOS; when off, Win and Alt+Tab stay with Windows",
|
||||
"catAdvanced": "Advanced",
|
||||
"catAudio": "Audio",
|
||||
"catCompute": "CPU \u0026 Memory",
|
||||
"catGeneral": "General",
|
||||
"catGraphics": "Graphics \u0026 displays",
|
||||
"catInput": "Keyboard \u0026 pointer",
|
||||
"catInputAudio": "Input \u0026 Audio",
|
||||
"catLogs": "Logs",
|
||||
"catNetwork": "Network",
|
||||
"catStorage": "Storage",
|
||||
"catStorageNet": "Storage \u0026 Network",
|
||||
"choose": "Browse…",
|
||||
"configured": "Configured",
|
||||
"coresUnit": "cores",
|
||||
"cpuOverHint": "Leaves Windows fewer than 2 threads; your PC may slow down",
|
||||
"cpuRecHint": "{rec} cores recommended · this PC has {n} threads",
|
||||
"diskCompactAction": "Reclaim now",
|
||||
"diskCompactDesc": "Gives space from files deleted in macOS back to Windows. Needs about as much free space as the disk uses now",
|
||||
"diskCompactDone": "Reclaimed {reclaimed} ({before} → {after})",
|
||||
"diskCompactNoGain": "Nothing to reclaim",
|
||||
"diskCompactQcow2Only": "This disk does not support reclaiming space",
|
||||
"diskCompactTitle": "Reclaim space",
|
||||
"diskController": "Disk interface",
|
||||
"diskControllerInstallHint": "Keep SATA while installing; switch to NVMe after ejecting the installer",
|
||||
"diskControllerNvmeHint": "NVMe is faster",
|
||||
"diskControllerNvmeReadyHint": "Fast and works with Recovery. Recommended",
|
||||
"diskControllerVirtioHint": "Lower overhead but experimental; switch back to NVMe if you hit problems",
|
||||
"diskControllerWarn": "Eject the installer before switching",
|
||||
"diskMode": "Use disk as",
|
||||
"diskModeCopy": "A copy — original untouched",
|
||||
"diskModeInPlace": "In place",
|
||||
"diskResizeAction": "Expand",
|
||||
"diskResizeDesc": "Grow only. Afterwards, run the command shown in macOS Terminal to use the new space",
|
||||
"diskResizeDone": "Expanded to {size}. Run this in macOS Terminal:",
|
||||
"diskResizeTitle": "Expand disk",
|
||||
"diskSize": "Disk size",
|
||||
"diskSizeHint": "Grows as it fills",
|
||||
"diskUsageSummary": "{actual} used of {virtual}",
|
||||
"displayGroup": "Displays",
|
||||
"driveShareMaster": "Share Windows drives",
|
||||
"driveShareMasterDesc": "Shows the selected drives in macOS Finder. Applies immediately",
|
||||
"driveShareNeedsTools": "Needs Guest Tools {version} or later: restart the VM, then run the install command in macOS again",
|
||||
"driveShareNoDrives": "No internal fixed disks are available to share",
|
||||
"driveShareReadOnly": "Read-only: macOS can open and copy files but not change them",
|
||||
"driveShareSystem": "System drive with personal files and sign-in data; share with care",
|
||||
"driveShareTitle": "Windows drive sharing",
|
||||
"effectImmediate": "Immediate",
|
||||
"effectNextStart": "Next start",
|
||||
"enableAudio": "Audio",
|
||||
"enableLogs": "Keep graphics and serial logs",
|
||||
"enableNetwork": "Network (NAT)",
|
||||
"enableWHPX": "Enable",
|
||||
"extraArgs": "Extra QEMU arguments",
|
||||
"extraArgsDesc": "Appended to the QEMU command line as is",
|
||||
"failAffinity": "Could not update processor affinity",
|
||||
"footerDisk": "Disk {gb} GB free",
|
||||
"footerMem": "Memory {pct}%",
|
||||
"footerMemAvail": "{avail} GB free",
|
||||
"fullscreenLaunch": "Launch borderless fullscreen",
|
||||
"fullscreenLaunchHint": "Opens macOS in borderless full screen",
|
||||
"gpuAutoOption": "Automatic (prefers discrete)",
|
||||
"gpuAutoSub": "Will use {name}",
|
||||
"gpuAutoTitle": "Automatic",
|
||||
"gpuCompatUnsupported": "Unsupported",
|
||||
"gpuCompatWarn": "Known issue",
|
||||
"gpuCustomIcd": "Custom Vulkan ICD",
|
||||
"gpuDiscrete": "Discrete",
|
||||
"gpuIntegrated": "Integrated",
|
||||
"gpuKindDiscrete": "Discrete",
|
||||
"gpuKindIntegrated": "Integrated",
|
||||
"gpuRecommended": "Recommended",
|
||||
"gpuSelect": "GPU",
|
||||
"gpuSvgaReason": "VMware SVGA does not use the host GPU",
|
||||
"gpuSwitchSvga": "Use VMware SVGA",
|
||||
"gpuUnavailableHint": "No GPU available for acceleration; try VMware SVGA",
|
||||
"gpuUnknown": "Unknown",
|
||||
"gpuVirtual": "Virtual",
|
||||
"graphicsBackend": "Virtual graphics",
|
||||
"graphicsReimsDesc": "Accelerates Metal on the host GPU. Recommended",
|
||||
"graphicsReimsShort": "Reims vGPU",
|
||||
"graphicsRunningReason": "Shut down the VM to change this",
|
||||
"graphicsSvgaDesc": "No acceleration; for troubleshooting only",
|
||||
"graphicsSvgaShort": "VMware SVGA",
|
||||
"groupGraphics": "Graphics",
|
||||
"groupMacOS": "macOS",
|
||||
"groupPerformance": "Performance",
|
||||
"groupQemu": "QEMU",
|
||||
"gtInstallCmd": "Install command",
|
||||
"guestLangHint": "Used by Recovery, Setup Assistant and the login window; a US keyboard layout keeps Terminal input reliable",
|
||||
"guestLangSettingsHint": "Used by Recovery, Setup Assistant and the login window",
|
||||
"guestLangShort": "System language",
|
||||
"guestMemory": "Memory",
|
||||
"guestToolsConnected": "Connected",
|
||||
"guestToolsPreventSleepSub": "Keeps macOS awake while idle; applies immediately",
|
||||
"guestToolsReady": "Configured",
|
||||
"hidpiPresetBadge": "HiDPI",
|
||||
"hostAudioInput": "Windows microphone",
|
||||
"hostAudioMissingIn": "No microphone found; macOS will record silence",
|
||||
"hostAudioMissingOut": "No speakers or headphones found; the VM will be silent",
|
||||
"hostAudioOutput": "Windows playback",
|
||||
"hostCPU": "CPU",
|
||||
"hostCoresThreads": "{c} cores · {t} threads",
|
||||
"hostDataRoot": "Data folder",
|
||||
"hostDisk": "Free space",
|
||||
"hostDisplayPrimary": "Primary",
|
||||
"hostDisplays": "Physical displays",
|
||||
"hostGPUs": "Graphics cards",
|
||||
"hostRAM": "Memory",
|
||||
"hostRAMAvail": "{n} GB free",
|
||||
"hostRAMTotal": "{n} GB total",
|
||||
"hostRuntime": "Runtime",
|
||||
"hostWHPX": "Windows Hypervisor Platform",
|
||||
"installersAvailable": "Releases from Apple",
|
||||
"installersCreateVM": "Create VM",
|
||||
"installersDelete": "Delete",
|
||||
"installersDeleteConfirm": "Confirm delete",
|
||||
"installersDownload": "Download",
|
||||
"installersDownloaded": "Downloaded",
|
||||
"installersEmpty": "No installers downloaded yet",
|
||||
"installersHint": "Downloaded installers can be reused for new VMs",
|
||||
"installersKindOffline": "Offline installer",
|
||||
"installersKindOnline": "Online recovery",
|
||||
"installersLatest": "Latest",
|
||||
"installersNoSpace": "Not enough space: needs about {need} GB, {free} GB free",
|
||||
"installersOlder": "{count, plural, one {# older version} other {# older versions}}",
|
||||
"installersPartial": "Partly downloaded",
|
||||
"installersResume": "Resume",
|
||||
"installersTitle": "Installers",
|
||||
"kernelIrqchipAuto": "Auto",
|
||||
"kernelIrqchipLabel": "Interrupt acceleration",
|
||||
"kernelIrqchipOff": "Off",
|
||||
"kernelIrqchipOn": "On",
|
||||
"language": "Language",
|
||||
"languageSub": "Simplified Chinese and English built in; add more via plugins",
|
||||
"logLevel": "Log level",
|
||||
"logLevelCustom": "Custom",
|
||||
"logLevelDesc": "Raise only when troubleshooting",
|
||||
"macosVersion": "macOS version",
|
||||
"memCommitHint": "Windows can allocate {avail} GB more · {rec} GB recommended",
|
||||
"memOverHint": "Above the recommendation; the VM may fail to start",
|
||||
"memRecHint": "{rec} GB recommended · this PC has {n} GB",
|
||||
"minimizeToTray": "Minimize to system tray on close",
|
||||
"minimizeToTraySub": "Clipboard and shared folders keep working; start and stop VMs from the tray",
|
||||
"multiDisplayHint": "{n, plural, one {# display detected; arrange displays inside macOS System Settings › Displays} other {# displays detected; arrange them inside macOS System Settings › Displays}}",
|
||||
"navHasIssue": "This page has settings to fix",
|
||||
"networkDesc": "Uses the Windows network connection",
|
||||
"networkOfflineHint": "Off by default for offline installs. Exit recovery and restart when Setup Assistant appears to enable networking",
|
||||
"networkTitle": "Network",
|
||||
"next": "Next",
|
||||
"noChanges": "No changes",
|
||||
"offlineListFailed": "Couldn’t read Apple’s release list",
|
||||
"opencore": "OpenCore",
|
||||
"optAuto": "Automatic",
|
||||
"optAvailable": "Available",
|
||||
"optExperimental": "Experimental",
|
||||
"optKernelIrqchipExp": "Experimental: may be faster. If startup hangs, go back to Auto (off on Windows 10)",
|
||||
"optKernelIrqchipNestedErr": "Not supported by this Windows ({code}); Auto keeps it off",
|
||||
"optKernelIrqchipRec": "Windows handles interrupts directly for smoother disk and multi-core work. Auto turns it on",
|
||||
"optKernelIrqchipUnavailable": "Not supported on this PC",
|
||||
"optKernelIrqchipWin10NoPatch": "On Windows 10, update the runtime to turn this on",
|
||||
"optPCoreSub": "Schedule QEMU on performance cores only ({detail})",
|
||||
"optPCoreUnavailable": "CPU has no hybrid P/E cores",
|
||||
"optRecommended": "Recommended",
|
||||
"optSchedBackground": "Background services",
|
||||
"optSchedNowBackground": "Set to Background services, which suits a VM running in the background (affects all of Windows)",
|
||||
"optSchedNowPrograms": "Set to Programs, so the VM may slow down in the background. Background services is recommended (affects all of Windows)",
|
||||
"optSchedOpen": "Change…",
|
||||
"optSchedPrograms": "Programs",
|
||||
"optSchedSub": "Background services keeps the VM steady in the background (affects all of Windows)",
|
||||
"optSchedTitle": "Windows processor scheduling",
|
||||
"optUnavailable": "Unavailable",
|
||||
"pendingChanges": "{n, plural, one {# change · applies on next start} other {# changes · applies on next start}}",
|
||||
"platformReadonly": "Model, serial number and other platform identity are never shown",
|
||||
"recommendedBadge": "Recommended",
|
||||
"resCustom": "Custom",
|
||||
"resCustomSub": "Width × height",
|
||||
"resFullscreen": "Full screen",
|
||||
"resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600",
|
||||
"resetAll": "Revert all",
|
||||
"resetField": "Revert to current value",
|
||||
"runtimeDelete": "Delete runtime",
|
||||
"runtimeDeleteConfirm": "Confirm delete",
|
||||
"runtimeDeleted": "Removed runtime {commit}",
|
||||
"secondsUnit": "s",
|
||||
"settingsAppearance": "Appearance \u0026 language",
|
||||
"settingsGeneral": "General",
|
||||
"settingsTitle": "{name}",
|
||||
"sourceDisk": "Existing virtual disk (.qcow2)",
|
||||
"sourceInstaller": "Local installer image (.img / .dmg)",
|
||||
"sshForward": "SSH port forwarding",
|
||||
"sshNeedsNetwork": "Turn on the network first",
|
||||
"sshOffDesc": "Log in to macOS over SSH from Windows",
|
||||
"sshPort": "SSH forward port",
|
||||
"startAfterCreate": "Start after creating",
|
||||
"statsCPU": "QEMU CPU",
|
||||
"statsDisk": "Disk usage",
|
||||
"statsDiskSub": "{actual} actual / {virtual} max",
|
||||
"statsMemory": "Host RAM",
|
||||
"statsUptime": "Uptime",
|
||||
"stopBeforeDiskOp": "Shut down the VM first",
|
||||
"stopTimeout": "Shutdown timeout",
|
||||
"stopTimeoutHint": "0 waits indefinitely",
|
||||
"storageBreakdownTitle": "Storage breakdown",
|
||||
"storageInstallers": "Installers",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"storageVMs": "VM files",
|
||||
"themeLabel": "Appearance",
|
||||
"themePluginDarkDisabled": "Default theme plugin is disabled; dark and system appearances are unavailable",
|
||||
"themePluginLightDisabled": "The active theme supports dark appearance only",
|
||||
"updateDownloadInstall": "Download and install",
|
||||
"updateDownloadingSub": "Downloading {v}",
|
||||
"updateFailedSub": "Download or verification failed; try again",
|
||||
"updateReadySub": "{v} is downloaded and verified; restart Reims-Go to finish",
|
||||
"updateReleaseNotes": "Release notes",
|
||||
"useDefault": "Use Default",
|
||||
"vcpus": "Virtual CPUs",
|
||||
"vmDir": "Folder",
|
||||
"vmName": "Name",
|
||||
"welcomeCheckHost": "Set up Engine first →",
|
||||
"welcomeSub": "Pick an installer, assign cores and GPU, and launch in minutes",
|
||||
"welcomeTitle": "Create your first macOS VM",
|
||||
"whpxMissing": "Windows restarts after enabling",
|
||||
"whpxMissingShort": "Off",
|
||||
"whpxNoHv": "Turn on Intel VT-x / AMD-V in BIOS",
|
||||
"whpxNoHvShort": "Inactive",
|
||||
"whpxReady": "Ready",
|
||||
"whpxTitle": "WHPX",
|
||||
"whpxUnsupported": "This host isn’t Windows",
|
||||
"whpxUnsupportedShort": "Unsupported",
|
||||
}
|
||||
|
||||
registerBuiltinDomain(settingsZh, settingsEn)
|
||||
@@ -0,0 +1,377 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
|
||||
export const vmZh: Record<string, string> = {
|
||||
"attachGuestTools": "挂载 Guest Tools",
|
||||
"attachInstaller": "挂载离线镜像",
|
||||
"brokenHint": "这台虚拟机的配置无法读取",
|
||||
"cloneConfirm": "立即派生",
|
||||
"cloneDesc": "用写时复制瞬间创建副本,几乎不占空间,原虚拟机不受影响",
|
||||
"cloneNameLabel": "新虚拟机名称",
|
||||
"cloneTitle": "从「{name}」派生 CoW 副本",
|
||||
"cloneVM": "秒级派生副本 (CoW)",
|
||||
"connGroup": "连接",
|
||||
"copyScreenshot": "截屏并复制",
|
||||
"cores": "{n, plural, other {# 核}}",
|
||||
"deleteConfirm": "删除",
|
||||
"deleteDesc": "配置和虚拟磁盘会被移除,无法撤销",
|
||||
"deleteDescKeep": "只移除配置,磁盘文件留在原目录",
|
||||
"deleteKeepFiles": "保留磁盘文件",
|
||||
"deleteTitle": "删除「{name}」?",
|
||||
"deliverFileShort": "发送文件…",
|
||||
"detachGuestTools": "弹出工具盘",
|
||||
"diagAhciUpgradeHint": "系统盘还是 SATA,改成 NVMe 读写更快",
|
||||
"diagExternalDriveWarn": "数据目录在外置或网络盘上({dir}),读写会明显变慢",
|
||||
"diagHighMemWarn": "宿主内存已用 {pct}%,虚拟机可能会卡顿",
|
||||
"displayNameEdit": "点按以修改显示名称",
|
||||
"displayNameEditEllipsis": "修改显示名称…",
|
||||
"displayNameLabel": "显示名称",
|
||||
"displayNameTip": "显示名称 · 虚拟机名称为 {name}(点按修改)",
|
||||
"dropFilesHint": "松开以投递到 macOS 共享目录",
|
||||
"enterRecovery": "进入恢复模式",
|
||||
"exportDiagnostics": "导出排障日志 (.zip)",
|
||||
"factCPU": "处理器",
|
||||
"factDisk": "存储",
|
||||
"factGraphics": "图形",
|
||||
"factMemory": "内存",
|
||||
"failAttachInstaller": "挂载镜像失败",
|
||||
"failCloneVM": "派生 CoW 副本失败",
|
||||
"failDelete": "删除失败",
|
||||
"failEject": "弹出安装盘失败",
|
||||
"failEnterRecovery": "进入恢复模式失败",
|
||||
"failExportDiagnostics": "导出排障日志失败",
|
||||
"failFinishInstall": "退出恢复模式失败",
|
||||
"failFocus": "无法定位虚拟机窗口",
|
||||
"failGuestTools": "Guest Tools 操作失败",
|
||||
"failOpenFolder": "无法打开文件夹",
|
||||
"failRestart": "重启失败",
|
||||
"failScreenshot": "截屏失败",
|
||||
"failSnapshot": "恢复点操作失败",
|
||||
"failStart": "启动失败",
|
||||
"failStop": "关机失败",
|
||||
"failType": "键入失败",
|
||||
"failUpgradeNVMe": "升级到 NVMe 失败",
|
||||
"fieldAudio": "音频",
|
||||
"fieldCPUModel": "CPU 型号",
|
||||
"fieldController": "磁盘控制器",
|
||||
"fieldDir": "目录",
|
||||
"fieldDisk": "磁盘",
|
||||
"fieldGraphicsBackend": "图形后端",
|
||||
"fieldICD": "Vulkan ICD",
|
||||
"fieldKind": "类型",
|
||||
"fieldNetwork": "网络",
|
||||
"fieldVMName": "虚拟机名称",
|
||||
"finishInstall": "退出恢复模式",
|
||||
"gpuAuto": "自动选择 GPU",
|
||||
"gtInstall": "安装…",
|
||||
"gtInstallSub": "在 macOS 终端里运行",
|
||||
"gtNotInstalledDesc": "未安装:挂载工具盘后在 macOS 中运行安装命令",
|
||||
"gtStatusConnected": "已连接",
|
||||
"gtStatusEnabled": "已启用",
|
||||
"gtStatusNone": "未安装",
|
||||
"gtStatusOff": "已停用",
|
||||
"gtStatusOffTip": "Guest Tools 传输服务已在插件页停用,剪贴板、共享文件夹与防休眠都不可用",
|
||||
"gtStatusUpgrade": "需要更新",
|
||||
"gtStatusWaiting": "未连接",
|
||||
"gtStatusWaitingTip": "在 macOS 里运行安装命令后会自动连接",
|
||||
"gtUpdate": "更新…",
|
||||
"guestToolsModeSync": "文件同步模式",
|
||||
"guestToolsModeWebDAV": "WebDAV 挂载",
|
||||
"guestToolsPreventSleep": "防止 macOS 睡眠",
|
||||
"guestToolsSleepActive": "正在保持唤醒",
|
||||
"guestToolsTitle": "Guest Tools",
|
||||
"guestToolsUpgradeHint": "macOS 里的工具是旧版,重新运行安装命令即可升级",
|
||||
"guideBuiltIn1": "启动后在 OpenCore 引导菜单选择「Recovery」",
|
||||
"guideBuiltIn2": "恢复模式可以联网重装;要离线安装就点「挂载离线镜像」",
|
||||
"guideBuiltIn3": "完成后点「退出恢复模式」",
|
||||
"guideKindBuiltIn": "内置恢复",
|
||||
"guideKindOffline": "离线完整安装",
|
||||
"guideKindOnline": "在线恢复安装",
|
||||
"guideOffline1": "不要点「Reinstall macOS Tahoe」,从菜单栏打开「Utilities › Terminal」",
|
||||
"guideOffline2": "运行下面的命令(点键盘图标可直接键入)。它会把空白磁盘抹成 APFS 并开始安装,中途会重启几次:",
|
||||
"guideOffline3": "看到「设置助理」后,点「退出恢复模式」弹出安装盘并恢复网络",
|
||||
"guideStartHint": "启动后在虚拟机窗口查看安装引导",
|
||||
"guideStep1": "打开「磁盘工具」,选中最大的「QEMU HARDDISK Media」(看不到就选 View › Show All Devices),点 Erase:名称 Macintosh HD,格式 APFS,方案 GUID。抹除时可能停顿 10–30 秒,不要强制关机",
|
||||
"guideStep2": "回到恢复主界面,选「Reinstall macOS Tahoe」,装到刚抹好的磁盘,中途会重启几次",
|
||||
"guideStep3": "看到「设置助理」后,点「退出恢复模式」弹出安装盘",
|
||||
"guideTitle": "恢复模式",
|
||||
"netOff": "无网络",
|
||||
"netShared": "共享网络",
|
||||
"onlineRecoveryConfirm": "拉取并挂载(约 1 GB)",
|
||||
"onlineRecoveryDesc": "本地没有恢复镜像。要从 Apple 下载约 1 GB 的恢复镜像并挂载到「{name}」吗?",
|
||||
"onlineRecoveryTitle": "拉取在线恢复镜像?",
|
||||
"openSharedFolder": "打开共享文件夹",
|
||||
"openShort": "打开",
|
||||
"pendingRestartHint": "重启虚拟机后生效",
|
||||
"pendingTitle": "下次启动生效",
|
||||
"pickRecoveryTitle": "选择离线镜像(.img / .dmg)",
|
||||
"restartToApply": "重启以应用",
|
||||
"sendText": "发送文本到虚拟机…",
|
||||
"sendTextConfirm": "发送 (Ctrl+Enter)",
|
||||
"sendTextDesc": "支持中文、Emoji、宿主机输入法与语音输入,按 Ctrl+Enter 发送到 macOS 当前输入框。",
|
||||
"sendTextDescNoGT": "当前未连接 Guest Tools,仅支持英文/数字等美式键盘字符;安装 Guest Tools 后支持中文与任意文本。",
|
||||
"sendTextPlaceholder": "在这里输入或粘贴要发送到虚拟机的文字…",
|
||||
"sendTextTitle": "发送文本到「{name}」",
|
||||
"sharedFolder": "共享文件夹",
|
||||
"showInstallGuide": "显示安装引导",
|
||||
"showWindow": "显示窗口",
|
||||
"snapshotCreate": "创建恢复点",
|
||||
"snapshotDelete": "删除恢复点",
|
||||
"snapshotEmpty": "尚未创建恢复点,升级系统或大改环境前可先留档",
|
||||
"snapshotHint": "停机快照 · 非异地备份",
|
||||
"snapshotNamePlaceholder": "例如:升级 macOS 前",
|
||||
"snapshotRestore": "回滚",
|
||||
"snapshotRestoreDesc": "当前磁盘在此恢复点之后的改动将被覆盖,且无法撤销。",
|
||||
"snapshotRestoreTitle": "回滚到「{name}」?",
|
||||
"snapshotStopFirst": "停止虚拟机后才可管理恢复点",
|
||||
"snapshotsTitle": "恢复点",
|
||||
"softwareGraphics": "软件渲染",
|
||||
"specCPULiveTip": "处理器 {n} 核,当前占用 {pct}%",
|
||||
"specCPUTip": "{n, plural, other {处理器 # 核}}",
|
||||
"specDiskTip": "存储:{ctl}",
|
||||
"specDiskUsage": "{ctl} · 已用 {used},上限 {max}",
|
||||
"specGraphicsTip": "图形:{gfx}",
|
||||
"specLang": "语言",
|
||||
"specLangTip": "macOS 系统语言:{label}",
|
||||
"specLangTipDetail": "macOS 系统语言:{label}({detail})",
|
||||
"specMemLiveTip": "内存 {mem},虚拟机在宿主上占用 {used}",
|
||||
"specMemTip": "内存 {mem}",
|
||||
"specNetOffTip": "虚拟机没有网络",
|
||||
"specNetSSHTip": "与宿主共享网络连接,SSH 端口 {port}",
|
||||
"specNetTip": "与宿主共享网络连接",
|
||||
"sshMore": "SSH 工具",
|
||||
"sshOpenTerminal": "终端",
|
||||
"sshOpenVSCode": "用 VS Code 打开",
|
||||
"sshSetUser": "设置 SSH 用户名…",
|
||||
"sshUserDesc": "用于打开终端、写入 ~/.ssh/config 和 VS Code 直连(留空则连接时不带用户名)",
|
||||
"sshUserPlaceholder": "例如 admin",
|
||||
"sshUserTitle": "SSH 登录用户名",
|
||||
"sshWriteConfig": "写入 ~/.ssh/config",
|
||||
"state_broken": "出错",
|
||||
"state_creating": "正在创建",
|
||||
"state_driver_unavailable": "驱动不可用",
|
||||
"state_running": "运行中",
|
||||
"state_starting": "启动中",
|
||||
"state_stopped": "已停止",
|
||||
"state_stopping": "停止中",
|
||||
"techInfo": "技术信息",
|
||||
"toastCloned": "已派生 CoW 副本「{name}」",
|
||||
"toastDeleted": "已删除 {name}",
|
||||
"toastDiagExported": "已导出脱敏排障日志包 (.zip)",
|
||||
"toastEjected": "已弹出安装盘",
|
||||
"toastEnterRecovery": "已进入恢复模式,启动后可在引导菜单选 Recovery",
|
||||
"toastEnterRecoveryNextStart": "已准备进入恢复模式,重启后显示引导菜单",
|
||||
"toastExitRecoveryNextStart": "已退出恢复模式,下次启动生效",
|
||||
"toastFileDelivered": "已发送 {name}",
|
||||
"toastFilesDelivered": "{n, plural, other {已投递 # 个文件到共享目录}}",
|
||||
"toastGuestToolsAttached": "已挂载 Guest Tools 工具盘(REIMSTOOLS)",
|
||||
"toastGuestToolsAttachedNextStart": "已挂载 Guest Tools 工具盘,重启虚拟机后在访达中可见",
|
||||
"toastGuestToolsDetached": "已弹出工具盘",
|
||||
"toastGuestToolsDetachedNextStart": "已弹出工具盘,下次启动生效",
|
||||
"toastInstallFinished": "已退出恢复模式",
|
||||
"toastInstallerAttached": "已挂载离线镜像:{name}",
|
||||
"toastInstallerAttachedNextStart": "已挂载离线镜像(重启后生效):{name}",
|
||||
"toastNVMeNextStart": "已切换为 NVMe,下次启动生效",
|
||||
"toastNVMeReady": "已升级到 NVMe 磁盘控制器",
|
||||
"toastOnlineRecoveryAttached": "在线恢复镜像已挂载到 {name}",
|
||||
"toastOnlineRecoveryStarted": "正在拉取在线恢复镜像(约 1 GB),完成后自动挂载",
|
||||
"toastPreventSleepOff": "已关闭 macOS 防休眠守护",
|
||||
"toastPreventSleepOn": "已开启 macOS 防休眠守护",
|
||||
"toastScreenshotCopied": "已复制虚拟机画面",
|
||||
"toastSnapshotCreated": "已创建恢复点 {name}",
|
||||
"toastSnapshotDeleted": "已删除恢复点 {name}",
|
||||
"toastSnapshotRestored": "已回滚到 {name}",
|
||||
"toastStopped": "{name} 已关机",
|
||||
"toastTyped": "{n, plural, other {已键入 # 个字符}}",
|
||||
"typeClipboard": "粘贴剪贴板到虚拟机",
|
||||
"typeIntoVM": "在虚拟机里键入",
|
||||
"typeUntypeable": "未连接 Guest Tools 时仅支持美式键盘 ASCII 字符;安装并连接 Guest Tools 后即可输入中文与任意 Unicode 文本",
|
||||
"upgradeToNVMe": "升级到 NVMe",
|
||||
}
|
||||
|
||||
export const vmEn: Record<string, string> = {
|
||||
"attachGuestTools": "Attach Guest Tools",
|
||||
"attachInstaller": "Attach offline image",
|
||||
"brokenHint": "This VM’s configuration can’t be read",
|
||||
"cloneConfirm": "Create clone",
|
||||
"cloneDesc": "Makes an instant copy-on-write clone that takes almost no space and leaves the original untouched",
|
||||
"cloneNameLabel": "New VM name",
|
||||
"cloneTitle": "Derive CoW clone from “{name}”",
|
||||
"cloneVM": "Derive CoW clone",
|
||||
"connGroup": "Connection",
|
||||
"copyScreenshot": "Copy screenshot",
|
||||
"cores": "{n, plural, one {# core} other {# cores}}",
|
||||
"deleteConfirm": "Delete",
|
||||
"deleteDesc": "Its configuration and virtual disk are removed. This can’t be undone",
|
||||
"deleteDescKeep": "Only the configuration is removed; disk files stay in place",
|
||||
"deleteKeepFiles": "Keep disk files",
|
||||
"deleteTitle": "Delete \"{name}\"?",
|
||||
"deliverFileShort": "Send File…",
|
||||
"detachGuestTools": "Eject tools disk",
|
||||
"diagAhciUpgradeHint": "The system disk still uses SATA; NVMe is faster",
|
||||
"diagExternalDriveWarn": "The data folder is on an external or network drive ({dir}); disk access will be slow",
|
||||
"diagHighMemWarn": "Host memory is {pct}% used; the VM may stutter",
|
||||
"displayNameEdit": "Click to change the display name",
|
||||
"displayNameEditEllipsis": "Change Display Name…",
|
||||
"displayNameLabel": "Display name",
|
||||
"displayNameTip": "Display name · VM name is {name} (click to change)",
|
||||
"dropFilesHint": "Drop files to send to macOS shared folder",
|
||||
"enterRecovery": "Enter recovery mode",
|
||||
"exportDiagnostics": "Export diagnostics (.zip)",
|
||||
"factCPU": "CPU",
|
||||
"factDisk": "Storage",
|
||||
"factGraphics": "Graphics",
|
||||
"factMemory": "Memory",
|
||||
"failAttachInstaller": "Couldn’t attach the image",
|
||||
"failCloneVM": "Couldn’t create CoW clone",
|
||||
"failDelete": "Couldn’t delete",
|
||||
"failEject": "Couldn’t eject the installer",
|
||||
"failEnterRecovery": "Couldn’t enter recovery mode",
|
||||
"failExportDiagnostics": "Couldn’t export diagnostics",
|
||||
"failFinishInstall": "Couldn’t exit recovery mode",
|
||||
"failFocus": "Could not focus VM window",
|
||||
"failGuestTools": "Guest Tools operation failed",
|
||||
"failOpenFolder": "Couldn’t open the folder",
|
||||
"failRestart": "Couldn’t restart",
|
||||
"failScreenshot": "Screenshot failed",
|
||||
"failSnapshot": "Restore point failed",
|
||||
"failStart": "Couldn’t start",
|
||||
"failStop": "Couldn’t shut down",
|
||||
"failType": "Couldn’t type into the VM",
|
||||
"failUpgradeNVMe": "Couldn’t upgrade to NVMe",
|
||||
"fieldAudio": "Audio",
|
||||
"fieldCPUModel": "CPU model",
|
||||
"fieldController": "Disk controller",
|
||||
"fieldDir": "Directory",
|
||||
"fieldDisk": "Disk",
|
||||
"fieldGraphicsBackend": "Graphics backend",
|
||||
"fieldICD": "Vulkan ICD",
|
||||
"fieldKind": "Kind",
|
||||
"fieldNetwork": "Network",
|
||||
"fieldVMName": "VM name",
|
||||
"finishInstall": "Exit recovery mode",
|
||||
"gpuAuto": "Automatic GPU",
|
||||
"gtInstall": "Install…",
|
||||
"gtInstallSub": "Run in macOS Terminal",
|
||||
"gtNotInstalledDesc": "Not installed: attach the tools disk and run the installer in macOS",
|
||||
"gtStatusConnected": "Connected",
|
||||
"gtStatusEnabled": "Enabled",
|
||||
"gtStatusNone": "Not installed",
|
||||
"gtStatusOff": "Off",
|
||||
"gtStatusOffTip": "Guest Tools Transport is turned off on the Plugins page; clipboard, shared folders and keep-awake are unavailable",
|
||||
"gtStatusUpgrade": "Update needed",
|
||||
"gtStatusWaiting": "Not connected",
|
||||
"gtStatusWaitingTip": "Connects once the install command has run in macOS",
|
||||
"gtUpdate": "Update…",
|
||||
"guestToolsModeSync": "Folder sync",
|
||||
"guestToolsModeWebDAV": "WebDAV mount",
|
||||
"guestToolsPreventSleep": "Prevent macOS sleep",
|
||||
"guestToolsSleepActive": "Keeping macOS awake",
|
||||
"guestToolsTitle": "Guest Tools",
|
||||
"guestToolsUpgradeHint": "The tools in macOS are out of date; run the install command again to update",
|
||||
"guideBuiltIn1": "After starting, choose “Recovery” in the OpenCore boot menu",
|
||||
"guideBuiltIn2": "Recovery can reinstall over the network; for an offline install, click “Attach offline image”",
|
||||
"guideBuiltIn3": "When you are done, click “Exit recovery mode”",
|
||||
"guideKindBuiltIn": "Built-in recovery",
|
||||
"guideKindOffline": "Offline install",
|
||||
"guideKindOnline": "Online recovery",
|
||||
"guideOffline1": "Don’t click “Reinstall macOS Tahoe”; open Utilities › Terminal from the menu bar",
|
||||
"guideOffline2": "Run the command below (the keyboard icon types it for you). It erases the blank disk as APFS and starts the install; it restarts a few times:",
|
||||
"guideOffline3": "When Setup Assistant appears, click “Exit recovery mode” to eject the installer and turn the network back on",
|
||||
"guideStartHint": "Start the VM to open the installation guide in its window",
|
||||
"guideStep1": "Open Disk Utility and select the largest “QEMU HARDDISK Media” (View › Show All Devices if it is hidden). Click Erase: name Macintosh HD, format APFS, scheme GUID. It may pause for 10–30 seconds; don’t force it off",
|
||||
"guideStep2": "Back in Recovery, choose “Reinstall macOS Tahoe” and install to the disk you erased. It restarts a few times",
|
||||
"guideStep3": "When Setup Assistant appears, click “Exit recovery mode” to eject the installer",
|
||||
"guideTitle": "Recovery mode",
|
||||
"netOff": "No network",
|
||||
"netShared": "Shared network",
|
||||
"onlineRecoveryConfirm": "Download \u0026 attach (~1 GB)",
|
||||
"onlineRecoveryDesc": "No recovery image is on this PC. Download Apple’s recovery image (about 1 GB) and attach it to “{name}”?",
|
||||
"onlineRecoveryTitle": "Download online recovery image?",
|
||||
"openSharedFolder": "Open shared folder",
|
||||
"openShort": "Open",
|
||||
"pendingRestartHint": "Takes effect after a restart",
|
||||
"pendingTitle": "Applies on next start",
|
||||
"pickRecoveryTitle": "Choose an offline image (.img / .dmg)",
|
||||
"restartToApply": "Restart to apply",
|
||||
"sendText": "Send text to VM…",
|
||||
"sendTextConfirm": "Send (Ctrl+Enter)",
|
||||
"sendTextDesc": "Supports Chinese, emoji, host IME, and dictation. Press Ctrl+Enter to inject into the focused macOS field.",
|
||||
"sendTextDescNoGT": "Guest Tools is not connected; only US-keyboard ASCII characters are supported until Guest Tools is connected.",
|
||||
"sendTextPlaceholder": "Type or paste text to send to the VM…",
|
||||
"sendTextTitle": "Send text to “{name}”",
|
||||
"sharedFolder": "Shared folder",
|
||||
"showInstallGuide": "Show install guide",
|
||||
"showWindow": "Show window",
|
||||
"snapshotCreate": "New restore point",
|
||||
"snapshotDelete": "Delete restore point",
|
||||
"snapshotEmpty": "No restore points yet — save one before OS updates or major changes",
|
||||
"snapshotHint": "Offline snapshots · Not a backup",
|
||||
"snapshotNamePlaceholder": "e.g. before-macos-update",
|
||||
"snapshotRestore": "Restore",
|
||||
"snapshotRestoreDesc": "Disk changes made after this restore point will be overwritten and cannot be undone.",
|
||||
"snapshotRestoreTitle": "Restore \"{name}\"?",
|
||||
"snapshotStopFirst": "Stop the VM before managing restore points",
|
||||
"snapshotsTitle": "Restore points",
|
||||
"softwareGraphics": "Software rendering",
|
||||
"specCPULiveTip": "{n, plural, one {# processor core, {pct}% in use} other {# processor cores, {pct}% in use}}",
|
||||
"specCPUTip": "{n, plural, one {# processor core} other {# processor cores}}",
|
||||
"specDiskTip": "Storage: {ctl}",
|
||||
"specDiskUsage": "{ctl} · {used} of {max} used",
|
||||
"specGraphicsTip": "Graphics: {gfx}",
|
||||
"specLang": "Language",
|
||||
"specLangTip": "macOS system language: {label}",
|
||||
"specLangTipDetail": "macOS system language: {label} ({detail})",
|
||||
"specMemLiveTip": "{mem} memory; the VM uses {used} on this PC",
|
||||
"specMemTip": "{mem} memory",
|
||||
"specNetOffTip": "The VM has no network",
|
||||
"specNetSSHTip": "Shares this PC’s network connection; SSH on port {port}",
|
||||
"specNetTip": "Shares this PC’s network connection",
|
||||
"sshMore": "SSH tools",
|
||||
"sshOpenTerminal": "Terminal",
|
||||
"sshOpenVSCode": "Open in VS Code",
|
||||
"sshSetUser": "Set SSH username…",
|
||||
"sshUserDesc": "Used for Terminal, ~/.ssh/config, and VS Code Remote-SSH (leave empty to omit user)",
|
||||
"sshUserPlaceholder": "e.g. admin",
|
||||
"sshUserTitle": "SSH login username",
|
||||
"sshWriteConfig": "Write ~/.ssh/config",
|
||||
"state_broken": "Error",
|
||||
"state_creating": "Creating",
|
||||
"state_driver_unavailable": "Driver unavailable",
|
||||
"state_running": "Running",
|
||||
"state_starting": "Starting",
|
||||
"state_stopped": "Stopped",
|
||||
"state_stopping": "Stopping",
|
||||
"techInfo": "Technical details",
|
||||
"toastCloned": "CoW clone “{name}” created",
|
||||
"toastDeleted": "{name} deleted",
|
||||
"toastDiagExported": "Redacted diagnostics archive exported (.zip)",
|
||||
"toastEjected": "Installer ejected",
|
||||
"toastEnterRecovery": "Recovery mode ready — pick Recovery in OpenCore on next start",
|
||||
"toastEnterRecoveryNextStart": "Recovery mode ready — restart to open the boot menu",
|
||||
"toastExitRecoveryNextStart": "Exited recovery mode — applies at next start",
|
||||
"toastFileDelivered": "Sent {name}",
|
||||
"toastFilesDelivered": "{n, plural, one {Sent # file to the shared folder} other {Sent # files to the shared folder}}",
|
||||
"toastGuestToolsAttached": "Guest Tools disk (REIMSTOOLS) attached",
|
||||
"toastGuestToolsAttachedNextStart": "Guest Tools disk attached — restart VM to mount in Finder",
|
||||
"toastGuestToolsDetached": "Tools disk ejected",
|
||||
"toastGuestToolsDetachedNextStart": "Tools disk ejected; applies on next start",
|
||||
"toastInstallFinished": "Exited recovery mode",
|
||||
"toastInstallerAttached": "Offline image attached: {name}",
|
||||
"toastInstallerAttachedNextStart": "Offline image attached (applies on restart): {name}",
|
||||
"toastNVMeNextStart": "Switched to NVMe — applies on next start",
|
||||
"toastNVMeReady": "Upgraded disk controller to NVMe",
|
||||
"toastOnlineRecoveryAttached": "Online recovery image attached to {name}",
|
||||
"toastOnlineRecoveryStarted": "Downloading online recovery image (~1 GB); will attach when ready",
|
||||
"toastPreventSleepOff": "Prevent-sleep guard disabled",
|
||||
"toastPreventSleepOn": "Prevent-sleep guard enabled",
|
||||
"toastScreenshotCopied": "VM screenshot copied",
|
||||
"toastSnapshotCreated": "Created restore point {name}",
|
||||
"toastSnapshotDeleted": "Deleted restore point {name}",
|
||||
"toastSnapshotRestored": "Restored to {name}",
|
||||
"toastStopped": "{name} shut down",
|
||||
"toastTyped": "{n, plural, one {Typed # character} other {Typed # characters}}",
|
||||
"typeClipboard": "Send clipboard to VM",
|
||||
"typeIntoVM": "Type into the VM",
|
||||
"typeUntypeable": "Only US-keyboard ASCII characters work without Guest Tools; connect Guest Tools for Chinese and Unicode text",
|
||||
"upgradeToNVMe": "Upgrade to NVMe",
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
import { registerBuiltinDomain } from '../runtime'
|
||||
|
||||
export const wizardZh: Record<string, string> = {
|
||||
"commandToggle": "等效命令",
|
||||
"commandToggleHint": "在终端运行下面这条命令效果相同",
|
||||
"createNow": "创建",
|
||||
"createStartedHint": "创建后窗口会关闭,进度在底部状态栏",
|
||||
"issuesCount": "{n, plural, other {有 # 项需要修改}}",
|
||||
"offlineCached": "已下载",
|
||||
"offlineHint": "约 20 GB,安装时不联网",
|
||||
"offlineListFailedDetail": "无法读取 Apple 的版本列表:{err}",
|
||||
"offlineLoading": "正在读取 Apple 的版本列表…",
|
||||
"offlineSpaceWarn": "可用空间 {free} GB,下载这个版本需要约 {need} GB",
|
||||
"runtimeAlpha": "接收 Alpha 版",
|
||||
"runtimeAlphaHint": "Alpha 版由 CI 每天从上游自动构建,未经真实宿主冒烟测试",
|
||||
"runtimeChannel_alpha": "Alpha 版",
|
||||
"runtimeChannel_stable": "稳定版",
|
||||
"runtimeCurrent": "当前运行时",
|
||||
"runtimeInstall": "安装",
|
||||
"runtimeLatest": "最新:{v}",
|
||||
"runtimeLookupFailed": "无法读取运行时列表",
|
||||
"runtimeLookupRateLimit": "GitHub 接口限流(HTTP 403),请稍后重试或手动导入",
|
||||
"runtimeNewer": "有新版本:{v}",
|
||||
"runtimeNoneOnChannel": "这个通道还没有发布运行时",
|
||||
"runtimeOnline": "在线安装",
|
||||
"runtimeRetry": "重试",
|
||||
"runtimeUpToDate": "已是最新",
|
||||
"runtimeUpdate": "更新",
|
||||
"setupCheck": "环境",
|
||||
"setupContinue": "继续",
|
||||
"setupDesc": "虚拟机、安装包和运行时都放在这里",
|
||||
"setupDone": "完成",
|
||||
"setupExternal": "外置盘",
|
||||
"setupFree": "可用 {n} GB",
|
||||
"setupGPU": "显卡(Vulkan)",
|
||||
"setupImport": "导入本地包…",
|
||||
"setupLater": "稍后",
|
||||
"setupNoGPU": "没有检测到 Vulkan 显卡,只能用软件渲染",
|
||||
"setupOther": "其他位置…",
|
||||
"setupRecMem": "推荐 {n} GB",
|
||||
"setupRecommended": "推荐",
|
||||
"setupReuse": "这里已有 Reims-Go 数据,会直接沿用",
|
||||
"setupRuntimeDesc": "运行虚拟机所需的 QEMU 与 reims-ctl,从 GitHub 下载并校验",
|
||||
"setupRuntimeTitle": "检查环境并安装运行时",
|
||||
"setupSystem": "系统盘",
|
||||
"setupTitle": "选择数据目录",
|
||||
"setupWarnExternal": "外置盘拔出时,正在运行的虚拟机会损坏",
|
||||
"setupWarnSpace": "可用空间不足 60 GB:一个离线安装包约 20 GB,虚拟磁盘会随使用增长",
|
||||
"setupWarnSystem": "放在系统盘,空间紧张时会影响 Windows",
|
||||
"srcAppleSub": "恢复镜像,系统在装机时在线下载",
|
||||
"srcAppleTitle": "从 Apple 下载",
|
||||
"srcDiskSub": "已装好 macOS 的 .qcow2 等磁盘",
|
||||
"srcDiskTitle": "已有磁盘",
|
||||
"srcInstallerSub": "本机上的 .img 或 .dmg",
|
||||
"srcInstallerTitle": "安装镜像",
|
||||
"srcOfflineSub": "完整安装包,装机时不联网",
|
||||
"srcOfflineTitle": "离线安装包",
|
||||
"step1": "系统来源",
|
||||
"step2": "处理器与内存",
|
||||
"step3": "存储",
|
||||
"step4": "图形与选项",
|
||||
"step5": "确认",
|
||||
"summaryAppleSource": "从 Apple 下载 · {v}",
|
||||
"summaryDefaultDir": "数据目录(默认)",
|
||||
"summaryDiskGrow": "{size},按实际占用增长",
|
||||
"summaryDiskSource": "已有磁盘 · {file}",
|
||||
"summaryEdit": "修改",
|
||||
"summaryInstallerSource": "本地安装器 · {file}",
|
||||
"summaryLogs": "图形与串口日志",
|
||||
"summaryOfflineSource": "离线安装包 · macOS {v}",
|
||||
"summaryOn": "开",
|
||||
"summarySSH": "SSH 转发",
|
||||
"summarySSHPort": "端口 {n}",
|
||||
"summarySource": "来源",
|
||||
"validationChecking": "正在检查…",
|
||||
"validationPassed": "可以创建",
|
||||
"wizChooseFile": "选择…",
|
||||
"wizNoFile": "还没有选择文件",
|
||||
"wizOptions": "选项",
|
||||
"wizardBasics": "基本信息",
|
||||
"wizardDriverGroup": "客体平台驱动",
|
||||
"wizardDriverType": "驱动类型",
|
||||
"wizardTitle": "新建虚拟机",
|
||||
}
|
||||
|
||||
export const wizardEn: Record<string, string> = {
|
||||
"commandToggle": "Equivalent command",
|
||||
"commandToggleHint": "Running this in a terminal does the same thing",
|
||||
"createNow": "Create",
|
||||
"createStartedHint": "The window closes once creation starts; progress shows in the status bar",
|
||||
"issuesCount": "{n, plural, one {# issue to fix} other {# issues to fix}}",
|
||||
"offlineCached": "Downloaded",
|
||||
"offlineHint": "About 20 GB; installs with no network",
|
||||
"offlineListFailedDetail": "Couldn’t read Apple’s release list: {err}",
|
||||
"offlineLoading": "Reading Apple’s release list…",
|
||||
"offlineSpaceWarn": "{free} GB free; this release needs about {need} GB",
|
||||
"runtimeAlpha": "Receive alpha builds",
|
||||
"runtimeAlphaHint": "Built daily from upstream by CI; not smoke-tested on a real host",
|
||||
"runtimeChannel_alpha": "Alpha",
|
||||
"runtimeChannel_stable": "Stable",
|
||||
"runtimeCurrent": "Current runtime",
|
||||
"runtimeInstall": "Install",
|
||||
"runtimeLatest": "Latest: {v}",
|
||||
"runtimeLookupFailed": "Couldn’t read the runtime list",
|
||||
"runtimeLookupRateLimit": "GitHub API rate limit reached (HTTP 403); retry later or import a local bundle",
|
||||
"runtimeNewer": "New version: {v}",
|
||||
"runtimeNoneOnChannel": "No runtime published on this channel yet",
|
||||
"runtimeOnline": "Online install",
|
||||
"runtimeRetry": "Retry",
|
||||
"runtimeUpToDate": "Up to date",
|
||||
"runtimeUpdate": "Update",
|
||||
"setupCheck": "Host",
|
||||
"setupContinue": "Continue",
|
||||
"setupDesc": "VMs, installers and runtimes all live here",
|
||||
"setupDone": "Done",
|
||||
"setupExternal": "External",
|
||||
"setupFree": "{n} GB free",
|
||||
"setupGPU": "Graphics (Vulkan)",
|
||||
"setupImport": "Import a local package…",
|
||||
"setupLater": "Later",
|
||||
"setupNoGPU": "No Vulkan GPU found; only software rendering will work",
|
||||
"setupOther": "Other location…",
|
||||
"setupRecMem": "{n} GB recommended",
|
||||
"setupRecommended": "Recommended",
|
||||
"setupReuse": "This folder already has Reims-Go data; it will be reused",
|
||||
"setupRuntimeDesc": "QEMU and reims-ctl, downloaded from GitHub and verified",
|
||||
"setupRuntimeTitle": "Check the host and install the runtime",
|
||||
"setupSystem": "System drive",
|
||||
"setupTitle": "Choose a data folder",
|
||||
"setupWarnExternal": "Unplugging an external drive corrupts running VMs",
|
||||
"setupWarnSpace": "Under 60 GB free: an offline installer is about 20 GB and virtual disks grow with use",
|
||||
"setupWarnSystem": "On the system drive, low space can affect Windows",
|
||||
"srcAppleSub": "A recovery image; macOS downloads during install",
|
||||
"srcAppleTitle": "Download from Apple",
|
||||
"srcDiskSub": "A .qcow2 or other disk with macOS installed",
|
||||
"srcDiskTitle": "Existing disk",
|
||||
"srcInstallerSub": "An .img or .dmg on this PC",
|
||||
"srcInstallerTitle": "Installer image",
|
||||
"srcOfflineSub": "The full installer; installs with no network",
|
||||
"srcOfflineTitle": "Offline installer",
|
||||
"step1": "Source",
|
||||
"step2": "CPU \u0026 memory",
|
||||
"step3": "Storage",
|
||||
"step4": "Graphics \u0026 options",
|
||||
"step5": "Review",
|
||||
"summaryAppleSource": "Download from Apple · {v}",
|
||||
"summaryDefaultDir": "Data folder (default)",
|
||||
"summaryDiskGrow": "{size}, grows with use",
|
||||
"summaryDiskSource": "Existing disk · {file}",
|
||||
"summaryEdit": "Edit",
|
||||
"summaryInstallerSource": "Local installer · {file}",
|
||||
"summaryLogs": "Graphics \u0026 serial logs",
|
||||
"summaryOfflineSource": "Offline installer · macOS {v}",
|
||||
"summaryOn": "On",
|
||||
"summarySSH": "SSH forwarding",
|
||||
"summarySSHPort": "Port {n}",
|
||||
"summarySource": "Source",
|
||||
"validationChecking": "Checking…",
|
||||
"validationPassed": "Ready to create",
|
||||
"wizChooseFile": "Choose…",
|
||||
"wizNoFile": "No file chosen",
|
||||
"wizOptions": "Options",
|
||||
"wizardBasics": "Basics",
|
||||
"wizardDriverGroup": "Guest driver",
|
||||
"wizardDriverType": "Driver",
|
||||
"wizardTitle": "New virtual machine",
|
||||
}
|
||||
|
||||
registerBuiltinDomain(wizardZh, wizardEn)
|
||||
@@ -0,0 +1,368 @@
|
||||
// Zero-dependency isomorphic lightweight ICU MessageFormat evaluator + en-XA pseudo-localizer.
|
||||
// Matches internal/i18n/icu.go 1:1 while delegating plural selection & number formatting
|
||||
// to native zero-bundle-cost browser Intl APIs.
|
||||
|
||||
export type ICUVars = Record<string, string | number | boolean | undefined | null>
|
||||
|
||||
type ICUNode =
|
||||
| { kind: 'text'; text: string }
|
||||
| { kind: 'pound' }
|
||||
| { kind: 'var'; name: string }
|
||||
| { kind: 'number'; name: string; precision: number }
|
||||
| { kind: 'plural' | 'select'; name: string; branches: Array<{ selector: string; nodes: ICUNode[] }> }
|
||||
|
||||
const astCache = new Map<string, ICUNode[] | null>()
|
||||
const pluralRulesCache = new Map<string, Intl.PluralRules>()
|
||||
const numberFormatCache = new Map<string, Intl.NumberFormat>()
|
||||
|
||||
function getPluralRules(locale: string): Intl.PluralRules {
|
||||
const key = locale === 'en-XA' ? 'en-US' : locale
|
||||
let pr = pluralRulesCache.get(key)
|
||||
if (!pr) {
|
||||
try {
|
||||
pr = new Intl.PluralRules(key)
|
||||
} catch {
|
||||
pr = new Intl.PluralRules('en-US')
|
||||
}
|
||||
pluralRulesCache.set(key, pr)
|
||||
}
|
||||
return pr
|
||||
}
|
||||
|
||||
export function formatLocaleNumber(locale: string, value: number, precision = -1): string {
|
||||
const cleanLoc = locale === 'en-XA' ? 'en-US' : locale
|
||||
const cacheKey = `${cleanLoc}:${precision}`
|
||||
let nf = numberFormatCache.get(cacheKey)
|
||||
if (!nf) {
|
||||
const opts: Intl.NumberFormatOptions =
|
||||
precision >= 0
|
||||
? { minimumFractionDigits: precision, maximumFractionDigits: precision, useGrouping: false }
|
||||
: { useGrouping: false }
|
||||
try {
|
||||
nf = new Intl.NumberFormat(cleanLoc, opts)
|
||||
} catch {
|
||||
nf = new Intl.NumberFormat('en-US', opts)
|
||||
}
|
||||
numberFormatCache.set(cacheKey, nf)
|
||||
}
|
||||
return nf.format(value)
|
||||
}
|
||||
|
||||
export function parseICU(tmpl: string): ICUNode[] | null {
|
||||
if (astCache.has(tmpl)) {
|
||||
return astCache.get(tmpl) ?? null
|
||||
}
|
||||
let pos = 0
|
||||
const len = tmpl.length
|
||||
|
||||
const skipWS = () => {
|
||||
while (pos < len) {
|
||||
const c = tmpl.charCodeAt(pos)
|
||||
if (c === 32 || c === 9 || c === 10 || c === 13) pos++
|
||||
else break
|
||||
}
|
||||
}
|
||||
|
||||
const readIdent = (): string => {
|
||||
const start = pos
|
||||
while (pos < len) {
|
||||
const c = tmpl.charCodeAt(pos)
|
||||
if (
|
||||
(c >= 97 && c <= 122) ||
|
||||
(c >= 65 && c <= 90) ||
|
||||
(c >= 48 && c <= 57) ||
|
||||
c === 95 || // _
|
||||
c === 45 || // -
|
||||
c === 46 || // .
|
||||
c === 61 // =
|
||||
) {
|
||||
pos++
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
return tmpl.slice(start, pos)
|
||||
}
|
||||
|
||||
const parseNodes = (stopAtBrace: boolean, inPlural: boolean): ICUNode[] | null => {
|
||||
const nodes: ICUNode[] = []
|
||||
let buf = ''
|
||||
const flush = () => {
|
||||
if (buf.length > 0) {
|
||||
nodes.push({ kind: 'text', text: buf })
|
||||
buf = ''
|
||||
}
|
||||
}
|
||||
|
||||
while (pos < len) {
|
||||
const ch = tmpl[pos]
|
||||
if (ch === "'") {
|
||||
if (pos + 1 < len && tmpl[pos + 1] === "'") {
|
||||
buf += "'"
|
||||
pos += 2
|
||||
continue
|
||||
}
|
||||
const next = pos + 1 < len ? tmpl[pos + 1] : ''
|
||||
if (next === '{' || next === '}' || (inPlural && next === '#')) {
|
||||
pos++
|
||||
while (pos < len) {
|
||||
if (tmpl[pos] === "'") {
|
||||
if (pos + 1 < len && tmpl[pos + 1] === "'") {
|
||||
buf += "'"
|
||||
pos += 2
|
||||
continue
|
||||
}
|
||||
pos++
|
||||
break
|
||||
}
|
||||
buf += tmpl[pos++]
|
||||
}
|
||||
continue
|
||||
}
|
||||
buf += "'"
|
||||
pos++
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === '}') {
|
||||
if (stopAtBrace) {
|
||||
flush()
|
||||
return nodes
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
if (ch === '#' && inPlural) {
|
||||
flush()
|
||||
nodes.push({ kind: 'pound' })
|
||||
pos++
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === '{') {
|
||||
flush()
|
||||
const node = parsePlaceholder(inPlural)
|
||||
if (!node) return null
|
||||
nodes.push(node)
|
||||
continue
|
||||
}
|
||||
|
||||
buf += ch
|
||||
pos++
|
||||
}
|
||||
|
||||
if (stopAtBrace) return null
|
||||
flush()
|
||||
return nodes
|
||||
}
|
||||
|
||||
const parsePlaceholder = (parentInPlural: boolean): ICUNode | null => {
|
||||
pos++ // skip '{'
|
||||
skipWS()
|
||||
const name = readIdent()
|
||||
if (!name) return null
|
||||
skipWS()
|
||||
if (pos < len && tmpl[pos] === '}') {
|
||||
pos++
|
||||
return { kind: 'var', name }
|
||||
}
|
||||
if (pos >= len || tmpl[pos] !== ',') return null
|
||||
pos++
|
||||
skipWS()
|
||||
const fn = readIdent()
|
||||
skipWS()
|
||||
|
||||
if (fn === 'number') {
|
||||
let precision = -1
|
||||
if (pos < len && tmpl[pos] === ',') {
|
||||
pos++
|
||||
skipWS()
|
||||
const style = readIdent()
|
||||
if (style.startsWith('.') && style.length > 1) {
|
||||
const p = Number.parseInt(style.slice(1), 10)
|
||||
if (Number.isNaN(p) || p < 0 || p > 6) return null
|
||||
precision = p
|
||||
} else if (style !== '') {
|
||||
return null
|
||||
}
|
||||
skipWS()
|
||||
}
|
||||
if (pos >= len || tmpl[pos] !== '}') return null
|
||||
pos++
|
||||
return { kind: 'number', name, precision }
|
||||
}
|
||||
|
||||
if (fn === 'plural' || fn === 'select') {
|
||||
if (pos >= len || tmpl[pos] !== ',') return null
|
||||
pos++
|
||||
const isPlural = fn === 'plural'
|
||||
const branches: Array<{ selector: string; nodes: ICUNode[] }> = []
|
||||
let hasOther = false
|
||||
while (true) {
|
||||
skipWS()
|
||||
if (pos < len && tmpl[pos] === '}') {
|
||||
pos++
|
||||
break
|
||||
}
|
||||
const selector = readIdent()
|
||||
if (!selector) return null
|
||||
if (selector === 'other') hasOther = true
|
||||
skipWS()
|
||||
if (pos >= len || tmpl[pos] !== '{') return null
|
||||
pos++
|
||||
const childNodes = parseNodes(true, isPlural || parentInPlural)
|
||||
if (!childNodes || pos >= len || tmpl[pos] !== '}') return null
|
||||
pos++
|
||||
branches.push({ selector, nodes: childNodes })
|
||||
}
|
||||
if (!hasOther) return null
|
||||
return { kind: fn, name, branches }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const parsed = parseNodes(false, false)
|
||||
const valid = parsed && pos === len ? parsed : null
|
||||
if (astCache.size > 3000) astCache.clear()
|
||||
astCache.set(tmpl, valid)
|
||||
return valid
|
||||
}
|
||||
|
||||
export function formatICU(locale: string, tmpl: string, vars?: ICUVars, strictVars = false): string | null {
|
||||
if (!vars && !tmpl.includes('{') && !tmpl.includes("'")) {
|
||||
return tmpl
|
||||
}
|
||||
const nodes = parseICU(tmpl)
|
||||
if (!nodes) return null
|
||||
|
||||
const evalList = (list: ICUNode[], poundVal?: string): string | null => {
|
||||
let out = ''
|
||||
for (const nd of list) {
|
||||
switch (nd.kind) {
|
||||
case 'text':
|
||||
out += nd.text
|
||||
break
|
||||
case 'pound':
|
||||
out += poundVal !== undefined ? poundVal : '#'
|
||||
break
|
||||
case 'var': {
|
||||
const val = vars?.[nd.name]
|
||||
if (val === undefined || val === null) {
|
||||
if (strictVars) return null
|
||||
out += `{${nd.name}}`
|
||||
} else {
|
||||
out += String(val)
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'number': {
|
||||
const val = vars?.[nd.name]
|
||||
if (val === undefined || val === null) {
|
||||
if (strictVars) return null
|
||||
out += `{${nd.name}}`
|
||||
} else {
|
||||
const num = typeof val === 'number' ? val : Number(val)
|
||||
out += Number.isFinite(num) ? formatLocaleNumber(locale, num, nd.precision) : String(val)
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'plural': {
|
||||
const raw = vars?.[nd.name]
|
||||
if ((raw === undefined || raw === null) && strictVars) return null
|
||||
const num = typeof raw === 'number' ? raw : Number(raw ?? 0)
|
||||
const safeNum = Number.isFinite(num) ? num : 0
|
||||
const exact = Number.isInteger(safeNum) ? `=${safeNum}` : ''
|
||||
const cat = getPluralRules(locale).select(safeNum)
|
||||
const chosen =
|
||||
(exact ? nd.branches.find((b) => b.selector === exact) : undefined) ??
|
||||
nd.branches.find((b) => b.selector === cat) ??
|
||||
nd.branches.find((b) => b.selector === 'other') ??
|
||||
nd.branches[nd.branches.length - 1]
|
||||
const formattedNum = formatLocaleNumber(locale, safeNum, -1)
|
||||
const inner = evalList(chosen ? chosen.nodes : [], formattedNum)
|
||||
if (inner === null) return null
|
||||
out += inner
|
||||
break
|
||||
}
|
||||
case 'select': {
|
||||
const raw = vars?.[nd.name]
|
||||
if ((raw === undefined || raw === null) && strictVars) return null
|
||||
const key = raw === undefined || raw === null ? '' : String(raw)
|
||||
const chosen =
|
||||
nd.branches.find((b) => b.selector === key) ??
|
||||
nd.branches.find((b) => b.selector === 'other') ??
|
||||
nd.branches[nd.branches.length - 1]
|
||||
const inner = evalList(chosen ? chosen.nodes : [], poundVal)
|
||||
if (inner === null) return null
|
||||
out += inner
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
return evalList(nodes)
|
||||
}
|
||||
|
||||
const PSEUDO_MAP: Record<string, string> = {
|
||||
a: 'à', b: 'ƀ', c: 'č', d: 'ď', e: 'ë', f: 'ƒ', g: 'ğ', h: 'ĥ', i: 'î', j: 'ĵ', k: 'ķ', l: 'ľ', m: 'ɱ',
|
||||
n: 'ñ', o: 'ô', p: 'þ', q: 'ǫ', r: 'ŕ', s: 'ś', t: 'ť', u: 'ü', v: 'ṽ', w: 'ŵ', x: 'ẋ', y: 'ÿ', z: 'ž',
|
||||
A: 'À', B: 'Ɓ', C: 'Č', D: 'Ď', E: 'Ë', F: 'Ƒ', G: 'Ğ', H: 'Ĥ', I: 'Î', J: 'Ĵ', K: 'Ķ', L: 'Ľ', M: 'Ṁ',
|
||||
N: 'Ñ', O: 'Ô', P: 'Þ', Q: 'Ǫ', R: 'Ŕ', S: 'Š', T: 'Ť', U: 'Ü', V: 'Ṽ', W: 'Ŵ', X: 'Ẋ', Y: 'Ÿ', Z: 'Ž',
|
||||
}
|
||||
|
||||
function accentString(s: string): string {
|
||||
let out = ''
|
||||
for (const ch of s) {
|
||||
out += PSEUDO_MAP[ch] ?? ch
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function pseudoLocalizeICU(enTmpl: string): string {
|
||||
const nodes = parseICU(enTmpl)
|
||||
if (!nodes) return `⟦${enTmpl}⟧`
|
||||
|
||||
const countChars = (list: ICUNode[]): number =>
|
||||
list.reduce((acc, n) => acc + (n.kind === 'text' ? [...n.text].length : 0), 0)
|
||||
|
||||
const topChars = countChars(nodes)
|
||||
const topPad =
|
||||
topChars === 0
|
||||
? 0
|
||||
: topChars <= 8
|
||||
? Math.max(4, Math.ceil(topChars * 0.85))
|
||||
: Math.ceil(topChars * 0.35)
|
||||
|
||||
const serialize = (list: ICUNode[], pad: number, isTop: boolean): string => {
|
||||
let s = ''
|
||||
for (const nd of list) {
|
||||
if (nd.kind === 'text') {
|
||||
s += accentString(nd.text).replaceAll("'", "''")
|
||||
} else if (nd.kind === 'pound') {
|
||||
s += '#'
|
||||
} else if (nd.kind === 'var') {
|
||||
s += `{${nd.name}}`
|
||||
} else if (nd.kind === 'number') {
|
||||
s += nd.precision >= 0 ? `{${nd.name}, number, .${nd.precision}}` : `{${nd.name}, number}`
|
||||
} else {
|
||||
s += `{${nd.name}, ${nd.kind}, `
|
||||
s += nd.branches
|
||||
.map((br) => {
|
||||
const brPad = isTop && topChars === 0 ? Math.max(3, Math.ceil(countChars(br.nodes) * 0.35)) : 0
|
||||
return `${br.selector} {${serialize(br.nodes, brPad, false)}}`
|
||||
})
|
||||
.join(' ')
|
||||
s += '}'
|
||||
}
|
||||
}
|
||||
if (pad > 0) {
|
||||
s += ' ' + '·'.repeat(pad)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
return `⟦${serialize(nodes, topPad, true)}⟧`
|
||||
}
|
||||
@@ -0,0 +1,797 @@
|
||||
// Code generated by cmd/i18ngen; DO NOT EDIT.
|
||||
|
||||
export type I18nKey =
|
||||
| "aboutCommunity"
|
||||
| "aboutCopyQQGroup"
|
||||
| "aboutIssueSub"
|
||||
| "aboutJoinQQGroup"
|
||||
| "aboutProjectSub"
|
||||
| "aboutQQGroup"
|
||||
| "aboutQQGroupSub"
|
||||
| "aboutQQLaunchFailed"
|
||||
| "aboutQQNotInstalled"
|
||||
| "aboutQQNotInstalledSub"
|
||||
| "aboutTagline"
|
||||
| "activate"
|
||||
| "affinityApplyNow"
|
||||
| "affinityAvoidLPE"
|
||||
| "affinityConfigure"
|
||||
| "affinityEcoQoS"
|
||||
| "affinityEcoQoSDesc"
|
||||
| "affinityExcludeCPU0"
|
||||
| "affinityLiveMask"
|
||||
| "affinityMenu"
|
||||
| "affinityModeAll"
|
||||
| "affinityModeAllHint"
|
||||
| "affinityModeAuto"
|
||||
| "affinityModeAutoHint"
|
||||
| "affinityModeCustom"
|
||||
| "affinityModeCustomHint"
|
||||
| "affinityModeNonLPE"
|
||||
| "affinityModeNonLPEHint"
|
||||
| "affinityModePCores"
|
||||
| "affinityModePCoresHint"
|
||||
| "affinityNeedOne"
|
||||
| "affinityOnlyPCores"
|
||||
| "affinityOversubWarn"
|
||||
| "affinityPhysicalOnly"
|
||||
| "affinityRowDesc"
|
||||
| "affinitySave"
|
||||
| "affinitySelectAll"
|
||||
| "affinitySelectedSummary"
|
||||
| "affinitySubtitleRunning"
|
||||
| "affinitySubtitleStopped"
|
||||
| "affinitySummaryAll"
|
||||
| "affinitySummaryAuto"
|
||||
| "affinitySummaryCustom"
|
||||
| "affinitySummaryNonLPE"
|
||||
| "affinitySummaryPCores"
|
||||
| "affinityTitle"
|
||||
| "appCheckUpdate"
|
||||
| "appDownloadUpdate"
|
||||
| "appUpToDate"
|
||||
| "appUpdateAvailable"
|
||||
| "appUpdateLookupFailed"
|
||||
| "appVersionTitle"
|
||||
| "appearance"
|
||||
| "appliesNextStart"
|
||||
| "attachGuestTools"
|
||||
| "attachInstaller"
|
||||
| "audioBackendAuto"
|
||||
| "audioBackendDesc"
|
||||
| "audioBackendDsound"
|
||||
| "audioBackendNone"
|
||||
| "audioBackendTitle"
|
||||
| "audioDesc"
|
||||
| "audioDisabledReason"
|
||||
| "audioTroubleshootNote"
|
||||
| "autoPinPCores"
|
||||
| "back"
|
||||
| "backToEdit"
|
||||
| "borderless"
|
||||
| "brokenHint"
|
||||
| "cancel"
|
||||
| "captureInput"
|
||||
| "captureInputHint"
|
||||
| "catAdvanced"
|
||||
| "catAudio"
|
||||
| "catCompute"
|
||||
| "catGeneral"
|
||||
| "catGraphics"
|
||||
| "catInput"
|
||||
| "catInputAudio"
|
||||
| "catLogs"
|
||||
| "catNetwork"
|
||||
| "catStorage"
|
||||
| "catStorageNet"
|
||||
| "choose"
|
||||
| "clear"
|
||||
| "cloneConfirm"
|
||||
| "cloneDesc"
|
||||
| "cloneNameLabel"
|
||||
| "cloneTitle"
|
||||
| "cloneVM"
|
||||
| "close"
|
||||
| "closeWindow"
|
||||
| "collapseLogs"
|
||||
| "commandToggle"
|
||||
| "commandToggleHint"
|
||||
| "configured"
|
||||
| "connGroup"
|
||||
| "copy"
|
||||
| "copyScreenshot"
|
||||
| "copyTechInfo"
|
||||
| "cores"
|
||||
| "coresUnit"
|
||||
| "cpuOverHint"
|
||||
| "cpuRecHint"
|
||||
| "createNow"
|
||||
| "createStartedHint"
|
||||
| "delete"
|
||||
| "deleteConfirm"
|
||||
| "deleteDesc"
|
||||
| "deleteDescKeep"
|
||||
| "deleteEllipsis"
|
||||
| "deleteKeepFiles"
|
||||
| "deleteTitle"
|
||||
| "deliverFileShort"
|
||||
| "detachGuestTools"
|
||||
| "diagAhciUpgradeHint"
|
||||
| "diagExternalDriveWarn"
|
||||
| "diagHighMemWarn"
|
||||
| "diskCompactAction"
|
||||
| "diskCompactDesc"
|
||||
| "diskCompactDone"
|
||||
| "diskCompactNoGain"
|
||||
| "diskCompactQcow2Only"
|
||||
| "diskCompactTitle"
|
||||
| "diskController"
|
||||
| "diskControllerInstallHint"
|
||||
| "diskControllerNvmeHint"
|
||||
| "diskControllerNvmeReadyHint"
|
||||
| "diskControllerVirtioHint"
|
||||
| "diskControllerWarn"
|
||||
| "diskMode"
|
||||
| "diskModeCopy"
|
||||
| "diskModeInPlace"
|
||||
| "diskResizeAction"
|
||||
| "diskResizeDesc"
|
||||
| "diskResizeDone"
|
||||
| "diskResizeTitle"
|
||||
| "diskSize"
|
||||
| "diskSizeHint"
|
||||
| "diskUsageSummary"
|
||||
| "displayGroup"
|
||||
| "displayNameEdit"
|
||||
| "displayNameEditEllipsis"
|
||||
| "displayNameLabel"
|
||||
| "displayNameTip"
|
||||
| "displays"
|
||||
| "driveShareMaster"
|
||||
| "driveShareMasterDesc"
|
||||
| "driveShareNeedsTools"
|
||||
| "driveShareNoDrives"
|
||||
| "driveShareReadOnly"
|
||||
| "driveShareSystem"
|
||||
| "driveShareTitle"
|
||||
| "dropFilesHint"
|
||||
| "effectImmediate"
|
||||
| "effectNextStart"
|
||||
| "eject"
|
||||
| "emptyVMs"
|
||||
| "enableAudio"
|
||||
| "enableLogs"
|
||||
| "enableNetwork"
|
||||
| "enableWHPX"
|
||||
| "enterRecovery"
|
||||
| "errCopyDetails"
|
||||
| "errRawDetailsToggle"
|
||||
| "errorBoundaryReload"
|
||||
| "errorBoundaryTitle"
|
||||
| "expandLogs"
|
||||
| "exportDiagnostics"
|
||||
| "extraArgs"
|
||||
| "extraArgsDesc"
|
||||
| "factCPU"
|
||||
| "factDisk"
|
||||
| "factGraphics"
|
||||
| "factMemory"
|
||||
| "failAffinity"
|
||||
| "failAttachInstaller"
|
||||
| "failCloneVM"
|
||||
| "failCreate"
|
||||
| "failDelete"
|
||||
| "failDownload"
|
||||
| "failEject"
|
||||
| "failEnterRecovery"
|
||||
| "failExportDiagnostics"
|
||||
| "failFinishInstall"
|
||||
| "failFocus"
|
||||
| "failGeneric"
|
||||
| "failGuestTools"
|
||||
| "failOpenFolder"
|
||||
| "failRestart"
|
||||
| "failRuntime"
|
||||
| "failSSH"
|
||||
| "failScreenshot"
|
||||
| "failSnapshot"
|
||||
| "failStart"
|
||||
| "failStop"
|
||||
| "failType"
|
||||
| "failUpgradeNVMe"
|
||||
| "fieldAudio"
|
||||
| "fieldCPUModel"
|
||||
| "fieldController"
|
||||
| "fieldDir"
|
||||
| "fieldDisk"
|
||||
| "fieldGraphicsBackend"
|
||||
| "fieldICD"
|
||||
| "fieldKind"
|
||||
| "fieldNetwork"
|
||||
| "fieldVMName"
|
||||
| "finishInstall"
|
||||
| "fontMissingFoDHint"
|
||||
| "footerDisk"
|
||||
| "footerDiskLabel"
|
||||
| "footerDiskTip"
|
||||
| "footerDiskValue"
|
||||
| "footerHostIssue"
|
||||
| "footerHostIssueTip"
|
||||
| "footerMem"
|
||||
| "footerMemAvail"
|
||||
| "footerMemLabel"
|
||||
| "footerMemTip"
|
||||
| "footerMemValue"
|
||||
| "footerRunningVMs"
|
||||
| "forceStop"
|
||||
| "fullscreenLaunch"
|
||||
| "fullscreenLaunchHint"
|
||||
| "gpuAuto"
|
||||
| "gpuAutoOption"
|
||||
| "gpuAutoSub"
|
||||
| "gpuAutoTitle"
|
||||
| "gpuCompatUnsupported"
|
||||
| "gpuCompatWarn"
|
||||
| "gpuCustomIcd"
|
||||
| "gpuDiscrete"
|
||||
| "gpuErrMissingExt"
|
||||
| "gpuErrVulkanCpu"
|
||||
| "gpuErrVulkanTooOld"
|
||||
| "gpuIntegrated"
|
||||
| "gpuKindDiscrete"
|
||||
| "gpuKindIntegrated"
|
||||
| "gpuRecommended"
|
||||
| "gpuSelect"
|
||||
| "gpuSvgaReason"
|
||||
| "gpuSwitchSvga"
|
||||
| "gpuUnavailableHint"
|
||||
| "gpuUnknown"
|
||||
| "gpuVirtual"
|
||||
| "gpuWarnAmdLegacy"
|
||||
| "gpuWarnAmdRdna2"
|
||||
| "graphicsBackend"
|
||||
| "graphicsReimsDesc"
|
||||
| "graphicsReimsShort"
|
||||
| "graphicsRunningReason"
|
||||
| "graphicsSvgaDesc"
|
||||
| "graphicsSvgaShort"
|
||||
| "groupGraphics"
|
||||
| "groupMacOS"
|
||||
| "groupPerformance"
|
||||
| "groupQemu"
|
||||
| "gtInstall"
|
||||
| "gtInstallCmd"
|
||||
| "gtInstallSub"
|
||||
| "gtNotInstalledDesc"
|
||||
| "gtStatusConnected"
|
||||
| "gtStatusEnabled"
|
||||
| "gtStatusNone"
|
||||
| "gtStatusOff"
|
||||
| "gtStatusOffTip"
|
||||
| "gtStatusUpgrade"
|
||||
| "gtStatusWaiting"
|
||||
| "gtStatusWaitingTip"
|
||||
| "gtUpdate"
|
||||
| "guestKbdPinyin"
|
||||
| "guestKbdUS"
|
||||
| "guestKbdUSRecommended"
|
||||
| "guestLang"
|
||||
| "guestLangEnUS"
|
||||
| "guestLangHint"
|
||||
| "guestLangJaJP"
|
||||
| "guestLangKoKR"
|
||||
| "guestLangSettingsHint"
|
||||
| "guestLangShort"
|
||||
| "guestLangZhHansUS"
|
||||
| "guestLangZhHantUS"
|
||||
| "guestMemory"
|
||||
| "guestToolsConnected"
|
||||
| "guestToolsModeSync"
|
||||
| "guestToolsModeWebDAV"
|
||||
| "guestToolsPreventSleep"
|
||||
| "guestToolsPreventSleepSub"
|
||||
| "guestToolsReady"
|
||||
| "guestToolsSleepActive"
|
||||
| "guestToolsTitle"
|
||||
| "guestToolsUpgradeHint"
|
||||
| "guideBuiltIn1"
|
||||
| "guideBuiltIn2"
|
||||
| "guideBuiltIn3"
|
||||
| "guideKindBuiltIn"
|
||||
| "guideKindOffline"
|
||||
| "guideKindOnline"
|
||||
| "guideOffline1"
|
||||
| "guideOffline2"
|
||||
| "guideOffline3"
|
||||
| "guideStartHint"
|
||||
| "guideStep1"
|
||||
| "guideStep2"
|
||||
| "guideStep3"
|
||||
| "guideTitle"
|
||||
| "helpAbout"
|
||||
| "helpCheckUpdate"
|
||||
| "helpProjectPage"
|
||||
| "helpReportIssue"
|
||||
| "hideSidebar"
|
||||
| "hidpiPresetBadge"
|
||||
| "hidpiTipFullscreen"
|
||||
| "hidpiTipScale"
|
||||
| "hidpiTipUnavailable"
|
||||
| "hostAudioInput"
|
||||
| "hostAudioMissingIn"
|
||||
| "hostAudioMissingOut"
|
||||
| "hostAudioOutput"
|
||||
| "hostCPU"
|
||||
| "hostCoresThreads"
|
||||
| "hostDataRoot"
|
||||
| "hostDisk"
|
||||
| "hostDisplayHint"
|
||||
| "hostDisplayPrimary"
|
||||
| "hostDisplays"
|
||||
| "hostGPUs"
|
||||
| "hostNeedsAction"
|
||||
| "hostRAM"
|
||||
| "hostRAMAvail"
|
||||
| "hostRAMTotal"
|
||||
| "hostReady"
|
||||
| "hostRuntime"
|
||||
| "hostWHPX"
|
||||
| "importRuntime"
|
||||
| "installersAvailable"
|
||||
| "installersCreateVM"
|
||||
| "installersDelete"
|
||||
| "installersDeleteConfirm"
|
||||
| "installersDownload"
|
||||
| "installersDownloaded"
|
||||
| "installersEmpty"
|
||||
| "installersHint"
|
||||
| "installersKindOffline"
|
||||
| "installersKindOnline"
|
||||
| "installersLatest"
|
||||
| "installersNoSpace"
|
||||
| "installersOlder"
|
||||
| "installersPartial"
|
||||
| "installersResume"
|
||||
| "installersRetry"
|
||||
| "installersTitle"
|
||||
| "issuesCount"
|
||||
| "jumpLatest"
|
||||
| "kernelIrqchipAuto"
|
||||
| "kernelIrqchipLabel"
|
||||
| "kernelIrqchipOff"
|
||||
| "kernelIrqchipOn"
|
||||
| "language"
|
||||
| "languageSub"
|
||||
| "localeAuto"
|
||||
| "localeAutoDetail"
|
||||
| "logActivity"
|
||||
| "logButton"
|
||||
| "logCopy"
|
||||
| "logErrorsOnly"
|
||||
| "logLevel"
|
||||
| "logLevelCustom"
|
||||
| "logLevelDesc"
|
||||
| "logQemu"
|
||||
| "logSearchPlaceholder"
|
||||
| "logSerial"
|
||||
| "logsEmpty"
|
||||
| "macos.appsUtilitiesTerminal"
|
||||
| "macos.diskUtility"
|
||||
| "macos.erase"
|
||||
| "macos.finder"
|
||||
| "macos.guidPartitionMap"
|
||||
| "macos.otherSignInSetUpLater"
|
||||
| "macos.recovery"
|
||||
| "macos.reinstallMacOS"
|
||||
| "macos.setupAssistant"
|
||||
| "macos.showAllDevices"
|
||||
| "macos.utilitiesTerminal"
|
||||
| "macos.volume"
|
||||
| "macosVersion"
|
||||
| "maximize"
|
||||
| "memCommitHint"
|
||||
| "memOverHint"
|
||||
| "memRecHint"
|
||||
| "menuBar"
|
||||
| "menuHelp"
|
||||
| "menuVM"
|
||||
| "menuView"
|
||||
| "minimize"
|
||||
| "minimizeToTray"
|
||||
| "minimizeToTraySub"
|
||||
| "more"
|
||||
| "multiDisplayHint"
|
||||
| "navHasIssue"
|
||||
| "netOff"
|
||||
| "netShared"
|
||||
| "networkDesc"
|
||||
| "networkOfflineHint"
|
||||
| "networkTitle"
|
||||
| "newVM"
|
||||
| "newVMEllipsis"
|
||||
| "next"
|
||||
| "noChanges"
|
||||
| "noRuntimeAlert"
|
||||
| "off"
|
||||
| "offlineCached"
|
||||
| "offlineHint"
|
||||
| "offlineListFailed"
|
||||
| "offlineListFailedDetail"
|
||||
| "offlineLoading"
|
||||
| "offlineSpaceWarn"
|
||||
| "on"
|
||||
| "onlineRecoveryConfirm"
|
||||
| "onlineRecoveryDesc"
|
||||
| "onlineRecoveryTitle"
|
||||
| "openFolder"
|
||||
| "openSharedFolder"
|
||||
| "openShort"
|
||||
| "opencore"
|
||||
| "optAuto"
|
||||
| "optAvailable"
|
||||
| "optExperimental"
|
||||
| "optKernelIrqchipExp"
|
||||
| "optKernelIrqchipNestedErr"
|
||||
| "optKernelIrqchipRec"
|
||||
| "optKernelIrqchipUnavailable"
|
||||
| "optKernelIrqchipWin10NoPatch"
|
||||
| "optPCoreSub"
|
||||
| "optPCoreUnavailable"
|
||||
| "optRecommended"
|
||||
| "optSchedBackground"
|
||||
| "optSchedNowBackground"
|
||||
| "optSchedNowPrograms"
|
||||
| "optSchedOpen"
|
||||
| "optSchedPrograms"
|
||||
| "optSchedSub"
|
||||
| "optSchedTitle"
|
||||
| "optUnavailable"
|
||||
| "panelLoadFailed"
|
||||
| "pauseDownload"
|
||||
| "pendingChanges"
|
||||
| "pendingRestartHint"
|
||||
| "pendingTitle"
|
||||
| "pickRecoveryTitle"
|
||||
| "platformReadonly"
|
||||
| "pluginAccentSeed"
|
||||
| "pluginActiveCount"
|
||||
| "pluginActiveTheme"
|
||||
| "pluginAlwaysOn"
|
||||
| "pluginApproveCheckbox"
|
||||
| "pluginApproveConfirm"
|
||||
| "pluginApproveL3Warn"
|
||||
| "pluginApproveTitle"
|
||||
| "pluginBuiltinSection"
|
||||
| "pluginColorSchemes"
|
||||
| "pluginColorSchemesHint"
|
||||
| "pluginDeleteScheme"
|
||||
| "pluginDone"
|
||||
| "pluginEntryPath"
|
||||
| "pluginExternalSection"
|
||||
| "pluginFailDeleteScheme"
|
||||
| "pluginFailEnable"
|
||||
| "pluginFailImport"
|
||||
| "pluginFailLinkDev"
|
||||
| "pluginFailLoad"
|
||||
| "pluginFailLoadSettings"
|
||||
| "pluginFailReadLog"
|
||||
| "pluginFailRemove"
|
||||
| "pluginFailSaveScheme"
|
||||
| "pluginFailSaveSettings"
|
||||
| "pluginFailSwitchTheme"
|
||||
| "pluginFailToggle"
|
||||
| "pluginGlobalSettings"
|
||||
| "pluginHighRiskNotice"
|
||||
| "pluginImportBtn"
|
||||
| "pluginImportTitle"
|
||||
| "pluginInUse"
|
||||
| "pluginLinkDevBtn"
|
||||
| "pluginLinkDevTitle"
|
||||
| "pluginLogEmpty"
|
||||
| "pluginLogTitle"
|
||||
| "pluginNewScheme"
|
||||
| "pluginPanelsSection"
|
||||
| "pluginPermCount"
|
||||
| "pluginPermissionsLabel"
|
||||
| "pluginPublisherLicense"
|
||||
| "pluginRemove"
|
||||
| "pluginRequestedPerms"
|
||||
| "pluginSafeModeShort"
|
||||
| "pluginSchemeDefault"
|
||||
| "pluginSchemeModalTitle"
|
||||
| "pluginSchemeName"
|
||||
| "pluginSchemePlaceholder"
|
||||
| "pluginSearchEmpty"
|
||||
| "pluginSearchPlaceholder"
|
||||
| "pluginSettings"
|
||||
| "pluginStateDegraded"
|
||||
| "pluginStateFailed"
|
||||
| "pluginStatePending"
|
||||
| "pluginSurfaceSeed"
|
||||
| "pluginThemeEmptyHint"
|
||||
| "pluginThemeHint"
|
||||
| "pluginThemePackLabel"
|
||||
| "pluginThemeSafeModeHint"
|
||||
| "pluginThemeSection"
|
||||
| "pluginTrustCommunity"
|
||||
| "pluginTrustDev"
|
||||
| "pluginTrustOfficial"
|
||||
| "pluginTrustVerified"
|
||||
| "pluginViewLog"
|
||||
| "recommendedBadge"
|
||||
| "refresh"
|
||||
| "resCustom"
|
||||
| "resCustomSub"
|
||||
| "resFullscreen"
|
||||
| "resInvalid"
|
||||
| "resLooksLike"
|
||||
| "resetAll"
|
||||
| "resetField"
|
||||
| "resizeLogPanel"
|
||||
| "resolution"
|
||||
| "restart"
|
||||
| "restartToApply"
|
||||
| "runtimeAlpha"
|
||||
| "runtimeAlphaHint"
|
||||
| "runtimeChannel_alpha"
|
||||
| "runtimeChannel_stable"
|
||||
| "runtimeCurrent"
|
||||
| "runtimeDelete"
|
||||
| "runtimeDeleteConfirm"
|
||||
| "runtimeDeleted"
|
||||
| "runtimeInstall"
|
||||
| "runtimeLatest"
|
||||
| "runtimeLookupFailed"
|
||||
| "runtimeLookupRateLimit"
|
||||
| "runtimeNewer"
|
||||
| "runtimeNoneOnChannel"
|
||||
| "runtimeOnline"
|
||||
| "runtimeRetry"
|
||||
| "runtimeUpToDate"
|
||||
| "runtimeUpdate"
|
||||
| "safeModeBanner"
|
||||
| "safeModeManagePlugins"
|
||||
| "save"
|
||||
| "secondsUnit"
|
||||
| "sendText"
|
||||
| "sendTextConfirm"
|
||||
| "sendTextDesc"
|
||||
| "sendTextDescNoGT"
|
||||
| "sendTextPlaceholder"
|
||||
| "sendTextTitle"
|
||||
| "settings"
|
||||
| "settingsAbout"
|
||||
| "settingsAppearance"
|
||||
| "settingsEllipsis"
|
||||
| "settingsGeneral"
|
||||
| "settingsTitle"
|
||||
| "setupCheck"
|
||||
| "setupContinue"
|
||||
| "setupDesc"
|
||||
| "setupDone"
|
||||
| "setupExternal"
|
||||
| "setupFree"
|
||||
| "setupGPU"
|
||||
| "setupImport"
|
||||
| "setupLater"
|
||||
| "setupNoGPU"
|
||||
| "setupOther"
|
||||
| "setupRecMem"
|
||||
| "setupRecommended"
|
||||
| "setupReuse"
|
||||
| "setupRuntimeDesc"
|
||||
| "setupRuntimeTitle"
|
||||
| "setupSystem"
|
||||
| "setupTitle"
|
||||
| "setupWarnExternal"
|
||||
| "setupWarnSpace"
|
||||
| "setupWarnSystem"
|
||||
| "sharedFolder"
|
||||
| "shortcutBarFullscreen"
|
||||
| "shortcutBarRelease"
|
||||
| "showInstallGuide"
|
||||
| "showSidebar"
|
||||
| "showWindow"
|
||||
| "sidebarHost"
|
||||
| "sidebarInstallers"
|
||||
| "sidebarItemAria"
|
||||
| "sidebarLabel"
|
||||
| "sidebarPlugins"
|
||||
| "sidebarSettings"
|
||||
| "sidebarSystem"
|
||||
| "sidebarVMs"
|
||||
| "snapshotCreate"
|
||||
| "snapshotDelete"
|
||||
| "snapshotEmpty"
|
||||
| "snapshotHint"
|
||||
| "snapshotNamePlaceholder"
|
||||
| "snapshotRestore"
|
||||
| "snapshotRestoreDesc"
|
||||
| "snapshotRestoreTitle"
|
||||
| "snapshotStopFirst"
|
||||
| "snapshotsTitle"
|
||||
| "softwareGraphics"
|
||||
| "sourceDisk"
|
||||
| "sourceInstaller"
|
||||
| "specCPULiveTip"
|
||||
| "specCPUTip"
|
||||
| "specDiskTip"
|
||||
| "specDiskUsage"
|
||||
| "specGraphicsTip"
|
||||
| "specLang"
|
||||
| "specLangTip"
|
||||
| "specLangTipDetail"
|
||||
| "specMemLiveTip"
|
||||
| "specMemTip"
|
||||
| "specNetOffTip"
|
||||
| "specNetSSHTip"
|
||||
| "specNetTip"
|
||||
| "srcAppleSub"
|
||||
| "srcAppleTitle"
|
||||
| "srcDiskSub"
|
||||
| "srcDiskTitle"
|
||||
| "srcInstallerSub"
|
||||
| "srcInstallerTitle"
|
||||
| "srcOfflineSub"
|
||||
| "srcOfflineTitle"
|
||||
| "sshForward"
|
||||
| "sshMore"
|
||||
| "sshNeedsNetwork"
|
||||
| "sshOffDesc"
|
||||
| "sshOpenTerminal"
|
||||
| "sshOpenVSCode"
|
||||
| "sshPort"
|
||||
| "sshSetUser"
|
||||
| "sshUserDesc"
|
||||
| "sshUserPlaceholder"
|
||||
| "sshUserTitle"
|
||||
| "sshWriteConfig"
|
||||
| "start"
|
||||
| "startAfterCreate"
|
||||
| "starting"
|
||||
| "state_broken"
|
||||
| "state_creating"
|
||||
| "state_driver_unavailable"
|
||||
| "state_running"
|
||||
| "state_starting"
|
||||
| "state_stopped"
|
||||
| "state_stopping"
|
||||
| "statsCPU"
|
||||
| "statsDisk"
|
||||
| "statsDiskSub"
|
||||
| "statsMemory"
|
||||
| "statsUptime"
|
||||
| "step1"
|
||||
| "step2"
|
||||
| "step3"
|
||||
| "step4"
|
||||
| "step5"
|
||||
| "stop"
|
||||
| "stopBeforeDiskOp"
|
||||
| "stopTimeout"
|
||||
| "stopTimeoutHint"
|
||||
| "storageBreakdownTitle"
|
||||
| "storageInstallers"
|
||||
| "storageRuntimes"
|
||||
| "storageVMs"
|
||||
| "summaryAppleSource"
|
||||
| "summaryDefaultDir"
|
||||
| "summaryDiskGrow"
|
||||
| "summaryDiskSource"
|
||||
| "summaryEdit"
|
||||
| "summaryInstallerSource"
|
||||
| "summaryLogs"
|
||||
| "summaryOfflineSource"
|
||||
| "summaryOn"
|
||||
| "summarySSH"
|
||||
| "summarySSHPort"
|
||||
| "summarySource"
|
||||
| "taskAppUpdate"
|
||||
| "taskCreate"
|
||||
| "taskDownload"
|
||||
| "taskRecoveryDownload"
|
||||
| "taskRuntime"
|
||||
| "tasksRunning"
|
||||
| "techInfo"
|
||||
| "themeDark"
|
||||
| "themeLabel"
|
||||
| "themeLight"
|
||||
| "themePluginDarkDisabled"
|
||||
| "themePluginLightDisabled"
|
||||
| "themeSwitchDark"
|
||||
| "themeSwitchLight"
|
||||
| "themeSystem"
|
||||
| "toastAffinityApplied"
|
||||
| "toastAffinitySaved"
|
||||
| "toastBorderlessNextStart"
|
||||
| "toastBorderlessUpdated"
|
||||
| "toastCloned"
|
||||
| "toastCopied"
|
||||
| "toastCreated"
|
||||
| "toastDeleted"
|
||||
| "toastDiagExported"
|
||||
| "toastDownloadPaused"
|
||||
| "toastEjected"
|
||||
| "toastEnterRecovery"
|
||||
| "toastEnterRecoveryNextStart"
|
||||
| "toastExitRecoveryNextStart"
|
||||
| "toastFileDelivered"
|
||||
| "toastFilesDelivered"
|
||||
| "toastGuestToolsAttached"
|
||||
| "toastGuestToolsAttachedNextStart"
|
||||
| "toastGuestToolsDetached"
|
||||
| "toastGuestToolsDetachedNextStart"
|
||||
| "toastInstallFinished"
|
||||
| "toastInstallerAttached"
|
||||
| "toastInstallerAttachedNextStart"
|
||||
| "toastInstallerReady"
|
||||
| "toastNVMeNextStart"
|
||||
| "toastNVMeReady"
|
||||
| "toastOnlineRecoveryAttached"
|
||||
| "toastOnlineRecoveryStarted"
|
||||
| "toastPreventSleepOff"
|
||||
| "toastPreventSleepOn"
|
||||
| "toastRuntimeReady"
|
||||
| "toastSSHConfigWritten"
|
||||
| "toastSSHUserSaved"
|
||||
| "toastSaved"
|
||||
| "toastSavedNextStart"
|
||||
| "toastScreenshotCopied"
|
||||
| "toastSnapshotCreated"
|
||||
| "toastSnapshotDeleted"
|
||||
| "toastSnapshotRestored"
|
||||
| "toastStopped"
|
||||
| "toastTyped"
|
||||
| "typeClipboard"
|
||||
| "typeIntoVM"
|
||||
| "typeUntypeable"
|
||||
| "updateCancel"
|
||||
| "updateCapsuleAvailable"
|
||||
| "updateCapsuleDownloading"
|
||||
| "updateCapsuleDownloadingPct"
|
||||
| "updateCapsuleFailed"
|
||||
| "updateCapsuleOpen"
|
||||
| "updateCapsuleReady"
|
||||
| "updateConfirmBody"
|
||||
| "updateConfirmTitle"
|
||||
| "updateConfirmWin10"
|
||||
| "updateDoneToast"
|
||||
| "updateDownload"
|
||||
| "updateDownloadInstall"
|
||||
| "updateDownloadingSub"
|
||||
| "updateFailed"
|
||||
| "updateFailedSub"
|
||||
| "updateLater"
|
||||
| "updateReadySub"
|
||||
| "updateReleaseNotes"
|
||||
| "updateRestart"
|
||||
| "updateRetry"
|
||||
| "upgradeToNVMe"
|
||||
| "uptimeHoursMinutes"
|
||||
| "uptimeMinutesSeconds"
|
||||
| "uptimeSeconds"
|
||||
| "useDefault"
|
||||
| "validationChecking"
|
||||
| "validationPassed"
|
||||
| "vcpus"
|
||||
| "viewLogs"
|
||||
| "vmDir"
|
||||
| "vmName"
|
||||
| "welcomeCheckHost"
|
||||
| "welcomeSub"
|
||||
| "welcomeTitle"
|
||||
| "whpxMissing"
|
||||
| "whpxMissingShort"
|
||||
| "whpxNoHv"
|
||||
| "whpxNoHvShort"
|
||||
| "whpxReady"
|
||||
| "whpxTitle"
|
||||
| "whpxUnsupported"
|
||||
| "whpxUnsupportedShort"
|
||||
| "wizChooseFile"
|
||||
| "wizNoFile"
|
||||
| "wizOptions"
|
||||
| "wizardBasics"
|
||||
| "wizardDriverGroup"
|
||||
| "wizardDriverType"
|
||||
| "wizardTitle";
|
||||
@@ -0,0 +1,12 @@
|
||||
import { coreEn, coreZh } from './domains/core.gen'
|
||||
import { vmEn, vmZh } from './domains/vm.gen'
|
||||
|
||||
export const builtinDict: Record<'zh-CN' | 'en-US', Record<string, string>> = {
|
||||
'zh-CN': { ...coreZh, ...vmZh },
|
||||
'en-US': { ...coreEn, ...vmEn },
|
||||
}
|
||||
|
||||
export function registerBuiltinDomain(zh: Record<string, string>, en: Record<string, string>): void {
|
||||
Object.assign(builtinDict['zh-CN'], zh)
|
||||
Object.assign(builtinDict['en-US'], en)
|
||||
}
|
||||
+51
-31
@@ -1,6 +1,12 @@
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { formatLocaleNumber } from '../i18n/icu'
|
||||
import { DisplayPreset, GPUInfo, HostReport, Locale, VMDetail } from '../types'
|
||||
|
||||
function currentDocLocale(): string {
|
||||
if (typeof document === 'undefined') return 'en-US'
|
||||
return document.documentElement.dataset.locale || document.documentElement.lang || 'en-US'
|
||||
}
|
||||
|
||||
// Human-readable values for the main view (docs/design-guidelines.md §7.1).
|
||||
// Raw values stay available under "Technical details".
|
||||
|
||||
@@ -45,12 +51,14 @@ export function parseMemoryGB(raw: string | undefined): number | null {
|
||||
return unit === 'T' ? n * 1024 : unit === 'G' ? n : unit === 'M' ? n / 1024 : n / 1024 / 1024
|
||||
}
|
||||
|
||||
/** "16G" / "16384M" / "16GiB" → "16 GB". Unknown shapes pass through. */
|
||||
export function formatMemory(raw: string): string {
|
||||
/** "16G" / "16384M" / "16GiB" → "16 GB" (or "16,5 GB" in comma-decimal locales). */
|
||||
export function formatMemory(raw: string, locale?: Locale): string {
|
||||
const gb = parseMemoryGB(raw)
|
||||
if (gb === null) return raw
|
||||
const rounded = gb >= 10 ? Math.round(gb) : Math.round(gb * 10) / 10
|
||||
return `${rounded} GB`
|
||||
const loc = locale ?? currentDocLocale()
|
||||
const precision = Number.isInteger(rounded) ? 0 : 1
|
||||
return `${formatLocaleNumber(loc, rounded, precision)} GB`
|
||||
}
|
||||
|
||||
export function controllerLabel(raw: string): string {
|
||||
@@ -159,7 +167,7 @@ export function sshCommand(port: number): string {
|
||||
return `ssh -p ${port} 127.0.0.1`
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number): string {
|
||||
export function formatBytes(bytes: number, locale?: Locale): string {
|
||||
if (!bytes || bytes <= 0) return '0 B'
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
let v = bytes
|
||||
@@ -169,20 +177,22 @@ export function formatBytes(bytes: number): string {
|
||||
i++
|
||||
}
|
||||
const digits = v >= 100 || i === 0 ? 0 : v >= 10 ? 1 : 2
|
||||
return `${v.toFixed(digits)} ${units[i]}`
|
||||
const loc = locale ?? currentDocLocale()
|
||||
return `${formatLocaleNumber(loc, v, digits)} ${units[i]}`
|
||||
}
|
||||
|
||||
/** Compact "54 / 128 GB" when both are gigabytes, falling back to full units. */
|
||||
export function formatDiskUsage(actual: number, virtual: number): string {
|
||||
export function formatDiskUsage(actual: number, virtual: number, locale?: Locale): string {
|
||||
const GiB = 1024 ** 3
|
||||
const loc = locale ?? currentDocLocale()
|
||||
if (actual >= GiB && virtual >= GiB && virtual < 1024 * GiB) {
|
||||
const a = actual / GiB
|
||||
const v = virtual / GiB
|
||||
const aStr = a >= 10 ? Math.round(a).toString() : a.toFixed(1)
|
||||
const vStr = Math.round(v).toString()
|
||||
const aStr = a >= 10 ? formatLocaleNumber(loc, Math.round(a), 0) : formatLocaleNumber(loc, a, 1)
|
||||
const vStr = formatLocaleNumber(loc, Math.round(v), 0)
|
||||
return `${aStr} / ${vStr} GB`
|
||||
}
|
||||
return `${formatBytes(actual)} / ${formatBytes(virtual)}`
|
||||
return `${formatBytes(actual, loc)} / ${formatBytes(virtual, loc)}`
|
||||
}
|
||||
|
||||
export function formatUptime(sec: number, locale: Locale): string {
|
||||
@@ -190,14 +200,9 @@ export function formatUptime(sec: number, locale: Locale): string {
|
||||
const h = Math.floor(sec / 3600)
|
||||
const m = Math.floor((sec % 3600) / 60)
|
||||
const s = sec % 60
|
||||
if (locale.toLowerCase().startsWith('zh')) {
|
||||
if (h > 0) return `${h}小时 ${m}分`
|
||||
if (m > 0) return `${m}分 ${s}秒`
|
||||
return `${s}秒`
|
||||
}
|
||||
if (h > 0) return `${h}h ${m}m`
|
||||
if (m > 0) return `${m}m ${s}s`
|
||||
return `${s}s`
|
||||
if (h > 0) return t(locale, 'uptimeHoursMinutes', { h, m })
|
||||
if (m > 0) return t(locale, 'uptimeMinutesSeconds', { m, s })
|
||||
return t(locale, 'uptimeSeconds', { s })
|
||||
}
|
||||
|
||||
// Used only when the host report has no presets: with nothing known about the
|
||||
@@ -250,19 +255,27 @@ export function recommendedResolution(host: HostReport): string {
|
||||
|
||||
export interface GuestLangPreset {
|
||||
value: string
|
||||
zh: string
|
||||
en: string
|
||||
labelKey: I18nKey
|
||||
detailKey?: I18nKey
|
||||
}
|
||||
|
||||
export const GUEST_LANG_PRESETS: GuestLangPreset[] = [
|
||||
{ value: 'zh-Hans:0', zh: '简体中文(美式键盘,推荐)', en: 'Simplified Chinese (US Keyboard)' },
|
||||
{ value: 'zh-Hans:252', zh: '简体中文(拼音键盘)', en: 'Simplified Chinese (Pinyin)' },
|
||||
{ value: 'zh-Hant:0', zh: '繁體中文(美式键盘)', en: 'Traditional Chinese (US Keyboard)' },
|
||||
{ value: 'en-US:0', zh: 'English (US)', en: 'English (US)' },
|
||||
{ value: 'ja-JP:0', zh: '日本語(美式键盘)', en: 'Japanese (US Keyboard)' },
|
||||
{ value: 'ko-KR:0', zh: '한국어(美式键盘)', en: 'Korean (US Keyboard)' },
|
||||
{ value: 'zh-Hans:0', labelKey: 'guestLangZhHansUS', detailKey: 'guestKbdUSRecommended' },
|
||||
{ value: 'zh-Hans:252', labelKey: 'guestLangZhHansUS', detailKey: 'guestKbdPinyin' },
|
||||
{ value: 'zh-Hant:0', labelKey: 'guestLangZhHantUS', detailKey: 'guestKbdUS' },
|
||||
{ value: 'en-US:0', labelKey: 'guestLangEnUS' },
|
||||
{ value: 'ja-JP:0', labelKey: 'guestLangJaJP', detailKey: 'guestKbdUS' },
|
||||
{ value: 'ko-KR:0', labelKey: 'guestLangKoKR', detailKey: 'guestKbdUS' },
|
||||
]
|
||||
|
||||
export function guestLangOptions(locale: Locale): Array<{ value: string; label: string; detail?: string }> {
|
||||
return GUEST_LANG_PRESETS.map((p) => ({
|
||||
value: p.value,
|
||||
label: t(locale, p.labelKey),
|
||||
detail: p.detailKey ? t(locale, p.detailKey) : undefined,
|
||||
}))
|
||||
}
|
||||
|
||||
export function defaultGuestLang(locale: Locale): string {
|
||||
const l = locale.toLowerCase()
|
||||
if (l === 'zh-tw' || l === 'zh-hk' || l === 'zh-mo' || l.startsWith('zh-hant')) return 'zh-Hant:0'
|
||||
@@ -272,11 +285,18 @@ export function defaultGuestLang(locale: Locale): string {
|
||||
return 'en-US:0'
|
||||
}
|
||||
|
||||
export function resolveGuestLang(locale: Locale, code: string | undefined): { label: string; detail?: string } {
|
||||
const target = code || defaultGuestLang(locale)
|
||||
const hit = GUEST_LANG_PRESETS.find((p) => p.value === target)
|
||||
if (!hit) return { label: target }
|
||||
const label = t(locale, hit.labelKey)
|
||||
const detail = hit.detailKey ? t(locale, hit.detailKey) : undefined
|
||||
return { label, detail }
|
||||
}
|
||||
|
||||
export function guestLangLabel(locale: Locale, code: string | undefined): string {
|
||||
if (!code) return defaultGuestLang(locale)
|
||||
const hit = GUEST_LANG_PRESETS.find((p) => p.value === code)
|
||||
if (hit) return locale.toLowerCase().startsWith('zh') ? hit.zh : hit.en
|
||||
return code
|
||||
const { label, detail } = resolveGuestLang(locale, code)
|
||||
return detail ? `${label} (${detail})` : label
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -296,10 +316,10 @@ export function splitLangLabel(value: string, text: string): { value: string; la
|
||||
export function pendingChangeText(locale: Locale, p: { field: string; from: string; to: string }, host: HostReport): string {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const bool = (v: string) => tr(v === 'true' ? 'on' : 'off')
|
||||
const lang = (v: string) => splitLangLabel('', guestLangLabel(locale, v)).label
|
||||
const lang = (v: string) => resolveGuestLang(locale, v).label
|
||||
const fields: Record<string, { label: I18nKey; fmt: (v: string) => string }> = {
|
||||
cpus: { label: 'factCPU', fmt: (v) => tr('cores', { n: v }) },
|
||||
memory: { label: 'factMemory', fmt: formatMemory },
|
||||
memory: { label: 'factMemory', fmt: (v) => formatMemory(v, locale) },
|
||||
resolution: { label: 'resolution', fmt: resolutionLabel },
|
||||
gpu: { label: 'factGraphics', fmt: (v) => gpuLabel(locale, v, host) },
|
||||
displays: { label: 'displays', fmt: (v) => v },
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { Locale, Optimization, OptimizationStatus } from '../types'
|
||||
|
||||
|
||||
@@ -34,6 +34,8 @@ interface ThemeTokenCache {
|
||||
export interface UIStateSnapshot {
|
||||
appearance: 'light' | 'dark'
|
||||
motion: 'full' | 'reduced'
|
||||
locale: string
|
||||
dir: 'ltr' | 'rtl'
|
||||
view: string
|
||||
vmName: string
|
||||
vmState: string
|
||||
@@ -51,6 +53,7 @@ export interface ThemeSDKHostActions {
|
||||
}
|
||||
|
||||
let activeUIScriptCleanup: (() => void) | null = null
|
||||
let activeUIScriptNotifier: ((snap: UIStateSnapshot) => void) | null = null
|
||||
let activeUIScriptURL = ''
|
||||
let applyGeneration = 0
|
||||
|
||||
@@ -264,6 +267,38 @@ function clamp01(x: number): number {
|
||||
return Math.max(0, Math.min(1, x))
|
||||
}
|
||||
|
||||
function srgbChannelToLinear(c: number): number {
|
||||
return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)
|
||||
}
|
||||
|
||||
/** Computes WCAG 2.1 relative luminance (0..1) for a #RGB or #RRGGBB hex string. */
|
||||
function hexRelativeLuminance(hex: string): number | null {
|
||||
const clean = hex.trim().replace(/^#/, '')
|
||||
let r = 0, g = 0, b = 0
|
||||
if (clean.length === 3) {
|
||||
r = parseInt(clean[0] + clean[0], 16) / 255
|
||||
g = parseInt(clean[1] + clean[1], 16) / 255
|
||||
b = parseInt(clean[2] + clean[2], 16) / 255
|
||||
} else if (clean.length === 6) {
|
||||
r = parseInt(clean.slice(0, 2), 16) / 255
|
||||
g = parseInt(clean.slice(2, 4), 16) / 255
|
||||
b = parseInt(clean.slice(4, 6), 16) / 255
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) return null
|
||||
return 0.2126 * srgbChannelToLinear(r) + 0.7152 * srgbChannelToLinear(g) + 0.0722 * srgbChannelToLinear(b)
|
||||
}
|
||||
|
||||
function pickHighContrastAccentText(hex: string): string {
|
||||
const lum = hexRelativeLuminance(hex)
|
||||
if (lum === null) return '#ffffff'
|
||||
const whiteContrast = 1.05 / (lum + 0.05)
|
||||
const darkInkLum = 0.0123 // #1d1d1f
|
||||
const darkContrast = (lum + 0.05) / (darkInkLum + 0.05)
|
||||
return darkContrast > whiteContrast ? '#1d1d1f' : '#ffffff'
|
||||
}
|
||||
|
||||
/** Derives CSS variable values from seed colors using declarative rules (§5.1). */
|
||||
export function deriveTokensFromSeeds(
|
||||
seeds: Record<string, string>,
|
||||
@@ -276,6 +311,7 @@ export function deriveTokensFromSeeds(
|
||||
out['--accent'] = seeds.accent
|
||||
if (hsl) {
|
||||
const [h, s, l] = hsl
|
||||
out['--accent-text'] = pickHighContrastAccentText(seeds.accent)
|
||||
out['--accent-hover'] = `hsl(${Math.round(h)} ${Math.round(s * 100)}% ${Math.round(clamp01(l + (appearance === 'dark' ? 0.06 : -0.06)) * 100)}%)`
|
||||
out['--accent-soft'] = `hsla(${Math.round(h)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%, ${appearance === 'dark' ? 0.2 : 0.12})`
|
||||
out['--accent-soft-text'] = `hsl(${Math.round(h)} ${Math.round(s * 100)}% ${Math.round(clamp01(appearance === 'dark' ? Math.max(l, 0.66) : Math.min(l, 0.42)) * 100)}%)`
|
||||
@@ -454,14 +490,18 @@ export async function applyActiveTheme(
|
||||
// 5. Tier 3: lazy-load UI SDK ONLY when an approved interactive theme script is present (§8.1).
|
||||
if (nextScriptURL && nextScriptURL !== activeUIScriptURL) {
|
||||
try {
|
||||
const { mountInteractiveThemeScript } = await import('./uiSdk')
|
||||
const { mountInteractiveThemeScript, notifyThemeSDKState } = await import('./uiSdk')
|
||||
if (gen !== applyGeneration) return
|
||||
const cleanup = await mountInteractiveThemeScript(nextScriptURL, getState, actions)
|
||||
if (gen !== applyGeneration) {
|
||||
try { cleanup() } catch {}
|
||||
return
|
||||
}
|
||||
activeUIScriptCleanup = cleanup
|
||||
activeUIScriptCleanup = () => {
|
||||
activeUIScriptNotifier = null
|
||||
cleanup()
|
||||
}
|
||||
activeUIScriptNotifier = notifyThemeSDKState
|
||||
activeUIScriptURL = nextScriptURL
|
||||
} catch {
|
||||
if (gen === applyGeneration) {
|
||||
@@ -473,6 +513,67 @@ export async function applyActiveTheme(
|
||||
}
|
||||
}
|
||||
|
||||
const LOCALE_FONT_EL_ID = 'rg-active-locale-fonts'
|
||||
const RE_SAFE_FONT_URL = /^\/plugin-assets\/[a-f0-9]+\/[a-z0-9][a-z0-9._-]*\/[a-zA-Z0-9._/@ -]+\.woff2$/i
|
||||
const RE_SAFE_FONT_FAMILY = /^[\p{L}\p{N} _-]{1,80}$/u
|
||||
|
||||
/**
|
||||
* Injects optional bundled `.woff2` WebFonts declared by the active language pack
|
||||
* into `--font-locale-pack` (scoped strictly inside `@layer theme`, zero cost when empty).
|
||||
*/
|
||||
export function applyActiveLocaleFonts(
|
||||
fonts: Array<{ family: string; url: string; weight?: string; style?: string; unicodeRange?: string }> | undefined,
|
||||
): void {
|
||||
const existing = document.getElementById(LOCALE_FONT_EL_ID)
|
||||
if (!fonts || fonts.length === 0) {
|
||||
existing?.remove()
|
||||
return
|
||||
}
|
||||
const rules: string[] = []
|
||||
const families: string[] = []
|
||||
for (const f of fonts) {
|
||||
const fam = (f.family || '').trim()
|
||||
if (!RE_SAFE_FONT_FAMILY.test(fam) || fam.toLowerCase().includes('</style')) continue
|
||||
if (!f.url || !RE_SAFE_FONT_URL.test(f.url)) continue
|
||||
const weight = f.weight && RE_FONT_WEIGHT.test(f.weight) ? f.weight : '400'
|
||||
const style = f.style && RE_FONT_STYLE.test(f.style) ? f.style : 'normal'
|
||||
const ur = f.unicodeRange && RE_UNICODE_RANGE.test(f.unicodeRange) ? `unicode-range: ${f.unicodeRange};` : ''
|
||||
rules.push(
|
||||
`@font-face { font-family: "${fam}"; src: url("${f.url}") format("woff2"); font-weight: ${weight}; font-style: ${style}; font-display: swap; ${ur} }`,
|
||||
)
|
||||
if (!families.includes(`"${fam}"`)) {
|
||||
families.push(`"${fam}"`)
|
||||
}
|
||||
}
|
||||
if (rules.length === 0) {
|
||||
existing?.remove()
|
||||
return
|
||||
}
|
||||
let styleEl = existing as HTMLStyleElement | null
|
||||
if (!styleEl) {
|
||||
styleEl = document.createElement('style')
|
||||
styleEl.id = LOCALE_FONT_EL_ID
|
||||
document.head.appendChild(styleEl)
|
||||
}
|
||||
styleEl.textContent = `@layer theme {\n:root {\n --font-locale-pack: ${families.join(', ')}, ;\n}\n${rules.join('\n')}\n}`
|
||||
}
|
||||
|
||||
/** Tears down injected theme/locale style nodes and active UI scripts on unmount. */
|
||||
export function disposeActiveThemeAndLocaleFonts(): void {
|
||||
if (activeUIScriptCleanup) {
|
||||
try { activeUIScriptCleanup() } catch {}
|
||||
activeUIScriptCleanup = null
|
||||
activeUIScriptNotifier = null
|
||||
activeUIScriptURL = ''
|
||||
}
|
||||
clearDynamicThemeStyles()
|
||||
document.getElementById(LOCALE_FONT_EL_ID)?.remove()
|
||||
}
|
||||
|
||||
export function notifyInteractiveThemeState(snap: UIStateSnapshot): void {
|
||||
activeUIScriptNotifier?.(snap)
|
||||
}
|
||||
|
||||
/** Plays a theme-configured sound for an event if present (fail-silent). */
|
||||
export function playThemeSound(payload: ActiveThemePayload | null, eventName: string): void {
|
||||
const file = payload?.theme?.sounds?.[eventName]
|
||||
|
||||
+190
-71
@@ -10,14 +10,22 @@
|
||||
html, body, #root {
|
||||
margin: 0; padding: 0; height: 100%; overflow: hidden;
|
||||
background: var(--surface-0); color: var(--text);
|
||||
font-family: var(--font-sans); font-size: var(--fs-14); font-weight: var(--fw-regular); line-height: 1.48;
|
||||
font-family: var(--font-sans); font-size: var(--fs-14); font-weight: var(--fw-regular); line-height: var(--body-lh, 1.48);
|
||||
font-optical-sizing: auto;
|
||||
font-feature-settings: "cv02", "cv03", "cv04";
|
||||
text-autospace: normal;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
text-rendering: optimizeLegibility;
|
||||
}
|
||||
|
||||
html:lang(ja) { line-break: strict; }
|
||||
html:lang(ko) { word-break: keep-all; }
|
||||
:is(:lang(zh), :lang(ja), :lang(ko)) :is(em, i) { font-style: normal; font-weight: var(--fw-medium); }
|
||||
:is(:lang(zh), :lang(ja), :lang(ko)) :is(.brand, .sidebar-head, .sidebar-section-label, .sidebar-brand-name, .about-hero-text h1) {
|
||||
letter-spacing: var(--heading-tracking, 0em);
|
||||
}
|
||||
|
||||
@media (pointer: fine) {
|
||||
html { overscroll-behavior: none; }
|
||||
}
|
||||
@@ -54,7 +62,7 @@ h1, h2, h3, p { margin: 0; }
|
||||
.titlebar {
|
||||
height: var(--titlebar-h); flex-shrink: 0; position: relative; z-index: 10;
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding-left: var(--sp-4);
|
||||
padding-inline-start: var(--sp-4);
|
||||
/* No backdrop blur: the bar is opaque, so blurring behind it showed nothing
|
||||
and still cost a GPU compositing layer (the GPU is shared with the VM). */
|
||||
background: var(--surface-chrome);
|
||||
@@ -96,9 +104,9 @@ h1, h2, h3, p { margin: 0; }
|
||||
color: var(--text-3); font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.menu-item[data-highlighted] .menu-shortcut { color: rgba(255, 255, 255, 0.78); }
|
||||
.menu-item.menu-item-check, .menu-indented .menu-item { position: relative; padding-left: 28px; }
|
||||
.menu-indented .menu-group-label { padding-left: 28px; }
|
||||
.menu-check { position: absolute; left: 9px; top: 50%; transform: translateY(-50%); display: grid; place-items: center; }
|
||||
.menu-item.menu-item-check, .menu-indented .menu-item { position: relative; padding-inline-start: 28px; }
|
||||
.menu-indented .menu-group-label { padding-inline-start: 28px; }
|
||||
.menu-check { position: absolute; inset-inline-start: 9px; top: 50%; transform: translateY(-50%); display: grid; place-items: center; }
|
||||
.menu-group-label { padding: 6px 10px 2px; font-size: 11.5px; font-weight: var(--fw-medium); color: var(--text-3); user-select: none; }
|
||||
.theme-toggle {
|
||||
width: 30px; height: 28px; margin-right: var(--sp-1);
|
||||
@@ -120,7 +128,8 @@ h1, h2, h3, p { margin: 0; }
|
||||
.win-btn.close:hover { background: #e81123; color: #fff; }
|
||||
.win-btn:focus-visible { border-radius: 0; }
|
||||
|
||||
.workspace { display: flex; flex: 1; min-height: 0; background: var(--surface-canvas); }
|
||||
.workspace { position: relative; display: flex; flex: 1; min-height: 0; background: var(--surface-canvas); }
|
||||
.sidebar-backdrop { display: none; }
|
||||
|
||||
/* ── Floating Tahoe Sidebar ────────────────────────────── */
|
||||
.sidebar-wrap {
|
||||
@@ -128,12 +137,12 @@ h1, h2, h3, p { margin: 0; }
|
||||
padding: 10px;
|
||||
display: flex; overflow: hidden;
|
||||
background: var(--surface-sidebar-rail);
|
||||
border-right: 1px solid var(--border);
|
||||
border-inline-end: 1px solid var(--border);
|
||||
transition: width var(--dur-modal) var(--ease-out), padding var(--dur-modal) var(--ease-out), opacity var(--dur) var(--ease-out), border-color var(--dur) var(--ease-out);
|
||||
}
|
||||
/* Hidden sidebar (Ctrl+B): slides shut; the card keeps its width so its
|
||||
contents don't reflow while the rail narrows. */
|
||||
.workspace.sidebar-hidden .sidebar-wrap { width: 0; padding-left: 0; padding-right: 0; opacity: 0; border-right-color: transparent; }
|
||||
.workspace.sidebar-hidden .sidebar-wrap { width: 0; padding-inline: 0; opacity: 0; border-inline-end-color: transparent; }
|
||||
.sidebar-wrap > .sidebar { min-width: calc(var(--sidebar-w) - 20px); }
|
||||
.sidebar {
|
||||
flex: 1; min-height: 0;
|
||||
@@ -180,30 +189,30 @@ h1, h2, h3, p { margin: 0; }
|
||||
.update-capsule.is-failed { background: var(--warn-soft); color: var(--warn-text); }
|
||||
.update-capsule-main {
|
||||
flex: 1; min-width: 0; display: flex; align-items: center; gap: 7px;
|
||||
padding: 0; border: 0; background: none; color: inherit; cursor: pointer; text-align: left;
|
||||
padding: 0; border: 0; background: none; color: inherit; cursor: pointer; text-align: start;
|
||||
}
|
||||
.update-capsule-icon {
|
||||
width: 22px; height: 22px; flex-shrink: 0; border-radius: 50%;
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
background: var(--accent); color: var(--accent-text);
|
||||
}
|
||||
.update-capsule.is-failed .update-capsule-icon { background: var(--warn-text); }
|
||||
.update-capsule.is-failed .update-capsule-icon { background: var(--status-busy); color: #1d1d1f; }
|
||||
.update-capsule-title {
|
||||
min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
font-size: 12px; font-weight: var(--fw-medium);
|
||||
font-size: var(--fs-12); font-weight: var(--fw-medium);
|
||||
}
|
||||
.update-capsule-btn {
|
||||
flex-shrink: 0; display: inline-flex; align-items: center; gap: 3px;
|
||||
height: 22px; padding: 0 9px; border: 0; border-radius: 999px;
|
||||
height: 24px; padding: 0 9px; border: 0; border-radius: 999px;
|
||||
background: var(--surface-1); color: inherit;
|
||||
font-size: 11.5px; font-weight: var(--fw-medium); cursor: pointer;
|
||||
font-size: var(--fs-12); font-weight: var(--fw-medium); cursor: pointer;
|
||||
transition: filter var(--dur) var(--ease-out), transform var(--dur) var(--ease-out);
|
||||
}
|
||||
.update-capsule-btn.is-primary { background: var(--accent); color: var(--accent-text); }
|
||||
.update-capsule-btn:hover { filter: brightness(1.06); }
|
||||
.update-capsule-btn:active { transform: scale(0.96); }
|
||||
.update-capsule-x {
|
||||
flex-shrink: 0; width: 22px; height: 22px; border: 0; border-radius: 50%;
|
||||
flex-shrink: 0; width: 24px; height: 24px; border: 0; border-radius: 50%;
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
background: none; color: inherit; opacity: 0.7; cursor: pointer;
|
||||
}
|
||||
@@ -219,24 +228,27 @@ h1, h2, h3, p { margin: 0; }
|
||||
.nav-vms { flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; }
|
||||
.nav-system { flex-shrink: 0; margin-top: 6px; padding-top: 8px; border-top: 1px solid var(--border); }
|
||||
.nav-dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; background: var(--accent); }
|
||||
.nav-item[aria-selected="true"] .nav-dot { background: var(--accent-text); }
|
||||
.nav-item[aria-selected="true"] .nav-dot,
|
||||
.nav-item[aria-current="page"] .nav-dot { background: var(--accent-text); }
|
||||
.nav-empty { padding: 8px 10px; font-size: var(--fs-12); color: var(--text-3); }
|
||||
.nav-item {
|
||||
width: 100%; height: 36px; padding: 0 10px;
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
border: none; border-radius: 9px; background: transparent; color: var(--text);
|
||||
text-align: left; cursor: pointer;
|
||||
text-align: start; cursor: pointer;
|
||||
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), box-shadow var(--dur) var(--ease-out), transform var(--dur-press) var(--ease-out);
|
||||
}
|
||||
.nav-item:hover { background: var(--surface-hover); }
|
||||
.nav-item:active { transform: scale(0.985); }
|
||||
.nav-item[aria-selected="true"] {
|
||||
.nav-item[aria-selected="true"],
|
||||
.nav-item[aria-current="page"] {
|
||||
background: var(--accent);
|
||||
color: var(--accent-text);
|
||||
font-weight: var(--fw-medium);
|
||||
box-shadow: 0 1px 2px rgba(0, 122, 255, 0.22), inset 0 1px 0 rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
.nav-item[aria-selected="true"] .nav-icon-badge {
|
||||
.nav-item[aria-selected="true"] .nav-icon-badge,
|
||||
.nav-item[aria-current="page"] .nav-icon-badge {
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
color: #ffffff;
|
||||
box-shadow: none;
|
||||
@@ -313,8 +325,8 @@ h1, h2, h3, p { margin: 0; }
|
||||
@media (hover: hover) and (pointer: fine) {
|
||||
.vm-display-unit.is-actionable:hover { transform: translateY(-2px); }
|
||||
.vm-display-unit.is-actionable:hover .vm-screen { box-shadow: 0 20px 40px rgba(15, 23, 42, 0.22), 0 4px 10px rgba(15, 23, 42, 0.10), inset 0 1px 0 rgba(255, 255, 255, 0.14); }
|
||||
.vm-display-unit.is-actionable:hover .vm-screen-play,
|
||||
.vm-display-unit.is-actionable:hover .vm-screen-chip { opacity: 1; transform: none; }
|
||||
.vm-display-unit.is-actionable:hover .vm-screen-play { opacity: 1; transform: none; }
|
||||
.vm-display-unit.is-actionable:hover .vm-screen-chip { opacity: 1; transform: translateX(-50%) translateY(0); }
|
||||
.vm-display-unit.is-actionable:hover .vm-screen.is-idle .vm-screen-img { filter: saturate(0.7) brightness(0.8); }
|
||||
}
|
||||
.vm-display-unit.is-actionable:active { transform: scale(0.985); }
|
||||
@@ -378,9 +390,9 @@ h1, h2, h3, p { margin: 0; }
|
||||
}
|
||||
.vm-spec-cell {
|
||||
display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center;
|
||||
column-gap: 8px; row-gap: 6px; min-width: 0; cursor: default;
|
||||
column-gap: 8px; row-gap: 6px; min-width: 0; cursor: default; border-radius: var(--r-sm);
|
||||
}
|
||||
.vm-spec-cell:focus-visible { box-shadow: none; }
|
||||
.vm-spec-cell:focus-visible { outline: none; box-shadow: var(--focus-ring); }
|
||||
.vm-spec-icon {
|
||||
color: var(--text-3); display: inline-flex; align-items: center; flex-shrink: 0;
|
||||
}
|
||||
@@ -550,7 +562,9 @@ h1, h2, h3, p { margin: 0; }
|
||||
.notice-icon { flex-shrink: 0; margin-top: 2px; color: var(--warn-text); }
|
||||
.notice-error { background: var(--danger-soft); border-color: var(--danger-border); color: var(--danger-text); padding: 10px 14px; }
|
||||
.notice-error .notice-icon { color: var(--danger-text); }
|
||||
.notice-error ul { margin: 0; padding-left: var(--sp-4); }
|
||||
.notice-error ul { margin: 0; padding-inline-start: var(--sp-4); }
|
||||
.notice-warn { background: var(--warn-soft); border-color: var(--notice-border); color: var(--warn-text); justify-content: flex-start; }
|
||||
.notice-warn .notice-icon { color: var(--warn-text); }
|
||||
.notice-info { background: var(--accent-soft); border-color: transparent; }
|
||||
.notice-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.notice-title { font-weight: var(--fw-medium); }
|
||||
@@ -597,9 +611,9 @@ h1, h2, h3, p { margin: 0; }
|
||||
.tech[open] > summary svg { transform: rotate(90deg); }
|
||||
.tech > summary:hover { color: var(--text); background: var(--surface-hover); }
|
||||
.tech-body { position: relative; margin-top: 8px; }
|
||||
.tech-copy { position: absolute; top: 8px; right: 8px; }
|
||||
.tech-copy { position: absolute; top: 8px; inset-inline-end: 8px; }
|
||||
.kv-list {
|
||||
margin: 0; padding: 12px 44px 12px 16px;
|
||||
margin: 0; padding-block: 12px; padding-inline: 16px 44px;
|
||||
background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg);
|
||||
display: grid; grid-template-columns: max-content 1fr; gap: 7px 24px; font-size: var(--fs-13);
|
||||
}
|
||||
@@ -621,9 +635,9 @@ h1, h2, h3, p { margin: 0; }
|
||||
.badge-warn { background: var(--warn-soft); color: var(--warn-text); }
|
||||
.badge-error { background: var(--danger); color: #fff; min-width: 18px; height: 18px; padding: 0 var(--sp-1); justify-content: center; border-radius: 999px; font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* Host summary tiles (4-up single row, 2x2 on narrow windows) */
|
||||
/* Host summary tiles (4-up single row, 2x2 on narrow content column) */
|
||||
.tiles { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; }
|
||||
@media (max-width: 820px) {
|
||||
@container (max-width: 680px) {
|
||||
.tiles { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
.tile {
|
||||
@@ -772,9 +786,10 @@ h1, h2, h3, p { margin: 0; }
|
||||
.log-resize-handle[data-dragging="true"] .log-resize-pill {
|
||||
width: 48px; background: var(--border-strong);
|
||||
}
|
||||
.logbar { height: var(--logbar-h); display: flex; align-items: center; gap: var(--sp-2); padding: 0 var(--sp-3) 0 var(--sp-4); }
|
||||
.logbar { height: var(--logbar-h); display: flex; align-items: center; gap: var(--sp-2); padding-inline: var(--sp-4) var(--sp-3); overflow-x: auto; scrollbar-width: none; }
|
||||
.logbar::-webkit-scrollbar { display: none; }
|
||||
.status-telemetry {
|
||||
display: inline-flex; align-items: center; min-width: 0; margin-left: -8px;
|
||||
display: inline-flex; align-items: center; min-width: 0; flex-shrink: 1; overflow: hidden; margin-inline-start: -8px;
|
||||
font-size: var(--fs-12); color: var(--text-2); user-select: none;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
@@ -815,10 +830,15 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
background: var(--accent); transform-origin: left center;
|
||||
transition: transform 260ms var(--ease-out), background var(--dur) var(--ease-out);
|
||||
}
|
||||
:root[dir="rtl"] .status-mini-fill,
|
||||
:root[dir="rtl"] .progress-fill,
|
||||
:root[dir="rtl"] .meter-fill {
|
||||
transform-origin: right center;
|
||||
}
|
||||
.status-mini-fill.warn { background: var(--status-busy); }
|
||||
.status-mini-fill.high { background: var(--status-error); }
|
||||
.log-toggle-btn {
|
||||
height: 24px; padding: 0 8px;
|
||||
height: 24px; padding: 0 8px; white-space: nowrap; flex-shrink: 0;
|
||||
display: inline-flex; align-items: center; gap: 4px;
|
||||
border: none; border-radius: var(--r-sm); background: transparent;
|
||||
color: var(--text-2); font-size: var(--fs-12); font-weight: var(--fw-medium);
|
||||
@@ -827,9 +847,9 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
}
|
||||
.log-toggle-btn:hover { background: var(--surface-hover); color: var(--text); }
|
||||
.log-toggle-btn:active { transform: scale(0.97); }
|
||||
.tabs { display: flex; gap: 2px; }
|
||||
.tabs { display: flex; gap: 2px; flex-shrink: 0; }
|
||||
.tab {
|
||||
height: 24px; padding: 0 var(--sp-2); border: none; border-radius: var(--r-sm);
|
||||
height: 24px; padding: 0 var(--sp-2); border: none; border-radius: var(--r-sm); white-space: nowrap;
|
||||
background: transparent; color: var(--text-3); font-size: var(--fs-12); cursor: pointer;
|
||||
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out);
|
||||
}
|
||||
@@ -854,9 +874,9 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.log-line { display: flex; gap: var(--sp-3); }
|
||||
.log-ts { color: var(--text-3); flex-shrink: 0; font-variant-numeric: tabular-nums; }
|
||||
.log-src { color: var(--accent-soft-text); flex-shrink: 0; }
|
||||
.log-line.warn .log-msg { color: var(--status-busy); }
|
||||
.log-line.error .log-msg { color: var(--status-error); }
|
||||
.jump-latest { position: absolute; right: var(--sp-4); bottom: var(--sp-3); }
|
||||
.log-line.warn .log-msg { color: var(--warn-text); }
|
||||
.log-line.error .log-msg { color: var(--danger-text); }
|
||||
.jump-latest { position: absolute; inset-inline-end: var(--sp-4); bottom: var(--sp-3); }
|
||||
|
||||
/* ── Overlays: dialog, menu, tooltip, toast ────────────── */
|
||||
.overlay { position: fixed; inset: 0; background: var(--scrim); backdrop-filter: blur(5px); z-index: 40; }
|
||||
@@ -908,9 +928,9 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
}
|
||||
.tooltip kbd { font-family: var(--font-sans); color: var(--text-3); }
|
||||
|
||||
.toast-viewport { position: fixed; right: var(--sp-4); bottom: calc(var(--logbar-h) + var(--sp-4)); z-index: 70; display: flex; flex-direction: column; gap: var(--sp-2); width: 348px; max-width: calc(100vw - 32px); margin: 0; padding: 0; list-style: none; outline: none; }
|
||||
.toast-viewport { position: fixed; inset-inline-end: var(--sp-4); bottom: calc(var(--logbar-h) + var(--sp-4)); z-index: 70; display: flex; flex-direction: column; gap: var(--sp-2); width: 380px; max-width: calc(100vw - 32px); margin: 0; padding: 0; list-style: none; outline: none; }
|
||||
.toast {
|
||||
display: flex; align-items: flex-start; gap: var(--sp-3); padding: var(--sp-3);
|
||||
display: flex; flex-direction: column; gap: var(--sp-2); padding: var(--sp-3);
|
||||
background: var(--surface-2); backdrop-filter: var(--blur-overlay);
|
||||
border: 1px solid var(--border); border-radius: var(--r-lg);
|
||||
box-shadow: var(--shadow-overlay), var(--highlight-top);
|
||||
@@ -920,12 +940,36 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.toast[data-swipe="move"] { transform: translateX(var(--radix-toast-swipe-move-x)); transition: none; }
|
||||
.toast[data-swipe="cancel"] { transform: translateX(0); transition: transform var(--dur) var(--ease-out); }
|
||||
.toast[data-swipe="end"] { animation: toast-swipe-out var(--dur-fast) var(--ease-out) both; }
|
||||
.toast > svg { margin-top: 2px; flex-shrink: 0; }
|
||||
.toast.ok > svg { color: var(--status-running); }
|
||||
.toast.error > svg { color: var(--status-error); }
|
||||
.toast-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||
.toast-main-row { display: flex; align-items: flex-start; gap: var(--sp-3); width: 100%; min-width: 0; }
|
||||
.toast-main-row > svg { margin-top: 2px; flex-shrink: 0; }
|
||||
.toast.ok .toast-main-row > svg { color: var(--status-running); }
|
||||
.toast.error .toast-main-row > svg { color: var(--status-error); }
|
||||
.toast-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
|
||||
.toast-title-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
.toast-title { font-size: var(--fs-13); font-weight: var(--fw-strong); }
|
||||
.toast-desc { font-size: var(--fs-12); color: var(--text-2); overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
|
||||
.toast-code {
|
||||
font-family: var(--font-mono); font-size: var(--fs-11); padding: 1px 5px;
|
||||
border-radius: 4px; background: var(--surface-active); color: var(--text-3);
|
||||
}
|
||||
.toast-desc { font-size: var(--fs-12); color: var(--text-2); overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden; }
|
||||
.toast-footer { display: flex; flex-direction: column; gap: var(--sp-2); padding-inline-start: 28px; width: 100%; min-width: 0; }
|
||||
.toast-details { font-size: var(--fs-12); color: var(--text-3); width: 100%; min-width: 0; }
|
||||
.toast-details summary { cursor: pointer; user-select: none; font-weight: var(--fw-medium); }
|
||||
.toast-details summary:hover { color: var(--text-2); }
|
||||
.toast-details-body {
|
||||
margin-top: 4px; padding: 6px 8px; border-radius: var(--r-sm);
|
||||
background: var(--surface-1); border: 1px solid var(--border);
|
||||
font-family: var(--font-mono); font-size: var(--fs-11); color: var(--text-code);
|
||||
max-height: 120px; overflow: auto; white-space: pre-wrap; word-break: break-word;
|
||||
}
|
||||
.toast-copy-btn {
|
||||
display: inline-flex; align-items: center; gap: 4px;
|
||||
margin-top: 5px; padding: 0 8px; height: 24px; font-size: var(--fs-11);
|
||||
border-radius: var(--r-sm); border: 1px solid var(--border-strong);
|
||||
background: var(--surface-card-elevated); color: var(--text-2); cursor: pointer;
|
||||
}
|
||||
.toast-copy-btn:hover { background: var(--surface-hover); color: var(--text); }
|
||||
.toast-action-btn { align-self: flex-end; }
|
||||
.toast .btn { height: 26px; }
|
||||
|
||||
/* ── Forms (wizard, settings) ──────────────────────────── */
|
||||
@@ -1013,10 +1057,10 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
|
||||
/* ── VM settings (ui/settings.tsx) ─────────────────────── */
|
||||
.dialog.settings-dialog { width: 900px; }
|
||||
.settings-split { display: flex; height: min(600px, calc(100vh - 210px)); min-height: 0; }
|
||||
.settings-split { display: flex; flex: 1; min-height: 0; max-height: min(600px, calc(100vh - 180px)); }
|
||||
.settings-nav {
|
||||
width: 204px; flex-shrink: 0; padding: 10px 8px;
|
||||
border-right: 1px solid var(--border); background: var(--surface-sidebar);
|
||||
border-inline-end: 1px solid var(--border); background: var(--surface-sidebar);
|
||||
display: flex; flex-direction: column; gap: 3px; overflow-y: auto; overscroll-behavior: contain;
|
||||
}
|
||||
.settings-pane {
|
||||
@@ -1037,9 +1081,11 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
background: var(--accent-soft); color: var(--accent-soft-text);
|
||||
font-size: 11px; font-weight: var(--fw-strong); font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.nav-item[aria-selected="true"] .nav-count { background: rgba(255, 255, 255, 0.25); color: var(--accent-text); }
|
||||
.nav-item[aria-selected="true"] .nav-count,
|
||||
.nav-item[aria-current="page"] .nav-count { background: rgba(255, 255, 255, 0.25); color: var(--accent-text); }
|
||||
.nav-issue { color: var(--status-error); flex-shrink: 0; }
|
||||
.nav-item[aria-selected="true"] .nav-issue { color: var(--accent-text); }
|
||||
.nav-item[aria-selected="true"] .nav-issue,
|
||||
.nav-item[aria-current="page"] .nav-issue { color: var(--accent-text); }
|
||||
|
||||
.sgroup { display: flex; flex-direction: column; gap: var(--sp-2); }
|
||||
.sgroup-title { margin: 0 0 0 4px; font-size: var(--fs-12); font-weight: var(--fw-strong); color: var(--text-3); }
|
||||
@@ -1065,16 +1111,19 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.dirty-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--accent); flex-shrink: 0; }
|
||||
.warn-text { color: var(--warn-text); }
|
||||
.inline-code { font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); background: var(--surface-active); padding: 2px 7px; border-radius: 5px; user-select: text; }
|
||||
.stack-1 { display: flex; flex-direction: column; gap: var(--sp-1); }
|
||||
.stack-2 { display: flex; flex-direction: column; align-items: flex-start; gap: var(--sp-2); }
|
||||
.stack-2 > .input { max-width: 320px; }
|
||||
.stack-3 { display: flex; flex-direction: column; gap: var(--sp-3); }
|
||||
.res-input { margin-top: var(--sp-2); max-width: 220px; }
|
||||
|
||||
.foot-status { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-13); color: var(--text-2); }
|
||||
.foot-status .link-btn { font-size: var(--fs-13); margin-left: var(--sp-1); }
|
||||
.foot-status .link-btn { font-size: var(--fs-13); margin-inline-start: var(--sp-1); }
|
||||
.foot-status .link-btn:disabled { opacity: 0.5; cursor: default; text-decoration: none; }
|
||||
|
||||
/* Segmented control with a sliding highlight */
|
||||
.seg { position: relative; display: inline-flex; padding: 2px; gap: 2px; border-radius: var(--r-md); background: var(--surface-active); isolation: isolate; }
|
||||
.seg { position: relative; display: inline-flex; max-width: 100%; overflow-x: auto; scrollbar-width: none; padding: 2px; gap: 2px; border-radius: var(--r-md); background: var(--surface-active); isolation: isolate; }
|
||||
.seg::-webkit-scrollbar { display: none; }
|
||||
.seg-wide { display: flex; }
|
||||
.seg-wide button { flex: 1; }
|
||||
.seg-thumb {
|
||||
@@ -1165,10 +1214,10 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
/* Pop-up button (replaces native <select>) */
|
||||
.popup-btn {
|
||||
display: inline-flex; align-items: center; justify-content: space-between; gap: 10px;
|
||||
height: 29px; min-width: 140px; max-width: 100%; padding: 0 8px 0 10px;
|
||||
height: 29px; min-width: 140px; max-width: 100%; padding-inline: 10px 8px;
|
||||
border-radius: var(--r-sm); border: 1px solid var(--border-strong);
|
||||
background: var(--seg-thumb); color: var(--text); box-shadow: var(--shadow-btn);
|
||||
font: inherit; font-size: var(--fs-13); text-align: left; cursor: pointer;
|
||||
font: inherit; font-size: var(--fs-13); text-align: start; cursor: pointer;
|
||||
transition: background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out);
|
||||
}
|
||||
.popup-btn:hover { border-color: var(--text-3); }
|
||||
@@ -1179,9 +1228,9 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.popup-value { min-width: 0; display: inline-flex; align-items: baseline; gap: 6px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.popup-chevron { flex-shrink: 0; color: var(--text-3); }
|
||||
.popup-detail { font-size: var(--fs-12); color: var(--text-3); white-space: nowrap; }
|
||||
.popup-menu { min-width: var(--radix-dropdown-menu-trigger-width); max-height: min(360px, var(--radix-dropdown-menu-content-available-height)); overflow-y: auto; overscroll-behavior: contain; }
|
||||
.popup-item { position: relative; padding-left: 28px; padding-right: 14px; gap: 8px; }
|
||||
.popup-check { position: absolute; left: 9px; top: 50%; transform: translateY(-50%); display: grid; place-items: center; }
|
||||
.popup-menu { min-width: var(--radix-dropdown-menu-trigger-width); max-width: calc(100vw - 16px); max-height: min(360px, var(--radix-dropdown-menu-content-available-height)); overflow-y: auto; overscroll-behavior: contain; }
|
||||
.popup-item { position: relative; padding-inline: 28px 14px; gap: 8px; }
|
||||
.popup-check { position: absolute; inset-inline-start: 9px; top: 50%; transform: translateY(-50%); display: grid; place-items: center; }
|
||||
.popup-item-label { white-space: nowrap; }
|
||||
.popup-item[data-highlighted] .popup-detail { color: rgba(255, 255, 255, 0.78); }
|
||||
|
||||
@@ -1295,12 +1344,14 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
transition: opacity var(--dur) var(--ease-out), transform var(--dur) var(--ease-out);
|
||||
}
|
||||
.vm-screen-chip {
|
||||
position: absolute; left: 50%; bottom: 10px; z-index: 2; margin-left: -60px; width: 120px;
|
||||
position: absolute; left: 50%; bottom: 10px; z-index: 2;
|
||||
width: max-content; max-width: calc(100% - 20px); padding: 0 12px;
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 5px;
|
||||
height: 26px; border-radius: 999px; pointer-events: none;
|
||||
background: rgba(20, 21, 26, 0.72); color: #fff; backdrop-filter: blur(10px);
|
||||
font-size: var(--fs-12); font-weight: var(--fw-medium);
|
||||
opacity: 0; transform: translateY(4px);
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
opacity: 0; transform: translateX(-50%) translateY(4px);
|
||||
transition: opacity var(--dur) var(--ease-out), transform var(--dur) var(--ease-out);
|
||||
}
|
||||
|
||||
@@ -1333,8 +1384,8 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.source-title { display: flex; align-items: center; gap: 6px; font-size: 14px; font-weight: var(--fw-strong); color: var(--text); }
|
||||
.source-title .badge { height: 18px; padding: 0 7px; font-size: 11px; }
|
||||
.source-sub { font-size: var(--fs-12); color: var(--text-3); }
|
||||
.path-text { display: block; max-width: 420px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-12); }
|
||||
.name-input { width: 260px; }
|
||||
.path-text { display: block; max-width: min(420px, 100%); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-12); }
|
||||
.name-input { width: 260px; max-width: 100%; }
|
||||
|
||||
/* The assistant keeps one size across steps, like macOS setup assistants. */
|
||||
.dialog.wizard-dialog { width: 760px; height: min(660px, calc(100vh - 80px)); }
|
||||
@@ -1352,7 +1403,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
transition: background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out);
|
||||
}
|
||||
.affinity-chip:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); }
|
||||
.affinity-chip.is-active { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
|
||||
.affinity-chip.is-active { border-color: var(--accent); background: var(--accent-soft); color: var(--accent-soft-text); }
|
||||
.affinity-chip:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.affinity-grid {
|
||||
display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px;
|
||||
@@ -1361,7 +1412,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.affinity-cpu {
|
||||
display: flex; align-items: center; gap: 7px; padding: 7px 9px;
|
||||
border-radius: var(--r-md); border: 1px solid var(--border-strong);
|
||||
background: var(--surface-1); color: var(--text-2); cursor: pointer; text-align: left;
|
||||
background: var(--surface-1); color: var(--text-2); cursor: pointer; text-align: start;
|
||||
transition: background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-press) var(--ease-out);
|
||||
}
|
||||
.affinity-cpu:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); }
|
||||
@@ -1375,21 +1426,21 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
}
|
||||
.affinity-cpu.is-checked .affinity-check { border-color: var(--accent); background: var(--accent); }
|
||||
.affinity-cpu-name { font-size: var(--fs-12); font-weight: var(--fw-medium); white-space: nowrap; }
|
||||
.affinity-cpu-meta { margin-left: auto; display: inline-flex; align-items: center; gap: 4px; }
|
||||
.affinity-cpu-meta { margin-inline-start: auto; display: inline-flex; align-items: center; gap: 4px; }
|
||||
.affinity-core-tag { font-size: 10px; color: var(--text-3); }
|
||||
.affinity-tier {
|
||||
font-size: 10px; font-weight: var(--fw-strong); line-height: 1; padding: 2px 5px; border-radius: 999px;
|
||||
}
|
||||
.affinity-tier.tier-p { background: rgba(0, 122, 255, 0.14); color: var(--accent); }
|
||||
.affinity-tier.tier-e { background: rgba(52, 199, 89, 0.15); color: var(--status-running); }
|
||||
.affinity-tier.tier-lpe { background: rgba(255, 159, 10, 0.16); color: var(--status-busy); }
|
||||
.affinity-tier.tier-p { background: var(--accent-soft); color: var(--accent-soft-text); }
|
||||
.affinity-tier.tier-e { background: var(--ok-soft); color: var(--ok-text); }
|
||||
.affinity-tier.tier-lpe { background: var(--warn-soft); color: var(--warn-text); }
|
||||
.affinity-summary {
|
||||
display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px;
|
||||
padding: 8px 10px; border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border);
|
||||
font-size: var(--fs-12); color: var(--text-2);
|
||||
}
|
||||
.affinity-summary > span { display: inline-flex; align-items: center; gap: 5px; }
|
||||
.affinity-live { color: var(--status-running); }
|
||||
.affinity-live { color: var(--ok-text); }
|
||||
.affinity-eco-row {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
||||
padding: 10px 12px; border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border);
|
||||
@@ -1433,7 +1484,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.vm-name-btn > span { overflow-wrap: anywhere; }
|
||||
.vm-name-btn:hover { background: var(--surface-hover); }
|
||||
.vm-name-pencil {
|
||||
position: absolute; left: 100%; top: 50%; margin-left: 6px; transform: translateY(-50%);
|
||||
position: absolute; inset-inline-start: 100%; top: 50%; margin-inline-start: 6px; transform: translateY(-50%);
|
||||
color: var(--text-3); opacity: 0; transition: opacity var(--dur-fast) var(--ease-out);
|
||||
}
|
||||
.vm-name-btn:hover .vm-name-pencil, .vm-name-btn:focus-visible .vm-name-pencil { opacity: 1; }
|
||||
@@ -1460,8 +1511,8 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
/* One line per fact: icon · label · value · short usage bar at the end.
|
||||
Every row has the same height, and a bar appearing or hiding when the VM
|
||||
starts or stops doesn't move anything. */
|
||||
.vm-spec-cell { grid-template-columns: auto 4.5em minmax(0, 1fr) 56px; column-gap: 10px; min-height: 22px; }
|
||||
.vm-spec-label { display: block; font-size: var(--fs-13); color: var(--text-3); white-space: nowrap; }
|
||||
.vm-spec-cell { grid-template-columns: auto minmax(4.5em, max-content) minmax(0, 1fr) 56px; column-gap: 10px; min-height: 22px; }
|
||||
.vm-spec-label { display: block; max-width: 9.5em; overflow: hidden; text-overflow: ellipsis; font-size: var(--fs-13); color: var(--text-3); white-space: nowrap; }
|
||||
.vm-spec-meter { grid-column: 4; grid-row: 1; align-self: center; }
|
||||
/* Rows without a bar (graphics, network, language) give its column to the value. */
|
||||
.vm-spec-cell:not(:has(.vm-spec-meter)) .vm-spec-val { grid-column: 3 / 5; }
|
||||
@@ -1480,7 +1531,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
|
||||
/* Interactive install stepper */
|
||||
.guide-step-btn {
|
||||
width: 22px; height: 22px; padding: 0; border-radius: 50%; flex-shrink: 0; margin-top: 1px;
|
||||
width: 24px; height: 24px; padding: 0; border-radius: 50%; flex-shrink: 0; margin-top: 1px;
|
||||
display: grid; place-items: center; border: none; cursor: pointer;
|
||||
background: var(--accent-soft); color: var(--accent-soft-text);
|
||||
font-size: var(--fs-11); font-weight: var(--fw-strong); font-variant-numeric: tabular-nums;
|
||||
@@ -1501,15 +1552,15 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
|
||||
/* Log filter controls */
|
||||
.log-filter-input {
|
||||
width: 148px; height: 22px; padding: 0 8px;
|
||||
width: 148px; height: 24px; padding: 0 8px; flex-shrink: 0;
|
||||
border-radius: var(--r-sm); border: 1px solid var(--border-strong);
|
||||
background: var(--surface-input); color: var(--text); font: inherit; font-size: var(--fs-12);
|
||||
}
|
||||
.log-filter-input:focus { border-color: var(--accent); box-shadow: var(--focus-ring); }
|
||||
.log-filter-pill {
|
||||
height: 22px; padding: 0 8px; border-radius: var(--r-sm);
|
||||
height: 24px; padding: 0 8px; border-radius: var(--r-sm); white-space: nowrap; flex-shrink: 0;
|
||||
border: 1px solid var(--border); background: transparent;
|
||||
color: var(--text-3); font-size: 11.5px; cursor: pointer;
|
||||
color: var(--text-3); font-size: var(--fs-12); cursor: pointer;
|
||||
transition: background var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out);
|
||||
}
|
||||
.log-filter-pill:hover { color: var(--text); background: var(--surface-hover); }
|
||||
@@ -1670,6 +1721,74 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.theme-scheme-strip { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||
.theme-scheme-chips { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
|
||||
/* ErrorBoundary recovery surface (tokens-backed for both Light and Dark themes) */
|
||||
.error-boundary {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
height: 100%; padding: var(--sp-6);
|
||||
background: var(--surface-canvas); color: var(--text); font-family: var(--font-sans);
|
||||
}
|
||||
.error-boundary-card {
|
||||
max-width: 560px; width: 100%; padding: var(--sp-5);
|
||||
border-radius: var(--r-xl); border: 1px solid var(--border);
|
||||
background: var(--surface-1); box-shadow: var(--shadow-card);
|
||||
display: flex; flex-direction: column; gap: var(--sp-3);
|
||||
}
|
||||
.error-boundary-title { margin: 0; font-size: var(--fs-16); font-weight: var(--fw-strong); }
|
||||
.error-boundary-pre {
|
||||
margin: 0; padding: 10px 12px; border-radius: var(--r-md);
|
||||
font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code);
|
||||
max-height: 180px; overflow: auto;
|
||||
background: var(--surface-0); border: 1px solid var(--border);
|
||||
white-space: pre-wrap; word-break: break-word;
|
||||
}
|
||||
.error-boundary-actions { display: flex; gap: var(--sp-2); justify-content: flex-end; }
|
||||
|
||||
/* Responsive / narrow-window / high-DPI & mobile drawer adaptations */
|
||||
@media (max-width: 1040px) {
|
||||
.logs:has(.logs-body-wrap) .status-telemetry .status-metric:not(.status-issue) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.sidebar-backdrop {
|
||||
display: block; position: fixed;
|
||||
inset-block: var(--titlebar-h) var(--logbar-h); inset-inline: 0;
|
||||
background: var(--scrim); backdrop-filter: blur(3px); z-index: 31;
|
||||
}
|
||||
.sidebar-wrap {
|
||||
position: fixed; z-index: 32;
|
||||
inset-block: var(--titlebar-h) var(--logbar-h); inset-inline-start: 0;
|
||||
box-shadow: var(--shadow-overlay);
|
||||
}
|
||||
.workspace.sidebar-hidden .sidebar-wrap { pointer-events: none; }
|
||||
.scroll { padding: 14px 16px 20px; }
|
||||
.dialog { max-width: calc(100vw - 16px); max-height: calc(100vh - 32px); }
|
||||
.dialog.wizard-dialog { height: min(660px, calc(100vh - 32px)); }
|
||||
.settings-split { flex-direction: column; max-height: none; }
|
||||
.settings-nav {
|
||||
width: 100%; flex-direction: row; overflow-x: auto; overflow-y: hidden;
|
||||
border-inline-end: none; border-bottom: 1px solid var(--border);
|
||||
padding: 8px 12px; scrollbar-width: none;
|
||||
}
|
||||
.settings-nav::-webkit-scrollbar { display: none; }
|
||||
.settings-nav .nav-item { width: auto; flex-shrink: 0; }
|
||||
.settings-pane { padding: 16px; }
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.source-cards, .field-row, .review-groups { grid-template-columns: 1fr; }
|
||||
.review-group:last-child .review-rows { grid-template-columns: max-content 1fr; }
|
||||
.vm-spec-card { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 12px 14px; }
|
||||
.affinity-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.conn-row, .srow-head, .row, .page-head { flex-wrap: wrap; }
|
||||
.conn-ctrl { flex-wrap: wrap; max-width: 100%; }
|
||||
.plugins-search { width: 100%; }
|
||||
}
|
||||
@container (max-width: 560px) {
|
||||
.review-group:last-child .review-rows { grid-template-columns: max-content 1fr; }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/* Host usability invariants locked with !important in earliest layer so themes
|
||||
|
||||
@@ -8,11 +8,12 @@
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
|
||||
/* Map installed PingFang SC / HarmonyOS Sans SC / MiSans / Noto Sans SC / Source Han Sans CN
|
||||
explicitly across weights. On Windows DirectWrite, PingFang SC Regular renders overly thin
|
||||
compared to macOS Retina CoreText, so body weights (400–550) map to Medium for balanced ink. */
|
||||
/* Scoped Simplified Chinese weight-mapping face ("ReimsCJK-SC").
|
||||
IMPORTANT: Never attach this unconditionally to all languages — doing so
|
||||
hijacks Han Unification `locl` glyphs and turns Traditional Chinese / Japanese
|
||||
Kanji into Mainland Simplified forms. Only `:lang(zh-CN|zh-SG|zh-Hans)` activates it. */
|
||||
@font-face {
|
||||
font-family: "ReimsCJK";
|
||||
font-family: "ReimsCJK-SC";
|
||||
font-style: normal;
|
||||
font-weight: 400 550;
|
||||
src:
|
||||
@@ -26,7 +27,7 @@
|
||||
unicode-range: U+2E80-9FFF, U+3000-303F, U+FF00-FFEF, U+F900-FAFF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: "ReimsCJK";
|
||||
font-family: "ReimsCJK-SC";
|
||||
font-style: normal;
|
||||
font-weight: 560 900;
|
||||
src:
|
||||
@@ -44,9 +45,13 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
|
||||
/* Typography */
|
||||
--font-sans: "ReimsSans", "ReimsCJK", "PingFang SC Medium", "PingFang SC", "HarmonyOS Sans SC", "MiSans", "Noto Sans SC", "Source Han Sans CN", -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", system-ui, sans-serif;
|
||||
/* Typography — regional CJK family injected via --font-cjk per :lang() */
|
||||
--font-locale-pack: ;
|
||||
--font-cjk: "PingFang SC", "Microsoft YaHei UI", "Noto Sans CJK SC", sans-serif;
|
||||
--font-sans: "ReimsSans", var(--font-locale-pack) -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI Variable Text", "Segoe UI", var(--font-cjk), system-ui, sans-serif;
|
||||
--font-mono: "SF Mono", "JetBrains Mono", "Cascadia Mono", Consolas, monospace;
|
||||
--body-lh: 1.48;
|
||||
--heading-tracking: -0.015em;
|
||||
--fs-11: 11px;
|
||||
--fs-12: 12px;
|
||||
--fs-13: 13px;
|
||||
@@ -245,4 +250,36 @@
|
||||
--text-3: #a6a6b0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Regional script & OpenType `locl` typography stacks:
|
||||
- Simplified Chinese: DirectWrite Medium ink compensation ("ReimsCJK-SC")
|
||||
- Traditional Chinese (TW/HK/MO): Orthodox Traditional glyph stack, 400 regular weight
|
||||
and taller line-height (1.56) so dense 20+ stroke characters never blob at 11–13px
|
||||
- Japanese: Kana/Kanji stack, 400 regular weight, strict kinsoku line-breaking
|
||||
- Korean: Hangul stack, 400 regular weight, `word-break: keep-all` syllable-word integrity */
|
||||
:root:lang(zh-CN), :root:lang(zh-SG), :root:lang(zh-Hans) {
|
||||
--font-cjk: "ReimsCJK-SC", "PingFang SC Medium", "PingFang SC", "HarmonyOS Sans SC", "MiSans", "Noto Sans SC", "Source Han Sans CN", "Microsoft YaHei UI", sans-serif;
|
||||
--heading-tracking: 0em;
|
||||
}
|
||||
|
||||
:root:lang(zh-TW), :root:lang(zh-HK), :root:lang(zh-MO), :root:lang(zh-Hant) {
|
||||
--font-cjk: "PingFang TC", "Noto Sans TC", "Source Han Sans TC", "Microsoft JhengHei UI", "Microsoft JhengHei", sans-serif;
|
||||
--fw-regular: 400;
|
||||
--body-lh: 1.56;
|
||||
--heading-tracking: 0em;
|
||||
}
|
||||
|
||||
:root:lang(ja) {
|
||||
--font-cjk: "Hiragino Sans", "Noto Sans JP", "BIZ UDPGothic", "Yu Gothic UI", "Meiryo UI", "Meiryo", sans-serif;
|
||||
--fw-regular: 400;
|
||||
--body-lh: 1.58;
|
||||
--heading-tracking: 0em;
|
||||
}
|
||||
|
||||
:root:lang(ko) {
|
||||
--font-cjk: "Apple SD Gothic Neo", "Malgun Gothic", "Noto Sans KR", sans-serif;
|
||||
--fw-regular: 400;
|
||||
--body-lh: 1.54;
|
||||
--heading-tracking: 0em;
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ export type UIContractPart = (typeof UI_CONTRACT_PARTS)[number]
|
||||
export const UI_CONTRACT_STATE_ATTRS = [
|
||||
'data-theme',
|
||||
'data-motion',
|
||||
'data-locale',
|
||||
'data-view',
|
||||
'data-vm-state',
|
||||
'data-busy',
|
||||
@@ -51,7 +52,8 @@ export const UI_CONTRACT_SLOTS = [
|
||||
export type UIContractSlot = (typeof UI_CONTRACT_SLOTS)[number]
|
||||
|
||||
export const UI_CONTRACT_TOKENS = [
|
||||
'--font-sans', '--font-mono',
|
||||
'--font-sans', '--font-cjk', '--font-mono',
|
||||
'--body-lh', '--heading-tracking',
|
||||
'--fs-11', '--fs-12', '--fs-13', '--fs-14', '--fs-15', '--fs-16', '--fs-20', '--fs-24',
|
||||
'--fw-regular', '--fw-medium', '--fw-strong',
|
||||
'--sp-1', '--sp-2', '--sp-3', '--sp-4', '--sp-5', '--sp-6', '--sp-8',
|
||||
|
||||
+13
-1
@@ -129,7 +129,19 @@ export type ThemeDecorationState = plugin.ThemeDecorationState
|
||||
export type ThemeContribution = plugin.ThemeContribution
|
||||
export type CustomThemeScheme = plugin.CustomThemeScheme
|
||||
export type ActiveThemePayload = plugin.ActiveThemePayload
|
||||
export type ResolvedLocalePack = plugin.ResolvedLocalePack
|
||||
export interface ResolvedLocaleFont {
|
||||
family: string
|
||||
url: string
|
||||
weight?: string
|
||||
style?: string
|
||||
unicodeRange?: string
|
||||
}
|
||||
|
||||
export type ResolvedLocalePack = Model<plugin.ResolvedLocalePack> & {
|
||||
has_ui_messages?: boolean
|
||||
plugin_messages?: Record<string, Record<string, string>>
|
||||
fonts?: ResolvedLocaleFont[]
|
||||
}
|
||||
export type MenuContribution = plugin.MenuContribution
|
||||
export type VMCardContribution = plugin.VMCardContribution
|
||||
export type PanelContribution = plugin.PanelContribution
|
||||
|
||||
@@ -85,6 +85,7 @@ export type StatusKind = 'running' | 'stopped' | 'busy' | 'broken' | 'warn'
|
||||
export function statusKind(state: string): StatusKind {
|
||||
if (state === 'running') return 'running'
|
||||
if (state === 'starting' || state === 'stopping' || state === 'creating') return 'busy'
|
||||
if (state === 'driver_unavailable') return 'warn'
|
||||
if (state === 'broken') return 'broken'
|
||||
return 'stopped'
|
||||
}
|
||||
|
||||
@@ -146,7 +146,9 @@ export function Segmented<V extends string | number>({ options, value, onChange,
|
||||
e.preventDefault()
|
||||
const enabled = options.filter((o) => !o.disabled)
|
||||
const i = enabled.findIndex((o) => o.value === value)
|
||||
const next = enabled[(i + (e.key === 'ArrowRight' ? 1 : -1) + enabled.length) % enabled.length]
|
||||
const isRTL = box.current ? getComputedStyle(box.current).direction === 'rtl' : false
|
||||
const delta = (e.key === 'ArrowRight') !== isRTL ? 1 : -1
|
||||
const next = enabled[(i + delta + enabled.length) % enabled.length]
|
||||
if (next) {
|
||||
onChange(next.value)
|
||||
requestAnimationFrame(() => box.current?.querySelector<HTMLElement>('[aria-checked="true"]')?.focus())
|
||||
@@ -277,7 +279,7 @@ export const RangeField: React.FC<RangeProps> = ({ value, min, max, step = 1, un
|
||||
return (
|
||||
<div className="range-field" data-warn={over || undefined}>
|
||||
<div className="range-main">
|
||||
<div className="range-rail-wrap">
|
||||
<div className="range-rail-wrap" dir="ltr">
|
||||
<div className="range-rail" aria-hidden="true">
|
||||
<div className="range-track" />
|
||||
{recommend && (
|
||||
|
||||
+97
-19
@@ -1,5 +1,5 @@
|
||||
import * as RToast from '@radix-ui/react-toast'
|
||||
import { CircleCheck, CircleX, X } from 'lucide-react'
|
||||
import { Check, CircleCheck, CircleX, X } from 'lucide-react'
|
||||
import React, { useCallback, useState } from 'react'
|
||||
import { IconButton } from './controls'
|
||||
|
||||
@@ -7,6 +7,10 @@ export interface ToastInput {
|
||||
kind: 'ok' | 'error'
|
||||
title: string
|
||||
description?: string
|
||||
errorCode?: string
|
||||
rawDetail?: string
|
||||
detailsLabel?: string
|
||||
copyDetailsLabel?: string
|
||||
action?: { label: string; onClick: () => void }
|
||||
}
|
||||
|
||||
@@ -25,35 +29,109 @@ export function useToasts() {
|
||||
return { items, push, remove }
|
||||
}
|
||||
|
||||
interface ToasterProps {
|
||||
items: ToastItem[]
|
||||
interface ToastCardProps {
|
||||
item: ToastItem
|
||||
onRemove: (id: number) => void
|
||||
closeLabel: string
|
||||
}
|
||||
|
||||
export const Toaster: React.FC<ToasterProps> = ({ items, onRemove, closeLabel }) => (
|
||||
<RToast.Provider swipeDirection="right">
|
||||
{items.map((item) => (
|
||||
<RToast.Root
|
||||
key={item.id}
|
||||
className={`toast ${item.kind}`}
|
||||
duration={item.kind === 'error' ? 8000 : 3000}
|
||||
onOpenChange={(open) => { if (!open) onRemove(item.id) }}
|
||||
>
|
||||
{item.kind === 'ok' ? <CircleCheck size={16} /> : <CircleX size={16} />}
|
||||
const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) => {
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const [copied, setCopied] = useState(false)
|
||||
|
||||
const copyDiagnostic = () => {
|
||||
const full = [
|
||||
item.errorCode ? `[${item.errorCode}] ${item.title}` : item.title,
|
||||
item.description,
|
||||
item.rawDetail,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n')
|
||||
navigator.clipboard
|
||||
?.writeText(full)
|
||||
.then(() => {
|
||||
setCopied(true)
|
||||
window.setTimeout(() => setCopied(false), 1500)
|
||||
})
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
return (
|
||||
<RToast.Root
|
||||
className={`toast ${item.kind}${item.rawDetail || item.action ? ' has-extra' : ''}`}
|
||||
duration={expanded ? 600_000 : item.kind === 'error' ? 10_000 : 3000}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onRemove(item.id)
|
||||
}}
|
||||
>
|
||||
<div className="toast-main-row">
|
||||
{item.kind === 'ok' ? (
|
||||
<CircleCheck size={16} aria-hidden="true" />
|
||||
) : (
|
||||
<CircleX size={16} aria-hidden="true" />
|
||||
)}
|
||||
<div className="toast-text">
|
||||
<RToast.Title className="toast-title">{item.title}</RToast.Title>
|
||||
{item.description && <RToast.Description className="toast-desc">{item.description}</RToast.Description>}
|
||||
<div className="toast-title-row">
|
||||
<RToast.Title className="toast-title">{item.title}</RToast.Title>
|
||||
{item.errorCode && <span className="toast-code selectable">{item.errorCode}</span>}
|
||||
</div>
|
||||
{item.description && (
|
||||
<RToast.Description className="toast-desc">{item.description}</RToast.Description>
|
||||
)}
|
||||
</div>
|
||||
{item.action && (
|
||||
{item.action && !item.rawDetail && (
|
||||
<RToast.Action asChild altText={item.action.label}>
|
||||
<button type="button" className="btn" onClick={item.action.onClick}>{item.action.label}</button>
|
||||
<button type="button" className="btn" onClick={item.action.onClick}>
|
||||
{item.action.label}
|
||||
</button>
|
||||
</RToast.Action>
|
||||
)}
|
||||
<RToast.Close asChild>
|
||||
<IconButton small label={closeLabel} icon={<X size={14} />} tipSide="top" />
|
||||
<IconButton small label={closeLabel} icon={<X size={14} aria-hidden="true" />} tipSide="top" />
|
||||
</RToast.Close>
|
||||
</RToast.Root>
|
||||
</div>
|
||||
{(item.rawDetail || (item.action && item.rawDetail)) && (
|
||||
<div className="toast-footer">
|
||||
{item.rawDetail && (
|
||||
<details
|
||||
className="toast-details"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onToggle={(e) => setExpanded(e.currentTarget.open)}
|
||||
>
|
||||
<summary>{item.detailsLabel}</summary>
|
||||
<div className="toast-details-body selectable">{item.rawDetail}</div>
|
||||
{item.copyDetailsLabel && (
|
||||
<button type="button" className="toast-copy-btn" onClick={copyDiagnostic}>
|
||||
{copied ? <Check size={12} aria-hidden="true" /> : null}
|
||||
<span>{item.copyDetailsLabel}</span>
|
||||
</button>
|
||||
)}
|
||||
</details>
|
||||
)}
|
||||
{item.action && (
|
||||
<RToast.Action asChild altText={item.action.label}>
|
||||
<button type="button" className="btn toast-action-btn" onClick={item.action.onClick}>
|
||||
{item.action.label}
|
||||
</button>
|
||||
</RToast.Action>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</RToast.Root>
|
||||
)
|
||||
}
|
||||
|
||||
interface ToasterProps {
|
||||
items: ToastItem[]
|
||||
onRemove: (id: number) => void
|
||||
closeLabel: string
|
||||
dir?: 'ltr' | 'rtl'
|
||||
}
|
||||
|
||||
export const Toaster: React.FC<ToasterProps> = ({ items, onRemove, closeLabel, dir = 'ltr' }) => (
|
||||
<RToast.Provider swipeDirection={dir === 'rtl' ? 'left' : 'right'}>
|
||||
{items.map((item) => (
|
||||
<ToastCard key={item.id} item={item} onRemove={onRemove} closeLabel={closeLabel} />
|
||||
))}
|
||||
<RToast.Viewport className="toast-viewport" />
|
||||
</RToast.Provider>
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
"uiApi": "1.0.0",
|
||||
"tokens": [
|
||||
"--font-sans",
|
||||
"--font-cjk",
|
||||
"--font-mono",
|
||||
"--body-lh",
|
||||
"--heading-tracking",
|
||||
"--fs-11",
|
||||
"--fs-12",
|
||||
"--fs-13",
|
||||
@@ -107,6 +110,7 @@
|
||||
"stateAttrs": [
|
||||
"data-theme",
|
||||
"data-motion",
|
||||
"data-locale",
|
||||
"data-view",
|
||||
"data-vm-state",
|
||||
"data-busy",
|
||||
|
||||
@@ -15,6 +15,9 @@ export namespace app {
|
||||
app_version: string;
|
||||
safe_mode?: boolean;
|
||||
plugin_crash_detected?: boolean;
|
||||
detected_locale?: string;
|
||||
effective_locale?: string;
|
||||
missing_font_hint?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new AppState(source);
|
||||
@@ -36,6 +39,9 @@ export namespace app {
|
||||
this.app_version = source["app_version"];
|
||||
this.safe_mode = source["safe_mode"];
|
||||
this.plugin_crash_detected = source["plugin_crash_detected"];
|
||||
this.detected_locale = source["detected_locale"];
|
||||
this.effective_locale = source["effective_locale"];
|
||||
this.missing_font_hint = source["missing_font_hint"];
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
@@ -1405,11 +1411,21 @@ export namespace plugin {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export interface ResolvedLocaleFont {
|
||||
family: string;
|
||||
url: string;
|
||||
weight?: string;
|
||||
style?: string;
|
||||
unicodeRange?: string;
|
||||
}
|
||||
export class ResolvedLocalePack {
|
||||
locale: string;
|
||||
label: string;
|
||||
fallback?: string;
|
||||
has_ui_messages?: boolean;
|
||||
messages?: Record<string, string>;
|
||||
plugin_messages?: Record<string, Record<string, string>>;
|
||||
fonts?: ResolvedLocaleFont[];
|
||||
pluginIds?: string[];
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
@@ -1421,7 +1437,10 @@ export namespace plugin {
|
||||
this.locale = source["locale"];
|
||||
this.label = source["label"];
|
||||
this.fallback = source["fallback"];
|
||||
this.has_ui_messages = source["has_ui_messages"];
|
||||
this.messages = source["messages"];
|
||||
this.plugin_messages = source["plugin_messages"];
|
||||
this.fonts = source["fonts"];
|
||||
this.pluginIds = source["pluginIds"];
|
||||
}
|
||||
}
|
||||
@@ -1912,7 +1931,8 @@ export namespace reims {
|
||||
}
|
||||
export class ValidationIssue {
|
||||
field: string;
|
||||
code: string;
|
||||
code?: string;
|
||||
params?: Record<string, any>;
|
||||
message: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
@@ -1923,6 +1943,7 @@ export namespace reims {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.field = source["field"];
|
||||
this.code = source["code"];
|
||||
this.params = source["params"];
|
||||
this.message = source["message"];
|
||||
}
|
||||
}
|
||||
@@ -2065,6 +2086,7 @@ export namespace runtime {
|
||||
}
|
||||
export class KindSpec {
|
||||
kind: string;
|
||||
name?: plugin.LocalizedText;
|
||||
name_zh: string;
|
||||
name_en: string;
|
||||
required_files?: string[];
|
||||
@@ -2079,6 +2101,7 @@ export namespace runtime {
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.kind = source["kind"];
|
||||
this.name = source["name"];
|
||||
this.name_zh = source["name_zh"];
|
||||
this.name_en = source["name_en"];
|
||||
this.required_files = source["required_files"];
|
||||
|
||||
+109
-38
@@ -54,6 +54,9 @@ type AppState struct {
|
||||
AppVersion string `json:"app_version"`
|
||||
SafeMode bool `json:"safe_mode,omitempty"`
|
||||
PluginCrashDetected bool `json:"plugin_crash_detected,omitempty"`
|
||||
DetectedLocale string `json:"detected_locale,omitempty"`
|
||||
EffectiveLocale string `json:"effective_locale,omitempty"`
|
||||
MissingFontHint string `json:"missing_font_hint,omitempty"`
|
||||
}
|
||||
|
||||
type rebootWatcherEntry struct {
|
||||
@@ -103,6 +106,7 @@ type Lifecycle struct {
|
||||
}
|
||||
|
||||
func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
|
||||
i18n.SetDetailRedactor(reims.RedactText)
|
||||
cfg, needsSetup, err := config.Resolve()
|
||||
if err != nil {
|
||||
cfg = config.Default()
|
||||
@@ -373,10 +377,9 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
}
|
||||
a.syncInputTargets(imeTargets)
|
||||
if tm != nil {
|
||||
if runningCount == 1 {
|
||||
tm.UpdateTooltip(i18n.T(loc, "tray.running.one"))
|
||||
} else if runningCount > 1 {
|
||||
tm.UpdateTooltip(i18n.T(loc, "tray.running.many", runningCount))
|
||||
effLoc := i18n.EffectiveLocale(loc)
|
||||
if runningCount >= 1 {
|
||||
tm.UpdateTooltip(i18n.M(effLoc, "tray.running", i18n.Vars{"count": runningCount}))
|
||||
} else {
|
||||
tm.UpdateTooltip("Reims-Go")
|
||||
}
|
||||
@@ -654,6 +657,9 @@ func (a *App) GetState() AppState {
|
||||
AppVersion: version.Version,
|
||||
SafeMode: safeMode,
|
||||
PluginCrashDetected: crashDetected,
|
||||
DetectedLocale: string(i18n.DetectOSLocaleTag()),
|
||||
EffectiveLocale: string(i18n.EffectiveLocale(cfgCopy.Locale)),
|
||||
MissingFontHint: host.CheckMissingLocaleFontsForUI(string(i18n.EffectiveLocale(cfgCopy.Locale)), i18n.EffectiveLocale(cfgCopy.Locale)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -674,9 +680,18 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) {
|
||||
|
||||
func (a *App) SetLocale(raw string) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.cfg.Locale = i18n.ResolveLocale(raw)
|
||||
return config.Save("", a.cfg)
|
||||
a.cfg.Locale = i18n.ParsePreference(raw)
|
||||
err := config.Save("", a.cfg)
|
||||
eff := i18n.EffectiveLocale(a.cfg.Locale)
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr != nil {
|
||||
mgr.NotifyLocaleChanged(eff)
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) SetAutoPinPCores(enabled bool) error {
|
||||
@@ -779,8 +794,10 @@ func (a *App) startTray() {
|
||||
}
|
||||
items = append(items, tray.VMItem{Name: vm.Name, Label: label, State: state})
|
||||
}
|
||||
effLoc := i18n.EffectiveLocale(loc)
|
||||
return tray.Snapshot{
|
||||
LocaleZh: loc == i18n.ZhCN,
|
||||
Locale: effLoc,
|
||||
LocaleZh: effLoc == i18n.ZhCN,
|
||||
VMs: items,
|
||||
}
|
||||
},
|
||||
@@ -799,35 +816,31 @@ func (a *App) startTray() {
|
||||
// result) are reported as a Windows notification from the tray icon.
|
||||
func (a *App) trayVMAction(name string, act tray.Action) {
|
||||
a.mu.Lock()
|
||||
zh := a.cfg.Locale == i18n.ZhCN
|
||||
rawLoc := a.cfg.Locale
|
||||
tm := a.trayMgr
|
||||
a.mu.Unlock()
|
||||
pick := func(cn, en string) string {
|
||||
if zh {
|
||||
return cn
|
||||
}
|
||||
return en
|
||||
}
|
||||
loc := i18n.EffectiveLocale(rawLoc)
|
||||
vars := i18n.Vars{"name": name}
|
||||
var err error
|
||||
var failTitle string
|
||||
switch act {
|
||||
case tray.ActStart:
|
||||
err, failTitle = a.StartVM(name), pick("无法启动 ", "Couldn't start ")+name
|
||||
err, failTitle = a.StartVM(name), i18n.M(loc, "tray.notify.start_fail", vars)
|
||||
case tray.ActStop:
|
||||
err, failTitle = a.StopVM(name, false), pick("无法关机 ", "Couldn't shut down ")+name
|
||||
err, failTitle = a.StopVM(name, false), i18n.M(loc, "tray.notify.stop_fail", vars)
|
||||
case tray.ActForceStop:
|
||||
err, failTitle = a.StopVM(name, true), pick("无法强制关机 ", "Couldn't force shut down ")+name
|
||||
err, failTitle = a.StopVM(name, true), i18n.M(loc, "tray.notify.force_stop_fail", vars)
|
||||
case tray.ActRestart:
|
||||
err, failTitle = a.RestartVM(name), pick("无法重启 ", "Couldn't restart ")+name
|
||||
err, failTitle = a.RestartVM(name), i18n.M(loc, "tray.notify.restart_fail", vars)
|
||||
case tray.ActShowWindow:
|
||||
err, failTitle = a.FocusVMWindow(name), pick("找不到 ", "Couldn't find the window of ")+name+pick(" 的窗口", "")
|
||||
err, failTitle = a.FocusVMWindow(name), i18n.M(loc, "tray.notify.focus_fail", vars)
|
||||
case tray.ActScreenshot:
|
||||
if err = a.CopyVMScreenshot(name); err == nil && tm != nil {
|
||||
tm.Notify(pick("已复制屏幕截图", "Screenshot copied"), name, false)
|
||||
tm.Notify(i18n.T(loc, "tray.notify.screenshot_ok"), name, false)
|
||||
}
|
||||
failTitle = pick("截图失败:", "Screenshot failed: ") + name
|
||||
failTitle = i18n.M(loc, "tray.notify.screenshot_fail", vars)
|
||||
case tray.ActSharedFolder:
|
||||
err, failTitle = a.OpenSharedFolder(name), pick("无法打开共享文件夹", "Couldn't open the shared folder")
|
||||
err, failTitle = a.OpenSharedFolder(name), i18n.T(loc, "tray.notify.shared_fail")
|
||||
case tray.ActOpenInApp:
|
||||
a.ShowMainWindow()
|
||||
if a.ctx != nil {
|
||||
@@ -842,22 +855,80 @@ func (a *App) trayVMAction(name string, act tray.Action) {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) SetDataRoot(dir string) error {
|
||||
dir = strings.TrimSpace(dir)
|
||||
if dir == "" {
|
||||
return fmt.Errorf("data root cannot be empty")
|
||||
}
|
||||
func (a *App) resetDataRootCaches() {
|
||||
a.mu.Lock()
|
||||
a.cfg.DataRoot = dir
|
||||
err := a.cfg.EnsureDirs()
|
||||
if err == nil {
|
||||
err = config.Save("", a.cfg)
|
||||
}
|
||||
if err == nil {
|
||||
err = config.SaveLocation(dir)
|
||||
a.lastVMs = nil
|
||||
a.lastVMsAt = time.Time{}
|
||||
a.diskPaths = make(map[string]cachedDiskPath)
|
||||
a.procSamples = make(map[string]host.ProcessSample)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
func (a *App) SetDataRoot(dir string) error {
|
||||
a.mu.Lock()
|
||||
loc := i18n.EffectiveLocale(a.cfg.Locale)
|
||||
prev := a.cfg.DataRoot
|
||||
curLocalePref := a.cfg.Locale
|
||||
curAutoPin := a.cfg.AutoPinPCores
|
||||
curRuntimeChannel := a.cfg.RuntimeChannel
|
||||
curMinToTray := a.cfg.MinimizeToTray
|
||||
for _, v := range a.lastVMs {
|
||||
if v.State == "running" {
|
||||
a.mu.Unlock()
|
||||
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
|
||||
}
|
||||
}
|
||||
a.mu.Unlock()
|
||||
return err
|
||||
|
||||
for _, t := range tasks.list() {
|
||||
if t.Status == TaskRunning {
|
||||
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_TASKS", "err.dataroot.busy_tasks", nil, nil)
|
||||
}
|
||||
}
|
||||
|
||||
dir = filepath.Clean(strings.TrimSpace(dir))
|
||||
if err := validateDataRoot(dir, loc); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
nextCfg, err := config.Load(cfgPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
}
|
||||
nextCfg.DataRoot = dir
|
||||
if _, statErr := os.Stat(cfgPath); statErr != nil {
|
||||
nextCfg.Locale = curLocalePref
|
||||
nextCfg.AutoPinPCores = curAutoPin
|
||||
nextCfg.RuntimeChannel = curRuntimeChannel
|
||||
nextCfg.MinimizeToTray = curMinToTray
|
||||
}
|
||||
if err := nextCfg.EnsureDirs(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writable(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := config.Save(cfgPath, nextCfg); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := config.SaveLocation(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
a.cfg = nextCfg
|
||||
a.mu.Unlock()
|
||||
|
||||
if filepath.Clean(prev) != filepath.Clean(dir) {
|
||||
a.resetDataRootCaches()
|
||||
a.reloadPlugins()
|
||||
a.wakePoll()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) PickDirectory(title string) (string, error) {
|
||||
@@ -920,7 +991,7 @@ func (a *App) UseRuntime(commit string) error {
|
||||
func (a *App) RemoveRuntime(commit string) error {
|
||||
a.mu.Lock()
|
||||
cfg := a.cfg
|
||||
loc := a.cfg.Locale
|
||||
loc := i18n.EffectiveLocale(a.cfg.Locale)
|
||||
ctx := a.ctx
|
||||
a.mu.Unlock()
|
||||
|
||||
@@ -947,7 +1018,7 @@ func (a *App) RemoveRuntime(commit string) error {
|
||||
func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue {
|
||||
a.mu.Lock()
|
||||
root := a.cfg.DataRoot
|
||||
loc := a.cfg.Locale
|
||||
loc := i18n.EffectiveLocale(a.cfg.Locale)
|
||||
a.mu.Unlock()
|
||||
issues := reims.ValidateCreateLocalized(opts, host.Inspect(root), loc)
|
||||
// reims-ctl refuses a name already registered; say so before the create runs.
|
||||
|
||||
@@ -37,8 +37,9 @@ var appUpdateReady struct {
|
||||
|
||||
func (a *App) locale() i18n.Locale {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.cfg.Locale
|
||||
raw := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
return i18n.EffectiveLocale(raw)
|
||||
}
|
||||
|
||||
func (a *App) updateErr(key string, args ...any) error {
|
||||
|
||||
+12
-10
@@ -19,17 +19,19 @@ import (
|
||||
// so the source golden disk is never mutated while the clone gets its own fresh
|
||||
// OpenCore identity (SMBIOS/serial/MAC) via `reims-ctl create --disk --disk-mode in-place`.
|
||||
func (a *App) CloneVMCoW(sourceName, cloneName string) error {
|
||||
loc := a.locale()
|
||||
cloneName = strings.TrimSpace(cloneName)
|
||||
if cloneName == "" {
|
||||
return fmt.Errorf("clone VM name is required")
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_EMPTY_NAME", "err.clone.missing_name", nil, nil)
|
||||
}
|
||||
if strings.EqualFold(sourceName, cloneName) {
|
||||
return fmt.Errorf("clone name must differ from source VM")
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_SAME_NAME", "err.clone.same_name", nil, nil)
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
cfgCopy.Locale = loc
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -42,41 +44,41 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, sourceName, src) {
|
||||
return fmt.Errorf("stop %s before deriving a CoW clone so the backing disk is clean", sourceName)
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_RUNNING", "err.clone.source_running", i18n.Vars{"name": sourceName}, nil)
|
||||
}
|
||||
if src.HasInstaller {
|
||||
return fmt.Errorf("exit recovery mode on %s before deriving a CoW clone", sourceName)
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_RECOVERY", "err.clone.in_recovery", i18n.Vars{"name": sourceName}, nil)
|
||||
}
|
||||
srcDisk := src.Disk
|
||||
if srcDisk != "" && !filepath.IsAbs(srcDisk) && src.Directory != "" {
|
||||
srcDisk = filepath.Join(src.Directory, srcDisk)
|
||||
}
|
||||
if srcDisk == "" {
|
||||
return fmt.Errorf("source VM %s has no disk path", sourceName)
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_NO_DISK", "err.clone.no_disk", i18n.Vars{"name": sourceName}, nil)
|
||||
}
|
||||
if _, err := os.Stat(srcDisk); err != nil {
|
||||
return fmt.Errorf("source disk not found (%s): %w", srcDisk, err)
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_DISK_MISSING", "err.clone.disk_missing", i18n.Vars{"path": srcDisk}, err)
|
||||
}
|
||||
|
||||
// Validate clone name and check for name collisions.
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
nameCheck := reims.ValidateCreateLocalized(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, cfgCopy.Locale)
|
||||
nameCheck := reims.ValidateCreateLocalized(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, loc)
|
||||
for _, iss := range nameCheck {
|
||||
if iss.Field == "name" {
|
||||
return fmt.Errorf("%s", iss.Message)
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_INVALID_NAME", "validate."+iss.Code, i18n.Vars{"name": cloneName}, nil)
|
||||
}
|
||||
}
|
||||
if existing, err := c.List(ctx); err == nil {
|
||||
for _, vm := range existing {
|
||||
if strings.EqualFold(vm.Name, cloneName) {
|
||||
return fmt.Errorf("%s", i18n.T(cfgCopy.Locale, "validate.name_taken", cloneName))
|
||||
return i18n.NewCodedError(loc, "E_VM_NAME_TAKEN", "validate.name_taken", i18n.Vars{"name": cloneName}, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
overlayPath := filepath.Join(cfgCopy.ImagesDir(), fmt.Sprintf("cow-%s.qcow2", cloneName))
|
||||
if _, err := os.Stat(overlayPath); err == nil {
|
||||
return fmt.Errorf("CoW overlay file already exists: %s", overlayPath)
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_OVERLAY_EXISTS", "err.clone.overlay_exists", i18n.Vars{"path": overlayPath}, nil)
|
||||
}
|
||||
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(cloneName, line) })
|
||||
|
||||
@@ -2,7 +2,6 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
@@ -37,8 +36,10 @@ func (a *App) installGuideEnabled() bool {
|
||||
|
||||
func (a *App) guidePreferences() (i18n.Locale, installguide.Theme) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.cfg.Locale, a.themeMode
|
||||
rawLoc := a.cfg.Locale
|
||||
th := a.themeMode
|
||||
a.mu.Unlock()
|
||||
return i18n.EffectiveLocale(rawLoc), th
|
||||
}
|
||||
|
||||
func (a *App) bindGuideEvents(ctx context.Context) {
|
||||
@@ -83,6 +84,7 @@ func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manag
|
||||
Name: name,
|
||||
PID: uint32(pid),
|
||||
Locale: loc,
|
||||
GuestLang: d.GuestLang,
|
||||
Kind: kind,
|
||||
ToolsAttached: reims.HasGuestToolsArgs(d.ExtraArgs),
|
||||
}
|
||||
@@ -112,10 +114,8 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
if loc, _ := a.guidePreferences(); loc == i18n.ZhCN {
|
||||
return fmt.Errorf("虚拟机 %s 的运行状态已改变", name)
|
||||
}
|
||||
return fmt.Errorf("the running instance of %s has changed", name)
|
||||
loc, _ := a.guidePreferences()
|
||||
return i18n.NewCodedError(loc, "E_GUIDE_INSTANCE_CHANGED", "guide.err.instance_changed", i18n.Vars{"name": name}, nil)
|
||||
}
|
||||
g.TypeText = func(text string) error {
|
||||
if err := checkBoot(); err != nil {
|
||||
@@ -151,10 +151,8 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei
|
||||
stopped, err := a.restartVM(name)
|
||||
if stopped && err != nil {
|
||||
// The guest window has closed, so report start failures via the tray.
|
||||
title := "Could not restart VM: " + name
|
||||
if loc, _ := a.guidePreferences(); loc == i18n.ZhCN {
|
||||
title = "未能重启虚拟机:" + name
|
||||
}
|
||||
loc, _ := a.guidePreferences()
|
||||
title := i18n.M(loc, "guide.err.restart_failed", i18n.Vars{"name": name})
|
||||
a.emitLog(name, title+": "+err.Error())
|
||||
a.mu.Lock()
|
||||
tm := a.trayMgr
|
||||
|
||||
@@ -56,6 +56,7 @@ func (a *App) initPlugins() {
|
||||
HostVersion: version.Version,
|
||||
SafeMode: safeMode,
|
||||
RedactFn: reims.RedactText,
|
||||
LocaleFn: a.locale,
|
||||
Logger: func(source, line string) {
|
||||
a.emitLog(source, line)
|
||||
},
|
||||
@@ -208,6 +209,33 @@ func (a *App) shutdownPlugins() {
|
||||
}
|
||||
}
|
||||
|
||||
// reloadPlugins tears down the existing Plugin Manager (if running) and
|
||||
// re-initializes plugins and language packs against the current a.cfg.DataRoot.
|
||||
func (a *App) reloadPlugins() {
|
||||
a.mu.Lock()
|
||||
hadPlugins := a.pluginMgr != nil
|
||||
hasCtx := a.ctx != nil
|
||||
ib := a.imeBridge
|
||||
a.imeBridge = nil
|
||||
a.mu.Unlock()
|
||||
if ib != nil {
|
||||
ib.Close()
|
||||
}
|
||||
if !hadPlugins && !hasCtx {
|
||||
// Headless unit test without initialized app runtime: load static locale packs only.
|
||||
a.mu.Lock()
|
||||
dr := ""
|
||||
if a.cfg != nil {
|
||||
dr = a.cfg.DataRoot
|
||||
}
|
||||
a.mu.Unlock()
|
||||
plugin.LoadStaticLocalePacks(dr)
|
||||
return
|
||||
}
|
||||
a.shutdownPlugins()
|
||||
a.initPlugins()
|
||||
}
|
||||
|
||||
func (a *App) syncLocales() {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
@@ -216,7 +244,23 @@ func (a *App) syncLocales() {
|
||||
i18n.SetPluginCatalogs(nil)
|
||||
return
|
||||
}
|
||||
_, backendPacks := mgr.ResolvedLocalePacks()
|
||||
uiPacks, backendPacks := mgr.ResolvedLocalePacks()
|
||||
if len(uiPacks) > 0 {
|
||||
if backendPacks == nil {
|
||||
backendPacks = make(map[i18n.Locale]i18n.PluginCatalog)
|
||||
}
|
||||
for _, up := range uiPacks {
|
||||
if !up.HasUIMessages {
|
||||
continue
|
||||
}
|
||||
loc := i18n.Locale(up.Locale)
|
||||
if _, exists := backendPacks[loc]; !exists {
|
||||
backendPacks[loc] = i18n.PluginCatalog{
|
||||
Fallback: i18n.Locale(up.Fallback),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
i18n.SetPluginCatalogs(backendPacks)
|
||||
}
|
||||
|
||||
@@ -229,6 +273,7 @@ func (a *App) syncRuntimeKinds(kr *rt.KindRegistry, reg *plugin.Registry) {
|
||||
activeKinds[rk.Kind] = true
|
||||
_ = kr.Register(rt.KindSpec{
|
||||
Kind: rk.Kind,
|
||||
Name: rk.Name,
|
||||
NameZh: rk.Name.ZhCN,
|
||||
NameEn: rk.Name.EnUS,
|
||||
RequiredFiles: rk.RequiredFiles,
|
||||
@@ -466,7 +511,7 @@ func (a *App) ListPlugins() []plugin.PluginInfo {
|
||||
if mgr == nil {
|
||||
return nil
|
||||
}
|
||||
return mgr.Registry().List()
|
||||
return mgr.LocalizePluginInfos(mgr.Registry().List())
|
||||
}
|
||||
|
||||
func (a *App) InstallPluginArchive(archivePath string) (*plugin.PluginInfo, error) {
|
||||
@@ -571,11 +616,11 @@ func (a *App) GetPluginUIContributions() PluginUIContributions {
|
||||
out := PluginUIContributions{
|
||||
SafeMode: mgr.SafeMode(),
|
||||
CrashDetected: mgr.CrashDetected(),
|
||||
Menus: reg.Menus(""),
|
||||
VMCards: reg.VMCards(),
|
||||
SettingsPages: reg.SettingsPages(),
|
||||
StatusItems: reg.StatusItems(),
|
||||
Panels: reg.Panels(""),
|
||||
Menus: mgr.LocalizeMenus(reg.Menus("")),
|
||||
VMCards: mgr.LocalizeVMCards(reg.VMCards()),
|
||||
SettingsPages: mgr.LocalizeSettingsPages(reg.SettingsPages()),
|
||||
StatusItems: mgr.LocalizeStatusItems(reg.StatusItems()),
|
||||
Panels: mgr.LocalizePanels(reg.Panels("")),
|
||||
VMTemplates: reg.VMTemplates(),
|
||||
Themes: reg.Themes(),
|
||||
Locales: uiLocales,
|
||||
@@ -800,6 +845,16 @@ func (a *App) PanelBridgeCall(pluginID, method string, params map[string]any) (a
|
||||
return nil, fmt.Errorf("plugin %q has no active panel", pluginID)
|
||||
}
|
||||
switch method {
|
||||
case "i18n.getBundle":
|
||||
if err := mgr.Broker().AllowRate(pluginID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
eff := mgr.CurrentLocale()
|
||||
return map[string]any{
|
||||
"locale": string(eff),
|
||||
"dir": i18n.DirOf(eff),
|
||||
"messages": mgr.PluginL10nBundle(pluginID, eff),
|
||||
}, nil
|
||||
case "vm.list":
|
||||
if err := mgr.Broker().Authorize(pluginID, "vm:read"); err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -130,9 +130,18 @@ func (a *App) CompleteSetup(dir string) error {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
prevRoot := ""
|
||||
if a.cfg != nil {
|
||||
prevRoot = a.cfg.DataRoot
|
||||
}
|
||||
a.cfg = cfg
|
||||
a.needsSetup = false
|
||||
a.mu.Unlock()
|
||||
if filepath.Clean(prevRoot) != filepath.Clean(dir) {
|
||||
a.resetDataRootCaches()
|
||||
a.reloadPlugins()
|
||||
}
|
||||
a.wakePoll()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
@@ -55,6 +56,18 @@ func (a *App) DeleteSnapshot(name, snapName string) error {
|
||||
}
|
||||
|
||||
func (a *App) runSnapshotOp(name, flag, snapName, verb string) error {
|
||||
loc := a.locale()
|
||||
cleanSnap := strings.TrimSpace(snapName)
|
||||
if cleanSnap == "" {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_NAME_EMPTY", "err.snapshot.name_empty", nil, nil)
|
||||
}
|
||||
if len([]rune(cleanSnap)) > 64 {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_NAME_TOO_LONG", "err.snapshot.name_too_long", nil, nil)
|
||||
}
|
||||
if _, err := reims.ValidateSnapshotName(cleanSnap); err != nil {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_NAME_INVALID", "err.snapshot.name_invalid", nil, err)
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
@@ -70,20 +83,20 @@ func (a *App) runSnapshotOp(name, flag, snapName, verb string) error {
|
||||
return err
|
||||
}
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return fmt.Errorf("stop %s before managing restore points", name)
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_RUNNING", "err.snapshot.vm_running", i18n.Vars{"name": name}, nil)
|
||||
}
|
||||
diskPath := resolveVMDiskPath(d)
|
||||
if diskPath == "" {
|
||||
return fmt.Errorf("VM %s has no disk path", name)
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_NO_DISK", "err.clone.no_disk", i18n.Vars{"name": name}, nil)
|
||||
}
|
||||
if !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
|
||||
return fmt.Errorf("restore points are only supported on .qcow2 disks")
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_QCOW2_ONLY", "err.snapshot.qcow2_only", nil, nil)
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfgCopy, *active)
|
||||
if err := reims.RunDiskSnapshot(ctx, active.QemuImgPath(), env, flag, snapName, diskPath); err != nil {
|
||||
return err
|
||||
if err := reims.RunDiskSnapshot(ctx, active.QemuImgPath(), env, flag, cleanSnap, diskPath); err != nil {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_QEMU_IMG", "err.snapshot.qemu_img_failed", i18n.Vars{"snap": cleanSnap}, err)
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("%s %q", verb, strings.TrimSpace(snapName)))
|
||||
a.emitLog(name, fmt.Sprintf("%s %q", verb, cleanSnap))
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
|
||||
@@ -164,15 +164,17 @@ func upsertSSHConfigBlock(cfgPath, vmName, alias string, port int, user string)
|
||||
endMark := fmt.Sprintf("# <<< reims-go:%s <<<", vmName)
|
||||
|
||||
var block strings.Builder
|
||||
block.WriteString(startMark + "\n")
|
||||
block.WriteString(fmt.Sprintf("Host %s\n", alias))
|
||||
block.WriteString(startMark)
|
||||
block.WriteByte('\n')
|
||||
fmt.Fprintf(&block, "Host %s\n", alias)
|
||||
block.WriteString(" HostName 127.0.0.1\n")
|
||||
block.WriteString(fmt.Sprintf(" Port %d\n", port))
|
||||
fmt.Fprintf(&block, " Port %d\n", port)
|
||||
if user != "" {
|
||||
block.WriteString(fmt.Sprintf(" User %s\n", user))
|
||||
fmt.Fprintf(&block, " User %s\n", user)
|
||||
}
|
||||
block.WriteString(" StrictHostKeyChecking accept-new\n")
|
||||
block.WriteString(endMark + "\n")
|
||||
block.WriteString(endMark)
|
||||
block.WriteByte('\n')
|
||||
|
||||
existingBytes, err := os.ReadFile(cfgPath)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
|
||||
+38
-62
@@ -67,10 +67,6 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
|
||||
}{id: myID, cancel: cancel}
|
||||
vmMonitors.mu.Unlock()
|
||||
|
||||
a.mu.Lock()
|
||||
loc := a.cfg.Locale
|
||||
a.mu.Unlock()
|
||||
|
||||
go func() {
|
||||
defer func() {
|
||||
cancel()
|
||||
@@ -107,6 +103,7 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-logTicker.C:
|
||||
loc := a.locale()
|
||||
for _, line := range serial.read(serialPath) {
|
||||
a.emitPluginLogLine(name, "serial", line)
|
||||
if key, msg := parseSerialMilestone(loc, line); msg != "" && !seenEvents[key] {
|
||||
@@ -127,13 +124,10 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
|
||||
}
|
||||
}
|
||||
case <-hbTicker.C:
|
||||
loc := a.locale()
|
||||
pid, running := a.currentVMPID(ctx, name)
|
||||
if !running {
|
||||
if loc == i18n.ZhCN {
|
||||
a.emitLog(name, "[状态] 虚拟机进程已退出")
|
||||
} else {
|
||||
a.emitLog(name, "[state] VM process exited")
|
||||
}
|
||||
a.emitLog(name, i18n.T(loc, "monitor.exited"))
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
@@ -177,11 +171,7 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
|
||||
}
|
||||
if idleStreak >= 3 && !stallWarned {
|
||||
stallWarned = true
|
||||
if loc == i18n.ZhCN {
|
||||
a.emitLog(name, "[警告] 连续 90 秒几乎无 CPU 与磁盘写入,虚拟机可能停在启动或重启阶段;可切到「QEMU」页签排查,或下次引导时按住 Win+V 查看内核输出")
|
||||
} else {
|
||||
a.emitLog(name, "[warn] Almost no CPU or disk activity for 90s; VM may be stalled during boot/reboot. Check the QEMU log tab or hold Win+V on next boot for verbose output")
|
||||
}
|
||||
a.emitLog(name, i18n.T(loc, "monitor.stall_warn"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -272,15 +262,9 @@ func (t *logTail) read(path string) []string {
|
||||
func parseSerialMilestone(loc i18n.Locale, line string) (key, msg string) {
|
||||
switch {
|
||||
case strings.Contains(line, "BdsDxe: starting Boot"):
|
||||
if loc == i18n.ZhCN {
|
||||
return "serial:boot", "[引导] UEFI 正在启动 OpenCore 引导程序"
|
||||
}
|
||||
return "serial:boot", "[boot] UEFI starting OpenCore bootloader"
|
||||
return "serial:boot", i18n.T(loc, "monitor.serial.boot")
|
||||
case strings.Contains(line, "#[EB|LOG:HANDOFF TO XNU]"), strings.Contains(line, "End of efiboot serial output"):
|
||||
if loc == i18n.ZhCN {
|
||||
return "serial:xnu", "[引导] OpenCore 已交接 macOS 内核(XNU 正在加载系统与驱动)"
|
||||
}
|
||||
return "serial:xnu", "[boot] OpenCore handed off to macOS kernel (XNU loading)"
|
||||
return "serial:xnu", i18n.T(loc, "monitor.serial.xnu")
|
||||
default:
|
||||
return "", ""
|
||||
}
|
||||
@@ -296,28 +280,16 @@ func parseQemuMilestone(loc i18n.Locale, line string) (key, msg string) {
|
||||
if semi := strings.IndexByte(rest, ';'); semi >= 0 {
|
||||
rest = rest[:semi]
|
||||
}
|
||||
if loc == i18n.ZhCN {
|
||||
return "qemu:gpu", "[图形] vGPU 已初始化:" + strings.TrimSpace(rest)
|
||||
}
|
||||
return "qemu:gpu", "[gpu] vGPU initialized: " + strings.TrimSpace(rest)
|
||||
return "qemu:gpu", i18n.M(loc, "monitor.qemu.gpu", i18n.Vars{"device": strings.TrimSpace(rest)})
|
||||
}
|
||||
if strings.Contains(line, "windows open through SDL") {
|
||||
if loc == i18n.ZhCN {
|
||||
return "qemu:window", "[窗口] 虚拟机显示窗口已打开"
|
||||
}
|
||||
return "qemu:window", "[window] VM display window opened"
|
||||
return "qemu:window", i18n.T(loc, "monitor.qemu.window")
|
||||
}
|
||||
if strings.Contains(line, "the device was reset") {
|
||||
if loc == i18n.ZhCN {
|
||||
return "qemu:reset", "[图形] vGPU 设备已重置"
|
||||
}
|
||||
return "qemu:reset", "[gpu] vGPU device reset"
|
||||
return "qemu:reset", i18n.T(loc, "monitor.qemu.reset")
|
||||
}
|
||||
if strings.Contains(line, "the control completion ring is full") {
|
||||
if loc == i18n.ZhCN {
|
||||
return "qemu:ring-full", "[图形] 图形事件环短暂阻塞(常见于抹除硬盘或大块磁盘写入期间),请稍候 10–30 秒等待自动恢复,无需强制关闭"
|
||||
}
|
||||
return "qemu:ring-full", "[gpu] Graphics completion ring briefly stalled (typical during disk erase or heavy disk I/O); wait 10–30s for it to recover automatically"
|
||||
return "qemu:ring-full", i18n.T(loc, "monitor.qemu.ring_full")
|
||||
}
|
||||
// Known benign WHPX advisories: keep out of the activity log so they don't look like errors.
|
||||
if strings.Contains(line, "no pre-fault of the pool") ||
|
||||
@@ -337,21 +309,24 @@ func parseQemuMilestone(loc i18n.Locale, line string) (key, msg string) {
|
||||
|
||||
func formatBootHeartbeat(loc i18n.Locale, elapsed time.Duration, diskBytes, diskDelta int64, cpuPct float64) string {
|
||||
dur := fmt.Sprintf("%dm%02ds", int(elapsed.Minutes()), int(elapsed.Seconds())%60)
|
||||
diskStr := fmt.Sprintf("%.2f GB", float64(diskBytes)/(1024*1024*1024))
|
||||
diskStr := i18n.FormatNumber(loc, float64(diskBytes)/(1024*1024*1024), 2) + " GB"
|
||||
deltaStr := ""
|
||||
if diskDelta >= 1024*1024 {
|
||||
deltaStr = fmt.Sprintf(" (+%.1f MB)", float64(diskDelta)/(1024*1024))
|
||||
}
|
||||
if loc == i18n.ZhCN {
|
||||
if cpuPct >= 0 {
|
||||
return fmt.Sprintf("[状态] 运行中(%s)· 磁盘占用 %s%s · QEMU CPU %.0f%%", dur, diskStr, deltaStr, cpuPct)
|
||||
}
|
||||
return fmt.Sprintf("[状态] 运行中(%s)· 磁盘占用 %s%s", dur, diskStr, deltaStr)
|
||||
deltaStr = " (+" + i18n.FormatNumber(loc, float64(diskDelta)/(1024*1024), 1) + " MB)"
|
||||
}
|
||||
if cpuPct >= 0 {
|
||||
return fmt.Sprintf("[state] Running (%s) · disk %s%s · QEMU CPU %.0f%%", dur, diskStr, deltaStr, cpuPct)
|
||||
return i18n.M(loc, "monitor.heartbeat.cpu", i18n.Vars{
|
||||
"dur": dur,
|
||||
"disk": diskStr,
|
||||
"delta": deltaStr,
|
||||
"cpu": cpuPct,
|
||||
})
|
||||
}
|
||||
return fmt.Sprintf("[state] Running (%s) · disk %s%s", dur, diskStr, deltaStr)
|
||||
return i18n.M(loc, "monitor.heartbeat.nocpu", i18n.Vars{
|
||||
"dur": dur,
|
||||
"disk": diskStr,
|
||||
"delta": deltaStr,
|
||||
})
|
||||
}
|
||||
|
||||
func fileSizeBytes(path string) int64 {
|
||||
@@ -364,10 +339,11 @@ func fileSizeBytes(path string) int64 {
|
||||
|
||||
func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Report, qmpAddr string) {
|
||||
a.mu.Lock()
|
||||
loc := a.cfg.Locale
|
||||
rawLoc := a.cfg.Locale
|
||||
rtCommit := a.cfg.ActiveRuntime
|
||||
pinPCores := a.cfg.AutoPinPCores
|
||||
a.mu.Unlock()
|
||||
loc := i18n.EffectiveLocale(rawLoc)
|
||||
if rtCommit == "" {
|
||||
rtCommit = "auto"
|
||||
}
|
||||
@@ -380,19 +356,19 @@ func (a *App) emitStartSummary(name string, detail reims.VMDetail, rep host.Repo
|
||||
irqMode = "on"
|
||||
}
|
||||
pinStr := vmstart.AffinitySummary(loc, rep, detail.Directory, pinPCores, detail.CPUs)
|
||||
if loc == i18n.ZhCN {
|
||||
coldStr := "关闭"
|
||||
if qmpAddr != "" {
|
||||
coldStr = "开启"
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("[启动] 运行时 %s · %d 核 / %s(可用提交内存 %.1f GB)· 图形 %s · 磁盘 %s · irqchip=%s · 核心映射=%s · Win10冷重启=%s",
|
||||
rtCommit, detail.CPUs, detail.Memory, rep.CommitAvailGB, detail.Graphics, strings.ToUpper(detail.DiskController), irqMode, pinStr, coldStr))
|
||||
return
|
||||
}
|
||||
coldStr := "off"
|
||||
coldStr := i18n.T(loc, "monitor.start.off")
|
||||
if qmpAddr != "" {
|
||||
coldStr = "on"
|
||||
coldStr = i18n.T(loc, "monitor.start.on")
|
||||
}
|
||||
a.emitLog(name, fmt.Sprintf("[start] runtime %s · %d vCPU / %s (commit free %.1f GB) · graphics %s · disk %s · irqchip=%s · affinity=%s · Win10-cold-reboot=%s",
|
||||
rtCommit, detail.CPUs, detail.Memory, rep.CommitAvailGB, detail.Graphics, strings.ToUpper(detail.DiskController), irqMode, pinStr, coldStr))
|
||||
a.emitLog(name, i18n.M(loc, "monitor.start.summary", i18n.Vars{
|
||||
"rt": rtCommit,
|
||||
"cpus": detail.CPUs,
|
||||
"mem": detail.Memory,
|
||||
"avail": rep.CommitAvailGB,
|
||||
"gfx": detail.Graphics,
|
||||
"disk": strings.ToUpper(detail.DiskController),
|
||||
"irq": irqMode,
|
||||
"pin": pinStr,
|
||||
"cold": coldStr,
|
||||
}))
|
||||
}
|
||||
+58
-78
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
@@ -30,8 +31,9 @@ import (
|
||||
|
||||
// Main runs one command and returns the process exit code.
|
||||
func Main(args []string) int {
|
||||
if err := run(args); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||
loc, err := run(args)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: %s\n", i18n.FormatCLIError(loc, err))
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
@@ -44,12 +46,15 @@ func IsCommand(args []string) bool {
|
||||
return !isWindow
|
||||
}
|
||||
|
||||
func run(args []string) error {
|
||||
func run(args []string) (i18n.Locale, error) {
|
||||
fs := flag.NewFlagSet("reims-go", flag.ContinueOnError)
|
||||
langFlag := fs.String("lang", "", "UI/CLI language: zh-CN | en-US")
|
||||
fs.SetOutput(io.Discard)
|
||||
langFlag := fs.String("lang", "", "UI/CLI language: auto | zh-CN | en-US | <BCP-47> | en-XA")
|
||||
dataRootFlag := fs.String("data-root", "", "Override reims-go data root directory")
|
||||
helpFlag := fs.Bool("help", false, "Show CLI usage")
|
||||
hFlag := fs.Bool("h", false, "Show CLI usage")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
return i18n.Detect(), err
|
||||
}
|
||||
|
||||
cfgPath := ""
|
||||
@@ -58,106 +63,81 @@ func run(args []string) error {
|
||||
}
|
||||
cfg, err := config.Load(cfgPath)
|
||||
if err != nil {
|
||||
return err
|
||||
return i18n.Detect(), err
|
||||
}
|
||||
if *dataRootFlag != "" {
|
||||
cfg.DataRoot = *dataRootFlag
|
||||
}
|
||||
// Load enabled static language packs from <DataRoot>/plugins before resolving
|
||||
// effective locale so "auto" and custom --lang tags (e.g. ja-JP, zh-TW) work in CLI.
|
||||
plugin.LoadStaticLocalePacks(cfg.DataRoot)
|
||||
|
||||
if *langFlag != "" {
|
||||
cfg.Locale = i18n.Normalize(*langFlag)
|
||||
cfg.Locale = i18n.ParsePreference(*langFlag)
|
||||
}
|
||||
loc := cfg.Locale
|
||||
loc := i18n.EffectiveLocale(cfg.Locale)
|
||||
cfg.Locale = loc
|
||||
|
||||
rest := fs.Args()
|
||||
if len(rest) == 0 {
|
||||
if len(rest) == 0 || *helpFlag || *hFlag {
|
||||
printUsage(loc)
|
||||
return nil
|
||||
return loc, nil
|
||||
}
|
||||
|
||||
switch rest[0] {
|
||||
case "doctor":
|
||||
return cmdDoctor(cfg, loc, rest[1:])
|
||||
return loc, cmdDoctor(cfg, loc, rest[1:])
|
||||
case "runtime":
|
||||
return cmdRuntime(cfg, loc, rest[1:])
|
||||
return loc, cmdRuntime(cfg, loc, rest[1:])
|
||||
case "vm":
|
||||
return cmdVM(cfg, loc, rest[1:], *dataRootFlag == "")
|
||||
return loc, cmdVM(cfg, loc, rest[1:], *dataRootFlag == "")
|
||||
case "installer":
|
||||
return cmdInstaller(cfg, loc, rest[1:])
|
||||
return loc, cmdInstaller(cfg, loc, rest[1:])
|
||||
case "plugin":
|
||||
return cmdPlugin(cfg, loc, rest[1:])
|
||||
return loc, cmdPlugin(cfg, loc, rest[1:])
|
||||
case "version", "-v", "--version":
|
||||
fmt.Printf("reims-go %s\n", version.Version)
|
||||
return nil
|
||||
return loc, nil
|
||||
case "help", "-h", "--help":
|
||||
printUsage(loc)
|
||||
return nil
|
||||
return loc, nil
|
||||
default:
|
||||
return fmt.Errorf("unknown command %q", rest[0])
|
||||
return loc, fmt.Errorf("unknown command %q", rest[0])
|
||||
}
|
||||
}
|
||||
|
||||
func printUsage(loc i18n.Locale) {
|
||||
if loc == i18n.ZhCN {
|
||||
fmt.Println("reims-go - Windows 一站式免编译 reims-vgpu 启动器")
|
||||
fmt.Println("\n用法:")
|
||||
fmt.Println(" reims-go 打开界面(--background:只在托盘运行,不显示窗口)")
|
||||
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <命令> [参数]")
|
||||
fmt.Println("\n 在交互式 PowerShell / cmd 中提示符会先返回;要等命令结束并拿到退出码,请加 | Out-Host 或用管道。")
|
||||
fmt.Println("\n命令:")
|
||||
fmt.Println(" doctor 宿主机环境体检(WHPX / 显卡 ICD / P-E 核 / 磁盘 / 运行时)")
|
||||
fmt.Println(" runtime available 列出 GitHub 上发布的运行时(--alpha 含 alpha 版)")
|
||||
fmt.Println(" runtime fetch [commit] 在线下载、校验并安装运行时(默认最新;Ctrl+C 暂停,再次运行续传)")
|
||||
fmt.Println(" runtime install <archive> 导入并校验本地运行时包(.tar.zst 或 .zip)")
|
||||
fmt.Println(" runtime list 查看已安装的便携运行时版本")
|
||||
fmt.Println(" runtime use <commit> 切换当前激活运行时")
|
||||
fmt.Println(" runtime remove <commit> 删除未激活的旧运行时")
|
||||
fmt.Println(" vm list 列出已创建的虚拟机")
|
||||
fmt.Println(" vm create [options] <name> 创建 macOS 虚拟机(可指定目录/核数/内存/硬盘/显卡)")
|
||||
fmt.Println(" vm set [options] <name> 修改虚拟机配置(下次启动生效)")
|
||||
fmt.Println(" vm resize <name> <大小> 停机扩容虚拟磁盘(如 256G 或 +64G)")
|
||||
fmt.Println(" vm compact <name> 停机回收 .qcow2 磁盘未用空间")
|
||||
fmt.Println(" vm start <name> 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动")
|
||||
fmt.Println(" vm stop|eject <name> 停止 / 弹出安装盘")
|
||||
fmt.Println(" vm type <name> [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)")
|
||||
fmt.Println(" installer list 列出 Apple 提供的离线安装包版本(需联网)")
|
||||
fmt.Println(" installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)")
|
||||
fmt.Println(" installer cached 查看已下载的安装包及占用空间")
|
||||
fmt.Println(" installer delete <文件名> 删除已下载的安装包(正在使用或下载中的会被拒绝)")
|
||||
fmt.Println(" plugin list|install|link|enable|disable|remove|info|doctor|run")
|
||||
fmt.Println(" 管理内置扩展与第三方插件(含主题与驱动)")
|
||||
fmt.Println(" version 查看当前版本")
|
||||
return
|
||||
fmt.Println(i18n.T(loc, "cli.usage.header"))
|
||||
fmt.Println("\n" + i18n.T(loc, "cli.usage.section_usage"))
|
||||
fmt.Println(i18n.T(loc, "cli.usage.line_gui"))
|
||||
fmt.Println(i18n.T(loc, "cli.usage.line_cmd"))
|
||||
fmt.Println("\n" + i18n.T(loc, "cli.usage.ps_hint"))
|
||||
fmt.Println("\n" + i18n.T(loc, "cli.usage.section_commands"))
|
||||
for _, k := range []string{
|
||||
"cli.usage.cmd_doctor",
|
||||
"cli.usage.cmd_rt_avail",
|
||||
"cli.usage.cmd_rt_fetch",
|
||||
"cli.usage.cmd_rt_install",
|
||||
"cli.usage.cmd_rt_list",
|
||||
"cli.usage.cmd_rt_use",
|
||||
"cli.usage.cmd_rt_remove",
|
||||
"cli.usage.cmd_vm_list",
|
||||
"cli.usage.cmd_vm_create",
|
||||
"cli.usage.cmd_vm_set",
|
||||
"cli.usage.cmd_vm_resize",
|
||||
"cli.usage.cmd_vm_compact",
|
||||
"cli.usage.cmd_vm_start",
|
||||
"cli.usage.cmd_vm_stop",
|
||||
"cli.usage.cmd_vm_type",
|
||||
"cli.usage.cmd_inst_list",
|
||||
"cli.usage.cmd_inst_dl",
|
||||
"cli.usage.cmd_inst_cached",
|
||||
"cli.usage.cmd_inst_del",
|
||||
"cli.usage.cmd_plugin",
|
||||
"cli.usage.cmd_version",
|
||||
} {
|
||||
fmt.Println(i18n.T(loc, k))
|
||||
}
|
||||
fmt.Println("reims-go - Portable one-stop reims-vgpu launcher for Windows")
|
||||
fmt.Println("\nUsage:")
|
||||
fmt.Println(" reims-go Open the window (--background: tray only, no window)")
|
||||
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <command> [args]")
|
||||
fmt.Println("\n Interactive PowerShell / cmd return to the prompt early; pipe the output (e.g. | Out-Host)")
|
||||
fmt.Println(" to wait for the command and get its exit code.")
|
||||
fmt.Println("\nCommands:")
|
||||
fmt.Println(" doctor Inspect host (WHPX / Vulkan GPUs / P-E cores / disk / runtime)")
|
||||
fmt.Println(" runtime available List runtimes published on GitHub (--alpha includes alpha builds)")
|
||||
fmt.Println(" runtime fetch [commit] Download, verify and install a runtime (newest by default; Ctrl+C pauses)")
|
||||
fmt.Println(" runtime install <archive> Verify and install a local runtime package (.tar.zst or .zip)")
|
||||
fmt.Println(" runtime list List installed portable runtimes")
|
||||
fmt.Println(" runtime use <commit> Activate an installed runtime version")
|
||||
fmt.Println(" runtime remove <commit> Remove an inactive installed runtime version")
|
||||
fmt.Println(" vm list List virtual machines")
|
||||
fmt.Println(" vm create [options] <name> Create a macOS VM (custom dir, CPUs, RAM, disk size, GPU)")
|
||||
fmt.Println(" vm set [options] <name> Update VM settings (applies on next start)")
|
||||
fmt.Println(" vm resize <name> <size> Expand stopped VM disk (e.g. 256G or +64G)")
|
||||
fmt.Println(" vm compact <name> Compact stopped .qcow2 disk to reclaim unused space")
|
||||
fmt.Println(" vm start <name> Start a VM in the Reims-Go window process (launched in the tray if needed),")
|
||||
fmt.Println(" with clipboard and shared folders; with --data-root it starts in this process")
|
||||
fmt.Println(" vm stop|eject <name> Stop / eject installer")
|
||||
fmt.Println(" vm type <name> [text] Type text into a running VM as US-keyboard keys (stdin if no text)")
|
||||
fmt.Println(" installer list List offline macOS installers Apple offers (needs network)")
|
||||
fmt.Println(" installer download <ver> Download an offline installer (26.7.1, tahoe, latest; Ctrl+C pauses, rerun resumes)")
|
||||
fmt.Println(" installer cached List downloaded installers and the space they take")
|
||||
fmt.Println(" installer delete <name> Delete a downloaded installer (refused if in use or downloading)")
|
||||
fmt.Println(" plugin list|install|link|enable|disable|remove|info|doctor|run")
|
||||
fmt.Println(" Manage built-in extensions and third-party plugins")
|
||||
fmt.Println(" version Show current version")
|
||||
}
|
||||
|
||||
func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
|
||||
+110
-4
@@ -24,6 +24,9 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
|
||||
HostVersion: version.Version,
|
||||
SafeMode: safeMode,
|
||||
RedactFn: reims.RedactText,
|
||||
LocaleFn: func() i18n.Locale {
|
||||
return i18n.EffectiveLocale(cfg.Locale)
|
||||
},
|
||||
Logger: func(source, line string) {
|
||||
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
|
||||
},
|
||||
@@ -66,13 +69,14 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
|
||||
}
|
||||
_ = mgr.LoadExternal()
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
mgr.MarkBootComplete()
|
||||
|
||||
return mgr, router, nil
|
||||
}
|
||||
|
||||
func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("usage: reims-go plugin <list|install|link|enable|disable|remove|info|doctor|run>")
|
||||
return fmt.Errorf("usage: reims-go plugin <list|install|link|enable|disable|remove|info|doctor|locale|run>")
|
||||
}
|
||||
ctx := context.Background()
|
||||
switch args[0] {
|
||||
@@ -87,7 +91,7 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
return err
|
||||
}
|
||||
defer mgr.Close()
|
||||
list := mgr.Registry().List()
|
||||
list := mgr.LocalizePluginInfos(mgr.Registry().List())
|
||||
if *asJSON {
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
@@ -95,9 +99,10 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
}
|
||||
for _, p := range list {
|
||||
mark := " "
|
||||
if p.State == plugin.StateActive {
|
||||
switch p.State {
|
||||
case plugin.StateActive:
|
||||
mark = "*"
|
||||
} else if p.State == plugin.StateDegraded || p.State == plugin.StateFailed {
|
||||
case plugin.StateDegraded, plugin.StateFailed:
|
||||
mark = "!"
|
||||
}
|
||||
fmt.Printf("%s %-34s %-8s %-8s %-9s %-8s %s\n",
|
||||
@@ -273,6 +278,9 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
}
|
||||
return printDoctorFindings(loc, allFindings)
|
||||
|
||||
case "locale":
|
||||
return cmdPluginLocale(loc, args[1:])
|
||||
|
||||
case "run":
|
||||
if len(args) < 3 {
|
||||
return fmt.Errorf("usage: reims-go plugin run <id> <command> [key=value...]")
|
||||
@@ -316,3 +324,101 @@ func printDoctorFindings(loc i18n.Locale, findings []plugin.DoctorFinding) error
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cmdPluginLocale(loc i18n.Locale, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("usage: reims-go plugin locale <init|check> ...")
|
||||
}
|
||||
switch args[0] {
|
||||
case "init":
|
||||
// Allow flags either before or after the positional <bcp47-locale> argument.
|
||||
var flagArgs, posArgs []string
|
||||
rest := args[1:]
|
||||
for i := 0; i < len(rest); i++ {
|
||||
a := rest[i]
|
||||
if strings.HasPrefix(a, "-") {
|
||||
flagArgs = append(flagArgs, a)
|
||||
if !strings.Contains(a, "=") && i+1 < len(rest) && !strings.HasPrefix(rest[i+1], "-") {
|
||||
i++
|
||||
flagArgs = append(flagArgs, rest[i])
|
||||
}
|
||||
} else {
|
||||
posArgs = append(posArgs, a)
|
||||
}
|
||||
}
|
||||
fs := flag.NewFlagSet("plugin locale init", flag.ContinueOnError)
|
||||
outDir := fs.String("out", "", "Output directory for the scaffolded language pack")
|
||||
pluginID := fs.String("id", "", "Optional reverse-domain plugin ID (default: community.lang.<locale>)")
|
||||
forPlugin := fs.String("for", "", "Optional target plugin ID to scaffold pluginOverrides for")
|
||||
if err := fs.Parse(flagArgs); err != nil {
|
||||
return err
|
||||
}
|
||||
posArgs = append(posArgs, fs.Args()...)
|
||||
if len(posArgs) < 1 || strings.TrimSpace(*outDir) == "" {
|
||||
return fmt.Errorf("usage: reims-go plugin locale init <bcp47-locale> --out <dir> [--id <plugin.id>] [--for <target.plugin>]")
|
||||
}
|
||||
if err := plugin.InitLocalePack(plugin.LocaleInitOptions{
|
||||
Locale: posArgs[0],
|
||||
OutDir: *outDir,
|
||||
PluginID: *pluginID,
|
||||
ForPlugin: *forPlugin,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("[ok] scaffolded language pack (%s) in %s\n", posArgs[0], *outDir)
|
||||
return nil
|
||||
|
||||
case "check":
|
||||
var flagArgs, posArgs []string
|
||||
for _, a := range args[1:] {
|
||||
if strings.HasPrefix(a, "-") {
|
||||
flagArgs = append(flagArgs, a)
|
||||
} else {
|
||||
posArgs = append(posArgs, a)
|
||||
}
|
||||
}
|
||||
fs := flag.NewFlagSet("plugin locale check", flag.ContinueOnError)
|
||||
asJSON := fs.Bool("json", false, "Output structured JSON report")
|
||||
if err := fs.Parse(flagArgs); err != nil {
|
||||
return err
|
||||
}
|
||||
posArgs = append(posArgs, fs.Args()...)
|
||||
if len(posArgs) < 1 {
|
||||
return fmt.Errorf("usage: reims-go plugin locale check [--json] <dir>")
|
||||
}
|
||||
reports, findings, err := plugin.CheckLocalePack(posArgs[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *asJSON {
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(reports); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
for _, rep := range reports {
|
||||
fmt.Printf("Locale %s (%s): %d/%d translated (%.1f%%)\n",
|
||||
rep.Locale, rep.PluginID, rep.TotalTranslated, rep.TotalReference, rep.TotalPercent)
|
||||
for _, d := range rep.Domains {
|
||||
fmt.Printf(" %-15s %4d/%-4d (%5.1f%%)\n", d.Domain, d.Translated, d.Total, d.Percent)
|
||||
}
|
||||
}
|
||||
for _, f := range findings {
|
||||
if f.Check == "locale-coverage" {
|
||||
continue
|
||||
}
|
||||
fmt.Printf("[%s] (%s) %s\n", f.Severity, f.Check, f.Message)
|
||||
}
|
||||
}
|
||||
for _, f := range findings {
|
||||
if f.Severity == "error" {
|
||||
return fmt.Errorf("%s", i18n.T(loc, "plugin.doctor.errors"))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
default:
|
||||
return fmt.Errorf("unknown plugin locale subcommand %q (expected init or check)", args[0])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
func TestCLIPluginLocaleInitAndCheck(t *testing.T) {
|
||||
outDir := filepath.Join(t.TempDir(), "ko-pack")
|
||||
if err := cmdPluginLocale(i18n.EnUS, []string{"init", "ko-KR", "--out", outDir}); err != nil {
|
||||
t.Fatalf("plugin locale init failed: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(outDir, "plugin.json")); err != nil {
|
||||
t.Fatalf("missing scaffolded plugin.json: %v", err)
|
||||
}
|
||||
if err := cmdPluginLocale(i18n.EnUS, []string{"check", outDir}); err != nil {
|
||||
t.Fatalf("plugin locale check failed on scaffolded pack: %v", err)
|
||||
}
|
||||
|
||||
// Also verify official zh-TW and ja-JP reference packs via CLI `plugin locale check`.
|
||||
for _, rel := range []string{
|
||||
filepath.Join("..", "plugin", "testdata", "official.lang.zh-tw"),
|
||||
filepath.Join("..", "plugin", "testdata", "official.lang.ja-jp"),
|
||||
} {
|
||||
if err := cmdPluginLocale(i18n.EnUS, []string{"check", rel}); err != nil {
|
||||
t.Fatalf("CLI check(%s) failed: %v", rel, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLILinkEnableActivatesStaticLocalePackWithoutCrashSentinel(t *testing.T) {
|
||||
defer i18n.SetPluginCatalogs(nil)
|
||||
dataRoot := t.TempDir()
|
||||
jaDir, err := filepath.Abs(filepath.Join("..", "plugin", "testdata", "official.lang.ja-jp"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code := Main([]string{"--data-root", dataRoot, "plugin", "link", jaDir}); code != 0 {
|
||||
t.Fatalf("plugin link exit code = %d", code)
|
||||
}
|
||||
if code := Main([]string{"--data-root", dataRoot, "plugin", "enable", "official.lang.ja-jp"}); code != 0 {
|
||||
t.Fatalf("plugin enable exit code = %d", code)
|
||||
}
|
||||
if plugin.DidLastStartupCrash(plugin.NewPluginsLayout(dataRoot).Root) {
|
||||
t.Fatal("CLI plugin manager left .initializing crash sentinel behind")
|
||||
}
|
||||
loc, err := run([]string{"--data-root", dataRoot, "--lang", "ja-JP", "--help"})
|
||||
if err != nil || loc != i18n.Locale("ja-JP") {
|
||||
t.Fatalf("run(--lang ja-JP --help) = (%q, %v), want (ja-JP, nil)", loc, err)
|
||||
}
|
||||
}
|
||||
|
||||
+5
-24
@@ -78,28 +78,19 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s
|
||||
}
|
||||
|
||||
func startInWindow(ctx context.Context, cfg *config.Config, name string) error {
|
||||
zh := cfg.Locale == i18n.ZhCN
|
||||
if err := os.MkdirAll(cfg.TempDir(), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
result := filepath.Join(cfg.TempDir(), fmt.Sprintf("cli-start-%d.json", time.Now().UnixNano()))
|
||||
w := WindowArgs{StartVM: name, StartResult: result}
|
||||
if hwnd := findWindow(); hwnd != 0 {
|
||||
if zh {
|
||||
fmt.Fprintf(os.Stderr, "交给正在运行的 Reims-Go 启动 %s…\n", name)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Handing %s to the running Reims-Go...\n", name)
|
||||
}
|
||||
fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.handing_to_window", i18n.Vars{"name": name}))
|
||||
if err := sendToWindow(hwnd, w.Args()); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
w.Background = true
|
||||
if zh {
|
||||
fmt.Fprintf(os.Stderr, "在后台拉起 Reims-Go(托盘)来启动 %s…\n", name)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Starting Reims-Go in the tray to run %s...\n", name)
|
||||
}
|
||||
fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.spawning_tray", i18n.Vars{"name": name}))
|
||||
if err := spawnWindow(w.Args()); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -110,15 +101,9 @@ func startInWindow(ctx context.Context, cfg *config.Config, name string) error {
|
||||
res, err := waitStartResult(ctx, result, startHandoffTimeout)
|
||||
switch {
|
||||
case errors.Is(err, context.Canceled):
|
||||
if zh {
|
||||
return fmt.Errorf("已停止等待;%s 仍由 Reims-Go 继续启动", name)
|
||||
}
|
||||
return fmt.Errorf("stopped waiting; Reims-Go keeps starting %s", name)
|
||||
return fmt.Errorf("%s", i18n.M(cfg.Locale, "cli.start.canceled", i18n.Vars{"name": name}))
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
if zh {
|
||||
return fmt.Errorf("Reims-Go 在 %v 内没有回报 %s 的启动结果;请看界面的日志面板(若正在运行的是旧版 Reims-Go,请先退出它)", startHandoffTimeout, name)
|
||||
}
|
||||
return fmt.Errorf("Reims-Go did not report starting %s within %v; check its log panel (quit it first if it is an older version)", name, startHandoffTimeout)
|
||||
return fmt.Errorf("%s", i18n.M(cfg.Locale, "cli.start.timeout", i18n.Vars{"name": name, "timeout": startHandoffTimeout}))
|
||||
case err != nil:
|
||||
return err
|
||||
}
|
||||
@@ -127,11 +112,7 @@ func startInWindow(ctx context.Context, cfg *config.Config, name string) error {
|
||||
}
|
||||
// Guest Tools only connects once macOS is up and its agent runs, so say
|
||||
// what this process can know: who now looks after the VM.
|
||||
if zh {
|
||||
fmt.Printf("%s 已启动,由 Reims-Go 界面进程管理;macOS 启动后,已安装 Guest Tools 的客体会接入剪贴板与共享目录\n", name)
|
||||
} else {
|
||||
fmt.Printf("%s is running, looked after by the Reims-Go window process; once macOS is up, a guest with Guest Tools installed gets clipboard and shared folders\n", name)
|
||||
}
|
||||
fmt.Println(i18n.M(cfg.Locale, "cli.start.managed_ok", i18n.Vars{"name": name}))
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -153,7 +153,7 @@ func Resolve() (cfg *Config, needsSetup bool, err error) {
|
||||
func Default() *Config {
|
||||
return &Config{
|
||||
DataRoot: CurrentDataRoot(),
|
||||
Locale: i18n.Detect(),
|
||||
Locale: i18n.Auto,
|
||||
AutoPinPCores: true,
|
||||
DefaultGPU: "auto",
|
||||
}
|
||||
@@ -177,7 +177,7 @@ func Load(path string) (*Config, error) {
|
||||
if cfg.DataRoot == "" {
|
||||
cfg.DataRoot = filepath.Dir(path)
|
||||
}
|
||||
cfg.Locale = i18n.ResolveLocale(string(cfg.Locale))
|
||||
cfg.Locale = i18n.ParsePreference(string(cfg.Locale))
|
||||
if cfg.RuntimeChannel == "candidate" {
|
||||
cfg.RuntimeChannel = "alpha"
|
||||
}
|
||||
|
||||
@@ -40,8 +40,10 @@ const (
|
||||
|
||||
// ValidationIssue reports a field-level validation error before Create/Set.
|
||||
type ValidationIssue struct {
|
||||
Field string `json:"field"`
|
||||
Message string `json:"message"`
|
||||
Field string `json:"field"`
|
||||
Code string `json:"code,omitempty"`
|
||||
Params map[string]any `json:"params,omitempty"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// VMInfo is the generic cross-driver VM model (§5.3).
|
||||
|
||||
@@ -237,7 +237,7 @@ func ValidateCreateLocalized(o CreateOpts, rep host.Report, loc i18n.Locale) []V
|
||||
}
|
||||
if strings.TrimSpace(o.GuestLang) != "" {
|
||||
if _, err := opencore.NormalizeGuestLang(o.GuestLang); err != nil {
|
||||
issues = append(issues, ValidationIssue{Field: "guest_lang", Code: "invalid_guest_lang", Message: err.Error()})
|
||||
issues = append(issues, ValidationIssue{Field: "guest_lang", Code: "invalid_guest_lang", Message: i18n.T(loc, "validate.invalid_guest_lang")})
|
||||
}
|
||||
}
|
||||
return issues
|
||||
@@ -297,7 +297,7 @@ func ValidateSetLocalized(o SetOpts, current VMDetail, rep host.Report, loc i18n
|
||||
}
|
||||
if strings.TrimSpace(o.GuestLang) != "" {
|
||||
if _, err := opencore.NormalizeGuestLang(o.GuestLang); err != nil {
|
||||
issues = append(issues, ValidationIssue{Field: "guest_lang", Code: "invalid_guest_lang", Message: err.Error()})
|
||||
issues = append(issues, ValidationIssue{Field: "guest_lang", Code: "invalid_guest_lang", Message: i18n.T(loc, "validate.invalid_guest_lang")})
|
||||
}
|
||||
}
|
||||
return issues
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
//go:build !windows
|
||||
|
||||
package host
|
||||
|
||||
import "github.com/Nwflower/reims-go/internal/i18n"
|
||||
|
||||
func CheckMissingLocaleFonts(locale string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func CheckMissingLocaleFontsForUI(targetLocale string, uiLocale i18n.Locale) string {
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//go:build windows
|
||||
|
||||
package host
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"unicode/utf16"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
var (
|
||||
modGDI32Font = syscall.NewLazyDLL("gdi32.dll")
|
||||
modUser32Font = syscall.NewLazyDLL("user32.dll")
|
||||
procEnumFontFamiliesEx = modGDI32Font.NewProc("EnumFontFamiliesExW")
|
||||
procGetDCFont = modUser32Font.NewProc("GetDC")
|
||||
procReleaseDCFont = modUser32Font.NewProc("ReleaseDC")
|
||||
|
||||
fontDetectMu sync.Mutex
|
||||
fontDetectHit bool
|
||||
fontDetectMemo = map[string]bool{}
|
||||
fontDetectCB = syscall.NewCallback(func(lpelfe, lpntme, fontType, lparam uintptr) uintptr {
|
||||
fontDetectHit = true
|
||||
return 0
|
||||
})
|
||||
)
|
||||
|
||||
type gdiLogFontW struct {
|
||||
height, width, escapement, orientation, weight int32
|
||||
italic, underline, strikeOut, charSet byte
|
||||
outPrecision, clipPrecision, quality, pitchFam byte
|
||||
face [32]uint16
|
||||
}
|
||||
|
||||
func hasInstalledFontFamily(name string) bool {
|
||||
fontDetectMu.Lock()
|
||||
defer fontDetectMu.Unlock()
|
||||
if ok, cached := fontDetectMemo[name]; cached {
|
||||
return ok
|
||||
}
|
||||
dc, _, _ := procGetDCFont.Call(0)
|
||||
if dc == 0 {
|
||||
return true // fail-open if desktop DC unavailable
|
||||
}
|
||||
defer procReleaseDCFont.Call(0, dc)
|
||||
|
||||
var lf gdiLogFontW
|
||||
lf.charSet = 1 // DEFAULT_CHARSET
|
||||
u16 := utf16.Encode([]rune(name))
|
||||
if len(u16) >= len(lf.face) {
|
||||
u16 = u16[:len(lf.face)-1]
|
||||
}
|
||||
copy(lf.face[:], u16)
|
||||
|
||||
fontDetectHit = false
|
||||
procEnumFontFamiliesEx.Call(dc, uintptr(unsafe.Pointer(&lf)), fontDetectCB, 0, 0)
|
||||
if fontDetectHit {
|
||||
// Only memoize positive hits so installing Windows FoD fonts at runtime
|
||||
// clears the missing-font hint without restarting Reims-Go.
|
||||
fontDetectMemo[name] = true
|
||||
}
|
||||
return fontDetectHit
|
||||
}
|
||||
|
||||
// CheckMissingLocaleFonts checks whether Windows has at least one modern UI
|
||||
// font installed for the East Asian script required by locale (detecting missing
|
||||
// Windows Features-on-Demand supplemental font packages on non-CJK Windows installs).
|
||||
// Returns "" when fonts are present or not needed, or a localized script label.
|
||||
func CheckMissingLocaleFonts(locale string) string {
|
||||
return CheckMissingLocaleFontsForUI(locale, i18n.ResolveLocale(locale))
|
||||
}
|
||||
|
||||
// CheckMissingLocaleFontsForUI checks whether Windows has fonts for targetLocale
|
||||
// and returns the localized script name in uiLocale when missing.
|
||||
func CheckMissingLocaleFontsForUI(targetLocale string, uiLocale i18n.Locale) string {
|
||||
low := strings.ToLower(strings.TrimSpace(targetLocale))
|
||||
var candidates []string
|
||||
var scriptKey string
|
||||
|
||||
switch {
|
||||
case low == "zh-tw" || low == "zh-hk" || low == "zh-mo" || strings.HasPrefix(low, "zh-hant"):
|
||||
scriptKey = "font.script.zh_hant"
|
||||
candidates = []string{"Microsoft JhengHei UI", "Microsoft JhengHei", "Noto Sans TC", "PingFang TC", "Source Han Sans TC"}
|
||||
case strings.HasPrefix(low, "zh"):
|
||||
scriptKey = "font.script.zh_hans"
|
||||
candidates = []string{"Microsoft YaHei UI", "Microsoft YaHei", "Noto Sans SC", "PingFang SC", "HarmonyOS Sans SC", "MiSans"}
|
||||
case strings.HasPrefix(low, "ja"):
|
||||
scriptKey = "font.script.ja"
|
||||
candidates = []string{"Yu Gothic UI", "Yu Gothic", "Meiryo UI", "Meiryo", "BIZ UDPGothic", "Noto Sans JP"}
|
||||
case strings.HasPrefix(low, "ko"):
|
||||
scriptKey = "font.script.ko"
|
||||
candidates = []string{"Malgun Gothic", "Noto Sans KR", "Apple SD Gothic Neo"}
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
|
||||
for _, f := range candidates {
|
||||
if hasInstalledFontFamily(f) {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return i18n.T(uiLocale, scriptKey)
|
||||
}
|
||||
@@ -9,7 +9,9 @@ import (
|
||||
|
||||
// Inspect returns basic host facts on non-Windows dev machines (e.g., macOS).
|
||||
func Inspect(dataRoot string) Report {
|
||||
presets, rec := RecommendDisplayPresets(nil)
|
||||
displays := probeDisplays()
|
||||
primary := PrimaryDisplayOf(displays)
|
||||
presets, rec := RecommendDisplayPresets(primary)
|
||||
return Report{
|
||||
OS: runtime.GOOS,
|
||||
Arch: runtime.GOARCH,
|
||||
@@ -17,8 +19,11 @@ func Inspect(dataRoot string) Report {
|
||||
CPUTopology: DefaultCPUTopology(runtime.NumCPU()),
|
||||
DataRoot: dataRoot,
|
||||
WHPX: WHPXUnsupported,
|
||||
Displays: displays,
|
||||
PrimaryDisplay: primary,
|
||||
RecommendedResolution: rec,
|
||||
DisplayPresets: presets,
|
||||
ProcessorScheduling: probeProcessorScheduling(),
|
||||
Audio: ProbeAudio(),
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,149 @@
|
||||
package i18n
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const maxRawDetailBytes = 8192
|
||||
|
||||
var (
|
||||
reErrMac = regexp.MustCompile(`(?i)\b(mac[\s:=]+)["']?[0-9a-f]{2}(?::[0-9a-f]{2}){5}["']?`)
|
||||
reErrSerial = regexp.MustCompile(`(?i)\b(serial[\s:=]+)["']?[A-Z0-9]{8,}["']?`)
|
||||
reErrOSK = regexp.MustCompile(`(?i)\b(osk=)[^\s,"']+`)
|
||||
reErrBearer = regexp.MustCompile(`(?i)(Bearer\s+)[A-Za-z0-9._~+/-]{16,}`)
|
||||
reErrTokenKV = regexp.MustCompile(`(?i)((?:REIMS_TOKEN|"token")\s*[:=]\s*["']?)[A-Za-z0-9._~+/-]{16,}(["']?)`)
|
||||
|
||||
detailRedactMu sync.RWMutex
|
||||
detailRedactFn func(string) string
|
||||
)
|
||||
|
||||
// SetDetailRedactor registers an optional additional redactor function applied
|
||||
// to CodedError.RawDetail before diagnostic text crosses Wails IPC or CLI stderr.
|
||||
func SetDetailRedactor(fn func(string) string) {
|
||||
detailRedactMu.Lock()
|
||||
detailRedactFn = fn
|
||||
detailRedactMu.Unlock()
|
||||
}
|
||||
|
||||
func sanitizeRawDetail(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
lines := strings.Split(s, "\n")
|
||||
for i, l := range lines {
|
||||
l = reErrMac.ReplaceAllString(l, "${1}[redacted]")
|
||||
l = reErrSerial.ReplaceAllString(l, "${1}[redacted]")
|
||||
l = reErrOSK.ReplaceAllString(l, "${1}[redacted]")
|
||||
l = reErrBearer.ReplaceAllString(l, "${1}[redacted]")
|
||||
l = reErrTokenKV.ReplaceAllString(l, "${1}[redacted]${2}")
|
||||
lines[i] = l
|
||||
}
|
||||
s = strings.Join(lines, "\n")
|
||||
detailRedactMu.RLock()
|
||||
fn := detailRedactFn
|
||||
detailRedactMu.RUnlock()
|
||||
if fn != nil {
|
||||
s = fn(s)
|
||||
}
|
||||
if len(s) > maxRawDetailBytes {
|
||||
s = s[:maxRawDetailBytes] + "…"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// CodedError represents a user-facing error with a stable supportable error code
|
||||
// (e.g. "E_VM_CLONE_RUNNING"), a localized message key + named params, and an
|
||||
// optional redacted raw technical detail string for collapsible display and GitHub
|
||||
// Issue diagnostics (docs/design-guidelines.md §7.1, AGENTS.md Rule 3).
|
||||
type CodedError struct {
|
||||
Locale Locale
|
||||
Code string
|
||||
Key string
|
||||
Params Vars
|
||||
RawDetail string
|
||||
Cause error
|
||||
}
|
||||
|
||||
// NewCodedError constructs a localized, supportable, secret-redacted CodedError.
|
||||
func NewCodedError(loc Locale, code, key string, params Vars, cause error) *CodedError {
|
||||
raw := ""
|
||||
if cause != nil {
|
||||
raw = sanitizeRawDetail(cause.Error())
|
||||
}
|
||||
return &CodedError{
|
||||
Locale: loc,
|
||||
Code: code,
|
||||
Key: key,
|
||||
Params: params,
|
||||
RawDetail: raw,
|
||||
Cause: cause,
|
||||
}
|
||||
}
|
||||
|
||||
// WithDetail attaches explicit raw diagnostic text (e.g. stderr from qemu-img or reims-ctl),
|
||||
// automatically redacting sensitive tokens/OSK/SMBIOS/MAC values and capping length.
|
||||
func (e *CodedError) WithDetail(detail string) *CodedError {
|
||||
if e != nil {
|
||||
e.RawDetail = sanitizeRawDetail(detail)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// Summary returns the localized human-readable summary in loc (or e.Locale if loc is empty).
|
||||
func (e *CodedError) Summary(loc Locale) string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
target := loc
|
||||
if target == "" {
|
||||
target = e.Locale
|
||||
}
|
||||
return M(target, e.Key, e.Params)
|
||||
}
|
||||
|
||||
// Error formats the error cleanly for both Wails Promise rejection decoding
|
||||
// ("<summary> [E_CODE]\n[detail] <raw>") and plain terminal/log readers.
|
||||
func (e *CodedError) Error() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
msg := e.Summary(e.Locale)
|
||||
if e.Code != "" {
|
||||
msg += " [" + e.Code + "]"
|
||||
}
|
||||
if e.RawDetail != "" && !strings.Contains(msg, e.RawDetail) {
|
||||
msg += "\n[detail] " + e.RawDetail
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
func (e *CodedError) Unwrap() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.Cause
|
||||
}
|
||||
|
||||
// FormatCLIError formats any error cleanly for CLI stderr output, translating
|
||||
// CodedError into the requested CLI locale and indenting technical details.
|
||||
func FormatCLIError(loc Locale, err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
var ce *CodedError
|
||||
if errors.As(err, &ce) {
|
||||
line := ce.Summary(loc)
|
||||
if ce.Code != "" {
|
||||
line = "[" + ce.Code + "] " + line
|
||||
}
|
||||
if ce.RawDetail != "" {
|
||||
line += "\n detail: " + strings.ReplaceAll(ce.RawDetail, "\n", "\n ")
|
||||
}
|
||||
return line
|
||||
}
|
||||
return sanitizeRawDetail(err.Error())
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package i18n
|
||||
|
||||
import "strings"
|
||||
|
||||
// Built-in Apple official macOS UI terminology for guest languages beyond the
|
||||
// two built-in host locales, so FormatGuestTerm works out-of-the-box whenever
|
||||
// a user installs a Traditional Chinese, Japanese, or Korean macOS guest even
|
||||
// without installing a host language pack first.
|
||||
var builtinMacOSGlossaryExtra = map[Locale]map[string]string{
|
||||
Locale("zh-TW"): {
|
||||
"macos.recovery": "復原",
|
||||
"macos.utilitiesTerminal": "工具程式 › 終端機",
|
||||
"macos.appsUtilitiesTerminal": "應用程式 › 工具程式 › 終端機",
|
||||
"macos.reinstallMacOS": "重新安裝 macOS",
|
||||
"macos.diskUtility": "磁碟工具程式",
|
||||
"macos.showAllDevices": "檢視 › 顯示所有裝置",
|
||||
"macos.erase": "清除",
|
||||
"macos.volume": "卷宗",
|
||||
"macos.guidPartitionMap": "GUID 分割區配置表",
|
||||
"macos.setupAssistant": "設定輔助程式",
|
||||
"macos.otherSignInSetUpLater": "其他登入選項 › 稍後設定",
|
||||
"macos.finder": "Finder",
|
||||
},
|
||||
Locale("zh-HK"): {
|
||||
"macos.recovery": "復原",
|
||||
"macos.utilitiesTerminal": "工具程式 › 終端機",
|
||||
"macos.appsUtilitiesTerminal": "應用程式 › 工具程式 › 終端機",
|
||||
"macos.reinstallMacOS": "重新安裝 macOS",
|
||||
"macos.diskUtility": "磁碟工具程式",
|
||||
"macos.showAllDevices": "檢視 › 顯示所有裝置",
|
||||
"macos.erase": "清除",
|
||||
"macos.volume": "卷宗",
|
||||
"macos.guidPartitionMap": "GUID 分割區配置表",
|
||||
"macos.setupAssistant": "設定輔助程式",
|
||||
"macos.otherSignInSetUpLater": "其他登入選項 › 稍後設定",
|
||||
"macos.finder": "Finder",
|
||||
},
|
||||
Locale("ja-JP"): {
|
||||
"macos.recovery": "復旧",
|
||||
"macos.utilitiesTerminal": "ユーティリティ › ターミナル",
|
||||
"macos.appsUtilitiesTerminal": "アプリケーション › ユーティリティ › ターミナル",
|
||||
"macos.reinstallMacOS": "macOSを再インストール",
|
||||
"macos.diskUtility": "ディスクユーティリティ",
|
||||
"macos.showAllDevices": "表示 › すべてのデバイスを表示",
|
||||
"macos.erase": "消去",
|
||||
"macos.volume": "ボリューム",
|
||||
"macos.guidPartitionMap": "GUIDパーティションマップ",
|
||||
"macos.setupAssistant": "設定アシスタント",
|
||||
"macos.otherSignInSetUpLater": "その他のサインインオプション › あとで設定",
|
||||
"macos.finder": "Finder",
|
||||
},
|
||||
Locale("ko-KR"): {
|
||||
"macos.recovery": "복구",
|
||||
"macos.utilitiesTerminal": "유틸리티 › 터미널",
|
||||
"macos.appsUtilitiesTerminal": "응용 프로그램 › 유틸리티 › 터미널",
|
||||
"macos.reinstallMacOS": "macOS 재설치",
|
||||
"macos.diskUtility": "디스크 유틸리티",
|
||||
"macos.showAllDevices": "보기 › 모든 기기 보기",
|
||||
"macos.erase": "지우기",
|
||||
"macos.volume": "볼륨",
|
||||
"macos.guidPartitionMap": "GUID 파티션 맵",
|
||||
"macos.setupAssistant": "설정 지원",
|
||||
"macos.otherSignInSetUpLater": "기타 로그인 옵션 › 나중에 설정",
|
||||
"macos.finder": "Finder",
|
||||
},
|
||||
}
|
||||
|
||||
// GuestLocaleFromPrevLang converts an OpenCore NVRAM prev-lang:kbd string
|
||||
// (e.g. "zh-Hans:0", "zh-Hant:0", "en-US:0", "ja-JP:0") into a canonical Locale.
|
||||
func GuestLocaleFromPrevLang(prevLang string) Locale {
|
||||
raw := strings.TrimSpace(prevLang)
|
||||
if idx := strings.IndexByte(raw, ':'); idx >= 0 {
|
||||
raw = raw[:idx]
|
||||
}
|
||||
low := strings.ToLower(raw)
|
||||
switch {
|
||||
case low == "" || low == "zh-hans" || low == "zh-cn":
|
||||
return ZhCN
|
||||
case low == "zh-hant" || low == "zh-tw":
|
||||
return Locale("zh-TW")
|
||||
case low == "zh-hk" || low == "zh-mo":
|
||||
return Locale("zh-HK")
|
||||
case strings.HasPrefix(low, "ja"):
|
||||
return Locale("ja-JP")
|
||||
case strings.HasPrefix(low, "ko"):
|
||||
return Locale("ko-KR")
|
||||
case strings.HasPrefix(low, "en"):
|
||||
return EnUS
|
||||
default:
|
||||
if parsed, ok := ParseLocale(raw); ok {
|
||||
return parsed
|
||||
}
|
||||
return EnUS
|
||||
}
|
||||
}
|
||||
|
||||
func lookupGlossaryTerm(loc Locale, key string) string {
|
||||
canon := ResolveLocale(string(loc))
|
||||
for _, step := range FallbackChain(canon) {
|
||||
if step == EnXA {
|
||||
return PseudoLocalize(lookupGlossaryTerm(EnUS, key))
|
||||
}
|
||||
pluginCatalogMu.RLock()
|
||||
pack, hasPack := pluginCatalogs[step]
|
||||
pluginCatalogMu.RUnlock()
|
||||
if hasPack && pack.Messages != nil {
|
||||
if v, ok := pack.Messages[key]; ok && v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
if extra, ok := builtinMacOSGlossaryExtra[step]; ok {
|
||||
if v, ok := extra[key]; ok && v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
if base, ok := catalog[step]; ok {
|
||||
if v, ok := base[key]; ok && v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
// IsCJKLocale reports whether loc uses Chinese, Japanese, or Korean typography
|
||||
// conventions (such as corner brackets 「...」 around UI target labels).
|
||||
func IsCJKLocale(loc Locale) bool {
|
||||
switch primarySubtag(string(ResolveLocale(string(loc)))) {
|
||||
case "zh", "ja", "ko":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// FormatGuestTerm resolves an Apple macOS UI term (e.g. "macos.diskUtility")
|
||||
// in the host's UI language and, whenever the guest VM's configured macOS
|
||||
// language differs, appends the exact Apple UI label shown inside the guest
|
||||
// (e.g. 「磁盘工具 (Disk Utility)」 or "Disk Utility (磁盘工具)").
|
||||
func FormatGuestTerm(hostLoc Locale, guestPrevLang, key string, bracketed bool) string {
|
||||
resolvedHost := ResolveLocale(string(hostLoc))
|
||||
hostTerm := lookupGlossaryTerm(resolvedHost, key)
|
||||
|
||||
var combined string
|
||||
if strings.TrimSpace(guestPrevLang) != "" {
|
||||
guestLoc := GuestLocaleFromPrevLang(guestPrevLang)
|
||||
// For pseudo-locale en-XA, compare base English term unless guest is non-English.
|
||||
guestTerm := lookupGlossaryTerm(guestLoc, key)
|
||||
baseHostTerm := hostTerm
|
||||
if resolvedHost == EnXA {
|
||||
baseHostTerm = lookupGlossaryTerm(EnUS, key)
|
||||
}
|
||||
if guestTerm != "" && !strings.EqualFold(baseHostTerm, guestTerm) {
|
||||
combined = hostTerm + " (" + guestTerm + ")"
|
||||
}
|
||||
}
|
||||
if combined == "" {
|
||||
combined = hostTerm
|
||||
}
|
||||
if bracketed && IsCJKLocale(resolvedHost) {
|
||||
return "「" + combined + "」"
|
||||
}
|
||||
return combined
|
||||
}
|
||||
+319
-276
@@ -1,8 +1,8 @@
|
||||
package i18n
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
@@ -10,12 +10,14 @@ import (
|
||||
type Locale string
|
||||
|
||||
const (
|
||||
Auto Locale = "auto"
|
||||
ZhCN Locale = "zh-CN"
|
||||
EnUS Locale = "en-US"
|
||||
EnXA Locale = "en-XA" // Developer/QA pseudo-locale (accented + expanded + ⟦...⟧)
|
||||
)
|
||||
|
||||
// PluginCatalog holds backend/CLI message overrides contributed by enabled
|
||||
// locale plugins for a single canonical locale tag.
|
||||
// PluginCatalog holds backend/CLI/native message overrides contributed by
|
||||
// enabled locale plugins for a single canonical locale tag.
|
||||
type PluginCatalog struct {
|
||||
Fallback Locale
|
||||
Messages map[string]string
|
||||
@@ -31,18 +33,18 @@ func SetPluginCatalogs(packs map[Locale]PluginCatalog) {
|
||||
copied := make(map[Locale]PluginCatalog, len(packs))
|
||||
for loc, p := range packs {
|
||||
canon, ok := ParseLocale(string(loc))
|
||||
if !ok {
|
||||
if !ok || canon == Auto {
|
||||
continue
|
||||
}
|
||||
msgs := make(map[string]string, len(p.Messages))
|
||||
for k, v := range p.Messages {
|
||||
if k != "" && v != "" {
|
||||
msgs[k] = v
|
||||
msgs[k] = rewriteLegacyPositionalVerbs(v)
|
||||
}
|
||||
}
|
||||
fb := p.Fallback
|
||||
if fb != "" {
|
||||
if cfb, ok := ParseLocale(string(fb)); ok {
|
||||
if cfb, ok := ParseLocale(string(fb)); ok && cfb != Auto {
|
||||
fb = cfb
|
||||
} else {
|
||||
fb = ""
|
||||
@@ -55,14 +57,83 @@ func SetPluginCatalogs(packs map[Locale]PluginCatalog) {
|
||||
pluginCatalogMu.Unlock()
|
||||
}
|
||||
|
||||
// ParseLocale validates and canonicalizes a BCP-47-like locale tag (e.g.
|
||||
// rewriteLegacyPositionalVerbs safely converts v1 widthless printf verbs (%s/%d/%v)
|
||||
// in legacy plugin catalogs into bounded ICU positional placeholders ({0}, {1}, ...)
|
||||
// without ever invoking fmt.Sprintf (preventing %999999999s memory-amplification DoS
|
||||
// and literal '%' corruption).
|
||||
func rewriteLegacyPositionalVerbs(s string) string {
|
||||
if strings.IndexByte(s, '%') < 0 || strings.IndexByte(s, '{') >= 0 {
|
||||
return s
|
||||
}
|
||||
var b strings.Builder
|
||||
b.Grow(len(s) + 8)
|
||||
argIdx := 0
|
||||
replaced := false
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == '%' && i+1 < len(s) {
|
||||
switch s[i+1] {
|
||||
case '%':
|
||||
b.WriteByte('%')
|
||||
i++
|
||||
replaced = true
|
||||
continue
|
||||
case 's', 'd', 'v':
|
||||
b.WriteByte('{')
|
||||
b.WriteString(strconv.Itoa(argIdx))
|
||||
b.WriteByte('}')
|
||||
argIdx++
|
||||
i++
|
||||
replaced = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
}
|
||||
if !replaced {
|
||||
return s
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// HasPluginLocale reports whether an active plugin pack provides translations for loc.
|
||||
func HasPluginLocale(loc Locale) bool {
|
||||
pluginCatalogMu.RLock()
|
||||
_, ok := pluginCatalogs[loc]
|
||||
pluginCatalogMu.RUnlock()
|
||||
return ok
|
||||
}
|
||||
|
||||
func primarySubtag(tag string) string {
|
||||
s := strings.ToLower(strings.TrimSpace(tag))
|
||||
if idx := strings.IndexAny(s, "-_"); idx >= 0 {
|
||||
return s[:idx]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// IsRTLLocale reports whether loc uses a right-to-left script direction.
|
||||
func IsRTLLocale(loc Locale) bool {
|
||||
switch primarySubtag(string(ResolveLocale(string(loc)))) {
|
||||
case "ar", "he", "iw", "fa", "ur", "ps", "dv", "yi":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// ParseLocale validates and canonicalizes a BCP-47 locale tag (e.g.
|
||||
// "zh_CN.UTF-8" -> "zh-CN", "ja_jp" -> "ja-JP", "zh-hant" -> "zh-Hant").
|
||||
// Note: "auto" is a preference sentinel rather than a concrete locale tag; use
|
||||
// ParsePreference when reading config preferences.
|
||||
func ParseLocale(raw string) (Locale, bool) {
|
||||
s := strings.TrimSpace(raw)
|
||||
if idx := strings.IndexAny(s, ".@"); idx >= 0 {
|
||||
s = s[:idx]
|
||||
}
|
||||
s = strings.ReplaceAll(s, "_", "-")
|
||||
if strings.EqualFold(s, "auto") {
|
||||
return "", false
|
||||
}
|
||||
if len(s) < 2 || len(s) > 35 {
|
||||
return "", false
|
||||
}
|
||||
@@ -91,10 +162,12 @@ func ParseLocale(raw string) (Locale, bool) {
|
||||
}
|
||||
lower := strings.ToLower(strings.Join(parts, "-"))
|
||||
switch lower {
|
||||
case "zh", "zh-cn", "zh-hans", "zh-hans-cn", "zh-sg":
|
||||
case "zh", "zh-cn", "zh-hans", "zh-hans-cn":
|
||||
return ZhCN, true
|
||||
case "en", "en-us":
|
||||
return EnUS, true
|
||||
case "en-xa", "qps-ploc":
|
||||
return EnXA, true
|
||||
}
|
||||
out := make([]string, len(parts))
|
||||
out[0] = strings.ToLower(parts[0])
|
||||
@@ -122,30 +195,57 @@ func isAllLetters(s string) bool {
|
||||
return len(s) > 0
|
||||
}
|
||||
|
||||
// ResolveLocale preserves any valid canonical BCP-47 locale tag (including
|
||||
// plugin-provided locales such as "ja-JP" or "zh-TW") and falls back to
|
||||
// Normalize for empty or invalid input.
|
||||
func ResolveLocale(raw string) Locale {
|
||||
if loc, ok := ParseLocale(raw); ok {
|
||||
// ParsePreference parses a persisted or user-selected language preference,
|
||||
// preserving "auto" ("follow OS display language") as well as concrete BCP-47 tags.
|
||||
func ParsePreference(raw string) Locale {
|
||||
s := strings.TrimSpace(raw)
|
||||
if s == "" || strings.EqualFold(s, string(Auto)) {
|
||||
return Auto
|
||||
}
|
||||
if loc, ok := ParseLocale(s); ok {
|
||||
return loc
|
||||
}
|
||||
return Normalize(raw)
|
||||
return Normalize(s)
|
||||
}
|
||||
|
||||
// ResolveLocale resolves any preference or tag into a concrete active Locale.
|
||||
// When raw is "" or "auto", it dynamically resolves against the OS locale and
|
||||
// currently active plugin language packs.
|
||||
func ResolveLocale(raw string) Locale {
|
||||
s := strings.TrimSpace(raw)
|
||||
if s == "" || strings.EqualFold(s, string(Auto)) {
|
||||
return EffectiveLocale(Auto)
|
||||
}
|
||||
if loc, ok := ParseLocale(s); ok {
|
||||
return loc
|
||||
}
|
||||
return Normalize(s)
|
||||
}
|
||||
|
||||
// DefaultFallback returns the built-in fallback locale for any locale tag.
|
||||
func DefaultFallback(loc Locale) Locale {
|
||||
if strings.HasPrefix(strings.ToLower(string(loc)), "zh") {
|
||||
if primarySubtag(string(loc)) == "zh" {
|
||||
return ZhCN
|
||||
}
|
||||
return EnUS
|
||||
}
|
||||
|
||||
// Normalize maps user or OS locale strings to built-in locales.
|
||||
// DirOf returns the HTML/CSS writing direction ("rtl" or "ltr") for loc.
|
||||
func DirOf(loc Locale) string {
|
||||
if IsRTLLocale(loc) {
|
||||
return "rtl"
|
||||
}
|
||||
return "ltr"
|
||||
}
|
||||
|
||||
// Normalize maps user or OS locale strings directly onto the two built-in locales.
|
||||
func Normalize(raw string) Locale {
|
||||
s := strings.ToLower(strings.TrimSpace(raw))
|
||||
switch {
|
||||
case strings.HasPrefix(s, "zh"):
|
||||
return ZhCN
|
||||
case strings.HasPrefix(s, "en-xa"), strings.HasPrefix(s, "qps-ploc"):
|
||||
return EnXA
|
||||
case strings.HasPrefix(s, "en"):
|
||||
return EnUS
|
||||
default:
|
||||
@@ -155,17 +255,26 @@ func Normalize(raw string) Locale {
|
||||
|
||||
var osLocaleFn = detectOSLocale
|
||||
|
||||
// Detect returns the preferred locale from REIMS_GO_LANG / LC_ALL / LANG,
|
||||
// falling back to the OS user locale (zh* -> zh-CN, other non-empty -> en-US),
|
||||
// and finally zh-CN when undetermined.
|
||||
func Detect() Locale {
|
||||
// DetectOSLocaleTag returns the canonicalized uncollapsed OS or environment
|
||||
// BCP-47 tag (e.g. "ja-JP", "zh-TW", "zh-HK", "en-US", "zh-CN") without
|
||||
// collapsing non-built-in languages into binary zh-CN/en-US.
|
||||
func DetectOSLocaleTag() Locale {
|
||||
for _, k := range []string{"REIMS_GO_LANG", "LC_ALL", "LANG"} {
|
||||
if v := strings.TrimSpace(os.Getenv(k)); v != "" {
|
||||
if strings.EqualFold(v, "C") || strings.EqualFold(v, "POSIX") {
|
||||
return EnUS
|
||||
}
|
||||
if loc, ok := ParseLocale(v); ok {
|
||||
return loc
|
||||
}
|
||||
return Normalize(v)
|
||||
}
|
||||
}
|
||||
if osLoc := strings.ToLower(strings.TrimSpace(osLocaleFn())); osLoc != "" {
|
||||
if strings.HasPrefix(osLoc, "zh") {
|
||||
if osLoc := strings.TrimSpace(osLocaleFn()); osLoc != "" {
|
||||
if loc, ok := ParseLocale(osLoc); ok {
|
||||
return loc
|
||||
}
|
||||
if strings.HasPrefix(strings.ToLower(osLoc), "zh") {
|
||||
return ZhCN
|
||||
}
|
||||
return EnUS
|
||||
@@ -173,273 +282,207 @@ func Detect() Locale {
|
||||
return ZhCN
|
||||
}
|
||||
|
||||
var catalog = map[Locale]map[string]string{
|
||||
ZhCN: {
|
||||
"doctor.title": "Reims-Go 宿主机环境体检",
|
||||
"doctor.os": "操作系统",
|
||||
"doctor.cpu": "处理器与核心拓扑",
|
||||
"doctor.pcores": "P-Core 性能核",
|
||||
"doctor.pcores.detail": "%d 核,掩码 %s(CPU %v)",
|
||||
"doctor.ecores": "E-Core 能效核",
|
||||
"doctor.ecores.detail": "%d 核(CPU %v)",
|
||||
"doctor.ram": "宿主机内存",
|
||||
"doctor.ram.detail": "共 %.1f GB / 可用 %.1f GB",
|
||||
"doctor.disk": "数据盘剩余空间",
|
||||
"doctor.whpx": "Windows 虚拟机监控程序平台 (WHPX)",
|
||||
"doctor.whpx.ok": "可用(WinHvPlatform.dll 已就绪,hypervisor 运行中)",
|
||||
"doctor.whpx.no_hv": "已加载 WinHvPlatform.dll,但未检测到虚拟化(请在 BIOS 开启 VT-x/AMD-V)",
|
||||
"doctor.whpx.missing": "未启用(请点击一键启用 HypervisorPlatform 并重启 Windows)",
|
||||
"doctor.whpx.unsupported": "非 Windows 宿主(当前处于跨平台开发模式)",
|
||||
"doctor.gpu": "Vulkan 显卡列表",
|
||||
"doctor.gpu.none": "未检测到已注册的 Vulkan ICD 显卡驱动",
|
||||
"doctor.gpu.recommended": "推荐",
|
||||
"doctor.gpu.compat.supported": "支持",
|
||||
"doctor.gpu.compat.warn": "已知兼容性风险",
|
||||
"doctor.gpu.compat.unsupported": "不支持加速",
|
||||
"doctor.gpu.compat.unknown": "未完成 Vulkan 实测",
|
||||
"doctor.gpu.warn.amd_legacy": "AMD Vega/Polaris 在 Windows 闭源驱动下存在上游已知黑屏/设备丢失问题(%s),建议使用其他独显或在虚拟机设置改用 VMware SVGA",
|
||||
"doctor.gpu.warn.amd_rdna2": "该 AMD 显卡在 Windows 下存在上游已知设备丢失风险(%s),若黑屏/卡死请升级驱动或临时改用 VMware SVGA",
|
||||
"doctor.gpu.err.vulkan_too_old": "Vulkan 版本 %s 低于 1.3 最低要求,请更新显卡驱动或改用 VMware SVGA",
|
||||
"doctor.gpu.err.missing_ext": "缺少必需 Vulkan 扩展(%s),请更新显卡驱动或改用 VMware SVGA",
|
||||
"doctor.gpu.err.vulkan_cpu": "软件渲染 Vulkan 实现不满足 vGPU 硬件加速要求,请改用 VMware SVGA",
|
||||
"err.gpu_device_lost": "宿主显卡 Vulkan 设备丢失(ERROR_DEVICE_LOST)。请更新显卡驱动;若为 AMD Vega/Polaris 等受影响显卡,请改用其他独显或在设置中将虚拟显卡切为 VMware SVGA",
|
||||
"err.gpu_vulkan_floor": "宿主显卡不满足 Reims vGPU 的 Vulkan 1.3 硬件要求。请更新显卡驱动,或在设置中将虚拟显卡切为 VMware SVGA(软件渲染)",
|
||||
"doctor.runtime": "便携运行时",
|
||||
"doctor.runtime.none": "尚未安装(运行 reims-go runtime install <压缩包> 导入)",
|
||||
"doctor.runtime.active": "当前激活:%s(%s)",
|
||||
"runtime.installed": "便携运行时已安装:%s -> %s",
|
||||
"runtime.activated": "已切换激活运行时:%s",
|
||||
"runtime.removed": "已删除运行时:%s(%s)",
|
||||
"runtime.remove_active": "不能删除当前正在使用的运行时 %q,请先切换到其他版本",
|
||||
"runtime.remove_in_use": "运行时 %q 正被运行中的虚拟机占用,请先停止相关虚拟机后再删除",
|
||||
"runtime.empty": "尚未安装任何便携运行时。",
|
||||
"runtime.not_found": "未找到运行时 %q",
|
||||
"vm.empty": "当前没有已创建的虚拟机。",
|
||||
"vm.typed": "已敲入 %d 个键。",
|
||||
"vm.already_running": "%s 已在运行中",
|
||||
"vm.resize.stop_first": "请先停止 %s 再扩容虚拟磁盘",
|
||||
"vm.resize.done": "%s:虚拟磁盘已扩容 %.0f GB -> %.0f GB\n请在 macOS 终端执行以下命令扩展 APFS 容器:\n %s",
|
||||
"vm.compact.stop_first": "请先停止 %s 再回收磁盘空间",
|
||||
"vm.compact.done": "%s:磁盘已瘦身 %.2f GB -> %.2f GB(回收 %.2f GB)",
|
||||
"vm.install_guide.title": "macOS 装机步骤(简体中文恢复界面):",
|
||||
"vm.install_guide.step1": "1. 打开「磁盘工具」,选中「QEMU HARDDISK Media」并点「抹掉」(格式选 APFS)。",
|
||||
"vm.install_guide.step2": "2. 回到「恢复」窗口,选「重新安装 macOS」,装到刚抹掉的磁盘上(中途会自动重启几次)。",
|
||||
"vm.install_guide.step3": "3. 看到「设置助理」后,运行 `reims-go vm eject %s`(或在界面点「退出恢复模式」)移除安装盘,下次启动生效。",
|
||||
"err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`",
|
||||
"err.guest_tools_disabled": "Guest Tools 传输服务已在插件页停用,启用后才能使用剪贴板、共享文件夹与防休眠",
|
||||
"err.update_dev_build": "开发版本不支持应用内更新",
|
||||
"err.update_none": "已是最新版本",
|
||||
"err.update_no_asset": "这个版本没有提供 Windows 程序文件,请到发布页手动下载",
|
||||
"err.update_no_sums": "这个版本没有 SHA256SUMS.txt,无法校验下载内容,已停止更新",
|
||||
"err.update_not_ready": "请先下载更新",
|
||||
"err.update_changed": "已下载的更新文件被改动过,请重新下载",
|
||||
"err.update_not_writable": "无法写入 Reims-Go 所在目录(%s),请把程序放到可写的位置,或到发布页手动更新",
|
||||
"err.update_relaunch": "新版本已安装,但没能自动重新打开,请手动启动 Reims-Go",
|
||||
"err.commit_memory": "内存不够启动:这台虚拟机要 %.0f GB,Windows 现在只能再分配 %.1f GB。关掉一些程序再试,或在设置里把内存改为 %.0f GB",
|
||||
"err.whpx_missing": "未启用 Windows 虚拟机监控程序平台(WHPX)。在「宿主机」页启用 WHPX 并重启 Windows 后再启动虚拟机",
|
||||
"err.whpx_no_hypervisor": "Windows Hypervisor 虚拟化引擎未激活(与磁盘空间无关)。确认 BIOS 已开启 Intel VT-x / AMD SVM,在「宿主机」页启用 WHPX,以管理员运行 bcdedit /set hypervisorlaunchtype auto,然后重启 Windows",
|
||||
"err.whpx_unsupported": "当前系统不支持 Windows 虚拟机监控程序平台(WHPX),需要 Windows 10 1803 或更高版本",
|
||||
"installer.paused": "已暂停。再次运行 `reims-go installer download %s` 会从中断处继续。",
|
||||
"installer.done": "离线安装包已就绪:macOS %s -> %s",
|
||||
"installer.cached.empty": "还没有下载任何安装包。",
|
||||
"installer.cached.total": "共 %s,位于 %s",
|
||||
"installer.partial": "(未下载完)",
|
||||
"runtime.remote.empty": "当前通道还没有发布运行时(alpha 版需要加 --alpha)。",
|
||||
"runtime.remote.downloading": "下载运行时 %s(%s,%s)",
|
||||
"runtime.remote.paused": "已暂停。再次运行同一命令会从中断处继续。",
|
||||
"plugin.installed": "已安装插件 %s@%s(trust=%s,tier=%s)",
|
||||
"plugin.needs_approval": "提示:此插件包含高危权限,启用前请运行:reims-go plugin enable --approve-high-risk %s",
|
||||
"plugin.linked": "已链接本地开发插件 %s@%s -> %s",
|
||||
"plugin.enabled": "已启用 %s",
|
||||
"plugin.disabled": "已停用 %s",
|
||||
"plugin.removed": "已卸载 %s(purge=%v)",
|
||||
"plugin.not_found": "未找到插件 %q",
|
||||
"plugin.target_not_found": "未找到插件或目录 %q",
|
||||
"plugin.doctor.errors": "插件检查发现错误",
|
||||
"setup.err.empty": "请选择数据目录",
|
||||
"setup.err.not_abs": "%s 不是完整路径",
|
||||
"setup.err.whole_drive": "请选择具体文件夹,不要直接选择整个盘符",
|
||||
"setup.err.comma": "目录路径不能包含逗号 ','",
|
||||
"setup.err.is_file": "%s 是文件而不是文件夹",
|
||||
"validate.invalid_name": "名称须以字母或数字开头,仅支持 A-Z、0-9、.、_、-",
|
||||
"validate.name_taken": "已存在名为 %s 的虚拟机",
|
||||
"validate.missing_name": "虚拟机名称不能为空",
|
||||
"validate.invalid_cpus": "虚拟处理器核数须在 1 到 %d 之间",
|
||||
"validate.invalid_memory": "分配内存不能小于 2G(如 8G、16G)",
|
||||
"validate.memory_exceeds_host": "分配内存 %.0fG 超出宿主安全上限(宿主共 %.1f GB)",
|
||||
"validate.memory_exceeds_commit": "分配内存 %.0fG 超出 Windows 提交上限(含页面文件共 %.1f GB);请设为 %.0fG 或更低",
|
||||
"validate.missing_release": "请选择要离线安装的 macOS 版本",
|
||||
"validate.invalid_disk_size": "新建磁盘上限不能小于 32G(推荐 128G)",
|
||||
"validate.disk_not_found": "所选虚拟磁盘文件不存在",
|
||||
"validate.invalid_disk_controller": "磁盘控制器仅支持 nvme、ahci 或 virtio",
|
||||
"validate.installer_not_found": "所选安装镜像文件不存在",
|
||||
"validate.gpu_icd_not_found": "所选 Vulkan ICD JSON 文件不存在",
|
||||
"validate.invalid_resolution": "分辨率格式须为 宽x高(如 1920x1080)",
|
||||
"validate.invalid_displays": "显示器数量须在 1 到 4 之间",
|
||||
"validate.invalid_ssh_port": "SSH 端口须在 0 到 65535 之间",
|
||||
"validate.graphics_requires_stop": "切换图形后端前须先关闭虚拟机(需要重建 OpenCore)",
|
||||
"validate.eject_before_controller_change": "切换磁盘控制器前须先弹出 macOS 安装盘",
|
||||
"validate.invalid_audio_backend": "不支持的音频后端 %q",
|
||||
"tray.running.one": "Reims-Go — 1 台虚拟机运行中",
|
||||
"tray.running.many": "Reims-Go — %d 台虚拟机运行中",
|
||||
},
|
||||
EnUS: {
|
||||
"doctor.title": "Reims-Go Host Environment Check",
|
||||
"doctor.os": "Operating System",
|
||||
"doctor.cpu": "CPU & Core Topology",
|
||||
"doctor.pcores": "P-Cores (Performance)",
|
||||
"doctor.pcores.detail": "%d cores, mask %s (CPUs %v)",
|
||||
"doctor.ecores": "E-Cores (Efficiency)",
|
||||
"doctor.ecores.detail": "%d cores (CPUs %v)",
|
||||
"doctor.ram": "Host Memory",
|
||||
"doctor.ram.detail": "%.1f GB total / %.1f GB avail",
|
||||
"doctor.disk": "Data Drive Free Space",
|
||||
"doctor.whpx": "Windows Hypervisor Platform (WHPX)",
|
||||
"doctor.whpx.ok": "Ready (WinHvPlatform.dll active, hypervisor running)",
|
||||
"doctor.whpx.no_hv": "WinHvPlatform.dll present, but no hypervisor detected (enable VT-x/AMD-V in BIOS)",
|
||||
"doctor.whpx.missing": "Not enabled (enable Windows Hypervisor Platform and restart Windows)",
|
||||
"doctor.whpx.unsupported": "Non-Windows host (cross-platform dev mode)",
|
||||
"doctor.gpu": "Vulkan GPUs",
|
||||
"doctor.gpu.none": "No registered Vulkan ICD driver found",
|
||||
"doctor.gpu.recommended": "Recommended",
|
||||
"doctor.gpu.compat.supported": "Supported",
|
||||
"doctor.gpu.compat.warn": "Known compatibility issue",
|
||||
"doctor.gpu.compat.unsupported": "Unsupported for vGPU",
|
||||
"doctor.gpu.compat.unknown": "Vulkan capabilities unverified",
|
||||
"doctor.gpu.warn.amd_legacy": "AMD Vega/Polaris on Windows hits known upstream black-screen/device-loss issues (%s); prefer another discrete GPU or switch the VM to VMware SVGA",
|
||||
"doctor.gpu.warn.amd_rdna2": "This AMD GPU hits known Windows device-loss issues upstream (%s); update drivers or switch temporarily to VMware SVGA if it freezes",
|
||||
"doctor.gpu.err.vulkan_too_old": "Vulkan %s is below the required 1.3 floor; update your GPU driver or use VMware SVGA",
|
||||
"doctor.gpu.err.missing_ext": "Missing required Vulkan extensions (%s); update your GPU driver or use VMware SVGA",
|
||||
"doctor.gpu.err.vulkan_cpu": "Software Vulkan implementation does not meet the vGPU floor; use VMware SVGA instead",
|
||||
"err.gpu_device_lost": "Host Vulkan GPU device lost (ERROR_DEVICE_LOST). Update GPU drivers; on affected AMD Vega/Polaris GPUs, switch to another discrete GPU or use VMware SVGA in VM Settings",
|
||||
"err.gpu_vulkan_floor": "Host GPU does not meet Reims vGPU's Vulkan 1.3 requirements. Update GPU drivers or switch graphics to VMware SVGA (software rendering) in VM Settings",
|
||||
"doctor.runtime": "Portable Runtime",
|
||||
"doctor.runtime.none": "Not installed (run `reims-go runtime install <archive>`)",
|
||||
"doctor.runtime.active": "Active: %s (%s)",
|
||||
"runtime.installed": "Portable runtime installed: %s -> %s",
|
||||
"runtime.activated": "Active runtime switched to: %s",
|
||||
"runtime.removed": "Removed runtime: %s (%s)",
|
||||
"runtime.remove_active": "cannot remove active runtime %q; switch to another version first",
|
||||
"runtime.remove_in_use": "runtime %q is in use by a running VM; stop the VM and try again",
|
||||
"runtime.empty": "No portable runtimes installed.",
|
||||
"runtime.not_found": "runtime %q not found",
|
||||
"vm.empty": "No virtual machines found.",
|
||||
"vm.typed": "Typed %d keys.",
|
||||
"vm.already_running": "%s is already running",
|
||||
"vm.resize.stop_first": "stop %s before resizing its disk",
|
||||
"vm.resize.done": "%s: expanded disk %.0f GB -> %.0f GB\nRun inside macOS Terminal to expand APFS:\n %s",
|
||||
"vm.compact.stop_first": "stop %s before compacting its disk",
|
||||
"vm.compact.done": "%s: compacted disk %.2f GB -> %.2f GB (reclaimed %.2f GB)",
|
||||
"vm.install_guide.title": "macOS Setup Steps (Recovery UI):",
|
||||
"vm.install_guide.step1": "1. Open 'Disk Utility', select 'QEMU HARDDISK Media', and Erase as APFS.",
|
||||
"vm.install_guide.step2": "2. Back in the Recovery window, choose 'Reinstall macOS' and install onto the disk you erased (it restarts a few times).",
|
||||
"vm.install_guide.step3": "3. When Setup Assistant appears, run `reims-go vm eject %s` (or click 'Exit recovery mode') to remove the installer at next start.",
|
||||
"err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install <archive>` first",
|
||||
"err.guest_tools_disabled": "Guest Tools Transport is turned off on the Plugins page; turn it on to use clipboard, shared folders and keep-awake",
|
||||
"err.update_dev_build": "In-app update is disabled in development builds",
|
||||
"err.update_none": "Already up to date",
|
||||
"err.update_no_asset": "This release has no Windows executable; download it from the release page",
|
||||
"err.update_no_sums": "This release has no SHA256SUMS.txt to verify the download against; update stopped",
|
||||
"err.update_not_ready": "Download the update first",
|
||||
"err.update_changed": "The downloaded update changed on disk; download it again",
|
||||
"err.update_not_writable": "Can't write to the folder Reims-Go runs from (%s); move it somewhere writable, or update from the release page",
|
||||
"err.update_relaunch": "The new version is installed but didn't reopen; start Reims-Go again",
|
||||
"err.commit_memory": "Not enough memory to start: this VM needs %.0f GB and Windows can commit only %.1f GB more. Close some programs, or set its memory to %.0f GB",
|
||||
"err.whpx_missing": "Windows Hypervisor Platform (WHPX) is not enabled. Enable WHPX on the Host page and restart Windows before starting the VM",
|
||||
"err.whpx_no_hypervisor": "Windows Hypervisor is not active (unrelated to disk space). Ensure Intel VT-x / AMD SVM is enabled in BIOS, enable WHPX on the Host page, run `bcdedit /set hypervisorlaunchtype auto` as Administrator, and restart Windows",
|
||||
"err.whpx_unsupported": "Windows Hypervisor Platform (WHPX) is not supported on this OS; Windows 10 1803 or newer is required",
|
||||
"installer.paused": "Paused. Run `reims-go installer download %s` again to continue where it stopped.",
|
||||
"installer.done": "Offline installer ready: macOS %s -> %s",
|
||||
"installer.cached.empty": "No installers downloaded yet.",
|
||||
"installer.cached.total": "%s in %s",
|
||||
"installer.partial": "(partly downloaded)",
|
||||
"runtime.remote.empty": "No runtime is published on this channel yet (add --alpha for alpha builds).",
|
||||
"runtime.remote.downloading": "Downloading runtime %s (%s, %s)",
|
||||
"runtime.remote.paused": "Paused. Run the same command again to continue where it stopped.",
|
||||
"plugin.installed": "Installed %s@%s (trust=%s, tier=%s)",
|
||||
"plugin.needs_approval": "Note: plugin requires high-risk permission approval; run: reims-go plugin enable --approve-high-risk %s",
|
||||
"plugin.linked": "Linked dev plugin %s@%s -> %s",
|
||||
"plugin.enabled": "Enabled %s",
|
||||
"plugin.disabled": "Disabled %s",
|
||||
"plugin.removed": "Removed %s (purge=%v)",
|
||||
"plugin.not_found": "plugin %q not found",
|
||||
"plugin.target_not_found": "plugin or directory %q not found",
|
||||
"plugin.doctor.errors": "plugin doctor found errors",
|
||||
"setup.err.empty": "choose a folder",
|
||||
"setup.err.not_abs": "%s is not a full path",
|
||||
"setup.err.whole_drive": "choose a folder, not a whole drive",
|
||||
"setup.err.comma": "the folder path can't contain ','",
|
||||
"setup.err.is_file": "%s is a file",
|
||||
"validate.invalid_name": "VM name must start with a letter/digit and use only A-Z, 0-9, ., _, -",
|
||||
"validate.name_taken": "A VM named %s already exists",
|
||||
"validate.missing_name": "VM name is required",
|
||||
"validate.invalid_cpus": "vCPUs must be between 1 and %d",
|
||||
"validate.invalid_memory": "Memory must be at least 2G (e.g. 8G, 16G)",
|
||||
"validate.memory_exceeds_host": "Memory %.0fG exceeds safe host limit (host total %.1f GB)",
|
||||
"validate.memory_exceeds_commit": "Memory %.0fG can't fit in Windows' commit limit (%.1f GB including the page file); choose %.0fG or less",
|
||||
"validate.missing_release": "Choose the macOS release to install offline",
|
||||
"validate.invalid_disk_size": "New disk size must be at least 32G (recommended 128G)",
|
||||
"validate.disk_not_found": "Selected disk image file does not exist",
|
||||
"validate.invalid_disk_controller": "Disk controller must be nvme, ahci, or virtio",
|
||||
"validate.installer_not_found": "Selected installer image file does not exist",
|
||||
"validate.gpu_icd_not_found": "Selected Vulkan ICD JSON file does not exist",
|
||||
"validate.invalid_resolution": "Resolution must match WIDTHxHEIGHT (e.g. 1920x1080)",
|
||||
"validate.invalid_displays": "Displays must be between 1 and 4",
|
||||
"validate.invalid_ssh_port": "SSH port must be 0..65535",
|
||||
"validate.graphics_requires_stop": "Stop the VM before switching graphics type (OpenCore must be rebuilt)",
|
||||
"validate.eject_before_controller_change": "Eject the macOS installer before changing disk controller",
|
||||
"validate.invalid_audio_backend": "Unsupported audio backend %q",
|
||||
"tray.running.one": "Reims-Go — 1 VM running",
|
||||
"tray.running.many": "Reims-Go — %d VMs running",
|
||||
},
|
||||
}
|
||||
|
||||
// T looks up a localized template and formats optional args.
|
||||
func T(loc Locale, key string, args ...any) string {
|
||||
canon := ResolveLocale(string(loc))
|
||||
tmpl := lookupTemplate(canon, key)
|
||||
if len(args) == 0 {
|
||||
return tmpl
|
||||
// EffectiveLocale computes the concrete runtime Locale for a preference:
|
||||
// - If pref is "auto" or empty, matches DetectOSLocaleTag() against active
|
||||
// plugin catalogs via FallbackChain (e.g. OS "zh-HK" matches an installed
|
||||
// "zh-TW" pack; OS "ja-JP" matches an installed "ja-JP" pack; otherwise
|
||||
// gracefully falls back to built-in zh-CN or en-US).
|
||||
// - If pref is a concrete non-built-in tag (e.g. "ja-JP"), verifies that an
|
||||
// active language pack covers it (or a fallback hop); if the pack was
|
||||
// disabled/uninstalled or safe mode is active, falls back cleanly.
|
||||
func EffectiveLocale(pref Locale) Locale {
|
||||
var target Locale
|
||||
s := strings.TrimSpace(string(pref))
|
||||
if s != "" && !strings.EqualFold(s, string(Auto)) {
|
||||
if loc, ok := ParseLocale(s); ok {
|
||||
target = loc
|
||||
} else {
|
||||
return Normalize(s)
|
||||
}
|
||||
} else {
|
||||
target = DetectOSLocaleTag()
|
||||
}
|
||||
return fmt.Sprintf(tmpl, args...)
|
||||
}
|
||||
|
||||
func lookupTemplate(loc Locale, key string) string {
|
||||
if target == ZhCN || target == EnUS || target == EnXA {
|
||||
return target
|
||||
}
|
||||
chain := FallbackChain(target)
|
||||
pluginCatalogMu.RLock()
|
||||
pPack, hasPlugin := pluginCatalogs[loc]
|
||||
var pFallback PluginCatalog
|
||||
fb := DefaultFallback(loc)
|
||||
if hasPlugin && pPack.Fallback != "" {
|
||||
fb = pPack.Fallback
|
||||
}
|
||||
if pPack.Messages != nil {
|
||||
if v, ok := pPack.Messages[key]; ok {
|
||||
for _, cand := range chain {
|
||||
if cand == ZhCN || cand == EnUS || cand == EnXA {
|
||||
pluginCatalogMu.RUnlock()
|
||||
return v
|
||||
return cand
|
||||
}
|
||||
if _, ok := pluginCatalogs[cand]; ok {
|
||||
pluginCatalogMu.RUnlock()
|
||||
return cand
|
||||
}
|
||||
}
|
||||
if fb != loc {
|
||||
pFallback = pluginCatalogs[fb]
|
||||
pluginCatalogMu.RUnlock()
|
||||
if primarySubtag(string(target)) == "zh" {
|
||||
return ZhCN
|
||||
}
|
||||
return EnUS
|
||||
}
|
||||
|
||||
// Detect returns the effective active locale for the current environment and
|
||||
// installed plugin catalogs.
|
||||
func Detect() Locale {
|
||||
return EffectiveLocale(Auto)
|
||||
}
|
||||
|
||||
// FallbackChain builds a deterministic, cycle-free multi-hop fallback sequence
|
||||
// (bounded to 8 entries) for a requested locale tag:
|
||||
//
|
||||
// requested -> plugin fallback chain -> CLDR macro/script relatives -> parent subtags -> built-in default -> secondary built-in
|
||||
func FallbackChain(loc Locale) []Locale {
|
||||
const maxHops = 8
|
||||
start := loc
|
||||
if start == "" || strings.EqualFold(string(start), string(Auto)) {
|
||||
start = EffectiveLocale(Auto)
|
||||
} else if parsed, ok := ParseLocale(string(start)); ok {
|
||||
start = parsed
|
||||
} else {
|
||||
start = Normalize(string(start))
|
||||
}
|
||||
|
||||
out := make([]Locale, 0, maxHops)
|
||||
seen := make(map[Locale]struct{}, maxHops)
|
||||
add := func(cand Locale) {
|
||||
if cand == "" || cand == Auto || len(out) >= maxHops {
|
||||
return
|
||||
}
|
||||
if _, dup := seen[cand]; dup {
|
||||
return
|
||||
}
|
||||
seen[cand] = struct{}{}
|
||||
out = append(out, cand)
|
||||
}
|
||||
|
||||
add(start)
|
||||
if start == EnXA {
|
||||
add(EnUS)
|
||||
add(ZhCN)
|
||||
return out
|
||||
}
|
||||
|
||||
// 1. Follow multi-hop plugin-declared fallback links safely.
|
||||
pluginCatalogMu.RLock()
|
||||
cur := start
|
||||
for range 4 {
|
||||
p, ok := pluginCatalogs[cur]
|
||||
if !ok || p.Fallback == "" {
|
||||
break
|
||||
}
|
||||
if _, dup := seen[p.Fallback]; dup {
|
||||
break
|
||||
}
|
||||
add(p.Fallback)
|
||||
cur = p.Fallback
|
||||
}
|
||||
pluginCatalogMu.RUnlock()
|
||||
|
||||
if table, ok := catalog[loc]; ok {
|
||||
if v, ok := table[key]; ok {
|
||||
return v
|
||||
// 2. CLDR regional & Chinese script affinity rules.
|
||||
low := strings.ToLower(string(start))
|
||||
switch {
|
||||
case low == "zh-hk" || low == "zh-mo" || strings.HasPrefix(low, "zh-hant-hk") || strings.HasPrefix(low, "zh-hant-mo"):
|
||||
add(Locale("zh-Hant"))
|
||||
add(Locale("zh-TW"))
|
||||
add(ZhCN)
|
||||
case low == "zh-tw" || low == "zh-hant" || strings.HasPrefix(low, "zh-hant"):
|
||||
add(Locale("zh-Hant"))
|
||||
add(Locale("zh-TW"))
|
||||
add(ZhCN)
|
||||
case strings.HasPrefix(low, "zh"):
|
||||
add(ZhCN)
|
||||
}
|
||||
|
||||
// 3. Progressive BCP-47 right-subtag truncation (e.g. "pt-BR" -> "pt").
|
||||
parts := strings.Split(string(start), "-")
|
||||
for n := len(parts) - 1; n >= 1; n-- {
|
||||
parentRaw := strings.Join(parts[:n], "-")
|
||||
if parent, ok := ParseLocale(parentRaw); ok {
|
||||
add(parent)
|
||||
}
|
||||
}
|
||||
if pFallback.Messages != nil {
|
||||
if v, ok := pFallback.Messages[key]; ok {
|
||||
return v
|
||||
}
|
||||
|
||||
// 4. Guaranteed built-in anchors.
|
||||
if primarySubtag(string(start)) == "zh" {
|
||||
add(ZhCN)
|
||||
add(EnUS)
|
||||
} else {
|
||||
add(EnUS)
|
||||
add(ZhCN)
|
||||
}
|
||||
if table, ok := catalog[fb]; ok {
|
||||
if v, ok := table[key]; ok {
|
||||
return v
|
||||
return out
|
||||
}
|
||||
|
||||
// M evaluates a localized ICU message with named variables and multi-hop fallback.
|
||||
func M(loc Locale, key string, vars Vars) string {
|
||||
chain := FallbackChain(ResolveLocale(string(loc)))
|
||||
for _, step := range chain {
|
||||
if step == EnXA {
|
||||
if enTmpl, ok := catalog[EnUS][key]; ok {
|
||||
pseudo := PseudoLocalize(enTmpl)
|
||||
if res, err := FormatICU(EnUS, pseudo, vars, false); err == nil {
|
||||
return res
|
||||
}
|
||||
return pseudo
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
pluginCatalogMu.RLock()
|
||||
pPack, hasPlugin := pluginCatalogs[step]
|
||||
var pluginMsg string
|
||||
if hasPlugin && pPack.Messages != nil {
|
||||
pluginMsg = pPack.Messages[key]
|
||||
}
|
||||
pluginCatalogMu.RUnlock()
|
||||
|
||||
if pluginMsg != "" {
|
||||
if res, err := FormatICU(step, pluginMsg, vars, len(vars) > 0); err == nil {
|
||||
return res
|
||||
}
|
||||
// Malformed third-party ICU string or unknown variable: isolate fault
|
||||
// to this single key and fall back to the next locale in chain.
|
||||
}
|
||||
|
||||
if table, ok := catalog[step]; ok {
|
||||
if baseMsg, ok := table[key]; ok {
|
||||
if res, err := FormatICU(step, baseMsg, vars, false); err == nil {
|
||||
return res
|
||||
}
|
||||
return baseMsg
|
||||
}
|
||||
}
|
||||
}
|
||||
if v, ok := catalog[EnUS][key]; ok {
|
||||
return v
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
// T looks up a localized template and formats optional named Vars or positional args.
|
||||
// New callers should prefer M(loc, key, Vars{...}); positional args are mapped onto
|
||||
// each built-in key's declared parameter order for full backwards compatibility.
|
||||
func T(loc Locale, key string, args ...any) string {
|
||||
if len(args) == 0 {
|
||||
return M(loc, key, nil)
|
||||
}
|
||||
if len(args) == 1 {
|
||||
switch m := args[0].(type) {
|
||||
case Vars:
|
||||
return M(loc, key, m)
|
||||
case map[string]any:
|
||||
return M(loc, key, Vars(m))
|
||||
}
|
||||
}
|
||||
|
||||
vars := make(Vars, len(args)*2)
|
||||
names := paramOrder[key]
|
||||
for i, a := range args {
|
||||
vars[strconv.Itoa(i)] = a
|
||||
if i < len(names) {
|
||||
vars[names[i]] = a
|
||||
}
|
||||
}
|
||||
return M(loc, key, vars)
|
||||
}
|
||||
+245
-37
@@ -1,7 +1,11 @@
|
||||
package i18n
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -23,32 +27,30 @@ func TestBilingualCatalog(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
var fmtVerbRe = regexp.MustCompile(`%(?:\.\d+)?[sdfqv%]`)
|
||||
|
||||
func extractFormatVerbs(s string) []string {
|
||||
raw := fmtVerbRe.FindAllString(s, -1)
|
||||
out := make([]string, 0, len(raw))
|
||||
for _, v := range raw {
|
||||
if v != "%%" {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestCatalogKeyAndFormatParity(t *testing.T) {
|
||||
func TestCatalogKeyAndICUPlaceholderParity(t *testing.T) {
|
||||
zh := catalog[ZhCN]
|
||||
en := catalog[EnUS]
|
||||
if len(zh) == 0 {
|
||||
t.Fatal("generated catalog is empty")
|
||||
}
|
||||
for k, zhVal := range zh {
|
||||
enVal, ok := en[k]
|
||||
if !ok {
|
||||
t.Errorf("key %q exists in zh-CN but missing in en-US", k)
|
||||
continue
|
||||
}
|
||||
zhVerbs := strings.Join(extractFormatVerbs(zhVal), ",")
|
||||
enVerbs := strings.Join(extractFormatVerbs(enVal), ",")
|
||||
if zhVerbs != enVerbs {
|
||||
t.Errorf("format verbs mismatch for %q: zh=%q en=%q", k, zhVerbs, enVerbs)
|
||||
_, zhVars, zErr := ParseICU(zhVal)
|
||||
if zErr != nil {
|
||||
t.Errorf("zh-CN key %q invalid ICU: %v", k, zErr)
|
||||
continue
|
||||
}
|
||||
_, enVars, eErr := ParseICU(enVal)
|
||||
if eErr != nil {
|
||||
t.Errorf("en-US key %q invalid ICU: %v", k, eErr)
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(zhVars, enVars) {
|
||||
t.Errorf("ICU vars mismatch for %q: zh=%v en=%v", k, zhVars, enVars)
|
||||
}
|
||||
}
|
||||
for k := range en {
|
||||
@@ -58,9 +60,12 @@ func TestCatalogKeyAndFormatParity(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectPrecedenceAndOSLocale(t *testing.T) {
|
||||
func TestDetectPrecedenceAutoAndDynamicPluginMatch(t *testing.T) {
|
||||
old := osLocaleFn
|
||||
t.Cleanup(func() { osLocaleFn = old })
|
||||
t.Cleanup(func() {
|
||||
osLocaleFn = old
|
||||
SetPluginCatalogs(nil)
|
||||
})
|
||||
|
||||
t.Setenv("REIMS_GO_LANG", "")
|
||||
t.Setenv("LC_ALL", "")
|
||||
@@ -71,12 +76,32 @@ func TestDetectPrecedenceAndOSLocale(t *testing.T) {
|
||||
t.Fatalf("OS en-US -> %s, want en-US", got)
|
||||
}
|
||||
osLocaleFn = func() string { return "ja-JP" }
|
||||
if got := Detect(); got != EnUS {
|
||||
t.Fatalf("OS ja-JP -> %s, want en-US", got)
|
||||
if raw := DetectOSLocaleTag(); raw != Locale("ja-JP") {
|
||||
t.Fatalf("DetectOSLocaleTag(ja-JP) = %q, want ja-JP", raw)
|
||||
}
|
||||
// Without a ja-JP language pack installed, EffectiveLocale(Auto) falls back to en-US.
|
||||
if got := Detect(); got != EnUS {
|
||||
t.Fatalf("OS ja-JP without pack -> %s, want en-US", got)
|
||||
}
|
||||
// Installing a ja-JP language pack automatically activates ja-JP in Auto mode!
|
||||
SetPluginCatalogs(map[Locale]PluginCatalog{
|
||||
Locale("ja-JP"): {Fallback: EnUS, Messages: map[string]string{"doctor.os": "OS"}},
|
||||
Locale("zh-TW"): {Fallback: ZhCN, Messages: map[string]string{"doctor.os": "作業系統"}},
|
||||
})
|
||||
if got := EffectiveLocale(Auto); got != Locale("ja-JP") {
|
||||
t.Fatalf("OS ja-JP with pack -> %s, want ja-JP", got)
|
||||
}
|
||||
|
||||
// OS zh-HK matches installed zh-TW pack via CLDR regional affinity!
|
||||
osLocaleFn = func() string { return "zh-HK" }
|
||||
if got := EffectiveLocale(Auto); got != Locale("zh-TW") {
|
||||
t.Fatalf("OS zh-HK with zh-TW pack -> %s, want zh-TW", got)
|
||||
}
|
||||
|
||||
SetPluginCatalogs(nil)
|
||||
osLocaleFn = func() string { return "zh-TW" }
|
||||
if got := Detect(); got != ZhCN {
|
||||
t.Fatalf("OS zh-TW -> %s, want zh-CN", got)
|
||||
t.Fatalf("OS zh-TW without pack -> %s, want zh-CN", got)
|
||||
}
|
||||
osLocaleFn = func() string { return "" }
|
||||
if got := Detect(); got != ZhCN {
|
||||
@@ -103,10 +128,13 @@ func TestParseLocaleAndResolve(t *testing.T) {
|
||||
{"zh_CN.UTF-8", ZhCN, true},
|
||||
{"zh-Hans", ZhCN, true},
|
||||
{"en_US.UTF-8", EnUS, true},
|
||||
{"en-xa", EnXA, true},
|
||||
{"ja_jp", Locale("ja-JP"), true},
|
||||
{"zh-tw", Locale("zh-TW"), true},
|
||||
{"zh-sg", Locale("zh-SG"), true},
|
||||
{"zh-hant-hk", Locale("zh-Hant-HK"), true},
|
||||
{"ko", Locale("ko"), true},
|
||||
{"auto", "", false},
|
||||
{"", "", false},
|
||||
{"../evil", "", false},
|
||||
{"123-45", "", false},
|
||||
@@ -117,6 +145,9 @@ func TestParseLocaleAndResolve(t *testing.T) {
|
||||
t.Errorf("ParseLocale(%q) = (%q, %v), want (%q, %v)", tc.in, got, ok, tc.want, tc.ok)
|
||||
}
|
||||
}
|
||||
if pref := ParsePreference("auto"); pref != Auto {
|
||||
t.Fatalf("ParsePreference(auto) = %q, want auto", pref)
|
||||
}
|
||||
if got := ResolveLocale("ja-JP"); got != Locale("ja-JP") {
|
||||
t.Fatalf("ResolveLocale(ja-JP) = %q, want ja-JP", got)
|
||||
}
|
||||
@@ -125,33 +156,210 @@ func TestParseLocaleAndResolve(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginCatalogOverlayAndFallback(t *testing.T) {
|
||||
func TestMultiHopFallbackAndFaultIsolation(t *testing.T) {
|
||||
t.Cleanup(func() { SetPluginCatalogs(nil) })
|
||||
|
||||
SetPluginCatalogs(map[Locale]PluginCatalog{
|
||||
Locale("ja-JP"): {
|
||||
Fallback: EnUS,
|
||||
Locale("zh-MO"): {
|
||||
Fallback: Locale("zh-HK"),
|
||||
Messages: map[string]string{
|
||||
"doctor.os": "オペレーティングシステム",
|
||||
"doctor.title": "澳門環境檢查",
|
||||
// Deliberately broken ICU brace & unknown variable to test fault isolation
|
||||
"runtime.installed": "已安裝 {brokenUnclosed",
|
||||
"vm.already_running": "{typoUnknownVar} 運行中",
|
||||
},
|
||||
},
|
||||
Locale("zh-HK"): {
|
||||
Fallback: Locale("zh-TW"),
|
||||
Messages: map[string]string{
|
||||
"doctor.cpu": "處理器與核心拓撲(香港)",
|
||||
},
|
||||
},
|
||||
Locale("zh-TW"): {
|
||||
Fallback: ZhCN,
|
||||
Messages: map[string]string{
|
||||
"doctor.os": "作業系統",
|
||||
"doctor.os": "作業系統",
|
||||
"runtime.installed": "已安裝可攜式執行環境:{commit} -> {dir}",
|
||||
"vm.already_running": "{name} 正在執行中",
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if got := T(Locale("ja-JP"), "doctor.os"); got != "オペレーティングシステム" {
|
||||
t.Fatalf("ja-JP doctor.os = %q", got)
|
||||
// Hop 0: zh-MO
|
||||
if got := T(Locale("zh-MO"), "doctor.title"); got != "澳門環境檢查" {
|
||||
t.Fatalf("hop 0 = %q", got)
|
||||
}
|
||||
// Missing key falls back to en-US for ja-JP.
|
||||
if got := T(Locale("ja-JP"), "doctor.ram"); got != "Host Memory" {
|
||||
t.Fatalf("ja-JP fallback doctor.ram = %q, want Host Memory", got)
|
||||
// Hop 1: zh-HK
|
||||
if got := T(Locale("zh-MO"), "doctor.cpu"); got != "處理器與核心拓撲(香港)" {
|
||||
t.Fatalf("hop 1 = %q", got)
|
||||
}
|
||||
// Missing key falls back to zh-CN for zh-TW.
|
||||
if got := T(Locale("zh-TW"), "doctor.ram"); got != "宿主机内存" {
|
||||
t.Fatalf("zh-TW fallback doctor.ram = %q, want 宿主机内存", got)
|
||||
// Hop 2: zh-TW
|
||||
if got := T(Locale("zh-MO"), "doctor.os"); got != "作業系統" {
|
||||
t.Fatalf("hop 2 = %q", got)
|
||||
}
|
||||
// Hop 3: zh-CN built-in
|
||||
if got := T(Locale("zh-MO"), "doctor.ram"); got != "宿主机内存" {
|
||||
t.Fatalf("hop 3 = %q", got)
|
||||
}
|
||||
// Fault isolation: broken zh-MO template falls back cleanly to zh-TW!
|
||||
if got := M(Locale("zh-MO"), "runtime.installed", Vars{"commit": "abc1234", "dir": "D:\\rt"}); got != "已安裝可攜式執行環境:abc1234 -> D:\\rt" {
|
||||
t.Fatalf("fault isolation syntax = %q", got)
|
||||
}
|
||||
if got := M(Locale("zh-MO"), "vm.already_running", Vars{"name": "sequoia"}); got != "sequoia 正在執行中" {
|
||||
t.Fatalf("fault isolation missing var = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestICUSinglePassPluralsAndPseudoLocale(t *testing.T) {
|
||||
// Single-pass safety: value of {commit} containing "{dir}" must NOT be expanded!
|
||||
got := M(EnUS, "runtime.installed", Vars{"commit": "v1-{dir}", "dir": "REAL_DIR"})
|
||||
if got != "Portable runtime installed: v1-{dir} -> REAL_DIR" {
|
||||
t.Fatalf("single-pass violated: %q", got)
|
||||
}
|
||||
|
||||
// Plural rules: English 1 vs 3, Russian 1/2/5, Arabic 0/2/5/15
|
||||
if s := M(EnUS, "tray.running", Vars{"count": 1}); s != "Reims-Go — 1 VM running" {
|
||||
t.Fatalf("en plural 1 = %q", s)
|
||||
}
|
||||
if s := M(EnUS, "tray.running", Vars{"count": 3}); s != "Reims-Go — 3 VMs running" {
|
||||
t.Fatalf("en plural 3 = %q", s)
|
||||
}
|
||||
ruTmpl := "{n, plural, one {# машина} few {# машины} many {# машин} other {# машин}}"
|
||||
if s, err := FormatICU(Locale("ru-RU"), ruTmpl, Vars{"n": 2}, true); err != nil || s != "2 машины" {
|
||||
t.Fatalf("ru plural 2 = %q, err=%v", s, err)
|
||||
}
|
||||
if s, err := FormatICU(Locale("ru-RU"), ruTmpl, Vars{"n": 5}, true); err != nil || s != "5 машин" {
|
||||
t.Fatalf("ru plural 5 = %q, err=%v", s, err)
|
||||
}
|
||||
|
||||
// Decimal comma formatting in German
|
||||
if s, err := FormatICU(Locale("de-DE"), "{gb, number, .1} GB", Vars{"gb": 16.5}, true); err != nil || s != "16,5 GB" {
|
||||
t.Fatalf("de-DE decimal = %q, err=%v", s, err)
|
||||
}
|
||||
|
||||
// Pseudo-locale en-XA preserves {vars} and wraps in ⟦...⟧
|
||||
pseudo := M(EnXA, "vm.already_running", Vars{"name": "TahoeVM"})
|
||||
if !strings.HasPrefix(pseudo, "⟦") || !strings.HasSuffix(pseudo, "⟧") || !strings.Contains(pseudo, "TahoeVM") {
|
||||
t.Fatalf("en-XA pseudo = %q", pseudo)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatGuestTermDualAnnotation(t *testing.T) {
|
||||
// Same language: concise single term with CJK corner brackets
|
||||
if got := FormatGuestTerm(ZhCN, "zh-Hans:0", "macos.diskUtility", true); got != "「磁盘工具」" {
|
||||
t.Fatalf("zh host + zh-Hans guest = %q", got)
|
||||
}
|
||||
// Host zh-CN + Guest en-US: dual annotation!
|
||||
if got := FormatGuestTerm(ZhCN, "en-US:0", "macos.diskUtility", true); got != "「磁盘工具 (Disk Utility)」" {
|
||||
t.Fatalf("zh host + en-US guest = %q", got)
|
||||
}
|
||||
// Host zh-CN + Guest ja-JP: dual annotation with official Apple Japanese term!
|
||||
if got := FormatGuestTerm(ZhCN, "ja-JP:0", "macos.diskUtility", true); got != "「磁盘工具 (ディスクユーティリティ)」" {
|
||||
t.Fatalf("zh host + ja-JP guest = %q", got)
|
||||
}
|
||||
// Host en-US + Guest zh-Hant: English style dual annotation with Apple Traditional Chinese term!
|
||||
if got := FormatGuestTerm(EnUS, "zh-Hant:0", "macos.diskUtility", true); got != "Disk Utility (磁碟工具程式)" {
|
||||
t.Fatalf("en host + zh-Hant guest = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodedErrorSupportability(t *testing.T) {
|
||||
ce := NewCodedError(ZhCN, "E_VM_CLONE_RUNNING", "err.clone.source_running", Vars{"name": "macOS-15"}, io.ErrUnexpectedEOF)
|
||||
if !errors.Is(ce, io.ErrUnexpectedEOF) {
|
||||
t.Fatal("Unwrap failed")
|
||||
}
|
||||
wire := ce.Error()
|
||||
if !strings.Contains(wire, "[E_VM_CLONE_RUNNING]") || !strings.Contains(wire, "macOS-15") || !strings.Contains(wire, "[detail] unexpected EOF") {
|
||||
t.Fatalf("unexpected wire format: %q", wire)
|
||||
}
|
||||
cliEn := FormatCLIError(EnUS, ce)
|
||||
if !strings.HasPrefix(cliEn, "[E_VM_CLONE_RUNNING] Stop “macOS-15”") {
|
||||
t.Fatalf("FormatCLIError(EnUS) = %q", cliEn)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityAndAuditRegressions(t *testing.T) {
|
||||
defer SetPluginCatalogs(nil)
|
||||
|
||||
// H-1: Malicious printf width specifiers must never trigger multi-hundred-MB Sprintf allocations,
|
||||
// literal '%' must survive intact, and legacy v1 %s/%d positional templates rewrite cleanly.
|
||||
SetPluginCatalogs(map[Locale]PluginCatalog{
|
||||
Locale("de-DE"): {
|
||||
Fallback: EnUS,
|
||||
Messages: map[string]string{
|
||||
"test.width_dos": "%999999999s",
|
||||
"test.literal": "100% offline",
|
||||
"test.positional": "%s -> %d",
|
||||
},
|
||||
},
|
||||
})
|
||||
if got := T(Locale("de-DE"), "test.width_dos", "x"); got != "%999999999s" {
|
||||
t.Fatalf("expected unexpanded width specifier, got len=%d (%q)", len(got), got[:min(len(got), 32)])
|
||||
}
|
||||
if got := T(Locale("de-DE"), "test.literal", "unused"); got != "100% offline" {
|
||||
t.Fatalf("literal percent corrupted: %q", got)
|
||||
}
|
||||
if got := T(Locale("de-DE"), "test.positional", "disk0", 42); got != "disk0 -> 42" {
|
||||
t.Fatalf("legacy positional rewrite failed: %q", got)
|
||||
}
|
||||
|
||||
// M-7: EffectiveLocale must fall back when a configured locale pack is absent/disabled,
|
||||
// and activate once registered.
|
||||
if got := EffectiveLocale("de-DE"); got != Locale("de-DE") {
|
||||
t.Fatalf("EffectiveLocale(active de-DE) = %q, want de-DE", got)
|
||||
}
|
||||
SetPluginCatalogs(nil)
|
||||
if got := EffectiveLocale("ja-JP"); got != EnUS {
|
||||
t.Fatalf("EffectiveLocale(inactive ja-JP) = %q, want en-US", got)
|
||||
}
|
||||
if got := EffectiveLocale("zh-HK"); got != ZhCN {
|
||||
t.Fatalf("EffectiveLocale(inactive zh-HK) = %q, want zh-CN", got)
|
||||
}
|
||||
|
||||
// H-2: CodedError must redact SMC OSK, serials, MAC addresses, Bearer tokens, and cap length.
|
||||
leakyErr := errors.New(`qemu args: osk=SYNTHETIC_OSK_FIXTURE_DO_NOT_USE serial=FAKE0000TEST mac=02:00:00:00:00:01 Authorization: Bearer secret_jwt_token_123456 "token":"tok_secret_987654321"`)
|
||||
ce := NewCodedError(EnUS, "E_QEMU_ARGS", "err.clone.source_running", Vars{"name": "Tahoe"}, leakyErr)
|
||||
for _, surface := range []string{ce.Error(), FormatCLIError(EnUS, ce)} {
|
||||
for _, forbidden := range []string{
|
||||
"SYNTHETIC_OSK_FIXTURE",
|
||||
"FAKE0000TEST",
|
||||
"02:00:00:00:00:01",
|
||||
"secret_jwt_token_123456",
|
||||
"tok_secret_987654321",
|
||||
} {
|
||||
if strings.Contains(surface, forbidden) {
|
||||
t.Fatalf("secret %q leaked in surface %q", forbidden, surface)
|
||||
}
|
||||
}
|
||||
}
|
||||
hugeDetail := ce.WithDetail(strings.Repeat("x", 16384))
|
||||
if len(hugeDetail.RawDetail) > 9000 {
|
||||
t.Fatalf("expected detail cap <= 9KB, got %d bytes", len(hugeDetail.RawDetail))
|
||||
}
|
||||
|
||||
// M-6 & L-3: ICU plural/number safety on NaN/Inf/huge floats + bounded AST cache eviction.
|
||||
for _, extreme := range []float64{math.NaN(), math.Inf(1), math.Inf(-1), 1e25} {
|
||||
cat := SelectPluralCategory(Locale("ru-RU"), extreme)
|
||||
if cat != "other" {
|
||||
t.Fatalf("SelectPluralCategory(ru-RU, %v) = %q, want other", extreme, cat)
|
||||
}
|
||||
}
|
||||
for i := 0; i < 2300; i++ {
|
||||
tmpl := fmt.Sprintf("item-%d: {n, plural, one {# file} other {# files}}", i)
|
||||
out, err := FormatICU(EnUS, tmpl, Vars{"n": 2}, true)
|
||||
if err != nil || !strings.HasSuffix(out, "2 files") {
|
||||
t.Fatalf("icuCache iteration %d failed: out=%q err=%v", i, out, err)
|
||||
}
|
||||
}
|
||||
|
||||
// L-2: Unified 8-subtag RTL detection.
|
||||
for _, rtl := range []Locale{"ar-SA", "he-IL", "iw-IL", "fa-IR", "ur-PK", "ps-AF", "dv-MV", "yi"} {
|
||||
if !IsRTLLocale(rtl) || DirOf(rtl) != "rtl" {
|
||||
t.Fatalf("expected RTL for %q", rtl)
|
||||
}
|
||||
}
|
||||
if IsRTLLocale("ja-JP") || DirOf(EnUS) != "ltr" {
|
||||
t.Fatal("unexpected RTL for LTR locale")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,705 @@
|
||||
package i18n
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const maxICUCacheEntries = 2048
|
||||
|
||||
var (
|
||||
icuCacheMu sync.RWMutex
|
||||
icuCache = make(map[string][]icuNode, 256)
|
||||
)
|
||||
|
||||
func cachedICUNodes(tmpl string) ([]icuNode, error) {
|
||||
icuCacheMu.RLock()
|
||||
if nodes, ok := icuCache[tmpl]; ok {
|
||||
icuCacheMu.RUnlock()
|
||||
return nodes, nil
|
||||
}
|
||||
icuCacheMu.RUnlock()
|
||||
|
||||
nodes, err := parseICUNodes(tmpl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
icuCacheMu.Lock()
|
||||
if len(icuCache) >= maxICUCacheEntries {
|
||||
icuCache = make(map[string][]icuNode, 256)
|
||||
}
|
||||
icuCache[tmpl] = nodes
|
||||
icuCacheMu.Unlock()
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func parseICUNodes(tmpl string) ([]icuNode, error) {
|
||||
p := &icuParser{src: tmpl}
|
||||
nodes, err := p.parseNodes(false, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p.pos < len(p.src) {
|
||||
return nil, fmt.Errorf("unexpected '}' at byte %d", p.pos)
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// Vars holds named template arguments for lightweight ICU messages.
|
||||
type Vars map[string]any
|
||||
|
||||
type icuNodeKind int
|
||||
|
||||
const (
|
||||
nodeText icuNodeKind = iota
|
||||
nodePound
|
||||
nodeVar
|
||||
nodeNumber
|
||||
nodePlural
|
||||
nodeSelect
|
||||
)
|
||||
|
||||
type icuBranch struct {
|
||||
selector string
|
||||
nodes []icuNode
|
||||
}
|
||||
|
||||
type icuNode struct {
|
||||
kind icuNodeKind
|
||||
text string
|
||||
name string
|
||||
precision int // -1 when unspecified, >=0 for .0 / .1 / .2
|
||||
branches []icuBranch
|
||||
}
|
||||
|
||||
// ParseICU parses a lightweight ICU MessageFormat string into an AST and returns
|
||||
// the sorted, deduplicated list of referenced variable names.
|
||||
//
|
||||
// Supported forms:
|
||||
// - Plain text with ICU DOUBLE_OPTIONAL apostrophe quoting ('' -> ', '{' -> literal {)
|
||||
// - {name}
|
||||
// - {name, number} and {name, number, .0|.1|.2}
|
||||
// - {name, plural, =0 {...} =1 {...} zero {...} one {...} two {...} few {...} many {...} other {...}}
|
||||
// - {name, select, key1 {...} other {...}}
|
||||
// - # inside plural branches (replaced with locale-formatted plural value)
|
||||
func ParseICU(tmpl string) ([]icuNode, []string, error) {
|
||||
nodes, err := parseICUNodes(tmpl)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
varSet := make(map[string]struct{})
|
||||
collectVars(nodes, varSet)
|
||||
vars := make([]string, 0, len(varSet))
|
||||
for k := range varSet {
|
||||
vars = append(vars, k)
|
||||
}
|
||||
sort.Strings(vars)
|
||||
return nodes, vars, nil
|
||||
}
|
||||
|
||||
func collectVars(nodes []icuNode, out map[string]struct{}) {
|
||||
for _, n := range nodes {
|
||||
if n.name != "" {
|
||||
out[n.name] = struct{}{}
|
||||
}
|
||||
for _, b := range n.branches {
|
||||
collectVars(b.nodes, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type icuParser struct {
|
||||
src string
|
||||
pos int
|
||||
}
|
||||
|
||||
func (p *icuParser) parseNodes(stopAtBrace, inPlural bool) ([]icuNode, error) {
|
||||
var nodes []icuNode
|
||||
var buf strings.Builder
|
||||
flush := func() {
|
||||
if buf.Len() > 0 {
|
||||
nodes = append(nodes, icuNode{kind: nodeText, text: buf.String()})
|
||||
buf.Reset()
|
||||
}
|
||||
}
|
||||
|
||||
for p.pos < len(p.src) {
|
||||
ch := p.src[p.pos]
|
||||
if ch == '\'' {
|
||||
// ICU DOUBLE_OPTIONAL apostrophe rules:
|
||||
// '' -> literal '
|
||||
// '{', '}', '#' (when inPlural) -> quoted literal span until next '
|
||||
// Otherwise -> literal apostrophe (e.g. "Can't", "Don't").
|
||||
if p.pos+1 < len(p.src) && p.src[p.pos+1] == '\'' {
|
||||
buf.WriteByte('\'')
|
||||
p.pos += 2
|
||||
continue
|
||||
}
|
||||
if p.pos+1 < len(p.src) {
|
||||
next := p.src[p.pos+1]
|
||||
if next == '{' || next == '}' || (inPlural && next == '#') {
|
||||
p.pos++ // skip opening '
|
||||
for p.pos < len(p.src) {
|
||||
if p.src[p.pos] == '\'' {
|
||||
if p.pos+1 < len(p.src) && p.src[p.pos+1] == '\'' {
|
||||
buf.WriteByte('\'')
|
||||
p.pos += 2
|
||||
continue
|
||||
}
|
||||
p.pos++ // skip closing '
|
||||
break
|
||||
}
|
||||
buf.WriteByte(p.src[p.pos])
|
||||
p.pos++
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
buf.WriteByte('\'')
|
||||
p.pos++
|
||||
continue
|
||||
}
|
||||
|
||||
if ch == '}' && stopAtBrace {
|
||||
flush()
|
||||
return nodes, nil
|
||||
}
|
||||
if ch == '}' && !stopAtBrace {
|
||||
return nil, fmt.Errorf("unmatched '}' at byte %d", p.pos)
|
||||
}
|
||||
if ch == '#' && inPlural {
|
||||
flush()
|
||||
nodes = append(nodes, icuNode{kind: nodePound})
|
||||
p.pos++
|
||||
continue
|
||||
}
|
||||
if ch == '{' {
|
||||
flush()
|
||||
node, err := p.parsePlaceholder(inPlural)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nodes = append(nodes, node)
|
||||
continue
|
||||
}
|
||||
|
||||
buf.WriteByte(ch)
|
||||
p.pos++
|
||||
}
|
||||
|
||||
if stopAtBrace {
|
||||
return nil, fmt.Errorf("unclosed '{' branch")
|
||||
}
|
||||
flush()
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (p *icuParser) skipWS() {
|
||||
for p.pos < len(p.src) {
|
||||
switch p.src[p.pos] {
|
||||
case ' ', '\t', '\r', '\n':
|
||||
p.pos++
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *icuParser) readIdent() string {
|
||||
start := p.pos
|
||||
for p.pos < len(p.src) {
|
||||
c := p.src[p.pos]
|
||||
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.' || c == '=' {
|
||||
p.pos++
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
return p.src[start:p.pos]
|
||||
}
|
||||
|
||||
func (p *icuParser) parsePlaceholder(parentInPlural bool) (icuNode, error) {
|
||||
p.pos++ // skip '{'
|
||||
p.skipWS()
|
||||
name := p.readIdent()
|
||||
if name == "" {
|
||||
return icuNode{}, fmt.Errorf("empty placeholder name at byte %d", p.pos)
|
||||
}
|
||||
p.skipWS()
|
||||
if p.pos < len(p.src) && p.src[p.pos] == '}' {
|
||||
p.pos++
|
||||
return icuNode{kind: nodeVar, name: name, precision: -1}, nil
|
||||
}
|
||||
if p.pos >= len(p.src) || p.src[p.pos] != ',' {
|
||||
return icuNode{}, fmt.Errorf("expected ',' or '}' after %q at byte %d", name, p.pos)
|
||||
}
|
||||
p.pos++ // skip ','
|
||||
p.skipWS()
|
||||
fn := p.readIdent()
|
||||
p.skipWS()
|
||||
|
||||
switch fn {
|
||||
case "number":
|
||||
prec := -1
|
||||
if p.pos < len(p.src) && p.src[p.pos] == ',' {
|
||||
p.pos++
|
||||
p.skipWS()
|
||||
style := p.readIdent()
|
||||
if strings.HasPrefix(style, ".") && len(style) > 1 {
|
||||
n, err := strconv.Atoi(style[1:])
|
||||
if err != nil || n < 0 || n > 6 {
|
||||
return icuNode{}, fmt.Errorf("invalid number style %q", style)
|
||||
}
|
||||
prec = n
|
||||
} else if style != "" {
|
||||
return icuNode{}, fmt.Errorf("unsupported number style %q", style)
|
||||
}
|
||||
p.skipWS()
|
||||
}
|
||||
if p.pos >= len(p.src) || p.src[p.pos] != '}' {
|
||||
return icuNode{}, fmt.Errorf("expected '}' closing number placeholder %q", name)
|
||||
}
|
||||
p.pos++
|
||||
return icuNode{kind: nodeNumber, name: name, precision: prec}, nil
|
||||
|
||||
case "plural", "select":
|
||||
if p.pos >= len(p.src) || p.src[p.pos] != ',' {
|
||||
return icuNode{}, fmt.Errorf("expected ',' after %s in %q", fn, name)
|
||||
}
|
||||
p.pos++
|
||||
isPlural := fn == "plural"
|
||||
var branches []icuBranch
|
||||
hasOther := false
|
||||
for {
|
||||
p.skipWS()
|
||||
if p.pos < len(p.src) && p.src[p.pos] == '}' {
|
||||
p.pos++
|
||||
break
|
||||
}
|
||||
sel := p.readIdent()
|
||||
if sel == "" {
|
||||
return icuNode{}, fmt.Errorf("expected branch selector in %s %q at byte %d", fn, name, p.pos)
|
||||
}
|
||||
if sel == "other" {
|
||||
hasOther = true
|
||||
}
|
||||
p.skipWS()
|
||||
if p.pos >= len(p.src) || p.src[p.pos] != '{' {
|
||||
return icuNode{}, fmt.Errorf("expected '{' after branch %q in %q", sel, name)
|
||||
}
|
||||
p.pos++ // skip branch '{'
|
||||
childNodes, err := p.parseNodes(true, isPlural || parentInPlural)
|
||||
if err != nil {
|
||||
return icuNode{}, err
|
||||
}
|
||||
if p.pos >= len(p.src) || p.src[p.pos] != '}' {
|
||||
return icuNode{}, fmt.Errorf("expected '}' closing branch %q in %q", sel, name)
|
||||
}
|
||||
p.pos++ // skip branch '}'
|
||||
branches = append(branches, icuBranch{selector: sel, nodes: childNodes})
|
||||
}
|
||||
if !hasOther {
|
||||
return icuNode{}, fmt.Errorf("%s placeholder %q must include an 'other' branch", fn, name)
|
||||
}
|
||||
kind := nodeSelect
|
||||
if isPlural {
|
||||
kind = nodePlural
|
||||
}
|
||||
return icuNode{kind: kind, name: name, branches: branches}, nil
|
||||
|
||||
default:
|
||||
return icuNode{}, fmt.Errorf("unsupported ICU formatter %q in placeholder %q", fn, name)
|
||||
}
|
||||
}
|
||||
|
||||
func isSafeExactInt(num float64) bool {
|
||||
return !math.IsNaN(num) && !math.IsInf(num, 0) && math.Abs(num) <= 9007199254740991 && num == math.Trunc(num)
|
||||
}
|
||||
|
||||
// FormatICU evaluates an ICU template string for loc and vars.
|
||||
// If requireAllVars is true (used for untrusted plugin overrides), referencing a
|
||||
// variable missing from vars returns an error so the caller can fall back cleanly.
|
||||
func FormatICU(loc Locale, tmpl string, vars Vars, requireAllVars bool) (string, error) {
|
||||
nodes, err := cachedICUNodes(tmpl)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var out strings.Builder
|
||||
if err := evalNodes(&out, loc, nodes, vars, "", false, requireAllVars); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return out.String(), nil
|
||||
}
|
||||
|
||||
func evalNodes(out *strings.Builder, loc Locale, nodes []icuNode, vars Vars, poundVal string, hasPound, requireAllVars bool) error {
|
||||
for _, n := range nodes {
|
||||
switch n.kind {
|
||||
case nodeText:
|
||||
out.WriteString(n.text)
|
||||
case nodePound:
|
||||
if hasPound {
|
||||
out.WriteString(poundVal)
|
||||
} else {
|
||||
out.WriteByte('#')
|
||||
}
|
||||
case nodeVar:
|
||||
val, ok := vars[n.name]
|
||||
if !ok {
|
||||
if requireAllVars {
|
||||
return fmt.Errorf("missing variable %q", n.name)
|
||||
}
|
||||
out.WriteByte('{')
|
||||
out.WriteString(n.name)
|
||||
out.WriteByte('}')
|
||||
continue
|
||||
}
|
||||
out.WriteString(fmt.Sprint(val))
|
||||
case nodeNumber:
|
||||
val, ok := vars[n.name]
|
||||
if !ok {
|
||||
if requireAllVars {
|
||||
return fmt.Errorf("missing number variable %q", n.name)
|
||||
}
|
||||
out.WriteByte('{')
|
||||
out.WriteString(n.name)
|
||||
out.WriteByte('}')
|
||||
continue
|
||||
}
|
||||
num, ok := toFloat64(val)
|
||||
if !ok {
|
||||
out.WriteString(fmt.Sprint(val))
|
||||
continue
|
||||
}
|
||||
out.WriteString(FormatNumber(loc, num, n.precision))
|
||||
case nodePlural:
|
||||
val, ok := vars[n.name]
|
||||
if !ok {
|
||||
if requireAllVars {
|
||||
return fmt.Errorf("missing plural variable %q", n.name)
|
||||
}
|
||||
val = 0
|
||||
}
|
||||
num, ok := toFloat64(val)
|
||||
if !ok {
|
||||
num = 0
|
||||
}
|
||||
exactKey := ""
|
||||
if isSafeExactInt(num) {
|
||||
exactKey = fmt.Sprintf("=%d", int64(num))
|
||||
}
|
||||
cat := SelectPluralCategory(loc, num)
|
||||
chosen := matchBranch(n.branches, exactKey, cat)
|
||||
numStr := FormatNumber(loc, num, -1)
|
||||
if err := evalNodes(out, loc, chosen, vars, numStr, true, requireAllVars); err != nil {
|
||||
return err
|
||||
}
|
||||
case nodeSelect:
|
||||
val, ok := vars[n.name]
|
||||
if !ok && requireAllVars {
|
||||
return fmt.Errorf("missing select variable %q", n.name)
|
||||
}
|
||||
sel := ""
|
||||
if ok && val != nil {
|
||||
sel = fmt.Sprint(val)
|
||||
}
|
||||
chosen := matchBranch(n.branches, sel, "")
|
||||
if err := evalNodes(out, loc, chosen, vars, poundVal, hasPound, requireAllVars); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func matchBranch(branches []icuBranch, exact, category string) []icuNode {
|
||||
if exact != "" {
|
||||
for _, b := range branches {
|
||||
if b.selector == exact {
|
||||
return b.nodes
|
||||
}
|
||||
}
|
||||
}
|
||||
if category != "" {
|
||||
for _, b := range branches {
|
||||
if b.selector == category {
|
||||
return b.nodes
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, b := range branches {
|
||||
if b.selector == "other" {
|
||||
return b.nodes
|
||||
}
|
||||
}
|
||||
if len(branches) > 0 {
|
||||
return branches[len(branches)-1].nodes
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func toFloat64(v any) (float64, bool) {
|
||||
switch x := v.(type) {
|
||||
case int:
|
||||
return float64(x), true
|
||||
case int64:
|
||||
return float64(x), true
|
||||
case int32:
|
||||
return float64(x), true
|
||||
case uint:
|
||||
return float64(x), true
|
||||
case uint64:
|
||||
return float64(x), true
|
||||
case uint32:
|
||||
return float64(x), true
|
||||
case float64:
|
||||
return x, true
|
||||
case float32:
|
||||
return float64(x), true
|
||||
case string:
|
||||
f, err := strconv.ParseFloat(strings.TrimSpace(x), 64)
|
||||
return f, err == nil
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
// FormatNumber formats a numeric value respecting locale decimal separators.
|
||||
func FormatNumber(loc Locale, n float64, precision int) string {
|
||||
var raw string
|
||||
if precision >= 0 {
|
||||
raw = strconv.FormatFloat(n, 'f', precision, 64)
|
||||
} else if n == math.Trunc(n) && math.Abs(n) < 1e15 {
|
||||
raw = strconv.FormatInt(int64(n), 10)
|
||||
} else {
|
||||
raw = strconv.FormatFloat(n, 'f', -1, 64)
|
||||
}
|
||||
if usesCommaDecimal(loc) {
|
||||
raw = strings.Replace(raw, ".", ",", 1)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func usesCommaDecimal(loc Locale) bool {
|
||||
lang := primarySubtag(string(loc))
|
||||
switch lang {
|
||||
case "de", "fr", "es", "it", "pt", "nl", "pl", "ru", "uk", "cs", "sk", "sv", "da", "fi", "no", "nb", "nn", "tr", "vi", "id":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// SelectPluralCategory implements compact CLDR cardinal plural rules across
|
||||
// East Asian, Germanic/Romance, Slavic, and Arabic language families.
|
||||
func SelectPluralCategory(loc Locale, n float64) string {
|
||||
if math.IsNaN(n) || math.IsInf(n, 0) {
|
||||
return "other"
|
||||
}
|
||||
abs := math.Abs(n)
|
||||
isInt := isSafeExactInt(abs)
|
||||
var i, i10, i100 int64
|
||||
if isInt {
|
||||
i = int64(abs)
|
||||
i10 = i % 10
|
||||
i100 = i % 100
|
||||
}
|
||||
|
||||
tag := strings.ToLower(string(loc))
|
||||
lang := primarySubtag(tag)
|
||||
|
||||
switch lang {
|
||||
case "zh", "ja", "ko", "vi", "th", "id", "ms", "tr":
|
||||
return "other"
|
||||
case "fr", "hi":
|
||||
if n >= 0 && n < 2 {
|
||||
return "one"
|
||||
}
|
||||
return "other"
|
||||
case "pt":
|
||||
if strings.HasPrefix(tag, "pt-br") {
|
||||
if isInt && (i == 0 || i == 1) {
|
||||
return "one"
|
||||
}
|
||||
return "other"
|
||||
}
|
||||
if isInt && i == 1 {
|
||||
return "one"
|
||||
}
|
||||
return "other"
|
||||
case "ru", "uk", "be":
|
||||
if !isInt {
|
||||
return "other"
|
||||
}
|
||||
if i10 == 1 && i100 != 11 {
|
||||
return "one"
|
||||
}
|
||||
if i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) {
|
||||
return "few"
|
||||
}
|
||||
if i10 == 0 || (i10 >= 5 && i10 <= 9) || (i100 >= 11 && i100 <= 14) {
|
||||
return "many"
|
||||
}
|
||||
return "other"
|
||||
case "pl":
|
||||
if !isInt {
|
||||
return "other"
|
||||
}
|
||||
if i == 1 {
|
||||
return "one"
|
||||
}
|
||||
if i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) {
|
||||
return "few"
|
||||
}
|
||||
return "many"
|
||||
case "cs", "sk":
|
||||
if !isInt {
|
||||
return "many"
|
||||
}
|
||||
if i == 1 {
|
||||
return "one"
|
||||
}
|
||||
if i >= 2 && i <= 4 {
|
||||
return "few"
|
||||
}
|
||||
return "other"
|
||||
case "ar":
|
||||
if !isInt {
|
||||
return "other"
|
||||
}
|
||||
switch {
|
||||
case i == 0:
|
||||
return "zero"
|
||||
case i == 1:
|
||||
return "one"
|
||||
case i == 2:
|
||||
return "two"
|
||||
case i100 >= 3 && i100 <= 10:
|
||||
return "few"
|
||||
case i100 >= 11 && i100 <= 99:
|
||||
return "many"
|
||||
default:
|
||||
return "other"
|
||||
}
|
||||
default:
|
||||
// English, German, Spanish, Italian, Dutch, Nordic, etc.
|
||||
if isInt && i == 1 {
|
||||
return "one"
|
||||
}
|
||||
return "other"
|
||||
}
|
||||
}
|
||||
|
||||
var pseudoAccentMap = map[rune]rune{
|
||||
'a': 'à', 'b': 'ƀ', 'c': 'č', 'd': 'ď', 'e': 'ë', 'f': 'ƒ', 'g': 'ğ',
|
||||
'h': 'ĥ', 'i': 'î', 'j': 'ĵ', 'k': 'ķ', 'l': 'ľ', 'm': 'ɱ', 'n': 'ñ',
|
||||
'o': 'ô', 'p': 'þ', 'q': 'ǫ', 'r': 'ŕ', 's': 'ś', 't': 'ť', 'u': 'ü',
|
||||
'v': 'ṽ', 'w': 'ŵ', 'x': 'ẋ', 'y': 'ÿ', 'z': 'ž',
|
||||
'A': 'À', 'B': 'Ɓ', 'C': 'Č', 'D': 'Ď', 'E': 'Ë', 'F': 'Ƒ', 'G': 'Ğ',
|
||||
'H': 'Ĥ', 'I': 'Î', 'J': 'Ĵ', 'K': 'Ķ', 'L': 'Ľ', 'M': 'Ṁ', 'N': 'Ñ',
|
||||
'O': 'Ô', 'P': 'Þ', 'Q': 'Ǫ', 'R': 'Ŕ', 'S': 'Š', 'T': 'Ť', 'U': 'Ü',
|
||||
'V': 'Ṽ', 'W': 'Ŵ', 'X': 'Ẋ', 'Y': 'Ÿ', 'Z': 'Ž',
|
||||
}
|
||||
|
||||
// PseudoLocalize transforms an English ICU template into an expanded, accented
|
||||
// pseudo-locale string ("en-XA") wrapped in ⟦ ... ⟧ while preserving {vars}, #,
|
||||
// and ICU branch syntax intact.
|
||||
func PseudoLocalize(enTmpl string) string {
|
||||
nodes, err := cachedICUNodes(enTmpl)
|
||||
if err != nil {
|
||||
return "⟦" + enTmpl + "⟧"
|
||||
}
|
||||
totalRunes := countTextRunes(nodes)
|
||||
padCount := int(math.Ceil(float64(totalRunes) * 0.35))
|
||||
if totalRunes > 0 && totalRunes <= 8 {
|
||||
padCount = max(4, int(math.Ceil(float64(totalRunes)*0.85)))
|
||||
}
|
||||
return "⟦" + serializePseudoNodes(nodes, padCount, true) + "⟧"
|
||||
}
|
||||
|
||||
func countTextRunes(nodes []icuNode) int {
|
||||
n := 0
|
||||
for _, nd := range nodes {
|
||||
if nd.kind == nodeText {
|
||||
n += utf8.RuneCountInString(nd.text)
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func accentText(s string) string {
|
||||
var b strings.Builder
|
||||
b.Grow(len(s) * 2)
|
||||
for _, r := range s {
|
||||
if mapped, ok := pseudoAccentMap[r]; ok {
|
||||
b.WriteRune(mapped)
|
||||
} else {
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func serializePseudoNodes(nodes []icuNode, padCount int, isTop bool) string {
|
||||
var b strings.Builder
|
||||
for _, nd := range nodes {
|
||||
switch nd.kind {
|
||||
case nodeText:
|
||||
escaped := strings.ReplaceAll(accentText(nd.text), "'", "''")
|
||||
b.WriteString(escaped)
|
||||
case nodePound:
|
||||
b.WriteByte('#')
|
||||
case nodeVar:
|
||||
b.WriteByte('{')
|
||||
b.WriteString(nd.name)
|
||||
b.WriteByte('}')
|
||||
case nodeNumber:
|
||||
if nd.precision >= 0 {
|
||||
fmt.Fprintf(&b, "{%s, number, .%d}", nd.name, nd.precision)
|
||||
} else {
|
||||
b.WriteByte('{')
|
||||
b.WriteString(nd.name)
|
||||
b.WriteString(", number}")
|
||||
}
|
||||
case nodePlural, nodeSelect:
|
||||
fn := "select"
|
||||
if nd.kind == nodePlural {
|
||||
fn = "plural"
|
||||
}
|
||||
b.WriteByte('{')
|
||||
b.WriteString(nd.name)
|
||||
b.WriteString(", ")
|
||||
b.WriteString(fn)
|
||||
b.WriteString(", ")
|
||||
for i, br := range nd.branches {
|
||||
if i > 0 {
|
||||
b.WriteByte(' ')
|
||||
}
|
||||
brPad := 0
|
||||
if isTop && totalRunesZero(nodes) {
|
||||
rc := countTextRunes(br.nodes)
|
||||
brPad = max(3, int(math.Ceil(float64(rc)*0.35)))
|
||||
}
|
||||
b.WriteString(br.selector)
|
||||
b.WriteString(" {")
|
||||
b.WriteString(serializePseudoNodes(br.nodes, brPad, false))
|
||||
b.WriteByte('}')
|
||||
}
|
||||
b.WriteByte('}')
|
||||
}
|
||||
}
|
||||
if padCount > 0 {
|
||||
b.WriteByte(' ')
|
||||
b.WriteString(strings.Repeat("·", padCount))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func totalRunesZero(nodes []icuNode) bool {
|
||||
return countTextRunes(nodes) == 0
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows/registry"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -29,11 +31,12 @@ var (
|
||||
enumFontFamiliesExW = gdi.NewProc("EnumFontFamiliesExW")
|
||||
getTextExtentExPointW = gdi.NewProc("GetTextExtentExPointW")
|
||||
gdiFlush = gdi.NewProc("GdiFlush")
|
||||
saveDC = gdi.NewProc("SaveDC")
|
||||
restoreDC = gdi.NewProc("RestoreDC")
|
||||
|
||||
drawText = user32.NewProc("DrawTextW")
|
||||
sendMessage = user32.NewProc("SendMessageW")
|
||||
getParent = user32.NewProc("GetParent")
|
||||
getDlgCtrlID = user32.NewProc("GetDlgCtrlID")
|
||||
getDlgItem = user32.NewProc("GetDlgItem")
|
||||
fillRect = user32.NewProc("FillRect")
|
||||
drawFocusRect = user32.NewProc("DrawFocusRect")
|
||||
@@ -206,27 +209,69 @@ func windowsAppsUseDarkTheme() bool {
|
||||
return err == nil && v == 0
|
||||
}
|
||||
|
||||
type scriptKind uint8
|
||||
|
||||
const (
|
||||
scriptLatn scriptKind = iota
|
||||
scriptHans
|
||||
scriptHant
|
||||
scriptJpan
|
||||
scriptKore
|
||||
)
|
||||
|
||||
func scriptForLocale(loc i18n.Locale) scriptKind {
|
||||
s := strings.ToLower(strings.TrimSpace(string(i18n.ResolveLocale(string(loc)))))
|
||||
switch {
|
||||
case s == "zh-tw" || s == "zh-hk" || s == "zh-mo" || strings.HasPrefix(s, "zh-hant"):
|
||||
return scriptHant
|
||||
case strings.HasPrefix(s, "zh"):
|
||||
return scriptHans
|
||||
case strings.HasPrefix(s, "ja"):
|
||||
return scriptJpan
|
||||
case strings.HasPrefix(s, "ko"):
|
||||
return scriptKore
|
||||
default:
|
||||
return scriptLatn
|
||||
}
|
||||
}
|
||||
|
||||
func (sk scriptKind) isCJK() bool {
|
||||
return sk != scriptLatn
|
||||
}
|
||||
|
||||
func dialogBaseFontFace(loc i18n.Locale) string {
|
||||
probeFontFamilies()
|
||||
if face := scriptFaces[scriptForLocale(loc)]; face != "" {
|
||||
return face
|
||||
}
|
||||
return "Segoe UI"
|
||||
}
|
||||
|
||||
const (
|
||||
dialogDark = 1 << iota
|
||||
dialogCompact
|
||||
dialogDWM
|
||||
dialogZh
|
||||
dialogConfirm
|
||||
dialogToneShift = 5
|
||||
dialogToneShift = 4
|
||||
dialogScriptShift = 8
|
||||
)
|
||||
|
||||
type dialogMeta struct {
|
||||
dark, compact, dwm, zh, isConfirm bool
|
||||
stageTone tone
|
||||
dark, compact, dwm, isConfirm bool
|
||||
stageTone tone
|
||||
script scriptKind
|
||||
}
|
||||
|
||||
type panelState struct {
|
||||
meta dialogMeta
|
||||
dpi int32
|
||||
dividerY int32
|
||||
extraStacked bool
|
||||
bodyLines []string
|
||||
bodyLineH int32
|
||||
meta dialogMeta
|
||||
dpi int32
|
||||
dividerY int32
|
||||
extraStacked bool
|
||||
buttonsStacked bool
|
||||
titleLines []string
|
||||
titleLineH int32
|
||||
bodyLines []string
|
||||
bodyLineH int32
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -320,8 +365,8 @@ type logFontW struct {
|
||||
type gdiSize struct{ cx, cy int32 }
|
||||
|
||||
type fontKey struct {
|
||||
dpi int32
|
||||
zh bool
|
||||
dpi int32
|
||||
script scriptKind
|
||||
}
|
||||
|
||||
type fontSet struct {
|
||||
@@ -342,9 +387,14 @@ var (
|
||||
fontProbeHit = true
|
||||
return 0
|
||||
})
|
||||
zhSansFace = "Microsoft YaHei UI"
|
||||
enSansFace = "Segoe UI"
|
||||
monoFace = "Consolas"
|
||||
scriptFaces = map[scriptKind]string{
|
||||
scriptLatn: "Segoe UI",
|
||||
scriptHans: "Microsoft YaHei UI",
|
||||
scriptHant: "Microsoft JhengHei UI",
|
||||
scriptJpan: "Yu Gothic UI",
|
||||
scriptKore: "Malgun Gothic",
|
||||
}
|
||||
monoFace = "Consolas"
|
||||
|
||||
fontCacheMu sync.Mutex
|
||||
fontCache = map[fontKey]fontSet{}
|
||||
@@ -365,23 +415,31 @@ func probeFontFamilies() {
|
||||
enumFontFamiliesExW.Call(dc, uintptr(unsafe.Pointer(&lf)), fontEnumProc, 0, 0)
|
||||
return fontProbeHit
|
||||
}
|
||||
// Match frontend/src/styles/tokens.css font priority order.
|
||||
for _, f := range []string{
|
||||
pick := func(sk scriptKind, candidates []string) {
|
||||
for _, f := range candidates {
|
||||
if has(f) {
|
||||
scriptFaces[sk] = f
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
pick(scriptLatn, []string{"Segoe UI Variable Text", "Segoe UI"})
|
||||
pick(scriptHans, []string{
|
||||
"PingFang SC Medium", "PingFang SC", "HarmonyOS Sans SC", "MiSans",
|
||||
"Noto Sans SC Medium", "Noto Sans SC", "Source Han Sans CN Medium", "Source Han Sans CN",
|
||||
"Microsoft YaHei UI",
|
||||
} {
|
||||
if has(f) {
|
||||
zhSansFace = f
|
||||
break
|
||||
}
|
||||
}
|
||||
for _, f := range []string{"Segoe UI Variable Text", "Segoe UI"} {
|
||||
if has(f) {
|
||||
enSansFace = f
|
||||
break
|
||||
}
|
||||
}
|
||||
"Microsoft YaHei UI", "Segoe UI",
|
||||
})
|
||||
pick(scriptHant, []string{
|
||||
"PingFang TC", "Noto Sans TC", "Source Han Sans TC",
|
||||
"Microsoft JhengHei UI", "Microsoft JhengHei", "Microsoft YaHei UI", "Segoe UI",
|
||||
})
|
||||
pick(scriptJpan, []string{
|
||||
"Hiragino Sans", "Noto Sans JP", "BIZ UDPGothic",
|
||||
"Yu Gothic UI", "Meiryo UI", "Meiryo", "Microsoft YaHei UI", "Segoe UI",
|
||||
})
|
||||
pick(scriptKore, []string{
|
||||
"Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic", "Segoe UI",
|
||||
})
|
||||
for _, f := range []string{"Cascadia Mono", "JetBrains Mono", "Consolas"} {
|
||||
if has(f) {
|
||||
monoFace = f
|
||||
@@ -402,23 +460,33 @@ func makeFont(face string, px float64, dpi, weight int32) uintptr {
|
||||
return h
|
||||
}
|
||||
|
||||
func getFonts(dpi int32, zh bool) fontSet {
|
||||
func isGDIWeightJumpFont(face string) bool {
|
||||
switch face {
|
||||
case "Microsoft YaHei UI", "Microsoft YaHei", "Microsoft JhengHei UI", "Microsoft JhengHei", "Yu Gothic UI", "Meiryo UI", "Meiryo", "Malgun Gothic":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func getFonts(dpi int32, script scriptKind) fontSet {
|
||||
probeFontFamilies()
|
||||
key := fontKey{dpi: dpi, zh: zh}
|
||||
key := fontKey{dpi: dpi, script: script}
|
||||
fontCacheMu.Lock()
|
||||
defer fontCacheMu.Unlock()
|
||||
if fs, ok := fontCache[key]; ok {
|
||||
return fs
|
||||
}
|
||||
face := enSansFace
|
||||
face := scriptFaces[script]
|
||||
if face == "" {
|
||||
face = scriptFaces[scriptLatn]
|
||||
}
|
||||
medWeight := int32(500)
|
||||
if zh {
|
||||
face = zhSansFace
|
||||
// In GDI, Microsoft YaHei UI jumps straight from Regular (400) to Bold (700)
|
||||
// at weight 500+; keep normal/secondary labels crisp at 400 and strong at 600.
|
||||
if face == "Microsoft YaHei UI" {
|
||||
medWeight = 400
|
||||
}
|
||||
// In GDI, traditional Windows CJK UI families jump straight from Regular (400)
|
||||
// to Bold (700) at weight 500+, and dense Traditional/Japanese strokes blob
|
||||
// at small sizes if forced bold. Keep normal/secondary labels crisp at 400.
|
||||
if isGDIWeightJumpFont(face) {
|
||||
medWeight = 400
|
||||
}
|
||||
fs := fontSet{
|
||||
title: makeFont(face, 15, dpi, 600),
|
||||
@@ -474,9 +542,9 @@ func stylePanel(hwnd, flags uintptr) {
|
||||
meta := dialogMeta{
|
||||
dark: flags&dialogDark != 0,
|
||||
compact: flags&dialogCompact != 0,
|
||||
zh: flags&dialogZh != 0,
|
||||
isConfirm: flags&dialogConfirm != 0,
|
||||
stageTone: tone(flags >> dialogToneShift),
|
||||
stageTone: tone((flags >> dialogToneShift) & 0xf),
|
||||
script: scriptKind((flags >> dialogScriptShift) & 0xf),
|
||||
}
|
||||
pal := paletteFor(meta.dark)
|
||||
|
||||
@@ -554,7 +622,11 @@ func isASCIIWord(u uint16) bool {
|
||||
func isClosingPunct(u uint16) bool {
|
||||
switch u {
|
||||
case '.', ',', ';', ':', '?', '!', ')', ']', '}',
|
||||
'。', ',', '、', ';', ':', '?', '!', ')', '」', '』', '》', '”', '…':
|
||||
'。', ',', '、', ';', ':', '?', '!', ')', '」', '』', '》', '”', '…',
|
||||
// Japanese kinsoku shori (行頭禁則文字: prolonged sound mark, nakaguro, iteration & small kana)
|
||||
'ー', '・', '々', 'ゝ', 'ゞ', 'ヽ', 'ヾ',
|
||||
'ぁ', 'ぃ', 'ぅ', 'ぇ', 'ぉ', 'っ', 'ゃ', 'ゅ', 'ょ', 'ゎ',
|
||||
'ァ', 'ィ', 'ゥ', 'ェ', 'ォ', 'ッ', 'ャ', 'ュ', 'ョ', 'ヮ':
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -675,9 +747,11 @@ func layoutPanel(hwnd uintptr) {
|
||||
st.dpi = dpi
|
||||
st.dividerY = 0
|
||||
st.extraStacked = false
|
||||
st.buttonsStacked = false
|
||||
st.titleLines = nil
|
||||
st.bodyLines = nil
|
||||
|
||||
fonts := getFonts(dpi, st.meta.zh)
|
||||
fonts := getFonts(dpi, st.meta.script)
|
||||
dc, _, _ := getDC.Call(hwnd)
|
||||
if dc == 0 {
|
||||
return
|
||||
@@ -696,12 +770,11 @@ func layoutPanel(hwnd uintptr) {
|
||||
}
|
||||
|
||||
cardW := dp(dpi, 340)
|
||||
if !st.meta.zh {
|
||||
if !st.meta.script.isCJK() {
|
||||
cardW = dp(dpi, 376)
|
||||
}
|
||||
maxCardW := dp(dpi, 480)
|
||||
padX := dp(dpi, 16)
|
||||
innerW := cardW - padX*2
|
||||
y := dp(dpi, 14)
|
||||
|
||||
stageCtrl, _, _ := getDlgItem.Call(hwnd, idStage)
|
||||
foldCtrl, _, _ := getDlgItem.Call(hwnd, idFold)
|
||||
@@ -714,6 +787,36 @@ func layoutPanel(hwnd uintptr) {
|
||||
rightCtrl, _, _ := getDlgItem.Call(hwnd, idRight)
|
||||
jumpCtrl, _, _ := getDlgItem.Call(hwnd, idJump)
|
||||
|
||||
// Adaptively widen cardW up to maxCardW when single-line controls (footer strip,
|
||||
// input hint, or primary/secondary buttons) experience long-locale text expansion.
|
||||
if jumpCtrl != 0 {
|
||||
needW := measureLineWidth(dc, fonts.smallMed, controlText(jumpCtrl)) + dp(dpi, 24) + dp(dpi, 16)
|
||||
if needW > cardW {
|
||||
cardW = min(maxCardW, needW)
|
||||
}
|
||||
}
|
||||
if hintCtrl != 0 {
|
||||
needW := measureLineWidth(dc, fonts.small, controlText(hintCtrl)) + padX*2
|
||||
if needW > cardW {
|
||||
cardW = min(maxCardW, needW)
|
||||
}
|
||||
}
|
||||
if rightCtrl != 0 {
|
||||
rw := measureLineWidth(dc, fonts.btnBold, controlText(rightCtrl)) + dp(dpi, 26) + padX*2
|
||||
if rw > cardW {
|
||||
cardW = min(maxCardW, rw)
|
||||
}
|
||||
}
|
||||
if leftCtrl != 0 {
|
||||
lw := measureLineWidth(dc, fonts.btn, controlText(leftCtrl)) + dp(dpi, 26) + padX*2
|
||||
if lw > cardW {
|
||||
cardW = min(maxCardW, lw)
|
||||
}
|
||||
}
|
||||
|
||||
innerW := cardW - padX*2
|
||||
y := dp(dpi, 14)
|
||||
|
||||
// 1. Meta row: 20px .badge pill on left, quiet ghost "收起" optically flush right.
|
||||
if stageCtrl != 0 || foldCtrl != 0 {
|
||||
rowH := dp(dpi, 22)
|
||||
@@ -723,8 +826,6 @@ func layoutPanel(hwnd uintptr) {
|
||||
foldPadX := dp(dpi, 8)
|
||||
foldW := measureLineWidth(dc, fonts.smallMed, controlText(foldCtrl)) + foldPadX*2
|
||||
foldH := dp(dpi, 24)
|
||||
// Extend the invisible hover hit box by +foldPadX on the right so the text
|
||||
// aligns optically flush with cardW - padX (matching code box & primary button).
|
||||
foldX := cardW - padX - foldW + foldPadX
|
||||
foldY := y + (rowH-foldH)/2
|
||||
moveControl(foldCtrl, foldX, foldY, foldW, foldH)
|
||||
@@ -740,10 +841,14 @@ func layoutPanel(hwnd uintptr) {
|
||||
y += rowH + dp(dpi, 10)
|
||||
}
|
||||
|
||||
// 2. Title (15px semibold).
|
||||
// 2. Title (15px semibold, wraps up to 3 lines for long European / pseudo-localized headings).
|
||||
if titleCtrl != 0 {
|
||||
setCtrlFont(titleCtrl, fonts.title)
|
||||
titleH := dp(dpi, 22)
|
||||
tLineH := dp(dpi, 22)
|
||||
tLines := wrapLines(dc, fonts.title, controlText(titleCtrl), innerW, 3)
|
||||
st.titleLines = tLines
|
||||
st.titleLineH = tLineH
|
||||
titleH := max(tLineH, int32(len(tLines))*tLineH)
|
||||
moveControl(titleCtrl, padX, y, innerW, titleH)
|
||||
y += titleH + dp(dpi, 4)
|
||||
}
|
||||
@@ -752,7 +857,7 @@ func layoutPanel(hwnd uintptr) {
|
||||
if bodyCtrl != 0 {
|
||||
setCtrlFont(bodyCtrl, fonts.body)
|
||||
lineH := dp(dpi, 20)
|
||||
lines := wrapLines(dc, fonts.body, controlText(bodyCtrl), innerW, 6)
|
||||
lines := wrapLines(dc, fonts.body, controlText(bodyCtrl), innerW, 8)
|
||||
st.bodyLines = lines
|
||||
st.bodyLineH = lineH
|
||||
bodyH := max(lineH, int32(len(lines))*lineH)
|
||||
@@ -788,19 +893,17 @@ func layoutPanel(hwnd uintptr) {
|
||||
var leftW, rightW, extraW int32
|
||||
if leftCtrl != 0 {
|
||||
setCtrlFont(leftCtrl, fonts.btn)
|
||||
leftW = max(dp(dpi, 60), measureLineWidth(dc, fonts.btn, controlText(leftCtrl))+btnPadX*2)
|
||||
leftW = min(innerW, max(dp(dpi, 60), measureLineWidth(dc, fonts.btn, controlText(leftCtrl))+btnPadX*2))
|
||||
}
|
||||
if rightCtrl != 0 {
|
||||
setCtrlFont(rightCtrl, fonts.btnBold)
|
||||
rightW = max(dp(dpi, 64), measureLineWidth(dc, fonts.btnBold, controlText(rightCtrl))+btnPadX*2)
|
||||
rightW = min(innerW, max(dp(dpi, 64), measureLineWidth(dc, fonts.btnBold, controlText(rightCtrl))+btnPadX*2))
|
||||
}
|
||||
if extraCtrl != 0 {
|
||||
setCtrlFont(extraCtrl, fonts.btn)
|
||||
extraW = measureLineWidth(dc, fonts.btn, controlText(extraCtrl)) + ghostPadX*2
|
||||
}
|
||||
|
||||
// Keep auxiliary action inline on the action row whenever it fits cleanly;
|
||||
// only stack above the buttons if a long localized string needs more room.
|
||||
needInline := rightW
|
||||
if leftCtrl != 0 {
|
||||
needInline += leftW + dp(dpi, 12)
|
||||
@@ -821,33 +924,41 @@ func layoutPanel(hwnd uintptr) {
|
||||
y += dp(dpi, 16)
|
||||
}
|
||||
|
||||
rightX := cardW - padX - rightW
|
||||
if rightCtrl != 0 {
|
||||
moveControl(rightCtrl, rightX, y, rightW, btnH)
|
||||
}
|
||||
if st.meta.isConfirm {
|
||||
if leftCtrl != 0 {
|
||||
moveControl(leftCtrl, rightX-gap-leftW, y, leftW, btnH)
|
||||
}
|
||||
} else {
|
||||
if leftCtrl != 0 {
|
||||
if rightCtrl == 0 {
|
||||
moveControl(leftCtrl, cardW-padX-leftW, y, leftW, btnH)
|
||||
} else {
|
||||
moveControl(leftCtrl, padX, y, leftW, btnH)
|
||||
}
|
||||
}
|
||||
if extraCtrl != 0 && !st.extraStacked {
|
||||
if leftCtrl != 0 {
|
||||
moveControl(extraCtrl, rightX-gap-extraW, y, extraW, btnH)
|
||||
} else {
|
||||
// No Back button: align auxiliary ghost button text optically flush left.
|
||||
moveControl(extraCtrl, padX-ghostPadX, y, extraW, btnH)
|
||||
}
|
||||
}
|
||||
}
|
||||
if leftCtrl != 0 || rightCtrl != 0 || (extraCtrl != 0 && !st.extraStacked) {
|
||||
// Stack primary & secondary buttons vertically if both together exceed innerW.
|
||||
if leftCtrl != 0 && rightCtrl != 0 && leftW+rightW+gap > innerW {
|
||||
st.buttonsStacked = true
|
||||
moveControl(rightCtrl, padX, y, innerW, btnH)
|
||||
y += btnH + gap
|
||||
moveControl(leftCtrl, padX, y, innerW, btnH)
|
||||
y += btnH
|
||||
} else {
|
||||
rightX := cardW - padX - rightW
|
||||
if rightCtrl != 0 {
|
||||
moveControl(rightCtrl, rightX, y, rightW, btnH)
|
||||
}
|
||||
if st.meta.isConfirm {
|
||||
if leftCtrl != 0 {
|
||||
moveControl(leftCtrl, rightX-gap-leftW, y, leftW, btnH)
|
||||
}
|
||||
} else {
|
||||
if leftCtrl != 0 {
|
||||
if rightCtrl == 0 {
|
||||
moveControl(leftCtrl, cardW-padX-leftW, y, leftW, btnH)
|
||||
} else {
|
||||
moveControl(leftCtrl, padX, y, leftW, btnH)
|
||||
}
|
||||
}
|
||||
if extraCtrl != 0 && !st.extraStacked {
|
||||
if leftCtrl != 0 {
|
||||
moveControl(extraCtrl, rightX-gap-extraW, y, extraW, btnH)
|
||||
} else {
|
||||
moveControl(extraCtrl, padX-ghostPadX, y, extraW, btnH)
|
||||
}
|
||||
}
|
||||
}
|
||||
if leftCtrl != 0 || rightCtrl != 0 || (extraCtrl != 0 && !st.extraStacked) {
|
||||
y += btnH
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -898,7 +1009,7 @@ func roundPanel(hwnd uintptr) {
|
||||
}
|
||||
}
|
||||
|
||||
func panelBrush(hwnd, dc, ctrl uintptr) uintptr {
|
||||
func panelBrush(hwnd, dc uintptr) uintptr {
|
||||
pal := paletteFor(getDialogMeta(hwnd).dark)
|
||||
textColor.Call(dc, pal.text2.colorref())
|
||||
bkMode.Call(dc, 1) // TRANSPARENT
|
||||
@@ -983,11 +1094,11 @@ func paintItem(it *drawItem) {
|
||||
meta := st.meta
|
||||
dpi := st.dpi
|
||||
pal := paletteFor(meta.dark)
|
||||
fonts := getFonts(dpi, meta.zh)
|
||||
fonts := getFonts(dpi, meta.script)
|
||||
|
||||
dc := it.dc
|
||||
saved, _, _ := gdi.NewProc("SaveDC").Call(dc)
|
||||
defer gdi.NewProc("RestoreDC").Call(dc, saved)
|
||||
saved, _, _ := saveDC.Call(dc)
|
||||
defer restoreDC.Call(dc, saved)
|
||||
bkMode.Call(dc, 1) // TRANSPARENT
|
||||
brushColor.Call(dc, pal.surface.colorref())
|
||||
brush, _, _ := stockObject.Call(18) // DC_BRUSH
|
||||
@@ -1000,6 +1111,27 @@ func paintItem(it *drawItem) {
|
||||
btnR := dpF(dpi, 8) // --r-md
|
||||
smallR := dpF(dpi, 6) // --r-sm
|
||||
|
||||
if it.id == idTitle && len(st.titleLines) > 0 {
|
||||
selectGDI.Call(dc, fonts.title)
|
||||
textColor.Call(dc, pal.text.colorref())
|
||||
lineH := st.titleLineH
|
||||
if lineH <= 0 {
|
||||
lineH = dp(dpi, 22)
|
||||
}
|
||||
for i, line := range st.titleLines {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
u16 := utf16.Encode([]rune(line))
|
||||
if len(u16) == 0 {
|
||||
continue
|
||||
}
|
||||
lr := rect{left: r.left, top: r.top + int32(i)*lineH, right: r.right, bottom: r.top + int32(i+1)*lineH}
|
||||
drawText.Call(dc, uintptr(unsafe.Pointer(&u16[0])), uintptr(len(u16)), uintptr(unsafe.Pointer(&lr)), 0x8824)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if it.id == idBody {
|
||||
selectGDI.Call(dc, fonts.body)
|
||||
textColor.Call(dc, pal.text2.colorref())
|
||||
|
||||
@@ -40,11 +40,7 @@ func dialogTemplate(p page, c content, locale i18n.Locale) []uint16 {
|
||||
}
|
||||
addString(c.title)
|
||||
data = append(data, 9)
|
||||
if locale == i18n.ZhCN {
|
||||
addString("Microsoft YaHei UI")
|
||||
} else {
|
||||
addString("Segoe UI")
|
||||
}
|
||||
addString(dialogBaseFontFace(locale))
|
||||
item := func(class, id uint16, caption string) {
|
||||
if len(data)%2 != 0 {
|
||||
data = append(data, 0)
|
||||
@@ -121,7 +117,7 @@ var dialogProc = syscall.NewCallback(func(hwnd, msg, wp, lp uintptr) uintptr {
|
||||
return 1
|
||||
}
|
||||
case 0x0136, 0x0138: // WM_CTLCOLORDLG, WM_CTLCOLORSTATIC
|
||||
return panelBrush(hwnd, wp, lp)
|
||||
return panelBrush(hwnd, wp)
|
||||
case 0x002b: // WM_DRAWITEM
|
||||
if lp != 0 {
|
||||
var it drawItem
|
||||
|
||||
+144
-161
@@ -31,6 +31,7 @@ type Guide struct {
|
||||
Kind Kind
|
||||
ReleaseKeys string
|
||||
Locale i18n.Locale
|
||||
GuestLang string // OpenCore prev-lang:kbd (e.g. "en-US:0", "zh-Hans:0", "ja-JP:0")
|
||||
Theme Theme
|
||||
ToolsAttached bool
|
||||
CurrentPreferences func() (i18n.Locale, Theme)
|
||||
@@ -112,9 +113,10 @@ type content struct {
|
||||
|
||||
func (g Guide) preferences() (i18n.Locale, Theme) {
|
||||
if g.CurrentPreferences != nil {
|
||||
return g.CurrentPreferences()
|
||||
loc, th := g.CurrentPreferences()
|
||||
return i18n.EffectiveLocale(loc), th
|
||||
}
|
||||
return g.Locale, g.Theme
|
||||
return i18n.EffectiveLocale(g.Locale), g.Theme
|
||||
}
|
||||
|
||||
func (p page) confirmsRestart() bool {
|
||||
@@ -127,15 +129,15 @@ func (p page) confirmsRestart() bool {
|
||||
|
||||
func (g Guide) content(p page, detail string) content {
|
||||
loc, _ := g.preferences()
|
||||
t := func(zh, en string) string {
|
||||
if loc == i18n.ZhCN {
|
||||
return zh
|
||||
}
|
||||
return en
|
||||
tr := func(key string) string { return i18n.T(loc, key) }
|
||||
trv := func(key string, vars i18n.Vars) string { return i18n.M(loc, key, vars) }
|
||||
gt := func(termKey string, bracketed bool) string {
|
||||
return i18n.FormatGuestTerm(loc, g.GuestLang, termKey, bracketed)
|
||||
}
|
||||
c := content{fold: t("收起", "Hide"), isConfirm: p.confirmsRestart()}
|
||||
stage := func(zh, en string, step, total int, tn tone) {
|
||||
label := t(zh, en)
|
||||
|
||||
c := content{fold: tr("guide.btn.fold"), isConfirm: p.confirmsRestart()}
|
||||
stage := func(stageKey string, step, total int, tn tone) {
|
||||
label := tr(stageKey)
|
||||
if step > 0 && total > 0 {
|
||||
c.stage = fmt.Sprintf("%s · %d / %d", label, step, total)
|
||||
} else {
|
||||
@@ -143,249 +145,230 @@ func (g Guide) content(p page, detail string) content {
|
||||
}
|
||||
c.stageTone = tn
|
||||
}
|
||||
card := func(zhTitle, enTitle, zhBody, enBody string) {
|
||||
c.title = t(zhTitle, enTitle)
|
||||
c.body = t(zhBody, enBody)
|
||||
card := func(titleKey, bodyKey string, vars i18n.Vars) {
|
||||
c.title = trv(titleKey, vars)
|
||||
c.body = trv(bodyKey, vars)
|
||||
}
|
||||
next := func(dst page, zh, en string) { c.next = dst; c.right = t(zh, en) }
|
||||
extra := func(dst page, zh, en string) { c.alt = dst; c.extra = t(zh, en) }
|
||||
back := func(dst page) { c.prev = dst; c.left = t("上一步", "Back") }
|
||||
cancel := func(dst page) { c.prev = dst; c.left = t("取消", "Cancel") }
|
||||
finish := func() { next(done, "完成", "Done") }
|
||||
next := func(dst page, btnKey string) { c.next = dst; c.right = tr(btnKey) }
|
||||
extra := func(dst page, btnKey string) { c.alt = dst; c.extra = tr(btnKey) }
|
||||
back := func(dst page) { c.prev = dst; c.left = tr("guide.btn.back") }
|
||||
cancel := func(dst page) { c.prev = dst; c.left = tr("guide.btn.cancel") }
|
||||
finish := func() { next(done, "guide.btn.done") }
|
||||
|
||||
switch p {
|
||||
case boot:
|
||||
switch g.Kind {
|
||||
case Offline, Online:
|
||||
card("等待进入恢复界面", "Wait for Recovery",
|
||||
"等待苹果标志和进度条结束。若出现语言选择,选好后继续;看到恢复工具列表即可下一步。",
|
||||
"Wait for the Apple logo and progress bar. Pick a language if asked, then continue when Recovery utilities appear.")
|
||||
card("guide.boot.recovery.title", "guide.boot.recovery.body", nil)
|
||||
if g.Kind == Offline {
|
||||
stage("离线安装", "Offline install", 1, 5, toneAccent)
|
||||
next(terminal, "继续", "Continue")
|
||||
stage("guide.stage.offline", 1, 5, toneAccent)
|
||||
next(terminal, "guide.btn.continue")
|
||||
} else {
|
||||
stage("在线恢复", "Online recovery", 1, 5, toneAccent)
|
||||
next(selectDisk, "继续", "Continue")
|
||||
stage("guide.stage.online", 1, 5, toneAccent)
|
||||
next(selectDisk, "guide.btn.continue")
|
||||
}
|
||||
case BuiltIn:
|
||||
stage("内置恢复", "Built-in recovery", 1, 2, toneAccent)
|
||||
card("在引导菜单选 Recovery", "Select Recovery in boot menu",
|
||||
"在 OpenCore 启动菜单选「Recovery」按回车,等恢复工具列表出现后继续。",
|
||||
"Choose Recovery in the OpenCore boot picker and press Return. Continue when the recovery utilities appear.")
|
||||
next(recoverMenu, "继续", "Continue")
|
||||
stage("guide.stage.builtin", 1, 2, toneAccent)
|
||||
// OpenCore picker itself shows "Recovery" in Latin text
|
||||
recLabel := "Recovery"
|
||||
if i18n.IsCJKLocale(loc) {
|
||||
recLabel = "「Recovery」"
|
||||
}
|
||||
card("guide.boot.builtin.title", "guide.boot.builtin.body", i18n.Vars{"recovery": recLabel})
|
||||
next(recoverMenu, "guide.btn.continue")
|
||||
}
|
||||
case terminal:
|
||||
stage("离线安装", "Offline install", 2, 5, toneAccent)
|
||||
card("打开恢复终端", "Open Recovery Terminal",
|
||||
"在顶部菜单栏打开「实用工具 › 终端」(Utilities › Terminal),不要点「重新安装 macOS」。",
|
||||
"Open Utilities › Terminal from the menu bar. Don’t click Reinstall macOS.")
|
||||
stage("guide.stage.offline", 2, 5, toneAccent)
|
||||
card("guide.terminal.title", "guide.terminal.body", i18n.Vars{
|
||||
"utilitiesTerminal": gt("macos.utilitiesTerminal", true),
|
||||
"reinstallMacOS": gt("macos.reinstallMacOS", true),
|
||||
})
|
||||
back(boot)
|
||||
next(command, "继续", "Continue")
|
||||
next(command, "guide.btn.continue")
|
||||
case command:
|
||||
stage("离线安装", "Offline install", 3, 5, toneAccent)
|
||||
card("键入安装命令", "Type installer command",
|
||||
"点「键入命令」自动输入到终端。脚本会抹除空白磁盘为 APFS 并启动安装。",
|
||||
"Click Type command to send this to Terminal. It formats a blank disk as APFS and starts installation.")
|
||||
stage("guide.stage.offline", 3, 5, toneAccent)
|
||||
card("guide.command.title", "guide.command.body", nil)
|
||||
c.code = OfflineCommand
|
||||
back(terminal)
|
||||
next(typingCommand, "键入命令", "Type command")
|
||||
extra(verifyCommand, "已手动输入", "Already typed it")
|
||||
next(typingCommand, "guide.command.btn.type")
|
||||
extra(verifyCommand, "guide.command.btn.typed")
|
||||
case verifyCommand:
|
||||
stage("离线安装", "Offline install", 4, 5, toneAccent)
|
||||
card("在终端按回车运行", "Press Return in Terminal",
|
||||
"核对终端命令后按回车;若提示抹盘,确认是目标磁盘再继续。看到安装进度后点下一步。",
|
||||
"Check the command in Terminal and press Return. Confirm the target disk if asked, then continue once installation starts.")
|
||||
stage("guide.stage.offline", 4, 5, toneAccent)
|
||||
card("guide.verify.title", "guide.verify.body", nil)
|
||||
back(command)
|
||||
next(waitInstall, "继续", "Continue")
|
||||
next(waitInstall, "guide.btn.continue")
|
||||
case selectDisk:
|
||||
stage("在线恢复", "Online recovery", 2, 5, toneAccent)
|
||||
card("选择目标磁盘", "Select target disk",
|
||||
"全新空盘打开「磁盘工具」,选「显示 › 显示所有设备」,按容量找到 QEMU 磁盘;已有 APFS 卷可直接重装。",
|
||||
"For a blank disk, open Disk Utility › View › Show All Devices and find the QEMU disk by size, or use an existing APFS volume.")
|
||||
stage("guide.stage.online", 2, 5, toneAccent)
|
||||
card("guide.select_disk.title", "guide.select_disk.body", i18n.Vars{
|
||||
"diskUtility": gt("macos.diskUtility", true),
|
||||
"showAllDevices": gt("macos.showAllDevices", true),
|
||||
"volume": gt("macos.volume", false),
|
||||
})
|
||||
back(boot)
|
||||
next(formatDisk, "抹掉空盘", "Erase disk")
|
||||
extra(reinstall, "使用现有 APFS 卷", "Use existing APFS volume")
|
||||
next(formatDisk, "guide.select_disk.btn.erase")
|
||||
extra(reinstall, "guide.select_disk.btn.existing")
|
||||
case formatDisk:
|
||||
stage("在线恢复", "Online recovery", 3, 5, toneAccent)
|
||||
card("抹掉空白系统盘", "Erase blank disk",
|
||||
"确认选中目标空盘后点「抹掉」:名称 Macintosh HD,格式 APFS,方案 GUID 分区图。完成后退出磁盘工具。",
|
||||
"Click Erase on the blank disk: name Macintosh HD, format APFS, scheme GUID Partition Map. Quit Disk Utility when finished.")
|
||||
stage("guide.stage.online", 3, 5, toneAccent)
|
||||
card("guide.format_disk.title", "guide.format_disk.body", i18n.Vars{
|
||||
"erase": gt("macos.erase", true),
|
||||
"guidMap": gt("macos.guidPartitionMap", false),
|
||||
"diskUtilityPlain": gt("macos.diskUtility", false),
|
||||
})
|
||||
back(selectDisk)
|
||||
next(reinstall, "继续", "Continue")
|
||||
next(reinstall, "guide.btn.continue")
|
||||
case reinstall:
|
||||
if g.Kind == BuiltIn {
|
||||
stage("内置恢复", "Built-in recovery", 0, 0, toneAccent)
|
||||
stage("guide.stage.builtin", 0, 0, toneAccent)
|
||||
back(mediaChoice)
|
||||
} else {
|
||||
stage("在线恢复", "Online recovery", 4, 5, toneAccent)
|
||||
stage("guide.stage.online", 4, 5, toneAccent)
|
||||
back(selectDisk)
|
||||
}
|
||||
card("开始安装 macOS", "Start macOS install",
|
||||
"在恢复工具选「重新安装 macOS」,选择目标系统卷并继续。出现安装进度条后点下一步。",
|
||||
"Choose Reinstall macOS in Recovery and select the target system volume. Continue once the progress bar appears.")
|
||||
next(waitInstall, "继续", "Continue")
|
||||
card("guide.reinstall.title", "guide.reinstall.body", i18n.Vars{
|
||||
"reinstallMacOS": gt("macos.reinstallMacOS", true),
|
||||
})
|
||||
next(waitInstall, "guide.btn.continue")
|
||||
case waitInstall:
|
||||
switch g.Kind {
|
||||
case Offline:
|
||||
stage("离线安装", "Offline install", 5, 5, toneAccent)
|
||||
stage("guide.stage.offline", 5, 5, toneAccent)
|
||||
back(verifyCommand)
|
||||
case Online:
|
||||
stage("在线恢复", "Online recovery", 5, 5, toneAccent)
|
||||
stage("guide.stage.online", 5, 5, toneAccent)
|
||||
back(reinstall)
|
||||
default:
|
||||
stage("内置恢复", "Built-in recovery", 0, 0, toneAccent)
|
||||
stage("guide.stage.builtin", 0, 0, toneAccent)
|
||||
back(reinstall)
|
||||
}
|
||||
card("等待安装完成", "Wait for installation",
|
||||
"进度条可能停留较久,中途会重启几次。看到「设置助理」或 Apple 账户页后,退出恢复模式。",
|
||||
"Progress may pause and the VM restarts several times. Exit recovery once Setup Assistant or Apple Account appears.")
|
||||
next(confirm, "退出恢复…", "Exit recovery…")
|
||||
card("guide.wait_install.title", "guide.wait_install.body", i18n.Vars{
|
||||
"setupAssistant": gt("macos.setupAssistant", true),
|
||||
})
|
||||
next(confirm, "guide.btn.exit_recovery")
|
||||
case recoverMenu:
|
||||
stage("内置恢复", "Built-in recovery", 2, 2, toneAccent)
|
||||
card("使用恢复工具", "Use recovery utilities",
|
||||
"可使用磁盘工具修复或排查问题;重装系统可选在线恢复或挂载本地镜像。",
|
||||
"Use Disk Utility or other recovery tools here, or choose to reinstall macOS online or from a local image.")
|
||||
stage("guide.stage.builtin", 2, 2, toneAccent)
|
||||
card("guide.recover_menu.title", "guide.recover_menu.body", i18n.Vars{
|
||||
"diskUtility": gt("macos.diskUtility", true),
|
||||
})
|
||||
back(boot)
|
||||
next(confirmRepair, "退出恢复…", "Exit recovery…")
|
||||
extra(mediaChoice, "重新安装 macOS", "Reinstall macOS")
|
||||
next(confirmRepair, "guide.btn.exit_recovery")
|
||||
extra(mediaChoice, "guide.recover_menu.btn.reinstall")
|
||||
case mediaChoice:
|
||||
stage("内置恢复", "Built-in recovery", 0, 0, toneAccent)
|
||||
card("选择重装方式", "Choose reinstall source",
|
||||
"在线重装直接使用当前恢复环境;本地镜像将在挂载并重启虚拟机后启动。",
|
||||
"Online reinstall uses this recovery environment. A local image boots after attaching it and restarting the VM.")
|
||||
stage("guide.stage.builtin", 0, 0, toneAccent)
|
||||
card("guide.media_choice.title", "guide.media_choice.body", nil)
|
||||
back(recoverMenu)
|
||||
next(reinstall, "在线重装", "Reinstall online")
|
||||
extra(pickImage, "选择本地镜像…", "Choose local image…")
|
||||
next(reinstall, "guide.media_choice.btn.online")
|
||||
extra(pickImage, "guide.media_choice.btn.local")
|
||||
case confirmImage:
|
||||
stage("确认重启", "Confirm restart", 0, 0, toneWarn)
|
||||
card("挂载镜像并重启?", "Attach image and restart?",
|
||||
"确认当前恢复操作已结束。继续会挂载该镜像并重启虚拟机。",
|
||||
"Make sure recovery work is done. Continuing attaches this image and restarts the VM.")
|
||||
stage("guide.stage.confirm_restart", 0, 0, toneWarn)
|
||||
card("guide.confirm_image.title", "guide.confirm_image.body", nil)
|
||||
c.code = detail
|
||||
cancel(mediaChoice)
|
||||
next(mounting, "挂载并重启", "Attach and restart")
|
||||
next(mounting, "guide.btn.attach_restart")
|
||||
case confirm, confirmRepair:
|
||||
stage("确认重启", "Confirm restart", 0, 0, toneWarn)
|
||||
card("退出恢复模式并重启?", "Exit recovery and restart?",
|
||||
"若仍有安装进度条,返回继续等待。确认后会退出恢复模式、启用网络并重启「"+g.Name+"」。",
|
||||
"If installation is still running, go back and wait. Confirm to exit recovery, enable networking and restart “"+g.Name+"”.")
|
||||
stage("guide.stage.confirm_restart", 0, 0, toneWarn)
|
||||
card("guide.confirm_exit.title", "guide.confirm_exit.body", i18n.Vars{"name": g.Name})
|
||||
if p == confirmRepair {
|
||||
cancel(recoverMenu)
|
||||
} else {
|
||||
cancel(waitInstall)
|
||||
}
|
||||
next(working, "退出并重启", "Exit and restart")
|
||||
next(working, "guide.confirm_exit.btn")
|
||||
case restartPending:
|
||||
stage("等待重启", "Restart required", 0, 0, toneWarn)
|
||||
card("重启虚拟机以生效", "Restart VM to apply",
|
||||
"配置已更新,重启这台虚拟机后即可生效。",
|
||||
"Settings were updated. Restart this VM to apply the changes.")
|
||||
next(working, "重启虚拟机", "Restart VM")
|
||||
stage("guide.stage.restart_pending", 0, 0, toneWarn)
|
||||
card("guide.restart_pending.title", "guide.restart_pending.body", nil)
|
||||
next(working, "guide.restart_pending.btn")
|
||||
case setup:
|
||||
stage("设置助理", "Setup Assistant", 1, 6, toneAccent)
|
||||
card("选择地区与键盘", "Region and keyboard",
|
||||
"等待系统盘启动。在设置助理中选好国家或地区、语言和键盘,已完成可直接下一步。",
|
||||
"Wait for macOS to boot, then choose your country or region, language and keyboard.")
|
||||
next(network, "继续", "Continue")
|
||||
extra(desktop, "已进入桌面", "Already at desktop")
|
||||
stage("guide.stage.setup_assistant", 1, 6, toneAccent)
|
||||
card("guide.setup.region.title", "guide.setup.region.body", i18n.Vars{
|
||||
"setupAssistantPlain": gt("macos.setupAssistant", false),
|
||||
})
|
||||
next(network, "guide.btn.continue")
|
||||
extra(desktop, "guide.setup.btn.at_desktop")
|
||||
case network:
|
||||
stage("设置助理", "Setup Assistant", 2, 6, toneAccent)
|
||||
card("连接虚拟以太网", "Connect via Ethernet",
|
||||
"网络现已启用。若提示联网,选择虚拟以太网;已自动连接可直接继续。",
|
||||
"Networking is enabled. Choose virtual Ethernet if prompted, or continue if already connected.")
|
||||
stage("guide.stage.setup_assistant", 2, 6, toneAccent)
|
||||
card("guide.setup.network.title", "guide.setup.network.body", nil)
|
||||
back(setup)
|
||||
next(account, "继续", "Continue")
|
||||
next(account, "guide.btn.continue")
|
||||
case account:
|
||||
stage("设置助理", "Setup Assistant", 3, 6, toneAccent)
|
||||
card("登录 Apple 账户", "Sign in to Apple Account",
|
||||
"可直接登录 Apple 账户;若想稍后再登,点「其他登录选项」并选「稍后设置」。",
|
||||
"Sign in to your Apple Account, or choose Other Sign-In Options › Set Up Later.")
|
||||
stage("guide.stage.setup_assistant", 3, 6, toneAccent)
|
||||
card("guide.setup.account.title", "guide.setup.account.body", i18n.Vars{
|
||||
"otherSignInLater": gt("macos.otherSignInSetUpLater", true),
|
||||
})
|
||||
back(network)
|
||||
next(localUser, "继续", "Continue")
|
||||
next(localUser, "guide.btn.continue")
|
||||
case localUser:
|
||||
stage("设置助理", "Setup Assistant", 4, 6, toneAccent)
|
||||
card("创建本地账户", "Create local account",
|
||||
"填写 macOS 用户名与登录密码;覆盖重装保留原账户时,直接登录即可。",
|
||||
"Enter a local user name and password, or sign in to an existing account after a reinstall.")
|
||||
stage("guide.stage.setup_assistant", 4, 6, toneAccent)
|
||||
card("guide.setup.user.title", "guide.setup.user.body", nil)
|
||||
back(account)
|
||||
next(preferences, "继续", "Continue")
|
||||
next(preferences, "guide.btn.continue")
|
||||
case preferences:
|
||||
stage("设置助理", "Setup Assistant", 5, 6, toneAccent)
|
||||
card("完成其余系统选项", "Finish setup screens",
|
||||
"按需完成隐私、定位与外观等页面,看到程序坞与顶部菜单栏即进入桌面。",
|
||||
"Finish the remaining privacy, location and appearance screens until the Dock and menu bar appear.")
|
||||
stage("guide.stage.setup_assistant", 5, 6, toneAccent)
|
||||
card("guide.setup.prefs.title", "guide.setup.prefs.body", nil)
|
||||
back(localUser)
|
||||
next(desktop, "继续", "Continue")
|
||||
next(desktop, "guide.btn.continue")
|
||||
case desktop:
|
||||
stage("设置助理", "Setup Assistant", 6, 6, toneOK)
|
||||
card("已进入 macOS 桌面", "macOS is ready",
|
||||
"现在可以开始使用 macOS。如需双向剪贴板和共享文件夹,可选装 Guest Tools。",
|
||||
"macOS is ready to use. Optionally install Guest Tools for shared clipboard and folders.")
|
||||
stage("guide.stage.setup_assistant", 6, 6, toneOK)
|
||||
card("guide.setup.desktop.title", "guide.setup.desktop.body", nil)
|
||||
back(preferences)
|
||||
finish()
|
||||
if g.ToolsAttached {
|
||||
extra(toolsTerminal, "安装 Guest Tools", "Install Guest Tools")
|
||||
extra(toolsTerminal, "guide.setup.btn.install_tools")
|
||||
} else {
|
||||
extra(confirmTools, "挂载 Guest Tools…", "Attach Guest Tools…")
|
||||
extra(confirmTools, "guide.setup.btn.attach_tools")
|
||||
}
|
||||
case confirmTools:
|
||||
stage("确认重启", "Confirm restart", 0, 0, toneWarn)
|
||||
card("挂载工具盘并重启?", "Attach Guest Tools and restart?",
|
||||
"先保存桌面上的内容。继续会挂载 REIMSTOOLS 工具盘并重启虚拟机。",
|
||||
"Save open work first. Continuing attaches the REIMSTOOLS disk and restarts the VM.")
|
||||
stage("guide.stage.confirm_restart", 0, 0, toneWarn)
|
||||
card("guide.confirm_tools.title", "guide.confirm_tools.body", nil)
|
||||
cancel(desktop)
|
||||
next(mountTools, "挂载并重启", "Attach and restart")
|
||||
next(mountTools, "guide.btn.attach_restart")
|
||||
case toolsTerminal:
|
||||
stage("Guest Tools", "Guest Tools", 1, 2, toneAccent)
|
||||
card("在 macOS 中打开终端", "Open Terminal in macOS",
|
||||
"打开「应用程序 › 实用工具 › 终端」,点下方按钮键入安装命令。",
|
||||
"Open Applications › Utilities › Terminal, then click below to type the command.")
|
||||
stage("guide.stage.guest_tools", 1, 2, toneAccent)
|
||||
card("guide.tools_terminal.title", "guide.tools_terminal.body", i18n.Vars{
|
||||
"appsUtilitiesTerminal": gt("macos.appsUtilitiesTerminal", true),
|
||||
})
|
||||
c.code = ToolsCommand
|
||||
back(desktop)
|
||||
next(typingTools, "键入命令", "Type command")
|
||||
next(typingTools, "guide.command.btn.type")
|
||||
case toolsVerify:
|
||||
stage("Guest Tools", "Guest Tools", 2, 2, toneOK)
|
||||
card("完成 Guest Tools 安装", "Finish Guest Tools setup",
|
||||
"在终端核对命令后按回车,按提示完成安装即可使用剪贴板与共享文件夹。",
|
||||
"Check the command in Terminal, press Return and follow the prompts to finish.")
|
||||
stage("guide.stage.guest_tools", 2, 2, toneOK)
|
||||
card("guide.tools_verify.title", "guide.tools_verify.body", nil)
|
||||
back(toolsTerminal)
|
||||
finish()
|
||||
case restored:
|
||||
stage("已回到系统", "Back on macOS", 0, 0, toneOK)
|
||||
card("从系统盘继续", "Continue from system disk",
|
||||
"可正常登录 macOS。若进入设置助理,可继续查看联网与账户步骤。",
|
||||
"Sign in to macOS as usual, or continue with Setup Assistant guidance if it appears.")
|
||||
extra(setup, "查看设置助理引导", "Open Setup Assistant guide")
|
||||
stage("guide.stage.restored", 0, 0, toneOK)
|
||||
card("guide.restored.title", "guide.restored.body", i18n.Vars{
|
||||
"setupAssistantPlain": gt("macos.setupAssistant", false),
|
||||
})
|
||||
extra(setup, "guide.restored.btn.guide")
|
||||
finish()
|
||||
case failed:
|
||||
stage("出错", "Error", 0, 0, toneDanger)
|
||||
card("操作未完成", "Could not complete step", detail, detail)
|
||||
c.left = t("返回", "Back")
|
||||
stage("guide.stage.error", 0, 0, toneDanger)
|
||||
c.title = tr("guide.failed.title")
|
||||
c.body = detail
|
||||
c.left = tr("guide.btn.return")
|
||||
case typingCommand, typingTools, working, mounting, mountTools:
|
||||
stage("进行中", "Working", 0, 0, toneAccent)
|
||||
stage("guide.stage.working", 0, 0, toneAccent)
|
||||
if p == typingCommand || p == typingTools {
|
||||
card("正在键入命令", "Typing command",
|
||||
"等待命令输入到终端…",
|
||||
"Waiting for the command to appear in Terminal…")
|
||||
card("guide.working.typing.title", "guide.working.typing.body", nil)
|
||||
} else {
|
||||
card("正在重启虚拟机", "Restarting VM",
|
||||
"等待虚拟机窗口重新打开…",
|
||||
"Waiting for the VM window to reopen…")
|
||||
card("guide.working.restarting.title", "guide.working.restarting.body", nil)
|
||||
}
|
||||
case compact:
|
||||
return content{right: t("安装引导", "Install guide")}
|
||||
return content{right: tr("guide.compact.label")}
|
||||
}
|
||||
if (c.next == "" && c.prev == "" && c.alt == "") || c.isConfirm {
|
||||
c.fold = ""
|
||||
}
|
||||
if p == boot && g.ReleaseKeys != "" {
|
||||
c.inputHint = t("释放键鼠:", "Release input: ") + g.ReleaseKeys
|
||||
c.inputHint = trv("guide.hint.release_input", i18n.Vars{"keys": g.ReleaseKeys})
|
||||
}
|
||||
// The guest may be ahead of the guide when the user follows the installer
|
||||
// directly. Keep the setup handoff reachable from earlier install screens.
|
||||
switch p {
|
||||
case boot, terminal, command, verifyCommand, selectDisk, formatDisk, reinstall:
|
||||
c.jump = t("已到设置助理?退出恢复模式", "At Setup Assistant? Exit recovery")
|
||||
c.jump = trv("guide.jump.setup_assistant", i18n.Vars{
|
||||
"setupAssistant": gt("macos.setupAssistant", false),
|
||||
})
|
||||
}
|
||||
return c
|
||||
}
|
||||
@@ -309,16 +309,13 @@ func (w *panel) sync(fg uintptr, g Guide, p page, failure string) error {
|
||||
g.Locale = loc
|
||||
c := g.content(p, failure)
|
||||
template := dialogTemplate(p, c, loc)
|
||||
flags := uintptr(c.stageTone) << dialogToneShift
|
||||
flags := (uintptr(c.stageTone) << dialogToneShift) | (uintptr(scriptForLocale(loc)) << dialogScriptShift)
|
||||
if dark {
|
||||
flags |= dialogDark
|
||||
}
|
||||
if p == compact {
|
||||
flags |= dialogCompact
|
||||
}
|
||||
if loc == i18n.ZhCN {
|
||||
flags |= dialogZh
|
||||
}
|
||||
if c.isConfirm {
|
||||
flags |= dialogConfirm
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package installguide
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"testing"
|
||||
@@ -143,9 +145,19 @@ func TestOwnedGuide(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify body, spacing, alignment rails, non-overlap and control labels across
|
||||
// every locale, kind and page.
|
||||
for _, loc := range []i18n.Locale{i18n.ZhCN, i18n.EnUS} {
|
||||
g.Locale = loc
|
||||
// built-in locales, cross-language Host/Guest dual-terms, and en-XA pseudo-locale!
|
||||
for _, tc := range []struct {
|
||||
loc i18n.Locale
|
||||
guestLang string
|
||||
}{
|
||||
{i18n.ZhCN, "zh-Hans:0"},
|
||||
{i18n.ZhCN, "en-US:0"}, // Host zh-CN + Guest en-US dual terminology
|
||||
{i18n.EnUS, "en-US:0"},
|
||||
{i18n.EnUS, "ja-JP:0"}, // Host en-US + Guest ja-JP dual terminology
|
||||
{i18n.EnXA, "en-US:0"}, // Extreme text-expansion pseudo-localization stress test
|
||||
} {
|
||||
g.Locale = tc.loc
|
||||
g.GuestLang = tc.guestLang
|
||||
g.Theme = ThemeLight
|
||||
g.ReleaseKeys = "Ctrl+Alt+Win"
|
||||
for _, kind := range []Kind{Offline, Online, BuiltIn} {
|
||||
@@ -174,24 +186,24 @@ func TestOwnedGuide(t *testing.T) {
|
||||
checkBodyFits(t, body, st, c.body)
|
||||
}
|
||||
if title, _, _ := getItem.Call(w.hwnd, idTitle); title != 0 {
|
||||
checkSingleLineFits(t, title, c.title, 0)
|
||||
checkTitleFits(t, title, st, c.title)
|
||||
}
|
||||
if right, _, _ := getItem.Call(w.hwnd, idRight); right != 0 && c.right != "" {
|
||||
if right, _, _ := getItem.Call(w.hwnd, idRight); right != 0 && c.right != "" && !st.buttonsStacked {
|
||||
checkSingleLineFits(t, right, c.right, dp(dpi, 20))
|
||||
}
|
||||
if left, _, _ := getItem.Call(w.hwnd, idLeft); left != 0 && c.left != "" {
|
||||
if left, _, _ := getItem.Call(w.hwnd, idLeft); left != 0 && c.left != "" && !st.buttonsStacked {
|
||||
checkSingleLineFits(t, left, c.left, dp(dpi, 20))
|
||||
}
|
||||
if extra, _, _ := getItem.Call(w.hwnd, idExtra); extra != 0 && c.extra != "" {
|
||||
if extra, _, _ := getItem.Call(w.hwnd, idExtra); extra != 0 && c.extra != "" && !st.extraStacked {
|
||||
checkSingleLineFits(t, extra, c.extra, dp(dpi, 12))
|
||||
}
|
||||
if fold, _, _ := getItem.Call(w.hwnd, idFold); fold != 0 && c.fold != "" {
|
||||
checkSingleLineFits(t, fold, c.fold, dp(dpi, 12))
|
||||
}
|
||||
if jump, _, _ := getItem.Call(w.hwnd, idJump); jump != 0 && c.jump != "" {
|
||||
if jump, _, _ := getItem.Call(w.hwnd, idJump); jump != 0 && c.jump != "" && tc.loc != i18n.EnXA {
|
||||
checkSingleLineFits(t, jump, c.jump, dp(dpi, 24))
|
||||
}
|
||||
if hint, _, _ := getItem.Call(w.hwnd, idInputHint); hint != 0 && c.inputHint != "" {
|
||||
if hint, _, _ := getItem.Call(w.hwnd, idInputHint); hint != 0 && c.inputHint != "" && tc.loc != i18n.EnXA {
|
||||
checkSingleLineFits(t, hint, c.inputHint, 0)
|
||||
}
|
||||
}
|
||||
@@ -207,6 +219,98 @@ func TestOwnedGuide(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverlayOfficialZhTWAndJaJPLanguagePacksFit(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
|
||||
loadMap := func(rel string) map[string]string {
|
||||
raw, err := os.ReadFile(rel)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", rel, err)
|
||||
}
|
||||
var out map[string]string
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
t.Fatalf("unmarshal %s: %v", rel, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
mergeMaps := func(a, b map[string]string) map[string]string {
|
||||
m := make(map[string]string, len(a)+len(b))
|
||||
for k, v := range a {
|
||||
m[k] = v
|
||||
}
|
||||
for k, v := range b {
|
||||
m[k] = v
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
twDir := filepath.Join("..", "plugin", "testdata", "official.lang.zh-tw", "locales")
|
||||
jaDir := filepath.Join("..", "plugin", "testdata", "official.lang.ja-jp", "locales")
|
||||
i18n.SetPluginCatalogs(map[i18n.Locale]i18n.PluginCatalog{
|
||||
"zh-TW": {
|
||||
Fallback: i18n.ZhCN,
|
||||
Messages: mergeMaps(loadMap(filepath.Join(twDir, "native.json")), loadMap(filepath.Join(twDir, "macos-glossary.json"))),
|
||||
},
|
||||
"ja-JP": {
|
||||
Fallback: i18n.EnUS,
|
||||
Messages: mergeMaps(loadMap(filepath.Join(jaDir, "native.json")), loadMap(filepath.Join(jaDir, "macos-glossary.json"))),
|
||||
},
|
||||
})
|
||||
defer i18n.SetPluginCatalogs(nil)
|
||||
|
||||
class, _ := syscall.UTF16PtrFromString("STATIC")
|
||||
offscreen := int32(-16000)
|
||||
owner, _, err := user32.NewProc("CreateWindowExW").Call(0x80, uintptr(unsafe.Pointer(class)), 0, 0x80000000,
|
||||
uintptr(offscreen), uintptr(offscreen), 1280, 800, 0, 0, 0, 0)
|
||||
if owner == 0 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer destroyWindow.Call(owner)
|
||||
getItem := user32.NewProc("GetDlgItem")
|
||||
|
||||
g := Guide{
|
||||
Name: "macos-tahoe-dev",
|
||||
PID: uint32(os.Getpid()),
|
||||
Kind: Online,
|
||||
ReleaseKeys: "Ctrl+Alt+Win",
|
||||
Theme: ThemeLight,
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
loc i18n.Locale
|
||||
guestLang string
|
||||
}{
|
||||
{"zh-TW", "zh-Hant:0"},
|
||||
{"zh-TW", "en-US:0"},
|
||||
{"ja-JP", "ja-JP:0"},
|
||||
{"ja-JP", "en-US:0"},
|
||||
} {
|
||||
g.Locale = tc.loc
|
||||
g.GuestLang = tc.guestLang
|
||||
for _, p := range []page{boot, selectDisk, formatDisk, confirm, setup, desktop, compact} {
|
||||
var w panel
|
||||
if err := w.sync(owner, g, p, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := g.content(p, "")
|
||||
st := getPanelState(w.hwnd)
|
||||
if st == nil {
|
||||
t.Fatalf("missing panelState for %s/%s", tc.loc, p)
|
||||
}
|
||||
if p != compact {
|
||||
checkCardGeometry(t, w.hwnd, st, p, c)
|
||||
if body, _, _ := getItem.Call(w.hwnd, idBody); body != 0 {
|
||||
checkBodyFits(t, body, st, c.body)
|
||||
}
|
||||
if title, _, _ := getItem.Call(w.hwnd, idTitle); title != 0 {
|
||||
checkTitleFits(t, title, st, c.title)
|
||||
}
|
||||
}
|
||||
w.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func childRectInParent(parent, child uintptr) rect {
|
||||
var r rect
|
||||
getWindowRect.Call(child, uintptr(unsafe.Pointer(&r)))
|
||||
@@ -259,7 +363,7 @@ func checkCardGeometry(t *testing.T, hwnd uintptr, st *panelState, p page, c con
|
||||
if r.bottom-r.top != dp(dpi, 31) {
|
||||
t.Errorf("page=%s secondary height=%d want %d", p, r.bottom-r.top, dp(dpi, 31))
|
||||
}
|
||||
if !c.isConfirm && c.right != "" && r.left != padX {
|
||||
if (!c.isConfirm || st.buttonsStacked) && c.right != "" && r.left != padX {
|
||||
t.Errorf("page=%s left button x=%d want padX=%d", p, r.left, padX)
|
||||
}
|
||||
case idJump:
|
||||
@@ -279,6 +383,24 @@ func checkCardGeometry(t *testing.T, hwnd uintptr, st *panelState, p page, c con
|
||||
}
|
||||
}
|
||||
|
||||
func checkTitleFits(t *testing.T, label uintptr, st *panelState, text string) {
|
||||
t.Helper()
|
||||
var available rect
|
||||
getClientRect.Call(label, uintptr(unsafe.Pointer(&available)))
|
||||
wantH := max(st.titleLineH, int32(len(st.titleLines))*st.titleLineH)
|
||||
if available.bottom != wantH {
|
||||
t.Errorf("title height=%d want exact %d (%d lines)", available.bottom, wantH, len(st.titleLines))
|
||||
}
|
||||
dc, _, _ := user32.NewProc("GetDC").Call(label)
|
||||
defer user32.NewProc("ReleaseDC").Call(label, dc)
|
||||
font, _, _ := sendMessage.Call(label, 0x0031, 0, 0) // WM_GETFONT
|
||||
for _, line := range st.titleLines {
|
||||
if w := measureLineWidth(dc, font, line); w > available.right {
|
||||
t.Errorf("wrapped title line %q width %d exceeds %d (full=%q)", line, w, available.right, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func checkBodyFits(t *testing.T, label uintptr, st *panelState, text string) {
|
||||
t.Helper()
|
||||
var available rect
|
||||
|
||||
@@ -29,24 +29,25 @@ type openFileName struct {
|
||||
reservedCount, flagsEx uint32
|
||||
}
|
||||
|
||||
var (
|
||||
comdlg32 = syscall.NewLazyDLL("comdlg32.dll")
|
||||
procGetOpenFileNameW = comdlg32.NewProc("GetOpenFileNameW")
|
||||
procCommDlgExtendedError = comdlg32.NewProc("CommDlgExtendedError")
|
||||
)
|
||||
|
||||
func chooseImage(owner uintptr, locale i18n.Locale) (string, error) {
|
||||
title := "Choose a macOS installer image"
|
||||
label := "Installer images"
|
||||
if locale == i18n.ZhCN {
|
||||
title = "选择 macOS 安装镜像"
|
||||
label = "安装镜像"
|
||||
}
|
||||
title := i18n.T(locale, "guide.picker.title")
|
||||
label := i18n.T(locale, "guide.picker.filter")
|
||||
titleW, _ := syscall.UTF16PtrFromString(title)
|
||||
filter := utf16.Encode([]rune(label + " (*.img, *.dmg)\x00*.img;*.dmg\x00\x00"))
|
||||
file := make([]uint16, 32768)
|
||||
opts := openFileName{owner: owner, filter: &filter[0], filterIndex: 1, file: &file[0], maxFile: uint32(len(file)), title: titleW,
|
||||
flags: 0x80000 | 0x1000 | 0x800 | 0x8} // Explorer; existing path/file; preserve current directory.
|
||||
opts.size = uint32(unsafe.Sizeof(opts))
|
||||
dll := syscall.NewLazyDLL("comdlg32.dll")
|
||||
if ok, _, _ := dll.NewProc("GetOpenFileNameW").Call(uintptr(unsafe.Pointer(&opts))); ok != 0 {
|
||||
if ok, _, _ := procGetOpenFileNameW.Call(uintptr(unsafe.Pointer(&opts))); ok != 0 {
|
||||
return syscall.UTF16ToString(file), nil
|
||||
}
|
||||
if code, _, _ := dll.NewProc("CommDlgExtendedError").Call(); code != 0 {
|
||||
if code, _, _ := procCommDlgExtendedError.Call(); code != 0 {
|
||||
return "", fmt.Errorf("file dialog: %#x", code)
|
||||
}
|
||||
return "", nil
|
||||
|
||||
@@ -40,10 +40,19 @@ func Presets() []Preset {
|
||||
|
||||
// DefaultGuestLang chooses the default macOS prev-lang:kbd matching the app UI locale.
|
||||
func DefaultGuestLang(locale i18n.Locale) string {
|
||||
if locale == i18n.EnUS {
|
||||
resolved := strings.ToLower(string(i18n.ResolveLocale(string(locale))))
|
||||
switch {
|
||||
case resolved == "zh-tw" || resolved == "zh-hk" || resolved == "zh-mo" || strings.HasPrefix(resolved, "zh-hant"):
|
||||
return "zh-Hant:0"
|
||||
case strings.HasPrefix(resolved, "zh"):
|
||||
return "zh-Hans:0"
|
||||
case strings.HasPrefix(resolved, "ja"):
|
||||
return "ja-JP:0"
|
||||
case strings.HasPrefix(resolved, "ko"):
|
||||
return "ko-KR:0"
|
||||
default:
|
||||
return "en-US:0"
|
||||
}
|
||||
return "zh-Hans:0"
|
||||
}
|
||||
|
||||
var reGuestLang = regexp.MustCompile(`^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2}:[0-9]{1,6}$`)
|
||||
|
||||
+43
-14
@@ -80,14 +80,27 @@ func (a *AssetServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
data, err := os.ReadFile(fullPath)
|
||||
if err != nil {
|
||||
http.Error(w, "read error", http.StatusInternalServerError)
|
||||
ext := strings.ToLower(filepath.Ext(fullPath))
|
||||
const (
|
||||
maxSanitizedTextBytes = 2 << 20 // 2 MiB for SVG / CSS buffered sanitization
|
||||
maxStaticAssetBytes = 16 << 20 // 16 MiB cap for WOFF2 / images / HTML / scripts
|
||||
)
|
||||
if (ext == ".svg" || ext == ".css") && info.Size() > maxSanitizedTextBytes {
|
||||
http.Error(w, "asset exceeds size limit", http.StatusRequestEntityTooLarge)
|
||||
return
|
||||
}
|
||||
if info.Size() > maxStaticAssetBytes {
|
||||
http.Error(w, "asset exceeds size limit", http.StatusRequestEntityTooLarge)
|
||||
return
|
||||
}
|
||||
|
||||
ext := strings.ToLower(filepath.Ext(fullPath))
|
||||
ct := mime.TypeByExtension(ext)
|
||||
switch ext {
|
||||
case ".woff2":
|
||||
ct = "font/woff2"
|
||||
case ".woff":
|
||||
ct = "font/woff"
|
||||
}
|
||||
if ct == "" {
|
||||
ct = "application/octet-stream"
|
||||
}
|
||||
@@ -102,23 +115,39 @@ func (a *AssetServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; font-src 'self'; sandbox")
|
||||
}
|
||||
|
||||
// Strip any embedded script/event handlers from SVG assets (§7.3).
|
||||
if ext == ".svg" {
|
||||
ct = "image/svg+xml; charset=utf-8"
|
||||
data = SanitizeSVG(data)
|
||||
}
|
||||
// Verify CSS files remain safe (including relative asset containment, B5).
|
||||
if ext == ".css" {
|
||||
if err := ValidateThemeCSSSafetyInDir(string(data), filepath.Dir(fullPath)); err != nil {
|
||||
http.Error(w, "unsafe stylesheet blocked", http.StatusForbidden)
|
||||
if ext == ".svg" || ext == ".css" {
|
||||
data, err := os.ReadFile(fullPath)
|
||||
if err != nil {
|
||||
http.Error(w, "read error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if ext == ".svg" {
|
||||
ct = "image/svg+xml; charset=utf-8"
|
||||
data = SanitizeSVG(data)
|
||||
} else {
|
||||
if err := ValidateThemeCSSSafetyInDir(string(data), filepath.Dir(fullPath)); err != nil {
|
||||
http.Error(w, "unsafe stylesheet blocked", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", ct)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if r.Method == http.MethodGet {
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
fh, err := os.Open(fullPath)
|
||||
if err != nil {
|
||||
http.Error(w, "read error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer fh.Close()
|
||||
w.Header().Set("Content-Type", ct)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if r.Method == http.MethodGet {
|
||||
_, _ = w.Write(data)
|
||||
_, _ = io.CopyN(w, fh, info.Size())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -116,6 +116,26 @@ func (b *Broker) Authorize(pluginID, perm string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// AllowRate checks that pluginID is active and within its 120 req/s Host API
|
||||
// rate window (used for zero-permission read-only calls such as i18n.getBundle).
|
||||
func (b *Broker) AllowRate(pluginID string) error {
|
||||
if b.reg == nil {
|
||||
return errors.New("registry unavailable")
|
||||
}
|
||||
info, ok := b.reg.Info(pluginID)
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown plugin %q", pluginID)
|
||||
}
|
||||
if info.State != StateActive && info.State != StateDegraded {
|
||||
return fmt.Errorf("plugin %q is not active (state=%s)", pluginID, info.State)
|
||||
}
|
||||
if !b.allowRate(pluginID, 120) {
|
||||
b.Audit(pluginID, "RATE_LIMIT", "i18n.getBundle")
|
||||
return fmt.Errorf("plugin %q exceeded Host API rate limit", pluginID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Broker) allowRate(pluginID string, limitPerSec int) bool {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/installer"
|
||||
"github.com/Nwflower/reims-go/internal/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
@@ -16,6 +17,14 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
func coreLocale(cb HostCallbacks) i18n.Locale {
|
||||
if cb.GetConfig != nil {
|
||||
cfg := cb.GetConfig()
|
||||
return i18n.EffectiveLocale(cfg.Locale)
|
||||
}
|
||||
return i18n.Detect()
|
||||
}
|
||||
|
||||
// IDCore is the always-on builtin that holds everything Reims-Go needs to run
|
||||
// macOS VMs: the reims driver, the default theme, start preparation and the
|
||||
// host workarounds. Users can't switch it off; the two workarounds have their
|
||||
@@ -183,7 +192,7 @@ func defCore(ver string, cb HostCallbacks) plugin.PluginDef {
|
||||
caps, _ := p.HostFacts["runtime.capabilities"].([]string)
|
||||
if whpxFallbackNeeded(p.HostFacts) && !hasCap(caps, "nested-virt-nonfatal") {
|
||||
return plugin.PreflightResult{
|
||||
Advices: []string{"Host lacks nested-virt property and runtime lacks nested-virt-nonfatal capability; kernel-irqchip=off will be auto-applied"},
|
||||
Advices: []string{i18n.T(coreLocale(cb), "core.preflight.whpx_irqchip_advice")},
|
||||
}, nil
|
||||
}
|
||||
return nil, nil
|
||||
@@ -253,7 +262,7 @@ func stepOfflineHelper(cb HostCallbacks, p plugin.BeforeStartPayload, in *plugin
|
||||
cfg := cb.GetConfig()
|
||||
helperPath, err := installer.EnsureOfflineHelperImage(cfg.XDGCacheDir(), p.InstallerPath)
|
||||
if err != nil {
|
||||
in.Warnings = append(in.Warnings, "offline install helper disk skipped: "+err.Error())
|
||||
in.Warnings = append(in.Warnings, i18n.M(coreLocale(cb), "core.start.warn.offline_helper_skipped", map[string]any{"err": err.Error()}))
|
||||
return
|
||||
}
|
||||
in.Args = append(in.Args, plugin.ArgFragment{
|
||||
@@ -291,7 +300,7 @@ func stepRecoveryBoot(ctx context.Context, cb HostCallbacks, p plugin.BeforeStar
|
||||
}
|
||||
})
|
||||
if err := reims.NewClient(&cfg, *active).UpdateOpenCore(ctx, p.VMName, show, w, w); err != nil {
|
||||
in.Warnings = append(in.Warnings, "could not update OpenCore boot picker: "+err.Error())
|
||||
in.Warnings = append(in.Warnings, i18n.M(coreLocale(cb), "core.start.warn.opencore_picker_failed", map[string]any{"err": err.Error()}))
|
||||
return
|
||||
}
|
||||
vmstart.WriteRecoveryMarker(p.VMDir, next)
|
||||
@@ -318,7 +327,7 @@ func stepGuestLang(ctx context.Context, cb HostCallbacks, p plugin.BeforeStartPa
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfg, *active)
|
||||
if _, err := opencore.PatchImagePrevLang(ctx, ocPath, saved, active.QemuImgPath(), env); err != nil {
|
||||
in.Warnings = append(in.Warnings, "could not apply macOS language to OpenCore: "+err.Error())
|
||||
in.Warnings = append(in.Warnings, i18n.M(coreLocale(cb), "core.start.warn.opencore_lang_failed", map[string]any{"err": err.Error()}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -357,7 +366,7 @@ func stepWHPXFallback(cb HostCallbacks, p plugin.BeforeStartPayload, in *plugin.
|
||||
Builtin: true,
|
||||
Priority: 90,
|
||||
})
|
||||
in.Warnings = append(in.Warnings, "Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically")
|
||||
in.Warnings = append(in.Warnings, i18n.T(coreLocale(cb), "core.start.warn.whpx_irqchip_applied"))
|
||||
}
|
||||
|
||||
// stepWin10ColdReboot adds -no-reboot with a private QMP socket on Windows 10
|
||||
|
||||
@@ -383,7 +383,7 @@ func TestL1RuleHooks(t *testing.T) {
|
||||
},
|
||||
Actions: []RuleAction{
|
||||
{Kind: "append_args", Key: "rtc", Tokens: []string{"-rtc", "base=localtime"}},
|
||||
{Kind: "warn", Message: "applied rtc rule"},
|
||||
{Kind: "warn", Message: LocalizedText{ZhCN: "已应用 RTC 规则", EnUS: "applied rtc rule"}},
|
||||
},
|
||||
}},
|
||||
},
|
||||
|
||||
@@ -3,8 +3,11 @@ package plugin
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
@@ -132,3 +135,315 @@ func TestManagerResolvedLocalePacks(t *testing.T) {
|
||||
t.Fatalf("expected empty locale packs after disable, got ui=%d backend=%d", len(uiPacks), len(backendPacks))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDualTrackLocaleV2FontsAndPluginOverrides(t *testing.T) {
|
||||
dataRoot := t.TempDir()
|
||||
|
||||
// 1. Create functional plugin `acme.snap` with private l10n (`locales/en-US.json`, `locales/zh-CN.json`).
|
||||
funcDir := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(funcDir, "locales"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(funcDir, "locales", "en-US.json"), []byte(`{
|
||||
"status.ok": {"message": "Backed up {count} items", "$comment": "Backup summary"}
|
||||
}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(funcDir, "locales", "zh-CN.json"), []byte(`{
|
||||
"status.ok": "已备份 {count} 项"
|
||||
}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
funcManifest := `{
|
||||
"schema": 1,
|
||||
"id": "acme.snap",
|
||||
"version": "1.0.0",
|
||||
"name": {"zh-CN": "快照助手", "en-US": "Snap Helper"},
|
||||
"description": {"zh-CN": "自动快照", "en-US": "Auto snapshots"},
|
||||
"l10n": "locales",
|
||||
"permissions": ["ui:slot"],
|
||||
"settings": {
|
||||
"x-scope": "app",
|
||||
"properties": {
|
||||
"keep_count": {
|
||||
"type": "integer",
|
||||
"title": {"zh-CN": "保留份数", "en-US": "Keep count"},
|
||||
"default": 5
|
||||
}
|
||||
}
|
||||
},
|
||||
"contributes": {
|
||||
"menus": [
|
||||
{"id": "quick", "slot": "vm.toolbar", "command": "snap.now", "title": {"zh-CN": "立即备份", "en-US": "Backup Now"}}
|
||||
]
|
||||
}
|
||||
}`
|
||||
if err := os.WriteFile(filepath.Join(funcDir, "plugin.json"), []byte(funcManifest), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 2. Create standalone Language Pack `official.lang.ja-jp` with domain files, valid WOFF2 font, and pluginOverrides for `acme.snap`.
|
||||
langDir := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(langDir, "locales"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(langDir, "fonts"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(langDir, "locales", "core.json"), []byte(`{"sidebarSettings": "設定"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(langDir, "locales", "native.json"), []byte(`{"tray.quit": "Reims-Go を終了"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Write a minimal dummy file starting with valid WOFF2 4-byte magic ("wOF2").
|
||||
woff2Bytes := append([]byte("wOF2"), make([]byte, 44)...)
|
||||
if err := os.WriteFile(filepath.Join(langDir, "fonts", "noto-jp-ui.woff2"), woff2Bytes, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Also test rejecting bad WOFF2 header.
|
||||
badFontPath := filepath.Join(langDir, "fonts", "bad.woff2")
|
||||
if err := os.WriteFile(badFontPath, []byte("OTTO0000"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ValidateLocaleContribution(LocaleContribution{
|
||||
Locale: "ja-JP",
|
||||
Fonts: []ThemeFont{{Family: "BadFont", File: "fonts/bad.woff2"}},
|
||||
}, langDir); err == nil {
|
||||
t.Fatal("expected error for non-wOF2 font magic header")
|
||||
}
|
||||
|
||||
langManifest := `{
|
||||
"schema": 1,
|
||||
"id": "official.lang.ja-jp",
|
||||
"version": "1.0.0",
|
||||
"name": {"zh-CN": "日语语言包", "en-US": "Japanese Language Pack", "ja-JP": "日本語言語パック"},
|
||||
"description": {"en-US": "Japanese UI and CLI localization"},
|
||||
"contributes": {
|
||||
"locales": [
|
||||
{
|
||||
"locale": "ja-JP",
|
||||
"label": "日本語",
|
||||
"fallback": "en-US",
|
||||
"files": {
|
||||
"core": "locales/core.json",
|
||||
"native": "locales/native.json"
|
||||
},
|
||||
"fonts": [
|
||||
{"family": "Reims Noto JP", "file": "fonts/noto-jp-ui.woff2", "weight": "400"}
|
||||
],
|
||||
"pluginOverrides": {
|
||||
"acme.snap": {
|
||||
"manifest": {
|
||||
"name": "スナップヘルパー",
|
||||
"description": "自動スナップショット",
|
||||
"fields": {
|
||||
"setting.keep_count.title": "保持数",
|
||||
"menu.quick.title": "今すぐバックアップ"
|
||||
}
|
||||
},
|
||||
"messages": {
|
||||
"status.ok": "{count} 件をバックアップしました"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}`
|
||||
if err := os.WriteFile(filepath.Join(langDir, "plugin.json"), []byte(langManifest), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
mgr, err := NewManager(ManagerOptions{DataRoot: dataRoot, HostVersion: "0.2.8"})
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager: %v", err)
|
||||
}
|
||||
defer mgr.Close()
|
||||
|
||||
if _, err := mgr.LinkDev(context.Background(), funcDir); err != nil {
|
||||
t.Fatalf("LinkDev funcDir: %v", err)
|
||||
}
|
||||
if err := mgr.Enable(context.Background(), "acme.snap", false); err != nil {
|
||||
t.Fatalf("Enable acme.snap: %v", err)
|
||||
}
|
||||
if _, err := mgr.LinkDev(context.Background(), langDir); err != nil {
|
||||
t.Fatalf("LinkDev langDir: %v", err)
|
||||
}
|
||||
if err := mgr.Enable(context.Background(), "official.lang.ja-jp", false); err != nil {
|
||||
t.Fatalf("Enable official.lang.ja-jp: %v", err)
|
||||
}
|
||||
|
||||
uiPacks, backendPacks := mgr.ResolvedLocalePacks()
|
||||
var jaPack *ResolvedLocalePack
|
||||
for i := range uiPacks {
|
||||
if uiPacks[i].Locale == "ja-JP" {
|
||||
jaPack = &uiPacks[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if jaPack == nil {
|
||||
t.Fatalf("ja-JP pack missing in %+v", uiPacks)
|
||||
}
|
||||
if jaPack.Messages["sidebarSettings"] != "設定" {
|
||||
t.Fatalf("jaPack.Messages[sidebarSettings] = %q, want 設定", jaPack.Messages["sidebarSettings"])
|
||||
}
|
||||
if len(jaPack.Fonts) != 1 || jaPack.Fonts[0].Family != "Reims Noto JP" {
|
||||
t.Fatalf("unexpected jaPack.Fonts: %+v", jaPack.Fonts)
|
||||
}
|
||||
if jaPack.PluginMessages["acme.snap"]["status.ok"] != "{count} 件をバックアップしました" {
|
||||
t.Fatalf("unexpected PluginMessages: %+v", jaPack.PluginMessages)
|
||||
}
|
||||
if backendPacks[i18n.Locale("ja-JP")].Messages["tray.quit"] != "Reims-Go を終了" {
|
||||
t.Fatalf("unexpected backend pack: %+v", backendPacks)
|
||||
}
|
||||
|
||||
// Verify PluginL10nBundle merges acme.snap's own en-US fallback + ja-JP override.
|
||||
bundle := mgr.PluginL10nBundle("acme.snap", i18n.Locale("ja-JP"))
|
||||
if bundle["status.ok"] != "{count} 件をバックアップしました" {
|
||||
t.Fatalf("PluginL10nBundle(ja-JP) = %+v", bundle)
|
||||
}
|
||||
|
||||
// Verify LocalizePluginInfos and LocalizeMenus apply manifest overrides non-destructively.
|
||||
infos := mgr.LocalizePluginInfos(mgr.Registry().List())
|
||||
var snapInfo *PluginInfo
|
||||
for i := range infos {
|
||||
if infos[i].ID == "acme.snap" {
|
||||
snapInfo = &infos[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if snapInfo == nil || snapInfo.Name.Get("ja-JP") != "スナップヘルパー" {
|
||||
t.Fatalf("LocalizePluginInfos failed: %+v", snapInfo)
|
||||
}
|
||||
if snapInfo.Settings.Properties["keep_count"].Title.Get("ja-JP") != "保持数" {
|
||||
t.Fatalf("Settings property title override failed: %+v", snapInfo.Settings.Properties["keep_count"])
|
||||
}
|
||||
menus := mgr.LocalizeMenus(mgr.Registry().Menus(""))
|
||||
if len(menus) != 1 || menus[0].Title.Get("ja-JP") != "今すぐバックアップ" {
|
||||
t.Fatalf("LocalizeMenus failed: %+v", menus)
|
||||
}
|
||||
|
||||
// Verify LoadStaticLocalePacks (< 2ms CLI path) loads native.json without starting Manager.
|
||||
staticPacks := LoadStaticLocalePacks(dataRoot)
|
||||
defer i18n.SetPluginCatalogs(nil)
|
||||
if got := i18n.T(i18n.Locale("ja-JP"), "tray.quit"); got != "Reims-Go を終了" {
|
||||
t.Fatalf("LoadStaticLocalePacks i18n.T(ja-JP, tray.quit) = %q, staticPacks=%+v", got, staticPacks)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityAndGhostLocaleRegressions(t *testing.T) {
|
||||
dataRoot := t.TempDir()
|
||||
|
||||
// H-3: A functional plugin shipping locales/de-DE.json (Track B) without contributes.locales (Track A)
|
||||
// must NOT mark HasUIMessages=true, while still serving its own German L10n bundle.
|
||||
funcDir := filepath.Join(t.TempDir(), "acme.german-tool")
|
||||
if err := os.MkdirAll(filepath.Join(funcDir, "locales"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest := `{
|
||||
"schema": 1,
|
||||
"id": "acme.german-tool",
|
||||
"version": "1.0.0",
|
||||
"name": {"en-US": "German Tool"},
|
||||
"description": {"en-US": "Ships plugin-scoped de-DE strings"},
|
||||
"l10n": "locales"
|
||||
}`
|
||||
if err := os.WriteFile(filepath.Join(funcDir, "plugin.json"), []byte(manifest), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(funcDir, "locales", "en-US.json"), []byte(`{"btn.run":"Run"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(funcDir, "locales", "de-DE.json"), []byte(`{"btn.run":"Ausführen"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Also prepare an oversized > 2 MiB SVG inside funcDir to verify M-4 AssetServer cap.
|
||||
bigSVG := `<svg xmlns="http://www.w3.org/2000/svg"><!--` + strings.Repeat("A", (2<<20)+1024) + `--></svg>`
|
||||
if err := os.WriteFile(filepath.Join(funcDir, "huge.svg"), []byte(bigSVG), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
mgr, err := NewManager(ManagerOptions{DataRoot: dataRoot, HostVersion: "0.2.8"})
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager: %v", err)
|
||||
}
|
||||
defer mgr.Close()
|
||||
|
||||
if _, err := mgr.LinkDev(context.Background(), funcDir); err != nil {
|
||||
t.Fatalf("LinkDev: %v", err)
|
||||
}
|
||||
if err := mgr.Enable(context.Background(), "acme.german-tool", false); err != nil {
|
||||
t.Fatalf("Enable: %v", err)
|
||||
}
|
||||
|
||||
uiPacks, _ := mgr.ResolvedLocalePacks()
|
||||
var dePack *ResolvedLocalePack
|
||||
for i := range uiPacks {
|
||||
if uiPacks[i].Locale == "de-DE" {
|
||||
dePack = &uiPacks[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if dePack == nil {
|
||||
t.Fatalf("expected de-DE plugin L10n entry in uiPacks, got %+v", uiPacks)
|
||||
}
|
||||
if dePack.HasUIMessages {
|
||||
t.Fatalf("expected HasUIMessages=false for functional plugin without Track A host UI messages")
|
||||
}
|
||||
if got := mgr.PluginL10nBundle("acme.german-tool", i18n.Locale("de-DE"))["btn.run"]; got != "Ausführen" {
|
||||
t.Fatalf("PluginL10nBundle(de-DE) = %q, want Ausführen", got)
|
||||
}
|
||||
|
||||
// M-2: LinkDev must reject a dev plugin directory with an invalid font magic header.
|
||||
badDevDir := filepath.Join(t.TempDir(), "bad.font.pack")
|
||||
if err := os.MkdirAll(filepath.Join(badDevDir, "fonts"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
badManifest := `{
|
||||
"schema": 1,
|
||||
"id": "bad.font.pack",
|
||||
"version": "1.0.0",
|
||||
"name": {"en-US": "Bad Font"},
|
||||
"contributes": {
|
||||
"locales": [{"locale": "fr-FR", "label": "Français", "fonts": [{"family": "Bad", "file": "fonts/bad.woff2"}]}]
|
||||
}
|
||||
}`
|
||||
if err := os.WriteFile(filepath.Join(badDevDir, "plugin.json"), []byte(badManifest), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(badDevDir, "fonts", "bad.woff2"), []byte("NOT_WOFF2"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := mgr.LinkDev(context.Background(), badDevDir); err == nil {
|
||||
t.Fatal("expected LinkDev to reject invalid WOFF2 magic header")
|
||||
}
|
||||
|
||||
// M-3: Broker.AllowRate enforces 120 req/s per active plugin.
|
||||
for i := 0; i < 120; i++ {
|
||||
if err := mgr.Broker().AllowRate("acme.german-tool"); err != nil {
|
||||
t.Fatalf("AllowRate call %d failed unexpectedly: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
if err := mgr.Broker().AllowRate("acme.german-tool"); err == nil {
|
||||
t.Fatal("expected 121st AllowRate call within 1s window to be rate-limited")
|
||||
}
|
||||
|
||||
// M-4: AssetServer rejects > 2 MiB SVG with 413 and path traversal with 400/403.
|
||||
reqOversized := httptest.NewRequest(http.MethodGet, mgr.Assets().AssetURL("acme.german-tool", "huge.svg"), nil)
|
||||
recOversized := httptest.NewRecorder()
|
||||
mgr.Assets().ServeHTTP(recOversized, reqOversized)
|
||||
if recOversized.Code != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("expected 413 for >2MiB SVG, got %d", recOversized.Code)
|
||||
}
|
||||
|
||||
rawTraversalURL := "/plugin-assets/" + mgr.Assets().Token() + "/acme.german-tool/../secret.txt"
|
||||
reqTraversal := httptest.NewRequest(http.MethodGet, rawTraversalURL, nil)
|
||||
recTraversal := httptest.NewRecorder()
|
||||
mgr.Assets().ServeHTTP(recTraversal, reqTraversal)
|
||||
if recTraversal.Code != http.StatusBadRequest && recTraversal.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 400/403 for traversal, got %d", recTraversal.Code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/locales"
|
||||
)
|
||||
|
||||
type localeDomainSpec struct {
|
||||
Key string // key in LocaleContribution.Files
|
||||
FileName string // filename under locales/<tag>/
|
||||
IsUI bool
|
||||
IsNative bool
|
||||
}
|
||||
|
||||
var canonicalLocaleDomains = []localeDomainSpec{
|
||||
{Key: "core", FileName: "core.json", IsUI: true, IsNative: true},
|
||||
{Key: "vm", FileName: "vm.json", IsUI: true},
|
||||
{Key: "wizard", FileName: "wizard.json", IsUI: true},
|
||||
{Key: "settings", FileName: "settings.json", IsUI: true},
|
||||
{Key: "plugins", FileName: "plugins.json", IsUI: true},
|
||||
{Key: "native", FileName: "native.json", IsNative: true},
|
||||
{Key: "macosGlossary", FileName: "macos-glossary.json", IsUI: true, IsNative: true},
|
||||
}
|
||||
|
||||
// LocaleInitOptions configures scaffolding for `reims-go plugin locale init`.
|
||||
type LocaleInitOptions struct {
|
||||
Locale string
|
||||
OutDir string
|
||||
PluginID string
|
||||
ForPlugin string
|
||||
}
|
||||
|
||||
// DomainCoverage summarizes translation completeness for a single catalog domain.
|
||||
type DomainCoverage struct {
|
||||
Domain string `json:"domain"`
|
||||
Translated int `json:"translated"`
|
||||
Total int `json:"total"`
|
||||
Percent float64 `json:"percent"`
|
||||
}
|
||||
|
||||
// LocaleCheckReport summarizes static verification and coverage of a language pack.
|
||||
type LocaleCheckReport struct {
|
||||
PluginID string `json:"plugin_id"`
|
||||
Locale string `json:"locale"`
|
||||
Domains []DomainCoverage `json:"domains,omitempty"`
|
||||
TotalTranslated int `json:"total_translated"`
|
||||
TotalReference int `json:"total_reference"`
|
||||
TotalPercent float64 `json:"total_percent"`
|
||||
UnknownKeys []string `json:"unknown_keys,omitempty"`
|
||||
Findings []DoctorFinding `json:"findings,omitempty"`
|
||||
Errors int `json:"errors"`
|
||||
Warnings int `json:"warnings"`
|
||||
}
|
||||
|
||||
// InitLocalePack scaffolds a v2 L1 Language Pack directory (or cross-plugin
|
||||
// override template when opts.ForPlugin is set) from Reims-Go's embedded catalogs.
|
||||
func InitLocalePack(opts LocaleInitOptions) error {
|
||||
canon, ok := i18n.ParseLocale(opts.Locale)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid BCP-47 locale tag %q (e.g. zh-TW, ja-JP, ko-KR, de-DE)", opts.Locale)
|
||||
}
|
||||
if strings.TrimSpace(opts.OutDir) == "" {
|
||||
return errors.New("output directory (--out) is required")
|
||||
}
|
||||
if opts.ForPlugin != "" && !reReverseDomainID.MatchString(opts.ForPlugin) {
|
||||
return fmt.Errorf("invalid target plugin id %q", opts.ForPlugin)
|
||||
}
|
||||
|
||||
tagLower := strings.ToLower(string(canon))
|
||||
pluginID := strings.TrimSpace(opts.PluginID)
|
||||
if pluginID == "" {
|
||||
if opts.ForPlugin != "" {
|
||||
pluginID = fmt.Sprintf("community.lang.%s.%s", strings.ReplaceAll(opts.ForPlugin, ".", "-"), tagLower)
|
||||
} else {
|
||||
pluginID = "community.lang." + tagLower
|
||||
}
|
||||
}
|
||||
if !reReverseDomainID.MatchString(pluginID) {
|
||||
return fmt.Errorf("invalid plugin id %q", pluginID)
|
||||
}
|
||||
|
||||
outDir := filepath.Clean(opts.OutDir)
|
||||
if _, err := os.Stat(filepath.Join(outDir, "plugin.json")); err == nil {
|
||||
return fmt.Errorf("refusing to overwrite existing plugin.json in %s", outDir)
|
||||
}
|
||||
if err := os.MkdirAll(outDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fb := i18n.DefaultFallback(canon)
|
||||
sourceLocale := "en-US"
|
||||
if fb == i18n.ZhCN {
|
||||
sourceLocale = "zh-CN"
|
||||
}
|
||||
|
||||
lc := LocaleContribution{
|
||||
Locale: string(canon),
|
||||
Label: defaultNativeLocaleLabel(string(canon)),
|
||||
Fallback: string(fb),
|
||||
}
|
||||
|
||||
if opts.ForPlugin != "" {
|
||||
ovDir := filepath.Join(outDir, "overrides")
|
||||
if err := os.MkdirAll(ovDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
manRel := "overrides/" + opts.ForPlugin + ".manifest.json"
|
||||
msgRel := "overrides/" + opts.ForPlugin + ".messages.json"
|
||||
sampleMan := PluginManifestOverride{
|
||||
Name: "",
|
||||
Description: "",
|
||||
Fields: map[string]string{
|
||||
"setting.example.title": "Translated title",
|
||||
},
|
||||
}
|
||||
if err := writeIndentedJSON(filepath.Join(outDir, filepath.FromSlash(manRel)), sampleMan); err != nil {
|
||||
return err
|
||||
}
|
||||
sampleMsg := map[string]any{
|
||||
"$comment": "Translate keys from target plugin " + opts.ForPlugin,
|
||||
"example": map[string]any{
|
||||
"message": "Translated message",
|
||||
"$comment": "Replace with keys declared in target plugin locales/",
|
||||
},
|
||||
}
|
||||
if err := writeIndentedJSON(filepath.Join(outDir, filepath.FromSlash(msgRel)), sampleMsg); err != nil {
|
||||
return err
|
||||
}
|
||||
lc.PluginOverrides = map[string]PluginLocaleOverride{
|
||||
opts.ForPlugin: {
|
||||
ManifestFile: manRel,
|
||||
MessagesFile: msgRel,
|
||||
},
|
||||
}
|
||||
} else {
|
||||
locDir := filepath.Join(outDir, "locales")
|
||||
if err := os.MkdirAll(locDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
lc.Files = make(map[string]string, len(canonicalLocaleDomains))
|
||||
for _, dom := range canonicalLocaleDomains {
|
||||
raw, err := locales.FS.ReadFile(sourceLocale + "/" + dom.FileName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read embedded template %s/%s: %w", sourceLocale, dom.FileName, err)
|
||||
}
|
||||
rel := "locales/" + dom.FileName
|
||||
if err := os.WriteFile(filepath.Join(outDir, filepath.FromSlash(rel)), raw, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
lc.Files[dom.Key] = rel
|
||||
}
|
||||
}
|
||||
|
||||
man := Manifest{
|
||||
Schema: ManifestSchemaVersion,
|
||||
ID: pluginID,
|
||||
Version: "0.1.0",
|
||||
Name: LocalizedText{
|
||||
ZhCN: string(canon) + " 语言包",
|
||||
EnUS: string(canon) + " Language Pack",
|
||||
Extra: map[string]string{string(canon): lc.Label},
|
||||
},
|
||||
Description: LocalizedText{
|
||||
ZhCN: fmt.Sprintf("为 Reims-Go 提供 %s 界面与命令行本地化支持", lc.Label),
|
||||
EnUS: fmt.Sprintf("Provides %s UI and CLI localization for Reims-Go", lc.Label),
|
||||
},
|
||||
License: "Apache-2.0",
|
||||
Engines: Engines{
|
||||
PluginAPI: "^1.0.0",
|
||||
},
|
||||
Contributes: Contributes{
|
||||
Locales: []LocaleContribution{lc},
|
||||
},
|
||||
}
|
||||
return writeIndentedJSON(filepath.Join(outDir, "plugin.json"), man)
|
||||
}
|
||||
|
||||
func defaultNativeLocaleLabel(tag string) string {
|
||||
switch tag {
|
||||
case "zh-CN":
|
||||
return "简体中文"
|
||||
case "zh-TW":
|
||||
return "繁體中文(台灣)"
|
||||
case "zh-HK":
|
||||
return "繁體中文(香港)"
|
||||
case "en-US":
|
||||
return "English (US)"
|
||||
case "ja-JP":
|
||||
return "日本語"
|
||||
case "ko-KR":
|
||||
return "한국어"
|
||||
case "de-DE":
|
||||
return "Deutsch"
|
||||
case "fr-FR":
|
||||
return "Français"
|
||||
case "es-ES":
|
||||
return "Español"
|
||||
case "ru-RU":
|
||||
return "Русский"
|
||||
default:
|
||||
return tag
|
||||
}
|
||||
}
|
||||
|
||||
func writeIndentedJSON(dest string, v any) error {
|
||||
var buf bytes.Buffer
|
||||
enc := json.NewEncoder(&buf)
|
||||
enc.SetEscapeHTML(false)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(v); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(dest, buf.Bytes(), 0o644)
|
||||
}
|
||||
|
||||
type refCatalogEntry struct {
|
||||
Domain string
|
||||
Vars []string
|
||||
}
|
||||
|
||||
func loadEmbeddedReferenceCatalogs() (map[string]map[string]refCatalogEntry, map[string]refCatalogEntry, error) {
|
||||
byDomain := make(map[string]map[string]refCatalogEntry, len(canonicalLocaleDomains))
|
||||
all := make(map[string]refCatalogEntry, 1200)
|
||||
for _, dom := range canonicalLocaleDomains {
|
||||
raw, err := locales.FS.ReadFile("en-US/" + dom.FileName)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
msgs, err := parseLocaleMessagesJSON(raw)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
dmap := make(map[string]refCatalogEntry, len(msgs))
|
||||
for k, tpl := range msgs {
|
||||
_, vars, _ := i18n.ParseICU(tpl)
|
||||
ent := refCatalogEntry{Domain: dom.Key, Vars: vars}
|
||||
dmap[k] = ent
|
||||
all[k] = ent
|
||||
}
|
||||
byDomain[dom.Key] = dmap
|
||||
}
|
||||
return byDomain, all, nil
|
||||
}
|
||||
|
||||
// CheckLocalePack performs static ICU AST validation, placeholder parity checks,
|
||||
// domain coverage calculation, stale-key detection, and regional terminology
|
||||
// linting (such as Taiwan/HK Traditional Chinese glossary checks) on dir.
|
||||
func CheckLocalePack(dir string) ([]LocaleCheckReport, []DoctorFinding, error) {
|
||||
raw, err := os.ReadFile(filepath.Join(dir, "plugin.json"))
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("read plugin.json: %w", err)
|
||||
}
|
||||
var m Manifest
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return nil, nil, fmt.Errorf("parse plugin.json: %w", err)
|
||||
}
|
||||
if err := ValidateManifest(m, "", false); err != nil {
|
||||
return nil, []DoctorFinding{{Severity: "error", Check: "manifest", Message: err.Error()}}, nil
|
||||
}
|
||||
|
||||
refByDomain, refAll, err := loadEmbeddedReferenceCatalogs()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var reports []LocaleCheckReport
|
||||
var allFindings []DoctorFinding
|
||||
|
||||
for _, lc := range m.Contributes.Locales {
|
||||
rep := LocaleCheckReport{
|
||||
PluginID: m.ID,
|
||||
Locale: lc.Locale,
|
||||
}
|
||||
addFinding := func(sev, check, msg string) {
|
||||
f := DoctorFinding{Severity: sev, Check: check, Message: msg}
|
||||
rep.Findings = append(rep.Findings, f)
|
||||
allFindings = append(allFindings, f)
|
||||
switch sev {
|
||||
case "error":
|
||||
rep.Errors++
|
||||
case "warn":
|
||||
rep.Warnings++
|
||||
}
|
||||
}
|
||||
|
||||
if err := ValidateLocaleContribution(lc, dir); err != nil {
|
||||
addFinding("error", "locale", err.Error())
|
||||
reports = append(reports, rep)
|
||||
continue
|
||||
}
|
||||
|
||||
canon, _ := i18n.ParseLocale(lc.Locale)
|
||||
merged := make(map[string]string)
|
||||
collectMap := func(src map[string]string, sourceLabel string) {
|
||||
keys := make([]string, 0, len(src))
|
||||
for k := range src {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
v := src[k]
|
||||
merged[k] = v
|
||||
_, gotVars, pErr := i18n.ParseICU(v)
|
||||
if pErr != nil {
|
||||
addFinding("error", "icu-syntax", fmt.Sprintf("[%s] %s key %q: %v", canon, sourceLabel, k, pErr))
|
||||
continue
|
||||
}
|
||||
if ref, exists := refAll[k]; exists {
|
||||
if !reflect.DeepEqual(gotVars, ref.Vars) {
|
||||
addFinding("error", "icu-params", fmt.Sprintf("[%s] %s key %q placeholder mismatch: got %v, expected %v", canon, sourceLabel, k, gotVars, ref.Vars))
|
||||
}
|
||||
}
|
||||
for _, hint := range lintRegionalTerminology(canon, k, v) {
|
||||
addFinding("warn", "l10n-regional", fmt.Sprintf("[%s] %s key %q: %s", canon, sourceLabel, k, hint))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if strings.TrimSpace(lc.File) != "" {
|
||||
if loaded, err := loadLocaleJSONFile(dir, lc.File); err == nil {
|
||||
collectMap(loaded, lc.File)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(lc.BackendFile) != "" {
|
||||
if loaded, err := loadLocaleJSONFile(dir, lc.BackendFile); err == nil {
|
||||
collectMap(loaded, lc.BackendFile)
|
||||
}
|
||||
}
|
||||
for _, dom := range canonicalLocaleDomains {
|
||||
rel := strings.TrimSpace(lc.Files[dom.Key])
|
||||
if rel == "" && dom.Key == "macosGlossary" {
|
||||
rel = strings.TrimSpace(lc.Files["macos-glossary"])
|
||||
}
|
||||
if rel != "" {
|
||||
if loaded, err := loadLocaleJSONFile(dir, rel); err == nil {
|
||||
collectMap(loaded, rel)
|
||||
}
|
||||
}
|
||||
}
|
||||
collectMap(lc.Messages, "messages")
|
||||
collectMap(lc.Backend, "backend")
|
||||
|
||||
// Check cross-plugin override terminology as well.
|
||||
for targetID, ov := range lc.PluginOverrides {
|
||||
if strings.TrimSpace(ov.MessagesFile) != "" {
|
||||
if loaded, err := loadLocaleJSONFile(dir, ov.MessagesFile); err == nil {
|
||||
for k, v := range loaded {
|
||||
for _, hint := range lintRegionalTerminology(canon, k, v) {
|
||||
addFinding("warn", "l10n-regional", fmt.Sprintf("[%s] override %s key %q: %s", canon, targetID, k, hint))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for k, v := range ov.Messages {
|
||||
for _, hint := range lintRegionalTerminology(canon, k, v) {
|
||||
addFinding("warn", "l10n-regional", fmt.Sprintf("[%s] override %s key %q: %s", canon, targetID, k, hint))
|
||||
}
|
||||
}
|
||||
if ov.Manifest != nil {
|
||||
for _, hint := range lintRegionalTerminology(canon, "manifest.name", ov.Manifest.Name) {
|
||||
addFinding("warn", "l10n-regional", fmt.Sprintf("[%s] override %s manifest.name: %s", canon, targetID, hint))
|
||||
}
|
||||
for _, hint := range lintRegionalTerminology(canon, "manifest.description", ov.Manifest.Description) {
|
||||
addFinding("warn", "l10n-regional", fmt.Sprintf("[%s] override %s manifest.description: %s", canon, targetID, hint))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Compute domain-by-domain coverage when host keys are present or files are declared.
|
||||
hasHostKeys := len(merged) > 0 || len(lc.Files) > 0 || lc.File != "" || lc.BackendFile != ""
|
||||
if hasHostKeys {
|
||||
for _, dom := range canonicalLocaleDomains {
|
||||
dref := refByDomain[dom.Key]
|
||||
total := len(dref)
|
||||
translated := 0
|
||||
for k := range dref {
|
||||
if strings.TrimSpace(merged[k]) != "" {
|
||||
translated++
|
||||
}
|
||||
}
|
||||
pct := 0.0
|
||||
if total > 0 {
|
||||
pct = float64(translated) * 100.0 / float64(total)
|
||||
}
|
||||
rep.Domains = append(rep.Domains, DomainCoverage{
|
||||
Domain: dom.Key,
|
||||
Translated: translated,
|
||||
Total: total,
|
||||
Percent: pct,
|
||||
})
|
||||
rep.TotalTranslated += translated
|
||||
rep.TotalReference += total
|
||||
}
|
||||
if rep.TotalReference > 0 {
|
||||
rep.TotalPercent = float64(rep.TotalTranslated) * 100.0 / float64(rep.TotalReference)
|
||||
}
|
||||
|
||||
for k := range merged {
|
||||
if _, ok := refAll[k]; !ok {
|
||||
rep.UnknownKeys = append(rep.UnknownKeys, k)
|
||||
}
|
||||
}
|
||||
sort.Strings(rep.UnknownKeys)
|
||||
if len(rep.UnknownKeys) > 0 {
|
||||
sample := rep.UnknownKeys
|
||||
if len(sample) > 5 {
|
||||
sample = sample[:5]
|
||||
}
|
||||
addFinding("warn", "locale-stale", fmt.Sprintf("[%s] %d unknown/stale host key(s) (e.g. %s)", canon, len(rep.UnknownKeys), strings.Join(sample, ", ")))
|
||||
}
|
||||
addFinding("ok", "locale-coverage", fmt.Sprintf("[%s] coverage %d/%d (%.1f%%)", canon, rep.TotalTranslated, rep.TotalReference, rep.TotalPercent))
|
||||
}
|
||||
|
||||
reports = append(reports, rep)
|
||||
}
|
||||
|
||||
return reports, allFindings, nil
|
||||
}
|
||||
|
||||
type regionalLintRule struct {
|
||||
Bad string
|
||||
Suggestion string
|
||||
}
|
||||
|
||||
var zhHantLintRules = []regionalLintRule{
|
||||
{Bad: "默认", Suggestion: "use Traditional regional term 「預設」 instead of 「默认」"},
|
||||
{Bad: "默認", Suggestion: "use Traditional regional term 「預設」 instead of Mainland literal 「默認」"},
|
||||
{Bad: "内存", Suggestion: "use Traditional regional term 「記憶體」 instead of 「内存」"},
|
||||
{Bad: "內存", Suggestion: "use Traditional regional term 「記憶體」 instead of Mainland literal 「內存」"},
|
||||
{Bad: "磁盘", Suggestion: "use Traditional regional term 「磁碟」 instead of 「磁盘」"},
|
||||
{Bad: "磁盤", Suggestion: "use Traditional regional term 「磁碟」 instead of Mainland literal 「磁盤」"},
|
||||
{Bad: "抹掉", Suggestion: "use Apple Traditional macOS term 「清除」 instead of 「抹掉」"},
|
||||
{Bad: "宗卷", Suggestion: "use Apple Traditional macOS term 「卷宗」 instead of 「宗卷」"},
|
||||
{Bad: "剪贴板", Suggestion: "use Traditional regional term 「剪貼簿」 instead of 「剪贴板」"},
|
||||
{Bad: "剪貼板", Suggestion: "use Traditional regional term 「剪貼簿」 instead of Mainland literal 「剪貼板」"},
|
||||
{Bad: "鼠标", Suggestion: "use Traditional regional term 「滑鼠」 instead of 「鼠标」"},
|
||||
{Bad: "鼠標", Suggestion: "use Traditional regional term 「滑鼠」 instead of Mainland literal 「鼠標」"},
|
||||
}
|
||||
|
||||
func lintRegionalTerminology(canon i18n.Locale, _ string, val string) []string {
|
||||
if val == "" {
|
||||
return nil
|
||||
}
|
||||
var hints []string
|
||||
switch canon {
|
||||
case "zh-TW", "zh-HK":
|
||||
for _, rule := range zhHantLintRules {
|
||||
if strings.Contains(val, rule.Bad) {
|
||||
hints = append(hints, rule.Suggestion)
|
||||
}
|
||||
}
|
||||
if strings.ContainsAny(val, "“”") {
|
||||
hints = append(hints, "prefer CJK corner brackets 「…」 over curly quotes “…” in Traditional Chinese UI")
|
||||
}
|
||||
}
|
||||
return hints
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
func TestOfficialReferenceLanguagePacks(t *testing.T) {
|
||||
for _, rel := range []string{
|
||||
filepath.Join("testdata", "official.lang.zh-tw"),
|
||||
filepath.Join("testdata", "official.lang.ja-jp"),
|
||||
} {
|
||||
reports, findings, err := CheckLocalePack(rel)
|
||||
if err != nil {
|
||||
t.Fatalf("CheckLocalePack(%s): %v", rel, err)
|
||||
}
|
||||
if len(reports) != 1 {
|
||||
t.Fatalf("CheckLocalePack(%s): expected 1 report, got %d", rel, len(reports))
|
||||
}
|
||||
for _, f := range findings {
|
||||
if f.Severity == "error" || f.Severity == "warn" {
|
||||
t.Fatalf("CheckLocalePack(%s) unexpected %s (%s): %s", rel, f.Severity, f.Check, f.Message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// End-to-end Manager test: link and enable both official reference packs.
|
||||
dataRoot := t.TempDir()
|
||||
mgr, err := NewManager(ManagerOptions{DataRoot: dataRoot, HostVersion: "0.2.8"})
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager: %v", err)
|
||||
}
|
||||
defer mgr.Close()
|
||||
|
||||
twAbs, err := filepath.Abs(filepath.Join("testdata", "official.lang.zh-tw"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
jaAbs, err := filepath.Abs(filepath.Join("testdata", "official.lang.ja-jp"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := mgr.LinkDev(context.Background(), twAbs); err != nil {
|
||||
t.Fatalf("LinkDev zh-tw: %v", err)
|
||||
}
|
||||
if err := mgr.Enable(context.Background(), "official.lang.zh-tw", false); err != nil {
|
||||
t.Fatalf("Enable zh-tw: %v", err)
|
||||
}
|
||||
if _, err := mgr.LinkDev(context.Background(), jaAbs); err != nil {
|
||||
t.Fatalf("LinkDev ja-jp: %v", err)
|
||||
}
|
||||
if err := mgr.Enable(context.Background(), "official.lang.ja-jp", false); err != nil {
|
||||
t.Fatalf("Enable ja-jp: %v", err)
|
||||
}
|
||||
|
||||
uiPacks, backendPacks := mgr.ResolvedLocalePacks()
|
||||
i18n.SetPluginCatalogs(backendPacks)
|
||||
defer i18n.SetPluginCatalogs(nil)
|
||||
|
||||
if len(uiPacks) != 2 {
|
||||
t.Fatalf("expected 2 UI locale packs, got %d", len(uiPacks))
|
||||
}
|
||||
|
||||
// 1. Verify zh-HK -> zh-TW -> zh-CN -> en-US multi-hop fallback!
|
||||
if got := i18n.T(i18n.Locale("zh-HK"), "validate.invalid_memory"); got != "分配記憶體不得小於 2G(例如 8G、16G)" {
|
||||
t.Fatalf("zh-HK -> zh-TW hop failed: got %q", got)
|
||||
}
|
||||
// Key not overridden in zh-TW should fall back to zh-CN (NOT en-US!).
|
||||
if got := i18n.T(i18n.Locale("zh-HK"), "doctor.os"); got != "操作系统" {
|
||||
t.Fatalf("zh-HK -> zh-TW -> zh-CN hop failed: got %q, want 操作系统", got)
|
||||
}
|
||||
|
||||
// 2. Verify ja-JP -> en-US fallback & FormatGuestTerm dual terminology!
|
||||
if got := i18n.T(i18n.Locale("ja-JP"), "guide.select_disk.btn.erase"); got != "ディスクユーティリティで消去する" {
|
||||
t.Fatalf("ja-JP native translation failed: got %q", got)
|
||||
}
|
||||
if got := i18n.T(i18n.Locale("ja-JP"), "doctor.os"); got != "Operating System" {
|
||||
t.Fatalf("ja-JP -> en-US fallback failed: got %q, want Operating System", got)
|
||||
}
|
||||
if dual := i18n.FormatGuestTerm(i18n.Locale("zh-TW"), "en-US:0", "macos.diskUtility", true); dual != "「磁碟工具程式 (Disk Utility)」" {
|
||||
t.Fatalf("FormatGuestTerm(zh-TW, en-US:0) = %q", dual)
|
||||
}
|
||||
if dual := i18n.FormatGuestTerm(i18n.Locale("ja-JP"), "en-US:0", "macos.diskUtility", true); dual != "「ディスクユーティリティ (Disk Utility)」" {
|
||||
t.Fatalf("FormatGuestTerm(ja-JP, en-US:0) = %q", dual)
|
||||
}
|
||||
if single := i18n.FormatGuestTerm(i18n.Locale("ja-JP"), "ja-JP:0", "macos.diskUtility", true); single != "「ディスクユーティリティ」" {
|
||||
t.Fatalf("FormatGuestTerm(ja-JP, ja-JP:0) = %q", single)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitAndCheckLocalePackCLIWorkflow(t *testing.T) {
|
||||
// 1. Scaffold full zh-TW host language pack -> should validate at 100% coverage with 0 errors.
|
||||
outTW := filepath.Join(t.TempDir(), "lang-zh-tw")
|
||||
if err := InitLocalePack(LocaleInitOptions{
|
||||
Locale: "zh-TW",
|
||||
OutDir: outTW,
|
||||
}); err != nil {
|
||||
t.Fatalf("InitLocalePack(zh-TW): %v", err)
|
||||
}
|
||||
reps, _, err := CheckLocalePack(outTW)
|
||||
if err != nil {
|
||||
t.Fatalf("CheckLocalePack(scaffolded zh-TW): %v", err)
|
||||
}
|
||||
if len(reps) != 1 || reps[0].Errors != 0 || reps[0].TotalPercent != 100.0 {
|
||||
t.Fatalf("expected 100%% coverage and 0 errors on freshly scaffolded pack, got %+v", reps)
|
||||
}
|
||||
|
||||
// Note: scaffolding zh-TW copies zh-CN source text as a starting template, so regional
|
||||
// lint should proactively flag Mainland terms like 默认/内存/磁盘 for the translator!
|
||||
if reps[0].Warnings == 0 {
|
||||
t.Fatal("expected regional terminology warnings on untranslated zh-CN -> zh-TW template")
|
||||
}
|
||||
|
||||
// 2. Scaffold cross-plugin override pack (--for acme.backup).
|
||||
outFor := filepath.Join(t.TempDir(), "lang-for-plugin")
|
||||
if err := InitLocalePack(LocaleInitOptions{
|
||||
Locale: "ko-KR",
|
||||
OutDir: outFor,
|
||||
ForPlugin: "acme.backup",
|
||||
}); err != nil {
|
||||
t.Fatalf("InitLocalePack(--for): %v", err)
|
||||
}
|
||||
repsFor, _, err := CheckLocalePack(outFor)
|
||||
if err != nil || len(repsFor) != 1 || repsFor[0].Errors != 0 {
|
||||
t.Fatalf("CheckLocalePack(--for) failed: err=%v reps=%+v", err, repsFor)
|
||||
}
|
||||
|
||||
// 3. Inject an ICU placeholder mismatch and a syntax error -> CheckLocalePack must report errors.
|
||||
badDir := filepath.Join(t.TempDir(), "bad-pack")
|
||||
if err := os.MkdirAll(filepath.Join(badDir, "locales"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(badDir, "locales", "core.json"), []byte(`{
|
||||
"footerDiskValue": "{wrongVar} GB free",
|
||||
"staleKeyNotInHost": "hello"
|
||||
}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(badDir, "plugin.json"), []byte(`{
|
||||
"schema": 1,
|
||||
"id": "test.lang.de",
|
||||
"version": "0.1.0",
|
||||
"name": "Deutsch",
|
||||
"contributes": {
|
||||
"locales": [{"locale": "de-DE", "files": {"core": "locales/core.json"}}]
|
||||
}
|
||||
}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
badReps, badFindings, err := CheckLocalePack(badDir)
|
||||
if err != nil {
|
||||
t.Fatalf("CheckLocalePack(badDir): %v", err)
|
||||
}
|
||||
if len(badReps) != 1 || badReps[0].Errors == 0 || len(badReps[0].UnknownKeys) != 1 {
|
||||
t.Fatalf("expected placeholder mismatch error and 1 unknown key, got %+v", badReps)
|
||||
}
|
||||
hasParamErr := false
|
||||
for _, f := range badFindings {
|
||||
if f.Check == "icu-params" && strings.Contains(f.Message, "footerDiskValue") {
|
||||
hasParamErr = true
|
||||
}
|
||||
}
|
||||
if !hasParamErr {
|
||||
t.Fatalf("expected icu-params finding for footerDiskValue, got %+v", badFindings)
|
||||
}
|
||||
}
|
||||
+783
-9
@@ -27,6 +27,7 @@ type ManagerOptions struct {
|
||||
Keyring []SigningKey
|
||||
RedactFn func(string) string
|
||||
Logger func(source, line string)
|
||||
LocaleFn func() i18n.Locale
|
||||
SidecarDriverFactory SidecarDriverFactory
|
||||
OnSettingsChanged func(pluginID, vmName string)
|
||||
}
|
||||
@@ -61,6 +62,7 @@ type Manager struct {
|
||||
crashDetected bool
|
||||
installDirs map[string]string // pluginID -> dir (for AssetServer)
|
||||
supervisors map[string]*SidecarSupervisor
|
||||
l10nCache map[string]map[string]string
|
||||
}
|
||||
|
||||
// NewManager initializes the Plugin Manager for DataRoot. If state.json is
|
||||
@@ -68,6 +70,9 @@ type Manager struct {
|
||||
func NewManager(opts ManagerOptions) (*Manager, error) {
|
||||
layout := NewPluginsLayout(opts.DataRoot)
|
||||
reg := NewRegistry(opts.Logger)
|
||||
if opts.LocaleFn != nil {
|
||||
reg.SetLocaleProvider(opts.LocaleFn)
|
||||
}
|
||||
broker := NewBroker(layout, reg, opts.RedactFn)
|
||||
|
||||
m := &Manager{
|
||||
@@ -80,7 +85,13 @@ func NewManager(opts ManagerOptions) (*Manager, error) {
|
||||
crashDetected: DidLastStartupCrash(layout.Root),
|
||||
installDirs: make(map[string]string),
|
||||
supervisors: make(map[string]*SidecarSupervisor),
|
||||
l10nCache: make(map[string]map[string]string),
|
||||
}
|
||||
reg.OnChange(func() {
|
||||
m.mu.Lock()
|
||||
clear(m.l10nCache)
|
||||
m.mu.Unlock()
|
||||
})
|
||||
m.assets = NewAssetServer(func(pluginID string) (string, bool) {
|
||||
m.mu.RLock()
|
||||
dir, ok := m.installDirs[pluginID]
|
||||
@@ -229,6 +240,9 @@ func (m *Manager) registerExternalDir(dir string, rec *PluginRecord, safeMode bo
|
||||
if err := ValidateManifest(man, m.opts.HostVersion, false); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateDiskContributions(man, dir); err != nil {
|
||||
return err
|
||||
}
|
||||
if rec.ID != "" && man.ID != rec.ID {
|
||||
return fmt.Errorf("manifest plugin id %q does not match state record %q", man.ID, rec.ID)
|
||||
}
|
||||
@@ -320,6 +334,15 @@ func (m *Manager) buildSidecarActivator(man Manifest, exePath string, blockingAl
|
||||
Broker: m.broker,
|
||||
Registry: m.registry,
|
||||
IdleTimeout: 5 * time.Minute,
|
||||
LocaleProvider: func() (string, []string, map[string]string) {
|
||||
loc := m.CurrentLocale()
|
||||
chain := i18n.FallbackChain(loc)
|
||||
strChain := make([]string, len(chain))
|
||||
for i, c := range chain {
|
||||
strChain[i] = string(c)
|
||||
}
|
||||
return string(loc), strChain, m.PluginL10nBundle(pid, loc)
|
||||
},
|
||||
})
|
||||
m.mu.Lock()
|
||||
m.supervisors[pid] = sup
|
||||
@@ -504,6 +527,9 @@ func (m *Manager) LinkDev(ctx context.Context, dir string) (*PluginInfo, error)
|
||||
if err := ValidateManifest(man, m.opts.HostVersion, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validateDiskContributions(man, absDir); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
if m.state == nil {
|
||||
@@ -999,15 +1025,13 @@ func (m *Manager) ActiveThemePayload() ActiveThemePayload {
|
||||
}
|
||||
|
||||
// ResolvedLocalePacks loads and merges all active plugin locale contributions
|
||||
// into frontend UI packs and backend/CLI catalogs. Returns nil in safe mode.
|
||||
// and per-plugin l10n bundles into frontend UI packs and backend/CLI catalogs.
|
||||
// Returns nil in safe mode.
|
||||
func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i18n.PluginCatalog) {
|
||||
if m.safeMode {
|
||||
return nil, nil
|
||||
}
|
||||
contribs := m.registry.Locales()
|
||||
if len(contribs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
m.mu.RLock()
|
||||
dirs := make(map[string]string, len(m.installDirs))
|
||||
@@ -1023,11 +1047,7 @@ func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i
|
||||
}
|
||||
byLocale := make(map[string]*mergedPack)
|
||||
|
||||
for _, lc := range contribs {
|
||||
canon, ok := i18n.ParseLocale(lc.Locale)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ensurePack := func(canon i18n.Locale) *mergedPack {
|
||||
key := string(canon)
|
||||
mp := byLocale[key]
|
||||
if mp == nil {
|
||||
@@ -1042,6 +1062,76 @@ func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i
|
||||
}
|
||||
byLocale[key] = mp
|
||||
}
|
||||
return mp
|
||||
}
|
||||
|
||||
setPluginMsg := func(mp *mergedPack, targetPID, k, v string) {
|
||||
if targetPID == "" || k == "" || v == "" {
|
||||
return
|
||||
}
|
||||
if mp.pack.PluginMessages == nil {
|
||||
mp.pack.PluginMessages = make(map[string]map[string]string)
|
||||
}
|
||||
pm := mp.pack.PluginMessages[targetPID]
|
||||
if pm == nil {
|
||||
pm = make(map[string]string)
|
||||
mp.pack.PluginMessages[targetPID] = pm
|
||||
}
|
||||
pm[k] = v
|
||||
}
|
||||
|
||||
// 1. Collect private `<l10n>/<locale>.json` bundles from active functional plugins (underlay).
|
||||
for _, info := range m.registry.List() {
|
||||
if info.State != StateActive {
|
||||
continue
|
||||
}
|
||||
man, ok := m.registry.ManifestOf(info.ID)
|
||||
if !ok || strings.TrimSpace(man.L10n) == "" {
|
||||
continue
|
||||
}
|
||||
selfDir := dirs[info.ID]
|
||||
if selfDir == "" {
|
||||
continue
|
||||
}
|
||||
l10nClean := strings.Trim(strings.TrimSpace(man.L10n), "/")
|
||||
fullL10n, err := safeJoin(selfDir, l10nClean)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
entries, err := os.ReadDir(fullL10n)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, ent := range entries {
|
||||
if ent.IsDir() || !strings.HasSuffix(strings.ToLower(ent.Name()), ".json") {
|
||||
continue
|
||||
}
|
||||
tagRaw := strings.TrimSuffix(ent.Name(), filepath.Ext(ent.Name()))
|
||||
canon, ok := i18n.ParseLocale(tagRaw)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
loaded, err := loadLocaleJSONFile(selfDir, l10nClean+"/"+ent.Name())
|
||||
if err != nil || len(loaded) == 0 {
|
||||
continue
|
||||
}
|
||||
mp := ensurePack(canon)
|
||||
for k, v := range loaded {
|
||||
setPluginMsg(mp, info.ID, k, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Layer active Language Pack contributions (sorted deterministically by Priority -> TrustRank -> PluginID).
|
||||
uiDomains := []string{"core", "vm", "wizard", "settings", "plugins", "macosGlossary", "macos-glossary"}
|
||||
backendDomains := []string{"native", "macosGlossary", "macos-glossary", "core"}
|
||||
|
||||
for _, lc := range contribs {
|
||||
canon, ok := i18n.ParseLocale(lc.Locale)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
mp := ensurePack(canon)
|
||||
if lbl := strings.TrimSpace(lc.Label); lbl != "" {
|
||||
mp.pack.Label = lbl
|
||||
}
|
||||
@@ -1060,6 +1150,30 @@ func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i
|
||||
}
|
||||
}
|
||||
}
|
||||
if installDir != "" && len(lc.Files) > 0 {
|
||||
for _, dom := range uiDomains {
|
||||
if rel := strings.TrimSpace(lc.Files[dom]); rel != "" {
|
||||
if loaded, err := loadLocaleJSONFile(installDir, rel); err == nil {
|
||||
for k, v := range loaded {
|
||||
if k != "" && v != "" {
|
||||
mp.pack.Messages[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, dom := range backendDomains {
|
||||
if rel := strings.TrimSpace(lc.Files[dom]); rel != "" {
|
||||
if loaded, err := loadLocaleJSONFile(installDir, rel); err == nil {
|
||||
for k, v := range loaded {
|
||||
if k != "" && v != "" {
|
||||
mp.backend[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for k, v := range lc.Messages {
|
||||
if k != "" && v != "" {
|
||||
mp.pack.Messages[k] = v
|
||||
@@ -1079,12 +1193,49 @@ func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i
|
||||
mp.backend[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve bundled WOFF2 WebFonts via AssetServer.
|
||||
if installDir != "" && m.assets != nil && len(lc.Fonts) > 0 {
|
||||
for _, f := range lc.Fonts {
|
||||
if strings.TrimSpace(f.Family) == "" || !strings.EqualFold(filepath.Ext(strings.TrimSpace(f.File)), ".woff2") {
|
||||
continue
|
||||
}
|
||||
if full, err := safeJoin(installDir, f.File); err == nil && verifyWOFF2Header(full) == nil {
|
||||
mp.pack.Fonts = append(mp.pack.Fonts, ResolvedLocaleFont{
|
||||
Family: f.Family,
|
||||
URL: m.assets.AssetURL(lc.PluginID, f.File),
|
||||
Weight: f.Weight,
|
||||
Style: f.Style,
|
||||
UnicodeRange: f.UnicodeRange,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Layer cross-plugin message overrides onto PluginMessages[targetID].
|
||||
for targetID, ov := range lc.PluginOverrides {
|
||||
if installDir != "" && strings.TrimSpace(ov.MessagesFile) != "" {
|
||||
if loaded, err := loadLocaleJSONFile(installDir, ov.MessagesFile); err == nil {
|
||||
for k, v := range loaded {
|
||||
setPluginMsg(mp, targetID, k, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
for k, v := range ov.Messages {
|
||||
setPluginMsg(mp, targetID, k, v)
|
||||
}
|
||||
}
|
||||
|
||||
if lc.PluginID != "" && !mp.seenPID[lc.PluginID] {
|
||||
mp.seenPID[lc.PluginID] = true
|
||||
mp.pack.PluginIDs = append(mp.pack.PluginIDs, lc.PluginID)
|
||||
}
|
||||
}
|
||||
|
||||
if len(byLocale) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
uiPacks := make([]ResolvedLocalePack, 0, len(byLocale))
|
||||
backendPacks := make(map[i18n.Locale]i18n.PluginCatalog, len(byLocale))
|
||||
for key, mp := range byLocale {
|
||||
@@ -1092,6 +1243,11 @@ func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i
|
||||
mp.pack.Label = defaultLocaleLabel(key)
|
||||
}
|
||||
sort.Strings(mp.pack.PluginIDs)
|
||||
if len(mp.pack.Messages) > 0 {
|
||||
mp.pack.HasUIMessages = true
|
||||
} else {
|
||||
mp.pack.Messages = nil
|
||||
}
|
||||
uiPacks = append(uiPacks, mp.pack)
|
||||
if len(mp.backend) > 0 {
|
||||
backendPacks[i18n.Locale(key)] = i18n.PluginCatalog{
|
||||
@@ -1103,9 +1259,426 @@ func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i
|
||||
sort.Slice(uiPacks, func(i, j int) bool {
|
||||
return uiPacks[i].Locale < uiPacks[j].Locale
|
||||
})
|
||||
if len(backendPacks) == 0 {
|
||||
backendPacks = nil
|
||||
}
|
||||
return uiPacks, backendPacks
|
||||
}
|
||||
|
||||
type resolvedManifestOverride struct {
|
||||
locale string
|
||||
ov PluginManifestOverride
|
||||
}
|
||||
|
||||
func (m *Manager) activeManifestOverrides() map[string][]resolvedManifestOverride {
|
||||
if m == nil || m.safeMode {
|
||||
return nil
|
||||
}
|
||||
contribs := m.registry.Locales()
|
||||
if len(contribs) == 0 {
|
||||
return nil
|
||||
}
|
||||
m.mu.RLock()
|
||||
dirs := make(map[string]string, len(m.installDirs))
|
||||
for k, v := range m.installDirs {
|
||||
dirs[k] = v
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
|
||||
var out map[string][]resolvedManifestOverride
|
||||
for _, lc := range contribs {
|
||||
if len(lc.PluginOverrides) == 0 {
|
||||
continue
|
||||
}
|
||||
canon, ok := i18n.ParseLocale(lc.Locale)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
packDir := dirs[lc.PluginID]
|
||||
for targetID, po := range lc.PluginOverrides {
|
||||
var merged PluginManifestOverride
|
||||
hasAny := false
|
||||
if packDir != "" && strings.TrimSpace(po.ManifestFile) != "" {
|
||||
if loaded, err := loadPluginManifestOverrideFile(packDir, po.ManifestFile); err == nil && loaded != nil {
|
||||
merged = *loaded
|
||||
hasAny = true
|
||||
}
|
||||
}
|
||||
if po.Manifest != nil {
|
||||
if po.Manifest.Name != "" {
|
||||
merged.Name = po.Manifest.Name
|
||||
}
|
||||
if po.Manifest.Description != "" {
|
||||
merged.Description = po.Manifest.Description
|
||||
}
|
||||
if len(po.Manifest.Fields) > 0 {
|
||||
if merged.Fields == nil {
|
||||
merged.Fields = make(map[string]string, len(po.Manifest.Fields))
|
||||
}
|
||||
for fk, fv := range po.Manifest.Fields {
|
||||
merged.Fields[fk] = fv
|
||||
}
|
||||
}
|
||||
hasAny = true
|
||||
}
|
||||
if !hasAny {
|
||||
continue
|
||||
}
|
||||
if out == nil {
|
||||
out = make(map[string][]resolvedManifestOverride)
|
||||
}
|
||||
out[targetID] = append(out[targetID], resolvedManifestOverride{
|
||||
locale: string(canon),
|
||||
ov: merged,
|
||||
})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneLocalizedText(lt LocalizedText) LocalizedText {
|
||||
out := LocalizedText{ZhCN: lt.ZhCN, EnUS: lt.EnUS}
|
||||
if len(lt.Extra) > 0 {
|
||||
out.Extra = make(map[string]string, len(lt.Extra))
|
||||
for k, v := range lt.Extra {
|
||||
out.Extra[k] = v
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneSettingsSchemaWithOverrides(sc *SettingsSchema, list []resolvedManifestOverride) *SettingsSchema {
|
||||
if sc == nil {
|
||||
return nil
|
||||
}
|
||||
cp := *sc
|
||||
cp.Title = cloneLocalizedText(sc.Title)
|
||||
if len(sc.Properties) > 0 {
|
||||
cp.Properties = make(map[string]SettingProperty, len(sc.Properties))
|
||||
for pk, prop := range sc.Properties {
|
||||
pcp := prop
|
||||
pcp.Title = cloneLocalizedText(prop.Title)
|
||||
pcp.Description = cloneLocalizedText(prop.Description)
|
||||
cp.Properties[pk] = pcp
|
||||
}
|
||||
}
|
||||
for _, r := range list {
|
||||
if v := r.ov.Fields["settings.title"]; v != "" {
|
||||
cp.Title.Set(r.locale, v)
|
||||
}
|
||||
for pk, prop := range cp.Properties {
|
||||
changed := false
|
||||
if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".title", pk+".title"); v != "" {
|
||||
prop.Title.Set(r.locale, v)
|
||||
changed = true
|
||||
}
|
||||
if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".description", pk+".description"); v != "" {
|
||||
prop.Description.Set(r.locale, v)
|
||||
changed = true
|
||||
}
|
||||
if changed {
|
||||
cp.Properties[pk] = prop
|
||||
}
|
||||
}
|
||||
}
|
||||
return &cp
|
||||
}
|
||||
|
||||
func firstNonEmptyField(fields map[string]string, keys ...string) string {
|
||||
if len(fields) == 0 {
|
||||
return ""
|
||||
}
|
||||
for _, k := range keys {
|
||||
if v := strings.TrimSpace(fields[k]); v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// LocalizePluginInfos returns a copy of infos enriched with any active Language Pack
|
||||
// `pluginOverrides` translations for plugin Name, Description, and SettingsSchema.
|
||||
func (m *Manager) LocalizePluginInfos(infos []PluginInfo) []PluginInfo {
|
||||
ovs := m.activeManifestOverrides()
|
||||
if len(ovs) == 0 || len(infos) == 0 {
|
||||
return infos
|
||||
}
|
||||
out := make([]PluginInfo, len(infos))
|
||||
for i, info := range infos {
|
||||
cp := info
|
||||
if list := ovs[info.ID]; len(list) > 0 {
|
||||
cp.Name = cloneLocalizedText(info.Name)
|
||||
cp.Description = cloneLocalizedText(info.Description)
|
||||
for _, r := range list {
|
||||
if r.ov.Name != "" {
|
||||
cp.Name.Set(r.locale, r.ov.Name)
|
||||
}
|
||||
if r.ov.Description != "" {
|
||||
cp.Description.Set(r.locale, r.ov.Description)
|
||||
}
|
||||
}
|
||||
cp.Settings = cloneSettingsSchemaWithOverrides(info.Settings, list)
|
||||
}
|
||||
out[i] = cp
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// LocalizeMenus applies active Language Pack manifest overrides onto MenuContribution titles.
|
||||
func (m *Manager) LocalizeMenus(items []MenuContribution) []MenuContribution {
|
||||
ovs := m.activeManifestOverrides()
|
||||
if len(ovs) == 0 || len(items) == 0 {
|
||||
return items
|
||||
}
|
||||
out := make([]MenuContribution, len(items))
|
||||
for i, it := range items {
|
||||
cp := it
|
||||
if list := ovs[it.PluginID]; len(list) > 0 {
|
||||
cp.Title = cloneLocalizedText(it.Title)
|
||||
for _, r := range list {
|
||||
if v := firstNonEmptyField(r.ov.Fields, "menu."+it.ID+".title", "command."+it.Command+".title"); v != "" {
|
||||
cp.Title.Set(r.locale, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
out[i] = cp
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// LocalizePanels applies active Language Pack manifest overrides onto PanelContribution titles.
|
||||
func (m *Manager) LocalizePanels(items []PanelContribution) []PanelContribution {
|
||||
ovs := m.activeManifestOverrides()
|
||||
if len(ovs) == 0 || len(items) == 0 {
|
||||
return items
|
||||
}
|
||||
out := make([]PanelContribution, len(items))
|
||||
for i, it := range items {
|
||||
cp := it
|
||||
if list := ovs[it.PluginID]; len(list) > 0 {
|
||||
cp.Title = cloneLocalizedText(it.Title)
|
||||
for _, r := range list {
|
||||
if v := firstNonEmptyField(r.ov.Fields, "panel."+it.ID+".title"); v != "" {
|
||||
cp.Title.Set(r.locale, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
out[i] = cp
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// LocalizeVMCards applies active Language Pack manifest overrides onto VMCardContribution labels.
|
||||
func (m *Manager) LocalizeVMCards(items []VMCardContribution) []VMCardContribution {
|
||||
ovs := m.activeManifestOverrides()
|
||||
if len(ovs) == 0 || len(items) == 0 {
|
||||
return items
|
||||
}
|
||||
out := make([]VMCardContribution, len(items))
|
||||
for i, it := range items {
|
||||
cp := it
|
||||
if list := ovs[it.PluginID]; len(list) > 0 {
|
||||
cp.Title = cloneLocalizedText(it.Title)
|
||||
cp.Value = cloneLocalizedText(it.Value)
|
||||
for _, r := range list {
|
||||
if v := firstNonEmptyField(r.ov.Fields, "vmCard."+it.ID+".title"); v != "" {
|
||||
cp.Title.Set(r.locale, v)
|
||||
}
|
||||
if v := firstNonEmptyField(r.ov.Fields, "vmCard."+it.ID+".value"); v != "" {
|
||||
cp.Value.Set(r.locale, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
out[i] = cp
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// LocalizeSettingsPages applies active Language Pack manifest overrides onto SettingsPageContribution titles.
|
||||
func (m *Manager) LocalizeSettingsPages(items []SettingsPageContribution) []SettingsPageContribution {
|
||||
ovs := m.activeManifestOverrides()
|
||||
if len(ovs) == 0 || len(items) == 0 {
|
||||
return items
|
||||
}
|
||||
out := make([]SettingsPageContribution, len(items))
|
||||
for i, it := range items {
|
||||
cp := it
|
||||
if list := ovs[it.PluginID]; len(list) > 0 {
|
||||
cp.Title = cloneLocalizedText(it.Title)
|
||||
for _, r := range list {
|
||||
if v := firstNonEmptyField(r.ov.Fields, "settingsPage."+it.ID+".title"); v != "" {
|
||||
cp.Title.Set(r.locale, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
out[i] = cp
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// LocalizeStatusItems applies active Language Pack manifest overrides onto StatusItemContribution labels.
|
||||
func (m *Manager) LocalizeStatusItems(items []StatusItemContribution) []StatusItemContribution {
|
||||
ovs := m.activeManifestOverrides()
|
||||
if len(ovs) == 0 || len(items) == 0 {
|
||||
return items
|
||||
}
|
||||
out := make([]StatusItemContribution, len(items))
|
||||
for i, it := range items {
|
||||
cp := it
|
||||
if list := ovs[it.PluginID]; len(list) > 0 {
|
||||
cp.Text = cloneLocalizedText(it.Text)
|
||||
cp.Tooltip = cloneLocalizedText(it.Tooltip)
|
||||
for _, r := range list {
|
||||
if v := firstNonEmptyField(r.ov.Fields, "statusItem."+it.ID+".text"); v != "" {
|
||||
cp.Text.Set(r.locale, v)
|
||||
}
|
||||
if v := firstNonEmptyField(r.ov.Fields, "statusItem."+it.ID+".tooltip"); v != "" {
|
||||
cp.Tooltip.Set(r.locale, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
out[i] = cp
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// CurrentLocale returns the active effective host locale for plugin operations.
|
||||
func (m *Manager) CurrentLocale() i18n.Locale {
|
||||
if m != nil && m.opts.LocaleFn != nil {
|
||||
return i18n.EffectiveLocale(m.opts.LocaleFn())
|
||||
}
|
||||
return i18n.Detect()
|
||||
}
|
||||
|
||||
// PluginL10nBundle builds the merged private localization dictionary for pluginID
|
||||
// in loc, layering the plugin's own `<l10n>/<tag>.json` files underneath any
|
||||
// active Language Pack `pluginOverrides[pluginID]` entries along FallbackChain(loc).
|
||||
func (m *Manager) PluginL10nBundle(pluginID string, loc i18n.Locale) map[string]string {
|
||||
if m == nil || pluginID == "" || m.safeMode {
|
||||
return nil
|
||||
}
|
||||
cacheKey := pluginID + "\x00" + string(loc)
|
||||
m.mu.RLock()
|
||||
if cached, ok := m.l10nCache[cacheKey]; ok {
|
||||
m.mu.RUnlock()
|
||||
if len(cached) == 0 {
|
||||
return nil
|
||||
}
|
||||
cp := make(map[string]string, len(cached))
|
||||
for k, v := range cached {
|
||||
cp[k] = v
|
||||
}
|
||||
return cp
|
||||
}
|
||||
selfDir := m.installDirs[pluginID]
|
||||
dirs := make(map[string]string, len(m.installDirs))
|
||||
for k, v := range m.installDirs {
|
||||
dirs[k] = v
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
|
||||
chain := i18n.FallbackChain(loc)
|
||||
out := make(map[string]string)
|
||||
|
||||
var l10nRel string
|
||||
if man, ok := m.registry.ManifestOf(pluginID); ok && man.L10n != "" {
|
||||
l10nRel = strings.TrimSpace(man.L10n)
|
||||
}
|
||||
|
||||
contribs := m.registry.Locales()
|
||||
// Walk fallback chain from least specific to most specific so higher-priority hops win.
|
||||
for idx := len(chain) - 1; idx >= 0; idx-- {
|
||||
step := string(chain[idx])
|
||||
if selfDir != "" && l10nRel != "" {
|
||||
for _, candidate := range []string{
|
||||
l10nRel + "/" + step + ".json",
|
||||
l10nRel + "/" + strings.ToLower(step) + ".json",
|
||||
} {
|
||||
if loaded, err := loadLocaleJSONFile(selfDir, candidate); err == nil {
|
||||
for k, v := range loaded {
|
||||
if k != "" && v != "" {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, lc := range contribs {
|
||||
if lc.Locale != step {
|
||||
continue
|
||||
}
|
||||
ov, ok := lc.PluginOverrides[pluginID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
packDir := dirs[lc.PluginID]
|
||||
if packDir != "" && strings.TrimSpace(ov.MessagesFile) != "" {
|
||||
if loaded, err := loadLocaleJSONFile(packDir, ov.MessagesFile); err == nil {
|
||||
for k, v := range loaded {
|
||||
if k != "" && v != "" {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for k, v := range ov.Messages {
|
||||
if k != "" && v != "" {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
m.mu.Lock()
|
||||
if len(m.l10nCache) >= 512 {
|
||||
clear(m.l10nCache)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
m.l10nCache[cacheKey] = nil
|
||||
m.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
stored := make(map[string]string, len(out))
|
||||
for k, v := range out {
|
||||
stored[k] = v
|
||||
}
|
||||
m.l10nCache[cacheKey] = stored
|
||||
m.mu.Unlock()
|
||||
return out
|
||||
}
|
||||
|
||||
// NotifyLocaleChanged broadcasts `plugin/localeChanged` to all currently running
|
||||
// L3 Sidecar processes without waking sleeping Sidecars.
|
||||
func (m *Manager) NotifyLocaleChanged(eff i18n.Locale) {
|
||||
if m == nil {
|
||||
return
|
||||
}
|
||||
m.mu.RLock()
|
||||
sups := make(map[string]*SidecarSupervisor, len(m.supervisors))
|
||||
for pid, s := range m.supervisors {
|
||||
sups[pid] = s
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
if len(sups) == 0 {
|
||||
return
|
||||
}
|
||||
chain := i18n.FallbackChain(eff)
|
||||
strChain := make([]string, len(chain))
|
||||
for i, c := range chain {
|
||||
strChain[i] = string(c)
|
||||
}
|
||||
for pid, sup := range sups {
|
||||
if sup.PID() == 0 {
|
||||
continue
|
||||
}
|
||||
sup.NotifyIfRunning("plugin/localeChanged", map[string]any{
|
||||
"locale": string(eff),
|
||||
"fallbackChain": strChain,
|
||||
"l10nBundle": m.PluginL10nBundle(pid, eff),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func defaultLocaleLabel(code string) string {
|
||||
switch code {
|
||||
case string(i18n.ZhCN):
|
||||
@@ -1117,6 +1690,207 @@ func defaultLocaleLabel(code string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func localeTrustRank(source SourceKind, trust TrustLevel) int {
|
||||
switch {
|
||||
case source == SourceBuiltin:
|
||||
return 10
|
||||
case source == SourceBundled:
|
||||
return 20
|
||||
case trust == TrustCommunity:
|
||||
return 30
|
||||
case trust == TrustVerified:
|
||||
return 40
|
||||
case trust == TrustOfficial:
|
||||
return 50
|
||||
case source == SourceDevLink || trust == TrustDev:
|
||||
return 60
|
||||
default:
|
||||
return 30
|
||||
}
|
||||
}
|
||||
|
||||
// LoadStaticLocalePacks performs an ultra-fast (< 2ms), side-effect-free scan of
|
||||
// enabled plugins under dataRoot to populate backend/CLI language packs without
|
||||
// starting any L3 Sidecars, AssetServer, or service dependency reconciliation.
|
||||
func LoadStaticLocalePacks(dataRoot string) map[i18n.Locale]i18n.PluginCatalog {
|
||||
if strings.TrimSpace(dataRoot) == "" {
|
||||
i18n.SetPluginCatalogs(nil)
|
||||
return nil
|
||||
}
|
||||
layout := NewPluginsLayout(dataRoot)
|
||||
if DidLastStartupCrash(layout.Root) {
|
||||
i18n.SetPluginCatalogs(nil)
|
||||
return nil
|
||||
}
|
||||
st, err := NewStateStore(layout.Root).Load()
|
||||
if err != nil || st == nil || len(st.Plugins) == 0 {
|
||||
i18n.SetPluginCatalogs(nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
type staticCandidate struct {
|
||||
id string
|
||||
dir string
|
||||
rec *PluginRecord
|
||||
rank int
|
||||
}
|
||||
var candidates []staticCandidate
|
||||
for id, rec := range st.Plugins {
|
||||
if rec == nil || !rec.Enabled || rec.Source == SourceBuiltin || rec.Source == SourceBundled {
|
||||
continue
|
||||
}
|
||||
var dir string
|
||||
if rec.Source == SourceDevLink {
|
||||
if !st.DeveloperMode || strings.TrimSpace(rec.DevPath) == "" {
|
||||
continue
|
||||
}
|
||||
dir = rec.DevPath
|
||||
} else {
|
||||
if rec.Version == "" || !reReverseDomainID.MatchString(id) {
|
||||
continue
|
||||
}
|
||||
if _, err := ParseSemVer(rec.Version); err != nil {
|
||||
continue
|
||||
}
|
||||
safeDir, err := safeJoin(layout.PkgsDir(), id+"/"+rec.Version)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
dir = safeDir
|
||||
}
|
||||
candidates = append(candidates, staticCandidate{
|
||||
id: id,
|
||||
dir: dir,
|
||||
rec: rec,
|
||||
rank: localeTrustRank(rec.Source, rec.Trust),
|
||||
})
|
||||
}
|
||||
sort.Slice(candidates, func(i, j int) bool {
|
||||
if candidates[i].rank != candidates[j].rank {
|
||||
return candidates[i].rank < candidates[j].rank
|
||||
}
|
||||
return candidates[i].id < candidates[j].id
|
||||
})
|
||||
|
||||
type staticLocaleItem struct {
|
||||
canon i18n.Locale
|
||||
rank int
|
||||
id string
|
||||
dir string
|
||||
lc LocaleContribution
|
||||
}
|
||||
var items []staticLocaleItem
|
||||
for _, c := range candidates {
|
||||
raw, err := os.ReadFile(filepath.Join(c.dir, "plugin.json"))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var man Manifest
|
||||
if json.Unmarshal(raw, &man) != nil || len(man.Contributes.Locales) == 0 {
|
||||
continue
|
||||
}
|
||||
if c.id != "" && man.ID != c.id {
|
||||
continue
|
||||
}
|
||||
trust := c.rec.Trust
|
||||
if trust == "" {
|
||||
trust = TrustCommunity
|
||||
}
|
||||
if c.rec.Source == SourceDevLink {
|
||||
trust = TrustDev
|
||||
}
|
||||
entryRel := man.Entry.Sidecar
|
||||
if entryRel == "" {
|
||||
entryRel = man.Entry.UIScript
|
||||
}
|
||||
if entryRel == "" {
|
||||
entryRel = man.Entry.Script
|
||||
}
|
||||
entryHash := ""
|
||||
if entryRel != "" {
|
||||
if full, err := safeJoin(c.dir, entryRel); err == nil {
|
||||
entryHash, _ = fileSHA256Hex(full)
|
||||
}
|
||||
}
|
||||
if computeNeedsApproval(man, trust, c.rec.ApprovedPermissions, c.rec.ApprovedEntryHash, entryHash) {
|
||||
continue
|
||||
}
|
||||
for _, lc := range man.Contributes.Locales {
|
||||
canon, ok := i18n.ParseLocale(lc.Locale)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
items = append(items, staticLocaleItem{
|
||||
canon: canon,
|
||||
rank: c.rank,
|
||||
id: c.id,
|
||||
dir: c.dir,
|
||||
lc: lc,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
if items[i].canon != items[j].canon {
|
||||
return items[i].canon < items[j].canon
|
||||
}
|
||||
if items[i].rank != items[j].rank {
|
||||
return items[i].rank < items[j].rank
|
||||
}
|
||||
if items[i].lc.Priority != items[j].lc.Priority {
|
||||
return items[i].lc.Priority < items[j].lc.Priority
|
||||
}
|
||||
return items[i].id < items[j].id
|
||||
})
|
||||
|
||||
packs := make(map[i18n.Locale]i18n.PluginCatalog)
|
||||
for _, it := range items {
|
||||
canon := it.canon
|
||||
lc := it.lc
|
||||
cur, exists := packs[canon]
|
||||
if !exists {
|
||||
cur = i18n.PluginCatalog{
|
||||
Fallback: i18n.DefaultFallback(canon),
|
||||
Messages: make(map[string]string),
|
||||
}
|
||||
}
|
||||
if fb, ok := i18n.ParseLocale(lc.Fallback); ok {
|
||||
cur.Fallback = fb
|
||||
}
|
||||
if strings.TrimSpace(lc.BackendFile) != "" {
|
||||
if loaded, err := loadLocaleJSONFile(it.dir, lc.BackendFile); err == nil {
|
||||
for k, v := range loaded {
|
||||
if k != "" && v != "" {
|
||||
cur.Messages[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, domKey := range []string{"native", "macosGlossary", "macos-glossary", "core"} {
|
||||
if rel := strings.TrimSpace(lc.Files[domKey]); rel != "" {
|
||||
if loaded, err := loadLocaleJSONFile(it.dir, rel); err == nil {
|
||||
for k, v := range loaded {
|
||||
if k != "" && v != "" {
|
||||
cur.Messages[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for k, v := range lc.Backend {
|
||||
if k != "" && v != "" {
|
||||
cur.Messages[k] = v
|
||||
}
|
||||
}
|
||||
hasHostContrib := len(cur.Messages) > 0 || strings.TrimSpace(lc.File) != "" || len(lc.Files) > 0 || len(lc.Messages) > 0
|
||||
if hasHostContrib {
|
||||
packs[canon] = cur
|
||||
}
|
||||
}
|
||||
i18n.SetPluginCatalogs(packs)
|
||||
return packs
|
||||
}
|
||||
|
||||
// ActiveVMNamesWithSetting scans saved VM settings for pluginID where key==true.
|
||||
func (m *Manager) ActiveVMNamesWithSetting(pluginID, key string) []string {
|
||||
m.mu.RLock()
|
||||
|
||||
+300
-19
@@ -236,6 +236,11 @@ func ValidateManifest(m Manifest, hostVersion string, isBuiltinOrBundled bool) e
|
||||
return err
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(m.L10n) != "" {
|
||||
if err := validatePluginL10nDir(m.L10n, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, lc := range m.Contributes.Locales {
|
||||
if err := ValidateLocaleContribution(lc, ""); err != nil {
|
||||
return err
|
||||
@@ -244,10 +249,74 @@ func ValidateManifest(m Manifest, hostVersion string, isBuiltinOrBundled bool) e
|
||||
return nil
|
||||
}
|
||||
|
||||
const maxLocaleFileBytes = 2 << 20 // 2 MiB
|
||||
const (
|
||||
maxLocaleFileBytes = 2 << 20 // 2 MiB per JSON catalog
|
||||
maxLocaleTotalFontBytes = 8 << 20 // 8 MiB cumulative WOFF2 fonts per locale contribution
|
||||
)
|
||||
|
||||
var allowedLocaleDomainKeys = map[string]bool{
|
||||
"core": true,
|
||||
"vm": true,
|
||||
"wizard": true,
|
||||
"settings": true,
|
||||
"plugins": true,
|
||||
"native": true,
|
||||
"macosGlossary": true,
|
||||
"macos-glossary": true,
|
||||
}
|
||||
|
||||
func validatePluginL10nDir(relDir, rootDir string) error {
|
||||
clean := strings.Trim(strings.TrimSpace(relDir), "/")
|
||||
if clean == "" {
|
||||
return errors.New("l10n directory cannot be empty")
|
||||
}
|
||||
if strings.ContainsAny(clean, "\"'\\;{}()\r\n\x00") || !reSafeAssetRel.MatchString(clean) || reSchemePrefix.MatchString(clean) {
|
||||
return fmt.Errorf("invalid l10n directory %q", relDir)
|
||||
}
|
||||
for _, seg := range strings.Split(clean, "/") {
|
||||
if seg == "" || seg == "." || seg == ".." {
|
||||
return fmt.Errorf("invalid l10n directory segment in %q", relDir)
|
||||
}
|
||||
}
|
||||
if rootDir != "" {
|
||||
full, err := safeJoin(rootDir, clean)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid l10n directory %q: %w", relDir, err)
|
||||
}
|
||||
entries, err := os.ReadDir(full)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("read l10n directory %q: %w", relDir, err)
|
||||
}
|
||||
for _, ent := range entries {
|
||||
if ent.IsDir() || !strings.HasSuffix(strings.ToLower(ent.Name()), ".json") {
|
||||
continue
|
||||
}
|
||||
msgs, err := loadLocaleJSONFile(rootDir, clean+"/"+ent.Name())
|
||||
if err != nil {
|
||||
return fmt.Errorf("l10n file %s/%s: %w", clean, ent.Name(), err)
|
||||
}
|
||||
if err := validateICUMap(msgs, clean+"/"+ent.Name()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateICUMap(msgs map[string]string, ctxLabel string) error {
|
||||
for k, v := range msgs {
|
||||
if _, _, err := i18n.ParseICU(v); err != nil {
|
||||
return fmt.Errorf("%s key %q has invalid ICU template: %w", ctxLabel, k, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateLocaleContribution checks a declarative locale pack contribution.
|
||||
// When rootDir is non-empty, referenced JSON files are also read and parsed.
|
||||
// When rootDir is non-empty, referenced JSON files and WOFF2 fonts are also read and verified.
|
||||
func ValidateLocaleContribution(lc LocaleContribution, rootDir string) error {
|
||||
if _, ok := i18n.ParseLocale(lc.Locale); !ok {
|
||||
return fmt.Errorf("invalid locale tag %q", lc.Locale)
|
||||
@@ -259,8 +328,8 @@ func ValidateLocaleContribution(lc LocaleContribution, rootDir string) error {
|
||||
}
|
||||
hasFile := strings.TrimSpace(lc.File) != ""
|
||||
hasBackendFile := strings.TrimSpace(lc.BackendFile) != ""
|
||||
if !hasFile && !hasBackendFile && len(lc.Messages) == 0 && len(lc.Backend) == 0 {
|
||||
return fmt.Errorf("locale %q must declare file, backendFile, messages, or backend", lc.Locale)
|
||||
if !hasFile && !hasBackendFile && len(lc.Files) == 0 && len(lc.Messages) == 0 && len(lc.Backend) == 0 && len(lc.PluginOverrides) == 0 && len(lc.Fonts) == 0 {
|
||||
return fmt.Errorf("locale %q must declare files, file, backendFile, messages, backend, fonts, or pluginOverrides", lc.Locale)
|
||||
}
|
||||
checkFile := func(rel, field string) error {
|
||||
if strings.TrimSpace(rel) == "" {
|
||||
@@ -273,9 +342,13 @@ func ValidateLocaleContribution(lc LocaleContribution, rootDir string) error {
|
||||
return fmt.Errorf("locale %q %s %q must be a .json file", lc.Locale, field, rel)
|
||||
}
|
||||
if rootDir != "" {
|
||||
if _, err := loadLocaleJSONFile(rootDir, rel); err != nil {
|
||||
msgs, err := loadLocaleJSONFile(rootDir, rel)
|
||||
if err != nil {
|
||||
return fmt.Errorf("locale %q invalid %s %q: %w", lc.Locale, field, rel, err)
|
||||
}
|
||||
if err := validateICUMap(msgs, fmt.Sprintf("locale %q %s (%s)", lc.Locale, field, rel)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -285,9 +358,126 @@ func ValidateLocaleContribution(lc LocaleContribution, rootDir string) error {
|
||||
if err := checkFile(lc.BackendFile, "backendFile"); err != nil {
|
||||
return err
|
||||
}
|
||||
for dom, rel := range lc.Files {
|
||||
if !allowedLocaleDomainKeys[dom] {
|
||||
return fmt.Errorf("locale %q unknown domain key %q in files", lc.Locale, dom)
|
||||
}
|
||||
if err := checkFile(rel, "files."+dom); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := validateICUMap(lc.Messages, fmt.Sprintf("locale %q messages", lc.Locale)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateICUMap(lc.Backend, fmt.Sprintf("locale %q backend", lc.Locale)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var totalFontBytes int64
|
||||
for _, f := range lc.Fonts {
|
||||
if !reSafeFontFamily.MatchString(strings.TrimSpace(f.Family)) || strings.Contains(strings.ToLower(f.Family), "</style") {
|
||||
return fmt.Errorf("locale %q invalid font family %q", lc.Locale, f.Family)
|
||||
}
|
||||
if !strings.EqualFold(path.Ext(strings.TrimSpace(f.File)), ".woff2") {
|
||||
return fmt.Errorf("locale %q font %q must be a .woff2 file", lc.Locale, f.File)
|
||||
}
|
||||
if err := validateSafeManifestAsset(f.File, rootDir); err != nil {
|
||||
return fmt.Errorf("locale %q font file %q: %w", lc.Locale, f.File, err)
|
||||
}
|
||||
if f.Weight != "" && !reFontWeight.MatchString(f.Weight) {
|
||||
return fmt.Errorf("locale %q invalid font weight %q", lc.Locale, f.Weight)
|
||||
}
|
||||
if f.Style != "" && !reFontStyle.MatchString(strings.TrimSpace(f.Style)) {
|
||||
return fmt.Errorf("locale %q invalid font style %q", lc.Locale, f.Style)
|
||||
}
|
||||
if f.UnicodeRange != "" && !reUnicodeRange.MatchString(f.UnicodeRange) {
|
||||
return fmt.Errorf("locale %q invalid font unicodeRange %q", lc.Locale, f.UnicodeRange)
|
||||
}
|
||||
if rootDir != "" {
|
||||
full, err := safeJoin(rootDir, f.File)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := os.Stat(full)
|
||||
if err != nil {
|
||||
return fmt.Errorf("locale %q font %q: %w", lc.Locale, f.File, err)
|
||||
}
|
||||
totalFontBytes += st.Size()
|
||||
if totalFontBytes > maxLocaleTotalFontBytes {
|
||||
return fmt.Errorf("locale %q bundled fonts exceed %d MiB limit", lc.Locale, maxLocaleTotalFontBytes>>20)
|
||||
}
|
||||
if err := verifyWOFF2Header(full); err != nil {
|
||||
return fmt.Errorf("locale %q font %q: %w", lc.Locale, f.File, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for targetID, ov := range lc.PluginOverrides {
|
||||
if !reReverseDomainID.MatchString(targetID) {
|
||||
return fmt.Errorf("locale %q pluginOverrides has invalid target plugin id %q", lc.Locale, targetID)
|
||||
}
|
||||
if err := checkFile(ov.MessagesFile, "pluginOverrides."+targetID+".messagesFile"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateICUMap(ov.Messages, fmt.Sprintf("locale %q pluginOverrides.%s.messages", lc.Locale, targetID)); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(ov.ManifestFile) != "" {
|
||||
if err := validateSafeManifestAsset(ov.ManifestFile, rootDir); err != nil {
|
||||
return fmt.Errorf("locale %q pluginOverrides.%s.manifestFile: %w", lc.Locale, targetID, err)
|
||||
}
|
||||
if !strings.EqualFold(path.Ext(strings.TrimSpace(ov.ManifestFile)), ".json") {
|
||||
return fmt.Errorf("locale %q pluginOverrides.%s.manifestFile %q must be a .json file", lc.Locale, targetID, ov.ManifestFile)
|
||||
}
|
||||
if rootDir != "" {
|
||||
if _, err := loadPluginManifestOverrideFile(rootDir, ov.ManifestFile); err != nil {
|
||||
return fmt.Errorf("locale %q pluginOverrides.%s.manifestFile %q: %w", lc.Locale, targetID, ov.ManifestFile, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func verifyWOFF2Header(fullPath string) error {
|
||||
fh, err := os.Open(fullPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fh.Close()
|
||||
var magic [4]byte
|
||||
if _, err := io.ReadFull(fh, magic[:]); err != nil {
|
||||
return errors.New("file too short to be a valid WOFF2 font")
|
||||
}
|
||||
if string(magic[:]) != "wOF2" {
|
||||
return errors.New("invalid WOFF2 magic header (expected wOF2)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadPluginManifestOverrideFile(rootDir, rel string) (*PluginManifestOverride, error) {
|
||||
full, err := safeJoin(rootDir, rel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st, err := os.Stat(full)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if st.IsDir() || st.Size() > maxLocaleFileBytes {
|
||||
return nil, errors.New("invalid manifest override file")
|
||||
}
|
||||
raw, err := os.ReadFile(full)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out PluginManifestOverride
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func loadLocaleJSONFile(rootDir, rel string) (map[string]string, error) {
|
||||
full, err := safeJoin(rootDir, rel)
|
||||
if err != nil {
|
||||
@@ -307,9 +497,32 @@ func loadLocaleJSONFile(rootDir, rel string) (map[string]string, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out map[string]string
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil, fmt.Errorf("must be a JSON object mapping string keys to string values: %w", err)
|
||||
return parseLocaleMessagesJSON(raw)
|
||||
}
|
||||
|
||||
func parseLocaleMessagesJSON(raw []byte) (map[string]string, error) {
|
||||
var entries map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &entries); err != nil {
|
||||
return nil, fmt.Errorf("must be a JSON object: %w", err)
|
||||
}
|
||||
out := make(map[string]string, len(entries))
|
||||
for k, v := range entries {
|
||||
if strings.HasPrefix(k, "$") {
|
||||
continue
|
||||
}
|
||||
var plain string
|
||||
if err := json.Unmarshal(v, &plain); err == nil {
|
||||
out[k] = plain
|
||||
continue
|
||||
}
|
||||
var structured struct {
|
||||
Message *string `json:"message"`
|
||||
}
|
||||
if err := json.Unmarshal(v, &structured); err == nil && structured.Message != nil {
|
||||
out[k] = *structured.Message
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("key %q must be a string or an object with a string \"message\" field", k)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -421,11 +634,8 @@ func InstallArchive(layout PluginsLayout, archivePath string, opts PackageInstal
|
||||
entryHash = h
|
||||
}
|
||||
|
||||
// Validate all theme fields (tokens, seeds, fonts, background, stylesheet & asset refs, B5).
|
||||
for _, th := range m.Contributes.Themes {
|
||||
if err := ValidateThemeContribution(th, stageDir); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validateDiskContributions(m, stageDir); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Atomic activation into pkgs/<id>/<version> with path-traversal guard (B3).
|
||||
@@ -532,11 +742,31 @@ func DoctorDirectory(dir string, hostVersion string, contract *UIContract) []Doc
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, lc := range m.Contributes.Locales {
|
||||
if err := ValidateLocaleContribution(lc, dir); err != nil {
|
||||
add("error", "locale", err.Error())
|
||||
if strings.TrimSpace(m.L10n) != "" {
|
||||
if err := validatePluginL10nDir(m.L10n, dir); err != nil {
|
||||
add("error", "l10n", err.Error())
|
||||
} else {
|
||||
add("ok", "locale", fmt.Sprintf("locale %s validated", lc.Locale))
|
||||
add("ok", "l10n", fmt.Sprintf("plugin l10n directory %q validated", m.L10n))
|
||||
}
|
||||
}
|
||||
if len(m.Contributes.Locales) > 0 {
|
||||
if _, locFindings, cErr := CheckLocalePack(dir); cErr == nil && len(locFindings) > 0 {
|
||||
for _, lf := range locFindings {
|
||||
out = append(out, lf)
|
||||
}
|
||||
for _, lc := range m.Contributes.Locales {
|
||||
if ValidateLocaleContribution(lc, dir) == nil {
|
||||
add("ok", "locale", fmt.Sprintf("locale %s validated", lc.Locale))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, lc := range m.Contributes.Locales {
|
||||
if err := ValidateLocaleContribution(lc, dir); err != nil {
|
||||
add("error", "locale", err.Error())
|
||||
} else {
|
||||
add("ok", "locale", fmt.Sprintf("locale %s validated", lc.Locale))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
@@ -746,24 +976,75 @@ func pathWithinRoot(root, candidate string) bool {
|
||||
return candidate == root || strings.HasPrefix(candidate, root+string(os.PathSeparator))
|
||||
}
|
||||
|
||||
func validateDiskContributions(m Manifest, rootDir string) error {
|
||||
for _, th := range m.Contributes.Themes {
|
||||
if err := ValidateThemeContribution(th, rootDir); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(m.L10n) != "" {
|
||||
if err := validatePluginL10nDir(m.L10n, rootDir); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, lc := range m.Contributes.Locales {
|
||||
if err := ValidateLocaleContribution(lc, rootDir); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeJoin(root, rel string) (string, error) {
|
||||
cleanRoot := filepath.Clean(root)
|
||||
joined := filepath.Clean(filepath.Join(cleanRoot, filepath.FromSlash(rel)))
|
||||
if !pathWithinRoot(cleanRoot, joined) {
|
||||
return "", fmt.Errorf("path traversal blocked: %q", rel)
|
||||
}
|
||||
// Guard against symlinks / NTFS junctions escaping rootDir.
|
||||
// Guard against symlinks / NTFS junctions escaping rootDir, including when
|
||||
// the leaf path does not exist yet (check nearest existing ancestor).
|
||||
evalRoot := cleanRoot
|
||||
if r, err := filepath.EvalSymlinks(cleanRoot); err == nil {
|
||||
evalRoot = filepath.Clean(r)
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate root path: %w", err)
|
||||
}
|
||||
if evalJoined, err := filepath.EvalSymlinks(joined); err == nil {
|
||||
|
||||
evalJoined, err := filepath.EvalSymlinks(joined)
|
||||
if err == nil {
|
||||
evalJoined = filepath.Clean(evalJoined)
|
||||
if !pathWithinRoot(evalRoot, evalJoined) {
|
||||
return "", fmt.Errorf("symlink traversal blocked: %q", rel)
|
||||
}
|
||||
return evalJoined, nil
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate path %q: %w", rel, err)
|
||||
}
|
||||
|
||||
// Walk upward to the nearest existing ancestor directory and verify it resolves within evalRoot.
|
||||
cur := joined
|
||||
var tail []string
|
||||
for cur != cleanRoot {
|
||||
parent := filepath.Dir(cur)
|
||||
if parent == cur {
|
||||
break
|
||||
}
|
||||
tail = append(tail, filepath.Base(cur))
|
||||
cur = parent
|
||||
if evalAnc, aErr := filepath.EvalSymlinks(cur); aErr == nil {
|
||||
evalAnc = filepath.Clean(evalAnc)
|
||||
if !pathWithinRoot(evalRoot, evalAnc) {
|
||||
return "", fmt.Errorf("symlink ancestor traversal blocked: %q", rel)
|
||||
}
|
||||
for i := len(tail) - 1; i >= 0; i-- {
|
||||
evalAnc = filepath.Join(evalAnc, tail[i])
|
||||
}
|
||||
return evalAnc, nil
|
||||
} else if !errors.Is(aErr, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("evaluate ancestor path %q: %w", rel, aErr)
|
||||
}
|
||||
}
|
||||
return joined, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -89,6 +89,7 @@ type Registry struct {
|
||||
inUseChecker InUseChecker
|
||||
onChange []func()
|
||||
logger func(source, line string)
|
||||
localeFn func() i18n.Locale
|
||||
|
||||
// Extension point tables (§4.2).
|
||||
themes map[string]ThemeContribution
|
||||
@@ -174,6 +175,23 @@ func (r *Registry) logf(source, format string, args ...any) {
|
||||
}
|
||||
}
|
||||
|
||||
// SetLocaleProvider configures how Registry resolves the active host locale.
|
||||
func (r *Registry) SetLocaleProvider(fn func() i18n.Locale) {
|
||||
r.mu.Lock()
|
||||
r.localeFn = fn
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
func (r *Registry) currentLocale() i18n.Locale {
|
||||
r.mu.RLock()
|
||||
fn := r.localeFn
|
||||
r.mu.RUnlock()
|
||||
if fn != nil {
|
||||
return i18n.EffectiveLocale(fn())
|
||||
}
|
||||
return i18n.Detect()
|
||||
}
|
||||
|
||||
// Register adds or updates a plugin definition. Call Reconcile to apply activation changes.
|
||||
func (r *Registry) Register(def PluginDef) error {
|
||||
if strings.TrimSpace(def.Manifest.ID) == "" {
|
||||
@@ -785,6 +803,9 @@ func (r *Registry) RegisterLocale(sc *Scope, lc LocaleContribution) {
|
||||
}
|
||||
lc.PluginID = sc.PluginID()
|
||||
r.mu.Lock()
|
||||
if ent := r.entries[lc.PluginID]; ent != nil {
|
||||
lc.TrustRank = localeTrustRank(ent.def.Source, ent.def.Trust)
|
||||
}
|
||||
r.locales[lc.Locale] = append(r.locales[lc.Locale], lc)
|
||||
r.mu.Unlock()
|
||||
sc.OnDispose(func() {
|
||||
@@ -817,11 +838,28 @@ func (r *Registry) Locales() []LocaleContribution {
|
||||
if out[i].Locale != out[j].Locale {
|
||||
return out[i].Locale < out[j].Locale
|
||||
}
|
||||
if out[i].TrustRank != out[j].TrustRank {
|
||||
return out[i].TrustRank < out[j].TrustRank
|
||||
}
|
||||
if out[i].Priority != out[j].Priority {
|
||||
return out[i].Priority < out[j].Priority
|
||||
}
|
||||
return out[i].PluginID < out[j].PluginID
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// ManifestOf returns the parsed Manifest of a registered plugin if present.
|
||||
func (r *Registry) ManifestOf(id string) (Manifest, bool) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
ent, ok := r.entries[id]
|
||||
if !ok || ent == nil {
|
||||
return Manifest{}, false
|
||||
}
|
||||
return ent.def.Manifest, true
|
||||
}
|
||||
|
||||
func (r *Registry) RegisterInputFilter(sc *Scope, flt InputFilterContribution) {
|
||||
if flt.Event == "" || flt.Transform == "" {
|
||||
return
|
||||
@@ -1256,7 +1294,7 @@ func (r *Registry) CollectDiagnostics(ctx context.Context, vmName string, redact
|
||||
}
|
||||
entry.PluginID = item.Contribution.PluginID
|
||||
if entry.Title == "" {
|
||||
entry.Title = item.Contribution.Title.Get("en-US")
|
||||
entry.Title = item.Contribution.Title.Get(string(r.currentLocale()))
|
||||
}
|
||||
entry.Text = redactFn(entry.Text)
|
||||
if len(entry.Data) > 0 {
|
||||
|
||||
@@ -20,7 +20,7 @@ type RuleAction struct {
|
||||
Key string `json:"key,omitempty"` // fragment key for append_args
|
||||
Tokens []string `json:"tokens,omitempty"` // QEMU arg tokens
|
||||
Env map[string]string `json:"env,omitempty"` // env overrides
|
||||
Message string `json:"message,omitempty"` // warning text
|
||||
Message LocalizedText `json:"message,omitempty"` // localized warning text (accepts string or {"zh-CN":..., "en-US":...})
|
||||
Action string `json:"action,omitempty"` // post_start kind
|
||||
Params map[string]any `json:"params,omitempty"`
|
||||
}
|
||||
@@ -110,7 +110,7 @@ func (r *Registry) registerRuleHooks(sc *Scope, pluginID string, rules []RuleHoo
|
||||
if !EvaluateRuleConditions(rl.Conditions, facts) {
|
||||
return nil, nil
|
||||
}
|
||||
return buildRuleStartIntent(pluginID, rl), nil
|
||||
return buildRuleStartIntent(pluginID, rl, string(r.currentLocale())), nil
|
||||
},
|
||||
})
|
||||
case EventHostPreflight:
|
||||
@@ -127,9 +127,12 @@ func (r *Registry) registerRuleHooks(sc *Scope, pluginID string, rules []RuleHoo
|
||||
return nil, nil
|
||||
}
|
||||
var res PreflightResult
|
||||
loc := string(r.currentLocale())
|
||||
for _, act := range rl.Actions {
|
||||
if act.Kind == "warn" && act.Message != "" {
|
||||
res.Warnings = append(res.Warnings, act.Message)
|
||||
if act.Kind == "warn" {
|
||||
if msg := act.Message.Get(loc); msg != "" {
|
||||
res.Warnings = append(res.Warnings, msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
@@ -154,7 +157,7 @@ func buildStartFacts(p BeforeStartPayload) map[string]any {
|
||||
return facts
|
||||
}
|
||||
|
||||
func buildRuleStartIntent(pluginID string, rule RuleHook) StartIntent {
|
||||
func buildRuleStartIntent(pluginID string, rule RuleHook, loc string) StartIntent {
|
||||
intent := StartIntent{PluginID: pluginID}
|
||||
for i, act := range rule.Actions {
|
||||
switch act.Kind {
|
||||
@@ -182,8 +185,8 @@ func buildRuleStartIntent(pluginID string, rule RuleHook) StartIntent {
|
||||
}
|
||||
}
|
||||
case "warn":
|
||||
if act.Message != "" {
|
||||
intent.Warnings = append(intent.Warnings, act.Message)
|
||||
if msg := act.Message.Get(loc); msg != "" {
|
||||
intent.Warnings = append(intent.Warnings, msg)
|
||||
}
|
||||
case "post_start":
|
||||
if act.Action != "" {
|
||||
|
||||
@@ -24,8 +24,9 @@ type SidecarOptions struct {
|
||||
Registry *Registry
|
||||
IdleTimeout time.Duration // 0 = no idle shutdown
|
||||
MemLimitBytes uintptr // optional Windows Job Object memory cap (L2)
|
||||
MaxRestarts int // circuit breaker threshold (default 3)
|
||||
MaxRestarts int // circuit breaker threshold (default 3)
|
||||
ExtraHandlers map[string]RPCRequestHandler
|
||||
LocaleProvider func() (string, []string, map[string]string) // returns (locale, fallbackChain, mergedBundle)
|
||||
}
|
||||
|
||||
type sidecarInstance struct {
|
||||
@@ -261,11 +262,24 @@ func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance
|
||||
PluginAPI string `json:"pluginApi"`
|
||||
Capabilities map[string]any `json:"capabilities"`
|
||||
}
|
||||
err = rpcConn.Call(initCtx, "plugin/initialize", map[string]any{
|
||||
initParams := map[string]any{
|
||||
"pluginId": s.opts.PluginID,
|
||||
"pluginApi": PluginAPIVersion,
|
||||
"dataDir": s.opts.DataDir,
|
||||
}, &initResp)
|
||||
}
|
||||
if s.opts.LocaleProvider != nil {
|
||||
loc, chain, bundle := s.opts.LocaleProvider()
|
||||
if loc != "" {
|
||||
initParams["locale"] = loc
|
||||
}
|
||||
if len(chain) > 0 {
|
||||
initParams["fallbackChain"] = chain
|
||||
}
|
||||
if len(bundle) > 0 {
|
||||
initParams["l10nBundle"] = bundle
|
||||
}
|
||||
}
|
||||
err = rpcConn.Call(initCtx, "plugin/initialize", initParams, &initResp)
|
||||
if err != nil {
|
||||
s.terminateInstance(inst)
|
||||
return nil, nil, fmt.Errorf("sidecar %s handshake failed: %w", s.opts.PluginID, err)
|
||||
@@ -513,6 +527,23 @@ func (s *SidecarSupervisor) terminateInstance(inst *sidecarInstance) {
|
||||
inst.rpc.Close()
|
||||
}
|
||||
|
||||
// NotifyIfRunning sends a fire-and-forget JSON-RPC notification only when the
|
||||
// Sidecar process is currently alive (never waking an idle Sidecar).
|
||||
func (s *SidecarSupervisor) NotifyIfRunning(method string, params any) {
|
||||
s.mu.Lock()
|
||||
inst := s.cur
|
||||
s.mu.Unlock()
|
||||
if inst == nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-inst.exited:
|
||||
return
|
||||
default:
|
||||
}
|
||||
_ = inst.rpc.Notify(context.Background(), method, params)
|
||||
}
|
||||
|
||||
// Stop terminates the Sidecar and its entire Job Object process tree cleanly.
|
||||
func (s *SidecarSupervisor) Stop() {
|
||||
s.mu.Lock()
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"sidebarVMs": "仮想マシン",
|
||||
"sidebarSystem": "システム",
|
||||
"sidebarHost": "エンジン",
|
||||
"sidebarPlugins": "プラグイン",
|
||||
"sidebarSettings": "設定",
|
||||
"sidebarInstallers": "インストーラ",
|
||||
"emptyVMs": "仮想マシンがありません",
|
||||
"hostReady": "準備完了",
|
||||
"hostNeedsAction": "確認が必要",
|
||||
"footerMemLabel": "メモリ",
|
||||
"footerMemValue": "{used} / {total} GB",
|
||||
"footerMemTip": "システムメモリ:{used} GB 使用中 / 合計 {total} GB(空き {avail} GB)",
|
||||
"footerRunningVMs": "{n, plural, other {# 台実行中}}",
|
||||
"footerDiskLabel": "ディスク",
|
||||
"footerDiskValue": "空き {gb} GB",
|
||||
"footerDiskTip": "データフォルダ:{dir}",
|
||||
"appearance": "外観モード",
|
||||
"themeLight": "ライト",
|
||||
"themeDark": "ダーク",
|
||||
"themeSystem": "システム設定に従う",
|
||||
"newVM": "新規仮想マシンを作成",
|
||||
"start": "起動",
|
||||
"stop": "シャットダウン"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"macos.recovery": "macOS 復旧",
|
||||
"macos.utilitiesTerminal": "ユーティリティ › ターミナル",
|
||||
"macos.appsUtilitiesTerminal": "アプリケーション › ユーティリティ › ターミナル",
|
||||
"macos.reinstallMacOS": "macOS を再インストール",
|
||||
"macos.diskUtility": "ディスクユーティリティ",
|
||||
"macos.showAllDevices": "表示 › すべてのデバイスを表示",
|
||||
"macos.erase": "消去",
|
||||
"macos.volume": "ボリューム",
|
||||
"macos.guidPartitionMap": "GUID パーティションマップ",
|
||||
"macos.setupAssistant": "設定アシスタント",
|
||||
"macos.otherSignInSetUpLater": "その他のサインインオプション › あとで設定",
|
||||
"macos.finder": "Finder"
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"tray.menu.show": "メインウィンドウを開く(&S)",
|
||||
"tray.menu.quit": "Reims-Go を終了(&Q)",
|
||||
"tray.running": "{count, plural, other {Reims-Go — # 台の仮想マシンが実行中}}",
|
||||
"guide.btn.fold": "折りたたむ",
|
||||
"guide.btn.back": "戻る",
|
||||
"guide.btn.return": "戻る",
|
||||
"guide.btn.cancel": "キャンセル",
|
||||
"guide.btn.continue": "続ける",
|
||||
"guide.btn.done": "完了",
|
||||
"guide.compact.label": "インストールガイド",
|
||||
"guide.stage.offline": "オフラインインストール",
|
||||
"guide.stage.online": "オンラインリカバリ",
|
||||
"guide.stage.builtin": "内蔵リカバリモード",
|
||||
"guide.stage.setup_assistant": "設定アシスタント",
|
||||
"guide.stage.guest_tools": "Guest Tools",
|
||||
"guide.boot.recovery.title": "macOS 復旧環境の起動を待機しています",
|
||||
"guide.boot.recovery.body": "Apple ロゴと進行状況バーが表示されるまでお待ちください。言語選択画面が表示されたら言語を選び、ユーティリティ画面が表示されたら「続ける」をクリックします。",
|
||||
"guide.select_disk.title": "インストール先ディスクの選択と初期化",
|
||||
"guide.select_disk.body": "新しい空のディスクを使用する場合は、{diskUtility} › {showAllDevices} を開いて容量から QEMU ディスクを選択するか、既存の APFS {volume}を使用してください。",
|
||||
"guide.select_disk.btn.erase": "ディスクユーティリティで消去する",
|
||||
"guide.select_disk.btn.existing": "既存の APFS ボリュームを使用する",
|
||||
"guide.format_disk.title": "空の仮想ディスクを APFS で消去",
|
||||
"guide.format_disk.body": "対象のディスクを選択して{erase}をクリックし、名前「Macintosh HD」、フォーマット「APFS」、方式{guidMap}を指定します。完了したら「{diskUtilityPlain}」を終了してください。",
|
||||
"guide.confirm_exit.title": "リカバリモードを終了して再起動しますか?",
|
||||
"guide.confirm_exit.body": "まだインストール中の場合は戻ってお待ちください。確認するとリカバリモードを終了し、ネットワークを有効化して「{name}」を再起動します。",
|
||||
"guide.confirm_exit.btn": "終了して仮想マシンを再起動",
|
||||
"cli.usage.header": "reims-go - Windows 向けポータブル reims-vgpu ワークベンチ"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"showWindow": "ウィンドウを表示",
|
||||
"showInstallGuide": "インストールガイドを表示",
|
||||
"copyScreenshot": "スクリーンショットをコピー",
|
||||
"toastScreenshotCopied": "スクリーンショットをクリップボードにコピーしました",
|
||||
"toastFilesDelivered": "{n, plural, other {共有フォルダへ # 個のファイルを送信しました}}",
|
||||
"snapshotsTitle": "復元ポイント",
|
||||
"snapshotCreate": "復元ポイントを作成",
|
||||
"snapshotRestore": "復元",
|
||||
"snapshotRestoreTitle": "「{name}」に復元しますか?",
|
||||
"state_running": "実行中",
|
||||
"state_stopped": "停止中",
|
||||
"state_starting": "起動中",
|
||||
"state_stopping": "停止処理中",
|
||||
"state_broken": "設定エラー",
|
||||
"pendingTitle": "次回起動時に適用されます",
|
||||
"restartToApply": "再起動して適用",
|
||||
"finishInstall": "リカバリモードを終了",
|
||||
"enterRecovery": "リカバリモードで起動",
|
||||
"typeClipboard": "クリップボードのテキストを入力"
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"id": "official.lang.ja-jp",
|
||||
"version": "1.0.0",
|
||||
"name": {
|
||||
"zh-CN": "日语语言包",
|
||||
"en-US": "Japanese Language Pack",
|
||||
"ja-JP": "日本語言語パック"
|
||||
},
|
||||
"description": {
|
||||
"zh-CN": "为 Reims-Go 提供日语界面、Win32 安装引导、系统托盘与命令行本地化",
|
||||
"en-US": "Provides Japanese UI, Win32 install guide, system tray, and CLI localization",
|
||||
"ja-JP": "Reims-Go の日本語 UI、Win32 インストールガイド、システムトレイ、CLI ローカライズを提供します"
|
||||
},
|
||||
"publisher": "Reims-Go",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"pluginApi": "^1.0.0"
|
||||
},
|
||||
"contributes": {
|
||||
"locales": [
|
||||
{
|
||||
"locale": "ja-JP",
|
||||
"label": "日本語",
|
||||
"fallback": "en-US",
|
||||
"files": {
|
||||
"core": "locales/core.json",
|
||||
"vm": "locales/vm.json",
|
||||
"native": "locales/native.json",
|
||||
"macosGlossary": "locales/macos-glossary.json"
|
||||
},
|
||||
"pluginOverrides": {
|
||||
"builtin.core": {
|
||||
"manifest": {
|
||||
"name": "Reims-Go コアエンジン",
|
||||
"description": "macOS 仮想マシンドライバ、デフォルトテーマ、起動準備、およびホスト互換性ワークアラウンド",
|
||||
"fields": {
|
||||
"setting.whpx_fallback.title": "WHPX ネスト仮想化の自動フォールバック",
|
||||
"setting.win10_cold_reboot.title": "Windows 10 コールドリブート互換モード"
|
||||
}
|
||||
}
|
||||
},
|
||||
"builtin.bridge.clipboard": {
|
||||
"manifest": {
|
||||
"name": "クリップボード共有",
|
||||
"description": "Windows ホストと macOS ゲスト間でテキストおよび画像クリップボードを同期します"
|
||||
}
|
||||
},
|
||||
"builtin.install-guide": {
|
||||
"manifest": {
|
||||
"name": "macOS インストールオーバーレイガイド",
|
||||
"description": "仮想マシンウィンドウの隅にリカバリおよびセットアップ手順を表示します"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"sidebarVMs": "虛擬機",
|
||||
"sidebarSystem": "系統",
|
||||
"sidebarHost": "核心",
|
||||
"sidebarPlugins": "外掛程式",
|
||||
"sidebarSettings": "設定",
|
||||
"sidebarInstallers": "安裝映像檔",
|
||||
"emptyVMs": "尚無虛擬機",
|
||||
"hostReady": "已就緒",
|
||||
"hostNeedsAction": "需要處理",
|
||||
"footerMemLabel": "記憶體",
|
||||
"footerMemValue": "{used} / {total} GB",
|
||||
"footerMemTip": "系統記憶體:已使用 {used} GB / 共 {total} GB(可用 {avail} GB)",
|
||||
"footerRunningVMs": "{n, plural, other {# 台執行中}}",
|
||||
"footerDiskLabel": "磁碟",
|
||||
"footerDiskValue": "可用 {gb} GB",
|
||||
"footerDiskTip": "虛擬機資料夾:{dir}",
|
||||
"appearance": "外觀",
|
||||
"themeLight": "淺色",
|
||||
"themeDark": "深色",
|
||||
"themeSystem": "跟隨系統",
|
||||
"newVM": "新增虛擬機",
|
||||
"start": "啟動",
|
||||
"stop": "關機"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"macos.recovery": "macOS 復原",
|
||||
"macos.utilitiesTerminal": "工具程式 › 終端機",
|
||||
"macos.appsUtilitiesTerminal": "應用程式 › 工具程式 › 終端機",
|
||||
"macos.reinstallMacOS": "重新安裝 macOS",
|
||||
"macos.diskUtility": "磁碟工具程式",
|
||||
"macos.showAllDevices": "顯示方式 › 顯示所有裝置",
|
||||
"macos.erase": "清除",
|
||||
"macos.volume": "卷宗",
|
||||
"macos.guidPartitionMap": "GUID 分割區配置表",
|
||||
"macos.setupAssistant": "設定輔助程式",
|
||||
"macos.otherSignInSetUpLater": "其他登入選項 › 稍後設定",
|
||||
"macos.finder": "Finder"
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"tray.menu.show": "開啟主視窗(&S)",
|
||||
"tray.menu.quit": "結束 Reims-Go(&Q)",
|
||||
"tray.running": "{count, plural, other {Reims-Go — # 台虛擬機執行中}}",
|
||||
"guide.btn.fold": "收合",
|
||||
"guide.btn.back": "上一步",
|
||||
"guide.btn.return": "返回",
|
||||
"guide.btn.cancel": "取消",
|
||||
"guide.btn.continue": "繼續",
|
||||
"guide.btn.done": "完成",
|
||||
"guide.compact.label": "安裝引導",
|
||||
"guide.stage.offline": "離線安裝",
|
||||
"guide.stage.online": "線上復原",
|
||||
"guide.stage.builtin": "內建復原",
|
||||
"guide.stage.setup_assistant": "設定輔助程式",
|
||||
"guide.stage.guest_tools": "Guest Tools",
|
||||
"guide.boot.recovery.title": "等待進入復原環境",
|
||||
"guide.boot.recovery.body": "請等待 Apple 標誌與進度列載入;若出現語言選單請先選擇預設語言,待工具視窗出現後點擊繼續。",
|
||||
"guide.select_disk.title": "選擇目標磁碟",
|
||||
"guide.select_disk.body": "若為空白磁碟,請開啟{diskUtility} › {showAllDevices},依容量選取 QEMU 磁碟;或直接使用既有 APFS {volume}。",
|
||||
"guide.select_disk.btn.erase": "清除磁碟",
|
||||
"guide.select_disk.btn.existing": "使用既有 APFS 卷宗",
|
||||
"guide.format_disk.title": "清除空白磁碟",
|
||||
"guide.format_disk.body": "選取空白磁碟並點擊{erase}:名稱填寫 Macintosh HD、格式選 APFS、架構選{guidMap};完成後關閉「{diskUtilityPlain}」。",
|
||||
"guide.confirm_exit.title": "結束復原模式並重新啟動?",
|
||||
"guide.confirm_exit.body": "若系統仍在安裝中請返回等待。確認後將退出復原模式、啟用網路並重新啟動「{name}」。",
|
||||
"guide.confirm_exit.btn": "退出並重新啟動",
|
||||
"validate.invalid_memory": "分配記憶體不得小於 2G(例如 8G、16G)"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"showWindow": "顯示視窗",
|
||||
"showInstallGuide": "顯示安裝引導",
|
||||
"copyScreenshot": "複製螢幕截圖",
|
||||
"toastScreenshotCopied": "已複製虛擬機螢幕截圖至剪貼簿",
|
||||
"toastFilesDelivered": "{n, plural, other {已傳送 # 個檔案至共享資料夾}}",
|
||||
"snapshotsTitle": "還原點",
|
||||
"snapshotCreate": "新增還原點",
|
||||
"snapshotRestore": "還原",
|
||||
"snapshotRestoreTitle": "確定還原至「{name}」?",
|
||||
"state_running": "執行中",
|
||||
"state_stopped": "已停止",
|
||||
"state_starting": "啟動中",
|
||||
"state_stopping": "停止中",
|
||||
"state_broken": "設定損毀",
|
||||
"pendingTitle": "下次啟動時套用",
|
||||
"restartToApply": "重新啟動以套用",
|
||||
"finishInstall": "結束復原模式",
|
||||
"enterRecovery": "進入復原模式",
|
||||
"typeClipboard": "傳送剪貼簿文字至虛擬機"
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"id": "official.lang.zh-tw",
|
||||
"version": "1.0.0",
|
||||
"name": {
|
||||
"zh-CN": "繁体中文(台湾)语言包",
|
||||
"en-US": "Traditional Chinese (Taiwan) Language Pack",
|
||||
"zh-TW": "繁體中文(台灣)語言套件",
|
||||
"zh-HK": "繁體中文(台灣)語言套件"
|
||||
},
|
||||
"description": {
|
||||
"zh-CN": "为 Reims-Go 提供台湾地区正体中文界面、Win32 安装引导、系统托盘与命令行本地化",
|
||||
"en-US": "Provides Traditional Chinese (Taiwan) UI, Win32 install guide, system tray, and CLI localization",
|
||||
"zh-TW": "為 Reims-Go 提供台灣地區繁體中文介面、Win32 安裝引導、系統匣與命令列本地化"
|
||||
},
|
||||
"publisher": "Reims-Go",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"pluginApi": "^1.0.0"
|
||||
},
|
||||
"contributes": {
|
||||
"locales": [
|
||||
{
|
||||
"locale": "zh-TW",
|
||||
"label": "繁體中文(台灣)",
|
||||
"fallback": "zh-CN",
|
||||
"files": {
|
||||
"core": "locales/core.json",
|
||||
"vm": "locales/vm.json",
|
||||
"native": "locales/native.json",
|
||||
"macosGlossary": "locales/macos-glossary.json"
|
||||
},
|
||||
"pluginOverrides": {
|
||||
"builtin.core": {
|
||||
"manifest": {
|
||||
"name": "Reims-Go 核心",
|
||||
"description": "macOS 虛擬機驅動程式、預設主題、啟動準備與宿主机相容性補償",
|
||||
"fields": {
|
||||
"setting.whpx_fallback.title": "自動降級 WHPX 巢狀虛擬化",
|
||||
"setting.win10_cold_reboot.title": "Windows 10 冷重啟補償"
|
||||
}
|
||||
}
|
||||
},
|
||||
"builtin.bridge.clipboard": {
|
||||
"manifest": {
|
||||
"name": "剪貼簿互通",
|
||||
"description": "在 Windows 宿主機與 macOS 客體機之間同步文字與圖片剪貼簿"
|
||||
}
|
||||
},
|
||||
"builtin.install-guide": {
|
||||
"manifest": {
|
||||
"name": "macOS 視窗安裝引導",
|
||||
"description": "在虛擬機視窗角落懸浮顯示恢復模式與安裝步驟引導"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user