From 891514892aeb377c39732d09ddfa5053f834cfee Mon Sep 17 00:00:00 2001 From: justinjohn0306 <34035011+justinjohn0306@users.noreply.github.com> Date: Fri, 9 Oct 2026 10:13:44 +0530 Subject: [PATCH 1/8] CJK text renders as tofu: fall back to a system CJK font MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Japanese (or Chinese/Korean) workbook opened fine — the engine reads the strings correctly — but every kanji and kana drew as a .notdef box, because egui's bundled fonts carry no CJK coverage and nothing added a CJK face to the fallback chain. Append a system CJK face to every font family (UI, cell, serif, mono): a Japanese face first for correct kana/JIS kanji, a Chinese face for breadth, and a Hangul face for Korean. epaint picks the first face in a family that has the glyph, so Latin still renders from the Latin fonts and only Han/Kana/Hangul reach the CJK fonts. No font bytes are bundled (AGENTS.md): families are loaded from the OS, and a machine with no CJK font simply keeps the old behaviour. Tests: the CJK keys end every family chain (Latin stays first); and the proportional family resolves 「カテゴリ」 to real glyphs, not the replacement character — verified to fail without the fallback. --- crates/ui-egui/src/theme.rs | 101 ++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 2dbd8df7b0..e14b9f880b 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -292,6 +292,9 @@ pub fn font_definitions() -> FontDefinitions { let mut fonts = FontDefinitions::default(); let base_prop: Vec = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default(); let base_mono: Vec = fonts.families.get(&FontFamily::Monospace).cloned().unwrap_or_default(); + // CJK has to sit at the end of each chain: a Latin font owns Latin, and epaint picks the first + // face that has the glyph, so the CJK faces only ever catch Han/Kana/Hangul. + let cjk = load_cjk(&mut fonts); for role in [UI, UI_BOLD, CELL, CELL_BOLD, CELL_ITALIC, CELL_BOLD_ITALIC, SERIF, MONO] { let paths = candidates(role); let refs: Vec<(&str, u32)> = paths.iter().map(|(p, i)| (p.as_str(), *i)).collect(); @@ -306,6 +309,7 @@ pub fn font_definitions() -> FontDefinitions { chain.push(format!("sys-{CELL}")); } chain.extend(if role == MONO { base_mono.clone() } else { base_prop.clone() }); + chain.extend(cjk.iter().cloned()); chain.retain(|k| fonts.font_data.contains_key(k)); fonts.families.insert(FontFamily::Name(role.into()), chain); } @@ -316,6 +320,65 @@ pub fn font_definitions() -> FontDefinitions { fonts } +/// Loads the system CJK faces (Han/Kana and Hangul, one file each) and returns their keys so every +/// family can carry them as fallback. egui's bundled fonts have no CJK coverage, so without this a +/// Japanese or Chinese workbook renders as tofu boxes even though the text was read correctly. +#[cfg(not(target_arch = "wasm32"))] +fn load_cjk(fonts: &mut FontDefinitions) -> Vec { + let mut keys = Vec::new(); + for (key, cands) in [("sys-cjk-han", cjk_han()), ("sys-cjk-hangul", cjk_hangul())] { + let refs: Vec<(&str, u32)> = cands.iter().map(|(p, i)| (p.as_str(), *i)).collect(); + if let Some(fd) = try_load(&refs) { + fonts.font_data.insert(key.to_string(), Arc::new(fd)); + keys.push(key.to_string()); + } + } + keys +} + +#[cfg(target_arch = "wasm32")] +fn load_cjk(_fonts: &mut FontDefinitions) -> Vec { + Vec::new() +} + +/// Han + Kana faces, in fallback order. A Japanese face comes first (kana and JIS kanji render +/// with Japanese glyph shapes); a Chinese face follows to widen coverage. Every CJK face carries +/// kana, so any of them renders Japanese; the order only decides kanji glyph style. +#[cfg(not(target_arch = "wasm32"))] +fn cjk_han() -> Vec<(String, u32)> { + let mac = "/System/Library/Fonts"; + let win = std::env::var("WINDIR").map(|w| format!("{w}\\Fonts")).unwrap_or_else(|_| "C:\\Windows\\Fonts".into()); + let lin = ["/usr/share/fonts/opentype/noto", "/usr/share/fonts/truetype/noto", "/usr/share/fonts/truetype", "/usr/share/fonts"]; + let mut v: Vec<(String, u32)> = Vec::new(); + v.push((format!("{win}\\YuGothR.ttc"), 0)); // Yu Gothic (Japanese) + v.push((format!("{win}\\msgothic.ttc"), 0)); // MS Gothic (Japanese) + v.push((format!("{win}\\msyh.ttc"), 0)); // Microsoft YaHei (Chinese) + v.push((format!("{mac}/Hiragino Sans GB.ttc"), 0)); + v.push((format!("{mac}/PingFang.ttc"), 0)); + for d in lin { + v.push((format!("{d}/NotoSansCJK-Regular.ttc"), 0)); + v.push((format!("{d}/NotoSansCJKjp-Regular.otf"), 0)); + v.push((format!("{d}/wqy-microhei.ttc"), 0)); + } + v +} + +/// Hangul faces (Korean; not covered by the Han fonts). +#[cfg(not(target_arch = "wasm32"))] +fn cjk_hangul() -> Vec<(String, u32)> { + let mac = "/System/Library/Fonts"; + let win = std::env::var("WINDIR").map(|w| format!("{w}\\Fonts")).unwrap_or_else(|_| "C:\\Windows\\Fonts".into()); + let lin = ["/usr/share/fonts/truetype/noto", "/usr/share/fonts/opentype/noto", "/usr/share/fonts/truetype"]; + let mut v: Vec<(String, u32)> = Vec::new(); + v.push((format!("{win}\\malgun.ttf"), 0)); // Malgun Gothic + v.push((format!("{mac}/AppleSDGothicNeo.ttc"), 0)); + for d in lin { + v.push((format!("{d}/NotoSansCJKkr-Regular.otf"), 0)); + v.push((format!("{d}/NotoSansCJK-Regular.ttc"), 0)); + } + v +} + pub fn apply(ctx: &egui::Context, dark: bool) { let t = if dark { Tokens::dark() } else { Tokens::light() }; let mut v = if dark { Visuals::dark() } else { Visuals::light() }; @@ -351,3 +414,41 @@ pub fn apply(ctx: &egui::Context, dark: bool) { pub fn color32(rgb: [u8; 3]) -> Color32 { Color32::from_rgb(rgb[0], rgb[1], rgb[2]) } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + #[test] + fn cjk_fallback_is_appended_to_every_family() { + // Structural: whatever loaded, the CJK keys must sit at the end of each chain (after the + // Latin/default fonts) so Latin still wins for Latin text. + let fonts = font_definitions(); + let cjk_keys: Vec = + ["sys-cjk-han", "sys-cjk-hangul"].into_iter().filter(|k| fonts.font_data.contains_key(*k)).map(str::to_string).collect(); + if cjk_keys.is_empty() { + return; // no CJK face on this machine (minimal Linux) + } + for role in [UI, UI_BOLD, CELL, CELL_BOLD, CELL_ITALIC, CELL_BOLD_ITALIC, SERIF, MONO] { + let chain = fonts.families.get(&FontFamily::Name(role.into())).map(Vec::as_slice).unwrap_or_default(); + assert!(chain.len() >= cjk_keys.len(), "{role} chain too short for its CJK fallback"); + let tail = &chain[chain.len() - cjk_keys.len()..]; + assert_eq!(tail, cjk_keys.as_slice(), "{role} must end its chain with the CJK faces"); + } + } + + #[test] + fn cjk_fallback_covers_japanese() { + // Real render check: the proportional family (what cells and the UI use) must resolve + // Japanese kana/kanji to a glyph, not the tofu replacement char. + if cjk_han().iter().all(|(p, _)| std::fs::read(p).is_err()) { + return; // no CJK face on this machine (minimal Linux); nothing to assert + } + let ctx = egui::Context::default(); + ctx.set_fonts(font_definitions()); + let mut out = ctx.run_ui(egui::RawInput::default(), |_ui| {}); + out.textures_delta.clear(); // nothing consumes the atlas in a headless test + let covered = ctx.fonts_mut(|f| f.has_glyphs(&FontId::proportional(14.0), "カテゴリ")); + assert!(covered, "Japanese text must render with a real glyph, not tofu"); + } +} From 7e24aa398a8c9978d002c61fc21b530d6fb62857 Mon Sep 17 00:00:00 2001 From: justinjohn0306 Date: Fri, 9 Oct 2026 13:08:28 +0530 Subject: [PATCH 2/8] CI: satisfy newer clippy lints (toolchain drift, behavior-preserving) Local clippy 1.96 flags pre-existing patterns the code has always had: manual range-contains comparisons, a dead `|| true` filter and a simplifiable boolean. None change behaviour; they only clear the lints so `cargo xtask ci` passes on a current toolchain. --- crates/core/src/date.rs | 2 +- crates/engine/src/cmd/file.rs | 2 +- crates/functions/src/math.rs | 2 +- crates/functions/src/stat.rs | 2 +- crates/functions/src/util.rs | 2 +- crates/numfmt/src/render.rs | 2 +- crates/ui-egui/src/formula_bar.rs | 2 +- crates/ui-egui/src/grid.rs | 9 ++------- 8 files changed, 9 insertions(+), 14 deletions(-) diff --git a/crates/core/src/date.rs b/crates/core/src/date.rs index 7fba23fe58..167522ba8a 100644 --- a/crates/core/src/date.rs +++ b/crates/core/src/date.rs @@ -97,7 +97,7 @@ pub fn serial_from_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Opti /// Date/time from a serial. `None` for negative or too-large serials. pub fn datetime_from_serial(sys: DateSystem, serial: f64) -> Option { - if !serial.is_finite() || serial < 0.0 || serial >= 2_958_466.0 { + if !serial.is_finite() || !(0.0..2_958_466.0).contains(&serial) { return None; } let mut day = serial.floor() as i64; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 37a58dd63a..34b957cce1 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -48,7 +48,7 @@ fn open(s: &mut Session, p: &Json) -> Result { }; let (wb, warnings) = crate::io::open_bytes(&name, &bytes)?; let title = std::path::Path::new(&name).file_name().and_then(|n| n.to_str()).unwrap_or("Book").to_string(); - let path = str_param(p, "path").map(str::to_string).filter(|p| crate::io::FileKind::from_path(p) == Some(crate::io::FileKind::Xlsx) || true); + let path = str_param(p, "path").map(str::to_string); // Replace an untouched blank Book1 like Excel does. if s.documents().len() == 1 && s.active().is_some_and(|d| d.path.is_none() && !d.is_dirty() && d.undo.is_empty() && d.wb.sheets.iter().all(|sh| sh.cells.is_empty())) diff --git a/crates/functions/src/math.rs b/crates/functions/src/math.rs index 3a0bab3853..654395f4b6 100644 --- a/crates/functions/src/math.rs +++ b/crates/functions/src/math.rs @@ -487,7 +487,7 @@ fn integer_args(a: &[Arg]) -> R> { v.iter() .map(|x| { let t = x.trunc(); - if t < 0.0 || t >= 9.007_199_254_740_992e15 { Err(CellError::Num) } else { Ok(t as u64) } + if !(0.0..9.007_199_254_740_992e15).contains(&t) { Err(CellError::Num) } else { Ok(t as u64) } }) .collect() } diff --git a/crates/functions/src/stat.rs b/crates/functions/src/stat.rs index abdb4e731b..51a5f32721 100644 --- a/crates/functions/src/stat.rs +++ b/crates/functions/src/stat.rs @@ -1185,7 +1185,7 @@ fn binom_dist_range(a: &[Arg], _: C) -> R { let p = num(a, 1)?; let s1 = num(a, 2)?.trunc(); let s2 = if has(a, 3) { num(a, 3)?.trunc() } else { s1 }; - if n < 0.0 || n > 1e15 || !(0.0..=1.0).contains(&p) || s1 < 0.0 || s1 > n || s2 < s1 || s2 > n { + if !(0.0..=1e15).contains(&n) || !(0.0..=1.0).contains(&p) || s1 < 0.0 || s1 > n || s2 < s1 || s2 > n { return Err(CellError::Num); } if s2 - s1 > 10_000.0 { diff --git a/crates/functions/src/util.rs b/crates/functions/src/util.rs index fca5dc42a5..fbd6649311 100644 --- a/crates/functions/src/util.rs +++ b/crates/functions/src/util.rs @@ -51,7 +51,7 @@ pub(crate) fn arg(args: &[Arg], i: usize) -> R<&Arg> { /// Whether argument `i` was supplied (present and not an empty literal like `F(1,)`). pub(crate) fn has(args: &[Arg], i: usize) -> bool { - matches!(args.get(i), Some(a) if !(matches!(a.value, Value::Empty) && !a.from_ref)) + matches!(args.get(i), Some(a) if !matches!(a.value, Value::Empty) || a.from_ref) } /// Number coercion for a scalar parameter: empty = 0, TRUE = 1, numeric text parses. diff --git a/crates/numfmt/src/render.rs b/crates/numfmt/src/render.rs index 363dec1d31..79fe490f19 100644 --- a/crates/numfmt/src/render.rs +++ b/crates/numfmt/src/render.rs @@ -58,7 +58,7 @@ pub(crate) fn render_general(sec: &Section, v: f64, width: usize) -> Out { /// Renders a date/time. `None` when the serial is outside the supported range. pub(crate) fn render_date(sec: &Section, v: f64, sys: DateSystem) -> Option { - if !v.is_finite() || v < 0.0 || v >= 2_958_466.0 { + if !v.is_finite() || !(0.0..2_958_466.0).contains(&v) { return None; } let sub_digits = sec.toks.iter().filter_map(|t| if let Tok::Date(DatePart::SubSec(n)) = t { Some(*n) } else { None }).max().unwrap_or(0).min(3); diff --git a/crates/ui-egui/src/formula_bar.rs b/crates/ui-egui/src/formula_bar.rs index 753585f108..48141c346a 100644 --- a/crates/ui-egui/src/formula_bar.rs +++ b/crates/ui-egui/src/formula_bar.rs @@ -166,7 +166,7 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font: ed.caret_to_end = false; ed.sync_caret = true; } - if !ed.autocomplete.is_empty() && (tab || (enter && false)) { + if !ed.autocomplete.is_empty() && tab { ed.accept_autocomplete(); } else if enter { action = Some((if shift { -1 } else { 1 }, 0, false, false)); diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 4b326cc36f..4faf43a558 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -577,7 +577,7 @@ fn paint_quadrant( }; let indent = st.align.indent as f32 * 9.0 * z; let pad = 2.5 * z; - if st.align.wrap || st.align.h == HAlign::Justify || text.contains('\n') && st.align.wrap { + if st.align.wrap || st.align.h == HAlign::Justify { let wrap_w = (rect.width() - 2.0 * pad - indent).max(4.0); let mut job = egui::text::LayoutJob::simple(text.clone(), font.clone(), color, wrap_w); job.halign = match halign { @@ -1651,12 +1651,7 @@ fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo) { let Some(sh) = wb.sheet(si) else { return }; let _ = geo; // Tables get an autofilter on demand. - let table_range = sh - .tables - .iter() - .find(|t| t.range.start.row <= at.y as u32 || true) - .filter(|t| col >= t.range.start.col && col <= t.range.end.col) - .map(|t| t.range); + let table_range = sh.tables.first().filter(|t| col >= t.range.start.col && col <= t.range.end.col).map(|t| t.range); if sh.autofilter.is_none() && let Some(r) = table_range { From e8e010b446cd7a35eff0ee64298c44b158a4e09c Mon Sep 17 00:00:00 2001 From: justinjohn0306 Date: Fri, 9 Oct 2026 13:09:48 +0530 Subject: [PATCH 3/8] i18n: switch the interface language (issue #20) Add an interface-language preference. It defaults to the system's language on first run (sys-locale, native only) and is switched by hand from the View tab, next to Dark Mode, or with app.language.english / app.language.japanese over the control channel. It is saved in ui.json. Follows the filmcraft house convention: a Language enum and a table of English-to-Japanese strings with English fallback, so coverage can grow incrementally. Japanese chrome renders without any bundled font: the CJK fallback faces already appended to every family cover kana and kanji. The ribbon chrome all flows through the small_button/big_button/ toggle_button/split_button/icon_button helpers and menu_items, so translating there localises the whole ribbon in one place; the language of the frame is read from egui context data (i18n::current). Command ids, file names and document text are never translated. --- Cargo.lock | 10 + Cargo.toml | 2 + crates/ui-egui/Cargo.toml | 5 + crates/ui-egui/examples/snapshot.rs | 12 +- crates/ui-egui/src/i18n.rs | 382 ++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 25 ++ crates/ui-egui/src/ribbon.rs | 68 +++-- crates/ui-egui/src/tabs.rs | 8 +- crates/ui-egui/src/widgets.rs | 21 +- crates/ui-egui/tests/interaction.rs | 16 ++ 10 files changed, 517 insertions(+), 32 deletions(-) create mode 100644 crates/ui-egui/src/i18n.rs diff --git a/Cargo.lock b/Cargo.lock index 29bd97ae64..fd6140b92d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1528,6 +1528,7 @@ dependencies = [ "log", "serde", "serde_json", + "sys-locale", "toml", ] @@ -3187,6 +3188,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "libc", +] + [[package]] name = "tempfile" version = "3.27.0" diff --git a/Cargo.toml b/Cargo.toml index 89f268eadc..9c0c145300 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,6 +43,8 @@ eframe = { version = "0.36", default-features = false } egui_kittest = "0.36" rfd = "0.17" arboard = { version = "3.6", default-features = false } +# The desktop's preferred language, for the first-run interface language (native only). +sys-locale = "0.3" [workspace.lints.rust] unsafe_code = "forbid" diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 01d7c00700..ee77578f52 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -20,6 +20,11 @@ image = { workspace = true } [dev-dependencies] egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# The desktop's preferred language, for the first-run interface language. The web build has no +# system locale, so the crate is native-only (see i18n::Language::system). +sys-locale = { workspace = true } + [build-dependencies] serde_json = { workspace = true } toml = "1" diff --git a/crates/ui-egui/examples/snapshot.rs b/crates/ui-egui/examples/snapshot.rs index 28fba9ebf4..f384d183df 100644 --- a/crates/ui-egui/examples/snapshot.rs +++ b/crates/ui-egui/examples/snapshot.rs @@ -1,7 +1,7 @@ //! Renders the whole GridCraft window offscreen (wgpu, no window) to a PNG. //! //! `cargo run --release -p gridcraft-ui-egui --example snapshot -- [--sample sales] [--in file.xlsx] -//! [--size 1440x900] [--scale 2] [--cmd 'id={json}']... [--tab Insert] [--dark] +//! [--size 1440x900] [--scale 2] [--cmd 'id={json}']... [--tab Insert] [--dark] [--language ja] //! [--dialog 'name={json}'] out.png` use gridcraft_engine::Session; @@ -20,6 +20,7 @@ fn main() { let mut pane: Option = None; let mut chart: Option = None; let mut dialog: Option = None; + let mut language: Option = None; let mut out = "snapshot.png".to_string(); let mut i = 0; while i < args.len() { @@ -65,6 +66,10 @@ fn main() { i += 1; dialog = args.get(i).cloned(); } + "--language" => { + i += 1; + language = args.get(i).cloned(); + } other => out = other.to_string(), } i += 1; @@ -93,6 +98,11 @@ fn main() { { let mut app = SheetApp::new(session, Default::default()); app.ui.dark = dark; + if let Some(code) = &language + && let Some(l) = gridcraft_ui_egui::i18n::Language::parse(code) + { + app.ui.language = l; + } if let Some(t) = tab { app.ui.ribbon_tab = t; } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs new file mode 100644 index 0000000000..48e809dd90 --- /dev/null +++ b/crates/ui-egui/src/i18n.rs @@ -0,0 +1,382 @@ +//! Interface translations. Command ids and document text stay stable; only interface chrome is +//! translated. Untranslated labels fall back to English, so coverage can grow incrementally. +//! +//! The interface language is a preference ([`crate::UiState::language`]): on first run it defaults +//! to the system's language ([`Language::system`]), and the View tab switches it by hand. +//! +//! No Japanese font is bundled and none is installed here: the CJK faces [`crate::theme`] appends +//! to every family already cover kana and kanji, so Japanese interface text renders without help. + +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Language { + #[default] + En, + Ja, +} + +impl Language { + pub const ALL: [Self; 2] = [Self::En, Self::Ja]; + + /// The language's own name, shown in the switcher. + pub fn name(self) -> &'static str { + match self { + Self::En => "English", + Self::Ja => "日本語", + } + } + + pub fn parse(code: &str) -> Option { + match code { + "en" => Some(Self::En), + "ja" => Some(Self::Ja), + _ => None, + } + } + + /// A language tag (`ja`, `ja-JP`, `en_US`) reduced to a supported language. Native only: the web + /// build has no system locale to read and tests exercise it on the host. + #[cfg(not(target_arch = "wasm32"))] + fn from_tag(tag: &str) -> Option { + Self::parse(&tag.split(['-', '_']).next().unwrap_or("").to_ascii_lowercase()) + } + + /// The system's preferred interface language, best effort; English when it is unknown or + /// unsupported. Used as the first-run default while nothing is saved. + pub fn system() -> Self { + #[cfg(not(target_arch = "wasm32"))] + { + sys_locale::get_locale().and_then(|tag| Self::from_tag(&tag)).unwrap_or(Self::En) + } + #[cfg(target_arch = "wasm32")] + { + Self::En + } + } + + pub fn tr(self, text: &str) -> &str { + if self == Self::Ja + && let Some((_, japanese)) = JAPANESE.iter().find(|(english, _)| *english == text) + { + return japanese; + } + text + } +} + +/// egui context-data key holding the language of the frame being drawn. Widgets that only get a +/// `Ui` (not the app) read it to translate their labels; [`set_current`] writes it once per frame. +fn lang_key() -> egui::Id { + egui::Id::new("gridcraft.language") +} + +/// The language the current frame is drawing in. `En` when unset. +pub fn current(ctx: &egui::Context) -> Language { + ctx.data(|d| d.get_temp(lang_key())).unwrap_or_default() +} + +/// Sets the language for the current frame; call once per frame before anything is drawn. +pub fn set_current(ctx: &egui::Context, language: Language) { + ctx.data_mut(|d| d.insert_temp(lang_key(), language)); +} + +/// English label → Japanese. Keys are the exact interface strings (command ids, file names and +/// document text are never translated); anything absent falls back to English. +const JAPANESE: &[(&str, &str)] = &[ + ("Paste", "貼り付け"), + ("Paste Values", "値の貼り付け"), + ("Paste Formulas", "数式の貼り付け"), + ("Paste Formatting", "書式の貼り付け"), + ("Transpose", "行列を入れ替え"), + ("Paste Link", "リンクの貼り付け"), + ("Paste Special…", "形式を選択して貼り付け…"), + ("Cut (⌘X)", "切り取り (⌘X)"), + ("Copy (⌘C)", "コピー (⌘C)"), + ("Format Painter (double-click to keep it on)", "書式のコピー/貼り付け (ダブルクリックで固定)"), + ("Bold (⌘B)", "太字 (⌘B)"), + ("Italic (⌘I)", "斜体 (⌘I)"), + ("Underline (⌘U)", "下線 (⌘U)"), + ("Double Underline", "二重下線"), + ("Strikethrough", "取り消し線"), + ("Underline", "下線"), + ("Increase Font Size", "フォントの拡大"), + ("Decrease Font Size", "フォントの縮小"), + ("Wrap Text", "折り返して全体を表示"), + ("Merge & Center", "セルを結合して中央揃え"), + ("Merge Cells", "セルの結合"), + ("Merge Across", "横方向に結合"), + ("Unmerge Cells", "セル結合の解除"), + ("Fill Color", "塗りつぶしの色"), + ("Font Color", "フォントの色"), + ("Borders", "罫線"), + ("Top\nAlign", "上揃え"), + ("Middle\nAlign", "中央揃え (縦)"), + ("Bottom\nAlign", "下揃え"), + ("Left", "左"), + ("Right", "右"), + ("Center", "中央"), + ("Horizontal", "水平"), + ("Vertical Text", "縦書き"), + ("Decrease Indent", "インデントを減らす"), + ("Increase Indent", "インデントを増やす"), + ("Orientation", "印刷の向き"), + ("Angle Counterclockwise", "左回りに回転"), + ("Angle Clockwise", "右回りに回転"), + ("Rotate Text Up", "文字列を上に回転"), + ("Rotate Text Down", "文字列を下に回転"), + ("Accounting Number Format", "通貨表示形式"), + ("Percent Style", "パーセント表示"), + ("Comma Style", "桁区切りスタイル"), + ("Increase Decimal", "小数点以下の桁数を増やす"), + ("Decrease Decimal", "小数点以下の桁数を減らす"), + ("More Accounting Formats…", "その他の通貨表示形式…"), + ("Conditional\nFormatting", "条件付き書式"), + ("Conditional Formatting", "条件付き書式"), + ("Format\nas Table", "テーブルとして書式設定"), + ("Cell\nStyles", "セルのスタイル"), + ("Format Cells…", "セルの書式設定…"), + ("Format Cell Alignment…", "セルの配置…"), + ("Format\nPane", "書式ウィンドウ"), + ("Format", "書式"), + ("Insert", "挿入"), + ("Insert Cells…", "セルの挿入…"), + ("Delete", "削除"), + ("Delete Cells…", "セルの削除…"), + ("Insert Sheet Rows", "シートの行を挿入"), + ("Insert Sheet Columns", "シートの列を挿入"), + ("Delete Sheet Rows", "シートの行を削除"), + ("Delete Sheet Columns", "シートの列を削除"), + ("Row Height…", "行の高さ…"), + ("AutoFit Row Height", "行の高さを自動調整"), + ("Column Width…", "列の幅…"), + ("AutoFit Column Width", "列の幅を自動調整"), + ("Default Width…", "標準の幅…"), + ("Hide Rows", "行の表示/非表示"), + ("Unhide Rows", "再表示"), + ("Hide Columns", "列の表示/非表示"), + ("Unhide Columns", "再表示"), + ("Lock Cell", "セルのロック"), + ("Clear", "クリア"), + ("Clear All", "すべてクリア"), + ("Clear Formats", "書式のクリア"), + ("Clear Contents", "数式と値のクリア"), + ("Clear Comments and Notes", "コメントとメモのクリア"), + ("Clear Hyperlinks", "ハイパーリンクのクリア"), + ("AutoSum", "オート SUM"), + ("AutoSum (⌘⇧T)", "オート SUM (⌘⇧T)"), + ("Flash\nFill", "フラッシュ フィル"), + ("Flash Fill", "フラッシュ フィル"), + ("Fill", "フィル"), + ("Clear Print Area", "印刷範囲のクリア"), + ("Find &\nSelect", "検索と選択"), + ("Find…", "検索…"), + ("Replace…", "置換…"), + ("Go To…", "ジャンプ…"), + ("Go To Special…", "セルを選択…"), + ("PivotTable", "ピボットテーブル"), + ("Recommended\nCharts", "推奨グラフ"), + ("Table", "テーブル"), + ("Pictures", "画像"), + ("Shapes", "図形"), + ("Icons", "アイコン"), + ("Text\nBox", "テキスト ボックス"), + ("Comment", "コメント"), + ("New\nComment", "新しいコメント"), + ("New Note", "新しいメモ"), + ("Show/Hide Note", "メモの表示/非表示"), + ("Header &\nFooter", "ヘッダーとフッター"), + ("Text to\nColumns", "区切り位置"), + ("Link", "リンク"), + ("Symbol", "記号"), + ("Sparklines", "スパークライン"), + ("Header & Footer", "ヘッダーとフッター"), + ("Draw with ink", "インクで描画"), + ("Eraser", "消しゴム"), + ("Ink to\nShape", "インクを図形に変換"), + ("Select\nObjects", "オブジェクトの選択"), + ("Themes", "テーマ"), + ("Margins", "余白"), + ("Size", "サイズ"), + ("Print\nArea", "印刷範囲"), + ("Set Print Area", "印刷範囲の設定"), + ("Breaks", "改ページ"), + ("Insert Page Break", "改ページの挿入"), + ("Remove Page Break", "改ページの解除"), + ("Reset All Page Breaks", "すべての改ページを解除"), + ("Print\nTitles", "印刷タイトル"), + ("Narrow", "狭い"), + ("Wide", "広い"), + ("Normal", "標準"), + ("Portrait", "縦"), + ("Landscape", "横"), + ("Custom Margins…", "ユーザー設定の余白…"), + ("Insert\nFunction", "関数の挿入"), + ("Name\nManager", "名前の管理"), + ("Define Name", "名前の定義"), + ("Use in Formula", "数式で使用"), + ("Create from Selection", "選択範囲から作成"), + ("Trace Precedents", "参照元のトレース"), + ("Trace Dependents", "依存元のトレース"), + ("Remove Arrows", "矢印の解除"), + ("Show Formulas", "数式の表示"), + ("Error Checking", "エラーチェック"), + ("Evaluate Formula", "数式の検証"), + ("Watch Window", "ウォッチ ウィンドウ"), + ("Calculation\nOptions", "計算方法の設定"), + ("Calculate Now", "再計算実行"), + ("Calculate Sheet", "シートの再計算"), + ("Automatic", "自動"), + ("Automatic Except for Data Tables", "データ テーブル以外は自動"), + ("Manual", "手動"), + ("Sort &\nFilter", "並べ替えとフィルター"), + ("Sort", "並べ替え"), + ("Sort A to Z", "昇順"), + ("Sort Z to A", "降順"), + ("Custom Sort…", "ユーザー設定の並べ替え…"), + ("Filter", "フィルター"), + ("Reapply", "再適用"), + ("Get Data\n(Text/CSV)", "データの取得 (テキスト/CSV)"), + ("Remove\nDuplicates", "重複の削除"), + ("Data\nValidation", "データの入力規則"), + ("Data Validation", "データの入力規則"), + ("Data Validation…", "データの入力規則…"), + ("Circle Invalid Data", "無効なデータをマーク"), + ("Clear Validation", "入力規則のクリア"), + ("Group", "グループ化"), + ("Ungroup", "グループ解除"), + ("Subtotal", "小計"), + ("What-If\nAnalysis", "What-If 分析"), + ("Data Table…", "データ テーブル…"), + ("Scenario Manager…", "シナリオ マネージャー…"), + ("Goal Seek…", "ゴール シーク…"), + ("Spelling", "スペルチェック"), + ("Check\nAccessibility", "アクセシビリティ チェック"), + ("Threaded Comments", "スレッド化されたコメント"), + ("Show\nComments", "コメントの表示"), + ("Protect\nWorkbook", "ブックの保護"), + ("Unprotect\nSheet", "シート保護の解除"), + ("Protect Sheet…", "シートの保護…"), + ("Comments", "コメント"), + ("Notes", "メモ"), + ("Page Break\nPreview", "改ページ プレビュー"), + ("Page\nLayout", "ページ レイアウト"), + ("Formula Bar", "数式バー"), + ("Gridlines", "目盛線"), + ("Headings", "見出し"), + ("Zoom", "ズーム"), + ("100%", "100%"), + ("Zoom to\nSelection", "選択範囲を拡大"), + ("Freeze\nPanes", "ウィンドウ枠の固定"), + ("Freeze Panes", "ウィンドウ枠の固定"), + ("Freeze Top Row", "最上行の固定"), + ("Freeze First Column", "最左列の固定"), + ("Unfreeze Panes", "ウィンドウ枠固定の解除"), + ("Dark Mode", "ダーク モード"), + ("Interface language", "表示言語"), + ("Command\nPalette", "コマンド パレット"), + ("Agent\nControl", "エージェント制御"), + ("Action\nJournal", "操作ジャーナル"), + ("About\nGridCraft", "GridCraft について"), + ("Share", "共有"), + ("Add Chart\nElement", "グラフ要素を追加"), + ("Change\nChart Type", "グラフの種類の変更"), + ("Switch\nRow/Column", "行/列の切り替え"), + ("Data Labels: None", "データ ラベル: なし"), + ("Data Labels: Show", "データ ラベル: 表示"), + ("Legend: None", "凡例: なし"), + ("Legend: Bottom", "凡例: 下"), + ("Legend: Top", "凡例: 上"), + ("Legend: Right", "凡例: 右"), + ("Gridlines: None", "目盛線: なし"), + ("Gridlines: Show", "目盛線: 表示"), + ("Chart\nTitle", "グラフ タイトル"), + ("Delete\nChart", "グラフの削除"), + ("Convert\nto Range", "範囲に変換"), + ("Table\nStyles", "テーブル スタイル"), + ("Top 10 Items", "上位 10 項目"), + ("Top 10%", "上位 10%"), + ("Bottom 10 Items", "下位 10 項目"), + ("Bottom 10%", "下位 10%"), + ("Above Average", "平均より上"), + ("Below Average", "平均より下"), + ("Clear Rules from Entire Sheet", "シート全体からルールをクリア"), + ("Clear Rules from Selected Cells", "選択したセルからルールをクリア"), + ("Constants", "定数"), + ("Data Bars", "データ バー"), + ("Color Scales", "カラー スケール"), + ("Icon Sets", "アイコン セット"), + ("Home", "ホーム"), + ("Draw", "描画"), + ("Page Layout", "ページ レイアウト"), + ("Formulas", "数式"), + ("Data", "データ"), + ("Review", "レビュー"), + ("View", "表示"), + ("Automate", "自動化"), + ("Table Design", "テーブル デザイン"), + ("Chart Design", "グラフ デザイン"), + ("Ready", "準備完了"), + ("Enter", "入力"), + ("Edit", "編集"), + ("Point", "ポイント"), + ("Calculate", "計算"), + ("Select destination and press Enter or choose Paste", "貼り付け先を選び、Enter キーを押すか [貼り付け] を選びます"), + ("General", "標準"), + ("Number", "数値"), + ("Currency", "通貨"), + ("Accounting", "会計"), + ("Date", "日付"), + ("Time", "時刻"), + ("Percentage", "パーセンテージ"), + ("Fraction", "分数"), + ("Scientific", "指数"), + ("Text", "文字列"), + ("Special", "特殊"), + ("Custom", "ユーザー設定"), + ("Short Date", "日付"), + ("Long Date", "長い日付"), + ("More Number Formats…", "その他の表示形式…"), + ("Financial", "財務"), + ("Logical", "論理"), + ("Date &\nTime", "日付/時刻"), + ("Lookup &\nReference", "検索/行列"), + ("Math &\nTrig", "数学/三角"), + ("More\nFunctions", "その他の関数"), +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn translations_are_unique_and_preserve_unknown_text() { + for (i, (en, ja)) in JAPANESE.iter().enumerate() { + assert!(!ja.is_empty()); + assert!(JAPANESE.iter().take(i).all(|(other, _)| en != other)); + assert_eq!(Language::En.tr(en), *en); + } + assert_eq!(Language::Ja.tr("Data"), "データ"); + assert_eq!(Language::Ja.tr("Sheet1!A1"), "Sheet1!A1"); + assert_eq!(Language::parse("xx"), None); + } + + #[test] + fn tags_reduce_to_a_supported_language() { + assert_eq!(Language::from_tag("ja-JP"), Some(Language::Ja)); + assert_eq!(Language::from_tag("en_US"), Some(Language::En)); + assert_eq!(Language::from_tag("de-DE"), None); + } + + #[test] + fn language_commands_switch_and_persist() { + let mut app = crate::SheetApp::new(gridcraft_engine::Session::default(), Default::default()); + app.run("app.language.japanese", serde_json::json!({})).unwrap(); + assert_eq!(app.ui.language, Language::Ja); + let restored: crate::UiState = serde_json::from_str(&serde_json::to_string(&app.ui).unwrap()).unwrap(); + assert_eq!(restored.language, Language::Ja); + app.run("app.language.english", serde_json::json!({})).unwrap(); + assert_eq!(app.ui.language, Language::En); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8eb1eca1ac..4e7a383e4a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -13,6 +13,7 @@ pub mod dialogs; pub mod editor; pub mod formula_bar; pub mod grid; +pub mod i18n; pub mod icons; pub mod panes; pub mod pivot_pane; @@ -41,6 +42,9 @@ pub struct UiState { pub formula_bar_expanded: bool, pub status_bar: bool, pub recent: Vec, + /// Interface language. Absent in older `ui.json` → the system's language (English fallback). + #[serde(default = "i18n::Language::system")] + pub language: i18n::Language, } impl Default for UiState { @@ -53,6 +57,7 @@ impl Default for UiState { formula_bar_expanded: false, status_bar: true, recent: vec![], + language: i18n::Language::system(), } } } @@ -187,6 +192,24 @@ impl SheetApp { Ok(json!({"on": self.ui.dark})) } "view.zoom100" => return Some(self.session.run("view.zoom", json!({"percent": 100})).inspect(|_| self.after_engine())), + "app.language.set" => { + let code = p.get("language").and_then(Json::as_str).and_then(i18n::Language::parse); + match code { + Some(l) => { + self.ui.language = l; + Ok(json!({"language": l})) + } + None => Err(format!("unknown language {:?} (use \"en\" or \"ja\")", p.get("language").and_then(Json::as_str).unwrap_or(""))), + } + } + "app.language.english" => { + self.ui.language = i18n::Language::En; + Ok(json!({"language": i18n::Language::En})) + } + "app.language.japanese" => { + self.ui.language = i18n::Language::Ja; + Ok(json!({"language": i18n::Language::Ja})) + } "ui.dialog" => { let name = p.get("name").and_then(Json::as_str).unwrap_or(""); self.open_dialog(name, p.clone()); @@ -399,6 +422,8 @@ impl SheetApp { return; } let t0 = now_ms(); + // The language the widgets translate with this frame (see `i18n::current`). + i18n::set_current(&ctx, self.ui.language); let t = theme::Tokens::get(&ctx); ribbon::title_bar(self, ui); ribbon::show(self, ui); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 47c5432b41..52bc34b809 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -139,7 +139,8 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) { let active = app.ui.ribbon_tab == tab; let contextual = ctx_tabs.contains(&tab); let font = theme::ui_font(13.5); - let tw = ui.painter().layout_no_wrap(tab.to_string(), font.clone(), t.text).size().x; + let label = app.ui.language.tr(tab); + let tw = ui.painter().layout_no_wrap(label.to_string(), font.clone(), t.text).size().x; let (r, resp) = ui.allocate_exact_size(vec2(tw + 22.0, 30.0), Sense::click()); if resp.hovered() && !active { ui.painter().rect_filled(r.shrink2(vec2(2.0, 4.0)), 5.0, t.hover); @@ -151,7 +152,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) { } else { t.text_dim }; - ui.painter().text(r.center(), Align2::CENTER_CENTER, tab, if active { theme::ui_bold(13.5) } else { font }, color); + ui.painter().text(r.center(), Align2::CENTER_CENTER, label, if active { theme::ui_bold(13.5) } else { font }, color); if active { let ul = Rect::from_center_size(pos2(r.center().x, r.bottom() - 3.0), vec2(tw.clamp(20.0, 40.0), 3.0)); ui.painter().rect_filled(ul, 1.5, t.accent); @@ -248,7 +249,8 @@ fn menu_items(app: &mut SheetApp, ui: &mut Ui, items: &[(&str, &str, serde_json: ui.separator(); continue; } - if ui.add(egui::Button::new(*label).frame(false).min_size(vec2(220.0, 22.0))).clicked() { + let lang = app.ui.language; + if ui.add(egui::Button::new(lang.tr(label)).frame(false).min_size(vec2(220.0, 22.0))).clicked() { if let Some(d) = id.strip_prefix("dialog:") { app.open_dialog(d, p.clone()); } else { @@ -445,7 +447,7 @@ fn home(app: &mut SheetApp, ui: &mut Ui) { if wrap.clicked() { act(app, "home.wrapText", json!({})); } - ui.label(egui::RichText::new("Wrap Text").font(theme::ui_font(12.5))); + ui.label(egui::RichText::new(app.ui.language.tr("Wrap Text")).font(theme::ui_font(12.5))); }); ui.horizontal(|ui| { for (icon, h, id, tip) in [ @@ -467,7 +469,7 @@ fn home(app: &mut SheetApp, ui: &mut Ui) { if m { act(app, "home.mergeCenter", json!({})); } - ui.label(egui::RichText::new("Merge & Center").font(theme::ui_font(12.5))); + ui.label(egui::RichText::new(app.ui.language.tr("Merge & Center")).font(theme::ui_font(12.5))); egui::Popup::menu(&ma).show(|ui| { menu_items( app, @@ -736,27 +738,28 @@ fn number_combo(app: &mut SheetApp, ui: &mut Ui, st: &Style) { let code = st.num_fmt.as_str().to_string(); let kind = gridcraft_engine::display::number_format(&code).kind(); let current = format!("{kind:?}"); + let lang = app.ui.language; let sample = app.session.active().and_then(|d| d.wb.active().map(|sh| sh.value(d.selection.active))).unwrap_or_default(); let mut picked: Option<&str> = None; - egui::ComboBox::from_id_salt("number_format").width(150.0).selected_text(egui::RichText::new(¤t).font(theme::ui_font(12.5))).show_ui( - ui, - |ui| { + egui::ComboBox::from_id_salt("number_format") + .width(150.0) + .selected_text(egui::RichText::new(lang.tr(¤t)).font(theme::ui_font(12.5))) + .show_ui(ui, |ui| { for name in ["General", "Number", "Currency", "Accounting", "Short Date", "Long Date", "Time", "Percentage", "Fraction", "Scientific", "Text"] { let code = gridcraft_engine::cmd::format::format_code_for(name); let preview = app.session.active().map(|d| gridcraft_engine::display::format(&sample, code, &d.wb).text).unwrap_or_default(); - let r = ui.add(egui::Button::selectable(current == name, format!("{name:<12} {preview}")).min_size(vec2(240.0, 22.0))); + let r = ui.add(egui::Button::selectable(current == name, format!("{:<12} {preview}", lang.tr(name))).min_size(vec2(240.0, 22.0))); if r.clicked() { picked = Some(name); } } ui.separator(); - if ui.button("More Number Formats…").clicked() { + if ui.button(lang.tr("More Number Formats…")).clicked() { picked = Some("__more"); } - }, - ); + }); match picked { Some("__more") => app.open_dialog("formatCells", json!({"tab": "Number"})), Some(n) => act(app, "home.numberFormat", json!({"format": n})), @@ -1263,25 +1266,28 @@ fn page_layout(app: &mut SheetApp, ui: &mut Ui) { .active() .and_then(|d| d.wb.active().map(|s| (s.show_gridlines, s.show_headings, s.print.gridlines, s.print.headings))) .unwrap_or((true, true, false, false)); + // These two checkboxes mean the screen view vs. the printed page, so they do not share the + // "View" tab label; pick per language rather than through the shared table. + let (screen, print) = if app.ui.language == crate::i18n::Language::Ja { ("画面", "印刷") } else { ("View", "Print") }; ui.vertical(|ui| { - ui.label(egui::RichText::new("Gridlines").strong().small()); + ui.label(egui::RichText::new(app.ui.language.tr("Gridlines")).strong().small()); let mut v = sh.0; - if ui.checkbox(&mut v, "View").changed() { + if ui.checkbox(&mut v, screen).changed() { act(app, "view.gridlines", json!({"on": v})); } let mut p = sh.2; - if ui.checkbox(&mut p, "Print").changed() { + if ui.checkbox(&mut p, print).changed() { act(app, "pageLayout.printGridlines", json!({"on": p})); } }); ui.vertical(|ui| { - ui.label(egui::RichText::new("Headings").strong().small()); + ui.label(egui::RichText::new(app.ui.language.tr("Headings")).strong().small()); let mut v = sh.1; - if ui.checkbox(&mut v, "View").changed() { + if ui.checkbox(&mut v, screen).changed() { act(app, "view.headings", json!({"on": v})); } let mut p = sh.3; - if ui.checkbox(&mut p, "Print").changed() { + if ui.checkbox(&mut p, print).changed() { act(app, "pageLayout.printHeadings", json!({"on": p})); } }); @@ -1526,17 +1532,18 @@ fn view(app: &mut SheetApp, ui: &mut Ui) { } sep(ui); let s = app.session.active().and_then(|d| d.wb.active().map(|s| (s.show_gridlines, s.show_headings))).unwrap_or((true, true)); + let lang = app.ui.language; ui.vertical(|ui| { let mut fb = app.ui.formula_bar; - if ui.checkbox(&mut fb, "Formula Bar").changed() { + if ui.checkbox(&mut fb, lang.tr("Formula Bar")).changed() { app.ui.formula_bar = fb; } let mut g = s.0; - if ui.checkbox(&mut g, "Gridlines").changed() { + if ui.checkbox(&mut g, lang.tr("Gridlines")).changed() { act(app, "view.gridlines", json!({"on": g})); } let mut h = s.1; - if ui.checkbox(&mut h, "Headings").changed() { + if ui.checkbox(&mut h, lang.tr("Headings")).changed() { act(app, "view.headings", json!({"on": h})); } }); @@ -1567,10 +1574,27 @@ fn view(app: &mut SheetApp, ui: &mut Ui) { }); let mut dark = app.ui.dark; ui.vertical(|ui| { - if ui.checkbox(&mut dark, "Dark Mode").changed() { + if ui.checkbox(&mut dark, lang.tr("Dark Mode")).changed() { app.ui.dark = dark; } }); + sep(ui); + // Interface language: settings live in the View tab, like Excel's Options. The label follows + // the current language so it stays readable; the choices are always shown in their own script. + ui.vertical(|ui| { + ui.label(egui::RichText::new(lang.tr("Interface language")).font(theme::ui_font(11.5)).color(t.text_dim)); + egui::ComboBox::from_id_salt("ui_language").width(120.0).selected_text(egui::RichText::new(lang.name()).font(theme::ui_font(12.5))).show_ui( + ui, + |ui| { + for l in crate::i18n::Language::ALL { + if ui.selectable_label(l == lang, l.name()).clicked() { + let code = if l == crate::i18n::Language::Ja { "app.language.japanese" } else { "app.language.english" }; + act(app, code, json!({})); + } + } + }, + ); + }); } fn automate(app: &mut SheetApp, ui: &mut Ui) { diff --git a/crates/ui-egui/src/tabs.rs b/crates/ui-egui/src/tabs.rs index 0258169def..e4a4068f75 100644 --- a/crates/ui-egui/src/tabs.rs +++ b/crates/ui-egui/src/tabs.rs @@ -190,11 +190,11 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) { gridcraft_engine::Mode::Edit => "Edit", gridcraft_engine::Mode::Point => "Point", }; - ui.label(egui::RichText::new(mode).font(theme::ui_font(12.5)).color(t.text_dim)); + ui.label(egui::RichText::new(app.ui.language.tr(mode)).font(theme::ui_font(12.5)).color(t.text_dim)); if let Some(d) = app.session.active() { if d.wb.calc.mode == gridcraft_engine::model::CalcMode::Manual { ui.add_space(12.0); - ui.label(egui::RichText::new("Calculate").font(theme::ui_font(12.5)).color(t.text_dim)); + ui.label(egui::RichText::new(app.ui.language.tr("Calculate")).font(theme::ui_font(12.5)).color(t.text_dim)); } if !d.calc.circular.is_empty() { ui.add_space(12.0); @@ -205,7 +205,9 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) { if app.session.clipboard.is_some() && app.editor.is_none() { ui.add_space(12.0); ui.label( - egui::RichText::new("Select destination and press Enter or choose Paste").font(theme::ui_font(12.5)).color(t.text_dim), + egui::RichText::new(app.ui.language.tr("Select destination and press Enter or choose Paste")) + .font(theme::ui_font(12.5)) + .color(t.text_dim), ); } } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 139256ffc9..058eca997c 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -4,9 +4,16 @@ use egui::{Align2, Color32, Rect, Response, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; use crate::SheetApp; +use crate::i18n; use crate::icons::{self, Icon}; use crate::theme::{self, Tokens}; +/// Translates a label or tooltip for the language of the frame being drawn (English if untranslated). +/// Ribbon chrome all flows through these widgets, so translating here localises it in one place. +fn tr<'a>(ui: &Ui, text: &'a str) -> &'a str { + i18n::current(ui.ctx()).tr(text) +} + /// A flat square icon button with hover highlight and tooltip. pub fn icon_button(ui: &mut Ui, icon: Icon, color: Color32, tip: &str, size: egui::Vec2) -> Response { let (rect, resp) = ui.allocate_exact_size(size, Sense::click()); @@ -17,7 +24,7 @@ pub fn icon_button(ui: &mut Ui, icon: Icon, color: Color32, tip: &str, size: egu ui.painter().rect_filled(rect, 4.0, t.hover); } icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(16.0, 16.0)), icon, color); - resp.on_hover_text(tip) + resp.on_hover_text(tr(ui, tip)) } /// A toggle-able small button (e.g. Bold) showing a checked state. @@ -31,13 +38,14 @@ pub fn toggle_button(ui: &mut Ui, icon: Icon, on: bool, tip: &str) -> Response { ui.painter().rect_filled(rect, 4.0, t.hover); } icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(16.0, 16.0)), icon, t.text); - resp.on_hover_text(tip) + resp.on_hover_text(tr(ui, tip)) } /// Large ribbon button: 32px icon over a one- or two-line label. pub fn big_button(ui: &mut Ui, icon: Icon, label: &str, tip: &str, dropdown: bool) -> Response { let t = Tokens::get(ui.ctx()); let font = theme::ui_font(11.5); + let label = tr(ui, label); let lines: Vec<&str> = label.split('\n').collect(); let text_w = lines.iter().map(|l| ui.painter().layout_no_wrap(l.to_string(), font.clone(), t.text).size().x).fold(0.0, f32::max); let w = (text_w + 12.0).max(44.0); @@ -49,19 +57,20 @@ pub fn big_button(ui: &mut Ui, icon: Icon, label: &str, tip: &str, dropdown: boo } icons::paint(ui.painter(), Rect::from_center_size(pos2(rect.center().x, rect.top() + 21.0), vec2(30.0, 30.0)), icon, t.text); for (i, l) in lines.iter().enumerate() { - let mut s = l.to_string(); + let mut s = (*l).to_string(); if dropdown && i + 1 == lines.len() { s.push_str(" ▾"); } ui.painter().text(pos2(rect.center().x, rect.top() + 46.0 + i as f32 * 13.0), Align2::CENTER_CENTER, s, font.clone(), t.text); } - resp.on_hover_text(tip) + resp.on_hover_text(tr(ui, tip)) } /// Small ribbon button: 16px icon with optional label to the right. pub fn small_button(ui: &mut Ui, icon: Icon, label: &str, tip: &str, dropdown: bool) -> Response { let t = Tokens::get(ui.ctx()); let font = theme::ui_font(12.5); + let label = tr(ui, label); let tw = if label.is_empty() { 0.0 } else { ui.painter().layout_no_wrap(label.to_string(), font.clone(), t.text).size().x + 6.0 }; let w = 24.0 + tw + if dropdown { 12.0 } else { 0.0 }; let (rect, resp) = ui.allocate_exact_size(vec2(w, 23.0), Sense::click()); @@ -82,7 +91,7 @@ pub fn small_button(ui: &mut Ui, icon: Icon, label: &str, tip: &str, dropdown: b t.text_dim, ); } - resp.on_hover_text(tip) + resp.on_hover_text(tr(ui, tip)) } /// A split button: main part runs the default action, the arrow opens a menu. @@ -103,7 +112,7 @@ pub fn split_button(ui: &mut Ui, icon: Icon, accent: Option, tip: &str) ui.painter().rect_filled(Rect::from_min_size(pos2(main.left() + 4.0, main.bottom() - 5.0), vec2(17.0, 3.0)), 0.0, c); } icons::paint(ui.painter(), Rect::from_center_size(arrow.center(), vec2(10.0, 10.0)), Icon::Chevron, t.text_dim); - (m.on_hover_text(tip).clicked(), a) + (m.on_hover_text(tr(ui, tip)).clicked(), a) } /// Our colour palette (theme row + tints + standard colours), returns a picked hex colour, diff --git a/crates/ui-egui/tests/interaction.rs b/crates/ui-egui/tests/interaction.rs index 74bbeb4950..63cdc81200 100644 --- a/crates/ui-egui/tests/interaction.rs +++ b/crates/ui-egui/tests/interaction.rs @@ -98,6 +98,22 @@ fn renders_every_ribbon_tab_without_panicking() { h.run_steps(3); } +#[test] +fn language_switch_translates_the_ribbon_and_persists() { + use gridcraft_ui_egui::i18n::Language; + let mut h = harness(blank()); + // English by default on a machine whose system language is not Japanese. + assert_ne!(h.state().ui.language, Language::Ja); + h.state_mut().run("app.language.japanese", json!({})).unwrap(); + h.run_steps(2); // the ribbon renders the Japanese tabs without panicking + assert_eq!(h.state().ui.language, Language::Ja); + // The preference round-trips through the saved UiState. + let restored: gridcraft_ui_egui::UiState = serde_json::from_str(&serde_json::to_string(&h.state().ui).unwrap()).unwrap(); + assert_eq!(restored.language, Language::Ja); + h.state_mut().run("app.language.english", json!({})).unwrap(); + assert_eq!(h.state().ui.language, Language::En); +} + #[test] fn dialogs_open_and_close() { let mut h = harness(blank()); From 6beb80ed367d3bd9a0bb29ba388f25a1b47663b8 Mon Sep 17 00:00:00 2001 From: justinjohn0306 Date: Fri, 9 Oct 2026 17:06:36 +0530 Subject: [PATCH 4/8] Fonts: render Thai and Hebrew (and any non-Latin) instead of tofu (issue #32) egui bundles only Latin glyphs, and the fallback chain appended just the Han/Kana and Hangul faces, so Thai and Hebrew text rendered as tofu boxes even though the text was read correctly. Generalise the CJK fallback into a per-script fallback: every family now also carries a Thai face (Leelawadee UI / Tahoma / Thonburi / Noto Sans Thai) and a Hebrew face (David / Arial Hebrew / Noto Sans Hebrew). epaint shapes the complex scripts itself via harfrust -- it only needed a face that has the glyphs. The faces stay at the end of each chain, so Latin still wins for Latin text. The tests become script-general: a structural check that every family ends with the loaded fallback faces, and a per-script render check that the sample string resolves to a real glyph when the face is present. Full bidi reordering of mixed LTR/RTL text is a separate epaint limitation (no Unicode Bidi Algorithm); a pure other-script run is shaped correctly. --- crates/ui-egui/src/theme.rs | 119 +++++++++++++++++++++++++++--------- 1 file changed, 91 insertions(+), 28 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index e14b9f880b..31f93ac589 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -292,9 +292,9 @@ pub fn font_definitions() -> FontDefinitions { let mut fonts = FontDefinitions::default(); let base_prop: Vec = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default(); let base_mono: Vec = fonts.families.get(&FontFamily::Monospace).cloned().unwrap_or_default(); - // CJK has to sit at the end of each chain: a Latin font owns Latin, and epaint picks the first - // face that has the glyph, so the CJK faces only ever catch Han/Kana/Hangul. - let cjk = load_cjk(&mut fonts); + // The non-Latin fallback faces have to sit at the end of each chain: a Latin font owns Latin, + // and epaint picks the first face that has the glyph, so they only catch their own scripts. + let fallback = load_fallback(&mut fonts); for role in [UI, UI_BOLD, CELL, CELL_BOLD, CELL_ITALIC, CELL_BOLD_ITALIC, SERIF, MONO] { let paths = candidates(role); let refs: Vec<(&str, u32)> = paths.iter().map(|(p, i)| (p.as_str(), *i)).collect(); @@ -309,7 +309,7 @@ pub fn font_definitions() -> FontDefinitions { chain.push(format!("sys-{CELL}")); } chain.extend(if role == MONO { base_mono.clone() } else { base_prop.clone() }); - chain.extend(cjk.iter().cloned()); + chain.extend(fallback.iter().cloned()); chain.retain(|k| fonts.font_data.contains_key(k)); fonts.families.insert(FontFamily::Name(role.into()), chain); } @@ -320,13 +320,15 @@ pub fn font_definitions() -> FontDefinitions { fonts } -/// Loads the system CJK faces (Han/Kana and Hangul, one file each) and returns their keys so every -/// family can carry them as fallback. egui's bundled fonts have no CJK coverage, so without this a -/// Japanese or Chinese workbook renders as tofu boxes even though the text was read correctly. +/// Loads the system non-Latin fallback faces (one file per script family) and returns their keys so +/// every family can carry them as fallback. egui's bundled fonts have no coverage beyond Latin, so +/// without this a Thai, Hebrew, Japanese or Chinese workbook renders as tofu boxes even though the +/// text was read correctly. epaint shapes the complex scripts itself (via `harfrust`); it only needs +/// a face that has the glyphs. #[cfg(not(target_arch = "wasm32"))] -fn load_cjk(fonts: &mut FontDefinitions) -> Vec { +fn load_fallback(fonts: &mut FontDefinitions) -> Vec { let mut keys = Vec::new(); - for (key, cands) in [("sys-cjk-han", cjk_han()), ("sys-cjk-hangul", cjk_hangul())] { + for (key, cands) in fallback_faces() { let refs: Vec<(&str, u32)> = cands.iter().map(|(p, i)| (p.as_str(), *i)).collect(); if let Some(fd) = try_load(&refs) { fonts.font_data.insert(key.to_string(), Arc::new(fd)); @@ -337,10 +339,18 @@ fn load_cjk(fonts: &mut FontDefinitions) -> Vec { } #[cfg(target_arch = "wasm32")] -fn load_cjk(_fonts: &mut FontDefinitions) -> Vec { +fn load_fallback(_fonts: &mut FontDefinitions) -> Vec { Vec::new() } +/// Every fallback face we look for, in chain order: `(key, candidate files)`. One file per script +/// family is enough — epaint picks the first face with the glyph, and a script's glyphs live in one +/// file. Order only matters between faces that both cover a glyph (e.g. Japanese vs Chinese kanji). +#[cfg(not(target_arch = "wasm32"))] +fn fallback_faces() -> Vec<(&'static str, Vec<(String, u32)>)> { + vec![("sys-cjk-han", cjk_han()), ("sys-cjk-hangul", cjk_hangul()), ("sys-thai", thai()), ("sys-hebrew", hebrew())] +} + /// Han + Kana faces, in fallback order. A Japanese face comes first (kana and JIS kanji render /// with Japanese glyph shapes); a Chinese face follows to widen coverage. Every CJK face carries /// kana, so any of them renders Japanese; the order only decides kanji glyph style. @@ -379,6 +389,51 @@ fn cjk_hangul() -> Vec<(String, u32)> { v } +/// Thai faces. Windows ships Leelawadee UI and Tahoma/Microsoft Sans Serif (both carry Thai); +/// macOS has Thonburi; Linux usually has Noto Sans Thai or Garuda. +#[cfg(not(target_arch = "wasm32"))] +fn thai() -> Vec<(String, u32)> { + let mac_sys = "/System/Library/Fonts"; + let mac_sup = "/System/Library/Fonts/Supplemental"; + let win = std::env::var("WINDIR").map(|w| format!("{w}\\Fonts")).unwrap_or_else(|_| "C:\\Windows\\Fonts".into()); + let lin = ["/usr/share/fonts/truetype/noto", "/usr/share/fonts/opentype/noto", "/usr/share/fonts/truetype", "/usr/share/fonts"]; + let mut v: Vec<(String, u32)> = Vec::new(); + v.push((format!("{win}\\LeelawUI.ttf"), 0)); // Leelawadee UI + v.push((format!("{win}\\tahoma.ttf"), 0)); // Tahoma + v.push((format!("{win}\\micross.ttf"), 0)); // Microsoft Sans Serif + v.push((format!("{mac_sup}/Thonburi.ttc"), 0)); + v.push((format!("{mac_sys}/SukhumvitSet.ttc"), 0)); + for d in lin { + v.push((format!("{d}/NotoSansThai-Regular.ttf"), 0)); + v.push((format!("{d}/tlwg/Garuda.ttf"), 0)); + v.push((format!("{d}/garuda/Garuda.ttf"), 0)); + } + v +} + +/// Hebrew faces. Windows has David and FrankRuehl (and Tahoma/Courier New carry Hebrew); macOS has +/// Arial Hebrew and David; Linux usually has Noto Sans Hebrew or DejaVu Sans. +#[cfg(not(target_arch = "wasm32"))] +fn hebrew() -> Vec<(String, u32)> { + let mac_sys = "/System/Library/Fonts"; + let mac_sup = "/System/Library/Fonts/Supplemental"; + let win = std::env::var("WINDIR").map(|w| format!("{w}\\Fonts")).unwrap_or_else(|_| "C:\\Windows\\Fonts".into()); + let lin = ["/usr/share/fonts/truetype/noto", "/usr/share/fonts/opentype/noto", "/usr/share/fonts/truetype", "/usr/share/fonts"]; + let mut v: Vec<(String, u32)> = Vec::new(); + v.push((format!("{win}\\david.ttf"), 0)); // David + v.push((format!("{win}\\frank.ttf"), 0)); // FrankRuehl + v.push((format!("{win}\\tahoma.ttf"), 0)); // Tahoma + v.push((format!("{mac_sup}/Arial Hebrew.ttf"), 0)); + v.push((format!("{mac_sup}/David.ttf"), 0)); + v.push((format!("{mac_sys}/Lucida Grande.ttc"), 0)); + for d in lin { + v.push((format!("{d}/NotoSansHebrew-Regular.ttf"), 0)); + v.push((format!("{d}/dejavu/DejaVuSans.ttf"), 0)); + v.push((format!("{d}/freefont/FreeSans.ttf"), 0)); + } + v +} + pub fn apply(ctx: &egui::Context, dark: bool) { let t = if dark { Tokens::dark() } else { Tokens::light() }; let mut v = if dark { Visuals::dark() } else { Visuals::light() }; @@ -420,35 +475,43 @@ mod tests { use super::*; #[test] - fn cjk_fallback_is_appended_to_every_family() { - // Structural: whatever loaded, the CJK keys must sit at the end of each chain (after the - // Latin/default fonts) so Latin still wins for Latin text. + fn fallback_faces_are_appended_to_every_family() { + // Structural: whatever loaded, the non-Latin fallback keys must sit at the end of each chain + // (after the Latin/default fonts) so Latin still wins for Latin text. let fonts = font_definitions(); - let cjk_keys: Vec = - ["sys-cjk-han", "sys-cjk-hangul"].into_iter().filter(|k| fonts.font_data.contains_key(*k)).map(str::to_string).collect(); - if cjk_keys.is_empty() { - return; // no CJK face on this machine (minimal Linux) + let fb_keys: Vec = fallback_faces().into_iter().map(|(k, _)| k.to_string()).filter(|k| fonts.font_data.contains_key(k)).collect(); + if fb_keys.is_empty() { + return; // no fallback face on this machine (minimal Linux) } for role in [UI, UI_BOLD, CELL, CELL_BOLD, CELL_ITALIC, CELL_BOLD_ITALIC, SERIF, MONO] { let chain = fonts.families.get(&FontFamily::Name(role.into())).map(Vec::as_slice).unwrap_or_default(); - assert!(chain.len() >= cjk_keys.len(), "{role} chain too short for its CJK fallback"); - let tail = &chain[chain.len() - cjk_keys.len()..]; - assert_eq!(tail, cjk_keys.as_slice(), "{role} must end its chain with the CJK faces"); + assert!(chain.len() >= fb_keys.len(), "{role} chain too short for its fallback"); + let tail = &chain[chain.len() - fb_keys.len()..]; + assert_eq!(tail, fb_keys.as_slice(), "{role} must end its chain with the fallback faces"); } } #[test] - fn cjk_fallback_covers_japanese() { - // Real render check: the proportional family (what cells and the UI use) must resolve - // Japanese kana/kanji to a glyph, not the tofu replacement char. - if cjk_han().iter().all(|(p, _)| std::fs::read(p).is_err()) { - return; // no CJK face on this machine (minimal Linux); nothing to assert - } + fn fallback_covers_its_script() { + // Real render check, per script: the proportional family (what cells and the UI use) must + // resolve a sample string to a real glyph, not the tofu replacement char. Skips a script + // whose face is absent (a minimal machine) and fails if a face is present but not wired in. + let cases: [(&str, Vec<(String, u32)>, &str); 4] = [ + ("sys-cjk-han", cjk_han(), "カテゴリ"), + ("sys-cjk-hangul", cjk_hangul(), "한글"), + ("sys-thai", thai(), "ทดสอบ"), + ("sys-hebrew", hebrew(), "עברית"), + ]; let ctx = egui::Context::default(); ctx.set_fonts(font_definitions()); let mut out = ctx.run_ui(egui::RawInput::default(), |_ui| {}); out.textures_delta.clear(); // nothing consumes the atlas in a headless test - let covered = ctx.fonts_mut(|f| f.has_glyphs(&FontId::proportional(14.0), "カテゴリ")); - assert!(covered, "Japanese text must render with a real glyph, not tofu"); + for (key, cands, sample) in cases { + if cands.iter().all(|(p, _)| std::fs::read(p).is_err()) { + continue; // no face for this script on this machine; nothing to assert + } + let covered = ctx.fonts_mut(|f| f.has_glyphs(&FontId::proportional(14.0), sample)); + assert!(covered, "{key} is present but {sample:?} still renders as tofu"); + } } } From f424d7d56b26fa72ac33c550fac418f5168f0ecc Mon Sep 17 00:00:00 2001 From: Eduardo Soares Date: Fri, 9 Oct 2026 18:18:57 -0300 Subject: [PATCH 5/8] i18n: Brazilian Portuguese interface language (#79) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds PtBr to the interface-language system from #31: a PORTUGUESE table covering the same 259 chrome strings as JAPANESE (a test keeps the two tables in step), Excel's pt-BR wording throughout, "pt"/"pt-br" codes (serde-stored as "pt"), Português (Brasil) in the switcher, the app.language.portuguese command, and first-run detection of a pt-BR system locale via the existing tag reduction. --- contributors/people.toml | 3 + crates/ui-egui/examples/snapshot.rs | 2 +- crates/ui-egui/src/i18n.rs | 303 +++++++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 8 +- crates/ui-egui/src/ribbon.rs | 6 +- 5 files changed, 311 insertions(+), 11 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index 89c6db2082..ea52018596 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -21,3 +21,6 @@ real_name = "Brandon Thomas" display_name = "Brandon Thomas" sync_github_name = false + +[people.edurbs] +sync_github_name = true diff --git a/crates/ui-egui/examples/snapshot.rs b/crates/ui-egui/examples/snapshot.rs index f384d183df..c1604719b2 100644 --- a/crates/ui-egui/examples/snapshot.rs +++ b/crates/ui-egui/examples/snapshot.rs @@ -1,7 +1,7 @@ //! Renders the whole GridCraft window offscreen (wgpu, no window) to a PNG. //! //! `cargo run --release -p gridcraft-ui-egui --example snapshot -- [--sample sales] [--in file.xlsx] -//! [--size 1440x900] [--scale 2] [--cmd 'id={json}']... [--tab Insert] [--dark] [--language ja] +//! [--size 1440x900] [--scale 2] [--cmd 'id={json}']... [--tab Insert] [--dark] [--language en|ja|pt] //! [--dialog 'name={json}'] out.png` use gridcraft_engine::Session; diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 48e809dd90..a1db0667d9 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -15,16 +15,19 @@ pub enum Language { #[default] En, Ja, + #[serde(rename = "pt")] + PtBr, } impl Language { - pub const ALL: [Self; 2] = [Self::En, Self::Ja]; + pub const ALL: [Self; 3] = [Self::En, Self::Ja, Self::PtBr]; /// The language's own name, shown in the switcher. pub fn name(self) -> &'static str { match self { Self::En => "English", Self::Ja => "日本語", + Self::PtBr => "Português (Brasil)", } } @@ -32,6 +35,7 @@ impl Language { match code { "en" => Some(Self::En), "ja" => Some(Self::Ja), + "pt" | "pt-br" => Some(Self::PtBr), _ => None, } } @@ -57,12 +61,12 @@ impl Language { } pub fn tr(self, text: &str) -> &str { - if self == Self::Ja - && let Some((_, japanese)) = JAPANESE.iter().find(|(english, _)| *english == text) - { - return japanese; - } - text + let table: &[(&str, &str)] = match self { + Self::En => &[], + Self::Ja => JAPANESE, + Self::PtBr => PORTUGUESE, + }; + table.iter().find(|(english, _)| *english == text).map_or(text, |(_, translated)| translated) } } @@ -346,6 +350,271 @@ const JAPANESE: &[(&str, &str)] = &[ ("More\nFunctions", "その他の関数"), ]; +/// English label → Brazilian Portuguese, keyed like [`JAPANESE`] so the tables stay in step (a test +/// enforces it) and the diff reads against the Japanese column. Labels follow Excel's pt-BR wording; +/// anything absent falls back to English. +const PORTUGUESE: &[(&str, &str)] = &[ + ("Paste", "Colar"), + ("Paste Values", "Colar Valores"), + ("Paste Formulas", "Colar Fórmulas"), + ("Paste Formatting", "Colar Formatação"), + ("Transpose", "Transpor"), + ("Paste Link", "Colar Vínculo"), + ("Paste Special…", "Colar Especial…"), + ("Cut (⌘X)", "Recortar (⌘X)"), + ("Copy (⌘C)", "Copiar (⌘C)"), + ("Format Painter (double-click to keep it on)", "Pincel de Formatação (clique duas vezes para mantê-lo ativo)"), + ("Bold (⌘B)", "Negrito (⌘B)"), + ("Italic (⌘I)", "Itálico (⌘I)"), + ("Underline (⌘U)", "Sublinhado (⌘U)"), + ("Double Underline", "Sublinhado Duplo"), + ("Strikethrough", "Riscado"), + ("Underline", "Sublinhado"), + ("Increase Font Size", "Aumentar Tamanho da Fonte"), + ("Decrease Font Size", "Diminuir Tamanho da Fonte"), + ("Wrap Text", "Quebrar Texto Automaticamente"), + ("Merge & Center", "Mesclar e Centralizar"), + ("Merge Cells", "Mesclar Células"), + ("Merge Across", "Mesclar Através"), + ("Unmerge Cells", "Desmesclar Células"), + ("Fill Color", "Cor de Preenchimento"), + ("Font Color", "Cor da Fonte"), + ("Borders", "Bordas"), + ("Top\nAlign", "Alinhar\nno Topo"), + ("Middle\nAlign", "Alinhar\nno Meio"), + ("Bottom\nAlign", "Alinhar\nem Baixo"), + ("Left", "Esquerda"), + ("Right", "Direita"), + ("Center", "Centro"), + ("Horizontal", "Horizontal"), + ("Vertical Text", "Texto Vertical"), + ("Decrease Indent", "Diminuir Recuo"), + ("Increase Indent", "Aumentar Recuo"), + ("Orientation", "Orientação"), + ("Angle Counterclockwise", "Ângulo Anti-Horário"), + ("Angle Clockwise", "Ângulo Horário"), + ("Rotate Text Up", "Girar Texto para Cima"), + ("Rotate Text Down", "Girar Texto para Baixo"), + ("Accounting Number Format", "Formato de Número Contábil"), + ("Percent Style", "Estilo de Porcentagem"), + ("Comma Style", "Estilo de Vírgula"), + ("Increase Decimal", "Aumentar Casas Decimais"), + ("Decrease Decimal", "Diminuir Casas Decimais"), + ("More Accounting Formats…", "Mais Formatos Contábeis…"), + ("Conditional\nFormatting", "Formatação\nCondicional"), + ("Conditional Formatting", "Formatação Condicional"), + ("Format\nas Table", "Formatar\ncomo Tabela"), + ("Cell\nStyles", "Estilos\nde Célula"), + ("Format Cells…", "Formatar Células…"), + ("Format Cell Alignment…", "Formatar Alinhamento de Células…"), + ("Format\nPane", "Painel de\nFormatação"), + ("Format", "Formatar"), + ("Insert", "Inserir"), + ("Insert Cells…", "Inserir Células…"), + ("Delete", "Excluir"), + ("Delete Cells…", "Excluir Células…"), + ("Insert Sheet Rows", "Inserir Linhas de Planilha"), + ("Insert Sheet Columns", "Inserir Colunas de Planilha"), + ("Delete Sheet Rows", "Excluir Linhas de Planilha"), + ("Delete Sheet Columns", "Excluir Colunas de Planilha"), + ("Row Height…", "Altura da Linha…"), + ("AutoFit Row Height", "Ajustar Altura da Linha"), + ("Column Width…", "Largura da Coluna…"), + ("AutoFit Column Width", "Ajustar Largura da Coluna"), + ("Default Width…", "Largura Padrão…"), + ("Hide Rows", "Ocultar Linhas"), + ("Unhide Rows", "Reexibir Linhas"), + ("Hide Columns", "Ocultar Colunas"), + ("Unhide Columns", "Reexibir Colunas"), + ("Lock Cell", "Bloquear Célula"), + ("Clear", "Limpar"), + ("Clear All", "Limpar Tudo"), + ("Clear Formats", "Limpar Formatos"), + ("Clear Contents", "Limpar Conteúdo"), + ("Clear Comments and Notes", "Limpar Comentários e Notas"), + ("Clear Hyperlinks", "Limpar Hiperlinks"), + ("AutoSum", "Soma Automática"), + ("AutoSum (⌘⇧T)", "Soma Automática (⌘⇧T)"), + ("Flash\nFill", "Preenchimento\nRelâmpago"), + ("Flash Fill", "Preenchimento Relâmpago"), + ("Fill", "Preencher"), + ("Clear Print Area", "Limpar Área de Impressão"), + ("Find &\nSelect", "Localizar e\nSelecionar"), + ("Find…", "Localizar…"), + ("Replace…", "Substituir…"), + ("Go To…", "Ir Para…"), + ("Go To Special…", "Ir Para Especial…"), + ("PivotTable", "Tabela Dinâmica"), + ("Recommended\nCharts", "Gráficos\nRecomendados"), + ("Table", "Tabela"), + ("Pictures", "Imagens"), + ("Shapes", "Formas"), + ("Icons", "Ícones"), + ("Text\nBox", "Caixa\nde Texto"), + ("Comment", "Comentário"), + ("New\nComment", "Novo\nComentário"), + ("New Note", "Nova Nota"), + ("Show/Hide Note", "Mostrar/Ocultar Nota"), + ("Header &\nFooter", "Cabeçalho e\nRodapé"), + ("Text to\nColumns", "Texto para\nColunas"), + ("Link", "Vínculo"), + ("Symbol", "Símbolo"), + ("Sparklines", "Minigráficos"), + ("Header & Footer", "Cabeçalho e Rodapé"), + ("Draw with ink", "Desenhar com Tinta"), + ("Eraser", "Borracha"), + ("Ink to\nShape", "Tinta para\nForma"), + ("Select\nObjects", "Selecionar\nObjetos"), + ("Themes", "Temas"), + ("Margins", "Margens"), + ("Size", "Tamanho"), + ("Print\nArea", "Área de\nImpressão"), + ("Set Print Area", "Definir Área de Impressão"), + ("Breaks", "Quebras"), + ("Insert Page Break", "Inserir Quebra de Página"), + ("Remove Page Break", "Remover Quebra de Página"), + ("Reset All Page Breaks", "Redefinir Todas as Quebras de Página"), + ("Print\nTitles", "Imprimir\nTítulos"), + ("Narrow", "Estreita"), + ("Wide", "Ampla"), + ("Normal", "Normal"), + ("Portrait", "Retrato"), + ("Landscape", "Paisagem"), + ("Custom Margins…", "Margens Personalizadas…"), + ("Insert\nFunction", "Inserir\nFunção"), + ("Name\nManager", "Gerenciador\nde Nomes"), + ("Define Name", "Definir Nome"), + ("Use in Formula", "Usar na Fórmula"), + ("Create from Selection", "Criar a Partir da Seleção"), + ("Trace Precedents", "Rastrear Precedentes"), + ("Trace Dependents", "Rastrear Dependentes"), + ("Remove Arrows", "Remover Setas"), + ("Show Formulas", "Exibir Fórmulas"), + ("Error Checking", "Verificação de Erros"), + ("Evaluate Formula", "Avaliar Fórmula"), + ("Watch Window", "Janela de Inspeção"), + ("Calculation\nOptions", "Opções de\nCálculo"), + ("Calculate Now", "Calcular Agora"), + ("Calculate Sheet", "Calcular Planilha"), + ("Automatic", "Automático"), + ("Automatic Except for Data Tables", "Automático Exceto Tabelas de Dados"), + ("Manual", "Manual"), + ("Sort &\nFilter", "Classificar e\nFiltrar"), + ("Sort", "Classificar"), + ("Sort A to Z", "Classificar de A a Z"), + ("Sort Z to A", "Classificar de Z a A"), + ("Custom Sort…", "Classificação Personalizada…"), + ("Filter", "Filtrar"), + ("Reapply", "Aplicar Novamente"), + ("Get Data\n(Text/CSV)", "Obter Dados\n(Texto/CSV)"), + ("Remove\nDuplicates", "Remover\nDuplicatas"), + ("Data\nValidation", "Validação\nde Dados"), + ("Data Validation", "Validação de Dados"), + ("Data Validation…", "Validação de Dados…"), + ("Circle Invalid Data", "Circundar Dados Inválidos"), + ("Clear Validation", "Limpar Validação"), + ("Group", "Agrupar"), + ("Ungroup", "Desagrupar"), + ("Subtotal", "Subtotal"), + ("What-If\nAnalysis", "Análise de\nHipóteses"), + ("Data Table…", "Tabela de Dados…"), + ("Scenario Manager…", "Gerenciador de Cenários…"), + ("Goal Seek…", "Buscar Objetivo…"), + ("Spelling", "Ortografia"), + ("Check\nAccessibility", "Verificar\nAcessibilidade"), + ("Threaded Comments", "Comentários Encadeados"), + ("Show\nComments", "Mostrar\nComentários"), + ("Protect\nWorkbook", "Proteger\nPasta de Trabalho"), + ("Unprotect\nSheet", "Desproteger\nPlanilha"), + ("Protect Sheet…", "Proteger Planilha…"), + ("Comments", "Comentários"), + ("Notes", "Notas"), + ("Page Break\nPreview", "Visualização\nde Quebras de Página"), + ("Page\nLayout", "Layout\nde Página"), + ("Formula Bar", "Barra de Fórmulas"), + ("Gridlines", "Linhas de Grade"), + ("Headings", "Títulos"), + ("Zoom", "Zoom"), + ("100%", "100%"), + ("Zoom to\nSelection", "Zoom na\nSeleção"), + ("Freeze\nPanes", "Congelar\nPainéis"), + ("Freeze Panes", "Congelar Painéis"), + ("Freeze Top Row", "Congelar Linha Superior"), + ("Freeze First Column", "Congelar Primeira Coluna"), + ("Unfreeze Panes", "Descongelar Painéis"), + ("Dark Mode", "Modo Escuro"), + ("Interface language", "Idioma da interface"), + ("Command\nPalette", "Paleta de\nComandos"), + ("Agent\nControl", "Controle\ndo Agente"), + ("Action\nJournal", "Registro\nde Ações"), + ("About\nGridCraft", "Sobre o\nGridCraft"), + ("Share", "Compartilhar"), + ("Add Chart\nElement", "Adicionar\nElemento de Gráfico"), + ("Change\nChart Type", "Alterar\nTipo de Gráfico"), + ("Switch\nRow/Column", "Alternar\nLinha/Coluna"), + ("Data Labels: None", "Rótulos de Dados: Nenhum"), + ("Data Labels: Show", "Rótulos de Dados: Exibir"), + ("Legend: None", "Legenda: Nenhuma"), + ("Legend: Bottom", "Legenda: Abaixo"), + ("Legend: Top", "Legenda: Acima"), + ("Legend: Right", "Legenda: À Direita"), + ("Gridlines: None", "Linhas de Grade: Nenhuma"), + ("Gridlines: Show", "Linhas de Grade: Exibir"), + ("Chart\nTitle", "Título\ndo Gráfico"), + ("Delete\nChart", "Excluir\nGráfico"), + ("Convert\nto Range", "Converter\nem Intervalo"), + ("Table\nStyles", "Estilos\nde Tabela"), + ("Top 10 Items", "10 Primeiros Itens"), + ("Top 10%", "10% Primeiros"), + ("Bottom 10 Items", "10 Últimos Itens"), + ("Bottom 10%", "10% Últimos"), + ("Above Average", "Acima da Média"), + ("Below Average", "Abaixo da Média"), + ("Clear Rules from Entire Sheet", "Limpar Regras de Toda a Planilha"), + ("Clear Rules from Selected Cells", "Limpar Regras das Células Selecionadas"), + ("Constants", "Constantes"), + ("Data Bars", "Barras de Dados"), + ("Color Scales", "Escalas de Cores"), + ("Icon Sets", "Conjuntos de Ícones"), + ("Home", "Página Inicial"), + ("Draw", "Desenhar"), + ("Page Layout", "Layout da Página"), + ("Formulas", "Fórmulas"), + ("Data", "Dados"), + ("Review", "Revisão"), + ("View", "Exibir"), + ("Automate", "Automatizar"), + ("Table Design", "Design de Tabela"), + ("Chart Design", "Design de Gráfico"), + ("Ready", "Pronto"), + ("Enter", "Inserir"), + ("Edit", "Editar"), + ("Point", "Apontar"), + ("Calculate", "Calcular"), + ("Select destination and press Enter or choose Paste", "Selecione o destino e pressione Enter ou escolha Colar"), + ("General", "Geral"), + ("Number", "Número"), + ("Currency", "Moeda"), + ("Accounting", "Contábil"), + ("Date", "Data"), + ("Time", "Hora"), + ("Percentage", "Porcentagem"), + ("Fraction", "Fração"), + ("Scientific", "Científico"), + ("Text", "Texto"), + ("Special", "Especial"), + ("Custom", "Personalizado"), + ("Short Date", "Data Abreviada"), + ("Long Date", "Data Por Extenso"), + ("More Number Formats…", "Mais Formatos de Número…"), + ("Financial", "Financeira"), + ("Logical", "Lógica"), + ("Date &\nTime", "Data e\nHora"), + ("Lookup &\nReference", "Pesquisa e\nReferência"), + ("Math &\nTrig", "Matemática e\nTrigonometria"), + ("More\nFunctions", "Mais\nFunções"), +]; + #[cfg(test)] mod tests { use super::*; @@ -357,8 +626,21 @@ mod tests { assert!(JAPANESE.iter().take(i).all(|(other, _)| en != other)); assert_eq!(Language::En.tr(en), *en); } + for (i, (en, pt)) in PORTUGUESE.iter().enumerate() { + assert!(!pt.is_empty()); + assert!(PORTUGUESE.iter().take(i).all(|(other, _)| en != other)); + assert_eq!(Language::En.tr(en), *en); + } + // The tables cover the same interface strings, so per-language coverage stays even. + for (en, _) in PORTUGUESE { + assert!(JAPANESE.iter().any(|(other, _)| en == other), "{en:?} missing from JAPANESE"); + } + assert_eq!(JAPANESE.len(), PORTUGUESE.len()); assert_eq!(Language::Ja.tr("Data"), "データ"); + assert_eq!(Language::PtBr.tr("Data"), "Dados"); + assert_eq!(Language::PtBr.tr("Date"), "Data"); assert_eq!(Language::Ja.tr("Sheet1!A1"), "Sheet1!A1"); + assert_eq!(Language::PtBr.tr("Sheet1!A1"), "Sheet1!A1"); assert_eq!(Language::parse("xx"), None); } @@ -367,6 +649,9 @@ mod tests { assert_eq!(Language::from_tag("ja-JP"), Some(Language::Ja)); assert_eq!(Language::from_tag("en_US"), Some(Language::En)); assert_eq!(Language::from_tag("de-DE"), None); + assert_eq!(Language::from_tag("pt-BR"), Some(Language::PtBr)); + assert_eq!(Language::parse("pt"), Some(Language::PtBr)); + assert_eq!(Language::parse("pt-br"), Some(Language::PtBr)); } #[test] @@ -374,8 +659,10 @@ mod tests { let mut app = crate::SheetApp::new(gridcraft_engine::Session::default(), Default::default()); app.run("app.language.japanese", serde_json::json!({})).unwrap(); assert_eq!(app.ui.language, Language::Ja); + app.run("app.language.portuguese", serde_json::json!({})).unwrap(); + assert_eq!(app.ui.language, Language::PtBr); let restored: crate::UiState = serde_json::from_str(&serde_json::to_string(&app.ui).unwrap()).unwrap(); - assert_eq!(restored.language, Language::Ja); + assert_eq!(restored.language, Language::PtBr); app.run("app.language.english", serde_json::json!({})).unwrap(); assert_eq!(app.ui.language, Language::En); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4e7a383e4a..f41ad36080 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -199,7 +199,9 @@ impl SheetApp { self.ui.language = l; Ok(json!({"language": l})) } - None => Err(format!("unknown language {:?} (use \"en\" or \"ja\")", p.get("language").and_then(Json::as_str).unwrap_or(""))), + None => { + Err(format!("unknown language {:?} (use \"en\", \"ja\" or \"pt\")", p.get("language").and_then(Json::as_str).unwrap_or(""))) + } } } "app.language.english" => { @@ -210,6 +212,10 @@ impl SheetApp { self.ui.language = i18n::Language::Ja; Ok(json!({"language": i18n::Language::Ja})) } + "app.language.portuguese" => { + self.ui.language = i18n::Language::PtBr; + Ok(json!({"language": i18n::Language::PtBr})) + } "ui.dialog" => { let name = p.get("name").and_then(Json::as_str).unwrap_or(""); self.open_dialog(name, p.clone()); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 52bc34b809..0dbc8850e3 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1588,7 +1588,11 @@ fn view(app: &mut SheetApp, ui: &mut Ui) { |ui| { for l in crate::i18n::Language::ALL { if ui.selectable_label(l == lang, l.name()).clicked() { - let code = if l == crate::i18n::Language::Ja { "app.language.japanese" } else { "app.language.english" }; + let code = match l { + crate::i18n::Language::En => "app.language.english", + crate::i18n::Language::Ja => "app.language.japanese", + crate::i18n::Language::PtBr => "app.language.portuguese", + }; act(app, code, json!({})); } } From 12bfdb07989bdfd11b637336ccd33418e3a7639d Mon Sep 17 00:00:00 2001 From: neko233-com <242357072+neko233-com@users.noreply.github.com> Date: Sat, 10 Oct 2026 10:20:59 +0800 Subject: [PATCH 6/8] i18n: add Chinese, Korean and Russian interface languages --- Cargo.lock | 1 + apps/gridcraft-web/src/web.rs | 2 +- apps/gridcraft/src/main.rs | 2 +- crates/ui-egui/Cargo.toml | 7 +- crates/ui-egui/src/i18n.rs | 92 +++++++--- crates/ui-egui/src/i18n/ko.rs | 268 ++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/ru.rs | 268 ++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/zh.rs | 268 ++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 23 ++- crates/ui-egui/src/ribbon.rs | 6 +- crates/ui-egui/src/theme.rs | 129 +++++++++---- crates/ui-egui/tests/interaction.rs | 19 +- 12 files changed, 1004 insertions(+), 81 deletions(-) create mode 100644 crates/ui-egui/src/i18n/ko.rs create mode 100644 crates/ui-egui/src/i18n/ru.rs create mode 100644 crates/ui-egui/src/i18n/zh.rs diff --git a/Cargo.lock b/Cargo.lock index fd6140b92d..fea43b6bff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1530,6 +1530,7 @@ dependencies = [ "serde_json", "sys-locale", "toml", + "web-sys", ] [[package]] diff --git a/apps/gridcraft-web/src/web.rs b/apps/gridcraft-web/src/web.rs index c06d890747..d046ce4470 100644 --- a/apps/gridcraft-web/src/web.rs +++ b/apps/gridcraft-web/src/web.rs @@ -38,7 +38,7 @@ pub fn start() { let _ = session.execute("file.new", serde_json::json!({"sample": "sales"})); } let app = SheetApp::new(session, services(inbox.clone(), cc.egui_ctx.clone())); - SheetApp::setup_context(&cc.egui_ctx, false); + SheetApp::setup_context_for_language(&cc.egui_ctx, false, app.ui.language); Ok(Box::new(WebShell { app, inbox })) }), ) diff --git a/apps/gridcraft/src/main.rs b/apps/gridcraft/src/main.rs index 6acaf51195..a1f20413a0 100644 --- a/apps/gridcraft/src/main.rs +++ b/apps/gridcraft/src/main.rs @@ -191,7 +191,7 @@ fn main() -> eframe::Result<()> { "GridCraft", options, Box::new(move |cc| { - SheetApp::setup_context(&cc.egui_ctx, app.ui.dark); + SheetApp::setup_context_for_language(&cc.egui_ctx, app.ui.dark, app.ui.language); if let Some(port) = control_port { match control_server::start(port, cc.egui_ctx.clone()) { Ok(rx) => app.control_rx = Some(rx), diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index ee77578f52..a6a2da2e3e 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -21,10 +21,13 @@ image = { workspace = true } egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -# The desktop's preferred language, for the first-run interface language. The web build has no -# system locale, so the crate is native-only (see i18n::Language::system). +# The desktop's preferred language for the first-run interface language. sys-locale = { workspace = true } +[target.'cfg(target_arch = "wasm32")'.dependencies] +# Read the browser's preferred language for the first-run web interface language. +web-sys = { version = "0.3", features = ["Window", "Navigator"] } + [build-dependencies] serde_json = { workspace = true } toml = "1" diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 48e809dd90..9d86a5ac4f 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -4,45 +4,65 @@ //! The interface language is a preference ([`crate::UiState::language`]): on first run it defaults //! to the system's language ([`Language::system`]), and the View tab switches it by hand. //! -//! No Japanese font is bundled and none is installed here: the CJK faces [`crate::theme`] appends -//! to every family already cover kana and kanji, so Japanese interface text renders without help. +//! CJK fonts stay system-provided: [`crate::theme`] appends available CJK faces to every family so +//! Japanese, Chinese and Korean labels and workbook text can render without bundling font files. use serde::{Deserialize, Serialize}; +mod ko; +mod ru; +mod zh; + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Language { #[default] En, + Zh, Ja, + Ko, + Ru, } impl Language { - pub const ALL: [Self; 2] = [Self::En, Self::Ja]; + pub const ALL: [Self; 5] = [Self::En, Self::Zh, Self::Ja, Self::Ko, Self::Ru]; /// The language's own name, shown in the switcher. pub fn name(self) -> &'static str { match self { Self::En => "English", + Self::Zh => "简体中文", Self::Ja => "日本語", + Self::Ko => "한국어", + Self::Ru => "Русский", + } + } + + pub const fn code(self) -> &'static str { + match self { + Self::En => "en", + Self::Zh => "zh", + Self::Ja => "ja", + Self::Ko => "ko", + Self::Ru => "ru", } } pub fn parse(code: &str) -> Option { - match code { + Self::from_tag(code) + } + + fn from_tag(tag: &str) -> Option { + match tag.trim().split(['-', '_']).next()?.to_ascii_lowercase().as_str() { "en" => Some(Self::En), + "zh" => Some(Self::Zh), "ja" => Some(Self::Ja), + "ko" => Some(Self::Ko), + "ru" => Some(Self::Ru), _ => None, } } - /// A language tag (`ja`, `ja-JP`, `en_US`) reduced to a supported language. Native only: the web - /// build has no system locale to read and tests exercise it on the host. - #[cfg(not(target_arch = "wasm32"))] - fn from_tag(tag: &str) -> Option { - Self::parse(&tag.split(['-', '_']).next().unwrap_or("").to_ascii_lowercase()) - } - /// The system's preferred interface language, best effort; English when it is unknown or /// unsupported. Used as the first-run default while nothing is saved. pub fn system() -> Self { @@ -52,17 +72,21 @@ impl Language { } #[cfg(target_arch = "wasm32")] { - Self::En + web_sys::window().and_then(|window| window.navigator().language()).and_then(|tag| Self::from_tag(&tag)).unwrap_or(Self::En) } } pub fn tr(self, text: &str) -> &str { - if self == Self::Ja - && let Some((_, japanese)) = JAPANESE.iter().find(|(english, _)| *english == text) - { - return japanese; + if self == Self::En { + return text; + } + match self { + Self::En => text, + Self::Ja => JAPANESE.iter().find(|(english, _)| *english == text).map(|(_, translated)| *translated).unwrap_or(text), + Self::Zh => zh::translate(text).unwrap_or(text), + Self::Ko => ko::translate(text).unwrap_or(text), + Self::Ru => ru::translate(text).unwrap_or(text), } - text } } @@ -344,6 +368,8 @@ const JAPANESE: &[(&str, &str)] = &[ ("Lookup &\nReference", "検索/行列"), ("Math &\nTrig", "数学/三角"), ("More\nFunctions", "その他の関数"), + ("Screen", "画面"), + ("Print", "印刷"), ]; #[cfg(test)] @@ -357,8 +383,19 @@ mod tests { assert!(JAPANESE.iter().take(i).all(|(other, _)| en != other)); assert_eq!(Language::En.tr(en), *en); } + for (english, _) in JAPANESE { + assert!(zh::translate(english).is_some_and(|text| !text.is_empty()), "missing Simplified Chinese: {english}"); + assert!(ko::translate(english).is_some_and(|text| !text.is_empty()), "missing Korean: {english}"); + assert!(ru::translate(english).is_some_and(|text| !text.is_empty()), "missing Russian: {english}"); + } assert_eq!(Language::Ja.tr("Data"), "データ"); + assert_eq!(Language::Zh.tr("Data"), "数据"); + assert_eq!(Language::Ko.tr("Data"), "데이터"); + assert_eq!(Language::Ru.tr("Data"), "Данные"); assert_eq!(Language::Ja.tr("Sheet1!A1"), "Sheet1!A1"); + assert_eq!(Language::Zh.tr("Sheet1!A1"), "Sheet1!A1"); + assert_eq!(Language::Ko.tr("Sheet1!A1"), "Sheet1!A1"); + assert_eq!(Language::Ru.tr("Sheet1!A1"), "Sheet1!A1"); assert_eq!(Language::parse("xx"), None); } @@ -366,17 +403,26 @@ mod tests { fn tags_reduce_to_a_supported_language() { assert_eq!(Language::from_tag("ja-JP"), Some(Language::Ja)); assert_eq!(Language::from_tag("en_US"), Some(Language::En)); + assert_eq!(Language::from_tag("zh-Hans-CN"), Some(Language::Zh)); + assert_eq!(Language::from_tag("ko-KR"), Some(Language::Ko)); + assert_eq!(Language::from_tag("RU_ru"), Some(Language::Ru)); assert_eq!(Language::from_tag("de-DE"), None); } + #[test] + fn an_unset_language_preference_uses_the_system_default() { + let restored: crate::UiState = serde_json::from_str("{}").unwrap(); + assert_eq!(restored.language, Language::system()); + } + #[test] fn language_commands_switch_and_persist() { let mut app = crate::SheetApp::new(gridcraft_engine::Session::default(), Default::default()); - app.run("app.language.japanese", serde_json::json!({})).unwrap(); - assert_eq!(app.ui.language, Language::Ja); - let restored: crate::UiState = serde_json::from_str(&serde_json::to_string(&app.ui).unwrap()).unwrap(); - assert_eq!(restored.language, Language::Ja); - app.run("app.language.english", serde_json::json!({})).unwrap(); - assert_eq!(app.ui.language, Language::En); + for language in Language::ALL { + app.run("app.language.set", serde_json::json!({"language": language.code()})).unwrap(); + assert_eq!(app.ui.language, language); + let restored: crate::UiState = serde_json::from_str(&serde_json::to_string(&app.ui).unwrap()).unwrap(); + assert_eq!(restored.language, language); + } } } diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs new file mode 100644 index 0000000000..ea7dc8cafa --- /dev/null +++ b/crates/ui-egui/src/i18n/ko.rs @@ -0,0 +1,268 @@ +//! Korean translations for the interface strings in i18n.rs. + +pub(super) fn translate(text: &str) -> Option<&'static str> { + Some(match text { + "Paste" => "붙여넣기", + "Paste Values" => "값 붙여넣기", + "Paste Formulas" => "수식 붙여넣기", + "Paste Formatting" => "서식 붙여넣기", + "Transpose" => "행/열 바꾸기", + "Paste Link" => "연결하여 붙여넣기", + "Paste Special…" => "선택하여 붙여넣기…", + "Cut (⌘X)" => "잘라내기 (⌘X)", + "Copy (⌘C)" => "복사 (⌘C)", + "Format Painter (double-click to keep it on)" => "서식 복사 (두 번 클릭하여 유지)", + "Bold (⌘B)" => "굵게 (⌘B)", + "Italic (⌘I)" => "기울임꼴 (⌘I)", + "Underline (⌘U)" => "밑줄 (⌘U)", + "Double Underline" => "이중 밑줄", + "Strikethrough" => "취소선", + "Underline" => "밑줄", + "Increase Font Size" => "글꼴 크기 늘리기", + "Decrease Font Size" => "글꼴 크기 줄이기", + "Wrap Text" => "텍스트 줄 바꿈", + "Merge & Center" => "병합하고 가운데 맞춤", + "Merge Cells" => "셀 병합", + "Merge Across" => "행 방향 병합", + "Unmerge Cells" => "셀 병합 취소", + "Fill Color" => "채우기 색", + "Font Color" => "글꼴 색", + "Borders" => "테두리", + "Top\nAlign" => "위쪽\n맞춤", + "Middle\nAlign" => "가운데\n맞춤", + "Bottom\nAlign" => "아래쪽\n맞춤", + "Left" => "왼쪽", + "Right" => "오른쪽", + "Center" => "가운데", + "Horizontal" => "가로", + "Vertical Text" => "세로 텍스트", + "Decrease Indent" => "들여쓰기 줄이기", + "Increase Indent" => "들여쓰기 늘리기", + "Orientation" => "방향", + "Angle Counterclockwise" => "시계 반대 방향 각도", + "Angle Clockwise" => "시계 방향 각도", + "Rotate Text Up" => "텍스트 위쪽으로 회전", + "Rotate Text Down" => "텍스트 아래쪽으로 회전", + "Accounting Number Format" => "회계 숫자 서식", + "Percent Style" => "백분율 스타일", + "Comma Style" => "쉼표 스타일", + "Increase Decimal" => "소수 자릿수 늘리기", + "Decrease Decimal" => "소수 자릿수 줄이기", + "More Accounting Formats…" => "회계 형식 더 보기…", + "Conditional\nFormatting" => "조건부\n서식", + "Conditional Formatting" => "조건부 서식", + "Format\nas Table" => "표 서식\n지정", + "Cell\nStyles" => "셀\n스타일", + "Format Cells…" => "셀 서식…", + "Format Cell Alignment…" => "셀 맞춤 서식…", + "Format\nPane" => "서식\n창", + "Format" => "서식", + "Insert" => "삽입", + "Insert Cells…" => "셀 삽입…", + "Delete" => "삭제", + "Delete Cells…" => "셀 삭제…", + "Insert Sheet Rows" => "시트 행 삽입", + "Insert Sheet Columns" => "시트 열 삽입", + "Delete Sheet Rows" => "시트 행 삭제", + "Delete Sheet Columns" => "시트 열 삭제", + "Row Height…" => "행 높이…", + "AutoFit Row Height" => "행 높이 자동 맞춤", + "Column Width…" => "열 너비…", + "AutoFit Column Width" => "열 너비 자동 맞춤", + "Default Width…" => "기본 너비…", + "Hide Rows" => "행 숨기기", + "Unhide Rows" => "행 숨기기 취소", + "Hide Columns" => "열 숨기기", + "Unhide Columns" => "열 숨기기 취소", + "Lock Cell" => "셀 잠금", + "Clear" => "지우기", + "Clear All" => "모두 지우기", + "Clear Formats" => "서식 지우기", + "Clear Contents" => "내용 지우기", + "Clear Comments and Notes" => "댓글 및 메모 지우기", + "Clear Hyperlinks" => "하이퍼링크 지우기", + "AutoSum" => "자동 합계", + "AutoSum (⌘⇧T)" => "자동 합계 (⌘⇧T)", + "Flash\nFill" => "빠른\n채우기", + "Flash Fill" => "빠른 채우기", + "Fill" => "채우기", + "Clear Print Area" => "인쇄 영역 지우기", + "Find &\nSelect" => "찾기 및\n선택", + "Find…" => "찾기…", + "Replace…" => "바꾸기…", + "Go To…" => "이동…", + "Go To Special…" => "선택하여 이동…", + "PivotTable" => "피벗 테이블", + "Recommended\nCharts" => "추천\n차트", + "Table" => "표", + "Pictures" => "그림", + "Shapes" => "도형", + "Icons" => "아이콘", + "Text\nBox" => "텍스트\n상자", + "Comment" => "댓글", + "New\nComment" => "새 댓글", + "New Note" => "새 메모", + "Show/Hide Note" => "메모 표시/숨기기", + "Header &\nFooter" => "머리글 및\n바닥글", + "Text to\nColumns" => "텍스트\n나누기", + "Link" => "링크", + "Symbol" => "기호", + "Sparklines" => "스파크라인", + "Header & Footer" => "머리글 및 바닥글", + "Draw with ink" => "잉크로 그리기", + "Eraser" => "지우개", + "Ink to\nShape" => "잉크를\n도형으로", + "Select\nObjects" => "개체\n선택", + "Themes" => "테마", + "Margins" => "여백", + "Size" => "용지 크기", + "Print\nArea" => "인쇄\n영역", + "Set Print Area" => "인쇄 영역 설정", + "Breaks" => "나누기", + "Insert Page Break" => "페이지 나누기 삽입", + "Remove Page Break" => "페이지 나누기 제거", + "Reset All Page Breaks" => "모든 페이지 나누기 다시 설정", + "Print\nTitles" => "인쇄\n제목", + "Narrow" => "좁게", + "Wide" => "넓게", + "Normal" => "보통", + "Portrait" => "세로", + "Landscape" => "가로", + "Custom Margins…" => "사용자 지정 여백…", + "Insert\nFunction" => "함수\n삽입", + "Name\nManager" => "이름\n관리자", + "Define Name" => "이름 정의", + "Use in Formula" => "수식에서 사용", + "Create from Selection" => "선택 영역에서 만들기", + "Trace Precedents" => "선행 셀 추적", + "Trace Dependents" => "종속 셀 추적", + "Remove Arrows" => "화살표 제거", + "Show Formulas" => "수식 표시", + "Error Checking" => "오류 검사", + "Evaluate Formula" => "수식 계산", + "Watch Window" => "감시 창", + "Calculation\nOptions" => "계산\n옵션", + "Calculate Now" => "지금 계산", + "Calculate Sheet" => "시트 계산", + "Automatic" => "자동", + "Automatic Except for Data Tables" => "데이터 표를 제외한 자동", + "Manual" => "수동", + "Sort &\nFilter" => "정렬 및\n필터", + "Sort" => "정렬", + "Sort A to Z" => "오름차순 정렬", + "Sort Z to A" => "내림차순 정렬", + "Custom Sort…" => "사용자 지정 정렬…", + "Filter" => "필터", + "Reapply" => "다시 적용", + "Get Data\n(Text/CSV)" => "데이터 가져오기\n(텍스트/CSV)", + "Remove\nDuplicates" => "중복\n항목 제거", + "Data\nValidation" => "데이터\n유효성 검사", + "Data Validation" => "데이터 유효성 검사", + "Data Validation…" => "데이터 유효성 검사…", + "Circle Invalid Data" => "잘못된 데이터 표시", + "Clear Validation" => "유효성 검사 지우기", + "Group" => "그룹", + "Ungroup" => "그룹 해제", + "Subtotal" => "부분합", + "What-If\nAnalysis" => "가상 분석", + "Data Table…" => "데이터 표…", + "Scenario Manager…" => "시나리오 관리자…", + "Goal Seek…" => "목표값 찾기…", + "Spelling" => "맞춤법 검사", + "Check\nAccessibility" => "접근성\n검사", + "Threaded Comments" => "스레드 댓글", + "Show\nComments" => "댓글\n표시", + "Protect\nWorkbook" => "통합 문서\n보호", + "Unprotect\nSheet" => "시트 보호\n해제", + "Protect Sheet…" => "시트 보호…", + "Comments" => "댓글", + "Notes" => "메모", + "Page Break\nPreview" => "페이지 나누기\n미리 보기", + "Page\nLayout" => "페이지\n레이아웃", + "Formula Bar" => "수식 입력줄", + "Gridlines" => "눈금선", + "Headings" => "머리글", + "Zoom" => "확대/축소", + "100%" => "100%", + "Zoom to\nSelection" => "선택 영역에\n맞춤", + "Freeze\nPanes" => "틀\n고정", + "Freeze Panes" => "틀 고정", + "Freeze Top Row" => "첫 행 고정", + "Freeze First Column" => "첫 열 고정", + "Unfreeze Panes" => "틀 고정 취소", + "Dark Mode" => "다크 모드", + "Interface language" => "인터페이스 언어", + "Command\nPalette" => "명령\n팔레트", + "Agent\nControl" => "에이전트\n제어", + "Action\nJournal" => "작업\n기록", + "About\nGridCraft" => "GridCraft\n정보", + "Share" => "공유", + "Add Chart\nElement" => "차트\n요소 추가", + "Change\nChart Type" => "차트 종류\n변경", + "Switch\nRow/Column" => "행/열\n전환", + "Data Labels: None" => "데이터 레이블: 없음", + "Data Labels: Show" => "데이터 레이블: 표시", + "Legend: None" => "범례: 없음", + "Legend: Bottom" => "범례: 아래쪽", + "Legend: Top" => "범례: 위쪽", + "Legend: Right" => "범례: 오른쪽", + "Gridlines: None" => "눈금선: 없음", + "Gridlines: Show" => "눈금선: 표시", + "Chart\nTitle" => "차트\n제목", + "Delete\nChart" => "차트\n삭제", + "Convert\nto Range" => "범위로\n변환", + "Table\nStyles" => "표\n스타일", + "Top 10 Items" => "상위 10개 항목", + "Top 10%" => "상위 10%", + "Bottom 10 Items" => "하위 10개 항목", + "Bottom 10%" => "하위 10%", + "Above Average" => "평균 초과", + "Below Average" => "평균 미만", + "Clear Rules from Entire Sheet" => "시트 전체에서 규칙 지우기", + "Clear Rules from Selected Cells" => "선택한 셀에서 규칙 지우기", + "Constants" => "상수", + "Data Bars" => "데이터 막대", + "Color Scales" => "색조", + "Icon Sets" => "아이콘 집합", + "Home" => "홈", + "Draw" => "그리기", + "Page Layout" => "페이지 레이아웃", + "Formulas" => "수식", + "Data" => "데이터", + "Review" => "검토", + "View" => "보기", + "Automate" => "자동화", + "Table Design" => "표 디자인", + "Chart Design" => "차트 디자인", + "Ready" => "준비", + "Enter" => "입력", + "Edit" => "편집", + "Point" => "가리키기", + "Calculate" => "계산", + "Select destination and press Enter or choose Paste" => "대상을 선택하고 Enter 키를 누르거나 [붙여넣기]를 선택하세요", + "General" => "일반", + "Number" => "숫자", + "Currency" => "통화", + "Accounting" => "회계", + "Date" => "날짜", + "Time" => "시간", + "Percentage" => "백분율", + "Fraction" => "분수", + "Scientific" => "과학", + "Text" => "텍스트", + "Special" => "특수", + "Custom" => "사용자 지정", + "Short Date" => "간단한 날짜", + "Long Date" => "자세한 날짜", + "More Number Formats…" => "숫자 서식 더 보기…", + "Financial" => "재무", + "Logical" => "논리", + "Date &\nTime" => "날짜 및\n시간", + "Lookup &\nReference" => "조회 및\n참조", + "Math &\nTrig" => "수학 및\n삼각", + "More\nFunctions" => "기타\n함수", + "Screen" => "화면", + "Print" => "인쇄", + _ => return None, + }) +} diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs new file mode 100644 index 0000000000..e55bcf5744 --- /dev/null +++ b/crates/ui-egui/src/i18n/ru.rs @@ -0,0 +1,268 @@ +//! Russian translations for the interface strings in i18n.rs. + +pub(super) fn translate(text: &str) -> Option<&'static str> { + Some(match text { + "Paste" => "Вставить", + "Paste Values" => "Вставить значения", + "Paste Formulas" => "Вставить формулы", + "Paste Formatting" => "Вставить форматирование", + "Transpose" => "Транспонировать", + "Paste Link" => "Вставить связь", + "Paste Special…" => "Специальная вставка…", + "Cut (⌘X)" => "Вырезать (⌘X)", + "Copy (⌘C)" => "Копировать (⌘C)", + "Format Painter (double-click to keep it on)" => "Формат по образцу (дважды щёлкните, чтобы закрепить)", + "Bold (⌘B)" => "Полужирный (⌘B)", + "Italic (⌘I)" => "Курсив (⌘I)", + "Underline (⌘U)" => "Подчёркивание (⌘U)", + "Double Underline" => "Двойное подчёркивание", + "Strikethrough" => "Зачёркивание", + "Underline" => "Подчёркивание", + "Increase Font Size" => "Увеличить размер шрифта", + "Decrease Font Size" => "Уменьшить размер шрифта", + "Wrap Text" => "Переносить текст", + "Merge & Center" => "Объединить и поместить в центре", + "Merge Cells" => "Объединить ячейки", + "Merge Across" => "Объединить по строкам", + "Unmerge Cells" => "Отменить объединение ячеек", + "Fill Color" => "Цвет заливки", + "Font Color" => "Цвет шрифта", + "Borders" => "Границы", + "Top\nAlign" => "По верхнему\nкраю", + "Middle\nAlign" => "По центру\nвертикали", + "Bottom\nAlign" => "По нижнему\nкраю", + "Left" => "Слева", + "Right" => "Справа", + "Center" => "По центру", + "Horizontal" => "По горизонтали", + "Vertical Text" => "Вертикальный текст", + "Decrease Indent" => "Уменьшить отступ", + "Increase Indent" => "Увеличить отступ", + "Orientation" => "Ориентация", + "Angle Counterclockwise" => "Повернуть против часовой стрелки", + "Angle Clockwise" => "Повернуть по часовой стрелке", + "Rotate Text Up" => "Повернуть текст вверх", + "Rotate Text Down" => "Повернуть текст вниз", + "Accounting Number Format" => "Финансовый числовой формат", + "Percent Style" => "Процентный формат", + "Comma Style" => "Разделитель разрядов", + "Increase Decimal" => "Увеличить разрядность", + "Decrease Decimal" => "Уменьшить разрядность", + "More Accounting Formats…" => "Другие финансовые форматы…", + "Conditional\nFormatting" => "Условное\nформатирование", + "Conditional Formatting" => "Условное форматирование", + "Format\nas Table" => "Форматировать\nкак таблицу", + "Cell\nStyles" => "Стили\nячеек", + "Format Cells…" => "Формат ячеек…", + "Format Cell Alignment…" => "Выравнивание ячеек…", + "Format\nPane" => "Область\nформатирования", + "Format" => "Формат", + "Insert" => "Вставить", + "Insert Cells…" => "Вставить ячейки…", + "Delete" => "Удалить", + "Delete Cells…" => "Удалить ячейки…", + "Insert Sheet Rows" => "Вставить строки листа", + "Insert Sheet Columns" => "Вставить столбцы листа", + "Delete Sheet Rows" => "Удалить строки листа", + "Delete Sheet Columns" => "Удалить столбцы листа", + "Row Height…" => "Высота строки…", + "AutoFit Row Height" => "Автоподбор высоты строки", + "Column Width…" => "Ширина столбца…", + "AutoFit Column Width" => "Автоподбор ширины столбца", + "Default Width…" => "Ширина по умолчанию…", + "Hide Rows" => "Скрыть строки", + "Unhide Rows" => "Показать строки", + "Hide Columns" => "Скрыть столбцы", + "Unhide Columns" => "Показать столбцы", + "Lock Cell" => "Заблокировать ячейку", + "Clear" => "Очистить", + "Clear All" => "Очистить всё", + "Clear Formats" => "Очистить форматы", + "Clear Contents" => "Очистить содержимое", + "Clear Comments and Notes" => "Удалить комментарии и заметки", + "Clear Hyperlinks" => "Удалить гиперссылки", + "AutoSum" => "Автосумма", + "AutoSum (⌘⇧T)" => "Автосумма (⌘⇧T)", + "Flash\nFill" => "Мгновенное\nзаполнение", + "Flash Fill" => "Мгновенное заполнение", + "Fill" => "Заполнить", + "Clear Print Area" => "Очистить область печати", + "Find &\nSelect" => "Найти и\nвыделить", + "Find…" => "Найти…", + "Replace…" => "Заменить…", + "Go To…" => "Перейти…", + "Go To Special…" => "Выделить группу ячеек…", + "PivotTable" => "Сводная таблица", + "Recommended\nCharts" => "Рекомендуемые\nдиаграммы", + "Table" => "Таблица", + "Pictures" => "Изображения", + "Shapes" => "Фигуры", + "Icons" => "Значки", + "Text\nBox" => "Текстовое\nполе", + "Comment" => "Комментарий", + "New\nComment" => "Новый\nкомментарий", + "New Note" => "Новая заметка", + "Show/Hide Note" => "Показать/скрыть заметку", + "Header &\nFooter" => "Верхний и\nнижний колонтитулы", + "Text to\nColumns" => "Текст\nпо столбцам", + "Link" => "Ссылка", + "Symbol" => "Символ", + "Sparklines" => "Спарклайны", + "Header & Footer" => "Верхний и нижний колонтитулы", + "Draw with ink" => "Рисование от руки", + "Eraser" => "Ластик", + "Ink to\nShape" => "Преобразовать рукописный\nввод в фигуру", + "Select\nObjects" => "Выбрать\nобъекты", + "Themes" => "Темы", + "Margins" => "Поля", + "Size" => "Размер", + "Print\nArea" => "Область\nпечати", + "Set Print Area" => "Задать область печати", + "Breaks" => "Разрывы", + "Insert Page Break" => "Вставить разрыв страницы", + "Remove Page Break" => "Удалить разрыв страницы", + "Reset All Page Breaks" => "Сбросить все разрывы страниц", + "Print\nTitles" => "Печатать\nзаголовки", + "Narrow" => "Узкие", + "Wide" => "Широкие", + "Normal" => "Обычные", + "Portrait" => "Книжная", + "Landscape" => "Альбомная", + "Custom Margins…" => "Настраиваемые поля…", + "Insert\nFunction" => "Вставить\nфункцию", + "Name\nManager" => "Диспетчер\nимён", + "Define Name" => "Присвоить имя", + "Use in Formula" => "Использовать в формуле", + "Create from Selection" => "Создать из выделенного", + "Trace Precedents" => "Влияющие ячейки", + "Trace Dependents" => "Зависимые ячейки", + "Remove Arrows" => "Убрать стрелки", + "Show Formulas" => "Показать формулы", + "Error Checking" => "Проверка ошибок", + "Evaluate Formula" => "Вычислить формулу", + "Watch Window" => "Окно контрольных значений", + "Calculation\nOptions" => "Параметры\nвычислений", + "Calculate Now" => "Вычислить сейчас", + "Calculate Sheet" => "Вычислить лист", + "Automatic" => "Автоматически", + "Automatic Except for Data Tables" => "Автоматически, кроме таблиц данных", + "Manual" => "Вручную", + "Sort &\nFilter" => "Сортировка и\nфильтр", + "Sort" => "Сортировка", + "Sort A to Z" => "Сортировка от А до Я", + "Sort Z to A" => "Сортировка от Я до А", + "Custom Sort…" => "Настраиваемая сортировка…", + "Filter" => "Фильтр", + "Reapply" => "Повторить", + "Get Data\n(Text/CSV)" => "Получить данные\n(текст/CSV)", + "Remove\nDuplicates" => "Удалить\nдубликаты", + "Data\nValidation" => "Проверка\nданных", + "Data Validation" => "Проверка данных", + "Data Validation…" => "Проверка данных…", + "Circle Invalid Data" => "Обвести неверные данные", + "Clear Validation" => "Очистить проверку данных", + "Group" => "Группировать", + "Ungroup" => "Разгруппировать", + "Subtotal" => "Промежуточный итог", + "What-If\nAnalysis" => "Анализ «что\nесли»", + "Data Table…" => "Таблица данных…", + "Scenario Manager…" => "Диспетчер сценариев…", + "Goal Seek…" => "Подбор параметра…", + "Spelling" => "Орфография", + "Check\nAccessibility" => "Проверка\nдоступности", + "Threaded Comments" => "Комментарии с ветками", + "Show\nComments" => "Показать\nкомментарии", + "Protect\nWorkbook" => "Защитить\nкнигу", + "Unprotect\nSheet" => "Снять защиту\nлиста", + "Protect Sheet…" => "Защитить лист…", + "Comments" => "Комментарии", + "Notes" => "Заметки", + "Page Break\nPreview" => "Предварительный просмотр\nразрывов страниц", + "Page\nLayout" => "Разметка\nстраницы", + "Formula Bar" => "Строка формул", + "Gridlines" => "Сетка", + "Headings" => "Заголовки", + "Zoom" => "Масштаб", + "100%" => "100%", + "Zoom to\nSelection" => "Масштаб по\nвыделению", + "Freeze\nPanes" => "Закрепить\nобласти", + "Freeze Panes" => "Закрепить области", + "Freeze Top Row" => "Закрепить верхнюю строку", + "Freeze First Column" => "Закрепить первый столбец", + "Unfreeze Panes" => "Снять закрепление областей", + "Dark Mode" => "Тёмный режим", + "Interface language" => "Язык интерфейса", + "Command\nPalette" => "Палитра\nкоманд", + "Agent\nControl" => "Управление\nагентом", + "Action\nJournal" => "Журнал\nдействий", + "About\nGridCraft" => "О\nGridCraft", + "Share" => "Поделиться", + "Add Chart\nElement" => "Добавить элемент\nдиаграммы", + "Change\nChart Type" => "Изменить тип\nдиаграммы", + "Switch\nRow/Column" => "Поменять\nстроки/столбцы", + "Data Labels: None" => "Подписи данных: нет", + "Data Labels: Show" => "Подписи данных: показать", + "Legend: None" => "Легенда: нет", + "Legend: Bottom" => "Легенда: снизу", + "Legend: Top" => "Легенда: сверху", + "Legend: Right" => "Легенда: справа", + "Gridlines: None" => "Линии сетки: нет", + "Gridlines: Show" => "Линии сетки: показать", + "Chart\nTitle" => "Название\nдиаграммы", + "Delete\nChart" => "Удалить\nдиаграмму", + "Convert\nto Range" => "Преобразовать\nв диапазон", + "Table\nStyles" => "Стили\nтаблиц", + "Top 10 Items" => "Первые 10 элементов", + "Top 10%" => "Верхние 10%", + "Bottom 10 Items" => "Последние 10 элементов", + "Bottom 10%" => "Нижние 10%", + "Above Average" => "Выше среднего", + "Below Average" => "Ниже среднего", + "Clear Rules from Entire Sheet" => "Очистить правила на всём листе", + "Clear Rules from Selected Cells" => "Очистить правила для выделенных ячеек", + "Constants" => "Константы", + "Data Bars" => "Гистограммы", + "Color Scales" => "Цветовые шкалы", + "Icon Sets" => "Наборы значков", + "Home" => "Главная", + "Draw" => "Рисование", + "Page Layout" => "Разметка страницы", + "Formulas" => "Формулы", + "Data" => "Данные", + "Review" => "Рецензирование", + "View" => "Вид", + "Automate" => "Автоматизация", + "Table Design" => "Конструктор таблиц", + "Chart Design" => "Конструктор диаграмм", + "Ready" => "Готово", + "Enter" => "Ввод", + "Edit" => "Изменение", + "Point" => "Указание", + "Calculate" => "Вычисление", + "Select destination and press Enter or choose Paste" => "Выберите место вставки и нажмите Enter или выберите «Вставить»", + "General" => "Общий", + "Number" => "Числовой", + "Currency" => "Денежный", + "Accounting" => "Финансовый", + "Date" => "Дата", + "Time" => "Время", + "Percentage" => "Процентный", + "Fraction" => "Дробный", + "Scientific" => "Экспоненциальный", + "Text" => "Текстовый", + "Special" => "Дополнительный", + "Custom" => "Пользовательский", + "Short Date" => "Краткая дата", + "Long Date" => "Длинная дата", + "More Number Formats…" => "Другие числовые форматы…", + "Financial" => "Финансовые", + "Logical" => "Логические", + "Date &\nTime" => "Дата и\nвремя", + "Lookup &\nReference" => "Поиск и\nссылки", + "Math &\nTrig" => "Математические и\nтригонометрические", + "More\nFunctions" => "Другие\nфункции", + "Screen" => "На экране", + "Print" => "Печать", + _ => return None, + }) +} diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs new file mode 100644 index 0000000000..9b2c66f944 --- /dev/null +++ b/crates/ui-egui/src/i18n/zh.rs @@ -0,0 +1,268 @@ +//! Simplified Chinese translations for the interface strings in i18n.rs. + +pub(super) fn translate(text: &str) -> Option<&'static str> { + Some(match text { + "Paste" => "粘贴", + "Paste Values" => "粘贴值", + "Paste Formulas" => "粘贴公式", + "Paste Formatting" => "粘贴格式", + "Transpose" => "转置", + "Paste Link" => "粘贴链接", + "Paste Special…" => "选择性粘贴…", + "Cut (⌘X)" => "剪切 (⌘X)", + "Copy (⌘C)" => "复制 (⌘C)", + "Format Painter (double-click to keep it on)" => "格式刷(双击可持续使用)", + "Bold (⌘B)" => "粗体 (⌘B)", + "Italic (⌘I)" => "斜体 (⌘I)", + "Underline (⌘U)" => "下划线 (⌘U)", + "Double Underline" => "双下划线", + "Strikethrough" => "删除线", + "Underline" => "下划线", + "Increase Font Size" => "增大字号", + "Decrease Font Size" => "减小字号", + "Wrap Text" => "自动换行", + "Merge & Center" => "合并后居中", + "Merge Cells" => "合并单元格", + "Merge Across" => "跨行合并", + "Unmerge Cells" => "取消合并单元格", + "Fill Color" => "填充颜色", + "Font Color" => "字体颜色", + "Borders" => "边框", + "Top\nAlign" => "顶端对齐", + "Middle\nAlign" => "垂直居中", + "Bottom\nAlign" => "底端对齐", + "Left" => "左对齐", + "Right" => "右对齐", + "Center" => "居中", + "Horizontal" => "水平", + "Vertical Text" => "竖排文字", + "Decrease Indent" => "减少缩进", + "Increase Indent" => "增加缩进", + "Orientation" => "文字方向", + "Angle Counterclockwise" => "逆时针旋转", + "Angle Clockwise" => "顺时针旋转", + "Rotate Text Up" => "文字向上旋转", + "Rotate Text Down" => "文字向下旋转", + "Accounting Number Format" => "会计数字格式", + "Percent Style" => "百分比样式", + "Comma Style" => "千位分隔样式", + "Increase Decimal" => "增加小数位数", + "Decrease Decimal" => "减少小数位数", + "More Accounting Formats…" => "更多会计格式…", + "Conditional\nFormatting" => "条件\n格式", + "Conditional Formatting" => "条件格式", + "Format\nas Table" => "套用表格\n格式", + "Cell\nStyles" => "单元格\n样式", + "Format Cells…" => "设置单元格格式…", + "Format Cell Alignment…" => "设置单元格对齐方式…", + "Format\nPane" => "格式\n窗格", + "Format" => "格式", + "Insert" => "插入", + "Insert Cells…" => "插入单元格…", + "Delete" => "删除", + "Delete Cells…" => "删除单元格…", + "Insert Sheet Rows" => "插入工作表行", + "Insert Sheet Columns" => "插入工作表列", + "Delete Sheet Rows" => "删除工作表行", + "Delete Sheet Columns" => "删除工作表列", + "Row Height…" => "行高…", + "AutoFit Row Height" => "自动调整行高", + "Column Width…" => "列宽…", + "AutoFit Column Width" => "自动调整列宽", + "Default Width…" => "默认列宽…", + "Hide Rows" => "隐藏行", + "Unhide Rows" => "取消隐藏行", + "Hide Columns" => "隐藏列", + "Unhide Columns" => "取消隐藏列", + "Lock Cell" => "锁定单元格", + "Clear" => "清除", + "Clear All" => "全部清除", + "Clear Formats" => "清除格式", + "Clear Contents" => "清除内容", + "Clear Comments and Notes" => "清除批注和备注", + "Clear Hyperlinks" => "清除超链接", + "AutoSum" => "自动求和", + "AutoSum (⌘⇧T)" => "自动求和 (⌘⇧T)", + "Flash\nFill" => "快速\n填充", + "Flash Fill" => "快速填充", + "Fill" => "填充", + "Clear Print Area" => "清除打印区域", + "Find &\nSelect" => "查找与\n选择", + "Find…" => "查找…", + "Replace…" => "替换…", + "Go To…" => "定位…", + "Go To Special…" => "定位条件…", + "PivotTable" => "数据透视表", + "Recommended\nCharts" => "推荐\n图表", + "Table" => "表格", + "Pictures" => "图片", + "Shapes" => "形状", + "Icons" => "图标", + "Text\nBox" => "文本\n框", + "Comment" => "批注", + "New\nComment" => "新建\n批注", + "New Note" => "新建备注", + "Show/Hide Note" => "显示/隐藏备注", + "Header &\nFooter" => "页眉和\n页脚", + "Text to\nColumns" => "分列", + "Link" => "链接", + "Symbol" => "符号", + "Sparklines" => "迷你图", + "Header & Footer" => "页眉和页脚", + "Draw with ink" => "墨迹绘制", + "Eraser" => "橡皮擦", + "Ink to\nShape" => "墨迹转\n形状", + "Select\nObjects" => "选择\n对象", + "Themes" => "主题", + "Margins" => "页边距", + "Size" => "纸张大小", + "Print\nArea" => "打印\n区域", + "Set Print Area" => "设置打印区域", + "Breaks" => "分页符", + "Insert Page Break" => "插入分页符", + "Remove Page Break" => "删除分页符", + "Reset All Page Breaks" => "重置所有分页符", + "Print\nTitles" => "打印\n标题", + "Narrow" => "窄", + "Wide" => "宽", + "Normal" => "普通", + "Portrait" => "纵向", + "Landscape" => "横向", + "Custom Margins…" => "自定义页边距…", + "Insert\nFunction" => "插入\n函数", + "Name\nManager" => "名称\n管理器", + "Define Name" => "定义名称", + "Use in Formula" => "在公式中使用", + "Create from Selection" => "根据所选内容创建", + "Trace Precedents" => "追踪引用单元格", + "Trace Dependents" => "追踪从属单元格", + "Remove Arrows" => "删除箭头", + "Show Formulas" => "显示公式", + "Error Checking" => "错误检查", + "Evaluate Formula" => "公式求值", + "Watch Window" => "监视窗口", + "Calculation\nOptions" => "计算\n选项", + "Calculate Now" => "立即计算", + "Calculate Sheet" => "计算工作表", + "Automatic" => "自动", + "Automatic Except for Data Tables" => "除数据表以外自动", + "Manual" => "手动", + "Sort &\nFilter" => "排序和\n筛选", + "Sort" => "排序", + "Sort A to Z" => "升序排序", + "Sort Z to A" => "降序排序", + "Custom Sort…" => "自定义排序…", + "Filter" => "筛选", + "Reapply" => "重新应用", + "Get Data\n(Text/CSV)" => "获取数据\n(文本/CSV)", + "Remove\nDuplicates" => "删除\n重复项", + "Data\nValidation" => "数据\n验证", + "Data Validation" => "数据验证", + "Data Validation…" => "数据验证…", + "Circle Invalid Data" => "圈出无效数据", + "Clear Validation" => "清除验证", + "Group" => "组合", + "Ungroup" => "取消组合", + "Subtotal" => "分类汇总", + "What-If\nAnalysis" => "假设分析", + "Data Table…" => "数据表…", + "Scenario Manager…" => "方案管理器…", + "Goal Seek…" => "单变量求解…", + "Spelling" => "拼写检查", + "Check\nAccessibility" => "检查\n辅助功能", + "Threaded Comments" => "线程式批注", + "Show\nComments" => "显示\n批注", + "Protect\nWorkbook" => "保护\n工作簿", + "Unprotect\nSheet" => "撤销\n工作表保护", + "Protect Sheet…" => "保护工作表…", + "Comments" => "批注", + "Notes" => "备注", + "Page Break\nPreview" => "分页符\n预览", + "Page\nLayout" => "页面\n布局", + "Formula Bar" => "编辑栏", + "Gridlines" => "网格线", + "Headings" => "标题", + "Zoom" => "缩放", + "100%" => "100%", + "Zoom to\nSelection" => "缩放到\n所选内容", + "Freeze\nPanes" => "冻结\n窗格", + "Freeze Panes" => "冻结窗格", + "Freeze Top Row" => "冻结首行", + "Freeze First Column" => "冻结首列", + "Unfreeze Panes" => "取消冻结窗格", + "Dark Mode" => "深色模式", + "Interface language" => "界面语言", + "Command\nPalette" => "命令\n面板", + "Agent\nControl" => "智能体\n控制", + "Action\nJournal" => "操作\n日志", + "About\nGridCraft" => "关于\nGridCraft", + "Share" => "分享", + "Add Chart\nElement" => "添加图表\n元素", + "Change\nChart Type" => "更改\n图表类型", + "Switch\nRow/Column" => "切换\n行/列", + "Data Labels: None" => "数据标签:无", + "Data Labels: Show" => "数据标签:显示", + "Legend: None" => "图例:无", + "Legend: Bottom" => "图例:底部", + "Legend: Top" => "图例:顶部", + "Legend: Right" => "图例:右侧", + "Gridlines: None" => "网格线:无", + "Gridlines: Show" => "网格线:显示", + "Chart\nTitle" => "图表\n标题", + "Delete\nChart" => "删除\n图表", + "Convert\nto Range" => "转换\n为区域", + "Table\nStyles" => "表格\n样式", + "Top 10 Items" => "前 10 项", + "Top 10%" => "前 10%", + "Bottom 10 Items" => "后 10 项", + "Bottom 10%" => "后 10%", + "Above Average" => "高于平均值", + "Below Average" => "低于平均值", + "Clear Rules from Entire Sheet" => "清除整张工作表的规则", + "Clear Rules from Selected Cells" => "清除所选单元格的规则", + "Constants" => "常量", + "Data Bars" => "数据条", + "Color Scales" => "色阶", + "Icon Sets" => "图标集", + "Home" => "开始", + "Draw" => "绘图", + "Page Layout" => "页面布局", + "Formulas" => "公式", + "Data" => "数据", + "Review" => "审阅", + "View" => "视图", + "Automate" => "自动化", + "Table Design" => "表格设计", + "Chart Design" => "图表设计", + "Ready" => "就绪", + "Enter" => "输入", + "Edit" => "编辑", + "Point" => "指向", + "Calculate" => "计算", + "Select destination and press Enter or choose Paste" => "选择目标位置并按 Enter,或选择“粘贴”", + "General" => "常规", + "Number" => "数值", + "Currency" => "货币", + "Accounting" => "会计专用", + "Date" => "日期", + "Time" => "时间", + "Percentage" => "百分比", + "Fraction" => "分数", + "Scientific" => "科学记数法", + "Text" => "文本", + "Special" => "特殊", + "Custom" => "自定义", + "Short Date" => "短日期", + "Long Date" => "长日期", + "More Number Formats…" => "更多数字格式…", + "Financial" => "财务", + "Logical" => "逻辑", + "Date &\nTime" => "日期和\n时间", + "Lookup &\nReference" => "查找和\n引用", + "Math &\nTrig" => "数学和\n三角函数", + "More\nFunctions" => "更多\n函数", + "Screen" => "屏幕", + "Print" => "打印", + _ => return None, + }) +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4e7a383e4a..ff1a734263 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -109,6 +109,7 @@ pub struct SheetApp { pub perf: Perf, pub fonts_ready: bool, fonts_set: bool, + fonts_language: Option, pub name_box: Option, pub(crate) shots: control::Shots, /// Chart selected on the sheet (id). @@ -138,6 +139,7 @@ impl SheetApp { perf: Perf::default(), fonts_ready: false, fonts_set: false, + fonts_language: None, name_box: None, shots: control::Shots::default(), selected_chart: None, @@ -145,9 +147,14 @@ impl SheetApp { } } - /// One-time context setup: fonts and visuals. + /// One-time context setup: fonts and visuals, using the system's preferred language. pub fn setup_context(ctx: &egui::Context, dark: bool) { - ctx.set_fonts(theme::font_definitions()); + Self::setup_context_for_language(ctx, dark, i18n::Language::system()); + } + + /// Sets up fonts and visuals for a specific persisted interface language. + pub fn setup_context_for_language(ctx: &egui::Context, dark: bool, language: i18n::Language) { + ctx.set_fonts(theme::font_definitions_for_language(language)); theme::apply(ctx, dark); } @@ -199,7 +206,10 @@ impl SheetApp { self.ui.language = l; Ok(json!({"language": l})) } - None => Err(format!("unknown language {:?} (use \"en\" or \"ja\")", p.get("language").and_then(Json::as_str).unwrap_or(""))), + None => Err(format!( + "unknown language {:?} (use \"en\", \"zh\", \"ja\", \"ko\" or \"ru\")", + p.get("language").and_then(Json::as_str).unwrap_or("") + )), } } "app.language.english" => { @@ -375,13 +385,18 @@ impl SheetApp { /// Per-frame logic (control channel, screenshots). Call before `ui`. pub fn logic(&mut self, ctx: &egui::Context) { + if self.fonts_language.is_some_and(|language| language != self.ui.language) { + self.fonts_ready = false; + self.fonts_set = false; + } if !self.fonts_ready { // New fonts apply from the next frame on: paint nothing until then. if self.fonts_set { self.fonts_ready = true; } else { - SheetApp::setup_context(ctx, self.ui.dark); + SheetApp::setup_context_for_language(ctx, self.ui.dark, self.ui.language); self.fonts_set = true; + self.fonts_language = Some(self.ui.language); ctx.request_repaint(); } } diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 52bc34b809..e436485b6f 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1268,7 +1268,8 @@ fn page_layout(app: &mut SheetApp, ui: &mut Ui) { .unwrap_or((true, true, false, false)); // These two checkboxes mean the screen view vs. the printed page, so they do not share the // "View" tab label; pick per language rather than through the shared table. - let (screen, print) = if app.ui.language == crate::i18n::Language::Ja { ("画面", "印刷") } else { ("View", "Print") }; + let screen = app.ui.language.tr("Screen"); + let print = app.ui.language.tr("Print"); ui.vertical(|ui| { ui.label(egui::RichText::new(app.ui.language.tr("Gridlines")).strong().small()); let mut v = sh.0; @@ -1588,8 +1589,7 @@ fn view(app: &mut SheetApp, ui: &mut Ui) { |ui| { for l in crate::i18n::Language::ALL { if ui.selectable_label(l == lang, l.name()).clicked() { - let code = if l == crate::i18n::Language::Ja { "app.language.japanese" } else { "app.language.english" }; - act(app, code, json!({})); + act(app, "app.language.set", json!({"language": l.code()})); } } }, diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index e14b9f880b..e69ca527f7 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -289,12 +289,18 @@ fn candidates(role: &str) -> Vec<(String, u32)> { /// Builds the font set from system fonts (with egui's defaults as fallback). pub fn font_definitions() -> FontDefinitions { + font_definitions_for_language(crate::i18n::Language::system()) +} + +/// Builds the font set with CJK glyph shapes ordered for the selected interface language. +pub fn font_definitions_for_language(language: crate::i18n::Language) -> FontDefinitions { let mut fonts = FontDefinitions::default(); let base_prop: Vec = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default(); let base_mono: Vec = fonts.families.get(&FontFamily::Monospace).cloned().unwrap_or_default(); // CJK has to sit at the end of each chain: a Latin font owns Latin, and epaint picks the first - // face that has the glyph, so the CJK faces only ever catch Han/Kana/Hangul. - let cjk = load_cjk(&mut fonts); + // face that has the glyph, so the CJK faces only ever catch Han/Kana/Hangul. Keep both + // simplified-Chinese and Japanese Han faces: either font may lack a less common glyph. + let cjk = load_cjk(&mut fonts, language); for role in [UI, UI_BOLD, CELL, CELL_BOLD, CELL_ITALIC, CELL_BOLD_ITALIC, SERIF, MONO] { let paths = candidates(role); let refs: Vec<(&str, u32)> = paths.iter().map(|(p, i)| (p.as_str(), *i)).collect(); @@ -324,40 +330,64 @@ pub fn font_definitions() -> FontDefinitions { /// family can carry them as fallback. egui's bundled fonts have no CJK coverage, so without this a /// Japanese or Chinese workbook renders as tofu boxes even though the text was read correctly. #[cfg(not(target_arch = "wasm32"))] -fn load_cjk(fonts: &mut FontDefinitions) -> Vec { - let mut keys = Vec::new(); - for (key, cands) in [("sys-cjk-han", cjk_han()), ("sys-cjk-hangul", cjk_hangul())] { - let refs: Vec<(&str, u32)> = cands.iter().map(|(p, i)| (p.as_str(), *i)).collect(); - if let Some(fd) = try_load(&refs) { - fonts.font_data.insert(key.to_string(), Arc::new(fd)); - keys.push(key.to_string()); - } - } - keys +fn load_cjk(fonts: &mut FontDefinitions, language: crate::i18n::Language) -> Vec { + let han_ja = load_cjk_face(fonts, "sys-cjk-han-ja", cjk_han_japanese()); + let han_zh = load_cjk_face(fonts, "sys-cjk-han-zh", cjk_han_simplified()); + let hangul = load_cjk_face(fonts, "sys-cjk-hangul", cjk_hangul()); + let order = match language { + crate::i18n::Language::Ja => [han_ja, han_zh, hangul], + crate::i18n::Language::Ko => [hangul, han_zh, han_ja], + _ => [han_zh, han_ja, hangul], + }; + order.into_iter().flatten().collect() } #[cfg(target_arch = "wasm32")] -fn load_cjk(_fonts: &mut FontDefinitions) -> Vec { +fn load_cjk(_fonts: &mut FontDefinitions, _language: crate::i18n::Language) -> Vec { Vec::new() } -/// Han + Kana faces, in fallback order. A Japanese face comes first (kana and JIS kanji render -/// with Japanese glyph shapes); a Chinese face follows to widen coverage. Every CJK face carries -/// kana, so any of them renders Japanese; the order only decides kanji glyph style. #[cfg(not(target_arch = "wasm32"))] -fn cjk_han() -> Vec<(String, u32)> { - let mac = "/System/Library/Fonts"; +fn load_cjk_face(fonts: &mut FontDefinitions, key: &str, candidates: Vec<(String, u32)>) -> Option { + let refs: Vec<(&str, u32)> = candidates.iter().map(|(path, index)| (path.as_str(), *index)).collect(); + let fd = try_load(&refs)?; + fonts.font_data.insert(key.to_string(), Arc::new(fd)); + Some(key.to_string()) +} + +/// Japanese Han/Kana faces. A Japanese face goes first when the interface is Japanese so kanji +/// use Japanese glyph shapes; Chinese remains later in the chain for glyphs it does not contain. +#[cfg(not(target_arch = "wasm32"))] +fn cjk_han_japanese() -> Vec<(String, u32)> { let win = std::env::var("WINDIR").map(|w| format!("{w}\\Fonts")).unwrap_or_else(|_| "C:\\Windows\\Fonts".into()); - let lin = ["/usr/share/fonts/opentype/noto", "/usr/share/fonts/truetype/noto", "/usr/share/fonts/truetype", "/usr/share/fonts"]; let mut v: Vec<(String, u32)> = Vec::new(); v.push((format!("{win}\\YuGothR.ttc"), 0)); // Yu Gothic (Japanese) v.push((format!("{win}\\msgothic.ttc"), 0)); // MS Gothic (Japanese) - v.push((format!("{win}\\msyh.ttc"), 0)); // Microsoft YaHei (Chinese) - v.push((format!("{mac}/Hiragino Sans GB.ttc"), 0)); - v.push((format!("{mac}/PingFang.ttc"), 0)); + v.push(("/System/Library/Fonts/Hiragino Sans W3.ttc".into(), 0)); + v.push(("/System/Library/Fonts/ヒラギノ角ゴシック W3.ttc".into(), 0)); + let lin = ["/usr/share/fonts/opentype/noto", "/usr/share/fonts/truetype/noto", "/usr/share/fonts/truetype", "/usr/share/fonts"]; for d in lin { - v.push((format!("{d}/NotoSansCJK-Regular.ttc"), 0)); v.push((format!("{d}/NotoSansCJKjp-Regular.otf"), 0)); + v.push((format!("{d}/NotoSansCJK-Regular.ttc"), 0)); + } + v +} + +/// Simplified Chinese Han faces. These are loaded separately from Japanese fonts so a missing +/// glyph in the first face can continue through the family chain instead of becoming tofu. +#[cfg(not(target_arch = "wasm32"))] +fn cjk_han_simplified() -> Vec<(String, u32)> { + let win = std::env::var("WINDIR").map(|w| format!("{w}\\Fonts")).unwrap_or_else(|_| "C:\\Windows\\Fonts".into()); + let mut v: Vec<(String, u32)> = Vec::new(); + v.push((format!("{win}\\msyh.ttc"), 0)); // Microsoft YaHei + v.push((format!("{win}\\simsun.ttc"), 0)); // SimSun + v.push((format!("{win}\\simhei.ttf"), 0)); // SimHei + v.push(("/System/Library/Fonts/PingFang.ttc".into(), 0)); + v.push(("/System/Library/Fonts/Hiragino Sans GB.ttc".into(), 0)); + let lin = ["/usr/share/fonts/opentype/noto", "/usr/share/fonts/truetype/noto", "/usr/share/fonts/truetype", "/usr/share/fonts"]; + for d in lin { + v.push((format!("{d}/NotoSansCJKsc-Regular.otf"), 0)); + v.push((format!("{d}/NotoSansCJK-Regular.ttc"), 2)); // Simplified Chinese face in the Noto collection v.push((format!("{d}/wqy-microhei.ttc"), 0)); } v @@ -374,7 +404,7 @@ fn cjk_hangul() -> Vec<(String, u32)> { v.push((format!("{mac}/AppleSDGothicNeo.ttc"), 0)); for d in lin { v.push((format!("{d}/NotoSansCJKkr-Regular.otf"), 0)); - v.push((format!("{d}/NotoSansCJK-Regular.ttc"), 0)); + v.push((format!("{d}/NotoSansCJK-Regular.ttc"), 1)); // Korean face in the Noto collection } v } @@ -423,32 +453,55 @@ mod tests { fn cjk_fallback_is_appended_to_every_family() { // Structural: whatever loaded, the CJK keys must sit at the end of each chain (after the // Latin/default fonts) so Latin still wins for Latin text. - let fonts = font_definitions(); - let cjk_keys: Vec = - ["sys-cjk-han", "sys-cjk-hangul"].into_iter().filter(|k| fonts.font_data.contains_key(*k)).map(str::to_string).collect(); + let language = crate::i18n::Language::Zh; + let fonts = font_definitions_for_language(language); + let cjk_keys: Vec = ["sys-cjk-han-zh", "sys-cjk-han-ja", "sys-cjk-hangul"] + .into_iter() + .filter(|key| fonts.font_data.contains_key(*key)) + .map(str::to_string) + .collect(); if cjk_keys.is_empty() { return; // no CJK face on this machine (minimal Linux) } for role in [UI, UI_BOLD, CELL, CELL_BOLD, CELL_ITALIC, CELL_BOLD_ITALIC, SERIF, MONO] { let chain = fonts.families.get(&FontFamily::Name(role.into())).map(Vec::as_slice).unwrap_or_default(); assert!(chain.len() >= cjk_keys.len(), "{role} chain too short for its CJK fallback"); - let tail = &chain[chain.len() - cjk_keys.len()..]; - assert_eq!(tail, cjk_keys.as_slice(), "{role} must end its chain with the CJK faces"); + let first_cjk = chain.iter().position(|key| key.starts_with("sys-cjk-")).unwrap_or(chain.len()); + let tail = &chain[first_cjk..]; + assert_eq!(tail, cjk_keys.as_slice(), "{role} must end its chain with CJK faces in the language order"); } } #[test] - fn cjk_fallback_covers_japanese() { - // Real render check: the proportional family (what cells and the UI use) must resolve - // Japanese kana/kanji to a glyph, not the tofu replacement char. - if cjk_han().iter().all(|(p, _)| std::fs::read(p).is_err()) { - return; // no CJK face on this machine (minimal Linux); nothing to assert + fn system_fallback_covers_supported_scripts() { + let cases = [ + (crate::i18n::Language::Zh, cjk_han_simplified(), &["页面布局", "自动化", "粘贴格式"][..]), + (crate::i18n::Language::Ja, cjk_han_japanese(), &["カテゴリ", "貼り付け"][..]), + (crate::i18n::Language::Ko, cjk_hangul(), &["한국어"][..]), + ]; + for (language, paths, samples) in cases { + if paths.iter().all(|(path, _)| std::fs::read(path).is_err()) { + continue; // this machine has no system face for this script + } + let ctx = egui::Context::default(); + ctx.set_fonts(font_definitions_for_language(language)); + let mut out = ctx.run_ui(egui::RawInput::default(), |_ui| {}); + out.textures_delta.clear(); // nothing consumes the atlas in a headless test + for sample in samples { + let covered = ctx.fonts_mut(|f| f.has_glyphs(&FontId::proportional(14.0), sample)); + assert!(covered, "{sample:?} must render with a real glyph, not tofu"); + } + if language == crate::i18n::Language::Zh { + let cell_font = FontId::new(14.0, FontFamily::Name(CELL.into())); + let covered = ctx.fonts_mut(|f| f.has_glyphs(&cell_font, "客户端配置 中文字体测试")); + assert!(covered, "Chinese workbook text must render with a real glyph, not tofu"); + } } let ctx = egui::Context::default(); - ctx.set_fonts(font_definitions()); + ctx.set_fonts(font_definitions_for_language(crate::i18n::Language::Ru)); let mut out = ctx.run_ui(egui::RawInput::default(), |_ui| {}); - out.textures_delta.clear(); // nothing consumes the atlas in a headless test - let covered = ctx.fonts_mut(|f| f.has_glyphs(&FontId::proportional(14.0), "カテゴリ")); - assert!(covered, "Japanese text must render with a real glyph, not tofu"); + out.textures_delta.clear(); + let cyrillic = ctx.fonts_mut(|f| f.has_glyphs(&ui_font(14.0), "Русский")); + assert!(cyrillic, "Russian interface text must render with a real glyph, not tofu"); } } diff --git a/crates/ui-egui/tests/interaction.rs b/crates/ui-egui/tests/interaction.rs index 63cdc81200..f3b5d31f31 100644 --- a/crates/ui-egui/tests/interaction.rs +++ b/crates/ui-egui/tests/interaction.rs @@ -102,15 +102,16 @@ fn renders_every_ribbon_tab_without_panicking() { fn language_switch_translates_the_ribbon_and_persists() { use gridcraft_ui_egui::i18n::Language; let mut h = harness(blank()); - // English by default on a machine whose system language is not Japanese. - assert_ne!(h.state().ui.language, Language::Ja); - h.state_mut().run("app.language.japanese", json!({})).unwrap(); - h.run_steps(2); // the ribbon renders the Japanese tabs without panicking - assert_eq!(h.state().ui.language, Language::Ja); - // The preference round-trips through the saved UiState. - let restored: gridcraft_ui_egui::UiState = serde_json::from_str(&serde_json::to_string(&h.state().ui).unwrap()).unwrap(); - assert_eq!(restored.language, Language::Ja); - h.state_mut().run("app.language.english", json!({})).unwrap(); + assert_eq!(h.state().ui.language, Language::system()); + for (language, expected) in [(Language::Zh, "数据"), (Language::Ja, "データ"), (Language::Ko, "데이터"), (Language::Ru, "Данные")] { + h.state_mut().run("app.language.set", json!({"language": language.code()})).unwrap(); + h.run_steps(2); // every locale renders the ribbon without panicking + assert_eq!(h.state().ui.language, language); + assert_eq!(language.tr("Data"), expected); + let restored: gridcraft_ui_egui::UiState = serde_json::from_str(&serde_json::to_string(&h.state().ui).unwrap()).unwrap(); + assert_eq!(restored.language, language); + } + h.state_mut().run("app.language.set", json!({"language": "en"})).unwrap(); assert_eq!(h.state().ui.language, Language::En); } From c4fd49afc2b7129fd59da0f309ec6a14a061a5b9 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sat, 10 Oct 2026 12:22:11 -0400 Subject: [PATCH 7/8] Review fix-up: dedupe CJK fallback load, wider Linux/macOS font paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Load each fallback font file once: the region-merged Noto Sans CJK .ttc found for Han also covers Hangul (and Tahoma covers Thai and Hebrew), so a later script whose candidate file is already loaded reuses it instead of loading tens of MB again. New test: no two fallback faces share a file. - Fold in the Linux CJK paths from #103: Fedora google-noto-cjk/, Arch noto-cjk/ and wenquanyi/, Debian truetype/wqy/wqy-microhei.ttc, the SC .otf builds, /usr/local, plus SimSun on Windows. Document the .ttc face indices (JP 0, KR 1, SC 2, TC 3, HK 4); Hangul uses the KR face. - macOS: Hiragino Sans (ヒラギノ角ゴシック W3) and Hiragino Sans GB come before PingFang.ttc, which recent macOS no longer ships in /System. - Comments promise glyphs instead of tofu, not correct rendering. - fallback_covers_its_script compared has_glyphs, which is a false negative when the owning face also draws the replacement glyph (DejaVu Sans as UI font owns Hebrew); compare laid-out glyphs with the tofu glyph instead. Co-authored-by: eyouhi <47080137+eyouhi@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/theme.rs | 94 ++++++++++++++++++++++++++++++------- 1 file changed, 76 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 1e8e8a70d8..b108427572 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -322,17 +322,27 @@ pub fn font_definitions() -> FontDefinitions { /// Loads the system non-Latin fallback faces (one file per script family) and returns their keys so /// every family can carry them as fallback. egui's bundled fonts have no coverage beyond Latin, so -/// without this a Thai, Hebrew, Japanese or Chinese workbook renders as tofu boxes even though the -/// text was read correctly. epaint shapes the complex scripts itself (via `harfrust`); it only needs -/// a face that has the glyphs. +/// without this a Thai, Hebrew, Japanese or Chinese workbook shows tofu boxes even though the text +/// was read correctly. With a face installed those scripts get real glyphs instead of tofu; nothing +/// is bundled, and a machine without the face keeps the old behaviour. #[cfg(not(target_arch = "wasm32"))] fn load_fallback(fonts: &mut FontDefinitions) -> Vec { let mut keys = Vec::new(); + // Files already loaded as a fallback face. A file serves at most one key: the region-merged + // Noto Sans CJK .ttc found for Han also carries Hangul (and Tahoma carries both Thai and + // Hebrew), so loading it again for a later script would only duplicate tens of MB in memory. + let mut loaded: Vec = Vec::new(); for (key, cands) in fallback_faces() { - let refs: Vec<(&str, u32)> = cands.iter().map(|(p, i)| (p.as_str(), *i)).collect(); - if let Some(fd) = try_load(&refs) { - fonts.font_data.insert(key.to_string(), Arc::new(fd)); - keys.push(key.to_string()); + for (path, index) in &cands { + if loaded.contains(path) { + break; // a face loaded for an earlier script already covers this one + } + if let Some(fd) = try_load(&[(path.as_str(), *index)]) { + fonts.font_data.insert(key.to_string(), Arc::new(fd)); + keys.push(key.to_string()); + loaded.push(path.clone()); + break; + } } } keys @@ -351,40 +361,66 @@ fn fallback_faces() -> Vec<(&'static str, Vec<(String, u32)>)> { vec![("sys-cjk-han", cjk_han()), ("sys-cjk-hangul", cjk_hangul()), ("sys-thai", thai()), ("sys-hebrew", hebrew())] } +/// Linux directories that hold CJK fonts across distributions: Debian/Ubuntu (`opentype/noto`, +/// `truetype/wqy`), Fedora (`google-noto-cjk`), Arch (`noto-cjk`, `wenquanyi`), plus local and +/// flat layouts. +#[cfg(not(target_arch = "wasm32"))] +const LINUX_CJK_DIRS: [&str; 10] = [ + "/usr/share/fonts/opentype/noto", + "/usr/share/fonts/google-noto-cjk", + "/usr/share/fonts/noto-cjk", + "/usr/share/fonts/truetype/noto", + "/usr/share/fonts/noto", + "/usr/share/fonts/truetype", + "/usr/share/fonts/TTF", + "/usr/share/fonts", + "/usr/local/share/fonts", + "/usr/local/share/fonts/noto-cjk", +]; + /// Han + Kana faces, in fallback order. A Japanese face comes first (kana and JIS kanji render /// with Japanese glyph shapes); a Chinese face follows to widen coverage. Every CJK face carries /// kana, so any of them renders Japanese; the order only decides kanji glyph style. +/// +/// The region-merged `NotoSansCJK-Regular.ttc` holds one face per locale (JP 0, KR 1, SC 2, TC 3, +/// HK 4) with the same glyph coverage; index 0 picks the Japanese glyph shapes. #[cfg(not(target_arch = "wasm32"))] fn cjk_han() -> Vec<(String, u32)> { let mac = "/System/Library/Fonts"; let win = std::env::var("WINDIR").map(|w| format!("{w}\\Fonts")).unwrap_or_else(|_| "C:\\Windows\\Fonts".into()); - let lin = ["/usr/share/fonts/opentype/noto", "/usr/share/fonts/truetype/noto", "/usr/share/fonts/truetype", "/usr/share/fonts"]; let mut v: Vec<(String, u32)> = Vec::new(); v.push((format!("{win}\\YuGothR.ttc"), 0)); // Yu Gothic (Japanese) v.push((format!("{win}\\msgothic.ttc"), 0)); // MS Gothic (Japanese) v.push((format!("{win}\\msyh.ttc"), 0)); // Microsoft YaHei (Chinese) - v.push((format!("{mac}/Hiragino Sans GB.ttc"), 0)); - v.push((format!("{mac}/PingFang.ttc"), 0)); - for d in lin { + v.push((format!("{win}\\simsun.ttc"), 0)); // SimSun (Chinese, older installs) + v.push((format!("{mac}/ヒラギノ角ゴシック W3.ttc"), 0)); // Hiragino Sans (Japanese) + v.push((format!("{mac}/Hiragino Sans GB.ttc"), 0)); // ships on every recent macOS + v.push((format!("{mac}/PingFang.ttc"), 0)); // older macOS only; now a downloadable asset + for d in LINUX_CJK_DIRS { v.push((format!("{d}/NotoSansCJK-Regular.ttc"), 0)); v.push((format!("{d}/NotoSansCJKjp-Regular.otf"), 0)); + v.push((format!("{d}/NotoSansCJKsc-Regular.otf"), 0)); + } + for d in LINUX_CJK_DIRS { + v.push((format!("{d}/wqy/wqy-microhei.ttc"), 0)); + v.push((format!("{d}/wenquanyi/wqy-microhei.ttc"), 0)); v.push((format!("{d}/wqy-microhei.ttc"), 0)); } v } -/// Hangul faces (Korean; not covered by the Han fonts). +/// Hangul faces (Korean). The Han faces above that come from the region-merged Noto Sans CJK file +/// already carry Hangul; [`load_fallback`] then skips this list rather than load the file twice. #[cfg(not(target_arch = "wasm32"))] fn cjk_hangul() -> Vec<(String, u32)> { let mac = "/System/Library/Fonts"; let win = std::env::var("WINDIR").map(|w| format!("{w}\\Fonts")).unwrap_or_else(|_| "C:\\Windows\\Fonts".into()); - let lin = ["/usr/share/fonts/truetype/noto", "/usr/share/fonts/opentype/noto", "/usr/share/fonts/truetype"]; let mut v: Vec<(String, u32)> = Vec::new(); v.push((format!("{win}\\malgun.ttf"), 0)); // Malgun Gothic v.push((format!("{mac}/AppleSDGothicNeo.ttc"), 0)); - for d in lin { + for d in LINUX_CJK_DIRS { v.push((format!("{d}/NotoSansCJKkr-Regular.otf"), 0)); - v.push((format!("{d}/NotoSansCJK-Regular.ttc"), 0)); + v.push((format!("{d}/NotoSansCJK-Regular.ttc"), 1)); // KR face } v } @@ -497,6 +533,19 @@ mod tests { } } + #[test] + fn fallback_faces_load_each_file_once() { + // The region-merged Noto Sans CJK .ttc serves Han and Hangul; it must be loaded once, not + // once per script (tens of MB each). + let fonts = font_definitions(); + let present: Vec<&Arc> = fallback_faces().into_iter().filter_map(|(k, _)| fonts.font_data.get(k)).collect(); + for (i, a) in present.iter().enumerate() { + for b in present.iter().skip(i + 1) { + assert!(a.font != b.font, "the same font file is loaded for two fallback scripts"); + } + } + } + #[test] fn fallback_covers_its_script() { // Real render check, per script: the proportional family (what cells and the UI use) must @@ -512,12 +561,21 @@ mod tests { ctx.set_fonts(font_definitions()); let mut out = ctx.run_ui(egui::RawInput::default(), |_ui| {}); out.textures_delta.clear(); // nothing consumes the atlas in a headless test + // `has_glyphs` is a false negative when the face that owns the script is also the face that + // draws the replacement glyph (DejaVu Sans as the UI font owns Hebrew), so compare the laid + // out glyphs with the tofu glyph itself instead. + let font = FontId::proportional(14.0); + let glyphs = |text: &str| { + let galley = ctx.fonts_mut(|f| f.layout_no_wrap(text.to_owned(), font.clone(), Color32::BLACK)); + galley.rows.iter().flat_map(|r| r.glyphs.iter().map(|g| g.uv_rect)).collect::>() + }; + let tofu = glyphs("\u{25FB}"); for (key, cands, sample) in cases { - if cands.iter().all(|(p, _)| std::fs::read(p).is_err()) { + if !cands.iter().any(|(p, _)| std::path::Path::new(p).exists()) { continue; // no face for this script on this machine; nothing to assert } - let covered = ctx.fonts_mut(|f| f.has_glyphs(&FontId::proportional(14.0), sample)); - assert!(covered, "{key} is present but {sample:?} still renders as tofu"); + let drawn = glyphs(sample); + assert!(!drawn.is_empty() && drawn.iter().all(|g| !tofu.contains(g)), "{key} is present but {sample:?} still renders as tofu"); } } } From d7c77e94cd161b97ce9d50db1d8c873871857df1 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sat, 10 Oct 2026 12:44:57 -0400 Subject: [PATCH 8/8] Review fix-up: locale-independent defaults, lenient saved language, listed commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - UiState::default() is English: tests, the kittest harness and the snapshot example no longer depend on the host's locale. The desktop app alone starts from the system language, when ui.json names no supported language (first run, an older file, an unknown value). - An unknown or malformed saved language reads as English instead of failing the whole UiState and resetting every other preference. - app.language.set takes {"language": "ja"} (with `code` as an alias, the name the PR description used); the View combo now uses it via Language::code(). The app.language.* commands are listed by engine.commands with the other UI commands and documented in docs/control-protocol.md. - Home's text "Orientation" (方向) and Page Layout's print "Orientation" (印刷の向き) get separate keys through a `context|label` key form. - Japanese: Hide Rows → 行を表示しない, Trace Dependents → 参照先のトレース; translate the display-theme combo merged in from main. - system_theme test: the View tab now has two combo boxes; pick the theme one. Co-Authored-By: Claude Opus 5.5 --- apps/gridcraft/src/main.rs | 7 ++- crates/ui-egui/src/control.rs | 21 ++++---- crates/ui-egui/src/i18n.rs | 77 ++++++++++++++++++++++++++-- crates/ui-egui/src/lib.rs | 16 +++--- crates/ui-egui/src/ribbon.rs | 5 +- crates/ui-egui/tests/interaction.rs | 14 ++++- crates/ui-egui/tests/system_theme.rs | 3 +- docs/control-protocol.md | 6 +++ 8 files changed, 122 insertions(+), 27 deletions(-) diff --git a/apps/gridcraft/src/main.rs b/apps/gridcraft/src/main.rs index 7343932f3a..55dc9c2705 100644 --- a/apps/gridcraft/src/main.rs +++ b/apps/gridcraft/src/main.rs @@ -79,11 +79,16 @@ fn load_prefs(app: &mut SheetApp) { if !prefs_enabled() { return; } + // First run (or a ui.json without a usable language): follow the desktop's language. + app.ui.language = gridcraft_ui_egui::i18n::Language::system(); let Some(dir) = config_dir() else { return }; if let Ok(b) = std::fs::read(dir.join("ui.json")) - && let Ok(ui) = serde_json::from_slice(&b) + && let Ok(ui) = serde_json::from_slice::(&b) { + let saved = serde_json::from_slice(&b).ok().and_then(|v| gridcraft_ui_egui::i18n::saved_language(&v)); + let language = saved.unwrap_or(app.ui.language); app.ui = ui; + app.ui.language = language; } if let Ok(b) = std::fs::read(dir.join("prefs.json")) && let Ok(p) = serde_json::from_slice(&b) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 902ec25aff..b1733fd11a 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -155,16 +155,19 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) - } "engine.commands" => { let mut v: Vec = app.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect(); - for (id, label) in [ - ("ui.ribbonTab", "Ribbon Tab"), - ("view.formulaBar", "Formula Bar"), - ("view.collapseRibbon", "Collapse Ribbon"), - ("view.darkMode", "Dark Mode"), - ("view.theme", "Display Theme"), - ("view.zoom100", "100%"), - ("ui.dialog", "Open Dialog"), + for (id, label, params) in [ + ("ui.ribbonTab", "Ribbon Tab", ""), + ("view.formulaBar", "Formula Bar", ""), + ("view.collapseRibbon", "Collapse Ribbon", ""), + ("view.darkMode", "Dark Mode", ""), + ("view.theme", "Display Theme", ""), + ("view.zoom100", "100%", ""), + ("ui.dialog", "Open Dialog", ""), + ("app.language.set", "Interface Language", "{language: \"en\"|\"ja\"} (alias: code)"), + ("app.language.english", "Interface Language: English", ""), + ("app.language.japanese", "Interface Language: Japanese", ""), ] { - v.push(json!({"id": id, "label": label, "enabled": true, "ui": true})); + v.push(json!({"id": id, "label": label, "params": params, "enabled": true, "ui": true})); } ok(Json::Array(v)) } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 48e809dd90..18fda086c0 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -28,6 +28,14 @@ impl Language { } } + /// The language's code, as saved in `ui.json` and taken by `app.language.set`. + pub fn code(self) -> &'static str { + match self { + Self::En => "en", + Self::Ja => "ja", + } + } + pub fn parse(code: &str) -> Option { match code { "en" => Some(Self::En), @@ -56,16 +64,43 @@ impl Language { } } + /// Translates an interface label; untranslated labels fall back to English. + /// + /// A label that needs two translations (Home's text "Orientation" vs Page Layout's print + /// "Orientation") is keyed `context|label`: English shows only the part after the `|`. pub fn tr(self, text: &str) -> &str { if self == Self::Ja && let Some((_, japanese)) = JAPANESE.iter().find(|(english, _)| *english == text) { return japanese; } - text + text.rsplit_once('|').map_or(text, |(_, label)| label) } } +/// Deserializes a saved language leniently: an unknown or malformed value (a language removed in a +/// later version, a hand-edited `ui.json`) reads as English instead of failing the whole `UiState`, +/// which would reset every other preference with it. +pub fn lenient<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + Code(String), + Other(serde::de::IgnoredAny), + } + Ok(match Raw::deserialize(d)? { + Raw::Code(code) => Language::parse(&code).unwrap_or_default(), + Raw::Other(_) => Language::default(), + }) +} + +/// The language a saved `ui.json` asks for, if it names a supported one. The desktop app uses it +/// to tell "saved English" from "nothing usable saved" (first run, an older file, an unknown +/// value), which starts from [`Language::system`] instead. +pub fn saved_language(ui_json: &serde_json::Value) -> Option { + ui_json.get("language").and_then(serde_json::Value::as_str).and_then(Language::parse) +} + /// egui context-data key holding the language of the frame being drawn. Widgets that only get a /// `Ui` (not the app) read it to translate their labels; [`set_current`] writes it once per frame. fn lang_key() -> egui::Id { @@ -121,7 +156,8 @@ const JAPANESE: &[(&str, &str)] = &[ ("Vertical Text", "縦書き"), ("Decrease Indent", "インデントを減らす"), ("Increase Indent", "インデントを増やす"), - ("Orientation", "印刷の向き"), + ("Orientation", "方向"), + ("Page Layout|Orientation", "印刷の向き"), ("Angle Counterclockwise", "左回りに回転"), ("Angle Clockwise", "右回りに回転"), ("Rotate Text Up", "文字列を上に回転"), @@ -153,7 +189,7 @@ const JAPANESE: &[(&str, &str)] = &[ ("Column Width…", "列の幅…"), ("AutoFit Column Width", "列の幅を自動調整"), ("Default Width…", "標準の幅…"), - ("Hide Rows", "行の表示/非表示"), + ("Hide Rows", "行を表示しない"), ("Unhide Rows", "再表示"), ("Hide Columns", "列の表示/非表示"), ("Unhide Columns", "再表示"), @@ -218,7 +254,7 @@ const JAPANESE: &[(&str, &str)] = &[ ("Use in Formula", "数式で使用"), ("Create from Selection", "選択範囲から作成"), ("Trace Precedents", "参照元のトレース"), - ("Trace Dependents", "依存元のトレース"), + ("Trace Dependents", "参照先のトレース"), ("Remove Arrows", "矢印の解除"), ("Show Formulas", "数式の表示"), ("Error Checking", "エラーチェック"), @@ -274,6 +310,10 @@ const JAPANESE: &[(&str, &str)] = &[ ("Freeze First Column", "最左列の固定"), ("Unfreeze Panes", "ウィンドウ枠固定の解除"), ("Dark Mode", "ダーク モード"), + ("Display theme", "表示テーマ"), + ("System", "システム"), + ("Light", "ライト"), + ("Dark", "ダーク"), ("Interface language", "表示言語"), ("Command\nPalette", "コマンド パレット"), ("Agent\nControl", "エージェント制御"), @@ -355,13 +395,32 @@ mod tests { for (i, (en, ja)) in JAPANESE.iter().enumerate() { assert!(!ja.is_empty()); assert!(JAPANESE.iter().take(i).all(|(other, _)| en != other)); - assert_eq!(Language::En.tr(en), *en); + assert_eq!(Language::En.tr(en), en.rsplit_once('|').map_or(*en, |(_, label)| label)); } assert_eq!(Language::Ja.tr("Data"), "データ"); assert_eq!(Language::Ja.tr("Sheet1!A1"), "Sheet1!A1"); + // A `context|label` key shows only its label in English and splits the translation. + assert_eq!(Language::En.tr("Page Layout|Orientation"), "Orientation"); + assert_eq!(Language::Ja.tr("Page Layout|Orientation"), "印刷の向き"); + assert_eq!(Language::Ja.tr("Orientation"), "方向"); assert_eq!(Language::parse("xx"), None); } + #[test] + fn unknown_saved_language_keeps_the_other_preferences() { + let ui: crate::UiState = serde_json::from_str(r#"{"dark": true, "language": "xx"}"#).unwrap(); + assert!(ui.dark); + assert_eq!(ui.language, Language::En); + let ui: crate::UiState = serde_json::from_str(r#"{"dark": true, "language": 7}"#).unwrap(); + assert!(ui.dark); + let ui: crate::UiState = serde_json::from_str(r#"{"language": "ja"}"#).unwrap(); + assert_eq!(ui.language, Language::Ja); + assert_eq!(crate::UiState::default().language, Language::En, "the default never reads the host locale"); + assert_eq!(saved_language(&serde_json::json!({"language": "ja"})), Some(Language::Ja)); + assert_eq!(saved_language(&serde_json::json!({"language": "xx"})), None); + assert_eq!(saved_language(&serde_json::json!({})), None); + } + #[test] fn tags_reduce_to_a_supported_language() { assert_eq!(Language::from_tag("ja-JP"), Some(Language::Ja)); @@ -378,5 +437,13 @@ mod tests { assert_eq!(restored.language, Language::Ja); app.run("app.language.english", serde_json::json!({})).unwrap(); assert_eq!(app.ui.language, Language::En); + app.run("app.language.set", serde_json::json!({"language": "ja"})).unwrap(); + assert_eq!(app.ui.language, Language::Ja); + app.run("app.language.set", serde_json::json!({"code": "en"})).unwrap(); + assert_eq!(app.ui.language, Language::En); + assert!(app.run("app.language.set", serde_json::json!({})).is_err(), "no language is an error, not a dialog"); + for l in Language::ALL { + assert_eq!(Language::parse(l.code()), Some(l)); + } } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a5e4ab5859..44580909f1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -45,8 +45,11 @@ pub struct UiState { pub formula_bar_expanded: bool, pub status_bar: bool, pub recent: Vec, - /// Interface language. Absent in older `ui.json` → the system's language (English fallback). - #[serde(default = "i18n::Language::system")] + /// Interface language. English by default (so tests and headless renders never depend on the + /// host's locale); the desktop app starts from [`i18n::Language::system`] when `ui.json` has + /// no usable language (see [`i18n::saved_language`]). An unknown saved value reads as English + /// rather than failing the whole `UiState`. + #[serde(deserialize_with = "i18n::lenient")] pub language: i18n::Language, } @@ -61,7 +64,7 @@ impl Default for UiState { formula_bar_expanded: false, status_bar: true, recent: vec![], - language: i18n::Language::system(), + language: i18n::Language::En, } } } @@ -234,13 +237,14 @@ impl SheetApp { } "view.zoom100" => return Some(self.session.run("view.zoom", json!({"percent": 100})).inspect(|_| self.after_engine())), "app.language.set" => { - let code = p.get("language").and_then(Json::as_str).and_then(i18n::Language::parse); - match code { + // `{"language": "ja"}`; `code` is accepted as an alias. + let code = p.get("language").or_else(|| p.get("code")).and_then(Json::as_str).unwrap_or(""); + match i18n::Language::parse(code) { Some(l) => { self.ui.language = l; Ok(json!({"language": l})) } - None => Err(format!("unknown language {:?} (use \"en\" or \"ja\")", p.get("language").and_then(Json::as_str).unwrap_or(""))), + None => Err(format!("unknown language {code:?} (use \"en\" or \"ja\")")), } } "app.language.english" => { diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 100bfc8567..06bb02d3d0 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1246,7 +1246,7 @@ fn page_layout(app: &mut SheetApp, ui: &mut Ui) { ], ); }); - let o = big_button(ui, Icon::Orient, "Orientation", "Orientation", true); + let o = big_button(ui, Icon::Orient, "Page Layout|Orientation", "Page Layout|Orientation", true); egui::Popup::menu(&o).show(|ui| { menu_items( app, @@ -1626,8 +1626,7 @@ fn view(app: &mut SheetApp, ui: &mut Ui) { |ui| { for l in crate::i18n::Language::ALL { if ui.selectable_label(l == lang, l.name()).clicked() { - let code = if l == crate::i18n::Language::Ja { "app.language.japanese" } else { "app.language.english" }; - act(app, code, json!({})); + act(app, "app.language.set", json!({"language": l.code()})); } } }, diff --git a/crates/ui-egui/tests/interaction.rs b/crates/ui-egui/tests/interaction.rs index ab33809288..5baf10ba68 100644 --- a/crates/ui-egui/tests/interaction.rs +++ b/crates/ui-egui/tests/interaction.rs @@ -187,8 +187,18 @@ fn renders_every_ribbon_tab_without_panicking() { fn language_switch_translates_the_ribbon_and_persists() { use gridcraft_ui_egui::i18n::Language; let mut h = harness(blank()); - // English by default on a machine whose system language is not Japanese. - assert_ne!(h.state().ui.language, Language::Ja); + // English by default whatever the host's locale: only the desktop app reads the system language. + assert_eq!(h.state().ui.language, Language::En); + // The language commands are listed with the other UI commands. + let ctx = h.ctx.clone(); + let gridcraft_ui_egui::control::Outcome::Done(listed) = gridcraft_ui_egui::control::handle(h.state_mut(), &ctx, "engine.commands", &json!({})) + else { + panic!("engine.commands returns a response"); + }; + let ids: Vec<&str> = listed["result"].as_array().into_iter().flatten().filter_map(|c| c["id"].as_str()).collect(); + for id in ["app.language.set", "app.language.english", "app.language.japanese"] { + assert!(ids.contains(&id), "engine.commands lists {id}"); + } h.state_mut().run("app.language.japanese", json!({})).unwrap(); h.run_steps(2); // the ribbon renders the Japanese tabs without panicking assert_eq!(h.state().ui.language, Language::Ja); diff --git a/crates/ui-egui/tests/system_theme.rs b/crates/ui-egui/tests/system_theme.rs index 2a5365aa05..0d2cdea323 100644 --- a/crates/ui-egui/tests/system_theme.rs +++ b/crates/ui-egui/tests/system_theme.rs @@ -44,7 +44,8 @@ fn set_mode(h: &mut egui_kittest::Harness<'static, SheetApp>, mode: &str) { } fn select_ribbon_theme(h: &mut egui_kittest::Harness<'static, SheetApp>, label: &str) { - h.get_by_role(egui::accesskit::Role::ComboBox).click(); + // The View tab's first combo box is the display theme (the interface language follows it). + h.get_all_by_role(egui::accesskit::Role::ComboBox).next().expect("display theme combo").click(); h.run_steps(2); h.get_by_role_and_label(egui::accesskit::Role::Button, label).click(); h.run_steps(2); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9c6c31b658..e465a0718b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -45,5 +45,11 @@ System follows live OS appearance changes and falls back to Light when the platf The saved choice remains System; new users still start in Light. The legacy `view.darkMode` command and `ui.set {dark}` select a fixed Light or Dark theme. +`{command: "app.language.set", params: {language: "ja"}}` switches the interface language +(`code` is accepted as an alias for `language`); `app.language.english` and +`app.language.japanese` are shortcuts. Only interface chrome is translated, never command ids or +document text. The choice is saved in `ui.json`; with nothing saved the desktop app follows the +system language. + For a headless equivalent (no window), use `gridcraft-cli mcp` or `gridcraft-cli run`; see [`mcp.md`](mcp.md) and [`cli.md`](cli.md).