feat(i18n): add Korean and live language switching (#582)

* feat(i18n): add Korean and live language switching

* i18n(ko): Edit Type (#598)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Brandon Thomas <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-10-07 09:06:33 -04:00
1 parent 45bedb0962
commit d4086ba11a
13 files changed
+2455 -16

No files matched your search

+1
View File
@@ -10,6 +10,7 @@ next to them.
| Path | Title | Author | Source | License |
|---|---|---|---|---|
| `crates/ui-egui/src/i18n/ko.tsv` | Korean UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | <https://github.com/rsms/inter> | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) |
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | <https://github.com/JetBrains/JetBrainsMono> | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) |
| `assets/icons/*.svg` except `slice-knife.svg`, `eraser-background.svg` and `eraser-magic.svg` (109 files) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
+8 -2
View File
@@ -263,7 +263,12 @@ fn section_list(app: &mut PhotocraftApp, ui: &mut egui::Ui, b: &mut BrushSetting
}
let color = if sel { t.text } else { t.text_dim };
let font = if i == 0 { theme::semibold(12.0) } else { theme::medium(12.0) };
ui.painter().text(egui::pos2(x, r.center().y), egui::Align2::LEFT_CENTER, tl!(name), font, color);
let mut job = egui::text::LayoutJob::simple_singleline(tl!(name).to_string(), font, color);
job.wrap = egui::text::TextWrapping::truncate_at_width((r.right() - 22.0 - x).max(0.0));
let galley = ui.painter().layout_job(job);
let elided = galley.elided;
ui.painter().galley(egui::pos2(x, r.center().y - galley.size().y / 2.0), galley, color);
let resp = if elided { resp.on_hover_text(tl!(name)) } else { resp };
let mut lock_clicked = false;
if let Some(lock) = section_lock(b, i) {
let lr = egui::Rect::from_center_size(egui::pos2(r.right() - 11.0, r.center().y), vec2(18.0, 18.0));
@@ -300,7 +305,8 @@ fn settings_tab(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
widgets::vline(ui, 482.0);
ui.vertical(|ui| {
ui.set_width(WIDTH - 190.0);
ui.label(RichText::new(tl!(SECTIONS[section].0)).font(theme::semibold(12.5)).color(t.text));
let name = SECTIONS.get(section).map_or("Brush Tip Shape", |entry| entry.0);
ui.label(RichText::new(tl!(name)).font(theme::semibold(12.5)).color(t.text));
ui.add_space(6.0);
let on = section_flag(&mut b, section).is_none_or(|f| *f);
egui::ScrollArea::vertical().id_salt(("brush-section", section)).max_height(450.0).auto_shrink([false, false]).show(ui, |ui| {
+51 -3
View File
@@ -51,7 +51,15 @@ pub fn no_embedded(_: CjkScript) -> Vec<&'static CraftFont> {
impl Sources {
#[cfg(not(target_arch = "wasm32"))]
pub fn system() -> Self {
Self { locale: || cjk::ui_locale().map(str::to_string), files: cjk::font_files, last_resort: cjk::last_resort_files, embedded: craft_embedded }
Self {
locale: || match crate::i18n::current().code() {
code @ ("ja" | "ko" | "zh-hans" | "zh-hant") => Some(code.to_string()),
_ => cjk::ui_locale().map(str::to_string),
},
files: cjk::font_files,
last_resort: cjk::last_resort_files,
embedded: craft_embedded,
}
}
#[cfg(target_arch = "wasm32")]
pub fn system() -> Self {
@@ -62,6 +70,8 @@ impl Sources {
/// The lazy loader's state: which scripts were tried and which files were read.
pub struct CjkFallback {
sources: Sources,
/// set_fonts takes effect next pass; do not collide with a previous loader's font names.
defer_after_reset: bool,
order: Option<[CjkScript; 4]>,
tried: Vec<CjkScript>,
last_resort_tried: bool,
@@ -72,7 +82,7 @@ pub struct CjkFallback {
impl CjkFallback {
pub fn new(sources: Sources) -> Self {
Self { sources, order: None, tried: Vec::new(), last_resort_tried: false, loaded: Vec::new(), registered: Vec::new() }
Self { sources, defer_after_reset: false, order: None, tried: Vec::new(), last_resort_tried: false, loaded: Vec::new(), registered: Vec::new() }
}
/// Script order for the UI locale (resolved on first use, not at startup).
@@ -247,6 +257,10 @@ impl egui::Plugin for CjkFontPlugin {
}
fn output_hook(&mut self, ctx: &egui::Context, output: &mut egui::FullOutput) {
if std::mem::take(&mut self.0.defer_after_reset) {
ctx.request_repaint();
return;
}
if self.0.exhausted() {
return;
}
@@ -268,7 +282,19 @@ pub fn install(ctx: &egui::Context) {
}
pub fn install_with(ctx: &egui::Context, sources: Sources) {
ctx.add_plugin(CjkFontPlugin(CjkFallback::new(sources)));
// egui keeps the first plugin of a type. set_fonts removes loaded fallbacks, so reset the
// existing loader too; otherwise its tried/loaded sets prevent fonts being added again.
let mut fallback = CjkFallback::new(sources.clone());
fallback.defer_after_reset = true;
if ctx
.with_plugin::<CjkFontPlugin, _>(|plugin| {
plugin.0 = CjkFallback::new(sources.clone());
plugin.0.defer_after_reset = true;
})
.is_none()
{
ctx.add_plugin(CjkFontPlugin(fallback));
}
}
#[cfg(test)]
@@ -279,6 +305,28 @@ mod tests {
static DIR: Mutex<Option<PathBuf>> = Mutex::new(None);
#[test]
fn changing_language_resets_the_loader_once_and_reorders_scripts() {
crate::i18n::with_language(crate::i18n::Lang::EN, || {
let ctx = egui::Context::default();
crate::i18n::sync_context(&ctx, "ja");
ctx.with_plugin::<CjkFontPlugin, _>(|plugin| {
assert_eq!(plugin.0.order()[0], CjkScript::Japanese);
plugin.0.tried = plugin.0.order().to_vec();
plugin.0.last_resort_tried = true;
})
.expect("font plugin");
crate::i18n::sync_context(&ctx, "ja");
assert!(ctx.with_plugin::<CjkFontPlugin, _>(|plugin| plugin.0.exhausted()).expect("font plugin"), "idle frames must not reload fonts");
crate::i18n::sync_context(&ctx, "ko");
ctx.with_plugin::<CjkFontPlugin, _>(|plugin| {
assert!(!plugin.0.exhausted());
assert_eq!(plugin.0.order()[0], CjkScript::Korean);
})
.expect("font plugin");
});
}
fn fake_dir() -> PathBuf {
let mut g = DIR.lock().unwrap();
g.get_or_insert_with(|| {
+6
View File
@@ -66,6 +66,12 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
let dialogs = app.ui.dialogs.clone();
let mut shown = Vec::new();
for d in dialogs {
let lang = if crate::prefs_ui::is_preferences(&d.fields) {
crate::i18n::Lang::from_pref(d.fields.get("values").and_then(|v| v.pointer("/interface/language")).and_then(Value::as_str).unwrap_or("auto"))
} else {
crate::i18n::current()
};
let _language = crate::i18n::language_scope(lang);
let mut fields = d.fields.clone();
let mut outcome: Option<bool> = None; // Some(true)=OK, Some(false)=Cancel
let mut apply_requested = false;
@@ -0,0 +1,6 @@
PhotoCraft's Korean UI translation catalog is licensed under MIT OR Apache-2.0,
at your option. The full license texts are in ../../../../LICENSE-MIT and
../../../../LICENSE-APACHE.
Korean translations: PhotoCraft contributors, original translations of
PhotoCraft's English labels; no proprietary translation resources were used.
File diff suppressed because it is too large. Load diff
+192
View File
@@ -0,0 +1,192 @@
//! Behavioural checks for switching languages in a running shell.
use super::*;
use crate::{PhotocraftApp, Services};
use serde_json::json;
fn lang(code: &str) -> Lang {
Lang::from_code(code).expect("registered language")
}
#[test]
fn requested_languages_resolve_regional_preferences() {
for (tag, code) in [("en-US", "en"), ("zh-CN", "zh-hans"), ("ja-JP", "ja"), ("ko-KR", "ko"), ("ru-RU", "ru"), ("fr-CA", "fr"), ("id-ID", "id")] {
assert_eq!(Lang::from_pref(tag), lang(code), "{tag}");
}
assert_eq!(lang_from_tag("ko_KR.UTF-8"), Some(lang("ko")));
assert_eq!(lang_from_tag("FR-fr"), Some(lang("fr")));
assert_eq!(lang_from_tag("ko"), Some(lang("ko")));
}
#[test]
fn french_and_korean_plural_messages_keep_placeholders() {
for (n, expected) in [(0, "0 élément"), (1, "1 élément"), (2, "2 éléments"), (21, "21 éléments")] {
assert_eq!(trn(lang("fr"), n, "{n} item", "{n} items"), expected);
}
for n in [0, 1, 2, 21, u64::MAX] {
assert_eq!(trn(lang("ko"), n, "{n} item", "{n} items"), format!("항목 {n}개"));
}
assert_eq!(fmt(tr(lang("ko"), "Version {version}"), &[("version", "0.2.0")]), "버전 0.2.0");
assert_eq!(tr(lang("fr"), "unknown translation"), "unknown translation");
}
#[test]
fn scoped_preview_restores_language_even_after_a_panic() {
with_language(Lang::EN, || {
with_language(lang("fr"), || {
assert_eq!(t("Layer"), "Calque");
with_language(lang("ko"), || assert_eq!(t("Layer"), "레이어"));
assert_eq!(t("Layer"), "Calque");
});
let result = std::panic::catch_unwind(|| with_language(lang("ja"), || panic!("test unwind")));
assert!(result.is_err());
assert_eq!(current(), Lang::EN);
});
}
#[test]
fn drawing_languages_are_isolated_between_threads() {
with_language(lang("fr"), || {
let thread = std::thread::spawn(|| {
assert_eq!(current(), Lang::EN);
with_language(lang("ko"), || assert_eq!(t("Layer"), "레이어"));
});
thread.join().expect("language thread");
assert_eq!(t("Layer"), "Calque");
});
}
#[test]
fn dynamic_brush_sections_have_translations_and_draw_in_the_selected_language() {
for language in Lang::all().filter(|language| language.complete_menus()) {
for (name, _) in crate::brush_panel::SECTIONS {
assert!(has(language, name), "{}: untranslated brush section {name}", language.code());
}
}
with_language(Lang::EN, || {
let mut h = harness();
h.state_mut().run("prefs.set", json!({"path": "interface.language", "value": "zh-hans"})).expect("language");
h.state_mut().ui.panels.brush_settings = true;
h.run_steps(4);
let text = drawn_text(&h);
assert!(text.iter().filter(|text| text.as_str() == "画笔笔尖形状").count() >= 2, "both the section row and heading must be translated");
assert!(!text.iter().any(|text| text == "Brush Tip Shape"));
});
}
#[test]
fn cjk_font_order_follows_the_selected_language() {
use photocraft_text::cjk::CjkScript;
for (code, script) in [("zh-hans", CjkScript::SimplifiedChinese), ("ja", CjkScript::Japanese), ("ko", CjkScript::Korean)] {
with_language(lang(code), || {
let mut fallback = crate::cjk_fonts::CjkFallback::new(crate::cjk_fonts::Sources::system());
assert_eq!(fallback.order().first(), Some(&script), "{code}");
});
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn korean_glyphs_remain_available_after_repeated_language_switches() {
use photocraft_text::cjk::{self, CjkChar, CjkScript};
if !cjk::font_files(CjkScript::Korean).iter().any(|font| font.path.is_file()) {
eprintln!("skipping: no installed Korean font");
return;
}
with_language(Lang::EN, || {
let mut h = harness();
let glyphs: std::collections::BTreeSet<_> = lang("ko").0.source.chars().filter(|c| cjk::classify(*c) == Some(CjkChar::Hangul)).collect();
for code in ["zh-hans", "ja", "ko", "fr", "ko"] {
h.state_mut().run("prefs.set", json!({"path": "interface.language", "value": code})).expect("language");
h.run_steps(12);
if code == "ko" {
h.ctx.fonts_mut(|fonts| {
for family in [egui::FontFamily::Proportional, egui::FontFamily::Name("medium".into()), egui::FontFamily::Name("semibold".into())] {
let font = egui::FontId::new(12.0, family);
for c in &glyphs {
assert!(fonts.has_glyph(&font, *c), "missing Korean glyph {c} after a hot language change");
}
}
});
}
}
});
}
fn harness() -> egui_kittest::Harness<'static, PhotocraftApp> {
let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(|cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default());
app.run("file.new", json!({"name": "User layer name", "width": 64, "height": 64})).expect("new document");
app
});
harness.run_steps(4);
harness
}
#[test]
fn a_control_request_changes_the_drawing_language_in_the_same_frame() {
with_language(Lang::EN, || {
let mut h = harness();
let document = h.state().session.active().expect("document").doc.clone();
for code in ["zh-hans", "ja", "ko", "ru", "fr", "id", "en"] {
let (tx, rx) = std::sync::mpsc::channel();
h.state_mut().control_rx = Some(rx);
let (request, reply) =
crate::control::ControlRequest::new("engine.execute", json!({"command": "prefs.set", "params": {"path": "interface.language", "value": code}}));
tx.send(request).expect("request");
h.step();
assert_eq!(reply.try_recv().expect("response")["ok"], true);
assert_eq!(current(), lang(code));
assert!(drawn_text(&h).iter().any(|text| text == tr(lang(code), "File")), "the menu must change in this frame: {code}");
assert!(std::sync::Arc::ptr_eq(&document, &h.state().session.active().expect("document").doc), "switching language must preserve the document");
}
assert!(h.state_mut().run("prefs.set", json!({"path": "interface.language", "value": []})).is_err());
h.step();
assert_eq!(current(), Lang::EN);
});
}
#[test]
fn preferences_preview_does_not_commit_until_applied_and_survives_reload() {
with_language(Lang::EN, || {
let mut h = harness();
let id = crate::prefs_ui::open_preferences(h.state_mut(), "interface");
let dialog = h.state_mut().ui.dialog_mut(id).expect("preferences");
dialog.fields.get_mut("values").expect("values")["interface"]["language"] = json!("fr");
h.run_steps(3);
let text = drawn_text(&h);
assert!(text.iter().any(|text| text == "Langue"), "the draft language must translate the actual dialog");
assert!(text.iter().any(|text| text == "Annuler"), "the dialog buttons must preview the language too");
assert!(text.iter().any(|text| text == "File"), "the main window keeps its committed language");
assert_eq!(h.state().session.prefs().interface.language, "auto");
assert_eq!(current(), Lang::EN, "preview must not leak to the main window");
h.state_mut().ui.close_dialog(id);
h.step();
assert_eq!(current(), Lang::EN);
let id = crate::prefs_ui::open_preferences(h.state_mut(), "interface");
h.state_mut().ui.dialog_mut(id).expect("preferences").fields.get_mut("values").expect("values")["interface"]["language"] = json!("ko");
crate::prefs_ui::apply(h.state_mut(), id).expect("apply");
h.step();
assert_eq!(current(), lang("ko"));
let saved = h.state().session.prefs_to_json();
let mut restored = photocraft_engine::Session::new();
restored.load_prefs_json(&saved).expect("reload preferences");
assert_eq!(restored.prefs().interface.language, "ko");
});
}
fn drawn_text(h: &egui_kittest::Harness<'_, PhotocraftApp>) -> Vec<String> {
fn collect(shape: &egui::Shape, text: &mut Vec<String>) {
match shape {
egui::Shape::Text(shape) => text.push(shape.galley.job.text.clone()),
egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, text)),
_ => {}
}
}
let mut text = Vec::new();
for shape in &h.output().shapes {
collect(&shape.shape, &mut text);
}
text
}
+56 -8
View File
@@ -20,8 +20,8 @@
mod catalog;
use std::cell::Cell;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicUsize, Ordering};
use catalog::Catalog;
@@ -75,7 +75,7 @@ fn plural_fr(n: u64) -> usize {
}
/// The registry. English first: it is the fallback and the source language.
pub static LANGUAGES: [LangInfo; 9] = [
pub static LANGUAGES: [LangInfo; 10] = [
LangInfo { code: "en", name: "English", source: "", plural: plural_one_other, complete_menus: false, catalog: OnceLock::new() },
LangInfo { code: "ja", name: "日本語", source: include_str!("ja.tsv"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() },
LangInfo {
@@ -91,6 +91,7 @@ pub static LANGUAGES: [LangInfo; 9] = [
LangInfo { code: "cs", name: "Čeština", source: include_str!("cs.tsv"), plural: plural_cs, complete_menus: true, catalog: OnceLock::new() },
LangInfo { code: "fr", name: "Français", source: include_str!("fr.tsv"), plural: plural_fr, complete_menus: true, catalog: OnceLock::new() },
LangInfo { code: "id", name: "Bahasa Indonesia", source: include_str!("id.tsv"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() },
LangInfo { code: "ko", name: "한국어", source: include_str!("ko.tsv"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() },
];
impl LangInfo {
@@ -132,7 +133,10 @@ impl Lang {
/// Resolve the `interface.language` preference: a language code, or `auto` (and anything
/// unknown, e.g. a code from a newer version) to follow the system locale.
pub fn from_pref(pref: &str) -> Lang {
Lang::from_code(pref).unwrap_or_else(system_lang)
if pref.eq_ignore_ascii_case("auto") {
return system_lang();
}
Lang::from_code(pref).or_else(|| lang_from_tag(pref)).unwrap_or_else(system_lang)
}
/// Every registered language.
@@ -228,19 +232,58 @@ fn detect_system_lang() -> Lang {
Lang::EN
}
/// Index into [`LANGUAGES`] of the language the UI is drawn in this frame.
static CURRENT: AtomicUsize = AtomicUsize::new(0);
thread_local! {
// Independent app/test threads must not change each other's drawing language.
static CURRENT: Cell<Lang> = const { Cell::new(Lang::EN) };
}
/// Set the UI language for drawing (the shell calls this once per frame from the preference), so
/// widgets can translate without every call site carrying a language around.
pub fn set_current(lang: Lang) {
let i = LANGUAGES.iter().position(|l| l.code == lang.code()).unwrap_or(0);
CURRENT.store(i, Ordering::Relaxed);
CURRENT.set(lang);
}
/// The language the UI is drawn in.
pub fn current() -> Lang {
Lang(LANGUAGES.get(CURRENT.load(Ordering::Relaxed)).unwrap_or(&LANGUAGES[0]))
CURRENT.get()
}
/// Temporarily draw in another language, restoring the previous one even on unwinding.
/// Preferences previews use this without changing the saved setting or other dialogs.
pub fn with_language<R>(lang: Lang, draw: impl FnOnce() -> R) -> R {
let _restore = language_scope(lang);
draw()
}
/// Keep the language active until this guard is dropped on the drawing thread.
#[must_use]
pub fn language_scope(lang: Lang) -> impl Drop {
struct Restore {
previous: Lang,
_thread: std::marker::PhantomData<std::rc::Rc<()>>,
}
impl Drop for Restore {
fn drop(&mut self) {
set_current(self.previous);
}
}
let restore = Restore { previous: current(), _thread: std::marker::PhantomData };
set_current(lang);
restore
}
/// Apply a committed language to this context. Font caches are rebuilt only on a language
/// change, so Han glyphs follow the selected script even when the previous font covered them.
pub fn sync_context(ctx: &egui::Context, language: &str) {
let lang = Lang::from_pref(language);
set_current(lang);
let id = egui::Id::new("photocraft-ui-language");
let changed = ctx.data(|data| data.get_temp::<Lang>(id) != Some(lang));
if changed {
ctx.data_mut(|data| data.insert_temp(id, lang));
crate::theme::install_fonts(ctx);
ctx.request_repaint();
}
}
/// Does `lang` have a catalog entry for this plain string? (English never does: it is the source.)
@@ -311,6 +354,7 @@ mod tests {
assert_eq!(lang_from_tag("POSIX"), Some(Lang::EN));
assert_eq!(lang_from_tag("cs_CZ.UTF-8"), Some(CS()));
assert_eq!(lang_from_tag("cs-CZ"), Some(CS()));
assert_eq!(lang_from_tag("fr_FR"), Lang::from_code("fr"));
assert_eq!(lang_from_tag("de_DE"), None);
// Traditional Chinese: by region, by script, and with a region after the script.
assert_eq!(lang_from_tag("zh_TW.UTF-8"), Some(ZH()));
@@ -340,6 +384,7 @@ mod tests {
#[test]
fn macos_language_list_is_parsed() {
assert_eq!(first_supported("(\n \"ja-JP\",\n \"en-US\"\n)\n"), Some(JA()));
assert_eq!(first_supported("(\n \"fr-FR\",\n \"en-US\"\n)\n"), Lang::from_code("fr"));
assert_eq!(first_supported("(\n \"de-DE\",\n \"en-US\"\n)\n"), Some(Lang::EN));
assert_eq!(first_supported("(\n \"zh-Hant-TW\",\n \"en-US\"\n)\n"), Some(ZH()));
assert_eq!(first_supported("("), None);
@@ -645,3 +690,6 @@ mod tests {
assert_eq!(text, "Фильтр Camera Raw ({Background} 影像)", "user layer names are not translated");
}
}
#[cfg(test)]
mod live_tests;
+3
View File
@@ -881,6 +881,8 @@ impl eframe::App for PhotocraftApp {
self.issue_screenshots(ctx);
prefs_ui::tick(self, ctx);
monitor_status::poll(self, ctx);
// Control requests and persisted preferences can change the language in this frame.
i18n::sync_context(ctx, &self.session.prefs().interface.language);
// A window bigger than its display (1440 × 900 on 1366 × 768) runs under the taskbar:
// maximize it into the work area once (#315).
work_area::fit_window(ctx);
@@ -914,6 +916,7 @@ impl eframe::App for PhotocraftApp {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let ctx = ui.ctx().clone();
i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language));
// Fonts registered via set_fonts only take effect next frame; named families would panic now.
if !self.fonts_ready {
ctx.request_repaint();
+5
View File
@@ -57,6 +57,11 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
## Engine commands
Change the UI language without restarting with `prefs.set`:
`{"path":"interface.language","value":"fr"}`. Supported codes and preview/apply behaviour
are documented in [UI localisation](localization.md). `prefs.get` and the existing preference
store expose and persist the same setting; scripts keep using canonical command IDs.
`engine.execute` runs any command by id. `engine.commands` (or the engine command `command.list`) lists them all, with labels, menu paths, shortcuts, a parameter description, and whether each is currently enabled. Examples:
| Command | Params |
+88
View File
@@ -0,0 +1,88 @@
# UI localisation and live language switching
PhotoCraft uses the same Rust catalog implementation in the native egui shell and the
WebAssembly build. English source strings are lookup keys. UTF-8 TSV catalogs supply plain,
contextual, command-ID and plural translations; missing entries fall back to English.
## Supported languages
| Language | Preference code | Integer plural forms |
|---|---|---|
| English | `en` | one / other |
| 简体中文 | `zh-hans` | one form |
| 日本語 | `ja` | one form |
| 한국어 | `ko` | one form |
| Русский | `ru` | one / few / many |
| Français | `fr` | singular for 0 and 1 / plural for 2+ |
| 繁體中文 | `zh-hant` | one form |
| Español | `es` | one / other |
| Čeština | `cs` | one / few / other |
| Bahasa Indonesia | `id` | one form |
Every non-English catalog covers the current menu labels, `tl!` literals, blend mode names,
and generated preference labels. Tests enforce that coverage. This does not include every
engine error or status message: those remain English, as do automation command IDs and
user-provided document, layer and preset names.
## Switch without restarting
Open **Edit > Preferences > Interface > Language** and choose a language. The Preferences
dialog previews its title, controls and buttons in the chosen language. **Cancel** discards
the preview, **Apply** commits it without closing the dialog, and **OK** commits and closes.
The rest of the interface follows the committed preference on its next draw. Existing
documents, undo history and tools remain available throughout a language change.
The existing preference store saves the selection for future launches. `auto` follows the
native system locale; an unsupported code follows the same fallback. Regional tags such as
`fr-CA`, `ko-KR` and `zh-CN` resolve to the corresponding registered catalog. Traditional and
Simplified Chinese remain distinct.
Agents use the existing `prefs.set` command through CLI, MCP or the desktop control channel:
```json
{"method":"engine.execute","params":{"command":"prefs.set","params":{"path":"interface.language","value":"ko"}}}
```
Control requests are processed before synchronising the drawing language, so a request
updates the labels in the same rendered frame. Drawing language is local to the UI thread;
a scoped preview restores the previous language even if drawing unwinds. Menu and dialog
identity continues to use command IDs, independent of translated labels.
This is hot switching among the bundled catalogs. Catalog files are embedded with
`include_str!`; editing a TSV file requires a rebuild. External catalog watching and
file-resource hot reload are not implemented.
## Fonts
The native lazy CJK font loader prioritises the selected Japanese, Korean or Chinese script.
Switching languages rebuilds the font definitions and resets the existing loader, so fonts
removed from the definitions can be registered again. Idle frames keep their font cache.
Other languages retain the system's CJK fallback preference for document names and text.
Font files are not added to this repository. Native rendering uses installed system fonts
and the optional craft-fonts build input; see [Fonts](development.md#fonts-craft-fonts).
The web build can select every catalog, but CJK glyph delivery and automatic browser-locale
detection remain separate outstanding work. Switching catalogs does not supply missing fonts.
## Add or maintain a catalog
1. Add `<code>.tsv` under `crates/ui-egui/src/i18n`, following the header in `ja.tsv`.
2. Register its code, native name and plural rule in `i18n::LANGUAGES`.
3. Translate the meaning of the English source keys. Preserve `{name}` placeholders, escaped
characters and the trailing `…` on dialog commands. Use `@id` to disambiguate a command
label and `@plural` for count-sensitive text. Keep product names such as PhotoCraft.
4. Set `complete_menus` when the catalog covers all enforced keys. Add source and license
attribution for translation assets, then run the catalog and shell tests.
```sh
cargo test -p photocraft-ui-egui --locked
cargo clippy -p photocraft-ui-egui --all-targets --locked -- -D warnings
cargo xtask i18n-coverage
cargo xtask layers
cargo xtask wasm
```
Render representative dialogs with the offscreen `snapshot` example, including a sequence
of language changes in one process. Inspect the PNGs for missing glyphs and truncated labels.
Translations are original work or reuse the open PhotoCraft contributions credited in
[ATTRIBUTION.md](../ATTRIBUTION.md); no proprietary localisation resources are used.
+1
View File
@@ -76,6 +76,7 @@ Confidence: moderate — the next users of 0.2.x will move these numbers either
| AI / generative | none | ~0% | Deferred by decision (#41). |
| Ecosystem | Sandboxed WebAssembly plug-ins instead of .8BF; no ExtendScript/UXP/.atn; no Adobe Fonts/Libraries/cloud docs | low | By design for 8BF; scripting compatibility open. |
| Platforms | macOS (notarized), Windows, Linux (AppImage/deb/rpm/Flatpak bundle), web | medium-high | Flathub later (#173); Windows signing material pending. |
| Localisation | 2026-10-07: 10 UI languages; menu, `tl!`, blend mode, preference and brush-section coverage enforced by tests; live switching and scoped Preferences previews | medium | Engine errors/status messages still partly English; CJK web fonts, browser-locale detection, and RTL remain open. |
### Where we're going (priority order)
+13 -3
View File
@@ -90,6 +90,10 @@ the tests enforce it):
scripts, so neither catalog is shown to the other script's locales.
- Spanish (`es`), complete.
- Russian (`ru`), complete, with three plural forms (`one|few|many`, see `plural_russian`).
- Korean (`ko`), complete, with one plural form.
- French (`fr`), complete, with two plural forms (0 and 1 use the singular).
- Czech (`cs`), complete, with three plural forms.
- Indonesian (`id`), complete, with one plural form.
- `tr(lang, s)` plain strings; `tr_ctx` when one English word needs different translations;
`tr_id(lang, command_id, label)` for menu items (keyed by command id, English label as the
@@ -97,6 +101,9 @@ the tests enforce it):
translators may reorder.
- The language is Preferences › Interface › Language (`interface.language`: `auto` or a language
code; `auto` follows the system locale, an unknown code falls back to `auto`).
- Language changes apply without a restart; Preferences previews the chosen language until
Apply or OK commits it. Cancel restores the committed language. Regional preference tags
resolve through the same locale matcher. See [`localization.md`](localization.md).
- To add a language: add `<code>.tsv` and one row in `i18n::LANGUAGES` (code, native name, catalog,
plural rule). The dropdown, locale matching and the catalog tests (well-formed, no duplicates,
placeholders and ellipses agree, command ids exist) pick it up. Set `complete_menus` once every
@@ -111,13 +118,16 @@ themselves). A test fails when a `tl!` literal, a menu string, a blend mode name
preference label has no entry in a language marked `complete_menus`. Not translated: status-bar
messages and errors (they stay English, also for agents), names that are user data (layers, styles,
documents), strings assembled with `format!` that were not converted to `fmt`/`trn`. Not done yet:
per-language font fallback (the CJK fallback prefers Japanese forms), right-to-left layout,
right-to-left layout,
locale-aware number and date formats, automatic language detection on the web build (native
builds read `LANG`/`LC_*`, the macOS preferred languages and the Windows user locale).
Camera Raw has explicit coverage for all seven available languages, including the partial
Simplified Chinese catalog. Its contextual `cameraRaw` entries distinguish tonal regions,
Camera Raw has explicit coverage for all ten available languages, including Korean and
Simplified Chinese. Its contextual `cameraRaw` entries distinguish tonal regions,
colour-band names and font-weight Light. The title uses a `{layer}` placeholder; user layer
names and the universal RGB/Lab channel symbols stay unchanged. Collapse IDs use English
source keys, so switching languages preserves open sections. Mixer tabs wrap within the
panel width. Catalog coverage and actual shell language-switch tests enforce these rules.
Native CJK font fallback follows the selected UI script and resets its cache when switching
languages; font delivery on the web remains separate work.