Files
soundcraft/docs/i18n/tools/gen_zh_hans_locale.py
T
SuperiorandFredApps 60950ba884 Localization: Simplified Chinese catalogs on the shared localization module (#783)
* Add the Simplified Chinese catalog to the shared localization module

English source text stays the key: crates/ui-egui/locales/zh-Hans/mod.rs is generated from
crates/ui-egui/src/i18n/zh-hans.tsv (1,383 strings) by docs/i18n/tools/gen_zh_hans_locale.py, so a
translator edits one TSV row per string and the module follows. The TSV is also the file
storytold/craft-i18n's sync script reads, so the catalog can move there when SoundCraft cuts over.

The catalog covers every string passed to localization::text / localized_format! in the crate and
every reference menu label (crates/engine/catalog/menus.txt). Tests compare placeholders against the
English source, reject duplicate keys and name any untranslated string by file. Engine diagnostics
stay English by design: a half-translated error reads worse than a whole one.

Language::SimplifiedChinese ("zh-Hans") joins the enum, the Appearance menu and the ui.language
command, and the choice is saved with the UI state like the theme. AI-authored from the English
source; native-speaker review is still pending.

* Add a Han font fallback for Chinese on the desktop and the web

egui's bundled faces carry no Han glyphs, so a Chinese interface and Chinese session, track and clip
names would draw boxes. fonts.rs now appends a Han fallback to every family:

- desktop: the operating system's own face, resolved through fontconfig with lang=zh-cn plus a list
  of per-platform candidates (PingFang, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, WenQuanYi,
  ...). Nothing is redistributed.
- web: the browser cannot reach system fonts, so the build embeds assets/fonts/NotoSansSC-SoundCraftSubset.ttf,
  a 1.1 MiB Open Font License subset of Noto Sans SC pinned at weight 400.

Han is ordered before the Hangul fallback for every interface language except Korean: the first face
with a glyph wins, and on Linux fontconfig often resolves Noto Sans CJK's Korean face, whose Han
glyphs are Korean-styled. Tests check the ordering, that every family draws Han when a system font
is present, that the bundled face draws the whole zh-Hans catalog in every family, and that it stays
inside its 2 MiB budget. ATTRIBUTION.md records the font and its OFL text; cargo xtask assets
enforces that.

* Document the zh-Hans catalog and refresh the localization numbers

docs/localization.md now describes what ships today (the Language enum, locales/<tag>/mod.rs,
text / localized_format! / error_text, the TSV-to-module step, the Han fallback, the tests) instead
of the packed-catalog design the branch carried before upstream landed the shared localization
module. docs/localization-zh-hans.md is the translator workflow; docs/i18n/glossary.md records the
wording decisions without citing another product's catalogs, and the earlier cross-corpus research
files are gone: the repository's clean-room rule forbids reading GPL translation sources, so the
terminology stands on its own reasoning.

ROADMAP.md, docs/roadmap.md, docs/localization-parity.md and docs/gaps.md move zh-Hans from "none"
to shipped-for-fixed-strings with native review pending, note the CJK fallback, and lower the
localization estimate from 70-110 h to 55-90 h.

* Align the localization numbers and the catalog-editing guidance

The localization row in docs/target-app-parity.md still listed pt-BR only, ~12 % and 70-110 h; the
G-09 row kept the old 20-40 h. Both now match ROADMAP.md, docs/roadmap.md and
docs/localization-parity.md: two shipped catalogs, ~19 %, 55-90 h to the target's eight languages.

Also, docs/localization-parity.md no longer tells a reader to add a Rust arm for every catalog: pt-BR
is hand-written, zh-Hans is generated from its TSV, and the two are now described separately. The
font regeneration commands in docs/localization.md and docs/localization-zh-hans.md name the input
the subset script requires (a Noto Sans SC variable font) instead of implying it runs with no
argument.

* zh-Hans: keep the slot and track order in "Insert {} for {}"

---------

Co-authored-by: FredApps <[email protected]>
2026-11-28 23:40:00 +01:00

139 lines
5.0 KiB
Python

#!/usr/bin/env python3
"""Generate `crates/ui-egui/locales/zh-Hans/mod.rs` from the translator-facing TSV.
The TSV (`crates/ui-egui/src/i18n/zh-hans.tsv`) is the source translators edit: one row per
string, `context<TAB>English source<TAB>Simplified Chinese`. The UI reads the Rust module, because
that is how every locale in this repository ships (see `locales/pt-BR/mod.rs`); this script is the
only thing that turns one into the other, so the two never drift.
Usage (from the repository root):
python3 docs/i18n/tools/gen_zh_hans_locale.py # write the module
python3 docs/i18n/tools/gen_zh_hans_locale.py --check # fail if it is out of date
`@plural` rows carry `singular|plural` in the source column, because English inflects where
Simplified Chinese does not; both English keys map to the same Chinese row. The columns use the
catalog's escapes (`\n`, `\t`, `\\`), which this script decodes before writing the Rust literal.
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
TSV = ROOT / "crates/ui-egui/src/i18n/zh-hans.tsv"
OUT = ROOT / "crates/ui-egui/locales/zh-Hans/mod.rs"
HEADER = """\
//! Simplified Chinese (`zh-Hans`) catalog, keyed by the English source string.
//!
//! Generated by `docs/i18n/tools/gen_zh_hans_locale.py` from
//! `crates/ui-egui/src/i18n/zh-hans.tsv`; edit the TSV, then rerun the script. Engine diagnostics
//! stay English by design, so this catalog has no error templates.
/// Returns the Simplified Chinese translation for a source-language UI string.
#[rustfmt::skip]
pub(super) fn translate(source: &str) -> Option<&'static str> {
Some(match source {
"""
FOOTER = """\
_ => return None,
})
}
/// Engine error messages with `{name}` placeholders standing for the values they embed. Simplified
/// Chinese keeps engine diagnostics in English by design (see `docs/localization-zh-hans.md`).
pub(super) const ERROR_TEMPLATES: &[(&str, &str)] = &[];
"""
def unescape(text: str) -> str:
"""Decode the catalog's `\\n`, `\\t` and `\\\\` escapes (the TSV is one row per string)."""
out = []
index = 0
while index < len(text):
ch = text[index]
if ch == "\\" and index + 1 < len(text):
nxt = text[index + 1]
if nxt == "n":
out.append("\n")
elif nxt == "t":
out.append("\t")
elif nxt == "\\":
out.append("\\")
else:
out.append(ch)
out.append(nxt)
index += 2
continue
out.append(ch)
index += 1
return "".join(out)
def rust_literal(text: str) -> str:
"""A Rust string literal for `text`; the catalogs contain quotes, braces and newlines."""
out = []
for ch in text:
if ch == "\\":
out.append("\\\\")
elif ch == '"':
out.append('\\"')
elif ch == "\n":
out.append("\\n")
elif ch == "\t":
out.append("\\t")
elif ch == "\r":
out.append("\\r")
elif ord(ch) < 0x20:
out.append(f"\\u{{{ord(ch):x}}}")
else:
out.append(ch)
return '"' + "".join(out) + '"'
def rows() -> dict[str, str]:
"""Every English source string mapped to its Chinese translation."""
pairs: dict[str, str] = {}
for number, line in enumerate(TSV.read_text(encoding="utf-8").splitlines(), start=1):
if not line or line.startswith("#"):
continue
columns = line.split("\t", 2)
if len(columns) != 3:
raise SystemExit(f"{TSV}:{number}: expected three tab-separated columns")
context, source, translation = (unescape(column) for column in columns)
if not source or not translation:
raise SystemExit(f"{TSV}:{number}: empty source or translation")
# A `@plural` row names both English forms; Chinese has one form for both.
sources = source.split("|") if context.startswith("@") else [source]
for key in sources:
previous = pairs.get(key)
if previous is not None and previous != translation:
raise SystemExit(f"{TSV}:{number}: {key!r} translated twice, differently")
pairs[key] = translation
return pairs
def render(pairs: dict[str, str]) -> str:
arms = "".join(f" {rust_literal(source)} => {rust_literal(pairs[source])},\n" for source in sorted(pairs))
return HEADER + arms + FOOTER
def main(argv: list[str]) -> int:
rendered = render(rows())
if "--check" in argv:
if not OUT.exists() or OUT.read_text(encoding="utf-8") != rendered:
print(f"{OUT} is out of date; run python3 docs/i18n/tools/gen_zh_hans_locale.py", file=sys.stderr)
return 1
print(f"{OUT}: up to date")
return 0
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(rendered, encoding="utf-8")
print(f"wrote {OUT.relative_to(ROOT)} ({len(rows())} strings)")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))