* claim: #3457 * Hebrew interface language with right-to-left text (#3457) Adds a complete Hebrew catalog (assets/locales/he.json, original translations) and registers `he`. egui 0.36 shapes each font run with harfrust, so a run of Hebrew letters is drawn right to left, but it places the runs of a line left to right in stored order. The new `bidi` module runs the Unicode Bidirectional Algorithm (unicode-bidi, MIT OR Apache-2.0) over each message of a right-to-left catalog once, giving egui the runs in display order with brackets mirrored and placeholders kept whole, while leaving each Hebrew run's letters in reading order for the shaper. A test lays messages out with a real Hebrew font and checks where the glyphs land. Desktop builds append a system Hebrew font (Arial Hebrew / SF Hebrew, Segoe UI / Arial, Noto Sans Hebrew / DejaVu Sans). Layout mirroring, wrapped multi-line RTL paragraphs and a web Hebrew font are follow-ups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Hebrew: translate the new Describe Command label; list he in the control protocol Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Hebrew: catch up with main's catalog and the new ribbon (#3457) - Translate the 258 messages main added since the branch was cut, drop the 38 it removed (10 renamed ones keep their translation) and retranslate the two whose English changed (toolbar → application bar). - The timeline title is ציר הזמן, matching the glossary. - Ribbon buttons split their labels into two lines from the start of the string; Hebrew labels come in display order, so the first line showed the end of the phrase ("חדשה / סקיצה"). For right-to-left labels the first line now takes the words at the end of the string, and a shortened line loses characters, and shows its ellipsis, on the left. The word-boundary sweep checks Hebrew from the lines the galley is built from, since epaint's right-to-left rows carry zero-width glyphs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Hebrew: after rebasing onto main, load the Hebrew face with the cached system fonts main now searches the system fallback faces once (SystemFonts, on a thread); the Hebrew face joins that search with its coverage check. Drop the three camera-animation messages main removed (#4296) from the Hebrew catalog. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Hebrew: translate the messages main added after the catch-up (#3457) Translates the messages main added since the last catch-up: the history bar's buttons and name toggles, the 3D mouse driver and axis mapping, the thread size columns, the File view (home page), the redesigned Preferences, the new issue report dialog, free orbit and the assistant's setup card. Drops the one message main removed. The catalog has every English message again, so the complete-catalog checks pass for he. * Arabic interface language (right-to-left, on the Hebrew bidi path) Adds an original Arabic translation of the whole English catalog (assets/locales/ar.json, every message) and registers it. `ar` joins the complete catalogs, so a message added to en.json later fails the build until it is translated. It goes through the right-to-left path of #3458 unchanged: crate::bidi puts each message in display order and leaves every Arabic word's letters in reading order for harfrust, which joins them with the font's own tables. Ribbon labels use the right-to-left line split from the same stack. fonts.rs adds a system Arabic fallback after the Latin interface font, which keeps spaces, digits and Latin text so each Arabic word stays one shaped run: Segoe UI/Tahoma/Arial on Windows, SF Arabic/Geeza Pro/ Damascus/Tahoma on macOS, Noto Sans or Naskh Arabic/KACST One/DejaVu Sans on Linux, or NotoSansArabic-Regular.ttf in CRAFT_FONTS_DIR. It is the first fallback for an Arabic UI (Arial Unicode, a CJK candidate, has Arabic letters without joining data) and the last otherwise; like Thai and Hebrew it is never promoted for a CJK interface. Tests: the catalog comes back in display order with no directional controls, and Arabic laid out with a real font lands on screen word by word in reading order. * Hebrew: review the catch-up translations; restore the camera-animation messages (#3457) - Review of the 533 messages translated in the previous commit: 21 corrected. Keys in the motion dialog are keyframes (נקודות מפתח, as in Add Key), the Design workspace is תכן as in its label, a dropped "(Direct Driver)" is restored, terms aligned with the rest of the catalog (פורמט, סוכן קוד, רצועת הכלים), and a few calques reworded. - Translate ui.animate_view_changes, ui.animation_speed and ui.look_at_anim_desc, which main has again, so he stays complete. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Arabic and Hebrew: translate the messages main added since (#3457, #3762) Both catalogs again carry every English message. The 760 messages main added since the last rebase (render workspace, material editor, standard views, sheet metal Path Flange, AI app connections, document-on-disk notices and more) come from A-AL-ANAZI's translations on #3768; the five Perforate dialog messages are new here. The earlier Hebrew review is kept on top of them, and 33 of the new Hebrew messages are corrected: "completed" was "perfect" (מושלם → גמור), Regrade read as ranking (now תיקון צבע מחדש), shaders, guarantee, the Mirror reflection mode, simulations and displacement. Co-authored-by: Abdullah <alksa2025@gmail.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Arabic and Hebrew: attribution rows as a pending file main now takes new ATTRIBUTION.md rows as one file per change (attribution/pending/), so the he.json and ar.json rows move there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Arabic and Hebrew: translate the 23 messages main added since (#3457, #3762) Both catalogs again carry every English message; the two theme-page messages main removed are dropped. Twelve of the new messages (link updates while loading, the agent chat's model choice, plugin search, render quality) come from A-AL-ANAZI's translations on #3768; the sketch plane descriptions, the rigid group and empty-boolean messages, free sketch points and the web update note are new here. Co-authored-by: Abdullah <alksa2025@gmail.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Arabic and Hebrew: translate the 12 messages main added since (#3457, #3762) Eleven come from A-AL-ANAZI's #3768; "Turn Up Axis" in Hebrew follows the catalog's existing up-axis wording, and the agent chat's no-tool-call message is new in both. Co-authored-by: Abdullah <alksa2025@gmail.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Arabic and Hebrew: translate the 22 messages main added since (#3457, #3762) * Arabic and Hebrew: a label found by its English text comes back in display order too (#3457, #3762) * Arabic and Hebrew: translate the 32 messages main added since (#3457, #3762) * Arabic and Hebrew: translate the 34 messages main added since (#3457, #3762) * Arabic and Hebrew: translate the 30 messages main added since (#3457, #3762) * Arabic and Hebrew: translate the 7 messages main added since (#3457, #3762) --------- Co-authored-by: rootarchitect <7781866+rootarchitect@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Abdullah alanazi <x1700@MacBook-Air-Abdullah-2.local>
This commit is contained in:
Generated
+7
@@ -4441,6 +4441,7 @@ dependencies = [
|
||||
"tiny-skia",
|
||||
"toml",
|
||||
"ttf-parser",
|
||||
"unicode-bidi",
|
||||
"web-time",
|
||||
"winreg",
|
||||
"zip",
|
||||
@@ -4950,6 +4951,12 @@ version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-bidi"
|
||||
version = "0.3.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-general-category"
|
||||
version = "1.1.0"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
||||
| assets/locales/ar.json | Abdullah (A-AL-ANAZI) | Original Arabic translation of SolidCraft's English catalog; no commercial CAD text used | MIT OR Apache-2.0 |
|
||||
| assets/locales/he.json | SolidCraft contributors | Original Hebrew translation of SolidCraft's English catalog; no commercial CAD text used | MIT OR Apache-2.0 |
|
||||
@@ -22,6 +22,9 @@ web-time = { workspace = true }
|
||||
# BMP and TIFF as PNG).
|
||||
image = { workspace = true, features = ["jpeg", "ico", "gif", "webp", "bmp", "tiff"] }
|
||||
ttf-parser = { workspace = true }
|
||||
# Right-to-left interface text (Hebrew): the Unicode Bidirectional Algorithm puts translated
|
||||
# strings in display order, which egui does not do itself (MIT OR Apache-2.0).
|
||||
unicode-bidi = "0.3"
|
||||
semver = { workspace = true }
|
||||
# Updates: the downloaded package's SHA-256 (against the release's SHA256SUMS.txt), its optional
|
||||
# minisign signature (MIT), and the portable .zip's executables.
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Right-to-left interface text. egui shapes each run of one font with harfrust, which draws a
|
||||
//! run of Hebrew letters right to left, but it has no bidirectional layout: the runs of a line
|
||||
//! (words, spaces, numbers, punctuation) are placed left to right in the order they are stored, so
|
||||
//! a Hebrew sentence would show its words in the wrong order and its punctuation on the wrong
|
||||
//! side. [`visual`] runs the Unicode Bidirectional Algorithm (UAX #9) over a string and returns
|
||||
//! the order egui needs: the runs of the line in display order, brackets inside right-to-left
|
||||
//! text mirrored, and the letters of each right-to-left run left in reading order for the shaper
|
||||
//! to reverse.
|
||||
//!
|
||||
//! This is for translated interface text, which is stored in reading (logical) order in the
|
||||
//! catalogs. Each line is its own paragraph and takes its direction from its first strong
|
||||
//! character, so English text comes back unchanged. The layout itself stays left to right, and
|
||||
//! text egui wraps onto several lines keeps the order of the whole string, so long right-to-left
|
||||
//! messages are best kept to one line or split with `\n`.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// Wraps a run that must stay one left-to-right unit inside right-to-left text: a left-to-right
|
||||
/// override inside an isolate, so the run is placed as a whole and keeps its own order.
|
||||
const UNIT_START: &str = "\u{2066}\u{202D}";
|
||||
const UNIT_END: &str = "\u{202C}\u{2069}";
|
||||
|
||||
/// Whether `text` has a character from a right-to-left script (Hebrew, Arabic, Syriac, Thaana,
|
||||
/// N'Ko, Samaritan, Mandaic and their presentation forms).
|
||||
pub fn has_rtl(text: &str) -> bool {
|
||||
text.chars().any(|c| matches!(c, '\u{0590}'..='\u{08FF}' | '\u{FB1D}'..='\u{FDFF}' | '\u{FE70}'..='\u{FEFC}'))
|
||||
}
|
||||
|
||||
/// `text` in the order egui draws correctly (see the module notes). Text without right-to-left
|
||||
/// characters is returned as it is.
|
||||
pub fn visual(text: &str) -> Cow<'_, str> {
|
||||
if !has_rtl(text) {
|
||||
return Cow::Borrowed(text);
|
||||
}
|
||||
let on_screen = screen_order(text);
|
||||
// The shaper reverses each run of right-to-left letters itself, so put those back in reading
|
||||
// order; everything between them stays where the algorithm placed it.
|
||||
let mut output = String::with_capacity(on_screen.len());
|
||||
let mut letters: Vec<char> = Vec::new();
|
||||
for c in on_screen.chars() {
|
||||
if has_rtl(c.encode_utf8(&mut [0; 4])) {
|
||||
letters.push(c);
|
||||
} else {
|
||||
output.extend(letters.drain(..).rev());
|
||||
output.push(c);
|
||||
}
|
||||
}
|
||||
output.extend(letters.drain(..).rev());
|
||||
Cow::Owned(output)
|
||||
}
|
||||
|
||||
/// `text` as it appears on screen, read left to right: what [`visual`] makes egui draw.
|
||||
pub(crate) fn screen_order(text: &str) -> String {
|
||||
let mut output = String::with_capacity(text.len());
|
||||
for (index, line) in text.split('\n').enumerate() {
|
||||
if index > 0 {
|
||||
output.push('\n');
|
||||
}
|
||||
visual_line(line, &mut output);
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
/// A catalog message in display order (see [`visual`]), with each `{placeholder}` kept whole
|
||||
/// where it stands, so a value substituted afterwards lands in the right place and keeps its own
|
||||
/// order: a number, a file name, or a label that is already in display order.
|
||||
pub fn visual_template(text: &str) -> Cow<'_, str> {
|
||||
if !has_rtl(text) || !text.contains('{') {
|
||||
return visual(text);
|
||||
}
|
||||
let mut marked = String::with_capacity(text.len() + 16);
|
||||
let mut rest = text;
|
||||
while let Some((before, after)) = rest.split_once('{') {
|
||||
marked.push_str(before);
|
||||
let Some((name, remaining)) = after.split_once('}') else {
|
||||
marked.push('{');
|
||||
rest = after;
|
||||
continue;
|
||||
};
|
||||
marked.push_str(UNIT_START);
|
||||
marked.push('{');
|
||||
marked.push_str(name);
|
||||
marked.push('}');
|
||||
marked.push_str(UNIT_END);
|
||||
rest = remaining;
|
||||
}
|
||||
marked.push_str(rest);
|
||||
Cow::Owned(visual(&marked).into_owned())
|
||||
}
|
||||
|
||||
fn visual_line(line: &str, output: &mut String) {
|
||||
let info = unicode_bidi::ParagraphBidiInfo::new(line, None);
|
||||
let (levels, runs) = info.visual_runs(0..line.len());
|
||||
for run in runs {
|
||||
let Some(text) = line.get(run.clone()) else { continue };
|
||||
let rtl = levels.get(run.start).is_some_and(|level| level.is_rtl());
|
||||
if rtl {
|
||||
output.extend(text.chars().rev().filter(|c| !is_control(*c)).map(mirrored));
|
||||
} else {
|
||||
output.extend(text.chars().filter(|c| !is_control(*c)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Directional formatting characters: they steer the algorithm and have no glyph to draw.
|
||||
fn is_control(c: char) -> bool {
|
||||
matches!(c, '\u{200E}' | '\u{200F}' | '\u{061C}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
|
||||
}
|
||||
|
||||
/// The mirrored form of a paired punctuation mark drawn inside a right-to-left run (UAX #9 L4),
|
||||
/// for the marks interface text uses.
|
||||
fn mirrored(c: char) -> char {
|
||||
match c {
|
||||
'(' => ')',
|
||||
')' => '(',
|
||||
'[' => ']',
|
||||
']' => '[',
|
||||
'{' => '}',
|
||||
'}' => '{',
|
||||
'<' => '>',
|
||||
'>' => '<',
|
||||
'«' => '»',
|
||||
'»' => '«',
|
||||
'‹' => '›',
|
||||
'›' => '‹',
|
||||
'≤' => '≥',
|
||||
'≥' => '≤',
|
||||
_ => c,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn left_to_right_text_is_unchanged() {
|
||||
for text in ["Extrude", "Save changes to Bracket?", "Units: mm", "", "a\nb", "↖ 2 selected"] {
|
||||
assert!(matches!(visual(text), Cow::Borrowed(t) if t == text), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// One Hebrew word is one run the shaper reverses itself; the words of a sentence swap
|
||||
/// places, so the first word ends up on the right.
|
||||
#[test]
|
||||
fn words_swap_places_and_letters_stay_in_reading_order() {
|
||||
assert_eq!(visual("שלום"), "שלום");
|
||||
assert_eq!(screen_order("שלום"), "םולש");
|
||||
assert_eq!(visual("שמור בשם"), "בשם שמור");
|
||||
assert_eq!(screen_order("שמור בשם"), "םשב רומש");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_units_and_latin_words_keep_their_order() {
|
||||
// "Units: mm": the colon follows the Hebrew word, so on screen it sits on its left.
|
||||
assert_eq!(visual("יחידות: mm"), "mm :יחידות");
|
||||
assert_eq!(screen_order("יחידות: mm"), "mm :תודיחי");
|
||||
assert_eq!(visual("סקיצה12"), "12סקיצה");
|
||||
assert_eq!(visual("ייצוא STEP"), "STEP ייצוא");
|
||||
assert_eq!(visual("עומק 20.5 mm"), "mm 20.5 עומק");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brackets_inside_right_to_left_text_are_mirrored() {
|
||||
// "Parameters (5)": the parentheses still open towards the number.
|
||||
assert_eq!(visual("פרמטרים (5)"), "(5) פרמטרים");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_line_is_its_own_paragraph() {
|
||||
assert_eq!(visual("שלום עולם\nworld"), "עולם שלום\nworld");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placeholders_stay_whole_where_they_stand() {
|
||||
// "Save the changes to {name}?": the question mark ends the sentence on the left.
|
||||
assert_eq!(visual_template("לשמור את השינויים ב־{name}?"), "?{name}ב־ השינויים את לשמור");
|
||||
assert_eq!(visual_template("{count} נבחרו"), "נבחרו {count}");
|
||||
assert_eq!(visual_template("Save {name}?"), "Save {name}?");
|
||||
// Unmarked, the Latin placeholder name would make the whole line left to right.
|
||||
assert_eq!(screen_order("{count} נבחרו"), "{count} ורחבנ");
|
||||
assert_eq!(visual_template("סגור {"), visual("סגור {"));
|
||||
}
|
||||
}
|
||||
+204
-19
@@ -1,4 +1,5 @@
|
||||
//! Bundled IBM Plex interface faces, user overrides, and language-specific system fallbacks.
|
||||
//! Bundled IBM Plex interface faces, user overrides, and language-specific system fallbacks
|
||||
//! (CJK, Hangul, Thai, Hebrew).
|
||||
//! The same definitions are used on desktop and web; the web shell adds Japanese on demand.
|
||||
|
||||
use std::sync::Arc;
|
||||
@@ -142,9 +143,17 @@ pub fn with_ui_font(mut fonts: FontDefinitions, font: egui::FontData) -> FontDef
|
||||
/// Name of the Hangul fallback entry in [`egui::FontDefinitions`], after the CJK ones.
|
||||
pub const HANGUL_FALLBACK: &str = "hangul_fallback";
|
||||
|
||||
/// Name of the Thai fallback entry in [`egui::FontDefinitions`], last (#1902).
|
||||
/// Name of the Thai fallback entry in [`egui::FontDefinitions`], after the CJK ones (#1902).
|
||||
pub const THAI_FALLBACK: &str = "thai_fallback";
|
||||
|
||||
/// Name of the Hebrew fallback entry in [`egui::FontDefinitions`], last (#3457).
|
||||
pub const HEBREW_FALLBACK: &str = "hebrew_fallback";
|
||||
|
||||
/// Name of the Arabic fallback entry in [`egui::FontDefinitions`]: first of the fallbacks for an
|
||||
/// Arabic UI, last otherwise. It stays after the Latin interface font, which keeps drawing spaces,
|
||||
/// digits and Latin text, so each Arabic word is one shaped run (see [`crate::bidi`]).
|
||||
pub const ARABIC_FALLBACK: &str = "arabic_fallback";
|
||||
|
||||
/// egui's built-in monospace face, also the last fallback of every sans family (#2955).
|
||||
pub const SYMBOL_FALLBACK: &str = "Hack";
|
||||
|
||||
@@ -479,6 +488,55 @@ const THAI_FONT_CANDIDATES: &[&str] = &[
|
||||
"/usr/share/fonts/tlwg/Loma.otf",
|
||||
];
|
||||
|
||||
/// Hebrew fonts, appended last: egui's built-in faces have no Hebrew, so without one the Hebrew
|
||||
/// interface and Hebrew names show as empty boxes (#3457).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const HEBREW_FONT_CANDIDATES: &[&str] = &[
|
||||
// Windows: Segoe UI, Arial
|
||||
"C:\\Windows\\Fonts\\segoeui.ttf",
|
||||
"C:\\Windows\\Fonts\\arial.ttf",
|
||||
// macOS: Arial Hebrew, SF Hebrew
|
||||
"/System/Library/Fonts/ArialHB.ttc",
|
||||
"/System/Library/Fonts/SFHebrew.ttf",
|
||||
"/System/Library/Fonts/Supplemental/Arial.ttf",
|
||||
// Linux: Noto Sans Hebrew, DejaVu Sans
|
||||
"/usr/share/fonts/noto/NotoSansHebrew-Regular.ttf",
|
||||
"/usr/share/fonts/truetype/noto/NotoSansHebrew-Regular.ttf",
|
||||
"/usr/share/fonts/google-noto/NotoSansHebrew-Regular.ttf",
|
||||
"/usr/share/fonts/google-noto-vf/NotoSansHebrew[wght].ttf",
|
||||
"/usr/share/fonts/opentype/noto/NotoSansHebrew-Regular.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
"/usr/share/fonts/TTF/DejaVuSans.ttf",
|
||||
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
|
||||
];
|
||||
|
||||
/// Arabic fonts with the joining forms the shaper uses. egui's built-in faces have no Arabic.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const ARABIC_FONT_CANDIDATES: &[&str] = &[
|
||||
// Windows: Segoe UI, Tahoma, Arial
|
||||
"C:\\Windows\\Fonts\\segoeui.ttf",
|
||||
"C:\\Windows\\Fonts\\tahoma.ttf",
|
||||
"C:\\Windows\\Fonts\\arial.ttf",
|
||||
// macOS: SF Arabic (11 and later), Geeza Pro, Damascus, Tahoma
|
||||
"/System/Library/Fonts/SFArabic.ttf",
|
||||
"/System/Library/Fonts/GeezaPro.ttc",
|
||||
"/System/Library/Fonts/Supplemental/GeezaPro.ttc",
|
||||
"/System/Library/Fonts/Supplemental/Damascus.ttc",
|
||||
"/System/Library/Fonts/Supplemental/Tahoma.ttf",
|
||||
// Linux: Noto Sans Arabic, Noto Naskh Arabic, KACST One, DejaVu Sans
|
||||
"/usr/share/fonts/noto/NotoSansArabic-Regular.ttf",
|
||||
"/usr/share/fonts/truetype/noto/NotoSansArabic-Regular.ttf",
|
||||
"/usr/share/fonts/google-noto/NotoSansArabic-Regular.ttf",
|
||||
"/usr/share/fonts/google-noto-vf/NotoSansArabic[wght].ttf",
|
||||
"/usr/share/fonts/opentype/noto/NotoSansArabic-Regular.ttf",
|
||||
"/usr/share/fonts/truetype/noto/NotoNaskhArabic-Regular.ttf",
|
||||
"/usr/share/fonts/noto/NotoNaskhArabic-Regular.ttf",
|
||||
"/usr/share/fonts/truetype/kacst-one/KacstOne.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
"/usr/share/fonts/TTF/DejaVuSans.ttf",
|
||||
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
|
||||
];
|
||||
|
||||
/// Fonts covering simplified Chinese, appended after the CJK fallback so Chinese renders even
|
||||
/// when the CJK font found is a Japanese one without simplified characters (Hiragino Gothic,
|
||||
/// Meiryo, Yu Gothic).
|
||||
@@ -503,6 +561,13 @@ const CHINESE_FONT_CANDIDATES: &[&str] = &[
|
||||
"/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf",
|
||||
];
|
||||
|
||||
/// Whether the first face in `bytes` draws `c`: some candidates (an older Arial, a trimmed
|
||||
/// DejaVu) may lack the script they are listed for.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn covers(bytes: &[u8], c: char) -> bool {
|
||||
ttf_parser::Face::parse(bytes, 0).is_ok_and(|face| face.glyph_index(c).is_some())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn try_read_font(path: &std::path::Path) -> Option<Vec<u8>> {
|
||||
if let Ok(bytes) = std::fs::read(path)
|
||||
@@ -654,16 +719,19 @@ fn find_system_cjk_font() -> Option<Vec<u8>> {
|
||||
/// epaint centres each face's own line height in the row, so glyphs from two faces of very
|
||||
/// different height (Meiryo ≈ 2.0 em, Microsoft YaHei ≈ 1.4 em) sit at different heights
|
||||
/// inside one word. One face for the whole word keeps them on one baseline.
|
||||
/// Thai comes last whatever the language: no other face draws it.
|
||||
pub fn fallback_order(language: &str) -> [&'static str; 4] {
|
||||
/// Thai, Hebrew and Arabic come last whatever the language: no other face draws them. Arabic
|
||||
/// goes first for `ar` instead: a CJK font such as Arial Unicode also has Arabic letters, without
|
||||
/// the shaping data that joins them.
|
||||
pub fn fallback_order(language: &str) -> [&'static str; 6] {
|
||||
match language {
|
||||
"zh" | "zh-TW" => [CHINESE_FALLBACK, CJK_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK],
|
||||
"ko" => [HANGUL_FALLBACK, CJK_FALLBACK, CHINESE_FALLBACK, THAI_FALLBACK],
|
||||
_ => [CJK_FALLBACK, CHINESE_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK],
|
||||
"zh" | "zh-TW" => [CHINESE_FALLBACK, CJK_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK, HEBREW_FALLBACK, ARABIC_FALLBACK],
|
||||
"ko" => [HANGUL_FALLBACK, CJK_FALLBACK, CHINESE_FALLBACK, THAI_FALLBACK, HEBREW_FALLBACK, ARABIC_FALLBACK],
|
||||
"ar" => [ARABIC_FALLBACK, CJK_FALLBACK, CHINESE_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK, HEBREW_FALLBACK],
|
||||
_ => [CJK_FALLBACK, CHINESE_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK, HEBREW_FALLBACK, ARABIC_FALLBACK],
|
||||
}
|
||||
}
|
||||
|
||||
/// Configure font definitions with system CJK, Chinese, Hangul and Thai fallbacks where available,
|
||||
/// Configure font definitions with system CJK, Chinese, Hangul, Thai and Hebrew fallbacks where available,
|
||||
/// ordered for the UI language (see [`fallback_order`]), after the interface font `ui_font`
|
||||
/// when one is chosen (see [`ui_font`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -680,6 +748,8 @@ struct SystemFonts {
|
||||
chinese: Option<Vec<u8>>,
|
||||
hangul: Option<Vec<u8>>,
|
||||
thai: Option<Vec<u8>>,
|
||||
hebrew: Option<Vec<u8>>,
|
||||
arabic: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -692,7 +762,9 @@ fn system_fallbacks() -> &'static SystemFonts {
|
||||
let chinese = find_system_chinese_font().filter(|bytes| cjk.as_ref() != Some(bytes));
|
||||
let hangul = HANGUL_FONT_CANDIDATES.iter().find_map(|path| try_read_font(std::path::Path::new(path)));
|
||||
let thai = THAI_FONT_CANDIDATES.iter().find_map(|path| try_read_font(std::path::Path::new(path)));
|
||||
SystemFonts { cjk, chinese, hangul, thai }
|
||||
let hebrew = HEBREW_FONT_CANDIDATES.iter().find_map(|path| try_read_font(std::path::Path::new(path)).filter(|bytes| covers(bytes, 'א')));
|
||||
let arabic = arabic_font();
|
||||
SystemFonts { cjk, chinese, hangul, thai, hebrew, arabic }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -733,9 +805,9 @@ pub fn setup_fonts_without_waiting(ctx: &egui::Context, language: &str, ui_font:
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn install_fonts(ctx: &egui::Context, language: &str, ui_font: &str, system: Option<&SystemFonts>) {
|
||||
let (cjk, chinese, hangul, thai) = match system {
|
||||
Some(f) => (f.cjk.clone(), f.chinese.clone(), f.hangul.clone(), f.thai.clone()),
|
||||
None => (None, None, None, None),
|
||||
let (cjk, chinese, hangul, thai, hebrew, arabic) = match system {
|
||||
Some(f) => (f.cjk.clone(), f.chinese.clone(), f.hangul.clone(), f.thai.clone(), f.hebrew.clone(), f.arabic.clone()),
|
||||
None => (None, None, None, None, None, None),
|
||||
};
|
||||
let mut fonts = base_font_definitions();
|
||||
if let Some(font) = self::ui_font(ui_font) {
|
||||
@@ -747,7 +819,9 @@ fn install_fonts(ctx: &egui::Context, language: &str, ui_font: &str, system: Opt
|
||||
CJK_FALLBACK => cjk.clone(),
|
||||
CHINESE_FALLBACK => chinese.clone(),
|
||||
HANGUL_FALLBACK => hangul.clone(),
|
||||
_ => thai.clone(),
|
||||
THAI_FALLBACK => thai.clone(),
|
||||
HEBREW_FALLBACK => hebrew.clone(),
|
||||
_ => arabic.clone(),
|
||||
};
|
||||
if let Some(bytes) = bytes
|
||||
&& let Some(with_fallback) = with_fallback(fonts.clone(), name, bytes)
|
||||
@@ -758,7 +832,9 @@ fn install_fonts(ctx: &egui::Context, language: &str, ui_font: &str, system: Opt
|
||||
if needs_cjk_font(language) {
|
||||
// Select the first installed face in language order (a duplicate Chinese face may
|
||||
// already be installed as CJK_FALLBACK). Keep explicit interface choices ahead of it.
|
||||
if let Some(primary) = order.into_iter().find(|name| *name != THAI_FALLBACK && fonts.font_data.contains_key(*name)) {
|
||||
if let Some(primary) =
|
||||
order.into_iter().find(|name| ![THAI_FALLBACK, HEBREW_FALLBACK, ARABIC_FALLBACK].contains(name) && fonts.font_data.contains_key(*name))
|
||||
{
|
||||
promote_font_to_front(&mut fonts, primary);
|
||||
}
|
||||
}
|
||||
@@ -843,6 +919,16 @@ fn find_chinese_font_in(dirs: &[std::path::PathBuf]) -> Option<Vec<u8>> {
|
||||
dirs.iter().find_map(|dir| scan_dir_for_font_where(dir, 3, is_chinese_font_name, draws_simplified_chinese))
|
||||
}
|
||||
|
||||
/// The first Arabic font in `CRAFT_FONTS_DIR` (`NotoSansArabic-Regular.ttf`) or the candidate
|
||||
/// paths that draws Arabic.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn arabic_font() -> Option<Vec<u8>> {
|
||||
let pack = std::env::var("CRAFT_FONTS_DIR").ok().map(|dir| std::path::PathBuf::from(dir).join("NotoSansArabic-Regular.ttf"));
|
||||
pack.into_iter()
|
||||
.chain(ARABIC_FONT_CANDIDATES.iter().map(std::path::PathBuf::from))
|
||||
.find_map(|path| try_read_font(&path).filter(|bytes| covers(bytes, 'ب')))
|
||||
}
|
||||
|
||||
/// Web installs the bundled faces synchronously; Japanese is fetched by the shell on demand.
|
||||
/// Preserve that downloaded face when preferences change later in the session.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -1112,13 +1198,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_chinese_ui_puts_the_chinese_face_before_the_japanese_one() {
|
||||
assert_eq!(fallback_order("zh"), [CHINESE_FALLBACK, CJK_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK]);
|
||||
assert_eq!(fallback_order("zh"), [CHINESE_FALLBACK, CJK_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK, HEBREW_FALLBACK, ARABIC_FALLBACK]);
|
||||
assert_eq!(fallback_order("zh-TW"), fallback_order("zh"));
|
||||
assert_eq!(fallback_order("ko"), [HANGUL_FALLBACK, CJK_FALLBACK, CHINESE_FALLBACK, THAI_FALLBACK]);
|
||||
for lang in ["en", "ja", "de"] {
|
||||
assert_eq!(fallback_order("ko"), [HANGUL_FALLBACK, CJK_FALLBACK, CHINESE_FALLBACK, THAI_FALLBACK, HEBREW_FALLBACK, ARABIC_FALLBACK]);
|
||||
assert_eq!(fallback_order("ar")[0], ARABIC_FALLBACK);
|
||||
for lang in ["en", "ja", "de", "he"] {
|
||||
assert_eq!(
|
||||
fallback_order(lang),
|
||||
[CJK_FALLBACK, CHINESE_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK],
|
||||
[CJK_FALLBACK, CHINESE_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK, HEBREW_FALLBACK, ARABIC_FALLBACK],
|
||||
"{lang} keeps the Japanese font first"
|
||||
);
|
||||
}
|
||||
@@ -1130,7 +1217,7 @@ mod tests {
|
||||
for family in all_families() {
|
||||
let list = &fonts.families[&family];
|
||||
assert_eq!(list.first(), defaults.families[&family].first(), "the Latin UI font stays first");
|
||||
assert_eq!(&list[list.len() - 4..], [CHINESE_FALLBACK, CJK_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK]);
|
||||
assert_eq!(&list[list.len() - 6..], [CHINESE_FALLBACK, CJK_FALLBACK, HANGUL_FALLBACK, THAI_FALLBACK, HEBREW_FALLBACK, ARABIC_FALLBACK]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1156,6 +1243,104 @@ mod tests {
|
||||
assert!(thai(with_fallback(egui::FontDefinitions::default(), THAI_FALLBACK, bytes).unwrap()), "Thai draws with the fallback");
|
||||
}
|
||||
|
||||
/// The Hebrew interface (#3457): every Hebrew candidate this machine has that passes the
|
||||
/// coverage check draws Hebrew, and the fonts set up must then draw it.
|
||||
#[test]
|
||||
fn a_hebrew_fallback_draws_hebrew() {
|
||||
let found: Vec<Vec<u8>> =
|
||||
HEBREW_FONT_CANDIDATES.iter().filter_map(|path| try_read_font(std::path::Path::new(path))).filter(|bytes| covers(bytes, 'א')).collect();
|
||||
for bytes in &found {
|
||||
let face = ttf_parser::Face::parse(bytes, 0).unwrap();
|
||||
for c in "שלום עולם".chars().filter(|c| !c.is_whitespace()) {
|
||||
assert!(face.glyph_index(c).is_some(), "{c:?} is in the Hebrew font");
|
||||
}
|
||||
}
|
||||
let hebrew = |fonts: egui::FontDefinitions| {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(fonts);
|
||||
ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear();
|
||||
ctx.fonts_mut(|f| f.has_glyphs(&egui::FontId::proportional(14.0), "שלום"))
|
||||
};
|
||||
assert!(!hebrew(base_font_definitions()), "the bundled faces have no Hebrew");
|
||||
let Some(bytes) = found.into_iter().next() else { return };
|
||||
assert!(hebrew(with_fallback(base_font_definitions(), HEBREW_FALLBACK, bytes).unwrap()), "Hebrew draws with the fallback");
|
||||
}
|
||||
|
||||
/// What a Hebrew interface shows depends on egui's own shaping as much as on `bidi::visual`:
|
||||
/// lay messages out with a real Hebrew font and read the glyphs left to right, as they land on
|
||||
/// screen. They must come out in the order the line has on screen (#3457).
|
||||
#[test]
|
||||
fn hebrew_messages_land_on_screen_in_display_order() {
|
||||
let Some(bytes) = HEBREW_FONT_CANDIDATES.iter().filter_map(|path| try_read_font(std::path::Path::new(path))).find(|bytes| covers(bytes, 'א'))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(with_symbol_fallback(with_fallback(base_font_definitions(), HEBREW_FALLBACK, bytes).unwrap()));
|
||||
ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear();
|
||||
let on_screen = |text: &str| {
|
||||
let galley = ctx.fonts_mut(|f| f.layout_no_wrap(text.to_owned(), egui::FontId::proportional(14.0), egui::Color32::WHITE));
|
||||
let mut glyphs: Vec<(f32, char)> =
|
||||
galley.rows.iter().flat_map(|row| row.row.glyphs.iter()).filter(|g| g.advance_width > 0.0).map(|g| (g.pos.x, g.chr)).collect();
|
||||
glyphs.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
glyphs.into_iter().map(|(_, c)| c).collect::<String>()
|
||||
};
|
||||
for text in ["עץ התכן", "שמירה בשם", "יחידות: mm", "ייצוא STEP", "פרמטרים (5)", "עומק 20.5 mm", "לשמור את השינויים ב־Bracket?"]
|
||||
{
|
||||
assert_eq!(on_screen(&crate::bidi::visual(text)), crate::bidi::screen_order(text), "{text}");
|
||||
}
|
||||
let he = crate::i18n::Locale::for_language("he");
|
||||
for id in ["ui.preferences", "ui.new_design", "ui.feature_history", "ui.needs_design"] {
|
||||
let logical = he.text(id).to_owned();
|
||||
assert_eq!(
|
||||
on_screen(&logical).chars().filter(|c| !c.is_whitespace()).count(),
|
||||
logical.chars().filter(|c| !c.is_whitespace()).count(),
|
||||
"{id}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Arabic interface: lay messages out with a real Arabic font and read the glyphs left to
|
||||
/// right, as they land on screen. The words come out in display order and each word is shaped
|
||||
/// whole (joined forms, so fewer visible glyphs is fine, but never a stray letter order).
|
||||
#[test]
|
||||
fn arabic_messages_land_on_screen_in_display_order() {
|
||||
let Some(bytes) = arabic_font() else { return };
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(with_symbol_fallback(with_fallback(egui::FontDefinitions::default(), ARABIC_FALLBACK, bytes).unwrap()));
|
||||
ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear();
|
||||
// Each space-separated word as the set of its characters (the shaper orders and joins a
|
||||
// word's glyphs, and a glyph's character comes from its cluster), placed by its leftmost
|
||||
// glyph, left to right.
|
||||
let words_left_to_right = |drawn: &str| {
|
||||
let galley = ctx.fonts_mut(|f| f.layout_no_wrap(drawn.to_owned(), egui::FontId::proportional(14.0), egui::Color32::WHITE));
|
||||
let mut words: Vec<(f32, Vec<char>)> = vec![(f32::MAX, Vec::new())];
|
||||
for glyph in galley.rows.iter().flat_map(|row| row.row.glyphs.iter()) {
|
||||
if glyph.chr == ' ' {
|
||||
words.push((f32::MAX, Vec::new()));
|
||||
} else if let Some((x, word)) = words.last_mut() {
|
||||
*x = x.min(glyph.pos.x);
|
||||
word.push(glyph.chr);
|
||||
}
|
||||
}
|
||||
words.retain(|(_, word)| !word.is_empty());
|
||||
words.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
words.into_iter().map(|(_, word)| char_set(word)).collect::<Vec<_>>()
|
||||
};
|
||||
fn char_set(mut chars: Vec<char>) -> Vec<char> {
|
||||
chars.sort_unstable();
|
||||
chars.dedup();
|
||||
chars
|
||||
}
|
||||
// Read right to left, the screen shows the sentence's words in reading order.
|
||||
for text in ["حفظ باسم", "تحليل خطوط المعامِل", "إعادة تعيين الكل", "تصدير STEP"] {
|
||||
let mut read = words_left_to_right(&crate::bidi::visual(text));
|
||||
read.reverse();
|
||||
let expected: Vec<Vec<char>> = text.split(' ').map(|word| char_set(word.chars().collect())).collect();
|
||||
assert_eq!(read, expected, "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cjk_ui_promotes_primary_cjk_font_to_front_for_consistent_baseline() {
|
||||
let defaults = base_font_definitions();
|
||||
|
||||
@@ -13,11 +13,13 @@ pub struct Catalog {
|
||||
pub name: &'static str,
|
||||
source: &'static str,
|
||||
messages: OnceLock<Messages>,
|
||||
/// The messages in display order, for a catalog with right-to-left text (see [`crate::bidi`]).
|
||||
shown: OnceLock<Option<Messages>>,
|
||||
}
|
||||
|
||||
impl Catalog {
|
||||
const fn new(id: &'static str, name: &'static str, source: &'static str) -> Self {
|
||||
Self { id, name, source, messages: OnceLock::new() }
|
||||
Self { id, name, source, messages: OnceLock::new(), shown: OnceLock::new() }
|
||||
}
|
||||
|
||||
fn messages(&'static self) -> &'static Messages {
|
||||
@@ -29,9 +31,32 @@ impl Catalog {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The messages as egui must be given them: right-to-left lines in display order, since egui
|
||||
/// has no bidirectional layout (see [`crate::bidi`]). The same map as [`Self::messages`] for
|
||||
/// every other catalog.
|
||||
fn shown(&'static self) -> &'static Messages {
|
||||
let shown = self.shown.get_or_init(|| {
|
||||
let messages = self.messages();
|
||||
messages
|
||||
.values()
|
||||
.any(|text| crate::bidi::has_rtl(text))
|
||||
.then(|| messages.iter().map(|(id, text)| (id.clone(), crate::bidi::visual_template(text).into_owned())).collect())
|
||||
});
|
||||
match shown {
|
||||
Some(shown) => shown,
|
||||
None => self.messages(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The language's own name as the language list draws it.
|
||||
pub fn display_name(&self) -> std::borrow::Cow<'static, str> {
|
||||
crate::bidi::visual(self.name)
|
||||
}
|
||||
}
|
||||
|
||||
static ENGLISH: Catalog = Catalog::new("en", "English", include_str!(concat!(env!("OUT_DIR"), "/locales/en.json")));
|
||||
static ARABIC: Catalog = Catalog::new("ar", "العربية", include_str!(concat!(env!("OUT_DIR"), "/locales/ar.json")));
|
||||
static CZECH: Catalog = Catalog::new("cs", "Čeština", include_str!(concat!(env!("OUT_DIR"), "/locales/cs.json")));
|
||||
static DANISH: Catalog = Catalog::new("da", "Dansk", include_str!(concat!(env!("OUT_DIR"), "/locales/da.json")));
|
||||
static GERMAN: Catalog = Catalog::new("de", "Deutsch", include_str!(concat!(env!("OUT_DIR"), "/locales/de.json")));
|
||||
@@ -40,6 +65,7 @@ static ENGLISH_UK: Catalog = Catalog::new("en-GB", "English (UK)", include_str!(
|
||||
static SPANISH: Catalog = Catalog::new("es", "Español (España)", include_str!(concat!(env!("OUT_DIR"), "/locales/es.json")));
|
||||
static FRENCH: Catalog = Catalog::new("fr", "Français", include_str!(concat!(env!("OUT_DIR"), "/locales/fr.json")));
|
||||
static GALICIAN: Catalog = Catalog::new("gl", "Galego", include_str!(concat!(env!("OUT_DIR"), "/locales/gl.json")));
|
||||
static HEBREW: Catalog = Catalog::new("he", "עברית", include_str!(concat!(env!("OUT_DIR"), "/locales/he.json")));
|
||||
static HUNGARIAN: Catalog = Catalog::new("hu", "Magyar", include_str!(concat!(env!("OUT_DIR"), "/locales/hu.json")));
|
||||
static INDONESIAN: Catalog = Catalog::new("id", "Bahasa Indonesia", include_str!(concat!(env!("OUT_DIR"), "/locales/id.json")));
|
||||
static ITALIAN: Catalog = Catalog::new("it", "Italiano", include_str!(concat!(env!("OUT_DIR"), "/locales/it.json")));
|
||||
@@ -63,6 +89,7 @@ static CHINESE_TRADITIONAL: Catalog = Catalog::new("zh-TW", "繁體中文", incl
|
||||
#[rustfmt::skip]
|
||||
pub const LOCALES: &[&Catalog] = &[
|
||||
&ENGLISH,
|
||||
&ARABIC,
|
||||
&CZECH,
|
||||
&DANISH,
|
||||
&GERMAN,
|
||||
@@ -70,6 +97,7 @@ pub const LOCALES: &[&Catalog] = &[
|
||||
&SPANISH,
|
||||
&FRENCH,
|
||||
&GALICIAN,
|
||||
&HEBREW,
|
||||
&HUNGARIAN,
|
||||
&INDONESIAN,
|
||||
&ITALIAN,
|
||||
@@ -107,9 +135,14 @@ impl Locale {
|
||||
self.0.name
|
||||
}
|
||||
|
||||
/// Stable message ID → translation → English → ID.
|
||||
/// The language's own name as the language list draws it.
|
||||
pub fn display_name(self) -> std::borrow::Cow<'static, str> {
|
||||
self.0.display_name()
|
||||
}
|
||||
|
||||
/// Stable message ID → translation → English → ID, in display order (see [`crate::bidi`]).
|
||||
pub fn text(self, id: &str) -> &str {
|
||||
self.0.messages().get(id).or_else(|| ENGLISH.messages().get(id)).map_or(id, String::as_str)
|
||||
self.0.shown().get(id).or_else(|| ENGLISH.messages().get(id)).map_or(id, String::as_str)
|
||||
}
|
||||
|
||||
/// Translate source labels from engine/UI tables, preserving unknown labels.
|
||||
@@ -131,7 +164,7 @@ impl Locale {
|
||||
if let Some(candidates) = ids.get(label) {
|
||||
// Preserve the old last-ID preference among available translations. A new
|
||||
// English-only alias must not hide a translation that already exists here.
|
||||
if let Some(text) = candidates.iter().rev().find_map(|id| self.0.messages().get(*id)) {
|
||||
if let Some(text) = candidates.iter().rev().find_map(|id| self.0.shown().get(*id)) {
|
||||
return text;
|
||||
}
|
||||
if let Some(id) = candidates.last() {
|
||||
@@ -397,13 +430,13 @@ mod tests {
|
||||
ENGLISH.messages().values().map(String::as_str).collect()
|
||||
}
|
||||
|
||||
/// Catalogs delivered complete. English is the source catalog; Czech, Italian, Japanese and Chinese
|
||||
/// Catalogs delivered complete. English is the source catalog; Arabic, Czech, Italian, Japanese and Chinese
|
||||
/// are complete. German, Korean, Malay, Russian, French and Ukrainian
|
||||
/// are partial (German and Korean predate the coverage guards; Russian, French and Ukrainian
|
||||
/// are kept partial so a new label doesn't need more translations), so their gaps fall back
|
||||
/// to English and are reported by `cargo xtask i18n` without failing the build, while
|
||||
/// nothing in the complete catalogs may regress.
|
||||
const COMPLETE: &[&str] = &["ja", "zh"];
|
||||
const COMPLETE: &[&str] = &["ar", "he", "ja", "zh"];
|
||||
|
||||
/// `text()` falls back to English silently, so a message a complete locale never received is
|
||||
/// shown in English inside an otherwise translated UI, with nothing in the build to say so.
|
||||
@@ -897,6 +930,61 @@ mod tests {
|
||||
assert_eq!(pt.label("NonExistentKey"), "NonExistentKey");
|
||||
}
|
||||
|
||||
/// Hebrew is stored in reading order; egui reverses each run of Hebrew letters but places
|
||||
/// the runs of a line left to right, so every message comes back with its words, numbers,
|
||||
/// units and placeholders in display order and brackets mirrored (#3457).
|
||||
/// Arabic goes through the same right-to-left path as Hebrew: its words, numbers, units and
|
||||
/// placeholders come back in display order, and each Arabic word's letters stay in reading
|
||||
/// order for the shaper, which joins and reverses them.
|
||||
#[test]
|
||||
fn arabic_catalog_is_registered_and_comes_back_in_display_order() {
|
||||
let ar = Locale::for_language("ar");
|
||||
assert!(is_supported("ar"));
|
||||
assert_eq!(ar.name(), "العربية");
|
||||
assert_eq!(ar.display_name(), "العربية");
|
||||
assert_eq!(ar.text("ui.preferences"), "التفضيلات");
|
||||
assert_eq!(ar.label("Extrude"), "بثق");
|
||||
// Two words: the second is drawn first, on the left.
|
||||
assert_eq!(ar.text("ui.new_design"), "جديد تصميم");
|
||||
assert_eq!(ar.dynamic("Units: mm"), "mm :الوحدات");
|
||||
assert_eq!(ar.dynamic("Sketch1"), "1 رسم");
|
||||
let saved = ar.format("document.save_changes", &[("name", "Bracket")]);
|
||||
assert!(saved.starts_with("؟Bracket "), "{saved}");
|
||||
let english: Messages = serde_json::from_str(ENGLISH.source).unwrap();
|
||||
for id in english.keys() {
|
||||
let text = ar.text(id);
|
||||
assert!(
|
||||
!text.chars().any(|c| matches!(c, '\u{200E}' | '\u{200F}' | '\u{061C}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')),
|
||||
"{id}: {text:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hebrew_catalog_is_registered_and_comes_back_in_display_order() {
|
||||
let he = Locale::for_language("he");
|
||||
assert!(is_supported("he"));
|
||||
assert_eq!(he.name(), "עברית");
|
||||
assert_eq!(he.display_name(), "עברית");
|
||||
assert_eq!(he.text("ui.preferences"), "העדפות");
|
||||
assert_eq!(he.label("Extrude"), "שליפה");
|
||||
assert_eq!(he.dynamic("Sketch1"), "1סקיצה");
|
||||
assert_eq!(he.dynamic("Units: mm"), "mm :יחידות");
|
||||
assert_eq!(he.dynamic("Parameters (5)"), "(5) פרמטרים");
|
||||
assert_eq!(he.format("document.save_changes", &[("name", "My {design}")]), "?My {design}ב־ השינויים את לשמור");
|
||||
assert_eq!(he.given_name("Sketch of bracket"), "Sketch of bracket");
|
||||
assert_eq!(he.label("NonExistentKey"), "NonExistentKey");
|
||||
// No directional control characters reach egui, which would draw them as boxes.
|
||||
let english: Messages = serde_json::from_str(ENGLISH.source).unwrap();
|
||||
for id in english.keys() {
|
||||
let text = he.text(id);
|
||||
assert!(
|
||||
!text.chars().any(|c| matches!(c, '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')),
|
||||
"{id}: {text:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn galician_catalog_is_registered_and_translates_keys() {
|
||||
let gl = Locale::for_language("gl");
|
||||
|
||||
@@ -13,6 +13,7 @@ pub mod access;
|
||||
pub mod agent_chat;
|
||||
pub mod agent_cursor;
|
||||
pub mod ai_connect;
|
||||
pub mod bidi;
|
||||
pub mod bom_panel;
|
||||
pub mod browser;
|
||||
pub mod browser_canvas;
|
||||
|
||||
@@ -9,9 +9,9 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
ui_kit::settings_form(ui, labels, |ui| {
|
||||
ui_kit::row(ui, app.tr("prefs.interface_language"), |ui| {
|
||||
ui_kit::settings_control_width(ui, t.form_card_width - t.space_4, |ui| {
|
||||
ui_kit::dropdown_menu(ui, "pref_language", crate::i18n::Locale::for_language(&app.preferences.language).name(), |ui| {
|
||||
ui_kit::dropdown_menu(ui, "pref_language", &crate::i18n::Locale::for_language(&app.preferences.language).display_name(), |ui| {
|
||||
for locale in crate::i18n::LOCALES {
|
||||
if ui_kit::list_picker(ui, locale.id, locale.name, app.preferences.language == locale.id).clicked() {
|
||||
if ui_kit::list_picker(ui, locale.id, &locale.display_name(), app.preferences.language == locale.id).clicked() {
|
||||
app.preferences.language = locale.id.into();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -818,15 +818,23 @@ fn export_as(app: &mut SolveApp, ext: &str, format: Option<&str>) {
|
||||
/// Unicode character boundaries. An oversized word stays on one line with an ellipsis.
|
||||
fn ribbon_button_lines(painter: &egui::Painter, label: &str, width: f32) -> Vec<String> {
|
||||
let mut lines = ribbon_label_lines(painter, label, width);
|
||||
// Right-to-left labels come in display order (see `bidi`): a line reads from its right end,
|
||||
// so a shortened line loses characters on the left, where the ellipsis then goes.
|
||||
let rtl = crate::bidi::has_rtl(label);
|
||||
for line in &mut lines {
|
||||
if ribbon_label_width(painter, line) > width {
|
||||
while !line.is_empty() {
|
||||
line.pop();
|
||||
if ribbon_label_width(painter, &format!("{}…", line.trim_end())) <= width {
|
||||
if rtl {
|
||||
line.remove(0);
|
||||
} else {
|
||||
line.pop();
|
||||
}
|
||||
let shortened = if rtl { format!("…{}", line.trim_start()) } else { format!("{}…", line.trim_end()) };
|
||||
if ribbon_label_width(painter, &shortened) <= width {
|
||||
break;
|
||||
}
|
||||
}
|
||||
*line = format!("{}…", line.trim_end());
|
||||
*line = if rtl { format!("…{}", line.trim_start()) } else { format!("{}…", line.trim_end()) };
|
||||
}
|
||||
}
|
||||
lines
|
||||
@@ -851,6 +859,27 @@ fn ribbon_label_lines(painter: &egui::Painter, label: &str, width: f32) -> Vec<S
|
||||
let measure = |text: &str| ribbon_label_width(painter, text);
|
||||
let normalized = label.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let label = normalized.as_str();
|
||||
if crate::bidi::has_rtl(label) {
|
||||
// Display-order right-to-left text reads from its end: the first line takes the words
|
||||
// at the end of the string, the second line the words before them.
|
||||
let breaks = label.char_indices().filter(|(_, c)| c.is_whitespace() || *c == '/').map(|(at, c)| at + c.len_utf8());
|
||||
let mut start = label.len();
|
||||
for cut in std::iter::once(0).chain(breaks).collect::<Vec<_>>().into_iter().rev() {
|
||||
if cut >= start {
|
||||
continue;
|
||||
}
|
||||
if start < label.len() && measure(label.get(cut..).unwrap_or_default().trim()) > width {
|
||||
break;
|
||||
}
|
||||
start = cut;
|
||||
}
|
||||
let (rest, first) = label.split_at(start);
|
||||
let mut lines = vec![first.trim().to_owned()];
|
||||
if !rest.trim().is_empty() {
|
||||
lines.push(rest.trim().to_owned());
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
let mut end = 0;
|
||||
for token in label.split_inclusive(|c: char| c.is_whitespace() || c == '/') {
|
||||
let next = end + token.len();
|
||||
@@ -3183,6 +3212,25 @@ mod ribbon_label_tests {
|
||||
let galley = ribbon_button_galley(&painter, label, width, Color32::WHITE);
|
||||
assert!(galley.rows.len() <= 2, "{}: {label}", command.id);
|
||||
assert!(galley.size().x <= width + 0.01, "{}: {label}: {} > {width}", command.id, galley.size().x);
|
||||
if crate::bidi::has_rtl(label) {
|
||||
// epaint adds zero-width glyphs to right-to-left rows, so their text
|
||||
// is not the source text: check the lines the galley is built from.
|
||||
let lines = ribbon_button_lines(&painter, label, width);
|
||||
let first = lines[0].strip_prefix('…').unwrap_or(&lines[0]);
|
||||
assert!(label.ends_with(first), "{}: {label} -> {lines:?}", command.id);
|
||||
if let [first, second] = lines.as_slice()
|
||||
&& !first.starts_with('…')
|
||||
&& !second.starts_with('…')
|
||||
{
|
||||
// Both lines whole: they split the label at a space or after a slash.
|
||||
assert!(
|
||||
*label == format!("{second} {first}") || *label == format!("{second}{first}"),
|
||||
"{}: {label} -> {lines:?}",
|
||||
command.id
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let first = galley.rows.first().unwrap().text();
|
||||
let visible = first.strip_suffix('…').unwrap_or(&first);
|
||||
assert!(label.starts_with(visible), "{}: {label} -> {first}", command.id);
|
||||
@@ -3234,6 +3282,15 @@ mod ribbon_label_tests {
|
||||
let lines = ribbon_button_lines(&painter, "長い日本語のラベル 続き", 50.0);
|
||||
assert_eq!(lines.len(), 2);
|
||||
assert!(lines[0].ends_with('…'));
|
||||
// Hebrew comes in display order (`bidi::visual`): the reader starts at the right end,
|
||||
// so "סקיצה חדשה" (New Sketch, stored as "חדשה סקיצה") puts סקיצה on the first line.
|
||||
let label = crate::bidi::visual("סקיצה חדשה").into_owned();
|
||||
let width = ribbon_label_width(&painter, "סקיצה").max(ribbon_label_width(&painter, "חדשה")) + 1.0;
|
||||
assert!(ribbon_label_width(&painter, &label) > width);
|
||||
assert_eq!(ribbon_button_lines(&painter, &label, width), vec!["סקיצה", "חדשה"]);
|
||||
let lines = ribbon_button_lines(&painter, &crate::bidi::visual("אחת שתיים שלוש ארבע חמש"), 50.0);
|
||||
assert_eq!(lines.len(), 2);
|
||||
assert!(lines[1].starts_with('…'), "{lines:?}");
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
+41
-3
@@ -1,6 +1,6 @@
|
||||
# UI localization
|
||||
|
||||
SolidCraft embeds its translations and works offline. English, Czech, Danish, German, English (UK), Spanish, French, Galician, Italian,
|
||||
SolidCraft embeds its translations and works offline. English, Arabic, Czech, Danish, German, English (UK), Spanish, French, Galician, Hebrew, Italian,
|
||||
Japanese, Korean, Malay, Norwegian Bokmål, Dutch, Polish, Brazilian Portuguese, Russian, Turkish, Ukrainian and Chinese are currently registered in `crates/ui-egui/src/i18n.rs`. Adding a language requires an
|
||||
embedded catalog and one registration there; the preferences selector and validation use the same
|
||||
registry.
|
||||
@@ -44,7 +44,7 @@ that looks untranslated. Two guards catch that in the build:
|
||||
|
||||
- `every_complete_catalog_carries_every_english_message` — adding a key to `en.json`
|
||||
without giving it to a complete catalog fails the tests. English is the source catalog,
|
||||
Japanese and Chinese are delivered complete; Danish, German, Spanish, Galician, Italian, Korean, Malay, Norwegian Bokmål, Polish, Brazilian Portuguese, Russian, French, Ukrainian and
|
||||
Arabic, Hebrew, Japanese and Chinese are delivered complete; Danish, German, Spanish, Galician, Italian, Korean, Malay, Norwegian Bokmål, Polish, Brazilian Portuguese, Russian, French, Ukrainian and
|
||||
Turkish are partial — their gaps fall back to English and are reported by `cargo xtask i18n` without
|
||||
failing the build. A new label needs en, ja, zh, de and ko; Russian, French, Ukrainian and Malay may
|
||||
follow later.
|
||||
@@ -114,8 +114,46 @@ preference is kept, so the next visit tries again. The bundled font specifically
|
||||
renders the kanji Chinese shares with Japanese, while Korean (Hangul) and simplified-only Chinese characters
|
||||
are not covered, so a self-hosted SC/Korean font bundle remains follow-up work for full web coverage.
|
||||
|
||||
## Right-to-left text
|
||||
|
||||
egui 0.36 shapes each run of one font with harfrust, so a run of Hebrew letters is drawn right to
|
||||
left, but it has no bidirectional layout: the runs of a line (words, spaces, numbers, punctuation)
|
||||
are placed left to right in the order they are stored. A Hebrew sentence stored in reading order
|
||||
would show its words in the wrong order and its punctuation on the wrong side. `crate::bidi` runs
|
||||
the Unicode Bidirectional Algorithm (the `unicode-bidi` crate, UAX #9) over every message of a
|
||||
catalog that has right-to-left text, once, when the catalog is first used, and `Locale::text`
|
||||
returns the order egui needs: the runs of the line in display order, brackets inside
|
||||
right-to-left text mirrored, and the letters of each Hebrew run left in reading order for the
|
||||
shaper to reverse. Each line is its own paragraph and takes its direction from its first strong
|
||||
letter, so English fallback text is unchanged. `hebrew_messages_land_on_screen_in_display_order`
|
||||
lays messages out with a real Hebrew font and checks where the glyphs land.
|
||||
|
||||
Arabic takes the same path. Its letters join, which the shaper does from the font's own tables, so
|
||||
each Arabic word is one run: the Arabic font comes after the Latin interface font, which keeps the
|
||||
spaces, digits and Latin text, and it is the first fallback for an Arabic UI (Segoe UI, Tahoma or
|
||||
Arial on Windows; SF Arabic, Geeza Pro, Damascus or Tahoma on macOS; Noto Sans or Naskh Arabic,
|
||||
KACST One or DejaVu Sans on Linux; `NotoSansArabic-Regular.ttf` in `CRAFT_FONTS_DIR`). Write Arabic
|
||||
messages with Western digits, which keep their left-to-right order inside the sentence.
|
||||
`arabic_messages_land_on_screen_in_display_order` checks the word order on screen.
|
||||
|
||||
Placeholders are kept whole where they stand, so `format` substitutes values into the
|
||||
display-order text and a value keeps the order it has: a number, a file name, a label that is
|
||||
already in display order. Translators write normal Hebrew in reading order; they never add
|
||||
directional marks. When a prefix letter joins a Latin word or a placeholder, use the maqaf
|
||||
(`ב־{name}`, `ל־STEP`), which is a Hebrew letter to the algorithm, not an ASCII hyphen.
|
||||
|
||||
This relies on Hebrew letters and the spaces and punctuation between them coming from different
|
||||
fonts (the bundled IBM Plex Sans has no Hebrew), which is how the default fonts are set up; an
|
||||
interface font that covers both Hebrew and Latin puts a whole line in one run and can reverse it.
|
||||
What this does not do yet: the layout is not mirrored (the browser stays on the left, labels stay
|
||||
left-aligned), and a message egui wraps onto several lines keeps the order of the whole string, so
|
||||
its lines read bottom to top. Names people type in Hebrew are shown as stored. The desktop host
|
||||
appends a system Hebrew font (Arial Hebrew or SF Hebrew on macOS, Segoe UI or Arial on Windows,
|
||||
Noto Sans Hebrew or DejaVu Sans on Linux); the web build has no Hebrew font yet, so a Hebrew
|
||||
interface shows empty boxes there.
|
||||
|
||||
The current messages support named substitution, not locale-specific plural selection,
|
||||
number/date formatting, or right-to-left layout and shaping. Add those capabilities when
|
||||
number/date formatting, right-to-left layout mirroring, or shaping for joining scripts such as Arabic. Add those capabilities when
|
||||
introducing messages or languages that need them; use an established message formatter for
|
||||
plural rules instead of adding language branches to panels. The catalogs cover the UI surfaces
|
||||
introduced by this PR, not every engine error or every newer command dialog.
|
||||
|
||||
Reference in New Issue
Block a user