From 8b70f13682bc5303aa439f03befa53d6e2449fec Mon Sep 17 00:00:00 2001 From: hasan-sdaif <306196098+hasan-sdaif@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:04:48 +0000 Subject: [PATCH] i18n: read Arabic labels right to left (the visual-order pass) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit egui 0.36 lays a label's runs left to right and runs no bidi over them (its text code still carries TODO(emilk): heed bidi characters), so an Arabic label read with its words in reverse order: each word was shaped correctly once a fallback face covered its glyphs, but it was drawn at the wrong end of the line. Languages flagged rtl now run each translation through a UAX #9 pass when the catalog is parsed (i18n/bidi.rs, unicode-bidi): the runs come out in visual order, the letters inside each run stay in logical order for the shaper, and brackets are mirrored — the pairs of BidiMirroring.txt, guillemets included, but not curly brackets, which in an interface label are almost always a {placeholder}'s own syntax: each placeholder rides through the pass as one character, so it can be neither split, reversed nor mirrored, and the fill always finds it. What a user types keeps its logical order — only catalog lookups go through the pass. --- Cargo.lock | 1 + crates/ui-egui/Cargo.toml | 5 +- crates/ui-egui/src/i18n/bidi.rs | 204 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/catalog.rs | 5 +- crates/ui-egui/src/i18n/mod.rs | 61 +++++---- 5 files changed, 249 insertions(+), 27 deletions(-) create mode 100644 crates/ui-egui/src/i18n/bidi.rs diff --git a/Cargo.lock b/Cargo.lock index fa594779403..45fe8bf0019 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4612,6 +4612,7 @@ dependencies = [ "serde_json", "sys-locale", "toml", + "unicode-bidi", "winsafe", ] diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index d6a49c0038c..544703e6726 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -36,7 +36,10 @@ serde_json = { workspace = true } log = { workspace = true } base64 = "0.22" # Inflating the translation catalogs, stored deflated (build.rs); already linked through photocraft-io. -flate2 = { workspace = true } +flate2 +# The Arabic catalog is parsed into visual order (i18n/bidi.rs): a UAX #9 pass for +# egui's run-by-run, left-to-right text layout. +unicode-bidi = "0.3.18" = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rayon = { workspace = true } diff --git a/crates/ui-egui/src/i18n/bidi.rs b/crates/ui-egui/src/i18n/bidi.rs new file mode 100644 index 00000000000..035ca6c4857 --- /dev/null +++ b/crates/ui-egui/src/i18n/bidi.rs @@ -0,0 +1,204 @@ +//! egui lays a label out run by run — every run one font, shaped on its own — and puts the runs +//! left to right in the order it met them. It does not run the Unicode bidirectional algorithm +//! (its text code still carries `TODO(emilk): heed bidi characters`), so a right-to-left label +//! reads with its words in reverse order: egui shapes each Arabic word correctly once the +//! language's system font has loaded, but it draws the first word at the left of the line, and +//! the reader meets the second one first. +//! +//! This module reorders a translation into *visual order* before egui sees it, the technique +//! immediate-mode UIs use until their text stack grows bidi support: the label's runs come out +//! in the order they must appear on screen, left to right, while the characters inside each run +//! stay in logical order, because the shaper reverses a right-to-left run itself (harfrust +//! picks the direction from the script). Brackets are mirrored here too, as UAX #9 L4 asks: +//! egui draws the glyph of the character it is handed. +//! +//! Only catalog lookups go through here, so what a user types into a field keeps its logical +//! order — the order the clipboard and search expect. A label long enough to wrap still wraps +//! from its visual end (egui wraps runs as it meets them), and the mirrored layout of the +//! widgets is a separate, larger step; this pass is what an Arabic interface needs until egui +//! grows bidi of its own. + +use unicode_bidi::{BidiClass, BidiInfo, Level}; + +/// A character the shaper lays out as part of a right-to-left run: a strong right-to-left +/// character (Arabic and Hebrew letters) or a mark riding on one. The stretches these form are +/// emitted in logical order; every other character keeps the place the reordering gave it. +fn is_rtl_shaped(c: char) -> bool { + matches!(unicode_bidi::bidi_class(c), BidiClass::R | BidiClass::AL | BidiClass::NSM) +} + +/// The glyph a bracket has to show in a right-to-left context: egui draws the glyph of the +/// character it is given, so the mirror pair has to be swapped in the text itself. The pairs +/// come from `BidiMirroring.txt` — the ones an interface label can hold, guillemets +/// included. Curly brackets are left alone: in an interface label they are almost always a +/// `{placeholder}`'s own syntax, and mirroring them would break the fill. +fn mirror(c: char) -> char { + match c { + '(' => ')', + ')' => '(', + '[' => ']', + ']' => '[', + '<' => '>', + '>' => '<', + '«' => '»', + '»' => '«', + '‹' => '›', + '›' => '‹', + _ => c, + } +} + +/// `label` in logical order, rearranged for egui's run-by-run, left-to-right layout: the runs in +/// visual order (left to right), the characters inside each run in logical order for the shaper, +/// brackets mirrored. Lines are reordered on their own (`\n` ends one). A `{placeholder}` is the +/// label's own syntax: it rides through the pass as one character, so the reordering can +/// neither split, reverse nor mirror it, and every placeholder comes back exactly as written. +/// A label with nothing right-to-left in it comes back as it was. +pub fn visual_rtl(label: &str) -> String { + if !label.chars().any(is_rtl_shaped) { + return label.into(); + } + // Each placeholder becomes one private-use character (a left-to-right one, like the name + // inside it) for the pass, and is restored afterwards; the mapping is per placeholder, so + // a reordered sentence still finds its own. + let mut tokens: Vec<&str> = Vec::new(); + let mut guarded = String::with_capacity(label.len()); + let mut rest = label; + while let Some(open) = rest.find('{') { + guarded.push_str(&rest[..open]); + let after = &rest[open + 1..]; + if let Some(close) = after.find('}') { + tokens.push(&rest[open..open + close + 2]); + guarded.push(char::from_u32(0xE000 + tokens.len() as u32 - 1).unwrap_or('\u{E000}')); + rest = &after[close + 1..]; + } else { + guarded.push('{'); + rest = after; + } + } + guarded.push_str(rest); + let mut out = String::with_capacity(label.len()); + let mut first = true; + for line in guarded.split('\n') { + if !first { + out.push('\n'); + } + first = false; + visual_rtl_line(line, &mut out); + } + if tokens.is_empty() { + return out; + } + let mut restored = String::with_capacity(out.len()); + for c in out.chars() { + let k = c as u32; + if (0xE000..0xE000 + tokens.len() as u32).contains(&k) { + restored.push_str(tokens[(k - 0xE000) as usize]); + } else { + restored.push(c); + } + } + restored +} + +/// One line of [`visual_rtl`] (no `\n` in it), appended to `out`. +fn visual_rtl_line(line: &str, out: &mut String) { + let bidi = BidiInfo::new(line, Some(Level::rtl())); + let Some(para) = bidi.paragraphs.first() else { + out.push_str(line); + return; + }; + let chars: Vec = line.chars().collect(); + let levels = bidi.reordered_levels_per_char(para, para.range.clone()); + // The line's characters in visual order, left to right (UAX #9 L1–L2). + let order = BidiInfo::reorder_visual(&levels); + let mut p = 0; + while p < order.len() { + let i = order[p]; + if is_rtl_shaped(chars[i]) { + // One shaping run: a stretch of right-to-left characters, contiguous in the line, + // whatever order the reordering brought it in (descending in a right-to-left + // context, ascending inside a left-to-right island). Emitted in logical order, + // which is ascending. + let (mut lo, mut hi) = (i, i); + let mut end = p + 1; + loop { + if let Some(&j) = order.get(end) + && is_rtl_shaped(chars[j]) + && (j + 1 == lo || j == hi + 1) + { + lo = lo.min(j); + hi = hi.max(j); + end += 1; + } else { + break; + } + } + let mut j = lo; + while j <= hi { + out.push(chars[j]); + j += 1; + } + p = end; + } else { + // A left-to-right run — a Latin word, a number — or a character between runs: a + // space, an ellipsis. It stands where the reordering put it; a bracket in a + // right-to-left context shows its mirror. + let c = chars[i]; + out.push(if levels[i].is_rtl() { mirror(c) } else { c }); + p += 1; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn runs_in_visual_order_letters_in_logical_order() { + // The first word of a sentence ends up rightmost; each word still reads correctly. + assert_eq!(visual_rtl("إعداد المستند"), "المستند إعداد"); + assert_eq!(visual_rtl("تحرير لوحات الرسم"), "الرسم لوحات تحرير"); + // One run (one word) is left as it is: the shaper reverses its letters itself. + assert_eq!(visual_rtl("المعاينة"), "المعاينة"); + // A mark rides on its letter inside the run. + assert_eq!(visual_rtl("عنصراً جديد"), "جديد عنصراً"); + } + + #[test] + fn left_to_right_islands_keep_their_own_order() { + // A left-to-right run keeps its own order, as one unit, in its place in the sentence; + // the ellipsis of a dialog command ends up at the reading end (the left). + assert_eq!(visual_rtl("حفظ كـ PDF…"), "…PDF كـ حفظ"); + assert_eq!(visual_rtl("تصدير كـ SVG"), "SVG كـ تصدير"); + // A number between Arabic words reads left to right, in its place in the sentence. + assert_eq!(visual_rtl("إنشاء 3 نسخ"), "نسخ 3 إنشاء"); + // A `{placeholder}` is the label's own syntax: it rides through as one unit, in the + // order it was written, and never mirrored. + assert_eq!(visual_rtl("لون مميز {n}"), "{n} مميز لون"); + assert_eq!(visual_rtl("جارٍ تنزيل {done} من {total}"), "{total} من {done} تنزيل جارٍ"); + } + + #[test] + fn brackets_mirror() { + assert_eq!(visual_rtl("حفظ (النسخة الحالية)"), "(الحالية النسخة) حفظ"); + // Guillemets mirror too (BidiMirroring.txt): quotes and breadcrumb separators point the + // reading way, not the way they were typed. + assert_eq!(visual_rtl("«ملف › الصفحة الرئيسية»"), "«الرئيسية الصفحة ‹ ملف»"); + assert_eq!(visual_rtl("«جديد…» يبدأ نسخة"), "نسخة يبدأ «…جديد»"); + } + + #[test] + fn lines_are_reordered_on_their_own() { + assert_eq!(visual_rtl("سطر أول\nسطر ثانٍ"), "أول سطر\nثانٍ سطر"); + assert_eq!(visual_rtl("سطر أول\nPDF"), "أول سطر\nPDF"); + } + + #[test] + fn nothing_right_to_left_comes_back_as_it_was() { + assert_eq!(visual_rtl("PDF"), "PDF"); + assert_eq!(visual_rtl("Plain label, 3 of them."), "Plain label, 3 of them."); + assert_eq!(visual_rtl(""), ""); + } +} diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs index 22552aa4a2a..f4ce42985e2 100644 --- a/crates/ui-egui/src/i18n/catalog.rs +++ b/crates/ui-egui/src/i18n/catalog.rs @@ -61,9 +61,12 @@ pub fn parse_entries(text: &str) -> (Vec, Vec) { } impl Catalog { - pub fn parse(text: &str) -> Catalog { + /// Parse a catalog. A right-to-left language's translations are stored in visual order + /// (`bidi.rs`) — the order egui draws its runs in — so the lookups read right to left. + pub fn parse(text: &str, rtl: bool) -> Catalog { let mut c = Catalog::default(); for (ctx, src, tr) in parse_entries(text).0 { + let tr = if rtl { super::bidi::visual_rtl(&tr) } else { tr }; match ctx.as_str() { "" => { c.plain.insert(src, tr); diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index 9b494128c8e..fd1d1b61b89 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -20,6 +20,7 @@ //! - [`trn`]: plural-aware (`{n}` is filled in). [`fmt`]: fill `{name}` placeholders after [`tr`]; //! translators may reorder placeholders freely. +mod bidi; mod catalog; mod system; @@ -45,6 +46,10 @@ pub struct LangInfo { pub plural: fn(u64) -> usize, /// Must the catalog cover every menu string? (checked by the tests) pub complete_menus: bool, + /// Does the language read right to left? Its translations are then stored in visual order + /// for egui's run-by-run layout (see `bidi.rs`), so lookups draw the runs in the order a + /// right-to-left reader meets them. + pub rtl: bool, catalog: OnceLock, } @@ -204,41 +209,41 @@ fn expand(packed: &str, keys: &[&str]) -> Result { /// The registry. English first: it is the fallback and the source language. pub static LANGUAGES: [LangInfo; 21] = [ - LangInfo { code: "en", name: "English", source: b"", plural: plural_one_other, complete_menus: false, catalog: OnceLock::new() }, - LangInfo { code: "ja", name: "日本語", source: catalog!("ja"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() }, - LangInfo { code: "zh-hans", name: "简体中文", source: catalog!("zh-hans"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() }, + LangInfo { code: "en", name: "English", source: b"", plural: plural_one_other, complete_menus: false, rtl: false, catalog: OnceLock::new() }, + LangInfo { code: "ja", name: "日本語", source: catalog!("ja"), plural: plural_none, complete_menus: true, rtl: false, catalog: OnceLock::new() }, + LangInfo { code: "zh-hans", name: "简体中文", source: catalog!("zh-hans"), plural: plural_none, complete_menus: true, rtl: false, catalog: OnceLock::new() }, // Traditional Chinese in the vocabulary used in Taiwan; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant-*` // locales all resolve here (see `candidates`). - LangInfo { code: "zh-hant", name: "繁體中文", source: catalog!("zh-hant"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() }, - LangInfo { code: "es", name: "Español", source: catalog!("es"), plural: plural_one_other, complete_menus: true, catalog: OnceLock::new() }, - LangInfo { code: "ru", name: "Русский", source: catalog!("ru"), plural: plural_russian, complete_menus: true, catalog: OnceLock::new() }, + LangInfo { code: "zh-hant", name: "繁體中文", source: catalog!("zh-hant"), plural: plural_none, complete_menus: true, rtl: false, catalog: OnceLock::new() }, + LangInfo { code: "es", name: "Español", source: catalog!("es"), plural: plural_one_other, complete_menus: true, rtl: false, catalog: OnceLock::new() }, + LangInfo { code: "ru", name: "Русский", source: catalog!("ru"), plural: plural_russian, complete_menus: true, rtl: false, catalog: OnceLock::new() }, // Ukrainian has the same one/few/many rule for integer counts. - LangInfo { code: "uk", name: "Українська", source: catalog!("uk"), plural: plural_russian, complete_menus: true, catalog: OnceLock::new() }, + LangInfo { code: "uk", name: "Українська", source: catalog!("uk"), plural: plural_russian, complete_menus: true, rtl: false, catalog: OnceLock::new() }, // Serbian (Latin script, Ekavian) has the same one/few/many rule for integer counts. `sr-RS`, // `sr-Latn-*` and `sr_RS@latin` resolve here; so do Cyrillic `sr` locales, which read Latin // rather than English. - LangInfo { code: "sr", name: "Srpski", source: catalog!("sr"), plural: plural_russian, complete_menus: true, catalog: OnceLock::new() }, - LangInfo { code: "cs", name: "Čeština", source: catalog!("cs"), plural: plural_cs, complete_menus: true, catalog: OnceLock::new() }, - LangInfo { code: "fr", name: "Français", source: catalog!("fr"), plural: plural_fr, complete_menus: true, catalog: OnceLock::new() }, - LangInfo { code: "id", name: "Bahasa Indonesia", source: catalog!("id"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() }, - LangInfo { code: "ko", name: "한국어", source: catalog!("ko"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() }, - LangInfo { code: "pl", name: "Polski", source: catalog!("pl"), plural: plural_polish, complete_menus: true, catalog: OnceLock::new() }, - LangInfo { code: "de", name: "Deutsch", source: catalog!("de"), plural: plural_one_other, complete_menus: true, catalog: OnceLock::new() }, + LangInfo { code: "sr", name: "Srpski", source: catalog!("sr"), plural: plural_russian, complete_menus: true, rtl: false, catalog: OnceLock::new() }, + LangInfo { code: "cs", name: "Čeština", source: catalog!("cs"), plural: plural_cs, complete_menus: true, rtl: false, catalog: OnceLock::new() }, + LangInfo { code: "fr", name: "Français", source: catalog!("fr"), plural: plural_fr, complete_menus: true, rtl: false, catalog: OnceLock::new() }, + LangInfo { code: "id", name: "Bahasa Indonesia", source: catalog!("id"), plural: plural_none, complete_menus: true, rtl: false, catalog: OnceLock::new() }, + LangInfo { code: "ko", name: "한국어", source: catalog!("ko"), plural: plural_none, complete_menus: true, rtl: false, catalog: OnceLock::new() }, + LangInfo { code: "pl", name: "Polski", source: catalog!("pl"), plural: plural_polish, complete_menus: true, rtl: false, catalog: OnceLock::new() }, + LangInfo { code: "de", name: "Deutsch", source: catalog!("de"), plural: plural_one_other, complete_menus: true, rtl: false, catalog: OnceLock::new() }, // Brazilian Portuguese; `pt`, `pt-BR` and `pt-PT` locales all resolve here (see `candidates`). - LangInfo { code: "pt-br", name: "Português (Brasil)", source: catalog!("pt-br"), plural: plural_pt, complete_menus: true, catalog: OnceLock::new() }, - LangInfo { code: "el", name: "Ελληνικά", source: catalog!("el"), plural: plural_one_other, complete_menus: true, catalog: OnceLock::new() }, + LangInfo { code: "pt-br", name: "Português (Brasil)", source: catalog!("pt-br"), plural: plural_pt, complete_menus: true, rtl: false, catalog: OnceLock::new() }, + LangInfo { code: "el", name: "Ελληνικά", source: catalog!("el"), plural: plural_one_other, complete_menus: true, rtl: false, catalog: OnceLock::new() }, // Dutch; `nl-NL` and `nl-BE` locales both resolve here. - LangInfo { code: "nl", name: "Nederlands", source: catalog!("nl"), plural: plural_one_other, complete_menus: true, catalog: OnceLock::new() }, - LangInfo { code: "it", name: "Italiano", source: catalog!("it"), plural: plural_one_other, complete_menus: true, catalog: OnceLock::new() }, + LangInfo { code: "nl", name: "Nederlands", source: catalog!("nl"), plural: plural_one_other, complete_menus: true, rtl: false, catalog: OnceLock::new() }, + LangInfo { code: "it", name: "Italiano", source: catalog!("it"), plural: plural_one_other, complete_menus: true, rtl: false, catalog: OnceLock::new() }, // Hungarian: a count takes the singular noun ("3 réteg"), so one plural form. - LangInfo { code: "hu", name: "Magyar", source: catalog!("hu"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() }, + LangInfo { code: "hu", name: "Magyar", source: catalog!("hu"), plural: plural_none, complete_menus: true, rtl: false, catalog: OnceLock::new() }, // Turkish; `tr`, `tr-TR` and `tr_TR` locales resolve here. - LangInfo { code: "tr", name: "Türkçe", source: catalog!("tr"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() }, + LangInfo { code: "tr", name: "Türkçe", source: catalog!("tr"), plural: plural_none, complete_menus: true, rtl: false, catalog: OnceLock::new() }, // Vietnamese; `vi-VN` resolves here. - LangInfo { code: "vi", name: "Tiếng Việt", source: catalog!("vi"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() }, + LangInfo { code: "vi", name: "Tiếng Việt", source: catalog!("vi"), plural: plural_none, complete_menus: true, rtl: false, catalog: OnceLock::new() }, // العربية: the whole interface with six-form plurals; it reads right-to-left (see // [`dir_for_code`] and [`crate::direction`]), so the shell mirrors for it. - LangInfo { code: "ar", name: "العربية", source: catalog!("ar"), plural: plural_arabic, complete_menus: true, catalog: OnceLock::new() }, + LangInfo { code: "ar", name: "العربية", source: catalog!("ar"), plural: plural_arabic, complete_menus: true, rtl: true, catalog: OnceLock::new() }, ]; impl LangInfo { @@ -251,7 +256,7 @@ impl LangInfo { } fn catalog(&self) -> &Catalog { - self.catalog.get_or_init(|| Catalog::parse(&self.text())) + self.catalog.get_or_init(|| Catalog::parse(&self.text(), self.rtl)) } } @@ -765,13 +770,19 @@ mod tests { #[test] fn catalog_kinds_are_parsed_and_looked_up() { - let c = Catalog::parse("# c\n\tHello\tこんにちは\n@id\tfile.save\t保存する\nmenu\tWindows\tウィンドウ群\n@plural\t{n} file|{n} files\t{n} 個\n\n"); + let c = Catalog::parse("# c\n\tHello\tこんにちは\n@id\tfile.save\t保存する\nmenu\tWindows\tウィンドウ群\n@plural\t{n} file|{n} files\t{n} 個\n\n", false); assert_eq!(c.plain("Hello"), Some("こんにちは")); assert_eq!(c.id("file.save"), Some("保存する")); assert_eq!(c.contextual("menu", "Windows"), Some("ウィンドウ群")); assert_eq!(c.contextual("other", "Windows"), None); assert_eq!(c.plural("{n} file", "{n} files", 0), Some("{n} 個")); assert_eq!(c.plural("{n} file", "{n} files", 5), Some("{n} 個"), "an index past the forms clamps"); + // A right-to-left catalog's rows come back in visual order (bidi.rs): the runs in the + // order egui draws them, the letters inside each run in logical order. + let c = Catalog::parse("\tDocument Setup…\tإعداد المستند…\n", true); + assert_eq!(c.plain("Document Setup…"), Some("…المستند إعداد")); + let c = Catalog::parse("\tDocument Setup…\tإعداد المستند…\n", false); + assert_eq!(c.plain("Document Setup…"), Some("إعداد المستند…")); } #[test] @@ -855,7 +866,7 @@ mod tests { source: b"\x00garbage", plural: plural_none, complete_menus: false, - catalog: OnceLock::new(), + rtl: false, catalog: OnceLock::new(), })); assert_eq!(info.text(), ""); assert_eq!(tr(Lang(info), "Layer"), "Layer", "falls back to English");