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..6243284 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,98 @@ 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; + } + if let Some(lang) = env_tags.first().and_then(|v| v.as_deref()).and_then(Lang::from_tag) { + return lang; + } + 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. +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)) = 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 + }; + 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; + }; + save_language_to(&file, 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() + .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); + // 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] + 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/src/assign.rs b/crates/ui-egui/src/assign.rs index f6b7bb5..419dc2b 100644 --- a/crates/ui-egui/src/assign.rs +++ b/crates/ui-egui/src/assign.rs @@ -272,14 +272,16 @@ 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)."), }; - 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..4aa2c83 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_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." - )) - .color(t.text_dim), + ), + |r| r.color(t.text_dim), ); } ui.add_space(6.0); @@ -392,13 +393,13 @@ 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"), }; - 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 2ed331d..946ee3a 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -1,15 +1,65 @@ //! 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}; +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)] +#[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 +69,285 @@ 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_logical: HashMap<&'static str, &'static str>, + 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_logical = HashMap::new(); + 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_logical.insert(key, logical); + en_to_visual.insert(key, visual); + visual_to_logical.insert(visual, logical); + } + HebrewCatalog { en_to_logical, en_to_visual, visual_to_logical } + }) +} + +/// 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 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), + 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 { + 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]; + } + 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 { + push_fitted_span(ctx, paragraph, word_start, idx, font_id, max_w, &mut spans); + in_word = false; + } + } else if !in_word { + word_start = idx; + in_word = true; + } + } + if in_word { + 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 = 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 { + if let Some(row) = paragraph.get(line_start..line_end) { + rows.push(row); + } + line_start = span_start; + line_end = span_end; + } + } + if let Some(row) = paragraph.get(line_start..line_end) { + rows.push(row); + } + rows +} + +/// Break `logical` text at `max_width` first using original logical substrings, then apply visual +/// RTL ordering to each display row containing RTL characters. +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 mut out = String::with_capacity(logical.len()); + 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); + } + } + } + out +} + +/// 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. +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 = + 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.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 **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). +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 +386,417 @@ fn pseudo(s: &str) -> &'static str { leaked } -/// Fill `{name}` placeholders in a (translated) template. +/// Fill `{name}` placeholders in `template` for `lang`, keeping logical text order (for +/// row-aware wrapping in [`wrapped_label`]). +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. +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 } +} + +/// 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 } #[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()); + } + + 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 path in files { + let text = std::fs::read_to_string(&path).unwrap(); + 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; + 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!( + 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!(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)"); + assert_eq!(visual_rtl("(*.projectcraft),"), "(*.projectcraft),"); + // Visual-to-logical recovery must never collide between two distinct logical translations, + // 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); + 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!(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] + 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("תרמה"), "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}"); + + // 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_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; + }); + }); + }) + .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:?}"); + 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:?}" + ); + + // 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:?}"); + + // 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/i18n/bidi.rs b/crates/ui-egui/src/i18n/bidi.rs new file mode 100644 index 0000000..a6cd981 --- /dev/null +++ b/crates/ui-egui/src/i18n/bidi.rs @@ -0,0 +1,309 @@ +//! 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..=0x06EF + | 0x06FA..=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_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 { + 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/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) + && (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) + { + *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 +} diff --git a/crates/ui-egui/src/i18n/he.tsv b/crates/ui-egui/src/i18n/he.tsv new file mode 100644 index 0000000..e882b64 --- /dev/null +++ b/crates/ui-egui/src/i18n/he.tsv @@ -0,0 +1,268 @@ +# 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 יונ׳ +Language שפה +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/lib.rs b/crates/ui-egui/src/lib.rs index c06b648..a61ce8d 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; @@ -136,19 +145,26 @@ 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`), Hebrew logical catalog +/// labels, or visually reordered Hebrew labels pre-filled from [`shown_cell`]. +fn typed_task_type(text: &str) -> Option { + 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 /// 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. @@ -278,6 +294,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 +360,7 @@ impl App { saved, recent: Vec::new(), recent_changed: false, + language_changed: false, file_request: None, prompt: None, after_save: None, @@ -369,6 +387,17 @@ 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) { + 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) { @@ -427,6 +456,11 @@ impl App { theme::apply(&ctx, self.appearance); 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.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| { @@ -755,11 +789,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) => { @@ -849,6 +883,20 @@ 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(); + let hebrew_ok = theme::hebrew_font_available(ui.ctx()); + for lang in i18n::Lang::ALL { + if lang == i18n::Lang::Pseudo || (lang == i18n::Lang::Hebrew && !hebrew_ok) { + continue; + } + if ui.radio(active == lang, lang.name()).clicked() { + self.set_language(lang); + ui.close(); + } + } + }); }); } @@ -988,7 +1036,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_logical!("Based on the project calendar: only what differs is its own."), |r| r.color(t.text_dim)); } ui.add_space(10.0); @@ -1061,7 +1109,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_logical!("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 { @@ -2247,4 +2297,32 @@ 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)); + } + + #[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(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/options.rs b/crates/ui-egui/src/options.rs index 2c13e51..2d06f55 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_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); egui::Grid::new("project_options_rows").num_columns(3).spacing([12.0, 6.0]).show(ui, |ui| { @@ -206,13 +207,13 @@ 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."), }; - 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, 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| { diff --git a/crates/ui-egui/src/recovery.rs b/crates/ui-egui/src/recovery.rs index 8cee3c6..8b24020 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( - tl!("ProjectCraft closed before changes to {name} were saved. A recovery copy of them was kept."), + let notice = i18n::fmt_logical( + tl_logical!("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_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 b636907..aa0bf84 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,239 @@ pub fn apply(ctx: &egui::Context, preference: egui::ThemePreference) { }); } +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), 'א')) +} + +/// 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; + } + let available = has_hebrew_glyphs(ctx); + ctx.data_mut(|d| d.insert_temp(hebrew_available_key(), available)); + 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 { + 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"))] +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() { + 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); + } + } + } + } + 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", + "/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/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"]; + #[cfg(not(any(unix, windows)))] + const CANDIDATES: &[&str] = &[]; + + 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")] +fn hebrew_font_data() -> Option { + None +} + +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 = hebrew_installed_key(); + 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 { + #[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)); +} + /// 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 +410,95 @@ 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_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 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(); + 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); + for ch in "אבגדהוזחטיכלמנסעפצקרשתךםןףץ".chars() { + assert!(fonts.has_glyph(&font, ch), "missing Hebrew glyph {ch} in {font:?}"); + } + } + }); + } + + #[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"); + } + } + + #[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")); + // 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, &valid_bytes[..valid_bytes.len() / 2]).expect("write truncated candidate"); + let good_candidate = dir.join("good.ttf"); + 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(); + 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); + } +} diff --git a/crates/ui-egui/tests/language_picker.rs b/crates/ui-egui/tests/language_picker.rs new file mode 100644 index 0000000..88b1e97 --- /dev/null +++ b/crates/ui-egui/tests/language_picker.rs @@ -0,0 +1,74 @@ +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); + + h.get_by_label("View").click(); + 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; + } + 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"); +} + +#[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| { + 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); +}