From fd1b961e6ef3b35afd366023e5250e84f35656c1 Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Fri, 20 Nov 2026 00:33:54 +0200 Subject: [PATCH 01/13] i18n(he): add Hebrew UI translation catalog, visual RTL reordering, and Hebrew fallback fonts --- crates/ui-egui/build.rs | 47 +++ crates/ui-egui/src/i18n.rs | 657 ++++++++++++++++++++++++++++++++- crates/ui-egui/src/i18n/he.tsv | 267 ++++++++++++++ crates/ui-egui/src/theme.rs | 87 ++++- 4 files changed, 1041 insertions(+), 17 deletions(-) create mode 100644 crates/ui-egui/build.rs create mode 100644 crates/ui-egui/src/i18n/he.tsv diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs new file mode 100644 index 0000000..dc81290 --- /dev/null +++ b/crates/ui-egui/build.rs @@ -0,0 +1,47 @@ +//! Optional build-time discovery of `NotoSansHebrew-Regular.ttf` in `craft-fonts`. +//! Builds without `CRAFT_FONTS_DIR` succeed cleanly and use desktop system font fallbacks. + +use std::path::{Path, PathBuf}; + +fn find_fonts_dir() -> Option { + if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|v| !v.is_empty()) { + let p = PathBuf::from(dir); + if p.is_dir() { + return Some(p); + } + } + let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + for ancestor in manifest.ancestors().skip(1) { + let sibling = ancestor.join("craft-fonts"); + if sibling.is_dir() { + return Some(sibling); + } + if ancestor.file_name().is_some_and(|n| n == "projectcraft") { + if let Some(parent) = ancestor.parent() { + let near = parent.join("craft-fonts"); + if near.is_dir() { + return Some(near); + } + } + break; + } + } + None +} + +fn candidate_hebrew_font(dir: &Path) -> Option { + let p = dir.join("fonts/noto-sans-hebrew/NotoSansHebrew-Regular.ttf"); + p.is_file().then_some(p) +} + +fn main() { + println!("cargo:rustc-check-cfg=cfg(has_hebrew_craft_font)"); + println!("cargo:rerun-if-env-changed=CRAFT_FONTS_DIR"); + if let Some(dir) = find_fonts_dir() + && let Some(font) = candidate_hebrew_font(&dir) + { + println!("cargo:rerun-if-changed={}", font.display()); + println!("cargo:rustc-cfg=has_hebrew_craft_font"); + println!("cargo:rustc-env=HEBREW_CRAFT_FONT_PATH={}", font.display()); + } +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 2ed331d..c8ca750 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -1,15 +1,62 @@ //! Interface text. Every string the interface shows goes through [`t`] (the `tl!` macro), keyed by -//! its English text, so language catalogs can be added without touching the widgets. English is -//! the only language so far; `Pseudo` (a test language) shows which strings skip the lookup. -//! As MailCraft and WordCraft. +//! its English text, so language catalogs work without touching the widgets. Includes English, +//! Hebrew (`he`, right-to-left with visual reordering for egui 0.36), and `Pseudo` (a test language +//! that highlights strings skipping translation). +use std::collections::HashMap; +use std::sync::OnceLock; use std::sync::atomic::{AtomicU8, Ordering}; +const HEBREW_TSV: &str = include_str!("i18n/he.tsv"); + #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] pub enum Lang { - English, + English = 0, /// Accented look-alikes of the English text, for finding strings that skip translation. - Pseudo, + Pseudo = 1, + /// Hebrew (עברית), right-to-left. + Hebrew = 2, +} + +impl Lang { + pub const ALL: [Lang; 3] = [Lang::English, Lang::Pseudo, Lang::Hebrew]; + + /// BCP 47 tag for this UI language. + pub const fn code(self) -> &'static str { + match self { + Lang::English => "en", + Lang::Pseudo => "pseudo", + Lang::Hebrew => "he", + } + } + + /// Display name of the language in itself. + pub const fn name(self) -> &'static str { + match self { + Lang::English => "English", + Lang::Pseudo => "Pseudo", + Lang::Hebrew => "עברית", + } + } + + /// Whether this language reads right-to-left. + pub const fn is_rtl(self) -> bool { + matches!(self, Lang::Hebrew) + } + + /// Resolve a locale or language tag (normalizing legacy `iw` tags to [`Lang::Hebrew`]). + pub fn from_tag(tag: &str) -> Option { + let cleaned = tag.trim().split(['.', '@']).next().unwrap_or_default().replace('_', "-").to_ascii_lowercase(); + let mut parts = cleaned.split('-'); + let primary = parts.next().unwrap_or(""); + match primary { + "en" => Some(Lang::English), + "pseudo" => Some(Lang::Pseudo), + "he" | "iw" => Some(Lang::Hebrew), + _ => None, + } + } } static CURRENT: AtomicU8 = AtomicU8::new(0); @@ -19,21 +66,88 @@ pub fn set_current(lang: Lang) { } pub fn current() -> Lang { - if CURRENT.load(Ordering::Relaxed) == Lang::Pseudo as u8 { Lang::Pseudo } else { Lang::English } + match CURRENT.load(Ordering::Relaxed) { + 1 => Lang::Pseudo, + 2 => Lang::Hebrew, + _ => Lang::English, + } } -/// `s` in the interface language. -pub fn t(s: &str) -> &str { - match current() { +/// Whether `code` names a right-to-left language or ISO 15924 script (normalizing legacy `iw` to +/// `he`, ignoring private-use `x-*` tags, and honoring an explicit script subtag after any +/// 3-letter extlang subtags). +pub fn is_rtl_code(code: &str) -> bool { + let cleaned = code.trim().split(['.', '@']).next().unwrap_or_default().replace('_', "-").to_ascii_lowercase(); + let mut parts = cleaned.split('-').filter(|p| !p.is_empty()); + let Some(base) = parts.next() else { + return false; + }; + if base == "x" { + return false; + } + let next = parts.find(|p| !(p.len() == 3 && p.bytes().all(|b| b.is_ascii_alphabetic()))); + if let Some(script) = next.filter(|p| p.len() == 4 && p.bytes().all(|b| b.is_ascii_alphabetic())) { + return matches!(script, "arab" | "hebr" | "nkoo" | "rohg" | "syrc" | "thaa" | "yezi"); + } + matches!(base, "ar" | "ckb" | "dv" | "fa" | "he" | "iw" | "ps" | "sd" | "ug" | "ur" | "yi") +} + +/// Whether the active interface language uses right-to-left script direction. +pub fn is_rtl() -> bool { + current().is_rtl() +} + +struct HebrewCatalog { + en_to_visual: HashMap<&'static str, &'static str>, + visual_to_logical: HashMap<&'static str, &'static str>, +} + +fn hebrew_catalog() -> &'static HebrewCatalog { + static CATALOG: OnceLock = OnceLock::new(); + CATALOG.get_or_init(|| { + let mut en_to_visual = HashMap::new(); + let mut visual_to_logical = HashMap::new(); + for line in HEBREW_TSV.lines() { + if line.trim().is_empty() || line.starts_with('#') { + continue; + } + let Some((key, logical)) = line.split_once('\t') else { + continue; + }; + if key.is_empty() || logical.trim().is_empty() { + continue; + } + let visual_str = visual_rtl(logical); + let visual: &'static str = if visual_str == logical { + logical + } else { + // Static catalog entries are small and fixed for the lifetime of the process. + Box::leak(visual_str.into_boxed_str()) + }; + en_to_visual.insert(key, visual); + visual_to_logical.insert(visual, logical); + } + HebrewCatalog { en_to_visual, visual_to_logical } + }) +} + +/// `s` in `lang` (in visual RTL order for egui 0.36 when [`Lang::Hebrew`] is passed). +pub fn t_for(lang: Lang, s: &str) -> &str { + match lang { Lang::English => s, Lang::Pseudo => pseudo(s), + Lang::Hebrew => hebrew_catalog().en_to_visual.get(s).copied().unwrap_or(s), } } +/// `s` in the interface language (in visual RTL order for egui 0.36 when Hebrew is active). +pub fn t(s: &str) -> &str { + t_for(current(), s) +} + /// The pseudo-language form of `s`, interned so it can be handed out as `&'static str`. fn pseudo(s: &str) -> &'static str { - use std::collections::HashMap; - use std::sync::{Mutex, OnceLock}; + use std::sync::Mutex; static CACHE: OnceLock>> = OnceLock::new(); let mut cache = CACHE.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner()); if let Some(done) = cache.get(s) { @@ -72,23 +186,536 @@ fn pseudo(s: &str) -> &'static str { leaked } -/// Fill `{name}` placeholders in a (translated) template. +/// Fill `{name}` placeholders in `template` for `lang`. When [`Lang::Hebrew`] is selected, +/// recovers the logical template before substituting so inserted values reorder cleanly for egui 0.36. +pub fn fmt_for(lang: Lang, template: &str, args: &[(&str, &str)]) -> String { + let source = if lang == Lang::Hebrew { hebrew_catalog().visual_to_logical.get(template).copied().unwrap_or(template) } else { template }; + let out = fill_placeholders(source, args); + if lang == Lang::Hebrew { visual_rtl(&out) } else { out } +} + +/// Fill `{name}` placeholders in a (translated) template in one pass. When Hebrew is active, +/// recovers the logical template before substituting so inserted values (including Hebrew task or +/// resource names) reorder consistently for egui 0.36 display. pub fn fmt(template: &str, args: &[(&str, &str)]) -> String { - let mut out = template.to_string(); - for (k, v) in args { - out = out.replace(&format!("{{{k}}}"), v); + fmt_for(current(), template, args) +} + +fn fill_placeholders(template: &str, args: &[(&str, &str)]) -> String { + let mut out = String::with_capacity(template.len()); + let mut rest = template; + while let Some(open) = rest.find('{') { + out.push_str(rest.get(..open).unwrap_or_default()); + let after_open = rest.get(open + 1..).unwrap_or_default(); + let Some(close) = after_open.find('}') else { + out.push_str(rest.get(open..).unwrap_or_default()); + return out; + }; + let key = after_open.get(..close).unwrap_or_default(); + if let Some((_, val)) = args.iter().find(|(k, _)| *k == key) { + out.push_str(val); + } else { + out.push('{'); + out.push_str(key); + out.push('}'); + } + rest = after_open.get(close + 1..).unwrap_or_default(); + } + out.push_str(rest); + out +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum BidiClass { + L, + R, + En, + N, +} + +fn is_rtl_script(c: char) -> bool { + matches!( + u32::from(c), + 0x0590..=0x05FF | 0x0600..=0x065F | 0x066E..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFC | 0x1_0800..=0x1_0FFF | 0x1_E800..=0x1_EFFF + ) +} + +fn is_bidi_digit(c: char) -> bool { + c.is_ascii_digit() || matches!(u32::from(c), 0x0660..=0x0669 | 0x06F0..=0x06F9) +} + +fn is_bidi_control(c: char) -> bool { + matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') +} + +fn is_joiner(c: char) -> bool { + matches!(c, '\u{200C}' | '\u{200D}') +} + +fn mirrored(c: char) -> char { + match c { + '(' => ')', + ')' => '(', + '[' => ']', + ']' => '[', + '{' => '}', + '}' => '{', + '<' => '>', + '>' => '<', + '«' => '»', + '»' => '«', + other => other, + } +} + +fn bracket_close(open: char) -> Option { + match open { + '(' => Some(')'), + '[' => Some(']'), + '{' => Some('}'), + '<' => Some('>'), + '«' => Some('»'), + _ => None, + } +} + +fn is_closing_bracket(c: char) -> bool { + matches!(c, ')' | ']' | '}' | '>' | '»') +} + +const PLACEHOLDER_BASE: u32 = 0xE000; +const MAX_PLACEHOLDERS: usize = 64; + +fn mask_placeholders(text: &str) -> (String, Vec<&str>) { + let reserved = text.chars().any(|c| (PLACEHOLDER_BASE..PLACEHOLDER_BASE.saturating_add(MAX_PLACEHOLDERS as u32)).contains(&u32::from(c))); + if reserved { + return (text.to_owned(), Vec::new()); + } + let mut masked = String::with_capacity(text.len()); + let mut names = Vec::new(); + let mut rest = text; + while names.len() < MAX_PLACEHOLDERS + && let Some(start) = rest.find('{') + && let Some(len) = rest.get(start..).and_then(|s| s.find('}')) + { + let end = start.saturating_add(len).saturating_add(1); + let (Some(before), Some(atom), Some(after)) = (rest.get(..start), rest.get(start..end), rest.get(end..)) else { + break; + }; + let Some(stand_in) = u32::try_from(names.len()).ok().and_then(|i| char::from_u32(PLACEHOLDER_BASE.saturating_add(i))) else { + break; + }; + masked.push_str(before); + masked.push(stand_in); + names.push(atom); + rest = after; + } + masked.push_str(rest); + (masked, names) +} + +fn push_unmasked(out: &mut String, c: char, names: &[&str]) { + let idx = u32::from(c).checked_sub(PLACEHOLDER_BASE).and_then(|i| usize::try_from(i).ok()); + if let Some(name) = idx.and_then(|i| names.get(i)) { + out.push_str(name); + } else { + out.push(c); + } +} + +fn push_visual_rtl_line(line: &str, out: &mut String) { + let (masked, names) = mask_placeholders(line); + let chars: Vec = masked.chars().filter(|c| !is_bidi_control(*c)).collect(); + if chars.is_empty() { + return; + } + let len = chars.len(); + let mut cls: Vec = chars + .iter() + .map(|&c| { + let is_placeholder = (PLACEHOLDER_BASE..PLACEHOLDER_BASE.saturating_add(MAX_PLACEHOLDERS as u32)).contains(&u32::from(c)); + if is_rtl_script(c) { + BidiClass::R + } else if is_bidi_digit(c) { + BidiClass::En + } else if is_placeholder || c.is_alphabetic() || matches!(c, '\u{2318}' | '\u{21E7}' | '\u{2325}' | '\u{2303}') { + BidiClass::L + } else { + BidiClass::N + } + }) + .collect(); + + for i in 1..len.saturating_sub(1) { + if cls.get(i) == Some(&BidiClass::N) + && chars.get(i).is_some_and(|c| matches!(c, '.' | ',' | ':' | '/' | '-' | '+' | '_')) + && let (Some(prev), Some(next)) = (cls.get(i - 1), cls.get(i + 1)) + { + if *prev == BidiClass::En && *next == BidiClass::En { + if let Some(slot) = cls.get_mut(i) { + *slot = BidiClass::En; + } + } else if matches!(prev, BidiClass::L | BidiClass::En) + && matches!(next, BidiClass::L | BidiClass::En) + && let Some(slot) = cls.get_mut(i) + { + *slot = BidiClass::L; + } + } + } + + for i in 0..len { + let Some(&ch) = chars.get(i) else { continue }; + if cls.get(i) != Some(&BidiClass::N) { + continue; + } + let next_en = cls.get(i + 1) == Some(&BidiClass::En); + let prev_en = i > 0 && cls.get(i - 1) == Some(&BidiClass::En); + let prev_is_r = i > 0 && cls.get(i - 1) == Some(&BidiClass::R); + let attach = match ch { + '%' | '°' | '$' | '€' | '£' | '₪' => prev_en || next_en, + '+' | '-' => next_en && !prev_is_r, + _ => false, + }; + if attach && let Some(slot) = cls.get_mut(i) { + *slot = BidiClass::En; + } + } + + let mut stack: Vec<(usize, char)> = Vec::new(); + let mut pairs: Vec<(usize, usize)> = Vec::new(); + for (i, &c) in chars.iter().enumerate() { + if cls.get(i) != Some(&BidiClass::N) { + continue; + } + if let Some(close) = bracket_close(c) { + if stack.len() < 63 { + stack.push((i, close)); + } + } else if is_closing_bracket(c) + && let Some(pos) = stack.iter().rposition(|(_, expected)| *expected == c) + { + let (open_idx, _) = stack.remove(pos); + pairs.push((open_idx, i)); + } + } + pairs.sort_by_key(|(open, _)| *open); + for (open, close) in pairs { + let inner = cls.get(open + 1..close).unwrap_or(&[]); + let has_r = inner.contains(&BidiClass::R); + let has_l = inner.iter().any(|c| matches!(c, BidiClass::L | BidiClass::En)); + let dir = if has_r { + BidiClass::R + } else if has_l { + let prev_strong = cls.get(..open).unwrap_or(&[]).iter().rev().find(|c| **c != BidiClass::N).copied(); + if matches!(prev_strong, Some(BidiClass::L | BidiClass::En)) { BidiClass::L } else { BidiClass::R } + } else { + BidiClass::R + }; + if let Some(s) = cls.get_mut(open) { + *s = dir; + } + if let Some(s) = cls.get_mut(close) { + *s = dir; + } + } + + for c in &mut cls { + if *c == BidiClass::En { + *c = BidiClass::L; + } + } + let mut i = 0; + while i < len { + if cls.get(i) == Some(&BidiClass::N) { + let start = i; + while cls.get(i) == Some(&BidiClass::N) { + i += 1; + } + let left_l = start > 0 && cls.get(start - 1) == Some(&BidiClass::L); + let right_l = cls.get(i) == Some(&BidiClass::L); + let resolved = if left_l && right_l { BidiClass::L } else { BidiClass::R }; + if let Some(slice) = cls.get_mut(start..i) { + slice.fill(resolved); + } + } else { + i += 1; + } + } + + let mut runs: Vec<(bool, usize, usize)> = Vec::new(); + let mut r_start = 0; + while r_start < len { + let rtl = cls.get(r_start) == Some(&BidiClass::R); + let mut r_end = r_start + 1; + while cls.get(r_end).is_some_and(|c| (*c == BidiClass::R) == rtl) { + r_end += 1; + } + runs.push((rtl, r_start, r_end)); + r_start = r_end; + } + + for (rtl, start, end) in runs.into_iter().rev() { + let Some(slice) = chars.get(start..end) else { continue }; + if rtl { + let mut stretch: Vec = Vec::new(); + for &c in slice.iter().rev() { + if is_rtl_script(c) || is_joiner(c) { + stretch.push(c); + } else { + for sc in stretch.drain(..).rev() { + push_unmasked(out, sc, &names); + } + push_unmasked(out, mirrored(c), &names); + } + } + for sc in stretch.drain(..).rev() { + push_unmasked(out, sc, &names); + } + } else { + for &c in slice { + push_unmasked(out, c, &names); + } + } + } +} + +/// Rearrange `text` into visual right-to-left order for egui 0.36 while keeping contiguous RTL +/// script stretches in logical order so epaint's harfrust shapes them cleanly. +fn visual_rtl(text: &str) -> String { + if !text.chars().any(is_rtl_script) { + return text.to_owned(); + } + let mut out = String::with_capacity(text.len()); + for (idx, raw_line) in text.split('\n').enumerate() { + if idx > 0 { + out.push('\n'); + } + let (line, cr) = raw_line.strip_suffix('\r').map_or((raw_line, false), |l| (l, true)); + push_visual_rtl_line(line, &mut out); + if cr { + out.push('\r'); + } } out } #[cfg(test)] mod tests { + use std::collections::{BTreeSet, HashMap}; + use super::*; + fn placeholders(s: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = s; + while let Some(open) = rest.find('{') { + let after = &rest[open + 1..]; + let Some(close) = after.find('}') else { break }; + out.push(after[..close].to_owned()); + rest = &after[close + 1..]; + } + out.sort(); + out + } + + fn parsed_hebrew_rows() -> HashMap { + let mut map = HashMap::new(); + for (idx, line) in HEBREW_TSV.lines().enumerate() { + if line.trim().is_empty() || line.starts_with('#') { + continue; + } + let (k, v) = line.split_once('\t').unwrap_or_else(|| panic!("he.tsv:{}: missing tab", idx + 1)); + assert!(!k.is_empty() && !v.trim().is_empty(), "he.tsv:{}: empty column", idx + 1); + assert!(!v.contains('\t'), "he.tsv:{}: extra tab", idx + 1); + assert!(map.insert(k.to_owned(), v.to_owned()).is_none(), "he.tsv:{}: duplicate key {k:?}", idx + 1); + } + map + } + #[test] fn formatting_and_pseudo() { assert_eq!(fmt("Start {start} · Finish {finish}", &[("start", "Mon"), ("finish", "Fri")]), "Start Mon · Finish Fri"); assert_eq!(pseudo("Task {name}"), "Tásk {name}"); assert_eq!(t("Undo"), "Undo"); } + + #[test] + fn locale_tags_and_rtl_detection_handle_hebrew_and_legacy_iw() { + assert_eq!(Lang::from_tag("en"), Some(Lang::English)); + assert_eq!(Lang::from_tag("en-US"), Some(Lang::English)); + assert_eq!(Lang::from_tag("he"), Some(Lang::Hebrew)); + assert_eq!(Lang::from_tag("he-IL"), Some(Lang::Hebrew)); + assert_eq!(Lang::from_tag("iw"), Some(Lang::Hebrew)); + assert_eq!(Lang::from_tag("iw_IL.UTF-8"), Some(Lang::Hebrew)); + assert_eq!(Lang::from_tag("xx"), None); + + assert!(is_rtl_code("he")); + assert!(is_rtl_code("he-Hebr-IL")); + assert!(is_rtl_code("he-u-nu-latn")); + assert!(is_rtl_code("iw-IL")); + assert!(is_rtl_code("ku-Arab-IQ")); + assert!(!is_rtl_code("ku")); + assert!(!is_rtl_code("ku-Latn-TR")); + assert!(!is_rtl_code("en-x-hebr")); + assert!(!is_rtl_code("x-Arab")); + assert!(!is_rtl_code("x-Hebr")); + assert!(!is_rtl_code("en")); + + assert_eq!(Lang::Hebrew.code(), "he"); + assert_eq!(Lang::Hebrew.name(), "עברית"); + assert!(Lang::Hebrew.is_rtl()); + assert!(!Lang::English.is_rtl()); + } + + #[test] + fn hebrew_catalog_covers_every_ui_string_and_keeps_placeholders() { + let catalog = parsed_hebrew_rows(); + let src_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut required = BTreeSet::new(); + for entry in std::fs::read_dir(&src_dir).unwrap() { + let path = entry.unwrap().path(); + if path.extension().and_then(|e| e.to_str()) != Some("rs") { + continue; + } + let text = std::fs::read_to_string(&path).unwrap(); + let mut rest = text.as_str(); + while let Some(at) = rest.find("tl!(\"") { + rest = &rest[at + 5..]; + let mut lit = String::new(); + let mut chars = rest.chars(); + let mut esc = false; + for ch in &mut chars { + if esc { + match ch { + 'n' => lit.push('\n'), + 'r' => lit.push('\r'), + 't' => lit.push('\t'), + other => lit.push(other), + } + esc = false; + } else if ch == '\\' { + esc = true; + } else if ch == '"' { + break; + } else { + lit.push(ch); + } + } + required.insert(lit); + rest = chars.as_str(); + } + } + // Dynamic table keys routed through `tl!` in ui-egui. + for dynamic in [ + // `lib.rs` COLUMNS, View menu, and `DAY_NAMES`, plus engine `WEEKDAYS` + "Task Name", + "Duration", + "Work", + "Start", + "Finish", + "Predecessors", + "Resource Names", + "Cost", + "Fixed Cost", + "Deadline", + "Type", + "Effort Driven", + "Priority", + "Leveling Delay", + "Gantt Chart", + "Resource Sheet", + "Resource Usage", + "Mon", + "Tue", + "Wed", + "Thu", + "Fri", + "Sat", + "Sun", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday", + // `timescale.rs` MONTHS and Preset::label + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + "Days", + "Weeks", + "Months", + // `assign.rs` headers & `resource_sheet.rs` COLUMNS / lowercased type names + "Resource Name", + "Units", + "Material", + "Initials", + "Group", + "Max. Units", + "Std. Rate", + "Ovt. Rate", + "Cost/Use", + "Accrue At", + "work", + "material", + "cost", + // `options.rs` ROWS labels and units + "Hours per day", + "hours", + "Hours per week", + "Days per month", + "days", + "Currency", + "ISO code", + "Currency symbol", + "Decimal places", + "in amounts", + // Model enum display strings: ResourceType, AccrueAt, TaskType, UnitsFormat, Yes/No, Outcome + "End", + "Prorated", + "Fixed Units", + "Fixed Duration", + "Fixed Work", + "Percentage", + "Decimal", + "Yes", + "No", + "Converted", + "Dropped", + "Not yet imported", + "Dates differ", + ] { + required.insert(dynamic.to_owned()); + } + let missing: Vec<_> = required.iter().filter(|k| !catalog.contains_key(k.as_str())).collect(); + assert!(missing.is_empty(), "missing Hebrew translations in he.tsv: {missing:?}"); + for (k, v) in &catalog { + assert_eq!(placeholders(k), placeholders(v), "placeholders differ for {k:?}"); + assert_eq!(k.ends_with('…'), v.ends_with('…'), "ellipsis mismatch for {k:?}"); + } + } + + #[test] + fn hebrew_translations_and_fmt_reorder_for_rtl() { + assert_eq!(t_for(Lang::Hebrew, "Save"), "שמירה"); + assert_eq!(t_for(Lang::Hebrew, "New Task"), "חדשה משימה"); + assert_eq!(t_for(Lang::Hebrew, "Assign Resources…"), "…משאבים הקצאת"); + assert_eq!(fmt_for(Lang::Hebrew, t_for(Lang::Hebrew, "Task: {name}"), &[("name", "Alpha")]), "Alpha :משימה"); + assert_eq!(fmt_for(Lang::Hebrew, t_for(Lang::Hebrew, "Task: {name}"), &[("name", "בדיקה ראשונה")]), "ראשונה בדיקה :משימה"); + assert_eq!(visual_rtl("פרויקט ProjectCraft (100%)"), "ProjectCraft (100%) פרויקט"); + assert_eq!(visual_rtl("שמור (Ctrl+O)"), "(Ctrl+O) שמור"); + assert_eq!(visual_rtl("הכול הושלם (100%)"), "(100%) הושלם הכול"); + assert_eq!(t_for(Lang::Hebrew, ""), ""); + } } diff --git a/crates/ui-egui/src/i18n/he.tsv b/crates/ui-egui/src/i18n/he.tsv new file mode 100644 index 0000000..31eee6a --- /dev/null +++ b/crates/ui-egui/src/i18n/he.tsv @@ -0,0 +1,267 @@ +# he: Hebrew UI translations (עברית). Licensed MIT OR Apache-2.0. +# UTF-8: English sourcetranslation. Keep {placeholders} and ellipsis intact. +/hr (לשעה) +A summary task is scheduled as Fixed Duration and is never effort-driven משימת סיכום מתוזמנת כמשך קבוע ואינה מונחית-מאמץ לעולם +A summary task's duration is rolled up from its subtasks משך של משימת סיכום מסוכם מתוך תת-המשימות שלה +Accrue At זקיפה ב +Add Exception הוספת חריגה +Add Times הוספת שעות +Added {name} to the Resource Sheet as a work resource (100% Max Units). {name} נוסף לגיליון המשאבים כמשאב עבודה (100% יחידות מרביות). +Added {names} to the Resource Sheet as work resources (100% Max Units). {names} נוספו לגיליון המשאבים כמשאבי עבודה (100% יחידות מרביות). +Always shown מוצג תמיד +Apply החלה +Apr אפר׳ +Assign הקצאה +Assign Resources הקצאת משאבים +Assign Resources… הקצאת משאבים… +Assign resources to the selected tasks (Alt+F10) הקצאת משאבים למשימות שנבחרו (Alt+F10) +Assigned to {count} of the {total} selected tasks מוקצה ל-{count} מתוך {total} משימות שנבחרו +Assignment units יחידות הקצאה +Aug אוג׳ +Autosave שמירה אוטומטית +Autosaved {path} נשמר אוטומטית: {path} +Based on the project calendar: only what differs is its own. מבוסס על לוח הפרויקט: רק מה ששונה הוא שלו. +Blank: the default hours ריק: שעות ברירת המחדל +CSV (*.csv): a copy; the project stays as it is CSV (*.csv): עותק; הפרויקט נשאר כפי שהוא +Can't schedule: {error} לא ניתן לתזמן: {error} +Cancel ביטול +Change Resource Type שינוי סוג משאב +Change Type שינוי סוג +Change Working Time שינוי זמן עבודה +Change Working Time… שינוי זמן עבודה… +Clear Leveling ניקוי איזון +Close סגירה +Columns עמודות +Columns… עמודות… +Constraint conflict: a link can't be honoured, so this task keeps its constraint date and has negative slack. התנגשות אילוצים: לא ניתן לכבד קישור, ולכן משימה זו שומרת על תאריך האילוץ ויש לה מרווח שלילי. +Converted הומר +Converting durations between hours, days, weeks and months; the currency of every amount; how units show המרת משכים בין שעות, ימים, שבועות וחודשים; המטבע של כל סכום; אופן הצגת היחידות +Copy Report העתקת דוח +Copy the report as text העתקת הדוח כטקסט +Cost עלות +Cost/Use עלות לשימוש +Couldn't autosave: {error} שמירה אוטומטית נכשלה: {error} +Couldn't delete the recovery copy: {error} מחיקת עותק השחזור נכשלה: {error} +Couldn't export: {error} הייצוא נכשל: {error} +Couldn't export: {path} is the project's own file לא ניתן לייצא: {path} הוא הקובץ של הפרויקט עצמו +Couldn't import: {error} הייבוא נכשל: {error} +Couldn't open: {error} הפתיחה נכשלה: {error} +Couldn't remove a temporary file left by an unfinished save לא ניתן להסיר קובץ זמני שנותר משמירה שלא הסתיימה +Couldn't restore: {error} השחזור נכשל: {error} +Couldn't save: {error} השמירה נכשלה: {error} +Couldn't save: {path} is a Microsoft Project XML or CSV name; ProjectCraft saves .projectcraft files לא ניתן לשמור: {path} הוא שם מסוג Microsoft Project XML או CSV; ProjectCraft שומר קובצי .projectcraft +Couldn't write the recovery copy: {error} כתיבת עותק השחזור נכשלה: {error} +Currency מטבע +Currency must be a three-letter ISO code, such as GBP, EUR or USD. המטבע חייב להיות קוד ISO בן שלוש אותיות, כגון GBP, EUR או USD. +Currency symbol סמל מטבע +Date תאריך +Dates differ תאריכים שונים +Days ימים +Days per month ימים בחודש +Days per month must be a whole number from 1 to 31. מספר הימים בחודש חייב להיות מספר שלם בין 1 ל-31. +Deadline תאריך יעד +Dec דצמ׳ +Decimal עשרוני +Decimal places ספרות עשרוניות +Decimal places must be a whole number from 0 to 4. מספר הספרות העשרוניות חייב להיות מספר שלם בין 0 ל-4. +Default task type סוג משימה כברירת מחדל +Delay tasks until no resource is overallocated, day by day דחיית משימות עד שאף משאב אינו בעומס יתר, יום אחר יום +Delete מחיקה +Delete Resource מחיקת משאב +Delete these working times מחיקת זמני עבודה אלה +Discard ביטול השינויים +Do you want to save the changes you made to {name}? האם לשמור את השינויים שביצעת ב-{name}? +Doesn't apply to a {type} resource אינו חל על משאב מסוג {type} +Don't Save אל תשמור +Dropped הושמט +Duration משך +Each working time must end after it starts. כל טווח עבודה חייב להסתיים לאחר שהוא מתחיל. +Effort Driven מונחה מאמץ +End סיום +Enter times as H:MM, such as 8:00 or 17:30. הזן שעות בתבנית H:MM, כגון 8:00 או 17:30. +Everything in the file was imported. הכול בקובץ יובא בהצלחה. +Exception hours שעות חריגה +Exceptions חריגות +Export ייצוא +Export as {format} ייצוא בתור {format} +Exported a copy as {format}: {path} יוצא עותק בתור {format}: {path} +Feature תכונה +Feb פבר׳ +File קובץ +File name: שם קובץ: +Finish סיום +Fixed Cost עלות קבועה +Fixed Duration משך קבוע +Fixed Units יחידות קבועות +Fixed Work עבודה קבועה +Fixed Work tasks are always effort driven משימות מסוג עבודה קבועה הן תמיד מונחות מאמץ +Fixed cost עלות קבועה +For calendar עבור לוח שנה +Fri ו׳ +Friday יום שישי +From מ- +Gantt Chart תרשים גאנט +Group קבוצה +Half time shows as 0.5, full time as 1. Typing 50% still works. חצי משרה מוצגת כ-0.5, משרה מלאה כ-1. הקלדת 50% עדיין עובדת. +Half time shows as 50%, full time as 100%. חצי משרה מוצגת כ-50%, משרה מלאה כ-100%. +Home בית +Home folder תיקיית הבית +Hours per day שעות ביום +Hours per day must be 1 to 24, in whole minutes (such as 7.5). מספר השעות ביום חייב להיות בין 1 ל-24, בדקות שלמות (כגון 7.5). +Hours per week שעות בשבוע +Hours per week must be 1 to 168, in whole minutes (such as 37.5). מספר השעות בשבוע חייב להיות בין 1 ל-168, בדקות שלמות (כגון 37.5). +ID מזהה +ISO code קוד ISO +Import Report דוח ייבוא +Imported {path} as a new project; Save keeps it as a ProjectCraft project {path} יובא כפרויקט חדש; שמירה תשמור אותו כפרויקט ProjectCraft +Initials ראשי תיבות +Jan ינו׳ +Jul יול׳ +Jun יונ׳ +Level All איזון הכול +Leveling Delay עיכוב איזון +Levelling delays a summary task's subtasks, never the summary איזון מעכב את תת-המשימות של משימת הסיכום, לעולם לא את הסיכום עצמו +Mar מרץ +Material חומר +Max. Units יחידות מרביות +May מאי +Microsoft Project XML (*.xml): a copy; the project stays as it is Microsoft Project XML (*.xml): עותק; הפרויקט נשאר כפי שהוא +Missed deadline: this task finishes after its deadline, so it has negative slack. תאריך יעד הוחמץ: משימה זו מסתיימת לאחר תאריך היעד שלה, ולכן יש לה מרווח שלילי. +Mon ב׳ +Monday יום שני +Months חודשים +New Resource משאב חדש +New Task משימה חדשה +New tasks משימות חדשות +New tasks are effort driven משימות חדשות מונחות מאמץ +No לא +No costs ללא עלויות +No folders or projects here. אין תיקיות או פרויקטים כאן. +No resources assigned אין משאבים מוקצים +No resources yet. Add them in the Resource Sheet, or type a name in the Resource Names column. עדיין אין משאבים. הוסף אותם בגיליון המשאבים, או הקלד שם בעמודת שמות המשאבים. +No resources yet. Add them in the Resource Sheet. עדיין אין משאבים. הוסף אותם בגיליון המשאבים. +No resources yet. Press Insert or New Resource to add one. עדיין אין משאבים. לחץ Insert או על משאב חדש כדי להוסיף. +Non-working יום חופשי +Non-working: add working times to work this day. לא עובדים: הוסף שעות עבודה כדי לעבוד ביום זה. +None: every day follows its weekday. ללא: כל יום פועל לפי יום השבוע שלו. +Not yet imported טרם יובא +Nov נוב׳ +Oct אוק׳ +Open פתיחה +Open Recent פתיחת קובץ אחרון +Opened {path} נפתח: {path} +Open… פתיחה… +Options… אפשרויות… +Overallocated: a resource on this task has more work than its Max Units allow on a day it works on it. עומס יתר: למשאב במשימה זו יש יותר עבודה מהמותר לפי היחידות המרביות שלו ביום עבודה עליה. +Overallocated: more work on some days than Max Units allow on this resource's calendar (see Resource Usage) עומס יתר: בימים מסוימים יש יותר עבודה מהמותר לפי היחידות המרביות בלוח המשאב (ראה שימוש במשאבים) +Overallocated: red days have more work than Max Units allow on this resource's calendar עומס יתר: בימים אדומים יש יותר עבודה מהמותר לפי היחידות המרביות בלוח המשאב +Ovt. Rate תעריף שעות נוספות +Parts of the file converted, dropped or not imported yet, and tasks whose dates differ from the file's: חלקים בקובץ שהומרו, הושמטו או טרם יובאו, ומשימות שתאריכיהן שונים מהקובץ: +Percentage אחוזים +Predecessors פעילויות קודמות +Priority עדיפות +Project פרויקט +Project Options אפשרויות פרויקט +Project calendar לוח הפרויקט +ProjectCraft closed before changes to {name} were saved. A recovery copy of them was kept. ProjectCraft נסגרה לפני ששינויים ב-{name} נשמרו. נשמר עותק שחזור שלהם. +ProjectCraft projects (*.projectcraft) פרויקטים של ProjectCraft (*.projectcraft) +ProjectCraft projects (*.projectcraft), and Microsoft Project XML (*.xml) and CSV (*.csv), imported as a new project פרויקטים של ProjectCraft (*.projectcraft), וכן Microsoft Project XML (*.xml) ו-CSV (*.csv), המיובאים כפרויקט חדש +Prorated יחסי +Recover unsaved changes? לשחזר שינויים שלא נשמרו? +Redo ביצוע חוזר +Remove הסרה +Resource משאב +Resource Name שם משאב +Resource Names שמות משאבים +Resource Sheet גיליון משאבים +Resource Usage שימוש במשאבים +Restore שחזור +Restore opens them as unsaved changes. Discard deletes the recovery copy. שחזור יפתח אותם כשינויים שלא נשמרו. ביטול השינויים ימחק את עותק השחזור. +Restored unsaved changes שוחזרו שינויים שלא נשמרו +Result תוצאה +Sat ש׳ +Saturday יום שבת +Save שמירה +Save As שמירה בשם +Save As… שמירה בשם… +Save changes? לשמור שינויים? +Save the file every 2 minutes while it has unsaved changes שמירת הקובץ כל 2 דקות כשיש שינויים שלא נשמרו +Saved {path} נשמר: {path} +Select a task to assign resources to. בחר משימה כדי להקצות לה משאבים. +Sep ספט׳ +Show All הצג הכול +Show assignment units as a הצג יחידות הקצאה בתור +Show or hide the task sheet's columns הצג או הסתר את עמודות גיליון המשימות +Showing the first {count} items. מציג את {count} הפריטים הראשונים. +Standard rate: {rate} תעריף רגיל: {rate} +Start התחלה +Start {start} · Finish {finish} · Cost {cost} התחלה {start} · סיום {finish} · עלות {cost} +Std. Rate תעריף רגיל +Subtasks תת-משימות +Sun א׳ +Sunday יום ראשון +Take away every levelling delay הסרת כל עיכובי האיזון +Task Name שם משימה +Task: {name} משימה: {name} +The project calendar's exceptions apply too, except on a day with one of its own. חריגות לוח הפרויקט חלות אף הן, למעט ביום שבו יש חריגה משלו. +The system file dialog isn't available, so ProjectCraft shows its own. To get the system dialog, install a file chooser portal (such as xdg-desktop-portal-gtk) or zenity. חלונית הקבצים של המערכת אינה זמינה, ולכן ProjectCraft מציגה חלונית משלה. כדי לקבל את חלונית המערכת, התקן שער בחירת קבצים (כגון xdg-desktop-portal-gtk) או zenity. +The task sheet's columns; saved with the project עמודות גיליון המשימות; נשמר עם הפרויקט +The {n} resources selected are assigned to {count} task(s). Deleting them removes those assignments. {n} המשאבים שנבחרו מוקצים ל-{count} משימות. מחיקתם תסיר הקצאות אלה. +This folder can't be read: {error} לא ניתן לקרוא תיקייה זו: {error} +This weekday follows the project calendar again יום שבוע זה חוזר לפעול לפי לוח הפרויקט +Thu ה׳ +Thursday יום חמישי +Timescale ציר זמן +To עד +Total סה״כ +Tue ג׳ +Tuesday יום שלישי +Type סוג +Type Fixed Units, Fixed Duration or Fixed Work. הקלד יחידות קבועות, משך קבוע או עבודה קבועה (או Fixed Units / Fixed Duration / Fixed Work). +Type Yes or No. הקלד כן או לא (Yes / No). +Type a priority from 0 to 1000. הקלד עדיפות בין 0 ל-1000. +Undo ביטול +Units יחידות +Units and work shown are for {name}. היחידות והעבודה המוצגות הן עבור {name}. +Units: a decimal for people and equipment (0.5, or 50%); for materials a quantity (5 tons) or a rate (2 tons/d). יחידות: מספר עשרוני לאנשים ולציוד (0.5 או 50%); לחומרים כמות (5 tons) או קצב (2 tons/d). +Units: a percentage for people and equipment (50%); for materials a quantity (5 tons) or a rate (2 tons/d). יחידות: אחוזים לאנשים ולציוד (50%); לחומרים כמות (5 tons) או קצב (2 tons/d). +Units: the share of each resource's working time (0.5 is half its day; 50% works too). יחידות: החלק מזמן העבודה של כל משאב (0.5 הוא חצי יום; גם 50% עובד). +Units: the share of each resource's working time (50% is half its day). יחידות: החלק מזמן העבודה של כל משאב (50% הוא חצי יום). +Untitled ללא שם +Up למעלה +Up one level רמה אחת למעלה +Use Project Times שימוש בשעות הפרויקט +View תצוגה +Wed ד׳ +Wednesday יום רביעי +Weeks שבועות +Where מיקום +Why סיבה +Work עבודה +Working יום עבודה +Working days ימי עבודה +Working times for זמני עבודה עבור +Working times must be in order and must not overlap. זמני העבודה חייבים להיות לפי הסדר וללא חפיפה. +Write a copy for another program; the project stays as it is כתיבת עותק לתוכנה אחרת; הפרויקט נשאר כפי שהוא +YYYY-MM-DD YYYY-MM-DD +Yes כן +You can undo this. ניתן לבטל פעולה זו. +Zoom In הגדלת תצוגה +Zoom Out הקטנת תצוגה +as the project calendar כמו בלוח הפרויקט +cost עלות +days ימים +hours שעות +in amounts בסכומים +its own שלו עצמו +material חומר +work עבודה +{count} tasks selected: Assign and Remove act on all of them. נבחרו {count} משימות: הקצאה והסרה חלות על כולן. +{file}: {tasks} tasks imported as a new, untitled project. ProjectCraft worked out every date; none were taken from the file. {file}: {tasks} משימות יובאו כפרויקט חדש וללא שם. ProjectCraft חישבה כל תאריך; אף תאריך לא נלקח מהקובץ. +{format}… {format}… +{name} - ProjectCraft {name} - ProjectCraft +{name} already exists. Choose Save again to replace it. {name} כבר קיים. בחר שמירה שוב כדי להחליף אותו. +{name} is assigned to {count} task(s). Deleting it removes those assignments. {name} מוקצה ל-{count} משימות. מחיקתו תסיר הקצאות אלה. +{name} is assigned to {count} task(s). Making it a {type} resource removes those assignments. {name} מוקצה ל-{count} משימות. הפיכתו למשאב מסוג {type} תסיר הקצאות אלה. +{name} wasn't found. {name} לא נמצא. +{names}: no working weekday on their own calendar, so scheduled on the project calendar {names}: אין יום עבודה בשבוע בלוח שלהם, ולכן תוזמנו לפי לוח הפרויקט diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index b636907..57ca2ac 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -116,9 +116,11 @@ impl Tokens { } } -/// Put both palettes into egui (ours as its light and its dark style) and pick the theme: -/// `System` follows the OS (or browser) appearance, `Light` and `Dark` pin it. +/// Put both palettes into egui (ours as its light and its dark style), install a Hebrew +/// fallback font if not yet registered on `ctx`, and pick the theme: `System` follows the OS (or +/// browser) appearance, `Light` and `Dark` pin it. pub fn apply(ctx: &egui::Context, preference: egui::ThemePreference) { + install_hebrew_fonts(ctx); ctx.set_visuals_of(egui::Theme::Light, visuals(&Tokens::light())); ctx.set_visuals_of(egui::Theme::Dark, visuals(&Tokens::dark())); ctx.all_styles_mut(|s| { @@ -133,6 +135,65 @@ pub fn apply(ctx: &egui::Context, preference: egui::ThemePreference) { }); } +fn hebrew_font_data() -> Option { + #[cfg(has_hebrew_craft_font)] + { + Some(egui::FontData::from_static(include_bytes!(env!("HEBREW_CRAFT_FONT_PATH")))) + } + #[cfg(not(has_hebrew_craft_font))] + { + #[cfg(not(target_arch = "wasm32"))] + { + #[cfg(target_os = "macos")] + const CANDIDATES: &[&str] = &[ + "/System/Library/Fonts/SFHebrew.ttf", + "/System/Library/Fonts/Supplemental/Arial.ttf", + "/System/Library/Fonts/Supplemental/Arial Unicode.ttf", + "/Library/Fonts/Arial Unicode.ttf", + ]; + #[cfg(all(unix, not(target_os = "macos")))] + const CANDIDATES: &[&str] = &[ + "/usr/share/fonts/truetype/noto/NotoSansHebrew-Regular.ttf", + "/usr/share/fonts/noto/NotoSansHebrew-Regular.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/truetype/freefont/FreeSans.ttf", + ]; + #[cfg(windows)] + const CANDIDATES: &[&str] = &[r"C:\Windows\Fonts\arial.ttf", r"C:\Windows\Fonts\segoeui.ttf", r"C:\Windows\Fonts\tahoma.ttf"]; + #[cfg(not(any(unix, windows)))] + const CANDIDATES: &[&str] = &[]; + + for path in CANDIDATES { + if let Ok(bytes) = std::fs::read(path) { + return Some(egui::FontData::from_owned(bytes)); + } + } + } + None + } +} + +fn install_hebrew_fonts(ctx: &egui::Context) { + let key = egui::Id::new("projectcraft_hebrew_fonts_installed"); + if ctx.data(|d| d.get_temp::(key)) == Some(true) { + return; + } + ctx.data_mut(|d| d.insert_temp(key, true)); + let Some(font_data) = hebrew_font_data() else { + return; + }; + let mut fonts = egui::FontDefinitions::default(); + fonts.font_data.insert("hebrew_fallback".to_owned(), std::sync::Arc::new(font_data)); + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + if let Some(list) = fonts.families.get_mut(&family) { + list.push("hebrew_fallback".to_owned()); + } + } + ctx.set_fonts(fonts); +} + /// egui's visuals for one of our palettes. fn visuals(t: &Tokens) -> Visuals { let mut v = if t.dark { Visuals::dark() } else { Visuals::light() }; @@ -175,3 +236,25 @@ fn visuals(t: &Tokens) -> Visuals { fn shadow(t: &Tokens, light: u8, dark: u8) -> Color32 { Color32::from_black_alpha(if t.dark { dark } else { light }) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hebrew_fallback_font_supplies_hebrew_glyphs_when_available() { + let ctx = egui::Context::default(); + apply(&ctx, egui::ThemePreference::Light); + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + if hebrew_font_data().is_some() { + ctx.fonts_mut(|fonts| { + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + let font = egui::FontId::new(14.0, family); + for ch in "אבגדהוזחטיכלמנסעפצקרשתךםןףץ".chars() { + assert!(fonts.has_glyph(&font, ch), "missing Hebrew glyph {ch} in {font:?}"); + } + } + }); + } + } +} From 74c60282161b4a3dd529d449ddbdb930abfc785b Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Fri, 20 Nov 2026 04:27:18 +0200 Subject: [PATCH 02/13] fix(i18n,build): watch font dir, absolutize font path, attach path separators, and wrap RTL per row --- crates/ui-egui/build.rs | 26 ++++++++--- crates/ui-egui/src/assign.rs | 2 +- crates/ui-egui/src/browser.rs | 11 +++-- crates/ui-egui/src/i18n.rs | 84 +++++++++++++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 6 ++- crates/ui-egui/src/options.rs | 11 +++-- crates/ui-egui/src/recovery.rs | 7 +-- 7 files changed, 123 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index dc81290..9baa98b 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -34,14 +34,28 @@ fn candidate_hebrew_font(dir: &Path) -> Option { p.is_file().then_some(p) } +fn absolutize(path: PathBuf) -> PathBuf { + if path.is_absolute() { + return path; + } + path.canonicalize().unwrap_or_else(|_| std::env::current_dir().map_or_else(|_| path.clone(), |cwd| cwd.join(&path))) +} + fn main() { println!("cargo:rustc-check-cfg=cfg(has_hebrew_craft_font)"); println!("cargo:rerun-if-env-changed=CRAFT_FONTS_DIR"); - if let Some(dir) = find_fonts_dir() - && let Some(font) = candidate_hebrew_font(&dir) - { - println!("cargo:rerun-if-changed={}", font.display()); - println!("cargo:rustc-cfg=has_hebrew_craft_font"); - println!("cargo:rustc-env=HEBREW_CRAFT_FONT_PATH={}", font.display()); + if let Some(dir) = find_fonts_dir() { + let dir = absolutize(dir); + println!("cargo:rerun-if-changed={}", dir.display()); + let font_dir = dir.join("fonts/noto-sans-hebrew"); + if font_dir.is_dir() { + println!("cargo:rerun-if-changed={}", font_dir.display()); + } + if let Some(font) = candidate_hebrew_font(&dir) { + let font = absolutize(font); + println!("cargo:rerun-if-changed={}", font.display()); + println!("cargo:rustc-cfg=has_hebrew_craft_font"); + println!("cargo:rustc-env=HEBREW_CRAFT_FONT_PATH={}", font.display()); + } } } diff --git a/crates/ui-egui/src/assign.rs b/crates/ui-egui/src/assign.rs index f6b7bb5..d7b0527 100644 --- a/crates/ui-egui/src/assign.rs +++ b/crates/ui-egui/src/assign.rs @@ -279,7 +279,7 @@ impl App { (false, false) => tl!("Units: the share of each resource's working time (50% is half its day)."), (false, true) => tl!("Units: the share of each resource's working time (0.5 is half its day; 50% works too)."), }; - ui.label(RichText::new(hint).color(t.text_dim)); + crate::i18n::wrapped_label(ui, hint, |r| r.color(t.text_dim)); if !error.is_empty() { ui.add_space(6.0); ui.label(RichText::new(error.as_str()).color(t.warning)); diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 3a51d9d..5a0e0af 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -289,11 +289,12 @@ fn body(ui: &mut Ui, b: &mut FileBrowser, t: &Tokens) -> Option> FileRequest::Export(f) => i18n::fmt(tl!("Export as {format}"), &[("format", f.name())]), }); if b.unavailable { - ui.label( - RichText::new(tl!( + crate::i18n::wrapped_label( + ui, + tl!( "The system file dialog isn't available, so ProjectCraft shows its own. To get the system dialog, install a file chooser portal (such as xdg-desktop-portal-gtk) or zenity." - )) - .color(t.text_dim), + ), + |r| r.color(t.text_dim), ); } ui.add_space(6.0); @@ -398,7 +399,7 @@ fn body(ui: &mut Ui, b: &mut FileBrowser, t: &Tokens) -> Option> FileRequest::Export(Format::Mspdi) => tl!("Microsoft Project XML (*.xml): a copy; the project stays as it is"), FileRequest::Export(Format::Csv) => tl!("CSV (*.csv): a copy; the project stays as it is"), }; - ui.label(RichText::new(kinds).color(t.text_dim)); + crate::i18n::wrapped_label(ui, kinds, |r| r.color(t.text_dim)); ui.add_space(8.0); let mut cancel = ui.input(|i| i.key_pressed(egui::Key::Escape)); let enter = !location_done && ui.input(|i| i.key_pressed(egui::Key::Enter)); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index c8ca750..61fc629 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -131,6 +131,43 @@ fn hebrew_catalog() -> &'static HebrewCatalog { }) } +/// Recover the logical string for a catalog entry when `s` was visually reordered for RTL. +pub fn logical_of(s: &str) -> &str { + if is_rtl() { hebrew_catalog().visual_to_logical.get(s).copied().unwrap_or(s) } else { s } +} + +/// Break `logical` text at `max_width` first, then apply visual RTL ordering to each display row. +pub fn wrapped_visual_lines(ctx: &egui::Context, lang: Lang, logical: &str, font_id: egui::FontId, max_width: f32) -> String { + if !lang.is_rtl() || !logical.chars().any(is_rtl_script) { + return logical.to_owned(); + } + let galley = ctx.fonts_mut(|f| f.layout(logical.to_owned(), font_id, Default::default(), max_width.max(1.0))); + let mut out = String::with_capacity(logical.len()); + for (idx, placed) in galley.rows.iter().enumerate() { + if idx > 0 { + out.push('\n'); + } + let row_text = placed.text(); + push_visual_rtl_line(row_text.trim_end_matches(' '), &mut out); + } + out +} + +/// Render a wrapping label, deferring RTL visual reordering until after egui determines line breaks. +pub fn wrapped_label(ui: &mut egui::Ui, text: &str, style: impl FnOnce(egui::RichText) -> egui::RichText) -> egui::Response { + let font_id = egui::TextStyle::Body.resolve(ui.style()); + let lang = current(); + let rtl = lang.is_rtl(); + let shown = if rtl { + let logical = logical_of(text); + wrapped_visual_lines(ui.ctx(), lang, logical, font_id.clone(), ui.available_width()) + } else { + text.to_owned() + }; + let rich = style(egui::RichText::new(shown).font(font_id)); + if rtl { ui.add(egui::Label::new(rich).extend()) } else { ui.add(egui::Label::new(rich).wrap()) } +} + /// `s` in `lang` (in visual RTL order for egui 0.36 when [`Lang::Hebrew`] is passed). pub fn t_for(lang: Lang, s: &str) -> &str { match lang { @@ -186,11 +223,22 @@ fn pseudo(s: &str) -> &'static str { leaked } +/// Fill `{name}` placeholders in `template` for `lang`, keeping logical text order (for +/// row-aware wrapping in [`wrapped_label`]). +pub fn fmt_logical_for(lang: Lang, template: &str, args: &[(&str, &str)]) -> String { + let source = if lang == Lang::Hebrew { hebrew_catalog().visual_to_logical.get(template).copied().unwrap_or(template) } else { template }; + fill_placeholders(source, args) +} + +/// Fill `{name}` placeholders in a (translated) template in one pass, keeping logical text order. +pub fn fmt_logical(template: &str, args: &[(&str, &str)]) -> String { + fmt_logical_for(current(), template, args) +} + /// Fill `{name}` placeholders in `template` for `lang`. When [`Lang::Hebrew`] is selected, /// recovers the logical template before substituting so inserted values reorder cleanly for egui 0.36. pub fn fmt_for(lang: Lang, template: &str, args: &[(&str, &str)]) -> String { - let source = if lang == Lang::Hebrew { hebrew_catalog().visual_to_logical.get(template).copied().unwrap_or(template) } else { template }; - let out = fill_placeholders(source, args); + let out = fmt_logical_for(lang, template, args); if lang == Lang::Hebrew { visual_rtl(&out) } else { out } } @@ -382,6 +430,18 @@ fn push_visual_rtl_line(line: &str, out: &mut String) { } } + // Keep leading path/dot prefixes (e.g. `/tmp/...`, `.env`) attached to following LTR/numeric runs. + for i in (0..len.saturating_sub(1)).rev() { + if cls.get(i) == Some(&BidiClass::N) + && chars.get(i).is_some_and(|c| matches!(c, '/' | '.' | '~' | '\\')) + && matches!(cls.get(i + 1), Some(BidiClass::L | BidiClass::En)) + && (i == 0 || cls.get(i - 1) != Some(&BidiClass::R)) + && let Some(slot) = cls.get_mut(i) + { + *slot = BidiClass::L; + } + } + let mut stack: Vec<(usize, char)> = Vec::new(); let mut pairs: Vec<(usize, usize)> = Vec::new(); for (i, &c) in chars.iter().enumerate() { @@ -713,9 +773,29 @@ mod tests { assert_eq!(t_for(Lang::Hebrew, "Assign Resources…"), "…משאבים הקצאת"); assert_eq!(fmt_for(Lang::Hebrew, t_for(Lang::Hebrew, "Task: {name}"), &[("name", "Alpha")]), "Alpha :משימה"); assert_eq!(fmt_for(Lang::Hebrew, t_for(Lang::Hebrew, "Task: {name}"), &[("name", "בדיקה ראשונה")]), "ראשונה בדיקה :משימה"); + assert_eq!( + fmt_for(Lang::Hebrew, t_for(Lang::Hebrew, "Opened {path}"), &[("path", "/tmp/demo.projectcraft")]), + "/tmp/demo.projectcraft :נפתח" + ); + assert_eq!(fmt_for(Lang::Hebrew, t_for(Lang::Hebrew, "Opened {path}"), &[("path", ".env")]), ".env :נפתח"); assert_eq!(visual_rtl("פרויקט ProjectCraft (100%)"), "ProjectCraft (100%) פרויקט"); assert_eq!(visual_rtl("שמור (Ctrl+O)"), "(Ctrl+O) שמור"); assert_eq!(visual_rtl("הכול הושלם (100%)"), "(100%) הושלם הכול"); assert_eq!(t_for(Lang::Hebrew, ""), ""); } + + #[test] + fn hebrew_wrapping_reorders_after_line_breaks() { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, egui::ThemePreference::Light); + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + let logical = "המרת משכים בין שעות, ימים, שבועות וחודשים; המטבע של כל סכום; אופן הצגת היחידות"; + let font = egui::FontId::proportional(14.0); + let wrapped = wrapped_visual_lines(&ctx, Lang::Hebrew, logical, font, 160.0); + let lines: Vec<&str> = wrapped.lines().collect(); + assert!(lines.len() >= 2, "expected wrapped lines, got {wrapped:?}"); + assert!(lines[0].contains("המרת"), "first wrapped row should begin with opening words: {lines:?}"); + assert!(!lines[0].contains("היחידות"), "first wrapped row should not start with paragraph end: {lines:?}"); + assert!(lines.last().unwrap().contains("היחידות"), "last wrapped row should contain closing words: {lines:?}"); + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c06b648..3ffe7a2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -988,7 +988,7 @@ impl App { .labelled_by(label.id); }); if form.resource.is_some() { - ui.label(RichText::new(tl!("Based on the project calendar: only what differs is its own.")).color(t.text_dim)); + i18n::wrapped_label(ui, tl!("Based on the project calendar: only what differs is its own."), |r| r.color(t.text_dim)); } ui.add_space(10.0); @@ -1061,7 +1061,9 @@ impl App { // A resource lists its own; the project calendar's apply to it too. Only the rows in // view are drawn. if own.is_some() { - ui.label(RichText::new(tl!("The project calendar's exceptions apply too, except on a day with one of its own.")).color(t.text_dim)); + i18n::wrapped_label(ui, tl!("The project calendar's exceptions apply too, except on a day with one of its own."), |r| { + r.color(t.text_dim) + }); } let count = own.map_or(base.exceptions.len(), |c| c.exceptions.len()); if count == 0 { diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index 2c13e51..c7959b2 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.rs @@ -152,9 +152,10 @@ impl App { let modal = egui::Modal::new(egui::Id::new("project_options")).show(ctx, |ui| { ui.set_width(400.0); ui.heading(tl!("Project Options")); - ui.label( - RichText::new(tl!("Converting durations between hours, days, weeks and months; the currency of every amount; how units show")) - .color(t.text_dim), + crate::i18n::wrapped_label( + ui, + tl!("Converting durations between hours, days, weeks and months; the currency of every amount; how units show"), + |r| r.color(t.text_dim), ); ui.add_space(10.0); egui::Grid::new("project_options_rows").num_columns(3).spacing([12.0, 6.0]).show(ui, |ui| { @@ -209,10 +210,10 @@ impl App { UnitsFormat::Percentage => tl!("Half time shows as 50%, full time as 100%."), UnitsFormat::Decimal => tl!("Half time shows as 0.5, full time as 1. Typing 50% still works."), }; - ui.label(RichText::new(example).color(t.text_dim)); + crate::i18n::wrapped_label(ui, example, |r| r.color(t.text_dim)); if !error.is_empty() { ui.add_space(6.0); - ui.label(RichText::new(error.as_str()).color(t.warning)); + crate::i18n::wrapped_label(ui, error.as_str(), |r| r.color(t.warning)); } ui.add_space(10.0); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { diff --git a/crates/ui-egui/src/recovery.rs b/crates/ui-egui/src/recovery.rs index 8cee3c6..436ee65 100644 --- a/crates/ui-egui/src/recovery.rs +++ b/crates/ui-egui/src/recovery.rs @@ -224,11 +224,12 @@ impl App { egui::Modal::new(egui::Id::new("recovery-copy")).show(ctx, |ui| { ui.set_max_width(420.0); ui.heading(tl!("Recover unsaved changes?")); - ui.label(i18n::fmt( + let notice = i18n::fmt_logical( tl!("ProjectCraft closed before changes to {name} were saved. A recovery copy of them was kept."), &[("name", &name)], - )); - ui.label(tl!("Restore opens them as unsaved changes. Discard deletes the recovery copy.")); + ); + i18n::wrapped_label(ui, ¬ice, |r| r); + i18n::wrapped_label(ui, tl!("Restore opens them as unsaved changes. Discard deletes the recovery copy."), |r| r); ui.add_space(8.0); ui.horizontal(|ui| { if ui.button(tl!("Restore")).clicked() { From f1d5604c9118b255cba6ced009dd3b6af4efb210 Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Fri, 20 Nov 2026 06:54:32 +0200 Subject: [PATCH 03/13] i18n(he): wrap RTL lines from logical substrings and keep .wrap() for LTR text --- crates/ui-egui/src/i18n.rs | 102 ++++++++++++++++++++++++++++++------- 1 file changed, 84 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 61fc629..eb6ea7f 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -136,36 +136,86 @@ pub fn logical_of(s: &str) -> &str { if is_rtl() { hebrew_catalog().visual_to_logical.get(s).copied().unwrap_or(s) } else { s } } -/// Break `logical` text at `max_width` first, then apply visual RTL ordering to each display row. +fn wrap_paragraph_logical<'a>(ctx: &egui::Context, paragraph: &'a str, font_id: &egui::FontId, max_width: f32) -> Vec<&'a str> { + if paragraph.is_empty() || !max_width.is_finite() { + return vec![paragraph]; + } + let max_w = max_width.max(1.0); + let mut spans: Vec<(usize, usize)> = Vec::new(); + let mut in_word = false; + let mut word_start = 0usize; + for (idx, ch) in paragraph.char_indices() { + if ch.is_whitespace() { + if in_word { + spans.push((word_start, idx)); + in_word = false; + } + } else if !in_word { + word_start = idx; + in_word = true; + } + } + if in_word { + spans.push((word_start, paragraph.len())); + } + let Some(&(mut line_start, mut line_end)) = spans.first() else { + return vec![paragraph]; + }; + let mut rows = Vec::new(); + for &(span_start, span_end) in spans.iter().skip(1) { + let candidate = ¶graph[line_start..span_end]; + let width = ctx.fonts_mut(|f| f.layout_no_wrap(candidate.to_owned(), font_id.clone(), Default::default()).rect.width()); + if width <= max_w { + line_end = span_end; + } else { + rows.push(¶graph[line_start..line_end]); + line_start = span_start; + line_end = span_end; + } + } + rows.push(¶graph[line_start..line_end]); + rows +} + +/// Break `logical` text at `max_width` first using original logical substrings, then apply visual +/// RTL ordering to each display row containing RTL characters. pub fn wrapped_visual_lines(ctx: &egui::Context, lang: Lang, logical: &str, font_id: egui::FontId, max_width: f32) -> String { if !lang.is_rtl() || !logical.chars().any(is_rtl_script) { return logical.to_owned(); } - let galley = ctx.fonts_mut(|f| f.layout(logical.to_owned(), font_id, Default::default(), max_width.max(1.0))); let mut out = String::with_capacity(logical.len()); - for (idx, placed) in galley.rows.iter().enumerate() { - if idx > 0 { - out.push('\n'); + let mut first_row = true; + for paragraph in logical.split('\n') { + for row_logical in wrap_paragraph_logical(ctx, paragraph, &font_id, max_width) { + if !first_row { + out.push('\n'); + } + first_row = false; + if row_logical.chars().any(is_rtl_script) { + push_visual_rtl_line(row_logical, &mut out); + } else { + out.push_str(row_logical); + } } - let row_text = placed.text(); - push_visual_rtl_line(row_text.trim_end_matches(' '), &mut out); } out } -/// Render a wrapping label, deferring RTL visual reordering until after egui determines line breaks. -pub fn wrapped_label(ui: &mut egui::Ui, text: &str, style: impl FnOnce(egui::RichText) -> egui::RichText) -> egui::Response { +/// Render a wrapping label for an explicit `lang`, deferring RTL visual reordering until after +/// egui determines line breaks. +pub fn wrapped_label_for(ui: &mut egui::Ui, lang: Lang, text: &str, style: impl FnOnce(egui::RichText) -> egui::RichText) -> egui::Response { let font_id = egui::TextStyle::Body.resolve(ui.style()); - let lang = current(); - let rtl = lang.is_rtl(); - let shown = if rtl { - let logical = logical_of(text); - wrapped_visual_lines(ui.ctx(), lang, logical, font_id.clone(), ui.available_width()) - } else { - text.to_owned() - }; + let logical = if lang.is_rtl() { logical_of(text) } else { text }; + let needs_rtl_wrap = lang.is_rtl() && logical.chars().any(is_rtl_script); + let shown = + if needs_rtl_wrap { wrapped_visual_lines(ui.ctx(), lang, logical, font_id.clone(), ui.available_width()) } else { logical.to_owned() }; let rich = style(egui::RichText::new(shown).font(font_id)); - if rtl { ui.add(egui::Label::new(rich).extend()) } else { ui.add(egui::Label::new(rich).wrap()) } + if needs_rtl_wrap { ui.add(egui::Label::new(rich).extend()) } else { ui.add(egui::Label::new(rich).wrap()) } +} + +/// Render a wrapping label, deferring RTL visual reordering until after egui determines line breaks. +pub fn wrapped_label(ui: &mut egui::Ui, text: &str, style: impl FnOnce(egui::RichText) -> egui::RichText) -> egui::Response { + wrapped_label_for(ui, current(), text, style) } /// `s` in `lang` (in visual RTL order for egui 0.36 when [`Lang::Hebrew`] is passed). @@ -795,7 +845,23 @@ mod tests { let lines: Vec<&str> = wrapped.lines().collect(); assert!(lines.len() >= 2, "expected wrapped lines, got {wrapped:?}"); assert!(lines[0].contains("המרת"), "first wrapped row should begin with opening words: {lines:?}"); + assert!(!lines[0].contains("תרמה"), "characters inside Hebrew words must remain logical: {lines:?}"); assert!(!lines[0].contains("היחידות"), "first wrapped row should not start with paragraph end: {lines:?}"); assert!(lines.last().unwrap().contains("היחידות"), "last wrapped row should contain closing words: {lines:?}"); + assert!(!lines.last().unwrap().contains("תודיחיה"), "closing word letters must remain logical: {lines:?}"); + + let english_long = "This is a long English-only fallback diagnostic message that should still wrap."; + let mut english_resp_width = 0.0f32; + ctx.run_ui(egui::RawInput::default(), |ui| { + egui::CentralPanel::default().show(ui, |ui| { + ui.allocate_ui(egui::vec2(140.0, 200.0), |ui| { + let resp = wrapped_label_for(ui, Lang::Hebrew, english_long, |r| r); + english_resp_width = resp.rect.width(); + }); + }); + }) + .textures_delta + .clear(); + assert!(english_resp_width <= 150.0, "English fallback in Hebrew mode must still wrap, got width {english_resp_width}"); } } From 97bfdefc751b6d891f418edc7f5e18484b3c461d Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Fri, 20 Nov 2026 22:40:12 +0200 Subject: [PATCH 04/13] i18n(he): extract BiDi module and warn when CRAFT_FONTS_DIR is invalid --- crates/ui-egui/build.rs | 6 +- crates/ui-egui/src/i18n.rs | 290 +------------------------------ crates/ui-egui/src/i18n/bidi.rs | 299 ++++++++++++++++++++++++++++++++ 3 files changed, 307 insertions(+), 288 deletions(-) create mode 100644 crates/ui-egui/src/i18n/bidi.rs diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 9baa98b..2a22b0a 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -5,10 +5,14 @@ use std::path::{Path, PathBuf}; fn find_fonts_dir() -> Option { if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|v| !v.is_empty()) { - let p = PathBuf::from(dir); + let p = PathBuf::from(&dir); if p.is_dir() { return Some(p); } + println!( + "cargo:warning=CRAFT_FONTS_DIR points to a missing directory ({}); falling back to sibling craft-fonts or system fonts", + p.display() + ); } let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR")); for ancestor in manifest.ancestors().skip(1) { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index eb6ea7f..bb558c1 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -7,6 +7,9 @@ use std::collections::HashMap; use std::sync::OnceLock; use std::sync::atomic::{AtomicU8, Ordering}; +mod bidi; +use bidi::{is_rtl_script, push_visual_rtl_line, visual_rtl}; + const HEBREW_TSV: &str = include_str!("i18n/he.tsv"); #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -323,293 +326,6 @@ fn fill_placeholders(template: &str, args: &[(&str, &str)]) -> String { out } -#[derive(Clone, Copy, PartialEq, Eq)] -enum BidiClass { - L, - R, - En, - N, -} - -fn is_rtl_script(c: char) -> bool { - matches!( - u32::from(c), - 0x0590..=0x05FF | 0x0600..=0x065F | 0x066E..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFC | 0x1_0800..=0x1_0FFF | 0x1_E800..=0x1_EFFF - ) -} - -fn is_bidi_digit(c: char) -> bool { - c.is_ascii_digit() || matches!(u32::from(c), 0x0660..=0x0669 | 0x06F0..=0x06F9) -} - -fn is_bidi_control(c: char) -> bool { - matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') -} - -fn is_joiner(c: char) -> bool { - matches!(c, '\u{200C}' | '\u{200D}') -} - -fn mirrored(c: char) -> char { - match c { - '(' => ')', - ')' => '(', - '[' => ']', - ']' => '[', - '{' => '}', - '}' => '{', - '<' => '>', - '>' => '<', - '«' => '»', - '»' => '«', - other => other, - } -} - -fn bracket_close(open: char) -> Option { - match open { - '(' => Some(')'), - '[' => Some(']'), - '{' => Some('}'), - '<' => Some('>'), - '«' => Some('»'), - _ => None, - } -} - -fn is_closing_bracket(c: char) -> bool { - matches!(c, ')' | ']' | '}' | '>' | '»') -} - -const PLACEHOLDER_BASE: u32 = 0xE000; -const MAX_PLACEHOLDERS: usize = 64; - -fn mask_placeholders(text: &str) -> (String, Vec<&str>) { - let reserved = text.chars().any(|c| (PLACEHOLDER_BASE..PLACEHOLDER_BASE.saturating_add(MAX_PLACEHOLDERS as u32)).contains(&u32::from(c))); - if reserved { - return (text.to_owned(), Vec::new()); - } - let mut masked = String::with_capacity(text.len()); - let mut names = Vec::new(); - let mut rest = text; - while names.len() < MAX_PLACEHOLDERS - && let Some(start) = rest.find('{') - && let Some(len) = rest.get(start..).and_then(|s| s.find('}')) - { - let end = start.saturating_add(len).saturating_add(1); - let (Some(before), Some(atom), Some(after)) = (rest.get(..start), rest.get(start..end), rest.get(end..)) else { - break; - }; - let Some(stand_in) = u32::try_from(names.len()).ok().and_then(|i| char::from_u32(PLACEHOLDER_BASE.saturating_add(i))) else { - break; - }; - masked.push_str(before); - masked.push(stand_in); - names.push(atom); - rest = after; - } - masked.push_str(rest); - (masked, names) -} - -fn push_unmasked(out: &mut String, c: char, names: &[&str]) { - let idx = u32::from(c).checked_sub(PLACEHOLDER_BASE).and_then(|i| usize::try_from(i).ok()); - if let Some(name) = idx.and_then(|i| names.get(i)) { - out.push_str(name); - } else { - out.push(c); - } -} - -fn push_visual_rtl_line(line: &str, out: &mut String) { - let (masked, names) = mask_placeholders(line); - let chars: Vec = masked.chars().filter(|c| !is_bidi_control(*c)).collect(); - if chars.is_empty() { - return; - } - let len = chars.len(); - let mut cls: Vec = chars - .iter() - .map(|&c| { - let is_placeholder = (PLACEHOLDER_BASE..PLACEHOLDER_BASE.saturating_add(MAX_PLACEHOLDERS as u32)).contains(&u32::from(c)); - if is_rtl_script(c) { - BidiClass::R - } else if is_bidi_digit(c) { - BidiClass::En - } else if is_placeholder || c.is_alphabetic() || matches!(c, '\u{2318}' | '\u{21E7}' | '\u{2325}' | '\u{2303}') { - BidiClass::L - } else { - BidiClass::N - } - }) - .collect(); - - for i in 1..len.saturating_sub(1) { - if cls.get(i) == Some(&BidiClass::N) - && chars.get(i).is_some_and(|c| matches!(c, '.' | ',' | ':' | '/' | '-' | '+' | '_')) - && let (Some(prev), Some(next)) = (cls.get(i - 1), cls.get(i + 1)) - { - if *prev == BidiClass::En && *next == BidiClass::En { - if let Some(slot) = cls.get_mut(i) { - *slot = BidiClass::En; - } - } else if matches!(prev, BidiClass::L | BidiClass::En) - && matches!(next, BidiClass::L | BidiClass::En) - && let Some(slot) = cls.get_mut(i) - { - *slot = BidiClass::L; - } - } - } - - for i in 0..len { - let Some(&ch) = chars.get(i) else { continue }; - if cls.get(i) != Some(&BidiClass::N) { - continue; - } - let next_en = cls.get(i + 1) == Some(&BidiClass::En); - let prev_en = i > 0 && cls.get(i - 1) == Some(&BidiClass::En); - let prev_is_r = i > 0 && cls.get(i - 1) == Some(&BidiClass::R); - let attach = match ch { - '%' | '°' | '$' | '€' | '£' | '₪' => prev_en || next_en, - '+' | '-' => next_en && !prev_is_r, - _ => false, - }; - if attach && let Some(slot) = cls.get_mut(i) { - *slot = BidiClass::En; - } - } - - // Keep leading path/dot prefixes (e.g. `/tmp/...`, `.env`) attached to following LTR/numeric runs. - for i in (0..len.saturating_sub(1)).rev() { - if cls.get(i) == Some(&BidiClass::N) - && chars.get(i).is_some_and(|c| matches!(c, '/' | '.' | '~' | '\\')) - && matches!(cls.get(i + 1), Some(BidiClass::L | BidiClass::En)) - && (i == 0 || cls.get(i - 1) != Some(&BidiClass::R)) - && let Some(slot) = cls.get_mut(i) - { - *slot = BidiClass::L; - } - } - - let mut stack: Vec<(usize, char)> = Vec::new(); - let mut pairs: Vec<(usize, usize)> = Vec::new(); - for (i, &c) in chars.iter().enumerate() { - if cls.get(i) != Some(&BidiClass::N) { - continue; - } - if let Some(close) = bracket_close(c) { - if stack.len() < 63 { - stack.push((i, close)); - } - } else if is_closing_bracket(c) - && let Some(pos) = stack.iter().rposition(|(_, expected)| *expected == c) - { - let (open_idx, _) = stack.remove(pos); - pairs.push((open_idx, i)); - } - } - pairs.sort_by_key(|(open, _)| *open); - for (open, close) in pairs { - let inner = cls.get(open + 1..close).unwrap_or(&[]); - let has_r = inner.contains(&BidiClass::R); - let has_l = inner.iter().any(|c| matches!(c, BidiClass::L | BidiClass::En)); - let dir = if has_r { - BidiClass::R - } else if has_l { - let prev_strong = cls.get(..open).unwrap_or(&[]).iter().rev().find(|c| **c != BidiClass::N).copied(); - if matches!(prev_strong, Some(BidiClass::L | BidiClass::En)) { BidiClass::L } else { BidiClass::R } - } else { - BidiClass::R - }; - if let Some(s) = cls.get_mut(open) { - *s = dir; - } - if let Some(s) = cls.get_mut(close) { - *s = dir; - } - } - - for c in &mut cls { - if *c == BidiClass::En { - *c = BidiClass::L; - } - } - let mut i = 0; - while i < len { - if cls.get(i) == Some(&BidiClass::N) { - let start = i; - while cls.get(i) == Some(&BidiClass::N) { - i += 1; - } - let left_l = start > 0 && cls.get(start - 1) == Some(&BidiClass::L); - let right_l = cls.get(i) == Some(&BidiClass::L); - let resolved = if left_l && right_l { BidiClass::L } else { BidiClass::R }; - if let Some(slice) = cls.get_mut(start..i) { - slice.fill(resolved); - } - } else { - i += 1; - } - } - - let mut runs: Vec<(bool, usize, usize)> = Vec::new(); - let mut r_start = 0; - while r_start < len { - let rtl = cls.get(r_start) == Some(&BidiClass::R); - let mut r_end = r_start + 1; - while cls.get(r_end).is_some_and(|c| (*c == BidiClass::R) == rtl) { - r_end += 1; - } - runs.push((rtl, r_start, r_end)); - r_start = r_end; - } - - for (rtl, start, end) in runs.into_iter().rev() { - let Some(slice) = chars.get(start..end) else { continue }; - if rtl { - let mut stretch: Vec = Vec::new(); - for &c in slice.iter().rev() { - if is_rtl_script(c) || is_joiner(c) { - stretch.push(c); - } else { - for sc in stretch.drain(..).rev() { - push_unmasked(out, sc, &names); - } - push_unmasked(out, mirrored(c), &names); - } - } - for sc in stretch.drain(..).rev() { - push_unmasked(out, sc, &names); - } - } else { - for &c in slice { - push_unmasked(out, c, &names); - } - } - } -} - -/// Rearrange `text` into visual right-to-left order for egui 0.36 while keeping contiguous RTL -/// script stretches in logical order so epaint's harfrust shapes them cleanly. -fn visual_rtl(text: &str) -> String { - if !text.chars().any(is_rtl_script) { - return text.to_owned(); - } - let mut out = String::with_capacity(text.len()); - for (idx, raw_line) in text.split('\n').enumerate() { - if idx > 0 { - out.push('\n'); - } - let (line, cr) = raw_line.strip_suffix('\r').map_or((raw_line, false), |l| (l, true)); - push_visual_rtl_line(line, &mut out); - if cr { - out.push('\r'); - } - } - out -} - #[cfg(test)] mod tests { use std::collections::{BTreeSet, HashMap}; diff --git a/crates/ui-egui/src/i18n/bidi.rs b/crates/ui-egui/src/i18n/bidi.rs new file mode 100644 index 0000000..d07a8cc --- /dev/null +++ b/crates/ui-egui/src/i18n/bidi.rs @@ -0,0 +1,299 @@ +//! Visual RTL BiDi reordering for `egui 0.36`, which renders strings in literal glyph order +//! without UAX #9 paragraph reordering. +//! +//! Assumptions and scope: +//! - Contiguous RTL script stretches (Hebrew, Arabic, Syriac, Thaana, N'Ko, Adlam) remain in +//! logical order internally so `epaint`/`harfrust` shapes each word cleanly. +//! - Runs are ordered visually right-to-left per line, keeping numbers, ASCII/Latin words, +//! path prefixes (`/tmp/...`, `.env`), currency/unit signs attached to numbers, and `{name}` +//! template placeholders intact (placeholders are masked into Private Use Area codepoints before +//! reordering and restored afterward). +//! - Paired brackets (`()`, `[]`, `{}`, `<>`, `«»`) resolve direction from their enclosed content +//! and are mirrored only inside RTL runs. + +#[derive(Clone, Copy, PartialEq, Eq)] +enum BidiClass { + L, + R, + En, + N, +} + +pub(super) fn is_rtl_script(c: char) -> bool { + matches!( + u32::from(c), + 0x0590..=0x05FF | 0x0600..=0x065F | 0x066E..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFC | 0x1_0800..=0x1_0FFF | 0x1_E800..=0x1_EFFF + ) +} + +fn is_bidi_digit(c: char) -> bool { + c.is_ascii_digit() || matches!(u32::from(c), 0x0660..=0x0669 | 0x06F0..=0x06F9) +} + +fn is_bidi_control(c: char) -> bool { + matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') +} + +fn is_joiner(c: char) -> bool { + matches!(c, '\u{200C}' | '\u{200D}') +} + +fn mirrored(c: char) -> char { + match c { + '(' => ')', + ')' => '(', + '[' => ']', + ']' => '[', + '{' => '}', + '}' => '{', + '<' => '>', + '>' => '<', + '«' => '»', + '»' => '«', + other => other, + } +} + +fn bracket_close(open: char) -> Option { + match open { + '(' => Some(')'), + '[' => Some(']'), + '{' => Some('}'), + '<' => Some('>'), + '«' => Some('»'), + _ => None, + } +} + +fn is_closing_bracket(c: char) -> bool { + matches!(c, ')' | ']' | '}' | '>' | '»') +} + +const PLACEHOLDER_BASE: u32 = 0xE000; +const MAX_PLACEHOLDERS: usize = 64; + +fn mask_placeholders(text: &str) -> (String, Vec<&str>) { + let reserved = text.chars().any(|c| (PLACEHOLDER_BASE..PLACEHOLDER_BASE.saturating_add(MAX_PLACEHOLDERS as u32)).contains(&u32::from(c))); + if reserved { + return (text.to_owned(), Vec::new()); + } + let mut masked = String::with_capacity(text.len()); + let mut names = Vec::new(); + let mut rest = text; + while names.len() < MAX_PLACEHOLDERS + && let Some(start) = rest.find('{') + && let Some(len) = rest.get(start..).and_then(|s| s.find('}')) + { + let end = start.saturating_add(len).saturating_add(1); + let (Some(before), Some(atom), Some(after)) = (rest.get(..start), rest.get(start..end), rest.get(end..)) else { + break; + }; + let Some(stand_in) = u32::try_from(names.len()).ok().and_then(|i| char::from_u32(PLACEHOLDER_BASE.saturating_add(i))) else { + break; + }; + masked.push_str(before); + masked.push(stand_in); + names.push(atom); + rest = after; + } + masked.push_str(rest); + (masked, names) +} + +fn push_unmasked(out: &mut String, c: char, names: &[&str]) { + let idx = u32::from(c).checked_sub(PLACEHOLDER_BASE).and_then(|i| usize::try_from(i).ok()); + if let Some(name) = idx.and_then(|i| names.get(i)) { + out.push_str(name); + } else { + out.push(c); + } +} + +pub(super) fn push_visual_rtl_line(line: &str, out: &mut String) { + let (masked, names) = mask_placeholders(line); + let chars: Vec = masked.chars().filter(|c| !is_bidi_control(*c)).collect(); + if chars.is_empty() { + return; + } + let len = chars.len(); + let mut cls: Vec = chars + .iter() + .map(|&c| { + let is_placeholder = (PLACEHOLDER_BASE..PLACEHOLDER_BASE.saturating_add(MAX_PLACEHOLDERS as u32)).contains(&u32::from(c)); + if is_rtl_script(c) { + BidiClass::R + } else if is_bidi_digit(c) { + BidiClass::En + } else if is_placeholder || c.is_alphabetic() || matches!(c, '\u{2318}' | '\u{21E7}' | '\u{2325}' | '\u{2303}') { + BidiClass::L + } else { + BidiClass::N + } + }) + .collect(); + + for i in 1..len.saturating_sub(1) { + if cls.get(i) == Some(&BidiClass::N) + && chars.get(i).is_some_and(|c| matches!(c, '.' | ',' | ':' | '/' | '-' | '+' | '_')) + && let (Some(prev), Some(next)) = (cls.get(i - 1), cls.get(i + 1)) + { + if *prev == BidiClass::En && *next == BidiClass::En { + if let Some(slot) = cls.get_mut(i) { + *slot = BidiClass::En; + } + } else if matches!(prev, BidiClass::L | BidiClass::En) + && matches!(next, BidiClass::L | BidiClass::En) + && let Some(slot) = cls.get_mut(i) + { + *slot = BidiClass::L; + } + } + } + + for i in 0..len { + let Some(&ch) = chars.get(i) else { continue }; + if cls.get(i) != Some(&BidiClass::N) { + continue; + } + let next_en = cls.get(i + 1) == Some(&BidiClass::En); + let prev_en = i > 0 && cls.get(i - 1) == Some(&BidiClass::En); + let prev_is_r = i > 0 && cls.get(i - 1) == Some(&BidiClass::R); + let attach = match ch { + '%' | '°' | '$' | '€' | '£' | '₪' => prev_en || next_en, + '+' | '-' => next_en && !prev_is_r, + _ => false, + }; + if attach && let Some(slot) = cls.get_mut(i) { + *slot = BidiClass::En; + } + } + + // Keep leading path/dot prefixes (e.g. `/tmp/...`, `.env`) attached to following LTR/numeric runs. + for i in (0..len.saturating_sub(1)).rev() { + if cls.get(i) == Some(&BidiClass::N) + && chars.get(i).is_some_and(|c| matches!(c, '/' | '.' | '~' | '\\')) + && matches!(cls.get(i + 1), Some(BidiClass::L | BidiClass::En)) + && (i == 0 || cls.get(i - 1) != Some(&BidiClass::R)) + && let Some(slot) = cls.get_mut(i) + { + *slot = BidiClass::L; + } + } + + let mut stack: Vec<(usize, char)> = Vec::new(); + let mut pairs: Vec<(usize, usize)> = Vec::new(); + for (i, &c) in chars.iter().enumerate() { + if cls.get(i) != Some(&BidiClass::N) { + continue; + } + if let Some(close) = bracket_close(c) { + if stack.len() < 63 { + stack.push((i, close)); + } + } else if is_closing_bracket(c) + && let Some(pos) = stack.iter().rposition(|(_, expected)| *expected == c) + { + let (open_idx, _) = stack.remove(pos); + pairs.push((open_idx, i)); + } + } + pairs.sort_by_key(|(open, _)| *open); + for (open, close) in pairs { + let inner = cls.get(open + 1..close).unwrap_or(&[]); + let has_r = inner.contains(&BidiClass::R); + let has_l = inner.iter().any(|c| matches!(c, BidiClass::L | BidiClass::En)); + let dir = if has_r { + BidiClass::R + } else if has_l { + let prev_strong = cls.get(..open).unwrap_or(&[]).iter().rev().find(|c| **c != BidiClass::N).copied(); + if matches!(prev_strong, Some(BidiClass::L | BidiClass::En)) { BidiClass::L } else { BidiClass::R } + } else { + BidiClass::R + }; + if let Some(s) = cls.get_mut(open) { + *s = dir; + } + if let Some(s) = cls.get_mut(close) { + *s = dir; + } + } + + for c in &mut cls { + if *c == BidiClass::En { + *c = BidiClass::L; + } + } + let mut i = 0; + while i < len { + if cls.get(i) == Some(&BidiClass::N) { + let start = i; + while cls.get(i) == Some(&BidiClass::N) { + i += 1; + } + let left_l = start > 0 && cls.get(start - 1) == Some(&BidiClass::L); + let right_l = cls.get(i) == Some(&BidiClass::L); + let resolved = if left_l && right_l { BidiClass::L } else { BidiClass::R }; + if let Some(slice) = cls.get_mut(start..i) { + slice.fill(resolved); + } + } else { + i += 1; + } + } + + let mut runs: Vec<(bool, usize, usize)> = Vec::new(); + let mut r_start = 0; + while r_start < len { + let rtl = cls.get(r_start) == Some(&BidiClass::R); + let mut r_end = r_start + 1; + while cls.get(r_end).is_some_and(|c| (*c == BidiClass::R) == rtl) { + r_end += 1; + } + runs.push((rtl, r_start, r_end)); + r_start = r_end; + } + + for (rtl, start, end) in runs.into_iter().rev() { + let Some(slice) = chars.get(start..end) else { continue }; + if rtl { + let mut stretch: Vec = Vec::new(); + for &c in slice.iter().rev() { + if is_rtl_script(c) || is_joiner(c) { + stretch.push(c); + } else { + for sc in stretch.drain(..).rev() { + push_unmasked(out, sc, &names); + } + push_unmasked(out, mirrored(c), &names); + } + } + for sc in stretch.drain(..).rev() { + push_unmasked(out, sc, &names); + } + } else { + for &c in slice { + push_unmasked(out, c, &names); + } + } + } +} + +/// Rearrange `text` into visual right-to-left order for egui 0.36 while keeping contiguous RTL +/// script stretches in logical order so epaint's harfrust shapes them cleanly. +pub(super) fn visual_rtl(text: &str) -> String { + if !text.chars().any(is_rtl_script) { + return text.to_owned(); + } + let mut out = String::with_capacity(text.len()); + for (idx, raw_line) in text.split('\n').enumerate() { + if idx > 0 { + out.push('\n'); + } + let (line, cr) = raw_line.strip_suffix('\r').map_or((raw_line, false), |l| (l, true)); + push_visual_rtl_line(line, &mut out); + if cr { + out.push('\r'); + } + } + out +} From 5b7fb90469dbe84a4052bc72b6c66c99a052108f Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Sat, 21 Nov 2026 01:51:03 +0200 Subject: [PATCH 05/13] i18n(he): wire View > Language picker, settings persistence, logical_of_for, RTL alignment, and font tests --- apps/projectcraft/src/main.rs | 4 ++ apps/projectcraft/src/settings.rs | 64 ++++++++++++++++++++++++- crates/ui-egui/src/i18n.rs | 37 ++++++++++++-- crates/ui-egui/src/i18n/he.tsv | 1 + crates/ui-egui/src/lib.rs | 25 ++++++++++ crates/ui-egui/src/theme.rs | 52 ++++++++++++++------ crates/ui-egui/tests/language_picker.rs | 36 ++++++++++++++ 7 files changed, 199 insertions(+), 20 deletions(-) create mode 100644 crates/ui-egui/tests/language_picker.rs diff --git a/apps/projectcraft/src/main.rs b/apps/projectcraft/src/main.rs index 534f557..0869727 100644 --- a/apps/projectcraft/src/main.rs +++ b/apps/projectcraft/src/main.rs @@ -38,6 +38,9 @@ impl eframe::App for Shell { if let Some(on) = self.app.take_autosave_changed() { settings::save_autosave(on); } + if let Some(lang) = self.app.take_language_changed() { + settings::save_language(lang); + } } /// Runs before `ui`, and also while the window is minimized or hidden, when `ui` does not: @@ -68,6 +71,7 @@ fn main() -> eframe::Result { }, _ => Session::new(projectcraft_engine::model::Project::new("New project", today())), }; + projectcraft_ui_egui::i18n::set_current(settings::load_language()); let mut app = App::new(session, if sample { None } else { path.clone() }); app.recent = settings::load_recent(); // `--sample` keeps nothing: no autosave, no recovery copy. diff --git a/apps/projectcraft/src/settings.rs b/apps/projectcraft/src/settings.rs index 1d7538a..17b3f99 100644 --- a/apps/projectcraft/src/settings.rs +++ b/apps/projectcraft/src/settings.rs @@ -1,9 +1,11 @@ //! The app's settings folder and what's kept in it: the recent-files list (`recent-files.txt`, one -//! path a line), the autosave switch (`autosave.txt`, `off` when turned off) and an untitled -//! project's recovery copy (`recovery/`). +//! path a line), the autosave switch (`autosave.txt`, `off` when turned off), the interface +//! language (`language.txt`, BCP 47 tag), and an untitled project's recovery copy (`recovery/`). use std::path::PathBuf; +use projectcraft_ui_egui::i18n::Lang; + /// The settings folder: macOS `~/Library/Application Support/ProjectCraft`, Windows /// `%APPDATA%\ProjectCraft`, otherwise `$XDG_CONFIG_HOME/projectcraft` or `~/.config/projectcraft`. /// `PROJECTCRAFT_PROFILE_DIR` overrides the whole folder for isolated runs. @@ -84,3 +86,61 @@ pub fn save_autosave(on: bool) { eprintln!("couldn't save the autosave setting to {}: {e}", file.display()); } } + +fn language_file() -> Option { + settings_dir().map(|d| d.join("language.txt")) +} + +fn resolve_language_from_str(saved: Option<&str>, env_tags: &[Option]) -> Lang { + if let Some(tag) = saved.and_then(Lang::from_tag) { + return tag; + } + for env_val in env_tags.iter().flatten() { + if let Some(lang) = Lang::from_tag(env_val) { + return lang; + } + } + Lang::English +} + +/// The interface language: `language.txt` if valid, otherwise `PROJECTCRAFT_LANG` / locale env vars. +pub fn load_language() -> Lang { + let mut bytes = Vec::new(); + let saved = if let Some(Ok(f)) = language_file().map(std::fs::File::open) { + let _ = std::io::Read::read_to_end(&mut std::io::Read::take(f, 64), &mut bytes); + Some(String::from_utf8_lossy(&bytes).into_owned()) + } else { + None + }; + let env_tags = ["PROJECTCRAFT_LANG", "LC_ALL", "LC_MESSAGES", "LANG"].map(|k| std::env::var(k).ok()); + resolve_language_from_str(saved.as_deref(), &env_tags) +} + +/// Writes the interface language tag. A failure only loses the setting, so it's reported and otherwise ignored. +pub fn save_language(lang: Lang) { + let Some(file) = language_file() else { + return; + }; + let body = format!("{}\n", lang.code()); + let result = file + .parent() + .map_or(Ok(()), projectcraft_engine::create_private_dir_all) + .and_then(|()| projectcraft_engine::write_private(&file, body.as_bytes())); + if let Err(e) = result { + eprintln!("couldn't save the language setting to {}: {e}", file.display()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn language_resolution_normalizes_hebrew_and_legacy_iw_tags() { + assert_eq!(resolve_language_from_str(Some("he\n"), &[]), Lang::Hebrew); + assert_eq!(resolve_language_from_str(Some("iw_IL.UTF-8"), &[]), Lang::Hebrew); + assert_eq!(resolve_language_from_str(None, &[None, Some("he_IL.UTF-8".to_owned())]), Lang::Hebrew); + assert_eq!(resolve_language_from_str(Some("xx"), &[Some("iw".to_owned())]), Lang::Hebrew); + assert_eq!(resolve_language_from_str(None, &[None, Some("fr_FR.UTF-8".to_owned())]), Lang::English); + } +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index bb558c1..ca50905 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -134,9 +134,14 @@ fn hebrew_catalog() -> &'static HebrewCatalog { }) } +/// Recover the logical string for a catalog entry when `s` was visually reordered for `lang`. +pub fn logical_of_for(lang: Lang, s: &str) -> &str { + if lang.is_rtl() { hebrew_catalog().visual_to_logical.get(s).copied().unwrap_or(s) } else { s } +} + /// Recover the logical string for a catalog entry when `s` was visually reordered for RTL. pub fn logical_of(s: &str) -> &str { - if is_rtl() { hebrew_catalog().visual_to_logical.get(s).copied().unwrap_or(s) } else { s } + logical_of_for(current(), s) } fn wrap_paragraph_logical<'a>(ctx: &egui::Context, paragraph: &'a str, font_id: &egui::FontId, max_width: f32) -> Vec<&'a str> { @@ -208,12 +213,16 @@ pub fn wrapped_visual_lines(ctx: &egui::Context, lang: Lang, logical: &str, font /// egui determines line breaks. pub fn wrapped_label_for(ui: &mut egui::Ui, lang: Lang, text: &str, style: impl FnOnce(egui::RichText) -> egui::RichText) -> egui::Response { let font_id = egui::TextStyle::Body.resolve(ui.style()); - let logical = if lang.is_rtl() { logical_of(text) } else { text }; + let logical = logical_of_for(lang, text); let needs_rtl_wrap = lang.is_rtl() && logical.chars().any(is_rtl_script); let shown = if needs_rtl_wrap { wrapped_visual_lines(ui.ctx(), lang, logical, font_id.clone(), ui.available_width()) } else { logical.to_owned() }; let rich = style(egui::RichText::new(shown).font(font_id)); - if needs_rtl_wrap { ui.add(egui::Label::new(rich).extend()) } else { ui.add(egui::Label::new(rich).wrap()) } + if needs_rtl_wrap { + ui.with_layout(egui::Layout::top_down(egui::Align::Max), |ui| ui.add(egui::Label::new(rich).extend())).inner + } else { + ui.add(egui::Label::new(rich).wrap()) + } } /// Render a wrapping label, deferring RTL visual reordering until after egui determines line breaks. @@ -579,5 +588,27 @@ mod tests { .textures_delta .clear(); assert!(english_resp_width <= 150.0, "English fallback in Hebrew mode must still wrap, got width {english_resp_width}"); + + // Calling wrapped_label_for(Lang::Hebrew, ...) while global current() is English must + // recover the logical catalog entry via logical_of_for(lang, ...) and right-align it. + let catalog_notice = + t_for(Lang::Hebrew, "Converting durations between hours, days, weeks and months; the currency of every amount; how units show"); + let mut rtl_rect = egui::Rect::NOTHING; + let mut container_rect = egui::Rect::NOTHING; + ctx.run_ui(egui::RawInput::default(), |ui| { + egui::CentralPanel::default().show(ui, |ui| { + ui.allocate_ui(egui::vec2(220.0, 200.0), |ui| { + container_rect = ui.max_rect(); + rtl_rect = wrapped_label_for(ui, Lang::Hebrew, catalog_notice, |r| r).rect; + }); + }); + }) + .textures_delta + .clear(); + assert!( + (rtl_rect.right() - container_rect.right()).abs() <= 2.0, + "Hebrew wrapped label should right-align to container edge: rtl={rtl_rect:?} container={container_rect:?}" + ); + assert!(rtl_rect.height() >= 24.0, "catalog notice should wrap into multiple lines: {rtl_rect:?}"); } } diff --git a/crates/ui-egui/src/i18n/he.tsv b/crates/ui-egui/src/i18n/he.tsv index 31eee6a..c5299a4 100644 --- a/crates/ui-egui/src/i18n/he.tsv +++ b/crates/ui-egui/src/i18n/he.tsv @@ -118,6 +118,7 @@ Initials ראשי תיבות Jan ינו׳ Jul יול׳ Jun יונ׳ +Language שפה Level All איזון הכול Leveling Delay עיכוב איזון Levelling delays a summary task's subtasks, never the summary איזון מעכב את תת-המשימות של משימת הסיכום, לעולם לא את הסיכום עצמו diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3ffe7a2..46ed2b3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -278,6 +278,7 @@ pub struct App { /// Recently opened or saved files, newest first (the shell loads and persists it). pub recent: Vec, recent_changed: bool, + language_changed: bool, /// A dialog for the shell to show. file_request: Option, /// The unsaved-changes prompt, and what follows it. @@ -343,6 +344,7 @@ impl App { saved, recent: Vec::new(), recent_changed: false, + language_changed: false, file_request: None, prompt: None, after_save: None, @@ -369,6 +371,19 @@ impl App { &self.status } + /// Switches the active interface language and marks it for the shell to persist. + pub fn set_language(&mut self, lang: i18n::Lang) { + if i18n::current() != lang { + i18n::set_current(lang); + self.language_changed = true; + } + } + + /// Returns the newly chosen language if the user changed it since the last call. + pub fn take_language_changed(&mut self) -> Option { + std::mem::take(&mut self.language_changed).then(i18n::current) + } + /// Runs a command; an error goes to the status bar. True when it ran. fn run(&mut self, id: &str, params: Value) -> bool { self.status = match self.session.run(id, ¶ms) { @@ -849,6 +864,16 @@ impl App { if ui.add_enabled(timed && w > timescale::MIN_DAY_W, egui::Button::new(tl!("Zoom Out")).shortcut_text(out_keys)).clicked() { self.zoom(false); } + ui.separator(); + ui.menu_button(tl!("Language"), |ui| { + let active = i18n::current(); + for lang in i18n::Lang::ALL { + if ui.radio(active == lang, lang.name()).clicked() { + self.set_language(lang); + ui.close(); + } + } + }); }); } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 57ca2ac..3229777 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -175,6 +175,15 @@ fn hebrew_font_data() -> Option { } } +fn apply_hebrew_fallback(fonts: &mut egui::FontDefinitions, font_data: egui::FontData) { + fonts.font_data.insert("hebrew_fallback".to_owned(), std::sync::Arc::new(font_data)); + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + if let Some(list) = fonts.families.get_mut(&family) { + list.push("hebrew_fallback".to_owned()); + } + } +} + fn install_hebrew_fonts(ctx: &egui::Context) { let key = egui::Id::new("projectcraft_hebrew_fonts_installed"); if ctx.data(|d| d.get_temp::(key)) == Some(true) { @@ -185,12 +194,7 @@ fn install_hebrew_fonts(ctx: &egui::Context) { return; }; let mut fonts = egui::FontDefinitions::default(); - fonts.font_data.insert("hebrew_fallback".to_owned(), std::sync::Arc::new(font_data)); - for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { - if let Some(list) = fonts.families.get_mut(&family) { - list.push("hebrew_fallback".to_owned()); - } - } + apply_hebrew_fallback(&mut fonts, font_data); ctx.set_fonts(fonts); } @@ -241,20 +245,38 @@ fn shadow(t: &Tokens, light: u8, dark: u8) -> Color32 { mod tests { use super::*; + #[test] + fn hebrew_fallback_registers_in_proportional_and_monospace_families() { + let mut fonts = egui::FontDefinitions::default(); + apply_hebrew_fallback(&mut fonts, egui::FontData::from_static(&[])); + assert!(fonts.font_data.contains_key("hebrew_fallback")); + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + let list = fonts.families.get(&family).expect("family present"); + assert_eq!(list.last().map(String::as_str), Some("hebrew_fallback")); + } + } + #[test] fn hebrew_fallback_font_supplies_hebrew_glyphs_when_available() { let ctx = egui::Context::default(); apply(&ctx, egui::ThemePreference::Light); ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); - if hebrew_font_data().is_some() { - ctx.fonts_mut(|fonts| { - for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { - let font = egui::FontId::new(14.0, family); - for ch in "אבגדהוזחטיכלמנסעפצקרשתךםןףץ".chars() { - assert!(fonts.has_glyph(&font, ch), "missing Hebrew glyph {ch} in {font:?}"); - } + let Some(_) = hebrew_font_data() else { + #[cfg(has_hebrew_craft_font)] + panic!("CRAFT_FONTS_DIR Hebrew font enabled at build time but missing at runtime"); + #[cfg(not(has_hebrew_craft_font))] + { + eprintln!("skipping glyph check: no CRAFT_FONTS_DIR or system Hebrew font found on this host"); + return; + } + }; + ctx.fonts_mut(|fonts| { + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + let font = egui::FontId::new(14.0, family); + for ch in "אבגדהוזחטיכלמנסעפצקרשתךםןףץ".chars() { + assert!(fonts.has_glyph(&font, ch), "missing Hebrew glyph {ch} in {font:?}"); } - }); - } + } + }); } } diff --git a/crates/ui-egui/tests/language_picker.rs b/crates/ui-egui/tests/language_picker.rs new file mode 100644 index 0000000..87bc4fa --- /dev/null +++ b/crates/ui-egui/tests/language_picker.rs @@ -0,0 +1,36 @@ +use egui_kittest::kittest::Queryable; +use projectcraft_ui_egui::App; +use projectcraft_ui_egui::i18n::{self, Lang}; + +#[test] +fn view_language_menu_selects_hebrew_and_switches_back() { + let app = App::new(projectcraft_engine::sample(), None); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 720.0)).build_ui_state(|ui, app: &mut App| app.ui(ui), app); + h.run_steps(2); + + h.get_by_label("View").click(); + h.run_steps(2); + h.get_by_label("Language ⏵").click(); + h.run_steps(2); + h.get_by_label("עברית").click(); + h.run_steps(2); + + assert_eq!(i18n::current(), Lang::Hebrew); + assert_eq!(h.state_mut().take_language_changed(), Some(Lang::Hebrew)); + // Toolbar labels now resolve through the active Hebrew catalog. + let _ = h.get_by_label(i18n::t("Save")); + let _ = h.get_by_label(i18n::t("New Task")); + + // Switch back through the translated View -> Language menus. + h.get_by_label(i18n::t("View")).click(); + h.run_steps(2); + let lang_submenu = format!("{} ⏵", i18n::t("Language")); + h.get_by_label(&lang_submenu).click(); + h.run_steps(2); + h.get_by_label("English").click(); + h.run_steps(2); + + assert_eq!(i18n::current(), Lang::English); + assert_eq!(h.state_mut().take_language_changed(), Some(Lang::English)); + let _ = h.get_by_label("Save"); +} From cc374b5b55b95148f426a89de9705fb41464af9b Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Sat, 21 Nov 2026 13:59:33 +0200 Subject: [PATCH 06/13] i18n(he): gate Hebrew on font glyph coverage and separate logical wrapped_label API --- apps/projectcraft/src/settings.rs | 31 ++++++- crates/ui-egui/build.rs | 65 ------------- crates/ui-egui/src/assign.rs | 10 +- crates/ui-egui/src/browser.rs | 10 +- crates/ui-egui/src/i18n.rs | 115 ++++++++++++++++------- crates/ui-egui/src/lib.rs | 20 +++- crates/ui-egui/src/options.rs | 6 +- crates/ui-egui/src/recovery.rs | 4 +- crates/ui-egui/src/theme.rs | 117 +++++++++++++++--------- crates/ui-egui/tests/language_picker.rs | 27 ++++++ 10 files changed, 244 insertions(+), 161 deletions(-) delete mode 100644 crates/ui-egui/build.rs diff --git a/apps/projectcraft/src/settings.rs b/apps/projectcraft/src/settings.rs index 17b3f99..1860838 100644 --- a/apps/projectcraft/src/settings.rs +++ b/apps/projectcraft/src/settings.rs @@ -105,15 +105,19 @@ fn resolve_language_from_str(saved: Option<&str>, env_tags: &[Option]) - /// The interface language: `language.txt` if valid, otherwise `PROJECTCRAFT_LANG` / locale env vars. pub fn load_language() -> Lang { + let env_tags = ["PROJECTCRAFT_LANG", "LC_ALL", "LC_MESSAGES", "LANG"].map(|k| std::env::var(k).ok()); + load_language_from(language_file().as_deref(), &env_tags) +} + +fn load_language_from(file: Option<&std::path::Path>, env_tags: &[Option]) -> Lang { let mut bytes = Vec::new(); - let saved = if let Some(Ok(f)) = language_file().map(std::fs::File::open) { + let saved = if let Some(Ok(f)) = file.map(std::fs::File::open) { let _ = std::io::Read::read_to_end(&mut std::io::Read::take(f, 64), &mut bytes); Some(String::from_utf8_lossy(&bytes).into_owned()) } else { None }; - let env_tags = ["PROJECTCRAFT_LANG", "LC_ALL", "LC_MESSAGES", "LANG"].map(|k| std::env::var(k).ok()); - resolve_language_from_str(saved.as_deref(), &env_tags) + resolve_language_from_str(saved.as_deref(), env_tags) } /// Writes the interface language tag. A failure only loses the setting, so it's reported and otherwise ignored. @@ -121,11 +125,15 @@ pub fn save_language(lang: Lang) { let Some(file) = language_file() else { return; }; + save_language_to(&file, lang); +} + +fn save_language_to(file: &std::path::Path, lang: Lang) { let body = format!("{}\n", lang.code()); let result = file .parent() .map_or(Ok(()), projectcraft_engine::create_private_dir_all) - .and_then(|()| projectcraft_engine::write_private(&file, body.as_bytes())); + .and_then(|()| projectcraft_engine::write_private(file, body.as_bytes())); if let Err(e) = result { eprintln!("couldn't save the language setting to {}: {e}", file.display()); } @@ -143,4 +151,19 @@ mod tests { assert_eq!(resolve_language_from_str(Some("xx"), &[Some("iw".to_owned())]), Lang::Hebrew); assert_eq!(resolve_language_from_str(None, &[None, Some("fr_FR.UTF-8".to_owned())]), Lang::English); } + + #[test] + fn language_file_round_trips_hebrew_and_back_to_english() { + let dir = std::env::temp_dir().join(format!("projectcraft-lang-test-{}", std::process::id())); + let file = dir.join("language.txt"); + let _ = std::fs::remove_dir_all(&dir); + + save_language_to(&file, Lang::Hebrew); + assert_eq!(load_language_from(Some(&file), &[]), Lang::Hebrew); + + save_language_to(&file, Lang::English); + assert_eq!(load_language_from(Some(&file), &[]), Lang::English); + + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs deleted file mode 100644 index 2a22b0a..0000000 --- a/crates/ui-egui/build.rs +++ /dev/null @@ -1,65 +0,0 @@ -//! Optional build-time discovery of `NotoSansHebrew-Regular.ttf` in `craft-fonts`. -//! Builds without `CRAFT_FONTS_DIR` succeed cleanly and use desktop system font fallbacks. - -use std::path::{Path, PathBuf}; - -fn find_fonts_dir() -> Option { - if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|v| !v.is_empty()) { - let p = PathBuf::from(&dir); - if p.is_dir() { - return Some(p); - } - println!( - "cargo:warning=CRAFT_FONTS_DIR points to a missing directory ({}); falling back to sibling craft-fonts or system fonts", - p.display() - ); - } - let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - for ancestor in manifest.ancestors().skip(1) { - let sibling = ancestor.join("craft-fonts"); - if sibling.is_dir() { - return Some(sibling); - } - if ancestor.file_name().is_some_and(|n| n == "projectcraft") { - if let Some(parent) = ancestor.parent() { - let near = parent.join("craft-fonts"); - if near.is_dir() { - return Some(near); - } - } - break; - } - } - None -} - -fn candidate_hebrew_font(dir: &Path) -> Option { - let p = dir.join("fonts/noto-sans-hebrew/NotoSansHebrew-Regular.ttf"); - p.is_file().then_some(p) -} - -fn absolutize(path: PathBuf) -> PathBuf { - if path.is_absolute() { - return path; - } - path.canonicalize().unwrap_or_else(|_| std::env::current_dir().map_or_else(|_| path.clone(), |cwd| cwd.join(&path))) -} - -fn main() { - println!("cargo:rustc-check-cfg=cfg(has_hebrew_craft_font)"); - println!("cargo:rerun-if-env-changed=CRAFT_FONTS_DIR"); - if let Some(dir) = find_fonts_dir() { - let dir = absolutize(dir); - println!("cargo:rerun-if-changed={}", dir.display()); - let font_dir = dir.join("fonts/noto-sans-hebrew"); - if font_dir.is_dir() { - println!("cargo:rerun-if-changed={}", font_dir.display()); - } - if let Some(font) = candidate_hebrew_font(&dir) { - let font = absolutize(font); - println!("cargo:rerun-if-changed={}", font.display()); - println!("cargo:rustc-cfg=has_hebrew_craft_font"); - println!("cargo:rustc-env=HEBREW_CRAFT_FONT_PATH={}", font.display()); - } - } -} diff --git a/crates/ui-egui/src/assign.rs b/crates/ui-egui/src/assign.rs index d7b0527..419dc2b 100644 --- a/crates/ui-egui/src/assign.rs +++ b/crates/ui-egui/src/assign.rs @@ -272,12 +272,14 @@ impl App { ui.add_space(6.0); let decimal = p.options.units_format == UnitsFormat::Decimal; let hint = match (p.resources.iter().any(|r| r.kind == ResourceType::Material), decimal) { - (true, false) => tl!("Units: a percentage for people and equipment (50%); for materials a quantity (5 tons) or a rate (2 tons/d)."), + (true, false) => { + tl_logical!("Units: a percentage for people and equipment (50%); for materials a quantity (5 tons) or a rate (2 tons/d).") + } (true, true) => { - tl!("Units: a decimal for people and equipment (0.5, or 50%); for materials a quantity (5 tons) or a rate (2 tons/d).") + tl_logical!("Units: a decimal for people and equipment (0.5, or 50%); for materials a quantity (5 tons) or a rate (2 tons/d).") } - (false, false) => tl!("Units: the share of each resource's working time (50% is half its day)."), - (false, true) => tl!("Units: the share of each resource's working time (0.5 is half its day; 50% works too)."), + (false, false) => tl_logical!("Units: the share of each resource's working time (50% is half its day)."), + (false, true) => tl_logical!("Units: the share of each resource's working time (0.5 is half its day; 50% works too)."), }; crate::i18n::wrapped_label(ui, hint, |r| r.color(t.text_dim)); if !error.is_empty() { diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 5a0e0af..4aa2c83 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -291,7 +291,7 @@ fn body(ui: &mut Ui, b: &mut FileBrowser, t: &Tokens) -> Option> if b.unavailable { crate::i18n::wrapped_label( ui, - tl!( + tl_logical!( "The system file dialog isn't available, so ProjectCraft shows its own. To get the system dialog, install a file chooser portal (such as xdg-desktop-portal-gtk) or zenity." ), |r| r.color(t.text_dim), @@ -393,11 +393,11 @@ fn body(ui: &mut Ui, b: &mut FileBrowser, t: &Tokens) -> Option> }); let kinds = match b.request { FileRequest::Open => { - tl!("ProjectCraft projects (*.projectcraft), and Microsoft Project XML (*.xml) and CSV (*.csv), imported as a new project") + tl_logical!("ProjectCraft projects (*.projectcraft), and Microsoft Project XML (*.xml) and CSV (*.csv), imported as a new project") } - FileRequest::SaveAs => tl!("ProjectCraft projects (*.projectcraft)"), - FileRequest::Export(Format::Mspdi) => tl!("Microsoft Project XML (*.xml): a copy; the project stays as it is"), - FileRequest::Export(Format::Csv) => tl!("CSV (*.csv): a copy; the project stays as it is"), + FileRequest::SaveAs => tl_logical!("ProjectCraft projects (*.projectcraft)"), + FileRequest::Export(Format::Mspdi) => tl_logical!("Microsoft Project XML (*.xml): a copy; the project stays as it is"), + FileRequest::Export(Format::Csv) => tl_logical!("CSV (*.csv): a copy; the project stays as it is"), }; crate::i18n::wrapped_label(ui, kinds, |r| r.color(t.text_dim)); ui.add_space(8.0); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index ca50905..0c7dd61 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -101,6 +101,7 @@ pub fn is_rtl() -> bool { } struct HebrewCatalog { + en_to_logical: HashMap<&'static str, &'static str>, en_to_visual: HashMap<&'static str, &'static str>, visual_to_logical: HashMap<&'static str, &'static str>, } @@ -108,6 +109,7 @@ struct HebrewCatalog { fn hebrew_catalog() -> &'static HebrewCatalog { static CATALOG: OnceLock = OnceLock::new(); CATALOG.get_or_init(|| { + let mut en_to_logical = HashMap::new(); let mut en_to_visual = HashMap::new(); let mut visual_to_logical = HashMap::new(); for line in HEBREW_TSV.lines() { @@ -127,10 +129,11 @@ fn hebrew_catalog() -> &'static HebrewCatalog { // Static catalog entries are small and fixed for the lifetime of the process. Box::leak(visual_str.into_boxed_str()) }; + en_to_logical.insert(key, logical); en_to_visual.insert(key, visual); visual_to_logical.insert(visual, logical); } - HebrewCatalog { en_to_visual, visual_to_logical } + HebrewCatalog { en_to_logical, en_to_visual, visual_to_logical } }) } @@ -209,11 +212,14 @@ pub fn wrapped_visual_lines(ctx: &egui::Context, lang: Lang, logical: &str, font out } -/// Render a wrapping label for an explicit `lang`, deferring RTL visual reordering until after -/// egui determines line breaks. -pub fn wrapped_label_for(ui: &mut egui::Ui, lang: Lang, text: &str, style: impl FnOnce(egui::RichText) -> egui::RichText) -> egui::Response { +/// Render a **logical-order** wrapping label for an explicit `lang` (for example from +/// [`t_logical_for`] / [`tl_logical!`] or [`fmt_logical`]), deferring visual RTL reordering until +/// after egui line breaks are measured. +/// +/// Callers must pass logical text rather than already-reordered strings from [`t`] / [`fmt`] so +/// formatted outputs are never double-reordered. +pub fn wrapped_label_for(ui: &mut egui::Ui, lang: Lang, logical: &str, style: impl FnOnce(egui::RichText) -> egui::RichText) -> egui::Response { let font_id = egui::TextStyle::Body.resolve(ui.style()); - let logical = logical_of_for(lang, text); let needs_rtl_wrap = lang.is_rtl() && logical.chars().any(is_rtl_script); let shown = if needs_rtl_wrap { wrapped_visual_lines(ui.ctx(), lang, logical, font_id.clone(), ui.available_width()) } else { logical.to_owned() }; @@ -225,9 +231,24 @@ pub fn wrapped_label_for(ui: &mut egui::Ui, lang: Lang, text: &str, style: impl } } -/// Render a wrapping label, deferring RTL visual reordering until after egui determines line breaks. -pub fn wrapped_label(ui: &mut egui::Ui, text: &str, style: impl FnOnce(egui::RichText) -> egui::RichText) -> egui::Response { - wrapped_label_for(ui, current(), text, style) +/// Render a **logical-order** wrapping label in the active interface language, deferring visual +/// RTL reordering until after egui line breaks are measured. +pub fn wrapped_label(ui: &mut egui::Ui, logical: &str, style: impl FnOnce(egui::RichText) -> egui::RichText) -> egui::Response { + wrapped_label_for(ui, current(), logical, style) +} + +/// `s` in `lang` in logical text order (for [`wrapped_label_for`] and [`fmt_logical_for`]). +pub fn t_logical_for(lang: Lang, s: &str) -> &str { + match lang { + Lang::English => s, + Lang::Pseudo => pseudo(s), + Lang::Hebrew => hebrew_catalog().en_to_logical.get(s).copied().unwrap_or(s), + } +} + +/// `s` in the active interface language in logical text order (the `tl_logical!` macro). +pub fn t_logical(s: &str) -> &str { + t_logical_for(current(), s) } /// `s` in `lang` (in visual RTL order for egui 0.36 when [`Lang::Hebrew`] is passed). @@ -414,31 +435,33 @@ mod tests { continue; } let text = std::fs::read_to_string(&path).unwrap(); - let mut rest = text.as_str(); - while let Some(at) = rest.find("tl!(\"") { - rest = &rest[at + 5..]; - let mut lit = String::new(); - let mut chars = rest.chars(); - let mut esc = false; - for ch in &mut chars { - if esc { - match ch { - 'n' => lit.push('\n'), - 'r' => lit.push('\r'), - 't' => lit.push('\t'), - other => lit.push(other), + for prefix in ["tl!(\"", "tl_logical!(\""] { + let mut rest = text.as_str(); + while let Some(at) = rest.find(prefix) { + rest = &rest[at + prefix.len()..]; + let mut lit = String::new(); + let mut chars = rest.chars(); + let mut esc = false; + for ch in &mut chars { + if esc { + match ch { + 'n' => lit.push('\n'), + 'r' => lit.push('\r'), + 't' => lit.push('\t'), + other => lit.push(other), + } + esc = false; + } else if ch == '\\' { + esc = true; + } else if ch == '"' { + break; + } else { + lit.push(ch); } - esc = false; - } else if ch == '\\' { - esc = true; - } else if ch == '"' { - break; - } else { - lit.push(ch); } + required.insert(lit); + rest = chars.as_str(); } - required.insert(lit); - rest = chars.as_str(); } } // Dynamic table keys routed through `tl!` in ui-egui. @@ -556,6 +579,20 @@ mod tests { assert_eq!(visual_rtl("פרויקט ProjectCraft (100%)"), "ProjectCraft (100%) פרויקט"); assert_eq!(visual_rtl("שמור (Ctrl+O)"), "(Ctrl+O) שמור"); assert_eq!(visual_rtl("הכול הושלם (100%)"), "(100%) הושלם הכול"); + // Visual-to-logical recovery must never collide between two distinct logical translations, + // and duplicate Hebrew translations (e.g. Cancel/Undo -> ביטול) must keep their Hebrew + // logical string rather than colliding on English keys. + let mut seen_visual: HashMap = HashMap::new(); + for (k, logical) in parsed_hebrew_rows() { + let vis = visual_rtl(&logical); + if let Some(prev) = seen_visual.insert(vis.clone(), logical.clone()) { + assert_eq!(prev, logical, "visual_rtl collision for {k:?}: {vis:?} maps to both {prev:?} and {logical:?}"); + } + } + assert_eq!(t_logical_for(Lang::Hebrew, "Cancel"), "ביטול"); + assert_eq!(t_logical_for(Lang::Hebrew, "Undo"), "ביטול"); + assert_eq!(logical_of_for(Lang::Hebrew, t_for(Lang::Hebrew, "Cancel")), "ביטול"); + assert_eq!(fmt_for(Lang::Hebrew, t_for(Lang::Hebrew, "Cancel"), &[]), "ביטול"); assert_eq!(t_for(Lang::Hebrew, ""), ""); } @@ -589,17 +626,25 @@ mod tests { .clear(); assert!(english_resp_width <= 150.0, "English fallback in Hebrew mode must still wrap, got width {english_resp_width}"); - // Calling wrapped_label_for(Lang::Hebrew, ...) while global current() is English must - // recover the logical catalog entry via logical_of_for(lang, ...) and right-align it. + // Calling wrapped_label_for(Lang::Hebrew, ...) with a logical catalog string (via + // t_logical_for) while global current() is English must wrap and right-align cleanly, and + // formatted logical strings must not be double-reordered. let catalog_notice = - t_for(Lang::Hebrew, "Converting durations between hours, days, weeks and months; the currency of every amount; how units show"); + t_logical_for(Lang::Hebrew, "Converting durations between hours, days, weeks and months; the currency of every amount; how units show"); + let formatted_notice = fmt_logical_for( + Lang::Hebrew, + t_logical_for(Lang::Hebrew, "ProjectCraft closed before changes to {name} were saved. A recovery copy of them was kept."), + &[("name", "AlphaPlan")], + ); let mut rtl_rect = egui::Rect::NOTHING; let mut container_rect = egui::Rect::NOTHING; + let mut formatted_rect = egui::Rect::NOTHING; ctx.run_ui(egui::RawInput::default(), |ui| { egui::CentralPanel::default().show(ui, |ui| { ui.allocate_ui(egui::vec2(220.0, 200.0), |ui| { container_rect = ui.max_rect(); rtl_rect = wrapped_label_for(ui, Lang::Hebrew, catalog_notice, |r| r).rect; + formatted_rect = wrapped_label_for(ui, Lang::Hebrew, &formatted_notice, |r| r).rect; }); }); }) @@ -610,5 +655,9 @@ mod tests { "Hebrew wrapped label should right-align to container edge: rtl={rtl_rect:?} container={container_rect:?}" ); assert!(rtl_rect.height() >= 24.0, "catalog notice should wrap into multiple lines: {rtl_rect:?}"); + assert!( + (formatted_rect.right() - container_rect.right()).abs() <= 2.0, + "formatted Hebrew wrapped label should right-align to container edge: formatted={formatted_rect:?} container={container_rect:?}" + ); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 46ed2b3..a293621 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -25,6 +25,15 @@ macro_rules! tl { }; } +/// An English UI string in the current interface language in logical text order +/// ([`i18n::t_logical`]), for [`i18n::wrapped_label`] and [`i18n::fmt_logical`]. +#[macro_export] +macro_rules! tl_logical { + ($s:expr) => { + $crate::i18n::t_logical($s) + }; +} + pub mod i18n; pub mod theme; pub mod timescale; @@ -442,6 +451,9 @@ impl App { theme::apply(&ctx, self.appearance); self.themed = Some(self.appearance); } + if i18n::current() == i18n::Lang::Hebrew && !theme::hebrew_font_available(&ctx) { + i18n::set_current(i18n::Lang::English); + } self.file_keys(&ctx); let (undo, redo) = ctx.input_mut(|i| (i.consume_key(egui::Modifiers::COMMAND, Key::Z), i.consume_key(egui::Modifiers::COMMAND, Key::Y))); let (zoom_in, zoom_out) = ctx.input_mut(|i| { @@ -867,7 +879,11 @@ impl App { ui.separator(); ui.menu_button(tl!("Language"), |ui| { let active = i18n::current(); + let hebrew_ok = theme::hebrew_font_available(ui.ctx()); for lang in i18n::Lang::ALL { + if lang == i18n::Lang::Hebrew && !hebrew_ok { + continue; + } if ui.radio(active == lang, lang.name()).clicked() { self.set_language(lang); ui.close(); @@ -1013,7 +1029,7 @@ impl App { .labelled_by(label.id); }); if form.resource.is_some() { - i18n::wrapped_label(ui, tl!("Based on the project calendar: only what differs is its own."), |r| r.color(t.text_dim)); + i18n::wrapped_label(ui, tl_logical!("Based on the project calendar: only what differs is its own."), |r| r.color(t.text_dim)); } ui.add_space(10.0); @@ -1086,7 +1102,7 @@ impl App { // A resource lists its own; the project calendar's apply to it too. Only the rows in // view are drawn. if own.is_some() { - i18n::wrapped_label(ui, tl!("The project calendar's exceptions apply too, except on a day with one of its own."), |r| { + i18n::wrapped_label(ui, tl_logical!("The project calendar's exceptions apply too, except on a day with one of its own."), |r| { r.color(t.text_dim) }); } diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index c7959b2..a1509df 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.rs @@ -154,7 +154,7 @@ impl App { ui.heading(tl!("Project Options")); crate::i18n::wrapped_label( ui, - tl!("Converting durations between hours, days, weeks and months; the currency of every amount; how units show"), + tl_logical!("Converting durations between hours, days, weeks and months; the currency of every amount; how units show"), |r| r.color(t.text_dim), ); ui.add_space(10.0); @@ -207,8 +207,8 @@ impl App { ui.end_row(); }); let example = match form.units_format { - UnitsFormat::Percentage => tl!("Half time shows as 50%, full time as 100%."), - UnitsFormat::Decimal => tl!("Half time shows as 0.5, full time as 1. Typing 50% still works."), + UnitsFormat::Percentage => tl_logical!("Half time shows as 50%, full time as 100%."), + UnitsFormat::Decimal => tl_logical!("Half time shows as 0.5, full time as 1. Typing 50% still works."), }; crate::i18n::wrapped_label(ui, example, |r| r.color(t.text_dim)); if !error.is_empty() { diff --git a/crates/ui-egui/src/recovery.rs b/crates/ui-egui/src/recovery.rs index 436ee65..8b24020 100644 --- a/crates/ui-egui/src/recovery.rs +++ b/crates/ui-egui/src/recovery.rs @@ -225,11 +225,11 @@ impl App { ui.set_max_width(420.0); ui.heading(tl!("Recover unsaved changes?")); let notice = i18n::fmt_logical( - tl!("ProjectCraft closed before changes to {name} were saved. A recovery copy of them was kept."), + tl_logical!("ProjectCraft closed before changes to {name} were saved. A recovery copy of them was kept."), &[("name", &name)], ); i18n::wrapped_label(ui, ¬ice, |r| r); - i18n::wrapped_label(ui, tl!("Restore opens them as unsaved changes. Discard deletes the recovery copy."), |r| r); + i18n::wrapped_label(ui, tl_logical!("Restore opens them as unsaved changes. Discard deletes the recovery copy."), |r| r); ui.add_space(8.0); ui.horizontal(|ui| { if ui.button(tl!("Restore")).clicked() { diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 3229777..b9157d7 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -135,44 +135,70 @@ pub fn apply(ctx: &egui::Context, preference: egui::ThemePreference) { }); } -fn hebrew_font_data() -> Option { - #[cfg(has_hebrew_craft_font)] - { - Some(egui::FontData::from_static(include_bytes!(env!("HEBREW_CRAFT_FONT_PATH")))) +fn hebrew_available_key() -> egui::Id { + egui::Id::new("projectcraft_hebrew_fonts_available") +} + +fn hebrew_installed_pass_key() -> egui::Id { + egui::Id::new("projectcraft_hebrew_fonts_installed_pass") +} + +fn has_hebrew_glyphs(ctx: &egui::Context) -> bool { + ctx.fonts_mut(|fonts| fonts.has_glyph(&egui::FontId::proportional(14.0), 'א') && fonts.has_glyph(&egui::FontId::monospace(14.0), 'א')) +} + +/// Returns whether the fonts loaded on `ctx` can render Hebrew glyphs. +/// +/// Must be called after `ctx` has completed at least one pass (or inside a `Ui` pass once any +/// queued `set_fonts` update has been applied). +pub fn hebrew_font_available(ctx: &egui::Context) -> bool { + if let Some(available) = ctx.data(|d| d.get_temp::(hebrew_available_key())) { + return available; + } + let installed_pass = ctx.data(|d| d.get_temp::(hebrew_installed_pass_key())); + if installed_pass.is_some_and(|pass| ctx.cumulative_pass_nr() <= pass) { + // `set_fonts` takes effect on the next pass; keep the candidate active until then. + return true; } - #[cfg(not(has_hebrew_craft_font))] - { - #[cfg(not(target_arch = "wasm32"))] - { - #[cfg(target_os = "macos")] - const CANDIDATES: &[&str] = &[ - "/System/Library/Fonts/SFHebrew.ttf", - "/System/Library/Fonts/Supplemental/Arial.ttf", - "/System/Library/Fonts/Supplemental/Arial Unicode.ttf", - "/Library/Fonts/Arial Unicode.ttf", - ]; - #[cfg(all(unix, not(target_os = "macos")))] - const CANDIDATES: &[&str] = &[ - "/usr/share/fonts/truetype/noto/NotoSansHebrew-Regular.ttf", - "/usr/share/fonts/noto/NotoSansHebrew-Regular.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/truetype/freefont/FreeSans.ttf", - ]; - #[cfg(windows)] - const CANDIDATES: &[&str] = &[r"C:\Windows\Fonts\arial.ttf", r"C:\Windows\Fonts\segoeui.ttf", r"C:\Windows\Fonts\tahoma.ttf"]; - #[cfg(not(any(unix, windows)))] - const CANDIDATES: &[&str] = &[]; + let available = has_hebrew_glyphs(ctx); + ctx.data_mut(|d| d.insert_temp(hebrew_available_key(), available)); + available +} - for path in CANDIDATES { - if let Ok(bytes) = std::fs::read(path) { - return Some(egui::FontData::from_owned(bytes)); - } - } +#[cfg(not(target_arch = "wasm32"))] +fn hebrew_font_data() -> Option { + #[cfg(target_os = "macos")] + const CANDIDATES: &[&str] = &[ + "/System/Library/Fonts/SFHebrew.ttf", + "/System/Library/Fonts/Supplemental/Arial.ttf", + "/System/Library/Fonts/Supplemental/Arial Unicode.ttf", + "/Library/Fonts/Arial Unicode.ttf", + ]; + #[cfg(all(unix, not(target_os = "macos")))] + const CANDIDATES: &[&str] = &[ + "/usr/share/fonts/truetype/noto/NotoSansHebrew-Regular.ttf", + "/usr/share/fonts/noto/NotoSansHebrew-Regular.ttf", + "/usr/share/fonts/opentype/noto/NotoSansHebrew-Regular.ttf", + "/usr/share/fonts/truetype/freefont/FreeSans.ttf", + "/usr/share/fonts/TTF/FreeSans.ttf", + "/usr/share/fonts/gnu-free/FreeSans.ttf", + ]; + #[cfg(windows)] + const CANDIDATES: &[&str] = &[r"C:\Windows\Fonts\arial.ttf", r"C:\Windows\Fonts\segoeui.ttf", r"C:\Windows\Fonts\tahoma.ttf"]; + #[cfg(not(any(unix, windows)))] + const CANDIDATES: &[&str] = &[]; + + for path in CANDIDATES { + if let Ok(bytes) = std::fs::read(path) { + return Some(egui::FontData::from_owned(bytes)); } - None } + None +} + +#[cfg(target_arch = "wasm32")] +fn hebrew_font_data() -> Option { + None } fn apply_hebrew_fallback(fonts: &mut egui::FontDefinitions, font_data: egui::FontData) { @@ -191,11 +217,14 @@ fn install_hebrew_fonts(ctx: &egui::Context) { } ctx.data_mut(|d| d.insert_temp(key, true)); let Some(font_data) = hebrew_font_data() else { + ctx.data_mut(|d| d.insert_temp(hebrew_available_key(), false)); return; }; let mut fonts = egui::FontDefinitions::default(); apply_hebrew_fallback(&mut fonts, font_data); ctx.set_fonts(fonts); + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|d| d.insert_temp(hebrew_installed_pass_key(), pass)); } /// egui's visuals for one of our palettes. @@ -256,20 +285,22 @@ mod tests { } } + #[test] + fn default_fonts_report_hebrew_unavailable_until_fallback_is_installed() { + let ctx = egui::Context::default(); + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + assert!(!hebrew_font_available(&ctx), "egui default fonts should not report Hebrew coverage"); + } + #[test] fn hebrew_fallback_font_supplies_hebrew_glyphs_when_available() { let ctx = egui::Context::default(); apply(&ctx, egui::ThemePreference::Light); ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); - let Some(_) = hebrew_font_data() else { - #[cfg(has_hebrew_craft_font)] - panic!("CRAFT_FONTS_DIR Hebrew font enabled at build time but missing at runtime"); - #[cfg(not(has_hebrew_craft_font))] - { - eprintln!("skipping glyph check: no CRAFT_FONTS_DIR or system Hebrew font found on this host"); - return; - } - }; + if !hebrew_font_available(&ctx) { + eprintln!("skipping glyph check: no system Hebrew font found on this host"); + return; + } ctx.fonts_mut(|fonts| { for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { let font = egui::FontId::new(14.0, family); diff --git a/crates/ui-egui/tests/language_picker.rs b/crates/ui-egui/tests/language_picker.rs index 87bc4fa..e45cbae 100644 --- a/crates/ui-egui/tests/language_picker.rs +++ b/crates/ui-egui/tests/language_picker.rs @@ -1,6 +1,7 @@ use egui_kittest::kittest::Queryable; use projectcraft_ui_egui::App; use projectcraft_ui_egui::i18n::{self, Lang}; +use projectcraft_ui_egui::theme; #[test] fn view_language_menu_selects_hebrew_and_switches_back() { @@ -12,6 +13,10 @@ fn view_language_menu_selects_hebrew_and_switches_back() { h.run_steps(2); h.get_by_label("Language ⏵").click(); h.run_steps(2); + if !theme::hebrew_font_available(&h.ctx) { + assert!(h.query_by_label("עברית").is_none(), "Hebrew must stay hidden when no Hebrew font is installed"); + return; + } h.get_by_label("עברית").click(); h.run_steps(2); @@ -33,4 +38,26 @@ fn view_language_menu_selects_hebrew_and_switches_back() { assert_eq!(i18n::current(), Lang::English); assert_eq!(h.state_mut().take_language_changed(), Some(Lang::English)); let _ = h.get_by_label("Save"); + + // When a host/wasm target has no Hebrew-capable font, Hebrew startup selection must fall back + // to English and the View -> Language menu must not offer עברית. + i18n::set_current(Lang::Hebrew); + let app_no_font = App::new(projectcraft_engine::sample(), None); + let mut h_no_font = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 720.0)).build_ui_state( + |ui, app: &mut App| { + ui.ctx().data_mut(|d| { + d.insert_temp(egui::Id::new("projectcraft_hebrew_fonts_installed"), true); + d.insert_temp(egui::Id::new("projectcraft_hebrew_fonts_available"), false); + }); + app.ui(ui); + }, + app_no_font, + ); + h_no_font.run_steps(2); + assert_eq!(i18n::current(), Lang::English); + h_no_font.get_by_label("View").click(); + h_no_font.run_steps(2); + h_no_font.get_by_label("Language ⏵").click(); + h_no_font.run_steps(2); + assert!(h_no_font.query_by_label("עברית").is_none(), "Hebrew must not be selectable without Hebrew glyphs"); } From fdf437481458fce1dac400abbcd3385abc2ff626 Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Sat, 21 Nov 2026 18:00:29 +0200 Subject: [PATCH 07/13] i18n(he): resolve LC_ALL precedence, split oversized wrapped words, keep glob prefixes, and fix font fallback state --- apps/projectcraft/src/settings.rs | 21 +++++-- crates/ui-egui/src/i18n.rs | 94 +++++++++++++++++++++++++++++-- crates/ui-egui/src/i18n/bidi.rs | 7 ++- crates/ui-egui/src/lib.rs | 15 +++-- crates/ui-egui/src/theme.rs | 39 ++++++++++++- 5 files changed, 158 insertions(+), 18 deletions(-) diff --git a/apps/projectcraft/src/settings.rs b/apps/projectcraft/src/settings.rs index 1860838..1c1dab1 100644 --- a/apps/projectcraft/src/settings.rs +++ b/apps/projectcraft/src/settings.rs @@ -95,12 +95,11 @@ fn resolve_language_from_str(saved: Option<&str>, env_tags: &[Option]) - if let Some(tag) = saved.and_then(Lang::from_tag) { return tag; } - for env_val in env_tags.iter().flatten() { - if let Some(lang) = Lang::from_tag(env_val) { - return lang; - } + if let Some(lang) = env_tags.first().and_then(|v| v.as_deref()).and_then(Lang::from_tag) { + return lang; } - Lang::English + let effective_posix = env_tags.get(1..).unwrap_or(&[]).iter().flatten().map(|s| s.trim()).find(|s| !s.is_empty()); + effective_posix.and_then(Lang::from_tag).unwrap_or(Lang::English) } /// The interface language: `language.txt` if valid, otherwise `PROJECTCRAFT_LANG` / locale env vars. @@ -150,6 +149,18 @@ mod tests { assert_eq!(resolve_language_from_str(None, &[None, Some("he_IL.UTF-8".to_owned())]), Lang::Hebrew); assert_eq!(resolve_language_from_str(Some("xx"), &[Some("iw".to_owned())]), Lang::Hebrew); assert_eq!(resolve_language_from_str(None, &[None, Some("fr_FR.UTF-8".to_owned())]), Lang::English); + // Non-empty LC_ALL overrides lower-priority LANG even when unsupported. + assert_eq!(resolve_language_from_str(None, &[None, Some("C".to_owned()), None, Some("he_IL.UTF-8".to_owned())]), Lang::English); + // Empty LC_ALL / LC_MESSAGES fall through to LANG. + assert_eq!( + resolve_language_from_str(None, &[None, Some(String::new()), Some(" ".to_owned()), Some("he_IL.UTF-8".to_owned())]), + Lang::Hebrew + ); + // PROJECTCRAFT_LANG keeps precedence over POSIX locale vars. + assert_eq!( + resolve_language_from_str(None, &[Some("iw".to_owned()), Some("C".to_owned()), None, Some("en_US.UTF-8".to_owned())]), + Lang::Hebrew + ); } #[test] diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 0c7dd61..2c42303 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -147,6 +147,60 @@ pub fn logical_of(s: &str) -> &str { logical_of_for(current(), s) } +fn is_combining_cluster_continuation(ch: char) -> bool { + matches!(u32::from(ch), 0x0300..=0x036F | 0x0591..=0x05C7 | 0x200C..=0x200D | 0xFE00..=0xFE0F) +} + +fn measure_no_wrap(ctx: &egui::Context, text: &str, font_id: &egui::FontId) -> f32 { + ctx.fonts_mut(|f| f.layout_no_wrap(text.to_owned(), font_id.clone(), Default::default()).rect.width()) +} + +fn push_fitted_span( + ctx: &egui::Context, + paragraph: &str, + span_start: usize, + span_end: usize, + font_id: &egui::FontId, + max_w: f32, + out: &mut Vec<(usize, usize)>, +) { + let Some(span) = paragraph.get(span_start..span_end) else { + return; + }; + if measure_no_wrap(ctx, span, font_id) <= max_w { + out.push((span_start, span_end)); + return; + } + + let mut clusters: Vec<(usize, usize)> = Vec::new(); + for (rel_idx, ch) in span.char_indices() { + let abs_idx = span_start.saturating_add(rel_idx); + let char_end = abs_idx.saturating_add(ch.len_utf8()); + if let Some(last) = clusters.last_mut() + && is_combining_cluster_continuation(ch) + { + last.1 = char_end; + } else { + clusters.push((abs_idx, char_end)); + } + } + + let Some(&(mut piece_start, mut piece_end)) = clusters.first() else { + return; + }; + for &(c_start, c_end) in clusters.iter().skip(1) { + let candidate = paragraph.get(piece_start..c_end).unwrap_or(""); + if measure_no_wrap(ctx, candidate, font_id) <= max_w { + piece_end = c_end; + } else { + out.push((piece_start, piece_end)); + piece_start = c_start; + piece_end = c_end; + } + } + out.push((piece_start, piece_end)); +} + fn wrap_paragraph_logical<'a>(ctx: &egui::Context, paragraph: &'a str, font_id: &egui::FontId, max_width: f32) -> Vec<&'a str> { if paragraph.is_empty() || !max_width.is_finite() { return vec![paragraph]; @@ -158,7 +212,7 @@ fn wrap_paragraph_logical<'a>(ctx: &egui::Context, paragraph: &'a str, font_id: for (idx, ch) in paragraph.char_indices() { if ch.is_whitespace() { if in_word { - spans.push((word_start, idx)); + push_fitted_span(ctx, paragraph, word_start, idx, font_id, max_w, &mut spans); in_word = false; } } else if !in_word { @@ -167,24 +221,28 @@ fn wrap_paragraph_logical<'a>(ctx: &egui::Context, paragraph: &'a str, font_id: } } if in_word { - spans.push((word_start, paragraph.len())); + push_fitted_span(ctx, paragraph, word_start, paragraph.len(), font_id, max_w, &mut spans); } let Some(&(mut line_start, mut line_end)) = spans.first() else { return vec![paragraph]; }; let mut rows = Vec::new(); for &(span_start, span_end) in spans.iter().skip(1) { - let candidate = ¶graph[line_start..span_end]; - let width = ctx.fonts_mut(|f| f.layout_no_wrap(candidate.to_owned(), font_id.clone(), Default::default()).rect.width()); + let candidate = paragraph.get(line_start..span_end).unwrap_or(""); + let width = measure_no_wrap(ctx, candidate, font_id); if width <= max_w { line_end = span_end; } else { - rows.push(¶graph[line_start..line_end]); + if let Some(row) = paragraph.get(line_start..line_end) { + rows.push(row); + } line_start = span_start; line_end = span_end; } } - rows.push(¶graph[line_start..line_end]); + if let Some(row) = paragraph.get(line_start..line_end) { + rows.push(row); + } rows } @@ -579,6 +637,10 @@ mod tests { assert_eq!(visual_rtl("פרויקט ProjectCraft (100%)"), "ProjectCraft (100%) פרויקט"); assert_eq!(visual_rtl("שמור (Ctrl+O)"), "(Ctrl+O) שמור"); assert_eq!(visual_rtl("הכול הושלם (100%)"), "(100%) הושלם הכול"); + assert_eq!(visual_rtl("(*.projectcraft), המיובאים"), "המיובאים ,(*.projectcraft)"); + assert_eq!(visual_rtl("פרויקטים (*.projectcraft)"), "(*.projectcraft) פרויקטים"); + assert_eq!(visual_rtl("(*.projectcraft), וכן"), "וכן ,(*.projectcraft)"); + assert_eq!(visual_rtl("(*.projectcraft),"), "(*.projectcraft),"); // Visual-to-logical recovery must never collide between two distinct logical translations, // and duplicate Hebrew translations (e.g. Cancel/Undo -> ביטול) must keep their Hebrew // logical string rather than colliding on English keys. @@ -659,5 +721,25 @@ mod tests { (formatted_rect.right() - container_rect.right()).abs() <= 2.0, "formatted Hebrew wrapped label should right-align to container edge: formatted={formatted_rect:?} container={container_rect:?}" ); + + // Oversized unbroken words inside a Hebrew notice must split before rendering so + // Label::extend() never widens a fixed-width dialog. + let long_name = "a".repeat(200); + let oversized = fmt_logical_for( + Lang::Hebrew, + t_logical_for(Lang::Hebrew, "ProjectCraft closed before changes to {name} were saved. A recovery copy of them was kept."), + &[("name", &long_name)], + ); + let mut oversized_rect = egui::Rect::NOTHING; + ctx.run_ui(egui::RawInput::default(), |ui| { + egui::CentralPanel::default().show(ui, |ui| { + ui.allocate_ui(egui::vec2(220.0, 400.0), |ui| { + oversized_rect = wrapped_label_for(ui, Lang::Hebrew, &oversized, |r| r).rect; + }); + }); + }) + .textures_delta + .clear(); + assert!(oversized_rect.width() <= 225.0, "oversized word must split within dialog width, got {oversized_rect:?}"); } } diff --git a/crates/ui-egui/src/i18n/bidi.rs b/crates/ui-egui/src/i18n/bidi.rs index d07a8cc..5069799 100644 --- a/crates/ui-egui/src/i18n/bidi.rs +++ b/crates/ui-egui/src/i18n/bidi.rs @@ -168,10 +168,13 @@ pub(super) fn push_visual_rtl_line(line: &str, out: &mut String) { } } - // Keep leading path/dot prefixes (e.g. `/tmp/...`, `.env`) attached to following LTR/numeric runs. + // Keep leading path/dot/wildcard prefixes (e.g. `/tmp/...`, `.env`, `*.projectcraft`) + // attached to following LTR/numeric runs. for i in (0..len.saturating_sub(1)).rev() { + let is_path_prefix = chars.get(i).is_some_and(|c| matches!(c, '/' | '.' | '~' | '\\')); + let is_glob_prefix = chars.get(i) == Some(&'*') && chars.get(i + 1) == Some(&'.') && cls.get(i + 1) == Some(&BidiClass::L); if cls.get(i) == Some(&BidiClass::N) - && chars.get(i).is_some_and(|c| matches!(c, '/' | '.' | '~' | '\\')) + && (is_path_prefix || is_glob_prefix) && matches!(cls.get(i + 1), Some(BidiClass::L | BidiClass::En)) && (i == 0 || cls.get(i - 1) != Some(&BidiClass::R)) && let Some(slot) = cls.get_mut(i) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a293621..6ef44ac 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -382,10 +382,8 @@ impl App { /// Switches the active interface language and marks it for the shell to persist. pub fn set_language(&mut self, lang: i18n::Lang) { - if i18n::current() != lang { - i18n::set_current(lang); - self.language_changed = true; - } + i18n::set_current(lang); + self.language_changed = true; } /// Returns the newly chosen language if the user changed it since the last call. @@ -453,6 +451,7 @@ impl App { } if i18n::current() == i18n::Lang::Hebrew && !theme::hebrew_font_available(&ctx) { i18n::set_current(i18n::Lang::English); + self.language_changed = true; } self.file_keys(&ctx); let (undo, redo) = ctx.input_mut(|i| (i.consume_key(egui::Modifiers::COMMAND, Key::Z), i.consume_key(egui::Modifiers::COMMAND, Key::Y))); @@ -2290,4 +2289,12 @@ mod tests { h.state_mut().commit(TaskId(5), Field::LevelingDelay, "".into()); assert_eq!(h.state().session.project.task(TaskId(5)).unwrap().leveling_delay, 0); } + + #[test] + fn explicit_english_selection_marks_language_for_persistence() { + let mut app = App::new(projectcraft_engine::sample(), None); + assert_eq!(app.take_language_changed(), None); + app.set_language(i18n::Lang::English); + assert_eq!(app.take_language_changed(), Some(i18n::Lang::English)); + } } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index b9157d7..80a0bd1 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -167,6 +167,18 @@ pub fn hebrew_font_available(ctx: &egui::Context) -> bool { #[cfg(not(target_arch = "wasm32"))] fn hebrew_font_data() -> Option { + for env_var in ["PROJECTCRAFT_FONT_DIR", "CRAFT_FONTS_DIR"] { + if let Ok(dir) = std::env::var(env_var) { + let trimmed = dir.trim(); + if !trimmed.is_empty() { + let candidate = std::path::Path::new(trimmed).join("NotoSansHebrew-Regular.ttf"); + if let Ok(bytes) = std::fs::read(candidate) { + return Some(egui::FontData::from_owned(bytes)); + } + } + } + } + #[cfg(target_os = "macos")] const CANDIDATES: &[&str] = &[ "/System/Library/Fonts/SFHebrew.ttf", @@ -179,9 +191,13 @@ fn hebrew_font_data() -> Option { "/usr/share/fonts/truetype/noto/NotoSansHebrew-Regular.ttf", "/usr/share/fonts/noto/NotoSansHebrew-Regular.ttf", "/usr/share/fonts/opentype/noto/NotoSansHebrew-Regular.ttf", + "/usr/local/share/fonts/noto/NotoSansHebrew-Regular.ttf", + "/run/current-system/sw/share/fonts/truetype/NotoSansHebrew-Regular.ttf", + "/run/current-system/sw/share/fonts/noto/NotoSansHebrew-Regular.ttf", "/usr/share/fonts/truetype/freefont/FreeSans.ttf", "/usr/share/fonts/TTF/FreeSans.ttf", "/usr/share/fonts/gnu-free/FreeSans.ttf", + "/usr/local/share/fonts/freefont-ttf/FreeSans.ttf", ]; #[cfg(windows)] const CANDIDATES: &[&str] = &[r"C:\Windows\Fonts\arial.ttf", r"C:\Windows\Fonts\segoeui.ttf", r"C:\Windows\Fonts\tahoma.ttf"]; @@ -217,12 +233,21 @@ fn install_hebrew_fonts(ctx: &egui::Context) { } ctx.data_mut(|d| d.insert_temp(key, true)); let Some(font_data) = hebrew_font_data() else { - ctx.data_mut(|d| d.insert_temp(hebrew_available_key(), false)); + #[cfg(not(target_arch = "wasm32"))] + { + static WARNED: std::sync::Once = std::sync::Once::new(); + WARNED.call_once(|| { + eprintln!( + "note: no Hebrew fallback font found (checked PROJECTCRAFT_FONT_DIR, CRAFT_FONTS_DIR, and system font paths); Hebrew UI disabled" + ); + }); + } return; }; let mut fonts = egui::FontDefinitions::default(); apply_hebrew_fallback(&mut fonts, font_data); ctx.set_fonts(fonts); + ctx.data_mut(|d| d.remove::(hebrew_available_key())); let pass = ctx.cumulative_pass_nr(); ctx.data_mut(|d| d.insert_temp(hebrew_installed_pass_key(), pass)); } @@ -310,4 +335,16 @@ mod tests { } }); } + + #[test] + fn early_hebrew_availability_cache_clears_when_fonts_are_applied() { + let ctx = egui::Context::default(); + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + assert!(!hebrew_font_available(&ctx)); + apply(&ctx, egui::ThemePreference::Light); + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + if hebrew_font_data().is_some() { + assert!(hebrew_font_available(&ctx), "cached false must clear once fallback font is applied"); + } + } } From 6eb55808b003a6dc7817a1f8348360460dcd0df5 Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Sat, 21 Nov 2026 23:00:10 +0200 Subject: [PATCH 08/13] i18n(he): hide Pseudo from picker/persistence, tighten helper visibility, and recurse catalog coverage test --- apps/projectcraft/src/settings.rs | 3 ++ crates/ui-egui/src/i18n.rs | 57 ++++++++++++++++--------- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/tests/language_picker.rs | 1 + 4 files changed, 41 insertions(+), 22 deletions(-) diff --git a/apps/projectcraft/src/settings.rs b/apps/projectcraft/src/settings.rs index 1c1dab1..6243284 100644 --- a/apps/projectcraft/src/settings.rs +++ b/apps/projectcraft/src/settings.rs @@ -128,6 +128,9 @@ pub fn save_language(lang: Lang) { } fn save_language_to(file: &std::path::Path, lang: Lang) { + if lang == Lang::Pseudo { + return; + } let body = format!("{}\n", lang.code()); let result = file .parent() diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 2c42303..f8e19bc 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -79,7 +79,8 @@ pub fn current() -> Lang { /// Whether `code` names a right-to-left language or ISO 15924 script (normalizing legacy `iw` to /// `he`, ignoring private-use `x-*` tags, and honoring an explicit script subtag after any /// 3-letter extlang subtags). -pub fn is_rtl_code(code: &str) -> bool { +#[cfg(test)] +fn is_rtl_code(code: &str) -> bool { let cleaned = code.trim().split(['.', '@']).next().unwrap_or_default().replace('_', "-").to_ascii_lowercase(); let mut parts = cleaned.split('-').filter(|p| !p.is_empty()); let Some(base) = parts.next() else { @@ -138,15 +139,11 @@ fn hebrew_catalog() -> &'static HebrewCatalog { } /// Recover the logical string for a catalog entry when `s` was visually reordered for `lang`. -pub fn logical_of_for(lang: Lang, s: &str) -> &str { +#[cfg(test)] +fn logical_of_for(lang: Lang, s: &str) -> &str { if lang.is_rtl() { hebrew_catalog().visual_to_logical.get(s).copied().unwrap_or(s) } else { s } } -/// Recover the logical string for a catalog entry when `s` was visually reordered for RTL. -pub fn logical_of(s: &str) -> &str { - logical_of_for(current(), s) -} - fn is_combining_cluster_continuation(ch: char) -> bool { matches!(u32::from(ch), 0x0300..=0x036F | 0x0591..=0x05C7 | 0x200C..=0x200D | 0xFE00..=0xFE0F) } @@ -248,7 +245,7 @@ fn wrap_paragraph_logical<'a>(ctx: &egui::Context, paragraph: &'a str, font_id: /// Break `logical` text at `max_width` first using original logical substrings, then apply visual /// RTL ordering to each display row containing RTL characters. -pub fn wrapped_visual_lines(ctx: &egui::Context, lang: Lang, logical: &str, font_id: egui::FontId, max_width: f32) -> String { +fn wrapped_visual_lines(ctx: &egui::Context, lang: Lang, logical: &str, font_id: egui::FontId, max_width: f32) -> String { if !lang.is_rtl() || !logical.chars().any(is_rtl_script) { return logical.to_owned(); } @@ -271,12 +268,12 @@ pub fn wrapped_visual_lines(ctx: &egui::Context, lang: Lang, logical: &str, font } /// Render a **logical-order** wrapping label for an explicit `lang` (for example from -/// [`t_logical_for`] / [`tl_logical!`] or [`fmt_logical`]), deferring visual RTL reordering until +/// `t_logical_for` / [`tl_logical!`] or [`fmt_logical`]), deferring visual RTL reordering until /// after egui line breaks are measured. /// /// Callers must pass logical text rather than already-reordered strings from [`t`] / [`fmt`] so /// formatted outputs are never double-reordered. -pub fn wrapped_label_for(ui: &mut egui::Ui, lang: Lang, logical: &str, style: impl FnOnce(egui::RichText) -> egui::RichText) -> egui::Response { +fn wrapped_label_for(ui: &mut egui::Ui, lang: Lang, logical: &str, style: impl FnOnce(egui::RichText) -> egui::RichText) -> egui::Response { let font_id = egui::TextStyle::Body.resolve(ui.style()); let needs_rtl_wrap = lang.is_rtl() && logical.chars().any(is_rtl_script); let shown = @@ -295,8 +292,8 @@ pub fn wrapped_label(ui: &mut egui::Ui, logical: &str, style: impl FnOnce(egui:: wrapped_label_for(ui, current(), logical, style) } -/// `s` in `lang` in logical text order (for [`wrapped_label_for`] and [`fmt_logical_for`]). -pub fn t_logical_for(lang: Lang, s: &str) -> &str { +/// `s` in `lang` in logical text order (for `wrapped_label_for` and `fmt_logical_for`). +fn t_logical_for(lang: Lang, s: &str) -> &str { match lang { Lang::English => s, Lang::Pseudo => pseudo(s), @@ -310,7 +307,7 @@ pub fn t_logical(s: &str) -> &str { } /// `s` in `lang` (in visual RTL order for egui 0.36 when [`Lang::Hebrew`] is passed). -pub fn t_for(lang: Lang, s: &str) -> &str { +fn t_for(lang: Lang, s: &str) -> &str { match lang { Lang::English => s, Lang::Pseudo => pseudo(s), @@ -366,7 +363,7 @@ fn pseudo(s: &str) -> &'static str { /// Fill `{name}` placeholders in `template` for `lang`, keeping logical text order (for /// row-aware wrapping in [`wrapped_label`]). -pub fn fmt_logical_for(lang: Lang, template: &str, args: &[(&str, &str)]) -> String { +fn fmt_logical_for(lang: Lang, template: &str, args: &[(&str, &str)]) -> String { let source = if lang == Lang::Hebrew { hebrew_catalog().visual_to_logical.get(template).copied().unwrap_or(template) } else { template }; fill_placeholders(source, args) } @@ -378,7 +375,7 @@ pub fn fmt_logical(template: &str, args: &[(&str, &str)]) -> String { /// Fill `{name}` placeholders in `template` for `lang`. When [`Lang::Hebrew`] is selected, /// recovers the logical template before substituting so inserted values reorder cleanly for egui 0.36. -pub fn fmt_for(lang: Lang, template: &str, args: &[(&str, &str)]) -> String { +fn fmt_for(lang: Lang, template: &str, args: &[(&str, &str)]) -> String { let out = fmt_logical_for(lang, template, args); if lang == Lang::Hebrew { visual_rtl(&out) } else { out } } @@ -482,21 +479,39 @@ mod tests { assert!(!Lang::English.is_rtl()); } + fn collect_rs_files(dir: &std::path::Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + collect_rs_files(&path, out); + } else if path.extension().and_then(|e| e.to_str()) == Some("rs") { + out.push(path); + } + } + } + #[test] fn hebrew_catalog_covers_every_ui_string_and_keeps_placeholders() { let catalog = parsed_hebrew_rows(); let src_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut files = Vec::new(); + collect_rs_files(&src_dir, &mut files); let mut required = BTreeSet::new(); - for entry in std::fs::read_dir(&src_dir).unwrap() { - let path = entry.unwrap().path(); - if path.extension().and_then(|e| e.to_str()) != Some("rs") { - continue; - } + for path in files { let text = std::fs::read_to_string(&path).unwrap(); - for prefix in ["tl!(\"", "tl_logical!(\""] { + for prefix in ["tl!(", "tl_logical!("] { let mut rest = text.as_str(); while let Some(at) = rest.find(prefix) { + let prev = rest[..at].chars().next_back(); rest = &rest[at + prefix.len()..]; + if matches!(prev, Some(c) if c == '"' || c.is_ascii_alphanumeric() || c == '_') { + continue; + } + rest = rest.trim_start(); + if !rest.starts_with('"') { + continue; + } + rest = &rest[1..]; let mut lit = String::new(); let mut chars = rest.chars(); let mut esc = false; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6ef44ac..f180f77 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -880,7 +880,7 @@ impl App { let active = i18n::current(); let hebrew_ok = theme::hebrew_font_available(ui.ctx()); for lang in i18n::Lang::ALL { - if lang == i18n::Lang::Hebrew && !hebrew_ok { + if lang == i18n::Lang::Pseudo || (lang == i18n::Lang::Hebrew && !hebrew_ok) { continue; } if ui.radio(active == lang, lang.name()).clicked() { diff --git a/crates/ui-egui/tests/language_picker.rs b/crates/ui-egui/tests/language_picker.rs index e45cbae..36ae50d 100644 --- a/crates/ui-egui/tests/language_picker.rs +++ b/crates/ui-egui/tests/language_picker.rs @@ -13,6 +13,7 @@ fn view_language_menu_selects_hebrew_and_switches_back() { h.run_steps(2); h.get_by_label("Language ⏵").click(); h.run_steps(2); + assert!(h.query_by_label("Pseudo").is_none(), "test-only Pseudo language must not appear in View -> Language"); if !theme::hebrew_font_available(&h.ctx) { assert!(h.query_by_label("עברית").is_none(), "Hebrew must stay hidden when no Hebrew font is installed"); return; From 92b66fc942cc0f7e10f73c670a6b0a50b56fd284 Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Sun, 22 Nov 2026 01:50:34 +0200 Subject: [PATCH 09/13] i18n(he): expand combining-mark cluster table, distinguish Undo from Cancel, and accept Hebrew typed sheet inputs --- crates/ui-egui/src/i18n.rs | 34 +++++++++++++++++++++++++---- crates/ui-egui/src/i18n/he.tsv | 2 +- crates/ui-egui/src/lib.rs | 39 ++++++++++++++++++++++++++++------ 3 files changed, 64 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index f8e19bc..df97b5a 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -145,7 +145,29 @@ fn logical_of_for(lang: Lang, s: &str) -> &str { } fn is_combining_cluster_continuation(ch: char) -> bool { - matches!(u32::from(ch), 0x0300..=0x036F | 0x0591..=0x05C7 | 0x200C..=0x200D | 0xFE00..=0xFE0F) + matches!( + u32::from(ch), + 0x0300..=0x036F + | 0x0591..=0x05C7 + | 0x0610..=0x061A + | 0x064B..=0x065F + | 0x0670 + | 0x06D6..=0x06DC + | 0x06DF..=0x06E4 + | 0x06E7..=0x06E8 + | 0x06EA..=0x06ED + | 0x0711 + | 0x0730..=0x074A + | 0x07A6..=0x07B0 + | 0x07EB..=0x07F3 + | 0x07FD + | 0x1AB0..=0x1AFF + | 0x1DC0..=0x1DFF + | 0x200C..=0x200D + | 0xFE00..=0xFE0F + | 0xFE20..=0xFE2F + | 0x1_E944..=0x1_E94A + ) } fn measure_no_wrap(ctx: &egui::Context, text: &str, font_id: &egui::FontId) -> f32 { @@ -657,8 +679,8 @@ mod tests { assert_eq!(visual_rtl("(*.projectcraft), וכן"), "וכן ,(*.projectcraft)"); assert_eq!(visual_rtl("(*.projectcraft),"), "(*.projectcraft),"); // Visual-to-logical recovery must never collide between two distinct logical translations, - // and duplicate Hebrew translations (e.g. Cancel/Undo -> ביטול) must keep their Hebrew - // logical string rather than colliding on English keys. + // and any duplicate Hebrew translations must preserve their shared Hebrew logical string + // rather than colliding on English keys. let mut seen_visual: HashMap = HashMap::new(); for (k, logical) in parsed_hebrew_rows() { let vis = visual_rtl(&logical); @@ -667,10 +689,14 @@ mod tests { } } assert_eq!(t_logical_for(Lang::Hebrew, "Cancel"), "ביטול"); - assert_eq!(t_logical_for(Lang::Hebrew, "Undo"), "ביטול"); + assert_eq!(t_logical_for(Lang::Hebrew, "Undo"), "ביטול פעולה"); assert_eq!(logical_of_for(Lang::Hebrew, t_for(Lang::Hebrew, "Cancel")), "ביטול"); + assert_eq!(logical_of_for(Lang::Hebrew, t_for(Lang::Hebrew, "Undo")), "ביטול פעולה"); assert_eq!(fmt_for(Lang::Hebrew, t_for(Lang::Hebrew, "Cancel"), &[]), "ביטול"); assert_eq!(t_for(Lang::Hebrew, ""), ""); + for ch in ['\u{05BC}', '\u{064E}', '\u{0730}', '\u{07A6}', '\u{07EB}', '\u{1E944}'] { + assert!(is_combining_cluster_continuation(ch), "expected combining mark U+{:04X}", u32::from(ch)); + } } #[test] diff --git a/crates/ui-egui/src/i18n/he.tsv b/crates/ui-egui/src/i18n/he.tsv index c5299a4..b0489c9 100644 --- a/crates/ui-egui/src/i18n/he.tsv +++ b/crates/ui-egui/src/i18n/he.tsv @@ -221,7 +221,7 @@ Type סוג Type Fixed Units, Fixed Duration or Fixed Work. הקלד יחידות קבועות, משך קבוע או עבודה קבועה (או Fixed Units / Fixed Duration / Fixed Work). Type Yes or No. הקלד כן או לא (Yes / No). Type a priority from 0 to 1000. הקלד עדיפות בין 0 ל-1000. -Undo ביטול +Undo ביטול פעולה Units יחידות Units and work shown are for {name}. היחידות והעבודה המוצגות הן עבור {name}. Units: a decimal for people and equipment (0.5, or 50%); for materials a quantity (5 tons) or a rate (2 tons/d). יחידות: מספר עשרוני לאנשים ולציוד (0.5 או 50%); לחומרים כמות (5 tons) או קצב (2 tons/d). diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f180f77..8d42350 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -145,19 +145,29 @@ fn shown_cell(sheet: &SheetText, row: usize, field: Field) -> (String, bool) { } } -/// Typed Effort Driven text: yes or no (or the start of either, or true, false, 1, 0), any case. +/// Typed Effort Driven text: yes or no (or the start of either, or true, false, 1, 0, כן, לא), any case. fn typed_yes_no(text: &str) -> Option { let t = text.trim().to_lowercase(); match t.as_str() { "" => None, - "true" | "1" => Some(true), - "false" | "0" => Some(false), + "true" | "1" | "כן" => Some(true), + "false" | "0" | "לא" => Some(false), _ if "yes".starts_with(&t) => Some(true), _ if "no".starts_with(&t) => Some(false), _ => None, } } +/// Typed task type text: English names/prefixes (`TaskType::from_name`) or Hebrew labels. +fn typed_task_type(text: &str) -> Option { + match text.trim() { + "יחידות קבועות" => Some(TaskType::FixedUnits), + "משך קבוע" => Some(TaskType::FixedDuration), + "עבודה קבועה" => Some(TaskType::FixedWork), + _ => TaskType::from_name(text).ok(), + } +} + /// The command a typed Start or Finish issues: Start No Earlier Than or Finish No Earlier Than /// that date. The cell keeps showing the scheduler's date, as in Microsoft Project. A typed /// Deadline sets the deadline; an empty one clears it. @@ -781,11 +791,11 @@ impl App { Field::Work => { self.run("task.setWork", json!({"id": id.0, "work": text.trim()})); } - Field::Type => match TaskType::from_name(&text) { - Ok(ty) => { + Field::Type => match typed_task_type(&text) { + Some(ty) => { self.run("task.setType", json!({"id": id.0, "type": ty.name()})); } - Err(_) => self.status = tl!("Type Fixed Units, Fixed Duration or Fixed Work.").to_owned(), + None => self.status = tl!("Type Fixed Units, Fixed Duration or Fixed Work.").to_owned(), }, Field::EffortDriven => match typed_yes_no(&text) { Some(on) => { @@ -2297,4 +2307,21 @@ mod tests { app.set_language(i18n::Lang::English); assert_eq!(app.take_language_changed(), Some(i18n::Lang::English)); } + + #[test] + fn typed_yes_no_and_task_type_accept_hebrew_and_english_inputs() { + assert_eq!(typed_yes_no("כן"), Some(true)); + assert_eq!(typed_yes_no("לא"), Some(false)); + assert_eq!(typed_yes_no("yes"), Some(true)); + assert_eq!(typed_yes_no("no"), Some(false)); + assert_eq!(typed_yes_no("1"), Some(true)); + assert_eq!(typed_yes_no("0"), Some(false)); + assert_eq!(typed_yes_no("maybe"), None); + + assert_eq!(typed_task_type("יחידות קבועות"), Some(TaskType::FixedUnits)); + assert_eq!(typed_task_type("משך קבוע"), Some(TaskType::FixedDuration)); + assert_eq!(typed_task_type("עבודה קבועה"), Some(TaskType::FixedWork)); + assert_eq!(typed_task_type("Fixed Work"), Some(TaskType::FixedWork)); + assert_eq!(typed_task_type("Fixed Cost"), None); + } } From 9c2d62dcc41b33e67e3fbb34b6a028f75c77d879 Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Sun, 22 Nov 2026 05:46:40 +0200 Subject: [PATCH 10/13] M6: recover logical order in options error label and read typed Hebrew task types from catalog --- crates/ui-egui/src/i18n.rs | 18 ++++++++++++++++-- crates/ui-egui/src/lib.rs | 10 +++------- crates/ui-egui/src/options.rs | 2 +- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index df97b5a..ef7a625 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -139,11 +139,15 @@ fn hebrew_catalog() -> &'static HebrewCatalog { } /// Recover the logical string for a catalog entry when `s` was visually reordered for `lang`. -#[cfg(test)] fn logical_of_for(lang: Lang, s: &str) -> &str { if lang.is_rtl() { hebrew_catalog().visual_to_logical.get(s).copied().unwrap_or(s) } else { s } } +/// Recover the logical string for a catalog entry when `s` was visually reordered for the active language. +pub fn logical_of(s: &str) -> &str { + logical_of_for(current(), s) +} + fn is_combining_cluster_continuation(ch: char) -> bool { matches!( u32::from(ch), @@ -315,7 +319,7 @@ pub fn wrapped_label(ui: &mut egui::Ui, logical: &str, style: impl FnOnce(egui:: } /// `s` in `lang` in logical text order (for `wrapped_label_for` and `fmt_logical_for`). -fn t_logical_for(lang: Lang, s: &str) -> &str { +pub fn t_logical_for(lang: Lang, s: &str) -> &str { match lang { Lang::English => s, Lang::Pseudo => pseudo(s), @@ -782,5 +786,15 @@ mod tests { .textures_delta .clear(); assert!(oversized_rect.width() <= 225.0, "oversized word must split within dialog width, got {oversized_rect:?}"); + + // Validation errors stored via `tl!` must recover logical order before `wrapped_label` + // wraps and reorders each line. + let stored_err = t_for(Lang::Hebrew, "Hours per day must be 1 to 24, in whole minutes (such as 7.5)."); + let recovered_err = logical_of_for(Lang::Hebrew, stored_err); + let wrapped_err = wrapped_visual_lines(&ctx, Lang::Hebrew, recovered_err, egui::FontId::proportional(14.0), 180.0); + let err_lines: Vec<&str> = wrapped_err.lines().collect(); + assert!(err_lines.len() >= 2, "expected wrapped validation error, got {wrapped_err:?}"); + assert!(err_lines[0].contains("מספר"), "first row should start with opening word: {err_lines:?}"); + assert!(err_lines.last().unwrap().contains("7.5)."), "last row should keep closing example: {err_lines:?}"); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8d42350..3707c49 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -158,14 +158,10 @@ fn typed_yes_no(text: &str) -> Option { } } -/// Typed task type text: English names/prefixes (`TaskType::from_name`) or Hebrew labels. +/// Typed task type text: English names/prefixes (`TaskType::from_name`) or Hebrew catalog labels. fn typed_task_type(text: &str) -> Option { - match text.trim() { - "יחידות קבועות" => Some(TaskType::FixedUnits), - "משך קבוע" => Some(TaskType::FixedDuration), - "עבודה קבועה" => Some(TaskType::FixedWork), - _ => TaskType::from_name(text).ok(), - } + let trimmed = text.trim(); + TaskType::ALL.into_iter().find(|ty| i18n::t_logical_for(i18n::Lang::Hebrew, ty.name()) == trimmed).or_else(|| TaskType::from_name(text).ok()) } /// The command a typed Start or Finish issues: Start No Earlier Than or Finish No Earlier Than diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index a1509df..2d06f55 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.rs @@ -213,7 +213,7 @@ impl App { crate::i18n::wrapped_label(ui, example, |r| r.color(t.text_dim)); if !error.is_empty() { ui.add_space(6.0); - crate::i18n::wrapped_label(ui, error.as_str(), |r| r.color(t.warning)); + crate::i18n::wrapped_label(ui, crate::i18n::logical_of(error.as_str()), |r| r.color(t.warning)); } ui.add_space(10.0); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { From a5314c5db4b58c212225e436f336a9e9a45bc902 Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Sun, 22 Nov 2026 09:52:30 +0200 Subject: [PATCH 11/13] M6: normalize visual Hebrew task type inputs and validate fallback font headers --- crates/ui-egui/src/i18n.rs | 4 +-- crates/ui-egui/src/lib.rs | 10 ++++-- crates/ui-egui/src/theme.rs | 70 +++++++++++++++++++++++++++++-------- 3 files changed, 64 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index ef7a625..4cb1e09 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -139,7 +139,7 @@ fn hebrew_catalog() -> &'static HebrewCatalog { } /// Recover the logical string for a catalog entry when `s` was visually reordered for `lang`. -fn logical_of_for(lang: Lang, s: &str) -> &str { +pub fn logical_of_for(lang: Lang, s: &str) -> &str { if lang.is_rtl() { hebrew_catalog().visual_to_logical.get(s).copied().unwrap_or(s) } else { s } } @@ -333,7 +333,7 @@ pub fn t_logical(s: &str) -> &str { } /// `s` in `lang` (in visual RTL order for egui 0.36 when [`Lang::Hebrew`] is passed). -fn t_for(lang: Lang, s: &str) -> &str { +pub fn t_for(lang: Lang, s: &str) -> &str { match lang { Lang::English => s, Lang::Pseudo => pseudo(s), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3707c49..b7e11fb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -158,10 +158,11 @@ fn typed_yes_no(text: &str) -> Option { } } -/// Typed task type text: English names/prefixes (`TaskType::from_name`) or Hebrew catalog labels. +/// Typed task type text: English names/prefixes (`TaskType::from_name`), Hebrew logical catalog +/// labels, or visually reordered Hebrew labels pre-filled from [`shown_cell`]. fn typed_task_type(text: &str) -> Option { - let trimmed = text.trim(); - TaskType::ALL.into_iter().find(|ty| i18n::t_logical_for(i18n::Lang::Hebrew, ty.name()) == trimmed).or_else(|| TaskType::from_name(text).ok()) + let logical = i18n::logical_of_for(i18n::Lang::Hebrew, text.trim()); + TaskType::ALL.into_iter().find(|ty| i18n::t_logical_for(i18n::Lang::Hebrew, ty.name()) == logical).or_else(|| TaskType::from_name(text).ok()) } /// The command a typed Start or Finish issues: Start No Earlier Than or Finish No Earlier Than @@ -2317,6 +2318,9 @@ mod tests { assert_eq!(typed_task_type("יחידות קבועות"), Some(TaskType::FixedUnits)); assert_eq!(typed_task_type("משך קבוע"), Some(TaskType::FixedDuration)); assert_eq!(typed_task_type("עבודה קבועה"), Some(TaskType::FixedWork)); + assert_eq!(typed_task_type(i18n::t_for(i18n::Lang::Hebrew, "Fixed Units")), Some(TaskType::FixedUnits)); + assert_eq!(typed_task_type(i18n::t_for(i18n::Lang::Hebrew, "Fixed Duration")), Some(TaskType::FixedDuration)); + assert_eq!(typed_task_type(i18n::t_for(i18n::Lang::Hebrew, "Fixed Work")), Some(TaskType::FixedWork)); assert_eq!(typed_task_type("Fixed Work"), Some(TaskType::FixedWork)); assert_eq!(typed_task_type("Fixed Cost"), None); } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 80a0bd1..8dc1525 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -166,19 +166,36 @@ pub fn hebrew_font_available(ctx: &egui::Context) -> bool { } #[cfg(not(target_arch = "wasm32"))] -fn hebrew_font_data() -> Option { - for env_var in ["PROJECTCRAFT_FONT_DIR", "CRAFT_FONTS_DIR"] { - if let Ok(dir) = std::env::var(env_var) { - let trimmed = dir.trim(); - if !trimmed.is_empty() { - let candidate = std::path::Path::new(trimmed).join("NotoSansHebrew-Regular.ttf"); - if let Ok(bytes) = std::fs::read(candidate) { - return Some(egui::FontData::from_owned(bytes)); - } +fn is_valid_font_bytes(bytes: &[u8]) -> bool { + matches!(bytes.get(..4), Some([0x00, 0x01, 0x00, 0x00] | b"OTTO" | b"true" | b"ttcf")) +} + +#[cfg(not(target_arch = "wasm32"))] +fn read_valid_font(path: &std::path::Path) -> Option { + let bytes = std::fs::read(path).ok()?; + if !is_valid_font_bytes(&bytes) { + eprintln!("note: skipping invalid Hebrew fallback font file: {}", path.display()); + return None; + } + Some(egui::FontData::from_owned(bytes)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn hebrew_font_data_from(env_dirs: &[Option], candidates: &[&str]) -> Option { + for dir in env_dirs.iter().flatten() { + let trimmed = dir.trim(); + if !trimmed.is_empty() { + let candidate = std::path::Path::new(trimmed).join("NotoSansHebrew-Regular.ttf"); + if let Some(data) = read_valid_font(&candidate) { + return Some(data); } } } + candidates.iter().find_map(|path| read_valid_font(std::path::Path::new(path))) +} +#[cfg(not(target_arch = "wasm32"))] +fn hebrew_font_data() -> Option { #[cfg(target_os = "macos")] const CANDIDATES: &[&str] = &[ "/System/Library/Fonts/SFHebrew.ttf", @@ -204,12 +221,8 @@ fn hebrew_font_data() -> Option { #[cfg(not(any(unix, windows)))] const CANDIDATES: &[&str] = &[]; - for path in CANDIDATES { - if let Ok(bytes) = std::fs::read(path) { - return Some(egui::FontData::from_owned(bytes)); - } - } - None + let env_dirs = [std::env::var("PROJECTCRAFT_FONT_DIR").ok(), std::env::var("CRAFT_FONTS_DIR").ok()]; + hebrew_font_data_from(&env_dirs, CANDIDATES) } #[cfg(target_arch = "wasm32")] @@ -347,4 +360,31 @@ mod tests { assert!(hebrew_font_available(&ctx), "cached false must clear once fallback font is applied"); } } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn corrupt_font_candidate_is_skipped_and_falls_through() { + assert!(!is_valid_font_bytes(b"")); + assert!(!is_valid_font_bytes(b"not a font")); + assert!(is_valid_font_bytes(&[0x00, 0x01, 0x00, 0x00, 0x00])); + assert!(is_valid_font_bytes(b"OTTO\0\0")); + assert!(is_valid_font_bytes(b"ttcf\0\0")); + + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let dir = std::env::temp_dir().join(format!("projectcraft-bogus-font-dir-{nanos}")); + std::fs::create_dir_all(&dir).expect("create temp font dir"); + std::fs::write(dir.join("NotoSansHebrew-Regular.ttf"), b"truncated").expect("write bogus env font"); + let bad_candidate = dir.join("bad.ttf"); + std::fs::write(&bad_candidate, b"html-not-a-font").expect("write bogus candidate"); + let good_candidate = dir.join("good.ttf"); + std::fs::write(&good_candidate, [0x00, 0x01, 0x00, 0x00, 0x00, 0x0C]).expect("write sfnt header"); + + let env_dir = dir.to_string_lossy().into_owned(); + let bad_str = bad_candidate.to_string_lossy().into_owned(); + let good_str = good_candidate.to_string_lossy().into_owned(); + assert!(hebrew_font_data_from(&[Some(env_dir.clone())], &[&bad_str]).is_none()); + let fell_through = hebrew_font_data_from(&[Some(env_dir)], &[&bad_str, &good_str]); + assert!(fell_through.is_some(), "valid candidate after invalid env/candidate files should be selected"); + let _ = std::fs::remove_dir_all(&dir); + } } From 6429a29d338898b5525f82fcad857a7d6cc6f4f5 Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Sun, 22 Nov 2026 14:14:57 +0200 Subject: [PATCH 12/13] M6: preserve Hebrew preference on automatic fallback, validate full font parsing, and split fallback test --- crates/ui-egui/src/i18n.rs | 3 +- crates/ui-egui/src/lib.rs | 3 +- crates/ui-egui/src/theme.rs | 126 ++++++++++++++++++++++-- crates/ui-egui/tests/language_picker.rs | 22 +++-- 4 files changed, 138 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 4cb1e09..97a9dff 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -79,8 +79,7 @@ pub fn current() -> Lang { /// Whether `code` names a right-to-left language or ISO 15924 script (normalizing legacy `iw` to /// `he`, ignoring private-use `x-*` tags, and honoring an explicit script subtag after any /// 3-letter extlang subtags). -#[cfg(test)] -fn is_rtl_code(code: &str) -> bool { +pub fn is_rtl_code(code: &str) -> bool { let cleaned = code.trim().split(['.', '@']).next().unwrap_or_default().replace('_', "-").to_ascii_lowercase(); let mut parts = cleaned.split('-').filter(|p| !p.is_empty()); let Some(base) = parts.next() else { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b7e11fb..a61ce8d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -457,8 +457,9 @@ impl App { self.themed = Some(self.appearance); } if i18n::current() == i18n::Lang::Hebrew && !theme::hebrew_font_available(&ctx) { + // Fall back to English for this session without marking `language_changed` so the + // user's saved or locale-derived Hebrew preference is not overwritten. i18n::set_current(i18n::Lang::English); - self.language_changed = true; } self.file_keys(&ctx); let (undo, redo) = ctx.input_mut(|i| (i.consume_key(egui::Modifiers::COMMAND, Key::Z), i.consume_key(egui::Modifiers::COMMAND, Key::Y))); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 8dc1525..e46f9fc 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -139,10 +139,24 @@ fn hebrew_available_key() -> egui::Id { egui::Id::new("projectcraft_hebrew_fonts_available") } +fn hebrew_installed_key() -> egui::Id { + egui::Id::new("projectcraft_hebrew_fonts_installed") +} + fn hebrew_installed_pass_key() -> egui::Id { egui::Id::new("projectcraft_hebrew_fonts_installed_pass") } +/// Simulates an environment with no Hebrew-capable fallback font for integration tests without +/// duplicating internal cache keys. +#[doc(hidden)] +pub fn disable_hebrew_font_for_test(ctx: &egui::Context) { + ctx.data_mut(|d| { + d.insert_temp(hebrew_installed_key(), true); + d.insert_temp(hebrew_available_key(), false); + }); +} + fn has_hebrew_glyphs(ctx: &egui::Context) -> bool { ctx.fonts_mut(|fonts| fonts.has_glyph(&egui::FontId::proportional(14.0), 'א') && fonts.has_glyph(&egui::FontId::monospace(14.0), 'א')) } @@ -165,9 +179,96 @@ pub fn hebrew_font_available(ctx: &egui::Context) -> bool { available } +#[cfg(not(target_arch = "wasm32"))] +fn read_be_u16(bytes: &[u8], offset: usize) -> Option { + let slice = bytes.get(offset..offset + 2)?; + Some(u16::from_be_bytes([slice[0], slice[1]])) +} + +#[cfg(not(target_arch = "wasm32"))] +fn read_be_u32(bytes: &[u8], offset: usize) -> Option { + let slice = bytes.get(offset..offset + 4)?; + Some(u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]])) +} + +#[cfg(not(target_arch = "wasm32"))] +fn has_valid_sfnt_at(bytes: &[u8], offset: usize) -> bool { + let Some(magic) = bytes.get(offset..offset + 4) else { + return false; + }; + if !matches!(magic, [0x00, 0x01, 0x00, 0x00] | b"OTTO" | b"true") { + return false; + } + let Some(num_tables) = read_be_u16(bytes, offset + 4).map(usize::from) else { + return false; + }; + if num_tables == 0 { + return false; + } + let Some(dir_end) = offset.checked_add(12).and_then(|s| s.checked_add(num_tables * 16)) else { + return false; + }; + if dir_end > bytes.len() { + return false; + } + let mut has_valid_head = false; + for i in 0..num_tables { + let rec = offset + 12 + i * 16; + let Some(tag) = bytes.get(rec..rec + 4) else { + return false; + }; + let Some(tbl_off) = read_be_u32(bytes, rec + 8).and_then(|v| usize::try_from(v).ok()) else { + return false; + }; + let Some(tbl_len) = read_be_u32(bytes, rec + 12).and_then(|v| usize::try_from(v).ok()) else { + return false; + }; + let Some(tbl_end) = tbl_off.checked_add(tbl_len) else { + return false; + }; + if tbl_end > bytes.len() { + return false; + } + if tag == b"head" { + if tbl_len < 54 || read_be_u32(bytes, tbl_off + 12) != Some(0x5F0F_3CF5) { + return false; + } + has_valid_head = true; + } + } + has_valid_head +} + +#[cfg(not(target_arch = "wasm32"))] +fn has_valid_sfnt_structure(bytes: &[u8]) -> bool { + if bytes.get(..4) == Some(b"ttcf") { + let Some(num_fonts) = read_be_u32(bytes, 8).and_then(|v| usize::try_from(v).ok()) else { + return false; + }; + if num_fonts == 0 { + return false; + } + let Some(first_offset) = read_be_u32(bytes, 12).and_then(|v| usize::try_from(v).ok()) else { + return false; + }; + return has_valid_sfnt_at(bytes, first_offset); + } + has_valid_sfnt_at(bytes, 0) +} + #[cfg(not(target_arch = "wasm32"))] fn is_valid_font_bytes(bytes: &[u8]) -> bool { - matches!(bytes.get(..4), Some([0x00, 0x01, 0x00, 0x00] | b"OTTO" | b"true" | b"ttcf")) + if !has_valid_sfnt_structure(bytes) { + return false; + } + let mut defs = egui::FontDefinitions::empty(); + defs.font_data.insert("hebrew-probe".to_owned(), std::sync::Arc::new(egui::FontData::from_owned(bytes.to_vec()))); + // Parse through epaint's loader so truncated/corrupt faces are skipped rather than panicking + // during FontDefinitions initialization. + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = egui::epaint::text::FontsImpl::new(egui::epaint::text::TextOptions::default(), defs); + })) + .is_ok() } #[cfg(not(target_arch = "wasm32"))] @@ -240,7 +341,7 @@ fn apply_hebrew_fallback(fonts: &mut egui::FontDefinitions, font_data: egui::Fon } fn install_hebrew_fonts(ctx: &egui::Context) { - let key = egui::Id::new("projectcraft_hebrew_fonts_installed"); + let key = hebrew_installed_key(); if ctx.data(|d| d.get_temp::(key)) == Some(true) { return; } @@ -364,20 +465,31 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn corrupt_font_candidate_is_skipped_and_falls_through() { + let valid_data = egui::FontDefinitions::default().font_data.into_values().next().expect("default egui font data present"); + let valid_bytes = valid_data.font.as_ref(); + assert!(is_valid_font_bytes(valid_bytes)); assert!(!is_valid_font_bytes(b"")); assert!(!is_valid_font_bytes(b"not a font")); - assert!(is_valid_font_bytes(&[0x00, 0x01, 0x00, 0x00, 0x00])); - assert!(is_valid_font_bytes(b"OTTO\0\0")); - assert!(is_valid_font_bytes(b"ttcf\0\0")); + // Truncated header or truncated real font bytes must fail validation. + assert!(!is_valid_font_bytes(&[0x00, 0x01, 0x00, 0x00, 0x00, 0x01])); + assert!(!is_valid_font_bytes(&valid_bytes[..valid_bytes.len() / 2])); + // Structurally valid SFNT directory pointing at a corrupt `head` table must fail too. + let mut corrupt_sfnt = vec![0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00]; + corrupt_sfnt.extend_from_slice(b"head"); + corrupt_sfnt.extend_from_slice(&[0u8; 4]); + corrupt_sfnt.extend_from_slice(&28u32.to_be_bytes()); + corrupt_sfnt.extend_from_slice(&4u32.to_be_bytes()); + corrupt_sfnt.extend_from_slice(&[0xFF; 4]); + assert!(!is_valid_font_bytes(&corrupt_sfnt)); let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); let dir = std::env::temp_dir().join(format!("projectcraft-bogus-font-dir-{nanos}")); std::fs::create_dir_all(&dir).expect("create temp font dir"); std::fs::write(dir.join("NotoSansHebrew-Regular.ttf"), b"truncated").expect("write bogus env font"); let bad_candidate = dir.join("bad.ttf"); - std::fs::write(&bad_candidate, b"html-not-a-font").expect("write bogus candidate"); + std::fs::write(&bad_candidate, &valid_bytes[..valid_bytes.len() / 2]).expect("write truncated candidate"); let good_candidate = dir.join("good.ttf"); - std::fs::write(&good_candidate, [0x00, 0x01, 0x00, 0x00, 0x00, 0x0C]).expect("write sfnt header"); + std::fs::write(&good_candidate, valid_bytes).expect("write valid font"); let env_dir = dir.to_string_lossy().into_owned(); let bad_str = bad_candidate.to_string_lossy().into_owned(); diff --git a/crates/ui-egui/tests/language_picker.rs b/crates/ui-egui/tests/language_picker.rs index 36ae50d..88b1e97 100644 --- a/crates/ui-egui/tests/language_picker.rs +++ b/crates/ui-egui/tests/language_picker.rs @@ -1,10 +1,17 @@ +use std::sync::Mutex; + use egui_kittest::kittest::Queryable; use projectcraft_ui_egui::App; use projectcraft_ui_egui::i18n::{self, Lang}; use projectcraft_ui_egui::theme; +static LANG_LOCK: Mutex<()> = Mutex::new(()); + #[test] fn view_language_menu_selects_hebrew_and_switches_back() { + let _guard = LANG_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + i18n::set_current(Lang::English); + let app = App::new(projectcraft_engine::sample(), None); let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 720.0)).build_ui_state(|ui, app: &mut App| app.ui(ui), app); h.run_steps(2); @@ -39,26 +46,29 @@ fn view_language_menu_selects_hebrew_and_switches_back() { assert_eq!(i18n::current(), Lang::English); assert_eq!(h.state_mut().take_language_changed(), Some(Lang::English)); let _ = h.get_by_label("Save"); +} - // When a host/wasm target has no Hebrew-capable font, Hebrew startup selection must fall back - // to English and the View -> Language menu must not offer עברית. +#[test] +fn hebrew_falls_back_to_english_without_persisting_when_font_missing() { + let _guard = LANG_LOCK.lock().unwrap_or_else(|e| e.into_inner()); i18n::set_current(Lang::Hebrew); + let app_no_font = App::new(projectcraft_engine::sample(), None); let mut h_no_font = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 720.0)).build_ui_state( |ui, app: &mut App| { - ui.ctx().data_mut(|d| { - d.insert_temp(egui::Id::new("projectcraft_hebrew_fonts_installed"), true); - d.insert_temp(egui::Id::new("projectcraft_hebrew_fonts_available"), false); - }); + theme::disable_hebrew_font_for_test(ui.ctx()); app.ui(ui); }, app_no_font, ); h_no_font.run_steps(2); assert_eq!(i18n::current(), Lang::English); + assert_eq!(h_no_font.state_mut().take_language_changed(), None, "automatic fallback must not overwrite saved Hebrew preference"); h_no_font.get_by_label("View").click(); h_no_font.run_steps(2); h_no_font.get_by_label("Language ⏵").click(); h_no_font.run_steps(2); assert!(h_no_font.query_by_label("עברית").is_none(), "Hebrew must not be selectable without Hebrew glyphs"); + + i18n::set_current(Lang::English); } From 29787e9e70556eddea9c69085d9572a7cb898287 Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Thu, 26 Nov 2026 16:17:12 +0200 Subject: [PATCH 13/13] M6: classify Extended Arabic-Indic digits before RTL script, support variable NotoSansHebrew lookup, and refine Hebrew phrasing --- crates/ui-egui/src/i18n.rs | 3 +++ crates/ui-egui/src/i18n/bidi.rs | 15 +++++++++++---- crates/ui-egui/src/i18n/he.tsv | 32 ++++++++++++++++---------------- crates/ui-egui/src/theme.rs | 8 +++++--- 4 files changed, 35 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 97a9dff..946ee3a 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -677,6 +677,9 @@ mod tests { assert_eq!(visual_rtl("פרויקט ProjectCraft (100%)"), "ProjectCraft (100%) פרויקט"); assert_eq!(visual_rtl("שמור (Ctrl+O)"), "(Ctrl+O) שמור"); assert_eq!(visual_rtl("הכול הושלם (100%)"), "(100%) הושלם הכול"); + assert_eq!(visual_rtl("הושלם 123%"), "123% הושלם"); + assert_eq!(visual_rtl("הושלם ۱۲۳%"), "۱۲۳% הושלם"); + assert_eq!(visual_rtl("۱۲۳%"), "۱۲۳%"); assert_eq!(visual_rtl("(*.projectcraft), המיובאים"), "המיובאים ,(*.projectcraft)"); assert_eq!(visual_rtl("פרויקטים (*.projectcraft)"), "(*.projectcraft) פרויקטים"); assert_eq!(visual_rtl("(*.projectcraft), וכן"), "וכן ,(*.projectcraft)"); diff --git a/crates/ui-egui/src/i18n/bidi.rs b/crates/ui-egui/src/i18n/bidi.rs index 5069799..a6cd981 100644 --- a/crates/ui-egui/src/i18n/bidi.rs +++ b/crates/ui-egui/src/i18n/bidi.rs @@ -22,7 +22,14 @@ enum BidiClass { pub(super) fn is_rtl_script(c: char) -> bool { matches!( u32::from(c), - 0x0590..=0x05FF | 0x0600..=0x065F | 0x066E..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFC | 0x1_0800..=0x1_0FFF | 0x1_E800..=0x1_EFFF + 0x0590..=0x05FF + | 0x0600..=0x065F + | 0x066E..=0x06EF + | 0x06FA..=0x08FF + | 0xFB1D..=0xFDFF + | 0xFE70..=0xFEFC + | 0x1_0800..=0x1_0FFF + | 0x1_E800..=0x1_EFFF ) } @@ -120,10 +127,10 @@ pub(super) fn push_visual_rtl_line(line: &str, out: &mut String) { .iter() .map(|&c| { let is_placeholder = (PLACEHOLDER_BASE..PLACEHOLDER_BASE.saturating_add(MAX_PLACEHOLDERS as u32)).contains(&u32::from(c)); - if is_rtl_script(c) { - BidiClass::R - } else if is_bidi_digit(c) { + if is_bidi_digit(c) { BidiClass::En + } else if is_rtl_script(c) { + BidiClass::R } else if is_placeholder || c.is_alphabetic() || matches!(c, '\u{2318}' | '\u{21E7}' | '\u{2325}' | '\u{2303}') { BidiClass::L } else { diff --git a/crates/ui-egui/src/i18n/he.tsv b/crates/ui-egui/src/i18n/he.tsv index b0489c9..e882b64 100644 --- a/crates/ui-egui/src/i18n/he.tsv +++ b/crates/ui-egui/src/i18n/he.tsv @@ -72,13 +72,13 @@ Delete these working times מחיקת זמני עבודה אלה Discard ביטול השינויים Do you want to save the changes you made to {name}? האם לשמור את השינויים שביצעת ב-{name}? Doesn't apply to a {type} resource אינו חל על משאב מסוג {type} -Don't Save אל תשמור +Don't Save לא לשמור Dropped הושמט Duration משך Each working time must end after it starts. כל טווח עבודה חייב להסתיים לאחר שהוא מתחיל. Effort Driven מונחה מאמץ End סיום -Enter times as H:MM, such as 8:00 or 17:30. הזן שעות בתבנית H:MM, כגון 8:00 או 17:30. +Enter times as H:MM, such as 8:00 or 17:30. יש להזין שעות בתבנית H:MM, כגון 8:00 או 17:30. Everything in the file was imported. הכול בקובץ יובא בהצלחה. Exception hours שעות חריגה Exceptions חריגות @@ -139,11 +139,11 @@ No לא No costs ללא עלויות No folders or projects here. אין תיקיות או פרויקטים כאן. No resources assigned אין משאבים מוקצים -No resources yet. Add them in the Resource Sheet, or type a name in the Resource Names column. עדיין אין משאבים. הוסף אותם בגיליון המשאבים, או הקלד שם בעמודת שמות המשאבים. -No resources yet. Add them in the Resource Sheet. עדיין אין משאבים. הוסף אותם בגיליון המשאבים. -No resources yet. Press Insert or New Resource to add one. עדיין אין משאבים. לחץ Insert או על משאב חדש כדי להוסיף. +No resources yet. Add them in the Resource Sheet, or type a name in the Resource Names column. עדיין אין משאבים. יש להוסיף אותם בגיליון המשאבים, או להקליד שם בעמודת שמות המשאבים. +No resources yet. Add them in the Resource Sheet. עדיין אין משאבים. יש להוסיף אותם בגיליון המשאבים. +No resources yet. Press Insert or New Resource to add one. עדיין אין משאבים. יש ללחוץ על Insert או על "משאב חדש" כדי להוסיף. Non-working יום חופשי -Non-working: add working times to work this day. לא עובדים: הוסף שעות עבודה כדי לעבוד ביום זה. +Non-working: add working times to work this day. יום חופשי: יש להוסיף זמני עבודה כדי לעבוד ביום זה. None: every day follows its weekday. ללא: כל יום פועל לפי יום השבוע שלו. Not yet imported טרם יובא Nov נוב׳ @@ -154,7 +154,7 @@ Opened {path} נפתח: {path} Open… פתיחה… Options… אפשרויות… Overallocated: a resource on this task has more work than its Max Units allow on a day it works on it. עומס יתר: למשאב במשימה זו יש יותר עבודה מהמותר לפי היחידות המרביות שלו ביום עבודה עליה. -Overallocated: more work on some days than Max Units allow on this resource's calendar (see Resource Usage) עומס יתר: בימים מסוימים יש יותר עבודה מהמותר לפי היחידות המרביות בלוח המשאב (ראה שימוש במשאבים) +Overallocated: more work on some days than Max Units allow on this resource's calendar (see Resource Usage) עומס יתר: בימים מסוימים יש יותר עבודה מהמותר לפי היחידות המרביות בלוח המשאב (ר׳ שימוש במשאבים) Overallocated: red days have more work than Max Units allow on this resource's calendar עומס יתר: בימים אדומים יש יותר עבודה מהמותר לפי היחידות המרביות בלוח המשאב Ovt. Rate תעריף שעות נוספות Parts of the file converted, dropped or not imported yet, and tasks whose dates differ from the file's: חלקים בקובץ שהומרו, הושמטו או טרם יובאו, ומשימות שתאריכיהן שונים מהקובץ: @@ -188,11 +188,11 @@ Save As… שמירה בשם… Save changes? לשמור שינויים? Save the file every 2 minutes while it has unsaved changes שמירת הקובץ כל 2 דקות כשיש שינויים שלא נשמרו Saved {path} נשמר: {path} -Select a task to assign resources to. בחר משימה כדי להקצות לה משאבים. +Select a task to assign resources to. יש לבחור משימה כדי להקצות לה משאבים. Sep ספט׳ -Show All הצג הכול -Show assignment units as a הצג יחידות הקצאה בתור -Show or hide the task sheet's columns הצג או הסתר את עמודות גיליון המשימות +Show All הצגת הכול +Show assignment units as a הצגת יחידות הקצאה בתור +Show or hide the task sheet's columns הצגה או הסתרה של עמודות גיליון המשימות Showing the first {count} items. מציג את {count} הפריטים הראשונים. Standard rate: {rate} תעריף רגיל: {rate} Start התחלה @@ -205,7 +205,7 @@ Take away every levelling delay הסרת כל עיכובי האיזון Task Name שם משימה Task: {name} משימה: {name} The project calendar's exceptions apply too, except on a day with one of its own. חריגות לוח הפרויקט חלות אף הן, למעט ביום שבו יש חריגה משלו. -The system file dialog isn't available, so ProjectCraft shows its own. To get the system dialog, install a file chooser portal (such as xdg-desktop-portal-gtk) or zenity. חלונית הקבצים של המערכת אינה זמינה, ולכן ProjectCraft מציגה חלונית משלה. כדי לקבל את חלונית המערכת, התקן שער בחירת קבצים (כגון xdg-desktop-portal-gtk) או zenity. +The system file dialog isn't available, so ProjectCraft shows its own. To get the system dialog, install a file chooser portal (such as xdg-desktop-portal-gtk) or zenity. חלונית הקבצים של המערכת אינה זמינה, ולכן ProjectCraft מציגה חלונית משלה. כדי לקבל את חלונית המערכת, יש להתקין שער בחירת קבצים (כגון xdg-desktop-portal-gtk) או zenity. The task sheet's columns; saved with the project עמודות גיליון המשימות; נשמר עם הפרויקט The {n} resources selected are assigned to {count} task(s). Deleting them removes those assignments. {n} המשאבים שנבחרו מוקצים ל-{count} משימות. מחיקתם תסיר הקצאות אלה. This folder can't be read: {error} לא ניתן לקרוא תיקייה זו: {error} @@ -218,9 +218,9 @@ Total סה״כ Tue ג׳ Tuesday יום שלישי Type סוג -Type Fixed Units, Fixed Duration or Fixed Work. הקלד יחידות קבועות, משך קבוע או עבודה קבועה (או Fixed Units / Fixed Duration / Fixed Work). -Type Yes or No. הקלד כן או לא (Yes / No). -Type a priority from 0 to 1000. הקלד עדיפות בין 0 ל-1000. +Type Fixed Units, Fixed Duration or Fixed Work. יש להקליד יחידות קבועות, משך קבוע או עבודה קבועה (או Fixed Units / Fixed Duration / Fixed Work). +Type Yes or No. יש להקליד כן או לא (Yes / No). +Type a priority from 0 to 1000. יש להקליד עדיפות בין 0 ל-1000. Undo ביטול פעולה Units יחידות Units and work shown are for {name}. היחידות והעבודה המוצגות הן עבור {name}. @@ -261,7 +261,7 @@ work עבודה {file}: {tasks} tasks imported as a new, untitled project. ProjectCraft worked out every date; none were taken from the file. {file}: {tasks} משימות יובאו כפרויקט חדש וללא שם. ProjectCraft חישבה כל תאריך; אף תאריך לא נלקח מהקובץ. {format}… {format}… {name} - ProjectCraft {name} - ProjectCraft -{name} already exists. Choose Save again to replace it. {name} כבר קיים. בחר שמירה שוב כדי להחליף אותו. +{name} already exists. Choose Save again to replace it. {name} כבר קיים. יש לבחור שמירה שוב כדי להחליף אותו. {name} is assigned to {count} task(s). Deleting it removes those assignments. {name} מוקצה ל-{count} משימות. מחיקתו תסיר הקצאות אלה. {name} is assigned to {count} task(s). Making it a {type} resource removes those assignments. {name} מוקצה ל-{count} משימות. הפיכתו למשאב מסוג {type} תסיר הקצאות אלה. {name} wasn't found. {name} לא נמצא. diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index e46f9fc..aa0bf84 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -286,9 +286,11 @@ fn hebrew_font_data_from(env_dirs: &[Option], candidates: &[&str]) -> Op for dir in env_dirs.iter().flatten() { let trimmed = dir.trim(); if !trimmed.is_empty() { - let candidate = std::path::Path::new(trimmed).join("NotoSansHebrew-Regular.ttf"); - if let Some(data) = read_valid_font(&candidate) { - return Some(data); + for filename in ["NotoSansHebrew-Regular.ttf", "NotoSansHebrew[wdth,wght].ttf"] { + let candidate = std::path::Path::new(trimmed).join(filename); + if let Some(data) = read_valid_font(&candidate) { + return Some(data); + } } } }